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