]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/fuse/fuse_io.c
fusefs: fix a bug with WriteBack cacheing
[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                 /*
223                  * Kludge: simulate write-through caching via write-around
224                  * caching.  Same effect, as far as never caching dirty data,
225                  * but slightly pessimal in that newly written data is not
226                  * cached.
227                  */
228                 if (directio || fuse_data_cache_mode == FUSE_CACHE_WT) {
229                         const int iosize = fuse_iosize(vp);
230                         off_t start, end, filesize;
231
232                         SDT_PROBE2(fusefs, , io, trace, 1,
233                                 "direct write of vnode");
234
235                         err = fuse_vnode_size(vp, &filesize, cred, curthread);
236                         if (err)
237                                 goto out;
238
239                         start = uio->uio_offset;
240                         end = start + uio->uio_resid;
241                         /* 
242                          * Invalidate the write cache unless we're coming from
243                          * VOP_PUTPAGES, in which case we're writing _from_ the
244                          * write cache
245                          */
246                         if (!pages )
247                                 v_inval_buf_range(vp, start, end, iosize);
248                         err = fuse_write_directbackend(vp, uio, cred, fufh,
249                                 filesize, ioflag, pages);
250                 } else {
251                         SDT_PROBE2(fusefs, , io, trace, 1,
252                                 "buffered write of vnode");
253                         err = fuse_write_biobackend(vp, uio, cred, fufh, ioflag,
254                                 pid);
255                 }
256                 fuse_io_clear_suid_on_write(vp, cred, uio->uio_td);
257                 break;
258         default:
259                 panic("uninterpreted mode passed to fuse_io_dispatch");
260         }
261
262 out:
263         if (closefufh)
264                 fuse_filehandle_close(vp, fufh, curthread, cred);
265
266         return (err);
267 }
268
269 SDT_PROBE_DEFINE4(fusefs, , io, read_bio_backend_start, "int", "int", "int", "int");
270 SDT_PROBE_DEFINE2(fusefs, , io, read_bio_backend_feed, "int", "struct buf*");
271 SDT_PROBE_DEFINE4(fusefs, , io, read_bio_backend_end, "int", "ssize_t", "int",
272                 "struct buf*");
273 static int
274 fuse_read_biobackend(struct vnode *vp, struct uio *uio, int ioflag,
275     struct ucred *cred, struct fuse_filehandle *fufh, pid_t pid)
276 {
277         struct buf *bp;
278         daddr_t lbn;
279         int bcount;
280         int err, n = 0, on = 0;
281         off_t filesize;
282
283         const int biosize = fuse_iosize(vp);
284
285         if (uio->uio_offset < 0)
286                 return (EINVAL);
287
288         err = fuse_vnode_size(vp, &filesize, cred, curthread);
289         if (err)
290                 return err;
291
292         for (err = 0, bp = NULL; uio->uio_resid > 0; bp = NULL) {
293                 if (fuse_isdeadfs(vp)) {
294                         err = ENXIO;
295                         break;
296                 }
297                 if (filesize - uio->uio_offset <= 0)
298                         break;
299                 lbn = uio->uio_offset / biosize;
300                 on = uio->uio_offset & (biosize - 1);
301
302                 if ((off_t)lbn * biosize >= filesize) {
303                         bcount = 0;
304                 } else if ((off_t)(lbn + 1) * biosize > filesize) {
305                         bcount = filesize - (off_t)lbn *biosize;
306                 } else {
307                         bcount = biosize;
308                 }
309
310                 SDT_PROBE4(fusefs, , io, read_bio_backend_start,
311                         biosize, (int)lbn, on, bcount);
312
313                 /* TODO: readahead.  See ext2_read for an example */
314                 err = bread(vp, lbn, bcount, NOCRED, &bp);
315                 if (err) {
316                         brelse(bp);
317                         bp = NULL;
318                         break;
319                 }
320
321                 /*
322                  * on is the offset into the current bp.  Figure out how many
323                  * bytes we can copy out of the bp.  Note that bcount is
324                  * NOT DEV_BSIZE aligned.
325                  *
326                  * Then figure out how many bytes we can copy into the uio.
327                  */
328
329                 n = 0;
330                 if (on < bcount)
331                         n = MIN((unsigned)(bcount - on), uio->uio_resid);
332                 if (n > 0) {
333                         SDT_PROBE2(fusefs, , io, read_bio_backend_feed, n, bp);
334                         err = uiomove(bp->b_data + on, n, uio);
335                 }
336                 vfs_bio_brelse(bp, ioflag);
337                 SDT_PROBE4(fusefs, , io, read_bio_backend_end, err,
338                         uio->uio_resid, n, bp);
339         }
340
341         return (err);
342 }
343
344 SDT_PROBE_DEFINE1(fusefs, , io, read_directbackend_start,
345         "struct fuse_read_in*");
346 SDT_PROBE_DEFINE3(fusefs, , io, read_directbackend_complete,
347         "struct fuse_dispatcher*", "struct fuse_read_in*", "struct uio*");
348
349 static int
350 fuse_read_directbackend(struct vnode *vp, struct uio *uio,
351     struct ucred *cred, struct fuse_filehandle *fufh)
352 {
353         struct fuse_data *data;
354         struct fuse_dispatcher fdi;
355         struct fuse_read_in *fri;
356         int err = 0;
357
358         data = fuse_get_mpdata(vp->v_mount);
359
360         if (uio->uio_resid == 0)
361                 return (0);
362
363         fdisp_init(&fdi, 0);
364
365         /*
366          * XXX In "normal" case we use an intermediate kernel buffer for
367          * transmitting data from daemon's context to ours. Eventually, we should
368          * get rid of this. Anyway, if the target uio lives in sysspace (we are
369          * called from pageops), and the input data doesn't need kernel-side
370          * processing (we are not called from readdir) we can already invoke
371          * an optimized, "peer-to-peer" I/O routine.
372          */
373         while (uio->uio_resid > 0) {
374                 fdi.iosize = sizeof(*fri);
375                 fdisp_make_vp(&fdi, FUSE_READ, vp, uio->uio_td, cred);
376                 fri = fdi.indata;
377                 fri->fh = fufh->fh_id;
378                 fri->offset = uio->uio_offset;
379                 fri->size = MIN(uio->uio_resid,
380                     fuse_get_mpdata(vp->v_mount)->max_read);
381                 if (fuse_libabi_geq(data, 7, 9)) {
382                         /* See comment regarding FUSE_WRITE_LOCKOWNER */
383                         fri->read_flags = 0;
384                         fri->flags = fufh_type_2_fflags(fufh->fufh_type);
385                 }
386
387                 SDT_PROBE1(fusefs, , io, read_directbackend_start, fri);
388
389                 if ((err = fdisp_wait_answ(&fdi)))
390                         goto out;
391
392                 SDT_PROBE3(fusefs, , io, read_directbackend_complete,
393                         &fdi, fri, uio);
394
395                 if ((err = uiomove(fdi.answ, MIN(fri->size, fdi.iosize), uio)))
396                         break;
397                 if (fdi.iosize < fri->size)
398                         break;
399         }
400
401 out:
402         fdisp_destroy(&fdi);
403         return (err);
404 }
405
406 static int
407 fuse_write_directbackend(struct vnode *vp, struct uio *uio,
408     struct ucred *cred, struct fuse_filehandle *fufh, off_t filesize,
409     int ioflag, bool pages)
410 {
411         struct fuse_vnode_data *fvdat = VTOFUD(vp);
412         struct fuse_data *data;
413         struct fuse_write_in *fwi;
414         struct fuse_write_out *fwo;
415         struct fuse_dispatcher fdi;
416         size_t chunksize;
417         void *fwi_data;
418         off_t as_written_offset;
419         int diff;
420         int err = 0;
421         bool direct_io = fufh->fuse_open_flags & FOPEN_DIRECT_IO;
422         uint32_t write_flags;
423
424         data = fuse_get_mpdata(vp->v_mount);
425
426         /* 
427          * Don't set FUSE_WRITE_LOCKOWNER in write_flags.  It can't be set
428          * accurately when using POSIX AIO, libfuse doesn't use it, and I'm not
429          * aware of any file systems that do.  It was an attempt to add
430          * Linux-style mandatory locking to the FUSE protocol, but mandatory
431          * locking is deprecated even on Linux.  See Linux commit
432          * f33321141b273d60cbb3a8f56a5489baad82ba5e .
433          */
434         /*
435          * Set FUSE_WRITE_CACHE whenever we don't know the uid, gid, and/or pid
436          * that originated a write.  For example when writing from the
437          * writeback cache.  I don't know of a single file system that cares,
438          * but the protocol says we're supposed to do this.
439          */
440         write_flags = !pages && (
441                 (ioflag & IO_DIRECT) ||
442                 !fsess_opt_datacache(vnode_mount(vp)) ||
443                 fuse_data_cache_mode != FUSE_CACHE_WB) ? 0 : FUSE_WRITE_CACHE;
444
445         if (uio->uio_resid == 0)
446                 return (0);
447
448         if (ioflag & IO_APPEND)
449                 uio_setoffset(uio, filesize);
450
451         if (vn_rlimit_fsize(vp, uio, uio->uio_td))
452                 return (EFBIG);
453
454         fdisp_init(&fdi, 0);
455
456         while (uio->uio_resid > 0) {
457                 chunksize = MIN(uio->uio_resid, data->max_write);
458
459                 fdi.iosize = sizeof(*fwi) + chunksize;
460                 fdisp_make_vp(&fdi, FUSE_WRITE, vp, uio->uio_td, cred);
461
462                 fwi = fdi.indata;
463                 fwi->fh = fufh->fh_id;
464                 fwi->offset = uio->uio_offset;
465                 fwi->size = chunksize;
466                 fwi->write_flags = write_flags;
467                 if (fuse_libabi_geq(data, 7, 9)) {
468                         fwi->flags = fufh_type_2_fflags(fufh->fufh_type);
469                         fwi_data = (char *)fdi.indata + sizeof(*fwi);
470                 } else {
471                         fwi_data = (char *)fdi.indata +
472                                 FUSE_COMPAT_WRITE_IN_SIZE;
473                 }
474
475                 if ((err = uiomove(fwi_data, chunksize, uio)))
476                         break;
477
478 retry:
479                 err = fdisp_wait_answ(&fdi);
480                 if (err == ERESTART || err == EINTR || err == EWOULDBLOCK) {
481                         /*
482                          * Rewind the uio so dofilewrite will know it's
483                          * incomplete
484                          */
485                         uio->uio_resid += fwi->size;
486                         uio->uio_offset -= fwi->size;
487                         /* 
488                          * Change ERESTART into EINTR because we can't rewind
489                          * uio->uio_iov.  Basically, once uiomove(9) has been
490                          * called, it's impossible to restart a syscall.
491                          */
492                         if (err == ERESTART)
493                                 err = EINTR;
494                         break;
495                 } else if (err) {
496                         break;
497                 }
498
499                 fwo = ((struct fuse_write_out *)fdi.answ);
500
501                 /* Adjust the uio in the case of short writes */
502                 diff = fwi->size - fwo->size;
503                 as_written_offset = uio->uio_offset - diff;
504
505                 if (as_written_offset - diff > filesize &&
506                     fuse_data_cache_mode != FUSE_CACHE_UC)
507                         fuse_vnode_setsize(vp, as_written_offset);
508                 if (as_written_offset - diff >= filesize)
509                         fvdat->flag &= ~FN_SIZECHANGE;
510
511                 if (diff < 0) {
512                         printf("WARNING: misbehaving FUSE filesystem "
513                                 "wrote more data than we provided it\n");
514                         err = EINVAL;
515                         break;
516                 } else if (diff > 0) {
517                         /* Short write */
518                         if (!direct_io) {
519                                 printf("WARNING: misbehaving FUSE filesystem: "
520                                         "short writes are only allowed with "
521                                         "direct_io\n");
522                         }
523                         if (ioflag & IO_DIRECT) {
524                                 /* Return early */
525                                 uio->uio_resid += diff;
526                                 uio->uio_offset -= diff;
527                                 break;
528                         } else {
529                                 /* Resend the unwritten portion of data */
530                                 fdi.iosize = sizeof(*fwi) + diff;
531                                 /* Refresh fdi without clearing data buffer */
532                                 fdisp_refresh_vp(&fdi, FUSE_WRITE, vp,
533                                         uio->uio_td, cred);
534                                 fwi = fdi.indata;
535                                 MPASS2(fwi == fdi.indata, "FUSE dispatcher "
536                                         "reallocated despite no increase in "
537                                         "size?");
538                                 void *src = (char*)fwi_data + fwo->size;
539                                 memmove(fwi_data, src, diff);
540                                 fwi->fh = fufh->fh_id;
541                                 fwi->offset = as_written_offset;
542                                 fwi->size = diff;
543                                 fwi->write_flags = write_flags;
544                                 goto retry;
545                         }
546                 }
547         }
548
549         fdisp_destroy(&fdi);
550
551         return (err);
552 }
553
554 SDT_PROBE_DEFINE6(fusefs, , io, write_biobackend_start, "int64_t", "int", "int",
555                 "struct uio*", "int", "bool");
556 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_append_race, "long", "int");
557 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_issue, "int", "struct buf*");
558
559 static int
560 fuse_write_biobackend(struct vnode *vp, struct uio *uio,
561     struct ucred *cred, struct fuse_filehandle *fufh, int ioflag, pid_t pid)
562 {
563         struct fuse_vnode_data *fvdat = VTOFUD(vp);
564         struct buf *bp;
565         daddr_t lbn;
566         off_t filesize;
567         int bcount;
568         int n, on, err = 0;
569         bool last_page;
570
571         const int biosize = fuse_iosize(vp);
572
573         KASSERT(uio->uio_rw == UIO_WRITE, ("fuse_write_biobackend mode"));
574         if (vp->v_type != VREG)
575                 return (EIO);
576         if (uio->uio_offset < 0)
577                 return (EINVAL);
578         if (uio->uio_resid == 0)
579                 return (0);
580
581         err = fuse_vnode_size(vp, &filesize, cred, curthread);
582         if (err)
583                 return err;
584
585         if (ioflag & IO_APPEND)
586                 uio_setoffset(uio, filesize);
587
588         if (vn_rlimit_fsize(vp, uio, uio->uio_td))
589                 return (EFBIG);
590
591         do {
592                 bool direct_append, extending;
593
594                 if (fuse_isdeadfs(vp)) {
595                         err = ENXIO;
596                         break;
597                 }
598                 lbn = uio->uio_offset / biosize;
599                 on = uio->uio_offset & (biosize - 1);
600                 n = MIN((unsigned)(biosize - on), uio->uio_resid);
601
602 again:
603                 /* Get or create a buffer for the write */
604                 direct_append = uio->uio_offset == filesize && n;
605                 if (uio->uio_offset + n < filesize) {
606                         extending = false;
607                         if ((off_t)(lbn + 1) * biosize < filesize) {
608                                 /* Not the file's last block */
609                                 bcount = biosize;
610                         } else {
611                                 /* The file's last block */
612                                 bcount = filesize - (off_t)lbn * biosize;
613                         }
614                 } else {
615                         extending = true;
616                         bcount = on + n;
617                 }
618                 if (howmany(((off_t)lbn * biosize + on + n - 1), PAGE_SIZE) >=
619                     howmany(filesize, PAGE_SIZE))
620                         last_page = true;
621                 else
622                         last_page = false;
623                 if (direct_append) {
624                         /* 
625                          * Take care to preserve the buffer's B_CACHE state so
626                          * as not to cause an unnecessary read.
627                          */
628                         bp = getblk(vp, lbn, on, PCATCH, 0, 0);
629                         if (bp != NULL) {
630                                 uint32_t save = bp->b_flags & B_CACHE;
631                                 allocbuf(bp, bcount);
632                                 bp->b_flags |= save;
633                         }
634                 } else {
635                         bp = getblk(vp, lbn, bcount, PCATCH, 0, 0);
636                 }
637                 if (!bp) {
638                         err = EINTR;
639                         break;
640                 }
641                 if (extending) {
642                         /* 
643                          * Extend file _after_ locking buffer so we won't race
644                          * with other readers
645                          */
646                         err = fuse_vnode_setsize(vp, uio->uio_offset + n);
647                         fvdat->flag |= FN_SIZECHANGE;
648                         if (err) {
649                                 brelse(bp);
650                                 break;
651                         } 
652                 }
653
654                 SDT_PROBE6(fusefs, , io, write_biobackend_start,
655                         lbn, on, n, uio, bcount, direct_append);
656                 /*
657                  * Issue a READ if B_CACHE is not set.  In special-append
658                  * mode, B_CACHE is based on the buffer prior to the write
659                  * op and is typically set, avoiding the read.  If a read
660                  * is required in special append mode, the server will
661                  * probably send us a short-read since we extended the file
662                  * on our end, resulting in b_resid == 0 and, thusly,
663                  * B_CACHE getting set.
664                  *
665                  * We can also avoid issuing the read if the write covers
666                  * the entire buffer.  We have to make sure the buffer state
667                  * is reasonable in this case since we will not be initiating
668                  * I/O.  See the comments in kern/vfs_bio.c's getblk() for
669                  * more information.
670                  *
671                  * B_CACHE may also be set due to the buffer being cached
672                  * normally.
673                  */
674
675                 if (on == 0 && n == bcount) {
676                         bp->b_flags |= B_CACHE;
677                         bp->b_flags &= ~B_INVAL;
678                         bp->b_ioflags &= ~BIO_ERROR;
679                 }
680                 if ((bp->b_flags & B_CACHE) == 0) {
681                         bp->b_iocmd = BIO_READ;
682                         vfs_busy_pages(bp, 0);
683                         fuse_io_strategy(vp, bp);
684                         if ((err = bp->b_error)) {
685                                 brelse(bp);
686                                 break;
687                         }
688                 }
689                 if (bp->b_wcred == NOCRED)
690                         bp->b_wcred = crhold(cred);
691
692                 /*
693                  * If dirtyend exceeds file size, chop it down.  This should
694                  * not normally occur but there is an append race where it
695                  * might occur XXX, so we log it.
696                  *
697                  * If the chopping creates a reverse-indexed or degenerate
698                  * situation with dirtyoff/end, we 0 both of them.
699                  */
700                 if (bp->b_dirtyend > bcount) {
701                         SDT_PROBE2(fusefs, , io, write_biobackend_append_race,
702                             (long)bp->b_blkno * biosize,
703                             bp->b_dirtyend - bcount);
704                         bp->b_dirtyend = bcount;
705                 }
706                 if (bp->b_dirtyoff >= bp->b_dirtyend)
707                         bp->b_dirtyoff = bp->b_dirtyend = 0;
708
709                 /*
710                  * If the new write will leave a contiguous dirty
711                  * area, just update the b_dirtyoff and b_dirtyend,
712                  * otherwise force a write rpc of the old dirty area.
713                  *
714                  * While it is possible to merge discontiguous writes due to
715                  * our having a B_CACHE buffer ( and thus valid read data
716                  * for the hole), we don't because it could lead to
717                  * significant cache coherency problems with multiple clients,
718                  * especially if locking is implemented later on.
719                  *
720                  * as an optimization we could theoretically maintain
721                  * a linked list of discontinuous areas, but we would still
722                  * have to commit them separately so there isn't much
723                  * advantage to it except perhaps a bit of asynchronization.
724                  */
725
726                 if (bp->b_dirtyend > 0 &&
727                     (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
728                         /*
729                          * Yes, we mean it. Write out everything to "storage"
730                          * immediately, without hesitation. (Apart from other
731                          * reasons: the only way to know if a write is valid
732                          * if its actually written out.)
733                          */
734                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 0, bp);
735                         bwrite(bp);
736                         if (bp->b_error == EINTR) {
737                                 err = EINTR;
738                                 break;
739                         }
740                         goto again;
741                 }
742                 err = uiomove((char *)bp->b_data + on, n, uio);
743
744                 if (err) {
745                         bp->b_ioflags |= BIO_ERROR;
746                         bp->b_error = err;
747                         brelse(bp);
748                         break;
749                         /* TODO: vfs_bio_clrbuf like ffs_write does? */
750                 }
751                 /*
752                  * Only update dirtyoff/dirtyend if not a degenerate
753                  * condition.
754                  */
755                 if (n) {
756                         if (bp->b_dirtyend > 0) {
757                                 bp->b_dirtyoff = MIN(on, bp->b_dirtyoff);
758                                 bp->b_dirtyend = MAX((on + n), bp->b_dirtyend);
759                         } else {
760                                 bp->b_dirtyoff = on;
761                                 bp->b_dirtyend = on + n;
762                         }
763                         vfs_bio_set_valid(bp, on, n);
764                 }
765
766                 vfs_bio_set_flags(bp, ioflag);
767
768                 if (last_page) {
769                         /* 
770                          * When writing the last page of a file we must write
771                          * synchronously.  If we didn't, then a subsequent
772                          * operation could extend the file, making the last
773                          * page of this buffer invalid because it would only be
774                          * partially cached.
775                          *
776                          * As an optimization, it would be allowable to only
777                          * write the last page synchronously.  Or, it should be
778                          * possible to synchronously flush the last
779                          * already-written page whenever extending a file with
780                          * ftruncate or another write.
781                          */
782                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 1, bp);
783                         err = bwrite(bp);
784                 } else if (ioflag & IO_SYNC) {
785                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 2, bp);
786                         err = bwrite(bp);
787                 } else if (vm_page_count_severe() ||
788                             buf_dirty_count_severe() ||
789                             (ioflag & IO_ASYNC)) {
790                         /* TODO: enable write clustering later */
791                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 3, bp);
792                         bawrite(bp);
793                 } else if (on == 0 && n == bcount) {
794                         if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0) {
795                                 SDT_PROBE2(fusefs, , io, write_biobackend_issue,
796                                         4, bp);
797                                 bdwrite(bp);
798                         } else {
799                                 SDT_PROBE2(fusefs, , io, write_biobackend_issue,
800                                         5, bp);
801                                 bawrite(bp);
802                         }
803                 } else if (ioflag & IO_DIRECT) {
804                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 6, bp);
805                         bawrite(bp);
806                 } else {
807                         bp->b_flags &= ~B_CLUSTEROK;
808                         SDT_PROBE2(fusefs, , io, write_biobackend_issue, 7, bp);
809                         bdwrite(bp);
810                 }
811                 if (err)
812                         break;
813         } while (uio->uio_resid > 0 && n > 0);
814
815         return (err);
816 }
817
818 int
819 fuse_io_strategy(struct vnode *vp, struct buf *bp)
820 {
821         struct fuse_filehandle *fufh;
822         struct ucred *cred;
823         struct uio *uiop;
824         struct uio uio;
825         struct iovec io;
826         off_t filesize;
827         int error = 0;
828         int fflag;
829         /* We don't know the true pid when we're dealing with the cache */
830         pid_t pid = 0;
831
832         const int biosize = fuse_iosize(vp);
833
834         MPASS(vp->v_type == VREG || vp->v_type == VDIR);
835         MPASS(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE);
836
837         fflag = bp->b_iocmd == BIO_READ ? FREAD : FWRITE;
838         cred = bp->b_iocmd == BIO_READ ? bp->b_rcred : bp->b_wcred;
839         error = fuse_filehandle_getrw(vp, fflag, &fufh, cred, pid);
840         if (bp->b_iocmd == BIO_READ && error == EBADF) {
841                 /* 
842                  * This may be a read-modify-write operation on a cached file
843                  * opened O_WRONLY.  The FUSE protocol allows this.
844                  */
845                 error = fuse_filehandle_get(vp, FWRITE, &fufh, cred, pid);
846         }
847         if (error) {
848                 printf("FUSE: strategy: filehandles are closed\n");
849                 bp->b_ioflags |= BIO_ERROR;
850                 bp->b_error = error;
851                 bufdone(bp);
852                 return (error);
853         }
854
855         uiop = &uio;
856         uiop->uio_iov = &io;
857         uiop->uio_iovcnt = 1;
858         uiop->uio_segflg = UIO_SYSSPACE;
859         uiop->uio_td = curthread;
860
861         /*
862          * clear BIO_ERROR and B_INVAL state prior to initiating the I/O.  We
863          * do this here so we do not have to do it in all the code that
864          * calls us.
865          */
866         bp->b_flags &= ~B_INVAL;
867         bp->b_ioflags &= ~BIO_ERROR;
868
869         KASSERT(!(bp->b_flags & B_DONE),
870             ("fuse_io_strategy: bp %p already marked done", bp));
871         if (bp->b_iocmd == BIO_READ) {
872                 io.iov_len = uiop->uio_resid = bp->b_bcount;
873                 io.iov_base = bp->b_data;
874                 uiop->uio_rw = UIO_READ;
875
876                 uiop->uio_offset = ((off_t)bp->b_lblkno) * biosize;
877                 error = fuse_read_directbackend(vp, uiop, cred, fufh);
878
879                 if (!error && uiop->uio_resid) {
880                         /*
881                          * If we had a short read with no error, we must have
882                          * hit a file hole.  We should zero-fill the remainder.
883                          * This can also occur if the server hits the file EOF.
884                          *
885                          * Holes used to be able to occur due to pending
886                          * writes, but that is not possible any longer.
887                          */
888                         int nread = bp->b_bcount - uiop->uio_resid;
889                         int left = uiop->uio_resid;
890
891                         if (left > 0)
892                                 bzero((char *)bp->b_data + nread, left);
893                         uiop->uio_resid = 0;
894                 }
895                 if (error) {
896                         bp->b_ioflags |= BIO_ERROR;
897                         bp->b_error = error;
898                 }
899         } else {
900                 /*
901                  * Setup for actual write
902                  */
903                 error = fuse_vnode_size(vp, &filesize, cred, curthread);
904                 if (error) {
905                         bp->b_ioflags |= BIO_ERROR;
906                         bp->b_error = error;
907                         bufdone(bp);
908                         return (error);
909                 }
910
911                 if ((off_t)bp->b_lblkno * biosize + bp->b_dirtyend > filesize)
912                         bp->b_dirtyend = filesize - 
913                                 (off_t)bp->b_lblkno * biosize;
914
915                 if (bp->b_dirtyend > bp->b_dirtyoff) {
916                         io.iov_len = uiop->uio_resid = bp->b_dirtyend
917                             - bp->b_dirtyoff;
918                         uiop->uio_offset = (off_t)bp->b_lblkno * biosize
919                             + bp->b_dirtyoff;
920                         io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
921                         uiop->uio_rw = UIO_WRITE;
922
923                         error = fuse_write_directbackend(vp, uiop, cred, fufh,
924                                 filesize, 0, false);
925
926                         if (error == EINTR || error == ETIMEDOUT) {
927                                 bp->b_flags &= ~(B_INVAL | B_NOCACHE);
928                                 if ((bp->b_flags & B_PAGING) == 0) {
929                                         bdirty(bp);
930                                         bp->b_flags &= ~B_DONE;
931                                 }
932                                 if ((error == EINTR || error == ETIMEDOUT) &&
933                                     (bp->b_flags & B_ASYNC) == 0)
934                                         bp->b_flags |= B_EINTR;
935                         } else {
936                                 if (error) {
937                                         bp->b_ioflags |= BIO_ERROR;
938                                         bp->b_flags |= B_INVAL;
939                                         bp->b_error = error;
940                                 }
941                                 bp->b_dirtyoff = bp->b_dirtyend = 0;
942                         }
943                 } else {
944                         bp->b_resid = 0;
945                         bufdone(bp);
946                         return (0);
947                 }
948         }
949         bp->b_resid = uiop->uio_resid;
950         bufdone(bp);
951         return (error);
952 }
953
954 int
955 fuse_io_flushbuf(struct vnode *vp, int waitfor, struct thread *td)
956 {
957
958         return (vn_fsync_buf(vp, waitfor));
959 }
960
961 /*
962  * Flush and invalidate all dirty buffers. If another process is already
963  * doing the flush, just wait for completion.
964  */
965 int
966 fuse_io_invalbuf(struct vnode *vp, struct thread *td)
967 {
968         struct fuse_vnode_data *fvdat = VTOFUD(vp);
969         int error = 0;
970
971         if (vp->v_iflag & VI_DOOMED)
972                 return 0;
973
974         ASSERT_VOP_ELOCKED(vp, "fuse_io_invalbuf");
975
976         while (fvdat->flag & FN_FLUSHINPROG) {
977                 struct proc *p = td->td_proc;
978
979                 if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF)
980                         return EIO;
981                 fvdat->flag |= FN_FLUSHWANT;
982                 tsleep(&fvdat->flag, PRIBIO + 2, "fusevinv", 2 * hz);
983                 error = 0;
984                 if (p != NULL) {
985                         PROC_LOCK(p);
986                         if (SIGNOTEMPTY(p->p_siglist) ||
987                             SIGNOTEMPTY(td->td_siglist))
988                                 error = EINTR;
989                         PROC_UNLOCK(p);
990                 }
991                 if (error == EINTR)
992                         return EINTR;
993         }
994         fvdat->flag |= FN_FLUSHINPROG;
995
996         if (vp->v_bufobj.bo_object != NULL) {
997                 VM_OBJECT_WLOCK(vp->v_bufobj.bo_object);
998                 vm_object_page_clean(vp->v_bufobj.bo_object, 0, 0, OBJPC_SYNC);
999                 VM_OBJECT_WUNLOCK(vp->v_bufobj.bo_object);
1000         }
1001         error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
1002         while (error) {
1003                 if (error == ERESTART || error == EINTR) {
1004                         fvdat->flag &= ~FN_FLUSHINPROG;
1005                         if (fvdat->flag & FN_FLUSHWANT) {
1006                                 fvdat->flag &= ~FN_FLUSHWANT;
1007                                 wakeup(&fvdat->flag);
1008                         }
1009                         return EINTR;
1010                 }
1011                 error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
1012         }
1013         fvdat->flag &= ~FN_FLUSHINPROG;
1014         if (fvdat->flag & FN_FLUSHWANT) {
1015                 fvdat->flag &= ~FN_FLUSHWANT;
1016                 wakeup(&fvdat->flag);
1017         }
1018         return (error);
1019 }