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