]> git.proxmox.com Git - qemu.git/blob - block/nbd.c
nbd: Keep hostname and port separate
[qemu.git] / block / nbd.c
1 /*
2 * QEMU Block driver for NBD
3 *
4 * Copyright (C) 2008 Bull S.A.S.
5 * Author: Laurent Vivier <Laurent.Vivier@bull.net>
6 *
7 * Some parts:
8 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
9 *
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:
16 *
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
19 *
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.
27 */
28
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"
35
36 #include <sys/types.h>
37 #include <unistd.h>
38
39 #define EN_OPTSTR ":exportname="
40
41 /* #define DEBUG_NBD */
42
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
49
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))
53
54 typedef struct BDRVNBDState {
55 int sock;
56 uint32_t nbdflags;
57 off_t size;
58 size_t blocksize;
59
60 CoMutex send_mutex;
61 CoMutex free_sema;
62 Coroutine *send_coroutine;
63 int in_flight;
64
65 Coroutine *recv_coroutine[MAX_NBD_REQUESTS];
66 struct nbd_reply reply;
67
68 int is_unix;
69 char *unix_path;
70
71 InetSocketAddress *inet_addr;
72
73 char *export_name; /* An NBD server may export several devices */
74 } BDRVNBDState;
75
76 static int nbd_parse_uri(BDRVNBDState *s, const char *filename)
77 {
78 URI *uri;
79 const char *p;
80 QueryParams *qp = NULL;
81 int ret = 0;
82
83 uri = uri_parse(filename);
84 if (!uri) {
85 return -EINVAL;
86 }
87
88 /* transport */
89 if (!strcmp(uri->scheme, "nbd")) {
90 s->is_unix = false;
91 } else if (!strcmp(uri->scheme, "nbd+tcp")) {
92 s->is_unix = false;
93 } else if (!strcmp(uri->scheme, "nbd+unix")) {
94 s->is_unix = true;
95 } else {
96 ret = -EINVAL;
97 goto out;
98 }
99
100 p = uri->path ? uri->path : "/";
101 p += strspn(p, "/");
102 if (p[0]) {
103 s->export_name = g_strdup(p);
104 }
105
106 qp = query_params_parse(uri->query);
107 if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {
108 ret = -EINVAL;
109 goto out;
110 }
111
112 if (s->is_unix) {
113 /* nbd+unix:///export?socket=path */
114 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
115 ret = -EINVAL;
116 goto out;
117 }
118 s->unix_path = g_strdup(qp->p[0].value);
119 } else {
120 /* nbd[+tcp]://host:port/export */
121 if (!uri->server) {
122 ret = -EINVAL;
123 goto out;
124 }
125 if (!uri->port) {
126 uri->port = NBD_DEFAULT_PORT;
127 }
128
129 s->inet_addr = g_new0(InetSocketAddress, 1);
130 *s->inet_addr = (InetSocketAddress) {
131 .host = g_strdup(uri->server),
132 .port = g_strdup_printf("%d", uri->port),
133 };
134 }
135
136 out:
137 if (qp) {
138 query_params_free(qp);
139 }
140 uri_free(uri);
141 return ret;
142 }
143
144 static int nbd_config(BDRVNBDState *s, const char *filename)
145 {
146 char *file;
147 char *export_name;
148 const char *host_spec;
149 const char *unixpath;
150 int err = -EINVAL;
151 Error *local_err = NULL;
152
153 if (strstr(filename, "://")) {
154 return nbd_parse_uri(s, filename);
155 }
156
157 file = g_strdup(filename);
158
159 export_name = strstr(file, EN_OPTSTR);
160 if (export_name) {
161 if (export_name[strlen(EN_OPTSTR)] == 0) {
162 goto out;
163 }
164 export_name[0] = 0; /* truncate 'file' */
165 export_name += strlen(EN_OPTSTR);
166 s->export_name = g_strdup(export_name);
167 }
168
169 /* extract the host_spec - fail if it's not nbd:... */
170 if (!strstart(file, "nbd:", &host_spec)) {
171 goto out;
172 }
173
174 /* are we a UNIX or TCP socket? */
175 if (strstart(host_spec, "unix:", &unixpath)) {
176 s->is_unix = true;
177 s->unix_path = g_strdup(unixpath);
178 } else {
179 s->is_unix = false;
180 s->inet_addr = inet_parse(host_spec, &local_err);
181 if (local_err != NULL) {
182 qerror_report_err(local_err);
183 error_free(local_err);
184 goto out;
185 }
186 }
187
188 err = 0;
189
190 out:
191 g_free(file);
192 if (err != 0) {
193 g_free(s->export_name);
194 g_free(s->unix_path);
195 qapi_free_InetSocketAddress(s->inet_addr);
196 }
197 return err;
198 }
199
200 static void nbd_coroutine_start(BDRVNBDState *s, struct nbd_request *request)
201 {
202 int i;
203
204 /* Poor man semaphore. The free_sema is locked when no other request
205 * can be accepted, and unlocked after receiving one reply. */
206 if (s->in_flight >= MAX_NBD_REQUESTS - 1) {
207 qemu_co_mutex_lock(&s->free_sema);
208 assert(s->in_flight < MAX_NBD_REQUESTS);
209 }
210 s->in_flight++;
211
212 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
213 if (s->recv_coroutine[i] == NULL) {
214 s->recv_coroutine[i] = qemu_coroutine_self();
215 break;
216 }
217 }
218
219 assert(i < MAX_NBD_REQUESTS);
220 request->handle = INDEX_TO_HANDLE(s, i);
221 }
222
223 static int nbd_have_request(void *opaque)
224 {
225 BDRVNBDState *s = opaque;
226
227 return s->in_flight > 0;
228 }
229
230 static void nbd_reply_ready(void *opaque)
231 {
232 BDRVNBDState *s = opaque;
233 uint64_t i;
234 int ret;
235
236 if (s->reply.handle == 0) {
237 /* No reply already in flight. Fetch a header. It is possible
238 * that another thread has done the same thing in parallel, so
239 * the socket is not readable anymore.
240 */
241 ret = nbd_receive_reply(s->sock, &s->reply);
242 if (ret == -EAGAIN) {
243 return;
244 }
245 if (ret < 0) {
246 s->reply.handle = 0;
247 goto fail;
248 }
249 }
250
251 /* There's no need for a mutex on the receive side, because the
252 * handler acts as a synchronization point and ensures that only
253 * one coroutine is called until the reply finishes. */
254 i = HANDLE_TO_INDEX(s, s->reply.handle);
255 if (i >= MAX_NBD_REQUESTS) {
256 goto fail;
257 }
258
259 if (s->recv_coroutine[i]) {
260 qemu_coroutine_enter(s->recv_coroutine[i], NULL);
261 return;
262 }
263
264 fail:
265 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
266 if (s->recv_coroutine[i]) {
267 qemu_coroutine_enter(s->recv_coroutine[i], NULL);
268 }
269 }
270 }
271
272 static void nbd_restart_write(void *opaque)
273 {
274 BDRVNBDState *s = opaque;
275 qemu_coroutine_enter(s->send_coroutine, NULL);
276 }
277
278 static int nbd_co_send_request(BDRVNBDState *s, struct nbd_request *request,
279 QEMUIOVector *qiov, int offset)
280 {
281 int rc, ret;
282
283 qemu_co_mutex_lock(&s->send_mutex);
284 s->send_coroutine = qemu_coroutine_self();
285 qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, nbd_restart_write,
286 nbd_have_request, s);
287 rc = nbd_send_request(s->sock, request);
288 if (rc >= 0 && qiov) {
289 ret = qemu_co_sendv(s->sock, qiov->iov, qiov->niov,
290 offset, request->len);
291 if (ret != request->len) {
292 return -EIO;
293 }
294 }
295 qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, NULL,
296 nbd_have_request, s);
297 s->send_coroutine = NULL;
298 qemu_co_mutex_unlock(&s->send_mutex);
299 return rc;
300 }
301
302 static void nbd_co_receive_reply(BDRVNBDState *s, struct nbd_request *request,
303 struct nbd_reply *reply,
304 QEMUIOVector *qiov, int offset)
305 {
306 int ret;
307
308 /* Wait until we're woken up by the read handler. TODO: perhaps
309 * peek at the next reply and avoid yielding if it's ours? */
310 qemu_coroutine_yield();
311 *reply = s->reply;
312 if (reply->handle != request->handle) {
313 reply->error = EIO;
314 } else {
315 if (qiov && reply->error == 0) {
316 ret = qemu_co_recvv(s->sock, qiov->iov, qiov->niov,
317 offset, request->len);
318 if (ret != request->len) {
319 reply->error = EIO;
320 }
321 }
322
323 /* Tell the read handler to read another header. */
324 s->reply.handle = 0;
325 }
326 }
327
328 static void nbd_coroutine_end(BDRVNBDState *s, struct nbd_request *request)
329 {
330 int i = HANDLE_TO_INDEX(s, request->handle);
331 s->recv_coroutine[i] = NULL;
332 if (s->in_flight-- == MAX_NBD_REQUESTS) {
333 qemu_co_mutex_unlock(&s->free_sema);
334 }
335 }
336
337 static int nbd_establish_connection(BlockDriverState *bs)
338 {
339 BDRVNBDState *s = bs->opaque;
340 int sock;
341 int ret;
342 off_t size;
343 size_t blocksize;
344
345 if (s->is_unix) {
346 sock = unix_socket_outgoing(s->unix_path);
347 } else {
348 QemuOpts *opts = qemu_opts_create_nofail(&socket_optslist);
349
350 qemu_opt_set(opts, "host", s->inet_addr->host);
351 qemu_opt_set(opts, "port", s->inet_addr->port);
352 if (s->inet_addr->has_to) {
353 qemu_opt_set_number(opts, "to", s->inet_addr->to);
354 }
355 if (s->inet_addr->has_ipv4) {
356 qemu_opt_set_number(opts, "ipv4", s->inet_addr->ipv4);
357 }
358 if (s->inet_addr->has_ipv6) {
359 qemu_opt_set_number(opts, "ipv6", s->inet_addr->ipv6);
360 }
361
362 sock = tcp_socket_outgoing_opts(opts);
363 qemu_opts_del(opts);
364 }
365
366 /* Failed to establish connection */
367 if (sock < 0) {
368 logout("Failed to establish connection to NBD server\n");
369 return -errno;
370 }
371
372 /* NBD handshake */
373 ret = nbd_receive_negotiate(sock, s->export_name, &s->nbdflags, &size,
374 &blocksize);
375 if (ret < 0) {
376 logout("Failed to negotiate with the NBD server\n");
377 closesocket(sock);
378 return ret;
379 }
380
381 /* Now that we're connected, set the socket to be non-blocking and
382 * kick the reply mechanism. */
383 socket_set_nonblock(sock);
384 qemu_aio_set_fd_handler(sock, nbd_reply_ready, NULL,
385 nbd_have_request, s);
386
387 s->sock = sock;
388 s->size = size;
389 s->blocksize = blocksize;
390
391 logout("Established connection with NBD server\n");
392 return 0;
393 }
394
395 static void nbd_teardown_connection(BlockDriverState *bs)
396 {
397 BDRVNBDState *s = bs->opaque;
398 struct nbd_request request;
399
400 request.type = NBD_CMD_DISC;
401 request.from = 0;
402 request.len = 0;
403 nbd_send_request(s->sock, &request);
404
405 qemu_aio_set_fd_handler(s->sock, NULL, NULL, NULL, NULL);
406 closesocket(s->sock);
407 }
408
409 static int nbd_open(BlockDriverState *bs, const char* filename,
410 QDict *options, int flags)
411 {
412 BDRVNBDState *s = bs->opaque;
413 int result;
414
415 qemu_co_mutex_init(&s->send_mutex);
416 qemu_co_mutex_init(&s->free_sema);
417
418 /* Pop the config into our state object. Exit if invalid. */
419 result = nbd_config(s, filename);
420 if (result != 0) {
421 return result;
422 }
423
424 /* establish TCP connection, return error if it fails
425 * TODO: Configurable retry-until-timeout behaviour.
426 */
427 result = nbd_establish_connection(bs);
428
429 return result;
430 }
431
432 static int nbd_co_readv_1(BlockDriverState *bs, int64_t sector_num,
433 int nb_sectors, QEMUIOVector *qiov,
434 int offset)
435 {
436 BDRVNBDState *s = bs->opaque;
437 struct nbd_request request;
438 struct nbd_reply reply;
439 ssize_t ret;
440
441 request.type = NBD_CMD_READ;
442 request.from = sector_num * 512;
443 request.len = nb_sectors * 512;
444
445 nbd_coroutine_start(s, &request);
446 ret = nbd_co_send_request(s, &request, NULL, 0);
447 if (ret < 0) {
448 reply.error = -ret;
449 } else {
450 nbd_co_receive_reply(s, &request, &reply, qiov, offset);
451 }
452 nbd_coroutine_end(s, &request);
453 return -reply.error;
454
455 }
456
457 static int nbd_co_writev_1(BlockDriverState *bs, int64_t sector_num,
458 int nb_sectors, QEMUIOVector *qiov,
459 int offset)
460 {
461 BDRVNBDState *s = bs->opaque;
462 struct nbd_request request;
463 struct nbd_reply reply;
464 ssize_t ret;
465
466 request.type = NBD_CMD_WRITE;
467 if (!bdrv_enable_write_cache(bs) && (s->nbdflags & NBD_FLAG_SEND_FUA)) {
468 request.type |= NBD_CMD_FLAG_FUA;
469 }
470
471 request.from = sector_num * 512;
472 request.len = nb_sectors * 512;
473
474 nbd_coroutine_start(s, &request);
475 ret = nbd_co_send_request(s, &request, qiov, offset);
476 if (ret < 0) {
477 reply.error = -ret;
478 } else {
479 nbd_co_receive_reply(s, &request, &reply, NULL, 0);
480 }
481 nbd_coroutine_end(s, &request);
482 return -reply.error;
483 }
484
485 /* qemu-nbd has a limit of slightly less than 1M per request. Try to
486 * remain aligned to 4K. */
487 #define NBD_MAX_SECTORS 2040
488
489 static int nbd_co_readv(BlockDriverState *bs, int64_t sector_num,
490 int nb_sectors, QEMUIOVector *qiov)
491 {
492 int offset = 0;
493 int ret;
494 while (nb_sectors > NBD_MAX_SECTORS) {
495 ret = nbd_co_readv_1(bs, sector_num, NBD_MAX_SECTORS, qiov, offset);
496 if (ret < 0) {
497 return ret;
498 }
499 offset += NBD_MAX_SECTORS * 512;
500 sector_num += NBD_MAX_SECTORS;
501 nb_sectors -= NBD_MAX_SECTORS;
502 }
503 return nbd_co_readv_1(bs, sector_num, nb_sectors, qiov, offset);
504 }
505
506 static int nbd_co_writev(BlockDriverState *bs, int64_t sector_num,
507 int nb_sectors, QEMUIOVector *qiov)
508 {
509 int offset = 0;
510 int ret;
511 while (nb_sectors > NBD_MAX_SECTORS) {
512 ret = nbd_co_writev_1(bs, sector_num, NBD_MAX_SECTORS, qiov, offset);
513 if (ret < 0) {
514 return ret;
515 }
516 offset += NBD_MAX_SECTORS * 512;
517 sector_num += NBD_MAX_SECTORS;
518 nb_sectors -= NBD_MAX_SECTORS;
519 }
520 return nbd_co_writev_1(bs, sector_num, nb_sectors, qiov, offset);
521 }
522
523 static int nbd_co_flush(BlockDriverState *bs)
524 {
525 BDRVNBDState *s = bs->opaque;
526 struct nbd_request request;
527 struct nbd_reply reply;
528 ssize_t ret;
529
530 if (!(s->nbdflags & NBD_FLAG_SEND_FLUSH)) {
531 return 0;
532 }
533
534 request.type = NBD_CMD_FLUSH;
535 if (s->nbdflags & NBD_FLAG_SEND_FUA) {
536 request.type |= NBD_CMD_FLAG_FUA;
537 }
538
539 request.from = 0;
540 request.len = 0;
541
542 nbd_coroutine_start(s, &request);
543 ret = nbd_co_send_request(s, &request, NULL, 0);
544 if (ret < 0) {
545 reply.error = -ret;
546 } else {
547 nbd_co_receive_reply(s, &request, &reply, NULL, 0);
548 }
549 nbd_coroutine_end(s, &request);
550 return -reply.error;
551 }
552
553 static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,
554 int nb_sectors)
555 {
556 BDRVNBDState *s = bs->opaque;
557 struct nbd_request request;
558 struct nbd_reply reply;
559 ssize_t ret;
560
561 if (!(s->nbdflags & NBD_FLAG_SEND_TRIM)) {
562 return 0;
563 }
564 request.type = NBD_CMD_TRIM;
565 request.from = sector_num * 512;;
566 request.len = nb_sectors * 512;
567
568 nbd_coroutine_start(s, &request);
569 ret = nbd_co_send_request(s, &request, NULL, 0);
570 if (ret < 0) {
571 reply.error = -ret;
572 } else {
573 nbd_co_receive_reply(s, &request, &reply, NULL, 0);
574 }
575 nbd_coroutine_end(s, &request);
576 return -reply.error;
577 }
578
579 static void nbd_close(BlockDriverState *bs)
580 {
581 BDRVNBDState *s = bs->opaque;
582 g_free(s->export_name);
583 g_free(s->unix_path);
584 qapi_free_InetSocketAddress(s->inet_addr);
585
586 nbd_teardown_connection(bs);
587 }
588
589 static int64_t nbd_getlength(BlockDriverState *bs)
590 {
591 BDRVNBDState *s = bs->opaque;
592
593 return s->size;
594 }
595
596 static BlockDriver bdrv_nbd = {
597 .format_name = "nbd",
598 .protocol_name = "nbd",
599 .instance_size = sizeof(BDRVNBDState),
600 .bdrv_file_open = nbd_open,
601 .bdrv_co_readv = nbd_co_readv,
602 .bdrv_co_writev = nbd_co_writev,
603 .bdrv_close = nbd_close,
604 .bdrv_co_flush_to_os = nbd_co_flush,
605 .bdrv_co_discard = nbd_co_discard,
606 .bdrv_getlength = nbd_getlength,
607 };
608
609 static BlockDriver bdrv_nbd_tcp = {
610 .format_name = "nbd",
611 .protocol_name = "nbd+tcp",
612 .instance_size = sizeof(BDRVNBDState),
613 .bdrv_file_open = nbd_open,
614 .bdrv_co_readv = nbd_co_readv,
615 .bdrv_co_writev = nbd_co_writev,
616 .bdrv_close = nbd_close,
617 .bdrv_co_flush_to_os = nbd_co_flush,
618 .bdrv_co_discard = nbd_co_discard,
619 .bdrv_getlength = nbd_getlength,
620 };
621
622 static BlockDriver bdrv_nbd_unix = {
623 .format_name = "nbd",
624 .protocol_name = "nbd+unix",
625 .instance_size = sizeof(BDRVNBDState),
626 .bdrv_file_open = nbd_open,
627 .bdrv_co_readv = nbd_co_readv,
628 .bdrv_co_writev = nbd_co_writev,
629 .bdrv_close = nbd_close,
630 .bdrv_co_flush_to_os = nbd_co_flush,
631 .bdrv_co_discard = nbd_co_discard,
632 .bdrv_getlength = nbd_getlength,
633 };
634
635 static void bdrv_nbd_init(void)
636 {
637 bdrv_register(&bdrv_nbd);
638 bdrv_register(&bdrv_nbd_tcp);
639 bdrv_register(&bdrv_nbd_unix);
640 }
641
642 block_init(bdrv_nbd_init);