Merge remote-tracking branch 'remotes/kraxel/tags/pull-gl-20150317-1' into staging
[qemu/ar7.git] / nbd.c
blob71159aff6a02d41f1003b423e58971430618d0cc
1 /*
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
4 * Network Block Device
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 "block/nbd.h"
20 #include "sysemu/block-backend.h"
22 #include "block/coroutine.h"
24 #include <errno.h>
25 #include <string.h>
26 #ifndef _WIN32
27 #include <sys/ioctl.h>
28 #endif
29 #if defined(__sun__) || defined(__HAIKU__)
30 #include <sys/ioccom.h>
31 #endif
32 #include <ctype.h>
33 #include <inttypes.h>
35 #ifdef __linux__
36 #include <linux/fs.h>
37 #endif
39 #include "qemu/sockets.h"
40 #include "qemu/queue.h"
41 #include "qemu/main-loop.h"
43 //#define DEBUG_NBD
45 #ifdef DEBUG_NBD
46 #define TRACE(msg, ...) do { \
47 LOG(msg, ## __VA_ARGS__); \
48 } while(0)
49 #else
50 #define TRACE(msg, ...) \
51 do { } while (0)
52 #endif
54 #define LOG(msg, ...) do { \
55 fprintf(stderr, "%s:%s():L%d: " msg "\n", \
56 __FILE__, __FUNCTION__, __LINE__, ## __VA_ARGS__); \
57 } while(0)
59 /* This is all part of the "official" NBD API.
61 * The most up-to-date documentation is available at:
62 * https://github.com/yoe/nbd/blob/master/doc/proto.txt
65 #define NBD_REQUEST_SIZE (4 + 4 + 8 + 8 + 4)
66 #define NBD_REPLY_SIZE (4 + 4 + 8)
67 #define NBD_REQUEST_MAGIC 0x25609513
68 #define NBD_REPLY_MAGIC 0x67446698
69 #define NBD_OPTS_MAGIC 0x49484156454F5054LL
70 #define NBD_CLIENT_MAGIC 0x0000420281861253LL
71 #define NBD_REP_MAGIC 0x3e889045565a9LL
73 #define NBD_SET_SOCK _IO(0xab, 0)
74 #define NBD_SET_BLKSIZE _IO(0xab, 1)
75 #define NBD_SET_SIZE _IO(0xab, 2)
76 #define NBD_DO_IT _IO(0xab, 3)
77 #define NBD_CLEAR_SOCK _IO(0xab, 4)
78 #define NBD_CLEAR_QUE _IO(0xab, 5)
79 #define NBD_PRINT_DEBUG _IO(0xab, 6)
80 #define NBD_SET_SIZE_BLOCKS _IO(0xab, 7)
81 #define NBD_DISCONNECT _IO(0xab, 8)
82 #define NBD_SET_TIMEOUT _IO(0xab, 9)
83 #define NBD_SET_FLAGS _IO(0xab, 10)
85 #define NBD_OPT_EXPORT_NAME (1)
86 #define NBD_OPT_ABORT (2)
87 #define NBD_OPT_LIST (3)
89 /* Definitions for opaque data types */
91 typedef struct NBDRequest NBDRequest;
93 struct NBDRequest {
94 QSIMPLEQ_ENTRY(NBDRequest) entry;
95 NBDClient *client;
96 uint8_t *data;
99 struct NBDExport {
100 int refcount;
101 void (*close)(NBDExport *exp);
103 BlockBackend *blk;
104 char *name;
105 off_t dev_offset;
106 off_t size;
107 uint32_t nbdflags;
108 QTAILQ_HEAD(, NBDClient) clients;
109 QTAILQ_ENTRY(NBDExport) next;
111 AioContext *ctx;
114 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
116 struct NBDClient {
117 int refcount;
118 void (*close)(NBDClient *client);
120 NBDExport *exp;
121 int sock;
123 Coroutine *recv_coroutine;
125 CoMutex send_lock;
126 Coroutine *send_coroutine;
128 bool can_read;
130 QTAILQ_ENTRY(NBDClient) next;
131 int nb_requests;
132 bool closing;
135 /* That's all folks */
137 static void nbd_set_handlers(NBDClient *client);
138 static void nbd_unset_handlers(NBDClient *client);
139 static void nbd_update_can_read(NBDClient *client);
141 ssize_t nbd_wr_sync(int fd, void *buffer, size_t size, bool do_read)
143 size_t offset = 0;
144 int err;
146 if (qemu_in_coroutine()) {
147 if (do_read) {
148 return qemu_co_recv(fd, buffer, size);
149 } else {
150 return qemu_co_send(fd, buffer, size);
154 while (offset < size) {
155 ssize_t len;
157 if (do_read) {
158 len = qemu_recv(fd, buffer + offset, size - offset, 0);
159 } else {
160 len = send(fd, buffer + offset, size - offset, 0);
163 if (len < 0) {
164 err = socket_error();
166 /* recoverable error */
167 if (err == EINTR || (offset > 0 && (err == EAGAIN || err == EWOULDBLOCK))) {
168 continue;
171 /* unrecoverable error */
172 return -err;
175 /* eof */
176 if (len == 0) {
177 break;
180 offset += len;
183 return offset;
186 static ssize_t read_sync(int fd, void *buffer, size_t size)
188 /* Sockets are kept in blocking mode in the negotiation phase. After
189 * that, a non-readable socket simply means that another thread stole
190 * our request/reply. Synchronization is done with recv_coroutine, so
191 * that this is coroutine-safe.
193 return nbd_wr_sync(fd, buffer, size, true);
196 static ssize_t write_sync(int fd, void *buffer, size_t size)
198 int ret;
199 do {
200 /* For writes, we do expect the socket to be writable. */
201 ret = nbd_wr_sync(fd, buffer, size, false);
202 } while (ret == -EAGAIN);
203 return ret;
206 /* Basic flow for negotiation
208 Server Client
209 Negotiate
213 Server Client
214 Negotiate #1
215 Option
216 Negotiate #2
218 ----
220 followed by
222 Server Client
223 Request
224 Response
225 Request
226 Response
229 Request (type == 2)
233 static int nbd_send_rep(int csock, uint32_t type, uint32_t opt)
235 uint64_t magic;
236 uint32_t len;
238 magic = cpu_to_be64(NBD_REP_MAGIC);
239 if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
240 LOG("write failed (rep magic)");
241 return -EINVAL;
243 opt = cpu_to_be32(opt);
244 if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
245 LOG("write failed (rep opt)");
246 return -EINVAL;
248 type = cpu_to_be32(type);
249 if (write_sync(csock, &type, sizeof(type)) != sizeof(type)) {
250 LOG("write failed (rep type)");
251 return -EINVAL;
253 len = cpu_to_be32(0);
254 if (write_sync(csock, &len, sizeof(len)) != sizeof(len)) {
255 LOG("write failed (rep data length)");
256 return -EINVAL;
258 return 0;
261 static int nbd_send_rep_list(int csock, NBDExport *exp)
263 uint64_t magic, name_len;
264 uint32_t opt, type, len;
266 name_len = strlen(exp->name);
267 magic = cpu_to_be64(NBD_REP_MAGIC);
268 if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
269 LOG("write failed (magic)");
270 return -EINVAL;
272 opt = cpu_to_be32(NBD_OPT_LIST);
273 if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
274 LOG("write failed (opt)");
275 return -EINVAL;
277 type = cpu_to_be32(NBD_REP_SERVER);
278 if (write_sync(csock, &type, sizeof(type)) != sizeof(type)) {
279 LOG("write failed (reply type)");
280 return -EINVAL;
282 len = cpu_to_be32(name_len + sizeof(len));
283 if (write_sync(csock, &len, sizeof(len)) != sizeof(len)) {
284 LOG("write failed (length)");
285 return -EINVAL;
287 len = cpu_to_be32(name_len);
288 if (write_sync(csock, &len, sizeof(len)) != sizeof(len)) {
289 LOG("write failed (length)");
290 return -EINVAL;
292 if (write_sync(csock, exp->name, name_len) != name_len) {
293 LOG("write failed (buffer)");
294 return -EINVAL;
296 return 0;
299 static int nbd_handle_list(NBDClient *client, uint32_t length)
301 int csock;
302 NBDExport *exp;
304 csock = client->sock;
305 if (length) {
306 return nbd_send_rep(csock, NBD_REP_ERR_INVALID, NBD_OPT_LIST);
309 /* For each export, send a NBD_REP_SERVER reply. */
310 QTAILQ_FOREACH(exp, &exports, next) {
311 if (nbd_send_rep_list(csock, exp)) {
312 return -EINVAL;
315 /* Finish with a NBD_REP_ACK. */
316 return nbd_send_rep(csock, NBD_REP_ACK, NBD_OPT_LIST);
319 static int nbd_handle_export_name(NBDClient *client, uint32_t length)
321 int rc = -EINVAL, csock = client->sock;
322 char name[256];
324 /* Client sends:
325 [20 .. xx] export name (length bytes)
327 TRACE("Checking length");
328 if (length > 255) {
329 LOG("Bad length received");
330 goto fail;
332 if (read_sync(csock, name, length) != length) {
333 LOG("read failed");
334 goto fail;
336 name[length] = '\0';
338 client->exp = nbd_export_find(name);
339 if (!client->exp) {
340 LOG("export not found");
341 goto fail;
344 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
345 nbd_export_get(client->exp);
346 rc = 0;
347 fail:
348 return rc;
351 static int nbd_receive_options(NBDClient *client)
353 while (1) {
354 int csock = client->sock;
355 uint32_t tmp, length;
356 uint64_t magic;
358 /* Client sends:
359 [ 0 .. 3] client flags
360 [ 4 .. 11] NBD_OPTS_MAGIC
361 [12 .. 15] NBD option
362 [16 .. 19] length
363 ... Rest of request
366 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
367 LOG("read failed");
368 return -EINVAL;
370 TRACE("Checking client flags");
371 tmp = be32_to_cpu(tmp);
372 if (tmp != 0 && tmp != NBD_FLAG_C_FIXED_NEWSTYLE) {
373 LOG("Bad client flags received");
374 return -EINVAL;
377 if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
378 LOG("read failed");
379 return -EINVAL;
381 TRACE("Checking opts magic");
382 if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
383 LOG("Bad magic received");
384 return -EINVAL;
387 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
388 LOG("read failed");
389 return -EINVAL;
392 if (read_sync(csock, &length, sizeof(length)) != sizeof(length)) {
393 LOG("read failed");
394 return -EINVAL;
396 length = be32_to_cpu(length);
398 TRACE("Checking option");
399 switch (be32_to_cpu(tmp)) {
400 case NBD_OPT_LIST:
401 if (nbd_handle_list(client, length) < 0) {
402 return 1;
404 break;
406 case NBD_OPT_ABORT:
407 return -EINVAL;
409 case NBD_OPT_EXPORT_NAME:
410 return nbd_handle_export_name(client, length);
412 default:
413 tmp = be32_to_cpu(tmp);
414 LOG("Unsupported option 0x%x", tmp);
415 nbd_send_rep(client->sock, NBD_REP_ERR_UNSUP, tmp);
416 return -EINVAL;
421 static int nbd_send_negotiate(NBDClient *client)
423 int csock = client->sock;
424 char buf[8 + 8 + 8 + 128];
425 int rc;
426 const int myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
427 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
429 /* Negotiation header without options:
430 [ 0 .. 7] passwd ("NBDMAGIC")
431 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
432 [16 .. 23] size
433 [24 .. 25] server flags (0)
434 [26 .. 27] export flags
435 [28 .. 151] reserved (0)
437 Negotiation header with options, part 1:
438 [ 0 .. 7] passwd ("NBDMAGIC")
439 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
440 [16 .. 17] server flags (0)
442 part 2 (after options are sent):
443 [18 .. 25] size
444 [26 .. 27] export flags
445 [28 .. 151] reserved (0)
448 qemu_set_block(csock);
449 rc = -EINVAL;
451 TRACE("Beginning negotiation.");
452 memset(buf, 0, sizeof(buf));
453 memcpy(buf, "NBDMAGIC", 8);
454 if (client->exp) {
455 assert ((client->exp->nbdflags & ~65535) == 0);
456 cpu_to_be64w((uint64_t*)(buf + 8), NBD_CLIENT_MAGIC);
457 cpu_to_be64w((uint64_t*)(buf + 16), client->exp->size);
458 cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
459 } else {
460 cpu_to_be64w((uint64_t*)(buf + 8), NBD_OPTS_MAGIC);
461 cpu_to_be16w((uint16_t *)(buf + 16), NBD_FLAG_FIXED_NEWSTYLE);
464 if (client->exp) {
465 if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
466 LOG("write failed");
467 goto fail;
469 } else {
470 if (write_sync(csock, buf, 18) != 18) {
471 LOG("write failed");
472 goto fail;
474 rc = nbd_receive_options(client);
475 if (rc != 0) {
476 LOG("option negotiation failed");
477 goto fail;
480 assert ((client->exp->nbdflags & ~65535) == 0);
481 cpu_to_be64w((uint64_t*)(buf + 18), client->exp->size);
482 cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
483 if (write_sync(csock, buf + 18, sizeof(buf) - 18) != sizeof(buf) - 18) {
484 LOG("write failed");
485 goto fail;
489 TRACE("Negotiation succeeded.");
490 rc = 0;
491 fail:
492 qemu_set_nonblock(csock);
493 return rc;
496 int nbd_receive_negotiate(int csock, const char *name, uint32_t *flags,
497 off_t *size, size_t *blocksize, Error **errp)
499 char buf[256];
500 uint64_t magic, s;
501 uint16_t tmp;
502 int rc;
504 TRACE("Receiving negotiation.");
506 rc = -EINVAL;
508 if (read_sync(csock, buf, 8) != 8) {
509 error_setg(errp, "Failed to read data");
510 goto fail;
513 buf[8] = '\0';
514 if (strlen(buf) == 0) {
515 error_setg(errp, "Server connection closed unexpectedly");
516 goto fail;
519 TRACE("Magic is %c%c%c%c%c%c%c%c",
520 qemu_isprint(buf[0]) ? buf[0] : '.',
521 qemu_isprint(buf[1]) ? buf[1] : '.',
522 qemu_isprint(buf[2]) ? buf[2] : '.',
523 qemu_isprint(buf[3]) ? buf[3] : '.',
524 qemu_isprint(buf[4]) ? buf[4] : '.',
525 qemu_isprint(buf[5]) ? buf[5] : '.',
526 qemu_isprint(buf[6]) ? buf[6] : '.',
527 qemu_isprint(buf[7]) ? buf[7] : '.');
529 if (memcmp(buf, "NBDMAGIC", 8) != 0) {
530 error_setg(errp, "Invalid magic received");
531 goto fail;
534 if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
535 error_setg(errp, "Failed to read magic");
536 goto fail;
538 magic = be64_to_cpu(magic);
539 TRACE("Magic is 0x%" PRIx64, magic);
541 if (name) {
542 uint32_t reserved = 0;
543 uint32_t opt;
544 uint32_t namesize;
546 TRACE("Checking magic (opts_magic)");
547 if (magic != NBD_OPTS_MAGIC) {
548 if (magic == NBD_CLIENT_MAGIC) {
549 error_setg(errp, "Server does not support export names");
550 } else {
551 error_setg(errp, "Bad magic received");
553 goto fail;
555 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
556 error_setg(errp, "Failed to read server flags");
557 goto fail;
559 *flags = be16_to_cpu(tmp) << 16;
560 /* reserved for future use */
561 if (write_sync(csock, &reserved, sizeof(reserved)) !=
562 sizeof(reserved)) {
563 error_setg(errp, "Failed to read reserved field");
564 goto fail;
566 /* write the export name */
567 magic = cpu_to_be64(magic);
568 if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
569 error_setg(errp, "Failed to send export name magic");
570 goto fail;
572 opt = cpu_to_be32(NBD_OPT_EXPORT_NAME);
573 if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
574 error_setg(errp, "Failed to send export name option number");
575 goto fail;
577 namesize = cpu_to_be32(strlen(name));
578 if (write_sync(csock, &namesize, sizeof(namesize)) !=
579 sizeof(namesize)) {
580 error_setg(errp, "Failed to send export name length");
581 goto fail;
583 if (write_sync(csock, (char*)name, strlen(name)) != strlen(name)) {
584 error_setg(errp, "Failed to send export name");
585 goto fail;
587 } else {
588 TRACE("Checking magic (cli_magic)");
590 if (magic != NBD_CLIENT_MAGIC) {
591 if (magic == NBD_OPTS_MAGIC) {
592 error_setg(errp, "Server requires an export name");
593 } else {
594 error_setg(errp, "Bad magic received");
596 goto fail;
600 if (read_sync(csock, &s, sizeof(s)) != sizeof(s)) {
601 error_setg(errp, "Failed to read export length");
602 goto fail;
604 *size = be64_to_cpu(s);
605 *blocksize = 1024;
606 TRACE("Size is %" PRIu64, *size);
608 if (!name) {
609 if (read_sync(csock, flags, sizeof(*flags)) != sizeof(*flags)) {
610 error_setg(errp, "Failed to read export flags");
611 goto fail;
613 *flags = be32_to_cpup(flags);
614 } else {
615 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
616 error_setg(errp, "Failed to read export flags");
617 goto fail;
619 *flags |= be32_to_cpu(tmp);
621 if (read_sync(csock, &buf, 124) != 124) {
622 error_setg(errp, "Failed to read reserved block");
623 goto fail;
625 rc = 0;
627 fail:
628 return rc;
631 #ifdef __linux__
632 int nbd_init(int fd, int csock, uint32_t flags, off_t size, size_t blocksize)
634 TRACE("Setting NBD socket");
636 if (ioctl(fd, NBD_SET_SOCK, csock) < 0) {
637 int serrno = errno;
638 LOG("Failed to set NBD socket");
639 return -serrno;
642 TRACE("Setting block size to %lu", (unsigned long)blocksize);
644 if (ioctl(fd, NBD_SET_BLKSIZE, blocksize) < 0) {
645 int serrno = errno;
646 LOG("Failed setting NBD block size");
647 return -serrno;
650 TRACE("Setting size to %zd block(s)", (size_t)(size / blocksize));
652 if (ioctl(fd, NBD_SET_SIZE_BLOCKS, size / blocksize) < 0) {
653 int serrno = errno;
654 LOG("Failed setting size (in blocks)");
655 return -serrno;
658 if (ioctl(fd, NBD_SET_FLAGS, flags) < 0) {
659 if (errno == ENOTTY) {
660 int read_only = (flags & NBD_FLAG_READ_ONLY) != 0;
661 TRACE("Setting readonly attribute");
663 if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
664 int serrno = errno;
665 LOG("Failed setting read-only attribute");
666 return -serrno;
668 } else {
669 int serrno = errno;
670 LOG("Failed setting flags");
671 return -serrno;
675 TRACE("Negotiation ended");
677 return 0;
680 int nbd_disconnect(int fd)
682 ioctl(fd, NBD_CLEAR_QUE);
683 ioctl(fd, NBD_DISCONNECT);
684 ioctl(fd, NBD_CLEAR_SOCK);
685 return 0;
688 int nbd_client(int fd)
690 int ret;
691 int serrno;
693 TRACE("Doing NBD loop");
695 ret = ioctl(fd, NBD_DO_IT);
696 if (ret < 0 && errno == EPIPE) {
697 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
698 * the socket via NBD_DISCONNECT. We do not want to return 1 in
699 * that case.
701 ret = 0;
703 serrno = errno;
705 TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
707 TRACE("Clearing NBD queue");
708 ioctl(fd, NBD_CLEAR_QUE);
710 TRACE("Clearing NBD socket");
711 ioctl(fd, NBD_CLEAR_SOCK);
713 errno = serrno;
714 return ret;
716 #else
717 int nbd_init(int fd, int csock, uint32_t flags, off_t size, size_t blocksize)
719 return -ENOTSUP;
722 int nbd_disconnect(int fd)
724 return -ENOTSUP;
727 int nbd_client(int fd)
729 return -ENOTSUP;
731 #endif
733 ssize_t nbd_send_request(int csock, struct nbd_request *request)
735 uint8_t buf[NBD_REQUEST_SIZE];
736 ssize_t ret;
738 cpu_to_be32w((uint32_t*)buf, NBD_REQUEST_MAGIC);
739 cpu_to_be32w((uint32_t*)(buf + 4), request->type);
740 cpu_to_be64w((uint64_t*)(buf + 8), request->handle);
741 cpu_to_be64w((uint64_t*)(buf + 16), request->from);
742 cpu_to_be32w((uint32_t*)(buf + 24), request->len);
744 TRACE("Sending request to client: "
745 "{ .from = %" PRIu64", .len = %u, .handle = %" PRIu64", .type=%i}",
746 request->from, request->len, request->handle, request->type);
748 ret = write_sync(csock, buf, sizeof(buf));
749 if (ret < 0) {
750 return ret;
753 if (ret != sizeof(buf)) {
754 LOG("writing to socket failed");
755 return -EINVAL;
757 return 0;
760 static ssize_t nbd_receive_request(int csock, struct nbd_request *request)
762 uint8_t buf[NBD_REQUEST_SIZE];
763 uint32_t magic;
764 ssize_t ret;
766 ret = read_sync(csock, buf, sizeof(buf));
767 if (ret < 0) {
768 return ret;
771 if (ret != sizeof(buf)) {
772 LOG("read failed");
773 return -EINVAL;
776 /* Request
777 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
778 [ 4 .. 7] type (0 == READ, 1 == WRITE)
779 [ 8 .. 15] handle
780 [16 .. 23] from
781 [24 .. 27] len
784 magic = be32_to_cpup((uint32_t*)buf);
785 request->type = be32_to_cpup((uint32_t*)(buf + 4));
786 request->handle = be64_to_cpup((uint64_t*)(buf + 8));
787 request->from = be64_to_cpup((uint64_t*)(buf + 16));
788 request->len = be32_to_cpup((uint32_t*)(buf + 24));
790 TRACE("Got request: "
791 "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
792 magic, request->type, request->from, request->len);
794 if (magic != NBD_REQUEST_MAGIC) {
795 LOG("invalid magic (got 0x%x)", magic);
796 return -EINVAL;
798 return 0;
801 ssize_t nbd_receive_reply(int csock, struct nbd_reply *reply)
803 uint8_t buf[NBD_REPLY_SIZE];
804 uint32_t magic;
805 ssize_t ret;
807 ret = read_sync(csock, buf, sizeof(buf));
808 if (ret < 0) {
809 return ret;
812 if (ret != sizeof(buf)) {
813 LOG("read failed");
814 return -EINVAL;
817 /* Reply
818 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
819 [ 4 .. 7] error (0 == no error)
820 [ 7 .. 15] handle
823 magic = be32_to_cpup((uint32_t*)buf);
824 reply->error = be32_to_cpup((uint32_t*)(buf + 4));
825 reply->handle = be64_to_cpup((uint64_t*)(buf + 8));
827 TRACE("Got reply: "
828 "{ magic = 0x%x, .error = %d, handle = %" PRIu64" }",
829 magic, reply->error, reply->handle);
831 if (magic != NBD_REPLY_MAGIC) {
832 LOG("invalid magic (got 0x%x)", magic);
833 return -EINVAL;
835 return 0;
838 static ssize_t nbd_send_reply(int csock, struct nbd_reply *reply)
840 uint8_t buf[NBD_REPLY_SIZE];
841 ssize_t ret;
843 /* Reply
844 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
845 [ 4 .. 7] error (0 == no error)
846 [ 7 .. 15] handle
848 cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);
849 cpu_to_be32w((uint32_t*)(buf + 4), reply->error);
850 cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);
852 TRACE("Sending response to client");
854 ret = write_sync(csock, buf, sizeof(buf));
855 if (ret < 0) {
856 return ret;
859 if (ret != sizeof(buf)) {
860 LOG("writing to socket failed");
861 return -EINVAL;
863 return 0;
866 #define MAX_NBD_REQUESTS 16
868 void nbd_client_get(NBDClient *client)
870 client->refcount++;
873 void nbd_client_put(NBDClient *client)
875 if (--client->refcount == 0) {
876 /* The last reference should be dropped by client->close,
877 * which is called by client_close.
879 assert(client->closing);
881 nbd_unset_handlers(client);
882 close(client->sock);
883 client->sock = -1;
884 if (client->exp) {
885 QTAILQ_REMOVE(&client->exp->clients, client, next);
886 nbd_export_put(client->exp);
888 g_free(client);
892 static void client_close(NBDClient *client)
894 if (client->closing) {
895 return;
898 client->closing = true;
900 /* Force requests to finish. They will drop their own references,
901 * then we'll close the socket and free the NBDClient.
903 shutdown(client->sock, 2);
905 /* Also tell the client, so that they release their reference. */
906 if (client->close) {
907 client->close(client);
911 static NBDRequest *nbd_request_get(NBDClient *client)
913 NBDRequest *req;
915 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
916 client->nb_requests++;
917 nbd_update_can_read(client);
919 req = g_slice_new0(NBDRequest);
920 nbd_client_get(client);
921 req->client = client;
922 return req;
925 static void nbd_request_put(NBDRequest *req)
927 NBDClient *client = req->client;
929 if (req->data) {
930 qemu_vfree(req->data);
932 g_slice_free(NBDRequest, req);
934 client->nb_requests--;
935 nbd_update_can_read(client);
936 nbd_client_put(client);
939 static void blk_aio_attached(AioContext *ctx, void *opaque)
941 NBDExport *exp = opaque;
942 NBDClient *client;
944 TRACE("Export %s: Attaching clients to AIO context %p\n", exp->name, ctx);
946 exp->ctx = ctx;
948 QTAILQ_FOREACH(client, &exp->clients, next) {
949 nbd_set_handlers(client);
953 static void blk_aio_detach(void *opaque)
955 NBDExport *exp = opaque;
956 NBDClient *client;
958 TRACE("Export %s: Detaching clients from AIO context %p\n", exp->name, exp->ctx);
960 QTAILQ_FOREACH(client, &exp->clients, next) {
961 nbd_unset_handlers(client);
964 exp->ctx = NULL;
967 NBDExport *nbd_export_new(BlockBackend *blk, off_t dev_offset, off_t size,
968 uint32_t nbdflags, void (*close)(NBDExport *))
970 NBDExport *exp = g_malloc0(sizeof(NBDExport));
971 exp->refcount = 1;
972 QTAILQ_INIT(&exp->clients);
973 exp->blk = blk;
974 exp->dev_offset = dev_offset;
975 exp->nbdflags = nbdflags;
976 exp->size = size == -1 ? blk_getlength(blk) : size;
977 exp->close = close;
978 exp->ctx = blk_get_aio_context(blk);
979 blk_ref(blk);
980 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
982 * NBD exports are used for non-shared storage migration. Make sure
983 * that BDRV_O_INCOMING is cleared and the image is ready for write
984 * access since the export could be available before migration handover.
986 blk_invalidate_cache(blk, NULL);
987 return exp;
990 NBDExport *nbd_export_find(const char *name)
992 NBDExport *exp;
993 QTAILQ_FOREACH(exp, &exports, next) {
994 if (strcmp(name, exp->name) == 0) {
995 return exp;
999 return NULL;
1002 void nbd_export_set_name(NBDExport *exp, const char *name)
1004 if (exp->name == name) {
1005 return;
1008 nbd_export_get(exp);
1009 if (exp->name != NULL) {
1010 g_free(exp->name);
1011 exp->name = NULL;
1012 QTAILQ_REMOVE(&exports, exp, next);
1013 nbd_export_put(exp);
1015 if (name != NULL) {
1016 nbd_export_get(exp);
1017 exp->name = g_strdup(name);
1018 QTAILQ_INSERT_TAIL(&exports, exp, next);
1020 nbd_export_put(exp);
1023 void nbd_export_close(NBDExport *exp)
1025 NBDClient *client, *next;
1027 nbd_export_get(exp);
1028 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1029 client_close(client);
1031 nbd_export_set_name(exp, NULL);
1032 nbd_export_put(exp);
1033 if (exp->blk) {
1034 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1035 blk_aio_detach, exp);
1036 blk_unref(exp->blk);
1037 exp->blk = NULL;
1041 void nbd_export_get(NBDExport *exp)
1043 assert(exp->refcount > 0);
1044 exp->refcount++;
1047 void nbd_export_put(NBDExport *exp)
1049 assert(exp->refcount > 0);
1050 if (exp->refcount == 1) {
1051 nbd_export_close(exp);
1054 if (--exp->refcount == 0) {
1055 assert(exp->name == NULL);
1057 if (exp->close) {
1058 exp->close(exp);
1061 g_free(exp);
1065 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1067 return exp->blk;
1070 void nbd_export_close_all(void)
1072 NBDExport *exp, *next;
1074 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1075 nbd_export_close(exp);
1079 static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
1080 int len)
1082 NBDClient *client = req->client;
1083 int csock = client->sock;
1084 ssize_t rc, ret;
1086 qemu_co_mutex_lock(&client->send_lock);
1087 client->send_coroutine = qemu_coroutine_self();
1088 nbd_set_handlers(client);
1090 if (!len) {
1091 rc = nbd_send_reply(csock, reply);
1092 } else {
1093 socket_set_cork(csock, 1);
1094 rc = nbd_send_reply(csock, reply);
1095 if (rc >= 0) {
1096 ret = qemu_co_send(csock, req->data, len);
1097 if (ret != len) {
1098 rc = -EIO;
1101 socket_set_cork(csock, 0);
1104 client->send_coroutine = NULL;
1105 nbd_set_handlers(client);
1106 qemu_co_mutex_unlock(&client->send_lock);
1107 return rc;
1110 static ssize_t nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)
1112 NBDClient *client = req->client;
1113 int csock = client->sock;
1114 uint32_t command;
1115 ssize_t rc;
1117 client->recv_coroutine = qemu_coroutine_self();
1118 nbd_update_can_read(client);
1120 rc = nbd_receive_request(csock, request);
1121 if (rc < 0) {
1122 if (rc != -EAGAIN) {
1123 rc = -EIO;
1125 goto out;
1128 if (request->len > NBD_MAX_BUFFER_SIZE) {
1129 LOG("len (%u) is larger than max len (%u)",
1130 request->len, NBD_MAX_BUFFER_SIZE);
1131 rc = -EINVAL;
1132 goto out;
1135 if ((request->from + request->len) < request->from) {
1136 LOG("integer overflow detected! "
1137 "you're probably being attacked");
1138 rc = -EINVAL;
1139 goto out;
1142 TRACE("Decoding type");
1144 command = request->type & NBD_CMD_MASK_COMMAND;
1145 if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {
1146 req->data = blk_blockalign(client->exp->blk, request->len);
1148 if (command == NBD_CMD_WRITE) {
1149 TRACE("Reading %u byte(s)", request->len);
1151 if (qemu_co_recv(csock, req->data, request->len) != request->len) {
1152 LOG("reading from socket failed");
1153 rc = -EIO;
1154 goto out;
1157 rc = 0;
1159 out:
1160 client->recv_coroutine = NULL;
1161 nbd_update_can_read(client);
1163 return rc;
1166 static void nbd_trip(void *opaque)
1168 NBDClient *client = opaque;
1169 NBDExport *exp = client->exp;
1170 NBDRequest *req;
1171 struct nbd_request request;
1172 struct nbd_reply reply;
1173 ssize_t ret;
1174 uint32_t command;
1176 TRACE("Reading request.");
1177 if (client->closing) {
1178 return;
1181 req = nbd_request_get(client);
1182 ret = nbd_co_receive_request(req, &request);
1183 if (ret == -EAGAIN) {
1184 goto done;
1186 if (ret == -EIO) {
1187 goto out;
1190 reply.handle = request.handle;
1191 reply.error = 0;
1193 if (ret < 0) {
1194 reply.error = -ret;
1195 goto error_reply;
1197 command = request.type & NBD_CMD_MASK_COMMAND;
1198 if (command != NBD_CMD_DISC && (request.from + request.len) > exp->size) {
1199 LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
1200 ", Offset: %" PRIu64 "\n",
1201 request.from, request.len,
1202 (uint64_t)exp->size, (uint64_t)exp->dev_offset);
1203 LOG("requested operation past EOF--bad client?");
1204 goto invalid_request;
1207 switch (command) {
1208 case NBD_CMD_READ:
1209 TRACE("Request type is READ");
1211 if (request.type & NBD_CMD_FLAG_FUA) {
1212 ret = blk_co_flush(exp->blk);
1213 if (ret < 0) {
1214 LOG("flush failed");
1215 reply.error = -ret;
1216 goto error_reply;
1220 ret = blk_read(exp->blk,
1221 (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
1222 req->data, request.len / BDRV_SECTOR_SIZE);
1223 if (ret < 0) {
1224 LOG("reading from file failed");
1225 reply.error = -ret;
1226 goto error_reply;
1229 TRACE("Read %u byte(s)", request.len);
1230 if (nbd_co_send_reply(req, &reply, request.len) < 0)
1231 goto out;
1232 break;
1233 case NBD_CMD_WRITE:
1234 TRACE("Request type is WRITE");
1236 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1237 TRACE("Server is read-only, return error");
1238 reply.error = EROFS;
1239 goto error_reply;
1242 TRACE("Writing to device");
1244 ret = blk_write(exp->blk,
1245 (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
1246 req->data, request.len / BDRV_SECTOR_SIZE);
1247 if (ret < 0) {
1248 LOG("writing to file failed");
1249 reply.error = -ret;
1250 goto error_reply;
1253 if (request.type & NBD_CMD_FLAG_FUA) {
1254 ret = blk_co_flush(exp->blk);
1255 if (ret < 0) {
1256 LOG("flush failed");
1257 reply.error = -ret;
1258 goto error_reply;
1262 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1263 goto out;
1265 break;
1266 case NBD_CMD_DISC:
1267 TRACE("Request type is DISCONNECT");
1268 errno = 0;
1269 goto out;
1270 case NBD_CMD_FLUSH:
1271 TRACE("Request type is FLUSH");
1273 ret = blk_co_flush(exp->blk);
1274 if (ret < 0) {
1275 LOG("flush failed");
1276 reply.error = -ret;
1278 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1279 goto out;
1281 break;
1282 case NBD_CMD_TRIM:
1283 TRACE("Request type is TRIM");
1284 ret = blk_co_discard(exp->blk, (request.from + exp->dev_offset)
1285 / BDRV_SECTOR_SIZE,
1286 request.len / BDRV_SECTOR_SIZE);
1287 if (ret < 0) {
1288 LOG("discard failed");
1289 reply.error = -ret;
1291 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1292 goto out;
1294 break;
1295 default:
1296 LOG("invalid request type (%u) received", request.type);
1297 invalid_request:
1298 reply.error = -EINVAL;
1299 error_reply:
1300 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1301 goto out;
1303 break;
1306 TRACE("Request/Reply complete");
1308 done:
1309 nbd_request_put(req);
1310 return;
1312 out:
1313 nbd_request_put(req);
1314 client_close(client);
1317 static void nbd_read(void *opaque)
1319 NBDClient *client = opaque;
1321 if (client->recv_coroutine) {
1322 qemu_coroutine_enter(client->recv_coroutine, NULL);
1323 } else {
1324 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip), client);
1328 static void nbd_restart_write(void *opaque)
1330 NBDClient *client = opaque;
1332 qemu_coroutine_enter(client->send_coroutine, NULL);
1335 static void nbd_set_handlers(NBDClient *client)
1337 if (client->exp && client->exp->ctx) {
1338 aio_set_fd_handler(client->exp->ctx, client->sock,
1339 client->can_read ? nbd_read : NULL,
1340 client->send_coroutine ? nbd_restart_write : NULL,
1341 client);
1345 static void nbd_unset_handlers(NBDClient *client)
1347 if (client->exp && client->exp->ctx) {
1348 aio_set_fd_handler(client->exp->ctx, client->sock, NULL, NULL, NULL);
1352 static void nbd_update_can_read(NBDClient *client)
1354 bool can_read = client->recv_coroutine ||
1355 client->nb_requests < MAX_NBD_REQUESTS;
1357 if (can_read != client->can_read) {
1358 client->can_read = can_read;
1359 nbd_set_handlers(client);
1361 /* There is no need to invoke aio_notify(), since aio_set_fd_handler()
1362 * in nbd_set_handlers() will have taken care of that */
1366 NBDClient *nbd_client_new(NBDExport *exp, int csock,
1367 void (*close)(NBDClient *))
1369 NBDClient *client;
1370 client = g_malloc0(sizeof(NBDClient));
1371 client->refcount = 1;
1372 client->exp = exp;
1373 client->sock = csock;
1374 client->can_read = true;
1375 if (nbd_send_negotiate(client)) {
1376 g_free(client);
1377 return NULL;
1379 client->close = close;
1380 qemu_co_mutex_init(&client->send_lock);
1381 nbd_set_handlers(client);
1383 if (exp) {
1384 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1385 nbd_export_get(exp);
1387 return client;