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