xref: /openbmc/qemu/block/rbd.c (revision 07a32d6b)
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, QemuOpts *opts, Error **errp)
293 {
294     Error *local_err = NULL;
295     int64_t bytes = 0;
296     int64_t objsize;
297     int obj_order = 0;
298     char pool[RBD_MAX_POOL_NAME_SIZE];
299     char name[RBD_MAX_IMAGE_NAME_SIZE];
300     char snap_buf[RBD_MAX_SNAP_NAME_SIZE];
301     char conf[RBD_MAX_CONF_SIZE];
302     char clientname_buf[RBD_MAX_CONF_SIZE];
303     char *clientname;
304     rados_t cluster;
305     rados_ioctx_t io_ctx;
306     int ret;
307 
308     if (qemu_rbd_parsename(filename, pool, sizeof(pool),
309                            snap_buf, sizeof(snap_buf),
310                            name, sizeof(name),
311                            conf, sizeof(conf), &local_err) < 0) {
312         error_propagate(errp, local_err);
313         return -EINVAL;
314     }
315 
316     /* Read out options */
317     bytes = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
318     objsize = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE, 0);
319     if (objsize) {
320         if ((objsize - 1) & objsize) {    /* not a power of 2? */
321             error_setg(errp, "obj size needs to be power of 2");
322             return -EINVAL;
323         }
324         if (objsize < 4096) {
325             error_setg(errp, "obj size too small");
326             return -EINVAL;
327         }
328         obj_order = ffs(objsize) - 1;
329     }
330 
331     clientname = qemu_rbd_parse_clientname(conf, clientname_buf);
332     if (rados_create(&cluster, clientname) < 0) {
333         error_setg(errp, "error initializing");
334         return -EIO;
335     }
336 
337     if (strstr(conf, "conf=") == NULL) {
338         /* try default location, but ignore failure */
339         rados_conf_read_file(cluster, NULL);
340     }
341 
342     if (conf[0] != '\0' &&
343         qemu_rbd_set_conf(cluster, conf, &local_err) < 0) {
344         rados_shutdown(cluster);
345         error_propagate(errp, local_err);
346         return -EIO;
347     }
348 
349     if (rados_connect(cluster) < 0) {
350         error_setg(errp, "error connecting");
351         rados_shutdown(cluster);
352         return -EIO;
353     }
354 
355     if (rados_ioctx_create(cluster, pool, &io_ctx) < 0) {
356         error_setg(errp, "error opening pool %s", pool);
357         rados_shutdown(cluster);
358         return -EIO;
359     }
360 
361     ret = rbd_create(io_ctx, name, bytes, &obj_order);
362     rados_ioctx_destroy(io_ctx);
363     rados_shutdown(cluster);
364 
365     return ret;
366 }
367 
368 /*
369  * This aio completion is being called from rbd_finish_bh() and runs in qemu
370  * BH context.
371  */
372 static void qemu_rbd_complete_aio(RADOSCB *rcb)
373 {
374     RBDAIOCB *acb = rcb->acb;
375     int64_t r;
376 
377     r = rcb->ret;
378 
379     if (acb->cmd != RBD_AIO_READ) {
380         if (r < 0) {
381             acb->ret = r;
382             acb->error = 1;
383         } else if (!acb->error) {
384             acb->ret = rcb->size;
385         }
386     } else {
387         if (r < 0) {
388             memset(rcb->buf, 0, rcb->size);
389             acb->ret = r;
390             acb->error = 1;
391         } else if (r < rcb->size) {
392             memset(rcb->buf + r, 0, rcb->size - r);
393             if (!acb->error) {
394                 acb->ret = rcb->size;
395             }
396         } else if (!acb->error) {
397             acb->ret = r;
398         }
399     }
400 
401     g_free(rcb);
402 
403     if (acb->cmd == RBD_AIO_READ) {
404         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
405     }
406     qemu_vfree(acb->bounce);
407     acb->common.cb(acb->common.opaque, (acb->ret > 0 ? 0 : acb->ret));
408     acb->status = 0;
409 
410     if (!acb->cancelled) {
411         qemu_aio_release(acb);
412     }
413 }
414 
415 /* TODO Convert to fine grained options */
416 static QemuOptsList runtime_opts = {
417     .name = "rbd",
418     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
419     .desc = {
420         {
421             .name = "filename",
422             .type = QEMU_OPT_STRING,
423             .help = "Specification of the rbd image",
424         },
425         { /* end of list */ }
426     },
427 };
428 
429 static int qemu_rbd_open(BlockDriverState *bs, QDict *options, int flags,
430                          Error **errp)
431 {
432     BDRVRBDState *s = bs->opaque;
433     char pool[RBD_MAX_POOL_NAME_SIZE];
434     char snap_buf[RBD_MAX_SNAP_NAME_SIZE];
435     char conf[RBD_MAX_CONF_SIZE];
436     char clientname_buf[RBD_MAX_CONF_SIZE];
437     char *clientname;
438     QemuOpts *opts;
439     Error *local_err = NULL;
440     const char *filename;
441     int r;
442 
443     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
444     qemu_opts_absorb_qdict(opts, options, &local_err);
445     if (local_err) {
446         error_propagate(errp, local_err);
447         qemu_opts_del(opts);
448         return -EINVAL;
449     }
450 
451     filename = qemu_opt_get(opts, "filename");
452 
453     if (qemu_rbd_parsename(filename, pool, sizeof(pool),
454                            snap_buf, sizeof(snap_buf),
455                            s->name, sizeof(s->name),
456                            conf, sizeof(conf), errp) < 0) {
457         r = -EINVAL;
458         goto failed_opts;
459     }
460 
461     clientname = qemu_rbd_parse_clientname(conf, clientname_buf);
462     r = rados_create(&s->cluster, clientname);
463     if (r < 0) {
464         error_setg(&local_err, "error initializing");
465         goto failed_opts;
466     }
467 
468     s->snap = NULL;
469     if (snap_buf[0] != '\0') {
470         s->snap = g_strdup(snap_buf);
471     }
472 
473     /*
474      * Fallback to more conservative semantics if setting cache
475      * options fails. Ignore errors from setting rbd_cache because the
476      * only possible error is that the option does not exist, and
477      * librbd defaults to no caching. If write through caching cannot
478      * be set up, fall back to no caching.
479      */
480     if (flags & BDRV_O_NOCACHE) {
481         rados_conf_set(s->cluster, "rbd_cache", "false");
482     } else {
483         rados_conf_set(s->cluster, "rbd_cache", "true");
484     }
485 
486     if (strstr(conf, "conf=") == NULL) {
487         /* try default location, but ignore failure */
488         rados_conf_read_file(s->cluster, NULL);
489     }
490 
491     if (conf[0] != '\0') {
492         r = qemu_rbd_set_conf(s->cluster, conf, errp);
493         if (r < 0) {
494             goto failed_shutdown;
495         }
496     }
497 
498     r = rados_connect(s->cluster);
499     if (r < 0) {
500         error_setg(&local_err, "error connecting");
501         goto failed_shutdown;
502     }
503 
504     r = rados_ioctx_create(s->cluster, pool, &s->io_ctx);
505     if (r < 0) {
506         error_setg(&local_err, "error opening pool %s", pool);
507         goto failed_shutdown;
508     }
509 
510     r = rbd_open(s->io_ctx, s->name, &s->image, s->snap);
511     if (r < 0) {
512         error_setg(&local_err, "error reading header from %s", s->name);
513         goto failed_open;
514     }
515 
516     bs->read_only = (s->snap != NULL);
517 
518     qemu_opts_del(opts);
519     return 0;
520 
521 failed_open:
522     rados_ioctx_destroy(s->io_ctx);
523 failed_shutdown:
524     rados_shutdown(s->cluster);
525     g_free(s->snap);
526 failed_opts:
527     qemu_opts_del(opts);
528     return r;
529 }
530 
531 static void qemu_rbd_close(BlockDriverState *bs)
532 {
533     BDRVRBDState *s = bs->opaque;
534 
535     rbd_close(s->image);
536     rados_ioctx_destroy(s->io_ctx);
537     g_free(s->snap);
538     rados_shutdown(s->cluster);
539 }
540 
541 /*
542  * Cancel aio. Since we don't reference acb in a non qemu threads,
543  * it is safe to access it here.
544  */
545 static void qemu_rbd_aio_cancel(BlockDriverAIOCB *blockacb)
546 {
547     RBDAIOCB *acb = (RBDAIOCB *) blockacb;
548     acb->cancelled = 1;
549 
550     while (acb->status == -EINPROGRESS) {
551         aio_poll(bdrv_get_aio_context(acb->common.bs), true);
552     }
553 
554     qemu_aio_release(acb);
555 }
556 
557 static const AIOCBInfo rbd_aiocb_info = {
558     .aiocb_size = sizeof(RBDAIOCB),
559     .cancel = qemu_rbd_aio_cancel,
560 };
561 
562 static void rbd_finish_bh(void *opaque)
563 {
564     RADOSCB *rcb = opaque;
565     qemu_bh_delete(rcb->acb->bh);
566     qemu_rbd_complete_aio(rcb);
567 }
568 
569 /*
570  * This is the callback function for rbd_aio_read and _write
571  *
572  * Note: this function is being called from a non qemu thread so
573  * we need to be careful about what we do here. Generally we only
574  * schedule a BH, and do the rest of the io completion handling
575  * from rbd_finish_bh() which runs in a qemu context.
576  */
577 static void rbd_finish_aiocb(rbd_completion_t c, RADOSCB *rcb)
578 {
579     RBDAIOCB *acb = rcb->acb;
580 
581     rcb->ret = rbd_aio_get_return_value(c);
582     rbd_aio_release(c);
583 
584     acb->bh = aio_bh_new(bdrv_get_aio_context(acb->common.bs),
585                          rbd_finish_bh, rcb);
586     qemu_bh_schedule(acb->bh);
587 }
588 
589 static int rbd_aio_discard_wrapper(rbd_image_t image,
590                                    uint64_t off,
591                                    uint64_t len,
592                                    rbd_completion_t comp)
593 {
594 #ifdef LIBRBD_SUPPORTS_DISCARD
595     return rbd_aio_discard(image, off, len, comp);
596 #else
597     return -ENOTSUP;
598 #endif
599 }
600 
601 static int rbd_aio_flush_wrapper(rbd_image_t image,
602                                  rbd_completion_t comp)
603 {
604 #ifdef LIBRBD_SUPPORTS_AIO_FLUSH
605     return rbd_aio_flush(image, comp);
606 #else
607     return -ENOTSUP;
608 #endif
609 }
610 
611 static BlockDriverAIOCB *rbd_start_aio(BlockDriverState *bs,
612                                        int64_t sector_num,
613                                        QEMUIOVector *qiov,
614                                        int nb_sectors,
615                                        BlockDriverCompletionFunc *cb,
616                                        void *opaque,
617                                        RBDAIOCmd cmd)
618 {
619     RBDAIOCB *acb;
620     RADOSCB *rcb;
621     rbd_completion_t c;
622     int64_t off, size;
623     char *buf;
624     int r;
625 
626     BDRVRBDState *s = bs->opaque;
627 
628     acb = qemu_aio_get(&rbd_aiocb_info, bs, cb, opaque);
629     acb->cmd = cmd;
630     acb->qiov = qiov;
631     if (cmd == RBD_AIO_DISCARD || cmd == RBD_AIO_FLUSH) {
632         acb->bounce = NULL;
633     } else {
634         acb->bounce = qemu_blockalign(bs, qiov->size);
635     }
636     acb->ret = 0;
637     acb->error = 0;
638     acb->s = s;
639     acb->cancelled = 0;
640     acb->bh = NULL;
641     acb->status = -EINPROGRESS;
642 
643     if (cmd == RBD_AIO_WRITE) {
644         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
645     }
646 
647     buf = acb->bounce;
648 
649     off = sector_num * BDRV_SECTOR_SIZE;
650     size = nb_sectors * BDRV_SECTOR_SIZE;
651 
652     rcb = g_malloc(sizeof(RADOSCB));
653     rcb->done = 0;
654     rcb->acb = acb;
655     rcb->buf = buf;
656     rcb->s = acb->s;
657     rcb->size = size;
658     r = rbd_aio_create_completion(rcb, (rbd_callback_t) rbd_finish_aiocb, &c);
659     if (r < 0) {
660         goto failed;
661     }
662 
663     switch (cmd) {
664     case RBD_AIO_WRITE:
665         r = rbd_aio_write(s->image, off, size, buf, c);
666         break;
667     case RBD_AIO_READ:
668         r = rbd_aio_read(s->image, off, size, buf, c);
669         break;
670     case RBD_AIO_DISCARD:
671         r = rbd_aio_discard_wrapper(s->image, off, size, c);
672         break;
673     case RBD_AIO_FLUSH:
674         r = rbd_aio_flush_wrapper(s->image, c);
675         break;
676     default:
677         r = -EINVAL;
678     }
679 
680     if (r < 0) {
681         goto failed_completion;
682     }
683 
684     return &acb->common;
685 
686 failed_completion:
687     rbd_aio_release(c);
688 failed:
689     g_free(rcb);
690     qemu_vfree(acb->bounce);
691     qemu_aio_release(acb);
692     return NULL;
693 }
694 
695 static BlockDriverAIOCB *qemu_rbd_aio_readv(BlockDriverState *bs,
696                                             int64_t sector_num,
697                                             QEMUIOVector *qiov,
698                                             int nb_sectors,
699                                             BlockDriverCompletionFunc *cb,
700                                             void *opaque)
701 {
702     return rbd_start_aio(bs, sector_num, qiov, nb_sectors, cb, opaque,
703                          RBD_AIO_READ);
704 }
705 
706 static BlockDriverAIOCB *qemu_rbd_aio_writev(BlockDriverState *bs,
707                                              int64_t sector_num,
708                                              QEMUIOVector *qiov,
709                                              int nb_sectors,
710                                              BlockDriverCompletionFunc *cb,
711                                              void *opaque)
712 {
713     return rbd_start_aio(bs, sector_num, qiov, nb_sectors, cb, opaque,
714                          RBD_AIO_WRITE);
715 }
716 
717 #ifdef LIBRBD_SUPPORTS_AIO_FLUSH
718 static BlockDriverAIOCB *qemu_rbd_aio_flush(BlockDriverState *bs,
719                                             BlockDriverCompletionFunc *cb,
720                                             void *opaque)
721 {
722     return rbd_start_aio(bs, 0, NULL, 0, cb, opaque, RBD_AIO_FLUSH);
723 }
724 
725 #else
726 
727 static int qemu_rbd_co_flush(BlockDriverState *bs)
728 {
729 #if LIBRBD_VERSION_CODE >= LIBRBD_VERSION(0, 1, 1)
730     /* rbd_flush added in 0.1.1 */
731     BDRVRBDState *s = bs->opaque;
732     return rbd_flush(s->image);
733 #else
734     return 0;
735 #endif
736 }
737 #endif
738 
739 static int qemu_rbd_getinfo(BlockDriverState *bs, BlockDriverInfo *bdi)
740 {
741     BDRVRBDState *s = bs->opaque;
742     rbd_image_info_t info;
743     int r;
744 
745     r = rbd_stat(s->image, &info, sizeof(info));
746     if (r < 0) {
747         return r;
748     }
749 
750     bdi->cluster_size = info.obj_size;
751     return 0;
752 }
753 
754 static int64_t qemu_rbd_getlength(BlockDriverState *bs)
755 {
756     BDRVRBDState *s = bs->opaque;
757     rbd_image_info_t info;
758     int r;
759 
760     r = rbd_stat(s->image, &info, sizeof(info));
761     if (r < 0) {
762         return r;
763     }
764 
765     return info.size;
766 }
767 
768 static int qemu_rbd_truncate(BlockDriverState *bs, int64_t offset)
769 {
770     BDRVRBDState *s = bs->opaque;
771     int r;
772 
773     r = rbd_resize(s->image, offset);
774     if (r < 0) {
775         return r;
776     }
777 
778     return 0;
779 }
780 
781 static int qemu_rbd_snap_create(BlockDriverState *bs,
782                                 QEMUSnapshotInfo *sn_info)
783 {
784     BDRVRBDState *s = bs->opaque;
785     int r;
786 
787     if (sn_info->name[0] == '\0') {
788         return -EINVAL; /* we need a name for rbd snapshots */
789     }
790 
791     /*
792      * rbd snapshots are using the name as the user controlled unique identifier
793      * we can't use the rbd snapid for that purpose, as it can't be set
794      */
795     if (sn_info->id_str[0] != '\0' &&
796         strcmp(sn_info->id_str, sn_info->name) != 0) {
797         return -EINVAL;
798     }
799 
800     if (strlen(sn_info->name) >= sizeof(sn_info->id_str)) {
801         return -ERANGE;
802     }
803 
804     r = rbd_snap_create(s->image, sn_info->name);
805     if (r < 0) {
806         error_report("failed to create snap: %s", strerror(-r));
807         return r;
808     }
809 
810     return 0;
811 }
812 
813 static int qemu_rbd_snap_remove(BlockDriverState *bs,
814                                 const char *snapshot_id,
815                                 const char *snapshot_name,
816                                 Error **errp)
817 {
818     BDRVRBDState *s = bs->opaque;
819     int r;
820 
821     if (!snapshot_name) {
822         error_setg(errp, "rbd need a valid snapshot name");
823         return -EINVAL;
824     }
825 
826     /* If snapshot_id is specified, it must be equal to name, see
827        qemu_rbd_snap_list() */
828     if (snapshot_id && strcmp(snapshot_id, snapshot_name)) {
829         error_setg(errp,
830                    "rbd do not support snapshot id, it should be NULL or "
831                    "equal to snapshot name");
832         return -EINVAL;
833     }
834 
835     r = rbd_snap_remove(s->image, snapshot_name);
836     if (r < 0) {
837         error_setg_errno(errp, -r, "Failed to remove the snapshot");
838     }
839     return r;
840 }
841 
842 static int qemu_rbd_snap_rollback(BlockDriverState *bs,
843                                   const char *snapshot_name)
844 {
845     BDRVRBDState *s = bs->opaque;
846     int r;
847 
848     r = rbd_snap_rollback(s->image, snapshot_name);
849     return r;
850 }
851 
852 static int qemu_rbd_snap_list(BlockDriverState *bs,
853                               QEMUSnapshotInfo **psn_tab)
854 {
855     BDRVRBDState *s = bs->opaque;
856     QEMUSnapshotInfo *sn_info, *sn_tab = NULL;
857     int i, snap_count;
858     rbd_snap_info_t *snaps;
859     int max_snaps = RBD_MAX_SNAPS;
860 
861     do {
862         snaps = g_malloc(sizeof(*snaps) * max_snaps);
863         snap_count = rbd_snap_list(s->image, snaps, &max_snaps);
864         if (snap_count <= 0) {
865             g_free(snaps);
866         }
867     } while (snap_count == -ERANGE);
868 
869     if (snap_count <= 0) {
870         goto done;
871     }
872 
873     sn_tab = g_malloc0(snap_count * sizeof(QEMUSnapshotInfo));
874 
875     for (i = 0; i < snap_count; i++) {
876         const char *snap_name = snaps[i].name;
877 
878         sn_info = sn_tab + i;
879         pstrcpy(sn_info->id_str, sizeof(sn_info->id_str), snap_name);
880         pstrcpy(sn_info->name, sizeof(sn_info->name), snap_name);
881 
882         sn_info->vm_state_size = snaps[i].size;
883         sn_info->date_sec = 0;
884         sn_info->date_nsec = 0;
885         sn_info->vm_clock_nsec = 0;
886     }
887     rbd_snap_list_end(snaps);
888     g_free(snaps);
889 
890  done:
891     *psn_tab = sn_tab;
892     return snap_count;
893 }
894 
895 #ifdef LIBRBD_SUPPORTS_DISCARD
896 static BlockDriverAIOCB* qemu_rbd_aio_discard(BlockDriverState *bs,
897                                               int64_t sector_num,
898                                               int nb_sectors,
899                                               BlockDriverCompletionFunc *cb,
900                                               void *opaque)
901 {
902     return rbd_start_aio(bs, sector_num, NULL, nb_sectors, cb, opaque,
903                          RBD_AIO_DISCARD);
904 }
905 #endif
906 
907 static QemuOptsList qemu_rbd_create_opts = {
908     .name = "rbd-create-opts",
909     .head = QTAILQ_HEAD_INITIALIZER(qemu_rbd_create_opts.head),
910     .desc = {
911         {
912             .name = BLOCK_OPT_SIZE,
913             .type = QEMU_OPT_SIZE,
914             .help = "Virtual disk size"
915         },
916         {
917             .name = BLOCK_OPT_CLUSTER_SIZE,
918             .type = QEMU_OPT_SIZE,
919             .help = "RBD object size"
920         },
921         { /* end of list */ }
922     }
923 };
924 
925 static BlockDriver bdrv_rbd = {
926     .format_name        = "rbd",
927     .instance_size      = sizeof(BDRVRBDState),
928     .bdrv_needs_filename = true,
929     .bdrv_file_open     = qemu_rbd_open,
930     .bdrv_close         = qemu_rbd_close,
931     .bdrv_create        = qemu_rbd_create,
932     .bdrv_has_zero_init = bdrv_has_zero_init_1,
933     .bdrv_get_info      = qemu_rbd_getinfo,
934     .create_opts        = &qemu_rbd_create_opts,
935     .bdrv_getlength     = qemu_rbd_getlength,
936     .bdrv_truncate      = qemu_rbd_truncate,
937     .protocol_name      = "rbd",
938 
939     .bdrv_aio_readv         = qemu_rbd_aio_readv,
940     .bdrv_aio_writev        = qemu_rbd_aio_writev,
941 
942 #ifdef LIBRBD_SUPPORTS_AIO_FLUSH
943     .bdrv_aio_flush         = qemu_rbd_aio_flush,
944 #else
945     .bdrv_co_flush_to_disk  = qemu_rbd_co_flush,
946 #endif
947 
948 #ifdef LIBRBD_SUPPORTS_DISCARD
949     .bdrv_aio_discard       = qemu_rbd_aio_discard,
950 #endif
951 
952     .bdrv_snapshot_create   = qemu_rbd_snap_create,
953     .bdrv_snapshot_delete   = qemu_rbd_snap_remove,
954     .bdrv_snapshot_list     = qemu_rbd_snap_list,
955     .bdrv_snapshot_goto     = qemu_rbd_snap_rollback,
956 };
957 
958 static void bdrv_rbd_init(void)
959 {
960     bdrv_register(&bdrv_rbd);
961 }
962 
963 block_init(bdrv_rbd_init);
964