Correct BSD License clause numbering from 1-2-4 to 1-2-3.
[dragonfly.git] / sys / vm / vnode_pager.c
1 /*
2  * (MPSAFE)
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. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      from: @(#)vnode_pager.c 7.5 (Berkeley) 4/20/91
39  * $FreeBSD: src/sys/vm/vnode_pager.c,v 1.116.2.7 2002/12/31 09:34:51 dillon Exp $
40  */
41
42 /*
43  * Page to/from files (vnodes).
44  */
45
46 /*
47  * TODO:
48  *      Implement VOP_GETPAGES/PUTPAGES interface for filesystems. Will
49  *      greatly re-simplify the vnode_pager.
50  */
51
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/kernel.h>
55 #include <sys/proc.h>
56 #include <sys/vnode.h>
57 #include <sys/mount.h>
58 #include <sys/buf.h>
59 #include <sys/vmmeter.h>
60 #include <sys/conf.h>
61
62 #include <cpu/lwbuf.h>
63
64 #include <vm/vm.h>
65 #include <vm/vm_object.h>
66 #include <vm/vm_page.h>
67 #include <vm/vm_pager.h>
68 #include <vm/vm_map.h>
69 #include <vm/vnode_pager.h>
70 #include <vm/swap_pager.h>
71 #include <vm/vm_extern.h>
72
73 #include <sys/thread2.h>
74 #include <vm/vm_page2.h>
75
76 static void vnode_pager_dealloc (vm_object_t);
77 static int vnode_pager_getpage (vm_object_t, vm_page_t *, int);
78 static void vnode_pager_putpages (vm_object_t, vm_page_t *, int, boolean_t, int *);
79 static boolean_t vnode_pager_haspage (vm_object_t, vm_pindex_t);
80
81 struct pagerops vnodepagerops = {
82         vnode_pager_dealloc,
83         vnode_pager_getpage,
84         vnode_pager_putpages,
85         vnode_pager_haspage
86 };
87
88 static struct krate vbadrate = { 1 };
89 static struct krate vresrate = { 1 };
90
91 long vnode_pbuf_freecnt = -1;   /* start out unlimited */
92
93 /*
94  * Allocate a VM object for a vnode, typically a regular file vnode.
95  *
96  * Some additional information is required to generate a properly sized
97  * object which covers the entire buffer cache buffer straddling the file
98  * EOF.  Userland does not see the extra pages as the VM fault code tests
99  * against v_filesize.
100  */
101 vm_object_t
102 vnode_pager_alloc(void *handle, off_t length, vm_prot_t prot, off_t offset,
103                   int blksize, int boff)
104 {
105         vm_object_t object;
106         struct vnode *vp;
107         off_t loffset;
108         vm_pindex_t lsize;
109
110         /*
111          * Pageout to vnode, no can do yet.
112          */
113         if (handle == NULL)
114                 return (NULL);
115
116         /*
117          * XXX hack - This initialization should be put somewhere else.
118          */
119         if (vnode_pbuf_freecnt < 0) {
120             vnode_pbuf_freecnt = nswbuf / 2 + 1;
121         }
122
123         /*
124          * Serialize potential vnode/object teardowns and interlocks
125          */
126         vp = (struct vnode *)handle;
127         lwkt_gettoken(&vp->v_token);
128
129         /*
130          * Prevent race condition when allocating the object. This
131          * can happen with NFS vnodes since the nfsnode isn't locked.
132          */
133         while (vp->v_flag & VOLOCK) {
134                 vsetflags(vp, VOWANT);
135                 tsleep(vp, 0, "vnpobj", 0);
136         }
137         vsetflags(vp, VOLOCK);
138         lwkt_reltoken(&vp->v_token);
139
140         /*
141          * If the object is being terminated, wait for it to
142          * go away.
143          */
144         while ((object = vp->v_object) != NULL) {
145                 vm_object_hold(object);
146                 if ((object->flags & OBJ_DEAD) == 0)
147                         break;
148                 vm_object_dead_sleep(object, "vadead");
149                 vm_object_drop(object);
150         }
151
152         if (vp->v_sysref.refcnt <= 0)
153                 panic("vnode_pager_alloc: no vnode reference");
154
155         /*
156          * Round up to the *next* block, then destroy the buffers in question.
157          * Since we are only removing some of the buffers we must rely on the
158          * scan count to determine whether a loop is necessary.
159          *
160          * Destroy any pages beyond the last buffer.
161          */
162         if (boff < 0)
163                 boff = (int)(length % blksize);
164         if (boff)
165                 loffset = length + (blksize - boff);
166         else
167                 loffset = length;
168         lsize = OFF_TO_IDX(round_page64(loffset));
169
170         if (object == NULL) {
171                 /*
172                  * And an object of the appropriate size
173                  */
174                 object = vm_object_allocate_hold(OBJT_VNODE, lsize);
175                 object->handle = handle;
176                 vp->v_object = object;
177                 vp->v_filesize = length;
178                 if (vp->v_mount && (vp->v_mount->mnt_kern_flag & MNTK_NOMSYNC))
179                         vm_object_set_flag(object, OBJ_NOMSYNC);
180         } else {
181                 object->ref_count++;
182                 if (object->size != lsize) {
183                         kprintf("vnode_pager_alloc: Warning, objsize "
184                                 "mismatch %jd/%jd vp=%p obj=%p\n",
185                                 (intmax_t)object->size,
186                                 (intmax_t)lsize,
187                                 vp, object);
188                 }
189                 if (vp->v_filesize != length) {
190                         kprintf("vnode_pager_alloc: Warning, filesize "
191                                 "mismatch %jd/%jd vp=%p obj=%p\n",
192                                 (intmax_t)vp->v_filesize,
193                                 (intmax_t)length,
194                                 vp, object);
195                 }
196         }
197
198         vref(vp);
199         lwkt_gettoken(&vp->v_token);
200         vclrflags(vp, VOLOCK);
201         if (vp->v_flag & VOWANT) {
202                 vclrflags(vp, VOWANT);
203                 wakeup(vp);
204         }
205         lwkt_reltoken(&vp->v_token);
206
207         vm_object_drop(object);
208
209         return (object);
210 }
211
212 /*
213  * Add a ref to a vnode's existing VM object, return the object or
214  * NULL if the vnode did not have one.  This does not create the
215  * object (we can't since we don't know what the proper blocksize/boff
216  * is to match the VFS's use of the buffer cache).
217  */
218 vm_object_t
219 vnode_pager_reference(struct vnode *vp)
220 {
221         vm_object_t object;
222
223         /*
224          * Prevent race condition when allocating the object. This
225          * can happen with NFS vnodes since the nfsnode isn't locked.
226          *
227          * Serialize potential vnode/object teardowns and interlocks
228          */
229         lwkt_gettoken(&vp->v_token);
230         while (vp->v_flag & VOLOCK) {
231                 vsetflags(vp, VOWANT);
232                 tsleep(vp, 0, "vnpobj", 0);
233         }
234         vsetflags(vp, VOLOCK);
235         lwkt_reltoken(&vp->v_token);
236
237         /*
238          * Prevent race conditions against deallocation of the VM
239          * object.
240          */
241         while ((object = vp->v_object) != NULL) {
242                 vm_object_hold(object);
243                 if ((object->flags & OBJ_DEAD) == 0)
244                         break;
245                 vm_object_dead_sleep(object, "vadead");
246                 vm_object_drop(object);
247         }
248
249         /*
250          * The object is expected to exist, the caller will handle
251          * NULL returns if it does not.
252          */
253         if (object) {
254                 object->ref_count++;
255                 vref(vp);
256         }
257
258         lwkt_gettoken(&vp->v_token);
259         vclrflags(vp, VOLOCK);
260         if (vp->v_flag & VOWANT) {
261                 vclrflags(vp, VOWANT);
262                 wakeup(vp);
263         }
264         lwkt_reltoken(&vp->v_token);
265         if (object)
266                 vm_object_drop(object);
267
268         return (object);
269 }
270
271 static void
272 vnode_pager_dealloc(vm_object_t object)
273 {
274         struct vnode *vp = object->handle;
275
276         if (vp == NULL)
277                 panic("vnode_pager_dealloc: pager already dealloced");
278
279         vm_object_pip_wait(object, "vnpdea");
280
281         object->handle = NULL;
282         object->type = OBJT_DEAD;
283         vp->v_object = NULL;
284         vp->v_filesize = NOOFFSET;
285         vclrflags(vp, VTEXT | VOBJBUF);
286         swap_pager_freespace_all(object);
287 }
288
289 /*
290  * Return whether the vnode pager has the requested page.  Return the
291  * number of disk-contiguous pages before and after the requested page,
292  * not including the requested page.
293  */
294 static boolean_t
295 vnode_pager_haspage(vm_object_t object, vm_pindex_t pindex)
296 {
297         struct vnode *vp = object->handle;
298         off_t loffset;
299         off_t doffset;
300         int voff;
301         int bsize;
302         int error;
303
304         /*
305          * If no vp or vp is doomed or marked transparent to VM, we do not
306          * have the page.
307          */
308         if ((vp == NULL) || (vp->v_flag & VRECLAIMED))
309                 return FALSE;
310
311         /*
312          * If filesystem no longer mounted or offset beyond end of file we do
313          * not have the page.
314          */
315         loffset = IDX_TO_OFF(pindex);
316
317         if (vp->v_mount == NULL || loffset >= vp->v_filesize)
318                 return FALSE;
319
320         bsize = vp->v_mount->mnt_stat.f_iosize;
321         voff = loffset % bsize;
322
323         /*
324          * XXX
325          *
326          * BMAP returns byte counts before and after, where after
327          * is inclusive of the base page.  haspage must return page
328          * counts before and after where after does not include the
329          * base page.
330          *
331          * BMAP is allowed to return a *after of 0 for backwards
332          * compatibility.  The base page is still considered valid if
333          * no error is returned.
334          */
335         error = VOP_BMAP(vp, loffset - voff, &doffset, NULL, NULL, 0);
336         if (error)
337                 return TRUE;
338         if (doffset == NOOFFSET)
339                 return FALSE;
340         return TRUE;
341 }
342
343 /*
344  * Lets the VM system know about a change in size for a file.
345  * We adjust our own internal size and flush any cached pages in
346  * the associated object that are affected by the size change.
347  *
348  * NOTE: This routine may be invoked as a result of a pager put
349  * operation (possibly at object termination time), so we must be careful.
350  *
351  * NOTE: vp->v_filesize is initialized to NOOFFSET (-1), be sure that
352  * we do not blow up on the case.  nsize will always be >= 0, however.
353  */
354 void
355 vnode_pager_setsize(struct vnode *vp, vm_ooffset_t nsize)
356 {
357         vm_pindex_t nobjsize;
358         vm_pindex_t oobjsize;
359         vm_object_t object;
360
361         while ((object = vp->v_object) != NULL) {
362                 vm_object_hold(object);
363                 if (vp->v_object == object)
364                         break;
365                 vm_object_drop(object);
366         }
367         if (object == NULL)
368                 return;
369
370         /*
371          * Hasn't changed size
372          */
373         if (nsize == vp->v_filesize) {
374                 vm_object_drop(object);
375                 return;
376         }
377
378         /*
379          * Has changed size.  Adjust the VM object's size and v_filesize
380          * before we start scanning pages to prevent new pages from being
381          * allocated during the scan.
382          */
383         nobjsize = OFF_TO_IDX(nsize + PAGE_MASK);
384         oobjsize = object->size;
385         object->size = nobjsize;
386
387         /*
388          * File has shrunk. Toss any cached pages beyond the new EOF.
389          */
390         if (nsize < vp->v_filesize) {
391                 vp->v_filesize = nsize;
392                 if (nobjsize < oobjsize) {
393                         vm_object_page_remove(object, nobjsize, oobjsize,
394                                               FALSE);
395                 }
396                 /*
397                  * This gets rid of garbage at the end of a page that is now
398                  * only partially backed by the vnode.  Since we are setting
399                  * the entire page valid & clean after we are done we have
400                  * to be sure that the portion of the page within the file
401                  * bounds is already valid.  If it isn't then making it
402                  * valid would create a corrupt block.
403                  */
404                 if (nsize & PAGE_MASK) {
405                         vm_offset_t kva;
406                         vm_page_t m;
407
408                         m = vm_page_lookup_busy_wait(object, OFF_TO_IDX(nsize),
409                                                      TRUE, "vsetsz");
410
411                         if (m && m->valid) {
412                                 int base = (int)nsize & PAGE_MASK;
413                                 int size = PAGE_SIZE - base;
414                                 struct lwbuf *lwb;
415                                 struct lwbuf lwb_cache;
416
417                                 /*
418                                  * Clear out partial-page garbage in case
419                                  * the page has been mapped.
420                                  *
421                                  * This is byte aligned.
422                                  */
423                                 lwb = lwbuf_alloc(m, &lwb_cache);
424                                 kva = lwbuf_kva(lwb);
425                                 bzero((caddr_t)kva + base, size);
426                                 lwbuf_free(lwb);
427
428                                 /*
429                                  * XXX work around SMP data integrity race
430                                  * by unmapping the page from user processes.
431                                  * The garbage we just cleared may be mapped
432                                  * to a user process running on another cpu
433                                  * and this code is not running through normal
434                                  * I/O channels which handle SMP issues for
435                                  * us, so unmap page to synchronize all cpus.
436                                  *
437                                  * XXX should vm_pager_unmap_page() have
438                                  * dealt with this?
439                                  */
440                                 vm_page_protect(m, VM_PROT_NONE);
441
442                                 /*
443                                  * Clear out partial-page dirty bits.  This
444                                  * has the side effect of setting the valid
445                                  * bits, but that is ok.  There are a bunch
446                                  * of places in the VM system where we expected
447                                  * m->dirty == VM_PAGE_BITS_ALL.  The file EOF
448                                  * case is one of them.  If the page is still
449                                  * partially dirty, make it fully dirty.
450                                  *
451                                  * NOTE: We do not clear out the valid
452                                  * bits.  This would prevent bogus_page
453                                  * replacement from working properly.
454                                  *
455                                  * NOTE: We do not want to clear the dirty
456                                  * bit for a partial DEV_BSIZE'd truncation!
457                                  * This is DEV_BSIZE aligned!
458                                  */
459                                 vm_page_clear_dirty_beg_nonincl(m, base, size);
460                                 if (m->dirty != 0)
461                                         m->dirty = VM_PAGE_BITS_ALL;
462                                 vm_page_wakeup(m);
463                         } else if (m) {
464                                 vm_page_wakeup(m);
465                         }
466                 }
467         } else {
468                 vp->v_filesize = nsize;
469         }
470         vm_object_drop(object);
471 }
472
473 /*
474  * Release a page busied for a getpages operation.  The page may have become
475  * wired (typically due to being used by the buffer cache) or otherwise been
476  * soft-busied and cannot be freed in that case.  A held page can still be
477  * freed.
478  */
479 void
480 vnode_pager_freepage(vm_page_t m)
481 {
482         if (m->busy || m->wire_count || (m->flags & PG_NEED_COMMIT)) {
483                 vm_page_activate(m);
484                 vm_page_wakeup(m);
485         } else {
486                 vm_page_free(m);
487         }
488 }
489
490 /*
491  * EOPNOTSUPP is no longer legal.  For local media VFS's that do not
492  * implement their own VOP_GETPAGES, their VOP_GETPAGES should call to
493  * vnode_pager_generic_getpages() to implement the previous behaviour.
494  *
495  * All other FS's should use the bypass to get to the local media
496  * backing vp's VOP_GETPAGES.
497  */
498 static int
499 vnode_pager_getpage(vm_object_t object, vm_page_t *mpp, int seqaccess)
500 {
501         int rtval;
502         struct vnode *vp;
503
504         vp = object->handle;
505         rtval = VOP_GETPAGES(vp, mpp, PAGE_SIZE, 0, 0, seqaccess);
506         if (rtval == EOPNOTSUPP)
507                 panic("vnode_pager: vfs's must implement vop_getpages");
508         return rtval;
509 }
510
511 /*
512  * This is now called from local media FS's to operate against their
513  * own vnodes if they fail to implement VOP_GETPAGES.
514  *
515  * With all the caching local media devices do these days there is really
516  * very little point to attempting to restrict the I/O size to contiguous
517  * blocks on-disk, especially if our caller thinks we need all the specified
518  * pages.  Just construct and issue a READ.
519  */
520 int
521 vnode_pager_generic_getpages(struct vnode *vp, vm_page_t *mpp, int bytecount,
522                              int reqpage, int seqaccess)
523 {
524         struct iovec aiov;
525         struct uio auio;
526         off_t foff;
527         int error;
528         int count;
529         int i;
530         int ioflags;
531
532         /*
533          * Do not do anything if the vnode is bad.
534          */
535         if (vp->v_mount == NULL)
536                 return VM_PAGER_BAD;
537
538         /*
539          * Calculate the number of pages.  Since we are paging in whole
540          * pages, adjust bytecount to be an integral multiple of the page
541          * size.  It will be clipped to the file EOF later on.
542          */
543         bytecount = round_page(bytecount);
544         count = bytecount / PAGE_SIZE;
545
546         /*
547          * We could check m[reqpage]->valid here and shortcut the operation,
548          * but doing so breaks read-ahead.  Instead assume that the VM
549          * system has already done at least the check, don't worry about
550          * any races, and issue the VOP_READ to allow read-ahead to function.
551          *
552          * This keeps the pipeline full for I/O bound sequentially scanned
553          * mmap()'s
554          */
555         /* don't shortcut */
556
557         /*
558          * Discard pages past the file EOF.  If the requested page is past
559          * the file EOF we just leave its valid bits set to 0, the caller
560          * expects to maintain ownership of the requested page.  If the
561          * entire range is past file EOF discard everything and generate
562          * a pagein error.
563          */
564         foff = IDX_TO_OFF(mpp[0]->pindex);
565         if (foff >= vp->v_filesize) {
566                 for (i = 0; i < count; i++) {
567                         if (i != reqpage)
568                                 vnode_pager_freepage(mpp[i]);
569                 }
570                 return VM_PAGER_ERROR;
571         }
572
573         if (foff + bytecount > vp->v_filesize) {
574                 bytecount = vp->v_filesize - foff;
575                 i = round_page(bytecount) / PAGE_SIZE;
576                 while (count > i) {
577                         --count;
578                         if (count != reqpage)
579                                 vnode_pager_freepage(mpp[count]);
580                 }
581         }
582
583         /*
584          * The size of the transfer is bytecount.  bytecount will be an
585          * integral multiple of the page size unless it has been clipped
586          * to the file EOF.  The transfer cannot exceed the file EOF.
587          *
588          * When dealing with real devices we must round-up to the device
589          * sector size.
590          */
591         if (vp->v_type == VBLK || vp->v_type == VCHR) {
592                 int secmask = vp->v_rdev->si_bsize_phys - 1;
593                 KASSERT(secmask < PAGE_SIZE, ("vnode_pager_generic_getpages: sector size %d too large", secmask + 1));
594                 bytecount = (bytecount + secmask) & ~secmask;
595         }
596
597         /*
598          * Severe hack to avoid deadlocks with the buffer cache
599          */
600         for (i = 0; i < count; ++i) {
601                 vm_page_t mt = mpp[i];
602
603                 vm_page_io_start(mt);
604                 vm_page_wakeup(mt);
605         }
606
607         /*
608          * Issue the I/O with some read-ahead if bytecount > PAGE_SIZE
609          */
610         ioflags = IO_VMIO;
611         if (seqaccess)
612                 ioflags |= IO_SEQMAX << IO_SEQSHIFT;
613
614         aiov.iov_base = NULL;
615         aiov.iov_len = bytecount;
616         auio.uio_iov = &aiov;
617         auio.uio_iovcnt = 1;
618         auio.uio_offset = foff;
619         auio.uio_segflg = UIO_NOCOPY;
620         auio.uio_rw = UIO_READ;
621         auio.uio_resid = bytecount;
622         auio.uio_td = NULL;
623         mycpu->gd_cnt.v_vnodein++;
624         mycpu->gd_cnt.v_vnodepgsin += count;
625
626         error = VOP_READ(vp, &auio, ioflags, proc0.p_ucred);
627
628         /*
629          * Severe hack to avoid deadlocks with the buffer cache
630          */
631         for (i = 0; i < count; ++i) {
632                 vm_page_busy_wait(mpp[i], FALSE, "getpgs");
633                 vm_page_io_finish(mpp[i]);
634         }
635
636         /*
637          * Calculate the actual number of bytes read and clean up the
638          * page list.  
639          */
640         bytecount -= auio.uio_resid;
641
642         for (i = 0; i < count; ++i) {
643                 vm_page_t mt = mpp[i];
644
645                 if (i != reqpage) {
646                         if (error == 0 && mt->valid) {
647                                 if (mt->flags & PG_REFERENCED)
648                                         vm_page_activate(mt);
649                                 else
650                                         vm_page_deactivate(mt);
651                                 vm_page_wakeup(mt);
652                         } else {
653                                 vnode_pager_freepage(mt);
654                         }
655                 } else if (mt->valid == 0) {
656                         if (error == 0) {
657                                 kprintf("page failed but no I/O error page "
658                                         "%p object %p pindex %d\n",
659                                         mt, mt->object, (int) mt->pindex);
660                                 /* whoops, something happened */
661                                 error = EINVAL;
662                         }
663                 } else if (mt->valid != VM_PAGE_BITS_ALL) {
664                         /*
665                          * Zero-extend the requested page if necessary (if
666                          * the filesystem is using a small block size).
667                          */
668                         vm_page_zero_invalid(mt, TRUE);
669                 }
670         }
671         if (error) {
672                 kprintf("vnode_pager_getpage: I/O read error\n");
673         }
674         return (error ? VM_PAGER_ERROR : VM_PAGER_OK);
675 }
676
677 /*
678  * EOPNOTSUPP is no longer legal.  For local media VFS's that do not
679  * implement their own VOP_PUTPAGES, their VOP_PUTPAGES should call to
680  * vnode_pager_generic_putpages() to implement the previous behaviour.
681  *
682  * Caller has already cleared the pmap modified bits, if any.
683  *
684  * All other FS's should use the bypass to get to the local media
685  * backing vp's VOP_PUTPAGES.
686  */
687 static void
688 vnode_pager_putpages(vm_object_t object, vm_page_t *m, int count,
689                      boolean_t sync, int *rtvals)
690 {
691         int rtval;
692         struct vnode *vp;
693         int bytes = count * PAGE_SIZE;
694
695         /*
696          * Force synchronous operation if we are extremely low on memory
697          * to prevent a low-memory deadlock.  VOP operations often need to
698          * allocate more memory to initiate the I/O ( i.e. do a BMAP 
699          * operation ).  The swapper handles the case by limiting the amount
700          * of asynchronous I/O, but that sort of solution doesn't scale well
701          * for the vnode pager without a lot of work.
702          *
703          * Also, the backing vnode's iodone routine may not wake the pageout
704          * daemon up.  This should be probably be addressed XXX.
705          */
706
707         if ((vmstats.v_free_count + vmstats.v_cache_count) <
708             vmstats.v_pageout_free_min) {
709                 sync |= OBJPC_SYNC;
710         }
711
712         /*
713          * Call device-specific putpages function
714          */
715         vp = object->handle;
716         rtval = VOP_PUTPAGES(vp, m, bytes, sync, rtvals, 0);
717         if (rtval == EOPNOTSUPP) {
718             kprintf("vnode_pager: *** WARNING *** stale FS putpages\n");
719             rtval = vnode_pager_generic_putpages( vp, m, bytes, sync, rtvals);
720         }
721 }
722
723
724 /*
725  * This is now called from local media FS's to operate against their
726  * own vnodes if they fail to implement VOP_PUTPAGES.
727  *
728  * This is typically called indirectly via the pageout daemon and
729  * clustering has already typically occured, so in general we ask the
730  * underlying filesystem to write the data out asynchronously rather
731  * then delayed.
732  */
733 int
734 vnode_pager_generic_putpages(struct vnode *vp, vm_page_t *m, int bytecount,
735                              int flags, int *rtvals)
736 {
737         int i;
738         int maxsize, ncount, count;
739         vm_ooffset_t poffset;
740         struct uio auio;
741         struct iovec aiov;
742         int error;
743         int ioflags;
744
745         count = bytecount / PAGE_SIZE;
746
747         for (i = 0; i < count; i++)
748                 rtvals[i] = VM_PAGER_AGAIN;
749
750         if ((int) m[0]->pindex < 0) {
751                 kprintf("vnode_pager_putpages: attempt to write meta-data!!! -- 0x%lx(%x)\n",
752                         (long)m[0]->pindex, m[0]->dirty);
753                 rtvals[0] = VM_PAGER_BAD;
754                 return VM_PAGER_BAD;
755         }
756
757         maxsize = count * PAGE_SIZE;
758         ncount = count;
759
760         poffset = IDX_TO_OFF(m[0]->pindex);
761
762         /*
763          * If the page-aligned write is larger then the actual file we
764          * have to invalidate pages occuring beyond the file EOF.
765          *
766          * If the file EOF resides in the middle of a page we still clear
767          * all of that page's dirty bits later on.  If we didn't it would
768          * endlessly re-write.
769          *
770          * We do not under any circumstances truncate the valid bits, as
771          * this will screw up bogus page replacement.
772          *
773          * The caller has already read-protected the pages.  The VFS must
774          * use the buffer cache to wrap the pages.  The pages might not
775          * be immediately flushed by the buffer cache but once under its
776          * control the pages themselves can wind up being marked clean
777          * and their covering buffer cache buffer can be marked dirty.
778          */
779         if (poffset + maxsize > vp->v_filesize) {
780                 if (poffset < vp->v_filesize) {
781                         maxsize = vp->v_filesize - poffset;
782                         ncount = btoc(maxsize);
783                 } else {
784                         maxsize = 0;
785                         ncount = 0;
786                 }
787                 if (ncount < count) {
788                         for (i = ncount; i < count; i++) {
789                                 rtvals[i] = VM_PAGER_BAD;
790                         }
791                 }
792         }
793
794         /*
795          * pageouts are already clustered, use IO_ASYNC to force a bawrite()
796          * rather then a bdwrite() to prevent paging I/O from saturating
797          * the buffer cache.  Dummy-up the sequential heuristic to cause
798          * large ranges to cluster.  If neither IO_SYNC or IO_ASYNC is set,
799          * the system decides how to cluster.
800          */
801         ioflags = IO_VMIO;
802         if (flags & (VM_PAGER_PUT_SYNC | VM_PAGER_PUT_INVAL))
803                 ioflags |= IO_SYNC;
804         else if ((flags & VM_PAGER_CLUSTER_OK) == 0)
805                 ioflags |= IO_ASYNC;
806         ioflags |= (flags & VM_PAGER_PUT_INVAL) ? IO_INVAL: 0;
807         ioflags |= IO_SEQMAX << IO_SEQSHIFT;
808
809         aiov.iov_base = (caddr_t) 0;
810         aiov.iov_len = maxsize;
811         auio.uio_iov = &aiov;
812         auio.uio_iovcnt = 1;
813         auio.uio_offset = poffset;
814         auio.uio_segflg = UIO_NOCOPY;
815         auio.uio_rw = UIO_WRITE;
816         auio.uio_resid = maxsize;
817         auio.uio_td = NULL;
818         error = VOP_WRITE(vp, &auio, ioflags, proc0.p_ucred);
819         mycpu->gd_cnt.v_vnodeout++;
820         mycpu->gd_cnt.v_vnodepgsout += ncount;
821
822         if (error) {
823                 krateprintf(&vbadrate,
824                             "vnode_pager_putpages: I/O error %d\n", error);
825         }
826         if (auio.uio_resid) {
827                 krateprintf(&vresrate,
828                             "vnode_pager_putpages: residual I/O %zd at %lu\n",
829                             auio.uio_resid, (u_long)m[0]->pindex);
830         }
831         if (error == 0) {
832                 for (i = 0; i < ncount; i++) {
833                         rtvals[i] = VM_PAGER_OK;
834                         vm_page_undirty(m[i]);
835                 }
836         }
837         return rtvals[0];
838 }
839
840 /*
841  * Run the chain and if the bottom-most object is a vnode-type lock the
842  * underlying vnode.  A locked vnode or NULL is returned.
843  */
844 struct vnode *
845 vnode_pager_lock(vm_object_t object)
846 {
847         struct vnode *vp = NULL;
848         vm_object_t lobject;
849         vm_object_t tobject;
850         int error;
851
852         if (object == NULL)
853                 return(NULL);
854
855         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
856         lobject = object;
857
858         while (lobject->type != OBJT_VNODE) {
859                 if (lobject->flags & OBJ_DEAD)
860                         break;
861                 tobject = lobject->backing_object;
862                 if (tobject == NULL)
863                         break;
864                 vm_object_hold_shared(tobject);
865                 if (tobject == lobject->backing_object) {
866                         if (lobject != object) {
867                                 vm_object_lock_swap();
868                                 vm_object_drop(lobject);
869                         }
870                         lobject = tobject;
871                 } else {
872                         vm_object_drop(tobject);
873                 }
874         }
875         while (lobject->type == OBJT_VNODE &&
876                (lobject->flags & OBJ_DEAD) == 0) {
877                 /*
878                  * Extract the vp
879                  */
880                 vp = lobject->handle;
881                 error = vget(vp, LK_SHARED | LK_RETRY | LK_CANRECURSE);
882                 if (error == 0) {
883                         if (lobject->handle == vp)
884                                 break;
885                         vput(vp);
886                 } else {
887                         kprintf("vnode_pager_lock: vp %p error %d "
888                                 "lockstatus %d, retrying\n",
889                                 vp, error,
890                                 lockstatus(&vp->v_lock, curthread));
891                         tsleep(object->handle, 0, "vnpgrl", hz);
892                 }
893                 vp = NULL;
894         }
895         if (lobject != object)
896                 vm_object_drop(lobject);
897         return (vp);
898 }