]> git.proxmox.com Git - qemu.git/blob - block/nbd.c
nbd: accept URIs
[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 "nbd.h"
31 #include "uri.h"
32 #include "block_int.h"
33 #include "module.h"
34 #include "qemu_socket.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 *host_spec;
70 char *export_name; /* An NBD server may export several devices */
71 } BDRVNBDState;
72
73 static int nbd_parse_uri(BDRVNBDState *s, const char *filename)
74 {
75 URI *uri;
76 const char *p;
77 QueryParams *qp = NULL;
78 int ret = 0;
79
80 uri = uri_parse(filename);
81 if (!uri) {
82 return -EINVAL;
83 }
84
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;
95 }
96
97 p = uri->path ? uri->path : "/";
98 p += strspn(p, "/");
99 if (p[0]) {
100 s->export_name = g_strdup(p);
101 }
102
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;
107 }
108
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;
114 }
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;
121 }
122 if (!uri->port) {
123 uri->port = NBD_DEFAULT_PORT;
124 }
125 s->host_spec = g_strdup_printf("%s:%d", uri->server, uri->port);
126 }
127
128 out:
129 if (qp) {
130 query_params_free(qp);
131 }
132 uri_free(uri);
133 return ret;
134 }
135
136 static int nbd_config(BDRVNBDState *s, const char *filename)
137 {
138 char *file;
139 char *export_name;
140 const char *host_spec;
141 const char *unixpath;
142 int err = -EINVAL;
143
144 if (strstr(filename, "://")) {
145 return nbd_parse_uri(s, filename);
146 }
147
148 file = g_strdup(filename);
149
150 export_name = strstr(file, EN_OPTSTR);
151 if (export_name) {
152 if (export_name[strlen(EN_OPTSTR)] == 0) {
153 goto out;
154 }
155 export_name[0] = 0; /* truncate 'file' */
156 export_name += strlen(EN_OPTSTR);
157 s->export_name = g_strdup(export_name);
158 }
159
160 /* extract the host_spec - fail if it's not nbd:... */
161 if (!strstart(file, "nbd:", &host_spec)) {
162 goto out;
163 }
164
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);
172 }
173
174 err = 0;
175
176 out:
177 g_free(file);
178 if (err != 0) {
179 g_free(s->export_name);
180 g_free(s->host_spec);
181 }
182 return err;
183 }
184
185 static void nbd_coroutine_start(BDRVNBDState *s, struct nbd_request *request)
186 {
187 int i;
188
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);
194 }
195 s->in_flight++;
196
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;
201 }
202 }
203
204 assert(i < MAX_NBD_REQUESTS);
205 request->handle = INDEX_TO_HANDLE(s, i);
206 }
207
208 static int nbd_have_request(void *opaque)
209 {
210 BDRVNBDState *s = opaque;
211
212 return s->in_flight > 0;
213 }
214
215 static void nbd_reply_ready(void *opaque)
216 {
217 BDRVNBDState *s = opaque;
218 uint64_t i;
219 int ret;
220
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.
225 */
226 ret = nbd_receive_reply(s->sock, &s->reply);
227 if (ret == -EAGAIN) {
228 return;
229 }
230 if (ret < 0) {
231 s->reply.handle = 0;
232 goto fail;
233 }
234 }
235
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;
242 }
243
244 if (s->recv_coroutine[i]) {
245 qemu_coroutine_enter(s->recv_coroutine[i], NULL);
246 return;
247 }
248
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);
253 }
254 }
255 }
256
257 static void nbd_restart_write(void *opaque)
258 {
259 BDRVNBDState *s = opaque;
260 qemu_coroutine_enter(s->send_coroutine, NULL);
261 }
262
263 static int nbd_co_send_request(BDRVNBDState *s, struct nbd_request *request,
264 QEMUIOVector *qiov, int offset)
265 {
266 int rc, ret;
267
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;
278 }
279 }
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;
285 }
286
287 static void nbd_co_receive_reply(BDRVNBDState *s, struct nbd_request *request,
288 struct nbd_reply *reply,
289 QEMUIOVector *qiov, int offset)
290 {
291 int ret;
292
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;
305 }
306 }
307
308 /* Tell the read handler to read another header. */
309 s->reply.handle = 0;
310 }
311 }
312
313 static void nbd_coroutine_end(BDRVNBDState *s, struct nbd_request *request)
314 {
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);
319 }
320 }
321
322 static int nbd_establish_connection(BlockDriverState *bs)
323 {
324 BDRVNBDState *s = bs->opaque;
325 int sock;
326 int ret;
327 off_t size;
328 size_t blocksize;
329
330 if (s->is_unix) {
331 sock = unix_socket_outgoing(s->host_spec);
332 } else {
333 sock = tcp_socket_outgoing_spec(s->host_spec);
334 }
335
336 /* Failed to establish connection */
337 if (sock < 0) {
338 logout("Failed to establish connection to NBD server\n");
339 return -errno;
340 }
341
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;
349 }
350
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);
356
357 s->sock = sock;
358 s->size = size;
359 s->blocksize = blocksize;
360
361 logout("Established connection with NBD server\n");
362 return 0;
363 }
364
365 static void nbd_teardown_connection(BlockDriverState *bs)
366 {
367 BDRVNBDState *s = bs->opaque;
368 struct nbd_request request;
369
370 request.type = NBD_CMD_DISC;
371 request.from = 0;
372 request.len = 0;
373 nbd_send_request(s->sock, &request);
374
375 qemu_aio_set_fd_handler(s->sock, NULL, NULL, NULL, NULL);
376 closesocket(s->sock);
377 }
378
379 static int nbd_open(BlockDriverState *bs, const char* filename, int flags)
380 {
381 BDRVNBDState *s = bs->opaque;
382 int result;
383
384 qemu_co_mutex_init(&s->send_mutex);
385 qemu_co_mutex_init(&s->free_sema);
386
387 /* Pop the config into our state object. Exit if invalid. */
388 result = nbd_config(s, filename);
389 if (result != 0) {
390 return result;
391 }
392
393 /* establish TCP connection, return error if it fails
394 * TODO: Configurable retry-until-timeout behaviour.
395 */
396 result = nbd_establish_connection(bs);
397
398 return result;
399 }
400
401 static int nbd_co_readv_1(BlockDriverState *bs, int64_t sector_num,
402 int nb_sectors, QEMUIOVector *qiov,
403 int offset)
404 {
405 BDRVNBDState *s = bs->opaque;
406 struct nbd_request request;
407 struct nbd_reply reply;
408 ssize_t ret;
409
410 request.type = NBD_CMD_READ;
411 request.from = sector_num * 512;
412 request.len = nb_sectors * 512;
413
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);
420 }
421 nbd_coroutine_end(s, &request);
422 return -reply.error;
423
424 }
425
426 static int nbd_co_writev_1(BlockDriverState *bs, int64_t sector_num,
427 int nb_sectors, QEMUIOVector *qiov,
428 int offset)
429 {
430 BDRVNBDState *s = bs->opaque;
431 struct nbd_request request;
432 struct nbd_reply reply;
433 ssize_t ret;
434
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;
438 }
439
440 request.from = sector_num * 512;
441 request.len = nb_sectors * 512;
442
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);
449 }
450 nbd_coroutine_end(s, &request);
451 return -reply.error;
452 }
453
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
457
458 static int nbd_co_readv(BlockDriverState *bs, int64_t sector_num,
459 int nb_sectors, QEMUIOVector *qiov)
460 {
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;
467 }
468 offset += NBD_MAX_SECTORS * 512;
469 sector_num += NBD_MAX_SECTORS;
470 nb_sectors -= NBD_MAX_SECTORS;
471 }
472 return nbd_co_readv_1(bs, sector_num, nb_sectors, qiov, offset);
473 }
474
475 static int nbd_co_writev(BlockDriverState *bs, int64_t sector_num,
476 int nb_sectors, QEMUIOVector *qiov)
477 {
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;
484 }
485 offset += NBD_MAX_SECTORS * 512;
486 sector_num += NBD_MAX_SECTORS;
487 nb_sectors -= NBD_MAX_SECTORS;
488 }
489 return nbd_co_writev_1(bs, sector_num, nb_sectors, qiov, offset);
490 }
491
492 static int nbd_co_flush(BlockDriverState *bs)
493 {
494 BDRVNBDState *s = bs->opaque;
495 struct nbd_request request;
496 struct nbd_reply reply;
497 ssize_t ret;
498
499 if (!(s->nbdflags & NBD_FLAG_SEND_FLUSH)) {
500 return 0;
501 }
502
503 request.type = NBD_CMD_FLUSH;
504 if (s->nbdflags & NBD_FLAG_SEND_FUA) {
505 request.type |= NBD_CMD_FLAG_FUA;
506 }
507
508 request.from = 0;
509 request.len = 0;
510
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);
517 }
518 nbd_coroutine_end(s, &request);
519 return -reply.error;
520 }
521
522 static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,
523 int nb_sectors)
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_TRIM)) {
531 return 0;
532 }
533 request.type = NBD_CMD_TRIM;
534 request.from = sector_num * 512;;
535 request.len = nb_sectors * 512;
536
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);
543 }
544 nbd_coroutine_end(s, &request);
545 return -reply.error;
546 }
547
548 static void nbd_close(BlockDriverState *bs)
549 {
550 BDRVNBDState *s = bs->opaque;
551 g_free(s->export_name);
552 g_free(s->host_spec);
553
554 nbd_teardown_connection(bs);
555 }
556
557 static int64_t nbd_getlength(BlockDriverState *bs)
558 {
559 BDRVNBDState *s = bs->opaque;
560
561 return s->size;
562 }
563
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,
575 };
576
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,
588 };
589
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,
601 };
602
603 static void bdrv_nbd_init(void)
604 {
605 bdrv_register(&bdrv_nbd);
606 bdrv_register(&bdrv_nbd_tcp);
607 bdrv_register(&bdrv_nbd_unix);
608 }
609
610 block_init(bdrv_nbd_init);