xref: /openbmc/qemu/block/nfs.c (revision 3aff6c2f)
1 /*
2  * QEMU Block driver for native access to files on NFS shares
3  *
4  * Copyright (c) 2014 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 "config-host.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 "block/block_int.h"
32 #include "trace.h"
33 #include "qemu/iov.h"
34 #include "qemu/uri.h"
35 #include "sysemu/sysemu.h"
36 #include <nfsc/libnfs.h>
37 
38 typedef struct NFSClient {
39     struct nfs_context *context;
40     struct nfsfh *fh;
41     int events;
42     bool has_zero_init;
43     AioContext *aio_context;
44 } NFSClient;
45 
46 typedef struct NFSRPC {
47     int ret;
48     int complete;
49     QEMUIOVector *iov;
50     struct stat *st;
51     Coroutine *co;
52     QEMUBH *bh;
53     NFSClient *client;
54 } NFSRPC;
55 
56 static void nfs_process_read(void *arg);
57 static void nfs_process_write(void *arg);
58 
59 static void nfs_set_events(NFSClient *client)
60 {
61     int ev = nfs_which_events(client->context);
62     if (ev != client->events) {
63         aio_set_fd_handler(client->aio_context,
64                            nfs_get_fd(client->context),
65                            (ev & POLLIN) ? nfs_process_read : NULL,
66                            (ev & POLLOUT) ? nfs_process_write : NULL,
67                            client);
68 
69     }
70     client->events = ev;
71 }
72 
73 static void nfs_process_read(void *arg)
74 {
75     NFSClient *client = arg;
76     nfs_service(client->context, POLLIN);
77     nfs_set_events(client);
78 }
79 
80 static void nfs_process_write(void *arg)
81 {
82     NFSClient *client = arg;
83     nfs_service(client->context, POLLOUT);
84     nfs_set_events(client);
85 }
86 
87 static void nfs_co_init_task(NFSClient *client, NFSRPC *task)
88 {
89     *task = (NFSRPC) {
90         .co             = qemu_coroutine_self(),
91         .client         = client,
92     };
93 }
94 
95 static void nfs_co_generic_bh_cb(void *opaque)
96 {
97     NFSRPC *task = opaque;
98     qemu_bh_delete(task->bh);
99     qemu_coroutine_enter(task->co, NULL);
100 }
101 
102 static void
103 nfs_co_generic_cb(int ret, struct nfs_context *nfs, void *data,
104                   void *private_data)
105 {
106     NFSRPC *task = private_data;
107     task->complete = 1;
108     task->ret = ret;
109     if (task->ret > 0 && task->iov) {
110         if (task->ret <= task->iov->size) {
111             qemu_iovec_from_buf(task->iov, 0, data, task->ret);
112         } else {
113             task->ret = -EIO;
114         }
115     }
116     if (task->ret == 0 && task->st) {
117         memcpy(task->st, data, sizeof(struct stat));
118     }
119     if (task->ret < 0) {
120         error_report("NFS Error: %s", nfs_get_error(nfs));
121     }
122     if (task->co) {
123         task->bh = aio_bh_new(task->client->aio_context,
124                               nfs_co_generic_bh_cb, task);
125         qemu_bh_schedule(task->bh);
126     }
127 }
128 
129 static int coroutine_fn nfs_co_readv(BlockDriverState *bs,
130                                      int64_t sector_num, int nb_sectors,
131                                      QEMUIOVector *iov)
132 {
133     NFSClient *client = bs->opaque;
134     NFSRPC task;
135 
136     nfs_co_init_task(client, &task);
137     task.iov = iov;
138 
139     if (nfs_pread_async(client->context, client->fh,
140                         sector_num * BDRV_SECTOR_SIZE,
141                         nb_sectors * BDRV_SECTOR_SIZE,
142                         nfs_co_generic_cb, &task) != 0) {
143         return -ENOMEM;
144     }
145 
146     while (!task.complete) {
147         nfs_set_events(client);
148         qemu_coroutine_yield();
149     }
150 
151     if (task.ret < 0) {
152         return task.ret;
153     }
154 
155     /* zero pad short reads */
156     if (task.ret < iov->size) {
157         qemu_iovec_memset(iov, task.ret, 0, iov->size - task.ret);
158     }
159 
160     return 0;
161 }
162 
163 static int coroutine_fn nfs_co_writev(BlockDriverState *bs,
164                                         int64_t sector_num, int nb_sectors,
165                                         QEMUIOVector *iov)
166 {
167     NFSClient *client = bs->opaque;
168     NFSRPC task;
169     char *buf = NULL;
170 
171     nfs_co_init_task(client, &task);
172 
173     buf = g_malloc(nb_sectors * BDRV_SECTOR_SIZE);
174     qemu_iovec_to_buf(iov, 0, buf, nb_sectors * BDRV_SECTOR_SIZE);
175 
176     if (nfs_pwrite_async(client->context, client->fh,
177                          sector_num * BDRV_SECTOR_SIZE,
178                          nb_sectors * BDRV_SECTOR_SIZE,
179                          buf, nfs_co_generic_cb, &task) != 0) {
180         g_free(buf);
181         return -ENOMEM;
182     }
183 
184     while (!task.complete) {
185         nfs_set_events(client);
186         qemu_coroutine_yield();
187     }
188 
189     g_free(buf);
190 
191     if (task.ret != nb_sectors * BDRV_SECTOR_SIZE) {
192         return task.ret < 0 ? task.ret : -EIO;
193     }
194 
195     return 0;
196 }
197 
198 static int coroutine_fn nfs_co_flush(BlockDriverState *bs)
199 {
200     NFSClient *client = bs->opaque;
201     NFSRPC task;
202 
203     nfs_co_init_task(client, &task);
204 
205     if (nfs_fsync_async(client->context, client->fh, nfs_co_generic_cb,
206                         &task) != 0) {
207         return -ENOMEM;
208     }
209 
210     while (!task.complete) {
211         nfs_set_events(client);
212         qemu_coroutine_yield();
213     }
214 
215     return task.ret;
216 }
217 
218 /* TODO Convert to fine grained options */
219 static QemuOptsList runtime_opts = {
220     .name = "nfs",
221     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
222     .desc = {
223         {
224             .name = "filename",
225             .type = QEMU_OPT_STRING,
226             .help = "URL to the NFS file",
227         },
228         { /* end of list */ }
229     },
230 };
231 
232 static void nfs_detach_aio_context(BlockDriverState *bs)
233 {
234     NFSClient *client = bs->opaque;
235 
236     aio_set_fd_handler(client->aio_context,
237                        nfs_get_fd(client->context),
238                        NULL, NULL, NULL);
239     client->events = 0;
240 }
241 
242 static void nfs_attach_aio_context(BlockDriverState *bs,
243                                    AioContext *new_context)
244 {
245     NFSClient *client = bs->opaque;
246 
247     client->aio_context = new_context;
248     nfs_set_events(client);
249 }
250 
251 static void nfs_client_close(NFSClient *client)
252 {
253     if (client->context) {
254         if (client->fh) {
255             nfs_close(client->context, client->fh);
256         }
257         aio_set_fd_handler(client->aio_context,
258                            nfs_get_fd(client->context),
259                            NULL, NULL, NULL);
260         nfs_destroy_context(client->context);
261     }
262     memset(client, 0, sizeof(NFSClient));
263 }
264 
265 static void nfs_file_close(BlockDriverState *bs)
266 {
267     NFSClient *client = bs->opaque;
268     nfs_client_close(client);
269 }
270 
271 static int64_t nfs_client_open(NFSClient *client, const char *filename,
272                                int flags, Error **errp)
273 {
274     int ret = -EINVAL, i;
275     struct stat st;
276     URI *uri;
277     QueryParams *qp = NULL;
278     char *file = NULL, *strp = NULL;
279 
280     uri = uri_parse(filename);
281     if (!uri) {
282         error_setg(errp, "Invalid URL specified");
283         goto fail;
284     }
285     if (!uri->server) {
286         error_setg(errp, "Invalid URL specified");
287         goto fail;
288     }
289     strp = strrchr(uri->path, '/');
290     if (strp == NULL) {
291         error_setg(errp, "Invalid URL specified");
292         goto fail;
293     }
294     file = g_strdup(strp);
295     *strp = 0;
296 
297     client->context = nfs_init_context();
298     if (client->context == NULL) {
299         error_setg(errp, "Failed to init NFS context");
300         goto fail;
301     }
302 
303     qp = query_params_parse(uri->query);
304     for (i = 0; i < qp->n; i++) {
305         if (!qp->p[i].value) {
306             error_setg(errp, "Value for NFS parameter expected: %s",
307                        qp->p[i].name);
308             goto fail;
309         }
310         if (!strncmp(qp->p[i].name, "uid", 3)) {
311             nfs_set_uid(client->context, atoi(qp->p[i].value));
312         } else if (!strncmp(qp->p[i].name, "gid", 3)) {
313             nfs_set_gid(client->context, atoi(qp->p[i].value));
314         } else if (!strncmp(qp->p[i].name, "tcp-syncnt", 10)) {
315             nfs_set_tcp_syncnt(client->context, atoi(qp->p[i].value));
316         } else {
317             error_setg(errp, "Unknown NFS parameter name: %s",
318                        qp->p[i].name);
319             goto fail;
320         }
321     }
322 
323     ret = nfs_mount(client->context, uri->server, uri->path);
324     if (ret < 0) {
325         error_setg(errp, "Failed to mount nfs share: %s",
326                    nfs_get_error(client->context));
327         goto fail;
328     }
329 
330     if (flags & O_CREAT) {
331         ret = nfs_creat(client->context, file, 0600, &client->fh);
332         if (ret < 0) {
333             error_setg(errp, "Failed to create file: %s",
334                        nfs_get_error(client->context));
335             goto fail;
336         }
337     } else {
338         ret = nfs_open(client->context, file, flags, &client->fh);
339         if (ret < 0) {
340             error_setg(errp, "Failed to open file : %s",
341                        nfs_get_error(client->context));
342             goto fail;
343         }
344     }
345 
346     ret = nfs_fstat(client->context, client->fh, &st);
347     if (ret < 0) {
348         error_setg(errp, "Failed to fstat file: %s",
349                    nfs_get_error(client->context));
350         goto fail;
351     }
352 
353     ret = DIV_ROUND_UP(st.st_size, BDRV_SECTOR_SIZE);
354     client->has_zero_init = S_ISREG(st.st_mode);
355     goto out;
356 fail:
357     nfs_client_close(client);
358 out:
359     if (qp) {
360         query_params_free(qp);
361     }
362     uri_free(uri);
363     g_free(file);
364     return ret;
365 }
366 
367 static int nfs_file_open(BlockDriverState *bs, QDict *options, int flags,
368                          Error **errp) {
369     NFSClient *client = bs->opaque;
370     int64_t ret;
371     QemuOpts *opts;
372     Error *local_err = NULL;
373 
374     client->aio_context = bdrv_get_aio_context(bs);
375 
376     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
377     qemu_opts_absorb_qdict(opts, options, &local_err);
378     if (local_err) {
379         error_propagate(errp, local_err);
380         return -EINVAL;
381     }
382     ret = nfs_client_open(client, qemu_opt_get(opts, "filename"),
383                           (flags & BDRV_O_RDWR) ? O_RDWR : O_RDONLY,
384                           errp);
385     if (ret < 0) {
386         return ret;
387     }
388     bs->total_sectors = ret;
389     return 0;
390 }
391 
392 static int nfs_file_create(const char *url, QEMUOptionParameter *options,
393                            Error **errp)
394 {
395     int ret = 0;
396     int64_t total_size = 0;
397     NFSClient *client = g_malloc0(sizeof(NFSClient));
398 
399     client->aio_context = qemu_get_aio_context();
400 
401     /* Read out options */
402     while (options && options->name) {
403         if (!strcmp(options->name, "size")) {
404             total_size = options->value.n;
405         }
406         options++;
407     }
408 
409     ret = nfs_client_open(client, url, O_CREAT, errp);
410     if (ret < 0) {
411         goto out;
412     }
413     ret = nfs_ftruncate(client->context, client->fh, total_size);
414     nfs_client_close(client);
415 out:
416     g_free(client);
417     return ret;
418 }
419 
420 static int nfs_has_zero_init(BlockDriverState *bs)
421 {
422     NFSClient *client = bs->opaque;
423     return client->has_zero_init;
424 }
425 
426 static int64_t nfs_get_allocated_file_size(BlockDriverState *bs)
427 {
428     NFSClient *client = bs->opaque;
429     NFSRPC task = {0};
430     struct stat st;
431 
432     task.st = &st;
433     if (nfs_fstat_async(client->context, client->fh, nfs_co_generic_cb,
434                         &task) != 0) {
435         return -ENOMEM;
436     }
437 
438     while (!task.complete) {
439         nfs_set_events(client);
440         aio_poll(client->aio_context, true);
441     }
442 
443     return (task.ret < 0 ? task.ret : st.st_blocks * st.st_blksize);
444 }
445 
446 static int nfs_file_truncate(BlockDriverState *bs, int64_t offset)
447 {
448     NFSClient *client = bs->opaque;
449     return nfs_ftruncate(client->context, client->fh, offset);
450 }
451 
452 static BlockDriver bdrv_nfs = {
453     .format_name                    = "nfs",
454     .protocol_name                  = "nfs",
455 
456     .instance_size                  = sizeof(NFSClient),
457     .bdrv_needs_filename            = true,
458     .bdrv_has_zero_init             = nfs_has_zero_init,
459     .bdrv_get_allocated_file_size   = nfs_get_allocated_file_size,
460     .bdrv_truncate                  = nfs_file_truncate,
461 
462     .bdrv_file_open                 = nfs_file_open,
463     .bdrv_close                     = nfs_file_close,
464     .bdrv_create                    = nfs_file_create,
465 
466     .bdrv_co_readv                  = nfs_co_readv,
467     .bdrv_co_writev                 = nfs_co_writev,
468     .bdrv_co_flush_to_disk          = nfs_co_flush,
469 
470     .bdrv_detach_aio_context        = nfs_detach_aio_context,
471     .bdrv_attach_aio_context        = nfs_attach_aio_context,
472 };
473 
474 static void nfs_block_init(void)
475 {
476     bdrv_register(&bdrv_nfs);
477 }
478 
479 block_init(nfs_block_init);
480