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