hw/arm: Qomify pxa2xx.c
[qemu/ar7.git] / block / nbd.c
blob814ab26dceedd485228976d4fadc77f482909c36
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/osdep.h"
30 #include "block/nbd-client.h"
31 #include "qapi/error.h"
32 #include "qemu/uri.h"
33 #include "block/block_int.h"
34 #include "qemu/module.h"
35 #include "qapi-visit.h"
36 #include "qapi/qobject-input-visitor.h"
37 #include "qapi/qobject-output-visitor.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qjson.h"
40 #include "qapi/qmp/qint.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qemu/cutils.h"
44 #define EN_OPTSTR ":exportname="
46 typedef struct BDRVNBDState {
47 NBDClientSession client;
49 /* For nbd_refresh_filename() */
50 SocketAddressFlat *saddr;
51 char *export, *tlscredsid;
52 } BDRVNBDState;
54 static int nbd_parse_uri(const char *filename, QDict *options)
56 URI *uri;
57 const char *p;
58 QueryParams *qp = NULL;
59 int ret = 0;
60 bool is_unix;
62 uri = uri_parse(filename);
63 if (!uri) {
64 return -EINVAL;
67 /* transport */
68 if (!strcmp(uri->scheme, "nbd")) {
69 is_unix = false;
70 } else if (!strcmp(uri->scheme, "nbd+tcp")) {
71 is_unix = false;
72 } else if (!strcmp(uri->scheme, "nbd+unix")) {
73 is_unix = true;
74 } else {
75 ret = -EINVAL;
76 goto out;
79 p = uri->path ? uri->path : "/";
80 p += strspn(p, "/");
81 if (p[0]) {
82 qdict_put(options, "export", qstring_from_str(p));
85 qp = query_params_parse(uri->query);
86 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
87 ret = -EINVAL;
88 goto out;
91 if (is_unix) {
92 /* nbd+unix:///export?socket=path */
93 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
94 ret = -EINVAL;
95 goto out;
97 qdict_put(options, "server.type", qstring_from_str("unix"));
98 qdict_put(options, "server.path",
99 qstring_from_str(qp->p[0].value));
100 } else {
101 QString *host;
102 char *port_str;
104 /* nbd[+tcp]://host[:port]/export */
105 if (!uri->server) {
106 ret = -EINVAL;
107 goto out;
110 /* strip braces from literal IPv6 address */
111 if (uri->server[0] == '[') {
112 host = qstring_from_substr(uri->server, 1,
113 strlen(uri->server) - 2);
114 } else {
115 host = qstring_from_str(uri->server);
118 qdict_put(options, "server.type", qstring_from_str("inet"));
119 qdict_put(options, "server.host", host);
121 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
122 qdict_put(options, "server.port", qstring_from_str(port_str));
123 g_free(port_str);
126 out:
127 if (qp) {
128 query_params_free(qp);
130 uri_free(uri);
131 return ret;
134 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
136 const QDictEntry *e;
138 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
139 if (!strcmp(e->key, "host") ||
140 !strcmp(e->key, "port") ||
141 !strcmp(e->key, "path") ||
142 !strcmp(e->key, "export") ||
143 strstart(e->key, "server.", NULL))
145 error_setg(errp, "Option '%s' cannot be used with a file name",
146 e->key);
147 return true;
151 return false;
154 static void nbd_parse_filename(const char *filename, QDict *options,
155 Error **errp)
157 char *file;
158 char *export_name;
159 const char *host_spec;
160 const char *unixpath;
162 if (nbd_has_filename_options_conflict(options, errp)) {
163 return;
166 if (strstr(filename, "://")) {
167 int ret = nbd_parse_uri(filename, options);
168 if (ret < 0) {
169 error_setg(errp, "No valid URL specified");
171 return;
174 file = g_strdup(filename);
176 export_name = strstr(file, EN_OPTSTR);
177 if (export_name) {
178 if (export_name[strlen(EN_OPTSTR)] == 0) {
179 goto out;
181 export_name[0] = 0; /* truncate 'file' */
182 export_name += strlen(EN_OPTSTR);
184 qdict_put(options, "export", qstring_from_str(export_name));
187 /* extract the host_spec - fail if it's not nbd:... */
188 if (!strstart(file, "nbd:", &host_spec)) {
189 error_setg(errp, "File name string for NBD must start with 'nbd:'");
190 goto out;
193 if (!*host_spec) {
194 goto out;
197 /* are we a UNIX or TCP socket? */
198 if (strstart(host_spec, "unix:", &unixpath)) {
199 qdict_put(options, "server.type", qstring_from_str("unix"));
200 qdict_put(options, "server.path", qstring_from_str(unixpath));
201 } else {
202 InetSocketAddress *addr = NULL;
204 addr = inet_parse(host_spec, errp);
205 if (!addr) {
206 goto out;
209 qdict_put(options, "server.type", qstring_from_str("inet"));
210 qdict_put(options, "server.host", qstring_from_str(addr->host));
211 qdict_put(options, "server.port", qstring_from_str(addr->port));
212 qapi_free_InetSocketAddress(addr);
215 out:
216 g_free(file);
219 static bool nbd_process_legacy_socket_options(QDict *output_options,
220 QemuOpts *legacy_opts,
221 Error **errp)
223 const char *path = qemu_opt_get(legacy_opts, "path");
224 const char *host = qemu_opt_get(legacy_opts, "host");
225 const char *port = qemu_opt_get(legacy_opts, "port");
226 const QDictEntry *e;
228 if (!path && !host && !port) {
229 return true;
232 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
234 if (strstart(e->key, "server.", NULL)) {
235 error_setg(errp, "Cannot use 'server' and path/host/port at the "
236 "same time");
237 return false;
241 if (path && host) {
242 error_setg(errp, "path and host may not be used at the same time");
243 return false;
244 } else if (path) {
245 if (port) {
246 error_setg(errp, "port may not be used without host");
247 return false;
250 qdict_put(output_options, "server.type", qstring_from_str("unix"));
251 qdict_put(output_options, "server.path", qstring_from_str(path));
252 } else if (host) {
253 qdict_put(output_options, "server.type", qstring_from_str("inet"));
254 qdict_put(output_options, "server.host", qstring_from_str(host));
255 qdict_put(output_options, "server.port",
256 qstring_from_str(port ?: stringify(NBD_DEFAULT_PORT)));
259 return true;
262 static SocketAddressFlat *nbd_config(BDRVNBDState *s, QDict *options,
263 Error **errp)
265 SocketAddressFlat *saddr = NULL;
266 QDict *addr = NULL;
267 QObject *crumpled_addr = NULL;
268 Visitor *iv = NULL;
269 Error *local_err = NULL;
271 qdict_extract_subqdict(options, &addr, "server.");
272 if (!qdict_size(addr)) {
273 error_setg(errp, "NBD server address missing");
274 goto done;
277 crumpled_addr = qdict_crumple(addr, errp);
278 if (!crumpled_addr) {
279 goto done;
283 * FIXME .numeric, .to, .ipv4 or .ipv6 don't work with -drive
284 * server.type=inet. .to doesn't matter, it's ignored anyway.
285 * That's because when @options come from -blockdev or
286 * blockdev_add, members are typed according to the QAPI schema,
287 * but when they come from -drive, they're all QString. The
288 * visitor expects the former.
290 iv = qobject_input_visitor_new(crumpled_addr);
291 visit_type_SocketAddressFlat(iv, NULL, &saddr, &local_err);
292 if (local_err) {
293 error_propagate(errp, local_err);
294 goto done;
297 done:
298 QDECREF(addr);
299 qobject_decref(crumpled_addr);
300 visit_free(iv);
301 return saddr;
304 NBDClientSession *nbd_get_client_session(BlockDriverState *bs)
306 BDRVNBDState *s = bs->opaque;
307 return &s->client;
310 static QIOChannelSocket *nbd_establish_connection(SocketAddressFlat *saddr_flat,
311 Error **errp)
313 SocketAddress *saddr = socket_address_crumple(saddr_flat);
314 QIOChannelSocket *sioc;
315 Error *local_err = NULL;
317 sioc = qio_channel_socket_new();
318 qio_channel_set_name(QIO_CHANNEL(sioc), "nbd-client");
320 qio_channel_socket_connect_sync(sioc,
321 saddr,
322 &local_err);
323 qapi_free_SocketAddress(saddr);
324 if (local_err) {
325 object_unref(OBJECT(sioc));
326 error_propagate(errp, local_err);
327 return NULL;
330 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
332 return sioc;
336 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
338 Object *obj;
339 QCryptoTLSCreds *creds;
341 obj = object_resolve_path_component(
342 object_get_objects_root(), id);
343 if (!obj) {
344 error_setg(errp, "No TLS credentials with id '%s'",
345 id);
346 return NULL;
348 creds = (QCryptoTLSCreds *)
349 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
350 if (!creds) {
351 error_setg(errp, "Object with id '%s' is not TLS credentials",
352 id);
353 return NULL;
356 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
357 error_setg(errp,
358 "Expecting TLS credentials with a client endpoint");
359 return NULL;
361 object_ref(obj);
362 return creds;
366 static QemuOptsList nbd_runtime_opts = {
367 .name = "nbd",
368 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
369 .desc = {
371 .name = "host",
372 .type = QEMU_OPT_STRING,
373 .help = "TCP host to connect to",
376 .name = "port",
377 .type = QEMU_OPT_STRING,
378 .help = "TCP port to connect to",
381 .name = "path",
382 .type = QEMU_OPT_STRING,
383 .help = "Unix socket path to connect to",
386 .name = "export",
387 .type = QEMU_OPT_STRING,
388 .help = "Name of the NBD export to open",
391 .name = "tls-creds",
392 .type = QEMU_OPT_STRING,
393 .help = "ID of the TLS credentials to use",
398 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
399 Error **errp)
401 BDRVNBDState *s = bs->opaque;
402 QemuOpts *opts = NULL;
403 Error *local_err = NULL;
404 QIOChannelSocket *sioc = NULL;
405 QCryptoTLSCreds *tlscreds = NULL;
406 const char *hostname = NULL;
407 int ret = -EINVAL;
409 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
410 qemu_opts_absorb_qdict(opts, options, &local_err);
411 if (local_err) {
412 error_propagate(errp, local_err);
413 goto error;
416 /* Translate @host, @port, and @path to a SocketAddressFlat */
417 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
418 goto error;
421 /* Pop the config into our state object. Exit if invalid. */
422 s->saddr = nbd_config(s, options, errp);
423 if (!s->saddr) {
424 goto error;
427 s->export = g_strdup(qemu_opt_get(opts, "export"));
429 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
430 if (s->tlscredsid) {
431 tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
432 if (!tlscreds) {
433 goto error;
436 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
437 if (s->saddr->type != SOCKET_ADDRESS_FLAT_TYPE_INET) {
438 error_setg(errp, "TLS only supported over IP sockets");
439 goto error;
441 hostname = s->saddr->u.inet.host;
444 /* establish TCP connection, return error if it fails
445 * TODO: Configurable retry-until-timeout behaviour.
447 sioc = nbd_establish_connection(s->saddr, errp);
448 if (!sioc) {
449 ret = -ECONNREFUSED;
450 goto error;
453 /* NBD handshake */
454 ret = nbd_client_init(bs, sioc, s->export,
455 tlscreds, hostname, errp);
456 error:
457 if (sioc) {
458 object_unref(OBJECT(sioc));
460 if (tlscreds) {
461 object_unref(OBJECT(tlscreds));
463 if (ret < 0) {
464 qapi_free_SocketAddressFlat(s->saddr);
465 g_free(s->export);
466 g_free(s->tlscredsid);
468 qemu_opts_del(opts);
469 return ret;
472 static int nbd_co_flush(BlockDriverState *bs)
474 return nbd_client_co_flush(bs);
477 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
479 bs->bl.max_pdiscard = NBD_MAX_BUFFER_SIZE;
480 bs->bl.max_pwrite_zeroes = NBD_MAX_BUFFER_SIZE;
481 bs->bl.max_transfer = NBD_MAX_BUFFER_SIZE;
484 static void nbd_close(BlockDriverState *bs)
486 BDRVNBDState *s = bs->opaque;
488 nbd_client_close(bs);
490 qapi_free_SocketAddressFlat(s->saddr);
491 g_free(s->export);
492 g_free(s->tlscredsid);
495 static int64_t nbd_getlength(BlockDriverState *bs)
497 BDRVNBDState *s = bs->opaque;
499 return s->client.size;
502 static void nbd_detach_aio_context(BlockDriverState *bs)
504 nbd_client_detach_aio_context(bs);
507 static void nbd_attach_aio_context(BlockDriverState *bs,
508 AioContext *new_context)
510 nbd_client_attach_aio_context(bs, new_context);
513 static void nbd_refresh_filename(BlockDriverState *bs, QDict *options)
515 BDRVNBDState *s = bs->opaque;
516 QDict *opts = qdict_new();
517 QObject *saddr_qdict;
518 Visitor *ov;
519 const char *host = NULL, *port = NULL, *path = NULL;
521 if (s->saddr->type == SOCKET_ADDRESS_FLAT_TYPE_INET) {
522 const InetSocketAddress *inet = &s->saddr->u.inet;
523 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
524 host = inet->host;
525 port = inet->port;
527 } else if (s->saddr->type == SOCKET_ADDRESS_FLAT_TYPE_UNIX) {
528 path = s->saddr->u.q_unix.path;
529 } /* else can't represent as pseudo-filename */
531 qdict_put(opts, "driver", qstring_from_str("nbd"));
533 if (path && s->export) {
534 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
535 "nbd+unix:///%s?socket=%s", s->export, path);
536 } else if (path && !s->export) {
537 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
538 "nbd+unix://?socket=%s", path);
539 } else if (host && s->export) {
540 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
541 "nbd://%s:%s/%s", host, port, s->export);
542 } else if (host && !s->export) {
543 snprintf(bs->exact_filename, sizeof(bs->exact_filename),
544 "nbd://%s:%s", host, port);
547 ov = qobject_output_visitor_new(&saddr_qdict);
548 visit_type_SocketAddressFlat(ov, NULL, &s->saddr, &error_abort);
549 visit_complete(ov, &saddr_qdict);
550 visit_free(ov);
551 qdict_put_obj(opts, "server", saddr_qdict);
553 if (s->export) {
554 qdict_put(opts, "export", qstring_from_str(s->export));
556 if (s->tlscredsid) {
557 qdict_put(opts, "tls-creds", qstring_from_str(s->tlscredsid));
560 qdict_flatten(opts);
561 bs->full_open_options = opts;
564 static BlockDriver bdrv_nbd = {
565 .format_name = "nbd",
566 .protocol_name = "nbd",
567 .instance_size = sizeof(BDRVNBDState),
568 .bdrv_parse_filename = nbd_parse_filename,
569 .bdrv_file_open = nbd_open,
570 .bdrv_co_preadv = nbd_client_co_preadv,
571 .bdrv_co_pwritev = nbd_client_co_pwritev,
572 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
573 .bdrv_close = nbd_close,
574 .bdrv_co_flush_to_os = nbd_co_flush,
575 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
576 .bdrv_refresh_limits = nbd_refresh_limits,
577 .bdrv_getlength = nbd_getlength,
578 .bdrv_detach_aio_context = nbd_detach_aio_context,
579 .bdrv_attach_aio_context = nbd_attach_aio_context,
580 .bdrv_refresh_filename = nbd_refresh_filename,
583 static BlockDriver bdrv_nbd_tcp = {
584 .format_name = "nbd",
585 .protocol_name = "nbd+tcp",
586 .instance_size = sizeof(BDRVNBDState),
587 .bdrv_parse_filename = nbd_parse_filename,
588 .bdrv_file_open = nbd_open,
589 .bdrv_co_preadv = nbd_client_co_preadv,
590 .bdrv_co_pwritev = nbd_client_co_pwritev,
591 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
592 .bdrv_close = nbd_close,
593 .bdrv_co_flush_to_os = nbd_co_flush,
594 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
595 .bdrv_refresh_limits = nbd_refresh_limits,
596 .bdrv_getlength = nbd_getlength,
597 .bdrv_detach_aio_context = nbd_detach_aio_context,
598 .bdrv_attach_aio_context = nbd_attach_aio_context,
599 .bdrv_refresh_filename = nbd_refresh_filename,
602 static BlockDriver bdrv_nbd_unix = {
603 .format_name = "nbd",
604 .protocol_name = "nbd+unix",
605 .instance_size = sizeof(BDRVNBDState),
606 .bdrv_parse_filename = nbd_parse_filename,
607 .bdrv_file_open = nbd_open,
608 .bdrv_co_preadv = nbd_client_co_preadv,
609 .bdrv_co_pwritev = nbd_client_co_pwritev,
610 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
611 .bdrv_close = nbd_close,
612 .bdrv_co_flush_to_os = nbd_co_flush,
613 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
614 .bdrv_refresh_limits = nbd_refresh_limits,
615 .bdrv_getlength = nbd_getlength,
616 .bdrv_detach_aio_context = nbd_detach_aio_context,
617 .bdrv_attach_aio_context = nbd_attach_aio_context,
618 .bdrv_refresh_filename = nbd_refresh_filename,
621 static void bdrv_nbd_init(void)
623 bdrv_register(&bdrv_nbd);
624 bdrv_register(&bdrv_nbd_tcp);
625 bdrv_register(&bdrv_nbd_unix);
628 block_init(bdrv_nbd_init);