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