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