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