]>
git.proxmox.com Git - qemu.git/blob - nbd.c
4c6d7f193d6db95530d367a7146d15c1ea870122
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 ssize_t
nbd_wr_sync(int fd
, void *buffer
, size_t size
, bool do_read
)
86 if (qemu_in_coroutine()) {
88 return qemu_co_recv(fd
, buffer
, size
);
90 return qemu_co_send(fd
, buffer
, size
);
94 while (offset
< size
) {
98 len
= qemu_recv(fd
, buffer
+ offset
, size
- offset
, 0);
100 len
= send(fd
, buffer
+ offset
, size
- offset
, 0);
104 err
= socket_error();
106 /* recoverable error */
107 if (err
== EINTR
|| (offset
> 0 && err
== EAGAIN
)) {
111 /* unrecoverable error */
126 static ssize_t
read_sync(int fd
, void *buffer
, size_t size
)
128 /* Sockets are kept in blocking mode in the negotiation phase. After
129 * that, a non-readable socket simply means that another thread stole
130 * our request/reply. Synchronization is done with recv_coroutine, so
131 * that this is coroutine-safe.
133 return nbd_wr_sync(fd
, buffer
, size
, true);
136 static ssize_t
write_sync(int fd
, void *buffer
, size_t size
)
140 /* For writes, we do expect the socket to be writable. */
141 ret
= nbd_wr_sync(fd
, buffer
, size
, false);
142 } while (ret
== -EAGAIN
);
146 static void combine_addr(char *buf
, size_t len
, const char* address
,
149 /* If the address-part contains a colon, it's an IPv6 IP so needs [] */
150 if (strstr(address
, ":")) {
151 snprintf(buf
, len
, "[%s]:%u", address
, port
);
153 snprintf(buf
, len
, "%s:%u", address
, port
);
157 int tcp_socket_outgoing(const char *address
, uint16_t port
)
159 char address_and_port
[128];
160 combine_addr(address_and_port
, 128, address
, port
);
161 return tcp_socket_outgoing_spec(address_and_port
);
164 int tcp_socket_outgoing_spec(const char *address_and_port
)
166 return inet_connect(address_and_port
, SOCK_STREAM
);
169 int tcp_socket_incoming(const char *address
, uint16_t port
)
171 char address_and_port
[128];
172 combine_addr(address_and_port
, 128, address
, port
);
173 return tcp_socket_incoming_spec(address_and_port
);
176 int tcp_socket_incoming_spec(const char *address_and_port
)
180 return inet_listen(address_and_port
, ostr
, olen
, SOCK_STREAM
, 0);
183 int unix_socket_incoming(const char *path
)
188 return unix_listen(path
, ostr
, olen
);
191 int unix_socket_outgoing(const char *path
)
193 return unix_connect(path
);
210 static int nbd_send_negotiate(int csock
, off_t size
, uint32_t flags
)
212 char buf
[8 + 8 + 8 + 128];
216 [ 0 .. 7] passwd ("NBDMAGIC")
217 [ 8 .. 15] magic (0x00420281861253)
220 [28 .. 151] reserved (0)
223 socket_set_block(csock
);
226 TRACE("Beginning negotiation.");
227 memcpy(buf
, "NBDMAGIC", 8);
228 cpu_to_be64w((uint64_t*)(buf
+ 8), 0x00420281861253LL
);
229 cpu_to_be64w((uint64_t*)(buf
+ 16), size
);
230 cpu_to_be32w((uint32_t*)(buf
+ 24),
231 flags
| NBD_FLAG_HAS_FLAGS
| NBD_FLAG_SEND_TRIM
|
232 NBD_FLAG_SEND_FLUSH
| NBD_FLAG_SEND_FUA
);
233 memset(buf
+ 28, 0, 124);
235 if (write_sync(csock
, buf
, sizeof(buf
)) != sizeof(buf
)) {
240 TRACE("Negotiation succeeded.");
243 socket_set_nonblock(csock
);
247 int nbd_receive_negotiate(int csock
, const char *name
, uint32_t *flags
,
248 off_t
*size
, size_t *blocksize
)
255 TRACE("Receiving negotiation.");
257 socket_set_block(csock
);
260 if (read_sync(csock
, buf
, 8) != 8) {
266 if (strlen(buf
) == 0) {
267 LOG("server connection closed");
271 TRACE("Magic is %c%c%c%c%c%c%c%c",
272 qemu_isprint(buf
[0]) ? buf
[0] : '.',
273 qemu_isprint(buf
[1]) ? buf
[1] : '.',
274 qemu_isprint(buf
[2]) ? buf
[2] : '.',
275 qemu_isprint(buf
[3]) ? buf
[3] : '.',
276 qemu_isprint(buf
[4]) ? buf
[4] : '.',
277 qemu_isprint(buf
[5]) ? buf
[5] : '.',
278 qemu_isprint(buf
[6]) ? buf
[6] : '.',
279 qemu_isprint(buf
[7]) ? buf
[7] : '.');
281 if (memcmp(buf
, "NBDMAGIC", 8) != 0) {
282 LOG("Invalid magic received");
286 if (read_sync(csock
, &magic
, sizeof(magic
)) != sizeof(magic
)) {
290 magic
= be64_to_cpu(magic
);
291 TRACE("Magic is 0x%" PRIx64
, magic
);
294 uint32_t reserved
= 0;
298 TRACE("Checking magic (opts_magic)");
299 if (magic
!= 0x49484156454F5054LL
) {
300 LOG("Bad magic received");
303 if (read_sync(csock
, &tmp
, sizeof(tmp
)) != sizeof(tmp
)) {
304 LOG("flags read failed");
307 *flags
= be16_to_cpu(tmp
) << 16;
308 /* reserved for future use */
309 if (write_sync(csock
, &reserved
, sizeof(reserved
)) !=
311 LOG("write failed (reserved)");
314 /* write the export name */
315 magic
= cpu_to_be64(magic
);
316 if (write_sync(csock
, &magic
, sizeof(magic
)) != sizeof(magic
)) {
317 LOG("write failed (magic)");
320 opt
= cpu_to_be32(NBD_OPT_EXPORT_NAME
);
321 if (write_sync(csock
, &opt
, sizeof(opt
)) != sizeof(opt
)) {
322 LOG("write failed (opt)");
325 namesize
= cpu_to_be32(strlen(name
));
326 if (write_sync(csock
, &namesize
, sizeof(namesize
)) !=
328 LOG("write failed (namesize)");
331 if (write_sync(csock
, (char*)name
, strlen(name
)) != strlen(name
)) {
332 LOG("write failed (name)");
336 TRACE("Checking magic (cli_magic)");
338 if (magic
!= 0x00420281861253LL
) {
339 LOG("Bad magic received");
344 if (read_sync(csock
, &s
, sizeof(s
)) != sizeof(s
)) {
348 *size
= be64_to_cpu(s
);
350 TRACE("Size is %" PRIu64
, *size
);
353 if (read_sync(csock
, flags
, sizeof(*flags
)) != sizeof(*flags
)) {
354 LOG("read failed (flags)");
357 *flags
= be32_to_cpup(flags
);
359 if (read_sync(csock
, &tmp
, sizeof(tmp
)) != sizeof(tmp
)) {
360 LOG("read failed (tmp)");
363 *flags
|= be32_to_cpu(tmp
);
365 if (read_sync(csock
, &buf
, 124) != 124) {
366 LOG("read failed (buf)");
372 socket_set_nonblock(csock
);
377 int nbd_init(int fd
, int csock
, uint32_t flags
, off_t size
, size_t blocksize
)
379 TRACE("Setting NBD socket");
381 if (ioctl(fd
, NBD_SET_SOCK
, csock
) < 0) {
383 LOG("Failed to set NBD socket");
387 TRACE("Setting block size to %lu", (unsigned long)blocksize
);
389 if (ioctl(fd
, NBD_SET_BLKSIZE
, blocksize
) < 0) {
391 LOG("Failed setting NBD block size");
395 TRACE("Setting size to %zd block(s)", (size_t)(size
/ blocksize
));
397 if (ioctl(fd
, NBD_SET_SIZE_BLOCKS
, size
/ blocksize
) < 0) {
399 LOG("Failed setting size (in blocks)");
403 if (flags
& NBD_FLAG_READ_ONLY
) {
405 TRACE("Setting readonly attribute");
407 if (ioctl(fd
, BLKROSET
, (unsigned long) &read_only
) < 0) {
409 LOG("Failed setting read-only attribute");
414 if (ioctl(fd
, NBD_SET_FLAGS
, flags
) < 0
415 && errno
!= ENOTTY
) {
417 LOG("Failed setting flags");
421 TRACE("Negotiation ended");
426 int nbd_disconnect(int fd
)
428 ioctl(fd
, NBD_CLEAR_QUE
);
429 ioctl(fd
, NBD_DISCONNECT
);
430 ioctl(fd
, NBD_CLEAR_SOCK
);
434 int nbd_client(int fd
)
439 TRACE("Doing NBD loop");
441 ret
= ioctl(fd
, NBD_DO_IT
);
442 if (ret
< 0 && errno
== EPIPE
) {
443 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
444 * the socket via NBD_DISCONNECT. We do not want to return 1 in
451 TRACE("NBD loop returned %d: %s", ret
, strerror(serrno
));
453 TRACE("Clearing NBD queue");
454 ioctl(fd
, NBD_CLEAR_QUE
);
456 TRACE("Clearing NBD socket");
457 ioctl(fd
, NBD_CLEAR_SOCK
);
463 int nbd_init(int fd
, int csock
, uint32_t flags
, off_t size
, size_t blocksize
)
468 int nbd_disconnect(int fd
)
473 int nbd_client(int fd
)
479 ssize_t
nbd_send_request(int csock
, struct nbd_request
*request
)
481 uint8_t buf
[4 + 4 + 8 + 8 + 4];
484 cpu_to_be32w((uint32_t*)buf
, NBD_REQUEST_MAGIC
);
485 cpu_to_be32w((uint32_t*)(buf
+ 4), request
->type
);
486 cpu_to_be64w((uint64_t*)(buf
+ 8), request
->handle
);
487 cpu_to_be64w((uint64_t*)(buf
+ 16), request
->from
);
488 cpu_to_be32w((uint32_t*)(buf
+ 24), request
->len
);
490 TRACE("Sending request to client: "
491 "{ .from = %" PRIu64
", .len = %u, .handle = %" PRIu64
", .type=%i}",
492 request
->from
, request
->len
, request
->handle
, request
->type
);
494 ret
= write_sync(csock
, buf
, sizeof(buf
));
499 if (ret
!= sizeof(buf
)) {
500 LOG("writing to socket failed");
506 static ssize_t
nbd_receive_request(int csock
, struct nbd_request
*request
)
508 uint8_t buf
[4 + 4 + 8 + 8 + 4];
512 ret
= read_sync(csock
, buf
, sizeof(buf
));
517 if (ret
!= sizeof(buf
)) {
523 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
524 [ 4 .. 7] type (0 == READ, 1 == WRITE)
530 magic
= be32_to_cpup((uint32_t*)buf
);
531 request
->type
= be32_to_cpup((uint32_t*)(buf
+ 4));
532 request
->handle
= be64_to_cpup((uint64_t*)(buf
+ 8));
533 request
->from
= be64_to_cpup((uint64_t*)(buf
+ 16));
534 request
->len
= be32_to_cpup((uint32_t*)(buf
+ 24));
536 TRACE("Got request: "
537 "{ magic = 0x%x, .type = %d, from = %" PRIu64
" , len = %u }",
538 magic
, request
->type
, request
->from
, request
->len
);
540 if (magic
!= NBD_REQUEST_MAGIC
) {
541 LOG("invalid magic (got 0x%x)", magic
);
547 ssize_t
nbd_receive_reply(int csock
, struct nbd_reply
*reply
)
549 uint8_t buf
[NBD_REPLY_SIZE
];
553 ret
= read_sync(csock
, buf
, sizeof(buf
));
558 if (ret
!= sizeof(buf
)) {
564 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
565 [ 4 .. 7] error (0 == no error)
569 magic
= be32_to_cpup((uint32_t*)buf
);
570 reply
->error
= be32_to_cpup((uint32_t*)(buf
+ 4));
571 reply
->handle
= be64_to_cpup((uint64_t*)(buf
+ 8));
574 "{ magic = 0x%x, .error = %d, handle = %" PRIu64
" }",
575 magic
, reply
->error
, reply
->handle
);
577 if (magic
!= NBD_REPLY_MAGIC
) {
578 LOG("invalid magic (got 0x%x)", magic
);
584 static ssize_t
nbd_send_reply(int csock
, struct nbd_reply
*reply
)
586 uint8_t buf
[4 + 4 + 8];
590 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
591 [ 4 .. 7] error (0 == no error)
594 cpu_to_be32w((uint32_t*)buf
, NBD_REPLY_MAGIC
);
595 cpu_to_be32w((uint32_t*)(buf
+ 4), reply
->error
);
596 cpu_to_be64w((uint64_t*)(buf
+ 8), reply
->handle
);
598 TRACE("Sending response to client");
600 ret
= write_sync(csock
, buf
, sizeof(buf
));
605 if (ret
!= sizeof(buf
)) {
606 LOG("writing to socket failed");
612 #define MAX_NBD_REQUESTS 16
614 typedef struct NBDRequest NBDRequest
;
617 QSIMPLEQ_ENTRY(NBDRequest
) entry
;
623 BlockDriverState
*bs
;
627 QSIMPLEQ_HEAD(, NBDRequest
) requests
;
632 void (*close
)(NBDClient
*client
);
637 Coroutine
*recv_coroutine
;
640 Coroutine
*send_coroutine
;
645 static void nbd_client_get(NBDClient
*client
)
650 static void nbd_client_put(NBDClient
*client
)
652 if (--client
->refcount
== 0) {
657 static void nbd_client_close(NBDClient
*client
)
659 qemu_set_fd_handler2(client
->sock
, NULL
, NULL
, NULL
, NULL
);
663 client
->close(client
);
665 nbd_client_put(client
);
668 static NBDRequest
*nbd_request_get(NBDClient
*client
)
671 NBDExport
*exp
= client
->exp
;
673 assert(client
->nb_requests
<= MAX_NBD_REQUESTS
- 1);
674 client
->nb_requests
++;
676 if (QSIMPLEQ_EMPTY(&exp
->requests
)) {
677 req
= g_malloc0(sizeof(NBDRequest
));
678 req
->data
= qemu_blockalign(exp
->bs
, NBD_BUFFER_SIZE
);
680 req
= QSIMPLEQ_FIRST(&exp
->requests
);
681 QSIMPLEQ_REMOVE_HEAD(&exp
->requests
, entry
);
683 nbd_client_get(client
);
684 req
->client
= client
;
688 static void nbd_request_put(NBDRequest
*req
)
690 NBDClient
*client
= req
->client
;
691 QSIMPLEQ_INSERT_HEAD(&client
->exp
->requests
, req
, entry
);
692 if (client
->nb_requests
-- == MAX_NBD_REQUESTS
) {
695 nbd_client_put(client
);
698 NBDExport
*nbd_export_new(BlockDriverState
*bs
, off_t dev_offset
,
699 off_t size
, uint32_t nbdflags
)
701 NBDExport
*exp
= g_malloc0(sizeof(NBDExport
));
702 QSIMPLEQ_INIT(&exp
->requests
);
704 exp
->dev_offset
= dev_offset
;
705 exp
->nbdflags
= nbdflags
;
706 exp
->size
= size
== -1 ? exp
->bs
->total_sectors
* 512 : size
;
710 void nbd_export_close(NBDExport
*exp
)
712 while (!QSIMPLEQ_EMPTY(&exp
->requests
)) {
713 NBDRequest
*first
= QSIMPLEQ_FIRST(&exp
->requests
);
714 QSIMPLEQ_REMOVE_HEAD(&exp
->requests
, entry
);
715 qemu_vfree(first
->data
);
723 static int nbd_can_read(void *opaque
);
724 static void nbd_read(void *opaque
);
725 static void nbd_restart_write(void *opaque
);
727 static ssize_t
nbd_co_send_reply(NBDRequest
*req
, struct nbd_reply
*reply
,
730 NBDClient
*client
= req
->client
;
731 int csock
= client
->sock
;
734 qemu_co_mutex_lock(&client
->send_lock
);
735 qemu_set_fd_handler2(csock
, nbd_can_read
, nbd_read
,
736 nbd_restart_write
, client
);
737 client
->send_coroutine
= qemu_coroutine_self();
740 rc
= nbd_send_reply(csock
, reply
);
742 socket_set_cork(csock
, 1);
743 rc
= nbd_send_reply(csock
, reply
);
745 ret
= qemu_co_send(csock
, req
->data
, len
);
750 socket_set_cork(csock
, 0);
753 client
->send_coroutine
= NULL
;
754 qemu_set_fd_handler2(csock
, nbd_can_read
, nbd_read
, NULL
, client
);
755 qemu_co_mutex_unlock(&client
->send_lock
);
759 static ssize_t
nbd_co_receive_request(NBDRequest
*req
, struct nbd_request
*request
)
761 NBDClient
*client
= req
->client
;
762 int csock
= client
->sock
;
765 client
->recv_coroutine
= qemu_coroutine_self();
766 rc
= nbd_receive_request(csock
, request
);
774 if (request
->len
> NBD_BUFFER_SIZE
) {
775 LOG("len (%u) is larger than max len (%u)",
776 request
->len
, NBD_BUFFER_SIZE
);
781 if ((request
->from
+ request
->len
) < request
->from
) {
782 LOG("integer overflow detected! "
783 "you're probably being attacked");
788 TRACE("Decoding type");
790 if ((request
->type
& NBD_CMD_MASK_COMMAND
) == NBD_CMD_WRITE
) {
791 TRACE("Reading %u byte(s)", request
->len
);
793 if (qemu_co_recv(csock
, req
->data
, request
->len
) != request
->len
) {
794 LOG("reading from socket failed");
802 client
->recv_coroutine
= NULL
;
806 static void nbd_trip(void *opaque
)
808 NBDClient
*client
= opaque
;
809 NBDRequest
*req
= nbd_request_get(client
);
810 NBDExport
*exp
= client
->exp
;
811 struct nbd_request request
;
812 struct nbd_reply reply
;
815 TRACE("Reading request.");
817 ret
= nbd_co_receive_request(req
, &request
);
818 if (ret
== -EAGAIN
) {
825 reply
.handle
= request
.handle
;
833 if ((request
.from
+ request
.len
) > exp
->size
) {
834 LOG("From: %" PRIu64
", Len: %u, Size: %" PRIu64
835 ", Offset: %" PRIu64
"\n",
836 request
.from
, request
.len
,
837 (uint64_t)exp
->size
, (uint64_t)exp
->dev_offset
);
838 LOG("requested operation past EOF--bad client?");
839 goto invalid_request
;
842 switch (request
.type
& NBD_CMD_MASK_COMMAND
) {
844 TRACE("Request type is READ");
846 ret
= bdrv_read(exp
->bs
, (request
.from
+ exp
->dev_offset
) / 512,
847 req
->data
, request
.len
/ 512);
849 LOG("reading from file failed");
854 TRACE("Read %u byte(s)", request
.len
);
855 if (nbd_co_send_reply(req
, &reply
, request
.len
) < 0)
859 TRACE("Request type is WRITE");
861 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
862 TRACE("Server is read-only, return error");
867 TRACE("Writing to device");
869 ret
= bdrv_write(exp
->bs
, (request
.from
+ exp
->dev_offset
) / 512,
870 req
->data
, request
.len
/ 512);
872 LOG("writing to file failed");
877 if (request
.type
& NBD_CMD_FLAG_FUA
) {
878 ret
= bdrv_co_flush(exp
->bs
);
886 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
891 TRACE("Request type is DISCONNECT");
895 TRACE("Request type is FLUSH");
897 ret
= bdrv_co_flush(exp
->bs
);
902 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
907 TRACE("Request type is TRIM");
908 ret
= bdrv_co_discard(exp
->bs
, (request
.from
+ exp
->dev_offset
) / 512,
911 LOG("discard failed");
914 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
919 LOG("invalid request type (%u) received", request
.type
);
921 reply
.error
= -EINVAL
;
923 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
929 TRACE("Request/Reply complete");
932 nbd_request_put(req
);
936 nbd_request_put(req
);
937 nbd_client_close(client
);
940 static int nbd_can_read(void *opaque
)
942 NBDClient
*client
= opaque
;
944 return client
->recv_coroutine
|| client
->nb_requests
< MAX_NBD_REQUESTS
;
947 static void nbd_read(void *opaque
)
949 NBDClient
*client
= opaque
;
951 if (client
->recv_coroutine
) {
952 qemu_coroutine_enter(client
->recv_coroutine
, NULL
);
954 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip
), client
);
958 static void nbd_restart_write(void *opaque
)
960 NBDClient
*client
= opaque
;
962 qemu_coroutine_enter(client
->send_coroutine
, NULL
);
965 NBDClient
*nbd_client_new(NBDExport
*exp
, int csock
,
966 void (*close
)(NBDClient
*))
969 if (nbd_send_negotiate(csock
, exp
->size
, exp
->nbdflags
) < 0) {
972 client
= g_malloc0(sizeof(NBDClient
));
973 client
->refcount
= 1;
975 client
->sock
= csock
;
976 client
->close
= close
;
977 qemu_co_mutex_init(&client
->send_lock
);
978 qemu_set_fd_handler2(csock
, nbd_can_read
, nbd_read
, NULL
, client
);