xref: /openbmc/qemu/block/gluster.c (revision b278b60d)
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-io.h"
15 #include "block/block_int.h"
16 #include "block/qdict.h"
17 #include "qapi/error.h"
18 #include "qapi/qmp/qdict.h"
19 #include "qapi/qmp/qerror.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"
102 #ifdef CONFIG_GLUSTERFS_FALLOCATE
103                     ", falloc"
104 #endif
105 #ifdef CONFIG_GLUSTERFS_ZEROFILL
106                     ", full"
107 #endif
108                     ")"
109         },
110         {
111             .name = GLUSTER_OPT_DEBUG,
112             .type = QEMU_OPT_NUMBER,
113             .help = "Gluster log level, valid range is 0-9",
114         },
115         {
116             .name = GLUSTER_OPT_LOGFILE,
117             .type = QEMU_OPT_STRING,
118             .help = "Logfile path of libgfapi",
119         },
120         { /* end of list */ }
121     }
122 };
123 
124 static QemuOptsList runtime_opts = {
125     .name = "gluster",
126     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
127     .desc = {
128         {
129             .name = GLUSTER_OPT_FILENAME,
130             .type = QEMU_OPT_STRING,
131             .help = "URL to the gluster image",
132         },
133         {
134             .name = GLUSTER_OPT_DEBUG,
135             .type = QEMU_OPT_NUMBER,
136             .help = "Gluster log level, valid range is 0-9",
137         },
138         {
139             .name = GLUSTER_OPT_LOGFILE,
140             .type = QEMU_OPT_STRING,
141             .help = "Logfile path of libgfapi",
142         },
143         { /* end of list */ }
144     },
145 };
146 
147 static QemuOptsList runtime_json_opts = {
148     .name = "gluster_json",
149     .head = QTAILQ_HEAD_INITIALIZER(runtime_json_opts.head),
150     .desc = {
151         {
152             .name = GLUSTER_OPT_VOLUME,
153             .type = QEMU_OPT_STRING,
154             .help = "name of gluster volume where VM image resides",
155         },
156         {
157             .name = GLUSTER_OPT_PATH,
158             .type = QEMU_OPT_STRING,
159             .help = "absolute path to image file in gluster volume",
160         },
161         {
162             .name = GLUSTER_OPT_DEBUG,
163             .type = QEMU_OPT_NUMBER,
164             .help = "Gluster log level, valid range is 0-9",
165         },
166         { /* end of list */ }
167     },
168 };
169 
170 static QemuOptsList runtime_type_opts = {
171     .name = "gluster_type",
172     .head = QTAILQ_HEAD_INITIALIZER(runtime_type_opts.head),
173     .desc = {
174         {
175             .name = GLUSTER_OPT_TYPE,
176             .type = QEMU_OPT_STRING,
177             .help = "inet|unix",
178         },
179         { /* end of list */ }
180     },
181 };
182 
183 static QemuOptsList runtime_unix_opts = {
184     .name = "gluster_unix",
185     .head = QTAILQ_HEAD_INITIALIZER(runtime_unix_opts.head),
186     .desc = {
187         {
188             .name = GLUSTER_OPT_SOCKET,
189             .type = QEMU_OPT_STRING,
190             .help = "socket file path (legacy)",
191         },
192         {
193             .name = GLUSTER_OPT_PATH,
194             .type = QEMU_OPT_STRING,
195             .help = "socket file path (QAPI)",
196         },
197         { /* end of list */ }
198     },
199 };
200 
201 static QemuOptsList runtime_inet_opts = {
202     .name = "gluster_inet",
203     .head = QTAILQ_HEAD_INITIALIZER(runtime_inet_opts.head),
204     .desc = {
205         {
206             .name = GLUSTER_OPT_TYPE,
207             .type = QEMU_OPT_STRING,
208             .help = "inet|unix",
209         },
210         {
211             .name = GLUSTER_OPT_HOST,
212             .type = QEMU_OPT_STRING,
213             .help = "host address (hostname/ipv4/ipv6 addresses)",
214         },
215         {
216             .name = GLUSTER_OPT_PORT,
217             .type = QEMU_OPT_STRING,
218             .help = "port number on which glusterd is listening (default 24007)",
219         },
220         {
221             .name = "to",
222             .type = QEMU_OPT_NUMBER,
223             .help = "max port number, not supported by gluster",
224         },
225         {
226             .name = "ipv4",
227             .type = QEMU_OPT_BOOL,
228             .help = "ipv4 bool value, not supported by gluster",
229         },
230         {
231             .name = "ipv6",
232             .type = QEMU_OPT_BOOL,
233             .help = "ipv6 bool value, not supported by gluster",
234         },
235         { /* end of list */ }
236     },
237 };
238 
239 static void glfs_set_preopened(const char *volume, glfs_t *fs)
240 {
241     ListElement *entry = NULL;
242 
243     entry = g_new(ListElement, 1);
244 
245     entry->saved.volume = g_strdup(volume);
246 
247     entry->saved.fs = fs;
248     entry->saved.ref = 1;
249 
250     QLIST_INSERT_HEAD(&glfs_list, entry, list);
251 }
252 
253 static glfs_t *glfs_find_preopened(const char *volume)
254 {
255     ListElement *entry = NULL;
256 
257      QLIST_FOREACH(entry, &glfs_list, list) {
258         if (strcmp(entry->saved.volume, volume) == 0) {
259             entry->saved.ref++;
260             return entry->saved.fs;
261         }
262      }
263 
264     return NULL;
265 }
266 
267 static void glfs_clear_preopened(glfs_t *fs)
268 {
269     ListElement *entry = NULL;
270     ListElement *next;
271 
272     if (fs == NULL) {
273         return;
274     }
275 
276     QLIST_FOREACH_SAFE(entry, &glfs_list, list, next) {
277         if (entry->saved.fs == fs) {
278             if (--entry->saved.ref) {
279                 return;
280             }
281 
282             QLIST_REMOVE(entry, list);
283 
284             glfs_fini(entry->saved.fs);
285             g_free(entry->saved.volume);
286             g_free(entry);
287         }
288     }
289 }
290 
291 static int parse_volume_options(BlockdevOptionsGluster *gconf, const char *path)
292 {
293     const char *p, *q;
294 
295     if (!path) {
296         return -EINVAL;
297     }
298 
299     /* volume */
300     p = q = path + strspn(path, "/");
301     p += strcspn(p, "/");
302     if (*p == '\0') {
303         return -EINVAL;
304     }
305     gconf->volume = g_strndup(q, p - q);
306 
307     /* path */
308     p += strspn(p, "/");
309     if (*p == '\0') {
310         return -EINVAL;
311     }
312     gconf->path = g_strdup(p);
313     return 0;
314 }
315 
316 /*
317  * file=gluster[+transport]://[host[:port]]/volume/path[?socket=...]
318  *
319  * 'gluster' is the protocol.
320  *
321  * 'transport' specifies the transport type used to connect to gluster
322  * management daemon (glusterd). Valid transport types are
323  * tcp or unix. If a transport type isn't specified, then tcp type is assumed.
324  *
325  * 'host' specifies the host where the volume file specification for
326  * the given volume resides. This can be either hostname or ipv4 address.
327  * If transport type is 'unix', then 'host' field should not be specified.
328  * The 'socket' field needs to be populated with the path to unix domain
329  * socket.
330  *
331  * 'port' is the port number on which glusterd is listening. This is optional
332  * and if not specified, QEMU will send 0 which will make gluster to use the
333  * default port. If the transport type is unix, then 'port' should not be
334  * specified.
335  *
336  * 'volume' is the name of the gluster volume which contains the VM image.
337  *
338  * 'path' is the path to the actual VM image that resides on gluster volume.
339  *
340  * Examples:
341  *
342  * file=gluster://1.2.3.4/testvol/a.img
343  * file=gluster+tcp://1.2.3.4/testvol/a.img
344  * file=gluster+tcp://1.2.3.4:24007/testvol/dir/a.img
345  * file=gluster+tcp://host.domain.com:24007/testvol/dir/a.img
346  * file=gluster+unix:///testvol/dir/a.img?socket=/tmp/glusterd.socket
347  */
348 static int qemu_gluster_parse_uri(BlockdevOptionsGluster *gconf,
349                                   const char *filename)
350 {
351     g_autoptr(GUri) uri = g_uri_parse(filename, G_URI_FLAGS_NONE, NULL);
352     g_autoptr(GHashTable) qp = NULL;
353     SocketAddress *gsconf;
354     bool is_unix = false;
355     const char *uri_scheme, *uri_query, *uri_server;
356     int uri_port, ret;
357 
358     if (!uri) {
359         return -EINVAL;
360     }
361 
362     gsconf = g_new0(SocketAddress, 1);
363     QAPI_LIST_PREPEND(gconf->server, gsconf);
364 
365     /* transport */
366     uri_scheme = g_uri_get_scheme(uri);
367     if (!uri_scheme || !strcmp(uri_scheme, "gluster")) {
368         gsconf->type = SOCKET_ADDRESS_TYPE_INET;
369     } else if (!strcmp(uri_scheme, "gluster+tcp")) {
370         gsconf->type = SOCKET_ADDRESS_TYPE_INET;
371     } else if (!strcmp(uri_scheme, "gluster+unix")) {
372         gsconf->type = SOCKET_ADDRESS_TYPE_UNIX;
373         is_unix = true;
374     } else {
375         return -EINVAL;
376     }
377 
378     ret = parse_volume_options(gconf, g_uri_get_path(uri));
379     if (ret < 0) {
380         return ret;
381     }
382 
383     uri_query = g_uri_get_query(uri);
384     if (uri_query) {
385         qp = g_uri_parse_params(uri_query, -1, "&", G_URI_PARAMS_NONE, NULL);
386         if (!qp) {
387             return -EINVAL;
388         }
389         ret = g_hash_table_size(qp);
390         if (ret > 1 || (is_unix && !ret) || (!is_unix && ret)) {
391             return -EINVAL;
392         }
393     }
394 
395     uri_server = g_uri_get_host(uri);
396     uri_port = g_uri_get_port(uri);
397 
398     if (is_unix) {
399         char *uri_socket = g_hash_table_lookup(qp, "socket");
400         if (uri_server || uri_port != -1 || !uri_socket) {
401             return -EINVAL;
402         }
403         gsconf->u.q_unix.path = g_strdup(uri_socket);
404     } else {
405         gsconf->u.inet.host = g_strdup(uri_server ? uri_server : "localhost");
406         if (uri_port > 0) {
407             gsconf->u.inet.port = g_strdup_printf("%d", uri_port);
408         } else {
409             gsconf->u.inet.port = g_strdup_printf("%d", GLUSTER_DEFAULT_PORT);
410         }
411     }
412 
413     return 0;
414 }
415 
416 static struct glfs *qemu_gluster_glfs_init(BlockdevOptionsGluster *gconf,
417                                            Error **errp)
418 {
419     struct glfs *glfs;
420     int ret;
421     int old_errno;
422     SocketAddressList *server;
423     uint64_t port;
424 
425     glfs = glfs_find_preopened(gconf->volume);
426     if (glfs) {
427         return glfs;
428     }
429 
430     glfs = glfs_new(gconf->volume);
431     if (!glfs) {
432         goto out;
433     }
434 
435     glfs_set_preopened(gconf->volume, glfs);
436 
437     for (server = gconf->server; server; server = server->next) {
438         switch (server->value->type) {
439         case SOCKET_ADDRESS_TYPE_UNIX:
440             ret = glfs_set_volfile_server(glfs, "unix",
441                                    server->value->u.q_unix.path, 0);
442             break;
443         case SOCKET_ADDRESS_TYPE_INET:
444             if (parse_uint_full(server->value->u.inet.port, 10, &port) < 0 ||
445                 port > 65535) {
446                 error_setg(errp, "'%s' is not a valid port number",
447                            server->value->u.inet.port);
448                 errno = EINVAL;
449                 goto out;
450             }
451             ret = glfs_set_volfile_server(glfs, "tcp",
452                                    server->value->u.inet.host,
453                                    (int)port);
454             break;
455         case SOCKET_ADDRESS_TYPE_VSOCK:
456         case SOCKET_ADDRESS_TYPE_FD:
457         default:
458             abort();
459         }
460 
461         if (ret < 0) {
462             goto out;
463         }
464     }
465 
466     ret = glfs_set_logging(glfs, gconf->logfile, gconf->debug);
467     if (ret < 0) {
468         goto out;
469     }
470 
471     ret = glfs_init(glfs);
472     if (ret) {
473         error_setg(errp, "Gluster connection for volume %s, path %s failed"
474                          " to connect", gconf->volume, gconf->path);
475         for (server = gconf->server; server; server = server->next) {
476             if (server->value->type  == SOCKET_ADDRESS_TYPE_UNIX) {
477                 error_append_hint(errp, "hint: failed on socket %s ",
478                                   server->value->u.q_unix.path);
479             } else {
480                 error_append_hint(errp, "hint: failed on host %s and port %s ",
481                                   server->value->u.inet.host,
482                                   server->value->u.inet.port);
483             }
484         }
485 
486         error_append_hint(errp, "Please refer to gluster logs for more info\n");
487 
488         /* glfs_init sometimes doesn't set errno although docs suggest that */
489         if (errno == 0) {
490             errno = EINVAL;
491         }
492 
493         goto out;
494     }
495     return glfs;
496 
497 out:
498     if (glfs) {
499         old_errno = errno;
500         glfs_clear_preopened(glfs);
501         errno = old_errno;
502     }
503     return NULL;
504 }
505 
506 /*
507  * Convert the json formatted command line into qapi.
508 */
509 static int qemu_gluster_parse_json(BlockdevOptionsGluster *gconf,
510                                   QDict *options, Error **errp)
511 {
512     QemuOpts *opts;
513     SocketAddress *gsconf = NULL;
514     SocketAddressList **tail;
515     QDict *backing_options = NULL;
516     Error *local_err = NULL;
517     const char *ptr;
518     int i, type, num_servers;
519 
520     /* create opts info from runtime_json_opts list */
521     opts = qemu_opts_create(&runtime_json_opts, NULL, 0, &error_abort);
522     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
523         goto out;
524     }
525 
526     num_servers = qdict_array_entries(options, GLUSTER_OPT_SERVER_PATTERN);
527     if (num_servers < 1) {
528         error_setg(&local_err, QERR_MISSING_PARAMETER, "server");
529         goto out;
530     }
531 
532     ptr = qemu_opt_get(opts, GLUSTER_OPT_VOLUME);
533     if (!ptr) {
534         error_setg(&local_err, QERR_MISSING_PARAMETER, GLUSTER_OPT_VOLUME);
535         goto out;
536     }
537     gconf->volume = g_strdup(ptr);
538 
539     ptr = qemu_opt_get(opts, GLUSTER_OPT_PATH);
540     if (!ptr) {
541         error_setg(&local_err, QERR_MISSING_PARAMETER, GLUSTER_OPT_PATH);
542         goto out;
543     }
544     gconf->path = g_strdup(ptr);
545     qemu_opts_del(opts);
546     tail = &gconf->server;
547 
548     for (i = 0; i < num_servers; i++) {
549         g_autofree char *str = g_strdup_printf(GLUSTER_OPT_SERVER_PATTERN"%d.",
550                                                i);
551         qdict_extract_subqdict(options, &backing_options, str);
552 
553         /* create opts info from runtime_type_opts list */
554         opts = qemu_opts_create(&runtime_type_opts, NULL, 0, &error_abort);
555         if (!qemu_opts_absorb_qdict(opts, backing_options, errp)) {
556             goto out;
557         }
558 
559         ptr = qemu_opt_get(opts, GLUSTER_OPT_TYPE);
560         if (!ptr) {
561             error_setg(&local_err, QERR_MISSING_PARAMETER, GLUSTER_OPT_TYPE);
562             error_append_hint(&local_err, GERR_INDEX_HINT, i);
563             goto out;
564 
565         }
566         gsconf = g_new0(SocketAddress, 1);
567         if (!strcmp(ptr, "tcp")) {
568             ptr = "inet";       /* accept legacy "tcp" */
569         }
570         type = qapi_enum_parse(&SocketAddressType_lookup, ptr, -1, NULL);
571         if (type != SOCKET_ADDRESS_TYPE_INET
572             && type != SOCKET_ADDRESS_TYPE_UNIX) {
573             error_setg(&local_err,
574                        "Parameter '%s' may be 'inet' or 'unix'",
575                        GLUSTER_OPT_TYPE);
576             error_append_hint(&local_err, GERR_INDEX_HINT, i);
577             goto out;
578         }
579         gsconf->type = type;
580         qemu_opts_del(opts);
581 
582         if (gsconf->type == SOCKET_ADDRESS_TYPE_INET) {
583             /* create opts info from runtime_inet_opts list */
584             opts = qemu_opts_create(&runtime_inet_opts, NULL, 0, &error_abort);
585             if (!qemu_opts_absorb_qdict(opts, backing_options, errp)) {
586                 goto out;
587             }
588 
589             ptr = qemu_opt_get(opts, GLUSTER_OPT_HOST);
590             if (!ptr) {
591                 error_setg(&local_err, QERR_MISSING_PARAMETER,
592                            GLUSTER_OPT_HOST);
593                 error_append_hint(&local_err, GERR_INDEX_HINT, i);
594                 goto out;
595             }
596             gsconf->u.inet.host = g_strdup(ptr);
597             ptr = qemu_opt_get(opts, GLUSTER_OPT_PORT);
598             if (!ptr) {
599                 error_setg(&local_err, QERR_MISSING_PARAMETER,
600                            GLUSTER_OPT_PORT);
601                 error_append_hint(&local_err, GERR_INDEX_HINT, i);
602                 goto out;
603             }
604             gsconf->u.inet.port = g_strdup(ptr);
605 
606             /* defend for unsupported fields in InetSocketAddress,
607              * i.e. @ipv4, @ipv6  and @to
608              */
609             ptr = qemu_opt_get(opts, GLUSTER_OPT_TO);
610             if (ptr) {
611                 gsconf->u.inet.has_to = true;
612             }
613             ptr = qemu_opt_get(opts, GLUSTER_OPT_IPV4);
614             if (ptr) {
615                 gsconf->u.inet.has_ipv4 = true;
616             }
617             ptr = qemu_opt_get(opts, GLUSTER_OPT_IPV6);
618             if (ptr) {
619                 gsconf->u.inet.has_ipv6 = true;
620             }
621             if (gsconf->u.inet.has_to) {
622                 error_setg(&local_err, "Parameter 'to' not supported");
623                 goto out;
624             }
625             if (gsconf->u.inet.has_ipv4 || gsconf->u.inet.has_ipv6) {
626                 error_setg(&local_err, "Parameters 'ipv4/ipv6' not supported");
627                 goto out;
628             }
629             qemu_opts_del(opts);
630         } else {
631             /* create opts info from runtime_unix_opts list */
632             opts = qemu_opts_create(&runtime_unix_opts, NULL, 0, &error_abort);
633             if (!qemu_opts_absorb_qdict(opts, backing_options, errp)) {
634                 goto out;
635             }
636 
637             ptr = qemu_opt_get(opts, GLUSTER_OPT_PATH);
638             if (!ptr) {
639                 ptr = qemu_opt_get(opts, GLUSTER_OPT_SOCKET);
640             } else if (qemu_opt_get(opts, GLUSTER_OPT_SOCKET)) {
641                 error_setg(&local_err,
642                            "Conflicting parameters 'path' and 'socket'");
643                 error_append_hint(&local_err, GERR_INDEX_HINT, i);
644                 goto out;
645             }
646             if (!ptr) {
647                 error_setg(&local_err, QERR_MISSING_PARAMETER,
648                            GLUSTER_OPT_PATH);
649                 error_append_hint(&local_err, GERR_INDEX_HINT, i);
650                 goto out;
651             }
652             gsconf->u.q_unix.path = g_strdup(ptr);
653             qemu_opts_del(opts);
654         }
655 
656         QAPI_LIST_APPEND(tail, gsconf);
657         gsconf = NULL;
658 
659         qobject_unref(backing_options);
660         backing_options = NULL;
661     }
662 
663     return 0;
664 
665 out:
666     error_propagate(errp, local_err);
667     qapi_free_SocketAddress(gsconf);
668     qemu_opts_del(opts);
669     qobject_unref(backing_options);
670     errno = EINVAL;
671     return -errno;
672 }
673 
674 /* Converts options given in @filename and the @options QDict into the QAPI
675  * object @gconf. */
676 static int qemu_gluster_parse(BlockdevOptionsGluster *gconf,
677                               const char *filename,
678                               QDict *options, Error **errp)
679 {
680     int ret;
681     if (filename) {
682         ret = qemu_gluster_parse_uri(gconf, filename);
683         if (ret < 0) {
684             error_setg(errp, "invalid URI %s", filename);
685             error_append_hint(errp, "Usage: file=gluster[+transport]://"
686                                     "[host[:port]]volume/path[?socket=...]"
687                                     "[,file.debug=N]"
688                                     "[,file.logfile=/path/filename.log]\n");
689             return ret;
690         }
691     } else {
692         ret = qemu_gluster_parse_json(gconf, options, errp);
693         if (ret < 0) {
694             error_append_hint(errp, "Usage: "
695                              "-drive driver=qcow2,file.driver=gluster,"
696                              "file.volume=testvol,file.path=/path/a.qcow2"
697                              "[,file.debug=9]"
698                              "[,file.logfile=/path/filename.log],"
699                              "file.server.0.type=inet,"
700                              "file.server.0.host=1.2.3.4,"
701                              "file.server.0.port=24007,"
702                              "file.server.1.transport=unix,"
703                              "file.server.1.path=/var/run/glusterd.socket ..."
704                              "\n");
705             return ret;
706         }
707     }
708 
709     return 0;
710 }
711 
712 static struct glfs *qemu_gluster_init(BlockdevOptionsGluster *gconf,
713                                       const char *filename,
714                                       QDict *options, Error **errp)
715 {
716     int ret;
717 
718     ret = qemu_gluster_parse(gconf, filename, options, errp);
719     if (ret < 0) {
720         errno = -ret;
721         return NULL;
722     }
723 
724     return qemu_gluster_glfs_init(gconf, errp);
725 }
726 
727 /*
728  * AIO callback routine called from GlusterFS thread.
729  */
730 static void gluster_finish_aiocb(struct glfs_fd *fd, ssize_t ret,
731 #ifdef CONFIG_GLUSTERFS_IOCB_HAS_STAT
732                                  struct glfs_stat *pre, struct glfs_stat *post,
733 #endif
734                                  void *arg)
735 {
736     GlusterAIOCB *acb = (GlusterAIOCB *)arg;
737 
738     if (!ret || ret == acb->size) {
739         acb->ret = 0; /* Success */
740     } else if (ret < 0) {
741         acb->ret = -errno; /* Read/Write failed */
742     } else {
743         acb->ret = -EIO; /* Partial read/write - fail it */
744     }
745 
746     aio_co_schedule(acb->aio_context, acb->coroutine);
747 }
748 
749 static void qemu_gluster_parse_flags(int bdrv_flags, int *open_flags)
750 {
751     assert(open_flags != NULL);
752 
753     *open_flags |= O_BINARY;
754 
755     if (bdrv_flags & BDRV_O_RDWR) {
756         *open_flags |= O_RDWR;
757     } else {
758         *open_flags |= O_RDONLY;
759     }
760 
761     if ((bdrv_flags & BDRV_O_NOCACHE)) {
762         *open_flags |= O_DIRECT;
763     }
764 }
765 
766 /*
767  * Do SEEK_DATA/HOLE to detect if it is functional. Older broken versions of
768  * gfapi incorrectly return the current offset when SEEK_DATA/HOLE is used.
769  * - Corrected versions return -1 and set errno to EINVAL.
770  * - Versions that support SEEK_DATA/HOLE correctly, will return -1 and set
771  *   errno to ENXIO when SEEK_DATA is called with a position of EOF.
772  */
773 static bool qemu_gluster_test_seek(struct glfs_fd *fd)
774 {
775     off_t ret = 0;
776 
777 #if defined SEEK_HOLE && defined SEEK_DATA
778     off_t eof;
779 
780     eof = glfs_lseek(fd, 0, SEEK_END);
781     if (eof < 0) {
782         /* this should never occur */
783         return false;
784     }
785 
786     /* this should always fail with ENXIO if SEEK_DATA is supported */
787     ret = glfs_lseek(fd, eof, SEEK_DATA);
788 #endif
789 
790     return (ret < 0) && (errno == ENXIO);
791 }
792 
793 static int qemu_gluster_open(BlockDriverState *bs,  QDict *options,
794                              int bdrv_flags, Error **errp)
795 {
796     BDRVGlusterState *s = bs->opaque;
797     int open_flags = 0;
798     int ret = 0;
799     BlockdevOptionsGluster *gconf = NULL;
800     QemuOpts *opts;
801     const char *filename, *logfile;
802 
803     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
804     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
805         ret = -EINVAL;
806         goto out;
807     }
808 
809     warn_report_once("'gluster' is deprecated");
810 
811     filename = qemu_opt_get(opts, GLUSTER_OPT_FILENAME);
812 
813     s->debug = qemu_opt_get_number(opts, GLUSTER_OPT_DEBUG,
814                                    GLUSTER_DEBUG_DEFAULT);
815     if (s->debug < 0) {
816         s->debug = 0;
817     } else if (s->debug > GLUSTER_DEBUG_MAX) {
818         s->debug = GLUSTER_DEBUG_MAX;
819     }
820 
821     gconf = g_new0(BlockdevOptionsGluster, 1);
822     gconf->debug = s->debug;
823     gconf->has_debug = true;
824 
825     logfile = qemu_opt_get(opts, GLUSTER_OPT_LOGFILE);
826     s->logfile = g_strdup(logfile ? logfile : GLUSTER_LOGFILE_DEFAULT);
827 
828     gconf->logfile = g_strdup(s->logfile);
829 
830     s->glfs = qemu_gluster_init(gconf, filename, options, errp);
831     if (!s->glfs) {
832         ret = -errno;
833         goto out;
834     }
835 
836 #ifdef CONFIG_GLUSTERFS_XLATOR_OPT
837     /* Without this, if fsync fails for a recoverable reason (for instance,
838      * ENOSPC), gluster will dump its cache, preventing retries.  This means
839      * almost certain data loss.  Not all gluster versions support the
840      * 'resync-failed-syncs-after-fsync' key value, but there is no way to
841      * discover during runtime if it is supported (this api returns success for
842      * unknown key/value pairs) */
843     ret = glfs_set_xlator_option(s->glfs, "*-write-behind",
844                                           "resync-failed-syncs-after-fsync",
845                                           "on");
846     if (ret < 0) {
847         error_setg_errno(errp, errno, "Unable to set xlator key/value pair");
848         ret = -errno;
849         goto out;
850     }
851 #endif
852 
853     qemu_gluster_parse_flags(bdrv_flags, &open_flags);
854 
855     s->fd = glfs_open(s->glfs, gconf->path, open_flags);
856     ret = s->fd ? 0 : -errno;
857 
858     if (ret == -EACCES || ret == -EROFS) {
859         /* Try to degrade to read-only, but if it doesn't work, still use the
860          * normal error message. */
861         bdrv_graph_rdlock_main_loop();
862         if (bdrv_apply_auto_read_only(bs, NULL, NULL) == 0) {
863             open_flags = (open_flags & ~O_RDWR) | O_RDONLY;
864             s->fd = glfs_open(s->glfs, gconf->path, open_flags);
865             ret = s->fd ? 0 : -errno;
866         }
867         bdrv_graph_rdunlock_main_loop();
868     }
869 
870     s->supports_seek_data = qemu_gluster_test_seek(s->fd);
871 
872 out:
873     qemu_opts_del(opts);
874     qapi_free_BlockdevOptionsGluster(gconf);
875     if (!ret) {
876         return ret;
877     }
878     g_free(s->logfile);
879     if (s->fd) {
880         glfs_close(s->fd);
881     }
882 
883     glfs_clear_preopened(s->glfs);
884 
885     return ret;
886 }
887 
888 static void qemu_gluster_refresh_limits(BlockDriverState *bs, Error **errp)
889 {
890     bs->bl.max_transfer = GLUSTER_MAX_TRANSFER;
891     bs->bl.max_pdiscard = MIN(SIZE_MAX, INT64_MAX);
892 }
893 
894 static int qemu_gluster_reopen_prepare(BDRVReopenState *state,
895                                        BlockReopenQueue *queue, Error **errp)
896 {
897     int ret = 0;
898     BDRVGlusterState *s;
899     BDRVGlusterReopenState *reop_s;
900     BlockdevOptionsGluster *gconf;
901     int open_flags = 0;
902 
903     assert(state != NULL);
904     assert(state->bs != NULL);
905 
906     s = state->bs->opaque;
907 
908     state->opaque = g_new0(BDRVGlusterReopenState, 1);
909     reop_s = state->opaque;
910 
911     qemu_gluster_parse_flags(state->flags, &open_flags);
912 
913     gconf = g_new0(BlockdevOptionsGluster, 1);
914     gconf->debug = s->debug;
915     gconf->has_debug = true;
916     gconf->logfile = g_strdup(s->logfile);
917 
918     /*
919      * If 'state->bs->exact_filename' is empty, 'state->options' should contain
920      * the JSON parameters already parsed.
921      */
922     if (state->bs->exact_filename[0] != '\0') {
923         reop_s->glfs = qemu_gluster_init(gconf, state->bs->exact_filename, NULL,
924                                          errp);
925     } else {
926         reop_s->glfs = qemu_gluster_init(gconf, NULL, state->options, errp);
927     }
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                                                       int64_t bytes,
1004                                                       BdrvRequestFlags flags)
1005 {
1006     int ret;
1007     GlusterAIOCB acb;
1008     BDRVGlusterState *s = bs->opaque;
1009 
1010     acb.size = bytes;
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, bytes, 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(BlockDriver *drv,
1117                                                     const char *filename,
1118                                                     QemuOpts *opts,
1119                                                     Error **errp)
1120 {
1121     BlockdevCreateOptions *options;
1122     BlockdevCreateOptionsGluster *gopts;
1123     BlockdevOptionsGluster *gconf;
1124     char *tmp = NULL;
1125     Error *local_err = NULL;
1126     int ret;
1127 
1128     options = g_new0(BlockdevCreateOptions, 1);
1129     options->driver = BLOCKDEV_DRIVER_GLUSTER;
1130     gopts = &options->u.gluster;
1131 
1132     gconf = g_new0(BlockdevOptionsGluster, 1);
1133     gopts->location = gconf;
1134 
1135     gopts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1136                            BDRV_SECTOR_SIZE);
1137 
1138     tmp = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1139     gopts->preallocation = qapi_enum_parse(&PreallocMode_lookup, tmp,
1140                                            PREALLOC_MODE_OFF, &local_err);
1141     g_free(tmp);
1142     if (local_err) {
1143         error_propagate(errp, local_err);
1144         ret = -EINVAL;
1145         goto fail;
1146     }
1147 
1148     gconf->debug = qemu_opt_get_number_del(opts, GLUSTER_OPT_DEBUG,
1149                                            GLUSTER_DEBUG_DEFAULT);
1150     if (gconf->debug < 0) {
1151         gconf->debug = 0;
1152     } else if (gconf->debug > GLUSTER_DEBUG_MAX) {
1153         gconf->debug = GLUSTER_DEBUG_MAX;
1154     }
1155     gconf->has_debug = true;
1156 
1157     gconf->logfile = qemu_opt_get_del(opts, GLUSTER_OPT_LOGFILE);
1158     if (!gconf->logfile) {
1159         gconf->logfile = g_strdup(GLUSTER_LOGFILE_DEFAULT);
1160     }
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                                                  bool exact,
1212                                                  PreallocMode prealloc,
1213                                                  BdrvRequestFlags flags,
1214                                                  Error **errp)
1215 {
1216     BDRVGlusterState *s = bs->opaque;
1217     return qemu_gluster_do_truncate(s->fd, offset, prealloc, errp);
1218 }
1219 
1220 static coroutine_fn int qemu_gluster_co_readv(BlockDriverState *bs,
1221                                               int64_t sector_num,
1222                                               int nb_sectors,
1223                                               QEMUIOVector *qiov)
1224 {
1225     return qemu_gluster_co_rw(bs, sector_num, nb_sectors, qiov, 0);
1226 }
1227 
1228 static coroutine_fn int qemu_gluster_co_writev(BlockDriverState *bs,
1229                                                int64_t sector_num,
1230                                                int nb_sectors,
1231                                                QEMUIOVector *qiov,
1232                                                int flags)
1233 {
1234     return qemu_gluster_co_rw(bs, sector_num, nb_sectors, qiov, 1);
1235 }
1236 
1237 static void qemu_gluster_close(BlockDriverState *bs)
1238 {
1239     BDRVGlusterState *s = bs->opaque;
1240 
1241     g_free(s->logfile);
1242     if (s->fd) {
1243         glfs_close(s->fd);
1244         s->fd = NULL;
1245     }
1246     glfs_clear_preopened(s->glfs);
1247 }
1248 
1249 static coroutine_fn int qemu_gluster_co_flush_to_disk(BlockDriverState *bs)
1250 {
1251     int ret;
1252     GlusterAIOCB acb;
1253     BDRVGlusterState *s = bs->opaque;
1254 
1255     acb.size = 0;
1256     acb.ret = 0;
1257     acb.coroutine = qemu_coroutine_self();
1258     acb.aio_context = bdrv_get_aio_context(bs);
1259 
1260     ret = glfs_fsync_async(s->fd, gluster_finish_aiocb, &acb);
1261     if (ret < 0) {
1262         ret = -errno;
1263         goto error;
1264     }
1265 
1266     qemu_coroutine_yield();
1267     if (acb.ret < 0) {
1268         ret = acb.ret;
1269         goto error;
1270     }
1271 
1272     return acb.ret;
1273 
1274 error:
1275     /* Some versions of Gluster (3.5.6 -> 3.5.8?) will not retain its cache
1276      * after a fsync failure, so we have no way of allowing the guest to safely
1277      * continue.  Gluster versions prior to 3.5.6 don't retain the cache
1278      * either, but will invalidate the fd on error, so this is again our only
1279      * option.
1280      *
1281      * The 'resync-failed-syncs-after-fsync' xlator option for the
1282      * write-behind cache will cause later gluster versions to retain its
1283      * cache after error, so long as the fd remains open.  However, we
1284      * currently have no way of knowing if this option is supported.
1285      *
1286      * TODO: Once gluster provides a way for us to determine if the option
1287      * is supported, bypass the closure and setting drv to NULL.  */
1288     qemu_gluster_close(bs);
1289     bs->drv = NULL;
1290     return ret;
1291 }
1292 
1293 #ifdef CONFIG_GLUSTERFS_DISCARD
1294 static coroutine_fn int qemu_gluster_co_pdiscard(BlockDriverState *bs,
1295                                                  int64_t offset, int64_t bytes)
1296 {
1297     int ret;
1298     GlusterAIOCB acb;
1299     BDRVGlusterState *s = bs->opaque;
1300 
1301     assert(bytes <= SIZE_MAX); /* rely on max_pdiscard */
1302 
1303     acb.size = 0;
1304     acb.ret = 0;
1305     acb.coroutine = qemu_coroutine_self();
1306     acb.aio_context = bdrv_get_aio_context(bs);
1307 
1308     ret = glfs_discard_async(s->fd, offset, bytes, gluster_finish_aiocb, &acb);
1309     if (ret < 0) {
1310         return -errno;
1311     }
1312 
1313     qemu_coroutine_yield();
1314     return acb.ret;
1315 }
1316 #endif
1317 
1318 static int64_t coroutine_fn qemu_gluster_co_getlength(BlockDriverState *bs)
1319 {
1320     BDRVGlusterState *s = bs->opaque;
1321     int64_t ret;
1322 
1323     ret = glfs_lseek(s->fd, 0, SEEK_END);
1324     if (ret < 0) {
1325         return -errno;
1326     } else {
1327         return ret;
1328     }
1329 }
1330 
1331 static int64_t coroutine_fn
1332 qemu_gluster_co_get_allocated_file_size(BlockDriverState *bs)
1333 {
1334     BDRVGlusterState *s = bs->opaque;
1335     struct stat st;
1336     int ret;
1337 
1338     ret = glfs_fstat(s->fd, &st);
1339     if (ret < 0) {
1340         return -errno;
1341     } else {
1342         return st.st_blocks * 512;
1343     }
1344 }
1345 
1346 /*
1347  * Find allocation range in @bs around offset @start.
1348  * May change underlying file descriptor's file offset.
1349  * If @start is not in a hole, store @start in @data, and the
1350  * beginning of the next hole in @hole, and return 0.
1351  * If @start is in a non-trailing hole, store @start in @hole and the
1352  * beginning of the next non-hole in @data, and return 0.
1353  * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1354  * If we can't find out, return a negative errno other than -ENXIO.
1355  *
1356  * (Shamefully copied from file-posix.c, only minuscule adaptions.)
1357  */
1358 static int find_allocation(BlockDriverState *bs, off_t start,
1359                            off_t *data, off_t *hole)
1360 {
1361     BDRVGlusterState *s = bs->opaque;
1362 
1363     if (!s->supports_seek_data) {
1364         goto exit;
1365     }
1366 
1367 #if defined SEEK_HOLE && defined SEEK_DATA
1368     off_t offs;
1369 
1370     /*
1371      * SEEK_DATA cases:
1372      * D1. offs == start: start is in data
1373      * D2. offs > start: start is in a hole, next data at offs
1374      * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1375      *                              or start is beyond EOF
1376      *     If the latter happens, the file has been truncated behind
1377      *     our back since we opened it.  All bets are off then.
1378      *     Treating like a trailing hole is simplest.
1379      * D4. offs < 0, errno != ENXIO: we learned nothing
1380      */
1381     offs = glfs_lseek(s->fd, start, SEEK_DATA);
1382     if (offs < 0) {
1383         return -errno;          /* D3 or D4 */
1384     }
1385 
1386     if (offs < start) {
1387         /* This is not a valid return by lseek().  We are safe to just return
1388          * -EIO in this case, and we'll treat it like D4. Unfortunately some
1389          *  versions of gluster server will return offs < start, so an assert
1390          *  here will unnecessarily abort QEMU. */
1391         return -EIO;
1392     }
1393 
1394     if (offs > start) {
1395         /* D2: in hole, next data at offs */
1396         *hole = start;
1397         *data = offs;
1398         return 0;
1399     }
1400 
1401     /* D1: in data, end not yet known */
1402 
1403     /*
1404      * SEEK_HOLE cases:
1405      * H1. offs == start: start is in a hole
1406      *     If this happens here, a hole has been dug behind our back
1407      *     since the previous lseek().
1408      * H2. offs > start: either start is in data, next hole at offs,
1409      *                   or start is in trailing hole, EOF at offs
1410      *     Linux treats trailing holes like any other hole: offs ==
1411      *     start.  Solaris seeks to EOF instead: offs > start (blech).
1412      *     If that happens here, a hole has been dug behind our back
1413      *     since the previous lseek().
1414      * H3. offs < 0, errno = ENXIO: start is beyond EOF
1415      *     If this happens, the file has been truncated behind our
1416      *     back since we opened it.  Treat it like a trailing hole.
1417      * H4. offs < 0, errno != ENXIO: we learned nothing
1418      *     Pretend we know nothing at all, i.e. "forget" about D1.
1419      */
1420     offs = glfs_lseek(s->fd, start, SEEK_HOLE);
1421     if (offs < 0) {
1422         return -errno;          /* D1 and (H3 or H4) */
1423     }
1424 
1425     if (offs < start) {
1426         /* This is not a valid return by lseek().  We are safe to just return
1427          * -EIO in this case, and we'll treat it like H4. Unfortunately some
1428          *  versions of gluster server will return offs < start, so an assert
1429          *  here will unnecessarily abort QEMU. */
1430         return -EIO;
1431     }
1432 
1433     if (offs > start) {
1434         /*
1435          * D1 and H2: either in data, next hole at offs, or it was in
1436          * data but is now in a trailing hole.  In the latter case,
1437          * all bets are off.  Treating it as if it there was data all
1438          * the way to EOF is safe, so simply do that.
1439          */
1440         *data = start;
1441         *hole = offs;
1442         return 0;
1443     }
1444 
1445     /* D1 and H1 */
1446     return -EBUSY;
1447 #endif
1448 
1449 exit:
1450     return -ENOTSUP;
1451 }
1452 
1453 /*
1454  * Returns the allocation status of the specified offset.
1455  *
1456  * The block layer guarantees 'offset' and 'bytes' are within bounds.
1457  *
1458  * 'pnum' is set to the number of bytes (including and immediately following
1459  * the specified offset) that are known to be in the same
1460  * allocated/unallocated state.
1461  *
1462  * 'bytes' is a soft cap for 'pnum'.  If the information is free, 'pnum' may
1463  * well exceed it.
1464  *
1465  * (Based on raw_co_block_status() from file-posix.c.)
1466  */
1467 static int coroutine_fn qemu_gluster_co_block_status(BlockDriverState *bs,
1468                                                      bool want_zero,
1469                                                      int64_t offset,
1470                                                      int64_t bytes,
1471                                                      int64_t *pnum,
1472                                                      int64_t *map,
1473                                                      BlockDriverState **file)
1474 {
1475     BDRVGlusterState *s = bs->opaque;
1476     off_t data = 0, hole = 0;
1477     int ret = -EINVAL;
1478 
1479     assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
1480 
1481     if (!s->fd) {
1482         return ret;
1483     }
1484 
1485     if (!want_zero) {
1486         *pnum = bytes;
1487         *map = offset;
1488         *file = bs;
1489         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1490     }
1491 
1492     ret = find_allocation(bs, offset, &data, &hole);
1493     if (ret == -ENXIO) {
1494         /* Trailing hole */
1495         *pnum = bytes;
1496         ret = BDRV_BLOCK_ZERO;
1497     } else if (ret < 0) {
1498         /* No info available, so pretend there are no holes */
1499         *pnum = bytes;
1500         ret = BDRV_BLOCK_DATA;
1501     } else if (data == offset) {
1502         /* On a data extent, compute bytes to the end of the extent,
1503          * possibly including a partial sector at EOF. */
1504         *pnum = hole - offset;
1505 
1506         /*
1507          * We are not allowed to return partial sectors, though, so
1508          * round up if necessary.
1509          */
1510         if (!QEMU_IS_ALIGNED(*pnum, bs->bl.request_alignment)) {
1511             int64_t file_length = qemu_gluster_co_getlength(bs);
1512             if (file_length > 0) {
1513                 /* Ignore errors, this is just a safeguard */
1514                 assert(hole == file_length);
1515             }
1516             *pnum = ROUND_UP(*pnum, bs->bl.request_alignment);
1517         }
1518 
1519         ret = BDRV_BLOCK_DATA;
1520     } else {
1521         /* On a hole, compute bytes to the beginning of the next extent.  */
1522         assert(hole == offset);
1523         *pnum = data - offset;
1524         ret = BDRV_BLOCK_ZERO;
1525     }
1526 
1527     *map = offset;
1528     *file = bs;
1529 
1530     return ret | BDRV_BLOCK_OFFSET_VALID;
1531 }
1532 
1533 
1534 static const char *const gluster_strong_open_opts[] = {
1535     GLUSTER_OPT_VOLUME,
1536     GLUSTER_OPT_PATH,
1537     GLUSTER_OPT_TYPE,
1538     GLUSTER_OPT_SERVER_PATTERN,
1539     GLUSTER_OPT_HOST,
1540     GLUSTER_OPT_PORT,
1541     GLUSTER_OPT_TO,
1542     GLUSTER_OPT_IPV4,
1543     GLUSTER_OPT_IPV6,
1544     GLUSTER_OPT_SOCKET,
1545 
1546     NULL
1547 };
1548 
1549 static BlockDriver bdrv_gluster = {
1550     .format_name                  = "gluster",
1551     .protocol_name                = "gluster",
1552     .instance_size                = sizeof(BDRVGlusterState),
1553     .bdrv_open                    = qemu_gluster_open,
1554     .bdrv_reopen_prepare          = qemu_gluster_reopen_prepare,
1555     .bdrv_reopen_commit           = qemu_gluster_reopen_commit,
1556     .bdrv_reopen_abort            = qemu_gluster_reopen_abort,
1557     .bdrv_close                   = qemu_gluster_close,
1558     .bdrv_co_create               = qemu_gluster_co_create,
1559     .bdrv_co_create_opts          = qemu_gluster_co_create_opts,
1560     .bdrv_co_getlength            = qemu_gluster_co_getlength,
1561     .bdrv_co_get_allocated_file_size = qemu_gluster_co_get_allocated_file_size,
1562     .bdrv_co_truncate             = qemu_gluster_co_truncate,
1563     .bdrv_co_readv                = qemu_gluster_co_readv,
1564     .bdrv_co_writev               = qemu_gluster_co_writev,
1565     .bdrv_co_flush_to_disk        = qemu_gluster_co_flush_to_disk,
1566 #ifdef CONFIG_GLUSTERFS_DISCARD
1567     .bdrv_co_pdiscard             = qemu_gluster_co_pdiscard,
1568 #endif
1569 #ifdef CONFIG_GLUSTERFS_ZEROFILL
1570     .bdrv_co_pwrite_zeroes        = qemu_gluster_co_pwrite_zeroes,
1571 #endif
1572     .bdrv_co_block_status         = qemu_gluster_co_block_status,
1573     .bdrv_refresh_limits          = qemu_gluster_refresh_limits,
1574     .create_opts                  = &qemu_gluster_create_opts,
1575     .strong_runtime_opts          = gluster_strong_open_opts,
1576 };
1577 
1578 static BlockDriver bdrv_gluster_tcp = {
1579     .format_name                  = "gluster",
1580     .protocol_name                = "gluster+tcp",
1581     .instance_size                = sizeof(BDRVGlusterState),
1582     .bdrv_open                    = qemu_gluster_open,
1583     .bdrv_reopen_prepare          = qemu_gluster_reopen_prepare,
1584     .bdrv_reopen_commit           = qemu_gluster_reopen_commit,
1585     .bdrv_reopen_abort            = qemu_gluster_reopen_abort,
1586     .bdrv_close                   = qemu_gluster_close,
1587     .bdrv_co_create               = qemu_gluster_co_create,
1588     .bdrv_co_create_opts          = qemu_gluster_co_create_opts,
1589     .bdrv_co_getlength            = qemu_gluster_co_getlength,
1590     .bdrv_co_get_allocated_file_size = qemu_gluster_co_get_allocated_file_size,
1591     .bdrv_co_truncate             = qemu_gluster_co_truncate,
1592     .bdrv_co_readv                = qemu_gluster_co_readv,
1593     .bdrv_co_writev               = qemu_gluster_co_writev,
1594     .bdrv_co_flush_to_disk        = qemu_gluster_co_flush_to_disk,
1595 #ifdef CONFIG_GLUSTERFS_DISCARD
1596     .bdrv_co_pdiscard             = qemu_gluster_co_pdiscard,
1597 #endif
1598 #ifdef CONFIG_GLUSTERFS_ZEROFILL
1599     .bdrv_co_pwrite_zeroes        = qemu_gluster_co_pwrite_zeroes,
1600 #endif
1601     .bdrv_co_block_status         = qemu_gluster_co_block_status,
1602     .bdrv_refresh_limits          = qemu_gluster_refresh_limits,
1603     .create_opts                  = &qemu_gluster_create_opts,
1604     .strong_runtime_opts          = gluster_strong_open_opts,
1605 };
1606 
1607 static BlockDriver bdrv_gluster_unix = {
1608     .format_name                  = "gluster",
1609     .protocol_name                = "gluster+unix",
1610     .instance_size                = sizeof(BDRVGlusterState),
1611     .bdrv_open                    = qemu_gluster_open,
1612     .bdrv_reopen_prepare          = qemu_gluster_reopen_prepare,
1613     .bdrv_reopen_commit           = qemu_gluster_reopen_commit,
1614     .bdrv_reopen_abort            = qemu_gluster_reopen_abort,
1615     .bdrv_close                   = qemu_gluster_close,
1616     .bdrv_co_create               = qemu_gluster_co_create,
1617     .bdrv_co_create_opts          = qemu_gluster_co_create_opts,
1618     .bdrv_co_getlength            = qemu_gluster_co_getlength,
1619     .bdrv_co_get_allocated_file_size = qemu_gluster_co_get_allocated_file_size,
1620     .bdrv_co_truncate             = qemu_gluster_co_truncate,
1621     .bdrv_co_readv                = qemu_gluster_co_readv,
1622     .bdrv_co_writev               = qemu_gluster_co_writev,
1623     .bdrv_co_flush_to_disk        = qemu_gluster_co_flush_to_disk,
1624 #ifdef CONFIG_GLUSTERFS_DISCARD
1625     .bdrv_co_pdiscard             = qemu_gluster_co_pdiscard,
1626 #endif
1627 #ifdef CONFIG_GLUSTERFS_ZEROFILL
1628     .bdrv_co_pwrite_zeroes        = qemu_gluster_co_pwrite_zeroes,
1629 #endif
1630     .bdrv_co_block_status         = qemu_gluster_co_block_status,
1631     .bdrv_refresh_limits          = qemu_gluster_refresh_limits,
1632     .create_opts                  = &qemu_gluster_create_opts,
1633     .strong_runtime_opts          = gluster_strong_open_opts,
1634 };
1635 
1636 static void bdrv_gluster_init(void)
1637 {
1638     bdrv_register(&bdrv_gluster_unix);
1639     bdrv_register(&bdrv_gluster_tcp);
1640     bdrv_register(&bdrv_gluster);
1641 }
1642 
1643 block_init(bdrv_gluster_init);
1644