]> git.proxmox.com Git - mirror_qemu.git/blame - block/rbd.c
block: Convert bdrv_get_allocated_file_size() to co_wrapper
[mirror_qemu.git] / block / rbd.c
CommitLineData
f27aaf4b
CB
1/*
2 * QEMU Block driver for RADOS (Ceph)
3 *
ad32e9c0
JD
4 * Copyright (C) 2010-2011 Christian Brunner <chb@muc.de>,
5 * Josh Durgin <josh.durgin@dreamhost.com>
f27aaf4b
CB
6 *
7 * This work is licensed under the terms of the GNU GPL, version 2. See
8 * the COPYING file in the top-level directory.
9 *
6b620ca3
PB
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.
f27aaf4b
CB
12 */
13
80c71a24 14#include "qemu/osdep.h"
ad32e9c0 15
2836284d 16#include <rbd/librbd.h>
da34e65c 17#include "qapi/error.h"
1de7afc9 18#include "qemu/error-report.h"
0b8fa32f 19#include "qemu/module.h"
922a01a0 20#include "qemu/option.h"
e2c1c34f 21#include "block/block-io.h"
737e150e 22#include "block/block_int.h"
609f45ea 23#include "block/qdict.h"
60390a21 24#include "crypto/secret.h"
f348b6d1 25#include "qemu/cutils.h"
e4ec5ad4 26#include "sysemu/replay.h"
c7cacb3e 27#include "qapi/qmp/qstring.h"
452fcdbc 28#include "qapi/qmp/qdict.h"
e98c6961 29#include "qapi/qmp/qjson.h"
47e6b297 30#include "qapi/qmp/qlist.h"
4bfb2741
KW
31#include "qapi/qobject-input-visitor.h"
32#include "qapi/qapi-visit-block-core.h"
f27aaf4b 33
f27aaf4b
CB
34/*
35 * When specifying the image filename use:
36 *
fab5cf59 37 * rbd:poolname/devicename[@snapshotname][:option1=value1[:option2=value2...]]
f27aaf4b 38 *
9e1fbcde 39 * poolname must be the name of an existing rados pool.
f27aaf4b 40 *
9e1fbcde 41 * devicename is the name of the rbd image.
f27aaf4b 42 *
9e1fbcde
SW
43 * Each option given is used to configure rados, and may be any valid
44 * Ceph option, "id", or "conf".
fab5cf59 45 *
9e1fbcde
SW
46 * The "id" option indicates what user we should authenticate as to
47 * the Ceph cluster. If it is excluded we will use the Ceph default
48 * (normally 'admin').
f27aaf4b 49 *
9e1fbcde
SW
50 * The "conf" option specifies a Ceph configuration file to read. If
51 * it is not specified, we will read from the default Ceph locations
52 * (e.g., /etc/ceph/ceph.conf). To avoid reading _any_ configuration
53 * file, specify conf=/dev/null.
f27aaf4b 54 *
9e1fbcde
SW
55 * Configuration values containing :, @, or = can be escaped with a
56 * leading "\".
f27aaf4b
CB
57 */
58
59#define OBJ_MAX_SIZE (1UL << OBJ_DEFAULT_OBJ_ORDER)
60
ad32e9c0
JD
61#define RBD_MAX_SNAPS 100
62
42e4ac9e
OO
63#define RBD_ENCRYPTION_LUKS_HEADER_VERIFICATION_LEN 8
64
65static const char rbd_luks_header_verification[
66 RBD_ENCRYPTION_LUKS_HEADER_VERIFICATION_LEN] = {
67 'L', 'U', 'K', 'S', 0xBA, 0xBE, 0, 1
68};
69
70static const char rbd_luks2_header_verification[
71 RBD_ENCRYPTION_LUKS_HEADER_VERIFICATION_LEN] = {
72 'L', 'U', 'K', 'S', 0xBA, 0xBE, 0, 2
73};
74
787f3133
JD
75typedef enum {
76 RBD_AIO_READ,
77 RBD_AIO_WRITE,
dc7588c1 78 RBD_AIO_DISCARD,
c56ac27d
PL
79 RBD_AIO_FLUSH,
80 RBD_AIO_WRITE_ZEROES
787f3133
JD
81} RBDAIOCmd;
82
f27aaf4b 83typedef struct BDRVRBDState {
ad32e9c0
JD
84 rados_t cluster;
85 rados_ioctx_t io_ctx;
86 rbd_image_t image;
80b61a27 87 char *image_name;
ad32e9c0 88 char *snap;
19ae9ae0 89 char *namespace;
d24f8023 90 uint64_t image_size;
832a93dc 91 uint64_t object_size;
f27aaf4b
CB
92} BDRVRBDState;
93
c3e5fac5
PL
94typedef struct RBDTask {
95 BlockDriverState *bs;
96 Coroutine *co;
97 bool complete;
98 int64_t ret;
99} RBDTask;
100
0347a8fd
PL
101typedef struct RBDDiffIterateReq {
102 uint64_t offs;
103 uint64_t bytes;
104 bool exists;
105} RBDDiffIterateReq;
106
aa045c2d
KW
107static int qemu_rbd_connect(rados_t *cluster, rados_ioctx_t *io_ctx,
108 BlockdevOptionsRbd *opts, bool cache,
109 const char *keypairs, const char *secretid,
110 Error **errp);
111
2b99cfce
CK
112static char *qemu_rbd_strchr(char *src, char delim)
113{
114 char *p;
115
116 for (p = src; *p; ++p) {
117 if (*p == delim) {
118 return p;
119 }
120 if (*p == '\\' && p[1] != '\0') {
121 ++p;
122 }
123 }
124
125 return NULL;
126}
127
128
730b00bb 129static char *qemu_rbd_next_tok(char *src, char delim, char **p)
f27aaf4b 130{
f27aaf4b
CB
131 char *end;
132
133 *p = NULL;
134
2b99cfce
CK
135 end = qemu_rbd_strchr(src, delim);
136 if (end) {
8efb339d
MA
137 *p = end + 1;
138 *end = '\0';
139 }
7830f909 140 return src;
f27aaf4b
CB
141}
142
16a06b24
SW
143static void qemu_rbd_unescape(char *src)
144{
145 char *p;
146
147 for (p = src; *src; ++src, ++p) {
148 if (*src == '\\' && src[1] != '\0') {
149 src++;
150 }
151 *p = *src;
152 }
153 *p = '\0';
154}
155
c7cacb3e
JC
156static void qemu_rbd_parse_filename(const char *filename, QDict *options,
157 Error **errp)
f27aaf4b
CB
158{
159 const char *start;
e98c6961
EB
160 char *p, *buf;
161 QList *keypairs = NULL;
19ae9ae0 162 char *found_str, *image_name;
f27aaf4b
CB
163
164 if (!strstart(filename, "rbd:", &start)) {
d61563b2 165 error_setg(errp, "File name must start with 'rbd:'");
c7cacb3e 166 return;
f27aaf4b
CB
167 }
168
7267c094 169 buf = g_strdup(start);
f27aaf4b
CB
170 p = buf;
171
730b00bb 172 found_str = qemu_rbd_next_tok(p, '/', &p);
7830f909 173 if (!p) {
7830f909 174 error_setg(errp, "Pool name is required");
f27aaf4b
CB
175 goto done;
176 }
7830f909 177 qemu_rbd_unescape(found_str);
46f5ac20 178 qdict_put_str(options, "pool", found_str);
fab5cf59 179
2b99cfce 180 if (qemu_rbd_strchr(p, '@')) {
19ae9ae0 181 image_name = qemu_rbd_next_tok(p, '@', &p);
7830f909 182
730b00bb 183 found_str = qemu_rbd_next_tok(p, ':', &p);
7830f909 184 qemu_rbd_unescape(found_str);
46f5ac20 185 qdict_put_str(options, "snapshot", found_str);
fab5cf59 186 } else {
19ae9ae0
FF
187 image_name = qemu_rbd_next_tok(p, ':', &p);
188 }
189 /* Check for namespace in the image_name */
2b99cfce 190 if (qemu_rbd_strchr(image_name, '/')) {
19ae9ae0 191 found_str = qemu_rbd_next_tok(image_name, '/', &image_name);
7830f909 192 qemu_rbd_unescape(found_str);
19ae9ae0
FF
193 qdict_put_str(options, "namespace", found_str);
194 } else {
195 qdict_put_str(options, "namespace", "");
f27aaf4b 196 }
19ae9ae0
FF
197 qemu_rbd_unescape(image_name);
198 qdict_put_str(options, "image", image_name);
7830f909 199 if (!p) {
f27aaf4b
CB
200 goto done;
201 }
202
c7cacb3e
JC
203 /* The following are essentially all key/value pairs, and we treat
204 * 'id' and 'conf' a bit special. Key/value pairs may be in any order. */
205 while (p) {
206 char *name, *value;
730b00bb 207 name = qemu_rbd_next_tok(p, '=', &p);
c7cacb3e
JC
208 if (!p) {
209 error_setg(errp, "conf option %s has no value", name);
210 break;
7c7e9df0 211 }
c7cacb3e
JC
212
213 qemu_rbd_unescape(name);
214
730b00bb 215 value = qemu_rbd_next_tok(p, ':', &p);
c7cacb3e
JC
216 qemu_rbd_unescape(value);
217
218 if (!strcmp(name, "conf")) {
46f5ac20 219 qdict_put_str(options, "conf", value);
c7cacb3e 220 } else if (!strcmp(name, "id")) {
46f5ac20 221 qdict_put_str(options, "user", value);
c7cacb3e 222 } else {
e98c6961
EB
223 /*
224 * We pass these internally to qemu_rbd_set_keypairs(), so
225 * we can get away with the simpler list of [ "key1",
226 * "value1", "key2", "value2" ] rather than a raw dict
227 * { "key1": "value1", "key2": "value2" } where we can't
228 * guarantee order, or even a more correct but complex
229 * [ { "key1": "value1" }, { "key2": "value2" } ]
230 */
231 if (!keypairs) {
232 keypairs = qlist_new();
c7cacb3e 233 }
46f5ac20
EB
234 qlist_append_str(keypairs, name);
235 qlist_append_str(keypairs, value);
c7cacb3e 236 }
7c7e9df0 237 }
c7cacb3e 238
e98c6961
EB
239 if (keypairs) {
240 qdict_put(options, "=keyvalue-pairs",
eab3a467 241 qstring_from_gstring(qobject_to_json(QOBJECT(keypairs))));
c7cacb3e
JC
242 }
243
c7cacb3e 244done:
c7cacb3e 245 g_free(buf);
cb3e7f08 246 qobject_unref(keypairs);
c7cacb3e 247 return;
7c7e9df0
SW
248}
249
d083f954 250static int qemu_rbd_set_auth(rados_t cluster, BlockdevOptionsRbd *opts,
60390a21
DB
251 Error **errp)
252{
d083f954 253 char *key, *acr;
a3699de4
MA
254 int r;
255 GString *accu;
256 RbdAuthModeList *auth;
257
d083f954
MA
258 if (opts->key_secret) {
259 key = qcrypto_secret_lookup_as_base64(opts->key_secret, errp);
260 if (!key) {
261 return -EIO;
262 }
263 r = rados_conf_set(cluster, "key", key);
264 g_free(key);
265 if (r < 0) {
266 error_setg_errno(errp, -r, "Could not set 'key'");
267 return r;
a3699de4 268 }
60390a21
DB
269 }
270
a3699de4
MA
271 if (opts->has_auth_client_required) {
272 accu = g_string_new("");
273 for (auth = opts->auth_client_required; auth; auth = auth->next) {
274 if (accu->str[0]) {
275 g_string_append_c(accu, ';');
276 }
277 g_string_append(accu, RbdAuthMode_str(auth->value));
278 }
279 acr = g_string_free(accu, FALSE);
280 r = rados_conf_set(cluster, "auth_client_required", acr);
281 g_free(acr);
282 if (r < 0) {
283 error_setg_errno(errp, -r,
284 "Could not set 'auth_client_required'");
285 return r;
286 }
287 }
60390a21
DB
288
289 return 0;
290}
291
e98c6961 292static int qemu_rbd_set_keypairs(rados_t cluster, const char *keypairs_json,
c7cacb3e 293 Error **errp)
fab5cf59 294{
e98c6961
EB
295 QList *keypairs;
296 QString *name;
297 QString *value;
298 const char *key;
299 size_t remaining;
fab5cf59
JD
300 int ret = 0;
301
e98c6961
EB
302 if (!keypairs_json) {
303 return ret;
304 }
7dc847eb
HR
305 keypairs = qobject_to(QList,
306 qobject_from_json(keypairs_json, &error_abort));
e98c6961
EB
307 remaining = qlist_size(keypairs) / 2;
308 assert(remaining);
309
310 while (remaining--) {
7dc847eb
HR
311 name = qobject_to(QString, qlist_pop(keypairs));
312 value = qobject_to(QString, qlist_pop(keypairs));
e98c6961
EB
313 assert(name && value);
314 key = qstring_get_str(name);
315
316 ret = rados_conf_set(cluster, key, qstring_get_str(value));
cb3e7f08 317 qobject_unref(value);
c7cacb3e 318 if (ret < 0) {
e98c6961 319 error_setg_errno(errp, -ret, "invalid conf option %s", key);
cb3e7f08 320 qobject_unref(name);
c7cacb3e
JC
321 ret = -EINVAL;
322 break;
fab5cf59 323 }
cb3e7f08 324 qobject_unref(name);
fab5cf59
JD
325 }
326
cb3e7f08 327 qobject_unref(keypairs);
fab5cf59
JD
328 return ret;
329}
330
42e4ac9e
OO
331#ifdef LIBRBD_SUPPORTS_ENCRYPTION
332static int qemu_rbd_convert_luks_options(
333 RbdEncryptionOptionsLUKSBase *luks_opts,
334 char **passphrase,
335 size_t *passphrase_len,
336 Error **errp)
337{
338 return qcrypto_secret_lookup(luks_opts->key_secret, (uint8_t **)passphrase,
339 passphrase_len, errp);
340}
341
342static int qemu_rbd_convert_luks_create_options(
343 RbdEncryptionCreateOptionsLUKSBase *luks_opts,
344 rbd_encryption_algorithm_t *alg,
345 char **passphrase,
346 size_t *passphrase_len,
347 Error **errp)
348{
349 int r = 0;
350
351 r = qemu_rbd_convert_luks_options(
352 qapi_RbdEncryptionCreateOptionsLUKSBase_base(luks_opts),
353 passphrase, passphrase_len, errp);
354 if (r < 0) {
355 return r;
356 }
357
358 if (luks_opts->has_cipher_alg) {
359 switch (luks_opts->cipher_alg) {
360 case QCRYPTO_CIPHER_ALG_AES_128: {
361 *alg = RBD_ENCRYPTION_ALGORITHM_AES128;
362 break;
363 }
364 case QCRYPTO_CIPHER_ALG_AES_256: {
365 *alg = RBD_ENCRYPTION_ALGORITHM_AES256;
366 break;
367 }
368 default: {
369 r = -ENOTSUP;
370 error_setg_errno(errp, -r, "unknown encryption algorithm: %u",
371 luks_opts->cipher_alg);
372 return r;
373 }
374 }
375 } else {
376 /* default alg */
377 *alg = RBD_ENCRYPTION_ALGORITHM_AES256;
378 }
379
380 return 0;
381}
382
383static int qemu_rbd_encryption_format(rbd_image_t image,
384 RbdEncryptionCreateOptions *encrypt,
385 Error **errp)
386{
387 int r = 0;
388 g_autofree char *passphrase = NULL;
389 size_t passphrase_len;
390 rbd_encryption_format_t format;
391 rbd_encryption_options_t opts;
392 rbd_encryption_luks1_format_options_t luks_opts;
393 rbd_encryption_luks2_format_options_t luks2_opts;
394 size_t opts_size;
395 uint64_t raw_size, effective_size;
396
397 r = rbd_get_size(image, &raw_size);
398 if (r < 0) {
399 error_setg_errno(errp, -r, "cannot get raw image size");
400 return r;
401 }
402
403 switch (encrypt->format) {
404 case RBD_IMAGE_ENCRYPTION_FORMAT_LUKS: {
405 memset(&luks_opts, 0, sizeof(luks_opts));
406 format = RBD_ENCRYPTION_FORMAT_LUKS1;
407 opts = &luks_opts;
408 opts_size = sizeof(luks_opts);
409 r = qemu_rbd_convert_luks_create_options(
410 qapi_RbdEncryptionCreateOptionsLUKS_base(&encrypt->u.luks),
411 &luks_opts.alg, &passphrase, &passphrase_len, errp);
412 if (r < 0) {
413 return r;
414 }
415 luks_opts.passphrase = passphrase;
416 luks_opts.passphrase_size = passphrase_len;
417 break;
418 }
419 case RBD_IMAGE_ENCRYPTION_FORMAT_LUKS2: {
420 memset(&luks2_opts, 0, sizeof(luks2_opts));
421 format = RBD_ENCRYPTION_FORMAT_LUKS2;
422 opts = &luks2_opts;
423 opts_size = sizeof(luks2_opts);
424 r = qemu_rbd_convert_luks_create_options(
425 qapi_RbdEncryptionCreateOptionsLUKS2_base(
426 &encrypt->u.luks2),
427 &luks2_opts.alg, &passphrase, &passphrase_len, errp);
428 if (r < 0) {
429 return r;
430 }
431 luks2_opts.passphrase = passphrase;
432 luks2_opts.passphrase_size = passphrase_len;
433 break;
434 }
435 default: {
436 r = -ENOTSUP;
437 error_setg_errno(
438 errp, -r, "unknown image encryption format: %u",
439 encrypt->format);
440 return r;
441 }
442 }
443
444 r = rbd_encryption_format(image, format, opts, opts_size);
445 if (r < 0) {
446 error_setg_errno(errp, -r, "encryption format fail");
447 return r;
448 }
449
450 r = rbd_get_size(image, &effective_size);
451 if (r < 0) {
452 error_setg_errno(errp, -r, "cannot get effective image size");
453 return r;
454 }
455
456 r = rbd_resize(image, raw_size + (raw_size - effective_size));
457 if (r < 0) {
458 error_setg_errno(errp, -r, "cannot resize image after format");
459 return r;
460 }
461
462 return 0;
463}
464
465static int qemu_rbd_encryption_load(rbd_image_t image,
466 RbdEncryptionOptions *encrypt,
467 Error **errp)
468{
469 int r = 0;
470 g_autofree char *passphrase = NULL;
471 size_t passphrase_len;
472 rbd_encryption_luks1_format_options_t luks_opts;
473 rbd_encryption_luks2_format_options_t luks2_opts;
474 rbd_encryption_format_t format;
475 rbd_encryption_options_t opts;
476 size_t opts_size;
477
478 switch (encrypt->format) {
479 case RBD_IMAGE_ENCRYPTION_FORMAT_LUKS: {
480 memset(&luks_opts, 0, sizeof(luks_opts));
481 format = RBD_ENCRYPTION_FORMAT_LUKS1;
482 opts = &luks_opts;
483 opts_size = sizeof(luks_opts);
484 r = qemu_rbd_convert_luks_options(
485 qapi_RbdEncryptionOptionsLUKS_base(&encrypt->u.luks),
486 &passphrase, &passphrase_len, errp);
487 if (r < 0) {
488 return r;
489 }
490 luks_opts.passphrase = passphrase;
491 luks_opts.passphrase_size = passphrase_len;
492 break;
493 }
494 case RBD_IMAGE_ENCRYPTION_FORMAT_LUKS2: {
495 memset(&luks2_opts, 0, sizeof(luks2_opts));
496 format = RBD_ENCRYPTION_FORMAT_LUKS2;
497 opts = &luks2_opts;
498 opts_size = sizeof(luks2_opts);
499 r = qemu_rbd_convert_luks_options(
500 qapi_RbdEncryptionOptionsLUKS2_base(&encrypt->u.luks2),
501 &passphrase, &passphrase_len, errp);
502 if (r < 0) {
503 return r;
504 }
505 luks2_opts.passphrase = passphrase;
506 luks2_opts.passphrase_size = passphrase_len;
507 break;
508 }
509 default: {
510 r = -ENOTSUP;
511 error_setg_errno(
512 errp, -r, "unknown image encryption format: %u",
513 encrypt->format);
514 return r;
515 }
516 }
517
518 r = rbd_encryption_load(image, format, opts, opts_size);
519 if (r < 0) {
520 error_setg_errno(errp, -r, "encryption load fail");
521 return r;
522 }
523
524 return 0;
525}
526#endif
527
d083f954 528/* FIXME Deprecate and remove keypairs or make it available in QMP. */
1bebea37
KW
529static int qemu_rbd_do_create(BlockdevCreateOptions *options,
530 const char *keypairs, const char *password_secret,
531 Error **errp)
f27aaf4b 532{
1bebea37 533 BlockdevCreateOptionsRbd *opts = &options->u.rbd;
ad32e9c0
JD
534 rados_t cluster;
535 rados_ioctx_t io_ctx;
1bebea37
KW
536 int obj_order = 0;
537 int ret;
538
539 assert(options->driver == BLOCKDEV_DRIVER_RBD);
54fde4ff 540 if (opts->location->snapshot) {
1bebea37
KW
541 error_setg(errp, "Can't use snapshot name for image creation");
542 return -EINVAL;
543 }
f27aaf4b 544
42e4ac9e 545#ifndef LIBRBD_SUPPORTS_ENCRYPTION
54fde4ff 546 if (opts->encrypt) {
42e4ac9e
OO
547 error_setg(errp, "RBD library does not support image encryption");
548 return -ENOTSUP;
549 }
550#endif
551
1bebea37
KW
552 if (opts->has_cluster_size) {
553 int64_t objsize = opts->cluster_size;
bd0cf596
CL
554 if ((objsize - 1) & objsize) { /* not a power of 2? */
555 error_setg(errp, "obj size needs to be power of 2");
1bebea37 556 return -EINVAL;
bd0cf596
CL
557 }
558 if (objsize < 4096) {
559 error_setg(errp, "obj size too small");
1bebea37 560 return -EINVAL;
f27aaf4b 561 }
786a4ea8 562 obj_order = ctz32(objsize);
f27aaf4b
CB
563 }
564
aa045c2d
KW
565 ret = qemu_rbd_connect(&cluster, &io_ctx, opts->location, false, keypairs,
566 password_secret, errp);
87cd3d20 567 if (ret < 0) {
1bebea37 568 return ret;
f27aaf4b
CB
569 }
570
1bebea37 571 ret = rbd_create(io_ctx, opts->location->image, opts->size, &obj_order);
87cd3d20
VU
572 if (ret < 0) {
573 error_setg_errno(errp, -ret, "error rbd create");
aa045c2d 574 goto out;
87cd3d20 575 }
f27aaf4b 576
42e4ac9e 577#ifdef LIBRBD_SUPPORTS_ENCRYPTION
54fde4ff 578 if (opts->encrypt) {
42e4ac9e
OO
579 rbd_image_t image;
580
581 ret = rbd_open(io_ctx, opts->location->image, &image, NULL);
582 if (ret < 0) {
583 error_setg_errno(errp, -ret,
584 "error opening image '%s' for encryption format",
585 opts->location->image);
586 goto out;
587 }
588
589 ret = qemu_rbd_encryption_format(image, opts->encrypt, errp);
590 rbd_close(image);
591 if (ret < 0) {
592 /* encryption format fail, try removing the image */
593 rbd_remove(io_ctx, opts->location->image);
594 goto out;
595 }
596 }
597#endif
598
1bebea37 599 ret = 0;
aa045c2d
KW
600out:
601 rados_ioctx_destroy(io_ctx);
e38f643a 602 rados_shutdown(cluster);
1bebea37
KW
603 return ret;
604}
605
606static int qemu_rbd_co_create(BlockdevCreateOptions *options, Error **errp)
607{
608 return qemu_rbd_do_create(options, NULL, NULL, errp);
609}
610
42e4ac9e
OO
611static int qemu_rbd_extract_encryption_create_options(
612 QemuOpts *opts,
613 RbdEncryptionCreateOptions **spec,
614 Error **errp)
615{
616 QDict *opts_qdict;
617 QDict *encrypt_qdict;
618 Visitor *v;
619 int ret = 0;
620
621 opts_qdict = qemu_opts_to_qdict(opts, NULL);
622 qdict_extract_subqdict(opts_qdict, &encrypt_qdict, "encrypt.");
623 qobject_unref(opts_qdict);
624 if (!qdict_size(encrypt_qdict)) {
625 *spec = NULL;
626 goto exit;
627 }
628
629 /* Convert options into a QAPI object */
630 v = qobject_input_visitor_new_flat_confused(encrypt_qdict, errp);
631 if (!v) {
632 ret = -EINVAL;
633 goto exit;
634 }
635
636 visit_type_RbdEncryptionCreateOptions(v, NULL, spec, errp);
637 visit_free(v);
638 if (!*spec) {
639 ret = -EINVAL;
640 goto exit;
641 }
642
643exit:
644 qobject_unref(encrypt_qdict);
645 return ret;
646}
647
b92902df
ML
648static int coroutine_fn qemu_rbd_co_create_opts(BlockDriver *drv,
649 const char *filename,
1bebea37
KW
650 QemuOpts *opts,
651 Error **errp)
652{
653 BlockdevCreateOptions *create_options;
654 BlockdevCreateOptionsRbd *rbd_opts;
655 BlockdevOptionsRbd *loc;
42e4ac9e 656 RbdEncryptionCreateOptions *encrypt = NULL;
1bebea37
KW
657 Error *local_err = NULL;
658 const char *keypairs, *password_secret;
659 QDict *options = NULL;
660 int ret = 0;
661
662 create_options = g_new0(BlockdevCreateOptions, 1);
663 create_options->driver = BLOCKDEV_DRIVER_RBD;
664 rbd_opts = &create_options->u.rbd;
665
666 rbd_opts->location = g_new0(BlockdevOptionsRbd, 1);
667
668 password_secret = qemu_opt_get(opts, "password-secret");
669
670 /* Read out options */
671 rbd_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
672 BDRV_SECTOR_SIZE);
673 rbd_opts->cluster_size = qemu_opt_get_size_del(opts,
674 BLOCK_OPT_CLUSTER_SIZE, 0);
675 rbd_opts->has_cluster_size = (rbd_opts->cluster_size != 0);
676
677 options = qdict_new();
678 qemu_rbd_parse_filename(filename, options, &local_err);
679 if (local_err) {
680 ret = -EINVAL;
681 error_propagate(errp, local_err);
682 goto exit;
683 }
684
42e4ac9e
OO
685 ret = qemu_rbd_extract_encryption_create_options(opts, &encrypt, errp);
686 if (ret < 0) {
687 goto exit;
688 }
689 rbd_opts->encrypt = encrypt;
42e4ac9e 690
1bebea37
KW
691 /*
692 * Caution: while qdict_get_try_str() is fine, getting non-string
693 * types would require more care. When @options come from -blockdev
694 * or blockdev_add, its members are typed according to the QAPI
695 * schema, but when they come from -drive, they're all QString.
696 */
697 loc = rbd_opts->location;
19ae9ae0
FF
698 loc->pool = g_strdup(qdict_get_try_str(options, "pool"));
699 loc->conf = g_strdup(qdict_get_try_str(options, "conf"));
19ae9ae0 700 loc->user = g_strdup(qdict_get_try_str(options, "user"));
19ae9ae0
FF
701 loc->q_namespace = g_strdup(qdict_get_try_str(options, "namespace"));
702 loc->image = g_strdup(qdict_get_try_str(options, "image"));
703 keypairs = qdict_get_try_str(options, "=keyvalue-pairs");
1bebea37
KW
704
705 ret = qemu_rbd_do_create(create_options, keypairs, password_secret, errp);
706 if (ret < 0) {
707 goto exit;
708 }
c7cacb3e
JC
709
710exit:
cb3e7f08 711 qobject_unref(options);
1bebea37 712 qapi_free_BlockdevCreateOptions(create_options);
f27aaf4b
CB
713 return ret;
714}
715
4bfb2741 716static char *qemu_rbd_mon_host(BlockdevOptionsRbd *opts, Error **errp)
0a55679b 717{
4bfb2741 718 const char **vals;
2836284d
MA
719 const char *host, *port;
720 char *rados_str;
4bfb2741
KW
721 InetSocketAddressBaseList *p;
722 int i, cnt;
723
724 if (!opts->has_server) {
725 return NULL;
726 }
727
728 for (cnt = 0, p = opts->server; p; p = p->next) {
729 cnt++;
730 }
731
732 vals = g_new(const char *, cnt + 1);
733
734 for (i = 0, p = opts->server; p; p = p->next, i++) {
735 host = p->value->host;
736 port = p->value->port;
0a55679b 737
2836284d 738 if (strchr(host, ':')) {
4bfb2741 739 vals[i] = g_strdup_printf("[%s]:%s", host, port);
0a55679b 740 } else {
4bfb2741 741 vals[i] = g_strdup_printf("%s:%s", host, port);
0a55679b 742 }
0a55679b 743 }
2836284d 744 vals[i] = NULL;
0a55679b 745
2836284d 746 rados_str = i ? g_strjoinv(";", (char **)vals) : NULL;
2836284d 747 g_strfreev((char **)vals);
0a55679b
JC
748 return rados_str;
749}
750
3d9136f9 751static int qemu_rbd_connect(rados_t *cluster, rados_ioctx_t *io_ctx,
4bfb2741 752 BlockdevOptionsRbd *opts, bool cache,
4ff45049
KW
753 const char *keypairs, const char *secretid,
754 Error **errp)
f27aaf4b 755{
0a55679b 756 char *mon_host = NULL;
3d9136f9 757 Error *local_err = NULL;
f27aaf4b
CB
758 int r;
759
d083f954
MA
760 if (secretid) {
761 if (opts->key_secret) {
762 error_setg(errp,
763 "Legacy 'password-secret' clashes with 'key-secret'");
764 return -EINVAL;
765 }
766 opts->key_secret = g_strdup(secretid);
d083f954
MA
767 }
768
4bfb2741 769 mon_host = qemu_rbd_mon_host(opts, &local_err);
0a55679b
JC
770 if (local_err) {
771 error_propagate(errp, local_err);
772 r = -EINVAL;
c1c1f6cf 773 goto out;
0a55679b
JC
774 }
775
4bfb2741 776 r = rados_create(cluster, opts->user);
ad32e9c0 777 if (r < 0) {
87cd3d20 778 error_setg_errno(errp, -r, "error initializing");
c1c1f6cf 779 goto out;
f27aaf4b
CB
780 }
781
c7cacb3e 782 /* try default location when conf=NULL, but ignore failure */
4bfb2741 783 r = rados_conf_read_file(*cluster, opts->conf);
54fde4ff 784 if (opts->conf && r < 0) {
4bfb2741 785 error_setg_errno(errp, -r, "error reading conf file %s", opts->conf);
c7cacb3e 786 goto failed_shutdown;
99a3c89d
JD
787 }
788
3d9136f9 789 r = qemu_rbd_set_keypairs(*cluster, keypairs, errp);
c7cacb3e
JC
790 if (r < 0) {
791 goto failed_shutdown;
99a3c89d
JD
792 }
793
0a55679b 794 if (mon_host) {
3d9136f9 795 r = rados_conf_set(*cluster, "mon_host", mon_host);
0a55679b
JC
796 if (r < 0) {
797 goto failed_shutdown;
798 }
799 }
800
d083f954
MA
801 r = qemu_rbd_set_auth(*cluster, opts, errp);
802 if (r < 0) {
60390a21
DB
803 goto failed_shutdown;
804 }
805
b11f38fc
JD
806 /*
807 * Fallback to more conservative semantics if setting cache
808 * options fails. Ignore errors from setting rbd_cache because the
809 * only possible error is that the option does not exist, and
810 * librbd defaults to no caching. If write through caching cannot
811 * be set up, fall back to no caching.
812 */
3d9136f9
KW
813 if (cache) {
814 rados_conf_set(*cluster, "rbd_cache", "true");
b11f38fc 815 } else {
3d9136f9 816 rados_conf_set(*cluster, "rbd_cache", "false");
b11f38fc
JD
817 }
818
3d9136f9 819 r = rados_connect(*cluster);
ad32e9c0 820 if (r < 0) {
87cd3d20 821 error_setg_errno(errp, -r, "error connecting");
eb93d5d9 822 goto failed_shutdown;
f27aaf4b
CB
823 }
824
4bfb2741 825 r = rados_ioctx_create(*cluster, opts->pool, io_ctx);
ad32e9c0 826 if (r < 0) {
4bfb2741 827 error_setg_errno(errp, -r, "error opening pool %s", opts->pool);
eb93d5d9 828 goto failed_shutdown;
f27aaf4b 829 }
66dc5f96
SG
830
831#ifdef HAVE_RBD_NAMESPACE_EXISTS
54fde4ff 832 if (opts->q_namespace && strlen(opts->q_namespace) > 0) {
66dc5f96
SG
833 bool exists;
834
835 r = rbd_namespace_exists(*io_ctx, opts->q_namespace, &exists);
836 if (r < 0) {
837 error_setg_errno(errp, -r, "error checking namespace");
838 goto failed_ioctx_destroy;
839 }
840
841 if (!exists) {
842 error_setg(errp, "namespace '%s' does not exist",
843 opts->q_namespace);
844 r = -ENOENT;
845 goto failed_ioctx_destroy;
846 }
847 }
848#endif
849
19ae9ae0
FF
850 /*
851 * Set the namespace after opening the io context on the pool,
852 * if nspace == NULL or if nspace == "", it is just as we did nothing
853 */
854 rados_ioctx_set_namespace(*io_ctx, opts->q_namespace);
f27aaf4b 855
c1c1f6cf
SG
856 r = 0;
857 goto out;
3d9136f9 858
66dc5f96
SG
859#ifdef HAVE_RBD_NAMESPACE_EXISTS
860failed_ioctx_destroy:
861 rados_ioctx_destroy(*io_ctx);
862#endif
3d9136f9
KW
863failed_shutdown:
864 rados_shutdown(*cluster);
c1c1f6cf 865out:
3d9136f9
KW
866 g_free(mon_host);
867 return r;
868}
869
f24b03b5
JC
870static int qemu_rbd_convert_options(QDict *options, BlockdevOptionsRbd **opts,
871 Error **errp)
872{
873 Visitor *v;
f24b03b5
JC
874
875 /* Convert the remaining options into a QAPI object */
876 v = qobject_input_visitor_new_flat_confused(options, errp);
877 if (!v) {
878 return -EINVAL;
879 }
880
b11a093c 881 visit_type_BlockdevOptionsRbd(v, NULL, opts, errp);
f24b03b5 882 visit_free(v);
b11a093c 883 if (!opts) {
f24b03b5
JC
884 return -EINVAL;
885 }
886
887 return 0;
888}
889
084d1d13
JC
890static int qemu_rbd_attempt_legacy_options(QDict *options,
891 BlockdevOptionsRbd **opts,
892 char **keypairs)
893{
894 char *filename;
895 int r;
896
897 filename = g_strdup(qdict_get_try_str(options, "filename"));
898 if (!filename) {
899 return -EINVAL;
900 }
901 qdict_del(options, "filename");
902
903 qemu_rbd_parse_filename(filename, options, NULL);
904
905 /* keypairs freed by caller */
906 *keypairs = g_strdup(qdict_get_try_str(options, "=keyvalue-pairs"));
907 if (*keypairs) {
908 qdict_del(options, "=keyvalue-pairs");
909 }
910
911 r = qemu_rbd_convert_options(options, opts, NULL);
912
913 g_free(filename);
914 return r;
915}
916
3d9136f9
KW
917static int qemu_rbd_open(BlockDriverState *bs, QDict *options, int flags,
918 Error **errp)
919{
920 BDRVRBDState *s = bs->opaque;
4bfb2741 921 BlockdevOptionsRbd *opts = NULL;
bfb15b4b 922 const QDictEntry *e;
3d9136f9 923 Error *local_err = NULL;
4ff45049 924 char *keypairs, *secretid;
832a93dc 925 rbd_image_info_t info;
3d9136f9
KW
926 int r;
927
4ff45049
KW
928 keypairs = g_strdup(qdict_get_try_str(options, "=keyvalue-pairs"));
929 if (keypairs) {
930 qdict_del(options, "=keyvalue-pairs");
931 }
932
933 secretid = g_strdup(qdict_get_try_str(options, "password-secret"));
934 if (secretid) {
935 qdict_del(options, "password-secret");
936 }
937
f24b03b5 938 r = qemu_rbd_convert_options(options, &opts, &local_err);
4bfb2741 939 if (local_err) {
084d1d13
JC
940 /* If keypairs are present, that means some options are present in
941 * the modern option format. Don't attempt to parse legacy option
942 * formats, as we won't support mixed usage. */
943 if (keypairs) {
944 error_propagate(errp, local_err);
945 goto out;
946 }
947
948 /* If the initial attempt to convert and process the options failed,
949 * we may be attempting to open an image file that has the rbd options
950 * specified in the older format consisting of all key/value pairs
951 * encoded in the filename. Go ahead and attempt to parse the
952 * filename, and see if we can pull out the required options. */
953 r = qemu_rbd_attempt_legacy_options(options, &opts, &keypairs);
954 if (r < 0) {
955 /* Propagate the original error, not the legacy parsing fallback
956 * error, as the latter was just a best-effort attempt. */
957 error_propagate(errp, local_err);
958 goto out;
959 }
960 /* Take care whenever deciding to actually deprecate; once this ability
961 * is removed, we will not be able to open any images with legacy-styled
962 * backing image strings. */
5197f445
MA
963 warn_report("RBD options encoded in the filename as keyvalue pairs "
964 "is deprecated");
4bfb2741
KW
965 }
966
bfb15b4b
JC
967 /* Remove the processed options from the QDict (the visitor processes
968 * _all_ options in the QDict) */
969 while ((e = qdict_first(options))) {
970 qdict_del(options, e->key);
971 }
972
d41a5588
KW
973 r = qemu_rbd_connect(&s->cluster, &s->io_ctx, opts,
974 !(flags & BDRV_O_NOCACHE), keypairs, secretid, errp);
3d9136f9 975 if (r < 0) {
4ff45049 976 goto out;
3d9136f9
KW
977 }
978
d41a5588
KW
979 s->snap = g_strdup(opts->snapshot);
980 s->image_name = g_strdup(opts->image);
981
e2b8247a 982 /* rbd_open is always r/w */
80b61a27 983 r = rbd_open(s->io_ctx, s->image_name, &s->image, s->snap);
f27aaf4b 984 if (r < 0) {
80b61a27
JC
985 error_setg_errno(errp, -r, "error reading header from %s",
986 s->image_name);
eb93d5d9 987 goto failed_open;
f27aaf4b
CB
988 }
989
54fde4ff 990 if (opts->encrypt) {
42e4ac9e
OO
991#ifdef LIBRBD_SUPPORTS_ENCRYPTION
992 r = qemu_rbd_encryption_load(s->image, opts->encrypt, errp);
993 if (r < 0) {
994 goto failed_post_open;
995 }
996#else
997 r = -ENOTSUP;
998 error_setg(errp, "RBD library does not support image encryption");
999 goto failed_post_open;
1000#endif
1001 }
1002
832a93dc 1003 r = rbd_stat(s->image, &info, sizeof(info));
d24f8023 1004 if (r < 0) {
832a93dc 1005 error_setg_errno(errp, -r, "error getting image info from %s",
d24f8023 1006 s->image_name);
42e4ac9e 1007 goto failed_post_open;
d24f8023 1008 }
832a93dc
PL
1009 s->image_size = info.size;
1010 s->object_size = info.obj_size;
d24f8023 1011
e2b8247a
JC
1012 /* If we are using an rbd snapshot, we must be r/o, otherwise
1013 * leave as-is */
1014 if (s->snap != NULL) {
eaa2410f
KW
1015 r = bdrv_apply_auto_read_only(bs, "rbd snapshots are read-only", errp);
1016 if (r < 0) {
42e4ac9e 1017 goto failed_post_open;
e2b8247a
JC
1018 }
1019 }
f27aaf4b 1020
c56ac27d
PL
1021#ifdef LIBRBD_SUPPORTS_WRITE_ZEROES
1022 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK;
1023#endif
1024
2f98910d
EB
1025 /* When extending regular files, we get zeros from the OS */
1026 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
1027
4ff45049
KW
1028 r = 0;
1029 goto out;
f27aaf4b 1030
42e4ac9e
OO
1031failed_post_open:
1032 rbd_close(s->image);
eb93d5d9 1033failed_open:
ad32e9c0 1034 rados_ioctx_destroy(s->io_ctx);
eb93d5d9 1035 g_free(s->snap);
80b61a27 1036 g_free(s->image_name);
3d9136f9 1037 rados_shutdown(s->cluster);
4ff45049 1038out:
4bfb2741 1039 qapi_free_BlockdevOptionsRbd(opts);
4ff45049
KW
1040 g_free(keypairs);
1041 g_free(secretid);
f27aaf4b
CB
1042 return r;
1043}
1044
56e7cf8d
JC
1045
1046/* Since RBD is currently always opened R/W via the API,
1047 * we just need to check if we are using a snapshot or not, in
1048 * order to determine if we will allow it to be R/W */
1049static int qemu_rbd_reopen_prepare(BDRVReopenState *state,
1050 BlockReopenQueue *queue, Error **errp)
1051{
1052 BDRVRBDState *s = state->bs->opaque;
1053 int ret = 0;
1054
1055 if (s->snap && state->flags & BDRV_O_RDWR) {
1056 error_setg(errp,
1057 "Cannot change node '%s' to r/w when using RBD snapshot",
1058 bdrv_get_device_or_node_name(state->bs));
1059 ret = -EINVAL;
1060 }
1061
1062 return ret;
1063}
1064
ad32e9c0 1065static void qemu_rbd_close(BlockDriverState *bs)
f27aaf4b
CB
1066{
1067 BDRVRBDState *s = bs->opaque;
1068
ad32e9c0
JD
1069 rbd_close(s->image);
1070 rados_ioctx_destroy(s->io_ctx);
7267c094 1071 g_free(s->snap);
80b61a27 1072 g_free(s->image_name);
ad32e9c0 1073 rados_shutdown(s->cluster);
f27aaf4b
CB
1074}
1075
d24f8023
SG
1076/* Resize the RBD image and update the 'image_size' with the current size */
1077static int qemu_rbd_resize(BlockDriverState *bs, uint64_t size)
1078{
1079 BDRVRBDState *s = bs->opaque;
1080 int r;
1081
1082 r = rbd_resize(s->image, size);
1083 if (r < 0) {
1084 return r;
1085 }
1086
1087 s->image_size = size;
1088
1089 return 0;
1090}
1091
c3e5fac5 1092static void qemu_rbd_finish_bh(void *opaque)
f27aaf4b 1093{
c3e5fac5 1094 RBDTask *task = opaque;
64cc845b 1095 task->complete = true;
c3e5fac5 1096 aio_co_wake(task->co);
ad32e9c0
JD
1097}
1098
1099/*
c3e5fac5
PL
1100 * This is the completion callback function for all rbd aio calls
1101 * started from qemu_rbd_start_co().
ad32e9c0
JD
1102 *
1103 * Note: this function is being called from a non qemu thread so
1104 * we need to be careful about what we do here. Generally we only
e04fb07f 1105 * schedule a BH, and do the rest of the io completion handling
c3e5fac5 1106 * from qemu_rbd_finish_bh() which runs in a qemu context.
ad32e9c0 1107 */
c3e5fac5 1108static void qemu_rbd_completion_cb(rbd_completion_t c, RBDTask *task)
ad32e9c0 1109{
c3e5fac5 1110 task->ret = rbd_aio_get_return_value(c);
ad32e9c0 1111 rbd_aio_release(c);
c3e5fac5
PL
1112 aio_bh_schedule_oneshot(bdrv_get_aio_context(task->bs),
1113 qemu_rbd_finish_bh, task);
f27aaf4b
CB
1114}
1115
c3e5fac5
PL
1116static int coroutine_fn qemu_rbd_start_co(BlockDriverState *bs,
1117 uint64_t offset,
1118 uint64_t bytes,
1119 QEMUIOVector *qiov,
1120 int flags,
1121 RBDAIOCmd cmd)
f27aaf4b 1122{
c3e5fac5
PL
1123 BDRVRBDState *s = bs->opaque;
1124 RBDTask task = { .bs = bs, .co = qemu_coroutine_self() };
ad32e9c0 1125 rbd_completion_t c;
51a13528 1126 int r;
f27aaf4b 1127
c3e5fac5 1128 assert(!qiov || qiov->size == bytes);
1d393bde 1129
cc5387a5
SG
1130 if (cmd == RBD_AIO_WRITE || cmd == RBD_AIO_WRITE_ZEROES) {
1131 /*
1132 * RBD APIs don't allow us to write more than actual size, so in order
1133 * to support growing images, we resize the image before write
1134 * operations that exceed the current size.
1135 */
1136 if (offset + bytes > s->image_size) {
1137 int r = qemu_rbd_resize(bs, offset + bytes);
1138 if (r < 0) {
1139 return r;
1140 }
1141 }
1142 }
1143
c3e5fac5
PL
1144 r = rbd_aio_create_completion(&task,
1145 (rbd_callback_t) qemu_rbd_completion_cb, &c);
51a13528 1146 if (r < 0) {
c3e5fac5 1147 return r;
51a13528 1148 }
f27aaf4b 1149
787f3133 1150 switch (cmd) {
787f3133 1151 case RBD_AIO_READ:
c3e5fac5
PL
1152 r = rbd_aio_readv(s->image, qiov->iov, qiov->niov, offset, c);
1153 break;
1154 case RBD_AIO_WRITE:
1155 r = rbd_aio_writev(s->image, qiov->iov, qiov->niov, offset, c);
787f3133
JD
1156 break;
1157 case RBD_AIO_DISCARD:
c3e5fac5 1158 r = rbd_aio_discard(s->image, offset, bytes, c);
787f3133 1159 break;
dc7588c1 1160 case RBD_AIO_FLUSH:
48672ac0 1161 r = rbd_aio_flush(s->image, c);
dc7588c1 1162 break;
c56ac27d
PL
1163#ifdef LIBRBD_SUPPORTS_WRITE_ZEROES
1164 case RBD_AIO_WRITE_ZEROES: {
1165 int zero_flags = 0;
1166#ifdef RBD_WRITE_ZEROES_FLAG_THICK_PROVISION
1167 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1168 zero_flags = RBD_WRITE_ZEROES_FLAG_THICK_PROVISION;
1169 }
1170#endif
1171 r = rbd_aio_write_zeroes(s->image, offset, bytes, c, zero_flags, 0);
1172 break;
1173 }
1174#endif
787f3133
JD
1175 default:
1176 r = -EINVAL;
51a13528
JD
1177 }
1178
1179 if (r < 0) {
c3e5fac5
PL
1180 error_report("rbd request failed early: cmd %d offset %" PRIu64
1181 " bytes %" PRIu64 " flags %d r %d (%s)", cmd, offset,
1182 bytes, flags, r, strerror(-r));
1183 rbd_aio_release(c);
1184 return r;
f27aaf4b 1185 }
51a13528 1186
c3e5fac5
PL
1187 while (!task.complete) {
1188 qemu_coroutine_yield();
1189 }
1d393bde 1190
c3e5fac5
PL
1191 if (task.ret < 0) {
1192 error_report("rbd request failed: cmd %d offset %" PRIu64 " bytes %"
1193 PRIu64 " flags %d task.ret %" PRIi64 " (%s)", cmd, offset,
1194 bytes, flags, task.ret, strerror(-task.ret));
1195 return task.ret;
1196 }
1197
1198 /* zero pad short reads */
1199 if (cmd == RBD_AIO_READ && task.ret < qiov->size) {
1200 qemu_iovec_memset(qiov, task.ret, 0, qiov->size - task.ret);
1201 }
1202
1203 return 0;
1204}
1205
1206static int
f7ef38dd
VSO
1207coroutine_fn qemu_rbd_co_preadv(BlockDriverState *bs, int64_t offset,
1208 int64_t bytes, QEMUIOVector *qiov,
1209 BdrvRequestFlags flags)
c3e5fac5
PL
1210{
1211 return qemu_rbd_start_co(bs, offset, bytes, qiov, flags, RBD_AIO_READ);
f27aaf4b
CB
1212}
1213
c3e5fac5 1214static int
e75abeda
VSO
1215coroutine_fn qemu_rbd_co_pwritev(BlockDriverState *bs, int64_t offset,
1216 int64_t bytes, QEMUIOVector *qiov,
1217 BdrvRequestFlags flags)
f27aaf4b 1218{
c3e5fac5 1219 return qemu_rbd_start_co(bs, offset, bytes, qiov, flags, RBD_AIO_WRITE);
f27aaf4b
CB
1220}
1221
c3e5fac5 1222static int coroutine_fn qemu_rbd_co_flush(BlockDriverState *bs)
f27aaf4b 1223{
c3e5fac5 1224 return qemu_rbd_start_co(bs, 0, 0, NULL, 0, RBD_AIO_FLUSH);
f27aaf4b
CB
1225}
1226
c3e5fac5 1227static int coroutine_fn qemu_rbd_co_pdiscard(BlockDriverState *bs,
0c802287 1228 int64_t offset, int64_t bytes)
dc7588c1 1229{
0c802287 1230 return qemu_rbd_start_co(bs, offset, bytes, NULL, 0, RBD_AIO_DISCARD);
dc7588c1
JD
1231}
1232
c56ac27d
PL
1233#ifdef LIBRBD_SUPPORTS_WRITE_ZEROES
1234static int
1235coroutine_fn qemu_rbd_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
f34b2bcf 1236 int64_t bytes, BdrvRequestFlags flags)
c56ac27d 1237{
f34b2bcf 1238 return qemu_rbd_start_co(bs, offset, bytes, NULL, flags,
c56ac27d
PL
1239 RBD_AIO_WRITE_ZEROES);
1240}
1241#endif
1242
ad32e9c0 1243static int qemu_rbd_getinfo(BlockDriverState *bs, BlockDriverInfo *bdi)
f27aaf4b
CB
1244{
1245 BDRVRBDState *s = bs->opaque;
832a93dc 1246 bdi->cluster_size = s->object_size;
f27aaf4b
CB
1247 return 0;
1248}
1249
42e4ac9e
OO
1250static ImageInfoSpecific *qemu_rbd_get_specific_info(BlockDriverState *bs,
1251 Error **errp)
1252{
1253 BDRVRBDState *s = bs->opaque;
1254 ImageInfoSpecific *spec_info;
1255 char buf[RBD_ENCRYPTION_LUKS_HEADER_VERIFICATION_LEN] = {0};
1256 int r;
1257
1258 if (s->image_size >= RBD_ENCRYPTION_LUKS_HEADER_VERIFICATION_LEN) {
1259 r = rbd_read(s->image, 0,
1260 RBD_ENCRYPTION_LUKS_HEADER_VERIFICATION_LEN, buf);
1261 if (r < 0) {
1262 error_setg_errno(errp, -r, "cannot read image start for probe");
1263 return NULL;
1264 }
1265 }
1266
1267 spec_info = g_new(ImageInfoSpecific, 1);
1268 *spec_info = (ImageInfoSpecific){
1269 .type = IMAGE_INFO_SPECIFIC_KIND_RBD,
1270 .u.rbd.data = g_new0(ImageInfoSpecificRbd, 1),
1271 };
1272
1273 if (memcmp(buf, rbd_luks_header_verification,
1274 RBD_ENCRYPTION_LUKS_HEADER_VERIFICATION_LEN) == 0) {
1275 spec_info->u.rbd.data->encryption_format =
1276 RBD_IMAGE_ENCRYPTION_FORMAT_LUKS;
1277 spec_info->u.rbd.data->has_encryption_format = true;
1278 } else if (memcmp(buf, rbd_luks2_header_verification,
1279 RBD_ENCRYPTION_LUKS_HEADER_VERIFICATION_LEN) == 0) {
1280 spec_info->u.rbd.data->encryption_format =
1281 RBD_IMAGE_ENCRYPTION_FORMAT_LUKS2;
1282 spec_info->u.rbd.data->has_encryption_format = true;
1283 } else {
1284 spec_info->u.rbd.data->has_encryption_format = false;
1285 }
1286
1287 return spec_info;
1288}
1289
0347a8fd
PL
1290/*
1291 * rbd_diff_iterate2 allows to interrupt the exection by returning a negative
1292 * value in the callback routine. Choose a value that does not conflict with
1293 * an existing exitcode and return it if we want to prematurely stop the
1294 * execution because we detected a change in the allocation status.
1295 */
1296#define QEMU_RBD_EXIT_DIFF_ITERATE2 -9000
1297
1298static int qemu_rbd_diff_iterate_cb(uint64_t offs, size_t len,
1299 int exists, void *opaque)
1300{
1301 RBDDiffIterateReq *req = opaque;
1302
1303 assert(req->offs + req->bytes <= offs);
9e302f64
PL
1304
1305 /* treat a hole like an unallocated area and bail out */
1306 if (!exists) {
1307 return 0;
1308 }
0347a8fd
PL
1309
1310 if (!req->exists && offs > req->offs) {
1311 /*
1312 * we started in an unallocated area and hit the first allocated
1313 * block. req->bytes must be set to the length of the unallocated area
1314 * before the allocated area. stop further processing.
1315 */
1316 req->bytes = offs - req->offs;
1317 return QEMU_RBD_EXIT_DIFF_ITERATE2;
1318 }
1319
1320 if (req->exists && offs > req->offs + req->bytes) {
1321 /*
1322 * we started in an allocated area and jumped over an unallocated area,
1323 * req->bytes contains the length of the allocated area before the
1324 * unallocated area. stop further processing.
1325 */
1326 return QEMU_RBD_EXIT_DIFF_ITERATE2;
1327 }
1328
1329 req->bytes += len;
1330 req->exists = true;
1331
1332 return 0;
1333}
1334
1335static int coroutine_fn qemu_rbd_co_block_status(BlockDriverState *bs,
1336 bool want_zero, int64_t offset,
1337 int64_t bytes, int64_t *pnum,
1338 int64_t *map,
1339 BlockDriverState **file)
1340{
1341 BDRVRBDState *s = bs->opaque;
1342 int status, r;
1343 RBDDiffIterateReq req = { .offs = offset };
1344 uint64_t features, flags;
fc176116 1345 uint64_t head = 0;
0347a8fd
PL
1346
1347 assert(offset + bytes <= s->image_size);
1348
1349 /* default to all sectors allocated */
1350 status = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1351 *map = offset;
1352 *file = bs;
1353 *pnum = bytes;
1354
1355 /* check if RBD image supports fast-diff */
1356 r = rbd_get_features(s->image, &features);
1357 if (r < 0) {
1358 return status;
1359 }
1360 if (!(features & RBD_FEATURE_FAST_DIFF)) {
1361 return status;
1362 }
1363
1364 /* check if RBD fast-diff result is valid */
1365 r = rbd_get_flags(s->image, &flags);
1366 if (r < 0) {
1367 return status;
1368 }
1369 if (flags & RBD_FLAG_FAST_DIFF_INVALID) {
1370 return status;
1371 }
1372
fc176116
PL
1373#if LIBRBD_VERSION_CODE < LIBRBD_VERSION(1, 17, 0)
1374 /*
1375 * librbd had a bug until early 2022 that affected all versions of ceph that
1376 * supported fast-diff. This bug results in reporting of incorrect offsets
1377 * if the offset parameter to rbd_diff_iterate2 is not object aligned.
1378 * Work around this bug by rounding down the offset to object boundaries.
1379 * This is OK because we call rbd_diff_iterate2 with whole_object = true.
1380 * However, this workaround only works for non cloned images with default
1381 * striping.
1382 *
1383 * See: https://tracker.ceph.com/issues/53784
1384 */
1385
1386 /* check if RBD image has non-default striping enabled */
1387 if (features & RBD_FEATURE_STRIPINGV2) {
1388 return status;
1389 }
1390
1391#pragma GCC diagnostic push
1392#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
1393 /*
1394 * check if RBD image is a clone (= has a parent).
1395 *
1396 * rbd_get_parent_info is deprecated from Nautilus onwards, but the
1397 * replacement rbd_get_parent is not present in Luminous and Mimic.
1398 */
1399 if (rbd_get_parent_info(s->image, NULL, 0, NULL, 0, NULL, 0) != -ENOENT) {
1400 return status;
1401 }
1402#pragma GCC diagnostic pop
1403
1404 head = req.offs & (s->object_size - 1);
1405 req.offs -= head;
1406 bytes += head;
1407#endif
1408
1409 r = rbd_diff_iterate2(s->image, NULL, req.offs, bytes, true, true,
0347a8fd
PL
1410 qemu_rbd_diff_iterate_cb, &req);
1411 if (r < 0 && r != QEMU_RBD_EXIT_DIFF_ITERATE2) {
1412 return status;
1413 }
1414 assert(req.bytes <= bytes);
1415 if (!req.exists) {
1416 if (r == 0) {
1417 /*
1418 * rbd_diff_iterate2 does not invoke callbacks for unallocated
1419 * areas. This here catches the case where no callback was
1420 * invoked at all (req.bytes == 0).
1421 */
1422 assert(req.bytes == 0);
1423 req.bytes = bytes;
1424 }
1425 status = BDRV_BLOCK_ZERO | BDRV_BLOCK_OFFSET_VALID;
1426 }
1427
fc176116
PL
1428 assert(req.bytes > head);
1429 *pnum = req.bytes - head;
0347a8fd
PL
1430 return status;
1431}
1432
c86422c5 1433static int64_t coroutine_fn qemu_rbd_co_getlength(BlockDriverState *bs)
f27aaf4b
CB
1434{
1435 BDRVRBDState *s = bs->opaque;
ad32e9c0 1436 int r;
f27aaf4b 1437
6d921418 1438 r = rbd_get_size(s->image, &s->image_size);
ad32e9c0
JD
1439 if (r < 0) {
1440 return r;
1441 }
1442
6d921418 1443 return s->image_size;
f27aaf4b
CB
1444}
1445
061ca8a3
KW
1446static int coroutine_fn qemu_rbd_co_truncate(BlockDriverState *bs,
1447 int64_t offset,
c80d8b06 1448 bool exact,
061ca8a3 1449 PreallocMode prealloc,
92b92799 1450 BdrvRequestFlags flags,
061ca8a3 1451 Error **errp)
30cdc48c 1452{
30cdc48c
JD
1453 int r;
1454
8243ccb7
HR
1455 if (prealloc != PREALLOC_MODE_OFF) {
1456 error_setg(errp, "Unsupported preallocation mode '%s'",
977c736f 1457 PreallocMode_str(prealloc));
8243ccb7
HR
1458 return -ENOTSUP;
1459 }
1460
d24f8023 1461 r = qemu_rbd_resize(bs, offset);
30cdc48c 1462 if (r < 0) {
f59adb32 1463 error_setg_errno(errp, -r, "Failed to resize file");
30cdc48c
JD
1464 return r;
1465 }
1466
1467 return 0;
1468}
1469
ad32e9c0
JD
1470static int qemu_rbd_snap_create(BlockDriverState *bs,
1471 QEMUSnapshotInfo *sn_info)
f27aaf4b
CB
1472{
1473 BDRVRBDState *s = bs->opaque;
f27aaf4b 1474 int r;
f27aaf4b
CB
1475
1476 if (sn_info->name[0] == '\0') {
1477 return -EINVAL; /* we need a name for rbd snapshots */
1478 }
1479
1480 /*
1481 * rbd snapshots are using the name as the user controlled unique identifier
1482 * we can't use the rbd snapid for that purpose, as it can't be set
1483 */
1484 if (sn_info->id_str[0] != '\0' &&
1485 strcmp(sn_info->id_str, sn_info->name) != 0) {
1486 return -EINVAL;
1487 }
1488
1489 if (strlen(sn_info->name) >= sizeof(sn_info->id_str)) {
1490 return -ERANGE;
1491 }
1492
ad32e9c0 1493 r = rbd_snap_create(s->image, sn_info->name);
f27aaf4b 1494 if (r < 0) {
ad32e9c0 1495 error_report("failed to create snap: %s", strerror(-r));
f27aaf4b
CB
1496 return r;
1497 }
1498
f27aaf4b
CB
1499 return 0;
1500}
1501
bd603247 1502static int qemu_rbd_snap_remove(BlockDriverState *bs,
a89d89d3
WX
1503 const char *snapshot_id,
1504 const char *snapshot_name,
1505 Error **errp)
bd603247
GF
1506{
1507 BDRVRBDState *s = bs->opaque;
1508 int r;
1509
a89d89d3
WX
1510 if (!snapshot_name) {
1511 error_setg(errp, "rbd need a valid snapshot name");
1512 return -EINVAL;
1513 }
1514
1515 /* If snapshot_id is specified, it must be equal to name, see
1516 qemu_rbd_snap_list() */
1517 if (snapshot_id && strcmp(snapshot_id, snapshot_name)) {
1518 error_setg(errp,
1519 "rbd do not support snapshot id, it should be NULL or "
1520 "equal to snapshot name");
1521 return -EINVAL;
1522 }
1523
bd603247 1524 r = rbd_snap_remove(s->image, snapshot_name);
a89d89d3
WX
1525 if (r < 0) {
1526 error_setg_errno(errp, -r, "Failed to remove the snapshot");
1527 }
bd603247
GF
1528 return r;
1529}
1530
1531static int qemu_rbd_snap_rollback(BlockDriverState *bs,
1532 const char *snapshot_name)
1533{
1534 BDRVRBDState *s = bs->opaque;
bd603247 1535
9be38598 1536 return rbd_snap_rollback(s->image, snapshot_name);
bd603247
GF
1537}
1538
ad32e9c0
JD
1539static int qemu_rbd_snap_list(BlockDriverState *bs,
1540 QEMUSnapshotInfo **psn_tab)
f27aaf4b
CB
1541{
1542 BDRVRBDState *s = bs->opaque;
f27aaf4b 1543 QEMUSnapshotInfo *sn_info, *sn_tab = NULL;
ad32e9c0
JD
1544 int i, snap_count;
1545 rbd_snap_info_t *snaps;
1546 int max_snaps = RBD_MAX_SNAPS;
f27aaf4b 1547
ad32e9c0 1548 do {
02c4f26b 1549 snaps = g_new(rbd_snap_info_t, max_snaps);
ad32e9c0 1550 snap_count = rbd_snap_list(s->image, snaps, &max_snaps);
9e6337d0 1551 if (snap_count <= 0) {
7267c094 1552 g_free(snaps);
f27aaf4b 1553 }
ad32e9c0 1554 } while (snap_count == -ERANGE);
f27aaf4b 1555
ad32e9c0 1556 if (snap_count <= 0) {
b9c53290 1557 goto done;
f27aaf4b
CB
1558 }
1559
5839e53b 1560 sn_tab = g_new0(QEMUSnapshotInfo, snap_count);
f27aaf4b 1561
ad32e9c0
JD
1562 for (i = 0; i < snap_count; i++) {
1563 const char *snap_name = snaps[i].name;
f27aaf4b
CB
1564
1565 sn_info = sn_tab + i;
1566 pstrcpy(sn_info->id_str, sizeof(sn_info->id_str), snap_name);
1567 pstrcpy(sn_info->name, sizeof(sn_info->name), snap_name);
f27aaf4b 1568
ad32e9c0 1569 sn_info->vm_state_size = snaps[i].size;
f27aaf4b
CB
1570 sn_info->date_sec = 0;
1571 sn_info->date_nsec = 0;
1572 sn_info->vm_clock_nsec = 0;
1573 }
ad32e9c0 1574 rbd_snap_list_end(snaps);
9e6337d0 1575 g_free(snaps);
ad32e9c0 1576
b9c53290 1577 done:
f27aaf4b 1578 *psn_tab = sn_tab;
f27aaf4b 1579 return snap_count;
f27aaf4b
CB
1580}
1581
2b148f39
PB
1582static void coroutine_fn qemu_rbd_co_invalidate_cache(BlockDriverState *bs,
1583 Error **errp)
be217884
AC
1584{
1585 BDRVRBDState *s = bs->opaque;
1586 int r = rbd_invalidate_cache(s->image);
1587 if (r < 0) {
1588 error_setg_errno(errp, -r, "Failed to invalidate the cache");
1589 }
1590}
be217884 1591
bd0cf596
CL
1592static QemuOptsList qemu_rbd_create_opts = {
1593 .name = "rbd-create-opts",
1594 .head = QTAILQ_HEAD_INITIALIZER(qemu_rbd_create_opts.head),
1595 .desc = {
1596 {
1597 .name = BLOCK_OPT_SIZE,
1598 .type = QEMU_OPT_SIZE,
1599 .help = "Virtual disk size"
1600 },
1601 {
1602 .name = BLOCK_OPT_CLUSTER_SIZE,
1603 .type = QEMU_OPT_SIZE,
1604 .help = "RBD object size"
1605 },
60390a21
DB
1606 {
1607 .name = "password-secret",
1608 .type = QEMU_OPT_STRING,
1609 .help = "ID of secret providing the password",
1610 },
42e4ac9e
OO
1611 {
1612 .name = "encrypt.format",
1613 .type = QEMU_OPT_STRING,
1614 .help = "Encrypt the image, format choices: 'luks', 'luks2'",
1615 },
1616 {
1617 .name = "encrypt.cipher-alg",
1618 .type = QEMU_OPT_STRING,
1619 .help = "Name of encryption cipher algorithm"
1620 " (allowed values: aes-128, aes-256)",
1621 },
1622 {
1623 .name = "encrypt.key-secret",
1624 .type = QEMU_OPT_STRING,
1625 .help = "ID of secret providing LUKS passphrase",
1626 },
bd0cf596
CL
1627 { /* end of list */ }
1628 }
f27aaf4b
CB
1629};
1630
2654267c
HR
1631static const char *const qemu_rbd_strong_runtime_opts[] = {
1632 "pool",
7bae7c80 1633 "namespace",
2654267c
HR
1634 "image",
1635 "conf",
1636 "snapshot",
1637 "user",
1638 "server.",
1639 "password-secret",
1640
1641 NULL
1642};
1643
f27aaf4b 1644static BlockDriver bdrv_rbd = {
c7cacb3e
JC
1645 .format_name = "rbd",
1646 .instance_size = sizeof(BDRVRBDState),
1647 .bdrv_parse_filename = qemu_rbd_parse_filename,
1648 .bdrv_file_open = qemu_rbd_open,
1649 .bdrv_close = qemu_rbd_close,
56e7cf8d 1650 .bdrv_reopen_prepare = qemu_rbd_reopen_prepare,
1bebea37 1651 .bdrv_co_create = qemu_rbd_co_create,
efc75e2a 1652 .bdrv_co_create_opts = qemu_rbd_co_create_opts,
c7cacb3e
JC
1653 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1654 .bdrv_get_info = qemu_rbd_getinfo,
42e4ac9e 1655 .bdrv_get_specific_info = qemu_rbd_get_specific_info,
c7cacb3e 1656 .create_opts = &qemu_rbd_create_opts,
c86422c5 1657 .bdrv_co_getlength = qemu_rbd_co_getlength,
061ca8a3 1658 .bdrv_co_truncate = qemu_rbd_co_truncate,
c7cacb3e 1659 .protocol_name = "rbd",
f27aaf4b 1660
c3e5fac5
PL
1661 .bdrv_co_preadv = qemu_rbd_co_preadv,
1662 .bdrv_co_pwritev = qemu_rbd_co_pwritev,
1663 .bdrv_co_flush_to_disk = qemu_rbd_co_flush,
1664 .bdrv_co_pdiscard = qemu_rbd_co_pdiscard,
c56ac27d
PL
1665#ifdef LIBRBD_SUPPORTS_WRITE_ZEROES
1666 .bdrv_co_pwrite_zeroes = qemu_rbd_co_pwrite_zeroes,
1667#endif
0347a8fd 1668 .bdrv_co_block_status = qemu_rbd_co_block_status,
787f3133 1669
c68b89ac 1670 .bdrv_snapshot_create = qemu_rbd_snap_create,
bd603247 1671 .bdrv_snapshot_delete = qemu_rbd_snap_remove,
c68b89ac 1672 .bdrv_snapshot_list = qemu_rbd_snap_list,
bd603247 1673 .bdrv_snapshot_goto = qemu_rbd_snap_rollback,
2b148f39 1674 .bdrv_co_invalidate_cache = qemu_rbd_co_invalidate_cache,
2654267c
HR
1675
1676 .strong_runtime_opts = qemu_rbd_strong_runtime_opts,
f27aaf4b
CB
1677};
1678
1679static void bdrv_rbd_init(void)
1680{
1681 bdrv_register(&bdrv_rbd);
1682}
1683
1684block_init(bdrv_rbd_init);