]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/fuse/fuse_io.c
fusefs: implement non-clustered readahead
[FreeBSD/FreeBSD.git] / sys / fs / fuse / fuse_io.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2007-2009 Google Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are
9  * met:
10  *
11  * * Redistributions of source code must retain the above copyright
12  *   notice, this list of conditions and the following disclaimer.
13  * * Redistributions in binary form must reproduce the above
14  *   copyright notice, this list of conditions and the following disclaimer
15  *   in the documentation and/or other materials provided with the
16  *   distribution.
17  * * Neither the name of Google Inc. nor the names of its
18  *   contributors may be used to endorse or promote products derived from
19  *   this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  * Copyright (C) 2005 Csaba Henk.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  *
45  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57
58 #include <sys/cdefs.h>
59 __FBSDID("$FreeBSD$");
60
61 #include <sys/types.h>
62 #include <sys/module.h>
63 #include <sys/systm.h>
64 #include <sys/errno.h>
65 #include <sys/param.h>
66 #include <sys/kernel.h>
67 #include <sys/conf.h>
68 #include <sys/uio.h>
69 #include <sys/malloc.h>
70 #include <sys/queue.h>
71 #include <sys/lock.h>
72 #include <sys/sx.h>
73 #include <sys/mutex.h>
74 #include <sys/rwlock.h>
75 #include <sys/priv.h>
76 #include <sys/proc.h>
77 #include <sys/mount.h>
78 #include <sys/vnode.h>
79 #include <sys/stat.h>
80 #include <sys/unistd.h>
81 #include <sys/filedesc.h>
82 #include <sys/file.h>
83 #include <sys/fcntl.h>
84 #include <sys/bio.h>
85 #include <sys/buf.h>
86 #include <sys/sysctl.h>
87 #include <sys/vmmeter.h>
88
89 #include <vm/vm.h>
90 #include <vm/vm_extern.h>
91 #include <vm/pmap.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_object.h>
95
96 #include "fuse.h"
97 #include "fuse_file.h"
98 #include "fuse_node.h"
99 #include "fuse_internal.h"
100 #include "fuse_ipc.h"
101 #include "fuse_io.h"
102
103 SDT_PROVIDER_DECLARE(fusefs);
104 /* 
105  * Fuse trace probe:
106  * arg0: verbosity.  Higher numbers give more verbose messages
107  * arg1: Textual message
108  */
109 SDT_PROBE_DEFINE2(fusefs, , io, trace, "int", "char*");
110
111 static void
112 fuse_io_clear_suid_on_write(struct vnode *vp, struct ucred *cred,
113         struct thread *td);
114 static int 
115 fuse_read_directbackend(struct vnode *vp, struct uio *uio,
116     struct ucred *cred, struct fuse_filehandle *fufh);
117 static int 
118 fuse_read_biobackend(struct vnode *vp, struct uio *uio, int ioflag,
119     struct ucred *cred, struct fuse_filehandle *fufh, pid_t pid);
120 static int 
121 fuse_write_directbackend(struct vnode *vp, struct uio *uio,
122     struct ucred *cred, struct fuse_filehandle *fufh, off_t filesize,
123     int ioflag, bool pages);
124 static int 
125 fuse_write_biobackend(struct vnode *vp, struct uio *uio,
126     struct ucred *cred, struct fuse_filehandle *fufh, int ioflag, pid_t pid);
127
128 /*
129  * FreeBSD clears the SUID and SGID bits on any write by a non-root user.
130  */
131 static void
132 fuse_io_clear_suid_on_write(struct vnode *vp, struct ucred *cred,
133         struct thread *td)
134 {
135         struct fuse_data *data;
136         struct mount *mp;
137         struct vattr va;
138         int dataflags;
139
140         mp = vnode_mount(vp);
141         data = fuse_get_mpdata(mp);
142         dataflags = data->dataflags;
143
144         if (dataflags & FSESS_DEFAULT_PERMISSIONS) {
145                 if (priv_check_cred(cred, PRIV_VFS_RETAINSUGID)) {
146                         fuse_internal_getattr(vp, &va, cred, td);
147                         if (va.va_mode & (S_ISUID | S_ISGID)) {
148                                 mode_t mode = va.va_mode & ~(S_ISUID | S_ISGID);
149                                 /* Clear all vattr fields except mode */
150                                 vattr_null(&va);
151                                 va.va_mode = mode;
152
153                                 /*
154                                  * Ignore fuse_internal_setattr's return value,
155                                  * because at this point the write operation has
156                                  * already succeeded and we don't want to return
157                                  * failing status for that.
158                                  */
159                                 (void)fuse_internal_setattr(vp, &va, td, NULL);
160                         }
161                 }
162         }
163 }
164
165 SDT_PROBE_DEFINE5(fusefs, , io, io_dispatch, "struct vnode*", "struct uio*",
166                 "int", "struct ucred*", "struct fuse_filehandle*");
167 int
168 fuse_io_dispatch(struct vnode *vp, struct uio *uio, int ioflag, bool pages,
169     struct ucred *cred, pid_t pid)
170 {
171         struct fuse_filehandle *fufh;
172         int err, directio;
173         int fflag;
174         bool closefufh = false;
175
176         MPASS(vp->v_type == VREG || vp->v_type == VDIR);
177
178         fflag = (uio->uio_rw == UIO_READ) ? FREAD : FWRITE;
179         err = fuse_filehandle_getrw(vp, fflag, &fufh, cred, pid);
180         if (err == EBADF && vnode_mount(vp)->mnt_flag & MNT_EXPORTED) {
181                 /* 
182                  * nfsd will do I/O without first doing VOP_OPEN.  We
183                  * must implicitly open the file here
184                  */
185                 err = fuse_filehandle_open(vp, fflag, &fufh, curthread, cred);
186                 closefufh = true;
187         }
188         else if (err) {
189                 printf("FUSE: io dispatch: filehandles are closed\n");
190                 return err;
191         }
192         if (err)
193                 goto out;
194         SDT_PROBE5(fusefs, , io, io_dispatch, vp, uio, ioflag, cred, fufh);
195
196         /*
197          * Ideally, when the daemon asks for direct io at open time, the
198          * standard file flag should be set according to this, so that would
199          * just change the default mode, which later on could be changed via
200          * fcntl(2).
201          * But this doesn't work, the O_DIRECT flag gets cleared at some point
202          * (don't know where). So to make any use of the Fuse direct_io option,
203          * we hardwire it into the file's private data (similarly to Linux,
204          * btw.).
205          */
206         directio = (ioflag & IO_DIRECT) || !fsess_opt_datacache(vnode_mount(vp));
207
208         switch (uio->uio_rw) {
209         case UIO_READ:
210                 if (directio) {
211                         SDT_PROBE2(fusefs, , io, trace, 1,
212                                 "direct read of vnode");
213                         err = fuse_read_directbackend(vp, uio, cred, fufh);
214                 } else {
215                         SDT_PROBE2(fusefs, , io, trace, 1,
216                                 "buffered read of vnode");
217                         err = fuse_read_biobackend(vp, uio, ioflag, cred, fufh,
218                                 pid);
219                 }
220                 break;
221         case UIO_WRITE:
222                 if (directio) {
223                         const int iosize = fuse_iosize(vp);
224                         off_t start, end, filesize;
225
226                         SDT_PROBE2(fusefs, , io, trace, 1,
227                                 "direct write of vnode");
228
229                         err = fuse_vnode_size(vp, &filesize, cred, curthread);
230                         if (err)
231                                 goto out;
232
233                         start = uio->uio_offset;
234                         end = start + uio->uio_resid;
235                         /* 
236                          * Invalidate the write cache unless we're coming from
237                          * VOP_PUTPAGES, in which case we're writing _from_ the
238                          * write cache
239                          */
240                         if (!pages )
241                                 v_inval_buf_range(vp, start, end, iosize);
242                         err = fuse_write_directbackend(vp, uio, cred, fufh,
243                                 filesize, ioflag, pages);
244                 } else {
245                         SDT_PROBE2(fusefs, , io, trace, 1,
246                                 "buffered write of vnode");
247                         if (fuse_data_cache_mode == FUSE_CACHE_WT)
248                                 ioflag |= IO_SYNC;
249                         err = fuse_write_biobackend(vp, uio, cred, fufh, ioflag,
250                                 pid);
251                 }
252                 fuse_io_clear_suid_on_write(vp, cred, uio->uio_td);
253                 break;
254         default:
255                 panic("uninterpreted mode passed to fuse_io_dispatch");
256         }
257
258 out:
259         if (closefufh)
260                 fuse_filehandle_close(vp, fufh, curthread, cred);
261
262         return (err);
263 }
264
265 SDT_PROBE_DEFINE4(fusefs, , io, read_bio_backend_start, "int", "int", "int", "int");
266 SDT_PROBE_DEFINE2(fusefs, , io, read_bio_backend_feed, "int", "struct buf*");
267 SDT_PROBE_DEFINE4(fusefs, , io, read_bio_backend_end, "int", "ssize_t", "int",
268                 "struct buf*");
269 static int
270 fuse_read_biobackend(struct vnode *vp, struct uio *uio, int ioflag,
271     struct ucred *cred, struct fuse_filehandle *fufh, pid_t pid)
272 {
273         struct buf *bp;
274         struct mount *mp;
275         struct fuse_data *data;
276         daddr_t lbn, nextlbn;
277         int bcount, nextsize;
278         int err, n = 0, on = 0, seqcount;
279         off_t filesize;
280
281         const int biosize = fuse_iosize(vp);
282         mp = vnode_mount(vp);
283         data = fuse_get_mpdata(mp);
284
285         if (uio->uio_offset < 0)
286                 return (EINVAL);
287
288         seqcount = ioflag >> IO_SEQSHIFT;
289
290         err = fuse_vnode_size(vp, &filesize, cred, curthread);
291         if (err)
292                 return err;
293
294         for (err = 0, bp = NULL; uio->uio_resid > 0; bp = NULL) {
295                 if (fuse_isdeadfs(vp)) {
296                         err = ENXIO;
297                         break;
298                 }
299                 if (filesize - uio->uio_offset <= 0)
300                         break;
301                 lbn = uio->uio_offset / biosize;
302                 on = uio->uio_offset & (biosize - 1);
303
304                 if ((off_t)lbn * biosize >= filesize) {
305                         bcount = 0;
306                 } else if ((off_t)(lbn + 1) * biosize > filesize) {
307                         bcount = filesize - (off_t)lbn *biosize;
308                 } else {
309                         bcount = biosize;
310                 }
311                 nextlbn = lbn + 1;
312                 nextsize = MIN(biosize, filesize - nextlbn * biosize);
313
314                 SDT_PROBE4(fusefs, , io, read_bio_backend_start,
315                         biosize, (int)lbn, on, bcount);
316
317                 if (bcount < biosize) {
318                         /* If near EOF, don't do readahead */
319                         err = bread(vp, lbn, bcount, NOCRED, &bp);
320                 /* TODO: clustered read */
321                 } else if (seqcount > 1 && data->max_readahead >= nextsize) {
322                         /* Try non-clustered readahead */
323                         err = breadn(vp, lbn, bcount, &nextlbn, &nextsize, 1,
324                                 NOCRED, &bp);
325                 } else {
326                         /* Just read what was requested */
327                         err = bread(vp, lbn, bcount, NOCRED, &bp);
328                 }
329
330                 if (err) {
331                         brelse(bp);
332                         bp = NULL;
333                         break;
334                 }
335
336                 /*
337                  * on is the offset into the current bp.  Figure out how many
338                  * bytes we can copy out of the bp.  Note that bcount is
339                  * NOT DEV_BSIZE aligned.
340                  *
341                  * Then figure out how many bytes we can copy into the uio.
342                  */
343
344                 n = 0;
345                 if (on < bcount)
346                         n = MIN((unsigned)(bcount - on), uio->uio_resid);
347                 if (n > 0) {
348                         SDT_PROBE2(fusefs, , io, read_bio_backend_feed, n, bp);
349                         err = uiomove(bp->b_data + on, n, uio);
350                 }
351                 vfs_bio_brelse(bp, ioflag);
352                 SDT_PROBE4(fusefs, , io, read_bio_backend_end, err,
353                         uio->uio_resid, n, bp);
354         }
355
356         return (err);
357 }
358
359 SDT_PROBE_DEFINE1(fusefs, , io, read_directbackend_start,
360         "struct fuse_read_in*");
361 SDT_PROBE_DEFINE3(fusefs, , io, read_directbackend_complete,
362         "struct fuse_dispatcher*", "struct fuse_read_in*", "struct uio*");
363
364 static int
365 fuse_read_directbackend(struct vnode *vp, struct uio *uio,
366     struct ucred *cred, struct fuse_filehandle *fufh)
367 {
368         struct fuse_data *data;
369         struct fuse_dispatcher fdi;
370         struct fuse_read_in *fri;
371         int err = 0;
372
373         data = fuse_get_mpdata(vp->v_mount);
374
375         if (uio->uio_resid == 0)
376                 return (0);
377
378         fdisp_init(&fdi, 0);
379
380         /*
381          * XXX In "normal" case we use an intermediate kernel buffer for
382          * transmitting data from daemon's context to ours. Eventually, we should
383          * get rid of this. Anyway, if the target uio lives in sysspace (we are
384          * called from pageops), and the input data doesn't need kernel-side
385          * processing (we are not called from readdir) we can already invoke
386          * an optimized, "peer-to-peer" I/O routine.
387          */
388         while (uio->uio_resid > 0) {
389                 fdi.iosize = sizeof(*fri);
390                 fdisp_make_vp(&fdi, FUSE_READ, vp, uio->uio_td, cred);
391                 fri = fdi.indata;
392                 fri->fh = fufh->fh_id;
393                 fri->offset = uio->uio_offset;
394                 fri->size = MIN(uio->uio_resid,
395                     fuse_get_mpdata(vp->v_mount)->max_read);
396                 if (fuse_libabi_geq(data, 7, 9)) {
397                         /* See comment regarding FUSE_WRITE_LOCKOWNER */
398                         fri->read_flags = 0;
399                         fri->flags = fufh_type_2_fflags(fufh->fufh_type);
400                 }
401
402                 SDT_PROBE1(fusefs, , io, read_directbackend_start, fri);
403
404                 if ((err = fdisp_wait_answ(&fdi)))
405                         goto out;
406
407                 SDT_PROBE3(fusefs, , io, read_directbackend_complete,
408                         &fdi, fri, uio);
409
410                 if ((err = uiomove(fdi.answ, MIN(fri->size, fdi.iosize), uio)))
411                         break;
412                 if (fdi.iosize < fri->size)
413                         break;
414         }
415
416 out:
417         fdisp_destroy(&fdi);
418         return (err);
419 }
420
421 static int
422 fuse_write_directbackend(struct vnode *vp, struct uio *uio,
423     struct ucred *cred, struct fuse_filehandle *fufh, off_t filesize,
424     int ioflag, bool pages)
425 {
426         struct fuse_vnode_data *fvdat = VTOFUD(vp);
427         struct fuse_data *data;
428         struct fuse_write_in *fwi;
429         struct fuse_write_out *fwo;
430         struct fuse_dispatcher fdi;
431         size_t chunksize;
432         void *fwi_data;
433         off_t as_written_offset;
434         int diff;
435         int err = 0;
436         bool direct_io = fufh->fuse_open_flags & FOPEN_DIRECT_IO;
437         uint32_t write_flags;
438
439         data = fuse_get_mpdata(vp->v_mount);
440
441         /* 
442          * Don't set FUSE_WRITE_LOCKOWNER in write_flags.  It can't be set
443          * accurately when using POSIX AIO, libfuse doesn't use it, and I'm not
444          * aware of any file systems that do.  It was an attempt to add
445          * Linux-style mandatory locking to the FUSE protocol, but mandatory
446          * locking is deprecated even on Linux.  See Linux commit
447          * f33321141b273d60cbb3a8f56a5489baad82ba5e .
448          */
449         /*
450          * Set FUSE_WRITE_CACHE whenever we don't know the uid, gid, and/or pid
451          * that originated a write.  For example when writing from the
452          * writeback cache.  I don't know of a single file system that cares,
453          * but the protocol says we're supposed to do this.
454          */
455         write_flags = !pages && (
456                 (ioflag & IO_DIRECT) ||
457                 !fsess_opt_datacache(vnode_mount(vp)) ||
458                 fuse_data_cache_mode != FUSE_CACHE_WB) ? 0 : FUSE_WRITE_CACHE;
459
460         if (uio->uio_resid == 0)
461                 return (0);
462
463         if (ioflag & IO_APPEND)
464                 uio_setoffset(uio, filesize);
465
466         if (vn_rlimit_fsize(vp, uio, uio->uio_td))
467                 return (EFBIG);
468
469         fdisp_init(&fdi, 0);
470
471         while (uio->uio_resid > 0) {
472                 chunksize = MIN(uio->uio_resid, data->max_write);
473
474                 fdi.iosize = sizeof(*fwi) + chunksize;
475                 fdisp_make_vp(&fdi, FUSE_WRITE, vp, uio->uio_td, cred);
476
477                 fwi = fdi.indata;
478                 fwi->fh = fufh->fh_id;
479                 fwi->offset = uio->uio_offset;
480                 fwi->size = chunksize;
481                 fwi->write_flags = write_flags;
482                 if (fuse_libabi_geq(data, 7, 9)) {
483                         fwi->flags = fufh_type_2_fflags(fufh->fufh_type);
484                         fwi_data = (char *)fdi.indata + sizeof(*fwi);
485                 } else {
486                         fwi_data = (char *)fdi.indata +
487                                 FUSE_COMPAT_WRITE_IN_SIZE;
488                 }
489
490                 if ((err = uiomove(fwi_data, chunksize, uio)))
491                         break;
492
493 retry:
494                 err = fdisp_wait_answ(&fdi);
495                 if (err == ERESTART || err == EINTR || err == EWOULDBLOCK) {
496                         /*
497                          * Rewind the uio so dofilewrite will know it's
498                          * incomplete
499                          */
500                         uio->uio_resid += fwi->size;
501                         uio->uio_offset -= fwi->size;
502                         /* 
503                          * Change ERESTART into EINTR because we can't rewind
504                          * uio->uio_iov.  Basically, once uiomove(9) has been
505                          * called, it's impossible to restart a syscall.
506                          */
507                         if (err == ERESTART)
508                                 err = EINTR;
509                         break;
510                 } else if (err) {
511                         break;
512                 }
513
514                 fwo = ((struct fuse_write_out *)fdi.answ);
515
516                 /* Adjust the uio in the case of short writes */
517                 diff = fwi->size - fwo->size;
518                 as_written_offset = uio->uio_offset - diff;
519
520                 if (as_written_offset - diff > filesize &&
521                     fuse_data_cache_mode != FUSE_CACHE_UC)
522                         fuse_vnode_setsize(vp, as_written_offset);
523                 if (as_written_offset - diff >= filesize)
524                         fvdat->flag &= ~FN_SIZECHANGE;
525
526                 if (diff < 0) {
527                         printf("WARNING: misbehaving FUSE filesystem "
528                                 "wrote more data than we provided it\n");
529                         err = EINVAL;
530                         break;
531                 } else if (diff > 0) {
532                         /* Short write */
533                         if (!direct_io) {
534                                 printf("WARNING: misbehaving FUSE filesystem: "
535                                         "short writes are only allowed with "
536                                         "direct_io\n");
537                         }
538                         if (ioflag & IO_DIRECT) {
539                                 /* Return early */
540                                 uio->uio_resid += diff;
541                                 uio->uio_offset -= diff;
542                                 break;
543                         } else {
544                                 /* Resend the unwritten portion of data */
545                                 fdi.iosize = sizeof(*fwi) + diff;
546                                 /* Refresh fdi without clearing data buffer */
547                                 fdisp_refresh_vp(&fdi, FUSE_WRITE, vp,
548                                         uio->uio_td, cred);
549                                 fwi = fdi.indata;
550                                 MPASS2(fwi == fdi.indata, "FUSE dispatcher "
551                                         "reallocated despite no increase in "
552                                         "size?");
553                                 void *src = (char*)fwi_data + fwo->size;
554                                 memmove(fwi_data, src, diff);
555                                 fwi->fh = fufh->fh_id;
556                                 fwi->offset = as_written_offset;
557                                 fwi->size = diff;
558                                 fwi->write_flags = write_flags;
559                                 goto retry;
560                         }
561                 }
562         }
563
564         fdisp_destroy(&fdi);
565
566         return (err);
567 }
568
569 SDT_PROBE_DEFINE6(fusefs, , io, write_biobackend_start, "int64_t", "int", "int",
570                 "struct uio*", "int", "bool");
571 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_append_race, "long", "int");
572 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_issue, "int", "struct buf*");
573
574 static int
575 fuse_write_biobackend(struct vnode *vp, struct uio *uio,
576     struct ucred *cred, struct fuse_filehandle *fufh, int ioflag, pid_t pid)
577 {
578         struct fuse_vnode_data *fvdat = VTOFUD(vp);
579         struct buf *bp;
580         daddr_t lbn;
581         off_t filesize;
582         int bcount;
583         int n, on, seqcount, err = 0;
584         bool last_page;
585
586         const int biosize = fuse_iosize(vp);
587
588         seqcount = ioflag >> IO_SEQSHIFT;
589
590         KASSERT(uio->uio_rw == UIO_WRITE, ("fuse_write_biobackend mode"));
591         if (vp->v_type != VREG)
592                 return (EIO);
593         if (uio->uio_offset < 0)
594                 return (EINVAL);
595         if (uio->uio_resid == 0)
596                 return (0);
597
598         err = fuse_vnode_size(vp, &filesize, cred, curthread);
599         if (err)
600                 return err;
601
602         if (ioflag & IO_APPEND)
603                 uio_setoffset(uio, filesize);
604
605         if (vn_rlimit_fsize(vp, uio, uio->uio_td))
606                 return (EFBIG);
607
608         do {
609                 bool direct_append, extending;
610
611                 if (fuse_isdeadfs(vp)) {
612                         err = ENXIO;
613                         break;
614                 }
615                 lbn = uio->uio_offset / biosize;
616                 on = uio->uio_offset & (biosize - 1);
617                 n = MIN((unsigned)(biosize - on), uio->uio_resid);
618
619 again:
620                 /* Get or create a buffer for the write */
621                 direct_append = uio->uio_offset == filesize && n;
622                 if (uio->uio_offset + n < filesize) {
623                         extending = false;
624                         if ((off_t)(lbn + 1) * biosize < filesize) {
625                                 /* Not the file's last block */
626                                 bcount = biosize;
627                         } else {
628                                 /* The file's last block */
629                                 bcount = filesize - (off_t)lbn * biosize;
630                         }
631                 } else {
632                         extending = true;
633                         bcount = on + n;
634                 }
635                 if (howmany(((off_t)lbn * biosize + on + n - 1), PAGE_SIZE) >=
636                     howmany(filesize, PAGE_SIZE))
637                         last_page = true;
638                 else
639                         last_page = false;
640                 if (direct_append) {
641                         /* 
642                          * Take care to preserve the buffer's B_CACHE state so
643                          * as not to cause an unnecessary read.
644                          */
645                         bp = getblk(vp, lbn, on, PCATCH, 0, 0);
646                         if (bp != NULL) {
647                                 uint32_t save = bp->b_flags & B_CACHE;
648                                 allocbuf(bp, bcount);
649                                 bp->b_flags |= save;
650                         }
651                 } else {
652                         bp = getblk(vp, lbn, bcount, PCATCH, 0, 0);
653                 }
654                 if (!bp) {
655                         err = EINTR;
656                         break;
657                 }
658                 if (extending) {
659                         /* 
660                          * Extend file _after_ locking buffer so we won't race
661                          * with other readers
662                          */
663                         err = fuse_vnode_setsize(vp, uio->uio_offset + n);
664                         filesize = uio->uio_offset + n;
665                         fvdat->flag |= FN_SIZECHANGE;
666                         if (err) {
667                                 brelse(bp);
668                                 break;
669                         } 
670                 }
671
672                 SDT_PROBE6(fusefs, , io, write_biobackend_start,
673                         lbn, on, n, uio, bcount, direct_append);
674                 /*
675                  * Issue a READ if B_CACHE is not set.  In special-append
676                  * mode, B_CACHE is based on the buffer prior to the write
677                  * op and is typically set, avoiding the read.  If a read
678                  * is required in special append mode, the server will
679                  * probably send us a short-read since we extended the file
680                  * on our end, resulting in b_resid == 0 and, thusly,
681                  * B_CACHE getting set.
682                  *
683                  * We can also avoid issuing the read if the write covers
684                  * the entire buffer.  We have to make sure the buffer state
685                  * is reasonable in this case since we will not be initiating
686                  * I/O.  See the comments in kern/vfs_bio.c's getblk() for
687                  * more information.
688                  *
689                  * B_CACHE may also be set due to the buffer being cached
690                  * normally.
691                  */
692
693                 if (on == 0 && n == bcount) {
694                         bp->b_flags |= B_CACHE;
695                         bp->b_flags &= ~B_INVAL;
696                         bp->b_ioflags &= ~BIO_ERROR;
697                 }
698                 if ((bp->b_flags & B_CACHE) == 0) {
699                         bp->b_iocmd = BIO_READ;
700                         vfs_busy_pages(bp, 0);
701                         fuse_io_strategy(vp, bp);
702                         if ((err = bp->b_error)) {
703                                 brelse(bp);
704                                 break;
705                         }
706                 }
707                 if (bp->b_wcred == NOCRED)
708                         bp->b_wcred = crhold(cred);
709
710                 /*
711                  * If dirtyend exceeds file size, chop it down.  This should
712                  * not normally occur but there is an append race where it
713                  * might occur XXX, so we log it.
714                  *
715                  * If the chopping creates a reverse-indexed or degenerate
716                  * situation with dirtyoff/end, we 0 both of them.
717                  */
718                 if (bp->b_dirtyend > bcount) {
719                         SDT_PROBE2(fusefs, , io, write_biobackend_append_race,
720                             (long)bp->b_blkno * biosize,
721                             bp->b_dirtyend - bcount);
722                         bp->b_dirtyend = bcount;
723                 }
724                 if (bp->b_dirtyoff >= bp->b_dirtyend)
725                         bp->b_dirtyoff = bp->b_dirtyend = 0;
726
727                 /*
728                  * If the new write will leave a contiguous dirty
729                  * area, just update the b_dirtyoff and b_dirtyend,
730                  * otherwise force a write rpc of the old dirty area.
731                  *
732                  * While it is possible to merge discontiguous writes due to
733                  * our having a B_CACHE buffer ( and thus valid read data
734                  * for the hole), we don't because it could lead to
735                  * significant cache coherency problems with multiple clients,
736                  * especially if locking is implemented later on.
737                  *
738                  * as an optimization we could theoretically maintain
739                  * a linked list of discontinuous areas, but we would still
740                  * have to commit them separately so there isn't much
741                  * advantage to it except perhaps a bit of asynchronization.
742                  */
743
744                 if (bp->b_dirtyend > 0 &&
745                     (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
746                         /*
747                          * Yes, we mean it. Write out everything to "storage"
748                          * immediately, without hesitation. (Apart from other
749                          * reasons: the only way to know if a write is valid
750                          * if its actually written out.)
751                          */
752                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 0, bp);
753                         bwrite(bp);
754                         if (bp->b_error == EINTR) {
755                                 err = EINTR;
756                                 break;
757                         }
758                         goto again;
759                 }
760                 err = uiomove((char *)bp->b_data + on, n, uio);
761
762                 if (err) {
763                         bp->b_ioflags |= BIO_ERROR;
764                         bp->b_error = err;
765                         brelse(bp);
766                         break;
767                         /* TODO: vfs_bio_clrbuf like ffs_write does? */
768                 }
769                 /*
770                  * Only update dirtyoff/dirtyend if not a degenerate
771                  * condition.
772                  */
773                 if (n) {
774                         if (bp->b_dirtyend > 0) {
775                                 bp->b_dirtyoff = MIN(on, bp->b_dirtyoff);
776                                 bp->b_dirtyend = MAX((on + n), bp->b_dirtyend);
777                         } else {
778                                 bp->b_dirtyoff = on;
779                                 bp->b_dirtyend = on + n;
780                         }
781                         vfs_bio_set_valid(bp, on, n);
782                 }
783
784                 vfs_bio_set_flags(bp, ioflag);
785
786                 if (last_page) {
787                         /* 
788                          * When writing the last page of a file we must write
789                          * synchronously.  If we didn't, then a subsequent
790                          * operation could extend the file, making the last
791                          * page of this buffer invalid because it would only be
792                          * partially cached.
793                          *
794                          * As an optimization, it would be allowable to only
795                          * write the last page synchronously.  Or, it should be
796                          * possible to synchronously flush the last
797                          * already-written page whenever extending a file with
798                          * ftruncate or another write.
799                          */
800                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 1, bp);
801                         err = bwrite(bp);
802                 } else if (ioflag & IO_SYNC) {
803                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 2, bp);
804                         err = bwrite(bp);
805                 } else if (vm_page_count_severe() ||
806                             buf_dirty_count_severe() ||
807                             (ioflag & IO_ASYNC)) {
808                         bp->b_flags |= B_CLUSTEROK;
809                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 3, bp);
810                         bawrite(bp);
811                 } else if (on == 0 && n == bcount) {
812                         if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0) {
813                                 bp->b_flags |= B_CLUSTEROK;
814                                 SDT_PROBE2(fusefs, , io, write_biobackend_issue,
815                                         4, bp);
816                                 cluster_write(vp, bp, filesize, seqcount, 0);
817                         } else {
818                                 SDT_PROBE2(fusefs, , io, write_biobackend_issue,
819                                         5, bp);
820                                 bawrite(bp);
821                         }
822                 } else if (ioflag & IO_DIRECT) {
823                         bp->b_flags |= B_CLUSTEROK;
824                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 6, bp);
825                         bawrite(bp);
826                 } else {
827                         bp->b_flags &= ~B_CLUSTEROK;
828                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 7, bp);
829                         bdwrite(bp);
830                 }
831                 if (err)
832                         break;
833         } while (uio->uio_resid > 0 && n > 0);
834
835         return (err);
836 }
837
838 int
839 fuse_io_strategy(struct vnode *vp, struct buf *bp)
840 {
841         struct fuse_filehandle *fufh;
842         struct ucred *cred;
843         struct uio *uiop;
844         struct uio uio;
845         struct iovec io;
846         off_t filesize;
847         int error = 0;
848         int fflag;
849         /* We don't know the true pid when we're dealing with the cache */
850         pid_t pid = 0;
851
852         const int biosize = fuse_iosize(vp);
853
854         MPASS(vp->v_type == VREG || vp->v_type == VDIR);
855         MPASS(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE);
856
857         fflag = bp->b_iocmd == BIO_READ ? FREAD : FWRITE;
858         cred = bp->b_iocmd == BIO_READ ? bp->b_rcred : bp->b_wcred;
859         error = fuse_filehandle_getrw(vp, fflag, &fufh, cred, pid);
860         if (bp->b_iocmd == BIO_READ && error == EBADF) {
861                 /* 
862                  * This may be a read-modify-write operation on a cached file
863                  * opened O_WRONLY.  The FUSE protocol allows this.
864                  */
865                 error = fuse_filehandle_get(vp, FWRITE, &fufh, cred, pid);
866         }
867         if (error) {
868                 printf("FUSE: strategy: filehandles are closed\n");
869                 bp->b_ioflags |= BIO_ERROR;
870                 bp->b_error = error;
871                 bufdone(bp);
872                 return (error);
873         }
874
875         uiop = &uio;
876         uiop->uio_iov = &io;
877         uiop->uio_iovcnt = 1;
878         uiop->uio_segflg = UIO_SYSSPACE;
879         uiop->uio_td = curthread;
880
881         /*
882          * clear BIO_ERROR and B_INVAL state prior to initiating the I/O.  We
883          * do this here so we do not have to do it in all the code that
884          * calls us.
885          */
886         bp->b_flags &= ~B_INVAL;
887         bp->b_ioflags &= ~BIO_ERROR;
888
889         KASSERT(!(bp->b_flags & B_DONE),
890             ("fuse_io_strategy: bp %p already marked done", bp));
891         if (bp->b_iocmd == BIO_READ) {
892                 io.iov_len = uiop->uio_resid = bp->b_bcount;
893                 io.iov_base = bp->b_data;
894                 uiop->uio_rw = UIO_READ;
895
896                 uiop->uio_offset = ((off_t)bp->b_lblkno) * biosize;
897                 error = fuse_read_directbackend(vp, uiop, cred, fufh);
898
899                 if (!error && uiop->uio_resid) {
900                         /*
901                          * If we had a short read with no error, we must have
902                          * hit a file hole.  We should zero-fill the remainder.
903                          * This can also occur if the server hits the file EOF.
904                          *
905                          * Holes used to be able to occur due to pending
906                          * writes, but that is not possible any longer.
907                          */
908                         int nread = bp->b_bcount - uiop->uio_resid;
909                         int left = uiop->uio_resid;
910
911                         if (left > 0)
912                                 bzero((char *)bp->b_data + nread, left);
913                         uiop->uio_resid = 0;
914                 }
915                 if (error) {
916                         bp->b_ioflags |= BIO_ERROR;
917                         bp->b_error = error;
918                 }
919         } else {
920                 /*
921                  * Setup for actual write
922                  */
923                 error = fuse_vnode_size(vp, &filesize, cred, curthread);
924                 if (error) {
925                         bp->b_ioflags |= BIO_ERROR;
926                         bp->b_error = error;
927                         bufdone(bp);
928                         return (error);
929                 }
930
931                 if ((off_t)bp->b_lblkno * biosize + bp->b_dirtyend > filesize)
932                         bp->b_dirtyend = filesize - 
933                                 (off_t)bp->b_lblkno * biosize;
934
935                 if (bp->b_dirtyend > bp->b_dirtyoff) {
936                         io.iov_len = uiop->uio_resid = bp->b_dirtyend
937                             - bp->b_dirtyoff;
938                         uiop->uio_offset = (off_t)bp->b_lblkno * biosize
939                             + bp->b_dirtyoff;
940                         io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
941                         uiop->uio_rw = UIO_WRITE;
942
943                         error = fuse_write_directbackend(vp, uiop, cred, fufh,
944                                 filesize, 0, false);
945
946                         if (error == EINTR || error == ETIMEDOUT) {
947                                 bp->b_flags &= ~(B_INVAL | B_NOCACHE);
948                                 if ((bp->b_flags & B_PAGING) == 0) {
949                                         bdirty(bp);
950                                         bp->b_flags &= ~B_DONE;
951                                 }
952                                 if ((error == EINTR || error == ETIMEDOUT) &&
953                                     (bp->b_flags & B_ASYNC) == 0)
954                                         bp->b_flags |= B_EINTR;
955                         } else {
956                                 if (error) {
957                                         bp->b_ioflags |= BIO_ERROR;
958                                         bp->b_flags |= B_INVAL;
959                                         bp->b_error = error;
960                                 }
961                                 bp->b_dirtyoff = bp->b_dirtyend = 0;
962                         }
963                 } else {
964                         bp->b_resid = 0;
965                         bufdone(bp);
966                         return (0);
967                 }
968         }
969         bp->b_resid = uiop->uio_resid;
970         bufdone(bp);
971         return (error);
972 }
973
974 int
975 fuse_io_flushbuf(struct vnode *vp, int waitfor, struct thread *td)
976 {
977
978         return (vn_fsync_buf(vp, waitfor));
979 }
980
981 /*
982  * Flush and invalidate all dirty buffers. If another process is already
983  * doing the flush, just wait for completion.
984  */
985 int
986 fuse_io_invalbuf(struct vnode *vp, struct thread *td)
987 {
988         struct fuse_vnode_data *fvdat = VTOFUD(vp);
989         int error = 0;
990
991         if (vp->v_iflag & VI_DOOMED)
992                 return 0;
993
994         ASSERT_VOP_ELOCKED(vp, "fuse_io_invalbuf");
995
996         while (fvdat->flag & FN_FLUSHINPROG) {
997                 struct proc *p = td->td_proc;
998
999                 if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF)
1000                         return EIO;
1001                 fvdat->flag |= FN_FLUSHWANT;
1002                 tsleep(&fvdat->flag, PRIBIO + 2, "fusevinv", 2 * hz);
1003                 error = 0;
1004                 if (p != NULL) {
1005                         PROC_LOCK(p);
1006                         if (SIGNOTEMPTY(p->p_siglist) ||
1007                             SIGNOTEMPTY(td->td_siglist))
1008                                 error = EINTR;
1009                         PROC_UNLOCK(p);
1010                 }
1011                 if (error == EINTR)
1012                         return EINTR;
1013         }
1014         fvdat->flag |= FN_FLUSHINPROG;
1015
1016         if (vp->v_bufobj.bo_object != NULL) {
1017                 VM_OBJECT_WLOCK(vp->v_bufobj.bo_object);
1018                 vm_object_page_clean(vp->v_bufobj.bo_object, 0, 0, OBJPC_SYNC);
1019                 VM_OBJECT_WUNLOCK(vp->v_bufobj.bo_object);
1020         }
1021         error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
1022         while (error) {
1023                 if (error == ERESTART || error == EINTR) {
1024                         fvdat->flag &= ~FN_FLUSHINPROG;
1025                         if (fvdat->flag & FN_FLUSHWANT) {
1026                                 fvdat->flag &= ~FN_FLUSHWANT;
1027                                 wakeup(&fvdat->flag);
1028                         }
1029                         return EINTR;
1030                 }
1031                 error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
1032         }
1033         fvdat->flag &= ~FN_FLUSHINPROG;
1034         if (fvdat->flag & FN_FLUSHWANT) {
1035                 fvdat->flag &= ~FN_FLUSHWANT;
1036                 wakeup(&fvdat->flag);
1037         }
1038         return (error);
1039 }