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