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