xref: /qemu/block/gluster.c (revision 01b2ffce)
1 /*
2  * GlusterFS backend for QEMU
3  *
4  * Copyright (C) 2012 Bharata B Rao <bharata@linux.vnet.ibm.com>
5  *
6  * This work is licensed under the terms of the GNU GPL, version 2 or later.
7  * See the COPYING file in the top-level directory.
8  *
9  */
10 #include "qemu/osdep.h"
11 #include <glusterfs/api/glfs.h>
12 #include "block/block_int.h"
13 #include "qapi/error.h"
14 #include "qapi/qmp/qerror.h"
15 #include "qapi/util.h"
16 #include "qemu/uri.h"
17 #include "qemu/error-report.h"
18 #include "qemu/cutils.h"
19 
20 #define GLUSTER_OPT_FILENAME        "filename"
21 #define GLUSTER_OPT_VOLUME          "volume"
22 #define GLUSTER_OPT_PATH            "path"
23 #define GLUSTER_OPT_TYPE            "type"
24 #define GLUSTER_OPT_SERVER_PATTERN  "server."
25 #define GLUSTER_OPT_HOST            "host"
26 #define GLUSTER_OPT_PORT            "port"
27 #define GLUSTER_OPT_TO              "to"
28 #define GLUSTER_OPT_IPV4            "ipv4"
29 #define GLUSTER_OPT_IPV6            "ipv6"
30 #define GLUSTER_OPT_SOCKET          "socket"
31 #define GLUSTER_OPT_DEBUG           "debug"
32 #define GLUSTER_DEFAULT_PORT        24007
33 #define GLUSTER_DEBUG_DEFAULT       4
34 #define GLUSTER_DEBUG_MAX           9
35 #define GLUSTER_OPT_LOGFILE         "logfile"
36 #define GLUSTER_LOGFILE_DEFAULT     "-" /* handled in libgfapi as /dev/stderr */
37 
38 #define GERR_INDEX_HINT "hint: check in 'server' array index '%d'\n"
39 
40 typedef struct GlusterAIOCB {
41     int64_t size;
42     int ret;
43     Coroutine *coroutine;
44     AioContext *aio_context;
45 } GlusterAIOCB;
46 
47 typedef struct BDRVGlusterState {
48     struct glfs *glfs;
49     struct glfs_fd *fd;
50     char *logfile;
51     bool supports_seek_data;
52     int debug;
53 } BDRVGlusterState;
54 
55 typedef struct BDRVGlusterReopenState {
56     struct glfs *glfs;
57     struct glfs_fd *fd;
58 } BDRVGlusterReopenState;
59 
60 
61 typedef struct GlfsPreopened {
62     char *volume;
63     glfs_t *fs;
64     int ref;
65 } GlfsPreopened;
66 
67 typedef struct ListElement {
68     QLIST_ENTRY(ListElement) list;
69     GlfsPreopened saved;
70 } ListElement;
71 
72 static QLIST_HEAD(glfs_list, ListElement) glfs_list;
73 
74 static QemuOptsList qemu_gluster_create_opts = {
75     .name = "qemu-gluster-create-opts",
76     .head = QTAILQ_HEAD_INITIALIZER(qemu_gluster_create_opts.head),
77     .desc = {
78         {
79             .name = BLOCK_OPT_SIZE,
80             .type = QEMU_OPT_SIZE,
81             .help = "Virtual disk size"
82         },
83         {
84             .name = BLOCK_OPT_PREALLOC,
85             .type = QEMU_OPT_STRING,
86             .help = "Preallocation mode (allowed values: off, full)"
87         },
88         {
89             .name = GLUSTER_OPT_DEBUG,
90             .type = QEMU_OPT_NUMBER,
91             .help = "Gluster log level, valid range is 0-9",
92         },
93         {
94             .name = GLUSTER_OPT_LOGFILE,
95             .type = QEMU_OPT_STRING,
96             .help = "Logfile path of libgfapi",
97         },
98         { /* end of list */ }
99     }
100 };
101 
102 static QemuOptsList runtime_opts = {
103     .name = "gluster",
104     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
105     .desc = {
106         {
107             .name = GLUSTER_OPT_FILENAME,
108             .type = QEMU_OPT_STRING,
109             .help = "URL to the gluster image",
110         },
111         {
112             .name = GLUSTER_OPT_DEBUG,
113             .type = QEMU_OPT_NUMBER,
114             .help = "Gluster log level, valid range is 0-9",
115         },
116         {
117             .name = GLUSTER_OPT_LOGFILE,
118             .type = QEMU_OPT_STRING,
119             .help = "Logfile path of libgfapi",
120         },
121         { /* end of list */ }
122     },
123 };
124 
125 static QemuOptsList runtime_json_opts = {
126     .name = "gluster_json",
127     .head = QTAILQ_HEAD_INITIALIZER(runtime_json_opts.head),
128     .desc = {
129         {
130             .name = GLUSTER_OPT_VOLUME,
131             .type = QEMU_OPT_STRING,
132             .help = "name of gluster volume where VM image resides",
133         },
134         {
135             .name = GLUSTER_OPT_PATH,
136             .type = QEMU_OPT_STRING,
137             .help = "absolute path to image file in gluster volume",
138         },
139         {
140             .name = GLUSTER_OPT_DEBUG,
141             .type = QEMU_OPT_NUMBER,
142             .help = "Gluster log level, valid range is 0-9",
143         },
144         { /* end of list */ }
145     },
146 };
147 
148 static QemuOptsList runtime_type_opts = {
149     .name = "gluster_type",
150     .head = QTAILQ_HEAD_INITIALIZER(runtime_type_opts.head),
151     .desc = {
152         {
153             .name = GLUSTER_OPT_TYPE,
154             .type = QEMU_OPT_STRING,
155             .help = "inet|unix",
156         },
157         { /* end of list */ }
158     },
159 };
160 
161 static QemuOptsList runtime_unix_opts = {
162     .name = "gluster_unix",
163     .head = QTAILQ_HEAD_INITIALIZER(runtime_unix_opts.head),
164     .desc = {
165         {
166             .name = GLUSTER_OPT_SOCKET,
167             .type = QEMU_OPT_STRING,
168             .help = "socket file path)",
169         },
170         { /* end of list */ }
171     },
172 };
173 
174 static QemuOptsList runtime_inet_opts = {
175     .name = "gluster_inet",
176     .head = QTAILQ_HEAD_INITIALIZER(runtime_inet_opts.head),
177     .desc = {
178         {
179             .name = GLUSTER_OPT_TYPE,
180             .type = QEMU_OPT_STRING,
181             .help = "inet|unix",
182         },
183         {
184             .name = GLUSTER_OPT_HOST,
185             .type = QEMU_OPT_STRING,
186             .help = "host address (hostname/ipv4/ipv6 addresses)",
187         },
188         {
189             .name = GLUSTER_OPT_PORT,
190             .type = QEMU_OPT_STRING,
191             .help = "port number on which glusterd is listening (default 24007)",
192         },
193         {
194             .name = "to",
195             .type = QEMU_OPT_NUMBER,
196             .help = "max port number, not supported by gluster",
197         },
198         {
199             .name = "ipv4",
200             .type = QEMU_OPT_BOOL,
201             .help = "ipv4 bool value, not supported by gluster",
202         },
203         {
204             .name = "ipv6",
205             .type = QEMU_OPT_BOOL,
206             .help = "ipv6 bool value, not supported by gluster",
207         },
208         { /* end of list */ }
209     },
210 };
211 
212 static void glfs_set_preopened(const char *volume, glfs_t *fs)
213 {
214     ListElement *entry = NULL;
215 
216     entry = g_new(ListElement, 1);
217 
218     entry->saved.volume = g_strdup(volume);
219 
220     entry->saved.fs = fs;
221     entry->saved.ref = 1;
222 
223     QLIST_INSERT_HEAD(&glfs_list, entry, list);
224 }
225 
226 static glfs_t *glfs_find_preopened(const char *volume)
227 {
228     ListElement *entry = NULL;
229 
230      QLIST_FOREACH(entry, &glfs_list, list) {
231         if (strcmp(entry->saved.volume, volume) == 0) {
232             entry->saved.ref++;
233             return entry->saved.fs;
234         }
235      }
236 
237     return NULL;
238 }
239 
240 static void glfs_clear_preopened(glfs_t *fs)
241 {
242     ListElement *entry = NULL;
243     ListElement *next;
244 
245     if (fs == NULL) {
246         return;
247     }
248 
249     QLIST_FOREACH_SAFE(entry, &glfs_list, list, next) {
250         if (entry->saved.fs == fs) {
251             if (--entry->saved.ref) {
252                 return;
253             }
254 
255             QLIST_REMOVE(entry, list);
256 
257             glfs_fini(entry->saved.fs);
258             g_free(entry->saved.volume);
259             g_free(entry);
260         }
261     }
262 }
263 
264 static int parse_volume_options(BlockdevOptionsGluster *gconf, char *path)
265 {
266     char *p, *q;
267 
268     if (!path) {
269         return -EINVAL;
270     }
271 
272     /* volume */
273     p = q = path + strspn(path, "/");
274     p += strcspn(p, "/");
275     if (*p == '\0') {
276         return -EINVAL;
277     }
278     gconf->volume = g_strndup(q, p - q);
279 
280     /* path */
281     p += strspn(p, "/");
282     if (*p == '\0') {
283         return -EINVAL;
284     }
285     gconf->path = g_strdup(p);
286     return 0;
287 }
288 
289 /*
290  * file=gluster[+transport]://[host[:port]]/volume/path[?socket=...]
291  *
292  * 'gluster' is the protocol.
293  *
294  * 'transport' specifies the transport type used to connect to gluster
295  * management daemon (glusterd). Valid transport types are
296  * tcp or unix. If a transport type isn't specified, then tcp type is assumed.
297  *
298  * 'host' specifies the host where the volume file specification for
299  * the given volume resides. This can be either hostname or ipv4 address.
300  * If transport type is 'unix', then 'host' field should not be specified.
301  * The 'socket' field needs to be populated with the path to unix domain
302  * socket.
303  *
304  * 'port' is the port number on which glusterd is listening. This is optional
305  * and if not specified, QEMU will send 0 which will make gluster to use the
306  * default port. If the transport type is unix, then 'port' should not be
307  * specified.
308  *
309  * 'volume' is the name of the gluster volume which contains the VM image.
310  *
311  * 'path' is the path to the actual VM image that resides on gluster volume.
312  *
313  * Examples:
314  *
315  * file=gluster://1.2.3.4/testvol/a.img
316  * file=gluster+tcp://1.2.3.4/testvol/a.img
317  * file=gluster+tcp://1.2.3.4:24007/testvol/dir/a.img
318  * file=gluster+tcp://host.domain.com:24007/testvol/dir/a.img
319  * file=gluster+unix:///testvol/dir/a.img?socket=/tmp/glusterd.socket
320  */
321 static int qemu_gluster_parse_uri(BlockdevOptionsGluster *gconf,
322                                   const char *filename)
323 {
324     SocketAddress *gsconf;
325     URI *uri;
326     QueryParams *qp = NULL;
327     bool is_unix = false;
328     int ret = 0;
329 
330     uri = uri_parse(filename);
331     if (!uri) {
332         return -EINVAL;
333     }
334 
335     gconf->server = g_new0(SocketAddressList, 1);
336     gconf->server->value = gsconf = g_new0(SocketAddress, 1);
337 
338     /* transport */
339     if (!uri->scheme || !strcmp(uri->scheme, "gluster")) {
340         gsconf->type = SOCKET_ADDRESS_TYPE_INET;
341     } else if (!strcmp(uri->scheme, "gluster+tcp")) {
342         gsconf->type = SOCKET_ADDRESS_TYPE_INET;
343     } else if (!strcmp(uri->scheme, "gluster+unix")) {
344         gsconf->type = SOCKET_ADDRESS_TYPE_UNIX;
345         is_unix = true;
346     } else if (!strcmp(uri->scheme, "gluster+rdma")) {
347         gsconf->type = SOCKET_ADDRESS_TYPE_INET;
348         error_report("Warning: rdma feature is not supported, falling "
349                      "back to tcp");
350     } else {
351         ret = -EINVAL;
352         goto out;
353     }
354 
355     ret = parse_volume_options(gconf, uri->path);
356     if (ret < 0) {
357         goto out;
358     }
359 
360     qp = query_params_parse(uri->query);
361     if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
362         ret = -EINVAL;
363         goto out;
364     }
365 
366     if (is_unix) {
367         if (uri->server || uri->port) {
368             ret = -EINVAL;
369             goto out;
370         }
371         if (strcmp(qp->p[0].name, "socket")) {
372             ret = -EINVAL;
373             goto out;
374         }
375         gsconf->u.q_unix.path = g_strdup(qp->p[0].value);
376     } else {
377         gsconf->u.inet.host = g_strdup(uri->server ? uri->server : "localhost");
378         if (uri->port) {
379             gsconf->u.inet.port = g_strdup_printf("%d", uri->port);
380         } else {
381             gsconf->u.inet.port = g_strdup_printf("%d", GLUSTER_DEFAULT_PORT);
382         }
383     }
384 
385 out:
386     if (qp) {
387         query_params_free(qp);
388     }
389     uri_free(uri);
390     return ret;
391 }
392 
393 static struct glfs *qemu_gluster_glfs_init(BlockdevOptionsGluster *gconf,
394                                            Error **errp)
395 {
396     struct glfs *glfs;
397     int ret;
398     int old_errno;
399     SocketAddressList *server;
400     unsigned long long port;
401 
402     glfs = glfs_find_preopened(gconf->volume);
403     if (glfs) {
404         return glfs;
405     }
406 
407     glfs = glfs_new(gconf->volume);
408     if (!glfs) {
409         goto out;
410     }
411 
412     glfs_set_preopened(gconf->volume, glfs);
413 
414     for (server = gconf->server; server; server = server->next) {
415         switch (server->value->type) {
416         case SOCKET_ADDRESS_TYPE_UNIX:
417             ret = glfs_set_volfile_server(glfs, "unix",
418                                    server->value->u.q_unix.path, 0);
419             break;
420         case SOCKET_ADDRESS_TYPE_INET:
421             if (parse_uint_full(server->value->u.inet.port, &port, 10) < 0 ||
422                 port > 65535) {
423                 error_setg(errp, "'%s' is not a valid port number",
424                            server->value->u.inet.port);
425                 errno = EINVAL;
426                 goto out;
427             }
428             ret = glfs_set_volfile_server(glfs, "tcp",
429                                    server->value->u.inet.host,
430                                    (int)port);
431             break;
432         case SOCKET_ADDRESS_TYPE_VSOCK:
433         case SOCKET_ADDRESS_TYPE_FD:
434         default:
435             abort();
436         }
437 
438         if (ret < 0) {
439             goto out;
440         }
441     }
442 
443     ret = glfs_set_logging(glfs, gconf->logfile, gconf->debug);
444     if (ret < 0) {
445         goto out;
446     }
447 
448     ret = glfs_init(glfs);
449     if (ret) {
450         error_setg(errp, "Gluster connection for volume %s, path %s failed"
451                          " to connect", gconf->volume, gconf->path);
452         for (server = gconf->server; server; server = server->next) {
453             if (server->value->type  == SOCKET_ADDRESS_TYPE_UNIX) {
454                 error_append_hint(errp, "hint: failed on socket %s ",
455                                   server->value->u.q_unix.path);
456             } else {
457                 error_append_hint(errp, "hint: failed on host %s and port %s ",
458                                   server->value->u.inet.host,
459                                   server->value->u.inet.port);
460             }
461         }
462 
463         error_append_hint(errp, "Please refer to gluster logs for more info\n");
464 
465         /* glfs_init sometimes doesn't set errno although docs suggest that */
466         if (errno == 0) {
467             errno = EINVAL;
468         }
469 
470         goto out;
471     }
472     return glfs;
473 
474 out:
475     if (glfs) {
476         old_errno = errno;
477         glfs_clear_preopened(glfs);
478         errno = old_errno;
479     }
480     return NULL;
481 }
482 
483 /*
484  * Convert the json formatted command line into qapi.
485 */
486 static int qemu_gluster_parse_json(BlockdevOptionsGluster *gconf,
487                                   QDict *options, Error **errp)
488 {
489     QemuOpts *opts;
490     SocketAddress *gsconf = NULL;
491     SocketAddressList *curr = NULL;
492     QDict *backing_options = NULL;
493     Error *local_err = NULL;
494     char *str = NULL;
495     const char *ptr;
496     int i, type, num_servers;
497 
498     /* create opts info from runtime_json_opts list */
499     opts = qemu_opts_create(&runtime_json_opts, NULL, 0, &error_abort);
500     qemu_opts_absorb_qdict(opts, options, &local_err);
501     if (local_err) {
502         goto out;
503     }
504 
505     num_servers = qdict_array_entries(options, GLUSTER_OPT_SERVER_PATTERN);
506     if (num_servers < 1) {
507         error_setg(&local_err, QERR_MISSING_PARAMETER, "server");
508         goto out;
509     }
510 
511     ptr = qemu_opt_get(opts, GLUSTER_OPT_VOLUME);
512     if (!ptr) {
513         error_setg(&local_err, QERR_MISSING_PARAMETER, GLUSTER_OPT_VOLUME);
514         goto out;
515     }
516     gconf->volume = g_strdup(ptr);
517 
518     ptr = qemu_opt_get(opts, GLUSTER_OPT_PATH);
519     if (!ptr) {
520         error_setg(&local_err, QERR_MISSING_PARAMETER, GLUSTER_OPT_PATH);
521         goto out;
522     }
523     gconf->path = g_strdup(ptr);
524     qemu_opts_del(opts);
525 
526     for (i = 0; i < num_servers; i++) {
527         str = g_strdup_printf(GLUSTER_OPT_SERVER_PATTERN"%d.", i);
528         qdict_extract_subqdict(options, &backing_options, str);
529 
530         /* create opts info from runtime_type_opts list */
531         opts = qemu_opts_create(&runtime_type_opts, NULL, 0, &error_abort);
532         qemu_opts_absorb_qdict(opts, backing_options, &local_err);
533         if (local_err) {
534             goto out;
535         }
536 
537         ptr = qemu_opt_get(opts, GLUSTER_OPT_TYPE);
538         if (!ptr) {
539             error_setg(&local_err, QERR_MISSING_PARAMETER, GLUSTER_OPT_TYPE);
540             error_append_hint(&local_err, GERR_INDEX_HINT, i);
541             goto out;
542 
543         }
544         gsconf = g_new0(SocketAddress, 1);
545         if (!strcmp(ptr, "tcp")) {
546             ptr = "inet";       /* accept legacy "tcp" */
547         }
548         type = qapi_enum_parse(SocketAddressType_lookup, ptr,
549                                SOCKET_ADDRESS_TYPE__MAX, -1, NULL);
550         if (type != SOCKET_ADDRESS_TYPE_INET
551             && type != SOCKET_ADDRESS_TYPE_UNIX) {
552             error_setg(&local_err,
553                        "Parameter '%s' may be 'inet' or 'unix'",
554                        GLUSTER_OPT_TYPE);
555             error_append_hint(&local_err, GERR_INDEX_HINT, i);
556             goto out;
557         }
558         gsconf->type = type;
559         qemu_opts_del(opts);
560 
561         if (gsconf->type == SOCKET_ADDRESS_TYPE_INET) {
562             /* create opts info from runtime_inet_opts list */
563             opts = qemu_opts_create(&runtime_inet_opts, NULL, 0, &error_abort);
564             qemu_opts_absorb_qdict(opts, backing_options, &local_err);
565             if (local_err) {
566                 goto out;
567             }
568 
569             ptr = qemu_opt_get(opts, GLUSTER_OPT_HOST);
570             if (!ptr) {
571                 error_setg(&local_err, QERR_MISSING_PARAMETER,
572                            GLUSTER_OPT_HOST);
573                 error_append_hint(&local_err, GERR_INDEX_HINT, i);
574                 goto out;
575             }
576             gsconf->u.inet.host = g_strdup(ptr);
577             ptr = qemu_opt_get(opts, GLUSTER_OPT_PORT);
578             if (!ptr) {
579                 error_setg(&local_err, QERR_MISSING_PARAMETER,
580                            GLUSTER_OPT_PORT);
581                 error_append_hint(&local_err, GERR_INDEX_HINT, i);
582                 goto out;
583             }
584             gsconf->u.inet.port = g_strdup(ptr);
585 
586             /* defend for unsupported fields in InetSocketAddress,
587              * i.e. @ipv4, @ipv6  and @to
588              */
589             ptr = qemu_opt_get(opts, GLUSTER_OPT_TO);
590             if (ptr) {
591                 gsconf->u.inet.has_to = true;
592             }
593             ptr = qemu_opt_get(opts, GLUSTER_OPT_IPV4);
594             if (ptr) {
595                 gsconf->u.inet.has_ipv4 = true;
596             }
597             ptr = qemu_opt_get(opts, GLUSTER_OPT_IPV6);
598             if (ptr) {
599                 gsconf->u.inet.has_ipv6 = true;
600             }
601             if (gsconf->u.inet.has_to) {
602                 error_setg(&local_err, "Parameter 'to' not supported");
603                 goto out;
604             }
605             if (gsconf->u.inet.has_ipv4 || gsconf->u.inet.has_ipv6) {
606                 error_setg(&local_err, "Parameters 'ipv4/ipv6' not supported");
607                 goto out;
608             }
609             qemu_opts_del(opts);
610         } else {
611             /* create opts info from runtime_unix_opts list */
612             opts = qemu_opts_create(&runtime_unix_opts, NULL, 0, &error_abort);
613             qemu_opts_absorb_qdict(opts, backing_options, &local_err);
614             if (local_err) {
615                 goto out;
616             }
617 
618             ptr = qemu_opt_get(opts, GLUSTER_OPT_SOCKET);
619             if (!ptr) {
620                 error_setg(&local_err, QERR_MISSING_PARAMETER,
621                            GLUSTER_OPT_SOCKET);
622                 error_append_hint(&local_err, GERR_INDEX_HINT, i);
623                 goto out;
624             }
625             gsconf->u.q_unix.path = g_strdup(ptr);
626             qemu_opts_del(opts);
627         }
628 
629         if (gconf->server == NULL) {
630             gconf->server = g_new0(SocketAddressList, 1);
631             gconf->server->value = gsconf;
632             curr = gconf->server;
633         } else {
634             curr->next = g_new0(SocketAddressList, 1);
635             curr->next->value = gsconf;
636             curr = curr->next;
637         }
638         gsconf = NULL;
639 
640         QDECREF(backing_options);
641         backing_options = NULL;
642         g_free(str);
643         str = NULL;
644     }
645 
646     return 0;
647 
648 out:
649     error_propagate(errp, local_err);
650     qapi_free_SocketAddress(gsconf);
651     qemu_opts_del(opts);
652     g_free(str);
653     QDECREF(backing_options);
654     errno = EINVAL;
655     return -errno;
656 }
657 
658 static struct glfs *qemu_gluster_init(BlockdevOptionsGluster *gconf,
659                                       const char *filename,
660                                       QDict *options, Error **errp)
661 {
662     int ret;
663     if (filename) {
664         ret = qemu_gluster_parse_uri(gconf, filename);
665         if (ret < 0) {
666             error_setg(errp, "invalid URI");
667             error_append_hint(errp, "Usage: file=gluster[+transport]://"
668                                     "[host[:port]]volume/path[?socket=...]"
669                                     "[,file.debug=N]"
670                                     "[,file.logfile=/path/filename.log]\n");
671             errno = -ret;
672             return NULL;
673         }
674     } else {
675         ret = qemu_gluster_parse_json(gconf, options, errp);
676         if (ret < 0) {
677             error_append_hint(errp, "Usage: "
678                              "-drive driver=qcow2,file.driver=gluster,"
679                              "file.volume=testvol,file.path=/path/a.qcow2"
680                              "[,file.debug=9]"
681                              "[,file.logfile=/path/filename.log],"
682                              "file.server.0.type=inet,"
683                              "file.server.0.host=1.2.3.4,"
684                              "file.server.0.port=24007,"
685                              "file.server.1.transport=unix,"
686                              "file.server.1.socket=/var/run/glusterd.socket ..."
687                              "\n");
688             errno = -ret;
689             return NULL;
690         }
691 
692     }
693 
694     return qemu_gluster_glfs_init(gconf, errp);
695 }
696 
697 /*
698  * AIO callback routine called from GlusterFS thread.
699  */
700 static void gluster_finish_aiocb(struct glfs_fd *fd, ssize_t ret, void *arg)
701 {
702     GlusterAIOCB *acb = (GlusterAIOCB *)arg;
703 
704     if (!ret || ret == acb->size) {
705         acb->ret = 0; /* Success */
706     } else if (ret < 0) {
707         acb->ret = -errno; /* Read/Write failed */
708     } else {
709         acb->ret = -EIO; /* Partial read/write - fail it */
710     }
711 
712     aio_co_schedule(acb->aio_context, acb->coroutine);
713 }
714 
715 static void qemu_gluster_parse_flags(int bdrv_flags, int *open_flags)
716 {
717     assert(open_flags != NULL);
718 
719     *open_flags |= O_BINARY;
720 
721     if (bdrv_flags & BDRV_O_RDWR) {
722         *open_flags |= O_RDWR;
723     } else {
724         *open_flags |= O_RDONLY;
725     }
726 
727     if ((bdrv_flags & BDRV_O_NOCACHE)) {
728         *open_flags |= O_DIRECT;
729     }
730 }
731 
732 /*
733  * Do SEEK_DATA/HOLE to detect if it is functional. Older broken versions of
734  * gfapi incorrectly return the current offset when SEEK_DATA/HOLE is used.
735  * - Corrected versions return -1 and set errno to EINVAL.
736  * - Versions that support SEEK_DATA/HOLE correctly, will return -1 and set
737  *   errno to ENXIO when SEEK_DATA is called with a position of EOF.
738  */
739 static bool qemu_gluster_test_seek(struct glfs_fd *fd)
740 {
741     off_t ret = 0;
742 
743 #if defined SEEK_HOLE && defined SEEK_DATA
744     off_t eof;
745 
746     eof = glfs_lseek(fd, 0, SEEK_END);
747     if (eof < 0) {
748         /* this should never occur */
749         return false;
750     }
751 
752     /* this should always fail with ENXIO if SEEK_DATA is supported */
753     ret = glfs_lseek(fd, eof, SEEK_DATA);
754 #endif
755 
756     return (ret < 0) && (errno == ENXIO);
757 }
758 
759 static int qemu_gluster_open(BlockDriverState *bs,  QDict *options,
760                              int bdrv_flags, Error **errp)
761 {
762     BDRVGlusterState *s = bs->opaque;
763     int open_flags = 0;
764     int ret = 0;
765     BlockdevOptionsGluster *gconf = NULL;
766     QemuOpts *opts;
767     Error *local_err = NULL;
768     const char *filename, *logfile;
769 
770     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
771     qemu_opts_absorb_qdict(opts, options, &local_err);
772     if (local_err) {
773         error_propagate(errp, local_err);
774         ret = -EINVAL;
775         goto out;
776     }
777 
778     filename = qemu_opt_get(opts, GLUSTER_OPT_FILENAME);
779 
780     s->debug = qemu_opt_get_number(opts, GLUSTER_OPT_DEBUG,
781                                    GLUSTER_DEBUG_DEFAULT);
782     if (s->debug < 0) {
783         s->debug = 0;
784     } else if (s->debug > GLUSTER_DEBUG_MAX) {
785         s->debug = GLUSTER_DEBUG_MAX;
786     }
787 
788     gconf = g_new0(BlockdevOptionsGluster, 1);
789     gconf->debug = s->debug;
790     gconf->has_debug = true;
791 
792     logfile = qemu_opt_get(opts, GLUSTER_OPT_LOGFILE);
793     s->logfile = g_strdup(logfile ? logfile : GLUSTER_LOGFILE_DEFAULT);
794 
795     gconf->logfile = g_strdup(s->logfile);
796     gconf->has_logfile = true;
797 
798     s->glfs = qemu_gluster_init(gconf, filename, options, errp);
799     if (!s->glfs) {
800         ret = -errno;
801         goto out;
802     }
803 
804 #ifdef CONFIG_GLUSTERFS_XLATOR_OPT
805     /* Without this, if fsync fails for a recoverable reason (for instance,
806      * ENOSPC), gluster will dump its cache, preventing retries.  This means
807      * almost certain data loss.  Not all gluster versions support the
808      * 'resync-failed-syncs-after-fsync' key value, but there is no way to
809      * discover during runtime if it is supported (this api returns success for
810      * unknown key/value pairs) */
811     ret = glfs_set_xlator_option(s->glfs, "*-write-behind",
812                                           "resync-failed-syncs-after-fsync",
813                                           "on");
814     if (ret < 0) {
815         error_setg_errno(errp, errno, "Unable to set xlator key/value pair");
816         ret = -errno;
817         goto out;
818     }
819 #endif
820 
821     qemu_gluster_parse_flags(bdrv_flags, &open_flags);
822 
823     s->fd = glfs_open(s->glfs, gconf->path, open_flags);
824     if (!s->fd) {
825         ret = -errno;
826     }
827 
828     s->supports_seek_data = qemu_gluster_test_seek(s->fd);
829 
830 out:
831     qemu_opts_del(opts);
832     qapi_free_BlockdevOptionsGluster(gconf);
833     if (!ret) {
834         return ret;
835     }
836     g_free(s->logfile);
837     if (s->fd) {
838         glfs_close(s->fd);
839     }
840 
841     glfs_clear_preopened(s->glfs);
842 
843     return ret;
844 }
845 
846 static int qemu_gluster_reopen_prepare(BDRVReopenState *state,
847                                        BlockReopenQueue *queue, Error **errp)
848 {
849     int ret = 0;
850     BDRVGlusterState *s;
851     BDRVGlusterReopenState *reop_s;
852     BlockdevOptionsGluster *gconf;
853     int open_flags = 0;
854 
855     assert(state != NULL);
856     assert(state->bs != NULL);
857 
858     s = state->bs->opaque;
859 
860     state->opaque = g_new0(BDRVGlusterReopenState, 1);
861     reop_s = state->opaque;
862 
863     qemu_gluster_parse_flags(state->flags, &open_flags);
864 
865     gconf = g_new0(BlockdevOptionsGluster, 1);
866     gconf->debug = s->debug;
867     gconf->has_debug = true;
868     gconf->logfile = g_strdup(s->logfile);
869     gconf->has_logfile = true;
870     reop_s->glfs = qemu_gluster_init(gconf, state->bs->filename, NULL, errp);
871     if (reop_s->glfs == NULL) {
872         ret = -errno;
873         goto exit;
874     }
875 
876 #ifdef CONFIG_GLUSTERFS_XLATOR_OPT
877     ret = glfs_set_xlator_option(reop_s->glfs, "*-write-behind",
878                                  "resync-failed-syncs-after-fsync", "on");
879     if (ret < 0) {
880         error_setg_errno(errp, errno, "Unable to set xlator key/value pair");
881         ret = -errno;
882         goto exit;
883     }
884 #endif
885 
886     reop_s->fd = glfs_open(reop_s->glfs, gconf->path, open_flags);
887     if (reop_s->fd == NULL) {
888         /* reops->glfs will be cleaned up in _abort */
889         ret = -errno;
890         goto exit;
891     }
892 
893 exit:
894     /* state->opaque will be freed in either the _abort or _commit */
895     qapi_free_BlockdevOptionsGluster(gconf);
896     return ret;
897 }
898 
899 static void qemu_gluster_reopen_commit(BDRVReopenState *state)
900 {
901     BDRVGlusterReopenState *reop_s = state->opaque;
902     BDRVGlusterState *s = state->bs->opaque;
903 
904 
905     /* close the old */
906     if (s->fd) {
907         glfs_close(s->fd);
908     }
909 
910     glfs_clear_preopened(s->glfs);
911 
912     /* use the newly opened image / connection */
913     s->fd         = reop_s->fd;
914     s->glfs       = reop_s->glfs;
915 
916     g_free(state->opaque);
917     state->opaque = NULL;
918 
919     return;
920 }
921 
922 
923 static void qemu_gluster_reopen_abort(BDRVReopenState *state)
924 {
925     BDRVGlusterReopenState *reop_s = state->opaque;
926 
927     if (reop_s == NULL) {
928         return;
929     }
930 
931     if (reop_s->fd) {
932         glfs_close(reop_s->fd);
933     }
934 
935     glfs_clear_preopened(reop_s->glfs);
936 
937     g_free(state->opaque);
938     state->opaque = NULL;
939 
940     return;
941 }
942 
943 #ifdef CONFIG_GLUSTERFS_ZEROFILL
944 static coroutine_fn int qemu_gluster_co_pwrite_zeroes(BlockDriverState *bs,
945                                                       int64_t offset,
946                                                       int size,
947                                                       BdrvRequestFlags flags)
948 {
949     int ret;
950     GlusterAIOCB acb;
951     BDRVGlusterState *s = bs->opaque;
952 
953     acb.size = size;
954     acb.ret = 0;
955     acb.coroutine = qemu_coroutine_self();
956     acb.aio_context = bdrv_get_aio_context(bs);
957 
958     ret = glfs_zerofill_async(s->fd, offset, size, gluster_finish_aiocb, &acb);
959     if (ret < 0) {
960         return -errno;
961     }
962 
963     qemu_coroutine_yield();
964     return acb.ret;
965 }
966 #endif
967 
968 static int qemu_gluster_create(const char *filename,
969                                QemuOpts *opts, Error **errp)
970 {
971     BlockdevOptionsGluster *gconf;
972     struct glfs *glfs;
973     struct glfs_fd *fd;
974     int ret = 0;
975     PreallocMode prealloc;
976     int64_t total_size = 0;
977     char *tmp = NULL;
978     Error *local_err = NULL;
979 
980     gconf = g_new0(BlockdevOptionsGluster, 1);
981     gconf->debug = qemu_opt_get_number_del(opts, GLUSTER_OPT_DEBUG,
982                                            GLUSTER_DEBUG_DEFAULT);
983     if (gconf->debug < 0) {
984         gconf->debug = 0;
985     } else if (gconf->debug > GLUSTER_DEBUG_MAX) {
986         gconf->debug = GLUSTER_DEBUG_MAX;
987     }
988     gconf->has_debug = true;
989 
990     gconf->logfile = qemu_opt_get_del(opts, GLUSTER_OPT_LOGFILE);
991     if (!gconf->logfile) {
992         gconf->logfile = g_strdup(GLUSTER_LOGFILE_DEFAULT);
993     }
994     gconf->has_logfile = true;
995 
996     glfs = qemu_gluster_init(gconf, filename, NULL, errp);
997     if (!glfs) {
998         ret = -errno;
999         goto out;
1000     }
1001 
1002     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1003                           BDRV_SECTOR_SIZE);
1004 
1005     tmp = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1006     prealloc = qapi_enum_parse(PreallocMode_lookup, tmp,
1007                                PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
1008                                &local_err);
1009     g_free(tmp);
1010     if (local_err) {
1011         error_propagate(errp, local_err);
1012         ret = -EINVAL;
1013         goto out;
1014     }
1015 
1016     fd = glfs_creat(glfs, gconf->path,
1017                     O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR | S_IWUSR);
1018     if (!fd) {
1019         ret = -errno;
1020         goto out;
1021     }
1022 
1023     switch (prealloc) {
1024 #ifdef CONFIG_GLUSTERFS_FALLOCATE
1025     case PREALLOC_MODE_FALLOC:
1026         if (glfs_fallocate(fd, 0, 0, total_size)) {
1027             error_setg(errp, "Could not preallocate data for the new file");
1028             ret = -errno;
1029         }
1030         break;
1031 #endif /* CONFIG_GLUSTERFS_FALLOCATE */
1032 #ifdef CONFIG_GLUSTERFS_ZEROFILL
1033     case PREALLOC_MODE_FULL:
1034         if (!glfs_ftruncate(fd, total_size)) {
1035             if (glfs_zerofill(fd, 0, total_size)) {
1036                 error_setg(errp, "Could not zerofill the new file");
1037                 ret = -errno;
1038             }
1039         } else {
1040             error_setg(errp, "Could not resize file");
1041             ret = -errno;
1042         }
1043         break;
1044 #endif /* CONFIG_GLUSTERFS_ZEROFILL */
1045     case PREALLOC_MODE_OFF:
1046         if (glfs_ftruncate(fd, total_size) != 0) {
1047             ret = -errno;
1048             error_setg(errp, "Could not resize file");
1049         }
1050         break;
1051     default:
1052         ret = -EINVAL;
1053         error_setg(errp, "Unsupported preallocation mode: %s",
1054                    PreallocMode_lookup[prealloc]);
1055         break;
1056     }
1057 
1058     if (glfs_close(fd) != 0) {
1059         ret = -errno;
1060     }
1061 out:
1062     qapi_free_BlockdevOptionsGluster(gconf);
1063     glfs_clear_preopened(glfs);
1064     return ret;
1065 }
1066 
1067 static coroutine_fn int qemu_gluster_co_rw(BlockDriverState *bs,
1068                                            int64_t sector_num, int nb_sectors,
1069                                            QEMUIOVector *qiov, int write)
1070 {
1071     int ret;
1072     GlusterAIOCB acb;
1073     BDRVGlusterState *s = bs->opaque;
1074     size_t size = nb_sectors * BDRV_SECTOR_SIZE;
1075     off_t offset = sector_num * BDRV_SECTOR_SIZE;
1076 
1077     acb.size = size;
1078     acb.ret = 0;
1079     acb.coroutine = qemu_coroutine_self();
1080     acb.aio_context = bdrv_get_aio_context(bs);
1081 
1082     if (write) {
1083         ret = glfs_pwritev_async(s->fd, qiov->iov, qiov->niov, offset, 0,
1084                                  gluster_finish_aiocb, &acb);
1085     } else {
1086         ret = glfs_preadv_async(s->fd, qiov->iov, qiov->niov, offset, 0,
1087                                 gluster_finish_aiocb, &acb);
1088     }
1089 
1090     if (ret < 0) {
1091         return -errno;
1092     }
1093 
1094     qemu_coroutine_yield();
1095     return acb.ret;
1096 }
1097 
1098 static int qemu_gluster_truncate(BlockDriverState *bs, int64_t offset,
1099                                  Error **errp)
1100 {
1101     int ret;
1102     BDRVGlusterState *s = bs->opaque;
1103 
1104     ret = glfs_ftruncate(s->fd, offset);
1105     if (ret < 0) {
1106         ret = -errno;
1107         error_setg_errno(errp, -ret, "Failed to truncate file");
1108         return ret;
1109     }
1110 
1111     return 0;
1112 }
1113 
1114 static coroutine_fn int qemu_gluster_co_readv(BlockDriverState *bs,
1115                                               int64_t sector_num,
1116                                               int nb_sectors,
1117                                               QEMUIOVector *qiov)
1118 {
1119     return qemu_gluster_co_rw(bs, sector_num, nb_sectors, qiov, 0);
1120 }
1121 
1122 static coroutine_fn int qemu_gluster_co_writev(BlockDriverState *bs,
1123                                                int64_t sector_num,
1124                                                int nb_sectors,
1125                                                QEMUIOVector *qiov)
1126 {
1127     return qemu_gluster_co_rw(bs, sector_num, nb_sectors, qiov, 1);
1128 }
1129 
1130 static void qemu_gluster_close(BlockDriverState *bs)
1131 {
1132     BDRVGlusterState *s = bs->opaque;
1133 
1134     g_free(s->logfile);
1135     if (s->fd) {
1136         glfs_close(s->fd);
1137         s->fd = NULL;
1138     }
1139     glfs_clear_preopened(s->glfs);
1140 }
1141 
1142 static coroutine_fn int qemu_gluster_co_flush_to_disk(BlockDriverState *bs)
1143 {
1144     int ret;
1145     GlusterAIOCB acb;
1146     BDRVGlusterState *s = bs->opaque;
1147 
1148     acb.size = 0;
1149     acb.ret = 0;
1150     acb.coroutine = qemu_coroutine_self();
1151     acb.aio_context = bdrv_get_aio_context(bs);
1152 
1153     ret = glfs_fsync_async(s->fd, gluster_finish_aiocb, &acb);
1154     if (ret < 0) {
1155         ret = -errno;
1156         goto error;
1157     }
1158 
1159     qemu_coroutine_yield();
1160     if (acb.ret < 0) {
1161         ret = acb.ret;
1162         goto error;
1163     }
1164 
1165     return acb.ret;
1166 
1167 error:
1168     /* Some versions of Gluster (3.5.6 -> 3.5.8?) will not retain its cache
1169      * after a fsync failure, so we have no way of allowing the guest to safely
1170      * continue.  Gluster versions prior to 3.5.6 don't retain the cache
1171      * either, but will invalidate the fd on error, so this is again our only
1172      * option.
1173      *
1174      * The 'resync-failed-syncs-after-fsync' xlator option for the
1175      * write-behind cache will cause later gluster versions to retain its
1176      * cache after error, so long as the fd remains open.  However, we
1177      * currently have no way of knowing if this option is supported.
1178      *
1179      * TODO: Once gluster provides a way for us to determine if the option
1180      * is supported, bypass the closure and setting drv to NULL.  */
1181     qemu_gluster_close(bs);
1182     bs->drv = NULL;
1183     return ret;
1184 }
1185 
1186 #ifdef CONFIG_GLUSTERFS_DISCARD
1187 static coroutine_fn int qemu_gluster_co_pdiscard(BlockDriverState *bs,
1188                                                  int64_t offset, int size)
1189 {
1190     int ret;
1191     GlusterAIOCB acb;
1192     BDRVGlusterState *s = bs->opaque;
1193 
1194     acb.size = 0;
1195     acb.ret = 0;
1196     acb.coroutine = qemu_coroutine_self();
1197     acb.aio_context = bdrv_get_aio_context(bs);
1198 
1199     ret = glfs_discard_async(s->fd, offset, size, gluster_finish_aiocb, &acb);
1200     if (ret < 0) {
1201         return -errno;
1202     }
1203 
1204     qemu_coroutine_yield();
1205     return acb.ret;
1206 }
1207 #endif
1208 
1209 static int64_t qemu_gluster_getlength(BlockDriverState *bs)
1210 {
1211     BDRVGlusterState *s = bs->opaque;
1212     int64_t ret;
1213 
1214     ret = glfs_lseek(s->fd, 0, SEEK_END);
1215     if (ret < 0) {
1216         return -errno;
1217     } else {
1218         return ret;
1219     }
1220 }
1221 
1222 static int64_t qemu_gluster_allocated_file_size(BlockDriverState *bs)
1223 {
1224     BDRVGlusterState *s = bs->opaque;
1225     struct stat st;
1226     int ret;
1227 
1228     ret = glfs_fstat(s->fd, &st);
1229     if (ret < 0) {
1230         return -errno;
1231     } else {
1232         return st.st_blocks * 512;
1233     }
1234 }
1235 
1236 static int qemu_gluster_has_zero_init(BlockDriverState *bs)
1237 {
1238     /* GlusterFS volume could be backed by a block device */
1239     return 0;
1240 }
1241 
1242 /*
1243  * Find allocation range in @bs around offset @start.
1244  * May change underlying file descriptor's file offset.
1245  * If @start is not in a hole, store @start in @data, and the
1246  * beginning of the next hole in @hole, and return 0.
1247  * If @start is in a non-trailing hole, store @start in @hole and the
1248  * beginning of the next non-hole in @data, and return 0.
1249  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1250  * If we can't find out, return a negative errno other than -ENXIO.
1251  *
1252  * (Shamefully copied from file-posix.c, only miniscule adaptions.)
1253  */
1254 static int find_allocation(BlockDriverState *bs, off_t start,
1255                            off_t *data, off_t *hole)
1256 {
1257     BDRVGlusterState *s = bs->opaque;
1258 
1259     if (!s->supports_seek_data) {
1260         goto exit;
1261     }
1262 
1263 #if defined SEEK_HOLE && defined SEEK_DATA
1264     off_t offs;
1265 
1266     /*
1267      * SEEK_DATA cases:
1268      * D1. offs == start: start is in data
1269      * D2. offs > start: start is in a hole, next data at offs
1270      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1271      *                              or start is beyond EOF
1272      *     If the latter happens, the file has been truncated behind
1273      *     our back since we opened it.  All bets are off then.
1274      *     Treating like a trailing hole is simplest.
1275      * D4. offs < 0, errno != ENXIO: we learned nothing
1276      */
1277     offs = glfs_lseek(s->fd, start, SEEK_DATA);
1278     if (offs < 0) {
1279         return -errno;          /* D3 or D4 */
1280     }
1281 
1282     if (offs < start) {
1283         /* This is not a valid return by lseek().  We are safe to just return
1284          * -EIO in this case, and we'll treat it like D4. Unfortunately some
1285          *  versions of gluster server will return offs < start, so an assert
1286          *  here will unnecessarily abort QEMU. */
1287         return -EIO;
1288     }
1289 
1290     if (offs > start) {
1291         /* D2: in hole, next data at offs */
1292         *hole = start;
1293         *data = offs;
1294         return 0;
1295     }
1296 
1297     /* D1: in data, end not yet known */
1298 
1299     /*
1300      * SEEK_HOLE cases:
1301      * H1. offs == start: start is in a hole
1302      *     If this happens here, a hole has been dug behind our back
1303      *     since the previous lseek().
1304      * H2. offs > start: either start is in data, next hole at offs,
1305      *                   or start is in trailing hole, EOF at offs
1306      *     Linux treats trailing holes like any other hole: offs ==
1307      *     start.  Solaris seeks to EOF instead: offs > start (blech).
1308      *     If that happens here, a hole has been dug behind our back
1309      *     since the previous lseek().
1310      * H3. offs < 0, errno = ENXIO: start is beyond EOF
1311      *     If this happens, the file has been truncated behind our
1312      *     back since we opened it.  Treat it like a trailing hole.
1313      * H4. offs < 0, errno != ENXIO: we learned nothing
1314      *     Pretend we know nothing at all, i.e. "forget" about D1.
1315      */
1316     offs = glfs_lseek(s->fd, start, SEEK_HOLE);
1317     if (offs < 0) {
1318         return -errno;          /* D1 and (H3 or H4) */
1319     }
1320 
1321     if (offs < start) {
1322         /* This is not a valid return by lseek().  We are safe to just return
1323          * -EIO in this case, and we'll treat it like H4. Unfortunately some
1324          *  versions of gluster server will return offs < start, so an assert
1325          *  here will unnecessarily abort QEMU. */
1326         return -EIO;
1327     }
1328 
1329     if (offs > start) {
1330         /*
1331          * D1 and H2: either in data, next hole at offs, or it was in
1332          * data but is now in a trailing hole.  In the latter case,
1333          * all bets are off.  Treating it as if it there was data all
1334          * the way to EOF is safe, so simply do that.
1335          */
1336         *data = start;
1337         *hole = offs;
1338         return 0;
1339     }
1340 
1341     /* D1 and H1 */
1342     return -EBUSY;
1343 #endif
1344 
1345 exit:
1346     return -ENOTSUP;
1347 }
1348 
1349 /*
1350  * Returns the allocation status of the specified sectors.
1351  *
1352  * If 'sector_num' is beyond the end of the disk image the return value is 0
1353  * and 'pnum' is set to 0.
1354  *
1355  * 'pnum' is set to the number of sectors (including and immediately following
1356  * the specified sector) that are known to be in the same
1357  * allocated/unallocated state.
1358  *
1359  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
1360  * beyond the end of the disk image it will be clamped.
1361  *
1362  * (Based on raw_co_get_block_status() from file-posix.c.)
1363  */
1364 static int64_t coroutine_fn qemu_gluster_co_get_block_status(
1365         BlockDriverState *bs, int64_t sector_num, int nb_sectors, int *pnum,
1366         BlockDriverState **file)
1367 {
1368     BDRVGlusterState *s = bs->opaque;
1369     off_t start, data = 0, hole = 0;
1370     int64_t total_size;
1371     int ret = -EINVAL;
1372 
1373     if (!s->fd) {
1374         return ret;
1375     }
1376 
1377     start = sector_num * BDRV_SECTOR_SIZE;
1378     total_size = bdrv_getlength(bs);
1379     if (total_size < 0) {
1380         return total_size;
1381     } else if (start >= total_size) {
1382         *pnum = 0;
1383         return 0;
1384     } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
1385         nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
1386     }
1387 
1388     ret = find_allocation(bs, start, &data, &hole);
1389     if (ret == -ENXIO) {
1390         /* Trailing hole */
1391         *pnum = nb_sectors;
1392         ret = BDRV_BLOCK_ZERO;
1393     } else if (ret < 0) {
1394         /* No info available, so pretend there are no holes */
1395         *pnum = nb_sectors;
1396         ret = BDRV_BLOCK_DATA;
1397     } else if (data == start) {
1398         /* On a data extent, compute sectors to the end of the extent,
1399          * possibly including a partial sector at EOF. */
1400         *pnum = MIN(nb_sectors, DIV_ROUND_UP(hole - start, BDRV_SECTOR_SIZE));
1401         ret = BDRV_BLOCK_DATA;
1402     } else {
1403         /* On a hole, compute sectors to the beginning of the next extent.  */
1404         assert(hole == start);
1405         *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1406         ret = BDRV_BLOCK_ZERO;
1407     }
1408 
1409     *file = bs;
1410 
1411     return ret | BDRV_BLOCK_OFFSET_VALID | start;
1412 }
1413 
1414 
1415 static BlockDriver bdrv_gluster = {
1416     .format_name                  = "gluster",
1417     .protocol_name                = "gluster",
1418     .instance_size                = sizeof(BDRVGlusterState),
1419     .bdrv_needs_filename          = false,
1420     .bdrv_file_open               = qemu_gluster_open,
1421     .bdrv_reopen_prepare          = qemu_gluster_reopen_prepare,
1422     .bdrv_reopen_commit           = qemu_gluster_reopen_commit,
1423     .bdrv_reopen_abort            = qemu_gluster_reopen_abort,
1424     .bdrv_close                   = qemu_gluster_close,
1425     .bdrv_create                  = qemu_gluster_create,
1426     .bdrv_getlength               = qemu_gluster_getlength,
1427     .bdrv_get_allocated_file_size = qemu_gluster_allocated_file_size,
1428     .bdrv_truncate                = qemu_gluster_truncate,
1429     .bdrv_co_readv                = qemu_gluster_co_readv,
1430     .bdrv_co_writev               = qemu_gluster_co_writev,
1431     .bdrv_co_flush_to_disk        = qemu_gluster_co_flush_to_disk,
1432     .bdrv_has_zero_init           = qemu_gluster_has_zero_init,
1433 #ifdef CONFIG_GLUSTERFS_DISCARD
1434     .bdrv_co_pdiscard             = qemu_gluster_co_pdiscard,
1435 #endif
1436 #ifdef CONFIG_GLUSTERFS_ZEROFILL
1437     .bdrv_co_pwrite_zeroes        = qemu_gluster_co_pwrite_zeroes,
1438 #endif
1439     .bdrv_co_get_block_status     = qemu_gluster_co_get_block_status,
1440     .create_opts                  = &qemu_gluster_create_opts,
1441 };
1442 
1443 static BlockDriver bdrv_gluster_tcp = {
1444     .format_name                  = "gluster",
1445     .protocol_name                = "gluster+tcp",
1446     .instance_size                = sizeof(BDRVGlusterState),
1447     .bdrv_needs_filename          = false,
1448     .bdrv_file_open               = qemu_gluster_open,
1449     .bdrv_reopen_prepare          = qemu_gluster_reopen_prepare,
1450     .bdrv_reopen_commit           = qemu_gluster_reopen_commit,
1451     .bdrv_reopen_abort            = qemu_gluster_reopen_abort,
1452     .bdrv_close                   = qemu_gluster_close,
1453     .bdrv_create                  = qemu_gluster_create,
1454     .bdrv_getlength               = qemu_gluster_getlength,
1455     .bdrv_get_allocated_file_size = qemu_gluster_allocated_file_size,
1456     .bdrv_truncate                = qemu_gluster_truncate,
1457     .bdrv_co_readv                = qemu_gluster_co_readv,
1458     .bdrv_co_writev               = qemu_gluster_co_writev,
1459     .bdrv_co_flush_to_disk        = qemu_gluster_co_flush_to_disk,
1460     .bdrv_has_zero_init           = qemu_gluster_has_zero_init,
1461 #ifdef CONFIG_GLUSTERFS_DISCARD
1462     .bdrv_co_pdiscard             = qemu_gluster_co_pdiscard,
1463 #endif
1464 #ifdef CONFIG_GLUSTERFS_ZEROFILL
1465     .bdrv_co_pwrite_zeroes        = qemu_gluster_co_pwrite_zeroes,
1466 #endif
1467     .bdrv_co_get_block_status     = qemu_gluster_co_get_block_status,
1468     .create_opts                  = &qemu_gluster_create_opts,
1469 };
1470 
1471 static BlockDriver bdrv_gluster_unix = {
1472     .format_name                  = "gluster",
1473     .protocol_name                = "gluster+unix",
1474     .instance_size                = sizeof(BDRVGlusterState),
1475     .bdrv_needs_filename          = true,
1476     .bdrv_file_open               = qemu_gluster_open,
1477     .bdrv_reopen_prepare          = qemu_gluster_reopen_prepare,
1478     .bdrv_reopen_commit           = qemu_gluster_reopen_commit,
1479     .bdrv_reopen_abort            = qemu_gluster_reopen_abort,
1480     .bdrv_close                   = qemu_gluster_close,
1481     .bdrv_create                  = qemu_gluster_create,
1482     .bdrv_getlength               = qemu_gluster_getlength,
1483     .bdrv_get_allocated_file_size = qemu_gluster_allocated_file_size,
1484     .bdrv_truncate                = qemu_gluster_truncate,
1485     .bdrv_co_readv                = qemu_gluster_co_readv,
1486     .bdrv_co_writev               = qemu_gluster_co_writev,
1487     .bdrv_co_flush_to_disk        = qemu_gluster_co_flush_to_disk,
1488     .bdrv_has_zero_init           = qemu_gluster_has_zero_init,
1489 #ifdef CONFIG_GLUSTERFS_DISCARD
1490     .bdrv_co_pdiscard             = qemu_gluster_co_pdiscard,
1491 #endif
1492 #ifdef CONFIG_GLUSTERFS_ZEROFILL
1493     .bdrv_co_pwrite_zeroes        = qemu_gluster_co_pwrite_zeroes,
1494 #endif
1495     .bdrv_co_get_block_status     = qemu_gluster_co_get_block_status,
1496     .create_opts                  = &qemu_gluster_create_opts,
1497 };
1498 
1499 /* rdma is deprecated (actually never supported for volfile fetch).
1500  * Let's maintain it for the protocol compatibility, to make sure things
1501  * won't break immediately. For now, gluster+rdma will fall back to gluster+tcp
1502  * protocol with a warning.
1503  * TODO: remove gluster+rdma interface support
1504  */
1505 static BlockDriver bdrv_gluster_rdma = {
1506     .format_name                  = "gluster",
1507     .protocol_name                = "gluster+rdma",
1508     .instance_size                = sizeof(BDRVGlusterState),
1509     .bdrv_needs_filename          = true,
1510     .bdrv_file_open               = qemu_gluster_open,
1511     .bdrv_reopen_prepare          = qemu_gluster_reopen_prepare,
1512     .bdrv_reopen_commit           = qemu_gluster_reopen_commit,
1513     .bdrv_reopen_abort            = qemu_gluster_reopen_abort,
1514     .bdrv_close                   = qemu_gluster_close,
1515     .bdrv_create                  = qemu_gluster_create,
1516     .bdrv_getlength               = qemu_gluster_getlength,
1517     .bdrv_get_allocated_file_size = qemu_gluster_allocated_file_size,
1518     .bdrv_truncate                = qemu_gluster_truncate,
1519     .bdrv_co_readv                = qemu_gluster_co_readv,
1520     .bdrv_co_writev               = qemu_gluster_co_writev,
1521     .bdrv_co_flush_to_disk        = qemu_gluster_co_flush_to_disk,
1522     .bdrv_has_zero_init           = qemu_gluster_has_zero_init,
1523 #ifdef CONFIG_GLUSTERFS_DISCARD
1524     .bdrv_co_pdiscard             = qemu_gluster_co_pdiscard,
1525 #endif
1526 #ifdef CONFIG_GLUSTERFS_ZEROFILL
1527     .bdrv_co_pwrite_zeroes        = qemu_gluster_co_pwrite_zeroes,
1528 #endif
1529     .bdrv_co_get_block_status     = qemu_gluster_co_get_block_status,
1530     .create_opts                  = &qemu_gluster_create_opts,
1531 };
1532 
1533 static void bdrv_gluster_init(void)
1534 {
1535     bdrv_register(&bdrv_gluster_rdma);
1536     bdrv_register(&bdrv_gluster_unix);
1537     bdrv_register(&bdrv_gluster_tcp);
1538     bdrv_register(&bdrv_gluster);
1539 }
1540 
1541 block_init(bdrv_gluster_init);
1542