xref: /openbmc/qemu/block/rbd.c (revision 3aff6c2f)
1 /*
2  * QEMU Block driver for RADOS (Ceph)
3  *
4  * Copyright (C) 2010-2011 Christian Brunner <chb@muc.de>,
5  *                         Josh Durgin <josh.durgin@dreamhost.com>
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  *
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.
12  */
13 
14 #include <inttypes.h>
15 
16 #include "qemu-common.h"
17 #include "qemu/error-report.h"
18 #include "block/block_int.h"
19 
20 #include <rbd/librbd.h>
21 
22 /*
23  * When specifying the image filename use:
24  *
25  * rbd:poolname/devicename[@snapshotname][:option1=value1[:option2=value2...]]
26  *
27  * poolname must be the name of an existing rados pool.
28  *
29  * devicename is the name of the rbd image.
30  *
31  * Each option given is used to configure rados, and may be any valid
32  * Ceph option, "id", or "conf".
33  *
34  * The "id" option indicates what user we should authenticate as to
35  * the Ceph cluster.  If it is excluded we will use the Ceph default
36  * (normally 'admin').
37  *
38  * The "conf" option specifies a Ceph configuration file to read.  If
39  * it is not specified, we will read from the default Ceph locations
40  * (e.g., /etc/ceph/ceph.conf).  To avoid reading _any_ configuration
41  * file, specify conf=/dev/null.
42  *
43  * Configuration values containing :, @, or = can be escaped with a
44  * leading "\".
45  */
46 
47 /* rbd_aio_discard added in 0.1.2 */
48 #if LIBRBD_VERSION_CODE >= LIBRBD_VERSION(0, 1, 2)
49 #define LIBRBD_SUPPORTS_DISCARD
50 #else
51 #undef LIBRBD_SUPPORTS_DISCARD
52 #endif
53 
54 #define OBJ_MAX_SIZE (1UL << OBJ_DEFAULT_OBJ_ORDER)
55 
56 #define RBD_MAX_CONF_NAME_SIZE 128
57 #define RBD_MAX_CONF_VAL_SIZE 512
58 #define RBD_MAX_CONF_SIZE 1024
59 #define RBD_MAX_POOL_NAME_SIZE 128
60 #define RBD_MAX_SNAP_NAME_SIZE 128
61 #define RBD_MAX_SNAPS 100
62 
63 typedef enum {
64     RBD_AIO_READ,
65     RBD_AIO_WRITE,
66     RBD_AIO_DISCARD,
67     RBD_AIO_FLUSH
68 } RBDAIOCmd;
69 
70 typedef struct RBDAIOCB {
71     BlockDriverAIOCB common;
72     QEMUBH *bh;
73     int64_t ret;
74     QEMUIOVector *qiov;
75     char *bounce;
76     RBDAIOCmd cmd;
77     int64_t sector_num;
78     int error;
79     struct BDRVRBDState *s;
80     int cancelled;
81     int status;
82 } RBDAIOCB;
83 
84 typedef struct RADOSCB {
85     int rcbid;
86     RBDAIOCB *acb;
87     struct BDRVRBDState *s;
88     int done;
89     int64_t size;
90     char *buf;
91     int64_t ret;
92 } RADOSCB;
93 
94 #define RBD_FD_READ 0
95 #define RBD_FD_WRITE 1
96 
97 typedef struct BDRVRBDState {
98     rados_t cluster;
99     rados_ioctx_t io_ctx;
100     rbd_image_t image;
101     char name[RBD_MAX_IMAGE_NAME_SIZE];
102     char *snap;
103 } BDRVRBDState;
104 
105 static int qemu_rbd_next_tok(char *dst, int dst_len,
106                              char *src, char delim,
107                              const char *name,
108                              char **p, Error **errp)
109 {
110     int l;
111     char *end;
112 
113     *p = NULL;
114 
115     if (delim != '\0') {
116         for (end = src; *end; ++end) {
117             if (*end == delim) {
118                 break;
119             }
120             if (*end == '\\' && end[1] != '\0') {
121                 end++;
122             }
123         }
124         if (*end == delim) {
125             *p = end + 1;
126             *end = '\0';
127         }
128     }
129     l = strlen(src);
130     if (l >= dst_len) {
131         error_setg(errp, "%s too long", name);
132         return -EINVAL;
133     } else if (l == 0) {
134         error_setg(errp, "%s too short", name);
135         return -EINVAL;
136     }
137 
138     pstrcpy(dst, dst_len, src);
139 
140     return 0;
141 }
142 
143 static 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 
156 static int qemu_rbd_parsename(const char *filename,
157                               char *pool, int pool_len,
158                               char *snap, int snap_len,
159                               char *name, int name_len,
160                               char *conf, int conf_len,
161                               Error **errp)
162 {
163     const char *start;
164     char *p, *buf;
165     int ret;
166 
167     if (!strstart(filename, "rbd:", &start)) {
168         error_setg(errp, "File name must start with 'rbd:'");
169         return -EINVAL;
170     }
171 
172     buf = g_strdup(start);
173     p = buf;
174     *snap = '\0';
175     *conf = '\0';
176 
177     ret = qemu_rbd_next_tok(pool, pool_len, p,
178                             '/', "pool name", &p, errp);
179     if (ret < 0 || !p) {
180         ret = -EINVAL;
181         goto done;
182     }
183     qemu_rbd_unescape(pool);
184 
185     if (strchr(p, '@')) {
186         ret = qemu_rbd_next_tok(name, name_len, p,
187                                 '@', "object name", &p, errp);
188         if (ret < 0) {
189             goto done;
190         }
191         ret = qemu_rbd_next_tok(snap, snap_len, p,
192                                 ':', "snap name", &p, errp);
193         qemu_rbd_unescape(snap);
194     } else {
195         ret = qemu_rbd_next_tok(name, name_len, p,
196                                 ':', "object name", &p, errp);
197     }
198     qemu_rbd_unescape(name);
199     if (ret < 0 || !p) {
200         goto done;
201     }
202 
203     ret = qemu_rbd_next_tok(conf, conf_len, p,
204                             '\0', "configuration", &p, errp);
205 
206 done:
207     g_free(buf);
208     return ret;
209 }
210 
211 static char *qemu_rbd_parse_clientname(const char *conf, char *clientname)
212 {
213     const char *p = conf;
214 
215     while (*p) {
216         int len;
217         const char *end = strchr(p, ':');
218 
219         if (end) {
220             len = end - p;
221         } else {
222             len = strlen(p);
223         }
224 
225         if (strncmp(p, "id=", 3) == 0) {
226             len -= 3;
227             strncpy(clientname, p + 3, len);
228             clientname[len] = '\0';
229             return clientname;
230         }
231         if (end == NULL) {
232             break;
233         }
234         p = end + 1;
235     }
236     return NULL;
237 }
238 
239 static int qemu_rbd_set_conf(rados_t cluster, const char *conf, Error **errp)
240 {
241     char *p, *buf;
242     char name[RBD_MAX_CONF_NAME_SIZE];
243     char value[RBD_MAX_CONF_VAL_SIZE];
244     int ret = 0;
245 
246     buf = g_strdup(conf);
247     p = buf;
248 
249     while (p) {
250         ret = qemu_rbd_next_tok(name, sizeof(name), p,
251                                 '=', "conf option name", &p, errp);
252         if (ret < 0) {
253             break;
254         }
255         qemu_rbd_unescape(name);
256 
257         if (!p) {
258             error_setg(errp, "conf option %s has no value", name);
259             ret = -EINVAL;
260             break;
261         }
262 
263         ret = qemu_rbd_next_tok(value, sizeof(value), p,
264                                 ':', "conf option value", &p, errp);
265         if (ret < 0) {
266             break;
267         }
268         qemu_rbd_unescape(value);
269 
270         if (strcmp(name, "conf") == 0) {
271             ret = rados_conf_read_file(cluster, value);
272             if (ret < 0) {
273                 error_setg(errp, "error reading conf file %s", value);
274                 break;
275             }
276         } else if (strcmp(name, "id") == 0) {
277             /* ignore, this is parsed by qemu_rbd_parse_clientname() */
278         } else {
279             ret = rados_conf_set(cluster, name, value);
280             if (ret < 0) {
281                 error_setg(errp, "invalid conf option %s", name);
282                 ret = -EINVAL;
283                 break;
284             }
285         }
286     }
287 
288     g_free(buf);
289     return ret;
290 }
291 
292 static int qemu_rbd_create(const char *filename, QEMUOptionParameter *options,
293                            Error **errp)
294 {
295     Error *local_err = NULL;
296     int64_t bytes = 0;
297     int64_t objsize;
298     int obj_order = 0;
299     char pool[RBD_MAX_POOL_NAME_SIZE];
300     char name[RBD_MAX_IMAGE_NAME_SIZE];
301     char snap_buf[RBD_MAX_SNAP_NAME_SIZE];
302     char conf[RBD_MAX_CONF_SIZE];
303     char clientname_buf[RBD_MAX_CONF_SIZE];
304     char *clientname;
305     rados_t cluster;
306     rados_ioctx_t io_ctx;
307     int ret;
308 
309     if (qemu_rbd_parsename(filename, pool, sizeof(pool),
310                            snap_buf, sizeof(snap_buf),
311                            name, sizeof(name),
312                            conf, sizeof(conf), &local_err) < 0) {
313         error_propagate(errp, local_err);
314         return -EINVAL;
315     }
316 
317     /* Read out options */
318     while (options && options->name) {
319         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
320             bytes = options->value.n;
321         } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
322             if (options->value.n) {
323                 objsize = options->value.n;
324                 if ((objsize - 1) & objsize) {    /* not a power of 2? */
325                     error_setg(errp, "obj size needs to be power of 2");
326                     return -EINVAL;
327                 }
328                 if (objsize < 4096) {
329                     error_setg(errp, "obj size too small");
330                     return -EINVAL;
331                 }
332                 obj_order = ffs(objsize) - 1;
333             }
334         }
335         options++;
336     }
337 
338     clientname = qemu_rbd_parse_clientname(conf, clientname_buf);
339     if (rados_create(&cluster, clientname) < 0) {
340         error_setg(errp, "error initializing");
341         return -EIO;
342     }
343 
344     if (strstr(conf, "conf=") == NULL) {
345         /* try default location, but ignore failure */
346         rados_conf_read_file(cluster, NULL);
347     }
348 
349     if (conf[0] != '\0' &&
350         qemu_rbd_set_conf(cluster, conf, &local_err) < 0) {
351         rados_shutdown(cluster);
352         error_propagate(errp, local_err);
353         return -EIO;
354     }
355 
356     if (rados_connect(cluster) < 0) {
357         error_setg(errp, "error connecting");
358         rados_shutdown(cluster);
359         return -EIO;
360     }
361 
362     if (rados_ioctx_create(cluster, pool, &io_ctx) < 0) {
363         error_setg(errp, "error opening pool %s", pool);
364         rados_shutdown(cluster);
365         return -EIO;
366     }
367 
368     ret = rbd_create(io_ctx, name, bytes, &obj_order);
369     rados_ioctx_destroy(io_ctx);
370     rados_shutdown(cluster);
371 
372     return ret;
373 }
374 
375 /*
376  * This aio completion is being called from rbd_finish_bh() and runs in qemu
377  * BH context.
378  */
379 static void qemu_rbd_complete_aio(RADOSCB *rcb)
380 {
381     RBDAIOCB *acb = rcb->acb;
382     int64_t r;
383 
384     r = rcb->ret;
385 
386     if (acb->cmd != RBD_AIO_READ) {
387         if (r < 0) {
388             acb->ret = r;
389             acb->error = 1;
390         } else if (!acb->error) {
391             acb->ret = rcb->size;
392         }
393     } else {
394         if (r < 0) {
395             memset(rcb->buf, 0, rcb->size);
396             acb->ret = r;
397             acb->error = 1;
398         } else if (r < rcb->size) {
399             memset(rcb->buf + r, 0, rcb->size - r);
400             if (!acb->error) {
401                 acb->ret = rcb->size;
402             }
403         } else if (!acb->error) {
404             acb->ret = r;
405         }
406     }
407 
408     g_free(rcb);
409 
410     if (acb->cmd == RBD_AIO_READ) {
411         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
412     }
413     qemu_vfree(acb->bounce);
414     acb->common.cb(acb->common.opaque, (acb->ret > 0 ? 0 : acb->ret));
415     acb->status = 0;
416 
417     if (!acb->cancelled) {
418         qemu_aio_release(acb);
419     }
420 }
421 
422 /* TODO Convert to fine grained options */
423 static QemuOptsList runtime_opts = {
424     .name = "rbd",
425     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
426     .desc = {
427         {
428             .name = "filename",
429             .type = QEMU_OPT_STRING,
430             .help = "Specification of the rbd image",
431         },
432         { /* end of list */ }
433     },
434 };
435 
436 static int qemu_rbd_open(BlockDriverState *bs, QDict *options, int flags,
437                          Error **errp)
438 {
439     BDRVRBDState *s = bs->opaque;
440     char pool[RBD_MAX_POOL_NAME_SIZE];
441     char snap_buf[RBD_MAX_SNAP_NAME_SIZE];
442     char conf[RBD_MAX_CONF_SIZE];
443     char clientname_buf[RBD_MAX_CONF_SIZE];
444     char *clientname;
445     QemuOpts *opts;
446     Error *local_err = NULL;
447     const char *filename;
448     int r;
449 
450     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
451     qemu_opts_absorb_qdict(opts, options, &local_err);
452     if (local_err) {
453         error_propagate(errp, local_err);
454         qemu_opts_del(opts);
455         return -EINVAL;
456     }
457 
458     filename = qemu_opt_get(opts, "filename");
459 
460     if (qemu_rbd_parsename(filename, pool, sizeof(pool),
461                            snap_buf, sizeof(snap_buf),
462                            s->name, sizeof(s->name),
463                            conf, sizeof(conf), errp) < 0) {
464         r = -EINVAL;
465         goto failed_opts;
466     }
467 
468     clientname = qemu_rbd_parse_clientname(conf, clientname_buf);
469     r = rados_create(&s->cluster, clientname);
470     if (r < 0) {
471         error_setg(&local_err, "error initializing");
472         goto failed_opts;
473     }
474 
475     s->snap = NULL;
476     if (snap_buf[0] != '\0') {
477         s->snap = g_strdup(snap_buf);
478     }
479 
480     /*
481      * Fallback to more conservative semantics if setting cache
482      * options fails. Ignore errors from setting rbd_cache because the
483      * only possible error is that the option does not exist, and
484      * librbd defaults to no caching. If write through caching cannot
485      * be set up, fall back to no caching.
486      */
487     if (flags & BDRV_O_NOCACHE) {
488         rados_conf_set(s->cluster, "rbd_cache", "false");
489     } else {
490         rados_conf_set(s->cluster, "rbd_cache", "true");
491     }
492 
493     if (strstr(conf, "conf=") == NULL) {
494         /* try default location, but ignore failure */
495         rados_conf_read_file(s->cluster, NULL);
496     }
497 
498     if (conf[0] != '\0') {
499         r = qemu_rbd_set_conf(s->cluster, conf, errp);
500         if (r < 0) {
501             goto failed_shutdown;
502         }
503     }
504 
505     r = rados_connect(s->cluster);
506     if (r < 0) {
507         error_setg(&local_err, "error connecting");
508         goto failed_shutdown;
509     }
510 
511     r = rados_ioctx_create(s->cluster, pool, &s->io_ctx);
512     if (r < 0) {
513         error_setg(&local_err, "error opening pool %s", pool);
514         goto failed_shutdown;
515     }
516 
517     r = rbd_open(s->io_ctx, s->name, &s->image, s->snap);
518     if (r < 0) {
519         error_setg(&local_err, "error reading header from %s", s->name);
520         goto failed_open;
521     }
522 
523     bs->read_only = (s->snap != NULL);
524 
525     qemu_opts_del(opts);
526     return 0;
527 
528 failed_open:
529     rados_ioctx_destroy(s->io_ctx);
530 failed_shutdown:
531     rados_shutdown(s->cluster);
532     g_free(s->snap);
533 failed_opts:
534     qemu_opts_del(opts);
535     return r;
536 }
537 
538 static void qemu_rbd_close(BlockDriverState *bs)
539 {
540     BDRVRBDState *s = bs->opaque;
541 
542     rbd_close(s->image);
543     rados_ioctx_destroy(s->io_ctx);
544     g_free(s->snap);
545     rados_shutdown(s->cluster);
546 }
547 
548 /*
549  * Cancel aio. Since we don't reference acb in a non qemu threads,
550  * it is safe to access it here.
551  */
552 static void qemu_rbd_aio_cancel(BlockDriverAIOCB *blockacb)
553 {
554     RBDAIOCB *acb = (RBDAIOCB *) blockacb;
555     acb->cancelled = 1;
556 
557     while (acb->status == -EINPROGRESS) {
558         aio_poll(bdrv_get_aio_context(acb->common.bs), true);
559     }
560 
561     qemu_aio_release(acb);
562 }
563 
564 static const AIOCBInfo rbd_aiocb_info = {
565     .aiocb_size = sizeof(RBDAIOCB),
566     .cancel = qemu_rbd_aio_cancel,
567 };
568 
569 static void rbd_finish_bh(void *opaque)
570 {
571     RADOSCB *rcb = opaque;
572     qemu_bh_delete(rcb->acb->bh);
573     qemu_rbd_complete_aio(rcb);
574 }
575 
576 /*
577  * This is the callback function for rbd_aio_read and _write
578  *
579  * Note: this function is being called from a non qemu thread so
580  * we need to be careful about what we do here. Generally we only
581  * schedule a BH, and do the rest of the io completion handling
582  * from rbd_finish_bh() which runs in a qemu context.
583  */
584 static void rbd_finish_aiocb(rbd_completion_t c, RADOSCB *rcb)
585 {
586     RBDAIOCB *acb = rcb->acb;
587 
588     rcb->ret = rbd_aio_get_return_value(c);
589     rbd_aio_release(c);
590 
591     acb->bh = aio_bh_new(bdrv_get_aio_context(acb->common.bs),
592                          rbd_finish_bh, rcb);
593     qemu_bh_schedule(acb->bh);
594 }
595 
596 static int rbd_aio_discard_wrapper(rbd_image_t image,
597                                    uint64_t off,
598                                    uint64_t len,
599                                    rbd_completion_t comp)
600 {
601 #ifdef LIBRBD_SUPPORTS_DISCARD
602     return rbd_aio_discard(image, off, len, comp);
603 #else
604     return -ENOTSUP;
605 #endif
606 }
607 
608 static int rbd_aio_flush_wrapper(rbd_image_t image,
609                                  rbd_completion_t comp)
610 {
611 #ifdef LIBRBD_SUPPORTS_AIO_FLUSH
612     return rbd_aio_flush(image, comp);
613 #else
614     return -ENOTSUP;
615 #endif
616 }
617 
618 static BlockDriverAIOCB *rbd_start_aio(BlockDriverState *bs,
619                                        int64_t sector_num,
620                                        QEMUIOVector *qiov,
621                                        int nb_sectors,
622                                        BlockDriverCompletionFunc *cb,
623                                        void *opaque,
624                                        RBDAIOCmd cmd)
625 {
626     RBDAIOCB *acb;
627     RADOSCB *rcb;
628     rbd_completion_t c;
629     int64_t off, size;
630     char *buf;
631     int r;
632 
633     BDRVRBDState *s = bs->opaque;
634 
635     acb = qemu_aio_get(&rbd_aiocb_info, bs, cb, opaque);
636     acb->cmd = cmd;
637     acb->qiov = qiov;
638     if (cmd == RBD_AIO_DISCARD || cmd == RBD_AIO_FLUSH) {
639         acb->bounce = NULL;
640     } else {
641         acb->bounce = qemu_blockalign(bs, qiov->size);
642     }
643     acb->ret = 0;
644     acb->error = 0;
645     acb->s = s;
646     acb->cancelled = 0;
647     acb->bh = NULL;
648     acb->status = -EINPROGRESS;
649 
650     if (cmd == RBD_AIO_WRITE) {
651         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
652     }
653 
654     buf = acb->bounce;
655 
656     off = sector_num * BDRV_SECTOR_SIZE;
657     size = nb_sectors * BDRV_SECTOR_SIZE;
658 
659     rcb = g_malloc(sizeof(RADOSCB));
660     rcb->done = 0;
661     rcb->acb = acb;
662     rcb->buf = buf;
663     rcb->s = acb->s;
664     rcb->size = size;
665     r = rbd_aio_create_completion(rcb, (rbd_callback_t) rbd_finish_aiocb, &c);
666     if (r < 0) {
667         goto failed;
668     }
669 
670     switch (cmd) {
671     case RBD_AIO_WRITE:
672         r = rbd_aio_write(s->image, off, size, buf, c);
673         break;
674     case RBD_AIO_READ:
675         r = rbd_aio_read(s->image, off, size, buf, c);
676         break;
677     case RBD_AIO_DISCARD:
678         r = rbd_aio_discard_wrapper(s->image, off, size, c);
679         break;
680     case RBD_AIO_FLUSH:
681         r = rbd_aio_flush_wrapper(s->image, c);
682         break;
683     default:
684         r = -EINVAL;
685     }
686 
687     if (r < 0) {
688         goto failed_completion;
689     }
690 
691     return &acb->common;
692 
693 failed_completion:
694     rbd_aio_release(c);
695 failed:
696     g_free(rcb);
697     qemu_vfree(acb->bounce);
698     qemu_aio_release(acb);
699     return NULL;
700 }
701 
702 static BlockDriverAIOCB *qemu_rbd_aio_readv(BlockDriverState *bs,
703                                             int64_t sector_num,
704                                             QEMUIOVector *qiov,
705                                             int nb_sectors,
706                                             BlockDriverCompletionFunc *cb,
707                                             void *opaque)
708 {
709     return rbd_start_aio(bs, sector_num, qiov, nb_sectors, cb, opaque,
710                          RBD_AIO_READ);
711 }
712 
713 static BlockDriverAIOCB *qemu_rbd_aio_writev(BlockDriverState *bs,
714                                              int64_t sector_num,
715                                              QEMUIOVector *qiov,
716                                              int nb_sectors,
717                                              BlockDriverCompletionFunc *cb,
718                                              void *opaque)
719 {
720     return rbd_start_aio(bs, sector_num, qiov, nb_sectors, cb, opaque,
721                          RBD_AIO_WRITE);
722 }
723 
724 #ifdef LIBRBD_SUPPORTS_AIO_FLUSH
725 static BlockDriverAIOCB *qemu_rbd_aio_flush(BlockDriverState *bs,
726                                             BlockDriverCompletionFunc *cb,
727                                             void *opaque)
728 {
729     return rbd_start_aio(bs, 0, NULL, 0, cb, opaque, RBD_AIO_FLUSH);
730 }
731 
732 #else
733 
734 static int qemu_rbd_co_flush(BlockDriverState *bs)
735 {
736 #if LIBRBD_VERSION_CODE >= LIBRBD_VERSION(0, 1, 1)
737     /* rbd_flush added in 0.1.1 */
738     BDRVRBDState *s = bs->opaque;
739     return rbd_flush(s->image);
740 #else
741     return 0;
742 #endif
743 }
744 #endif
745 
746 static int qemu_rbd_getinfo(BlockDriverState *bs, BlockDriverInfo *bdi)
747 {
748     BDRVRBDState *s = bs->opaque;
749     rbd_image_info_t info;
750     int r;
751 
752     r = rbd_stat(s->image, &info, sizeof(info));
753     if (r < 0) {
754         return r;
755     }
756 
757     bdi->cluster_size = info.obj_size;
758     return 0;
759 }
760 
761 static int64_t qemu_rbd_getlength(BlockDriverState *bs)
762 {
763     BDRVRBDState *s = bs->opaque;
764     rbd_image_info_t info;
765     int r;
766 
767     r = rbd_stat(s->image, &info, sizeof(info));
768     if (r < 0) {
769         return r;
770     }
771 
772     return info.size;
773 }
774 
775 static int qemu_rbd_truncate(BlockDriverState *bs, int64_t offset)
776 {
777     BDRVRBDState *s = bs->opaque;
778     int r;
779 
780     r = rbd_resize(s->image, offset);
781     if (r < 0) {
782         return r;
783     }
784 
785     return 0;
786 }
787 
788 static int qemu_rbd_snap_create(BlockDriverState *bs,
789                                 QEMUSnapshotInfo *sn_info)
790 {
791     BDRVRBDState *s = bs->opaque;
792     int r;
793 
794     if (sn_info->name[0] == '\0') {
795         return -EINVAL; /* we need a name for rbd snapshots */
796     }
797 
798     /*
799      * rbd snapshots are using the name as the user controlled unique identifier
800      * we can't use the rbd snapid for that purpose, as it can't be set
801      */
802     if (sn_info->id_str[0] != '\0' &&
803         strcmp(sn_info->id_str, sn_info->name) != 0) {
804         return -EINVAL;
805     }
806 
807     if (strlen(sn_info->name) >= sizeof(sn_info->id_str)) {
808         return -ERANGE;
809     }
810 
811     r = rbd_snap_create(s->image, sn_info->name);
812     if (r < 0) {
813         error_report("failed to create snap: %s", strerror(-r));
814         return r;
815     }
816 
817     return 0;
818 }
819 
820 static int qemu_rbd_snap_remove(BlockDriverState *bs,
821                                 const char *snapshot_id,
822                                 const char *snapshot_name,
823                                 Error **errp)
824 {
825     BDRVRBDState *s = bs->opaque;
826     int r;
827 
828     if (!snapshot_name) {
829         error_setg(errp, "rbd need a valid snapshot name");
830         return -EINVAL;
831     }
832 
833     /* If snapshot_id is specified, it must be equal to name, see
834        qemu_rbd_snap_list() */
835     if (snapshot_id && strcmp(snapshot_id, snapshot_name)) {
836         error_setg(errp,
837                    "rbd do not support snapshot id, it should be NULL or "
838                    "equal to snapshot name");
839         return -EINVAL;
840     }
841 
842     r = rbd_snap_remove(s->image, snapshot_name);
843     if (r < 0) {
844         error_setg_errno(errp, -r, "Failed to remove the snapshot");
845     }
846     return r;
847 }
848 
849 static int qemu_rbd_snap_rollback(BlockDriverState *bs,
850                                   const char *snapshot_name)
851 {
852     BDRVRBDState *s = bs->opaque;
853     int r;
854 
855     r = rbd_snap_rollback(s->image, snapshot_name);
856     return r;
857 }
858 
859 static int qemu_rbd_snap_list(BlockDriverState *bs,
860                               QEMUSnapshotInfo **psn_tab)
861 {
862     BDRVRBDState *s = bs->opaque;
863     QEMUSnapshotInfo *sn_info, *sn_tab = NULL;
864     int i, snap_count;
865     rbd_snap_info_t *snaps;
866     int max_snaps = RBD_MAX_SNAPS;
867 
868     do {
869         snaps = g_malloc(sizeof(*snaps) * max_snaps);
870         snap_count = rbd_snap_list(s->image, snaps, &max_snaps);
871         if (snap_count <= 0) {
872             g_free(snaps);
873         }
874     } while (snap_count == -ERANGE);
875 
876     if (snap_count <= 0) {
877         goto done;
878     }
879 
880     sn_tab = g_malloc0(snap_count * sizeof(QEMUSnapshotInfo));
881 
882     for (i = 0; i < snap_count; i++) {
883         const char *snap_name = snaps[i].name;
884 
885         sn_info = sn_tab + i;
886         pstrcpy(sn_info->id_str, sizeof(sn_info->id_str), snap_name);
887         pstrcpy(sn_info->name, sizeof(sn_info->name), snap_name);
888 
889         sn_info->vm_state_size = snaps[i].size;
890         sn_info->date_sec = 0;
891         sn_info->date_nsec = 0;
892         sn_info->vm_clock_nsec = 0;
893     }
894     rbd_snap_list_end(snaps);
895     g_free(snaps);
896 
897  done:
898     *psn_tab = sn_tab;
899     return snap_count;
900 }
901 
902 #ifdef LIBRBD_SUPPORTS_DISCARD
903 static BlockDriverAIOCB* qemu_rbd_aio_discard(BlockDriverState *bs,
904                                               int64_t sector_num,
905                                               int nb_sectors,
906                                               BlockDriverCompletionFunc *cb,
907                                               void *opaque)
908 {
909     return rbd_start_aio(bs, sector_num, NULL, nb_sectors, cb, opaque,
910                          RBD_AIO_DISCARD);
911 }
912 #endif
913 
914 static QEMUOptionParameter qemu_rbd_create_options[] = {
915     {
916      .name = BLOCK_OPT_SIZE,
917      .type = OPT_SIZE,
918      .help = "Virtual disk size"
919     },
920     {
921      .name = BLOCK_OPT_CLUSTER_SIZE,
922      .type = OPT_SIZE,
923      .help = "RBD object size"
924     },
925     {NULL}
926 };
927 
928 static BlockDriver bdrv_rbd = {
929     .format_name        = "rbd",
930     .instance_size      = sizeof(BDRVRBDState),
931     .bdrv_needs_filename = true,
932     .bdrv_file_open     = qemu_rbd_open,
933     .bdrv_close         = qemu_rbd_close,
934     .bdrv_create        = qemu_rbd_create,
935     .bdrv_has_zero_init = bdrv_has_zero_init_1,
936     .bdrv_get_info      = qemu_rbd_getinfo,
937     .create_options     = qemu_rbd_create_options,
938     .bdrv_getlength     = qemu_rbd_getlength,
939     .bdrv_truncate      = qemu_rbd_truncate,
940     .protocol_name      = "rbd",
941 
942     .bdrv_aio_readv         = qemu_rbd_aio_readv,
943     .bdrv_aio_writev        = qemu_rbd_aio_writev,
944 
945 #ifdef LIBRBD_SUPPORTS_AIO_FLUSH
946     .bdrv_aio_flush         = qemu_rbd_aio_flush,
947 #else
948     .bdrv_co_flush_to_disk  = qemu_rbd_co_flush,
949 #endif
950 
951 #ifdef LIBRBD_SUPPORTS_DISCARD
952     .bdrv_aio_discard       = qemu_rbd_aio_discard,
953 #endif
954 
955     .bdrv_snapshot_create   = qemu_rbd_snap_create,
956     .bdrv_snapshot_delete   = qemu_rbd_snap_remove,
957     .bdrv_snapshot_list     = qemu_rbd_snap_list,
958     .bdrv_snapshot_goto     = qemu_rbd_snap_rollback,
959 };
960 
961 static void bdrv_rbd_init(void)
962 {
963     bdrv_register(&bdrv_rbd);
964 }
965 
966 block_init(bdrv_rbd_init);
967