Update GitHub action for new Meson based build
[qemu/ar7.git] / block / rbd.c
blobbf0a919733bc67d89989b90b41625375a29aa0cc
1 /*
2 * QEMU Block driver for RADOS (Ceph)
4 * Copyright (C) 2010-2011 Christian Brunner <chb@muc.de>,
5 * Josh Durgin <josh.durgin@dreamhost.com>
7 * This work is licensed under the terms of the GNU GPL, version 2. See
8 * the COPYING file in the top-level directory.
10 * Contributions after 2012-01-13 are licensed under the terms of the
11 * GNU GPL, version 2 or (at your option) any later version.
14 #include "qemu/osdep.h"
16 #include <rbd/librbd.h>
17 #include "qapi/error.h"
18 #include "qemu/error-report.h"
19 #include "qemu/module.h"
20 #include "qemu/option.h"
21 #include "block/block_int.h"
22 #include "block/qdict.h"
23 #include "crypto/secret.h"
24 #include "qemu/cutils.h"
25 #include "sysemu/replay.h"
26 #include "qapi/qmp/qstring.h"
27 #include "qapi/qmp/qdict.h"
28 #include "qapi/qmp/qjson.h"
29 #include "qapi/qmp/qlist.h"
30 #include "qapi/qobject-input-visitor.h"
31 #include "qapi/qapi-visit-block-core.h"
34 * When specifying the image filename use:
36 * rbd:poolname/devicename[@snapshotname][:option1=value1[:option2=value2...]]
38 * poolname must be the name of an existing rados pool.
40 * devicename is the name of the rbd image.
42 * Each option given is used to configure rados, and may be any valid
43 * Ceph option, "id", or "conf".
45 * The "id" option indicates what user we should authenticate as to
46 * the Ceph cluster. If it is excluded we will use the Ceph default
47 * (normally 'admin').
49 * The "conf" option specifies a Ceph configuration file to read. If
50 * it is not specified, we will read from the default Ceph locations
51 * (e.g., /etc/ceph/ceph.conf). To avoid reading _any_ configuration
52 * file, specify conf=/dev/null.
54 * Configuration values containing :, @, or = can be escaped with a
55 * leading "\".
58 /* rbd_aio_discard added in 0.1.2 */
59 #if LIBRBD_VERSION_CODE >= LIBRBD_VERSION(0, 1, 2)
60 #define LIBRBD_SUPPORTS_DISCARD
61 #else
62 #undef LIBRBD_SUPPORTS_DISCARD
63 #endif
65 #define OBJ_MAX_SIZE (1UL << OBJ_DEFAULT_OBJ_ORDER)
67 #define RBD_MAX_SNAPS 100
69 /* The LIBRBD_SUPPORTS_IOVEC is defined in librbd.h */
70 #ifdef LIBRBD_SUPPORTS_IOVEC
71 #define LIBRBD_USE_IOVEC 1
72 #else
73 #define LIBRBD_USE_IOVEC 0
74 #endif
76 typedef enum {
77 RBD_AIO_READ,
78 RBD_AIO_WRITE,
79 RBD_AIO_DISCARD,
80 RBD_AIO_FLUSH
81 } RBDAIOCmd;
83 typedef struct RBDAIOCB {
84 BlockAIOCB common;
85 int64_t ret;
86 QEMUIOVector *qiov;
87 char *bounce;
88 RBDAIOCmd cmd;
89 int error;
90 struct BDRVRBDState *s;
91 } RBDAIOCB;
93 typedef struct RADOSCB {
94 RBDAIOCB *acb;
95 struct BDRVRBDState *s;
96 int64_t size;
97 char *buf;
98 int64_t ret;
99 } RADOSCB;
101 typedef struct BDRVRBDState {
102 rados_t cluster;
103 rados_ioctx_t io_ctx;
104 rbd_image_t image;
105 char *image_name;
106 char *snap;
107 char *namespace;
108 uint64_t image_size;
109 } BDRVRBDState;
111 static int qemu_rbd_connect(rados_t *cluster, rados_ioctx_t *io_ctx,
112 BlockdevOptionsRbd *opts, bool cache,
113 const char *keypairs, const char *secretid,
114 Error **errp);
116 static char *qemu_rbd_next_tok(char *src, char delim, char **p)
118 char *end;
120 *p = NULL;
122 for (end = src; *end; ++end) {
123 if (*end == delim) {
124 break;
126 if (*end == '\\' && end[1] != '\0') {
127 end++;
130 if (*end == delim) {
131 *p = end + 1;
132 *end = '\0';
134 return src;
137 static void qemu_rbd_unescape(char *src)
139 char *p;
141 for (p = src; *src; ++src, ++p) {
142 if (*src == '\\' && src[1] != '\0') {
143 src++;
145 *p = *src;
147 *p = '\0';
150 static void qemu_rbd_parse_filename(const char *filename, QDict *options,
151 Error **errp)
153 const char *start;
154 char *p, *buf;
155 QList *keypairs = NULL;
156 char *found_str, *image_name;
158 if (!strstart(filename, "rbd:", &start)) {
159 error_setg(errp, "File name must start with 'rbd:'");
160 return;
163 buf = g_strdup(start);
164 p = buf;
166 found_str = qemu_rbd_next_tok(p, '/', &p);
167 if (!p) {
168 error_setg(errp, "Pool name is required");
169 goto done;
171 qemu_rbd_unescape(found_str);
172 qdict_put_str(options, "pool", found_str);
174 if (strchr(p, '@')) {
175 image_name = qemu_rbd_next_tok(p, '@', &p);
177 found_str = qemu_rbd_next_tok(p, ':', &p);
178 qemu_rbd_unescape(found_str);
179 qdict_put_str(options, "snapshot", found_str);
180 } else {
181 image_name = qemu_rbd_next_tok(p, ':', &p);
183 /* Check for namespace in the image_name */
184 if (strchr(image_name, '/')) {
185 found_str = qemu_rbd_next_tok(image_name, '/', &image_name);
186 qemu_rbd_unescape(found_str);
187 qdict_put_str(options, "namespace", found_str);
188 } else {
189 qdict_put_str(options, "namespace", "");
191 qemu_rbd_unescape(image_name);
192 qdict_put_str(options, "image", image_name);
193 if (!p) {
194 goto done;
197 /* The following are essentially all key/value pairs, and we treat
198 * 'id' and 'conf' a bit special. Key/value pairs may be in any order. */
199 while (p) {
200 char *name, *value;
201 name = qemu_rbd_next_tok(p, '=', &p);
202 if (!p) {
203 error_setg(errp, "conf option %s has no value", name);
204 break;
207 qemu_rbd_unescape(name);
209 value = qemu_rbd_next_tok(p, ':', &p);
210 qemu_rbd_unescape(value);
212 if (!strcmp(name, "conf")) {
213 qdict_put_str(options, "conf", value);
214 } else if (!strcmp(name, "id")) {
215 qdict_put_str(options, "user", value);
216 } else {
218 * We pass these internally to qemu_rbd_set_keypairs(), so
219 * we can get away with the simpler list of [ "key1",
220 * "value1", "key2", "value2" ] rather than a raw dict
221 * { "key1": "value1", "key2": "value2" } where we can't
222 * guarantee order, or even a more correct but complex
223 * [ { "key1": "value1" }, { "key2": "value2" } ]
225 if (!keypairs) {
226 keypairs = qlist_new();
228 qlist_append_str(keypairs, name);
229 qlist_append_str(keypairs, value);
233 if (keypairs) {
234 qdict_put(options, "=keyvalue-pairs",
235 qobject_to_json(QOBJECT(keypairs)));
238 done:
239 g_free(buf);
240 qobject_unref(keypairs);
241 return;
245 static void qemu_rbd_refresh_limits(BlockDriverState *bs, Error **errp)
247 /* XXX Does RBD support AIO on less than 512-byte alignment? */
248 bs->bl.request_alignment = 512;
252 static int qemu_rbd_set_auth(rados_t cluster, BlockdevOptionsRbd *opts,
253 Error **errp)
255 char *key, *acr;
256 int r;
257 GString *accu;
258 RbdAuthModeList *auth;
260 if (opts->key_secret) {
261 key = qcrypto_secret_lookup_as_base64(opts->key_secret, errp);
262 if (!key) {
263 return -EIO;
265 r = rados_conf_set(cluster, "key", key);
266 g_free(key);
267 if (r < 0) {
268 error_setg_errno(errp, -r, "Could not set 'key'");
269 return r;
273 if (opts->has_auth_client_required) {
274 accu = g_string_new("");
275 for (auth = opts->auth_client_required; auth; auth = auth->next) {
276 if (accu->str[0]) {
277 g_string_append_c(accu, ';');
279 g_string_append(accu, RbdAuthMode_str(auth->value));
281 acr = g_string_free(accu, FALSE);
282 r = rados_conf_set(cluster, "auth_client_required", acr);
283 g_free(acr);
284 if (r < 0) {
285 error_setg_errno(errp, -r,
286 "Could not set 'auth_client_required'");
287 return r;
291 return 0;
294 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
295 static int qemu_rbd_set_keypairs(rados_t cluster, const char *keypairs_json,
296 Error **errp)
298 QList *keypairs;
299 QString *name;
300 QString *value;
301 const char *key;
302 size_t remaining;
303 int ret = 0;
305 if (!keypairs_json) {
306 return ret;
308 keypairs = qobject_to(QList,
309 qobject_from_json(keypairs_json, &error_abort));
310 remaining = qlist_size(keypairs) / 2;
311 assert(remaining);
313 while (remaining--) {
314 name = qobject_to(QString, qlist_pop(keypairs));
315 value = qobject_to(QString, qlist_pop(keypairs));
316 assert(name && value);
317 key = qstring_get_str(name);
319 ret = rados_conf_set(cluster, key, qstring_get_str(value));
320 qobject_unref(value);
321 if (ret < 0) {
322 error_setg_errno(errp, -ret, "invalid conf option %s", key);
323 qobject_unref(name);
324 ret = -EINVAL;
325 break;
327 qobject_unref(name);
330 qobject_unref(keypairs);
331 return ret;
334 static void qemu_rbd_memset(RADOSCB *rcb, int64_t offs)
336 if (LIBRBD_USE_IOVEC) {
337 RBDAIOCB *acb = rcb->acb;
338 iov_memset(acb->qiov->iov, acb->qiov->niov, offs, 0,
339 acb->qiov->size - offs);
340 } else {
341 memset(rcb->buf + offs, 0, rcb->size - offs);
345 /* FIXME Deprecate and remove keypairs or make it available in QMP. */
346 static int qemu_rbd_do_create(BlockdevCreateOptions *options,
347 const char *keypairs, const char *password_secret,
348 Error **errp)
350 BlockdevCreateOptionsRbd *opts = &options->u.rbd;
351 rados_t cluster;
352 rados_ioctx_t io_ctx;
353 int obj_order = 0;
354 int ret;
356 assert(options->driver == BLOCKDEV_DRIVER_RBD);
357 if (opts->location->has_snapshot) {
358 error_setg(errp, "Can't use snapshot name for image creation");
359 return -EINVAL;
362 if (opts->has_cluster_size) {
363 int64_t objsize = opts->cluster_size;
364 if ((objsize - 1) & objsize) { /* not a power of 2? */
365 error_setg(errp, "obj size needs to be power of 2");
366 return -EINVAL;
368 if (objsize < 4096) {
369 error_setg(errp, "obj size too small");
370 return -EINVAL;
372 obj_order = ctz32(objsize);
375 ret = qemu_rbd_connect(&cluster, &io_ctx, opts->location, false, keypairs,
376 password_secret, errp);
377 if (ret < 0) {
378 return ret;
381 ret = rbd_create(io_ctx, opts->location->image, opts->size, &obj_order);
382 if (ret < 0) {
383 error_setg_errno(errp, -ret, "error rbd create");
384 goto out;
387 ret = 0;
388 out:
389 rados_ioctx_destroy(io_ctx);
390 rados_shutdown(cluster);
391 return ret;
394 static int qemu_rbd_co_create(BlockdevCreateOptions *options, Error **errp)
396 return qemu_rbd_do_create(options, NULL, NULL, errp);
399 static int coroutine_fn qemu_rbd_co_create_opts(BlockDriver *drv,
400 const char *filename,
401 QemuOpts *opts,
402 Error **errp)
404 BlockdevCreateOptions *create_options;
405 BlockdevCreateOptionsRbd *rbd_opts;
406 BlockdevOptionsRbd *loc;
407 Error *local_err = NULL;
408 const char *keypairs, *password_secret;
409 QDict *options = NULL;
410 int ret = 0;
412 create_options = g_new0(BlockdevCreateOptions, 1);
413 create_options->driver = BLOCKDEV_DRIVER_RBD;
414 rbd_opts = &create_options->u.rbd;
416 rbd_opts->location = g_new0(BlockdevOptionsRbd, 1);
418 password_secret = qemu_opt_get(opts, "password-secret");
420 /* Read out options */
421 rbd_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
422 BDRV_SECTOR_SIZE);
423 rbd_opts->cluster_size = qemu_opt_get_size_del(opts,
424 BLOCK_OPT_CLUSTER_SIZE, 0);
425 rbd_opts->has_cluster_size = (rbd_opts->cluster_size != 0);
427 options = qdict_new();
428 qemu_rbd_parse_filename(filename, options, &local_err);
429 if (local_err) {
430 ret = -EINVAL;
431 error_propagate(errp, local_err);
432 goto exit;
436 * Caution: while qdict_get_try_str() is fine, getting non-string
437 * types would require more care. When @options come from -blockdev
438 * or blockdev_add, its members are typed according to the QAPI
439 * schema, but when they come from -drive, they're all QString.
441 loc = rbd_opts->location;
442 loc->pool = g_strdup(qdict_get_try_str(options, "pool"));
443 loc->conf = g_strdup(qdict_get_try_str(options, "conf"));
444 loc->has_conf = !!loc->conf;
445 loc->user = g_strdup(qdict_get_try_str(options, "user"));
446 loc->has_user = !!loc->user;
447 loc->q_namespace = g_strdup(qdict_get_try_str(options, "namespace"));
448 loc->image = g_strdup(qdict_get_try_str(options, "image"));
449 keypairs = qdict_get_try_str(options, "=keyvalue-pairs");
451 ret = qemu_rbd_do_create(create_options, keypairs, password_secret, errp);
452 if (ret < 0) {
453 goto exit;
456 exit:
457 qobject_unref(options);
458 qapi_free_BlockdevCreateOptions(create_options);
459 return ret;
463 * This aio completion is being called from rbd_finish_bh() and runs in qemu
464 * BH context.
466 static void qemu_rbd_complete_aio(RADOSCB *rcb)
468 RBDAIOCB *acb = rcb->acb;
469 int64_t r;
471 r = rcb->ret;
473 if (acb->cmd != RBD_AIO_READ) {
474 if (r < 0) {
475 acb->ret = r;
476 acb->error = 1;
477 } else if (!acb->error) {
478 acb->ret = rcb->size;
480 } else {
481 if (r < 0) {
482 qemu_rbd_memset(rcb, 0);
483 acb->ret = r;
484 acb->error = 1;
485 } else if (r < rcb->size) {
486 qemu_rbd_memset(rcb, r);
487 if (!acb->error) {
488 acb->ret = rcb->size;
490 } else if (!acb->error) {
491 acb->ret = r;
495 g_free(rcb);
497 if (!LIBRBD_USE_IOVEC) {
498 if (acb->cmd == RBD_AIO_READ) {
499 qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
501 qemu_vfree(acb->bounce);
504 acb->common.cb(acb->common.opaque, (acb->ret > 0 ? 0 : acb->ret));
506 qemu_aio_unref(acb);
509 static char *qemu_rbd_mon_host(BlockdevOptionsRbd *opts, Error **errp)
511 const char **vals;
512 const char *host, *port;
513 char *rados_str;
514 InetSocketAddressBaseList *p;
515 int i, cnt;
517 if (!opts->has_server) {
518 return NULL;
521 for (cnt = 0, p = opts->server; p; p = p->next) {
522 cnt++;
525 vals = g_new(const char *, cnt + 1);
527 for (i = 0, p = opts->server; p; p = p->next, i++) {
528 host = p->value->host;
529 port = p->value->port;
531 if (strchr(host, ':')) {
532 vals[i] = g_strdup_printf("[%s]:%s", host, port);
533 } else {
534 vals[i] = g_strdup_printf("%s:%s", host, port);
537 vals[i] = NULL;
539 rados_str = i ? g_strjoinv(";", (char **)vals) : NULL;
540 g_strfreev((char **)vals);
541 return rados_str;
544 static int qemu_rbd_connect(rados_t *cluster, rados_ioctx_t *io_ctx,
545 BlockdevOptionsRbd *opts, bool cache,
546 const char *keypairs, const char *secretid,
547 Error **errp)
549 char *mon_host = NULL;
550 Error *local_err = NULL;
551 int r;
553 if (secretid) {
554 if (opts->key_secret) {
555 error_setg(errp,
556 "Legacy 'password-secret' clashes with 'key-secret'");
557 return -EINVAL;
559 opts->key_secret = g_strdup(secretid);
560 opts->has_key_secret = true;
563 mon_host = qemu_rbd_mon_host(opts, &local_err);
564 if (local_err) {
565 error_propagate(errp, local_err);
566 r = -EINVAL;
567 goto failed_opts;
570 r = rados_create(cluster, opts->user);
571 if (r < 0) {
572 error_setg_errno(errp, -r, "error initializing");
573 goto failed_opts;
576 /* try default location when conf=NULL, but ignore failure */
577 r = rados_conf_read_file(*cluster, opts->conf);
578 if (opts->has_conf && r < 0) {
579 error_setg_errno(errp, -r, "error reading conf file %s", opts->conf);
580 goto failed_shutdown;
583 r = qemu_rbd_set_keypairs(*cluster, keypairs, errp);
584 if (r < 0) {
585 goto failed_shutdown;
588 if (mon_host) {
589 r = rados_conf_set(*cluster, "mon_host", mon_host);
590 if (r < 0) {
591 goto failed_shutdown;
595 r = qemu_rbd_set_auth(*cluster, opts, errp);
596 if (r < 0) {
597 goto failed_shutdown;
601 * Fallback to more conservative semantics if setting cache
602 * options fails. Ignore errors from setting rbd_cache because the
603 * only possible error is that the option does not exist, and
604 * librbd defaults to no caching. If write through caching cannot
605 * be set up, fall back to no caching.
607 if (cache) {
608 rados_conf_set(*cluster, "rbd_cache", "true");
609 } else {
610 rados_conf_set(*cluster, "rbd_cache", "false");
613 r = rados_connect(*cluster);
614 if (r < 0) {
615 error_setg_errno(errp, -r, "error connecting");
616 goto failed_shutdown;
619 r = rados_ioctx_create(*cluster, opts->pool, io_ctx);
620 if (r < 0) {
621 error_setg_errno(errp, -r, "error opening pool %s", opts->pool);
622 goto failed_shutdown;
625 * Set the namespace after opening the io context on the pool,
626 * if nspace == NULL or if nspace == "", it is just as we did nothing
628 rados_ioctx_set_namespace(*io_ctx, opts->q_namespace);
630 return 0;
632 failed_shutdown:
633 rados_shutdown(*cluster);
634 failed_opts:
635 g_free(mon_host);
636 return r;
639 static int qemu_rbd_convert_options(QDict *options, BlockdevOptionsRbd **opts,
640 Error **errp)
642 Visitor *v;
644 /* Convert the remaining options into a QAPI object */
645 v = qobject_input_visitor_new_flat_confused(options, errp);
646 if (!v) {
647 return -EINVAL;
650 visit_type_BlockdevOptionsRbd(v, NULL, opts, errp);
651 visit_free(v);
652 if (!opts) {
653 return -EINVAL;
656 return 0;
659 static int qemu_rbd_attempt_legacy_options(QDict *options,
660 BlockdevOptionsRbd **opts,
661 char **keypairs)
663 char *filename;
664 int r;
666 filename = g_strdup(qdict_get_try_str(options, "filename"));
667 if (!filename) {
668 return -EINVAL;
670 qdict_del(options, "filename");
672 qemu_rbd_parse_filename(filename, options, NULL);
674 /* keypairs freed by caller */
675 *keypairs = g_strdup(qdict_get_try_str(options, "=keyvalue-pairs"));
676 if (*keypairs) {
677 qdict_del(options, "=keyvalue-pairs");
680 r = qemu_rbd_convert_options(options, opts, NULL);
682 g_free(filename);
683 return r;
686 static int qemu_rbd_open(BlockDriverState *bs, QDict *options, int flags,
687 Error **errp)
689 BDRVRBDState *s = bs->opaque;
690 BlockdevOptionsRbd *opts = NULL;
691 const QDictEntry *e;
692 Error *local_err = NULL;
693 char *keypairs, *secretid;
694 int r;
696 keypairs = g_strdup(qdict_get_try_str(options, "=keyvalue-pairs"));
697 if (keypairs) {
698 qdict_del(options, "=keyvalue-pairs");
701 secretid = g_strdup(qdict_get_try_str(options, "password-secret"));
702 if (secretid) {
703 qdict_del(options, "password-secret");
706 r = qemu_rbd_convert_options(options, &opts, &local_err);
707 if (local_err) {
708 /* If keypairs are present, that means some options are present in
709 * the modern option format. Don't attempt to parse legacy option
710 * formats, as we won't support mixed usage. */
711 if (keypairs) {
712 error_propagate(errp, local_err);
713 goto out;
716 /* If the initial attempt to convert and process the options failed,
717 * we may be attempting to open an image file that has the rbd options
718 * specified in the older format consisting of all key/value pairs
719 * encoded in the filename. Go ahead and attempt to parse the
720 * filename, and see if we can pull out the required options. */
721 r = qemu_rbd_attempt_legacy_options(options, &opts, &keypairs);
722 if (r < 0) {
723 /* Propagate the original error, not the legacy parsing fallback
724 * error, as the latter was just a best-effort attempt. */
725 error_propagate(errp, local_err);
726 goto out;
728 /* Take care whenever deciding to actually deprecate; once this ability
729 * is removed, we will not be able to open any images with legacy-styled
730 * backing image strings. */
731 warn_report("RBD options encoded in the filename as keyvalue pairs "
732 "is deprecated");
735 /* Remove the processed options from the QDict (the visitor processes
736 * _all_ options in the QDict) */
737 while ((e = qdict_first(options))) {
738 qdict_del(options, e->key);
741 r = qemu_rbd_connect(&s->cluster, &s->io_ctx, opts,
742 !(flags & BDRV_O_NOCACHE), keypairs, secretid, errp);
743 if (r < 0) {
744 goto out;
747 s->snap = g_strdup(opts->snapshot);
748 s->image_name = g_strdup(opts->image);
750 /* rbd_open is always r/w */
751 r = rbd_open(s->io_ctx, s->image_name, &s->image, s->snap);
752 if (r < 0) {
753 error_setg_errno(errp, -r, "error reading header from %s",
754 s->image_name);
755 goto failed_open;
758 r = rbd_get_size(s->image, &s->image_size);
759 if (r < 0) {
760 error_setg_errno(errp, -r, "error getting image size from %s",
761 s->image_name);
762 rbd_close(s->image);
763 goto failed_open;
766 /* If we are using an rbd snapshot, we must be r/o, otherwise
767 * leave as-is */
768 if (s->snap != NULL) {
769 r = bdrv_apply_auto_read_only(bs, "rbd snapshots are read-only", errp);
770 if (r < 0) {
771 rbd_close(s->image);
772 goto failed_open;
776 /* When extending regular files, we get zeros from the OS */
777 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
779 r = 0;
780 goto out;
782 failed_open:
783 rados_ioctx_destroy(s->io_ctx);
784 g_free(s->snap);
785 g_free(s->image_name);
786 rados_shutdown(s->cluster);
787 out:
788 qapi_free_BlockdevOptionsRbd(opts);
789 g_free(keypairs);
790 g_free(secretid);
791 return r;
795 /* Since RBD is currently always opened R/W via the API,
796 * we just need to check if we are using a snapshot or not, in
797 * order to determine if we will allow it to be R/W */
798 static int qemu_rbd_reopen_prepare(BDRVReopenState *state,
799 BlockReopenQueue *queue, Error **errp)
801 BDRVRBDState *s = state->bs->opaque;
802 int ret = 0;
804 if (s->snap && state->flags & BDRV_O_RDWR) {
805 error_setg(errp,
806 "Cannot change node '%s' to r/w when using RBD snapshot",
807 bdrv_get_device_or_node_name(state->bs));
808 ret = -EINVAL;
811 return ret;
814 static void qemu_rbd_close(BlockDriverState *bs)
816 BDRVRBDState *s = bs->opaque;
818 rbd_close(s->image);
819 rados_ioctx_destroy(s->io_ctx);
820 g_free(s->snap);
821 g_free(s->image_name);
822 rados_shutdown(s->cluster);
825 /* Resize the RBD image and update the 'image_size' with the current size */
826 static int qemu_rbd_resize(BlockDriverState *bs, uint64_t size)
828 BDRVRBDState *s = bs->opaque;
829 int r;
831 r = rbd_resize(s->image, size);
832 if (r < 0) {
833 return r;
836 s->image_size = size;
838 return 0;
841 static const AIOCBInfo rbd_aiocb_info = {
842 .aiocb_size = sizeof(RBDAIOCB),
845 static void rbd_finish_bh(void *opaque)
847 RADOSCB *rcb = opaque;
848 qemu_rbd_complete_aio(rcb);
852 * This is the callback function for rbd_aio_read and _write
854 * Note: this function is being called from a non qemu thread so
855 * we need to be careful about what we do here. Generally we only
856 * schedule a BH, and do the rest of the io completion handling
857 * from rbd_finish_bh() which runs in a qemu context.
859 static void rbd_finish_aiocb(rbd_completion_t c, RADOSCB *rcb)
861 RBDAIOCB *acb = rcb->acb;
863 rcb->ret = rbd_aio_get_return_value(c);
864 rbd_aio_release(c);
866 replay_bh_schedule_oneshot_event(bdrv_get_aio_context(acb->common.bs),
867 rbd_finish_bh, rcb);
870 static int rbd_aio_discard_wrapper(rbd_image_t image,
871 uint64_t off,
872 uint64_t len,
873 rbd_completion_t comp)
875 #ifdef LIBRBD_SUPPORTS_DISCARD
876 return rbd_aio_discard(image, off, len, comp);
877 #else
878 return -ENOTSUP;
879 #endif
882 static int rbd_aio_flush_wrapper(rbd_image_t image,
883 rbd_completion_t comp)
885 #ifdef LIBRBD_SUPPORTS_AIO_FLUSH
886 return rbd_aio_flush(image, comp);
887 #else
888 return -ENOTSUP;
889 #endif
892 static BlockAIOCB *rbd_start_aio(BlockDriverState *bs,
893 int64_t off,
894 QEMUIOVector *qiov,
895 int64_t size,
896 BlockCompletionFunc *cb,
897 void *opaque,
898 RBDAIOCmd cmd)
900 RBDAIOCB *acb;
901 RADOSCB *rcb = NULL;
902 rbd_completion_t c;
903 int r;
905 BDRVRBDState *s = bs->opaque;
907 acb = qemu_aio_get(&rbd_aiocb_info, bs, cb, opaque);
908 acb->cmd = cmd;
909 acb->qiov = qiov;
910 assert(!qiov || qiov->size == size);
912 rcb = g_new(RADOSCB, 1);
914 if (!LIBRBD_USE_IOVEC) {
915 if (cmd == RBD_AIO_DISCARD || cmd == RBD_AIO_FLUSH) {
916 acb->bounce = NULL;
917 } else {
918 acb->bounce = qemu_try_blockalign(bs, qiov->size);
919 if (acb->bounce == NULL) {
920 goto failed;
923 if (cmd == RBD_AIO_WRITE) {
924 qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
926 rcb->buf = acb->bounce;
929 acb->ret = 0;
930 acb->error = 0;
931 acb->s = s;
933 rcb->acb = acb;
934 rcb->s = acb->s;
935 rcb->size = size;
936 r = rbd_aio_create_completion(rcb, (rbd_callback_t) rbd_finish_aiocb, &c);
937 if (r < 0) {
938 goto failed;
941 switch (cmd) {
942 case RBD_AIO_WRITE: {
944 * RBD APIs don't allow us to write more than actual size, so in order
945 * to support growing images, we resize the image before write
946 * operations that exceed the current size.
948 if (off + size > s->image_size) {
949 r = qemu_rbd_resize(bs, off + size);
950 if (r < 0) {
951 goto failed_completion;
954 #ifdef LIBRBD_SUPPORTS_IOVEC
955 r = rbd_aio_writev(s->image, qiov->iov, qiov->niov, off, c);
956 #else
957 r = rbd_aio_write(s->image, off, size, rcb->buf, c);
958 #endif
959 break;
961 case RBD_AIO_READ:
962 #ifdef LIBRBD_SUPPORTS_IOVEC
963 r = rbd_aio_readv(s->image, qiov->iov, qiov->niov, off, c);
964 #else
965 r = rbd_aio_read(s->image, off, size, rcb->buf, c);
966 #endif
967 break;
968 case RBD_AIO_DISCARD:
969 r = rbd_aio_discard_wrapper(s->image, off, size, c);
970 break;
971 case RBD_AIO_FLUSH:
972 r = rbd_aio_flush_wrapper(s->image, c);
973 break;
974 default:
975 r = -EINVAL;
978 if (r < 0) {
979 goto failed_completion;
981 return &acb->common;
983 failed_completion:
984 rbd_aio_release(c);
985 failed:
986 g_free(rcb);
987 if (!LIBRBD_USE_IOVEC) {
988 qemu_vfree(acb->bounce);
991 qemu_aio_unref(acb);
992 return NULL;
995 static BlockAIOCB *qemu_rbd_aio_preadv(BlockDriverState *bs,
996 uint64_t offset, uint64_t bytes,
997 QEMUIOVector *qiov, int flags,
998 BlockCompletionFunc *cb,
999 void *opaque)
1001 return rbd_start_aio(bs, offset, qiov, bytes, cb, opaque,
1002 RBD_AIO_READ);
1005 static BlockAIOCB *qemu_rbd_aio_pwritev(BlockDriverState *bs,
1006 uint64_t offset, uint64_t bytes,
1007 QEMUIOVector *qiov, int flags,
1008 BlockCompletionFunc *cb,
1009 void *opaque)
1011 return rbd_start_aio(bs, offset, qiov, bytes, cb, opaque,
1012 RBD_AIO_WRITE);
1015 #ifdef LIBRBD_SUPPORTS_AIO_FLUSH
1016 static BlockAIOCB *qemu_rbd_aio_flush(BlockDriverState *bs,
1017 BlockCompletionFunc *cb,
1018 void *opaque)
1020 return rbd_start_aio(bs, 0, NULL, 0, cb, opaque, RBD_AIO_FLUSH);
1023 #else
1025 static int qemu_rbd_co_flush(BlockDriverState *bs)
1027 #if LIBRBD_VERSION_CODE >= LIBRBD_VERSION(0, 1, 1)
1028 /* rbd_flush added in 0.1.1 */
1029 BDRVRBDState *s = bs->opaque;
1030 return rbd_flush(s->image);
1031 #else
1032 return 0;
1033 #endif
1035 #endif
1037 static int qemu_rbd_getinfo(BlockDriverState *bs, BlockDriverInfo *bdi)
1039 BDRVRBDState *s = bs->opaque;
1040 rbd_image_info_t info;
1041 int r;
1043 r = rbd_stat(s->image, &info, sizeof(info));
1044 if (r < 0) {
1045 return r;
1048 bdi->cluster_size = info.obj_size;
1049 return 0;
1052 static int64_t qemu_rbd_getlength(BlockDriverState *bs)
1054 BDRVRBDState *s = bs->opaque;
1055 rbd_image_info_t info;
1056 int r;
1058 r = rbd_stat(s->image, &info, sizeof(info));
1059 if (r < 0) {
1060 return r;
1063 return info.size;
1066 static int coroutine_fn qemu_rbd_co_truncate(BlockDriverState *bs,
1067 int64_t offset,
1068 bool exact,
1069 PreallocMode prealloc,
1070 BdrvRequestFlags flags,
1071 Error **errp)
1073 int r;
1075 if (prealloc != PREALLOC_MODE_OFF) {
1076 error_setg(errp, "Unsupported preallocation mode '%s'",
1077 PreallocMode_str(prealloc));
1078 return -ENOTSUP;
1081 r = qemu_rbd_resize(bs, offset);
1082 if (r < 0) {
1083 error_setg_errno(errp, -r, "Failed to resize file");
1084 return r;
1087 return 0;
1090 static int qemu_rbd_snap_create(BlockDriverState *bs,
1091 QEMUSnapshotInfo *sn_info)
1093 BDRVRBDState *s = bs->opaque;
1094 int r;
1096 if (sn_info->name[0] == '\0') {
1097 return -EINVAL; /* we need a name for rbd snapshots */
1101 * rbd snapshots are using the name as the user controlled unique identifier
1102 * we can't use the rbd snapid for that purpose, as it can't be set
1104 if (sn_info->id_str[0] != '\0' &&
1105 strcmp(sn_info->id_str, sn_info->name) != 0) {
1106 return -EINVAL;
1109 if (strlen(sn_info->name) >= sizeof(sn_info->id_str)) {
1110 return -ERANGE;
1113 r = rbd_snap_create(s->image, sn_info->name);
1114 if (r < 0) {
1115 error_report("failed to create snap: %s", strerror(-r));
1116 return r;
1119 return 0;
1122 static int qemu_rbd_snap_remove(BlockDriverState *bs,
1123 const char *snapshot_id,
1124 const char *snapshot_name,
1125 Error **errp)
1127 BDRVRBDState *s = bs->opaque;
1128 int r;
1130 if (!snapshot_name) {
1131 error_setg(errp, "rbd need a valid snapshot name");
1132 return -EINVAL;
1135 /* If snapshot_id is specified, it must be equal to name, see
1136 qemu_rbd_snap_list() */
1137 if (snapshot_id && strcmp(snapshot_id, snapshot_name)) {
1138 error_setg(errp,
1139 "rbd do not support snapshot id, it should be NULL or "
1140 "equal to snapshot name");
1141 return -EINVAL;
1144 r = rbd_snap_remove(s->image, snapshot_name);
1145 if (r < 0) {
1146 error_setg_errno(errp, -r, "Failed to remove the snapshot");
1148 return r;
1151 static int qemu_rbd_snap_rollback(BlockDriverState *bs,
1152 const char *snapshot_name)
1154 BDRVRBDState *s = bs->opaque;
1156 return rbd_snap_rollback(s->image, snapshot_name);
1159 static int qemu_rbd_snap_list(BlockDriverState *bs,
1160 QEMUSnapshotInfo **psn_tab)
1162 BDRVRBDState *s = bs->opaque;
1163 QEMUSnapshotInfo *sn_info, *sn_tab = NULL;
1164 int i, snap_count;
1165 rbd_snap_info_t *snaps;
1166 int max_snaps = RBD_MAX_SNAPS;
1168 do {
1169 snaps = g_new(rbd_snap_info_t, max_snaps);
1170 snap_count = rbd_snap_list(s->image, snaps, &max_snaps);
1171 if (snap_count <= 0) {
1172 g_free(snaps);
1174 } while (snap_count == -ERANGE);
1176 if (snap_count <= 0) {
1177 goto done;
1180 sn_tab = g_new0(QEMUSnapshotInfo, snap_count);
1182 for (i = 0; i < snap_count; i++) {
1183 const char *snap_name = snaps[i].name;
1185 sn_info = sn_tab + i;
1186 pstrcpy(sn_info->id_str, sizeof(sn_info->id_str), snap_name);
1187 pstrcpy(sn_info->name, sizeof(sn_info->name), snap_name);
1189 sn_info->vm_state_size = snaps[i].size;
1190 sn_info->date_sec = 0;
1191 sn_info->date_nsec = 0;
1192 sn_info->vm_clock_nsec = 0;
1194 rbd_snap_list_end(snaps);
1195 g_free(snaps);
1197 done:
1198 *psn_tab = sn_tab;
1199 return snap_count;
1202 #ifdef LIBRBD_SUPPORTS_DISCARD
1203 static BlockAIOCB *qemu_rbd_aio_pdiscard(BlockDriverState *bs,
1204 int64_t offset,
1205 int bytes,
1206 BlockCompletionFunc *cb,
1207 void *opaque)
1209 return rbd_start_aio(bs, offset, NULL, bytes, cb, opaque,
1210 RBD_AIO_DISCARD);
1212 #endif
1214 #ifdef LIBRBD_SUPPORTS_INVALIDATE
1215 static void coroutine_fn qemu_rbd_co_invalidate_cache(BlockDriverState *bs,
1216 Error **errp)
1218 BDRVRBDState *s = bs->opaque;
1219 int r = rbd_invalidate_cache(s->image);
1220 if (r < 0) {
1221 error_setg_errno(errp, -r, "Failed to invalidate the cache");
1224 #endif
1226 static QemuOptsList qemu_rbd_create_opts = {
1227 .name = "rbd-create-opts",
1228 .head = QTAILQ_HEAD_INITIALIZER(qemu_rbd_create_opts.head),
1229 .desc = {
1231 .name = BLOCK_OPT_SIZE,
1232 .type = QEMU_OPT_SIZE,
1233 .help = "Virtual disk size"
1236 .name = BLOCK_OPT_CLUSTER_SIZE,
1237 .type = QEMU_OPT_SIZE,
1238 .help = "RBD object size"
1241 .name = "password-secret",
1242 .type = QEMU_OPT_STRING,
1243 .help = "ID of secret providing the password",
1245 { /* end of list */ }
1249 static const char *const qemu_rbd_strong_runtime_opts[] = {
1250 "pool",
1251 "namespace",
1252 "image",
1253 "conf",
1254 "snapshot",
1255 "user",
1256 "server.",
1257 "password-secret",
1259 NULL
1262 static BlockDriver bdrv_rbd = {
1263 .format_name = "rbd",
1264 .instance_size = sizeof(BDRVRBDState),
1265 .bdrv_parse_filename = qemu_rbd_parse_filename,
1266 .bdrv_refresh_limits = qemu_rbd_refresh_limits,
1267 .bdrv_file_open = qemu_rbd_open,
1268 .bdrv_close = qemu_rbd_close,
1269 .bdrv_reopen_prepare = qemu_rbd_reopen_prepare,
1270 .bdrv_co_create = qemu_rbd_co_create,
1271 .bdrv_co_create_opts = qemu_rbd_co_create_opts,
1272 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1273 .bdrv_get_info = qemu_rbd_getinfo,
1274 .create_opts = &qemu_rbd_create_opts,
1275 .bdrv_getlength = qemu_rbd_getlength,
1276 .bdrv_co_truncate = qemu_rbd_co_truncate,
1277 .protocol_name = "rbd",
1279 .bdrv_aio_preadv = qemu_rbd_aio_preadv,
1280 .bdrv_aio_pwritev = qemu_rbd_aio_pwritev,
1282 #ifdef LIBRBD_SUPPORTS_AIO_FLUSH
1283 .bdrv_aio_flush = qemu_rbd_aio_flush,
1284 #else
1285 .bdrv_co_flush_to_disk = qemu_rbd_co_flush,
1286 #endif
1288 #ifdef LIBRBD_SUPPORTS_DISCARD
1289 .bdrv_aio_pdiscard = qemu_rbd_aio_pdiscard,
1290 #endif
1292 .bdrv_snapshot_create = qemu_rbd_snap_create,
1293 .bdrv_snapshot_delete = qemu_rbd_snap_remove,
1294 .bdrv_snapshot_list = qemu_rbd_snap_list,
1295 .bdrv_snapshot_goto = qemu_rbd_snap_rollback,
1296 #ifdef LIBRBD_SUPPORTS_INVALIDATE
1297 .bdrv_co_invalidate_cache = qemu_rbd_co_invalidate_cache,
1298 #endif
1300 .strong_runtime_opts = qemu_rbd_strong_runtime_opts,
1303 static void bdrv_rbd_init(void)
1305 bdrv_register(&bdrv_rbd);
1308 block_init(bdrv_rbd_init);