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