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