2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
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/>.
21 #include "block_int.h"
23 #include "qemu-coroutine.h"
28 #include <sys/ioctl.h>
30 #if defined(__sun__) || defined(__HAIKU__)
31 #include <sys/ioccom.h>
40 #include "qemu_socket.h"
41 #include "qemu-queue.h"
46 #define TRACE(msg, ...) do { \
47 LOG(msg, ## __VA_ARGS__); \
50 #define TRACE(msg, ...) \
54 #define LOG(msg, ...) do { \
55 fprintf(stderr, "%s:%s():L%d: " msg "\n", \
56 __FILE__, __FUNCTION__, __LINE__, ## __VA_ARGS__); \
59 /* This is all part of the "official" NBD API */
61 #define NBD_REPLY_SIZE (4 + 4 + 8)
62 #define NBD_REQUEST_MAGIC 0x25609513
63 #define NBD_REPLY_MAGIC 0x67446698
65 #define NBD_SET_SOCK _IO(0xab, 0)
66 #define NBD_SET_BLKSIZE _IO(0xab, 1)
67 #define NBD_SET_SIZE _IO(0xab, 2)
68 #define NBD_DO_IT _IO(0xab, 3)
69 #define NBD_CLEAR_SOCK _IO(0xab, 4)
70 #define NBD_CLEAR_QUE _IO(0xab, 5)
71 #define NBD_PRINT_DEBUG _IO(0xab, 6)
72 #define NBD_SET_SIZE_BLOCKS _IO(0xab, 7)
73 #define NBD_DISCONNECT _IO(0xab, 8)
74 #define NBD_SET_TIMEOUT _IO(0xab, 9)
75 #define NBD_SET_FLAGS _IO(0xab, 10)
77 #define NBD_OPT_EXPORT_NAME (1 << 0)
79 /* That's all folks */
81 #define read_sync(fd, buffer, size) nbd_wr_sync(fd, buffer, size, true)
82 #define write_sync(fd, buffer, size) nbd_wr_sync(fd, buffer, size, false)
84 size_t nbd_wr_sync(int fd
, void *buffer
, size_t size
, bool do_read
)
88 if (qemu_in_coroutine()) {
90 return qemu_co_recv(fd
, buffer
, size
);
92 return qemu_co_send(fd
, buffer
, size
);
96 while (offset
< size
) {
100 len
= qemu_recv(fd
, buffer
+ offset
, size
- offset
, 0);
102 len
= send(fd
, buffer
+ offset
, size
- offset
, 0);
106 errno
= socket_error();
108 /* recoverable error */
109 if (len
== -1 && (errno
== EAGAIN
|| errno
== EINTR
)) {
118 /* unrecoverable error */
129 static void combine_addr(char *buf
, size_t len
, const char* address
,
132 /* If the address-part contains a colon, it's an IPv6 IP so needs [] */
133 if (strstr(address
, ":")) {
134 snprintf(buf
, len
, "[%s]:%u", address
, port
);
136 snprintf(buf
, len
, "%s:%u", address
, port
);
140 int tcp_socket_outgoing(const char *address
, uint16_t port
)
142 char address_and_port
[128];
143 combine_addr(address_and_port
, 128, address
, port
);
144 return tcp_socket_outgoing_spec(address_and_port
);
147 int tcp_socket_outgoing_spec(const char *address_and_port
)
149 return inet_connect(address_and_port
, SOCK_STREAM
);
152 int tcp_socket_incoming(const char *address
, uint16_t port
)
154 char address_and_port
[128];
155 combine_addr(address_and_port
, 128, address
, port
);
156 return tcp_socket_incoming_spec(address_and_port
);
159 int tcp_socket_incoming_spec(const char *address_and_port
)
163 return inet_listen(address_and_port
, ostr
, olen
, SOCK_STREAM
, 0);
166 int unix_socket_incoming(const char *path
)
171 return unix_listen(path
, ostr
, olen
);
174 int unix_socket_outgoing(const char *path
)
176 return unix_connect(path
);
193 static int nbd_send_negotiate(int csock
, off_t size
, uint32_t flags
)
195 char buf
[8 + 8 + 8 + 128];
198 [ 0 .. 7] passwd ("NBDMAGIC")
199 [ 8 .. 15] magic (0x00420281861253)
202 [28 .. 151] reserved (0)
205 TRACE("Beginning negotiation.");
206 memcpy(buf
, "NBDMAGIC", 8);
207 cpu_to_be64w((uint64_t*)(buf
+ 8), 0x00420281861253LL
);
208 cpu_to_be64w((uint64_t*)(buf
+ 16), size
);
209 cpu_to_be32w((uint32_t*)(buf
+ 24),
210 flags
| NBD_FLAG_HAS_FLAGS
| NBD_FLAG_SEND_TRIM
|
211 NBD_FLAG_SEND_FLUSH
| NBD_FLAG_SEND_FUA
);
212 memset(buf
+ 28, 0, 124);
214 if (write_sync(csock
, buf
, sizeof(buf
)) != sizeof(buf
)) {
220 TRACE("Negotiation succeeded.");
225 int nbd_receive_negotiate(int csock
, const char *name
, uint32_t *flags
,
226 off_t
*size
, size_t *blocksize
)
232 TRACE("Receiving negotiation.");
234 if (read_sync(csock
, buf
, 8) != 8) {
241 if (strlen(buf
) == 0) {
242 LOG("server connection closed");
247 TRACE("Magic is %c%c%c%c%c%c%c%c",
248 qemu_isprint(buf
[0]) ? buf
[0] : '.',
249 qemu_isprint(buf
[1]) ? buf
[1] : '.',
250 qemu_isprint(buf
[2]) ? buf
[2] : '.',
251 qemu_isprint(buf
[3]) ? buf
[3] : '.',
252 qemu_isprint(buf
[4]) ? buf
[4] : '.',
253 qemu_isprint(buf
[5]) ? buf
[5] : '.',
254 qemu_isprint(buf
[6]) ? buf
[6] : '.',
255 qemu_isprint(buf
[7]) ? buf
[7] : '.');
257 if (memcmp(buf
, "NBDMAGIC", 8) != 0) {
258 LOG("Invalid magic received");
263 if (read_sync(csock
, &magic
, sizeof(magic
)) != sizeof(magic
)) {
268 magic
= be64_to_cpu(magic
);
269 TRACE("Magic is 0x%" PRIx64
, magic
);
272 uint32_t reserved
= 0;
276 TRACE("Checking magic (opts_magic)");
277 if (magic
!= 0x49484156454F5054LL
) {
278 LOG("Bad magic received");
282 if (read_sync(csock
, &tmp
, sizeof(tmp
)) != sizeof(tmp
)) {
283 LOG("flags read failed");
287 *flags
= be16_to_cpu(tmp
) << 16;
288 /* reserved for future use */
289 if (write_sync(csock
, &reserved
, sizeof(reserved
)) !=
291 LOG("write failed (reserved)");
295 /* write the export name */
296 magic
= cpu_to_be64(magic
);
297 if (write_sync(csock
, &magic
, sizeof(magic
)) != sizeof(magic
)) {
298 LOG("write failed (magic)");
302 opt
= cpu_to_be32(NBD_OPT_EXPORT_NAME
);
303 if (write_sync(csock
, &opt
, sizeof(opt
)) != sizeof(opt
)) {
304 LOG("write failed (opt)");
308 namesize
= cpu_to_be32(strlen(name
));
309 if (write_sync(csock
, &namesize
, sizeof(namesize
)) !=
311 LOG("write failed (namesize)");
315 if (write_sync(csock
, (char*)name
, strlen(name
)) != strlen(name
)) {
316 LOG("write failed (name)");
321 TRACE("Checking magic (cli_magic)");
323 if (magic
!= 0x00420281861253LL
) {
324 LOG("Bad magic received");
330 if (read_sync(csock
, &s
, sizeof(s
)) != sizeof(s
)) {
335 *size
= be64_to_cpu(s
);
337 TRACE("Size is %" PRIu64
, *size
);
340 if (read_sync(csock
, flags
, sizeof(*flags
)) != sizeof(*flags
)) {
341 LOG("read failed (flags)");
345 *flags
= be32_to_cpup(flags
);
347 if (read_sync(csock
, &tmp
, sizeof(tmp
)) != sizeof(tmp
)) {
348 LOG("read failed (tmp)");
352 *flags
|= be32_to_cpu(tmp
);
354 if (read_sync(csock
, &buf
, 124) != 124) {
355 LOG("read failed (buf)");
363 int nbd_init(int fd
, int csock
, uint32_t flags
, off_t size
, size_t blocksize
)
365 TRACE("Setting NBD socket");
367 if (ioctl(fd
, NBD_SET_SOCK
, csock
) == -1) {
369 LOG("Failed to set NBD socket");
374 TRACE("Setting block size to %lu", (unsigned long)blocksize
);
376 if (ioctl(fd
, NBD_SET_BLKSIZE
, blocksize
) == -1) {
378 LOG("Failed setting NBD block size");
383 TRACE("Setting size to %zd block(s)", (size_t)(size
/ blocksize
));
385 if (ioctl(fd
, NBD_SET_SIZE_BLOCKS
, size
/ blocksize
) == -1) {
387 LOG("Failed setting size (in blocks)");
392 if (flags
& NBD_FLAG_READ_ONLY
) {
394 TRACE("Setting readonly attribute");
396 if (ioctl(fd
, BLKROSET
, (unsigned long) &read_only
) < 0) {
398 LOG("Failed setting read-only attribute");
404 if (ioctl(fd
, NBD_SET_FLAGS
, flags
) < 0
405 && errno
!= ENOTTY
) {
407 LOG("Failed setting flags");
412 TRACE("Negotiation ended");
417 int nbd_disconnect(int fd
)
419 ioctl(fd
, NBD_CLEAR_QUE
);
420 ioctl(fd
, NBD_DISCONNECT
);
421 ioctl(fd
, NBD_CLEAR_SOCK
);
425 int nbd_client(int fd
)
430 TRACE("Doing NBD loop");
432 ret
= ioctl(fd
, NBD_DO_IT
);
433 if (ret
== -1 && errno
== EPIPE
) {
434 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
435 * the socket via NBD_DISCONNECT. We do not want to return 1 in
442 TRACE("NBD loop returned %d: %s", ret
, strerror(serrno
));
444 TRACE("Clearing NBD queue");
445 ioctl(fd
, NBD_CLEAR_QUE
);
447 TRACE("Clearing NBD socket");
448 ioctl(fd
, NBD_CLEAR_SOCK
);
454 int nbd_init(int fd
, int csock
, uint32_t flags
, off_t size
, size_t blocksize
)
460 int nbd_disconnect(int fd
)
466 int nbd_client(int fd
)
473 int nbd_send_request(int csock
, struct nbd_request
*request
)
475 uint8_t buf
[4 + 4 + 8 + 8 + 4];
477 cpu_to_be32w((uint32_t*)buf
, NBD_REQUEST_MAGIC
);
478 cpu_to_be32w((uint32_t*)(buf
+ 4), request
->type
);
479 cpu_to_be64w((uint64_t*)(buf
+ 8), request
->handle
);
480 cpu_to_be64w((uint64_t*)(buf
+ 16), request
->from
);
481 cpu_to_be32w((uint32_t*)(buf
+ 24), request
->len
);
483 TRACE("Sending request to client: "
484 "{ .from = %" PRIu64
", .len = %u, .handle = %" PRIu64
", .type=%i}",
485 request
->from
, request
->len
, request
->handle
, request
->type
);
487 if (write_sync(csock
, buf
, sizeof(buf
)) != sizeof(buf
)) {
488 LOG("writing to socket failed");
495 static int nbd_receive_request(int csock
, struct nbd_request
*request
)
497 uint8_t buf
[4 + 4 + 8 + 8 + 4];
500 if (read_sync(csock
, buf
, sizeof(buf
)) != sizeof(buf
)) {
507 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
508 [ 4 .. 7] type (0 == READ, 1 == WRITE)
514 magic
= be32_to_cpup((uint32_t*)buf
);
515 request
->type
= be32_to_cpup((uint32_t*)(buf
+ 4));
516 request
->handle
= be64_to_cpup((uint64_t*)(buf
+ 8));
517 request
->from
= be64_to_cpup((uint64_t*)(buf
+ 16));
518 request
->len
= be32_to_cpup((uint32_t*)(buf
+ 24));
520 TRACE("Got request: "
521 "{ magic = 0x%x, .type = %d, from = %" PRIu64
" , len = %u }",
522 magic
, request
->type
, request
->from
, request
->len
);
524 if (magic
!= NBD_REQUEST_MAGIC
) {
525 LOG("invalid magic (got 0x%x)", magic
);
532 int nbd_receive_reply(int csock
, struct nbd_reply
*reply
)
534 uint8_t buf
[NBD_REPLY_SIZE
];
537 memset(buf
, 0xAA, sizeof(buf
));
539 if (read_sync(csock
, buf
, sizeof(buf
)) != sizeof(buf
)) {
546 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
547 [ 4 .. 7] error (0 == no error)
551 magic
= be32_to_cpup((uint32_t*)buf
);
552 reply
->error
= be32_to_cpup((uint32_t*)(buf
+ 4));
553 reply
->handle
= be64_to_cpup((uint64_t*)(buf
+ 8));
556 "{ magic = 0x%x, .error = %d, handle = %" PRIu64
" }",
557 magic
, reply
->error
, reply
->handle
);
559 if (magic
!= NBD_REPLY_MAGIC
) {
560 LOG("invalid magic (got 0x%x)", magic
);
567 static int nbd_send_reply(int csock
, struct nbd_reply
*reply
)
569 uint8_t buf
[4 + 4 + 8];
572 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
573 [ 4 .. 7] error (0 == no error)
576 cpu_to_be32w((uint32_t*)buf
, NBD_REPLY_MAGIC
);
577 cpu_to_be32w((uint32_t*)(buf
+ 4), reply
->error
);
578 cpu_to_be64w((uint64_t*)(buf
+ 8), reply
->handle
);
580 TRACE("Sending response to client");
582 if (write_sync(csock
, buf
, sizeof(buf
)) != sizeof(buf
)) {
583 LOG("writing to socket failed");
590 #define MAX_NBD_REQUESTS 16
592 typedef struct NBDRequest NBDRequest
;
595 QSIMPLEQ_ENTRY(NBDRequest
) entry
;
601 BlockDriverState
*bs
;
605 QSIMPLEQ_HEAD(, NBDRequest
) requests
;
610 void (*close
)(NBDClient
*client
);
615 Coroutine
*recv_coroutine
;
618 Coroutine
*send_coroutine
;
623 static void nbd_client_get(NBDClient
*client
)
628 static void nbd_client_put(NBDClient
*client
)
630 if (--client
->refcount
== 0) {
635 static void nbd_client_close(NBDClient
*client
)
637 qemu_set_fd_handler2(client
->sock
, NULL
, NULL
, NULL
, NULL
);
641 client
->close(client
);
643 nbd_client_put(client
);
646 static NBDRequest
*nbd_request_get(NBDClient
*client
)
649 NBDExport
*exp
= client
->exp
;
651 assert(client
->nb_requests
<= MAX_NBD_REQUESTS
- 1);
652 client
->nb_requests
++;
654 if (QSIMPLEQ_EMPTY(&exp
->requests
)) {
655 req
= g_malloc0(sizeof(NBDRequest
));
656 req
->data
= qemu_blockalign(exp
->bs
, NBD_BUFFER_SIZE
);
658 req
= QSIMPLEQ_FIRST(&exp
->requests
);
659 QSIMPLEQ_REMOVE_HEAD(&exp
->requests
, entry
);
661 nbd_client_get(client
);
662 req
->client
= client
;
666 static void nbd_request_put(NBDRequest
*req
)
668 NBDClient
*client
= req
->client
;
669 QSIMPLEQ_INSERT_HEAD(&client
->exp
->requests
, req
, entry
);
670 if (client
->nb_requests
-- == MAX_NBD_REQUESTS
) {
673 nbd_client_put(client
);
676 NBDExport
*nbd_export_new(BlockDriverState
*bs
, off_t dev_offset
,
677 off_t size
, uint32_t nbdflags
)
679 NBDExport
*exp
= g_malloc0(sizeof(NBDExport
));
680 QSIMPLEQ_INIT(&exp
->requests
);
682 exp
->dev_offset
= dev_offset
;
683 exp
->nbdflags
= nbdflags
;
684 exp
->size
= size
== -1 ? exp
->bs
->total_sectors
* 512 : size
;
688 void nbd_export_close(NBDExport
*exp
)
690 while (!QSIMPLEQ_EMPTY(&exp
->requests
)) {
691 NBDRequest
*first
= QSIMPLEQ_FIRST(&exp
->requests
);
692 QSIMPLEQ_REMOVE_HEAD(&exp
->requests
, entry
);
693 qemu_vfree(first
->data
);
701 static int nbd_can_read(void *opaque
);
702 static void nbd_read(void *opaque
);
703 static void nbd_restart_write(void *opaque
);
705 static int nbd_co_send_reply(NBDRequest
*req
, struct nbd_reply
*reply
,
708 NBDClient
*client
= req
->client
;
709 int csock
= client
->sock
;
712 qemu_co_mutex_lock(&client
->send_lock
);
713 qemu_set_fd_handler2(csock
, nbd_can_read
, nbd_read
,
714 nbd_restart_write
, client
);
715 client
->send_coroutine
= qemu_coroutine_self();
718 rc
= nbd_send_reply(csock
, reply
);
723 socket_set_cork(csock
, 1);
724 rc
= nbd_send_reply(csock
, reply
);
726 ret
= qemu_co_send(csock
, req
->data
, len
);
735 socket_set_cork(csock
, 0);
738 client
->send_coroutine
= NULL
;
739 qemu_set_fd_handler2(csock
, nbd_can_read
, nbd_read
, NULL
, client
);
740 qemu_co_mutex_unlock(&client
->send_lock
);
744 static int nbd_co_receive_request(NBDRequest
*req
, struct nbd_request
*request
)
746 NBDClient
*client
= req
->client
;
747 int csock
= client
->sock
;
750 client
->recv_coroutine
= qemu_coroutine_self();
751 if (nbd_receive_request(csock
, request
) == -1) {
756 if (request
->len
> NBD_BUFFER_SIZE
) {
757 LOG("len (%u) is larger than max len (%u)",
758 request
->len
, NBD_BUFFER_SIZE
);
763 if ((request
->from
+ request
->len
) < request
->from
) {
764 LOG("integer overflow detected! "
765 "you're probably being attacked");
770 TRACE("Decoding type");
772 if ((request
->type
& NBD_CMD_MASK_COMMAND
) == NBD_CMD_WRITE
) {
773 TRACE("Reading %u byte(s)", request
->len
);
775 if (qemu_co_recv(csock
, req
->data
, request
->len
) != request
->len
) {
776 LOG("reading from socket failed");
784 client
->recv_coroutine
= NULL
;
788 static void nbd_trip(void *opaque
)
790 NBDClient
*client
= opaque
;
791 NBDRequest
*req
= nbd_request_get(client
);
792 NBDExport
*exp
= client
->exp
;
793 struct nbd_request request
;
794 struct nbd_reply reply
;
797 TRACE("Reading request.");
799 ret
= nbd_co_receive_request(req
, &request
);
804 reply
.handle
= request
.handle
;
812 if ((request
.from
+ request
.len
) > exp
->size
) {
813 LOG("From: %" PRIu64
", Len: %u, Size: %" PRIu64
814 ", Offset: %" PRIu64
"\n",
815 request
.from
, request
.len
,
816 (uint64_t)exp
->size
, exp
->dev_offset
);
817 LOG("requested operation past EOF--bad client?");
818 goto invalid_request
;
821 switch (request
.type
& NBD_CMD_MASK_COMMAND
) {
823 TRACE("Request type is READ");
825 ret
= bdrv_read(exp
->bs
, (request
.from
+ exp
->dev_offset
) / 512,
826 req
->data
, request
.len
/ 512);
828 LOG("reading from file failed");
833 TRACE("Read %u byte(s)", request
.len
);
834 if (nbd_co_send_reply(req
, &reply
, request
.len
) < 0)
838 TRACE("Request type is WRITE");
840 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
841 TRACE("Server is read-only, return error");
846 TRACE("Writing to device");
848 ret
= bdrv_write(exp
->bs
, (request
.from
+ exp
->dev_offset
) / 512,
849 req
->data
, request
.len
/ 512);
851 LOG("writing to file failed");
856 if (request
.type
& NBD_CMD_FLAG_FUA
) {
857 ret
= bdrv_co_flush(exp
->bs
);
865 if (nbd_co_send_reply(req
, &reply
, 0) < 0)
869 TRACE("Request type is DISCONNECT");
873 TRACE("Request type is FLUSH");
875 ret
= bdrv_co_flush(exp
->bs
);
881 if (nbd_co_send_reply(req
, &reply
, 0) < 0)
885 TRACE("Request type is TRIM");
886 ret
= bdrv_co_discard(exp
->bs
, (request
.from
+ exp
->dev_offset
) / 512,
889 LOG("discard failed");
892 if (nbd_co_send_reply(req
, &reply
, 0) < 0)
896 LOG("invalid request type (%u) received", request
.type
);
898 reply
.error
= -EINVAL
;
900 if (nbd_co_send_reply(req
, &reply
, 0) == -1)
905 TRACE("Request/Reply complete");
907 nbd_request_put(req
);
911 nbd_request_put(req
);
912 nbd_client_close(client
);
915 static int nbd_can_read(void *opaque
)
917 NBDClient
*client
= opaque
;
919 return client
->recv_coroutine
|| client
->nb_requests
< MAX_NBD_REQUESTS
;
922 static void nbd_read(void *opaque
)
924 NBDClient
*client
= opaque
;
926 if (client
->recv_coroutine
) {
927 qemu_coroutine_enter(client
->recv_coroutine
, NULL
);
929 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip
), client
);
933 static void nbd_restart_write(void *opaque
)
935 NBDClient
*client
= opaque
;
937 qemu_coroutine_enter(client
->send_coroutine
, NULL
);
940 NBDClient
*nbd_client_new(NBDExport
*exp
, int csock
,
941 void (*close
)(NBDClient
*))
944 if (nbd_send_negotiate(csock
, exp
->size
, exp
->nbdflags
) == -1) {
947 client
= g_malloc0(sizeof(NBDClient
));
948 client
->refcount
= 1;
950 client
->sock
= csock
;
951 client
->close
= close
;
952 qemu_co_mutex_init(&client
->send_lock
);
953 qemu_set_fd_handler2(csock
, nbd_can_read
, nbd_read
, NULL
, client
);