]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vnode_pager.c
Merge compiler-rt trunk r351319, and resolve conflicts.
[FreeBSD/FreeBSD.git] / sys / vm / vnode_pager.c
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1990 University of Utah.
5  * Copyright (c) 1991 The Regents of the University of California.
6  * All rights reserved.
7  * Copyright (c) 1993, 1994 John S. Dyson
8  * Copyright (c) 1995, David Greenman
9  *
10  * This code is derived from software contributed to Berkeley by
11  * the Systems Programming Group of the University of Utah Computer
12  * Science Department.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *      This product includes software developed by the University of
25  *      California, Berkeley and its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *      from: @(#)vnode_pager.c 7.5 (Berkeley) 4/20/91
43  */
44
45 /*
46  * Page to/from files (vnodes).
47  */
48
49 /*
50  * TODO:
51  *      Implement VOP_GETPAGES/PUTPAGES interface for filesystems. Will
52  *      greatly re-simplify the vnode_pager.
53  */
54
55 #include <sys/cdefs.h>
56 __FBSDID("$FreeBSD$");
57
58 #include "opt_vm.h"
59
60 #include <sys/param.h>
61 #include <sys/kernel.h>
62 #include <sys/systm.h>
63 #include <sys/sysctl.h>
64 #include <sys/proc.h>
65 #include <sys/vnode.h>
66 #include <sys/mount.h>
67 #include <sys/bio.h>
68 #include <sys/buf.h>
69 #include <sys/vmmeter.h>
70 #include <sys/limits.h>
71 #include <sys/conf.h>
72 #include <sys/rwlock.h>
73 #include <sys/sf_buf.h>
74 #include <sys/domainset.h>
75
76 #include <machine/atomic.h>
77
78 #include <vm/vm.h>
79 #include <vm/vm_param.h>
80 #include <vm/vm_object.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_pager.h>
83 #include <vm/vm_map.h>
84 #include <vm/vnode_pager.h>
85 #include <vm/vm_extern.h>
86 #include <vm/uma.h>
87
88 static int vnode_pager_addr(struct vnode *vp, vm_ooffset_t address,
89     daddr_t *rtaddress, int *run);
90 static int vnode_pager_input_smlfs(vm_object_t object, vm_page_t m);
91 static int vnode_pager_input_old(vm_object_t object, vm_page_t m);
92 static void vnode_pager_dealloc(vm_object_t);
93 static int vnode_pager_getpages(vm_object_t, vm_page_t *, int, int *, int *);
94 static int vnode_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
95     int *, vop_getpages_iodone_t, void *);
96 static void vnode_pager_putpages(vm_object_t, vm_page_t *, int, int, int *);
97 static boolean_t vnode_pager_haspage(vm_object_t, vm_pindex_t, int *, int *);
98 static vm_object_t vnode_pager_alloc(void *, vm_ooffset_t, vm_prot_t,
99     vm_ooffset_t, struct ucred *cred);
100 static int vnode_pager_generic_getpages_done(struct buf *);
101 static void vnode_pager_generic_getpages_done_async(struct buf *);
102
103 struct pagerops vnodepagerops = {
104         .pgo_alloc =    vnode_pager_alloc,
105         .pgo_dealloc =  vnode_pager_dealloc,
106         .pgo_getpages = vnode_pager_getpages,
107         .pgo_getpages_async = vnode_pager_getpages_async,
108         .pgo_putpages = vnode_pager_putpages,
109         .pgo_haspage =  vnode_pager_haspage,
110 };
111
112 static struct domainset *vnode_domainset = NULL;
113
114 SYSCTL_PROC(_debug, OID_AUTO, vnode_domainset, CTLTYPE_STRING | CTLFLAG_RW,
115     &vnode_domainset, 0, sysctl_handle_domainset, "A",
116     "Default vnode NUMA policy");
117
118 static uma_zone_t vnode_pbuf_zone;
119
120 static void
121 vnode_pager_init(void *dummy)
122 {
123
124         vnode_pbuf_zone = pbuf_zsecond_create("vnpbuf", nswbuf * 8);
125 }
126 SYSINIT(vnode_pager, SI_SUB_CPU, SI_ORDER_ANY, vnode_pager_init, NULL);
127
128 /* Create the VM system backing object for this vnode */
129 int
130 vnode_create_vobject(struct vnode *vp, off_t isize, struct thread *td)
131 {
132         vm_object_t object;
133         vm_ooffset_t size = isize;
134         struct vattr va;
135
136         if (!vn_isdisk(vp, NULL) && vn_canvmio(vp) == FALSE)
137                 return (0);
138
139         while ((object = vp->v_object) != NULL) {
140                 VM_OBJECT_WLOCK(object);
141                 if (!(object->flags & OBJ_DEAD)) {
142                         VM_OBJECT_WUNLOCK(object);
143                         return (0);
144                 }
145                 VOP_UNLOCK(vp, 0);
146                 vm_object_set_flag(object, OBJ_DISCONNECTWNT);
147                 VM_OBJECT_SLEEP(object, object, PDROP | PVM, "vodead", 0);
148                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
149         }
150
151         if (size == 0) {
152                 if (vn_isdisk(vp, NULL)) {
153                         size = IDX_TO_OFF(INT_MAX);
154                 } else {
155                         if (VOP_GETATTR(vp, &va, td->td_ucred))
156                                 return (0);
157                         size = va.va_size;
158                 }
159         }
160
161         object = vnode_pager_alloc(vp, size, 0, 0, td->td_ucred);
162         /*
163          * Dereference the reference we just created.  This assumes
164          * that the object is associated with the vp.
165          */
166         VM_OBJECT_WLOCK(object);
167         object->ref_count--;
168         VM_OBJECT_WUNLOCK(object);
169         vrele(vp);
170
171         KASSERT(vp->v_object != NULL, ("vnode_create_vobject: NULL object"));
172
173         return (0);
174 }
175
176 void
177 vnode_destroy_vobject(struct vnode *vp)
178 {
179         struct vm_object *obj;
180
181         obj = vp->v_object;
182         if (obj == NULL)
183                 return;
184         ASSERT_VOP_ELOCKED(vp, "vnode_destroy_vobject");
185         VM_OBJECT_WLOCK(obj);
186         umtx_shm_object_terminated(obj);
187         if (obj->ref_count == 0) {
188                 /*
189                  * don't double-terminate the object
190                  */
191                 if ((obj->flags & OBJ_DEAD) == 0) {
192                         vm_object_terminate(obj);
193                 } else {
194                         /*
195                          * Waiters were already handled during object
196                          * termination.  The exclusive vnode lock hopefully
197                          * prevented new waiters from referencing the dying
198                          * object.
199                          */
200                         KASSERT((obj->flags & OBJ_DISCONNECTWNT) == 0,
201                             ("OBJ_DISCONNECTWNT set obj %p flags %x",
202                             obj, obj->flags));
203                         vp->v_object = NULL;
204                         VM_OBJECT_WUNLOCK(obj);
205                 }
206         } else {
207                 /*
208                  * Woe to the process that tries to page now :-).
209                  */
210                 vm_pager_deallocate(obj);
211                 VM_OBJECT_WUNLOCK(obj);
212         }
213         KASSERT(vp->v_object == NULL, ("vp %p obj %p", vp, vp->v_object));
214 }
215
216
217 /*
218  * Allocate (or lookup) pager for a vnode.
219  * Handle is a vnode pointer.
220  *
221  * MPSAFE
222  */
223 vm_object_t
224 vnode_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
225     vm_ooffset_t offset, struct ucred *cred)
226 {
227         vm_object_t object;
228         struct vnode *vp;
229
230         /*
231          * Pageout to vnode, no can do yet.
232          */
233         if (handle == NULL)
234                 return (NULL);
235
236         vp = (struct vnode *) handle;
237
238         /*
239          * If the object is being terminated, wait for it to
240          * go away.
241          */
242 retry:
243         while ((object = vp->v_object) != NULL) {
244                 VM_OBJECT_WLOCK(object);
245                 if ((object->flags & OBJ_DEAD) == 0)
246                         break;
247                 vm_object_set_flag(object, OBJ_DISCONNECTWNT);
248                 VM_OBJECT_SLEEP(object, object, PDROP | PVM, "vadead", 0);
249         }
250
251         KASSERT(vp->v_usecount != 0, ("vnode_pager_alloc: no vnode reference"));
252
253         if (object == NULL) {
254                 /*
255                  * Add an object of the appropriate size
256                  */
257                 object = vm_object_allocate(OBJT_VNODE, OFF_TO_IDX(round_page(size)));
258
259                 object->un_pager.vnp.vnp_size = size;
260                 object->un_pager.vnp.writemappings = 0;
261                 object->domain.dr_policy = vnode_domainset;
262
263                 object->handle = handle;
264                 VI_LOCK(vp);
265                 if (vp->v_object != NULL) {
266                         /*
267                          * Object has been created while we were sleeping
268                          */
269                         VI_UNLOCK(vp);
270                         VM_OBJECT_WLOCK(object);
271                         KASSERT(object->ref_count == 1,
272                             ("leaked ref %p %d", object, object->ref_count));
273                         object->type = OBJT_DEAD;
274                         object->ref_count = 0;
275                         VM_OBJECT_WUNLOCK(object);
276                         vm_object_destroy(object);
277                         goto retry;
278                 }
279                 vp->v_object = object;
280                 VI_UNLOCK(vp);
281         } else {
282                 object->ref_count++;
283 #if VM_NRESERVLEVEL > 0
284                 vm_object_color(object, 0);
285 #endif
286                 VM_OBJECT_WUNLOCK(object);
287         }
288         vrefact(vp);
289         return (object);
290 }
291
292 /*
293  *      The object must be locked.
294  */
295 static void
296 vnode_pager_dealloc(vm_object_t object)
297 {
298         struct vnode *vp;
299         int refs;
300
301         vp = object->handle;
302         if (vp == NULL)
303                 panic("vnode_pager_dealloc: pager already dealloced");
304
305         VM_OBJECT_ASSERT_WLOCKED(object);
306         vm_object_pip_wait(object, "vnpdea");
307         refs = object->ref_count;
308
309         object->handle = NULL;
310         object->type = OBJT_DEAD;
311         if (object->flags & OBJ_DISCONNECTWNT) {
312                 vm_object_clear_flag(object, OBJ_DISCONNECTWNT);
313                 wakeup(object);
314         }
315         ASSERT_VOP_ELOCKED(vp, "vnode_pager_dealloc");
316         if (object->un_pager.vnp.writemappings > 0) {
317                 object->un_pager.vnp.writemappings = 0;
318                 VOP_ADD_WRITECOUNT(vp, -1);
319                 CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
320                     __func__, vp, vp->v_writecount);
321         }
322         vp->v_object = NULL;
323         VOP_UNSET_TEXT(vp);
324         VM_OBJECT_WUNLOCK(object);
325         while (refs-- > 0)
326                 vunref(vp);
327         VM_OBJECT_WLOCK(object);
328 }
329
330 static boolean_t
331 vnode_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
332     int *after)
333 {
334         struct vnode *vp = object->handle;
335         daddr_t bn;
336         int err;
337         daddr_t reqblock;
338         int poff;
339         int bsize;
340         int pagesperblock, blocksperpage;
341
342         VM_OBJECT_ASSERT_WLOCKED(object);
343         /*
344          * If no vp or vp is doomed or marked transparent to VM, we do not
345          * have the page.
346          */
347         if (vp == NULL || vp->v_iflag & VI_DOOMED)
348                 return FALSE;
349         /*
350          * If the offset is beyond end of file we do
351          * not have the page.
352          */
353         if (IDX_TO_OFF(pindex) >= object->un_pager.vnp.vnp_size)
354                 return FALSE;
355
356         bsize = vp->v_mount->mnt_stat.f_iosize;
357         pagesperblock = bsize / PAGE_SIZE;
358         blocksperpage = 0;
359         if (pagesperblock > 0) {
360                 reqblock = pindex / pagesperblock;
361         } else {
362                 blocksperpage = (PAGE_SIZE / bsize);
363                 reqblock = pindex * blocksperpage;
364         }
365         VM_OBJECT_WUNLOCK(object);
366         err = VOP_BMAP(vp, reqblock, NULL, &bn, after, before);
367         VM_OBJECT_WLOCK(object);
368         if (err)
369                 return TRUE;
370         if (bn == -1)
371                 return FALSE;
372         if (pagesperblock > 0) {
373                 poff = pindex - (reqblock * pagesperblock);
374                 if (before) {
375                         *before *= pagesperblock;
376                         *before += poff;
377                 }
378                 if (after) {
379                         /*
380                          * The BMAP vop can report a partial block in the
381                          * 'after', but must not report blocks after EOF.
382                          * Assert the latter, and truncate 'after' in case
383                          * of the former.
384                          */
385                         KASSERT((reqblock + *after) * pagesperblock <
386                             roundup2(object->size, pagesperblock),
387                             ("%s: reqblock %jd after %d size %ju", __func__,
388                             (intmax_t )reqblock, *after,
389                             (uintmax_t )object->size));
390                         *after *= pagesperblock;
391                         *after += pagesperblock - (poff + 1);
392                         if (pindex + *after >= object->size)
393                                 *after = object->size - 1 - pindex;
394                 }
395         } else {
396                 if (before) {
397                         *before /= blocksperpage;
398                 }
399
400                 if (after) {
401                         *after /= blocksperpage;
402                 }
403         }
404         return TRUE;
405 }
406
407 /*
408  * Lets the VM system know about a change in size for a file.
409  * We adjust our own internal size and flush any cached pages in
410  * the associated object that are affected by the size change.
411  *
412  * Note: this routine may be invoked as a result of a pager put
413  * operation (possibly at object termination time), so we must be careful.
414  */
415 void
416 vnode_pager_setsize(struct vnode *vp, vm_ooffset_t nsize)
417 {
418         vm_object_t object;
419         vm_page_t m;
420         vm_pindex_t nobjsize;
421
422         if ((object = vp->v_object) == NULL)
423                 return;
424 /*      ASSERT_VOP_ELOCKED(vp, "vnode_pager_setsize and not locked vnode"); */
425         VM_OBJECT_WLOCK(object);
426         if (object->type == OBJT_DEAD) {
427                 VM_OBJECT_WUNLOCK(object);
428                 return;
429         }
430         KASSERT(object->type == OBJT_VNODE,
431             ("not vnode-backed object %p", object));
432         if (nsize == object->un_pager.vnp.vnp_size) {
433                 /*
434                  * Hasn't changed size
435                  */
436                 VM_OBJECT_WUNLOCK(object);
437                 return;
438         }
439         nobjsize = OFF_TO_IDX(nsize + PAGE_MASK);
440         if (nsize < object->un_pager.vnp.vnp_size) {
441                 /*
442                  * File has shrunk. Toss any cached pages beyond the new EOF.
443                  */
444                 if (nobjsize < object->size)
445                         vm_object_page_remove(object, nobjsize, object->size,
446                             0);
447                 /*
448                  * this gets rid of garbage at the end of a page that is now
449                  * only partially backed by the vnode.
450                  *
451                  * XXX for some reason (I don't know yet), if we take a
452                  * completely invalid page and mark it partially valid
453                  * it can screw up NFS reads, so we don't allow the case.
454                  */
455                 if ((nsize & PAGE_MASK) &&
456                     (m = vm_page_lookup(object, OFF_TO_IDX(nsize))) != NULL &&
457                     m->valid != 0) {
458                         int base = (int)nsize & PAGE_MASK;
459                         int size = PAGE_SIZE - base;
460
461                         /*
462                          * Clear out partial-page garbage in case
463                          * the page has been mapped.
464                          */
465                         pmap_zero_page_area(m, base, size);
466
467                         /*
468                          * Update the valid bits to reflect the blocks that
469                          * have been zeroed.  Some of these valid bits may
470                          * have already been set.
471                          */
472                         vm_page_set_valid_range(m, base, size);
473
474                         /*
475                          * Round "base" to the next block boundary so that the
476                          * dirty bit for a partially zeroed block is not
477                          * cleared.
478                          */
479                         base = roundup2(base, DEV_BSIZE);
480
481                         /*
482                          * Clear out partial-page dirty bits.
483                          *
484                          * note that we do not clear out the valid
485                          * bits.  This would prevent bogus_page
486                          * replacement from working properly.
487                          */
488                         vm_page_clear_dirty(m, base, PAGE_SIZE - base);
489                 }
490         }
491         object->un_pager.vnp.vnp_size = nsize;
492         object->size = nobjsize;
493         VM_OBJECT_WUNLOCK(object);
494 }
495
496 /*
497  * calculate the linear (byte) disk address of specified virtual
498  * file address
499  */
500 static int
501 vnode_pager_addr(struct vnode *vp, vm_ooffset_t address, daddr_t *rtaddress,
502     int *run)
503 {
504         int bsize;
505         int err;
506         daddr_t vblock;
507         daddr_t voffset;
508
509         if (address < 0)
510                 return -1;
511
512         if (vp->v_iflag & VI_DOOMED)
513                 return -1;
514
515         bsize = vp->v_mount->mnt_stat.f_iosize;
516         vblock = address / bsize;
517         voffset = address % bsize;
518
519         err = VOP_BMAP(vp, vblock, NULL, rtaddress, run, NULL);
520         if (err == 0) {
521                 if (*rtaddress != -1)
522                         *rtaddress += voffset / DEV_BSIZE;
523                 if (run) {
524                         *run += 1;
525                         *run *= bsize/PAGE_SIZE;
526                         *run -= voffset/PAGE_SIZE;
527                 }
528         }
529
530         return (err);
531 }
532
533 /*
534  * small block filesystem vnode pager input
535  */
536 static int
537 vnode_pager_input_smlfs(vm_object_t object, vm_page_t m)
538 {
539         struct vnode *vp;
540         struct bufobj *bo;
541         struct buf *bp;
542         struct sf_buf *sf;
543         daddr_t fileaddr;
544         vm_offset_t bsize;
545         vm_page_bits_t bits;
546         int error, i;
547
548         error = 0;
549         vp = object->handle;
550         if (vp->v_iflag & VI_DOOMED)
551                 return VM_PAGER_BAD;
552
553         bsize = vp->v_mount->mnt_stat.f_iosize;
554
555         VOP_BMAP(vp, 0, &bo, 0, NULL, NULL);
556
557         sf = sf_buf_alloc(m, 0);
558
559         for (i = 0; i < PAGE_SIZE / bsize; i++) {
560                 vm_ooffset_t address;
561
562                 bits = vm_page_bits(i * bsize, bsize);
563                 if (m->valid & bits)
564                         continue;
565
566                 address = IDX_TO_OFF(m->pindex) + i * bsize;
567                 if (address >= object->un_pager.vnp.vnp_size) {
568                         fileaddr = -1;
569                 } else {
570                         error = vnode_pager_addr(vp, address, &fileaddr, NULL);
571                         if (error)
572                                 break;
573                 }
574                 if (fileaddr != -1) {
575                         bp = uma_zalloc(vnode_pbuf_zone, M_WAITOK);
576
577                         /* build a minimal buffer header */
578                         bp->b_iocmd = BIO_READ;
579                         bp->b_iodone = bdone;
580                         KASSERT(bp->b_rcred == NOCRED, ("leaking read ucred"));
581                         KASSERT(bp->b_wcred == NOCRED, ("leaking write ucred"));
582                         bp->b_rcred = crhold(curthread->td_ucred);
583                         bp->b_wcred = crhold(curthread->td_ucred);
584                         bp->b_data = (caddr_t)sf_buf_kva(sf) + i * bsize;
585                         bp->b_blkno = fileaddr;
586                         pbgetbo(bo, bp);
587                         bp->b_vp = vp;
588                         bp->b_bcount = bsize;
589                         bp->b_bufsize = bsize;
590                         bp->b_runningbufspace = bp->b_bufsize;
591                         atomic_add_long(&runningbufspace, bp->b_runningbufspace);
592
593                         /* do the input */
594                         bp->b_iooffset = dbtob(bp->b_blkno);
595                         bstrategy(bp);
596
597                         bwait(bp, PVM, "vnsrd");
598
599                         if ((bp->b_ioflags & BIO_ERROR) != 0)
600                                 error = EIO;
601
602                         /*
603                          * free the buffer header back to the swap buffer pool
604                          */
605                         bp->b_vp = NULL;
606                         pbrelbo(bp);
607                         uma_zfree(vnode_pbuf_zone, bp);
608                         if (error)
609                                 break;
610                 } else
611                         bzero((caddr_t)sf_buf_kva(sf) + i * bsize, bsize);
612                 KASSERT((m->dirty & bits) == 0,
613                     ("vnode_pager_input_smlfs: page %p is dirty", m));
614                 VM_OBJECT_WLOCK(object);
615                 m->valid |= bits;
616                 VM_OBJECT_WUNLOCK(object);
617         }
618         sf_buf_free(sf);
619         if (error) {
620                 return VM_PAGER_ERROR;
621         }
622         return VM_PAGER_OK;
623 }
624
625 /*
626  * old style vnode pager input routine
627  */
628 static int
629 vnode_pager_input_old(vm_object_t object, vm_page_t m)
630 {
631         struct uio auio;
632         struct iovec aiov;
633         int error;
634         int size;
635         struct sf_buf *sf;
636         struct vnode *vp;
637
638         VM_OBJECT_ASSERT_WLOCKED(object);
639         error = 0;
640
641         /*
642          * Return failure if beyond current EOF
643          */
644         if (IDX_TO_OFF(m->pindex) >= object->un_pager.vnp.vnp_size) {
645                 return VM_PAGER_BAD;
646         } else {
647                 size = PAGE_SIZE;
648                 if (IDX_TO_OFF(m->pindex) + size > object->un_pager.vnp.vnp_size)
649                         size = object->un_pager.vnp.vnp_size - IDX_TO_OFF(m->pindex);
650                 vp = object->handle;
651                 VM_OBJECT_WUNLOCK(object);
652
653                 /*
654                  * Allocate a kernel virtual address and initialize so that
655                  * we can use VOP_READ/WRITE routines.
656                  */
657                 sf = sf_buf_alloc(m, 0);
658
659                 aiov.iov_base = (caddr_t)sf_buf_kva(sf);
660                 aiov.iov_len = size;
661                 auio.uio_iov = &aiov;
662                 auio.uio_iovcnt = 1;
663                 auio.uio_offset = IDX_TO_OFF(m->pindex);
664                 auio.uio_segflg = UIO_SYSSPACE;
665                 auio.uio_rw = UIO_READ;
666                 auio.uio_resid = size;
667                 auio.uio_td = curthread;
668
669                 error = VOP_READ(vp, &auio, 0, curthread->td_ucred);
670                 if (!error) {
671                         int count = size - auio.uio_resid;
672
673                         if (count == 0)
674                                 error = EINVAL;
675                         else if (count != PAGE_SIZE)
676                                 bzero((caddr_t)sf_buf_kva(sf) + count,
677                                     PAGE_SIZE - count);
678                 }
679                 sf_buf_free(sf);
680
681                 VM_OBJECT_WLOCK(object);
682         }
683         KASSERT(m->dirty == 0, ("vnode_pager_input_old: page %p is dirty", m));
684         if (!error)
685                 m->valid = VM_PAGE_BITS_ALL;
686         return error ? VM_PAGER_ERROR : VM_PAGER_OK;
687 }
688
689 /*
690  * generic vnode pager input routine
691  */
692
693 /*
694  * Local media VFS's that do not implement their own VOP_GETPAGES
695  * should have their VOP_GETPAGES call to vnode_pager_generic_getpages()
696  * to implement the previous behaviour.
697  *
698  * All other FS's should use the bypass to get to the local media
699  * backing vp's VOP_GETPAGES.
700  */
701 static int
702 vnode_pager_getpages(vm_object_t object, vm_page_t *m, int count, int *rbehind,
703     int *rahead)
704 {
705         struct vnode *vp;
706         int rtval;
707
708         vp = object->handle;
709         VM_OBJECT_WUNLOCK(object);
710         rtval = VOP_GETPAGES(vp, m, count, rbehind, rahead);
711         KASSERT(rtval != EOPNOTSUPP,
712             ("vnode_pager: FS getpages not implemented\n"));
713         VM_OBJECT_WLOCK(object);
714         return rtval;
715 }
716
717 static int
718 vnode_pager_getpages_async(vm_object_t object, vm_page_t *m, int count,
719     int *rbehind, int *rahead, vop_getpages_iodone_t iodone, void *arg)
720 {
721         struct vnode *vp;
722         int rtval;
723
724         vp = object->handle;
725         VM_OBJECT_WUNLOCK(object);
726         rtval = VOP_GETPAGES_ASYNC(vp, m, count, rbehind, rahead, iodone, arg);
727         KASSERT(rtval != EOPNOTSUPP,
728             ("vnode_pager: FS getpages_async not implemented\n"));
729         VM_OBJECT_WLOCK(object);
730         return (rtval);
731 }
732
733 /*
734  * The implementation of VOP_GETPAGES() and VOP_GETPAGES_ASYNC() for
735  * local filesystems, where partially valid pages can only occur at
736  * the end of file.
737  */
738 int
739 vnode_pager_local_getpages(struct vop_getpages_args *ap)
740 {
741
742         return (vnode_pager_generic_getpages(ap->a_vp, ap->a_m, ap->a_count,
743             ap->a_rbehind, ap->a_rahead, NULL, NULL));
744 }
745
746 int
747 vnode_pager_local_getpages_async(struct vop_getpages_async_args *ap)
748 {
749
750         return (vnode_pager_generic_getpages(ap->a_vp, ap->a_m, ap->a_count,
751             ap->a_rbehind, ap->a_rahead, ap->a_iodone, ap->a_arg));
752 }
753
754 /*
755  * This is now called from local media FS's to operate against their
756  * own vnodes if they fail to implement VOP_GETPAGES.
757  */
758 int
759 vnode_pager_generic_getpages(struct vnode *vp, vm_page_t *m, int count,
760     int *a_rbehind, int *a_rahead, vop_getpages_iodone_t iodone, void *arg)
761 {
762         vm_object_t object;
763         struct bufobj *bo;
764         struct buf *bp;
765         off_t foff;
766 #ifdef INVARIANTS
767         off_t blkno0;
768 #endif
769         int bsize, pagesperblock;
770         int error, before, after, rbehind, rahead, poff, i;
771         int bytecount, secmask;
772
773         KASSERT(vp->v_type != VCHR && vp->v_type != VBLK,
774             ("%s does not support devices", __func__));
775
776         if (vp->v_iflag & VI_DOOMED)
777                 return (VM_PAGER_BAD);
778
779         object = vp->v_object;
780         foff = IDX_TO_OFF(m[0]->pindex);
781         bsize = vp->v_mount->mnt_stat.f_iosize;
782         pagesperblock = bsize / PAGE_SIZE;
783
784         KASSERT(foff < object->un_pager.vnp.vnp_size,
785             ("%s: page %p offset beyond vp %p size", __func__, m[0], vp));
786         KASSERT(count <= sizeof(bp->b_pages),
787             ("%s: requested %d pages", __func__, count));
788
789         /*
790          * The last page has valid blocks.  Invalid part can only
791          * exist at the end of file, and the page is made fully valid
792          * by zeroing in vm_pager_get_pages().
793          */
794         if (m[count - 1]->valid != 0 && --count == 0) {
795                 if (iodone != NULL)
796                         iodone(arg, m, 1, 0);
797                 return (VM_PAGER_OK);
798         }
799
800         bp = uma_zalloc(vnode_pbuf_zone, M_WAITOK);
801
802         /*
803          * Get the underlying device blocks for the file with VOP_BMAP().
804          * If the file system doesn't support VOP_BMAP, use old way of
805          * getting pages via VOP_READ.
806          */
807         error = VOP_BMAP(vp, foff / bsize, &bo, &bp->b_blkno, &after, &before);
808         if (error == EOPNOTSUPP) {
809                 uma_zfree(vnode_pbuf_zone, bp);
810                 VM_OBJECT_WLOCK(object);
811                 for (i = 0; i < count; i++) {
812                         VM_CNT_INC(v_vnodein);
813                         VM_CNT_INC(v_vnodepgsin);
814                         error = vnode_pager_input_old(object, m[i]);
815                         if (error)
816                                 break;
817                 }
818                 VM_OBJECT_WUNLOCK(object);
819                 return (error);
820         } else if (error != 0) {
821                 uma_zfree(vnode_pbuf_zone, bp);
822                 return (VM_PAGER_ERROR);
823         }
824
825         /*
826          * If the file system supports BMAP, but blocksize is smaller
827          * than a page size, then use special small filesystem code.
828          */
829         if (pagesperblock == 0) {
830                 uma_zfree(vnode_pbuf_zone, bp);
831                 for (i = 0; i < count; i++) {
832                         VM_CNT_INC(v_vnodein);
833                         VM_CNT_INC(v_vnodepgsin);
834                         error = vnode_pager_input_smlfs(object, m[i]);
835                         if (error)
836                                 break;
837                 }
838                 return (error);
839         }
840
841         /*
842          * A sparse file can be encountered only for a single page request,
843          * which may not be preceded by call to vm_pager_haspage().
844          */
845         if (bp->b_blkno == -1) {
846                 KASSERT(count == 1,
847                     ("%s: array[%d] request to a sparse file %p", __func__,
848                     count, vp));
849                 uma_zfree(vnode_pbuf_zone, bp);
850                 pmap_zero_page(m[0]);
851                 KASSERT(m[0]->dirty == 0, ("%s: page %p is dirty",
852                     __func__, m[0]));
853                 VM_OBJECT_WLOCK(object);
854                 m[0]->valid = VM_PAGE_BITS_ALL;
855                 VM_OBJECT_WUNLOCK(object);
856                 return (VM_PAGER_OK);
857         }
858
859 #ifdef INVARIANTS
860         blkno0 = bp->b_blkno;
861 #endif
862         bp->b_blkno += (foff % bsize) / DEV_BSIZE;
863
864         /* Recalculate blocks available after/before to pages. */
865         poff = (foff % bsize) / PAGE_SIZE;
866         before *= pagesperblock;
867         before += poff;
868         after *= pagesperblock;
869         after += pagesperblock - (poff + 1);
870         if (m[0]->pindex + after >= object->size)
871                 after = object->size - 1 - m[0]->pindex;
872         KASSERT(count <= after + 1, ("%s: %d pages asked, can do only %d",
873             __func__, count, after + 1));
874         after -= count - 1;
875
876         /* Trim requested rbehind/rahead to possible values. */   
877         rbehind = a_rbehind ? *a_rbehind : 0;
878         rahead = a_rahead ? *a_rahead : 0;
879         rbehind = min(rbehind, before);
880         rbehind = min(rbehind, m[0]->pindex);
881         rahead = min(rahead, after);
882         rahead = min(rahead, object->size - m[count - 1]->pindex);
883         /*
884          * Check that total amount of pages fit into buf.  Trim rbehind and
885          * rahead evenly if not.
886          */
887         if (rbehind + rahead + count > nitems(bp->b_pages)) {
888                 int trim, sum;
889
890                 trim = rbehind + rahead + count - nitems(bp->b_pages) + 1;
891                 sum = rbehind + rahead;
892                 if (rbehind == before) {
893                         /* Roundup rbehind trim to block size. */
894                         rbehind -= roundup(trim * rbehind / sum, pagesperblock);
895                         if (rbehind < 0)
896                                 rbehind = 0;
897                 } else
898                         rbehind -= trim * rbehind / sum;
899                 rahead -= trim * rahead / sum;
900         }
901         KASSERT(rbehind + rahead + count <= nitems(bp->b_pages),
902             ("%s: behind %d ahead %d count %d", __func__,
903             rbehind, rahead, count));
904
905         /*
906          * Fill in the bp->b_pages[] array with requested and optional   
907          * read behind or read ahead pages.  Read behind pages are looked
908          * up in a backward direction, down to a first cached page.  Same
909          * for read ahead pages, but there is no need to shift the array
910          * in case of encountering a cached page.
911          */
912         i = bp->b_npages = 0;
913         if (rbehind) {
914                 vm_pindex_t startpindex, tpindex;
915                 vm_page_t p;
916
917                 VM_OBJECT_WLOCK(object);
918                 startpindex = m[0]->pindex - rbehind;
919                 if ((p = TAILQ_PREV(m[0], pglist, listq)) != NULL &&
920                     p->pindex >= startpindex)
921                         startpindex = p->pindex + 1;
922
923                 /* tpindex is unsigned; beware of numeric underflow. */
924                 for (tpindex = m[0]->pindex - 1;
925                     tpindex >= startpindex && tpindex < m[0]->pindex;
926                     tpindex--, i++) {
927                         p = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
928                         if (p == NULL) {
929                                 /* Shift the array. */
930                                 for (int j = 0; j < i; j++)
931                                         bp->b_pages[j] = bp->b_pages[j + 
932                                             tpindex + 1 - startpindex]; 
933                                 break;
934                         }
935                         bp->b_pages[tpindex - startpindex] = p;
936                 }
937
938                 bp->b_pgbefore = i;
939                 bp->b_npages += i;
940                 bp->b_blkno -= IDX_TO_OFF(i) / DEV_BSIZE;
941         } else
942                 bp->b_pgbefore = 0;
943
944         /* Requested pages. */
945         for (int j = 0; j < count; j++, i++)
946                 bp->b_pages[i] = m[j];
947         bp->b_npages += count;
948
949         if (rahead) {
950                 vm_pindex_t endpindex, tpindex;
951                 vm_page_t p;
952
953                 if (!VM_OBJECT_WOWNED(object))
954                         VM_OBJECT_WLOCK(object);
955                 endpindex = m[count - 1]->pindex + rahead + 1;
956                 if ((p = TAILQ_NEXT(m[count - 1], listq)) != NULL &&
957                     p->pindex < endpindex)
958                         endpindex = p->pindex;
959                 if (endpindex > object->size)
960                         endpindex = object->size;
961
962                 for (tpindex = m[count - 1]->pindex + 1;
963                     tpindex < endpindex; i++, tpindex++) {
964                         p = vm_page_alloc(object, tpindex, VM_ALLOC_NORMAL);
965                         if (p == NULL)
966                                 break;
967                         bp->b_pages[i] = p;
968                 }
969
970                 bp->b_pgafter = i - bp->b_npages;
971                 bp->b_npages = i;
972         } else
973                 bp->b_pgafter = 0;
974
975         if (VM_OBJECT_WOWNED(object))
976                 VM_OBJECT_WUNLOCK(object);
977
978         /* Report back actual behind/ahead read. */
979         if (a_rbehind)
980                 *a_rbehind = bp->b_pgbefore;
981         if (a_rahead)
982                 *a_rahead = bp->b_pgafter;
983
984 #ifdef INVARIANTS
985         KASSERT(bp->b_npages <= nitems(bp->b_pages),
986             ("%s: buf %p overflowed", __func__, bp));
987         for (int j = 1, prev = 0; j < bp->b_npages; j++) {
988                 if (bp->b_pages[j] == bogus_page)
989                         continue;
990                 KASSERT(bp->b_pages[j]->pindex - bp->b_pages[prev]->pindex ==
991                     j - prev, ("%s: pages array not consecutive, bp %p",
992                      __func__, bp));
993                 prev = j;
994         }
995 #endif
996
997         /*
998          * Recalculate first offset and bytecount with regards to read behind.
999          * Truncate bytecount to vnode real size and round up physical size
1000          * for real devices.
1001          */
1002         foff = IDX_TO_OFF(bp->b_pages[0]->pindex);
1003         bytecount = bp->b_npages << PAGE_SHIFT;
1004         if ((foff + bytecount) > object->un_pager.vnp.vnp_size)
1005                 bytecount = object->un_pager.vnp.vnp_size - foff;
1006         secmask = bo->bo_bsize - 1;
1007         KASSERT(secmask < PAGE_SIZE && secmask > 0,
1008             ("%s: sector size %d too large", __func__, secmask + 1));
1009         bytecount = (bytecount + secmask) & ~secmask;
1010
1011         /*
1012          * And map the pages to be read into the kva, if the filesystem
1013          * requires mapped buffers.
1014          */
1015         if ((vp->v_mount->mnt_kern_flag & MNTK_UNMAPPED_BUFS) != 0 &&
1016             unmapped_buf_allowed) {
1017                 bp->b_data = unmapped_buf;
1018                 bp->b_offset = 0;
1019         } else {
1020                 bp->b_data = bp->b_kvabase;
1021                 pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages, bp->b_npages);
1022         }
1023
1024         /* Build a minimal buffer header. */
1025         bp->b_iocmd = BIO_READ;
1026         KASSERT(bp->b_rcred == NOCRED, ("leaking read ucred"));
1027         KASSERT(bp->b_wcred == NOCRED, ("leaking write ucred"));
1028         bp->b_rcred = crhold(curthread->td_ucred);
1029         bp->b_wcred = crhold(curthread->td_ucred);
1030         pbgetbo(bo, bp);
1031         bp->b_vp = vp;
1032         bp->b_bcount = bp->b_bufsize = bp->b_runningbufspace = bytecount;
1033         bp->b_iooffset = dbtob(bp->b_blkno);
1034         KASSERT(IDX_TO_OFF(m[0]->pindex - bp->b_pages[0]->pindex) ==
1035             (blkno0 - bp->b_blkno) * DEV_BSIZE +
1036             IDX_TO_OFF(m[0]->pindex) % bsize,
1037             ("wrong offsets bsize %d m[0] %ju b_pages[0] %ju "
1038             "blkno0 %ju b_blkno %ju", bsize,
1039             (uintmax_t)m[0]->pindex, (uintmax_t)bp->b_pages[0]->pindex,
1040             (uintmax_t)blkno0, (uintmax_t)bp->b_blkno));
1041
1042         atomic_add_long(&runningbufspace, bp->b_runningbufspace);
1043         VM_CNT_INC(v_vnodein);
1044         VM_CNT_ADD(v_vnodepgsin, bp->b_npages);
1045
1046         if (iodone != NULL) { /* async */
1047                 bp->b_pgiodone = iodone;
1048                 bp->b_caller1 = arg;
1049                 bp->b_iodone = vnode_pager_generic_getpages_done_async;
1050                 bp->b_flags |= B_ASYNC;
1051                 BUF_KERNPROC(bp);
1052                 bstrategy(bp);
1053                 return (VM_PAGER_OK);
1054         } else {
1055                 bp->b_iodone = bdone;
1056                 bstrategy(bp);
1057                 bwait(bp, PVM, "vnread");
1058                 error = vnode_pager_generic_getpages_done(bp);
1059                 for (i = 0; i < bp->b_npages; i++)
1060                         bp->b_pages[i] = NULL;
1061                 bp->b_vp = NULL;
1062                 pbrelbo(bp);
1063                 uma_zfree(vnode_pbuf_zone, bp);
1064                 return (error != 0 ? VM_PAGER_ERROR : VM_PAGER_OK);
1065         }
1066 }
1067
1068 static void
1069 vnode_pager_generic_getpages_done_async(struct buf *bp)
1070 {
1071         int error;
1072
1073         error = vnode_pager_generic_getpages_done(bp);
1074         /* Run the iodone upon the requested range. */
1075         bp->b_pgiodone(bp->b_caller1, bp->b_pages + bp->b_pgbefore,
1076             bp->b_npages - bp->b_pgbefore - bp->b_pgafter, error);
1077         for (int i = 0; i < bp->b_npages; i++)
1078                 bp->b_pages[i] = NULL;
1079         bp->b_vp = NULL;
1080         pbrelbo(bp);
1081         uma_zfree(vnode_pbuf_zone, bp);
1082 }
1083
1084 static int
1085 vnode_pager_generic_getpages_done(struct buf *bp)
1086 {
1087         vm_object_t object;
1088         off_t tfoff, nextoff;
1089         int i, error;
1090
1091         error = (bp->b_ioflags & BIO_ERROR) != 0 ? EIO : 0;
1092         object = bp->b_vp->v_object;
1093
1094         if (error == 0 && bp->b_bcount != bp->b_npages * PAGE_SIZE) {
1095                 if (!buf_mapped(bp)) {
1096                         bp->b_data = bp->b_kvabase;
1097                         pmap_qenter((vm_offset_t)bp->b_data, bp->b_pages,
1098                             bp->b_npages);
1099                 }
1100                 bzero(bp->b_data + bp->b_bcount,
1101                     PAGE_SIZE * bp->b_npages - bp->b_bcount);
1102         }
1103         if (buf_mapped(bp)) {
1104                 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1105                 bp->b_data = unmapped_buf;
1106         }
1107
1108         VM_OBJECT_WLOCK(object);
1109         for (i = 0, tfoff = IDX_TO_OFF(bp->b_pages[0]->pindex);
1110             i < bp->b_npages; i++, tfoff = nextoff) {
1111                 vm_page_t mt;
1112
1113                 nextoff = tfoff + PAGE_SIZE;
1114                 mt = bp->b_pages[i];
1115
1116                 if (nextoff <= object->un_pager.vnp.vnp_size) {
1117                         /*
1118                          * Read filled up entire page.
1119                          */
1120                         mt->valid = VM_PAGE_BITS_ALL;
1121                         KASSERT(mt->dirty == 0,
1122                             ("%s: page %p is dirty", __func__, mt));
1123                         KASSERT(!pmap_page_is_mapped(mt),
1124                             ("%s: page %p is mapped", __func__, mt));
1125                 } else {
1126                         /*
1127                          * Read did not fill up entire page.
1128                          *
1129                          * Currently we do not set the entire page valid,
1130                          * we just try to clear the piece that we couldn't
1131                          * read.
1132                          */
1133                         vm_page_set_valid_range(mt, 0,
1134                             object->un_pager.vnp.vnp_size - tfoff);
1135                         KASSERT((mt->dirty & vm_page_bits(0,
1136                             object->un_pager.vnp.vnp_size - tfoff)) == 0,
1137                             ("%s: page %p is dirty", __func__, mt));
1138                 }
1139
1140                 if (i < bp->b_pgbefore || i >= bp->b_npages - bp->b_pgafter)
1141                         vm_page_readahead_finish(mt);
1142         }
1143         VM_OBJECT_WUNLOCK(object);
1144         if (error != 0)
1145                 printf("%s: I/O read error %d\n", __func__, error);
1146
1147         return (error);
1148 }
1149
1150 /*
1151  * EOPNOTSUPP is no longer legal.  For local media VFS's that do not
1152  * implement their own VOP_PUTPAGES, their VOP_PUTPAGES should call to
1153  * vnode_pager_generic_putpages() to implement the previous behaviour.
1154  *
1155  * All other FS's should use the bypass to get to the local media
1156  * backing vp's VOP_PUTPAGES.
1157  */
1158 static void
1159 vnode_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1160     int flags, int *rtvals)
1161 {
1162         int rtval;
1163         struct vnode *vp;
1164         int bytes = count * PAGE_SIZE;
1165
1166         /*
1167          * Force synchronous operation if we are extremely low on memory
1168          * to prevent a low-memory deadlock.  VOP operations often need to
1169          * allocate more memory to initiate the I/O ( i.e. do a BMAP
1170          * operation ).  The swapper handles the case by limiting the amount
1171          * of asynchronous I/O, but that sort of solution doesn't scale well
1172          * for the vnode pager without a lot of work.
1173          *
1174          * Also, the backing vnode's iodone routine may not wake the pageout
1175          * daemon up.  This should be probably be addressed XXX.
1176          */
1177
1178         if (vm_page_count_min())
1179                 flags |= VM_PAGER_PUT_SYNC;
1180
1181         /*
1182          * Call device-specific putpages function
1183          */
1184         vp = object->handle;
1185         VM_OBJECT_WUNLOCK(object);
1186         rtval = VOP_PUTPAGES(vp, m, bytes, flags, rtvals);
1187         KASSERT(rtval != EOPNOTSUPP, 
1188             ("vnode_pager: stale FS putpages\n"));
1189         VM_OBJECT_WLOCK(object);
1190 }
1191
1192 static int
1193 vn_off2bidx(vm_ooffset_t offset)
1194 {
1195
1196         return ((offset & PAGE_MASK) / DEV_BSIZE);
1197 }
1198
1199 static bool
1200 vn_dirty_blk(vm_page_t m, vm_ooffset_t offset)
1201 {
1202
1203         KASSERT(IDX_TO_OFF(m->pindex) <= offset &&
1204             offset < IDX_TO_OFF(m->pindex + 1),
1205             ("page %p pidx %ju offset %ju", m, (uintmax_t)m->pindex,
1206             (uintmax_t)offset));
1207         return ((m->dirty & ((vm_page_bits_t)1 << vn_off2bidx(offset))) != 0);
1208 }
1209
1210 /*
1211  * This is now called from local media FS's to operate against their
1212  * own vnodes if they fail to implement VOP_PUTPAGES.
1213  *
1214  * This is typically called indirectly via the pageout daemon and
1215  * clustering has already typically occurred, so in general we ask the
1216  * underlying filesystem to write the data out asynchronously rather
1217  * then delayed.
1218  */
1219 int
1220 vnode_pager_generic_putpages(struct vnode *vp, vm_page_t *ma, int bytecount,
1221     int flags, int *rtvals)
1222 {
1223         vm_object_t object;
1224         vm_page_t m;
1225         vm_ooffset_t maxblksz, next_offset, poffset, prev_offset;
1226         struct uio auio;
1227         struct iovec aiov;
1228         off_t prev_resid, wrsz;
1229         int count, error, i, maxsize, ncount, pgoff, ppscheck;
1230         bool in_hole;
1231         static struct timeval lastfail;
1232         static int curfail;
1233
1234         object = vp->v_object;
1235         count = bytecount / PAGE_SIZE;
1236
1237         for (i = 0; i < count; i++)
1238                 rtvals[i] = VM_PAGER_ERROR;
1239
1240         if ((int64_t)ma[0]->pindex < 0) {
1241                 printf("vnode_pager_generic_putpages: "
1242                     "attempt to write meta-data 0x%jx(%lx)\n",
1243                     (uintmax_t)ma[0]->pindex, (u_long)ma[0]->dirty);
1244                 rtvals[0] = VM_PAGER_BAD;
1245                 return (VM_PAGER_BAD);
1246         }
1247
1248         maxsize = count * PAGE_SIZE;
1249         ncount = count;
1250
1251         poffset = IDX_TO_OFF(ma[0]->pindex);
1252
1253         /*
1254          * If the page-aligned write is larger then the actual file we
1255          * have to invalidate pages occurring beyond the file EOF.  However,
1256          * there is an edge case where a file may not be page-aligned where
1257          * the last page is partially invalid.  In this case the filesystem
1258          * may not properly clear the dirty bits for the entire page (which
1259          * could be VM_PAGE_BITS_ALL due to the page having been mmap()d).
1260          * With the page locked we are free to fix-up the dirty bits here.
1261          *
1262          * We do not under any circumstances truncate the valid bits, as
1263          * this will screw up bogus page replacement.
1264          */
1265         VM_OBJECT_RLOCK(object);
1266         if (maxsize + poffset > object->un_pager.vnp.vnp_size) {
1267                 if (!VM_OBJECT_TRYUPGRADE(object)) {
1268                         VM_OBJECT_RUNLOCK(object);
1269                         VM_OBJECT_WLOCK(object);
1270                         if (maxsize + poffset <= object->un_pager.vnp.vnp_size)
1271                                 goto downgrade;
1272                 }
1273                 if (object->un_pager.vnp.vnp_size > poffset) {
1274                         maxsize = object->un_pager.vnp.vnp_size - poffset;
1275                         ncount = btoc(maxsize);
1276                         if ((pgoff = (int)maxsize & PAGE_MASK) != 0) {
1277                                 pgoff = roundup2(pgoff, DEV_BSIZE);
1278
1279                                 /*
1280                                  * If the object is locked and the following
1281                                  * conditions hold, then the page's dirty
1282                                  * field cannot be concurrently changed by a
1283                                  * pmap operation.
1284                                  */
1285                                 m = ma[ncount - 1];
1286                                 vm_page_assert_sbusied(m);
1287                                 KASSERT(!pmap_page_is_write_mapped(m),
1288                 ("vnode_pager_generic_putpages: page %p is not read-only", m));
1289                                 MPASS(m->dirty != 0);
1290                                 vm_page_clear_dirty(m, pgoff, PAGE_SIZE -
1291                                     pgoff);
1292                         }
1293                 } else {
1294                         maxsize = 0;
1295                         ncount = 0;
1296                 }
1297                 for (i = ncount; i < count; i++)
1298                         rtvals[i] = VM_PAGER_BAD;
1299 downgrade:
1300                 VM_OBJECT_LOCK_DOWNGRADE(object);
1301         }
1302
1303         auio.uio_iov = &aiov;
1304         auio.uio_segflg = UIO_NOCOPY;
1305         auio.uio_rw = UIO_WRITE;
1306         auio.uio_td = NULL;
1307         maxblksz = roundup2(poffset + maxsize, DEV_BSIZE);
1308
1309         for (prev_offset = poffset; prev_offset < maxblksz;) {
1310                 /* Skip clean blocks. */
1311                 for (in_hole = true; in_hole && prev_offset < maxblksz;) {
1312                         m = ma[OFF_TO_IDX(prev_offset - poffset)];
1313                         for (i = vn_off2bidx(prev_offset);
1314                             i < sizeof(vm_page_bits_t) * NBBY &&
1315                             prev_offset < maxblksz; i++) {
1316                                 if (vn_dirty_blk(m, prev_offset)) {
1317                                         in_hole = false;
1318                                         break;
1319                                 }
1320                                 prev_offset += DEV_BSIZE;
1321                         }
1322                 }
1323                 if (in_hole)
1324                         goto write_done;
1325
1326                 /* Find longest run of dirty blocks. */
1327                 for (next_offset = prev_offset; next_offset < maxblksz;) {
1328                         m = ma[OFF_TO_IDX(next_offset - poffset)];
1329                         for (i = vn_off2bidx(next_offset);
1330                             i < sizeof(vm_page_bits_t) * NBBY &&
1331                             next_offset < maxblksz; i++) {
1332                                 if (!vn_dirty_blk(m, next_offset))
1333                                         goto start_write;
1334                                 next_offset += DEV_BSIZE;
1335                         }
1336                 }
1337 start_write:
1338                 if (next_offset > poffset + maxsize)
1339                         next_offset = poffset + maxsize;
1340
1341                 /*
1342                  * Getting here requires finding a dirty block in the
1343                  * 'skip clean blocks' loop.
1344                  */
1345                 MPASS(prev_offset < next_offset);
1346
1347                 VM_OBJECT_RUNLOCK(object);
1348                 aiov.iov_base = NULL;
1349                 auio.uio_iovcnt = 1;
1350                 auio.uio_offset = prev_offset;
1351                 prev_resid = auio.uio_resid = aiov.iov_len = next_offset -
1352                     prev_offset;
1353                 error = VOP_WRITE(vp, &auio,
1354                     vnode_pager_putpages_ioflags(flags), curthread->td_ucred);
1355
1356                 wrsz = prev_resid - auio.uio_resid;
1357                 if (wrsz == 0) {
1358                         if (ppsratecheck(&lastfail, &curfail, 1) != 0) {
1359                                 vn_printf(vp, "vnode_pager_putpages: "
1360                                     "zero-length write at %ju resid %zd\n",
1361                                     auio.uio_offset, auio.uio_resid);
1362                         }
1363                         VM_OBJECT_RLOCK(object);
1364                         break;
1365                 }
1366
1367                 /* Adjust the starting offset for next iteration. */
1368                 prev_offset += wrsz;
1369                 MPASS(auio.uio_offset == prev_offset);
1370
1371                 ppscheck = 0;
1372                 if (error != 0 && (ppscheck = ppsratecheck(&lastfail,
1373                     &curfail, 1)) != 0)
1374                         vn_printf(vp, "vnode_pager_putpages: I/O error %d\n",
1375                             error);
1376                 if (auio.uio_resid != 0 && (ppscheck != 0 ||
1377                     ppsratecheck(&lastfail, &curfail, 1) != 0))
1378                         vn_printf(vp, "vnode_pager_putpages: residual I/O %zd "
1379                             "at %ju\n", auio.uio_resid,
1380                             (uintmax_t)ma[0]->pindex);
1381                 VM_OBJECT_RLOCK(object);
1382                 if (error != 0 || auio.uio_resid != 0)
1383                         break;
1384         }
1385 write_done:
1386         /* Mark completely processed pages. */
1387         for (i = 0; i < OFF_TO_IDX(prev_offset - poffset); i++)
1388                 rtvals[i] = VM_PAGER_OK;
1389         /* Mark partial EOF page. */
1390         if (prev_offset == poffset + maxsize && (prev_offset & PAGE_MASK) != 0)
1391                 rtvals[i++] = VM_PAGER_OK;
1392         /* Unwritten pages in range, free bonus if the page is clean. */
1393         for (; i < ncount; i++)
1394                 rtvals[i] = ma[i]->dirty == 0 ? VM_PAGER_OK : VM_PAGER_ERROR;
1395         VM_OBJECT_RUNLOCK(object);
1396         VM_CNT_ADD(v_vnodepgsout, i);
1397         VM_CNT_INC(v_vnodeout);
1398         return (rtvals[0]);
1399 }
1400
1401 int
1402 vnode_pager_putpages_ioflags(int pager_flags)
1403 {
1404         int ioflags;
1405
1406         /*
1407          * Pageouts are already clustered, use IO_ASYNC to force a
1408          * bawrite() rather then a bdwrite() to prevent paging I/O
1409          * from saturating the buffer cache.  Dummy-up the sequential
1410          * heuristic to cause large ranges to cluster.  If neither
1411          * IO_SYNC or IO_ASYNC is set, the system decides how to
1412          * cluster.
1413          */
1414         ioflags = IO_VMIO;
1415         if ((pager_flags & (VM_PAGER_PUT_SYNC | VM_PAGER_PUT_INVAL)) != 0)
1416                 ioflags |= IO_SYNC;
1417         else if ((pager_flags & VM_PAGER_CLUSTER_OK) == 0)
1418                 ioflags |= IO_ASYNC;
1419         ioflags |= (pager_flags & VM_PAGER_PUT_INVAL) != 0 ? IO_INVAL: 0;
1420         ioflags |= (pager_flags & VM_PAGER_PUT_NOREUSE) != 0 ? IO_NOREUSE : 0;
1421         ioflags |= IO_SEQMAX << IO_SEQSHIFT;
1422         return (ioflags);
1423 }
1424
1425 /*
1426  * vnode_pager_undirty_pages().
1427  *
1428  * A helper to mark pages as clean after pageout that was possibly
1429  * done with a short write.  The lpos argument specifies the page run
1430  * length in bytes, and the written argument specifies how many bytes
1431  * were actually written.  eof is the offset past the last valid byte
1432  * in the vnode using the absolute file position of the first byte in
1433  * the run as the base from which it is computed.
1434  */
1435 void
1436 vnode_pager_undirty_pages(vm_page_t *ma, int *rtvals, int written, off_t eof,
1437     int lpos)
1438 {
1439         vm_object_t obj;
1440         int i, pos, pos_devb;
1441
1442         if (written == 0 && eof >= lpos)
1443                 return;
1444         obj = ma[0]->object;
1445         VM_OBJECT_WLOCK(obj);
1446         for (i = 0, pos = 0; pos < written; i++, pos += PAGE_SIZE) {
1447                 if (pos < trunc_page(written)) {
1448                         rtvals[i] = VM_PAGER_OK;
1449                         vm_page_undirty(ma[i]);
1450                 } else {
1451                         /* Partially written page. */
1452                         rtvals[i] = VM_PAGER_AGAIN;
1453                         vm_page_clear_dirty(ma[i], 0, written & PAGE_MASK);
1454                 }
1455         }
1456         if (eof >= lpos) /* avoid truncation */
1457                 goto done;
1458         for (pos = eof, i = OFF_TO_IDX(trunc_page(pos)); pos < lpos; i++) {
1459                 if (pos != trunc_page(pos)) {
1460                         /*
1461                          * The page contains the last valid byte in
1462                          * the vnode, mark the rest of the page as
1463                          * clean, potentially making the whole page
1464                          * clean.
1465                          */
1466                         pos_devb = roundup2(pos & PAGE_MASK, DEV_BSIZE);
1467                         vm_page_clear_dirty(ma[i], pos_devb, PAGE_SIZE -
1468                             pos_devb);
1469
1470                         /*
1471                          * If the page was cleaned, report the pageout
1472                          * on it as successful.  msync() no longer
1473                          * needs to write out the page, endlessly
1474                          * creating write requests and dirty buffers.
1475                          */
1476                         if (ma[i]->dirty == 0)
1477                                 rtvals[i] = VM_PAGER_OK;
1478
1479                         pos = round_page(pos);
1480                 } else {
1481                         /* vm_pageout_flush() clears dirty */
1482                         rtvals[i] = VM_PAGER_BAD;
1483                         pos += PAGE_SIZE;
1484                 }
1485         }
1486 done:
1487         VM_OBJECT_WUNLOCK(obj);
1488 }
1489
1490 void
1491 vnode_pager_update_writecount(vm_object_t object, vm_offset_t start,
1492     vm_offset_t end)
1493 {
1494         struct vnode *vp;
1495         vm_ooffset_t old_wm;
1496
1497         VM_OBJECT_WLOCK(object);
1498         if (object->type != OBJT_VNODE) {
1499                 VM_OBJECT_WUNLOCK(object);
1500                 return;
1501         }
1502         old_wm = object->un_pager.vnp.writemappings;
1503         object->un_pager.vnp.writemappings += (vm_ooffset_t)end - start;
1504         vp = object->handle;
1505         if (old_wm == 0 && object->un_pager.vnp.writemappings != 0) {
1506                 ASSERT_VOP_ELOCKED(vp, "v_writecount inc");
1507                 VOP_ADD_WRITECOUNT(vp, 1);
1508                 CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
1509                     __func__, vp, vp->v_writecount);
1510         } else if (old_wm != 0 && object->un_pager.vnp.writemappings == 0) {
1511                 ASSERT_VOP_ELOCKED(vp, "v_writecount dec");
1512                 VOP_ADD_WRITECOUNT(vp, -1);
1513                 CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
1514                     __func__, vp, vp->v_writecount);
1515         }
1516         VM_OBJECT_WUNLOCK(object);
1517 }
1518
1519 void
1520 vnode_pager_release_writecount(vm_object_t object, vm_offset_t start,
1521     vm_offset_t end)
1522 {
1523         struct vnode *vp;
1524         struct mount *mp;
1525         vm_offset_t inc;
1526
1527         VM_OBJECT_WLOCK(object);
1528
1529         /*
1530          * First, recheck the object type to account for the race when
1531          * the vnode is reclaimed.
1532          */
1533         if (object->type != OBJT_VNODE) {
1534                 VM_OBJECT_WUNLOCK(object);
1535                 return;
1536         }
1537
1538         /*
1539          * Optimize for the case when writemappings is not going to
1540          * zero.
1541          */
1542         inc = end - start;
1543         if (object->un_pager.vnp.writemappings != inc) {
1544                 object->un_pager.vnp.writemappings -= inc;
1545                 VM_OBJECT_WUNLOCK(object);
1546                 return;
1547         }
1548
1549         vp = object->handle;
1550         vhold(vp);
1551         VM_OBJECT_WUNLOCK(object);
1552         mp = NULL;
1553         vn_start_write(vp, &mp, V_WAIT);
1554         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1555
1556         /*
1557          * Decrement the object's writemappings, by swapping the start
1558          * and end arguments for vnode_pager_update_writecount().  If
1559          * there was not a race with vnode reclaimation, then the
1560          * vnode's v_writecount is decremented.
1561          */
1562         vnode_pager_update_writecount(object, end, start);
1563         VOP_UNLOCK(vp, 0);
1564         vdrop(vp);
1565         if (mp != NULL)
1566                 vn_finished_write(mp);
1567 }