xref: /openbmc/qemu/block/nfs.c (revision 62be393423eac3d2fcb8313dc441db4e76f44c78)
1 /*
2  * QEMU Block driver for native access to files on NFS shares
3  *
4  * Copyright (c) 2014-2016 Peter Lieven <pl@kamp.de>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 
27 #include <poll.h>
28 #include "qemu-common.h"
29 #include "qemu/config-file.h"
30 #include "qemu/error-report.h"
31 #include "qapi/error.h"
32 #include "block/block_int.h"
33 #include "trace.h"
34 #include "qemu/iov.h"
35 #include "qemu/uri.h"
36 #include "qemu/cutils.h"
37 #include "sysemu/sysemu.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qint.h"
40 #include "qapi/qmp/qstring.h"
41 #include "qapi-visit.h"
42 #include "qapi/qobject-input-visitor.h"
43 #include "qapi/qobject-output-visitor.h"
44 #include <nfsc/libnfs.h>
45 
46 
47 #define QEMU_NFS_MAX_READAHEAD_SIZE 1048576
48 #define QEMU_NFS_MAX_PAGECACHE_SIZE (8388608 / NFS_BLKSIZE)
49 #define QEMU_NFS_MAX_DEBUG_LEVEL 2
50 
51 typedef struct NFSClient {
52     struct nfs_context *context;
53     struct nfsfh *fh;
54     int events;
55     bool has_zero_init;
56     AioContext *aio_context;
57     blkcnt_t st_blocks;
58     bool cache_used;
59     NFSServer *server;
60     char *path;
61     int64_t uid, gid, tcp_syncnt, readahead, pagecache, debug;
62 } NFSClient;
63 
64 typedef struct NFSRPC {
65     BlockDriverState *bs;
66     int ret;
67     int complete;
68     QEMUIOVector *iov;
69     struct stat *st;
70     Coroutine *co;
71     NFSClient *client;
72 } NFSRPC;
73 
74 static int nfs_parse_uri(const char *filename, QDict *options, Error **errp)
75 {
76     URI *uri = NULL;
77     QueryParams *qp = NULL;
78     int ret = -EINVAL, i;
79 
80     uri = uri_parse(filename);
81     if (!uri) {
82         error_setg(errp, "Invalid URI specified");
83         goto out;
84     }
85     if (strcmp(uri->scheme, "nfs") != 0) {
86         error_setg(errp, "URI scheme must be 'nfs'");
87         goto out;
88     }
89 
90     if (!uri->server) {
91         error_setg(errp, "missing hostname in URI");
92         goto out;
93     }
94 
95     if (!uri->path) {
96         error_setg(errp, "missing file path in URI");
97         goto out;
98     }
99 
100     qp = query_params_parse(uri->query);
101     if (!qp) {
102         error_setg(errp, "could not parse query parameters");
103         goto out;
104     }
105 
106     qdict_put(options, "server.host", qstring_from_str(uri->server));
107     qdict_put(options, "server.type", qstring_from_str("inet"));
108     qdict_put(options, "path", qstring_from_str(uri->path));
109 
110     for (i = 0; i < qp->n; i++) {
111         unsigned long long val;
112         if (!qp->p[i].value) {
113             error_setg(errp, "Value for NFS parameter expected: %s",
114                        qp->p[i].name);
115             goto out;
116         }
117         if (parse_uint_full(qp->p[i].value, &val, 0)) {
118             error_setg(errp, "Illegal value for NFS parameter: %s",
119                        qp->p[i].name);
120             goto out;
121         }
122         if (!strcmp(qp->p[i].name, "uid")) {
123             qdict_put(options, "user",
124                       qstring_from_str(qp->p[i].value));
125         } else if (!strcmp(qp->p[i].name, "gid")) {
126             qdict_put(options, "group",
127                       qstring_from_str(qp->p[i].value));
128         } else if (!strcmp(qp->p[i].name, "tcp-syncnt")) {
129             qdict_put(options, "tcp-syn-count",
130                       qstring_from_str(qp->p[i].value));
131         } else if (!strcmp(qp->p[i].name, "readahead")) {
132             qdict_put(options, "readahead-size",
133                       qstring_from_str(qp->p[i].value));
134         } else if (!strcmp(qp->p[i].name, "pagecache")) {
135             qdict_put(options, "page-cache-size",
136                       qstring_from_str(qp->p[i].value));
137         } else if (!strcmp(qp->p[i].name, "debug")) {
138             qdict_put(options, "debug",
139                       qstring_from_str(qp->p[i].value));
140         } else {
141             error_setg(errp, "Unknown NFS parameter name: %s",
142                        qp->p[i].name);
143             goto out;
144         }
145     }
146     ret = 0;
147 out:
148     if (qp) {
149         query_params_free(qp);
150     }
151     if (uri) {
152         uri_free(uri);
153     }
154     return ret;
155 }
156 
157 static bool nfs_has_filename_options_conflict(QDict *options, Error **errp)
158 {
159     const QDictEntry *qe;
160 
161     for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
162         if (!strcmp(qe->key, "host") ||
163             !strcmp(qe->key, "path") ||
164             !strcmp(qe->key, "user") ||
165             !strcmp(qe->key, "group") ||
166             !strcmp(qe->key, "tcp-syn-count") ||
167             !strcmp(qe->key, "readahead-size") ||
168             !strcmp(qe->key, "page-cache-size") ||
169             !strcmp(qe->key, "debug") ||
170             strstart(qe->key, "server.", NULL))
171         {
172             error_setg(errp, "Option %s cannot be used with a filename",
173                        qe->key);
174             return true;
175         }
176     }
177 
178     return false;
179 }
180 
181 static void nfs_parse_filename(const char *filename, QDict *options,
182                                Error **errp)
183 {
184     if (nfs_has_filename_options_conflict(options, errp)) {
185         return;
186     }
187 
188     nfs_parse_uri(filename, options, errp);
189 }
190 
191 static void nfs_process_read(void *arg);
192 static void nfs_process_write(void *arg);
193 
194 static void nfs_set_events(NFSClient *client)
195 {
196     int ev = nfs_which_events(client->context);
197     if (ev != client->events) {
198         aio_set_fd_handler(client->aio_context, nfs_get_fd(client->context),
199                            false,
200                            (ev & POLLIN) ? nfs_process_read : NULL,
201                            (ev & POLLOUT) ? nfs_process_write : NULL,
202                            NULL, client);
203 
204     }
205     client->events = ev;
206 }
207 
208 static void nfs_process_read(void *arg)
209 {
210     NFSClient *client = arg;
211 
212     aio_context_acquire(client->aio_context);
213     nfs_service(client->context, POLLIN);
214     nfs_set_events(client);
215     aio_context_release(client->aio_context);
216 }
217 
218 static void nfs_process_write(void *arg)
219 {
220     NFSClient *client = arg;
221 
222     aio_context_acquire(client->aio_context);
223     nfs_service(client->context, POLLOUT);
224     nfs_set_events(client);
225     aio_context_release(client->aio_context);
226 }
227 
228 static void nfs_co_init_task(BlockDriverState *bs, NFSRPC *task)
229 {
230     *task = (NFSRPC) {
231         .co             = qemu_coroutine_self(),
232         .bs             = bs,
233         .client         = bs->opaque,
234     };
235 }
236 
237 static void nfs_co_generic_bh_cb(void *opaque)
238 {
239     NFSRPC *task = opaque;
240 
241     task->complete = 1;
242     aio_co_wake(task->co);
243 }
244 
245 static void
246 nfs_co_generic_cb(int ret, struct nfs_context *nfs, void *data,
247                   void *private_data)
248 {
249     NFSRPC *task = private_data;
250     task->ret = ret;
251     assert(!task->st);
252     if (task->ret > 0 && task->iov) {
253         if (task->ret <= task->iov->size) {
254             qemu_iovec_from_buf(task->iov, 0, data, task->ret);
255         } else {
256             task->ret = -EIO;
257         }
258     }
259     if (task->ret < 0) {
260         error_report("NFS Error: %s", nfs_get_error(nfs));
261     }
262     aio_bh_schedule_oneshot(task->client->aio_context,
263                             nfs_co_generic_bh_cb, task);
264 }
265 
266 static int coroutine_fn nfs_co_readv(BlockDriverState *bs,
267                                      int64_t sector_num, int nb_sectors,
268                                      QEMUIOVector *iov)
269 {
270     NFSClient *client = bs->opaque;
271     NFSRPC task;
272 
273     nfs_co_init_task(bs, &task);
274     task.iov = iov;
275 
276     if (nfs_pread_async(client->context, client->fh,
277                         sector_num * BDRV_SECTOR_SIZE,
278                         nb_sectors * BDRV_SECTOR_SIZE,
279                         nfs_co_generic_cb, &task) != 0) {
280         return -ENOMEM;
281     }
282 
283     nfs_set_events(client);
284     while (!task.complete) {
285         qemu_coroutine_yield();
286     }
287 
288     if (task.ret < 0) {
289         return task.ret;
290     }
291 
292     /* zero pad short reads */
293     if (task.ret < iov->size) {
294         qemu_iovec_memset(iov, task.ret, 0, iov->size - task.ret);
295     }
296 
297     return 0;
298 }
299 
300 static int coroutine_fn nfs_co_writev(BlockDriverState *bs,
301                                         int64_t sector_num, int nb_sectors,
302                                         QEMUIOVector *iov)
303 {
304     NFSClient *client = bs->opaque;
305     NFSRPC task;
306     char *buf = NULL;
307 
308     nfs_co_init_task(bs, &task);
309 
310     buf = g_try_malloc(nb_sectors * BDRV_SECTOR_SIZE);
311     if (nb_sectors && buf == NULL) {
312         return -ENOMEM;
313     }
314 
315     qemu_iovec_to_buf(iov, 0, buf, nb_sectors * BDRV_SECTOR_SIZE);
316 
317     if (nfs_pwrite_async(client->context, client->fh,
318                          sector_num * BDRV_SECTOR_SIZE,
319                          nb_sectors * BDRV_SECTOR_SIZE,
320                          buf, nfs_co_generic_cb, &task) != 0) {
321         g_free(buf);
322         return -ENOMEM;
323     }
324 
325     nfs_set_events(client);
326     while (!task.complete) {
327         qemu_coroutine_yield();
328     }
329 
330     g_free(buf);
331 
332     if (task.ret != nb_sectors * BDRV_SECTOR_SIZE) {
333         return task.ret < 0 ? task.ret : -EIO;
334     }
335 
336     return 0;
337 }
338 
339 static int coroutine_fn nfs_co_flush(BlockDriverState *bs)
340 {
341     NFSClient *client = bs->opaque;
342     NFSRPC task;
343 
344     nfs_co_init_task(bs, &task);
345 
346     if (nfs_fsync_async(client->context, client->fh, nfs_co_generic_cb,
347                         &task) != 0) {
348         return -ENOMEM;
349     }
350 
351     nfs_set_events(client);
352     while (!task.complete) {
353         qemu_coroutine_yield();
354     }
355 
356     return task.ret;
357 }
358 
359 static QemuOptsList runtime_opts = {
360     .name = "nfs",
361     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
362     .desc = {
363         {
364             .name = "path",
365             .type = QEMU_OPT_STRING,
366             .help = "Path of the image on the host",
367         },
368         {
369             .name = "user",
370             .type = QEMU_OPT_NUMBER,
371             .help = "UID value to use when talking to the server",
372         },
373         {
374             .name = "group",
375             .type = QEMU_OPT_NUMBER,
376             .help = "GID value to use when talking to the server",
377         },
378         {
379             .name = "tcp-syn-count",
380             .type = QEMU_OPT_NUMBER,
381             .help = "Number of SYNs to send during the session establish",
382         },
383         {
384             .name = "readahead-size",
385             .type = QEMU_OPT_NUMBER,
386             .help = "Set the readahead size in bytes",
387         },
388         {
389             .name = "page-cache-size",
390             .type = QEMU_OPT_NUMBER,
391             .help = "Set the pagecache size in bytes",
392         },
393         {
394             .name = "debug",
395             .type = QEMU_OPT_NUMBER,
396             .help = "Set the NFS debug level (max 2)",
397         },
398         { /* end of list */ }
399     },
400 };
401 
402 static void nfs_detach_aio_context(BlockDriverState *bs)
403 {
404     NFSClient *client = bs->opaque;
405 
406     aio_set_fd_handler(client->aio_context, nfs_get_fd(client->context),
407                        false, NULL, NULL, NULL, NULL);
408     client->events = 0;
409 }
410 
411 static void nfs_attach_aio_context(BlockDriverState *bs,
412                                    AioContext *new_context)
413 {
414     NFSClient *client = bs->opaque;
415 
416     client->aio_context = new_context;
417     nfs_set_events(client);
418 }
419 
420 static void nfs_client_close(NFSClient *client)
421 {
422     if (client->context) {
423         if (client->fh) {
424             nfs_close(client->context, client->fh);
425         }
426         aio_set_fd_handler(client->aio_context, nfs_get_fd(client->context),
427                            false, NULL, NULL, NULL, NULL);
428         nfs_destroy_context(client->context);
429     }
430     memset(client, 0, sizeof(NFSClient));
431 }
432 
433 static void nfs_file_close(BlockDriverState *bs)
434 {
435     NFSClient *client = bs->opaque;
436     nfs_client_close(client);
437 }
438 
439 static NFSServer *nfs_config(QDict *options, Error **errp)
440 {
441     NFSServer *server = NULL;
442     QDict *addr = NULL;
443     QObject *crumpled_addr = NULL;
444     Visitor *iv = NULL;
445     Error *local_error = NULL;
446 
447     qdict_extract_subqdict(options, &addr, "server.");
448     if (!qdict_size(addr)) {
449         error_setg(errp, "NFS server address missing");
450         goto out;
451     }
452 
453     crumpled_addr = qdict_crumple(addr, errp);
454     if (!crumpled_addr) {
455         goto out;
456     }
457 
458     iv = qobject_input_visitor_new(crumpled_addr, true);
459     visit_type_NFSServer(iv, NULL, &server, &local_error);
460     if (local_error) {
461         error_propagate(errp, local_error);
462         goto out;
463     }
464 
465 out:
466     QDECREF(addr);
467     qobject_decref(crumpled_addr);
468     visit_free(iv);
469     return server;
470 }
471 
472 
473 static int64_t nfs_client_open(NFSClient *client, QDict *options,
474                                int flags, Error **errp, int open_flags)
475 {
476     int ret = -EINVAL;
477     QemuOpts *opts = NULL;
478     Error *local_err = NULL;
479     struct stat st;
480     char *file = NULL, *strp = NULL;
481 
482     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
483     qemu_opts_absorb_qdict(opts, options, &local_err);
484     if (local_err) {
485         error_propagate(errp, local_err);
486         ret = -EINVAL;
487         goto fail;
488     }
489 
490     client->path = g_strdup(qemu_opt_get(opts, "path"));
491     if (!client->path) {
492         ret = -EINVAL;
493         error_setg(errp, "No path was specified");
494         goto fail;
495     }
496 
497     strp = strrchr(client->path, '/');
498     if (strp == NULL) {
499         error_setg(errp, "Invalid URL specified");
500         goto fail;
501     }
502     file = g_strdup(strp);
503     *strp = 0;
504 
505     /* Pop the config into our state object, Exit if invalid */
506     client->server = nfs_config(options, errp);
507     if (!client->server) {
508         ret = -EINVAL;
509         goto fail;
510     }
511 
512     client->context = nfs_init_context();
513     if (client->context == NULL) {
514         error_setg(errp, "Failed to init NFS context");
515         goto fail;
516     }
517 
518     if (qemu_opt_get(opts, "user")) {
519         client->uid = qemu_opt_get_number(opts, "user", 0);
520         nfs_set_uid(client->context, client->uid);
521     }
522 
523     if (qemu_opt_get(opts, "group")) {
524         client->gid = qemu_opt_get_number(opts, "group", 0);
525         nfs_set_gid(client->context, client->gid);
526     }
527 
528     if (qemu_opt_get(opts, "tcp-syn-count")) {
529         client->tcp_syncnt = qemu_opt_get_number(opts, "tcp-syn-count", 0);
530         nfs_set_tcp_syncnt(client->context, client->tcp_syncnt);
531     }
532 
533 #ifdef LIBNFS_FEATURE_READAHEAD
534     if (qemu_opt_get(opts, "readahead-size")) {
535         if (open_flags & BDRV_O_NOCACHE) {
536             error_setg(errp, "Cannot enable NFS readahead "
537                              "if cache.direct = on");
538             goto fail;
539         }
540         client->readahead = qemu_opt_get_number(opts, "readahead-size", 0);
541         if (client->readahead > QEMU_NFS_MAX_READAHEAD_SIZE) {
542             error_report("NFS Warning: Truncating NFS readahead "
543                          "size to %d", QEMU_NFS_MAX_READAHEAD_SIZE);
544             client->readahead = QEMU_NFS_MAX_READAHEAD_SIZE;
545         }
546         nfs_set_readahead(client->context, client->readahead);
547 #ifdef LIBNFS_FEATURE_PAGECACHE
548         nfs_set_pagecache_ttl(client->context, 0);
549 #endif
550         client->cache_used = true;
551     }
552 #endif
553 
554 #ifdef LIBNFS_FEATURE_PAGECACHE
555     if (qemu_opt_get(opts, "page-cache-size")) {
556         if (open_flags & BDRV_O_NOCACHE) {
557             error_setg(errp, "Cannot enable NFS pagecache "
558                              "if cache.direct = on");
559             goto fail;
560         }
561         client->pagecache = qemu_opt_get_number(opts, "page-cache-size", 0);
562         if (client->pagecache > QEMU_NFS_MAX_PAGECACHE_SIZE) {
563             error_report("NFS Warning: Truncating NFS pagecache "
564                          "size to %d pages", QEMU_NFS_MAX_PAGECACHE_SIZE);
565             client->pagecache = QEMU_NFS_MAX_PAGECACHE_SIZE;
566         }
567         nfs_set_pagecache(client->context, client->pagecache);
568         nfs_set_pagecache_ttl(client->context, 0);
569         client->cache_used = true;
570     }
571 #endif
572 
573 #ifdef LIBNFS_FEATURE_DEBUG
574     if (qemu_opt_get(opts, "debug")) {
575         client->debug = qemu_opt_get_number(opts, "debug", 0);
576         /* limit the maximum debug level to avoid potential flooding
577          * of our log files. */
578         if (client->debug > QEMU_NFS_MAX_DEBUG_LEVEL) {
579             error_report("NFS Warning: Limiting NFS debug level "
580                          "to %d", QEMU_NFS_MAX_DEBUG_LEVEL);
581             client->debug = QEMU_NFS_MAX_DEBUG_LEVEL;
582         }
583         nfs_set_debug(client->context, client->debug);
584     }
585 #endif
586 
587     ret = nfs_mount(client->context, client->server->host, client->path);
588     if (ret < 0) {
589         error_setg(errp, "Failed to mount nfs share: %s",
590                    nfs_get_error(client->context));
591         goto fail;
592     }
593 
594     if (flags & O_CREAT) {
595         ret = nfs_creat(client->context, file, 0600, &client->fh);
596         if (ret < 0) {
597             error_setg(errp, "Failed to create file: %s",
598                        nfs_get_error(client->context));
599             goto fail;
600         }
601     } else {
602         ret = nfs_open(client->context, file, flags, &client->fh);
603         if (ret < 0) {
604             error_setg(errp, "Failed to open file : %s",
605                        nfs_get_error(client->context));
606             goto fail;
607         }
608     }
609 
610     ret = nfs_fstat(client->context, client->fh, &st);
611     if (ret < 0) {
612         error_setg(errp, "Failed to fstat file: %s",
613                    nfs_get_error(client->context));
614         goto fail;
615     }
616 
617     ret = DIV_ROUND_UP(st.st_size, BDRV_SECTOR_SIZE);
618     client->st_blocks = st.st_blocks;
619     client->has_zero_init = S_ISREG(st.st_mode);
620     *strp = '/';
621     goto out;
622 
623 fail:
624     nfs_client_close(client);
625 out:
626     qemu_opts_del(opts);
627     g_free(file);
628     return ret;
629 }
630 
631 static int nfs_file_open(BlockDriverState *bs, QDict *options, int flags,
632                          Error **errp) {
633     NFSClient *client = bs->opaque;
634     int64_t ret;
635 
636     client->aio_context = bdrv_get_aio_context(bs);
637 
638     ret = nfs_client_open(client, options,
639                           (flags & BDRV_O_RDWR) ? O_RDWR : O_RDONLY,
640                           errp, bs->open_flags);
641     if (ret < 0) {
642         return ret;
643     }
644     bs->total_sectors = ret;
645     ret = 0;
646     return ret;
647 }
648 
649 static QemuOptsList nfs_create_opts = {
650     .name = "nfs-create-opts",
651     .head = QTAILQ_HEAD_INITIALIZER(nfs_create_opts.head),
652     .desc = {
653         {
654             .name = BLOCK_OPT_SIZE,
655             .type = QEMU_OPT_SIZE,
656             .help = "Virtual disk size"
657         },
658         { /* end of list */ }
659     }
660 };
661 
662 static int nfs_file_create(const char *url, QemuOpts *opts, Error **errp)
663 {
664     int ret = 0;
665     int64_t total_size = 0;
666     NFSClient *client = g_new0(NFSClient, 1);
667     QDict *options = NULL;
668 
669     client->aio_context = qemu_get_aio_context();
670 
671     /* Read out options */
672     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
673                           BDRV_SECTOR_SIZE);
674 
675     options = qdict_new();
676     ret = nfs_parse_uri(url, options, errp);
677     if (ret < 0) {
678         goto out;
679     }
680 
681     ret = nfs_client_open(client, options, O_CREAT, errp, 0);
682     if (ret < 0) {
683         goto out;
684     }
685     ret = nfs_ftruncate(client->context, client->fh, total_size);
686     nfs_client_close(client);
687 out:
688     QDECREF(options);
689     g_free(client);
690     return ret;
691 }
692 
693 static int nfs_has_zero_init(BlockDriverState *bs)
694 {
695     NFSClient *client = bs->opaque;
696     return client->has_zero_init;
697 }
698 
699 static void
700 nfs_get_allocated_file_size_cb(int ret, struct nfs_context *nfs, void *data,
701                                void *private_data)
702 {
703     NFSRPC *task = private_data;
704     task->ret = ret;
705     if (task->ret == 0) {
706         memcpy(task->st, data, sizeof(struct stat));
707     }
708     if (task->ret < 0) {
709         error_report("NFS Error: %s", nfs_get_error(nfs));
710     }
711     task->complete = 1;
712     bdrv_wakeup(task->bs);
713 }
714 
715 static int64_t nfs_get_allocated_file_size(BlockDriverState *bs)
716 {
717     NFSClient *client = bs->opaque;
718     NFSRPC task = {0};
719     struct stat st;
720 
721     if (bdrv_is_read_only(bs) &&
722         !(bs->open_flags & BDRV_O_NOCACHE)) {
723         return client->st_blocks * 512;
724     }
725 
726     task.bs = bs;
727     task.st = &st;
728     if (nfs_fstat_async(client->context, client->fh, nfs_get_allocated_file_size_cb,
729                         &task) != 0) {
730         return -ENOMEM;
731     }
732 
733     nfs_set_events(client);
734     BDRV_POLL_WHILE(bs, !task.complete);
735 
736     return (task.ret < 0 ? task.ret : st.st_blocks * 512);
737 }
738 
739 static int nfs_file_truncate(BlockDriverState *bs, int64_t offset)
740 {
741     NFSClient *client = bs->opaque;
742     return nfs_ftruncate(client->context, client->fh, offset);
743 }
744 
745 /* Note that this will not re-establish a connection with the NFS server
746  * - it is effectively a NOP.  */
747 static int nfs_reopen_prepare(BDRVReopenState *state,
748                               BlockReopenQueue *queue, Error **errp)
749 {
750     NFSClient *client = state->bs->opaque;
751     struct stat st;
752     int ret = 0;
753 
754     if (state->flags & BDRV_O_RDWR && bdrv_is_read_only(state->bs)) {
755         error_setg(errp, "Cannot open a read-only mount as read-write");
756         return -EACCES;
757     }
758 
759     if ((state->flags & BDRV_O_NOCACHE) && client->cache_used) {
760         error_setg(errp, "Cannot disable cache if libnfs readahead or"
761                          " pagecache is enabled");
762         return -EINVAL;
763     }
764 
765     /* Update cache for read-only reopens */
766     if (!(state->flags & BDRV_O_RDWR)) {
767         ret = nfs_fstat(client->context, client->fh, &st);
768         if (ret < 0) {
769             error_setg(errp, "Failed to fstat file: %s",
770                        nfs_get_error(client->context));
771             return ret;
772         }
773         client->st_blocks = st.st_blocks;
774     }
775 
776     return 0;
777 }
778 
779 static void nfs_refresh_filename(BlockDriverState *bs, QDict *options)
780 {
781     NFSClient *client = bs->opaque;
782     QDict *opts = qdict_new();
783     QObject *server_qdict;
784     Visitor *ov;
785 
786     qdict_put(opts, "driver", qstring_from_str("nfs"));
787 
788     if (client->uid && !client->gid) {
789         snprintf(bs->exact_filename, sizeof(bs->exact_filename),
790                  "nfs://%s%s?uid=%" PRId64, client->server->host, client->path,
791                  client->uid);
792     } else if (!client->uid && client->gid) {
793         snprintf(bs->exact_filename, sizeof(bs->exact_filename),
794                  "nfs://%s%s?gid=%" PRId64, client->server->host, client->path,
795                  client->gid);
796     } else if (client->uid && client->gid) {
797         snprintf(bs->exact_filename, sizeof(bs->exact_filename),
798                  "nfs://%s%s?uid=%" PRId64 "&gid=%" PRId64,
799                  client->server->host, client->path, client->uid, client->gid);
800     } else {
801         snprintf(bs->exact_filename, sizeof(bs->exact_filename),
802                  "nfs://%s%s", client->server->host, client->path);
803     }
804 
805     ov = qobject_output_visitor_new(&server_qdict);
806     visit_type_NFSServer(ov, NULL, &client->server, &error_abort);
807     visit_complete(ov, &server_qdict);
808     assert(qobject_type(server_qdict) == QTYPE_QDICT);
809 
810     qdict_put_obj(opts, "server", server_qdict);
811     qdict_put(opts, "path", qstring_from_str(client->path));
812 
813     if (client->uid) {
814         qdict_put(opts, "user", qint_from_int(client->uid));
815     }
816     if (client->gid) {
817         qdict_put(opts, "group", qint_from_int(client->gid));
818     }
819     if (client->tcp_syncnt) {
820         qdict_put(opts, "tcp-syn-cnt",
821                   qint_from_int(client->tcp_syncnt));
822     }
823     if (client->readahead) {
824         qdict_put(opts, "readahead-size",
825                   qint_from_int(client->readahead));
826     }
827     if (client->pagecache) {
828         qdict_put(opts, "page-cache-size",
829                   qint_from_int(client->pagecache));
830     }
831     if (client->debug) {
832         qdict_put(opts, "debug", qint_from_int(client->debug));
833     }
834 
835     visit_free(ov);
836     qdict_flatten(opts);
837     bs->full_open_options = opts;
838 }
839 
840 #ifdef LIBNFS_FEATURE_PAGECACHE
841 static void nfs_invalidate_cache(BlockDriverState *bs,
842                                  Error **errp)
843 {
844     NFSClient *client = bs->opaque;
845     nfs_pagecache_invalidate(client->context, client->fh);
846 }
847 #endif
848 
849 static BlockDriver bdrv_nfs = {
850     .format_name                    = "nfs",
851     .protocol_name                  = "nfs",
852 
853     .instance_size                  = sizeof(NFSClient),
854     .bdrv_parse_filename            = nfs_parse_filename,
855     .create_opts                    = &nfs_create_opts,
856 
857     .bdrv_has_zero_init             = nfs_has_zero_init,
858     .bdrv_get_allocated_file_size   = nfs_get_allocated_file_size,
859     .bdrv_truncate                  = nfs_file_truncate,
860 
861     .bdrv_file_open                 = nfs_file_open,
862     .bdrv_close                     = nfs_file_close,
863     .bdrv_create                    = nfs_file_create,
864     .bdrv_reopen_prepare            = nfs_reopen_prepare,
865 
866     .bdrv_co_readv                  = nfs_co_readv,
867     .bdrv_co_writev                 = nfs_co_writev,
868     .bdrv_co_flush_to_disk          = nfs_co_flush,
869 
870     .bdrv_detach_aio_context        = nfs_detach_aio_context,
871     .bdrv_attach_aio_context        = nfs_attach_aio_context,
872     .bdrv_refresh_filename          = nfs_refresh_filename,
873 
874 #ifdef LIBNFS_FEATURE_PAGECACHE
875     .bdrv_invalidate_cache          = nfs_invalidate_cache,
876 #endif
877 };
878 
879 static void nfs_block_init(void)
880 {
881     bdrv_register(&bdrv_nfs);
882 }
883 
884 block_init(nfs_block_init);
885