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