xref: /openbmc/qemu/nbd/server.c (revision 864a2178)
1 /*
2  *  Copyright (C) 2016-2017 Red Hat, Inc.
3  *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
4  *
5  *  Network Block Device Server Side
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; under version 2 of the License.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qapi/error.h"
22 #include "trace.h"
23 #include "nbd-internal.h"
24 
25 static int system_errno_to_nbd_errno(int err)
26 {
27     switch (err) {
28     case 0:
29         return NBD_SUCCESS;
30     case EPERM:
31     case EROFS:
32         return NBD_EPERM;
33     case EIO:
34         return NBD_EIO;
35     case ENOMEM:
36         return NBD_ENOMEM;
37 #ifdef EDQUOT
38     case EDQUOT:
39 #endif
40     case EFBIG:
41     case ENOSPC:
42         return NBD_ENOSPC;
43     case ESHUTDOWN:
44         return NBD_ESHUTDOWN;
45     case EINVAL:
46     default:
47         return NBD_EINVAL;
48     }
49 }
50 
51 /* Definitions for opaque data types */
52 
53 typedef struct NBDRequestData NBDRequestData;
54 
55 struct NBDRequestData {
56     QSIMPLEQ_ENTRY(NBDRequestData) entry;
57     NBDClient *client;
58     uint8_t *data;
59     bool complete;
60 };
61 
62 struct NBDExport {
63     int refcount;
64     void (*close)(NBDExport *exp);
65 
66     BlockBackend *blk;
67     char *name;
68     char *description;
69     off_t dev_offset;
70     off_t size;
71     uint16_t nbdflags;
72     QTAILQ_HEAD(, NBDClient) clients;
73     QTAILQ_ENTRY(NBDExport) next;
74 
75     AioContext *ctx;
76 
77     BlockBackend *eject_notifier_blk;
78     Notifier eject_notifier;
79 };
80 
81 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
82 
83 struct NBDClient {
84     int refcount;
85     void (*close_fn)(NBDClient *client, bool negotiated);
86 
87     NBDExport *exp;
88     QCryptoTLSCreds *tlscreds;
89     char *tlsaclname;
90     QIOChannelSocket *sioc; /* The underlying data channel */
91     QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
92 
93     Coroutine *recv_coroutine;
94 
95     CoMutex send_lock;
96     Coroutine *send_coroutine;
97 
98     QTAILQ_ENTRY(NBDClient) next;
99     int nb_requests;
100     bool closing;
101 };
102 
103 /* That's all folks */
104 
105 static void nbd_client_receive_next_request(NBDClient *client);
106 
107 /* Basic flow for negotiation
108 
109    Server         Client
110    Negotiate
111 
112    or
113 
114    Server         Client
115    Negotiate #1
116                   Option
117    Negotiate #2
118 
119    ----
120 
121    followed by
122 
123    Server         Client
124                   Request
125    Response
126                   Request
127    Response
128                   ...
129    ...
130                   Request (type == 2)
131 
132 */
133 
134 /* Send a reply header, including length, but no payload.
135  * Return -errno on error, 0 on success. */
136 static int nbd_negotiate_send_rep_len(QIOChannel *ioc, uint32_t type,
137                                       uint32_t opt, uint32_t len, Error **errp)
138 {
139     uint64_t magic;
140 
141     trace_nbd_negotiate_send_rep_len(opt, nbd_opt_lookup(opt),
142                                      type, nbd_rep_lookup(type), len);
143 
144     assert(len < NBD_MAX_BUFFER_SIZE);
145     magic = cpu_to_be64(NBD_REP_MAGIC);
146     if (nbd_write(ioc, &magic, sizeof(magic), errp) < 0) {
147         error_prepend(errp, "write failed (rep magic): ");
148         return -EINVAL;
149     }
150 
151     opt = cpu_to_be32(opt);
152     if (nbd_write(ioc, &opt, sizeof(opt), errp) < 0) {
153         error_prepend(errp, "write failed (rep opt): ");
154         return -EINVAL;
155     }
156 
157     type = cpu_to_be32(type);
158     if (nbd_write(ioc, &type, sizeof(type), errp) < 0) {
159         error_prepend(errp, "write failed (rep type): ");
160         return -EINVAL;
161     }
162 
163     len = cpu_to_be32(len);
164     if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
165         error_prepend(errp, "write failed (rep data length): ");
166         return -EINVAL;
167     }
168     return 0;
169 }
170 
171 /* Send a reply header with default 0 length.
172  * Return -errno on error, 0 on success. */
173 static int nbd_negotiate_send_rep(QIOChannel *ioc, uint32_t type, uint32_t opt,
174                                   Error **errp)
175 {
176     return nbd_negotiate_send_rep_len(ioc, type, opt, 0, errp);
177 }
178 
179 /* Send an error reply.
180  * Return -errno on error, 0 on success. */
181 static int GCC_FMT_ATTR(5, 6)
182 nbd_negotiate_send_rep_err(QIOChannel *ioc, uint32_t type,
183                            uint32_t opt, Error **errp, const char *fmt, ...)
184 {
185     va_list va;
186     char *msg;
187     int ret;
188     size_t len;
189 
190     va_start(va, fmt);
191     msg = g_strdup_vprintf(fmt, va);
192     va_end(va);
193     len = strlen(msg);
194     assert(len < 4096);
195     trace_nbd_negotiate_send_rep_err(msg);
196     ret = nbd_negotiate_send_rep_len(ioc, type, opt, len, errp);
197     if (ret < 0) {
198         goto out;
199     }
200     if (nbd_write(ioc, msg, len, errp) < 0) {
201         error_prepend(errp, "write failed (error message): ");
202         ret = -EIO;
203     } else {
204         ret = 0;
205     }
206 
207 out:
208     g_free(msg);
209     return ret;
210 }
211 
212 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
213  * Return -errno on error, 0 on success. */
214 static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp,
215                                        Error **errp)
216 {
217     size_t name_len, desc_len;
218     uint32_t len;
219     const char *name = exp->name ? exp->name : "";
220     const char *desc = exp->description ? exp->description : "";
221     int ret;
222 
223     trace_nbd_negotiate_send_rep_list(name, desc);
224     name_len = strlen(name);
225     desc_len = strlen(desc);
226     len = name_len + desc_len + sizeof(len);
227     ret = nbd_negotiate_send_rep_len(ioc, NBD_REP_SERVER, NBD_OPT_LIST, len,
228                                      errp);
229     if (ret < 0) {
230         return ret;
231     }
232 
233     len = cpu_to_be32(name_len);
234     if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
235         error_prepend(errp, "write failed (name length): ");
236         return -EINVAL;
237     }
238 
239     if (nbd_write(ioc, name, name_len, errp) < 0) {
240         error_prepend(errp, "write failed (name buffer): ");
241         return -EINVAL;
242     }
243 
244     if (nbd_write(ioc, desc, desc_len, errp) < 0) {
245         error_prepend(errp, "write failed (description buffer): ");
246         return -EINVAL;
247     }
248 
249     return 0;
250 }
251 
252 /* Process the NBD_OPT_LIST command, with a potential series of replies.
253  * Return -errno on error, 0 on success. */
254 static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length,
255                                      Error **errp)
256 {
257     NBDExport *exp;
258 
259     if (length) {
260         if (nbd_drop(client->ioc, length, errp) < 0) {
261             return -EIO;
262         }
263         return nbd_negotiate_send_rep_err(client->ioc,
264                                           NBD_REP_ERR_INVALID, NBD_OPT_LIST,
265                                           errp,
266                                           "OPT_LIST should not have length");
267     }
268 
269     /* For each export, send a NBD_REP_SERVER reply. */
270     QTAILQ_FOREACH(exp, &exports, next) {
271         if (nbd_negotiate_send_rep_list(client->ioc, exp, errp)) {
272             return -EINVAL;
273         }
274     }
275     /* Finish with a NBD_REP_ACK. */
276     return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST, errp);
277 }
278 
279 /* Send a reply to NBD_OPT_EXPORT_NAME.
280  * Return -errno on error, 0 on success. */
281 static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length,
282                                             uint16_t myflags, bool no_zeroes,
283                                             Error **errp)
284 {
285     char name[NBD_MAX_NAME_SIZE + 1];
286     char buf[8 + 4 + 124] = "";
287     size_t len;
288     int ret;
289 
290     /* Client sends:
291         [20 ..  xx]   export name (length bytes)
292      */
293     trace_nbd_negotiate_handle_export_name();
294     if (length >= sizeof(name)) {
295         error_setg(errp, "Bad length received");
296         return -EINVAL;
297     }
298     if (nbd_read(client->ioc, name, length, errp) < 0) {
299         error_prepend(errp, "read failed: ");
300         return -EINVAL;
301     }
302     name[length] = '\0';
303 
304     trace_nbd_negotiate_handle_export_name_request(name);
305 
306     client->exp = nbd_export_find(name);
307     if (!client->exp) {
308         error_setg(errp, "export not found");
309         return -EINVAL;
310     }
311 
312     trace_nbd_negotiate_new_style_size_flags(client->exp->size,
313                                              client->exp->nbdflags | myflags);
314     stq_be_p(buf, client->exp->size);
315     stw_be_p(buf + 8, client->exp->nbdflags | myflags);
316     len = no_zeroes ? 10 : sizeof(buf);
317     ret = nbd_write(client->ioc, buf, len, errp);
318     if (ret < 0) {
319         error_prepend(errp, "write failed: ");
320         return ret;
321     }
322 
323     QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
324     nbd_export_get(client->exp);
325 
326     return 0;
327 }
328 
329 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
330  * The buffer does NOT include the info type prefix.
331  * Return -errno on error, 0 if ready to send more. */
332 static int nbd_negotiate_send_info(NBDClient *client, uint32_t opt,
333                                    uint16_t info, uint32_t length, void *buf,
334                                    Error **errp)
335 {
336     int rc;
337 
338     trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
339     rc = nbd_negotiate_send_rep_len(client->ioc, NBD_REP_INFO, opt,
340                                     sizeof(info) + length, errp);
341     if (rc < 0) {
342         return rc;
343     }
344     cpu_to_be16s(&info);
345     if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
346         return -EIO;
347     }
348     if (nbd_write(client->ioc, buf, length, errp) < 0) {
349         return -EIO;
350     }
351     return 0;
352 }
353 
354 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
355  * Return -errno on error, 0 if ready for next option, and 1 to move
356  * into transmission phase.  */
357 static int nbd_negotiate_handle_info(NBDClient *client, uint32_t length,
358                                      uint32_t opt, uint16_t myflags,
359                                      Error **errp)
360 {
361     int rc;
362     char name[NBD_MAX_NAME_SIZE + 1];
363     NBDExport *exp;
364     uint16_t requests;
365     uint16_t request;
366     uint32_t namelen;
367     bool sendname = false;
368     bool blocksize = false;
369     uint32_t sizes[3];
370     char buf[sizeof(uint64_t) + sizeof(uint16_t)];
371     const char *msg;
372 
373     /* Client sends:
374         4 bytes: L, name length (can be 0)
375         L bytes: export name
376         2 bytes: N, number of requests (can be 0)
377         N * 2 bytes: N requests
378     */
379     if (length < sizeof(namelen) + sizeof(requests)) {
380         msg = "overall request too short";
381         goto invalid;
382     }
383     if (nbd_read(client->ioc, &namelen, sizeof(namelen), errp) < 0) {
384         return -EIO;
385     }
386     be32_to_cpus(&namelen);
387     length -= sizeof(namelen);
388     if (namelen > length - sizeof(requests) || (length - namelen) % 2) {
389         msg = "name length is incorrect";
390         goto invalid;
391     }
392     if (nbd_read(client->ioc, name, namelen, errp) < 0) {
393         return -EIO;
394     }
395     name[namelen] = '\0';
396     length -= namelen;
397     trace_nbd_negotiate_handle_export_name_request(name);
398 
399     if (nbd_read(client->ioc, &requests, sizeof(requests), errp) < 0) {
400         return -EIO;
401     }
402     be16_to_cpus(&requests);
403     length -= sizeof(requests);
404     trace_nbd_negotiate_handle_info_requests(requests);
405     if (requests != length / sizeof(request)) {
406         msg = "incorrect number of  requests for overall length";
407         goto invalid;
408     }
409     while (requests--) {
410         if (nbd_read(client->ioc, &request, sizeof(request), errp) < 0) {
411             return -EIO;
412         }
413         be16_to_cpus(&request);
414         length -= sizeof(request);
415         trace_nbd_negotiate_handle_info_request(request,
416                                                 nbd_info_lookup(request));
417         /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
418          * everything else is either a request we don't know or
419          * something we send regardless of request */
420         switch (request) {
421         case NBD_INFO_NAME:
422             sendname = true;
423             break;
424         case NBD_INFO_BLOCK_SIZE:
425             blocksize = true;
426             break;
427         }
428     }
429 
430     exp = nbd_export_find(name);
431     if (!exp) {
432         return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_UNKNOWN,
433                                           opt, errp, "export '%s' not present",
434                                           name);
435     }
436 
437     /* Don't bother sending NBD_INFO_NAME unless client requested it */
438     if (sendname) {
439         rc = nbd_negotiate_send_info(client, opt, NBD_INFO_NAME, length, name,
440                                      errp);
441         if (rc < 0) {
442             return rc;
443         }
444     }
445 
446     /* Send NBD_INFO_DESCRIPTION only if available, regardless of
447      * client request */
448     if (exp->description) {
449         size_t len = strlen(exp->description);
450 
451         rc = nbd_negotiate_send_info(client, opt, NBD_INFO_DESCRIPTION,
452                                      len, exp->description, errp);
453         if (rc < 0) {
454             return rc;
455         }
456     }
457 
458     /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
459      * according to whether the client requested it, and according to
460      * whether this is OPT_INFO or OPT_GO. */
461     /* minimum - 1 for back-compat, or 512 if client is new enough.
462      * TODO: consult blk_bs(blk)->bl.request_alignment? */
463     sizes[0] = (opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;
464     /* preferred - Hard-code to 4096 for now.
465      * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
466     sizes[1] = 4096;
467     /* maximum - At most 32M, but smaller as appropriate. */
468     sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
469     trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
470     cpu_to_be32s(&sizes[0]);
471     cpu_to_be32s(&sizes[1]);
472     cpu_to_be32s(&sizes[2]);
473     rc = nbd_negotiate_send_info(client, opt, NBD_INFO_BLOCK_SIZE,
474                                  sizeof(sizes), sizes, errp);
475     if (rc < 0) {
476         return rc;
477     }
478 
479     /* Send NBD_INFO_EXPORT always */
480     trace_nbd_negotiate_new_style_size_flags(exp->size,
481                                              exp->nbdflags | myflags);
482     stq_be_p(buf, exp->size);
483     stw_be_p(buf + 8, exp->nbdflags | myflags);
484     rc = nbd_negotiate_send_info(client, opt, NBD_INFO_EXPORT,
485                                  sizeof(buf), buf, errp);
486     if (rc < 0) {
487         return rc;
488     }
489 
490     /* If the client is just asking for NBD_OPT_INFO, but forgot to
491      * request block sizes, return an error.
492      * TODO: consult blk_bs(blk)->request_align, and only error if it
493      * is not 1? */
494     if (opt == NBD_OPT_INFO && !blocksize) {
495         return nbd_negotiate_send_rep_err(client->ioc,
496                                           NBD_REP_ERR_BLOCK_SIZE_REQD, opt,
497                                           errp,
498                                           "request NBD_INFO_BLOCK_SIZE to "
499                                           "use this export");
500     }
501 
502     /* Final reply */
503     rc = nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, opt, errp);
504     if (rc < 0) {
505         return rc;
506     }
507 
508     if (opt == NBD_OPT_GO) {
509         client->exp = exp;
510         QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
511         nbd_export_get(client->exp);
512         rc = 1;
513     }
514     return rc;
515 
516  invalid:
517     if (nbd_drop(client->ioc, length, errp) < 0) {
518         return -EIO;
519     }
520     return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_INVALID, opt,
521                                       errp, "%s", msg);
522 }
523 
524 
525 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
526  * new channel for all further (now-encrypted) communication. */
527 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
528                                                  uint32_t length,
529                                                  Error **errp)
530 {
531     QIOChannel *ioc;
532     QIOChannelTLS *tioc;
533     struct NBDTLSHandshakeData data = { 0 };
534 
535     trace_nbd_negotiate_handle_starttls();
536     ioc = client->ioc;
537     if (length) {
538         if (nbd_drop(ioc, length, errp) < 0) {
539             return NULL;
540         }
541         nbd_negotiate_send_rep_err(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS,
542                                    errp,
543                                    "OPT_STARTTLS should not have length");
544         return NULL;
545     }
546 
547     if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
548                                NBD_OPT_STARTTLS, errp) < 0) {
549         return NULL;
550     }
551 
552     tioc = qio_channel_tls_new_server(ioc,
553                                       client->tlscreds,
554                                       client->tlsaclname,
555                                       errp);
556     if (!tioc) {
557         return NULL;
558     }
559 
560     qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
561     trace_nbd_negotiate_handle_starttls_handshake();
562     data.loop = g_main_loop_new(g_main_context_default(), FALSE);
563     qio_channel_tls_handshake(tioc,
564                               nbd_tls_handshake,
565                               &data,
566                               NULL);
567 
568     if (!data.complete) {
569         g_main_loop_run(data.loop);
570     }
571     g_main_loop_unref(data.loop);
572     if (data.error) {
573         object_unref(OBJECT(tioc));
574         error_propagate(errp, data.error);
575         return NULL;
576     }
577 
578     return QIO_CHANNEL(tioc);
579 }
580 
581 /* nbd_negotiate_options
582  * Process all NBD_OPT_* client option commands, during fixed newstyle
583  * negotiation.
584  * Return:
585  * -errno  on error, errp is set
586  * 0       on successful negotiation, errp is not set
587  * 1       if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
588  *         errp is not set
589  */
590 static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
591                                  Error **errp)
592 {
593     uint32_t flags;
594     bool fixedNewstyle = false;
595     bool no_zeroes = false;
596 
597     /* Client sends:
598         [ 0 ..   3]   client flags
599 
600        Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
601         [ 0 ..   7]   NBD_OPTS_MAGIC
602         [ 8 ..  11]   NBD option
603         [12 ..  15]   Data length
604         ...           Rest of request
605 
606         [ 0 ..   7]   NBD_OPTS_MAGIC
607         [ 8 ..  11]   Second NBD option
608         [12 ..  15]   Data length
609         ...           Rest of request
610     */
611 
612     if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
613         error_prepend(errp, "read failed: ");
614         return -EIO;
615     }
616     be32_to_cpus(&flags);
617     trace_nbd_negotiate_options_flags(flags);
618     if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
619         fixedNewstyle = true;
620         flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
621     }
622     if (flags & NBD_FLAG_C_NO_ZEROES) {
623         no_zeroes = true;
624         flags &= ~NBD_FLAG_C_NO_ZEROES;
625     }
626     if (flags != 0) {
627         error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
628         return -EINVAL;
629     }
630 
631     while (1) {
632         int ret;
633         uint32_t option, length;
634         uint64_t magic;
635 
636         if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
637             error_prepend(errp, "read failed: ");
638             return -EINVAL;
639         }
640         magic = be64_to_cpu(magic);
641         trace_nbd_negotiate_options_check_magic(magic);
642         if (magic != NBD_OPTS_MAGIC) {
643             error_setg(errp, "Bad magic received");
644             return -EINVAL;
645         }
646 
647         if (nbd_read(client->ioc, &option,
648                      sizeof(option), errp) < 0) {
649             error_prepend(errp, "read failed: ");
650             return -EINVAL;
651         }
652         option = be32_to_cpu(option);
653 
654         if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
655             error_prepend(errp, "read failed: ");
656             return -EINVAL;
657         }
658         length = be32_to_cpu(length);
659 
660         trace_nbd_negotiate_options_check_option(option,
661                                                  nbd_opt_lookup(option));
662         if (client->tlscreds &&
663             client->ioc == (QIOChannel *)client->sioc) {
664             QIOChannel *tioc;
665             if (!fixedNewstyle) {
666                 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
667                 return -EINVAL;
668             }
669             switch (option) {
670             case NBD_OPT_STARTTLS:
671                 tioc = nbd_negotiate_handle_starttls(client, length, errp);
672                 if (!tioc) {
673                     return -EIO;
674                 }
675                 object_unref(OBJECT(client->ioc));
676                 client->ioc = QIO_CHANNEL(tioc);
677                 break;
678 
679             case NBD_OPT_EXPORT_NAME:
680                 /* No way to return an error to client, so drop connection */
681                 error_setg(errp, "Option 0x%x not permitted before TLS",
682                            option);
683                 return -EINVAL;
684 
685             default:
686                 if (nbd_drop(client->ioc, length, errp) < 0) {
687                     return -EIO;
688                 }
689                 ret = nbd_negotiate_send_rep_err(client->ioc,
690                                                  NBD_REP_ERR_TLS_REQD,
691                                                  option, errp,
692                                                  "Option 0x%" PRIx32
693                                                  "not permitted before TLS",
694                                                  option);
695                 if (ret < 0) {
696                     return ret;
697                 }
698                 /* Let the client keep trying, unless they asked to
699                  * quit. In this mode, we've already sent an error, so
700                  * we can't ack the abort.  */
701                 if (option == NBD_OPT_ABORT) {
702                     return 1;
703                 }
704                 break;
705             }
706         } else if (fixedNewstyle) {
707             switch (option) {
708             case NBD_OPT_LIST:
709                 ret = nbd_negotiate_handle_list(client, length, errp);
710                 if (ret < 0) {
711                     return ret;
712                 }
713                 break;
714 
715             case NBD_OPT_ABORT:
716                 /* NBD spec says we must try to reply before
717                  * disconnecting, but that we must also tolerate
718                  * guests that don't wait for our reply. */
719                 nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, option, NULL);
720                 return 1;
721 
722             case NBD_OPT_EXPORT_NAME:
723                 return nbd_negotiate_handle_export_name(client, length,
724                                                         myflags, no_zeroes,
725                                                         errp);
726 
727             case NBD_OPT_INFO:
728             case NBD_OPT_GO:
729                 ret = nbd_negotiate_handle_info(client, length, option,
730                                                 myflags, errp);
731                 if (ret == 1) {
732                     assert(option == NBD_OPT_GO);
733                     return 0;
734                 }
735                 if (ret) {
736                     return ret;
737                 }
738                 break;
739 
740             case NBD_OPT_STARTTLS:
741                 if (nbd_drop(client->ioc, length, errp) < 0) {
742                     return -EIO;
743                 }
744                 if (client->tlscreds) {
745                     ret = nbd_negotiate_send_rep_err(client->ioc,
746                                                      NBD_REP_ERR_INVALID,
747                                                      option, errp,
748                                                      "TLS already enabled");
749                 } else {
750                     ret = nbd_negotiate_send_rep_err(client->ioc,
751                                                      NBD_REP_ERR_POLICY,
752                                                      option, errp,
753                                                      "TLS not configured");
754                 }
755                 if (ret < 0) {
756                     return ret;
757                 }
758                 break;
759             default:
760                 if (nbd_drop(client->ioc, length, errp) < 0) {
761                     return -EIO;
762                 }
763                 ret = nbd_negotiate_send_rep_err(client->ioc,
764                                                  NBD_REP_ERR_UNSUP,
765                                                  option, errp,
766                                                  "Unsupported option 0x%"
767                                                  PRIx32 " (%s)", option,
768                                                  nbd_opt_lookup(option));
769                 if (ret < 0) {
770                     return ret;
771                 }
772                 break;
773             }
774         } else {
775             /*
776              * If broken new-style we should drop the connection
777              * for anything except NBD_OPT_EXPORT_NAME
778              */
779             switch (option) {
780             case NBD_OPT_EXPORT_NAME:
781                 return nbd_negotiate_handle_export_name(client, length,
782                                                         myflags, no_zeroes,
783                                                         errp);
784 
785             default:
786                 error_setg(errp, "Unsupported option 0x%" PRIx32 " (%s)",
787                            option, nbd_opt_lookup(option));
788                 return -EINVAL;
789             }
790         }
791     }
792 }
793 
794 /* nbd_negotiate
795  * Return:
796  * -errno  on error, errp is set
797  * 0       on successful negotiation, errp is not set
798  * 1       if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
799  *         errp is not set
800  */
801 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
802 {
803     char buf[8 + 8 + 8 + 128];
804     int ret;
805     const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
806                               NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
807                               NBD_FLAG_SEND_WRITE_ZEROES);
808     bool oldStyle;
809 
810     /* Old style negotiation header without options
811         [ 0 ..   7]   passwd       ("NBDMAGIC")
812         [ 8 ..  15]   magic        (NBD_CLIENT_MAGIC)
813         [16 ..  23]   size
814         [24 ..  25]   server flags (0)
815         [26 ..  27]   export flags
816         [28 .. 151]   reserved     (0)
817 
818        New style negotiation header with options
819         [ 0 ..   7]   passwd       ("NBDMAGIC")
820         [ 8 ..  15]   magic        (NBD_OPTS_MAGIC)
821         [16 ..  17]   server flags (0)
822         ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
823      */
824 
825     qio_channel_set_blocking(client->ioc, false, NULL);
826 
827     trace_nbd_negotiate_begin();
828     memset(buf, 0, sizeof(buf));
829     memcpy(buf, "NBDMAGIC", 8);
830 
831     oldStyle = client->exp != NULL && !client->tlscreds;
832     if (oldStyle) {
833         trace_nbd_negotiate_old_style(client->exp->size,
834                                       client->exp->nbdflags | myflags);
835         stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
836         stq_be_p(buf + 16, client->exp->size);
837         stw_be_p(buf + 26, client->exp->nbdflags | myflags);
838 
839         if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {
840             error_prepend(errp, "write failed: ");
841             return -EINVAL;
842         }
843     } else {
844         stq_be_p(buf + 8, NBD_OPTS_MAGIC);
845         stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
846 
847         if (nbd_write(client->ioc, buf, 18, errp) < 0) {
848             error_prepend(errp, "write failed: ");
849             return -EINVAL;
850         }
851         ret = nbd_negotiate_options(client, myflags, errp);
852         if (ret != 0) {
853             if (ret < 0) {
854                 error_prepend(errp, "option negotiation failed: ");
855             }
856             return ret;
857         }
858     }
859 
860     trace_nbd_negotiate_success();
861 
862     return 0;
863 }
864 
865 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
866                                Error **errp)
867 {
868     uint8_t buf[NBD_REQUEST_SIZE];
869     uint32_t magic;
870     int ret;
871 
872     ret = nbd_read(ioc, buf, sizeof(buf), errp);
873     if (ret < 0) {
874         return ret;
875     }
876 
877     /* Request
878        [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)
879        [ 4 ..  5]   flags   (NBD_CMD_FLAG_FUA, ...)
880        [ 6 ..  7]   type    (NBD_CMD_READ, ...)
881        [ 8 .. 15]   handle
882        [16 .. 23]   from
883        [24 .. 27]   len
884      */
885 
886     magic = ldl_be_p(buf);
887     request->flags  = lduw_be_p(buf + 4);
888     request->type   = lduw_be_p(buf + 6);
889     request->handle = ldq_be_p(buf + 8);
890     request->from   = ldq_be_p(buf + 16);
891     request->len    = ldl_be_p(buf + 24);
892 
893     trace_nbd_receive_request(magic, request->flags, request->type,
894                               request->from, request->len);
895 
896     if (magic != NBD_REQUEST_MAGIC) {
897         error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
898         return -EINVAL;
899     }
900     return 0;
901 }
902 
903 static int nbd_send_reply(QIOChannel *ioc, NBDReply *reply, Error **errp)
904 {
905     uint8_t buf[NBD_REPLY_SIZE];
906 
907     reply->error = system_errno_to_nbd_errno(reply->error);
908 
909     trace_nbd_send_reply(reply->error, reply->handle);
910 
911     /* Reply
912        [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
913        [ 4 ..  7]    error   (0 == no error)
914        [ 7 .. 15]    handle
915      */
916     stl_be_p(buf, NBD_REPLY_MAGIC);
917     stl_be_p(buf + 4, reply->error);
918     stq_be_p(buf + 8, reply->handle);
919 
920     return nbd_write(ioc, buf, sizeof(buf), errp);
921 }
922 
923 #define MAX_NBD_REQUESTS 16
924 
925 void nbd_client_get(NBDClient *client)
926 {
927     client->refcount++;
928 }
929 
930 void nbd_client_put(NBDClient *client)
931 {
932     if (--client->refcount == 0) {
933         /* The last reference should be dropped by client->close,
934          * which is called by client_close.
935          */
936         assert(client->closing);
937 
938         qio_channel_detach_aio_context(client->ioc);
939         object_unref(OBJECT(client->sioc));
940         object_unref(OBJECT(client->ioc));
941         if (client->tlscreds) {
942             object_unref(OBJECT(client->tlscreds));
943         }
944         g_free(client->tlsaclname);
945         if (client->exp) {
946             QTAILQ_REMOVE(&client->exp->clients, client, next);
947             nbd_export_put(client->exp);
948         }
949         g_free(client);
950     }
951 }
952 
953 static void client_close(NBDClient *client, bool negotiated)
954 {
955     if (client->closing) {
956         return;
957     }
958 
959     client->closing = true;
960 
961     /* Force requests to finish.  They will drop their own references,
962      * then we'll close the socket and free the NBDClient.
963      */
964     qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
965                          NULL);
966 
967     /* Also tell the client, so that they release their reference.  */
968     if (client->close_fn) {
969         client->close_fn(client, negotiated);
970     }
971 }
972 
973 static NBDRequestData *nbd_request_get(NBDClient *client)
974 {
975     NBDRequestData *req;
976 
977     assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
978     client->nb_requests++;
979 
980     req = g_new0(NBDRequestData, 1);
981     nbd_client_get(client);
982     req->client = client;
983     return req;
984 }
985 
986 static void nbd_request_put(NBDRequestData *req)
987 {
988     NBDClient *client = req->client;
989 
990     if (req->data) {
991         qemu_vfree(req->data);
992     }
993     g_free(req);
994 
995     client->nb_requests--;
996     nbd_client_receive_next_request(client);
997 
998     nbd_client_put(client);
999 }
1000 
1001 static void blk_aio_attached(AioContext *ctx, void *opaque)
1002 {
1003     NBDExport *exp = opaque;
1004     NBDClient *client;
1005 
1006     trace_nbd_blk_aio_attached(exp->name, ctx);
1007 
1008     exp->ctx = ctx;
1009 
1010     QTAILQ_FOREACH(client, &exp->clients, next) {
1011         qio_channel_attach_aio_context(client->ioc, ctx);
1012         if (client->recv_coroutine) {
1013             aio_co_schedule(ctx, client->recv_coroutine);
1014         }
1015         if (client->send_coroutine) {
1016             aio_co_schedule(ctx, client->send_coroutine);
1017         }
1018     }
1019 }
1020 
1021 static void blk_aio_detach(void *opaque)
1022 {
1023     NBDExport *exp = opaque;
1024     NBDClient *client;
1025 
1026     trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1027 
1028     QTAILQ_FOREACH(client, &exp->clients, next) {
1029         qio_channel_detach_aio_context(client->ioc);
1030     }
1031 
1032     exp->ctx = NULL;
1033 }
1034 
1035 static void nbd_eject_notifier(Notifier *n, void *data)
1036 {
1037     NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1038     nbd_export_close(exp);
1039 }
1040 
1041 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
1042                           uint16_t nbdflags, void (*close)(NBDExport *),
1043                           bool writethrough, BlockBackend *on_eject_blk,
1044                           Error **errp)
1045 {
1046     BlockBackend *blk;
1047     NBDExport *exp = g_malloc0(sizeof(NBDExport));
1048     uint64_t perm;
1049     int ret;
1050 
1051     /* Don't allow resize while the NBD server is running, otherwise we don't
1052      * care what happens with the node. */
1053     perm = BLK_PERM_CONSISTENT_READ;
1054     if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
1055         perm |= BLK_PERM_WRITE;
1056     }
1057     blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1058                         BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1059     ret = blk_insert_bs(blk, bs, errp);
1060     if (ret < 0) {
1061         goto fail;
1062     }
1063     blk_set_enable_write_cache(blk, !writethrough);
1064 
1065     exp->refcount = 1;
1066     QTAILQ_INIT(&exp->clients);
1067     exp->blk = blk;
1068     exp->dev_offset = dev_offset;
1069     exp->nbdflags = nbdflags;
1070     exp->size = size < 0 ? blk_getlength(blk) : size;
1071     if (exp->size < 0) {
1072         error_setg_errno(errp, -exp->size,
1073                          "Failed to determine the NBD export's length");
1074         goto fail;
1075     }
1076     exp->size -= exp->size % BDRV_SECTOR_SIZE;
1077 
1078     exp->close = close;
1079     exp->ctx = blk_get_aio_context(blk);
1080     blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1081 
1082     if (on_eject_blk) {
1083         blk_ref(on_eject_blk);
1084         exp->eject_notifier_blk = on_eject_blk;
1085         exp->eject_notifier.notify = nbd_eject_notifier;
1086         blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1087     }
1088 
1089     /*
1090      * NBD exports are used for non-shared storage migration.  Make sure
1091      * that BDRV_O_INACTIVE is cleared and the image is ready for write
1092      * access since the export could be available before migration handover.
1093      */
1094     aio_context_acquire(exp->ctx);
1095     blk_invalidate_cache(blk, NULL);
1096     aio_context_release(exp->ctx);
1097     return exp;
1098 
1099 fail:
1100     blk_unref(blk);
1101     g_free(exp);
1102     return NULL;
1103 }
1104 
1105 NBDExport *nbd_export_find(const char *name)
1106 {
1107     NBDExport *exp;
1108     QTAILQ_FOREACH(exp, &exports, next) {
1109         if (strcmp(name, exp->name) == 0) {
1110             return exp;
1111         }
1112     }
1113 
1114     return NULL;
1115 }
1116 
1117 void nbd_export_set_name(NBDExport *exp, const char *name)
1118 {
1119     if (exp->name == name) {
1120         return;
1121     }
1122 
1123     nbd_export_get(exp);
1124     if (exp->name != NULL) {
1125         g_free(exp->name);
1126         exp->name = NULL;
1127         QTAILQ_REMOVE(&exports, exp, next);
1128         nbd_export_put(exp);
1129     }
1130     if (name != NULL) {
1131         nbd_export_get(exp);
1132         exp->name = g_strdup(name);
1133         QTAILQ_INSERT_TAIL(&exports, exp, next);
1134     }
1135     nbd_export_put(exp);
1136 }
1137 
1138 void nbd_export_set_description(NBDExport *exp, const char *description)
1139 {
1140     g_free(exp->description);
1141     exp->description = g_strdup(description);
1142 }
1143 
1144 void nbd_export_close(NBDExport *exp)
1145 {
1146     NBDClient *client, *next;
1147 
1148     nbd_export_get(exp);
1149     QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1150         client_close(client, true);
1151     }
1152     nbd_export_set_name(exp, NULL);
1153     nbd_export_set_description(exp, NULL);
1154     nbd_export_put(exp);
1155 }
1156 
1157 void nbd_export_get(NBDExport *exp)
1158 {
1159     assert(exp->refcount > 0);
1160     exp->refcount++;
1161 }
1162 
1163 void nbd_export_put(NBDExport *exp)
1164 {
1165     assert(exp->refcount > 0);
1166     if (exp->refcount == 1) {
1167         nbd_export_close(exp);
1168     }
1169 
1170     if (--exp->refcount == 0) {
1171         assert(exp->name == NULL);
1172         assert(exp->description == NULL);
1173 
1174         if (exp->close) {
1175             exp->close(exp);
1176         }
1177 
1178         if (exp->blk) {
1179             if (exp->eject_notifier_blk) {
1180                 notifier_remove(&exp->eject_notifier);
1181                 blk_unref(exp->eject_notifier_blk);
1182             }
1183             blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1184                                             blk_aio_detach, exp);
1185             blk_unref(exp->blk);
1186             exp->blk = NULL;
1187         }
1188 
1189         g_free(exp);
1190     }
1191 }
1192 
1193 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1194 {
1195     return exp->blk;
1196 }
1197 
1198 void nbd_export_close_all(void)
1199 {
1200     NBDExport *exp, *next;
1201 
1202     QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1203         nbd_export_close(exp);
1204     }
1205 }
1206 
1207 static int nbd_co_send_reply(NBDRequestData *req, NBDReply *reply, int len,
1208                              Error **errp)
1209 {
1210     NBDClient *client = req->client;
1211     int ret;
1212 
1213     g_assert(qemu_in_coroutine());
1214 
1215     trace_nbd_co_send_reply(reply->handle, reply->error, len);
1216 
1217     qemu_co_mutex_lock(&client->send_lock);
1218     client->send_coroutine = qemu_coroutine_self();
1219 
1220     if (!len) {
1221         ret = nbd_send_reply(client->ioc, reply, errp);
1222     } else {
1223         qio_channel_set_cork(client->ioc, true);
1224         ret = nbd_send_reply(client->ioc, reply, errp);
1225         if (ret == 0) {
1226             ret = nbd_write(client->ioc, req->data, len, errp);
1227             if (ret < 0) {
1228                 ret = -EIO;
1229             }
1230         }
1231         qio_channel_set_cork(client->ioc, false);
1232     }
1233 
1234     client->send_coroutine = NULL;
1235     qemu_co_mutex_unlock(&client->send_lock);
1236     return ret;
1237 }
1238 
1239 /* nbd_co_receive_request
1240  * Collect a client request. Return 0 if request looks valid, -EIO to drop
1241  * connection right away, and any other negative value to report an error to
1242  * the client (although the caller may still need to disconnect after reporting
1243  * the error).
1244  */
1245 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
1246                                   Error **errp)
1247 {
1248     NBDClient *client = req->client;
1249 
1250     g_assert(qemu_in_coroutine());
1251     assert(client->recv_coroutine == qemu_coroutine_self());
1252     if (nbd_receive_request(client->ioc, request, errp) < 0) {
1253         return -EIO;
1254     }
1255 
1256     trace_nbd_co_receive_request_decode_type(request->handle, request->type,
1257                                              nbd_cmd_lookup(request->type));
1258 
1259     if (request->type != NBD_CMD_WRITE) {
1260         /* No payload, we are ready to read the next request.  */
1261         req->complete = true;
1262     }
1263 
1264     if (request->type == NBD_CMD_DISC) {
1265         /* Special case: we're going to disconnect without a reply,
1266          * whether or not flags, from, or len are bogus */
1267         return -EIO;
1268     }
1269 
1270     /* Check for sanity in the parameters, part 1.  Defer as many
1271      * checks as possible until after reading any NBD_CMD_WRITE
1272      * payload, so we can try and keep the connection alive.  */
1273     if ((request->from + request->len) < request->from) {
1274         error_setg(errp,
1275                    "integer overflow detected, you're probably being attacked");
1276         return -EINVAL;
1277     }
1278 
1279     if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {
1280         if (request->len > NBD_MAX_BUFFER_SIZE) {
1281             error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1282                        request->len, NBD_MAX_BUFFER_SIZE);
1283             return -EINVAL;
1284         }
1285 
1286         req->data = blk_try_blockalign(client->exp->blk, request->len);
1287         if (req->data == NULL) {
1288             error_setg(errp, "No memory");
1289             return -ENOMEM;
1290         }
1291     }
1292     if (request->type == NBD_CMD_WRITE) {
1293         if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
1294             error_prepend(errp, "reading from socket failed: ");
1295             return -EIO;
1296         }
1297         req->complete = true;
1298 
1299         trace_nbd_co_receive_request_payload_received(request->handle,
1300                                                       request->len);
1301     }
1302 
1303     /* Sanity checks, part 2. */
1304     if (request->from + request->len > client->exp->size) {
1305         error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1306                    ", Size: %" PRIu64, request->from, request->len,
1307                    (uint64_t)client->exp->size);
1308         return request->type == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;
1309     }
1310     if (request->flags & ~(NBD_CMD_FLAG_FUA | NBD_CMD_FLAG_NO_HOLE)) {
1311         error_setg(errp, "unsupported flags (got 0x%x)", request->flags);
1312         return -EINVAL;
1313     }
1314     if (request->type != NBD_CMD_WRITE_ZEROES &&
1315         (request->flags & NBD_CMD_FLAG_NO_HOLE)) {
1316         error_setg(errp, "unexpected flags (got 0x%x)", request->flags);
1317         return -EINVAL;
1318     }
1319 
1320     return 0;
1321 }
1322 
1323 /* Owns a reference to the NBDClient passed as opaque.  */
1324 static coroutine_fn void nbd_trip(void *opaque)
1325 {
1326     NBDClient *client = opaque;
1327     NBDExport *exp = client->exp;
1328     NBDRequestData *req;
1329     NBDRequest request = { 0 };    /* GCC thinks it can be used uninitialized */
1330     NBDReply reply;
1331     int ret;
1332     int flags;
1333     int reply_data_len = 0;
1334     Error *local_err = NULL;
1335 
1336     trace_nbd_trip();
1337     if (client->closing) {
1338         nbd_client_put(client);
1339         return;
1340     }
1341 
1342     req = nbd_request_get(client);
1343     ret = nbd_co_receive_request(req, &request, &local_err);
1344     client->recv_coroutine = NULL;
1345     nbd_client_receive_next_request(client);
1346     if (ret == -EIO) {
1347         goto disconnect;
1348     }
1349 
1350     reply.handle = request.handle;
1351     reply.error = 0;
1352 
1353     if (ret < 0) {
1354         reply.error = -ret;
1355         goto reply;
1356     }
1357 
1358     if (client->closing) {
1359         /*
1360          * The client may be closed when we are blocked in
1361          * nbd_co_receive_request()
1362          */
1363         goto done;
1364     }
1365 
1366     switch (request.type) {
1367     case NBD_CMD_READ:
1368         /* XXX: NBD Protocol only documents use of FUA with WRITE */
1369         if (request.flags & NBD_CMD_FLAG_FUA) {
1370             ret = blk_co_flush(exp->blk);
1371             if (ret < 0) {
1372                 error_setg_errno(&local_err, -ret, "flush failed");
1373                 reply.error = -ret;
1374                 break;
1375             }
1376         }
1377 
1378         ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1379                         req->data, request.len);
1380         if (ret < 0) {
1381             error_setg_errno(&local_err, -ret, "reading from file failed");
1382             reply.error = -ret;
1383             break;
1384         }
1385 
1386         reply_data_len = request.len;
1387 
1388         break;
1389     case NBD_CMD_WRITE:
1390         if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1391             reply.error = EROFS;
1392             break;
1393         }
1394 
1395         flags = 0;
1396         if (request.flags & NBD_CMD_FLAG_FUA) {
1397             flags |= BDRV_REQ_FUA;
1398         }
1399         ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
1400                          req->data, request.len, flags);
1401         if (ret < 0) {
1402             error_setg_errno(&local_err, -ret, "writing to file failed");
1403             reply.error = -ret;
1404         }
1405 
1406         break;
1407     case NBD_CMD_WRITE_ZEROES:
1408         if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1409             error_setg(&local_err, "Server is read-only, return error");
1410             reply.error = EROFS;
1411             break;
1412         }
1413 
1414         flags = 0;
1415         if (request.flags & NBD_CMD_FLAG_FUA) {
1416             flags |= BDRV_REQ_FUA;
1417         }
1418         if (!(request.flags & NBD_CMD_FLAG_NO_HOLE)) {
1419             flags |= BDRV_REQ_MAY_UNMAP;
1420         }
1421         ret = blk_pwrite_zeroes(exp->blk, request.from + exp->dev_offset,
1422                                 request.len, flags);
1423         if (ret < 0) {
1424             error_setg_errno(&local_err, -ret, "writing to file failed");
1425             reply.error = -ret;
1426         }
1427 
1428         break;
1429     case NBD_CMD_DISC:
1430         /* unreachable, thanks to special case in nbd_co_receive_request() */
1431         abort();
1432 
1433     case NBD_CMD_FLUSH:
1434         ret = blk_co_flush(exp->blk);
1435         if (ret < 0) {
1436             error_setg_errno(&local_err, -ret, "flush failed");
1437             reply.error = -ret;
1438         }
1439 
1440         break;
1441     case NBD_CMD_TRIM:
1442         ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1443                               request.len);
1444         if (ret < 0) {
1445             error_setg_errno(&local_err, -ret, "discard failed");
1446             reply.error = -ret;
1447         }
1448 
1449         break;
1450     default:
1451         error_setg(&local_err, "invalid request type (%" PRIu32 ") received",
1452                    request.type);
1453         reply.error = EINVAL;
1454     }
1455 
1456 reply:
1457     if (local_err) {
1458         /* If we are here local_err is not fatal error, already stored in
1459          * reply.error */
1460         error_report_err(local_err);
1461         local_err = NULL;
1462     }
1463 
1464     if (nbd_co_send_reply(req, &reply, reply_data_len, &local_err) < 0) {
1465         error_prepend(&local_err, "Failed to send reply: ");
1466         goto disconnect;
1467     }
1468 
1469     /* We must disconnect after NBD_CMD_WRITE if we did not
1470      * read the payload.
1471      */
1472     if (!req->complete) {
1473         error_setg(&local_err, "Request handling failed in intermediate state");
1474         goto disconnect;
1475     }
1476 
1477 done:
1478     nbd_request_put(req);
1479     nbd_client_put(client);
1480     return;
1481 
1482 disconnect:
1483     if (local_err) {
1484         error_reportf_err(local_err, "Disconnect client, due to: ");
1485     }
1486     nbd_request_put(req);
1487     client_close(client, true);
1488     nbd_client_put(client);
1489 }
1490 
1491 static void nbd_client_receive_next_request(NBDClient *client)
1492 {
1493     if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
1494         nbd_client_get(client);
1495         client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
1496         aio_co_schedule(client->exp->ctx, client->recv_coroutine);
1497     }
1498 }
1499 
1500 static coroutine_fn void nbd_co_client_start(void *opaque)
1501 {
1502     NBDClient *client = opaque;
1503     NBDExport *exp = client->exp;
1504     Error *local_err = NULL;
1505 
1506     if (exp) {
1507         nbd_export_get(exp);
1508         QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1509     }
1510     qemu_co_mutex_init(&client->send_lock);
1511 
1512     if (nbd_negotiate(client, &local_err)) {
1513         if (local_err) {
1514             error_report_err(local_err);
1515         }
1516         client_close(client, false);
1517         return;
1518     }
1519 
1520     nbd_client_receive_next_request(client);
1521 }
1522 
1523 /*
1524  * Create a new client listener on the given export @exp, using the
1525  * given channel @sioc.  Begin servicing it in a coroutine.  When the
1526  * connection closes, call @close_fn with an indication of whether the
1527  * client completed negotiation.
1528  */
1529 void nbd_client_new(NBDExport *exp,
1530                     QIOChannelSocket *sioc,
1531                     QCryptoTLSCreds *tlscreds,
1532                     const char *tlsaclname,
1533                     void (*close_fn)(NBDClient *, bool))
1534 {
1535     NBDClient *client;
1536     Coroutine *co;
1537 
1538     client = g_malloc0(sizeof(NBDClient));
1539     client->refcount = 1;
1540     client->exp = exp;
1541     client->tlscreds = tlscreds;
1542     if (tlscreds) {
1543         object_ref(OBJECT(client->tlscreds));
1544     }
1545     client->tlsaclname = g_strdup(tlsaclname);
1546     client->sioc = sioc;
1547     object_ref(OBJECT(client->sioc));
1548     client->ioc = QIO_CHANNEL(sioc);
1549     object_ref(OBJECT(client->ioc));
1550     client->close_fn = close_fn;
1551 
1552     co = qemu_coroutine_create(nbd_co_client_start, client);
1553     qemu_coroutine_enter(co);
1554 }
1555