Major BUF/BIO work commit. Make I/O BIO-centric and specify the disk or
[dragonfly.git] / sys / vfs / nfs / nfs_bio.c
1 /*
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Rick Macklem at The University of Guelph.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      @(#)nfs_bio.c   8.9 (Berkeley) 3/30/95
37  * $FreeBSD: /repoman/r/ncvs/src/sys/nfsclient/nfs_bio.c,v 1.130 2004/04/14 23:23:55 peadar Exp $
38  * $DragonFly: src/sys/vfs/nfs/nfs_bio.c,v 1.28 2006/03/24 18:35:34 dillon Exp $
39  */
40
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/resourcevar.h>
45 #include <sys/signalvar.h>
46 #include <sys/proc.h>
47 #include <sys/buf.h>
48 #include <sys/vnode.h>
49 #include <sys/mount.h>
50 #include <sys/kernel.h>
51 #include <sys/buf2.h>
52 #include <sys/msfbuf.h>
53
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_page.h>
57 #include <vm/vm_object.h>
58 #include <vm/vm_pager.h>
59 #include <vm/vnode_pager.h>
60
61 #include <sys/thread2.h>
62
63 #include "rpcv2.h"
64 #include "nfsproto.h"
65 #include "nfs.h"
66 #include "nfsmount.h"
67 #include "nqnfs.h"
68 #include "nfsnode.h"
69
70 static struct buf *nfs_getcacheblk(struct vnode *vp, off_t loffset,
71                                    int size, struct thread *td);
72
73 extern int nfs_numasync;
74 extern int nfs_pbuf_freecnt;
75 extern struct nfsstats nfsstats;
76
77 /*
78  * Vnode op for VM getpages.
79  *
80  * nfs_getpages(struct vnode *a_vp, vm_page_t *a_m, int a_count,
81  *              int a_reqpage, vm_ooffset_t a_offset)
82  */
83 int
84 nfs_getpages(struct vop_getpages_args *ap)
85 {
86         struct thread *td = curthread;          /* XXX */
87         int i, error, nextoff, size, toff, count, npages;
88         struct uio uio;
89         struct iovec iov;
90         char *kva;
91         struct vnode *vp;
92         struct nfsmount *nmp;
93         vm_page_t *pages;
94         vm_page_t m;
95         struct msf_buf *msf;
96
97         vp = ap->a_vp;
98         nmp = VFSTONFS(vp->v_mount);
99         pages = ap->a_m;
100         count = ap->a_count;
101
102         if (vp->v_object == NULL) {
103                 printf("nfs_getpages: called with non-merged cache vnode??\n");
104                 return VM_PAGER_ERROR;
105         }
106
107         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
108             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
109                 (void)nfs_fsinfo(nmp, vp, td);
110
111         npages = btoc(count);
112
113         /*
114          * NOTE that partially valid pages may occur in cases other
115          * then file EOF, such as when a file is partially written and
116          * ftruncate()-extended to a larger size.   It is also possible
117          * for the valid bits to be set on garbage beyond the file EOF and
118          * clear in the area before EOF (e.g. m->valid == 0xfc), which can
119          * occur due to vtruncbuf() and the buffer cache's handling of
120          * pages which 'straddle' buffers or when b_bufsize is not a 
121          * multiple of PAGE_SIZE.... the buffer cache cannot normally
122          * clear the extra bits.  This kind of situation occurs when you
123          * make a small write() (m->valid == 0x03) and then mmap() and
124          * fault in the buffer(m->valid = 0xFF).  When NFS flushes the
125          * buffer (vinvalbuf() m->valid = 0xFC) we are left with a mess.
126          *
127          * This is combined with the possibility that the pages are partially
128          * dirty or that there is a buffer backing the pages that is dirty
129          * (even if m->dirty is 0).
130          *
131          * To solve this problem several hacks have been made:  (1) NFS
132          * guarentees that the IO block size is a multiple of PAGE_SIZE and
133          * (2) The buffer cache, when invalidating an NFS buffer, will
134          * disregard the buffer's fragmentory b_bufsize and invalidate
135          * the whole page rather then just the piece the buffer owns.
136          *
137          * This allows us to assume that a partially valid page found here
138          * is fully valid (vm_fault will zero'd out areas of the page not
139          * marked as valid).
140          */
141         m = pages[ap->a_reqpage];
142         if (m->valid != 0) {
143                 for (i = 0; i < npages; ++i) {
144                         if (i != ap->a_reqpage)
145                                 vnode_pager_freepage(pages[i]);
146                 }
147                 return(0);
148         }
149
150         /*
151          * Use an MSF_BUF as a medium to retrieve data from the pages.
152          */
153         msf_map_pagelist(&msf, pages, npages, 0);
154         KKASSERT(msf);
155         kva = msf_buf_kva(msf);
156
157         iov.iov_base = kva;
158         iov.iov_len = count;
159         uio.uio_iov = &iov;
160         uio.uio_iovcnt = 1;
161         uio.uio_offset = IDX_TO_OFF(pages[0]->pindex);
162         uio.uio_resid = count;
163         uio.uio_segflg = UIO_SYSSPACE;
164         uio.uio_rw = UIO_READ;
165         uio.uio_td = td;
166
167         error = nfs_readrpc(vp, &uio);
168         msf_buf_free(msf);
169
170         if (error && (uio.uio_resid == count)) {
171                 printf("nfs_getpages: error %d\n", error);
172                 for (i = 0; i < npages; ++i) {
173                         if (i != ap->a_reqpage)
174                                 vnode_pager_freepage(pages[i]);
175                 }
176                 return VM_PAGER_ERROR;
177         }
178
179         /*
180          * Calculate the number of bytes read and validate only that number
181          * of bytes.  Note that due to pending writes, size may be 0.  This
182          * does not mean that the remaining data is invalid!
183          */
184
185         size = count - uio.uio_resid;
186
187         for (i = 0, toff = 0; i < npages; i++, toff = nextoff) {
188                 nextoff = toff + PAGE_SIZE;
189                 m = pages[i];
190
191                 m->flags &= ~PG_ZERO;
192
193                 if (nextoff <= size) {
194                         /*
195                          * Read operation filled an entire page
196                          */
197                         m->valid = VM_PAGE_BITS_ALL;
198                         vm_page_undirty(m);
199                 } else if (size > toff) {
200                         /*
201                          * Read operation filled a partial page.
202                          */
203                         m->valid = 0;
204                         vm_page_set_validclean(m, 0, size - toff);
205                         /* handled by vm_fault now        */
206                         /* vm_page_zero_invalid(m, TRUE); */
207                 } else {
208                         /*
209                          * Read operation was short.  If no error occured
210                          * we may have hit a zero-fill section.   We simply
211                          * leave valid set to 0.
212                          */
213                         ;
214                 }
215                 if (i != ap->a_reqpage) {
216                         /*
217                          * Whether or not to leave the page activated is up in
218                          * the air, but we should put the page on a page queue
219                          * somewhere (it already is in the object).  Result:
220                          * It appears that emperical results show that
221                          * deactivating pages is best.
222                          */
223
224                         /*
225                          * Just in case someone was asking for this page we
226                          * now tell them that it is ok to use.
227                          */
228                         if (!error) {
229                                 if (m->flags & PG_WANTED)
230                                         vm_page_activate(m);
231                                 else
232                                         vm_page_deactivate(m);
233                                 vm_page_wakeup(m);
234                         } else {
235                                 vnode_pager_freepage(m);
236                         }
237                 }
238         }
239         return 0;
240 }
241
242 /*
243  * Vnode op for VM putpages.
244  *
245  * nfs_putpages(struct vnode *a_vp, vm_page_t *a_m, int a_count, int a_sync,
246  *              int *a_rtvals, vm_ooffset_t a_offset)
247  */
248 int
249 nfs_putpages(struct vop_putpages_args *ap)
250 {
251         struct thread *td = curthread;
252         struct uio uio;
253         struct iovec iov;
254         char *kva;
255         int iomode, must_commit, i, error, npages, count;
256         off_t offset;
257         int *rtvals;
258         struct vnode *vp;
259         struct nfsmount *nmp;
260         struct nfsnode *np;
261         vm_page_t *pages;
262         struct msf_buf *msf;
263
264         vp = ap->a_vp;
265         np = VTONFS(vp);
266         nmp = VFSTONFS(vp->v_mount);
267         pages = ap->a_m;
268         count = ap->a_count;
269         rtvals = ap->a_rtvals;
270         npages = btoc(count);
271         offset = IDX_TO_OFF(pages[0]->pindex);
272
273         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
274             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
275                 (void)nfs_fsinfo(nmp, vp, td);
276
277         for (i = 0; i < npages; i++) {
278                 rtvals[i] = VM_PAGER_AGAIN;
279         }
280
281         /*
282          * When putting pages, do not extend file past EOF.
283          */
284
285         if (offset + count > np->n_size) {
286                 count = np->n_size - offset;
287                 if (count < 0)
288                         count = 0;
289         }
290
291         /*
292          * Use an MSF_BUF as a medium to retrieve data from the pages.
293          */
294         msf_map_pagelist(&msf, pages, npages, 0);
295         KKASSERT(msf);
296         kva = msf_buf_kva(msf);
297
298         iov.iov_base = kva;
299         iov.iov_len = count;
300         uio.uio_iov = &iov;
301         uio.uio_iovcnt = 1;
302         uio.uio_offset = offset;
303         uio.uio_resid = count;
304         uio.uio_segflg = UIO_SYSSPACE;
305         uio.uio_rw = UIO_WRITE;
306         uio.uio_td = td;
307
308         if ((ap->a_sync & VM_PAGER_PUT_SYNC) == 0)
309             iomode = NFSV3WRITE_UNSTABLE;
310         else
311             iomode = NFSV3WRITE_FILESYNC;
312
313         error = nfs_writerpc(vp, &uio, &iomode, &must_commit);
314
315         msf_buf_free(msf);
316
317         if (!error) {
318                 int nwritten = round_page(count - uio.uio_resid) / PAGE_SIZE;
319                 for (i = 0; i < nwritten; i++) {
320                         rtvals[i] = VM_PAGER_OK;
321                         vm_page_undirty(pages[i]);
322                 }
323                 if (must_commit)
324                         nfs_clearcommit(vp->v_mount);
325         }
326         return rtvals[0];
327 }
328
329 /*
330  * Vnode op for read using bio
331  */
332 int
333 nfs_bioread(struct vnode *vp, struct uio *uio, int ioflag)
334 {
335         struct nfsnode *np = VTONFS(vp);
336         int biosize, i;
337         struct buf *bp = 0, *rabp;
338         struct vattr vattr;
339         struct thread *td;
340         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
341         daddr_t lbn, rabn;
342         off_t raoffset;
343         off_t loffset;
344         int bcount;
345         int seqcount;
346         int nra, error = 0, n = 0, on = 0;
347
348 #ifdef DIAGNOSTIC
349         if (uio->uio_rw != UIO_READ)
350                 panic("nfs_read mode");
351 #endif
352         if (uio->uio_resid == 0)
353                 return (0);
354         if (uio->uio_offset < 0)        /* XXX VDIR cookies can be negative */
355                 return (EINVAL);
356         td = uio->uio_td;
357
358         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
359             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
360                 (void)nfs_fsinfo(nmp, vp, td);
361         if (vp->v_type != VDIR &&
362             (uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
363                 return (EFBIG);
364         biosize = vp->v_mount->mnt_stat.f_iosize;
365         seqcount = (int)((off_t)(ioflag >> IO_SEQSHIFT) * biosize / BKVASIZE);
366
367         /*
368          * For nfs, cache consistency can only be maintained approximately.
369          * Although RFC1094 does not specify the criteria, the following is
370          * believed to be compatible with the reference port.
371          *
372          * NQNFS:       Full cache coherency is maintained within the loop.
373          *
374          * NFS:         If local changes have been made and this is a
375          *              directory, the directory must be invalidated and
376          *              the attribute cache must be cleared.
377          *
378          *              GETATTR is called to synchronize the file size.
379          *
380          *              If remote changes are detected local data is flushed
381          *              and the cache is invalidated.
382          *
383          *
384          *              NOTE: In the normal case the attribute cache is not
385          *              cleared which means GETATTR may use cached data and
386          *              not immediately detect changes made on the server.
387          */
388         if ((nmp->nm_flag & NFSMNT_NQNFS) == 0) {
389                 if ((np->n_flag & NLMODIFIED) && vp->v_type == VDIR) {
390                         nfs_invaldir(vp);
391                         error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
392                         if (error)
393                                 return (error);
394                         np->n_attrstamp = 0;
395                 }
396                 error = VOP_GETATTR(vp, &vattr, td);
397                 if (error)
398                         return (error);
399                 if (np->n_flag & NRMODIFIED) {
400                         if (vp->v_type == VDIR)
401                                 nfs_invaldir(vp);
402                         error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
403                         if (error)
404                                 return (error);
405                         np->n_flag &= ~NRMODIFIED;
406                 }
407         }
408         do {
409
410             /*
411              * Get a valid lease. If cached data is stale, flush it.
412              */
413             if (nmp->nm_flag & NFSMNT_NQNFS) {
414                 if (NQNFS_CKINVALID(vp, np, ND_READ)) {
415                     do {
416                         error = nqnfs_getlease(vp, ND_READ, td);
417                     } while (error == NQNFS_EXPIRED);
418                     if (error)
419                         return (error);
420                     if (np->n_lrev != np->n_brev ||
421                         (np->n_flag & NQNFSNONCACHE) ||
422                         ((np->n_flag & NLMODIFIED) && vp->v_type == VDIR)) {
423                         if (vp->v_type == VDIR)
424                             nfs_invaldir(vp);
425                         error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
426                         if (error)
427                             return (error);
428                         np->n_brev = np->n_lrev;
429                     }
430                 } else if (vp->v_type == VDIR && (np->n_flag & NLMODIFIED)) {
431                     nfs_invaldir(vp);
432                     error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
433                     if (error)
434                         return (error);
435                 }
436             }
437             if (np->n_flag & NQNFSNONCACHE) {
438                 switch (vp->v_type) {
439                 case VREG:
440                         return (nfs_readrpc(vp, uio));
441                 case VLNK:
442                         return (nfs_readlinkrpc(vp, uio));
443                 case VDIR:
444                         break;
445                 default:
446                         printf(" NQNFSNONCACHE: type %x unexpected\n",  
447                                 vp->v_type);
448                 };
449             }
450             switch (vp->v_type) {
451             case VREG:
452                 nfsstats.biocache_reads++;
453                 lbn = uio->uio_offset / biosize;
454                 on = uio->uio_offset & (biosize - 1);
455                 loffset = (off_t)lbn * biosize;
456
457                 /*
458                  * Start the read ahead(s), as required.
459                  */
460                 if (nfs_numasync > 0 && nmp->nm_readahead > 0) {
461                     for (nra = 0; nra < nmp->nm_readahead && nra < seqcount &&
462                         (off_t)(lbn + 1 + nra) * biosize < np->n_size; nra++) {
463                         rabn = lbn + 1 + nra;
464                         raoffset = (off_t)rabn * biosize;
465                         if (!findblk(vp, raoffset)) {
466                             rabp = nfs_getcacheblk(vp, raoffset, biosize, td);
467                             if (!rabp)
468                                 return (EINTR);
469                             if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
470                                 rabp->b_flags |= (B_READ | B_ASYNC);
471                                 vfs_busy_pages(rabp, 0);
472                                 if (nfs_asyncio(vp, &rabp->b_bio2, td)) {
473                                     rabp->b_flags |= B_INVAL|B_ERROR;
474                                     vfs_unbusy_pages(rabp);
475                                     brelse(rabp);
476                                     break;
477                                 }
478                             } else {
479                                 brelse(rabp);
480                             }
481                         }
482                     }
483                 }
484
485                 /*
486                  * Obtain the buffer cache block.  Figure out the buffer size
487                  * when we are at EOF.  If we are modifying the size of the
488                  * buffer based on an EOF condition we need to hold 
489                  * nfs_rslock() through obtaining the buffer to prevent
490                  * a potential writer-appender from messing with n_size.
491                  * Otherwise we may accidently truncate the buffer and
492                  * lose dirty data.
493                  *
494                  * Note that bcount is *not* DEV_BSIZE aligned.
495                  */
496
497 again:
498                 bcount = biosize;
499                 if (loffset >= np->n_size) {
500                         bcount = 0;
501                 } else if (loffset + biosize > np->n_size) {
502                         bcount = np->n_size - loffset;
503                 }
504                 if (bcount != biosize) {
505                         switch(nfs_rslock(np, td)) {
506                         case ENOLCK:
507                                 goto again;
508                                 /* not reached */
509                         case EINTR:
510                         case ERESTART:
511                                 return(EINTR);
512                                 /* not reached */
513                         default:
514                                 break;
515                         }
516                 }
517
518                 bp = nfs_getcacheblk(vp, loffset, bcount, td);
519
520                 if (bcount != biosize)
521                         nfs_rsunlock(np, td);
522                 if (!bp)
523                         return (EINTR);
524
525                 /*
526                  * If B_CACHE is not set, we must issue the read.  If this
527                  * fails, we return an error.
528                  */
529
530                 if ((bp->b_flags & B_CACHE) == 0) {
531                     bp->b_flags |= B_READ;
532                     vfs_busy_pages(bp, 0);
533                     error = nfs_doio(vp, &bp->b_bio2, td);
534                     if (error) {
535                         brelse(bp);
536                         return (error);
537                     }
538                 }
539
540                 /*
541                  * on is the offset into the current bp.  Figure out how many
542                  * bytes we can copy out of the bp.  Note that bcount is
543                  * NOT DEV_BSIZE aligned.
544                  *
545                  * Then figure out how many bytes we can copy into the uio.
546                  */
547
548                 n = 0;
549                 if (on < bcount)
550                         n = min((unsigned)(bcount - on), uio->uio_resid);
551                 break;
552             case VLNK:
553                 nfsstats.biocache_readlinks++;
554                 bp = nfs_getcacheblk(vp, (off_t)0, NFS_MAXPATHLEN, td);
555                 if (bp == NULL)
556                         return (EINTR);
557                 if ((bp->b_flags & B_CACHE) == 0) {
558                     bp->b_flags |= B_READ;
559                     vfs_busy_pages(bp, 0);
560                     error = nfs_doio(vp, &bp->b_bio2, td);
561                     if (error) {
562                         bp->b_flags |= B_ERROR;
563                         brelse(bp);
564                         return (error);
565                     }
566                 }
567                 n = min(uio->uio_resid, NFS_MAXPATHLEN - bp->b_resid);
568                 on = 0;
569                 break;
570             case VDIR:
571                 nfsstats.biocache_readdirs++;
572                 if (np->n_direofoffset
573                     && uio->uio_offset >= np->n_direofoffset) {
574                     return (0);
575                 }
576                 lbn = (uoff_t)uio->uio_offset / NFS_DIRBLKSIZ;
577                 on = uio->uio_offset & (NFS_DIRBLKSIZ - 1);
578                 loffset = uio->uio_offset - on;
579                 bp = nfs_getcacheblk(vp, loffset, NFS_DIRBLKSIZ, td);
580                 if (bp == NULL)
581                     return (EINTR);
582                 if ((bp->b_flags & B_CACHE) == 0) {
583                     bp->b_flags |= B_READ;
584                     vfs_busy_pages(bp, 0);
585                     error = nfs_doio(vp, &bp->b_bio2, td);
586                     if (error) {
587                             brelse(bp);
588                     }
589                     while (error == NFSERR_BAD_COOKIE) {
590                         printf("got bad cookie vp %p bp %p\n", vp, bp);
591                         nfs_invaldir(vp);
592                         error = nfs_vinvalbuf(vp, 0, td, 1);
593                         /*
594                          * Yuck! The directory has been modified on the
595                          * server. The only way to get the block is by
596                          * reading from the beginning to get all the
597                          * offset cookies.
598                          *
599                          * Leave the last bp intact unless there is an error.
600                          * Loop back up to the while if the error is another
601                          * NFSERR_BAD_COOKIE (double yuch!).
602                          */
603                         for (i = 0; i <= lbn && !error; i++) {
604                             if (np->n_direofoffset
605                                 && (i * NFS_DIRBLKSIZ) >= np->n_direofoffset)
606                                     return (0);
607                             bp = nfs_getcacheblk(vp, (off_t)i * NFS_DIRBLKSIZ,
608                                                  NFS_DIRBLKSIZ, td);
609                             if (!bp)
610                                 return (EINTR);
611                             if ((bp->b_flags & B_CACHE) == 0) {
612                                     bp->b_flags |= B_READ;
613                                     vfs_busy_pages(bp, 0);
614                                     error = nfs_doio(vp, &bp->b_bio2, td);
615                                     /*
616                                      * no error + B_INVAL == directory EOF,
617                                      * use the block.
618                                      */
619                                     if (error == 0 && (bp->b_flags & B_INVAL))
620                                             break;
621                             }
622                             /*
623                              * An error will throw away the block and the
624                              * for loop will break out.  If no error and this
625                              * is not the block we want, we throw away the
626                              * block and go for the next one via the for loop.
627                              */
628                             if (error || i < lbn)
629                                     brelse(bp);
630                         }
631                     }
632                     /*
633                      * The above while is repeated if we hit another cookie
634                      * error.  If we hit an error and it wasn't a cookie error,
635                      * we give up.
636                      */
637                     if (error)
638                             return (error);
639                 }
640
641                 /*
642                  * If not eof and read aheads are enabled, start one.
643                  * (You need the current block first, so that you have the
644                  *  directory offset cookie of the next block.)
645                  */
646                 if (nfs_numasync > 0 && nmp->nm_readahead > 0 &&
647                     (bp->b_flags & B_INVAL) == 0 &&
648                     (np->n_direofoffset == 0 ||
649                     loffset + NFS_DIRBLKSIZ < np->n_direofoffset) &&
650                     !(np->n_flag & NQNFSNONCACHE) &&
651                     !findblk(vp, loffset + NFS_DIRBLKSIZ)) {
652                         rabp = nfs_getcacheblk(vp, loffset + NFS_DIRBLKSIZ,
653                                                NFS_DIRBLKSIZ, td);
654                         if (rabp) {
655                             if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
656                                 rabp->b_flags |= (B_READ | B_ASYNC);
657                                 vfs_busy_pages(rabp, 0);
658                                 if (nfs_asyncio(vp, &rabp->b_bio2, td)) {
659                                     rabp->b_flags |= B_INVAL|B_ERROR;
660                                     vfs_unbusy_pages(rabp);
661                                     brelse(rabp);
662                                 }
663                             } else {
664                                 brelse(rabp);
665                             }
666                         }
667                 }
668                 /*
669                  * Unlike VREG files, whos buffer size ( bp->b_bcount ) is
670                  * chopped for the EOF condition, we cannot tell how large
671                  * NFS directories are going to be until we hit EOF.  So
672                  * an NFS directory buffer is *not* chopped to its EOF.  Now,
673                  * it just so happens that b_resid will effectively chop it
674                  * to EOF.  *BUT* this information is lost if the buffer goes
675                  * away and is reconstituted into a B_CACHE state ( due to
676                  * being VMIO ) later.  So we keep track of the directory eof
677                  * in np->n_direofoffset and chop it off as an extra step 
678                  * right here.
679                  */
680                 n = lmin(uio->uio_resid, NFS_DIRBLKSIZ - bp->b_resid - on);
681                 if (np->n_direofoffset && n > np->n_direofoffset - uio->uio_offset)
682                         n = np->n_direofoffset - uio->uio_offset;
683                 break;
684             default:
685                 printf(" nfs_bioread: type %x unexpected\n",vp->v_type);
686                 break;
687             };
688
689             switch (vp->v_type) {
690             case VREG:
691                 if (n > 0)
692                     error = uiomove(bp->b_data + on, (int)n, uio);
693                 break;
694             case VLNK:
695                 if (n > 0)
696                     error = uiomove(bp->b_data + on, (int)n, uio);
697                 n = 0;
698                 break;
699             case VDIR:
700                 if (n > 0) {
701                     off_t old_off = uio->uio_offset;
702                     caddr_t cpos, epos;
703                     struct nfs_dirent *dp;
704
705                     cpos = bp->b_data + on;
706                     epos = bp->b_data + on + n;
707                     while (cpos < epos && error == 0 && uio->uio_resid > 0) {
708                             dp = (struct nfs_dirent *)cpos;
709                             if (vop_write_dirent(&error, uio, dp->nfs_ino,
710                                 dp->nfs_type, dp->nfs_namlen, dp->nfs_name))
711                                     break;
712                             cpos += dp->nfs_reclen;
713                     }
714                     n = 0;
715                     if (error == 0)
716                             uio->uio_offset = old_off + cpos - bp->b_data - on;
717                 }
718                 /*
719                  * Invalidate buffer if caching is disabled, forcing a
720                  * re-read from the remote later.
721                  */
722                 if (np->n_flag & NQNFSNONCACHE)
723                         bp->b_flags |= B_INVAL;
724                 break;
725             default:
726                 printf(" nfs_bioread: type %x unexpected\n",vp->v_type);
727             }
728             brelse(bp);
729         } while (error == 0 && uio->uio_resid > 0 && n > 0);
730         return (error);
731 }
732
733 /*
734  * Vnode op for write using bio
735  *
736  * nfs_write(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
737  *           struct ucred *a_cred)
738  */
739 int
740 nfs_write(struct vop_write_args *ap)
741 {
742         struct uio *uio = ap->a_uio;
743         struct thread *td = uio->uio_td;
744         struct vnode *vp = ap->a_vp;
745         struct nfsnode *np = VTONFS(vp);
746         int ioflag = ap->a_ioflag;
747         struct buf *bp;
748         struct vattr vattr;
749         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
750         daddr_t lbn;
751         off_t loffset;
752         int n, on, error = 0, iomode, must_commit;
753         int haverslock = 0;
754         int bcount;
755         int biosize;
756
757 #ifdef DIAGNOSTIC
758         if (uio->uio_rw != UIO_WRITE)
759                 panic("nfs_write mode");
760         if (uio->uio_segflg == UIO_USERSPACE && uio->uio_td != curthread)
761                 panic("nfs_write proc");
762 #endif
763         if (vp->v_type != VREG)
764                 return (EIO);
765         if (np->n_flag & NWRITEERR) {
766                 np->n_flag &= ~NWRITEERR;
767                 return (np->n_error);
768         }
769         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
770             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
771                 (void)nfs_fsinfo(nmp, vp, td);
772
773         /*
774          * Synchronously flush pending buffers if we are in synchronous
775          * mode or if we are appending.
776          */
777         if (ioflag & (IO_APPEND | IO_SYNC)) {
778                 if (np->n_flag & NLMODIFIED) {
779                         np->n_attrstamp = 0;
780                         error = nfs_flush(vp, MNT_WAIT, td, 0);
781                         /* error = nfs_vinvalbuf(vp, V_SAVE, td, 1); */
782                         if (error)
783                                 return (error);
784                 }
785         }
786
787         /*
788          * If IO_APPEND then load uio_offset.  We restart here if we cannot
789          * get the append lock.
790          */
791 restart:
792         if (ioflag & IO_APPEND) {
793                 np->n_attrstamp = 0;
794                 error = VOP_GETATTR(vp, &vattr, td);
795                 if (error)
796                         return (error);
797                 uio->uio_offset = np->n_size;
798         }
799
800         if (uio->uio_offset < 0)
801                 return (EINVAL);
802         if ((uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
803                 return (EFBIG);
804         if (uio->uio_resid == 0)
805                 return (0);
806
807         /*
808          * We need to obtain the rslock if we intend to modify np->n_size
809          * in order to guarentee the append point with multiple contending
810          * writers, to guarentee that no other appenders modify n_size
811          * while we are trying to obtain a truncated buffer (i.e. to avoid
812          * accidently truncating data written by another appender due to
813          * the race), and to ensure that the buffer is populated prior to
814          * our extending of the file.  We hold rslock through the entire
815          * operation.
816          *
817          * Note that we do not synchronize the case where someone truncates
818          * the file while we are appending to it because attempting to lock
819          * this case may deadlock other parts of the system unexpectedly.
820          */
821         if ((ioflag & IO_APPEND) ||
822             uio->uio_offset + uio->uio_resid > np->n_size) {
823                 switch(nfs_rslock(np, td)) {
824                 case ENOLCK:
825                         goto restart;
826                         /* not reached */
827                 case EINTR:
828                 case ERESTART:
829                         return(EINTR);
830                         /* not reached */
831                 default:
832                         break;
833                 }
834                 haverslock = 1;
835         }
836
837         /*
838          * Maybe this should be above the vnode op call, but so long as
839          * file servers have no limits, i don't think it matters
840          */
841         if (td->td_proc && uio->uio_offset + uio->uio_resid >
842               td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
843                 psignal(td->td_proc, SIGXFSZ);
844                 if (haverslock)
845                         nfs_rsunlock(np, td);
846                 return (EFBIG);
847         }
848
849         biosize = vp->v_mount->mnt_stat.f_iosize;
850
851         do {
852                 /*
853                  * Check for a valid write lease.
854                  */
855                 if ((nmp->nm_flag & NFSMNT_NQNFS) &&
856                     NQNFS_CKINVALID(vp, np, ND_WRITE)) {
857                         do {
858                                 error = nqnfs_getlease(vp, ND_WRITE, td);
859                         } while (error == NQNFS_EXPIRED);
860                         if (error)
861                                 break;
862                         if (np->n_lrev != np->n_brev ||
863                             (np->n_flag & NQNFSNONCACHE)) {
864                                 error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
865                                 if (error)
866                                         break;
867                                 np->n_brev = np->n_lrev;
868                         }
869                 }
870                 if ((np->n_flag & NQNFSNONCACHE) && uio->uio_iovcnt == 1) {
871                     iomode = NFSV3WRITE_FILESYNC;
872                     error = nfs_writerpc(vp, uio, &iomode, &must_commit);
873                     if (must_commit)
874                             nfs_clearcommit(vp->v_mount);
875                     break;
876                 }
877                 nfsstats.biocache_writes++;
878                 lbn = uio->uio_offset / biosize;
879                 on = uio->uio_offset & (biosize-1);
880                 loffset = uio->uio_offset - on;
881                 n = min((unsigned)(biosize - on), uio->uio_resid);
882 again:
883                 /*
884                  * Handle direct append and file extension cases, calculate
885                  * unaligned buffer size.
886                  */
887
888                 if (uio->uio_offset == np->n_size && n) {
889                         /*
890                          * Get the buffer (in its pre-append state to maintain
891                          * B_CACHE if it was previously set).  Resize the
892                          * nfsnode after we have locked the buffer to prevent
893                          * readers from reading garbage.
894                          */
895                         bcount = on;
896                         bp = nfs_getcacheblk(vp, loffset, bcount, td);
897
898                         if (bp != NULL) {
899                                 long save;
900
901                                 np->n_size = uio->uio_offset + n;
902                                 np->n_flag |= NLMODIFIED;
903                                 vnode_pager_setsize(vp, np->n_size);
904
905                                 save = bp->b_flags & B_CACHE;
906                                 bcount += n;
907                                 allocbuf(bp, bcount);
908                                 bp->b_flags |= save;
909                         }
910                 } else {
911                         /*
912                          * Obtain the locked cache block first, and then 
913                          * adjust the file's size as appropriate.
914                          */
915                         bcount = on + n;
916                         if (loffset + bcount < np->n_size) {
917                                 if (loffset + biosize < np->n_size)
918                                         bcount = biosize;
919                                 else
920                                         bcount = np->n_size - loffset;
921                         }
922                         bp = nfs_getcacheblk(vp, loffset, bcount, td);
923                         if (uio->uio_offset + n > np->n_size) {
924                                 np->n_size = uio->uio_offset + n;
925                                 np->n_flag |= NLMODIFIED;
926                                 vnode_pager_setsize(vp, np->n_size);
927                         }
928                 }
929
930                 if (bp == NULL) {
931                         error = EINTR;
932                         break;
933                 }
934
935                 /*
936                  * Issue a READ if B_CACHE is not set.  In special-append
937                  * mode, B_CACHE is based on the buffer prior to the write
938                  * op and is typically set, avoiding the read.  If a read
939                  * is required in special append mode, the server will
940                  * probably send us a short-read since we extended the file
941                  * on our end, resulting in b_resid == 0 and, thusly, 
942                  * B_CACHE getting set.
943                  *
944                  * We can also avoid issuing the read if the write covers
945                  * the entire buffer.  We have to make sure the buffer state
946                  * is reasonable in this case since we will not be initiating
947                  * I/O.  See the comments in kern/vfs_bio.c's getblk() for
948                  * more information.
949                  *
950                  * B_CACHE may also be set due to the buffer being cached
951                  * normally.
952                  */
953
954                 if (on == 0 && n == bcount) {
955                         bp->b_flags |= B_CACHE;
956                         bp->b_flags &= ~(B_ERROR | B_INVAL);
957                 }
958
959                 if ((bp->b_flags & B_CACHE) == 0) {
960                         bp->b_flags |= B_READ;
961                         vfs_busy_pages(bp, 0);
962                         error = nfs_doio(vp, &bp->b_bio2, td);
963                         if (error) {
964                                 brelse(bp);
965                                 break;
966                         }
967                 }
968                 if (!bp) {
969                         error = EINTR;
970                         break;
971                 }
972                 np->n_flag |= NLMODIFIED;
973
974                 /*
975                  * If dirtyend exceeds file size, chop it down.  This should
976                  * not normally occur but there is an append race where it
977                  * might occur XXX, so we log it. 
978                  *
979                  * If the chopping creates a reverse-indexed or degenerate
980                  * situation with dirtyoff/end, we 0 both of them.
981                  */
982
983                 if (bp->b_dirtyend > bcount) {
984                         printf("NFS append race @%08llx:%d\n", 
985                             bp->b_bio2.bio_offset,
986                             bp->b_dirtyend - bcount);
987                         bp->b_dirtyend = bcount;
988                 }
989
990                 if (bp->b_dirtyoff >= bp->b_dirtyend)
991                         bp->b_dirtyoff = bp->b_dirtyend = 0;
992
993                 /*
994                  * If the new write will leave a contiguous dirty
995                  * area, just update the b_dirtyoff and b_dirtyend,
996                  * otherwise force a write rpc of the old dirty area.
997                  *
998                  * While it is possible to merge discontiguous writes due to 
999                  * our having a B_CACHE buffer ( and thus valid read data
1000                  * for the hole), we don't because it could lead to 
1001                  * significant cache coherency problems with multiple clients,
1002                  * especially if locking is implemented later on.
1003                  *
1004                  * as an optimization we could theoretically maintain
1005                  * a linked list of discontinuous areas, but we would still
1006                  * have to commit them separately so there isn't much
1007                  * advantage to it except perhaps a bit of asynchronization.
1008                  */
1009
1010                 if (bp->b_dirtyend > 0 &&
1011                     (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
1012                         if (VOP_BWRITE(vp, bp) == EINTR) {
1013                                 error = EINTR;
1014                                 break;
1015                         }
1016                         goto again;
1017                 }
1018
1019                 /*
1020                  * Check for valid write lease and get one as required.
1021                  * In case getblk() and/or bwrite() delayed us.
1022                  */
1023                 if ((nmp->nm_flag & NFSMNT_NQNFS) &&
1024                     NQNFS_CKINVALID(vp, np, ND_WRITE)) {
1025                         do {
1026                                 error = nqnfs_getlease(vp, ND_WRITE, td);
1027                         } while (error == NQNFS_EXPIRED);
1028                         if (error) {
1029                                 brelse(bp);
1030                                 break;
1031                         }
1032                         if (np->n_lrev != np->n_brev ||
1033                             (np->n_flag & NQNFSNONCACHE)) {
1034                                 brelse(bp);
1035                                 error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
1036                                 if (error)
1037                                         break;
1038                                 np->n_brev = np->n_lrev;
1039                                 goto again;
1040                         }
1041                 }
1042
1043                 error = uiomove((char *)bp->b_data + on, n, uio);
1044
1045                 /*
1046                  * Since this block is being modified, it must be written
1047                  * again and not just committed.  Since write clustering does
1048                  * not work for the stage 1 data write, only the stage 2
1049                  * commit rpc, we have to clear B_CLUSTEROK as well.
1050                  */
1051                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1052
1053                 if (error) {
1054                         bp->b_flags |= B_ERROR;
1055                         brelse(bp);
1056                         break;
1057                 }
1058
1059                 /*
1060                  * Only update dirtyoff/dirtyend if not a degenerate 
1061                  * condition.
1062                  */
1063                 if (n) {
1064                         if (bp->b_dirtyend > 0) {
1065                                 bp->b_dirtyoff = min(on, bp->b_dirtyoff);
1066                                 bp->b_dirtyend = max((on + n), bp->b_dirtyend);
1067                         } else {
1068                                 bp->b_dirtyoff = on;
1069                                 bp->b_dirtyend = on + n;
1070                         }
1071                         vfs_bio_set_validclean(bp, on, n);
1072                 }
1073                 /*
1074                  * If IO_NOWDRAIN then set B_NOWDRAIN (e.g. nfs-backed VN
1075                  * filesystem).  XXX also use for loopback NFS mounts.
1076                  */
1077                 if (ioflag & IO_NOWDRAIN)
1078                         bp->b_flags |= B_NOWDRAIN;
1079
1080                 /*
1081                  * If the lease is non-cachable or IO_SYNC do bwrite().
1082                  *
1083                  * IO_INVAL appears to be unused.  The idea appears to be
1084                  * to turn off caching in this case.  Very odd.  XXX
1085                  */
1086                 if ((np->n_flag & NQNFSNONCACHE) || (ioflag & IO_SYNC)) {
1087                         if (ioflag & IO_INVAL)
1088                                 bp->b_flags |= B_NOCACHE;
1089                         error = VOP_BWRITE(vp, bp);
1090                         if (error)
1091                                 break;
1092                         if (np->n_flag & NQNFSNONCACHE) {
1093                                 error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
1094                                 if (error)
1095                                         break;
1096                         }
1097                 } else if ((n + on) == biosize &&
1098                         (nmp->nm_flag & NFSMNT_NQNFS) == 0) {
1099                         bp->b_flags |= B_ASYNC;
1100                         nfs_writebp(bp, 0, 0);
1101                 } else {
1102                         bdwrite(bp);
1103                 }
1104         } while (uio->uio_resid > 0 && n > 0);
1105
1106         if (haverslock)
1107                 nfs_rsunlock(np, td);
1108
1109         return (error);
1110 }
1111
1112 /*
1113  * Get an nfs cache block.
1114  *
1115  * Allocate a new one if the block isn't currently in the cache
1116  * and return the block marked busy. If the calling process is
1117  * interrupted by a signal for an interruptible mount point, return
1118  * NULL.
1119  *
1120  * The caller must carefully deal with the possible B_INVAL state of
1121  * the buffer.  nfs_doio() clears B_INVAL (and nfs_asyncio() clears it
1122  * indirectly), so synchronous reads can be issued without worrying about
1123  * the B_INVAL state.  We have to be a little more careful when dealing
1124  * with writes (see comments in nfs_write()) when extending a file past
1125  * its EOF.
1126  */
1127 static struct buf *
1128 nfs_getcacheblk(struct vnode *vp, off_t loffset, int size, struct thread *td)
1129 {
1130         struct buf *bp;
1131         struct mount *mp;
1132         struct nfsmount *nmp;
1133
1134         mp = vp->v_mount;
1135         nmp = VFSTONFS(mp);
1136
1137         if (nmp->nm_flag & NFSMNT_INT) {
1138                 bp = getblk(vp, loffset, size, PCATCH, 0);
1139                 while (bp == NULL) {
1140                         if (nfs_sigintr(nmp, (struct nfsreq *)0, td))
1141                                 return (NULL);
1142                         bp = getblk(vp, loffset, size, 0, 2 * hz);
1143                 }
1144         } else {
1145                 bp = getblk(vp, loffset, size, 0, 0);
1146         }
1147
1148         /*
1149          * bio2, the 'device' layer.  Since BIOs use 64 bit byte offsets
1150          * now, no translation is necessary.
1151          */
1152         bp->b_bio2.bio_offset = loffset;
1153         return (bp);
1154 }
1155
1156 /*
1157  * Flush and invalidate all dirty buffers. If another process is already
1158  * doing the flush, just wait for completion.
1159  */
1160 int
1161 nfs_vinvalbuf(struct vnode *vp, int flags,
1162               struct thread *td, int intrflg)
1163 {
1164         struct nfsnode *np = VTONFS(vp);
1165         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1166         int error = 0, slpflag, slptimeo;
1167
1168         if (vp->v_flag & VRECLAIMED)
1169                 return (0);
1170
1171         if ((nmp->nm_flag & NFSMNT_INT) == 0)
1172                 intrflg = 0;
1173         if (intrflg) {
1174                 slpflag = PCATCH;
1175                 slptimeo = 2 * hz;
1176         } else {
1177                 slpflag = 0;
1178                 slptimeo = 0;
1179         }
1180         /*
1181          * First wait for any other process doing a flush to complete.
1182          */
1183         while (np->n_flag & NFLUSHINPROG) {
1184                 np->n_flag |= NFLUSHWANT;
1185                 error = tsleep((caddr_t)&np->n_flag, 0, "nfsvinval", slptimeo);
1186                 if (error && intrflg && nfs_sigintr(nmp, (struct nfsreq *)0, td))
1187                         return (EINTR);
1188         }
1189
1190         /*
1191          * Now, flush as required.
1192          */
1193         np->n_flag |= NFLUSHINPROG;
1194         error = vinvalbuf(vp, flags, td, slpflag, 0);
1195         while (error) {
1196                 if (intrflg && nfs_sigintr(nmp, (struct nfsreq *)0, td)) {
1197                         np->n_flag &= ~NFLUSHINPROG;
1198                         if (np->n_flag & NFLUSHWANT) {
1199                                 np->n_flag &= ~NFLUSHWANT;
1200                                 wakeup((caddr_t)&np->n_flag);
1201                         }
1202                         return (EINTR);
1203                 }
1204                 error = vinvalbuf(vp, flags, td, 0, slptimeo);
1205         }
1206         np->n_flag &= ~(NLMODIFIED | NFLUSHINPROG);
1207         if (np->n_flag & NFLUSHWANT) {
1208                 np->n_flag &= ~NFLUSHWANT;
1209                 wakeup((caddr_t)&np->n_flag);
1210         }
1211         return (0);
1212 }
1213
1214 /*
1215  * Initiate asynchronous I/O. Return an error if no nfsiods are available.
1216  * This is mainly to avoid queueing async I/O requests when the nfsiods
1217  * are all hung on a dead server.
1218  *
1219  * Note: nfs_asyncio() does not clear (B_ERROR|B_INVAL) but when the bp
1220  * is eventually dequeued by the async daemon, nfs_doio() *will*.
1221  */
1222 int
1223 nfs_asyncio(struct vnode *vp, struct bio *bio, struct thread *td)
1224 {
1225         struct buf *bp = bio->bio_buf;
1226         struct nfsmount *nmp;
1227         int i;
1228         int gotiod;
1229         int slpflag = 0;
1230         int slptimeo = 0;
1231         int error;
1232
1233         /*
1234          * If no async daemons then return EIO to force caller to run the rpc
1235          * synchronously.
1236          */
1237         if (nfs_numasync == 0)
1238                 return (EIO);
1239
1240         KKASSERT(vp->v_tag == VT_NFS);
1241         nmp = VFSTONFS(vp->v_mount);
1242
1243         /*
1244          * Commits are usually short and sweet so lets save some cpu and 
1245          * leave the async daemons for more important rpc's (such as reads
1246          * and writes).
1247          */
1248         if ((bp->b_flags & (B_READ|B_NEEDCOMMIT)) == B_NEEDCOMMIT &&
1249             (nmp->nm_bioqiods > nfs_numasync / 2)) {
1250                 return(EIO);
1251         }
1252
1253 again:
1254         if (nmp->nm_flag & NFSMNT_INT)
1255                 slpflag = PCATCH;
1256         gotiod = FALSE;
1257
1258         /*
1259          * Find a free iod to process this request.
1260          */
1261         for (i = 0; i < NFS_MAXASYNCDAEMON; i++)
1262                 if (nfs_iodwant[i]) {
1263                         /*
1264                          * Found one, so wake it up and tell it which
1265                          * mount to process.
1266                          */
1267                         NFS_DPF(ASYNCIO,
1268                                 ("nfs_asyncio: waking iod %d for mount %p\n",
1269                                  i, nmp));
1270                         nfs_iodwant[i] = NULL;
1271                         nfs_iodmount[i] = nmp;
1272                         nmp->nm_bioqiods++;
1273                         wakeup((caddr_t)&nfs_iodwant[i]);
1274                         gotiod = TRUE;
1275                         break;
1276                 }
1277
1278         /*
1279          * If none are free, we may already have an iod working on this mount
1280          * point.  If so, it will process our request.
1281          */
1282         if (!gotiod) {
1283                 if (nmp->nm_bioqiods > 0) {
1284                         NFS_DPF(ASYNCIO,
1285                                 ("nfs_asyncio: %d iods are already processing mount %p\n",
1286                                  nmp->nm_bioqiods, nmp));
1287                         gotiod = TRUE;
1288                 }
1289         }
1290
1291         /*
1292          * If we have an iod which can process the request, then queue
1293          * the buffer.
1294          */
1295         if (gotiod) {
1296                 /*
1297                  * Ensure that the queue never grows too large.  We still want
1298                  * to asynchronize so we block rather then return EIO.
1299                  */
1300                 while (nmp->nm_bioqlen >= 2*nfs_numasync) {
1301                         NFS_DPF(ASYNCIO,
1302                                 ("nfs_asyncio: waiting for mount %p queue to drain\n", nmp));
1303                         nmp->nm_bioqwant = TRUE;
1304                         error = tsleep(&nmp->nm_bioq, slpflag,
1305                                        "nfsaio", slptimeo);
1306                         if (error) {
1307                                 if (nfs_sigintr(nmp, NULL, td))
1308                                         return (EINTR);
1309                                 if (slpflag == PCATCH) {
1310                                         slpflag = 0;
1311                                         slptimeo = 2 * hz;
1312                                 }
1313                         }
1314                         /*
1315                          * We might have lost our iod while sleeping,
1316                          * so check and loop if nescessary.
1317                          */
1318                         if (nmp->nm_bioqiods == 0) {
1319                                 NFS_DPF(ASYNCIO,
1320                                         ("nfs_asyncio: no iods after mount %p queue was drained, looping\n", nmp));
1321                                 goto again;
1322                         }
1323                 }
1324                 BUF_KERNPROC(bp);
1325
1326                 /*
1327                  * The passed bio's buffer is not necessary associated with
1328                  * the NFS vnode it is being written to.  Store the NFS vnode
1329                  * in the BIO driver info.
1330                  */
1331                 bio->bio_driver_info = vp;
1332                 TAILQ_INSERT_TAIL(&nmp->nm_bioq, bio, bio_act);
1333                 nmp->nm_bioqlen++;
1334                 return (0);
1335         }
1336
1337         /*
1338          * All the iods are busy on other mounts, so return EIO to
1339          * force the caller to process the i/o synchronously.
1340          */
1341         NFS_DPF(ASYNCIO, ("nfs_asyncio: no iods available, i/o is synchronous\n"));
1342         return (EIO);
1343 }
1344
1345 /*
1346  * Do an I/O operation to/from a cache block. This may be called
1347  * synchronously or from an nfsiod.  The BIO is normalized for DEV_BSIZE.
1348  *
1349  * NOTE! TD MIGHT BE NULL
1350  */
1351 int
1352 nfs_doio(struct vnode *vp, struct bio *bio, struct thread *td)
1353 {
1354         struct buf *bp = bio->bio_buf;
1355         struct uio *uiop;
1356         struct nfsnode *np;
1357         struct nfsmount *nmp;
1358         int error = 0, iomode, must_commit = 0;
1359         struct uio uio;
1360         struct iovec io;
1361
1362         KKASSERT(vp->v_tag == VT_NFS);
1363         np = VTONFS(vp);
1364         nmp = VFSTONFS(vp->v_mount);
1365         uiop = &uio;
1366         uiop->uio_iov = &io;
1367         uiop->uio_iovcnt = 1;
1368         uiop->uio_segflg = UIO_SYSSPACE;
1369         uiop->uio_td = td;
1370
1371         /*
1372          * clear B_ERROR and B_INVAL state prior to initiating the I/O.  We
1373          * do this here so we do not have to do it in all the code that
1374          * calls us.
1375          */
1376         bp->b_flags &= ~(B_ERROR | B_INVAL);
1377
1378         KASSERT(!(bp->b_flags & B_DONE), ("nfs_doio: bp %p already marked done", bp));
1379
1380         /*
1381          * Historically, paging was done with physio, but no more.
1382          */
1383         if (bp->b_flags & B_PHYS) {
1384             /*
1385              * ...though reading /dev/drum still gets us here.
1386              */
1387             io.iov_len = uiop->uio_resid = bp->b_bcount;
1388             /* mapping was done by vmapbuf() */
1389             io.iov_base = bp->b_data;
1390             uiop->uio_offset = bio->bio_offset;
1391             if (bp->b_flags & B_READ) {
1392                 uiop->uio_rw = UIO_READ;
1393                 nfsstats.read_physios++;
1394                 error = nfs_readrpc(vp, uiop);
1395             } else {
1396                 int com;
1397
1398                 iomode = NFSV3WRITE_DATASYNC;
1399                 uiop->uio_rw = UIO_WRITE;
1400                 nfsstats.write_physios++;
1401                 error = nfs_writerpc(vp, uiop, &iomode, &com);
1402             }
1403             if (error) {
1404                 bp->b_flags |= B_ERROR;
1405                 bp->b_error = error;
1406             }
1407         } else if (bp->b_flags & B_READ) {
1408             io.iov_len = uiop->uio_resid = bp->b_bcount;
1409             io.iov_base = bp->b_data;
1410             uiop->uio_rw = UIO_READ;
1411
1412             switch (vp->v_type) {
1413             case VREG:
1414                 uiop->uio_offset = bio->bio_offset;
1415                 nfsstats.read_bios++;
1416                 error = nfs_readrpc(vp, uiop);
1417
1418                 if (!error) {
1419                     if (uiop->uio_resid) {
1420                         /*
1421                          * If we had a short read with no error, we must have
1422                          * hit a file hole.  We should zero-fill the remainder.
1423                          * This can also occur if the server hits the file EOF.
1424                          *
1425                          * Holes used to be able to occur due to pending 
1426                          * writes, but that is not possible any longer.
1427                          */
1428                         int nread = bp->b_bcount - uiop->uio_resid;
1429                         int left  = uiop->uio_resid;
1430
1431                         if (left > 0)
1432                                 bzero((char *)bp->b_data + nread, left);
1433                         uiop->uio_resid = 0;
1434                     }
1435                 }
1436                 if (td && td->td_proc && (vp->v_flag & VTEXT) &&
1437                         (((nmp->nm_flag & NFSMNT_NQNFS) &&
1438                           NQNFS_CKINVALID(vp, np, ND_READ) &&
1439                           np->n_lrev != np->n_brev) ||
1440                          (!(nmp->nm_flag & NFSMNT_NQNFS) &&
1441                           np->n_mtime != np->n_vattr.va_mtime.tv_sec))) {
1442                         uprintf("Process killed due to text file modification\n");
1443                         psignal(td->td_proc, SIGKILL);
1444                 }
1445                 break;
1446             case VLNK:
1447                 uiop->uio_offset = 0;
1448                 nfsstats.readlink_bios++;
1449                 error = nfs_readlinkrpc(vp, uiop);
1450                 break;
1451             case VDIR:
1452                 nfsstats.readdir_bios++;
1453                 uiop->uio_offset = bio->bio_offset;
1454                 if (nmp->nm_flag & NFSMNT_RDIRPLUS) {
1455                         error = nfs_readdirplusrpc(vp, uiop);
1456                         if (error == NFSERR_NOTSUPP)
1457                                 nmp->nm_flag &= ~NFSMNT_RDIRPLUS;
1458                 }
1459                 if ((nmp->nm_flag & NFSMNT_RDIRPLUS) == 0)
1460                         error = nfs_readdirrpc(vp, uiop);
1461                 /*
1462                  * end-of-directory sets B_INVAL but does not generate an
1463                  * error.
1464                  */
1465                 if (error == 0 && uiop->uio_resid == bp->b_bcount)
1466                         bp->b_flags |= B_INVAL;
1467                 break;
1468             default:
1469                 printf("nfs_doio:  type %x unexpected\n",vp->v_type);
1470                 break;
1471             };
1472             if (error) {
1473                 bp->b_flags |= B_ERROR;
1474                 bp->b_error = error;
1475             }
1476         } else {
1477             /* 
1478              * If we only need to commit, try to commit
1479              */
1480             if (bp->b_flags & B_NEEDCOMMIT) {
1481                     int retv;
1482                     off_t off;
1483
1484                     off = bio->bio_offset + bp->b_dirtyoff;
1485                     retv = nfs_commit(vp, off, 
1486                                 bp->b_dirtyend - bp->b_dirtyoff, td);
1487                     if (retv == 0) {
1488                             bp->b_dirtyoff = bp->b_dirtyend = 0;
1489                             bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1490                             bp->b_resid = 0;
1491                             biodone(bio);
1492                             return (0);
1493                     }
1494                     if (retv == NFSERR_STALEWRITEVERF) {
1495                             nfs_clearcommit(vp->v_mount);
1496                     }
1497             }
1498
1499             /*
1500              * Setup for actual write
1501              */
1502
1503             if (bio->bio_offset + bp->b_dirtyend > np->n_size)
1504                 bp->b_dirtyend = np->n_size - bio->bio_offset;
1505
1506             if (bp->b_dirtyend > bp->b_dirtyoff) {
1507                 io.iov_len = uiop->uio_resid = bp->b_dirtyend
1508                     - bp->b_dirtyoff;
1509                 uiop->uio_offset = bio->bio_offset + bp->b_dirtyoff;
1510                 io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1511                 uiop->uio_rw = UIO_WRITE;
1512                 nfsstats.write_bios++;
1513
1514                 if ((bp->b_flags & (B_ASYNC | B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == B_ASYNC)
1515                     iomode = NFSV3WRITE_UNSTABLE;
1516                 else
1517                     iomode = NFSV3WRITE_FILESYNC;
1518
1519                 error = nfs_writerpc(vp, uiop, &iomode, &must_commit);
1520
1521                 /*
1522                  * When setting B_NEEDCOMMIT also set B_CLUSTEROK to try
1523                  * to cluster the buffers needing commit.  This will allow
1524                  * the system to submit a single commit rpc for the whole
1525                  * cluster.  We can do this even if the buffer is not 100% 
1526                  * dirty (relative to the NFS blocksize), so we optimize the
1527                  * append-to-file-case.
1528                  *
1529                  * (when clearing B_NEEDCOMMIT, B_CLUSTEROK must also be
1530                  * cleared because write clustering only works for commit
1531                  * rpc's, not for the data portion of the write).
1532                  */
1533
1534                 if (!error && iomode == NFSV3WRITE_UNSTABLE) {
1535                     bp->b_flags |= B_NEEDCOMMIT;
1536                     if (bp->b_dirtyoff == 0
1537                         && bp->b_dirtyend == bp->b_bcount)
1538                         bp->b_flags |= B_CLUSTEROK;
1539                 } else {
1540                     bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1541                 }
1542
1543                 /*
1544                  * For an interrupted write, the buffer is still valid
1545                  * and the write hasn't been pushed to the server yet,
1546                  * so we can't set B_ERROR and report the interruption
1547                  * by setting B_EINTR. For the B_ASYNC case, B_EINTR
1548                  * is not relevant, so the rpc attempt is essentially
1549                  * a noop.  For the case of a V3 write rpc not being
1550                  * committed to stable storage, the block is still
1551                  * dirty and requires either a commit rpc or another
1552                  * write rpc with iomode == NFSV3WRITE_FILESYNC before
1553                  * the block is reused. This is indicated by setting
1554                  * the B_DELWRI and B_NEEDCOMMIT flags.
1555                  *
1556                  * If the buffer is marked B_PAGING, it does not reside on
1557                  * the vp's paging queues so we cannot call bdirty().  The
1558                  * bp in this case is not an NFS cache block so we should
1559                  * be safe. XXX
1560                  */
1561                 if (error == EINTR
1562                     || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1563                         crit_enter();
1564                         bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1565                         if ((bp->b_flags & B_PAGING) == 0) {
1566                             bdirty(bp);
1567                             bp->b_flags &= ~B_DONE;
1568                         }
1569                         if (error && (bp->b_flags & B_ASYNC) == 0)
1570                             bp->b_flags |= B_EINTR;
1571                         crit_exit();
1572                 } else {
1573                     if (error) {
1574                         bp->b_flags |= B_ERROR;
1575                         bp->b_error = np->n_error = error;
1576                         np->n_flag |= NWRITEERR;
1577                     }
1578                     bp->b_dirtyoff = bp->b_dirtyend = 0;
1579                 }
1580             } else {
1581                 bp->b_resid = 0;
1582                 biodone(bio);
1583                 return (0);
1584             }
1585         }
1586         bp->b_resid = uiop->uio_resid;
1587         if (must_commit)
1588             nfs_clearcommit(vp->v_mount);
1589         biodone(bio);
1590         return (error);
1591 }
1592
1593 /*
1594  * Used to aid in handling ftruncate() operations on the NFS client side.
1595  * Truncation creates a number of special problems for NFS.  We have to
1596  * throw away VM pages and buffer cache buffers that are beyond EOF, and
1597  * we have to properly handle VM pages or (potentially dirty) buffers
1598  * that straddle the truncation point.
1599  */
1600
1601 int
1602 nfs_meta_setsize(struct vnode *vp, struct thread *td, u_quad_t nsize)
1603 {
1604         struct nfsnode *np = VTONFS(vp);
1605         u_quad_t tsize = np->n_size;
1606         int biosize = vp->v_mount->mnt_stat.f_iosize;
1607         int error = 0;
1608
1609         np->n_size = nsize;
1610
1611         if (np->n_size < tsize) {
1612                 struct buf *bp;
1613                 daddr_t lbn;
1614                 off_t loffset;
1615                 int bufsize;
1616
1617                 /*
1618                  * vtruncbuf() doesn't get the buffer overlapping the 
1619                  * truncation point.  We may have a B_DELWRI and/or B_CACHE
1620                  * buffer that now needs to be truncated.
1621                  */
1622                 error = vtruncbuf(vp, td, nsize, biosize);
1623                 lbn = nsize / biosize;
1624                 bufsize = nsize & (biosize - 1);
1625                 loffset = nsize - bufsize;
1626                 bp = nfs_getcacheblk(vp, loffset, bufsize, td);
1627                 if (bp->b_dirtyoff > bp->b_bcount)
1628                         bp->b_dirtyoff = bp->b_bcount;
1629                 if (bp->b_dirtyend > bp->b_bcount)
1630                         bp->b_dirtyend = bp->b_bcount;
1631                 bp->b_flags |= B_RELBUF;  /* don't leave garbage around */
1632                 brelse(bp);
1633         } else {
1634                 vnode_pager_setsize(vp, nsize);
1635         }
1636         return(error);
1637 }
1638