nbd: Add qemu-nbd -D for human-readable description
[qemu.git] / nbd / server.c
0 / 1353 (  0%)
CommitLineData
1/*
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
3 *
4 * Network Block Device Server Side
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; under version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
17 */
18
19#include "qemu/osdep.h"
20#include "qapi/error.h"
21#include "nbd-internal.h"
22
23static int system_errno_to_nbd_errno(int err)
24{
25 switch (err) {
26 case 0:
27 return NBD_SUCCESS;
28 case EPERM:
29 case EROFS:
30 return NBD_EPERM;
31 case EIO:
32 return NBD_EIO;
33 case ENOMEM:
34 return NBD_ENOMEM;
35#ifdef EDQUOT
36 case EDQUOT:
37#endif
38 case EFBIG:
39 case ENOSPC:
40 return NBD_ENOSPC;
41 case EINVAL:
42 default:
43 return NBD_EINVAL;
44 }
45}
46
47/* Definitions for opaque data types */
48
49typedef struct NBDRequest NBDRequest;
50
51struct NBDRequest {
52 QSIMPLEQ_ENTRY(NBDRequest) entry;
53 NBDClient *client;
54 uint8_t *data;
55 bool complete;
56};
57
58struct NBDExport {
59 int refcount;
60 void (*close)(NBDExport *exp);
61
62 BlockBackend *blk;
63 char *name;
64 char *description;
65 off_t dev_offset;
66 off_t size;
67 uint16_t nbdflags;
68 QTAILQ_HEAD(, NBDClient) clients;
69 QTAILQ_ENTRY(NBDExport) next;
70
71 AioContext *ctx;
72
73 BlockBackend *eject_notifier_blk;
74 Notifier eject_notifier;
75};
76
77static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
78
79struct NBDClient {
80 int refcount;
81 void (*close)(NBDClient *client);
82
83 NBDExport *exp;
84 QCryptoTLSCreds *tlscreds;
85 char *tlsaclname;
86 QIOChannelSocket *sioc; /* The underlying data channel */
87 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
88
89 Coroutine *recv_coroutine;
90
91 CoMutex send_lock;
92 Coroutine *send_coroutine;
93
94 bool can_read;
95
96 QTAILQ_ENTRY(NBDClient) next;
97 int nb_requests;
98 bool closing;
99};
100
101/* That's all folks */
102
103static void nbd_set_handlers(NBDClient *client);
104static void nbd_unset_handlers(NBDClient *client);
105static void nbd_update_can_read(NBDClient *client);
106
107static gboolean nbd_negotiate_continue(QIOChannel *ioc,
108 GIOCondition condition,
109 void *opaque)
110{
111 qemu_coroutine_enter(opaque);
112 return TRUE;
113}
114
115static ssize_t nbd_negotiate_read(QIOChannel *ioc, void *buffer, size_t size)
116{
117 ssize_t ret;
118 guint watch;
119
120 assert(qemu_in_coroutine());
121 /* Negotiation are always in main loop. */
122 watch = qio_channel_add_watch(ioc,
123 G_IO_IN,
124 nbd_negotiate_continue,
125 qemu_coroutine_self(),
126 NULL);
127 ret = read_sync(ioc, buffer, size);
128 g_source_remove(watch);
129 return ret;
130
131}
132
133static ssize_t nbd_negotiate_write(QIOChannel *ioc, const void *buffer,
134 size_t size)
135{
136 ssize_t ret;
137 guint watch;
138
139 assert(qemu_in_coroutine());
140 /* Negotiation are always in main loop. */
141 watch = qio_channel_add_watch(ioc,
142 G_IO_OUT,
143 nbd_negotiate_continue,
144 qemu_coroutine_self(),
145 NULL);
146 ret = write_sync(ioc, buffer, size);
147 g_source_remove(watch);
148 return ret;
149}
150
151static ssize_t nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
152{
153 ssize_t ret, dropped = size;
154 uint8_t *buffer = g_malloc(MIN(65536, size));
155
156 while (size > 0) {
157 ret = nbd_negotiate_read(ioc, buffer, MIN(65536, size));
158 if (ret < 0) {
159 g_free(buffer);
160 return ret;
161 }
162
163 assert(ret <= size);
164 size -= ret;
165 }
166
167 g_free(buffer);
168 return dropped;
169}
170
171/* Basic flow for negotiation
172
173 Server Client
174 Negotiate
175
176 or
177
178 Server Client
179 Negotiate #1
180 Option
181 Negotiate #2
182
183 ----
184
185 followed by
186
187 Server Client
188 Request
189 Response
190 Request
191 Response
192 ...
193 ...
194 Request (type == 2)
195
196*/
197
198static int nbd_negotiate_send_rep(QIOChannel *ioc, uint32_t type, uint32_t opt)
199{
200 uint64_t magic;
201 uint32_t len;
202
203 TRACE("Reply opt=%" PRIx32 " type=%" PRIx32, type, opt);
204
205 magic = cpu_to_be64(NBD_REP_MAGIC);
206 if (nbd_negotiate_write(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
207 LOG("write failed (rep magic)");
208 return -EINVAL;
209 }
210 opt = cpu_to_be32(opt);
211 if (nbd_negotiate_write(ioc, &opt, sizeof(opt)) != sizeof(opt)) {
212 LOG("write failed (rep opt)");
213 return -EINVAL;
214 }
215 type = cpu_to_be32(type);
216 if (nbd_negotiate_write(ioc, &type, sizeof(type)) != sizeof(type)) {
217 LOG("write failed (rep type)");
218 return -EINVAL;
219 }
220 len = cpu_to_be32(0);
221 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
222 LOG("write failed (rep data length)");
223 return -EINVAL;
224 }
225 return 0;
226}
227
228static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp)
229{
230 uint64_t magic;
231 size_t name_len, desc_len;
232 uint32_t opt, type, len;
233 const char *name = exp->name ? exp->name : "";
234 const char *desc = exp->description ? exp->description : "";
235
236 TRACE("Advertising export name '%s' description '%s'", name, desc);
237 name_len = strlen(name);
238 desc_len = strlen(desc);
239 magic = cpu_to_be64(NBD_REP_MAGIC);
240 if (nbd_negotiate_write(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
241 LOG("write failed (magic)");
242 return -EINVAL;
243 }
244 opt = cpu_to_be32(NBD_OPT_LIST);
245 if (nbd_negotiate_write(ioc, &opt, sizeof(opt)) != sizeof(opt)) {
246 LOG("write failed (opt)");
247 return -EINVAL;
248 }
249 type = cpu_to_be32(NBD_REP_SERVER);
250 if (nbd_negotiate_write(ioc, &type, sizeof(type)) != sizeof(type)) {
251 LOG("write failed (reply type)");
252 return -EINVAL;
253 }
254 len = cpu_to_be32(name_len + desc_len + sizeof(len));
255 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
256 LOG("write failed (length)");
257 return -EINVAL;
258 }
259 len = cpu_to_be32(name_len);
260 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
261 LOG("write failed (name length)");
262 return -EINVAL;
263 }
264 if (nbd_negotiate_write(ioc, name, name_len) != name_len) {
265 LOG("write failed (name buffer)");
266 return -EINVAL;
267 }
268 if (nbd_negotiate_write(ioc, desc, desc_len) != desc_len) {
269 LOG("write failed (description buffer)");
270 return -EINVAL;
271 }
272 return 0;
273}
274
275static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length)
276{
277 NBDExport *exp;
278
279 if (length) {
280 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
281 return -EIO;
282 }
283 return nbd_negotiate_send_rep(client->ioc,
284 NBD_REP_ERR_INVALID, NBD_OPT_LIST);
285 }
286
287 /* For each export, send a NBD_REP_SERVER reply. */
288 QTAILQ_FOREACH(exp, &exports, next) {
289 if (nbd_negotiate_send_rep_list(client->ioc, exp)) {
290 return -EINVAL;
291 }
292 }
293 /* Finish with a NBD_REP_ACK. */
294 return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST);
295}
296
297static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length)
298{
299 int rc = -EINVAL;
300 char name[NBD_MAX_NAME_SIZE + 1];
301
302 /* Client sends:
303 [20 .. xx] export name (length bytes)
304 */
305 TRACE("Checking length");
306 if (length >= sizeof(name)) {
307 LOG("Bad length received");
308 goto fail;
309 }
310 if (nbd_negotiate_read(client->ioc, name, length) != length) {
311 LOG("read failed");
312 goto fail;
313 }
314 name[length] = '\0';
315
316 TRACE("Client requested export '%s'", name);
317
318 client->exp = nbd_export_find(name);
319 if (!client->exp) {
320 LOG("export not found");
321 goto fail;
322 }
323
324 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
325 nbd_export_get(client->exp);
326 rc = 0;
327fail:
328 return rc;
329}
330
331
332static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
333 uint32_t length)
334{
335 QIOChannel *ioc;
336 QIOChannelTLS *tioc;
337 struct NBDTLSHandshakeData data = { 0 };
338
339 TRACE("Setting up TLS");
340 ioc = client->ioc;
341 if (length) {
342 if (nbd_negotiate_drop_sync(ioc, length) != length) {
343 return NULL;
344 }
345 nbd_negotiate_send_rep(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS);
346 return NULL;
347 }
348
349 if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
350 NBD_OPT_STARTTLS) < 0) {
351 return NULL;
352 }
353
354 tioc = qio_channel_tls_new_server(ioc,
355 client->tlscreds,
356 client->tlsaclname,
357 NULL);
358 if (!tioc) {
359 return NULL;
360 }
361
362 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
363 TRACE("Starting TLS handshake");
364 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
365 qio_channel_tls_handshake(tioc,
366 nbd_tls_handshake,
367 &data,
368 NULL);
369
370 if (!data.complete) {
371 g_main_loop_run(data.loop);
372 }
373 g_main_loop_unref(data.loop);
374 if (data.error) {
375 object_unref(OBJECT(tioc));
376 error_free(data.error);
377 return NULL;
378 }
379
380 return QIO_CHANNEL(tioc);
381}
382
383
384static int nbd_negotiate_options(NBDClient *client)
385{
386 uint32_t flags;
387 bool fixedNewstyle = false;
388
389 /* Client sends:
390 [ 0 .. 3] client flags
391
392 [ 0 .. 7] NBD_OPTS_MAGIC
393 [ 8 .. 11] NBD option
394 [12 .. 15] Data length
395 ... Rest of request
396
397 [ 0 .. 7] NBD_OPTS_MAGIC
398 [ 8 .. 11] Second NBD option
399 [12 .. 15] Data length
400 ... Rest of request
401 */
402
403 if (nbd_negotiate_read(client->ioc, &flags, sizeof(flags)) !=
404 sizeof(flags)) {
405 LOG("read failed");
406 return -EIO;
407 }
408 TRACE("Checking client flags");
409 be32_to_cpus(&flags);
410 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
411 TRACE("Client supports fixed newstyle handshake");
412 fixedNewstyle = true;
413 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
414 }
415 if (flags != 0) {
416 TRACE("Unknown client flags 0x%" PRIx32 " received", flags);
417 return -EIO;
418 }
419
420 while (1) {
421 int ret;
422 uint32_t clientflags, length;
423 uint64_t magic;
424
425 if (nbd_negotiate_read(client->ioc, &magic, sizeof(magic)) !=
426 sizeof(magic)) {
427 LOG("read failed");
428 return -EINVAL;
429 }
430 TRACE("Checking opts magic");
431 if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
432 LOG("Bad magic received");
433 return -EINVAL;
434 }
435
436 if (nbd_negotiate_read(client->ioc, &clientflags,
437 sizeof(clientflags)) != sizeof(clientflags)) {
438 LOG("read failed");
439 return -EINVAL;
440 }
441 clientflags = be32_to_cpu(clientflags);
442
443 if (nbd_negotiate_read(client->ioc, &length, sizeof(length)) !=
444 sizeof(length)) {
445 LOG("read failed");
446 return -EINVAL;
447 }
448 length = be32_to_cpu(length);
449
450 TRACE("Checking option 0x%" PRIx32, clientflags);
451 if (client->tlscreds &&
452 client->ioc == (QIOChannel *)client->sioc) {
453 QIOChannel *tioc;
454 if (!fixedNewstyle) {
455 TRACE("Unsupported option 0x%" PRIx32, clientflags);
456 return -EINVAL;
457 }
458 switch (clientflags) {
459 case NBD_OPT_STARTTLS:
460 tioc = nbd_negotiate_handle_starttls(client, length);
461 if (!tioc) {
462 return -EIO;
463 }
464 object_unref(OBJECT(client->ioc));
465 client->ioc = QIO_CHANNEL(tioc);
466 break;
467
468 case NBD_OPT_EXPORT_NAME:
469 /* No way to return an error to client, so drop connection */
470 TRACE("Option 0x%x not permitted before TLS", clientflags);
471 return -EINVAL;
472
473 default:
474 TRACE("Option 0x%" PRIx32 " not permitted before TLS",
475 clientflags);
476 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
477 return -EIO;
478 }
479 ret = nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_TLS_REQD,
480 clientflags);
481 if (ret < 0) {
482 return ret;
483 }
484 break;
485 }
486 } else if (fixedNewstyle) {
487 switch (clientflags) {
488 case NBD_OPT_LIST:
489 ret = nbd_negotiate_handle_list(client, length);
490 if (ret < 0) {
491 return ret;
492 }
493 break;
494
495 case NBD_OPT_ABORT:
496 return -EINVAL;
497
498 case NBD_OPT_EXPORT_NAME:
499 return nbd_negotiate_handle_export_name(client, length);
500
501 case NBD_OPT_STARTTLS:
502 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
503 return -EIO;
504 }
505 if (client->tlscreds) {
506 TRACE("TLS already enabled");
507 ret = nbd_negotiate_send_rep(client->ioc,
508 NBD_REP_ERR_INVALID,
509 clientflags);
510 } else {
511 TRACE("TLS not configured");
512 ret = nbd_negotiate_send_rep(client->ioc,
513 NBD_REP_ERR_POLICY,
514 clientflags);
515 }
516 if (ret < 0) {
517 return ret;
518 }
519 break;
520 default:
521 TRACE("Unsupported option 0x%" PRIx32, clientflags);
522 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
523 return -EIO;
524 }
525 ret = nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_UNSUP,
526 clientflags);
527 if (ret < 0) {
528 return ret;
529 }
530 break;
531 }
532 } else {
533 /*
534 * If broken new-style we should drop the connection
535 * for anything except NBD_OPT_EXPORT_NAME
536 */
537 switch (clientflags) {
538 case NBD_OPT_EXPORT_NAME:
539 return nbd_negotiate_handle_export_name(client, length);
540
541 default:
542 TRACE("Unsupported option 0x%" PRIx32, clientflags);
543 return -EINVAL;
544 }
545 }
546 }
547}
548
549typedef struct {
550 NBDClient *client;
551 Coroutine *co;
552} NBDClientNewData;
553
554static coroutine_fn int nbd_negotiate(NBDClientNewData *data)
555{
556 NBDClient *client = data->client;
557 char buf[8 + 8 + 8 + 128];
558 int rc;
559 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
560 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
561 bool oldStyle;
562
563 /* Old style negotiation header without options
564 [ 0 .. 7] passwd ("NBDMAGIC")
565 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
566 [16 .. 23] size
567 [24 .. 25] server flags (0)
568 [26 .. 27] export flags
569 [28 .. 151] reserved (0)
570
571 New style negotiation header with options
572 [ 0 .. 7] passwd ("NBDMAGIC")
573 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
574 [16 .. 17] server flags (0)
575 ....options sent....
576 [18 .. 25] size
577 [26 .. 27] export flags
578 [28 .. 151] reserved (0)
579 */
580
581 qio_channel_set_blocking(client->ioc, false, NULL);
582 rc = -EINVAL;
583
584 TRACE("Beginning negotiation.");
585 memset(buf, 0, sizeof(buf));
586 memcpy(buf, "NBDMAGIC", 8);
587
588 oldStyle = client->exp != NULL && !client->tlscreds;
589 if (oldStyle) {
590 TRACE("advertising size %" PRIu64 " and flags %x",
591 client->exp->size, client->exp->nbdflags | myflags);
592 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
593 stq_be_p(buf + 16, client->exp->size);
594 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
595 } else {
596 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
597 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE);
598 }
599
600 if (oldStyle) {
601 if (client->tlscreds) {
602 TRACE("TLS cannot be enabled with oldstyle protocol");
603 goto fail;
604 }
605 if (nbd_negotiate_write(client->ioc, buf, sizeof(buf)) != sizeof(buf)) {
606 LOG("write failed");
607 goto fail;
608 }
609 } else {
610 if (nbd_negotiate_write(client->ioc, buf, 18) != 18) {
611 LOG("write failed");
612 goto fail;
613 }
614 rc = nbd_negotiate_options(client);
615 if (rc != 0) {
616 LOG("option negotiation failed");
617 goto fail;
618 }
619
620 TRACE("advertising size %" PRIu64 " and flags %x",
621 client->exp->size, client->exp->nbdflags | myflags);
622 stq_be_p(buf + 18, client->exp->size);
623 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
624 if (nbd_negotiate_write(client->ioc, buf + 18, sizeof(buf) - 18) !=
625 sizeof(buf) - 18) {
626 LOG("write failed");
627 goto fail;
628 }
629 }
630
631 TRACE("Negotiation succeeded.");
632 rc = 0;
633fail:
634 return rc;
635}
636
637static ssize_t nbd_receive_request(QIOChannel *ioc, struct nbd_request *request)
638{
639 uint8_t buf[NBD_REQUEST_SIZE];
640 uint32_t magic;
641 ssize_t ret;
642
643 ret = read_sync(ioc, buf, sizeof(buf));
644 if (ret < 0) {
645 return ret;
646 }
647
648 if (ret != sizeof(buf)) {
649 LOG("read failed");
650 return -EINVAL;
651 }
652
653 /* Request
654 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
655 [ 4 .. 7] type (0 == READ, 1 == WRITE)
656 [ 8 .. 15] handle
657 [16 .. 23] from
658 [24 .. 27] len
659 */
660
661 magic = ldl_be_p(buf);
662 request->type = ldl_be_p(buf + 4);
663 request->handle = ldq_be_p(buf + 8);
664 request->from = ldq_be_p(buf + 16);
665 request->len = ldl_be_p(buf + 24);
666
667 TRACE("Got request: { magic = 0x%" PRIx32 ", .type = %" PRIx32
668 ", from = %" PRIu64 " , len = %" PRIu32 " }",
669 magic, request->type, request->from, request->len);
670
671 if (magic != NBD_REQUEST_MAGIC) {
672 LOG("invalid magic (got 0x%" PRIx32 ")", magic);
673 return -EINVAL;
674 }
675 return 0;
676}
677
678static ssize_t nbd_send_reply(QIOChannel *ioc, struct nbd_reply *reply)
679{
680 uint8_t buf[NBD_REPLY_SIZE];
681 ssize_t ret;
682
683 reply->error = system_errno_to_nbd_errno(reply->error);
684
685 TRACE("Sending response to client: { .error = %" PRId32
686 ", handle = %" PRIu64 " }",
687 reply->error, reply->handle);
688
689 /* Reply
690 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
691 [ 4 .. 7] error (0 == no error)
692 [ 7 .. 15] handle
693 */
694 stl_be_p(buf, NBD_REPLY_MAGIC);
695 stl_be_p(buf + 4, reply->error);
696 stq_be_p(buf + 8, reply->handle);
697
698 ret = write_sync(ioc, buf, sizeof(buf));
699 if (ret < 0) {
700 return ret;
701 }
702
703 if (ret != sizeof(buf)) {
704 LOG("writing to socket failed");
705 return -EINVAL;
706 }
707 return 0;
708}
709
710#define MAX_NBD_REQUESTS 16
711
712void nbd_client_get(NBDClient *client)
713{
714 client->refcount++;
715}
716
717void nbd_client_put(NBDClient *client)
718{
719 if (--client->refcount == 0) {
720 /* The last reference should be dropped by client->close,
721 * which is called by client_close.
722 */
723 assert(client->closing);
724
725 nbd_unset_handlers(client);
726 object_unref(OBJECT(client->sioc));
727 object_unref(OBJECT(client->ioc));
728 if (client->tlscreds) {
729 object_unref(OBJECT(client->tlscreds));
730 }
731 g_free(client->tlsaclname);
732 if (client->exp) {
733 QTAILQ_REMOVE(&client->exp->clients, client, next);
734 nbd_export_put(client->exp);
735 }
736 g_free(client);
737 }
738}
739
740static void client_close(NBDClient *client)
741{
742 if (client->closing) {
743 return;
744 }
745
746 client->closing = true;
747
748 /* Force requests to finish. They will drop their own references,
749 * then we'll close the socket and free the NBDClient.
750 */
751 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
752 NULL);
753
754 /* Also tell the client, so that they release their reference. */
755 if (client->close) {
756 client->close(client);
757 }
758}
759
760static NBDRequest *nbd_request_get(NBDClient *client)
761{
762 NBDRequest *req;
763
764 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
765 client->nb_requests++;
766 nbd_update_can_read(client);
767
768 req = g_new0(NBDRequest, 1);
769 nbd_client_get(client);
770 req->client = client;
771 return req;
772}
773
774static void nbd_request_put(NBDRequest *req)
775{
776 NBDClient *client = req->client;
777
778 if (req->data) {
779 qemu_vfree(req->data);
780 }
781 g_free(req);
782
783 client->nb_requests--;
784 nbd_update_can_read(client);
785 nbd_client_put(client);
786}
787
788static void blk_aio_attached(AioContext *ctx, void *opaque)
789{
790 NBDExport *exp = opaque;
791 NBDClient *client;
792
793 TRACE("Export %s: Attaching clients to AIO context %p\n", exp->name, ctx);
794
795 exp->ctx = ctx;
796
797 QTAILQ_FOREACH(client, &exp->clients, next) {
798 nbd_set_handlers(client);
799 }
800}
801
802static void blk_aio_detach(void *opaque)
803{
804 NBDExport *exp = opaque;
805 NBDClient *client;
806
807 TRACE("Export %s: Detaching clients from AIO context %p\n", exp->name, exp->ctx);
808
809 QTAILQ_FOREACH(client, &exp->clients, next) {
810 nbd_unset_handlers(client);
811 }
812
813 exp->ctx = NULL;
814}
815
816static void nbd_eject_notifier(Notifier *n, void *data)
817{
818 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
819 nbd_export_close(exp);
820}
821
822NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
823 uint16_t nbdflags, void (*close)(NBDExport *),
824 bool writethrough, BlockBackend *on_eject_blk,
825 Error **errp)
826{
827 BlockBackend *blk;
828 NBDExport *exp = g_malloc0(sizeof(NBDExport));
829
830 blk = blk_new();
831 blk_insert_bs(blk, bs);
832 blk_set_enable_write_cache(blk, !writethrough);
833
834 exp->refcount = 1;
835 QTAILQ_INIT(&exp->clients);
836 exp->blk = blk;
837 exp->dev_offset = dev_offset;
838 exp->nbdflags = nbdflags;
839 exp->size = size < 0 ? blk_getlength(blk) : size;
840 if (exp->size < 0) {
841 error_setg_errno(errp, -exp->size,
842 "Failed to determine the NBD export's length");
843 goto fail;
844 }
845 exp->size -= exp->size % BDRV_SECTOR_SIZE;
846
847 exp->close = close;
848 exp->ctx = blk_get_aio_context(blk);
849 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
850
851 if (on_eject_blk) {
852 blk_ref(on_eject_blk);
853 exp->eject_notifier_blk = on_eject_blk;
854 exp->eject_notifier.notify = nbd_eject_notifier;
855 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
856 }
857
858 /*
859 * NBD exports are used for non-shared storage migration. Make sure
860 * that BDRV_O_INACTIVE is cleared and the image is ready for write
861 * access since the export could be available before migration handover.
862 */
863 aio_context_acquire(exp->ctx);
864 blk_invalidate_cache(blk, NULL);
865 aio_context_release(exp->ctx);
866 return exp;
867
868fail:
869 blk_unref(blk);
870 g_free(exp);
871 return NULL;
872}
873
874NBDExport *nbd_export_find(const char *name)
875{
876 NBDExport *exp;
877 QTAILQ_FOREACH(exp, &exports, next) {
878 if (strcmp(name, exp->name) == 0) {
879 return exp;
880 }
881 }
882
883 return NULL;
884}
885
886void nbd_export_set_name(NBDExport *exp, const char *name)
887{
888 if (exp->name == name) {
889 return;
890 }
891
892 nbd_export_get(exp);
893 if (exp->name != NULL) {
894 g_free(exp->name);
895 exp->name = NULL;
896 QTAILQ_REMOVE(&exports, exp, next);
897 nbd_export_put(exp);
898 }
899 if (name != NULL) {
900 nbd_export_get(exp);
901 exp->name = g_strdup(name);
902 QTAILQ_INSERT_TAIL(&exports, exp, next);
903 }
904 nbd_export_put(exp);
905}
906
907void nbd_export_set_description(NBDExport *exp, const char *description)
908{
909 g_free(exp->description);
910 exp->description = g_strdup(description);
911}
912
913void nbd_export_close(NBDExport *exp)
914{
915 NBDClient *client, *next;
916
917 nbd_export_get(exp);
918 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
919 client_close(client);
920 }
921 nbd_export_set_name(exp, NULL);
922 nbd_export_set_description(exp, NULL);
923 nbd_export_put(exp);
924}
925
926void nbd_export_get(NBDExport *exp)
927{
928 assert(exp->refcount > 0);
929 exp->refcount++;
930}
931
932void nbd_export_put(NBDExport *exp)
933{
934 assert(exp->refcount > 0);
935 if (exp->refcount == 1) {
936 nbd_export_close(exp);
937 }
938
939 if (--exp->refcount == 0) {
940 assert(exp->name == NULL);
941 assert(exp->description == NULL);
942
943 if (exp->close) {
944 exp->close(exp);
945 }
946
947 if (exp->blk) {
948 if (exp->eject_notifier_blk) {
949 notifier_remove(&exp->eject_notifier);
950 blk_unref(exp->eject_notifier_blk);
951 }
952 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
953 blk_aio_detach, exp);
954 blk_unref(exp->blk);
955 exp->blk = NULL;
956 }
957
958 g_free(exp);
959 }
960}
961
962BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
963{
964 return exp->blk;
965}
966
967void nbd_export_close_all(void)
968{
969 NBDExport *exp, *next;
970
971 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
972 nbd_export_close(exp);
973 }
974}
975
976static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
977 int len)
978{
979 NBDClient *client = req->client;
980 ssize_t rc, ret;
981
982 g_assert(qemu_in_coroutine());
983 qemu_co_mutex_lock(&client->send_lock);
984 client->send_coroutine = qemu_coroutine_self();
985 nbd_set_handlers(client);
986
987 if (!len) {
988 rc = nbd_send_reply(client->ioc, reply);
989 } else {
990 qio_channel_set_cork(client->ioc, true);
991 rc = nbd_send_reply(client->ioc, reply);
992 if (rc >= 0) {
993 ret = write_sync(client->ioc, req->data, len);
994 if (ret != len) {
995 rc = -EIO;
996 }
997 }
998 qio_channel_set_cork(client->ioc, false);
999 }
1000
1001 client->send_coroutine = NULL;
1002 nbd_set_handlers(client);
1003 qemu_co_mutex_unlock(&client->send_lock);
1004 return rc;
1005}
1006
1007/* Collect a client request. Return 0 if request looks valid, -EAGAIN
1008 * to keep trying the collection, -EIO to drop connection right away,
1009 * and any other negative value to report an error to the client
1010 * (although the caller may still need to disconnect after reporting
1011 * the error). */
1012static ssize_t nbd_co_receive_request(NBDRequest *req,
1013 struct nbd_request *request)
1014{
1015 NBDClient *client = req->client;
1016 uint32_t command;
1017 ssize_t rc;
1018
1019 g_assert(qemu_in_coroutine());
1020 client->recv_coroutine = qemu_coroutine_self();
1021 nbd_update_can_read(client);
1022
1023 rc = nbd_receive_request(client->ioc, request);
1024 if (rc < 0) {
1025 if (rc != -EAGAIN) {
1026 rc = -EIO;
1027 }
1028 goto out;
1029 }
1030
1031 TRACE("Decoding type");
1032
1033 command = request->type & NBD_CMD_MASK_COMMAND;
1034 if (command != NBD_CMD_WRITE) {
1035 /* No payload, we are ready to read the next request. */
1036 req->complete = true;
1037 }
1038
1039 if (command == NBD_CMD_DISC) {
1040 /* Special case: we're going to disconnect without a reply,
1041 * whether or not flags, from, or len are bogus */
1042 TRACE("Request type is DISCONNECT");
1043 rc = -EIO;
1044 goto out;
1045 }
1046
1047 /* Check for sanity in the parameters, part 1. Defer as many
1048 * checks as possible until after reading any NBD_CMD_WRITE
1049 * payload, so we can try and keep the connection alive. */
1050 if ((request->from + request->len) < request->from) {
1051 LOG("integer overflow detected, you're probably being attacked");
1052 rc = -EINVAL;
1053 goto out;
1054 }
1055
1056 if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {
1057 if (request->len > NBD_MAX_BUFFER_SIZE) {
1058 LOG("len (%" PRIu32" ) is larger than max len (%u)",
1059 request->len, NBD_MAX_BUFFER_SIZE);
1060 rc = -EINVAL;
1061 goto out;
1062 }
1063
1064 req->data = blk_try_blockalign(client->exp->blk, request->len);
1065 if (req->data == NULL) {
1066 rc = -ENOMEM;
1067 goto out;
1068 }
1069 }
1070 if (command == NBD_CMD_WRITE) {
1071 TRACE("Reading %" PRIu32 " byte(s)", request->len);
1072
1073 if (read_sync(client->ioc, req->data, request->len) != request->len) {
1074 LOG("reading from socket failed");
1075 rc = -EIO;
1076 goto out;
1077 }
1078 req->complete = true;
1079 }
1080
1081 /* Sanity checks, part 2. */
1082 if (request->from + request->len > client->exp->size) {
1083 LOG("operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1084 ", Size: %" PRIu64, request->from, request->len,
1085 (uint64_t)client->exp->size);
1086 rc = command == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;
1087 goto out;
1088 }
1089 if (request->type & ~NBD_CMD_MASK_COMMAND & ~NBD_CMD_FLAG_FUA) {
1090 LOG("unsupported flags (got 0x%x)",
1091 request->type & ~NBD_CMD_MASK_COMMAND);
1092 rc = -EINVAL;
1093 goto out;
1094 }
1095
1096 rc = 0;
1097
1098out:
1099 client->recv_coroutine = NULL;
1100 nbd_update_can_read(client);
1101
1102 return rc;
1103}
1104
1105static void nbd_trip(void *opaque)
1106{
1107 NBDClient *client = opaque;
1108 NBDExport *exp = client->exp;
1109 NBDRequest *req;
1110 struct nbd_request request;
1111 struct nbd_reply reply;
1112 ssize_t ret;
1113 uint32_t command;
1114 int flags;
1115
1116 TRACE("Reading request.");
1117 if (client->closing) {
1118 return;
1119 }
1120
1121 req = nbd_request_get(client);
1122 ret = nbd_co_receive_request(req, &request);
1123 if (ret == -EAGAIN) {
1124 goto done;
1125 }
1126 if (ret == -EIO) {
1127 goto out;
1128 }
1129
1130 reply.handle = request.handle;
1131 reply.error = 0;
1132
1133 if (ret < 0) {
1134 reply.error = -ret;
1135 goto error_reply;
1136 }
1137 command = request.type & NBD_CMD_MASK_COMMAND;
1138
1139 if (client->closing) {
1140 /*
1141 * The client may be closed when we are blocked in
1142 * nbd_co_receive_request()
1143 */
1144 goto done;
1145 }
1146
1147 switch (command) {
1148 case NBD_CMD_READ:
1149 TRACE("Request type is READ");
1150
1151 if (request.type & NBD_CMD_FLAG_FUA) {
1152 ret = blk_co_flush(exp->blk);
1153 if (ret < 0) {
1154 LOG("flush failed");
1155 reply.error = -ret;
1156 goto error_reply;
1157 }
1158 }
1159
1160 ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1161 req->data, request.len);
1162 if (ret < 0) {
1163 LOG("reading from file failed");
1164 reply.error = -ret;
1165 goto error_reply;
1166 }
1167
1168 TRACE("Read %" PRIu32" byte(s)", request.len);
1169 if (nbd_co_send_reply(req, &reply, request.len) < 0)
1170 goto out;
1171 break;
1172 case NBD_CMD_WRITE:
1173 TRACE("Request type is WRITE");
1174
1175 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1176 TRACE("Server is read-only, return error");
1177 reply.error = EROFS;
1178 goto error_reply;
1179 }
1180
1181 TRACE("Writing to device");
1182
1183 flags = 0;
1184 if (request.type & NBD_CMD_FLAG_FUA) {
1185 flags |= BDRV_REQ_FUA;
1186 }
1187 ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
1188 req->data, request.len, flags);
1189 if (ret < 0) {
1190 LOG("writing to file failed");
1191 reply.error = -ret;
1192 goto error_reply;
1193 }
1194
1195 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1196 goto out;
1197 }
1198 break;
1199
1200 case NBD_CMD_DISC:
1201 /* unreachable, thanks to special case in nbd_co_receive_request() */
1202 abort();
1203
1204 case NBD_CMD_FLUSH:
1205 TRACE("Request type is FLUSH");
1206
1207 ret = blk_co_flush(exp->blk);
1208 if (ret < 0) {
1209 LOG("flush failed");
1210 reply.error = -ret;
1211 }
1212 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1213 goto out;
1214 }
1215 break;
1216 case NBD_CMD_TRIM:
1217 TRACE("Request type is TRIM");
1218 ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1219 request.len);
1220 if (ret < 0) {
1221 LOG("discard failed");
1222 reply.error = -ret;
1223 }
1224 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1225 goto out;
1226 }
1227 break;
1228 default:
1229 LOG("invalid request type (%" PRIu32 ") received", request.type);
1230 reply.error = EINVAL;
1231 error_reply:
1232 /* We must disconnect after NBD_CMD_WRITE if we did not
1233 * read the payload.
1234 */
1235 if (nbd_co_send_reply(req, &reply, 0) < 0 || !req->complete) {
1236 goto out;
1237 }
1238 break;
1239 }
1240
1241 TRACE("Request/Reply complete");
1242
1243done:
1244 nbd_request_put(req);
1245 return;
1246
1247out:
1248 nbd_request_put(req);
1249 client_close(client);
1250}
1251
1252static void nbd_read(void *opaque)
1253{
1254 NBDClient *client = opaque;
1255
1256 if (client->recv_coroutine) {
1257 qemu_coroutine_enter(client->recv_coroutine);
1258 } else {
1259 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip, client));
1260 }
1261}
1262
1263static void nbd_restart_write(void *opaque)
1264{
1265 NBDClient *client = opaque;
1266
1267 qemu_coroutine_enter(client->send_coroutine);
1268}
1269
1270static void nbd_set_handlers(NBDClient *client)
1271{
1272 if (client->exp && client->exp->ctx) {
1273 aio_set_fd_handler(client->exp->ctx, client->sioc->fd,
1274 true,
1275 client->can_read ? nbd_read : NULL,
1276 client->send_coroutine ? nbd_restart_write : NULL,
1277 client);
1278 }
1279}
1280
1281static void nbd_unset_handlers(NBDClient *client)
1282{
1283 if (client->exp && client->exp->ctx) {
1284 aio_set_fd_handler(client->exp->ctx, client->sioc->fd,
1285 true, NULL, NULL, NULL);
1286 }
1287}
1288
1289static void nbd_update_can_read(NBDClient *client)
1290{
1291 bool can_read = client->recv_coroutine ||
1292 client->nb_requests < MAX_NBD_REQUESTS;
1293
1294 if (can_read != client->can_read) {
1295 client->can_read = can_read;
1296 nbd_set_handlers(client);
1297
1298 /* There is no need to invoke aio_notify(), since aio_set_fd_handler()
1299 * in nbd_set_handlers() will have taken care of that */
1300 }
1301}
1302
1303static coroutine_fn void nbd_co_client_start(void *opaque)
1304{
1305 NBDClientNewData *data = opaque;
1306 NBDClient *client = data->client;
1307 NBDExport *exp = client->exp;
1308
1309 if (exp) {
1310 nbd_export_get(exp);
1311 }
1312 if (nbd_negotiate(data)) {
1313 client_close(client);
1314 goto out;
1315 }
1316 qemu_co_mutex_init(&client->send_lock);
1317 nbd_set_handlers(client);
1318
1319 if (exp) {
1320 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1321 }
1322out:
1323 g_free(data);
1324}
1325
1326void nbd_client_new(NBDExport *exp,
1327 QIOChannelSocket *sioc,
1328 QCryptoTLSCreds *tlscreds,
1329 const char *tlsaclname,
1330 void (*close_fn)(NBDClient *))
1331{
1332 NBDClient *client;
1333 NBDClientNewData *data = g_new(NBDClientNewData, 1);
1334
1335 client = g_malloc0(sizeof(NBDClient));
1336 client->refcount = 1;
1337 client->exp = exp;
1338 client->tlscreds = tlscreds;
1339 if (tlscreds) {
1340 object_ref(OBJECT(client->tlscreds));
1341 }
1342 client->tlsaclname = g_strdup(tlsaclname);
1343 client->sioc = sioc;
1344 object_ref(OBJECT(client->sioc));
1345 client->ioc = QIO_CHANNEL(sioc);
1346 object_ref(OBJECT(client->ioc));
1347 client->can_read = true;
1348 client->close = close_fn;
1349
1350 data->client = client;
1351 data->co = qemu_coroutine_create(nbd_co_client_start, data);
1352 qemu_coroutine_enter(data->co);
1353}
This page took 0.043243 seconds and 4 git commands to generate.