nbd: use "" as a default export name if none provided
[qemu/rayw.git] / nbd / server.c
blob9fee1d4fa4eec4e5d350a82f11443109b5f9eeb3
1 /*
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
4 * Network Block Device Server Side
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.
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.
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/>.
19 #include "qemu/osdep.h"
20 #include "nbd-internal.h"
22 static int system_errno_to_nbd_errno(int err)
24 switch (err) {
25 case 0:
26 return NBD_SUCCESS;
27 case EPERM:
28 return NBD_EPERM;
29 case EIO:
30 return NBD_EIO;
31 case ENOMEM:
32 return NBD_ENOMEM;
33 #ifdef EDQUOT
34 case EDQUOT:
35 #endif
36 case EFBIG:
37 case ENOSPC:
38 return NBD_ENOSPC;
39 case EINVAL:
40 default:
41 return NBD_EINVAL;
45 /* Definitions for opaque data types */
47 typedef struct NBDRequest NBDRequest;
49 struct NBDRequest {
50 QSIMPLEQ_ENTRY(NBDRequest) entry;
51 NBDClient *client;
52 uint8_t *data;
55 struct NBDExport {
56 int refcount;
57 void (*close)(NBDExport *exp);
59 BlockBackend *blk;
60 char *name;
61 off_t dev_offset;
62 off_t size;
63 uint32_t nbdflags;
64 QTAILQ_HEAD(, NBDClient) clients;
65 QTAILQ_ENTRY(NBDExport) next;
67 AioContext *ctx;
69 Notifier eject_notifier;
72 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
74 struct NBDClient {
75 int refcount;
76 void (*close)(NBDClient *client);
78 NBDExport *exp;
79 QIOChannelSocket *sioc; /* The underlying data channel */
80 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
82 Coroutine *recv_coroutine;
84 CoMutex send_lock;
85 Coroutine *send_coroutine;
87 bool can_read;
89 QTAILQ_ENTRY(NBDClient) next;
90 int nb_requests;
91 bool closing;
94 /* That's all folks */
96 static void nbd_set_handlers(NBDClient *client);
97 static void nbd_unset_handlers(NBDClient *client);
98 static void nbd_update_can_read(NBDClient *client);
100 static gboolean nbd_negotiate_continue(QIOChannel *ioc,
101 GIOCondition condition,
102 void *opaque)
104 qemu_coroutine_enter(opaque, NULL);
105 return TRUE;
108 static ssize_t nbd_negotiate_read(QIOChannel *ioc, void *buffer, size_t size)
110 ssize_t ret;
111 guint watch;
113 assert(qemu_in_coroutine());
114 /* Negotiation are always in main loop. */
115 watch = qio_channel_add_watch(ioc,
116 G_IO_IN,
117 nbd_negotiate_continue,
118 qemu_coroutine_self(),
119 NULL);
120 ret = read_sync(ioc, buffer, size);
121 g_source_remove(watch);
122 return ret;
126 static ssize_t nbd_negotiate_write(QIOChannel *ioc, void *buffer, size_t size)
128 ssize_t ret;
129 guint watch;
131 assert(qemu_in_coroutine());
132 /* Negotiation are always in main loop. */
133 watch = qio_channel_add_watch(ioc,
134 G_IO_OUT,
135 nbd_negotiate_continue,
136 qemu_coroutine_self(),
137 NULL);
138 ret = write_sync(ioc, buffer, size);
139 g_source_remove(watch);
140 return ret;
143 static ssize_t nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
145 ssize_t ret, dropped = size;
146 uint8_t *buffer = g_malloc(MIN(65536, size));
148 while (size > 0) {
149 ret = nbd_negotiate_read(ioc, buffer, MIN(65536, size));
150 if (ret < 0) {
151 g_free(buffer);
152 return ret;
155 assert(ret <= size);
156 size -= ret;
159 g_free(buffer);
160 return dropped;
163 /* Basic flow for negotiation
165 Server Client
166 Negotiate
170 Server Client
171 Negotiate #1
172 Option
173 Negotiate #2
175 ----
177 followed by
179 Server Client
180 Request
181 Response
182 Request
183 Response
186 Request (type == 2)
190 static int nbd_negotiate_send_rep(QIOChannel *ioc, uint32_t type, uint32_t opt)
192 uint64_t magic;
193 uint32_t len;
195 magic = cpu_to_be64(NBD_REP_MAGIC);
196 if (nbd_negotiate_write(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
197 LOG("write failed (rep magic)");
198 return -EINVAL;
200 opt = cpu_to_be32(opt);
201 if (nbd_negotiate_write(ioc, &opt, sizeof(opt)) != sizeof(opt)) {
202 LOG("write failed (rep opt)");
203 return -EINVAL;
205 type = cpu_to_be32(type);
206 if (nbd_negotiate_write(ioc, &type, sizeof(type)) != sizeof(type)) {
207 LOG("write failed (rep type)");
208 return -EINVAL;
210 len = cpu_to_be32(0);
211 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
212 LOG("write failed (rep data length)");
213 return -EINVAL;
215 return 0;
218 static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp)
220 uint64_t magic, name_len;
221 uint32_t opt, type, len;
223 TRACE("Advertizing export name '%s'", exp->name ? exp->name : "");
224 name_len = strlen(exp->name);
225 magic = cpu_to_be64(NBD_REP_MAGIC);
226 if (nbd_negotiate_write(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
227 LOG("write failed (magic)");
228 return -EINVAL;
230 opt = cpu_to_be32(NBD_OPT_LIST);
231 if (nbd_negotiate_write(ioc, &opt, sizeof(opt)) != sizeof(opt)) {
232 LOG("write failed (opt)");
233 return -EINVAL;
235 type = cpu_to_be32(NBD_REP_SERVER);
236 if (nbd_negotiate_write(ioc, &type, sizeof(type)) != sizeof(type)) {
237 LOG("write failed (reply type)");
238 return -EINVAL;
240 len = cpu_to_be32(name_len + sizeof(len));
241 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
242 LOG("write failed (length)");
243 return -EINVAL;
245 len = cpu_to_be32(name_len);
246 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
247 LOG("write failed (length)");
248 return -EINVAL;
250 if (nbd_negotiate_write(ioc, exp->name, name_len) != name_len) {
251 LOG("write failed (buffer)");
252 return -EINVAL;
254 return 0;
257 static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length)
259 NBDExport *exp;
261 if (length) {
262 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
263 return -EIO;
265 return nbd_negotiate_send_rep(client->ioc,
266 NBD_REP_ERR_INVALID, NBD_OPT_LIST);
269 /* For each export, send a NBD_REP_SERVER reply. */
270 QTAILQ_FOREACH(exp, &exports, next) {
271 if (nbd_negotiate_send_rep_list(client->ioc, exp)) {
272 return -EINVAL;
275 /* Finish with a NBD_REP_ACK. */
276 return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST);
279 static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length)
281 int rc = -EINVAL;
282 char name[256];
284 /* Client sends:
285 [20 .. xx] export name (length bytes)
287 TRACE("Checking length");
288 if (length > 255) {
289 LOG("Bad length received");
290 goto fail;
292 if (nbd_negotiate_read(client->ioc, name, length) != length) {
293 LOG("read failed");
294 goto fail;
296 name[length] = '\0';
298 TRACE("Client requested export '%s'", name);
300 client->exp = nbd_export_find(name);
301 if (!client->exp) {
302 LOG("export not found");
303 goto fail;
306 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
307 nbd_export_get(client->exp);
308 rc = 0;
309 fail:
310 return rc;
313 static int nbd_negotiate_options(NBDClient *client)
315 uint32_t flags;
316 bool fixedNewstyle = false;
318 /* Client sends:
319 [ 0 .. 3] client flags
321 [ 0 .. 7] NBD_OPTS_MAGIC
322 [ 8 .. 11] NBD option
323 [12 .. 15] Data length
324 ... Rest of request
326 [ 0 .. 7] NBD_OPTS_MAGIC
327 [ 8 .. 11] Second NBD option
328 [12 .. 15] Data length
329 ... Rest of request
332 if (nbd_negotiate_read(client->ioc, &flags, sizeof(flags)) !=
333 sizeof(flags)) {
334 LOG("read failed");
335 return -EIO;
337 TRACE("Checking client flags");
338 be32_to_cpus(&flags);
339 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
340 TRACE("Support supports fixed newstyle handshake");
341 fixedNewstyle = true;
342 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
344 if (flags != 0) {
345 TRACE("Unknown client flags 0x%x received", flags);
346 return -EIO;
349 while (1) {
350 int ret;
351 uint32_t clientflags, length;
352 uint64_t magic;
354 if (nbd_negotiate_read(client->ioc, &magic, sizeof(magic)) !=
355 sizeof(magic)) {
356 LOG("read failed");
357 return -EINVAL;
359 TRACE("Checking opts magic");
360 if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
361 LOG("Bad magic received");
362 return -EINVAL;
365 if (nbd_negotiate_read(client->ioc, &clientflags,
366 sizeof(clientflags)) != sizeof(clientflags)) {
367 LOG("read failed");
368 return -EINVAL;
370 clientflags = be32_to_cpu(clientflags);
372 if (nbd_negotiate_read(client->ioc, &length, sizeof(length)) !=
373 sizeof(length)) {
374 LOG("read failed");
375 return -EINVAL;
377 length = be32_to_cpu(length);
379 TRACE("Checking option 0x%x", clientflags);
380 if (fixedNewstyle) {
381 switch (clientflags) {
382 case NBD_OPT_LIST:
383 ret = nbd_negotiate_handle_list(client, length);
384 if (ret < 0) {
385 return ret;
387 break;
389 case NBD_OPT_ABORT:
390 return -EINVAL;
392 case NBD_OPT_EXPORT_NAME:
393 return nbd_negotiate_handle_export_name(client, length);
395 default:
396 TRACE("Unsupported option 0x%x", clientflags);
397 nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_UNSUP,
398 clientflags);
399 return -EINVAL;
401 } else {
403 * If broken new-style we should drop the connection
404 * for anything except NBD_OPT_EXPORT_NAME
406 switch (clientflags) {
407 case NBD_OPT_EXPORT_NAME:
408 return nbd_negotiate_handle_export_name(client, length);
410 default:
411 TRACE("Unsupported option 0x%x", clientflags);
412 return -EINVAL;
418 typedef struct {
419 NBDClient *client;
420 Coroutine *co;
421 } NBDClientNewData;
423 static coroutine_fn int nbd_negotiate(NBDClientNewData *data)
425 NBDClient *client = data->client;
426 char buf[8 + 8 + 8 + 128];
427 int rc;
428 const int myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
429 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
431 /* Negotiation header without options:
432 [ 0 .. 7] passwd ("NBDMAGIC")
433 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
434 [16 .. 23] size
435 [24 .. 25] server flags (0)
436 [26 .. 27] export flags
437 [28 .. 151] reserved (0)
439 Negotiation header with options, part 1:
440 [ 0 .. 7] passwd ("NBDMAGIC")
441 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
442 [16 .. 17] server flags (0)
444 part 2 (after options are sent):
445 [18 .. 25] size
446 [26 .. 27] export flags
447 [28 .. 151] reserved (0)
450 qio_channel_set_blocking(client->ioc, false, NULL);
451 rc = -EINVAL;
453 TRACE("Beginning negotiation.");
454 memset(buf, 0, sizeof(buf));
455 memcpy(buf, "NBDMAGIC", 8);
456 if (client->exp) {
457 assert ((client->exp->nbdflags & ~65535) == 0);
458 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
459 stq_be_p(buf + 16, client->exp->size);
460 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
461 } else {
462 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
463 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE);
466 if (client->exp) {
467 if (nbd_negotiate_write(client->ioc, buf, sizeof(buf)) != sizeof(buf)) {
468 LOG("write failed");
469 goto fail;
471 } else {
472 if (nbd_negotiate_write(client->ioc, buf, 18) != 18) {
473 LOG("write failed");
474 goto fail;
476 rc = nbd_negotiate_options(client);
477 if (rc != 0) {
478 LOG("option negotiation failed");
479 goto fail;
482 assert ((client->exp->nbdflags & ~65535) == 0);
483 stq_be_p(buf + 18, client->exp->size);
484 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
485 if (nbd_negotiate_write(client->ioc, buf + 18, sizeof(buf) - 18) !=
486 sizeof(buf) - 18) {
487 LOG("write failed");
488 goto fail;
492 TRACE("Negotiation succeeded.");
493 rc = 0;
494 fail:
495 return rc;
498 #ifdef __linux__
500 int nbd_disconnect(int fd)
502 ioctl(fd, NBD_CLEAR_QUE);
503 ioctl(fd, NBD_DISCONNECT);
504 ioctl(fd, NBD_CLEAR_SOCK);
505 return 0;
508 #else
510 int nbd_disconnect(int fd)
512 return -ENOTSUP;
514 #endif
516 static ssize_t nbd_receive_request(QIOChannel *ioc, struct nbd_request *request)
518 uint8_t buf[NBD_REQUEST_SIZE];
519 uint32_t magic;
520 ssize_t ret;
522 ret = read_sync(ioc, buf, sizeof(buf));
523 if (ret < 0) {
524 return ret;
527 if (ret != sizeof(buf)) {
528 LOG("read failed");
529 return -EINVAL;
532 /* Request
533 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
534 [ 4 .. 7] type (0 == READ, 1 == WRITE)
535 [ 8 .. 15] handle
536 [16 .. 23] from
537 [24 .. 27] len
540 magic = be32_to_cpup((uint32_t*)buf);
541 request->type = be32_to_cpup((uint32_t*)(buf + 4));
542 request->handle = be64_to_cpup((uint64_t*)(buf + 8));
543 request->from = be64_to_cpup((uint64_t*)(buf + 16));
544 request->len = be32_to_cpup((uint32_t*)(buf + 24));
546 TRACE("Got request: "
547 "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
548 magic, request->type, request->from, request->len);
550 if (magic != NBD_REQUEST_MAGIC) {
551 LOG("invalid magic (got 0x%x)", magic);
552 return -EINVAL;
554 return 0;
557 static ssize_t nbd_send_reply(QIOChannel *ioc, struct nbd_reply *reply)
559 uint8_t buf[NBD_REPLY_SIZE];
560 ssize_t ret;
562 reply->error = system_errno_to_nbd_errno(reply->error);
564 /* Reply
565 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
566 [ 4 .. 7] error (0 == no error)
567 [ 7 .. 15] handle
569 stl_be_p(buf, NBD_REPLY_MAGIC);
570 stl_be_p(buf + 4, reply->error);
571 stq_be_p(buf + 8, reply->handle);
573 TRACE("Sending response to client");
575 ret = write_sync(ioc, buf, sizeof(buf));
576 if (ret < 0) {
577 return ret;
580 if (ret != sizeof(buf)) {
581 LOG("writing to socket failed");
582 return -EINVAL;
584 return 0;
587 #define MAX_NBD_REQUESTS 16
589 void nbd_client_get(NBDClient *client)
591 client->refcount++;
594 void nbd_client_put(NBDClient *client)
596 if (--client->refcount == 0) {
597 /* The last reference should be dropped by client->close,
598 * which is called by client_close.
600 assert(client->closing);
602 nbd_unset_handlers(client);
603 object_unref(OBJECT(client->sioc));
604 object_unref(OBJECT(client->ioc));
605 if (client->exp) {
606 QTAILQ_REMOVE(&client->exp->clients, client, next);
607 nbd_export_put(client->exp);
609 g_free(client);
613 static void client_close(NBDClient *client)
615 if (client->closing) {
616 return;
619 client->closing = true;
621 /* Force requests to finish. They will drop their own references,
622 * then we'll close the socket and free the NBDClient.
624 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
625 NULL);
627 /* Also tell the client, so that they release their reference. */
628 if (client->close) {
629 client->close(client);
633 static NBDRequest *nbd_request_get(NBDClient *client)
635 NBDRequest *req;
637 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
638 client->nb_requests++;
639 nbd_update_can_read(client);
641 req = g_new0(NBDRequest, 1);
642 nbd_client_get(client);
643 req->client = client;
644 return req;
647 static void nbd_request_put(NBDRequest *req)
649 NBDClient *client = req->client;
651 if (req->data) {
652 qemu_vfree(req->data);
654 g_free(req);
656 client->nb_requests--;
657 nbd_update_can_read(client);
658 nbd_client_put(client);
661 static void blk_aio_attached(AioContext *ctx, void *opaque)
663 NBDExport *exp = opaque;
664 NBDClient *client;
666 TRACE("Export %s: Attaching clients to AIO context %p\n", exp->name, ctx);
668 exp->ctx = ctx;
670 QTAILQ_FOREACH(client, &exp->clients, next) {
671 nbd_set_handlers(client);
675 static void blk_aio_detach(void *opaque)
677 NBDExport *exp = opaque;
678 NBDClient *client;
680 TRACE("Export %s: Detaching clients from AIO context %p\n", exp->name, exp->ctx);
682 QTAILQ_FOREACH(client, &exp->clients, next) {
683 nbd_unset_handlers(client);
686 exp->ctx = NULL;
689 static void nbd_eject_notifier(Notifier *n, void *data)
691 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
692 nbd_export_close(exp);
695 NBDExport *nbd_export_new(BlockBackend *blk, off_t dev_offset, off_t size,
696 uint32_t nbdflags, void (*close)(NBDExport *),
697 Error **errp)
699 NBDExport *exp = g_malloc0(sizeof(NBDExport));
700 exp->refcount = 1;
701 QTAILQ_INIT(&exp->clients);
702 exp->blk = blk;
703 exp->dev_offset = dev_offset;
704 exp->nbdflags = nbdflags;
705 exp->size = size < 0 ? blk_getlength(blk) : size;
706 if (exp->size < 0) {
707 error_setg_errno(errp, -exp->size,
708 "Failed to determine the NBD export's length");
709 goto fail;
711 exp->size -= exp->size % BDRV_SECTOR_SIZE;
713 exp->close = close;
714 exp->ctx = blk_get_aio_context(blk);
715 blk_ref(blk);
716 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
718 exp->eject_notifier.notify = nbd_eject_notifier;
719 blk_add_remove_bs_notifier(blk, &exp->eject_notifier);
722 * NBD exports are used for non-shared storage migration. Make sure
723 * that BDRV_O_INACTIVE is cleared and the image is ready for write
724 * access since the export could be available before migration handover.
726 aio_context_acquire(exp->ctx);
727 blk_invalidate_cache(blk, NULL);
728 aio_context_release(exp->ctx);
729 return exp;
731 fail:
732 g_free(exp);
733 return NULL;
736 NBDExport *nbd_export_find(const char *name)
738 NBDExport *exp;
739 QTAILQ_FOREACH(exp, &exports, next) {
740 if (strcmp(name, exp->name) == 0) {
741 return exp;
745 return NULL;
748 void nbd_export_set_name(NBDExport *exp, const char *name)
750 if (exp->name == name) {
751 return;
754 nbd_export_get(exp);
755 if (exp->name != NULL) {
756 g_free(exp->name);
757 exp->name = NULL;
758 QTAILQ_REMOVE(&exports, exp, next);
759 nbd_export_put(exp);
761 if (name != NULL) {
762 nbd_export_get(exp);
763 exp->name = g_strdup(name);
764 QTAILQ_INSERT_TAIL(&exports, exp, next);
766 nbd_export_put(exp);
769 void nbd_export_close(NBDExport *exp)
771 NBDClient *client, *next;
773 nbd_export_get(exp);
774 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
775 client_close(client);
777 nbd_export_set_name(exp, NULL);
778 nbd_export_put(exp);
781 void nbd_export_get(NBDExport *exp)
783 assert(exp->refcount > 0);
784 exp->refcount++;
787 void nbd_export_put(NBDExport *exp)
789 assert(exp->refcount > 0);
790 if (exp->refcount == 1) {
791 nbd_export_close(exp);
794 if (--exp->refcount == 0) {
795 assert(exp->name == NULL);
797 if (exp->close) {
798 exp->close(exp);
801 if (exp->blk) {
802 notifier_remove(&exp->eject_notifier);
803 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
804 blk_aio_detach, exp);
805 blk_unref(exp->blk);
806 exp->blk = NULL;
809 g_free(exp);
813 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
815 return exp->blk;
818 void nbd_export_close_all(void)
820 NBDExport *exp, *next;
822 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
823 nbd_export_close(exp);
827 static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
828 int len)
830 NBDClient *client = req->client;
831 ssize_t rc, ret;
833 g_assert(qemu_in_coroutine());
834 qemu_co_mutex_lock(&client->send_lock);
835 client->send_coroutine = qemu_coroutine_self();
836 nbd_set_handlers(client);
838 if (!len) {
839 rc = nbd_send_reply(client->ioc, reply);
840 } else {
841 qio_channel_set_cork(client->ioc, true);
842 rc = nbd_send_reply(client->ioc, reply);
843 if (rc >= 0) {
844 ret = write_sync(client->ioc, req->data, len);
845 if (ret != len) {
846 rc = -EIO;
849 qio_channel_set_cork(client->ioc, false);
852 client->send_coroutine = NULL;
853 nbd_set_handlers(client);
854 qemu_co_mutex_unlock(&client->send_lock);
855 return rc;
858 static ssize_t nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)
860 NBDClient *client = req->client;
861 uint32_t command;
862 ssize_t rc;
864 g_assert(qemu_in_coroutine());
865 client->recv_coroutine = qemu_coroutine_self();
866 nbd_update_can_read(client);
868 rc = nbd_receive_request(client->ioc, request);
869 if (rc < 0) {
870 if (rc != -EAGAIN) {
871 rc = -EIO;
873 goto out;
876 if ((request->from + request->len) < request->from) {
877 LOG("integer overflow detected! "
878 "you're probably being attacked");
879 rc = -EINVAL;
880 goto out;
883 TRACE("Decoding type");
885 command = request->type & NBD_CMD_MASK_COMMAND;
886 if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {
887 if (request->len > NBD_MAX_BUFFER_SIZE) {
888 LOG("len (%u) is larger than max len (%u)",
889 request->len, NBD_MAX_BUFFER_SIZE);
890 rc = -EINVAL;
891 goto out;
894 req->data = blk_try_blockalign(client->exp->blk, request->len);
895 if (req->data == NULL) {
896 rc = -ENOMEM;
897 goto out;
900 if (command == NBD_CMD_WRITE) {
901 TRACE("Reading %u byte(s)", request->len);
903 if (read_sync(client->ioc, req->data, request->len) != request->len) {
904 LOG("reading from socket failed");
905 rc = -EIO;
906 goto out;
909 rc = 0;
911 out:
912 client->recv_coroutine = NULL;
913 nbd_update_can_read(client);
915 return rc;
918 static void nbd_trip(void *opaque)
920 NBDClient *client = opaque;
921 NBDExport *exp = client->exp;
922 NBDRequest *req;
923 struct nbd_request request;
924 struct nbd_reply reply;
925 ssize_t ret;
926 uint32_t command;
928 TRACE("Reading request.");
929 if (client->closing) {
930 return;
933 req = nbd_request_get(client);
934 ret = nbd_co_receive_request(req, &request);
935 if (ret == -EAGAIN) {
936 goto done;
938 if (ret == -EIO) {
939 goto out;
942 reply.handle = request.handle;
943 reply.error = 0;
945 if (ret < 0) {
946 reply.error = -ret;
947 goto error_reply;
949 command = request.type & NBD_CMD_MASK_COMMAND;
950 if (command != NBD_CMD_DISC && (request.from + request.len) > exp->size) {
951 LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
952 ", Offset: %" PRIu64 "\n",
953 request.from, request.len,
954 (uint64_t)exp->size, (uint64_t)exp->dev_offset);
955 LOG("requested operation past EOF--bad client?");
956 goto invalid_request;
959 if (client->closing) {
961 * The client may be closed when we are blocked in
962 * nbd_co_receive_request()
964 goto done;
967 switch (command) {
968 case NBD_CMD_READ:
969 TRACE("Request type is READ");
971 if (request.type & NBD_CMD_FLAG_FUA) {
972 ret = blk_co_flush(exp->blk);
973 if (ret < 0) {
974 LOG("flush failed");
975 reply.error = -ret;
976 goto error_reply;
980 ret = blk_read(exp->blk,
981 (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
982 req->data, request.len / BDRV_SECTOR_SIZE);
983 if (ret < 0) {
984 LOG("reading from file failed");
985 reply.error = -ret;
986 goto error_reply;
989 TRACE("Read %u byte(s)", request.len);
990 if (nbd_co_send_reply(req, &reply, request.len) < 0)
991 goto out;
992 break;
993 case NBD_CMD_WRITE:
994 TRACE("Request type is WRITE");
996 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
997 TRACE("Server is read-only, return error");
998 reply.error = EROFS;
999 goto error_reply;
1002 TRACE("Writing to device");
1004 ret = blk_write(exp->blk,
1005 (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
1006 req->data, request.len / BDRV_SECTOR_SIZE);
1007 if (ret < 0) {
1008 LOG("writing to file failed");
1009 reply.error = -ret;
1010 goto error_reply;
1013 if (request.type & NBD_CMD_FLAG_FUA) {
1014 ret = blk_co_flush(exp->blk);
1015 if (ret < 0) {
1016 LOG("flush failed");
1017 reply.error = -ret;
1018 goto error_reply;
1022 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1023 goto out;
1025 break;
1026 case NBD_CMD_DISC:
1027 TRACE("Request type is DISCONNECT");
1028 errno = 0;
1029 goto out;
1030 case NBD_CMD_FLUSH:
1031 TRACE("Request type is FLUSH");
1033 ret = blk_co_flush(exp->blk);
1034 if (ret < 0) {
1035 LOG("flush failed");
1036 reply.error = -ret;
1038 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1039 goto out;
1041 break;
1042 case NBD_CMD_TRIM:
1043 TRACE("Request type is TRIM");
1044 ret = blk_co_discard(exp->blk, (request.from + exp->dev_offset)
1045 / BDRV_SECTOR_SIZE,
1046 request.len / BDRV_SECTOR_SIZE);
1047 if (ret < 0) {
1048 LOG("discard failed");
1049 reply.error = -ret;
1051 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1052 goto out;
1054 break;
1055 default:
1056 LOG("invalid request type (%u) received", request.type);
1057 invalid_request:
1058 reply.error = EINVAL;
1059 error_reply:
1060 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1061 goto out;
1063 break;
1066 TRACE("Request/Reply complete");
1068 done:
1069 nbd_request_put(req);
1070 return;
1072 out:
1073 nbd_request_put(req);
1074 client_close(client);
1077 static void nbd_read(void *opaque)
1079 NBDClient *client = opaque;
1081 if (client->recv_coroutine) {
1082 qemu_coroutine_enter(client->recv_coroutine, NULL);
1083 } else {
1084 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip), client);
1088 static void nbd_restart_write(void *opaque)
1090 NBDClient *client = opaque;
1092 qemu_coroutine_enter(client->send_coroutine, NULL);
1095 static void nbd_set_handlers(NBDClient *client)
1097 if (client->exp && client->exp->ctx) {
1098 aio_set_fd_handler(client->exp->ctx, client->sioc->fd,
1099 true,
1100 client->can_read ? nbd_read : NULL,
1101 client->send_coroutine ? nbd_restart_write : NULL,
1102 client);
1106 static void nbd_unset_handlers(NBDClient *client)
1108 if (client->exp && client->exp->ctx) {
1109 aio_set_fd_handler(client->exp->ctx, client->sioc->fd,
1110 true, NULL, NULL, NULL);
1114 static void nbd_update_can_read(NBDClient *client)
1116 bool can_read = client->recv_coroutine ||
1117 client->nb_requests < MAX_NBD_REQUESTS;
1119 if (can_read != client->can_read) {
1120 client->can_read = can_read;
1121 nbd_set_handlers(client);
1123 /* There is no need to invoke aio_notify(), since aio_set_fd_handler()
1124 * in nbd_set_handlers() will have taken care of that */
1128 static coroutine_fn void nbd_co_client_start(void *opaque)
1130 NBDClientNewData *data = opaque;
1131 NBDClient *client = data->client;
1132 NBDExport *exp = client->exp;
1134 if (exp) {
1135 nbd_export_get(exp);
1137 if (nbd_negotiate(data)) {
1138 client_close(client);
1139 goto out;
1141 qemu_co_mutex_init(&client->send_lock);
1142 nbd_set_handlers(client);
1144 if (exp) {
1145 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1147 out:
1148 g_free(data);
1151 void nbd_client_new(NBDExport *exp,
1152 QIOChannelSocket *sioc,
1153 void (*close_fn)(NBDClient *))
1155 NBDClient *client;
1156 NBDClientNewData *data = g_new(NBDClientNewData, 1);
1158 client = g_malloc0(sizeof(NBDClient));
1159 client->refcount = 1;
1160 client->exp = exp;
1161 client->sioc = sioc;
1162 object_ref(OBJECT(client->sioc));
1163 client->ioc = QIO_CHANNEL(sioc);
1164 object_ref(OBJECT(client->ioc));
1165 client->can_read = true;
1166 client->close = close_fn;
1168 data->client = client;
1169 data->co = qemu_coroutine_create(nbd_co_client_start);
1170 qemu_coroutine_enter(data->co, data);