]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_object.c
Revert r352406, which contained changes I didn't intend to commit.
[FreeBSD/FreeBSD.git] / sys / vm / vm_object.c
1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      from: @(#)vm_object.c   8.5 (Berkeley) 3/22/94
35  *
36  *
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62
63 /*
64  *      Virtual memory object module.
65  */
66
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
69
70 #include "opt_vm.h"
71
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/cpuset.h>
75 #include <sys/lock.h>
76 #include <sys/mman.h>
77 #include <sys/mount.h>
78 #include <sys/kernel.h>
79 #include <sys/pctrie.h>
80 #include <sys/sysctl.h>
81 #include <sys/mutex.h>
82 #include <sys/proc.h>           /* for curproc, pageproc */
83 #include <sys/refcount.h>
84 #include <sys/socket.h>
85 #include <sys/resourcevar.h>
86 #include <sys/rwlock.h>
87 #include <sys/user.h>
88 #include <sys/vnode.h>
89 #include <sys/vmmeter.h>
90 #include <sys/sx.h>
91
92 #include <vm/vm.h>
93 #include <vm/vm_param.h>
94 #include <vm/pmap.h>
95 #include <vm/vm_map.h>
96 #include <vm/vm_object.h>
97 #include <vm/vm_page.h>
98 #include <vm/vm_pageout.h>
99 #include <vm/vm_pager.h>
100 #include <vm/vm_phys.h>
101 #include <vm/vm_pagequeue.h>
102 #include <vm/swap_pager.h>
103 #include <vm/vm_kern.h>
104 #include <vm/vm_extern.h>
105 #include <vm/vm_radix.h>
106 #include <vm/vm_reserv.h>
107 #include <vm/uma.h>
108
109 static int old_msync;
110 SYSCTL_INT(_vm, OID_AUTO, old_msync, CTLFLAG_RW, &old_msync, 0,
111     "Use old (insecure) msync behavior");
112
113 static int      vm_object_page_collect_flush(vm_object_t object, vm_page_t p,
114                     int pagerflags, int flags, boolean_t *clearobjflags,
115                     boolean_t *eio);
116 static boolean_t vm_object_page_remove_write(vm_page_t p, int flags,
117                     boolean_t *clearobjflags);
118 static void     vm_object_qcollapse(vm_object_t object);
119 static void     vm_object_vndeallocate(vm_object_t object);
120
121 /*
122  *      Virtual memory objects maintain the actual data
123  *      associated with allocated virtual memory.  A given
124  *      page of memory exists within exactly one object.
125  *
126  *      An object is only deallocated when all "references"
127  *      are given up.  Only one "reference" to a given
128  *      region of an object should be writeable.
129  *
130  *      Associated with each object is a list of all resident
131  *      memory pages belonging to that object; this list is
132  *      maintained by the "vm_page" module, and locked by the object's
133  *      lock.
134  *
135  *      Each object also records a "pager" routine which is
136  *      used to retrieve (and store) pages to the proper backing
137  *      storage.  In addition, objects may be backed by other
138  *      objects from which they were virtual-copied.
139  *
140  *      The only items within the object structure which are
141  *      modified after time of creation are:
142  *              reference count         locked by object's lock
143  *              pager routine           locked by object's lock
144  *
145  */
146
147 struct object_q vm_object_list;
148 struct mtx vm_object_list_mtx;  /* lock for object list and count */
149
150 struct vm_object kernel_object_store;
151
152 static SYSCTL_NODE(_vm_stats, OID_AUTO, object, CTLFLAG_RD, 0,
153     "VM object stats");
154
155 static counter_u64_t object_collapses = EARLY_COUNTER;
156 SYSCTL_COUNTER_U64(_vm_stats_object, OID_AUTO, collapses, CTLFLAG_RD,
157     &object_collapses,
158     "VM object collapses");
159
160 static counter_u64_t object_bypasses = EARLY_COUNTER;
161 SYSCTL_COUNTER_U64(_vm_stats_object, OID_AUTO, bypasses, CTLFLAG_RD,
162     &object_bypasses,
163     "VM object bypasses");
164
165 static void
166 counter_startup(void)
167 {
168
169         object_collapses = counter_u64_alloc(M_WAITOK);
170         object_bypasses = counter_u64_alloc(M_WAITOK);
171 }
172 SYSINIT(object_counters, SI_SUB_CPU, SI_ORDER_ANY, counter_startup, NULL);
173
174 static uma_zone_t obj_zone;
175
176 static int vm_object_zinit(void *mem, int size, int flags);
177
178 #ifdef INVARIANTS
179 static void vm_object_zdtor(void *mem, int size, void *arg);
180
181 static void
182 vm_object_zdtor(void *mem, int size, void *arg)
183 {
184         vm_object_t object;
185
186         object = (vm_object_t)mem;
187         KASSERT(object->ref_count == 0,
188             ("object %p ref_count = %d", object, object->ref_count));
189         KASSERT(TAILQ_EMPTY(&object->memq),
190             ("object %p has resident pages in its memq", object));
191         KASSERT(vm_radix_is_empty(&object->rtree),
192             ("object %p has resident pages in its trie", object));
193 #if VM_NRESERVLEVEL > 0
194         KASSERT(LIST_EMPTY(&object->rvq),
195             ("object %p has reservations",
196             object));
197 #endif
198         KASSERT(REFCOUNT_COUNT(object->paging_in_progress) == 0,
199             ("object %p paging_in_progress = %d",
200             object, REFCOUNT_COUNT(object->paging_in_progress)));
201         KASSERT(object->resident_page_count == 0,
202             ("object %p resident_page_count = %d",
203             object, object->resident_page_count));
204         KASSERT(object->shadow_count == 0,
205             ("object %p shadow_count = %d",
206             object, object->shadow_count));
207         KASSERT(object->type == OBJT_DEAD,
208             ("object %p has non-dead type %d",
209             object, object->type));
210 }
211 #endif
212
213 static int
214 vm_object_zinit(void *mem, int size, int flags)
215 {
216         vm_object_t object;
217
218         object = (vm_object_t)mem;
219         rw_init_flags(&object->lock, "vm object", RW_DUPOK | RW_NEW);
220
221         /* These are true for any object that has been freed */
222         object->type = OBJT_DEAD;
223         object->ref_count = 0;
224         vm_radix_init(&object->rtree);
225         refcount_init(&object->paging_in_progress, 0);
226         object->resident_page_count = 0;
227         object->shadow_count = 0;
228         object->flags = OBJ_DEAD;
229
230         mtx_lock(&vm_object_list_mtx);
231         TAILQ_INSERT_TAIL(&vm_object_list, object, object_list);
232         mtx_unlock(&vm_object_list_mtx);
233         return (0);
234 }
235
236 static void
237 _vm_object_allocate(objtype_t type, vm_pindex_t size, vm_object_t object)
238 {
239
240         TAILQ_INIT(&object->memq);
241         LIST_INIT(&object->shadow_head);
242
243         object->type = type;
244         if (type == OBJT_SWAP)
245                 pctrie_init(&object->un_pager.swp.swp_blks);
246
247         /*
248          * Ensure that swap_pager_swapoff() iteration over object_list
249          * sees up to date type and pctrie head if it observed
250          * non-dead object.
251          */
252         atomic_thread_fence_rel();
253
254         switch (type) {
255         case OBJT_DEAD:
256                 panic("_vm_object_allocate: can't create OBJT_DEAD");
257         case OBJT_DEFAULT:
258         case OBJT_SWAP:
259                 object->flags = OBJ_ONEMAPPING;
260                 break;
261         case OBJT_DEVICE:
262         case OBJT_SG:
263                 object->flags = OBJ_FICTITIOUS | OBJ_UNMANAGED;
264                 break;
265         case OBJT_MGTDEVICE:
266                 object->flags = OBJ_FICTITIOUS;
267                 break;
268         case OBJT_PHYS:
269                 object->flags = OBJ_UNMANAGED;
270                 break;
271         case OBJT_VNODE:
272                 object->flags = 0;
273                 break;
274         default:
275                 panic("_vm_object_allocate: type %d is undefined", type);
276         }
277         object->size = size;
278         object->domain.dr_policy = NULL;
279         object->generation = 1;
280         object->ref_count = 1;
281         object->memattr = VM_MEMATTR_DEFAULT;
282         object->cred = NULL;
283         object->charge = 0;
284         object->handle = NULL;
285         object->backing_object = NULL;
286         object->backing_object_offset = (vm_ooffset_t) 0;
287 #if VM_NRESERVLEVEL > 0
288         LIST_INIT(&object->rvq);
289 #endif
290         umtx_shm_object_init(object);
291 }
292
293 /*
294  *      vm_object_init:
295  *
296  *      Initialize the VM objects module.
297  */
298 void
299 vm_object_init(void)
300 {
301         TAILQ_INIT(&vm_object_list);
302         mtx_init(&vm_object_list_mtx, "vm object_list", NULL, MTX_DEF);
303         
304         rw_init(&kernel_object->lock, "kernel vm object");
305         _vm_object_allocate(OBJT_PHYS, atop(VM_MAX_KERNEL_ADDRESS -
306             VM_MIN_KERNEL_ADDRESS), kernel_object);
307 #if VM_NRESERVLEVEL > 0
308         kernel_object->flags |= OBJ_COLORED;
309         kernel_object->pg_color = (u_short)atop(VM_MIN_KERNEL_ADDRESS);
310 #endif
311
312         /*
313          * The lock portion of struct vm_object must be type stable due
314          * to vm_pageout_fallback_object_lock locking a vm object
315          * without holding any references to it.
316          */
317         obj_zone = uma_zcreate("VM OBJECT", sizeof (struct vm_object), NULL,
318 #ifdef INVARIANTS
319             vm_object_zdtor,
320 #else
321             NULL,
322 #endif
323             vm_object_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
324
325         vm_radix_zinit();
326 }
327
328 void
329 vm_object_clear_flag(vm_object_t object, u_short bits)
330 {
331
332         VM_OBJECT_ASSERT_WLOCKED(object);
333         object->flags &= ~bits;
334 }
335
336 /*
337  *      Sets the default memory attribute for the specified object.  Pages
338  *      that are allocated to this object are by default assigned this memory
339  *      attribute.
340  *
341  *      Presently, this function must be called before any pages are allocated
342  *      to the object.  In the future, this requirement may be relaxed for
343  *      "default" and "swap" objects.
344  */
345 int
346 vm_object_set_memattr(vm_object_t object, vm_memattr_t memattr)
347 {
348
349         VM_OBJECT_ASSERT_WLOCKED(object);
350         switch (object->type) {
351         case OBJT_DEFAULT:
352         case OBJT_DEVICE:
353         case OBJT_MGTDEVICE:
354         case OBJT_PHYS:
355         case OBJT_SG:
356         case OBJT_SWAP:
357         case OBJT_VNODE:
358                 if (!TAILQ_EMPTY(&object->memq))
359                         return (KERN_FAILURE);
360                 break;
361         case OBJT_DEAD:
362                 return (KERN_INVALID_ARGUMENT);
363         default:
364                 panic("vm_object_set_memattr: object %p is of undefined type",
365                     object);
366         }
367         object->memattr = memattr;
368         return (KERN_SUCCESS);
369 }
370
371 void
372 vm_object_pip_add(vm_object_t object, short i)
373 {
374
375         refcount_acquiren(&object->paging_in_progress, i);
376 }
377
378 void
379 vm_object_pip_wakeup(vm_object_t object)
380 {
381
382         refcount_release(&object->paging_in_progress);
383 }
384
385 void
386 vm_object_pip_wakeupn(vm_object_t object, short i)
387 {
388
389         refcount_releasen(&object->paging_in_progress, i);
390 }
391
392 void
393 vm_object_pip_wait(vm_object_t object, char *waitid)
394 {
395
396         VM_OBJECT_ASSERT_WLOCKED(object);
397
398         while (REFCOUNT_COUNT(object->paging_in_progress) > 0) {
399                 VM_OBJECT_WUNLOCK(object);
400                 refcount_wait(&object->paging_in_progress, waitid, PVM);
401                 VM_OBJECT_WLOCK(object);
402         }
403 }
404
405 void
406 vm_object_pip_wait_unlocked(vm_object_t object, char *waitid)
407 {
408
409         VM_OBJECT_ASSERT_UNLOCKED(object);
410
411         while (REFCOUNT_COUNT(object->paging_in_progress) > 0)
412                 refcount_wait(&object->paging_in_progress, waitid, PVM);
413 }
414
415 /*
416  *      vm_object_allocate:
417  *
418  *      Returns a new object with the given size.
419  */
420 vm_object_t
421 vm_object_allocate(objtype_t type, vm_pindex_t size)
422 {
423         vm_object_t object;
424
425         object = (vm_object_t)uma_zalloc(obj_zone, M_WAITOK);
426         _vm_object_allocate(type, size, object);
427         return (object);
428 }
429
430
431 /*
432  *      vm_object_reference:
433  *
434  *      Gets another reference to the given object.  Note: OBJ_DEAD
435  *      objects can be referenced during final cleaning.
436  */
437 void
438 vm_object_reference(vm_object_t object)
439 {
440         if (object == NULL)
441                 return;
442         VM_OBJECT_WLOCK(object);
443         vm_object_reference_locked(object);
444         VM_OBJECT_WUNLOCK(object);
445 }
446
447 /*
448  *      vm_object_reference_locked:
449  *
450  *      Gets another reference to the given object.
451  *
452  *      The object must be locked.
453  */
454 void
455 vm_object_reference_locked(vm_object_t object)
456 {
457         struct vnode *vp;
458
459         VM_OBJECT_ASSERT_WLOCKED(object);
460         object->ref_count++;
461         if (object->type == OBJT_VNODE) {
462                 vp = object->handle;
463                 vref(vp);
464         }
465 }
466
467 /*
468  * Handle deallocating an object of type OBJT_VNODE.
469  */
470 static void
471 vm_object_vndeallocate(vm_object_t object)
472 {
473         struct vnode *vp = (struct vnode *) object->handle;
474
475         VM_OBJECT_ASSERT_WLOCKED(object);
476         KASSERT(object->type == OBJT_VNODE,
477             ("vm_object_vndeallocate: not a vnode object"));
478         KASSERT(vp != NULL, ("vm_object_vndeallocate: missing vp"));
479 #ifdef INVARIANTS
480         if (object->ref_count == 0) {
481                 vn_printf(vp, "vm_object_vndeallocate ");
482                 panic("vm_object_vndeallocate: bad object reference count");
483         }
484 #endif
485
486         if (!umtx_shm_vnobj_persistent && object->ref_count == 1)
487                 umtx_shm_object_terminated(object);
488
489         object->ref_count--;
490
491         /* vrele may need the vnode lock. */
492         VM_OBJECT_WUNLOCK(object);
493         vrele(vp);
494 }
495
496 /*
497  *      vm_object_deallocate:
498  *
499  *      Release a reference to the specified object,
500  *      gained either through a vm_object_allocate
501  *      or a vm_object_reference call.  When all references
502  *      are gone, storage associated with this object
503  *      may be relinquished.
504  *
505  *      No object may be locked.
506  */
507 void
508 vm_object_deallocate(vm_object_t object)
509 {
510         vm_object_t temp;
511
512         while (object != NULL) {
513                 VM_OBJECT_WLOCK(object);
514                 if (object->type == OBJT_VNODE) {
515                         vm_object_vndeallocate(object);
516                         return;
517                 }
518
519                 KASSERT(object->ref_count != 0,
520                         ("vm_object_deallocate: object deallocated too many times: %d", object->type));
521
522                 /*
523                  * If the reference count goes to 0 we start calling
524                  * vm_object_terminate() on the object chain.
525                  * A ref count of 1 may be a special case depending on the
526                  * shadow count being 0 or 1.
527                  */
528                 object->ref_count--;
529                 if (object->ref_count > 1) {
530                         VM_OBJECT_WUNLOCK(object);
531                         return;
532                 } else if (object->ref_count == 1) {
533                         if (object->shadow_count == 0 &&
534                             object->handle == NULL &&
535                             (object->type == OBJT_DEFAULT ||
536                             (object->type == OBJT_SWAP &&
537                             (object->flags & OBJ_TMPFS_NODE) == 0))) {
538                                 vm_object_set_flag(object, OBJ_ONEMAPPING);
539                         } else if ((object->shadow_count == 1) &&
540                             (object->handle == NULL) &&
541                             (object->type == OBJT_DEFAULT ||
542                              object->type == OBJT_SWAP)) {
543                                 vm_object_t robject;
544
545                                 robject = LIST_FIRST(&object->shadow_head);
546                                 KASSERT(robject != NULL,
547                                     ("vm_object_deallocate: ref_count: %d, shadow_count: %d",
548                                          object->ref_count,
549                                          object->shadow_count));
550                                 KASSERT((robject->flags & OBJ_TMPFS_NODE) == 0,
551                                     ("shadowed tmpfs v_object %p", object));
552                                 if (!VM_OBJECT_TRYWLOCK(robject)) {
553                                         /*
554                                          * Avoid a potential deadlock.
555                                          */
556                                         object->ref_count++;
557                                         VM_OBJECT_WUNLOCK(object);
558                                         /*
559                                          * More likely than not the thread
560                                          * holding robject's lock has lower
561                                          * priority than the current thread.
562                                          * Let the lower priority thread run.
563                                          */
564                                         pause("vmo_de", 1);
565                                         continue;
566                                 }
567                                 /*
568                                  * Collapse object into its shadow unless its
569                                  * shadow is dead.  In that case, object will
570                                  * be deallocated by the thread that is
571                                  * deallocating its shadow.
572                                  */
573                                 if ((robject->flags & OBJ_DEAD) == 0 &&
574                                     (robject->handle == NULL) &&
575                                     (robject->type == OBJT_DEFAULT ||
576                                      robject->type == OBJT_SWAP)) {
577
578                                         robject->ref_count++;
579 retry:
580                                         if (REFCOUNT_COUNT(robject->paging_in_progress) > 0) {
581                                                 VM_OBJECT_WUNLOCK(object);
582                                                 vm_object_pip_wait(robject,
583                                                     "objde1");
584                                                 temp = robject->backing_object;
585                                                 if (object == temp) {
586                                                         VM_OBJECT_WLOCK(object);
587                                                         goto retry;
588                                                 }
589                                         } else if (REFCOUNT_COUNT(object->paging_in_progress) > 0) {
590                                                 VM_OBJECT_WUNLOCK(robject);
591                                                 VM_OBJECT_WUNLOCK(object);
592                                                 refcount_wait(
593                                                     &object->paging_in_progress,
594                                                     "objde2", PVM);
595                                                 VM_OBJECT_WLOCK(robject);
596                                                 temp = robject->backing_object;
597                                                 if (object == temp) {
598                                                         VM_OBJECT_WLOCK(object);
599                                                         goto retry;
600                                                 }
601                                         } else
602                                                 VM_OBJECT_WUNLOCK(object);
603
604                                         if (robject->ref_count == 1) {
605                                                 robject->ref_count--;
606                                                 object = robject;
607                                                 goto doterm;
608                                         }
609                                         object = robject;
610                                         vm_object_collapse(object);
611                                         VM_OBJECT_WUNLOCK(object);
612                                         continue;
613                                 }
614                                 VM_OBJECT_WUNLOCK(robject);
615                         }
616                         VM_OBJECT_WUNLOCK(object);
617                         return;
618                 }
619 doterm:
620                 umtx_shm_object_terminated(object);
621                 temp = object->backing_object;
622                 if (temp != NULL) {
623                         KASSERT((object->flags & OBJ_TMPFS_NODE) == 0,
624                             ("shadowed tmpfs v_object 2 %p", object));
625                         VM_OBJECT_WLOCK(temp);
626                         LIST_REMOVE(object, shadow_list);
627                         temp->shadow_count--;
628                         VM_OBJECT_WUNLOCK(temp);
629                         object->backing_object = NULL;
630                 }
631                 /*
632                  * Don't double-terminate, we could be in a termination
633                  * recursion due to the terminate having to sync data
634                  * to disk.
635                  */
636                 if ((object->flags & OBJ_DEAD) == 0) {
637                         vm_object_set_flag(object, OBJ_DEAD);
638                         vm_object_terminate(object);
639                 } else
640                         VM_OBJECT_WUNLOCK(object);
641                 object = temp;
642         }
643 }
644
645 /*
646  *      vm_object_destroy removes the object from the global object list
647  *      and frees the space for the object.
648  */
649 void
650 vm_object_destroy(vm_object_t object)
651 {
652
653         /*
654          * Release the allocation charge.
655          */
656         if (object->cred != NULL) {
657                 swap_release_by_cred(object->charge, object->cred);
658                 object->charge = 0;
659                 crfree(object->cred);
660                 object->cred = NULL;
661         }
662
663         /*
664          * Free the space for the object.
665          */
666         uma_zfree(obj_zone, object);
667 }
668
669 /*
670  *      vm_object_terminate_pages removes any remaining pageable pages
671  *      from the object and resets the object to an empty state.
672  */
673 static void
674 vm_object_terminate_pages(vm_object_t object)
675 {
676         vm_page_t p, p_next;
677
678         VM_OBJECT_ASSERT_WLOCKED(object);
679
680         /*
681          * Free any remaining pageable pages.  This also removes them from the
682          * paging queues.  However, don't free wired pages, just remove them
683          * from the object.  Rather than incrementally removing each page from
684          * the object, the page and object are reset to any empty state. 
685          */
686         TAILQ_FOREACH_SAFE(p, &object->memq, listq, p_next) {
687                 vm_page_assert_unbusied(p);
688                 KASSERT(p->object == object &&
689                     (p->ref_count & VPRC_OBJREF) != 0,
690                     ("vm_object_terminate_pages: page %p is inconsistent", p));
691
692                 p->object = NULL;
693                 if (vm_page_drop(p, VPRC_OBJREF) == VPRC_OBJREF) {
694                         VM_CNT_INC(v_pfree);
695                         vm_page_free(p);
696                 }
697         }
698
699         /*
700          * If the object contained any pages, then reset it to an empty state.
701          * None of the object's fields, including "resident_page_count", were
702          * modified by the preceding loop.
703          */
704         if (object->resident_page_count != 0) {
705                 vm_radix_reclaim_allnodes(&object->rtree);
706                 TAILQ_INIT(&object->memq);
707                 object->resident_page_count = 0;
708                 if (object->type == OBJT_VNODE)
709                         vdrop(object->handle);
710         }
711 }
712
713 /*
714  *      vm_object_terminate actually destroys the specified object, freeing
715  *      up all previously used resources.
716  *
717  *      The object must be locked.
718  *      This routine may block.
719  */
720 void
721 vm_object_terminate(vm_object_t object)
722 {
723         VM_OBJECT_ASSERT_WLOCKED(object);
724         KASSERT((object->flags & OBJ_DEAD) != 0,
725             ("terminating non-dead obj %p", object));
726
727         /*
728          * wait for the pageout daemon to be done with the object
729          */
730         vm_object_pip_wait(object, "objtrm");
731
732         KASSERT(!REFCOUNT_COUNT(object->paging_in_progress),
733                 ("vm_object_terminate: pageout in progress"));
734
735         KASSERT(object->ref_count == 0, 
736                 ("vm_object_terminate: object with references, ref_count=%d",
737                 object->ref_count));
738
739         if ((object->flags & OBJ_PG_DTOR) == 0)
740                 vm_object_terminate_pages(object);
741
742 #if VM_NRESERVLEVEL > 0
743         if (__predict_false(!LIST_EMPTY(&object->rvq)))
744                 vm_reserv_break_all(object);
745 #endif
746
747         KASSERT(object->cred == NULL || object->type == OBJT_DEFAULT ||
748             object->type == OBJT_SWAP,
749             ("%s: non-swap obj %p has cred", __func__, object));
750
751         /*
752          * Let the pager know object is dead.
753          */
754         vm_pager_deallocate(object);
755         VM_OBJECT_WUNLOCK(object);
756
757         vm_object_destroy(object);
758 }
759
760 /*
761  * Make the page read-only so that we can clear the object flags.  However, if
762  * this is a nosync mmap then the object is likely to stay dirty so do not
763  * mess with the page and do not clear the object flags.  Returns TRUE if the
764  * page should be flushed, and FALSE otherwise.
765  */
766 static boolean_t
767 vm_object_page_remove_write(vm_page_t p, int flags, boolean_t *clearobjflags)
768 {
769
770         /*
771          * If we have been asked to skip nosync pages and this is a
772          * nosync page, skip it.  Note that the object flags were not
773          * cleared in this case so we do not have to set them.
774          */
775         if ((flags & OBJPC_NOSYNC) != 0 && (p->oflags & VPO_NOSYNC) != 0) {
776                 *clearobjflags = FALSE;
777                 return (FALSE);
778         } else {
779                 pmap_remove_write(p);
780                 return (p->dirty != 0);
781         }
782 }
783
784 /*
785  *      vm_object_page_clean
786  *
787  *      Clean all dirty pages in the specified range of object.  Leaves page 
788  *      on whatever queue it is currently on.   If NOSYNC is set then do not
789  *      write out pages with VPO_NOSYNC set (originally comes from MAP_NOSYNC),
790  *      leaving the object dirty.
791  *
792  *      When stuffing pages asynchronously, allow clustering.  XXX we need a
793  *      synchronous clustering mode implementation.
794  *
795  *      Odd semantics: if start == end, we clean everything.
796  *
797  *      The object must be locked.
798  *
799  *      Returns FALSE if some page from the range was not written, as
800  *      reported by the pager, and TRUE otherwise.
801  */
802 boolean_t
803 vm_object_page_clean(vm_object_t object, vm_ooffset_t start, vm_ooffset_t end,
804     int flags)
805 {
806         vm_page_t np, p;
807         vm_pindex_t pi, tend, tstart;
808         int curgeneration, n, pagerflags;
809         boolean_t clearobjflags, eio, res;
810
811         VM_OBJECT_ASSERT_WLOCKED(object);
812
813         /*
814          * The OBJ_MIGHTBEDIRTY flag is only set for OBJT_VNODE
815          * objects.  The check below prevents the function from
816          * operating on non-vnode objects.
817          */
818         if ((object->flags & OBJ_MIGHTBEDIRTY) == 0 ||
819             object->resident_page_count == 0)
820                 return (TRUE);
821
822         pagerflags = (flags & (OBJPC_SYNC | OBJPC_INVAL)) != 0 ?
823             VM_PAGER_PUT_SYNC : VM_PAGER_CLUSTER_OK;
824         pagerflags |= (flags & OBJPC_INVAL) != 0 ? VM_PAGER_PUT_INVAL : 0;
825
826         tstart = OFF_TO_IDX(start);
827         tend = (end == 0) ? object->size : OFF_TO_IDX(end + PAGE_MASK);
828         clearobjflags = tstart == 0 && tend >= object->size;
829         res = TRUE;
830
831 rescan:
832         curgeneration = object->generation;
833
834         for (p = vm_page_find_least(object, tstart); p != NULL; p = np) {
835                 pi = p->pindex;
836                 if (pi >= tend)
837                         break;
838                 np = TAILQ_NEXT(p, listq);
839                 if (p->valid == 0)
840                         continue;
841                 if (vm_page_sleep_if_busy(p, "vpcwai")) {
842                         if (object->generation != curgeneration) {
843                                 if ((flags & OBJPC_SYNC) != 0)
844                                         goto rescan;
845                                 else
846                                         clearobjflags = FALSE;
847                         }
848                         np = vm_page_find_least(object, pi);
849                         continue;
850                 }
851                 if (!vm_object_page_remove_write(p, flags, &clearobjflags))
852                         continue;
853
854                 n = vm_object_page_collect_flush(object, p, pagerflags,
855                     flags, &clearobjflags, &eio);
856                 if (eio) {
857                         res = FALSE;
858                         clearobjflags = FALSE;
859                 }
860                 if (object->generation != curgeneration) {
861                         if ((flags & OBJPC_SYNC) != 0)
862                                 goto rescan;
863                         else
864                                 clearobjflags = FALSE;
865                 }
866
867                 /*
868                  * If the VOP_PUTPAGES() did a truncated write, so
869                  * that even the first page of the run is not fully
870                  * written, vm_pageout_flush() returns 0 as the run
871                  * length.  Since the condition that caused truncated
872                  * write may be permanent, e.g. exhausted free space,
873                  * accepting n == 0 would cause an infinite loop.
874                  *
875                  * Forwarding the iterator leaves the unwritten page
876                  * behind, but there is not much we can do there if
877                  * filesystem refuses to write it.
878                  */
879                 if (n == 0) {
880                         n = 1;
881                         clearobjflags = FALSE;
882                 }
883                 np = vm_page_find_least(object, pi + n);
884         }
885 #if 0
886         VOP_FSYNC(vp, (pagerflags & VM_PAGER_PUT_SYNC) ? MNT_WAIT : 0);
887 #endif
888
889         if (clearobjflags)
890                 vm_object_clear_flag(object, OBJ_MIGHTBEDIRTY);
891         return (res);
892 }
893
894 static int
895 vm_object_page_collect_flush(vm_object_t object, vm_page_t p, int pagerflags,
896     int flags, boolean_t *clearobjflags, boolean_t *eio)
897 {
898         vm_page_t ma[vm_pageout_page_count], p_first, tp;
899         int count, i, mreq, runlen;
900
901         vm_page_lock_assert(p, MA_NOTOWNED);
902         VM_OBJECT_ASSERT_WLOCKED(object);
903
904         count = 1;
905         mreq = 0;
906
907         for (tp = p; count < vm_pageout_page_count; count++) {
908                 tp = vm_page_next(tp);
909                 if (tp == NULL || vm_page_busied(tp))
910                         break;
911                 if (!vm_object_page_remove_write(tp, flags, clearobjflags))
912                         break;
913         }
914
915         for (p_first = p; count < vm_pageout_page_count; count++) {
916                 tp = vm_page_prev(p_first);
917                 if (tp == NULL || vm_page_busied(tp))
918                         break;
919                 if (!vm_object_page_remove_write(tp, flags, clearobjflags))
920                         break;
921                 p_first = tp;
922                 mreq++;
923         }
924
925         for (tp = p_first, i = 0; i < count; tp = TAILQ_NEXT(tp, listq), i++)
926                 ma[i] = tp;
927
928         vm_pageout_flush(ma, count, pagerflags, mreq, &runlen, eio);
929         return (runlen);
930 }
931
932 /*
933  * Note that there is absolutely no sense in writing out
934  * anonymous objects, so we track down the vnode object
935  * to write out.
936  * We invalidate (remove) all pages from the address space
937  * for semantic correctness.
938  *
939  * If the backing object is a device object with unmanaged pages, then any
940  * mappings to the specified range of pages must be removed before this
941  * function is called.
942  *
943  * Note: certain anonymous maps, such as MAP_NOSYNC maps,
944  * may start out with a NULL object.
945  */
946 boolean_t
947 vm_object_sync(vm_object_t object, vm_ooffset_t offset, vm_size_t size,
948     boolean_t syncio, boolean_t invalidate)
949 {
950         vm_object_t backing_object;
951         struct vnode *vp;
952         struct mount *mp;
953         int error, flags, fsync_after;
954         boolean_t res;
955
956         if (object == NULL)
957                 return (TRUE);
958         res = TRUE;
959         error = 0;
960         VM_OBJECT_WLOCK(object);
961         while ((backing_object = object->backing_object) != NULL) {
962                 VM_OBJECT_WLOCK(backing_object);
963                 offset += object->backing_object_offset;
964                 VM_OBJECT_WUNLOCK(object);
965                 object = backing_object;
966                 if (object->size < OFF_TO_IDX(offset + size))
967                         size = IDX_TO_OFF(object->size) - offset;
968         }
969         /*
970          * Flush pages if writing is allowed, invalidate them
971          * if invalidation requested.  Pages undergoing I/O
972          * will be ignored by vm_object_page_remove().
973          *
974          * We cannot lock the vnode and then wait for paging
975          * to complete without deadlocking against vm_fault.
976          * Instead we simply call vm_object_page_remove() and
977          * allow it to block internally on a page-by-page
978          * basis when it encounters pages undergoing async
979          * I/O.
980          */
981         if (object->type == OBJT_VNODE &&
982             (object->flags & OBJ_MIGHTBEDIRTY) != 0 &&
983             ((vp = object->handle)->v_vflag & VV_NOSYNC) == 0) {
984                 VM_OBJECT_WUNLOCK(object);
985                 (void) vn_start_write(vp, &mp, V_WAIT);
986                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
987                 if (syncio && !invalidate && offset == 0 &&
988                     atop(size) == object->size) {
989                         /*
990                          * If syncing the whole mapping of the file,
991                          * it is faster to schedule all the writes in
992                          * async mode, also allowing the clustering,
993                          * and then wait for i/o to complete.
994                          */
995                         flags = 0;
996                         fsync_after = TRUE;
997                 } else {
998                         flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
999                         flags |= invalidate ? (OBJPC_SYNC | OBJPC_INVAL) : 0;
1000                         fsync_after = FALSE;
1001                 }
1002                 VM_OBJECT_WLOCK(object);
1003                 res = vm_object_page_clean(object, offset, offset + size,
1004                     flags);
1005                 VM_OBJECT_WUNLOCK(object);
1006                 if (fsync_after)
1007                         error = VOP_FSYNC(vp, MNT_WAIT, curthread);
1008                 VOP_UNLOCK(vp, 0);
1009                 vn_finished_write(mp);
1010                 if (error != 0)
1011                         res = FALSE;
1012                 VM_OBJECT_WLOCK(object);
1013         }
1014         if ((object->type == OBJT_VNODE ||
1015              object->type == OBJT_DEVICE) && invalidate) {
1016                 if (object->type == OBJT_DEVICE)
1017                         /*
1018                          * The option OBJPR_NOTMAPPED must be passed here
1019                          * because vm_object_page_remove() cannot remove
1020                          * unmanaged mappings.
1021                          */
1022                         flags = OBJPR_NOTMAPPED;
1023                 else if (old_msync)
1024                         flags = 0;
1025                 else
1026                         flags = OBJPR_CLEANONLY;
1027                 vm_object_page_remove(object, OFF_TO_IDX(offset),
1028                     OFF_TO_IDX(offset + size + PAGE_MASK), flags);
1029         }
1030         VM_OBJECT_WUNLOCK(object);
1031         return (res);
1032 }
1033
1034 /*
1035  * Determine whether the given advice can be applied to the object.  Advice is
1036  * not applied to unmanaged pages since they never belong to page queues, and
1037  * since MADV_FREE is destructive, it can apply only to anonymous pages that
1038  * have been mapped at most once.
1039  */
1040 static bool
1041 vm_object_advice_applies(vm_object_t object, int advice)
1042 {
1043
1044         if ((object->flags & OBJ_UNMANAGED) != 0)
1045                 return (false);
1046         if (advice != MADV_FREE)
1047                 return (true);
1048         return ((object->type == OBJT_DEFAULT || object->type == OBJT_SWAP) &&
1049             (object->flags & OBJ_ONEMAPPING) != 0);
1050 }
1051
1052 static void
1053 vm_object_madvise_freespace(vm_object_t object, int advice, vm_pindex_t pindex,
1054     vm_size_t size)
1055 {
1056
1057         if (advice == MADV_FREE && object->type == OBJT_SWAP)
1058                 swap_pager_freespace(object, pindex, size);
1059 }
1060
1061 /*
1062  *      vm_object_madvise:
1063  *
1064  *      Implements the madvise function at the object/page level.
1065  *
1066  *      MADV_WILLNEED   (any object)
1067  *
1068  *          Activate the specified pages if they are resident.
1069  *
1070  *      MADV_DONTNEED   (any object)
1071  *
1072  *          Deactivate the specified pages if they are resident.
1073  *
1074  *      MADV_FREE       (OBJT_DEFAULT/OBJT_SWAP objects,
1075  *                       OBJ_ONEMAPPING only)
1076  *
1077  *          Deactivate and clean the specified pages if they are
1078  *          resident.  This permits the process to reuse the pages
1079  *          without faulting or the kernel to reclaim the pages
1080  *          without I/O.
1081  */
1082 void
1083 vm_object_madvise(vm_object_t object, vm_pindex_t pindex, vm_pindex_t end,
1084     int advice)
1085 {
1086         vm_pindex_t tpindex;
1087         vm_object_t backing_object, tobject;
1088         vm_page_t m, tm;
1089
1090         if (object == NULL)
1091                 return;
1092
1093 relookup:
1094         VM_OBJECT_WLOCK(object);
1095         if (!vm_object_advice_applies(object, advice)) {
1096                 VM_OBJECT_WUNLOCK(object);
1097                 return;
1098         }
1099         for (m = vm_page_find_least(object, pindex); pindex < end; pindex++) {
1100                 tobject = object;
1101
1102                 /*
1103                  * If the next page isn't resident in the top-level object, we
1104                  * need to search the shadow chain.  When applying MADV_FREE, we
1105                  * take care to release any swap space used to store
1106                  * non-resident pages.
1107                  */
1108                 if (m == NULL || pindex < m->pindex) {
1109                         /*
1110                          * Optimize a common case: if the top-level object has
1111                          * no backing object, we can skip over the non-resident
1112                          * range in constant time.
1113                          */
1114                         if (object->backing_object == NULL) {
1115                                 tpindex = (m != NULL && m->pindex < end) ?
1116                                     m->pindex : end;
1117                                 vm_object_madvise_freespace(object, advice,
1118                                     pindex, tpindex - pindex);
1119                                 if ((pindex = tpindex) == end)
1120                                         break;
1121                                 goto next_page;
1122                         }
1123
1124                         tpindex = pindex;
1125                         do {
1126                                 vm_object_madvise_freespace(tobject, advice,
1127                                     tpindex, 1);
1128                                 /*
1129                                  * Prepare to search the next object in the
1130                                  * chain.
1131                                  */
1132                                 backing_object = tobject->backing_object;
1133                                 if (backing_object == NULL)
1134                                         goto next_pindex;
1135                                 VM_OBJECT_WLOCK(backing_object);
1136                                 tpindex +=
1137                                     OFF_TO_IDX(tobject->backing_object_offset);
1138                                 if (tobject != object)
1139                                         VM_OBJECT_WUNLOCK(tobject);
1140                                 tobject = backing_object;
1141                                 if (!vm_object_advice_applies(tobject, advice))
1142                                         goto next_pindex;
1143                         } while ((tm = vm_page_lookup(tobject, tpindex)) ==
1144                             NULL);
1145                 } else {
1146 next_page:
1147                         tm = m;
1148                         m = TAILQ_NEXT(m, listq);
1149                 }
1150
1151                 /*
1152                  * If the page is not in a normal state, skip it.
1153                  */
1154                 if (tm->valid != VM_PAGE_BITS_ALL ||
1155                     vm_page_wired(tm))
1156                         goto next_pindex;
1157                 KASSERT((tm->flags & PG_FICTITIOUS) == 0,
1158                     ("vm_object_madvise: page %p is fictitious", tm));
1159                 KASSERT((tm->oflags & VPO_UNMANAGED) == 0,
1160                     ("vm_object_madvise: page %p is not managed", tm));
1161                 if (vm_page_busied(tm)) {
1162                         if (object != tobject)
1163                                 VM_OBJECT_WUNLOCK(object);
1164                         if (advice == MADV_WILLNEED) {
1165                                 /*
1166                                  * Reference the page before unlocking and
1167                                  * sleeping so that the page daemon is less
1168                                  * likely to reclaim it.
1169                                  */
1170                                 vm_page_aflag_set(tm, PGA_REFERENCED);
1171                         }
1172                         vm_page_busy_sleep(tm, "madvpo", false);
1173                         goto relookup;
1174                 }
1175                 vm_page_lock(tm);
1176                 vm_page_advise(tm, advice);
1177                 vm_page_unlock(tm);
1178                 vm_object_madvise_freespace(tobject, advice, tm->pindex, 1);
1179 next_pindex:
1180                 if (tobject != object)
1181                         VM_OBJECT_WUNLOCK(tobject);
1182         }
1183         VM_OBJECT_WUNLOCK(object);
1184 }
1185
1186 /*
1187  *      vm_object_shadow:
1188  *
1189  *      Create a new object which is backed by the
1190  *      specified existing object range.  The source
1191  *      object reference is deallocated.
1192  *
1193  *      The new object and offset into that object
1194  *      are returned in the source parameters.
1195  */
1196 void
1197 vm_object_shadow(
1198         vm_object_t *object,    /* IN/OUT */
1199         vm_ooffset_t *offset,   /* IN/OUT */
1200         vm_size_t length)
1201 {
1202         vm_object_t source;
1203         vm_object_t result;
1204
1205         source = *object;
1206
1207         /*
1208          * Don't create the new object if the old object isn't shared.
1209          */
1210         if (source != NULL) {
1211                 VM_OBJECT_WLOCK(source);
1212                 if (source->ref_count == 1 &&
1213                     source->handle == NULL &&
1214                     (source->type == OBJT_DEFAULT ||
1215                      source->type == OBJT_SWAP)) {
1216                         VM_OBJECT_WUNLOCK(source);
1217                         return;
1218                 }
1219                 VM_OBJECT_WUNLOCK(source);
1220         }
1221
1222         /*
1223          * Allocate a new object with the given length.
1224          */
1225         result = vm_object_allocate(OBJT_DEFAULT, atop(length));
1226
1227         /*
1228          * The new object shadows the source object, adding a reference to it.
1229          * Our caller changes his reference to point to the new object,
1230          * removing a reference to the source object.  Net result: no change
1231          * of reference count.
1232          *
1233          * Try to optimize the result object's page color when shadowing
1234          * in order to maintain page coloring consistency in the combined 
1235          * shadowed object.
1236          */
1237         result->backing_object = source;
1238         /*
1239          * Store the offset into the source object, and fix up the offset into
1240          * the new object.
1241          */
1242         result->backing_object_offset = *offset;
1243         if (source != NULL) {
1244                 VM_OBJECT_WLOCK(source);
1245                 result->domain = source->domain;
1246                 LIST_INSERT_HEAD(&source->shadow_head, result, shadow_list);
1247                 source->shadow_count++;
1248 #if VM_NRESERVLEVEL > 0
1249                 result->flags |= source->flags & OBJ_COLORED;
1250                 result->pg_color = (source->pg_color + OFF_TO_IDX(*offset)) &
1251                     ((1 << (VM_NFREEORDER - 1)) - 1);
1252 #endif
1253                 VM_OBJECT_WUNLOCK(source);
1254         }
1255
1256
1257         /*
1258          * Return the new things
1259          */
1260         *offset = 0;
1261         *object = result;
1262 }
1263
1264 /*
1265  *      vm_object_split:
1266  *
1267  * Split the pages in a map entry into a new object.  This affords
1268  * easier removal of unused pages, and keeps object inheritance from
1269  * being a negative impact on memory usage.
1270  */
1271 void
1272 vm_object_split(vm_map_entry_t entry)
1273 {
1274         vm_page_t m, m_next;
1275         vm_object_t orig_object, new_object, source;
1276         vm_pindex_t idx, offidxstart;
1277         vm_size_t size;
1278
1279         orig_object = entry->object.vm_object;
1280         if (orig_object->type != OBJT_DEFAULT && orig_object->type != OBJT_SWAP)
1281                 return;
1282         if (orig_object->ref_count <= 1)
1283                 return;
1284         VM_OBJECT_WUNLOCK(orig_object);
1285
1286         offidxstart = OFF_TO_IDX(entry->offset);
1287         size = atop(entry->end - entry->start);
1288
1289         /*
1290          * If swap_pager_copy() is later called, it will convert new_object
1291          * into a swap object.
1292          */
1293         new_object = vm_object_allocate(OBJT_DEFAULT, size);
1294
1295         /*
1296          * At this point, the new object is still private, so the order in
1297          * which the original and new objects are locked does not matter.
1298          */
1299         VM_OBJECT_WLOCK(new_object);
1300         VM_OBJECT_WLOCK(orig_object);
1301         new_object->domain = orig_object->domain;
1302         source = orig_object->backing_object;
1303         if (source != NULL) {
1304                 VM_OBJECT_WLOCK(source);
1305                 if ((source->flags & OBJ_DEAD) != 0) {
1306                         VM_OBJECT_WUNLOCK(source);
1307                         VM_OBJECT_WUNLOCK(orig_object);
1308                         VM_OBJECT_WUNLOCK(new_object);
1309                         vm_object_deallocate(new_object);
1310                         VM_OBJECT_WLOCK(orig_object);
1311                         return;
1312                 }
1313                 LIST_INSERT_HEAD(&source->shadow_head,
1314                                   new_object, shadow_list);
1315                 source->shadow_count++;
1316                 vm_object_reference_locked(source);     /* for new_object */
1317                 vm_object_clear_flag(source, OBJ_ONEMAPPING);
1318                 VM_OBJECT_WUNLOCK(source);
1319                 new_object->backing_object_offset = 
1320                         orig_object->backing_object_offset + entry->offset;
1321                 new_object->backing_object = source;
1322         }
1323         if (orig_object->cred != NULL) {
1324                 new_object->cred = orig_object->cred;
1325                 crhold(orig_object->cred);
1326                 new_object->charge = ptoa(size);
1327                 KASSERT(orig_object->charge >= ptoa(size),
1328                     ("orig_object->charge < 0"));
1329                 orig_object->charge -= ptoa(size);
1330         }
1331 retry:
1332         m = vm_page_find_least(orig_object, offidxstart);
1333         for (; m != NULL && (idx = m->pindex - offidxstart) < size;
1334             m = m_next) {
1335                 m_next = TAILQ_NEXT(m, listq);
1336
1337                 /*
1338                  * We must wait for pending I/O to complete before we can
1339                  * rename the page.
1340                  *
1341                  * We do not have to VM_PROT_NONE the page as mappings should
1342                  * not be changed by this operation.
1343                  */
1344                 if (vm_page_busied(m)) {
1345                         VM_OBJECT_WUNLOCK(new_object);
1346                         vm_page_sleep_if_busy(m, "spltwt");
1347                         VM_OBJECT_WLOCK(new_object);
1348                         goto retry;
1349                 }
1350
1351                 /* vm_page_rename() will dirty the page. */
1352                 if (vm_page_rename(m, new_object, idx)) {
1353                         VM_OBJECT_WUNLOCK(new_object);
1354                         VM_OBJECT_WUNLOCK(orig_object);
1355                         vm_radix_wait();
1356                         VM_OBJECT_WLOCK(orig_object);
1357                         VM_OBJECT_WLOCK(new_object);
1358                         goto retry;
1359                 }
1360 #if VM_NRESERVLEVEL > 0
1361                 /*
1362                  * If some of the reservation's allocated pages remain with
1363                  * the original object, then transferring the reservation to
1364                  * the new object is neither particularly beneficial nor
1365                  * particularly harmful as compared to leaving the reservation
1366                  * with the original object.  If, however, all of the
1367                  * reservation's allocated pages are transferred to the new
1368                  * object, then transferring the reservation is typically
1369                  * beneficial.  Determining which of these two cases applies
1370                  * would be more costly than unconditionally renaming the
1371                  * reservation.
1372                  */
1373                 vm_reserv_rename(m, new_object, orig_object, offidxstart);
1374 #endif
1375                 if (orig_object->type == OBJT_SWAP)
1376                         vm_page_xbusy(m);
1377         }
1378         if (orig_object->type == OBJT_SWAP) {
1379                 /*
1380                  * swap_pager_copy() can sleep, in which case the orig_object's
1381                  * and new_object's locks are released and reacquired. 
1382                  */
1383                 swap_pager_copy(orig_object, new_object, offidxstart, 0);
1384                 TAILQ_FOREACH(m, &new_object->memq, listq)
1385                         vm_page_xunbusy(m);
1386         }
1387         VM_OBJECT_WUNLOCK(orig_object);
1388         VM_OBJECT_WUNLOCK(new_object);
1389         entry->object.vm_object = new_object;
1390         entry->offset = 0LL;
1391         vm_object_deallocate(orig_object);
1392         VM_OBJECT_WLOCK(new_object);
1393 }
1394
1395 #define OBSC_COLLAPSE_NOWAIT    0x0002
1396 #define OBSC_COLLAPSE_WAIT      0x0004
1397
1398 static vm_page_t
1399 vm_object_collapse_scan_wait(vm_object_t object, vm_page_t p, vm_page_t next,
1400     int op)
1401 {
1402         vm_object_t backing_object;
1403
1404         VM_OBJECT_ASSERT_WLOCKED(object);
1405         backing_object = object->backing_object;
1406         VM_OBJECT_ASSERT_WLOCKED(backing_object);
1407
1408         KASSERT(p == NULL || vm_page_busied(p), ("unbusy page %p", p));
1409         KASSERT(p == NULL || p->object == object || p->object == backing_object,
1410             ("invalid ownership %p %p %p", p, object, backing_object));
1411         if ((op & OBSC_COLLAPSE_NOWAIT) != 0)
1412                 return (next);
1413         /* The page is only NULL when rename fails. */
1414         if (p == NULL) {
1415                 vm_radix_wait();
1416         } else {
1417                 if (p->object == object)
1418                         VM_OBJECT_WUNLOCK(backing_object);
1419                 else
1420                         VM_OBJECT_WUNLOCK(object);
1421                 vm_page_busy_sleep(p, "vmocol", false);
1422         }
1423         VM_OBJECT_WLOCK(object);
1424         VM_OBJECT_WLOCK(backing_object);
1425         return (TAILQ_FIRST(&backing_object->memq));
1426 }
1427
1428 static bool
1429 vm_object_scan_all_shadowed(vm_object_t object)
1430 {
1431         vm_object_t backing_object;
1432         vm_page_t p, pp;
1433         vm_pindex_t backing_offset_index, new_pindex, pi, ps;
1434
1435         VM_OBJECT_ASSERT_WLOCKED(object);
1436         VM_OBJECT_ASSERT_WLOCKED(object->backing_object);
1437
1438         backing_object = object->backing_object;
1439
1440         if (backing_object->type != OBJT_DEFAULT &&
1441             backing_object->type != OBJT_SWAP)
1442                 return (false);
1443
1444         pi = backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
1445         p = vm_page_find_least(backing_object, pi);
1446         ps = swap_pager_find_least(backing_object, pi);
1447
1448         /*
1449          * Only check pages inside the parent object's range and
1450          * inside the parent object's mapping of the backing object.
1451          */
1452         for (;; pi++) {
1453                 if (p != NULL && p->pindex < pi)
1454                         p = TAILQ_NEXT(p, listq);
1455                 if (ps < pi)
1456                         ps = swap_pager_find_least(backing_object, pi);
1457                 if (p == NULL && ps >= backing_object->size)
1458                         break;
1459                 else if (p == NULL)
1460                         pi = ps;
1461                 else
1462                         pi = MIN(p->pindex, ps);
1463
1464                 new_pindex = pi - backing_offset_index;
1465                 if (new_pindex >= object->size)
1466                         break;
1467
1468                 /*
1469                  * See if the parent has the page or if the parent's object
1470                  * pager has the page.  If the parent has the page but the page
1471                  * is not valid, the parent's object pager must have the page.
1472                  *
1473                  * If this fails, the parent does not completely shadow the
1474                  * object and we might as well give up now.
1475                  */
1476                 pp = vm_page_lookup(object, new_pindex);
1477                 if ((pp == NULL || pp->valid == 0) &&
1478                     !vm_pager_has_page(object, new_pindex, NULL, NULL))
1479                         return (false);
1480         }
1481         return (true);
1482 }
1483
1484 static bool
1485 vm_object_collapse_scan(vm_object_t object, int op)
1486 {
1487         vm_object_t backing_object;
1488         vm_page_t next, p, pp;
1489         vm_pindex_t backing_offset_index, new_pindex;
1490
1491         VM_OBJECT_ASSERT_WLOCKED(object);
1492         VM_OBJECT_ASSERT_WLOCKED(object->backing_object);
1493
1494         backing_object = object->backing_object;
1495         backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
1496
1497         /*
1498          * Initial conditions
1499          */
1500         if ((op & OBSC_COLLAPSE_WAIT) != 0)
1501                 vm_object_set_flag(backing_object, OBJ_DEAD);
1502
1503         /*
1504          * Our scan
1505          */
1506         for (p = TAILQ_FIRST(&backing_object->memq); p != NULL; p = next) {
1507                 next = TAILQ_NEXT(p, listq);
1508                 new_pindex = p->pindex - backing_offset_index;
1509
1510                 /*
1511                  * Check for busy page
1512                  */
1513                 if (vm_page_busied(p)) {
1514                         next = vm_object_collapse_scan_wait(object, p, next, op);
1515                         continue;
1516                 }
1517
1518                 KASSERT(p->object == backing_object,
1519                     ("vm_object_collapse_scan: object mismatch"));
1520
1521                 if (p->pindex < backing_offset_index ||
1522                     new_pindex >= object->size) {
1523                         if (backing_object->type == OBJT_SWAP)
1524                                 swap_pager_freespace(backing_object, p->pindex,
1525                                     1);
1526
1527                         KASSERT(!pmap_page_is_mapped(p),
1528                             ("freeing mapped page %p", p));
1529                         if (vm_page_remove(p))
1530                                 vm_page_free(p);
1531                         continue;
1532                 }
1533
1534                 pp = vm_page_lookup(object, new_pindex);
1535                 if (pp != NULL && vm_page_busied(pp)) {
1536                         /*
1537                          * The page in the parent is busy and possibly not
1538                          * (yet) valid.  Until its state is finalized by the
1539                          * busy bit owner, we can't tell whether it shadows the
1540                          * original page.  Therefore, we must either skip it
1541                          * and the original (backing_object) page or wait for
1542                          * its state to be finalized.
1543                          *
1544                          * This is due to a race with vm_fault() where we must
1545                          * unbusy the original (backing_obj) page before we can
1546                          * (re)lock the parent.  Hence we can get here.
1547                          */
1548                         next = vm_object_collapse_scan_wait(object, pp, next,
1549                             op);
1550                         continue;
1551                 }
1552
1553                 KASSERT(pp == NULL || pp->valid != 0,
1554                     ("unbusy invalid page %p", pp));
1555
1556                 if (pp != NULL || vm_pager_has_page(object, new_pindex, NULL,
1557                         NULL)) {
1558                         /*
1559                          * The page already exists in the parent OR swap exists
1560                          * for this location in the parent.  Leave the parent's
1561                          * page alone.  Destroy the original page from the
1562                          * backing object.
1563                          */
1564                         if (backing_object->type == OBJT_SWAP)
1565                                 swap_pager_freespace(backing_object, p->pindex,
1566                                     1);
1567                         KASSERT(!pmap_page_is_mapped(p),
1568                             ("freeing mapped page %p", p));
1569                         if (vm_page_remove(p))
1570                                 vm_page_free(p);
1571                         continue;
1572                 }
1573
1574                 /*
1575                  * Page does not exist in parent, rename the page from the
1576                  * backing object to the main object.
1577                  *
1578                  * If the page was mapped to a process, it can remain mapped
1579                  * through the rename.  vm_page_rename() will dirty the page.
1580                  */
1581                 if (vm_page_rename(p, object, new_pindex)) {
1582                         next = vm_object_collapse_scan_wait(object, NULL, next,
1583                             op);
1584                         continue;
1585                 }
1586
1587                 /* Use the old pindex to free the right page. */
1588                 if (backing_object->type == OBJT_SWAP)
1589                         swap_pager_freespace(backing_object,
1590                             new_pindex + backing_offset_index, 1);
1591
1592 #if VM_NRESERVLEVEL > 0
1593                 /*
1594                  * Rename the reservation.
1595                  */
1596                 vm_reserv_rename(p, object, backing_object,
1597                     backing_offset_index);
1598 #endif
1599         }
1600         return (true);
1601 }
1602
1603
1604 /*
1605  * this version of collapse allows the operation to occur earlier and
1606  * when paging_in_progress is true for an object...  This is not a complete
1607  * operation, but should plug 99.9% of the rest of the leaks.
1608  */
1609 static void
1610 vm_object_qcollapse(vm_object_t object)
1611 {
1612         vm_object_t backing_object = object->backing_object;
1613
1614         VM_OBJECT_ASSERT_WLOCKED(object);
1615         VM_OBJECT_ASSERT_WLOCKED(backing_object);
1616
1617         if (backing_object->ref_count != 1)
1618                 return;
1619
1620         vm_object_collapse_scan(object, OBSC_COLLAPSE_NOWAIT);
1621 }
1622
1623 /*
1624  *      vm_object_collapse:
1625  *
1626  *      Collapse an object with the object backing it.
1627  *      Pages in the backing object are moved into the
1628  *      parent, and the backing object is deallocated.
1629  */
1630 void
1631 vm_object_collapse(vm_object_t object)
1632 {
1633         vm_object_t backing_object, new_backing_object;
1634
1635         VM_OBJECT_ASSERT_WLOCKED(object);
1636
1637         while (TRUE) {
1638                 /*
1639                  * Verify that the conditions are right for collapse:
1640                  *
1641                  * The object exists and the backing object exists.
1642                  */
1643                 if ((backing_object = object->backing_object) == NULL)
1644                         break;
1645
1646                 /*
1647                  * we check the backing object first, because it is most likely
1648                  * not collapsable.
1649                  */
1650                 VM_OBJECT_WLOCK(backing_object);
1651                 if (backing_object->handle != NULL ||
1652                     (backing_object->type != OBJT_DEFAULT &&
1653                     backing_object->type != OBJT_SWAP) ||
1654                     (backing_object->flags & (OBJ_DEAD | OBJ_NOSPLIT)) != 0 ||
1655                     object->handle != NULL ||
1656                     (object->type != OBJT_DEFAULT &&
1657                      object->type != OBJT_SWAP) ||
1658                     (object->flags & OBJ_DEAD)) {
1659                         VM_OBJECT_WUNLOCK(backing_object);
1660                         break;
1661                 }
1662
1663                 if (REFCOUNT_COUNT(object->paging_in_progress) > 0 ||
1664                     REFCOUNT_COUNT(backing_object->paging_in_progress) > 0) {
1665                         vm_object_qcollapse(object);
1666                         VM_OBJECT_WUNLOCK(backing_object);
1667                         break;
1668                 }
1669
1670                 /*
1671                  * We know that we can either collapse the backing object (if
1672                  * the parent is the only reference to it) or (perhaps) have
1673                  * the parent bypass the object if the parent happens to shadow
1674                  * all the resident pages in the entire backing object.
1675                  *
1676                  * This is ignoring pager-backed pages such as swap pages.
1677                  * vm_object_collapse_scan fails the shadowing test in this
1678                  * case.
1679                  */
1680                 if (backing_object->ref_count == 1) {
1681                         vm_object_pip_add(object, 1);
1682                         vm_object_pip_add(backing_object, 1);
1683
1684                         /*
1685                          * If there is exactly one reference to the backing
1686                          * object, we can collapse it into the parent.
1687                          */
1688                         vm_object_collapse_scan(object, OBSC_COLLAPSE_WAIT);
1689
1690 #if VM_NRESERVLEVEL > 0
1691                         /*
1692                          * Break any reservations from backing_object.
1693                          */
1694                         if (__predict_false(!LIST_EMPTY(&backing_object->rvq)))
1695                                 vm_reserv_break_all(backing_object);
1696 #endif
1697
1698                         /*
1699                          * Move the pager from backing_object to object.
1700                          */
1701                         if (backing_object->type == OBJT_SWAP) {
1702                                 /*
1703                                  * swap_pager_copy() can sleep, in which case
1704                                  * the backing_object's and object's locks are
1705                                  * released and reacquired.
1706                                  * Since swap_pager_copy() is being asked to
1707                                  * destroy the source, it will change the
1708                                  * backing_object's type to OBJT_DEFAULT.
1709                                  */
1710                                 swap_pager_copy(
1711                                     backing_object,
1712                                     object,
1713                                     OFF_TO_IDX(object->backing_object_offset), TRUE);
1714                         }
1715                         /*
1716                          * Object now shadows whatever backing_object did.
1717                          * Note that the reference to 
1718                          * backing_object->backing_object moves from within 
1719                          * backing_object to within object.
1720                          */
1721                         LIST_REMOVE(object, shadow_list);
1722                         backing_object->shadow_count--;
1723                         if (backing_object->backing_object) {
1724                                 VM_OBJECT_WLOCK(backing_object->backing_object);
1725                                 LIST_REMOVE(backing_object, shadow_list);
1726                                 LIST_INSERT_HEAD(
1727                                     &backing_object->backing_object->shadow_head,
1728                                     object, shadow_list);
1729                                 /*
1730                                  * The shadow_count has not changed.
1731                                  */
1732                                 VM_OBJECT_WUNLOCK(backing_object->backing_object);
1733                         }
1734                         object->backing_object = backing_object->backing_object;
1735                         object->backing_object_offset +=
1736                             backing_object->backing_object_offset;
1737
1738                         /*
1739                          * Discard backing_object.
1740                          *
1741                          * Since the backing object has no pages, no pager left,
1742                          * and no object references within it, all that is
1743                          * necessary is to dispose of it.
1744                          */
1745                         KASSERT(backing_object->ref_count == 1, (
1746 "backing_object %p was somehow re-referenced during collapse!",
1747                             backing_object));
1748                         vm_object_pip_wakeup(backing_object);
1749                         backing_object->type = OBJT_DEAD;
1750                         backing_object->ref_count = 0;
1751                         VM_OBJECT_WUNLOCK(backing_object);
1752                         vm_object_destroy(backing_object);
1753
1754                         vm_object_pip_wakeup(object);
1755                         counter_u64_add(object_collapses, 1);
1756                 } else {
1757                         /*
1758                          * If we do not entirely shadow the backing object,
1759                          * there is nothing we can do so we give up.
1760                          */
1761                         if (object->resident_page_count != object->size &&
1762                             !vm_object_scan_all_shadowed(object)) {
1763                                 VM_OBJECT_WUNLOCK(backing_object);
1764                                 break;
1765                         }
1766
1767                         /*
1768                          * Make the parent shadow the next object in the
1769                          * chain.  Deallocating backing_object will not remove
1770                          * it, since its reference count is at least 2.
1771                          */
1772                         LIST_REMOVE(object, shadow_list);
1773                         backing_object->shadow_count--;
1774
1775                         new_backing_object = backing_object->backing_object;
1776                         if ((object->backing_object = new_backing_object) != NULL) {
1777                                 VM_OBJECT_WLOCK(new_backing_object);
1778                                 LIST_INSERT_HEAD(
1779                                     &new_backing_object->shadow_head,
1780                                     object,
1781                                     shadow_list
1782                                 );
1783                                 new_backing_object->shadow_count++;
1784                                 vm_object_reference_locked(new_backing_object);
1785                                 VM_OBJECT_WUNLOCK(new_backing_object);
1786                                 object->backing_object_offset +=
1787                                         backing_object->backing_object_offset;
1788                         }
1789
1790                         /*
1791                          * Drop the reference count on backing_object. Since
1792                          * its ref_count was at least 2, it will not vanish.
1793                          */
1794                         backing_object->ref_count--;
1795                         VM_OBJECT_WUNLOCK(backing_object);
1796                         counter_u64_add(object_bypasses, 1);
1797                 }
1798
1799                 /*
1800                  * Try again with this object's new backing object.
1801                  */
1802         }
1803 }
1804
1805 /*
1806  *      vm_object_page_remove:
1807  *
1808  *      For the given object, either frees or invalidates each of the
1809  *      specified pages.  In general, a page is freed.  However, if a page is
1810  *      wired for any reason other than the existence of a managed, wired
1811  *      mapping, then it may be invalidated but not removed from the object.
1812  *      Pages are specified by the given range ["start", "end") and the option
1813  *      OBJPR_CLEANONLY.  As a special case, if "end" is zero, then the range
1814  *      extends from "start" to the end of the object.  If the option
1815  *      OBJPR_CLEANONLY is specified, then only the non-dirty pages within the
1816  *      specified range are affected.  If the option OBJPR_NOTMAPPED is
1817  *      specified, then the pages within the specified range must have no
1818  *      mappings.  Otherwise, if this option is not specified, any mappings to
1819  *      the specified pages are removed before the pages are freed or
1820  *      invalidated.
1821  *
1822  *      In general, this operation should only be performed on objects that
1823  *      contain managed pages.  There are, however, two exceptions.  First, it
1824  *      is performed on the kernel and kmem objects by vm_map_entry_delete().
1825  *      Second, it is used by msync(..., MS_INVALIDATE) to invalidate device-
1826  *      backed pages.  In both of these cases, the option OBJPR_CLEANONLY must
1827  *      not be specified and the option OBJPR_NOTMAPPED must be specified.
1828  *
1829  *      The object must be locked.
1830  */
1831 void
1832 vm_object_page_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
1833     int options)
1834 {
1835         vm_page_t p, next;
1836
1837         VM_OBJECT_ASSERT_WLOCKED(object);
1838         KASSERT((object->flags & OBJ_UNMANAGED) == 0 ||
1839             (options & (OBJPR_CLEANONLY | OBJPR_NOTMAPPED)) == OBJPR_NOTMAPPED,
1840             ("vm_object_page_remove: illegal options for object %p", object));
1841         if (object->resident_page_count == 0)
1842                 return;
1843         vm_object_pip_add(object, 1);
1844 again:
1845         p = vm_page_find_least(object, start);
1846
1847         /*
1848          * Here, the variable "p" is either (1) the page with the least pindex
1849          * greater than or equal to the parameter "start" or (2) NULL. 
1850          */
1851         for (; p != NULL && (p->pindex < end || end == 0); p = next) {
1852                 next = TAILQ_NEXT(p, listq);
1853
1854                 /*
1855                  * If the page is wired for any reason besides the existence
1856                  * of managed, wired mappings, then it cannot be freed.  For
1857                  * example, fictitious pages, which represent device memory,
1858                  * are inherently wired and cannot be freed.  They can,
1859                  * however, be invalidated if the option OBJPR_CLEANONLY is
1860                  * not specified.
1861                  */
1862                 if (vm_page_busied(p)) {
1863                         vm_page_sleep_if_busy(p, "vmopar");
1864                         goto again;
1865                 }
1866                 if (vm_page_wired(p)) {
1867 wired:
1868                         if ((options & OBJPR_NOTMAPPED) == 0 &&
1869                             object->ref_count != 0)
1870                                 pmap_remove_all(p);
1871                         if ((options & OBJPR_CLEANONLY) == 0) {
1872                                 p->valid = 0;
1873                                 vm_page_undirty(p);
1874                         }
1875                         continue;
1876                 }
1877                 KASSERT((p->flags & PG_FICTITIOUS) == 0,
1878                     ("vm_object_page_remove: page %p is fictitious", p));
1879                 if ((options & OBJPR_CLEANONLY) != 0 && p->valid != 0) {
1880                         if ((options & OBJPR_NOTMAPPED) == 0 &&
1881                             object->ref_count != 0 &&
1882                             !vm_page_try_remove_write(p))
1883                                 goto wired;
1884                         if (p->dirty != 0)
1885                                 continue;
1886                 }
1887                 if ((options & OBJPR_NOTMAPPED) == 0 &&
1888                     object->ref_count != 0 && !vm_page_try_remove_all(p))
1889                         goto wired;
1890                 vm_page_free(p);
1891         }
1892         vm_object_pip_wakeup(object);
1893 }
1894
1895 /*
1896  *      vm_object_page_noreuse:
1897  *
1898  *      For the given object, attempt to move the specified pages to
1899  *      the head of the inactive queue.  This bypasses regular LRU
1900  *      operation and allows the pages to be reused quickly under memory
1901  *      pressure.  If a page is wired for any reason, then it will not
1902  *      be queued.  Pages are specified by the range ["start", "end").
1903  *      As a special case, if "end" is zero, then the range extends from
1904  *      "start" to the end of the object.
1905  *
1906  *      This operation should only be performed on objects that
1907  *      contain non-fictitious, managed pages.
1908  *
1909  *      The object must be locked.
1910  */
1911 void
1912 vm_object_page_noreuse(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1913 {
1914         struct mtx *mtx;
1915         vm_page_t p, next;
1916
1917         VM_OBJECT_ASSERT_LOCKED(object);
1918         KASSERT((object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0,
1919             ("vm_object_page_noreuse: illegal object %p", object));
1920         if (object->resident_page_count == 0)
1921                 return;
1922         p = vm_page_find_least(object, start);
1923
1924         /*
1925          * Here, the variable "p" is either (1) the page with the least pindex
1926          * greater than or equal to the parameter "start" or (2) NULL. 
1927          */
1928         mtx = NULL;
1929         for (; p != NULL && (p->pindex < end || end == 0); p = next) {
1930                 next = TAILQ_NEXT(p, listq);
1931                 vm_page_change_lock(p, &mtx);
1932                 vm_page_deactivate_noreuse(p);
1933         }
1934         if (mtx != NULL)
1935                 mtx_unlock(mtx);
1936 }
1937
1938 /*
1939  *      Populate the specified range of the object with valid pages.  Returns
1940  *      TRUE if the range is successfully populated and FALSE otherwise.
1941  *
1942  *      Note: This function should be optimized to pass a larger array of
1943  *      pages to vm_pager_get_pages() before it is applied to a non-
1944  *      OBJT_DEVICE object.
1945  *
1946  *      The object must be locked.
1947  */
1948 boolean_t
1949 vm_object_populate(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1950 {
1951         vm_page_t m;
1952         vm_pindex_t pindex;
1953         int rv;
1954
1955         VM_OBJECT_ASSERT_WLOCKED(object);
1956         for (pindex = start; pindex < end; pindex++) {
1957                 rv = vm_page_grab_valid(&m, object, pindex, VM_ALLOC_NORMAL);
1958                 if (rv != VM_PAGER_OK)
1959                         break;
1960
1961                 /*
1962                  * Keep "m" busy because a subsequent iteration may unlock
1963                  * the object.
1964                  */
1965         }
1966         if (pindex > start) {
1967                 m = vm_page_lookup(object, start);
1968                 while (m != NULL && m->pindex < pindex) {
1969                         vm_page_xunbusy(m);
1970                         m = TAILQ_NEXT(m, listq);
1971                 }
1972         }
1973         return (pindex == end);
1974 }
1975
1976 /*
1977  *      Routine:        vm_object_coalesce
1978  *      Function:       Coalesces two objects backing up adjoining
1979  *                      regions of memory into a single object.
1980  *
1981  *      returns TRUE if objects were combined.
1982  *
1983  *      NOTE:   Only works at the moment if the second object is NULL -
1984  *              if it's not, which object do we lock first?
1985  *
1986  *      Parameters:
1987  *              prev_object     First object to coalesce
1988  *              prev_offset     Offset into prev_object
1989  *              prev_size       Size of reference to prev_object
1990  *              next_size       Size of reference to the second object
1991  *              reserved        Indicator that extension region has
1992  *                              swap accounted for
1993  *
1994  *      Conditions:
1995  *      The object must *not* be locked.
1996  */
1997 boolean_t
1998 vm_object_coalesce(vm_object_t prev_object, vm_ooffset_t prev_offset,
1999     vm_size_t prev_size, vm_size_t next_size, boolean_t reserved)
2000 {
2001         vm_pindex_t next_pindex;
2002
2003         if (prev_object == NULL)
2004                 return (TRUE);
2005         VM_OBJECT_WLOCK(prev_object);
2006         if ((prev_object->type != OBJT_DEFAULT &&
2007             prev_object->type != OBJT_SWAP) ||
2008             (prev_object->flags & OBJ_NOSPLIT) != 0) {
2009                 VM_OBJECT_WUNLOCK(prev_object);
2010                 return (FALSE);
2011         }
2012
2013         /*
2014          * Try to collapse the object first
2015          */
2016         vm_object_collapse(prev_object);
2017
2018         /*
2019          * Can't coalesce if: . more than one reference . paged out . shadows
2020          * another object . has a copy elsewhere (any of which mean that the
2021          * pages not mapped to prev_entry may be in use anyway)
2022          */
2023         if (prev_object->backing_object != NULL) {
2024                 VM_OBJECT_WUNLOCK(prev_object);
2025                 return (FALSE);
2026         }
2027
2028         prev_size >>= PAGE_SHIFT;
2029         next_size >>= PAGE_SHIFT;
2030         next_pindex = OFF_TO_IDX(prev_offset) + prev_size;
2031
2032         if (prev_object->ref_count > 1 &&
2033             prev_object->size != next_pindex &&
2034             (prev_object->flags & OBJ_ONEMAPPING) == 0) {
2035                 VM_OBJECT_WUNLOCK(prev_object);
2036                 return (FALSE);
2037         }
2038
2039         /*
2040          * Account for the charge.
2041          */
2042         if (prev_object->cred != NULL) {
2043
2044                 /*
2045                  * If prev_object was charged, then this mapping,
2046                  * although not charged now, may become writable
2047                  * later. Non-NULL cred in the object would prevent
2048                  * swap reservation during enabling of the write
2049                  * access, so reserve swap now. Failed reservation
2050                  * cause allocation of the separate object for the map
2051                  * entry, and swap reservation for this entry is
2052                  * managed in appropriate time.
2053                  */
2054                 if (!reserved && !swap_reserve_by_cred(ptoa(next_size),
2055                     prev_object->cred)) {
2056                         VM_OBJECT_WUNLOCK(prev_object);
2057                         return (FALSE);
2058                 }
2059                 prev_object->charge += ptoa(next_size);
2060         }
2061
2062         /*
2063          * Remove any pages that may still be in the object from a previous
2064          * deallocation.
2065          */
2066         if (next_pindex < prev_object->size) {
2067                 vm_object_page_remove(prev_object, next_pindex, next_pindex +
2068                     next_size, 0);
2069                 if (prev_object->type == OBJT_SWAP)
2070                         swap_pager_freespace(prev_object,
2071                                              next_pindex, next_size);
2072 #if 0
2073                 if (prev_object->cred != NULL) {
2074                         KASSERT(prev_object->charge >=
2075                             ptoa(prev_object->size - next_pindex),
2076                             ("object %p overcharged 1 %jx %jx", prev_object,
2077                                 (uintmax_t)next_pindex, (uintmax_t)next_size));
2078                         prev_object->charge -= ptoa(prev_object->size -
2079                             next_pindex);
2080                 }
2081 #endif
2082         }
2083
2084         /*
2085          * Extend the object if necessary.
2086          */
2087         if (next_pindex + next_size > prev_object->size)
2088                 prev_object->size = next_pindex + next_size;
2089
2090         VM_OBJECT_WUNLOCK(prev_object);
2091         return (TRUE);
2092 }
2093
2094 void
2095 vm_object_set_writeable_dirty(vm_object_t object)
2096 {
2097
2098         VM_OBJECT_ASSERT_WLOCKED(object);
2099         if (object->type != OBJT_VNODE) {
2100                 if ((object->flags & OBJ_TMPFS_NODE) != 0) {
2101                         KASSERT(object->type == OBJT_SWAP, ("non-swap tmpfs"));
2102                         vm_object_set_flag(object, OBJ_TMPFS_DIRTY);
2103                 }
2104                 return;
2105         }
2106         object->generation++;
2107         if ((object->flags & OBJ_MIGHTBEDIRTY) != 0)
2108                 return;
2109         vm_object_set_flag(object, OBJ_MIGHTBEDIRTY);
2110 }
2111
2112 /*
2113  *      vm_object_unwire:
2114  *
2115  *      For each page offset within the specified range of the given object,
2116  *      find the highest-level page in the shadow chain and unwire it.  A page
2117  *      must exist at every page offset, and the highest-level page must be
2118  *      wired.
2119  */
2120 void
2121 vm_object_unwire(vm_object_t object, vm_ooffset_t offset, vm_size_t length,
2122     uint8_t queue)
2123 {
2124         vm_object_t tobject, t1object;
2125         vm_page_t m, tm;
2126         vm_pindex_t end_pindex, pindex, tpindex;
2127         int depth, locked_depth;
2128
2129         KASSERT((offset & PAGE_MASK) == 0,
2130             ("vm_object_unwire: offset is not page aligned"));
2131         KASSERT((length & PAGE_MASK) == 0,
2132             ("vm_object_unwire: length is not a multiple of PAGE_SIZE"));
2133         /* The wired count of a fictitious page never changes. */
2134         if ((object->flags & OBJ_FICTITIOUS) != 0)
2135                 return;
2136         pindex = OFF_TO_IDX(offset);
2137         end_pindex = pindex + atop(length);
2138 again:
2139         locked_depth = 1;
2140         VM_OBJECT_RLOCK(object);
2141         m = vm_page_find_least(object, pindex);
2142         while (pindex < end_pindex) {
2143                 if (m == NULL || pindex < m->pindex) {
2144                         /*
2145                          * The first object in the shadow chain doesn't
2146                          * contain a page at the current index.  Therefore,
2147                          * the page must exist in a backing object.
2148                          */
2149                         tobject = object;
2150                         tpindex = pindex;
2151                         depth = 0;
2152                         do {
2153                                 tpindex +=
2154                                     OFF_TO_IDX(tobject->backing_object_offset);
2155                                 tobject = tobject->backing_object;
2156                                 KASSERT(tobject != NULL,
2157                                     ("vm_object_unwire: missing page"));
2158                                 if ((tobject->flags & OBJ_FICTITIOUS) != 0)
2159                                         goto next_page;
2160                                 depth++;
2161                                 if (depth == locked_depth) {
2162                                         locked_depth++;
2163                                         VM_OBJECT_RLOCK(tobject);
2164                                 }
2165                         } while ((tm = vm_page_lookup(tobject, tpindex)) ==
2166                             NULL);
2167                 } else {
2168                         tm = m;
2169                         m = TAILQ_NEXT(m, listq);
2170                 }
2171                 if (vm_page_xbusied(tm)) {
2172                         for (tobject = object; locked_depth > 1;
2173                             locked_depth--) {
2174                                 t1object = tobject->backing_object;
2175                                 VM_OBJECT_RUNLOCK(tobject);
2176                                 tobject = t1object;
2177                         }
2178                         vm_page_busy_sleep(tm, "unwbo", true);
2179                         goto again;
2180                 }
2181                 vm_page_unwire(tm, queue);
2182 next_page:
2183                 pindex++;
2184         }
2185         /* Release the accumulated object locks. */
2186         for (tobject = object; locked_depth >= 1; locked_depth--) {
2187                 t1object = tobject->backing_object;
2188                 VM_OBJECT_RUNLOCK(tobject);
2189                 tobject = t1object;
2190         }
2191 }
2192
2193 /*
2194  * Return the vnode for the given object, or NULL if none exists.
2195  * For tmpfs objects, the function may return NULL if there is
2196  * no vnode allocated at the time of the call.
2197  */
2198 struct vnode *
2199 vm_object_vnode(vm_object_t object)
2200 {
2201         struct vnode *vp;
2202
2203         VM_OBJECT_ASSERT_LOCKED(object);
2204         if (object->type == OBJT_VNODE) {
2205                 vp = object->handle;
2206                 KASSERT(vp != NULL, ("%s: OBJT_VNODE has no vnode", __func__));
2207         } else if (object->type == OBJT_SWAP &&
2208             (object->flags & OBJ_TMPFS) != 0) {
2209                 vp = object->un_pager.swp.swp_tmpfs;
2210                 KASSERT(vp != NULL, ("%s: OBJT_TMPFS has no vnode", __func__));
2211         } else {
2212                 vp = NULL;
2213         }
2214         return (vp);
2215 }
2216
2217 /*
2218  * Return the kvme type of the given object.
2219  * If vpp is not NULL, set it to the object's vm_object_vnode() or NULL.
2220  */
2221 int
2222 vm_object_kvme_type(vm_object_t object, struct vnode **vpp)
2223 {
2224
2225         VM_OBJECT_ASSERT_LOCKED(object);
2226         if (vpp != NULL)
2227                 *vpp = vm_object_vnode(object);
2228         switch (object->type) {
2229         case OBJT_DEFAULT:
2230                 return (KVME_TYPE_DEFAULT);
2231         case OBJT_VNODE:
2232                 return (KVME_TYPE_VNODE);
2233         case OBJT_SWAP:
2234                 if ((object->flags & OBJ_TMPFS_NODE) != 0)
2235                         return (KVME_TYPE_VNODE);
2236                 return (KVME_TYPE_SWAP);
2237         case OBJT_DEVICE:
2238                 return (KVME_TYPE_DEVICE);
2239         case OBJT_PHYS:
2240                 return (KVME_TYPE_PHYS);
2241         case OBJT_DEAD:
2242                 return (KVME_TYPE_DEAD);
2243         case OBJT_SG:
2244                 return (KVME_TYPE_SG);
2245         case OBJT_MGTDEVICE:
2246                 return (KVME_TYPE_MGTDEVICE);
2247         default:
2248                 return (KVME_TYPE_UNKNOWN);
2249         }
2250 }
2251
2252 static int
2253 sysctl_vm_object_list(SYSCTL_HANDLER_ARGS)
2254 {
2255         struct kinfo_vmobject *kvo;
2256         char *fullpath, *freepath;
2257         struct vnode *vp;
2258         struct vattr va;
2259         vm_object_t obj;
2260         vm_page_t m;
2261         int count, error;
2262
2263         if (req->oldptr == NULL) {
2264                 /*
2265                  * If an old buffer has not been provided, generate an
2266                  * estimate of the space needed for a subsequent call.
2267                  */
2268                 mtx_lock(&vm_object_list_mtx);
2269                 count = 0;
2270                 TAILQ_FOREACH(obj, &vm_object_list, object_list) {
2271                         if (obj->type == OBJT_DEAD)
2272                                 continue;
2273                         count++;
2274                 }
2275                 mtx_unlock(&vm_object_list_mtx);
2276                 return (SYSCTL_OUT(req, NULL, sizeof(struct kinfo_vmobject) *
2277                     count * 11 / 10));
2278         }
2279
2280         kvo = malloc(sizeof(*kvo), M_TEMP, M_WAITOK);
2281         error = 0;
2282
2283         /*
2284          * VM objects are type stable and are never removed from the
2285          * list once added.  This allows us to safely read obj->object_list
2286          * after reacquiring the VM object lock.
2287          */
2288         mtx_lock(&vm_object_list_mtx);
2289         TAILQ_FOREACH(obj, &vm_object_list, object_list) {
2290                 if (obj->type == OBJT_DEAD)
2291                         continue;
2292                 VM_OBJECT_RLOCK(obj);
2293                 if (obj->type == OBJT_DEAD) {
2294                         VM_OBJECT_RUNLOCK(obj);
2295                         continue;
2296                 }
2297                 mtx_unlock(&vm_object_list_mtx);
2298                 kvo->kvo_size = ptoa(obj->size);
2299                 kvo->kvo_resident = obj->resident_page_count;
2300                 kvo->kvo_ref_count = obj->ref_count;
2301                 kvo->kvo_shadow_count = obj->shadow_count;
2302                 kvo->kvo_memattr = obj->memattr;
2303                 kvo->kvo_active = 0;
2304                 kvo->kvo_inactive = 0;
2305                 TAILQ_FOREACH(m, &obj->memq, listq) {
2306                         /*
2307                          * A page may belong to the object but be
2308                          * dequeued and set to PQ_NONE while the
2309                          * object lock is not held.  This makes the
2310                          * reads of m->queue below racy, and we do not
2311                          * count pages set to PQ_NONE.  However, this
2312                          * sysctl is only meant to give an
2313                          * approximation of the system anyway.
2314                          */
2315                         if (m->queue == PQ_ACTIVE)
2316                                 kvo->kvo_active++;
2317                         else if (m->queue == PQ_INACTIVE)
2318                                 kvo->kvo_inactive++;
2319                 }
2320
2321                 kvo->kvo_vn_fileid = 0;
2322                 kvo->kvo_vn_fsid = 0;
2323                 kvo->kvo_vn_fsid_freebsd11 = 0;
2324                 freepath = NULL;
2325                 fullpath = "";
2326                 kvo->kvo_type = vm_object_kvme_type(obj, &vp);
2327                 if (vp != NULL)
2328                         vref(vp);
2329                 VM_OBJECT_RUNLOCK(obj);
2330                 if (vp != NULL) {
2331                         vn_fullpath(curthread, vp, &fullpath, &freepath);
2332                         vn_lock(vp, LK_SHARED | LK_RETRY);
2333                         if (VOP_GETATTR(vp, &va, curthread->td_ucred) == 0) {
2334                                 kvo->kvo_vn_fileid = va.va_fileid;
2335                                 kvo->kvo_vn_fsid = va.va_fsid;
2336                                 kvo->kvo_vn_fsid_freebsd11 = va.va_fsid;
2337                                                                 /* truncate */
2338                         }
2339                         vput(vp);
2340                 }
2341
2342                 strlcpy(kvo->kvo_path, fullpath, sizeof(kvo->kvo_path));
2343                 if (freepath != NULL)
2344                         free(freepath, M_TEMP);
2345
2346                 /* Pack record size down */
2347                 kvo->kvo_structsize = offsetof(struct kinfo_vmobject, kvo_path)
2348                     + strlen(kvo->kvo_path) + 1;
2349                 kvo->kvo_structsize = roundup(kvo->kvo_structsize,
2350                     sizeof(uint64_t));
2351                 error = SYSCTL_OUT(req, kvo, kvo->kvo_structsize);
2352                 mtx_lock(&vm_object_list_mtx);
2353                 if (error)
2354                         break;
2355         }
2356         mtx_unlock(&vm_object_list_mtx);
2357         free(kvo, M_TEMP);
2358         return (error);
2359 }
2360 SYSCTL_PROC(_vm, OID_AUTO, objects, CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_SKIP |
2361     CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_object_list, "S,kinfo_vmobject",
2362     "List of VM objects");
2363
2364 #include "opt_ddb.h"
2365 #ifdef DDB
2366 #include <sys/kernel.h>
2367
2368 #include <sys/cons.h>
2369
2370 #include <ddb/ddb.h>
2371
2372 static int
2373 _vm_object_in_map(vm_map_t map, vm_object_t object, vm_map_entry_t entry)
2374 {
2375         vm_map_t tmpm;
2376         vm_map_entry_t tmpe;
2377         vm_object_t obj;
2378         int entcount;
2379
2380         if (map == 0)
2381                 return 0;
2382
2383         if (entry == 0) {
2384                 tmpe = map->header.next;
2385                 entcount = map->nentries;
2386                 while (entcount-- && (tmpe != &map->header)) {
2387                         if (_vm_object_in_map(map, object, tmpe)) {
2388                                 return 1;
2389                         }
2390                         tmpe = tmpe->next;
2391                 }
2392         } else if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
2393                 tmpm = entry->object.sub_map;
2394                 tmpe = tmpm->header.next;
2395                 entcount = tmpm->nentries;
2396                 while (entcount-- && tmpe != &tmpm->header) {
2397                         if (_vm_object_in_map(tmpm, object, tmpe)) {
2398                                 return 1;
2399                         }
2400                         tmpe = tmpe->next;
2401                 }
2402         } else if ((obj = entry->object.vm_object) != NULL) {
2403                 for (; obj; obj = obj->backing_object)
2404                         if (obj == object) {
2405                                 return 1;
2406                         }
2407         }
2408         return 0;
2409 }
2410
2411 static int
2412 vm_object_in_map(vm_object_t object)
2413 {
2414         struct proc *p;
2415
2416         /* sx_slock(&allproc_lock); */
2417         FOREACH_PROC_IN_SYSTEM(p) {
2418                 if (!p->p_vmspace /* || (p->p_flag & (P_SYSTEM|P_WEXIT)) */)
2419                         continue;
2420                 if (_vm_object_in_map(&p->p_vmspace->vm_map, object, 0)) {
2421                         /* sx_sunlock(&allproc_lock); */
2422                         return 1;
2423                 }
2424         }
2425         /* sx_sunlock(&allproc_lock); */
2426         if (_vm_object_in_map(kernel_map, object, 0))
2427                 return 1;
2428         return 0;
2429 }
2430
2431 DB_SHOW_COMMAND(vmochk, vm_object_check)
2432 {
2433         vm_object_t object;
2434
2435         /*
2436          * make sure that internal objs are in a map somewhere
2437          * and none have zero ref counts.
2438          */
2439         TAILQ_FOREACH(object, &vm_object_list, object_list) {
2440                 if (object->handle == NULL &&
2441                     (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
2442                         if (object->ref_count == 0) {
2443                                 db_printf("vmochk: internal obj has zero ref count: %ld\n",
2444                                         (long)object->size);
2445                         }
2446                         if (!vm_object_in_map(object)) {
2447                                 db_printf(
2448                         "vmochk: internal obj is not in a map: "
2449                         "ref: %d, size: %lu: 0x%lx, backing_object: %p\n",
2450                                     object->ref_count, (u_long)object->size, 
2451                                     (u_long)object->size,
2452                                     (void *)object->backing_object);
2453                         }
2454                 }
2455         }
2456 }
2457
2458 /*
2459  *      vm_object_print:        [ debug ]
2460  */
2461 DB_SHOW_COMMAND(object, vm_object_print_static)
2462 {
2463         /* XXX convert args. */
2464         vm_object_t object = (vm_object_t)addr;
2465         boolean_t full = have_addr;
2466
2467         vm_page_t p;
2468
2469         /* XXX count is an (unused) arg.  Avoid shadowing it. */
2470 #define count   was_count
2471
2472         int count;
2473
2474         if (object == NULL)
2475                 return;
2476
2477         db_iprintf(
2478             "Object %p: type=%d, size=0x%jx, res=%d, ref=%d, flags=0x%x ruid %d charge %jx\n",
2479             object, (int)object->type, (uintmax_t)object->size,
2480             object->resident_page_count, object->ref_count, object->flags,
2481             object->cred ? object->cred->cr_ruid : -1, (uintmax_t)object->charge);
2482         db_iprintf(" sref=%d, backing_object(%d)=(%p)+0x%jx\n",
2483             object->shadow_count, 
2484             object->backing_object ? object->backing_object->ref_count : 0,
2485             object->backing_object, (uintmax_t)object->backing_object_offset);
2486
2487         if (!full)
2488                 return;
2489
2490         db_indent += 2;
2491         count = 0;
2492         TAILQ_FOREACH(p, &object->memq, listq) {
2493                 if (count == 0)
2494                         db_iprintf("memory:=");
2495                 else if (count == 6) {
2496                         db_printf("\n");
2497                         db_iprintf(" ...");
2498                         count = 0;
2499                 } else
2500                         db_printf(",");
2501                 count++;
2502
2503                 db_printf("(off=0x%jx,page=0x%jx)",
2504                     (uintmax_t)p->pindex, (uintmax_t)VM_PAGE_TO_PHYS(p));
2505         }
2506         if (count != 0)
2507                 db_printf("\n");
2508         db_indent -= 2;
2509 }
2510
2511 /* XXX. */
2512 #undef count
2513
2514 /* XXX need this non-static entry for calling from vm_map_print. */
2515 void
2516 vm_object_print(
2517         /* db_expr_t */ long addr,
2518         boolean_t have_addr,
2519         /* db_expr_t */ long count,
2520         char *modif)
2521 {
2522         vm_object_print_static(addr, have_addr, count, modif);
2523 }
2524
2525 DB_SHOW_COMMAND(vmopag, vm_object_print_pages)
2526 {
2527         vm_object_t object;
2528         vm_pindex_t fidx;
2529         vm_paddr_t pa;
2530         vm_page_t m, prev_m;
2531         int rcount, nl, c;
2532
2533         nl = 0;
2534         TAILQ_FOREACH(object, &vm_object_list, object_list) {
2535                 db_printf("new object: %p\n", (void *)object);
2536                 if (nl > 18) {
2537                         c = cngetc();
2538                         if (c != ' ')
2539                                 return;
2540                         nl = 0;
2541                 }
2542                 nl++;
2543                 rcount = 0;
2544                 fidx = 0;
2545                 pa = -1;
2546                 TAILQ_FOREACH(m, &object->memq, listq) {
2547                         if (m->pindex > 128)
2548                                 break;
2549                         if ((prev_m = TAILQ_PREV(m, pglist, listq)) != NULL &&
2550                             prev_m->pindex + 1 != m->pindex) {
2551                                 if (rcount) {
2552                                         db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2553                                                 (long)fidx, rcount, (long)pa);
2554                                         if (nl > 18) {
2555                                                 c = cngetc();
2556                                                 if (c != ' ')
2557                                                         return;
2558                                                 nl = 0;
2559                                         }
2560                                         nl++;
2561                                         rcount = 0;
2562                                 }
2563                         }                               
2564                         if (rcount &&
2565                                 (VM_PAGE_TO_PHYS(m) == pa + rcount * PAGE_SIZE)) {
2566                                 ++rcount;
2567                                 continue;
2568                         }
2569                         if (rcount) {
2570                                 db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2571                                         (long)fidx, rcount, (long)pa);
2572                                 if (nl > 18) {
2573                                         c = cngetc();
2574                                         if (c != ' ')
2575                                                 return;
2576                                         nl = 0;
2577                                 }
2578                                 nl++;
2579                         }
2580                         fidx = m->pindex;
2581                         pa = VM_PAGE_TO_PHYS(m);
2582                         rcount = 1;
2583                 }
2584                 if (rcount) {
2585                         db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2586                                 (long)fidx, rcount, (long)pa);
2587                         if (nl > 18) {
2588                                 c = cngetc();
2589                                 if (c != ' ')
2590                                         return;
2591                                 nl = 0;
2592                         }
2593                         nl++;
2594                 }
2595         }
2596 }
2597 #endif /* DDB */