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