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