help: Fix markup of heading "USB options" so it appears in -help
[qemu/pbrook.git] / block / nbd.c
bloba5812948d2bea77c807d9756750e81de6321f02f
1 /*
2 * QEMU Block driver for NBD
4 * Copyright (C) 2008 Bull S.A.S.
5 * Author: Laurent Vivier <Laurent.Vivier@bull.net>
7 * Some parts:
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
26 * THE SOFTWARE.
29 #include "qemu-common.h"
30 #include "block/nbd.h"
31 #include "qemu/uri.h"
32 #include "block/block_int.h"
33 #include "qemu/module.h"
34 #include "qemu/sockets.h"
36 #include <sys/types.h>
37 #include <unistd.h>
39 #define EN_OPTSTR ":exportname="
41 /* #define DEBUG_NBD */
43 #if defined(DEBUG_NBD)
44 #define logout(fmt, ...) \
45 fprintf(stderr, "nbd\t%-24s" fmt, __func__, ##__VA_ARGS__)
46 #else
47 #define logout(fmt, ...) ((void)0)
48 #endif
50 #define MAX_NBD_REQUESTS 16
51 #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ ((uint64_t)(intptr_t)bs))
52 #define INDEX_TO_HANDLE(bs, index) ((index) ^ ((uint64_t)(intptr_t)bs))
54 typedef struct BDRVNBDState {
55 int sock;
56 uint32_t nbdflags;
57 off_t size;
58 size_t blocksize;
60 CoMutex send_mutex;
61 CoMutex free_sema;
62 Coroutine *send_coroutine;
63 int in_flight;
65 Coroutine *recv_coroutine[MAX_NBD_REQUESTS];
66 struct nbd_reply reply;
68 int is_unix;
69 char *host_spec;
70 char *export_name; /* An NBD server may export several devices */
71 } BDRVNBDState;
73 static int nbd_parse_uri(BDRVNBDState *s, const char *filename)
75 URI *uri;
76 const char *p;
77 QueryParams *qp = NULL;
78 int ret = 0;
80 uri = uri_parse(filename);
81 if (!uri) {
82 return -EINVAL;
85 /* transport */
86 if (!strcmp(uri->scheme, "nbd")) {
87 s->is_unix = false;
88 } else if (!strcmp(uri->scheme, "nbd+tcp")) {
89 s->is_unix = false;
90 } else if (!strcmp(uri->scheme, "nbd+unix")) {
91 s->is_unix = true;
92 } else {
93 ret = -EINVAL;
94 goto out;
97 p = uri->path ? uri->path : "/";
98 p += strspn(p, "/");
99 if (p[0]) {
100 s->export_name = g_strdup(p);
103 qp = query_params_parse(uri->query);
104 if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {
105 ret = -EINVAL;
106 goto out;
109 if (s->is_unix) {
110 /* nbd+unix:///export?socket=path */
111 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
112 ret = -EINVAL;
113 goto out;
115 s->host_spec = g_strdup(qp->p[0].value);
116 } else {
117 /* nbd[+tcp]://host:port/export */
118 if (!uri->server) {
119 ret = -EINVAL;
120 goto out;
122 if (!uri->port) {
123 uri->port = NBD_DEFAULT_PORT;
125 s->host_spec = g_strdup_printf("%s:%d", uri->server, uri->port);
128 out:
129 if (qp) {
130 query_params_free(qp);
132 uri_free(uri);
133 return ret;
136 static int nbd_config(BDRVNBDState *s, const char *filename)
138 char *file;
139 char *export_name;
140 const char *host_spec;
141 const char *unixpath;
142 int err = -EINVAL;
144 if (strstr(filename, "://")) {
145 return nbd_parse_uri(s, filename);
148 file = g_strdup(filename);
150 export_name = strstr(file, EN_OPTSTR);
151 if (export_name) {
152 if (export_name[strlen(EN_OPTSTR)] == 0) {
153 goto out;
155 export_name[0] = 0; /* truncate 'file' */
156 export_name += strlen(EN_OPTSTR);
157 s->export_name = g_strdup(export_name);
160 /* extract the host_spec - fail if it's not nbd:... */
161 if (!strstart(file, "nbd:", &host_spec)) {
162 goto out;
165 /* are we a UNIX or TCP socket? */
166 if (strstart(host_spec, "unix:", &unixpath)) {
167 s->is_unix = true;
168 s->host_spec = g_strdup(unixpath);
169 } else {
170 s->is_unix = false;
171 s->host_spec = g_strdup(host_spec);
174 err = 0;
176 out:
177 g_free(file);
178 if (err != 0) {
179 g_free(s->export_name);
180 g_free(s->host_spec);
182 return err;
185 static void nbd_coroutine_start(BDRVNBDState *s, struct nbd_request *request)
187 int i;
189 /* Poor man semaphore. The free_sema is locked when no other request
190 * can be accepted, and unlocked after receiving one reply. */
191 if (s->in_flight >= MAX_NBD_REQUESTS - 1) {
192 qemu_co_mutex_lock(&s->free_sema);
193 assert(s->in_flight < MAX_NBD_REQUESTS);
195 s->in_flight++;
197 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
198 if (s->recv_coroutine[i] == NULL) {
199 s->recv_coroutine[i] = qemu_coroutine_self();
200 break;
204 assert(i < MAX_NBD_REQUESTS);
205 request->handle = INDEX_TO_HANDLE(s, i);
208 static int nbd_have_request(void *opaque)
210 BDRVNBDState *s = opaque;
212 return s->in_flight > 0;
215 static void nbd_reply_ready(void *opaque)
217 BDRVNBDState *s = opaque;
218 uint64_t i;
219 int ret;
221 if (s->reply.handle == 0) {
222 /* No reply already in flight. Fetch a header. It is possible
223 * that another thread has done the same thing in parallel, so
224 * the socket is not readable anymore.
226 ret = nbd_receive_reply(s->sock, &s->reply);
227 if (ret == -EAGAIN) {
228 return;
230 if (ret < 0) {
231 s->reply.handle = 0;
232 goto fail;
236 /* There's no need for a mutex on the receive side, because the
237 * handler acts as a synchronization point and ensures that only
238 * one coroutine is called until the reply finishes. */
239 i = HANDLE_TO_INDEX(s, s->reply.handle);
240 if (i >= MAX_NBD_REQUESTS) {
241 goto fail;
244 if (s->recv_coroutine[i]) {
245 qemu_coroutine_enter(s->recv_coroutine[i], NULL);
246 return;
249 fail:
250 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
251 if (s->recv_coroutine[i]) {
252 qemu_coroutine_enter(s->recv_coroutine[i], NULL);
257 static void nbd_restart_write(void *opaque)
259 BDRVNBDState *s = opaque;
260 qemu_coroutine_enter(s->send_coroutine, NULL);
263 static int nbd_co_send_request(BDRVNBDState *s, struct nbd_request *request,
264 QEMUIOVector *qiov, int offset)
266 int rc, ret;
268 qemu_co_mutex_lock(&s->send_mutex);
269 s->send_coroutine = qemu_coroutine_self();
270 qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, nbd_restart_write,
271 nbd_have_request, s);
272 rc = nbd_send_request(s->sock, request);
273 if (rc >= 0 && qiov) {
274 ret = qemu_co_sendv(s->sock, qiov->iov, qiov->niov,
275 offset, request->len);
276 if (ret != request->len) {
277 return -EIO;
280 qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, NULL,
281 nbd_have_request, s);
282 s->send_coroutine = NULL;
283 qemu_co_mutex_unlock(&s->send_mutex);
284 return rc;
287 static void nbd_co_receive_reply(BDRVNBDState *s, struct nbd_request *request,
288 struct nbd_reply *reply,
289 QEMUIOVector *qiov, int offset)
291 int ret;
293 /* Wait until we're woken up by the read handler. TODO: perhaps
294 * peek at the next reply and avoid yielding if it's ours? */
295 qemu_coroutine_yield();
296 *reply = s->reply;
297 if (reply->handle != request->handle) {
298 reply->error = EIO;
299 } else {
300 if (qiov && reply->error == 0) {
301 ret = qemu_co_recvv(s->sock, qiov->iov, qiov->niov,
302 offset, request->len);
303 if (ret != request->len) {
304 reply->error = EIO;
308 /* Tell the read handler to read another header. */
309 s->reply.handle = 0;
313 static void nbd_coroutine_end(BDRVNBDState *s, struct nbd_request *request)
315 int i = HANDLE_TO_INDEX(s, request->handle);
316 s->recv_coroutine[i] = NULL;
317 if (s->in_flight-- == MAX_NBD_REQUESTS) {
318 qemu_co_mutex_unlock(&s->free_sema);
322 static int nbd_establish_connection(BlockDriverState *bs)
324 BDRVNBDState *s = bs->opaque;
325 int sock;
326 int ret;
327 off_t size;
328 size_t blocksize;
330 if (s->is_unix) {
331 sock = unix_socket_outgoing(s->host_spec);
332 } else {
333 sock = tcp_socket_outgoing_spec(s->host_spec);
336 /* Failed to establish connection */
337 if (sock < 0) {
338 logout("Failed to establish connection to NBD server\n");
339 return -errno;
342 /* NBD handshake */
343 ret = nbd_receive_negotiate(sock, s->export_name, &s->nbdflags, &size,
344 &blocksize);
345 if (ret < 0) {
346 logout("Failed to negotiate with the NBD server\n");
347 closesocket(sock);
348 return ret;
351 /* Now that we're connected, set the socket to be non-blocking and
352 * kick the reply mechanism. */
353 socket_set_nonblock(sock);
354 qemu_aio_set_fd_handler(sock, nbd_reply_ready, NULL,
355 nbd_have_request, s);
357 s->sock = sock;
358 s->size = size;
359 s->blocksize = blocksize;
361 logout("Established connection with NBD server\n");
362 return 0;
365 static void nbd_teardown_connection(BlockDriverState *bs)
367 BDRVNBDState *s = bs->opaque;
368 struct nbd_request request;
370 request.type = NBD_CMD_DISC;
371 request.from = 0;
372 request.len = 0;
373 nbd_send_request(s->sock, &request);
375 qemu_aio_set_fd_handler(s->sock, NULL, NULL, NULL, NULL);
376 closesocket(s->sock);
379 static int nbd_open(BlockDriverState *bs, const char* filename, int flags)
381 BDRVNBDState *s = bs->opaque;
382 int result;
384 qemu_co_mutex_init(&s->send_mutex);
385 qemu_co_mutex_init(&s->free_sema);
387 /* Pop the config into our state object. Exit if invalid. */
388 result = nbd_config(s, filename);
389 if (result != 0) {
390 return result;
393 /* establish TCP connection, return error if it fails
394 * TODO: Configurable retry-until-timeout behaviour.
396 result = nbd_establish_connection(bs);
398 return result;
401 static int nbd_co_readv_1(BlockDriverState *bs, int64_t sector_num,
402 int nb_sectors, QEMUIOVector *qiov,
403 int offset)
405 BDRVNBDState *s = bs->opaque;
406 struct nbd_request request;
407 struct nbd_reply reply;
408 ssize_t ret;
410 request.type = NBD_CMD_READ;
411 request.from = sector_num * 512;
412 request.len = nb_sectors * 512;
414 nbd_coroutine_start(s, &request);
415 ret = nbd_co_send_request(s, &request, NULL, 0);
416 if (ret < 0) {
417 reply.error = -ret;
418 } else {
419 nbd_co_receive_reply(s, &request, &reply, qiov, offset);
421 nbd_coroutine_end(s, &request);
422 return -reply.error;
426 static int nbd_co_writev_1(BlockDriverState *bs, int64_t sector_num,
427 int nb_sectors, QEMUIOVector *qiov,
428 int offset)
430 BDRVNBDState *s = bs->opaque;
431 struct nbd_request request;
432 struct nbd_reply reply;
433 ssize_t ret;
435 request.type = NBD_CMD_WRITE;
436 if (!bdrv_enable_write_cache(bs) && (s->nbdflags & NBD_FLAG_SEND_FUA)) {
437 request.type |= NBD_CMD_FLAG_FUA;
440 request.from = sector_num * 512;
441 request.len = nb_sectors * 512;
443 nbd_coroutine_start(s, &request);
444 ret = nbd_co_send_request(s, &request, qiov, offset);
445 if (ret < 0) {
446 reply.error = -ret;
447 } else {
448 nbd_co_receive_reply(s, &request, &reply, NULL, 0);
450 nbd_coroutine_end(s, &request);
451 return -reply.error;
454 /* qemu-nbd has a limit of slightly less than 1M per request. Try to
455 * remain aligned to 4K. */
456 #define NBD_MAX_SECTORS 2040
458 static int nbd_co_readv(BlockDriverState *bs, int64_t sector_num,
459 int nb_sectors, QEMUIOVector *qiov)
461 int offset = 0;
462 int ret;
463 while (nb_sectors > NBD_MAX_SECTORS) {
464 ret = nbd_co_readv_1(bs, sector_num, NBD_MAX_SECTORS, qiov, offset);
465 if (ret < 0) {
466 return ret;
468 offset += NBD_MAX_SECTORS * 512;
469 sector_num += NBD_MAX_SECTORS;
470 nb_sectors -= NBD_MAX_SECTORS;
472 return nbd_co_readv_1(bs, sector_num, nb_sectors, qiov, offset);
475 static int nbd_co_writev(BlockDriverState *bs, int64_t sector_num,
476 int nb_sectors, QEMUIOVector *qiov)
478 int offset = 0;
479 int ret;
480 while (nb_sectors > NBD_MAX_SECTORS) {
481 ret = nbd_co_writev_1(bs, sector_num, NBD_MAX_SECTORS, qiov, offset);
482 if (ret < 0) {
483 return ret;
485 offset += NBD_MAX_SECTORS * 512;
486 sector_num += NBD_MAX_SECTORS;
487 nb_sectors -= NBD_MAX_SECTORS;
489 return nbd_co_writev_1(bs, sector_num, nb_sectors, qiov, offset);
492 static int nbd_co_flush(BlockDriverState *bs)
494 BDRVNBDState *s = bs->opaque;
495 struct nbd_request request;
496 struct nbd_reply reply;
497 ssize_t ret;
499 if (!(s->nbdflags & NBD_FLAG_SEND_FLUSH)) {
500 return 0;
503 request.type = NBD_CMD_FLUSH;
504 if (s->nbdflags & NBD_FLAG_SEND_FUA) {
505 request.type |= NBD_CMD_FLAG_FUA;
508 request.from = 0;
509 request.len = 0;
511 nbd_coroutine_start(s, &request);
512 ret = nbd_co_send_request(s, &request, NULL, 0);
513 if (ret < 0) {
514 reply.error = -ret;
515 } else {
516 nbd_co_receive_reply(s, &request, &reply, NULL, 0);
518 nbd_coroutine_end(s, &request);
519 return -reply.error;
522 static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,
523 int nb_sectors)
525 BDRVNBDState *s = bs->opaque;
526 struct nbd_request request;
527 struct nbd_reply reply;
528 ssize_t ret;
530 if (!(s->nbdflags & NBD_FLAG_SEND_TRIM)) {
531 return 0;
533 request.type = NBD_CMD_TRIM;
534 request.from = sector_num * 512;;
535 request.len = nb_sectors * 512;
537 nbd_coroutine_start(s, &request);
538 ret = nbd_co_send_request(s, &request, NULL, 0);
539 if (ret < 0) {
540 reply.error = -ret;
541 } else {
542 nbd_co_receive_reply(s, &request, &reply, NULL, 0);
544 nbd_coroutine_end(s, &request);
545 return -reply.error;
548 static void nbd_close(BlockDriverState *bs)
550 BDRVNBDState *s = bs->opaque;
551 g_free(s->export_name);
552 g_free(s->host_spec);
554 nbd_teardown_connection(bs);
557 static int64_t nbd_getlength(BlockDriverState *bs)
559 BDRVNBDState *s = bs->opaque;
561 return s->size;
564 static BlockDriver bdrv_nbd = {
565 .format_name = "nbd",
566 .protocol_name = "nbd",
567 .instance_size = sizeof(BDRVNBDState),
568 .bdrv_file_open = nbd_open,
569 .bdrv_co_readv = nbd_co_readv,
570 .bdrv_co_writev = nbd_co_writev,
571 .bdrv_close = nbd_close,
572 .bdrv_co_flush_to_os = nbd_co_flush,
573 .bdrv_co_discard = nbd_co_discard,
574 .bdrv_getlength = nbd_getlength,
577 static BlockDriver bdrv_nbd_tcp = {
578 .format_name = "nbd",
579 .protocol_name = "nbd+tcp",
580 .instance_size = sizeof(BDRVNBDState),
581 .bdrv_file_open = nbd_open,
582 .bdrv_co_readv = nbd_co_readv,
583 .bdrv_co_writev = nbd_co_writev,
584 .bdrv_close = nbd_close,
585 .bdrv_co_flush_to_os = nbd_co_flush,
586 .bdrv_co_discard = nbd_co_discard,
587 .bdrv_getlength = nbd_getlength,
590 static BlockDriver bdrv_nbd_unix = {
591 .format_name = "nbd",
592 .protocol_name = "nbd+unix",
593 .instance_size = sizeof(BDRVNBDState),
594 .bdrv_file_open = nbd_open,
595 .bdrv_co_readv = nbd_co_readv,
596 .bdrv_co_writev = nbd_co_writev,
597 .bdrv_close = nbd_close,
598 .bdrv_co_flush_to_os = nbd_co_flush,
599 .bdrv_co_discard = nbd_co_discard,
600 .bdrv_getlength = nbd_getlength,
603 static void bdrv_nbd_init(void)
605 bdrv_register(&bdrv_nbd);
606 bdrv_register(&bdrv_nbd_tcp);
607 bdrv_register(&bdrv_nbd_unix);
610 block_init(bdrv_nbd_init);