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