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