2 * QEMU Block driver for NBD
4 * Copyright (C) 2008 Bull S.A.S.
5 * Author: Laurent Vivier <Laurent.Vivier@bull.net>
8 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 #include "qemu-common.h"
30 #include "block/nbd.h"
32 #include "block/block_int.h"
33 #include "qemu/module.h"
34 #include "qemu/sockets.h"
35 #include "qapi/qmp/qjson.h"
36 #include "qapi/qmp/qint.h"
38 #include <sys/types.h>
41 #define EN_OPTSTR ":exportname="
43 /* #define DEBUG_NBD */
45 #if defined(DEBUG_NBD)
46 #define logout(fmt, ...) \
47 fprintf(stderr, "nbd\t%-24s" fmt, __func__, ##__VA_ARGS__)
49 #define logout(fmt, ...) ((void)0)
52 #define MAX_NBD_REQUESTS 16
53 #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ ((uint64_t)(intptr_t)bs))
54 #define INDEX_TO_HANDLE(bs, index) ((index) ^ ((uint64_t)(intptr_t)bs))
56 typedef struct BDRVNBDState
{
64 Coroutine
*send_coroutine
;
67 Coroutine
*recv_coroutine
[MAX_NBD_REQUESTS
];
68 struct nbd_reply reply
;
71 QemuOpts
*socket_opts
;
73 char *export_name
; /* An NBD server may export several devices */
76 static int nbd_parse_uri(const char *filename
, QDict
*options
)
80 QueryParams
*qp
= NULL
;
84 uri
= uri_parse(filename
);
90 if (!strcmp(uri
->scheme
, "nbd")) {
92 } else if (!strcmp(uri
->scheme
, "nbd+tcp")) {
94 } else if (!strcmp(uri
->scheme
, "nbd+unix")) {
101 p
= uri
->path
? uri
->path
: "/";
104 qdict_put(options
, "export", qstring_from_str(p
));
107 qp
= query_params_parse(uri
->query
);
108 if (qp
->n
> 1 || (is_unix
&& !qp
->n
) || (!is_unix
&& qp
->n
)) {
114 /* nbd+unix:///export?socket=path */
115 if (uri
->server
|| uri
->port
|| strcmp(qp
->p
[0].name
, "socket")) {
119 qdict_put(options
, "path", qstring_from_str(qp
->p
[0].value
));
122 /* nbd[+tcp]://host[:port]/export */
128 /* strip braces from literal IPv6 address */
129 if (uri
->server
[0] == '[') {
130 host
= qstring_from_substr(uri
->server
, 1,
131 strlen(uri
->server
) - 2);
133 host
= qstring_from_str(uri
->server
);
136 qdict_put(options
, "host", host
);
138 char* port_str
= g_strdup_printf("%d", uri
->port
);
139 qdict_put(options
, "port", qstring_from_str(port_str
));
146 query_params_free(qp
);
152 static void nbd_parse_filename(const char *filename
, QDict
*options
,
157 const char *host_spec
;
158 const char *unixpath
;
160 if (qdict_haskey(options
, "host")
161 || qdict_haskey(options
, "port")
162 || qdict_haskey(options
, "path"))
164 error_setg(errp
, "host/port/path and a file name may not be specified "
169 if (strstr(filename
, "://")) {
170 int ret
= nbd_parse_uri(filename
, options
);
172 error_setg(errp
, "No valid URL specified");
177 file
= g_strdup(filename
);
179 export_name
= strstr(file
, EN_OPTSTR
);
181 if (export_name
[strlen(EN_OPTSTR
)] == 0) {
184 export_name
[0] = 0; /* truncate 'file' */
185 export_name
+= strlen(EN_OPTSTR
);
187 qdict_put(options
, "export", qstring_from_str(export_name
));
190 /* extract the host_spec - fail if it's not nbd:... */
191 if (!strstart(file
, "nbd:", &host_spec
)) {
192 error_setg(errp
, "File name string for NBD must start with 'nbd:'");
200 /* are we a UNIX or TCP socket? */
201 if (strstart(host_spec
, "unix:", &unixpath
)) {
202 qdict_put(options
, "path", qstring_from_str(unixpath
));
204 InetSocketAddress
*addr
= NULL
;
206 addr
= inet_parse(host_spec
, errp
);
207 if (error_is_set(errp
)) {
211 qdict_put(options
, "host", qstring_from_str(addr
->host
));
212 qdict_put(options
, "port", qstring_from_str(addr
->port
));
213 qapi_free_InetSocketAddress(addr
);
220 static int nbd_config(BDRVNBDState
*s
, QDict
*options
)
222 Error
*local_err
= NULL
;
224 if (qdict_haskey(options
, "path")) {
225 if (qdict_haskey(options
, "host")) {
226 qerror_report(ERROR_CLASS_GENERIC_ERROR
, "path and host may not "
227 "be used at the same time.");
231 } else if (qdict_haskey(options
, "host")) {
237 s
->socket_opts
= qemu_opts_create_nofail(&socket_optslist
);
239 qemu_opts_absorb_qdict(s
->socket_opts
, options
, &local_err
);
240 if (error_is_set(&local_err
)) {
241 qerror_report_err(local_err
);
242 error_free(local_err
);
246 if (!qemu_opt_get(s
->socket_opts
, "port")) {
247 qemu_opt_set_number(s
->socket_opts
, "port", NBD_DEFAULT_PORT
);
250 s
->export_name
= g_strdup(qdict_get_try_str(options
, "export"));
251 if (s
->export_name
) {
252 qdict_del(options
, "export");
259 static void nbd_coroutine_start(BDRVNBDState
*s
, struct nbd_request
*request
)
263 /* Poor man semaphore. The free_sema is locked when no other request
264 * can be accepted, and unlocked after receiving one reply. */
265 if (s
->in_flight
>= MAX_NBD_REQUESTS
- 1) {
266 qemu_co_mutex_lock(&s
->free_sema
);
267 assert(s
->in_flight
< MAX_NBD_REQUESTS
);
271 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
272 if (s
->recv_coroutine
[i
] == NULL
) {
273 s
->recv_coroutine
[i
] = qemu_coroutine_self();
278 assert(i
< MAX_NBD_REQUESTS
);
279 request
->handle
= INDEX_TO_HANDLE(s
, i
);
282 static void nbd_reply_ready(void *opaque
)
284 BDRVNBDState
*s
= opaque
;
288 if (s
->reply
.handle
== 0) {
289 /* No reply already in flight. Fetch a header. It is possible
290 * that another thread has done the same thing in parallel, so
291 * the socket is not readable anymore.
293 ret
= nbd_receive_reply(s
->sock
, &s
->reply
);
294 if (ret
== -EAGAIN
) {
303 /* There's no need for a mutex on the receive side, because the
304 * handler acts as a synchronization point and ensures that only
305 * one coroutine is called until the reply finishes. */
306 i
= HANDLE_TO_INDEX(s
, s
->reply
.handle
);
307 if (i
>= MAX_NBD_REQUESTS
) {
311 if (s
->recv_coroutine
[i
]) {
312 qemu_coroutine_enter(s
->recv_coroutine
[i
], NULL
);
317 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
318 if (s
->recv_coroutine
[i
]) {
319 qemu_coroutine_enter(s
->recv_coroutine
[i
], NULL
);
324 static void nbd_restart_write(void *opaque
)
326 BDRVNBDState
*s
= opaque
;
327 qemu_coroutine_enter(s
->send_coroutine
, NULL
);
330 static int nbd_co_send_request(BDRVNBDState
*s
, struct nbd_request
*request
,
331 QEMUIOVector
*qiov
, int offset
)
335 qemu_co_mutex_lock(&s
->send_mutex
);
336 s
->send_coroutine
= qemu_coroutine_self();
337 qemu_aio_set_fd_handler(s
->sock
, nbd_reply_ready
, nbd_restart_write
, s
);
340 socket_set_cork(s
->sock
, 1);
342 rc
= nbd_send_request(s
->sock
, request
);
344 ret
= qemu_co_sendv(s
->sock
, qiov
->iov
, qiov
->niov
,
345 offset
, request
->len
);
346 if (ret
!= request
->len
) {
351 socket_set_cork(s
->sock
, 0);
354 rc
= nbd_send_request(s
->sock
, request
);
356 qemu_aio_set_fd_handler(s
->sock
, nbd_reply_ready
, NULL
, s
);
357 s
->send_coroutine
= NULL
;
358 qemu_co_mutex_unlock(&s
->send_mutex
);
362 static void nbd_co_receive_reply(BDRVNBDState
*s
, struct nbd_request
*request
,
363 struct nbd_reply
*reply
,
364 QEMUIOVector
*qiov
, int offset
)
368 /* Wait until we're woken up by the read handler. TODO: perhaps
369 * peek at the next reply and avoid yielding if it's ours? */
370 qemu_coroutine_yield();
372 if (reply
->handle
!= request
->handle
) {
375 if (qiov
&& reply
->error
== 0) {
376 ret
= qemu_co_recvv(s
->sock
, qiov
->iov
, qiov
->niov
,
377 offset
, request
->len
);
378 if (ret
!= request
->len
) {
383 /* Tell the read handler to read another header. */
388 static void nbd_coroutine_end(BDRVNBDState
*s
, struct nbd_request
*request
)
390 int i
= HANDLE_TO_INDEX(s
, request
->handle
);
391 s
->recv_coroutine
[i
] = NULL
;
392 if (s
->in_flight
-- == MAX_NBD_REQUESTS
) {
393 qemu_co_mutex_unlock(&s
->free_sema
);
397 static int nbd_establish_connection(BlockDriverState
*bs
)
399 BDRVNBDState
*s
= bs
->opaque
;
406 sock
= unix_socket_outgoing(qemu_opt_get(s
->socket_opts
, "path"));
408 sock
= tcp_socket_outgoing_opts(s
->socket_opts
);
410 socket_set_nodelay(sock
);
414 /* Failed to establish connection */
416 logout("Failed to establish connection to NBD server\n");
421 ret
= nbd_receive_negotiate(sock
, s
->export_name
, &s
->nbdflags
, &size
,
424 logout("Failed to negotiate with the NBD server\n");
429 /* Now that we're connected, set the socket to be non-blocking and
430 * kick the reply mechanism. */
431 qemu_set_nonblock(sock
);
432 qemu_aio_set_fd_handler(sock
, nbd_reply_ready
, NULL
, s
);
436 s
->blocksize
= blocksize
;
438 logout("Established connection with NBD server\n");
442 static void nbd_teardown_connection(BlockDriverState
*bs
)
444 BDRVNBDState
*s
= bs
->opaque
;
445 struct nbd_request request
;
447 request
.type
= NBD_CMD_DISC
;
450 nbd_send_request(s
->sock
, &request
);
452 qemu_aio_set_fd_handler(s
->sock
, NULL
, NULL
, NULL
);
453 closesocket(s
->sock
);
456 static int nbd_open(BlockDriverState
*bs
, QDict
*options
, int flags
)
458 BDRVNBDState
*s
= bs
->opaque
;
461 qemu_co_mutex_init(&s
->send_mutex
);
462 qemu_co_mutex_init(&s
->free_sema
);
464 /* Pop the config into our state object. Exit if invalid. */
465 result
= nbd_config(s
, options
);
470 /* establish TCP connection, return error if it fails
471 * TODO: Configurable retry-until-timeout behaviour.
473 result
= nbd_establish_connection(bs
);
478 static int nbd_co_readv_1(BlockDriverState
*bs
, int64_t sector_num
,
479 int nb_sectors
, QEMUIOVector
*qiov
,
482 BDRVNBDState
*s
= bs
->opaque
;
483 struct nbd_request request
;
484 struct nbd_reply reply
;
487 request
.type
= NBD_CMD_READ
;
488 request
.from
= sector_num
* 512;
489 request
.len
= nb_sectors
* 512;
491 nbd_coroutine_start(s
, &request
);
492 ret
= nbd_co_send_request(s
, &request
, NULL
, 0);
496 nbd_co_receive_reply(s
, &request
, &reply
, qiov
, offset
);
498 nbd_coroutine_end(s
, &request
);
503 static int nbd_co_writev_1(BlockDriverState
*bs
, int64_t sector_num
,
504 int nb_sectors
, QEMUIOVector
*qiov
,
507 BDRVNBDState
*s
= bs
->opaque
;
508 struct nbd_request request
;
509 struct nbd_reply reply
;
512 request
.type
= NBD_CMD_WRITE
;
513 if (!bdrv_enable_write_cache(bs
) && (s
->nbdflags
& NBD_FLAG_SEND_FUA
)) {
514 request
.type
|= NBD_CMD_FLAG_FUA
;
517 request
.from
= sector_num
* 512;
518 request
.len
= nb_sectors
* 512;
520 nbd_coroutine_start(s
, &request
);
521 ret
= nbd_co_send_request(s
, &request
, qiov
, offset
);
525 nbd_co_receive_reply(s
, &request
, &reply
, NULL
, 0);
527 nbd_coroutine_end(s
, &request
);
531 /* qemu-nbd has a limit of slightly less than 1M per request. Try to
532 * remain aligned to 4K. */
533 #define NBD_MAX_SECTORS 2040
535 static int nbd_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
536 int nb_sectors
, QEMUIOVector
*qiov
)
540 while (nb_sectors
> NBD_MAX_SECTORS
) {
541 ret
= nbd_co_readv_1(bs
, sector_num
, NBD_MAX_SECTORS
, qiov
, offset
);
545 offset
+= NBD_MAX_SECTORS
* 512;
546 sector_num
+= NBD_MAX_SECTORS
;
547 nb_sectors
-= NBD_MAX_SECTORS
;
549 return nbd_co_readv_1(bs
, sector_num
, nb_sectors
, qiov
, offset
);
552 static int nbd_co_writev(BlockDriverState
*bs
, int64_t sector_num
,
553 int nb_sectors
, QEMUIOVector
*qiov
)
557 while (nb_sectors
> NBD_MAX_SECTORS
) {
558 ret
= nbd_co_writev_1(bs
, sector_num
, NBD_MAX_SECTORS
, qiov
, offset
);
562 offset
+= NBD_MAX_SECTORS
* 512;
563 sector_num
+= NBD_MAX_SECTORS
;
564 nb_sectors
-= NBD_MAX_SECTORS
;
566 return nbd_co_writev_1(bs
, sector_num
, nb_sectors
, qiov
, offset
);
569 static int nbd_co_flush(BlockDriverState
*bs
)
571 BDRVNBDState
*s
= bs
->opaque
;
572 struct nbd_request request
;
573 struct nbd_reply reply
;
576 if (!(s
->nbdflags
& NBD_FLAG_SEND_FLUSH
)) {
580 request
.type
= NBD_CMD_FLUSH
;
581 if (s
->nbdflags
& NBD_FLAG_SEND_FUA
) {
582 request
.type
|= NBD_CMD_FLAG_FUA
;
588 nbd_coroutine_start(s
, &request
);
589 ret
= nbd_co_send_request(s
, &request
, NULL
, 0);
593 nbd_co_receive_reply(s
, &request
, &reply
, NULL
, 0);
595 nbd_coroutine_end(s
, &request
);
599 static int nbd_co_discard(BlockDriverState
*bs
, int64_t sector_num
,
602 BDRVNBDState
*s
= bs
->opaque
;
603 struct nbd_request request
;
604 struct nbd_reply reply
;
607 if (!(s
->nbdflags
& NBD_FLAG_SEND_TRIM
)) {
610 request
.type
= NBD_CMD_TRIM
;
611 request
.from
= sector_num
* 512;
612 request
.len
= nb_sectors
* 512;
614 nbd_coroutine_start(s
, &request
);
615 ret
= nbd_co_send_request(s
, &request
, NULL
, 0);
619 nbd_co_receive_reply(s
, &request
, &reply
, NULL
, 0);
621 nbd_coroutine_end(s
, &request
);
625 static void nbd_close(BlockDriverState
*bs
)
627 BDRVNBDState
*s
= bs
->opaque
;
628 g_free(s
->export_name
);
629 qemu_opts_del(s
->socket_opts
);
631 nbd_teardown_connection(bs
);
634 static int64_t nbd_getlength(BlockDriverState
*bs
)
636 BDRVNBDState
*s
= bs
->opaque
;
641 static BlockDriver bdrv_nbd
= {
642 .format_name
= "nbd",
643 .protocol_name
= "nbd",
644 .instance_size
= sizeof(BDRVNBDState
),
645 .bdrv_parse_filename
= nbd_parse_filename
,
646 .bdrv_file_open
= nbd_open
,
647 .bdrv_co_readv
= nbd_co_readv
,
648 .bdrv_co_writev
= nbd_co_writev
,
649 .bdrv_close
= nbd_close
,
650 .bdrv_co_flush_to_os
= nbd_co_flush
,
651 .bdrv_co_discard
= nbd_co_discard
,
652 .bdrv_getlength
= nbd_getlength
,
655 static BlockDriver bdrv_nbd_tcp
= {
656 .format_name
= "nbd",
657 .protocol_name
= "nbd+tcp",
658 .instance_size
= sizeof(BDRVNBDState
),
659 .bdrv_parse_filename
= nbd_parse_filename
,
660 .bdrv_file_open
= nbd_open
,
661 .bdrv_co_readv
= nbd_co_readv
,
662 .bdrv_co_writev
= nbd_co_writev
,
663 .bdrv_close
= nbd_close
,
664 .bdrv_co_flush_to_os
= nbd_co_flush
,
665 .bdrv_co_discard
= nbd_co_discard
,
666 .bdrv_getlength
= nbd_getlength
,
669 static BlockDriver bdrv_nbd_unix
= {
670 .format_name
= "nbd",
671 .protocol_name
= "nbd+unix",
672 .instance_size
= sizeof(BDRVNBDState
),
673 .bdrv_parse_filename
= nbd_parse_filename
,
674 .bdrv_file_open
= nbd_open
,
675 .bdrv_co_readv
= nbd_co_readv
,
676 .bdrv_co_writev
= nbd_co_writev
,
677 .bdrv_close
= nbd_close
,
678 .bdrv_co_flush_to_os
= nbd_co_flush
,
679 .bdrv_co_discard
= nbd_co_discard
,
680 .bdrv_getlength
= nbd_getlength
,
683 static void bdrv_nbd_init(void)
685 bdrv_register(&bdrv_nbd
);
686 bdrv_register(&bdrv_nbd_tcp
);
687 bdrv_register(&bdrv_nbd_unix
);
690 block_init(bdrv_nbd_init
);