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