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