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