5bd429002186007080954c03c6a53907899f8367
[dragonfly.git] / sys / vm / vm_object.c
1 /*
2  * Copyright (c) 1991, 1993, 2013
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      from: @(#)vm_object.c   8.5 (Berkeley) 3/22/94
33  *
34  *
35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36  * All rights reserved.
37  *
38  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
39  *
40  * Permission to use, copy, modify and distribute this software and
41  * its documentation is hereby granted, provided that both the copyright
42  * notice and this permission notice appear in all copies of the
43  * software, derivative works or modified versions, and any portions
44  * thereof, and that both notices appear in supporting documentation.
45  *
46  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
47  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
48  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
49  *
50  * Carnegie Mellon requests users of this software to return to
51  *
52  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
53  *  School of Computer Science
54  *  Carnegie Mellon University
55  *  Pittsburgh PA 15213-3890
56  *
57  * any improvements or extensions that they make and grant Carnegie the
58  * rights to redistribute these changes.
59  *
60  * $FreeBSD: src/sys/vm/vm_object.c,v 1.171.2.8 2003/05/26 19:17:56 alc Exp $
61  */
62
63 /*
64  *      Virtual memory object module.
65  */
66
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/proc.h>           /* for curproc, pageproc */
70 #include <sys/thread.h>
71 #include <sys/vnode.h>
72 #include <sys/vmmeter.h>
73 #include <sys/mman.h>
74 #include <sys/mount.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/refcount.h>
78
79 #include <vm/vm.h>
80 #include <vm/vm_param.h>
81 #include <vm/pmap.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_object.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_pageout.h>
86 #include <vm/vm_pager.h>
87 #include <vm/swap_pager.h>
88 #include <vm/vm_kern.h>
89 #include <vm/vm_extern.h>
90 #include <vm/vm_zone.h>
91
92 #include <vm/vm_page2.h>
93
94 #include <machine/specialreg.h>
95
96 #define EASY_SCAN_FACTOR        8
97
98 static void     vm_object_qcollapse(vm_object_t object,
99                                     vm_object_t backing_object);
100 static void     vm_object_page_collect_flush(vm_object_t object, vm_page_t p,
101                                              int pagerflags);
102 static void     vm_object_lock_init(vm_object_t);
103
104 /*
105  *      Virtual memory objects maintain the actual data
106  *      associated with allocated virtual memory.  A given
107  *      page of memory exists within exactly one object.
108  *
109  *      An object is only deallocated when all "references"
110  *      are given up.  Only one "reference" to a given
111  *      region of an object should be writeable.
112  *
113  *      Associated with each object is a list of all resident
114  *      memory pages belonging to that object; this list is
115  *      maintained by the "vm_page" module, and locked by the object's
116  *      lock.
117  *
118  *      Each object also records a "pager" routine which is
119  *      used to retrieve (and store) pages to the proper backing
120  *      storage.  In addition, objects may be backed by other
121  *      objects from which they were virtual-copied.
122  *
123  *      The only items within the object structure which are
124  *      modified after time of creation are:
125  *              reference count         locked by object's lock
126  *              pager routine           locked by object's lock
127  *
128  */
129
130 struct vm_object kernel_object;
131
132 static long object_collapses;
133 static long object_bypasses;
134
135 struct vm_object_hash vm_object_hash[VMOBJ_HSIZE];
136
137 MALLOC_DEFINE(M_VM_OBJECT, "vm_object", "vm_object structures");
138
139 #define VMOBJ_HASH_PRIME1       66555444443333333ULL
140 #define VMOBJ_HASH_PRIME2       989042931893ULL
141
142 int vm_object_debug;
143 SYSCTL_INT(_vm, OID_AUTO, object_debug, CTLFLAG_RW, &vm_object_debug, 0, "");
144
145 static __inline
146 struct vm_object_hash *
147 vmobj_hash(vm_object_t obj)
148 {
149         uintptr_t hash1;
150         uintptr_t hash2;
151
152         hash1 = (uintptr_t)obj + ((uintptr_t)obj >> 18);
153         hash1 %= VMOBJ_HASH_PRIME1;
154         hash2 = ((uintptr_t)obj >> 8) + ((uintptr_t)obj >> 24);
155         hash2 %= VMOBJ_HASH_PRIME2;
156         return (&vm_object_hash[(hash1 ^ hash2) & VMOBJ_HMASK]);
157 }
158
159 #if defined(DEBUG_LOCKS)
160
161 #define vm_object_vndeallocate(obj, vpp)        \
162                 debugvm_object_vndeallocate(obj, vpp, __FILE__, __LINE__)
163
164 /*
165  * Debug helper to track hold/drop/ref/deallocate calls.
166  */
167 static void
168 debugvm_object_add(vm_object_t obj, char *file, int line, int addrem)
169 {
170         int i;
171
172         i = atomic_fetchadd_int(&obj->debug_index, 1);
173         i = i & (VMOBJ_DEBUG_ARRAY_SIZE - 1);
174         ksnprintf(obj->debug_hold_thrs[i],
175                   sizeof(obj->debug_hold_thrs[i]),
176                   "%c%d:(%d):%s",
177                   (addrem == -1 ? '-' : (addrem == 1 ? '+' : '=')),
178                   (curthread->td_proc ? curthread->td_proc->p_pid : -1),
179                   obj->ref_count,
180                   curthread->td_comm);
181         obj->debug_hold_file[i] = file;
182         obj->debug_hold_line[i] = line;
183 #if 0
184         /* Uncomment for debugging obj refs/derefs in reproducable cases */
185         if (strcmp(curthread->td_comm, "sshd") == 0) {
186                 kprintf("%d %p refs=%d ar=%d file: %s/%d\n",
187                         (curthread->td_proc ? curthread->td_proc->p_pid : -1),
188                         obj, obj->ref_count, addrem, file, line);
189         }
190 #endif
191 }
192
193 #endif
194
195 /*
196  * Misc low level routines
197  */
198 static void
199 vm_object_lock_init(vm_object_t obj)
200 {
201 #if defined(DEBUG_LOCKS)
202         int i;
203
204         obj->debug_index = 0;
205         for (i = 0; i < VMOBJ_DEBUG_ARRAY_SIZE; i++) {
206                 obj->debug_hold_thrs[i][0] = 0;
207                 obj->debug_hold_file[i] = NULL;
208                 obj->debug_hold_line[i] = 0;
209         }
210 #endif
211 }
212
213 void
214 vm_object_lock_swap(void)
215 {
216         lwkt_token_swap();
217 }
218
219 void
220 vm_object_lock(vm_object_t obj)
221 {
222         lwkt_gettoken(&obj->token);
223 }
224
225 /*
226  * Returns TRUE on sucesss
227  */
228 static int
229 vm_object_lock_try(vm_object_t obj)
230 {
231         return(lwkt_trytoken(&obj->token));
232 }
233
234 void
235 vm_object_lock_shared(vm_object_t obj)
236 {
237         lwkt_gettoken_shared(&obj->token);
238 }
239
240 void
241 vm_object_unlock(vm_object_t obj)
242 {
243         lwkt_reltoken(&obj->token);
244 }
245
246 void
247 vm_object_upgrade(vm_object_t obj)
248 {
249         lwkt_reltoken(&obj->token);
250         lwkt_gettoken(&obj->token);
251 }
252
253 void
254 vm_object_downgrade(vm_object_t obj)
255 {
256         lwkt_reltoken(&obj->token);
257         lwkt_gettoken_shared(&obj->token);
258 }
259
260 static __inline void
261 vm_object_assert_held(vm_object_t obj)
262 {
263         ASSERT_LWKT_TOKEN_HELD(&obj->token);
264 }
265
266 static __inline int
267 vm_quickcolor(void)
268 {
269         globaldata_t gd = mycpu;
270         int pg_color;
271
272         pg_color = (int)(intptr_t)gd->gd_curthread >> 10;
273         pg_color += gd->gd_quick_color;
274         gd->gd_quick_color += PQ_PRIME2;
275
276         return pg_color;
277 }
278
279 void
280 VMOBJDEBUG(vm_object_hold)(vm_object_t obj VMOBJDBARGS)
281 {
282         KKASSERT(obj != NULL);
283
284         /*
285          * Object must be held (object allocation is stable due to callers
286          * context, typically already holding the token on a parent object)
287          * prior to potentially blocking on the lock, otherwise the object
288          * can get ripped away from us.
289          */
290         refcount_acquire(&obj->hold_count);
291         vm_object_lock(obj);
292
293 #if defined(DEBUG_LOCKS)
294         debugvm_object_add(obj, file, line, 1);
295 #endif
296 }
297
298 int
299 VMOBJDEBUG(vm_object_hold_try)(vm_object_t obj VMOBJDBARGS)
300 {
301         KKASSERT(obj != NULL);
302
303         /*
304          * Object must be held (object allocation is stable due to callers
305          * context, typically already holding the token on a parent object)
306          * prior to potentially blocking on the lock, otherwise the object
307          * can get ripped away from us.
308          */
309         refcount_acquire(&obj->hold_count);
310         if (vm_object_lock_try(obj) == 0) {
311                 if (refcount_release(&obj->hold_count)) {
312                         if (obj->ref_count == 0 && (obj->flags & OBJ_DEAD))
313                                 kfree(obj, M_VM_OBJECT);
314                 }
315                 return(0);
316         }
317
318 #if defined(DEBUG_LOCKS)
319         debugvm_object_add(obj, file, line, 1);
320 #endif
321         return(1);
322 }
323
324 void
325 VMOBJDEBUG(vm_object_hold_shared)(vm_object_t obj VMOBJDBARGS)
326 {
327         KKASSERT(obj != NULL);
328
329         /*
330          * Object must be held (object allocation is stable due to callers
331          * context, typically already holding the token on a parent object)
332          * prior to potentially blocking on the lock, otherwise the object
333          * can get ripped away from us.
334          */
335         refcount_acquire(&obj->hold_count);
336         vm_object_lock_shared(obj);
337
338 #if defined(DEBUG_LOCKS)
339         debugvm_object_add(obj, file, line, 1);
340 #endif
341 }
342
343 /*
344  * Drop the token and hold_count on the object.
345  *
346  * WARNING! Token might be shared.
347  */
348 void
349 VMOBJDEBUG(vm_object_drop)(vm_object_t obj VMOBJDBARGS)
350 {
351         if (obj == NULL)
352                 return;
353
354         /*
355          * No new holders should be possible once we drop hold_count 1->0 as
356          * there is no longer any way to reference the object.
357          */
358         KKASSERT(obj->hold_count > 0);
359         if (refcount_release(&obj->hold_count)) {
360 #if defined(DEBUG_LOCKS)
361                 debugvm_object_add(obj, file, line, -1);
362 #endif
363
364                 if (obj->ref_count == 0 && (obj->flags & OBJ_DEAD)) {
365                         vm_object_unlock(obj);
366                         kfree(obj, M_VM_OBJECT);
367                 } else {
368                         vm_object_unlock(obj);
369                 }
370         } else {
371 #if defined(DEBUG_LOCKS)
372                 debugvm_object_add(obj, file, line, -1);
373 #endif
374                 vm_object_unlock(obj);
375         }
376 }
377
378 /*
379  * Initialize a freshly allocated object, returning a held object.
380  *
381  * Used only by vm_object_allocate(), zinitna() and vm_object_init().
382  *
383  * No requirements.
384  */
385 void
386 _vm_object_allocate(objtype_t type, vm_pindex_t size, vm_object_t object)
387 {
388         struct vm_object_hash *hash;
389
390         RB_INIT(&object->rb_memq);
391         lwkt_token_init(&object->token, "vmobj");
392
393         object->type = type;
394         object->size = size;
395         object->ref_count = 1;
396         object->memattr = VM_MEMATTR_DEFAULT;
397         object->hold_count = 0;
398         object->flags = 0;
399         if ((object->type == OBJT_DEFAULT) || (object->type == OBJT_SWAP))
400                 vm_object_set_flag(object, OBJ_ONEMAPPING);
401         object->paging_in_progress = 0;
402         object->resident_page_count = 0;
403         /* cpu localization twist */
404         object->pg_color = vm_quickcolor();
405         object->handle = NULL;
406         object->backing_object = NULL;
407         object->backing_object_offset = (vm_ooffset_t)0;
408
409         atomic_add_int(&object->generation, 1);
410         object->swblock_count = 0;
411         RB_INIT(&object->swblock_root);
412         vm_object_lock_init(object);
413         pmap_object_init(object);
414
415         vm_object_hold(object);
416
417         hash = vmobj_hash(object);
418         lwkt_gettoken(&hash->token);
419         TAILQ_INSERT_TAIL(&hash->list, object, object_list);
420         lwkt_reltoken(&hash->token);
421 }
422
423 /*
424  * Initialize a VM object.
425  */
426 void
427 vm_object_init(vm_object_t object, vm_pindex_t size)
428 {
429         _vm_object_allocate(OBJT_DEFAULT, size, object);
430         vm_object_drop(object);
431 }
432
433 /*
434  * Initialize the VM objects module.
435  *
436  * Called from the low level boot code only.  Note that this occurs before
437  * kmalloc is initialized so we cannot allocate any VM objects.
438  */
439 void
440 vm_object_init1(void)
441 {
442         int i;
443
444         for (i = 0; i < VMOBJ_HSIZE; ++i) {
445                 TAILQ_INIT(&vm_object_hash[i].list);
446                 lwkt_token_init(&vm_object_hash[i].token, "vmobjlst");
447         }
448
449         _vm_object_allocate(OBJT_DEFAULT, OFF_TO_IDX(KvaEnd),
450                             &kernel_object);
451         vm_object_drop(&kernel_object);
452 }
453
454 void
455 vm_object_init2(void)
456 {
457         kmalloc_set_unlimited(M_VM_OBJECT);
458 }
459
460 /*
461  * Allocate and return a new object of the specified type and size.
462  *
463  * No requirements.
464  */
465 vm_object_t
466 vm_object_allocate(objtype_t type, vm_pindex_t size)
467 {
468         vm_object_t obj;
469
470         obj = kmalloc(sizeof(*obj), M_VM_OBJECT, M_INTWAIT|M_ZERO);
471         _vm_object_allocate(type, size, obj);
472         vm_object_drop(obj);
473
474         return (obj);
475 }
476
477 /*
478  * This version returns a held object, allowing further atomic initialization
479  * of the object.
480  */
481 vm_object_t
482 vm_object_allocate_hold(objtype_t type, vm_pindex_t size)
483 {
484         vm_object_t obj;
485
486         obj = kmalloc(sizeof(*obj), M_VM_OBJECT, M_INTWAIT|M_ZERO);
487         _vm_object_allocate(type, size, obj);
488
489         return (obj);
490 }
491
492 /*
493  * Add an additional reference to a vm_object.  The object must already be
494  * held.  The original non-lock version is no longer supported.  The object
495  * must NOT be chain locked by anyone at the time the reference is added.
496  *
497  * Referencing a chain-locked object can blow up the fairly sensitive
498  * ref_count tests in the deallocator.  Most callers
499  * will call vm_object_chain_wait() prior to calling
500  * vm_object_reference_locked() to avoid the case.  The held token
501  * allows the caller to pair the wait and ref.
502  *
503  * The object must be held, but may be held shared if desired (hence why
504  * we use an atomic op).
505  */
506 void
507 VMOBJDEBUG(vm_object_reference_locked)(vm_object_t object VMOBJDBARGS)
508 {
509         KKASSERT(object != NULL);
510         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
511         KKASSERT((object->chainlk & (CHAINLK_EXCL | CHAINLK_MASK)) == 0);
512         atomic_add_int(&object->ref_count, 1);
513         if (object->type == OBJT_VNODE) {
514                 vref(object->handle);
515                 /* XXX what if the vnode is being destroyed? */
516         }
517 #if defined(DEBUG_LOCKS)
518         debugvm_object_add(object, file, line, 1);
519 #endif
520 }
521
522 /*
523  * This version explicitly allows the chain to be held (i.e. by the
524  * caller).  The token must also be held.
525  */
526 void
527 VMOBJDEBUG(vm_object_reference_locked_chain_held)(vm_object_t object
528            VMOBJDBARGS)
529 {
530         KKASSERT(object != NULL);
531         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
532         atomic_add_int(&object->ref_count, 1);
533         if (object->type == OBJT_VNODE) {
534                 vref(object->handle);
535                 /* XXX what if the vnode is being destroyed? */
536         }
537 #if defined(DEBUG_LOCKS)
538         debugvm_object_add(object, file, line, 1);
539 #endif
540 }
541
542 /*
543  * This version is only allowed for vnode objects.
544  */
545 void
546 VMOBJDEBUG(vm_object_reference_quick)(vm_object_t object VMOBJDBARGS)
547 {
548         KKASSERT(object->type == OBJT_VNODE);
549         atomic_add_int(&object->ref_count, 1);
550         vref(object->handle);
551 #if defined(DEBUG_LOCKS)
552         debugvm_object_add(object, file, line, 1);
553 #endif
554 }
555
556 /*
557  * Object OBJ_CHAINLOCK lock handling.
558  *
559  * The caller can chain-lock backing objects recursively and then
560  * use vm_object_chain_release_all() to undo the whole chain.
561  *
562  * Chain locks are used to prevent collapses and are only applicable
563  * to OBJT_DEFAULT and OBJT_SWAP objects.  Chain locking operations
564  * on other object types are ignored.  This is also important because
565  * it allows e.g. the vnode underlying a memory mapping to take concurrent
566  * faults.
567  *
568  * The object must usually be held on entry, though intermediate
569  * objects need not be held on release.  The object must be held exclusively,
570  * NOT shared.  Note that the prefault path checks the shared state and
571  * avoids using the chain functions.
572  */
573 void
574 vm_object_chain_wait(vm_object_t object, int shared)
575 {
576         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
577         for (;;) {
578                 uint32_t chainlk = object->chainlk;
579
580                 cpu_ccfence();
581                 if (shared) {
582                         if (chainlk & (CHAINLK_EXCL | CHAINLK_EXCLREQ)) {
583                                 tsleep_interlock(object, 0);
584                                 if (atomic_cmpset_int(&object->chainlk,
585                                                       chainlk,
586                                                       chainlk | CHAINLK_WAIT)) {
587                                         tsleep(object, PINTERLOCKED,
588                                                "objchns", 0);
589                                 }
590                                 /* retry */
591                         } else {
592                                 break;
593                         }
594                         /* retry */
595                 } else {
596                         if (chainlk & (CHAINLK_MASK | CHAINLK_EXCL)) {
597                                 tsleep_interlock(object, 0);
598                                 if (atomic_cmpset_int(&object->chainlk,
599                                                       chainlk,
600                                                       chainlk | CHAINLK_WAIT))
601                                 {
602                                         tsleep(object, PINTERLOCKED,
603                                                "objchnx", 0);
604                                 }
605                                 /* retry */
606                         } else {
607                                 if (atomic_cmpset_int(&object->chainlk,
608                                                       chainlk,
609                                                       chainlk & ~CHAINLK_WAIT))
610                                 {
611                                         if (chainlk & CHAINLK_WAIT)
612                                                 wakeup(object);
613                                         break;
614                                 }
615                                 /* retry */
616                         }
617                 }
618                 /* retry */
619         }
620 }
621
622 void
623 vm_object_chain_acquire(vm_object_t object, int shared)
624 {
625         if (object->type != OBJT_DEFAULT && object->type != OBJT_SWAP)
626                 return;
627         if (vm_shared_fault == 0)
628                 shared = 0;
629
630         for (;;) {
631                 uint32_t chainlk = object->chainlk;
632
633                 cpu_ccfence();
634                 if (shared) {
635                         if (chainlk & (CHAINLK_EXCL | CHAINLK_EXCLREQ)) {
636                                 tsleep_interlock(object, 0);
637                                 if (atomic_cmpset_int(&object->chainlk,
638                                                       chainlk,
639                                                       chainlk | CHAINLK_WAIT)) {
640                                         tsleep(object, PINTERLOCKED,
641                                                "objchns", 0);
642                                 }
643                                 /* retry */
644                         } else if (atomic_cmpset_int(&object->chainlk,
645                                               chainlk, chainlk + 1)) {
646                                 break;
647                         }
648                         /* retry */
649                 } else {
650                         if (chainlk & (CHAINLK_MASK | CHAINLK_EXCL)) {
651                                 tsleep_interlock(object, 0);
652                                 if (atomic_cmpset_int(&object->chainlk,
653                                                       chainlk,
654                                                       chainlk |
655                                                        CHAINLK_WAIT |
656                                                        CHAINLK_EXCLREQ)) {
657                                         tsleep(object, PINTERLOCKED,
658                                                "objchnx", 0);
659                                 }
660                                 /* retry */
661                         } else {
662                                 if (atomic_cmpset_int(&object->chainlk,
663                                                       chainlk,
664                                                       (chainlk | CHAINLK_EXCL) &
665                                                       ~(CHAINLK_EXCLREQ |
666                                                         CHAINLK_WAIT))) {
667                                         if (chainlk & CHAINLK_WAIT)
668                                                 wakeup(object);
669                                         break;
670                                 }
671                                 /* retry */
672                         }
673                 }
674                 /* retry */
675         }
676 }
677
678 void
679 vm_object_chain_release(vm_object_t object)
680 {
681         /*ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));*/
682         if (object->type != OBJT_DEFAULT && object->type != OBJT_SWAP)
683                 return;
684         KKASSERT(object->chainlk & (CHAINLK_MASK | CHAINLK_EXCL));
685         for (;;) {
686                 uint32_t chainlk = object->chainlk;
687
688                 cpu_ccfence();
689                 if (chainlk & CHAINLK_MASK) {
690                         if ((chainlk & CHAINLK_MASK) == 1 &&
691                             atomic_cmpset_int(&object->chainlk,
692                                               chainlk,
693                                               (chainlk - 1) & ~CHAINLK_WAIT)) {
694                                 if (chainlk & CHAINLK_WAIT)
695                                         wakeup(object);
696                                 break;
697                         }
698                         if ((chainlk & CHAINLK_MASK) > 1 &&
699                             atomic_cmpset_int(&object->chainlk,
700                                               chainlk, chainlk - 1)) {
701                                 break;
702                         }
703                         /* retry */
704                 } else {
705                         KKASSERT(chainlk & CHAINLK_EXCL);
706                         if (atomic_cmpset_int(&object->chainlk,
707                                               chainlk,
708                                               chainlk & ~(CHAINLK_EXCL |
709                                                           CHAINLK_WAIT))) {
710                                 if (chainlk & CHAINLK_WAIT)
711                                         wakeup(object);
712                                 break;
713                         }
714                 }
715         }
716 }
717
718 /*
719  * Release the chain from first_object through and including stopobj.
720  * The caller is typically holding the first and last object locked
721  * (shared or exclusive) to prevent destruction races.
722  *
723  * We release stopobj first as an optimization as this object is most
724  * likely to be shared across multiple processes.
725  */
726 void
727 vm_object_chain_release_all(vm_object_t first_object, vm_object_t stopobj)
728 {
729         vm_object_t backing_object;
730         vm_object_t object;
731
732         vm_object_chain_release(stopobj);
733         object = first_object;
734
735         while (object != stopobj) {
736                 KKASSERT(object);
737                 backing_object = object->backing_object;
738                 vm_object_chain_release(object);
739                 object = backing_object;
740         }
741 }
742
743 /*
744  * Dereference an object and its underlying vnode.  The object may be
745  * held shared.  On return the object will remain held.
746  *
747  * This function may return a vnode in *vpp which the caller must release
748  * after the caller drops its own lock.  If vpp is NULL, we assume that
749  * the caller was holding an exclusive lock on the object and we vrele()
750  * the vp ourselves.
751  */
752 static void
753 VMOBJDEBUG(vm_object_vndeallocate)(vm_object_t object, struct vnode **vpp
754                                    VMOBJDBARGS)
755 {
756         struct vnode *vp = (struct vnode *) object->handle;
757
758         KASSERT(object->type == OBJT_VNODE,
759             ("vm_object_vndeallocate: not a vnode object"));
760         KASSERT(vp != NULL, ("vm_object_vndeallocate: missing vp"));
761         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
762 #ifdef INVARIANTS
763         if (object->ref_count == 0) {
764                 vprint("vm_object_vndeallocate", vp);
765                 panic("vm_object_vndeallocate: bad object reference count");
766         }
767 #endif
768         for (;;) {
769                 int count = object->ref_count;
770                 cpu_ccfence();
771                 if (count == 1) {
772                         vm_object_upgrade(object);
773                         if (atomic_cmpset_int(&object->ref_count, count, 0)) {
774                                 vclrflags(vp, VTEXT);
775                                 break;
776                         }
777                 } else {
778                         if (atomic_cmpset_int(&object->ref_count,
779                                               count, count - 1)) {
780                                 break;
781                         }
782                 }
783                 /* retry */
784         }
785 #if defined(DEBUG_LOCKS)
786         debugvm_object_add(object, file, line, -1);
787 #endif
788
789         /*
790          * vrele or return the vp to vrele.  We can only safely vrele(vp)
791          * if the object was locked exclusively.  But there are two races
792          * here.
793          *
794          * We had to upgrade the object above to safely clear VTEXT
795          * but the alternative path where the shared lock is retained
796          * can STILL race to 0 in other paths and cause our own vrele()
797          * to terminate the vnode.  We can't allow that if the VM object
798          * is still locked shared.
799          */
800         if (vpp)
801                 *vpp = vp;
802         else
803                 vrele(vp);
804 }
805
806 /*
807  * Release a reference to the specified object, gained either through a
808  * vm_object_allocate or a vm_object_reference call.  When all references
809  * are gone, storage associated with this object may be relinquished.
810  *
811  * The caller does not have to hold the object locked but must have control
812  * over the reference in question in order to guarantee that the object
813  * does not get ripped out from under us.
814  *
815  * XXX Currently all deallocations require an exclusive lock.
816  */
817 void
818 VMOBJDEBUG(vm_object_deallocate)(vm_object_t object VMOBJDBARGS)
819 {
820         struct vnode *vp;
821         int count;
822
823         if (object == NULL)
824                 return;
825
826         for (;;) {
827                 count = object->ref_count;
828                 cpu_ccfence();
829
830                 /*
831                  * If decrementing the count enters into special handling
832                  * territory (0, 1, or 2) we have to do it the hard way.
833                  * Fortunate though, objects with only a few refs like this
834                  * are not likely to be heavily contended anyway.
835                  *
836                  * For vnode objects we only care about 1->0 transitions.
837                  */
838                 if (count <= 3 || (object->type == OBJT_VNODE && count <= 1)) {
839 #if defined(DEBUG_LOCKS)
840                         debugvm_object_add(object, file, line, 0);
841 #endif
842                         vm_object_hold(object);
843                         vm_object_deallocate_locked(object);
844                         vm_object_drop(object);
845                         break;
846                 }
847
848                 /*
849                  * Try to decrement ref_count without acquiring a hold on
850                  * the object.  This is particularly important for the exec*()
851                  * and exit*() code paths because the program binary may
852                  * have a great deal of sharing and an exclusive lock will
853                  * crowbar performance in those circumstances.
854                  */
855                 if (object->type == OBJT_VNODE) {
856                         vp = (struct vnode *)object->handle;
857                         if (atomic_cmpset_int(&object->ref_count,
858                                               count, count - 1)) {
859 #if defined(DEBUG_LOCKS)
860                                 debugvm_object_add(object, file, line, -1);
861 #endif
862
863                                 vrele(vp);
864                                 break;
865                         }
866                         /* retry */
867                 } else {
868                         if (atomic_cmpset_int(&object->ref_count,
869                                               count, count - 1)) {
870 #if defined(DEBUG_LOCKS)
871                                 debugvm_object_add(object, file, line, -1);
872 #endif
873                                 break;
874                         }
875                         /* retry */
876                 }
877                 /* retry */
878         }
879 }
880
881 void
882 VMOBJDEBUG(vm_object_deallocate_locked)(vm_object_t object VMOBJDBARGS)
883 {
884         struct vm_object_dealloc_list *dlist = NULL;
885         struct vm_object_dealloc_list *dtmp;
886         vm_object_t temp;
887         int must_drop = 0;
888
889         /*
890          * We may chain deallocate object, but additional objects may
891          * collect on the dlist which also have to be deallocated.  We
892          * must avoid a recursion, vm_object chains can get deep.
893          */
894
895 again:
896         while (object != NULL) {
897                 /*
898                  * vnode case, caller either locked the object exclusively
899                  * or this is a recursion with must_drop != 0 and the vnode
900                  * object will be locked shared.
901                  *
902                  * If locked shared we have to drop the object before we can
903                  * call vrele() or risk a shared/exclusive livelock.
904                  */
905                 if (object->type == OBJT_VNODE) {
906                         ASSERT_LWKT_TOKEN_HELD(&object->token);
907                         if (must_drop) {
908                                 struct vnode *tmp_vp;
909
910                                 vm_object_vndeallocate(object, &tmp_vp);
911                                 vm_object_drop(object);
912                                 must_drop = 0;
913                                 object = NULL;
914                                 vrele(tmp_vp);
915                         } else {
916                                 vm_object_vndeallocate(object, NULL);
917                         }
918                         break;
919                 }
920                 ASSERT_LWKT_TOKEN_HELD_EXCL(&object->token);
921
922                 /*
923                  * Normal case (object is locked exclusively)
924                  */
925                 if (object->ref_count == 0) {
926                         panic("vm_object_deallocate: object deallocated "
927                               "too many times: %d", object->type);
928                 }
929                 if (object->ref_count > 2) {
930                         atomic_add_int(&object->ref_count, -1);
931 #if defined(DEBUG_LOCKS)
932                         debugvm_object_add(object, file, line, -1);
933 #endif
934                         break;
935                 }
936
937 #if 0
938                 /*
939                  * CODE REMOVAL IN PROGRESS.
940                  *
941                  * This code handled setting ONEMAPPING again on a DEFAULT
942                  * or SWAP object on the 2->1 transition of ref_count,
943                  *
944                  * This code also handled collapsing object chains on the
945                  * 2->1 transition when the second ref was due to a shadow.
946                  */
947                 /*
948                  * The ref_count is either 1 or 2.
949                  *
950                  * Here on ref_count of one or two, which are special cases for
951                  * objects.
952                  *
953                  * Nominal ref_count > 1 case if the second ref is not from
954                  * a shadow.
955                  *
956                  * (ONEMAPPING only applies to DEFAULT AND SWAP objects)
957                  */
958                 if (object->ref_count == 2 && object->shadow_count == 0) {
959                         if (object->type == OBJT_DEFAULT ||
960                             object->type == OBJT_SWAP) {
961                                 vm_object_set_flag(object, OBJ_ONEMAPPING);
962                         }
963                         atomic_add_int(&object->ref_count, -1);
964 #if defined(DEBUG_LOCKS)
965                         debugvm_object_add(object, file, line, -1);
966 #endif
967                         break;
968                 }
969
970                 /*
971                  * If the second ref is from a shadow we chain along it
972                  * upwards if object's handle is exhausted.
973                  *
974                  * We have to decrement object->ref_count before potentially
975                  * collapsing the first shadow object or the collapse code
976                  * will not be able to handle the degenerate case to remove
977                  * object.  However, if we do it too early the object can
978                  * get ripped out from under us.
979                  */
980                 if (object->ref_count == 2 && object->shadow_count == 1 &&
981                     object->handle == NULL && (object->type == OBJT_DEFAULT ||
982                                                object->type == OBJT_SWAP)) {
983                         temp = LIST_FIRST(&object->shadow_head);
984                         KKASSERT(temp != NULL);
985                         vm_object_hold(temp);
986
987                         /*
988                          * Wait for any paging to complete so the collapse
989                          * doesn't (or isn't likely to) qcollapse.  pip
990                          * waiting must occur before we acquire the
991                          * chainlock.
992                          */
993                         while (
994                                 temp->paging_in_progress ||
995                                 object->paging_in_progress
996                         ) {
997                                 vm_object_pip_wait(temp, "objde1");
998                                 vm_object_pip_wait(object, "objde2");
999                         }
1000
1001                         /*
1002                          * If the parent is locked we have to give up, as
1003                          * otherwise we would be acquiring locks in the
1004                          * wrong order and potentially deadlock.
1005                          */
1006                         if (temp->chainlk & (CHAINLK_EXCL | CHAINLK_MASK)) {
1007                                 vm_object_drop(temp);
1008                                 goto skip;
1009                         }
1010                         vm_object_chain_acquire(temp, 0);
1011
1012                         /*
1013                          * Recheck/retry after the hold and the paging
1014                          * wait, both of which can block us.
1015                          */
1016                         if (object->ref_count != 2 ||
1017                             object->shadow_count != 1 ||
1018                             object->handle ||
1019                             LIST_FIRST(&object->shadow_head) != temp ||
1020                             (object->type != OBJT_DEFAULT &&
1021                              object->type != OBJT_SWAP)) {
1022                                 vm_object_chain_release(temp);
1023                                 vm_object_drop(temp);
1024                                 continue;
1025                         }
1026
1027                         /*
1028                          * We can safely drop object's ref_count now.
1029                          */
1030                         KKASSERT(object->ref_count == 2);
1031                         atomic_add_int(&object->ref_count, -1);
1032 #if defined(DEBUG_LOCKS)
1033                         debugvm_object_add(object, file, line, -1);
1034 #endif
1035
1036                         /*
1037                          * If our single parent is not collapseable just
1038                          * decrement ref_count (2->1) and stop.
1039                          */
1040                         if (temp->handle || (temp->type != OBJT_DEFAULT &&
1041                                              temp->type != OBJT_SWAP)) {
1042                                 vm_object_chain_release(temp);
1043                                 vm_object_drop(temp);
1044                                 break;
1045                         }
1046
1047                         /*
1048                          * At this point we have already dropped object's
1049                          * ref_count so it is possible for a race to
1050                          * deallocate obj out from under us.  Any collapse
1051                          * will re-check the situation.  We must not block
1052                          * until we are able to collapse.
1053                          *
1054                          * Bump temp's ref_count to avoid an unwanted
1055                          * degenerate recursion (can't call
1056                          * vm_object_reference_locked() because it asserts
1057                          * that CHAINLOCK is not set).
1058                          */
1059                         atomic_add_int(&temp->ref_count, 1);
1060                         KKASSERT(temp->ref_count > 1);
1061
1062                         /*
1063                          * Collapse temp, then deallocate the extra ref
1064                          * formally.
1065                          */
1066                         vm_object_collapse(temp, &dlist);
1067                         vm_object_chain_release(temp);
1068                         if (must_drop) {
1069                                 vm_object_lock_swap();
1070                                 vm_object_drop(object);
1071                         }
1072                         object = temp;
1073                         must_drop = 1;
1074                         continue;
1075                 }
1076 skip:
1077                 ;
1078 #endif
1079
1080                 /*
1081                  * Drop the ref and handle termination on the 1->0 transition.
1082                  * We may have blocked above so we have to recheck.
1083                  */
1084                 KKASSERT(object->ref_count != 0);
1085                 if (object->ref_count >= 2) {
1086                         atomic_add_int(&object->ref_count, -1);
1087 #if defined(DEBUG_LOCKS)
1088                         debugvm_object_add(object, file, line, -1);
1089 #endif
1090                         break;
1091                 }
1092                 KKASSERT(object->ref_count == 1);
1093
1094                 /*
1095                  * 1->0 transition.  Chain through the backing_object.
1096                  * Maintain the ref until we've located the backing object,
1097                  * then re-check.
1098                  */
1099                 while ((temp = object->backing_object) != NULL) {
1100                         if (temp->type == OBJT_VNODE)
1101                                 vm_object_hold_shared(temp);
1102                         else
1103                                 vm_object_hold(temp);
1104                         if (temp == object->backing_object)
1105                                 break;
1106                         vm_object_drop(temp);
1107                 }
1108
1109                 /*
1110                  * 1->0 transition verified, retry if ref_count is no longer
1111                  * 1.  Otherwise disconnect the backing_object (temp) and
1112                  * clean up.
1113                  */
1114                 if (object->ref_count != 1) {
1115                         vm_object_drop(temp);
1116                         continue;
1117                 }
1118
1119                 /*
1120                  * It shouldn't be possible for the object to be chain locked
1121                  * if we're removing the last ref on it.
1122                  *
1123                  * Removing object from temp's shadow list requires dropping
1124                  * temp, which we will do on loop.
1125                  *
1126                  * NOTE! vnodes do not use the shadow list, but still have
1127                  *       the backing_object reference.
1128                  */
1129                 KKASSERT((object->chainlk & (CHAINLK_EXCL|CHAINLK_MASK)) == 0);
1130
1131                 if (temp) {
1132                         if (object->flags & OBJ_ONSHADOW) {
1133                                 atomic_add_int(&temp->generation, 1);
1134                                 vm_object_clear_flag(object, OBJ_ONSHADOW);
1135                         }
1136                         object->backing_object = NULL;
1137                 }
1138
1139                 atomic_add_int(&object->ref_count, -1);
1140                 if ((object->flags & OBJ_DEAD) == 0)
1141                         vm_object_terminate(object);
1142                 if (must_drop && temp)
1143                         vm_object_lock_swap();
1144                 if (must_drop)
1145                         vm_object_drop(object);
1146                 object = temp;
1147                 must_drop = 1;
1148         }
1149
1150         if (must_drop && object)
1151                 vm_object_drop(object);
1152
1153         /*
1154          * Additional tail recursion on dlist.  Avoid a recursion.  Objects
1155          * on the dlist have a hold count but are not locked.
1156          */
1157         if ((dtmp = dlist) != NULL) {
1158                 dlist = dtmp->next;
1159                 object = dtmp->object;
1160                 kfree(dtmp, M_TEMP);
1161
1162                 vm_object_lock(object); /* already held, add lock */
1163                 must_drop = 1;          /* and we're responsible for it */
1164                 goto again;
1165         }
1166 }
1167
1168 /*
1169  * Destroy the specified object, freeing up related resources.
1170  *
1171  * The object must have zero references.
1172  *
1173  * The object must held.  The caller is responsible for dropping the object
1174  * after terminate returns.  Terminate does NOT drop the object.
1175  */
1176 static int vm_object_terminate_callback(vm_page_t p, void *data);
1177
1178 void
1179 vm_object_terminate(vm_object_t object)
1180 {
1181         struct rb_vm_page_scan_info info;
1182         struct vm_object_hash *hash;
1183
1184         /*
1185          * Make sure no one uses us.  Once we set OBJ_DEAD we should be
1186          * able to safely block.
1187          */
1188         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1189         KKASSERT((object->flags & OBJ_DEAD) == 0);
1190         vm_object_set_flag(object, OBJ_DEAD);
1191
1192         /*
1193          * Wait for the pageout daemon to be done with the object
1194          */
1195         vm_object_pip_wait(object, "objtrm1");
1196
1197         KASSERT(!object->paging_in_progress,
1198                 ("vm_object_terminate: pageout in progress"));
1199
1200         /*
1201          * Clean and free the pages, as appropriate. All references to the
1202          * object are gone, so we don't need to lock it.
1203          */
1204         if (object->type == OBJT_VNODE) {
1205                 struct vnode *vp;
1206
1207                 /*
1208                  * Clean pages and flush buffers.
1209                  *
1210                  * NOTE!  TMPFS buffer flushes do not typically flush the
1211                  *        actual page to swap as this would be highly
1212                  *        inefficient, and normal filesystems usually wrap
1213                  *        page flushes with buffer cache buffers.
1214                  *
1215                  *        To deal with this we have to call vinvalbuf() both
1216                  *        before and after the vm_object_page_clean().
1217                  */
1218                 vp = (struct vnode *) object->handle;
1219                 vinvalbuf(vp, V_SAVE, 0, 0);
1220                 vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
1221                 vinvalbuf(vp, V_SAVE, 0, 0);
1222         }
1223
1224         /*
1225          * Wait for any I/O to complete, after which there had better not
1226          * be any references left on the object.
1227          */
1228         vm_object_pip_wait(object, "objtrm2");
1229
1230         if (object->ref_count != 0) {
1231                 panic("vm_object_terminate: object with references, "
1232                       "ref_count=%d", object->ref_count);
1233         }
1234
1235         /*
1236          * Cleanup any shared pmaps associated with this object.
1237          */
1238         pmap_object_free(object);
1239
1240         /*
1241          * Now free any remaining pages. For internal objects, this also
1242          * removes them from paging queues. Don't free wired pages, just
1243          * remove them from the object. 
1244          */
1245         info.count = 0;
1246         info.object = object;
1247         do {
1248                 info.error = 0;
1249                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL,
1250                                         vm_object_terminate_callback, &info);
1251         } while (info.error);
1252
1253         /*
1254          * Let the pager know object is dead.
1255          */
1256         vm_pager_deallocate(object);
1257
1258         /*
1259          * Wait for the object hold count to hit 1, clean out pages as
1260          * we go.  vmobj_token interlocks any race conditions that might
1261          * pick the object up from the vm_object_list after we have cleared
1262          * rb_memq.
1263          */
1264         for (;;) {
1265                 if (RB_ROOT(&object->rb_memq) == NULL)
1266                         break;
1267                 kprintf("vm_object_terminate: Warning, object %p "
1268                         "still has %ld pages\n",
1269                         object, object->resident_page_count);
1270                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL,
1271                                         vm_object_terminate_callback, &info);
1272         }
1273
1274         /*
1275          * There had better not be any pages left
1276          */
1277         KKASSERT(object->resident_page_count == 0);
1278
1279         /*
1280          * Remove the object from the global object list.
1281          */
1282         hash = vmobj_hash(object);
1283         lwkt_gettoken(&hash->token);
1284         TAILQ_REMOVE(&hash->list, object, object_list);
1285         lwkt_reltoken(&hash->token);
1286
1287         if (object->ref_count != 0) {
1288                 panic("vm_object_terminate2: object with references, "
1289                       "ref_count=%d", object->ref_count);
1290         }
1291
1292         /*
1293          * NOTE: The object hold_count is at least 1, so we cannot kfree()
1294          *       the object here.  See vm_object_drop().
1295          */
1296 }
1297
1298 /*
1299  * The caller must hold the object.
1300  */
1301 static int
1302 vm_object_terminate_callback(vm_page_t p, void *data)
1303 {
1304         struct rb_vm_page_scan_info *info = data;
1305         vm_object_t object;
1306
1307         object = p->object;
1308         KKASSERT(object == info->object);
1309         if (vm_page_busy_try(p, TRUE)) {
1310                 vm_page_sleep_busy(p, TRUE, "vmotrm");
1311                 info->error = 1;
1312                 return 0;
1313         }
1314         if (object != p->object) {
1315                 /* XXX remove once we determine it can't happen */
1316                 kprintf("vm_object_terminate: Warning: Encountered "
1317                         "busied page %p on queue %d\n", p, p->queue);
1318                 vm_page_wakeup(p);
1319                 info->error = 1;
1320         } else if (p->wire_count == 0) {
1321                 /*
1322                  * NOTE: p->dirty and PG_NEED_COMMIT are ignored.
1323                  */
1324                 vm_page_free(p);
1325                 mycpu->gd_cnt.v_pfree++;
1326         } else {
1327                 if (p->queue != PQ_NONE) {
1328                         kprintf("vm_object_terminate: Warning: Encountered "
1329                                 "wired page %p on queue %d\n", p, p->queue);
1330                         if (vm_object_debug > 0) {
1331                                 --vm_object_debug;
1332                                 print_backtrace(10);
1333                         }
1334                 }
1335                 vm_page_remove(p);
1336                 vm_page_wakeup(p);
1337         }
1338
1339         /*
1340          * Must be at end to avoid SMP races, caller holds object token
1341          */
1342         if ((++info->count & 63) == 0)
1343                 lwkt_user_yield();
1344         return(0);
1345 }
1346
1347 /*
1348  * Clean all dirty pages in the specified range of object.  Leaves page
1349  * on whatever queue it is currently on.   If NOSYNC is set then do not
1350  * write out pages with PG_NOSYNC set (originally comes from MAP_NOSYNC),
1351  * leaving the object dirty.
1352  *
1353  * When stuffing pages asynchronously, allow clustering.  XXX we need a
1354  * synchronous clustering mode implementation.
1355  *
1356  * Odd semantics: if start == end, we clean everything.
1357  *
1358  * The object must be locked? XXX
1359  */
1360 static int vm_object_page_clean_pass1(struct vm_page *p, void *data);
1361 static int vm_object_page_clean_pass2(struct vm_page *p, void *data);
1362
1363 void
1364 vm_object_page_clean(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
1365                      int flags)
1366 {
1367         struct rb_vm_page_scan_info info;
1368         struct vnode *vp;
1369         int wholescan;
1370         int pagerflags;
1371         int generation;
1372
1373         vm_object_hold(object);
1374         if (object->type != OBJT_VNODE ||
1375             (object->flags & OBJ_MIGHTBEDIRTY) == 0) {
1376                 vm_object_drop(object);
1377                 return;
1378         }
1379
1380         pagerflags = (flags & (OBJPC_SYNC | OBJPC_INVAL)) ? 
1381                         VM_PAGER_PUT_SYNC : VM_PAGER_CLUSTER_OK;
1382         pagerflags |= (flags & OBJPC_INVAL) ? VM_PAGER_PUT_INVAL : 0;
1383
1384         vp = object->handle;
1385
1386         /*
1387          * Interlock other major object operations.  This allows us to 
1388          * temporarily clear OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY.
1389          */
1390         vm_object_set_flag(object, OBJ_CLEANING);
1391
1392         /*
1393          * Handle 'entire object' case
1394          */
1395         info.start_pindex = start;
1396         if (end == 0) {
1397                 info.end_pindex = object->size - 1;
1398         } else {
1399                 info.end_pindex = end - 1;
1400         }
1401         wholescan = (start == 0 && info.end_pindex == object->size - 1);
1402         info.limit = flags;
1403         info.pagerflags = pagerflags;
1404         info.object = object;
1405
1406         /*
1407          * If cleaning the entire object do a pass to mark the pages read-only.
1408          * If everything worked out ok, clear OBJ_WRITEABLE and
1409          * OBJ_MIGHTBEDIRTY.
1410          */
1411         if (wholescan) {
1412                 info.error = 0;
1413                 info.count = 0;
1414                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1415                                         vm_object_page_clean_pass1, &info);
1416                 if (info.error == 0) {
1417                         vm_object_clear_flag(object,
1418                                              OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
1419                         if (object->type == OBJT_VNODE &&
1420                             (vp = (struct vnode *)object->handle) != NULL) {
1421                                 /*
1422                                  * Use new-style interface to clear VISDIRTY
1423                                  * because the vnode is not necessarily removed
1424                                  * from the syncer list(s) as often as it was
1425                                  * under the old interface, which can leave
1426                                  * the vnode on the syncer list after reclaim.
1427                                  */
1428                                 vclrobjdirty(vp);
1429                         }
1430                 }
1431         }
1432
1433         /*
1434          * Do a pass to clean all the dirty pages we find.
1435          */
1436         do {
1437                 info.error = 0;
1438                 info.count = 0;
1439                 generation = object->generation;
1440                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1441                                         vm_object_page_clean_pass2, &info);
1442         } while (info.error || generation != object->generation);
1443
1444         vm_object_clear_flag(object, OBJ_CLEANING);
1445         vm_object_drop(object);
1446 }
1447
1448 /*
1449  * The caller must hold the object.
1450  */
1451 static 
1452 int
1453 vm_object_page_clean_pass1(struct vm_page *p, void *data)
1454 {
1455         struct rb_vm_page_scan_info *info = data;
1456
1457         KKASSERT(p->object == info->object);
1458
1459         vm_page_flag_set(p, PG_CLEANCHK);
1460         if ((info->limit & OBJPC_NOSYNC) && (p->flags & PG_NOSYNC)) {
1461                 info->error = 1;
1462         } else if (vm_page_busy_try(p, FALSE)) {
1463                 info->error = 1;
1464         } else {
1465                 KKASSERT(p->object == info->object);
1466                 vm_page_protect(p, VM_PROT_READ);
1467                 vm_page_wakeup(p);
1468         }
1469
1470         /*
1471          * Must be at end to avoid SMP races, caller holds object token
1472          */
1473         if ((++info->count & 63) == 0)
1474                 lwkt_user_yield();
1475         return(0);
1476 }
1477
1478 /*
1479  * The caller must hold the object
1480  */
1481 static 
1482 int
1483 vm_object_page_clean_pass2(struct vm_page *p, void *data)
1484 {
1485         struct rb_vm_page_scan_info *info = data;
1486         int generation;
1487
1488         KKASSERT(p->object == info->object);
1489
1490         /*
1491          * Do not mess with pages that were inserted after we started
1492          * the cleaning pass.
1493          */
1494         if ((p->flags & PG_CLEANCHK) == 0)
1495                 goto done;
1496
1497         generation = info->object->generation;
1498
1499         if (vm_page_busy_try(p, TRUE)) {
1500                 vm_page_sleep_busy(p, TRUE, "vpcwai");
1501                 info->error = 1;
1502                 goto done;
1503         }
1504
1505         KKASSERT(p->object == info->object &&
1506                  info->object->generation == generation);
1507
1508         /*
1509          * Before wasting time traversing the pmaps, check for trivial
1510          * cases where the page cannot be dirty.
1511          */
1512         if (p->valid == 0 || (p->queue - p->pc) == PQ_CACHE) {
1513                 KKASSERT((p->dirty & p->valid) == 0 &&
1514                          (p->flags & PG_NEED_COMMIT) == 0);
1515                 vm_page_wakeup(p);
1516                 goto done;
1517         }
1518
1519         /*
1520          * Check whether the page is dirty or not.  The page has been set
1521          * to be read-only so the check will not race a user dirtying the
1522          * page.
1523          */
1524         vm_page_test_dirty(p);
1525         if ((p->dirty & p->valid) == 0 && (p->flags & PG_NEED_COMMIT) == 0) {
1526                 vm_page_flag_clear(p, PG_CLEANCHK);
1527                 vm_page_wakeup(p);
1528                 goto done;
1529         }
1530
1531         /*
1532          * If we have been asked to skip nosync pages and this is a
1533          * nosync page, skip it.  Note that the object flags were
1534          * not cleared in this case (because pass1 will have returned an
1535          * error), so we do not have to set them.
1536          */
1537         if ((info->limit & OBJPC_NOSYNC) && (p->flags & PG_NOSYNC)) {
1538                 vm_page_flag_clear(p, PG_CLEANCHK);
1539                 vm_page_wakeup(p);
1540                 goto done;
1541         }
1542
1543         /*
1544          * Flush as many pages as we can.  PG_CLEANCHK will be cleared on
1545          * the pages that get successfully flushed.  Set info->error if
1546          * we raced an object modification.
1547          */
1548         vm_object_page_collect_flush(info->object, p, info->pagerflags);
1549         /* vm_wait_nominal(); this can deadlock the system in syncer/pageout */
1550
1551         /*
1552          * Must be at end to avoid SMP races, caller holds object token
1553          */
1554 done:
1555         if ((++info->count & 63) == 0)
1556                 lwkt_user_yield();
1557         return(0);
1558 }
1559
1560 /*
1561  * Collect the specified page and nearby pages and flush them out.
1562  * The number of pages flushed is returned.  The passed page is busied
1563  * by the caller and we are responsible for its disposition.
1564  *
1565  * The caller must hold the object.
1566  */
1567 static void
1568 vm_object_page_collect_flush(vm_object_t object, vm_page_t p, int pagerflags)
1569 {
1570         int error;
1571         int is;
1572         int ib;
1573         int i;
1574         int page_base;
1575         vm_pindex_t pi;
1576         vm_page_t ma[BLIST_MAX_ALLOC];
1577
1578         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1579
1580         pi = p->pindex;
1581         page_base = pi % BLIST_MAX_ALLOC;
1582         ma[page_base] = p;
1583         ib = page_base - 1;
1584         is = page_base + 1;
1585
1586         while (ib >= 0) {
1587                 vm_page_t tp;
1588
1589                 tp = vm_page_lookup_busy_try(object, pi - page_base + ib,
1590                                              TRUE, &error);
1591                 if (error)
1592                         break;
1593                 if (tp == NULL)
1594                         break;
1595                 if ((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
1596                     (tp->flags & PG_CLEANCHK) == 0) {
1597                         vm_page_wakeup(tp);
1598                         break;
1599                 }
1600                 if ((tp->queue - tp->pc) == PQ_CACHE) {
1601                         vm_page_flag_clear(tp, PG_CLEANCHK);
1602                         vm_page_wakeup(tp);
1603                         break;
1604                 }
1605                 vm_page_test_dirty(tp);
1606                 if ((tp->dirty & tp->valid) == 0 &&
1607                     (tp->flags & PG_NEED_COMMIT) == 0) {
1608                         vm_page_flag_clear(tp, PG_CLEANCHK);
1609                         vm_page_wakeup(tp);
1610                         break;
1611                 }
1612                 ma[ib] = tp;
1613                 --ib;
1614         }
1615         ++ib;   /* fixup */
1616
1617         while (is < BLIST_MAX_ALLOC &&
1618                pi - page_base + is < object->size) {
1619                 vm_page_t tp;
1620
1621                 tp = vm_page_lookup_busy_try(object, pi - page_base + is,
1622                                              TRUE, &error);
1623                 if (error)
1624                         break;
1625                 if (tp == NULL)
1626                         break;
1627                 if ((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
1628                     (tp->flags & PG_CLEANCHK) == 0) {
1629                         vm_page_wakeup(tp);
1630                         break;
1631                 }
1632                 if ((tp->queue - tp->pc) == PQ_CACHE) {
1633                         vm_page_flag_clear(tp, PG_CLEANCHK);
1634                         vm_page_wakeup(tp);
1635                         break;
1636                 }
1637                 vm_page_test_dirty(tp);
1638                 if ((tp->dirty & tp->valid) == 0 &&
1639                     (tp->flags & PG_NEED_COMMIT) == 0) {
1640                         vm_page_flag_clear(tp, PG_CLEANCHK);
1641                         vm_page_wakeup(tp);
1642                         break;
1643                 }
1644                 ma[is] = tp;
1645                 ++is;
1646         }
1647
1648         /*
1649          * All pages in the ma[] array are busied now
1650          */
1651         for (i = ib; i < is; ++i) {
1652                 vm_page_flag_clear(ma[i], PG_CLEANCHK);
1653                 vm_page_hold(ma[i]);    /* XXX need this any more? */
1654         }
1655         vm_pageout_flush(&ma[ib], is - ib, pagerflags);
1656         for (i = ib; i < is; ++i)       /* XXX need this any more? */
1657                 vm_page_unhold(ma[i]);
1658 }
1659
1660 /*
1661  * Same as vm_object_pmap_copy, except range checking really
1662  * works, and is meant for small sections of an object.
1663  *
1664  * This code protects resident pages by making them read-only
1665  * and is typically called on a fork or split when a page
1666  * is converted to copy-on-write.  
1667  *
1668  * NOTE: If the page is already at VM_PROT_NONE, calling
1669  * vm_page_protect will have no effect.
1670  */
1671 void
1672 vm_object_pmap_copy_1(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1673 {
1674         vm_pindex_t idx;
1675         vm_page_t p;
1676
1677         if (object == NULL || (object->flags & OBJ_WRITEABLE) == 0)
1678                 return;
1679
1680         vm_object_hold(object);
1681         for (idx = start; idx < end; idx++) {
1682                 p = vm_page_lookup(object, idx);
1683                 if (p == NULL)
1684                         continue;
1685                 vm_page_protect(p, VM_PROT_READ);
1686         }
1687         vm_object_drop(object);
1688 }
1689
1690 /*
1691  * Removes all physical pages in the specified object range from all
1692  * physical maps.
1693  *
1694  * The object must *not* be locked.
1695  */
1696
1697 static int vm_object_pmap_remove_callback(vm_page_t p, void *data);
1698
1699 void
1700 vm_object_pmap_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1701 {
1702         struct rb_vm_page_scan_info info;
1703
1704         if (object == NULL)
1705                 return;
1706         if (start == end)
1707                 return;
1708         info.start_pindex = start;
1709         info.end_pindex = end - 1;
1710         info.count = 0;
1711         info.object = object;
1712
1713         vm_object_hold(object);
1714         do {
1715                 info.error = 0;
1716                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1717                                         vm_object_pmap_remove_callback, &info);
1718         } while (info.error);
1719         if (start == 0 && end == object->size)
1720                 vm_object_clear_flag(object, OBJ_WRITEABLE);
1721         vm_object_drop(object);
1722 }
1723
1724 /*
1725  * The caller must hold the object
1726  */
1727 static int
1728 vm_object_pmap_remove_callback(vm_page_t p, void *data)
1729 {
1730         struct rb_vm_page_scan_info *info = data;
1731
1732         if (info->object != p->object ||
1733             p->pindex < info->start_pindex ||
1734             p->pindex > info->end_pindex) {
1735                 kprintf("vm_object_pmap_remove_callback: obj/pg race %p/%p\n",
1736                         info->object, p);
1737                 info->error = 1;
1738                 return(0);
1739         }
1740
1741         vm_page_protect(p, VM_PROT_NONE);
1742
1743         /*
1744          * Must be at end to avoid SMP races, caller holds object token
1745          */
1746         if ((++info->count & 63) == 0)
1747                 lwkt_user_yield();
1748         return(0);
1749 }
1750
1751 /*
1752  * Implements the madvise function at the object/page level.
1753  *
1754  * MADV_WILLNEED        (any object)
1755  *
1756  *      Activate the specified pages if they are resident.
1757  *
1758  * MADV_DONTNEED        (any object)
1759  *
1760  *      Deactivate the specified pages if they are resident.
1761  *
1762  * MADV_FREE    (OBJT_DEFAULT/OBJT_SWAP objects, OBJ_ONEMAPPING only)
1763  *
1764  *      Deactivate and clean the specified pages if they are
1765  *      resident.  This permits the process to reuse the pages
1766  *      without faulting or the kernel to reclaim the pages
1767  *      without I/O.
1768  *
1769  * No requirements.
1770  */
1771 void
1772 vm_object_madvise(vm_object_t object, vm_pindex_t pindex,
1773                   vm_pindex_t count, int advise)
1774 {
1775         vm_pindex_t end, tpindex;
1776         vm_object_t tobject;
1777         vm_object_t xobj;
1778         vm_page_t m;
1779         int error;
1780
1781         if (object == NULL)
1782                 return;
1783
1784         end = pindex + count;
1785
1786         vm_object_hold(object);
1787         tobject = object;
1788
1789         /*
1790          * Locate and adjust resident pages
1791          */
1792         for (; pindex < end; pindex += 1) {
1793 relookup:
1794                 if (tobject != object)
1795                         vm_object_drop(tobject);
1796                 tobject = object;
1797                 tpindex = pindex;
1798 shadowlookup:
1799                 /*
1800                  * MADV_FREE only operates on OBJT_DEFAULT or OBJT_SWAP pages
1801                  * and those pages must be OBJ_ONEMAPPING.
1802                  */
1803                 if (advise == MADV_FREE) {
1804                         if ((tobject->type != OBJT_DEFAULT &&
1805                              tobject->type != OBJT_SWAP) ||
1806                             (tobject->flags & OBJ_ONEMAPPING) == 0) {
1807                                 continue;
1808                         }
1809                 }
1810
1811                 m = vm_page_lookup_busy_try(tobject, tpindex, TRUE, &error);
1812
1813                 if (error) {
1814                         vm_page_sleep_busy(m, TRUE, "madvpo");
1815                         goto relookup;
1816                 }
1817                 if (m == NULL) {
1818                         /*
1819                          * There may be swap even if there is no backing page
1820                          */
1821                         if (advise == MADV_FREE && tobject->type == OBJT_SWAP)
1822                                 swap_pager_freespace(tobject, tpindex, 1);
1823
1824                         /*
1825                          * next object
1826                          */
1827                         while ((xobj = tobject->backing_object) != NULL) {
1828                                 KKASSERT(xobj != object);
1829                                 vm_object_hold(xobj);
1830                                 if (xobj == tobject->backing_object)
1831                                         break;
1832                                 vm_object_drop(xobj);
1833                         }
1834                         if (xobj == NULL)
1835                                 continue;
1836                         tpindex += OFF_TO_IDX(tobject->backing_object_offset);
1837                         if (tobject != object) {
1838                                 vm_object_lock_swap();
1839                                 vm_object_drop(tobject);
1840                         }
1841                         tobject = xobj;
1842                         goto shadowlookup;
1843                 }
1844
1845                 /*
1846                  * If the page is not in a normal active state, we skip it.
1847                  * If the page is not managed there are no page queues to
1848                  * mess with.  Things can break if we mess with pages in
1849                  * any of the below states.
1850                  */
1851                 if (m->wire_count ||
1852                     (m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
1853                     m->valid != VM_PAGE_BITS_ALL
1854                 ) {
1855                         vm_page_wakeup(m);
1856                         continue;
1857                 }
1858
1859                 /*
1860                  * Theoretically once a page is known not to be busy, an
1861                  * interrupt cannot come along and rip it out from under us.
1862                  */
1863
1864                 if (advise == MADV_WILLNEED) {
1865                         vm_page_activate(m);
1866                 } else if (advise == MADV_DONTNEED) {
1867                         vm_page_dontneed(m);
1868                 } else if (advise == MADV_FREE) {
1869                         /*
1870                          * Mark the page clean.  This will allow the page
1871                          * to be freed up by the system.  However, such pages
1872                          * are often reused quickly by malloc()/free()
1873                          * so we do not do anything that would cause
1874                          * a page fault if we can help it.
1875                          *
1876                          * Specifically, we do not try to actually free
1877                          * the page now nor do we try to put it in the
1878                          * cache (which would cause a page fault on reuse).
1879                          *
1880                          * But we do make the page is freeable as we
1881                          * can without actually taking the step of unmapping
1882                          * it.
1883                          */
1884                         pmap_clear_modify(m);
1885                         m->dirty = 0;
1886                         m->act_count = 0;
1887                         vm_page_dontneed(m);
1888                         if (tobject->type == OBJT_SWAP)
1889                                 swap_pager_freespace(tobject, tpindex, 1);
1890                 }
1891                 vm_page_wakeup(m);
1892         }       
1893         if (tobject != object)
1894                 vm_object_drop(tobject);
1895         vm_object_drop(object);
1896 }
1897
1898 /*
1899  * Create a new object which is backed by the specified existing object
1900  * range.  Replace the pointer and offset that was pointing at the existing
1901  * object with the pointer/offset for the new object.
1902  *
1903  * If addref is non-zero the returned object is given an additional reference.
1904  * This mechanic exists to avoid the situation where refs might be 1 and
1905  * race against a collapse when the caller intends to bump it.  So the
1906  * caller cannot add the ref after the fact.  Used when the caller is
1907  * duplicating a vm_map_entry.
1908  *
1909  * No other requirements.
1910  */
1911 void
1912 vm_object_shadow(vm_object_t *objectp, vm_ooffset_t *offset, vm_size_t length,
1913                  int addref)
1914 {
1915         vm_object_t source;
1916         vm_object_t result;
1917         int useshadowlist;
1918
1919         source = *objectp;
1920
1921         /*
1922          * Don't create the new object if the old object isn't shared.
1923          * We have to chain wait before adding the reference to avoid
1924          * racing a collapse or deallocation.
1925          *
1926          * Clear OBJ_ONEMAPPING flag when shadowing.
1927          *
1928          * The caller owns a ref on source via *objectp which we are going
1929          * to replace.  This ref is inherited by the backing_object assignment.
1930          * from nobject and does not need to be incremented here.
1931          *
1932          * However, we add a temporary extra reference to the original source
1933          * prior to holding nobject in case we block, to avoid races where
1934          * someone else might believe that the source can be collapsed.
1935          */
1936         useshadowlist = 0;
1937         if (source) {
1938                 if (source->type != OBJT_VNODE) {
1939                         useshadowlist = 1;
1940                         vm_object_hold(source);
1941                         vm_object_chain_wait(source, 0);
1942                         if (source->ref_count == 1 &&
1943                             source->handle == NULL &&
1944                             (source->type == OBJT_DEFAULT ||
1945                              source->type == OBJT_SWAP)) {
1946                                 if (addref) {
1947                                         vm_object_reference_locked(source);
1948                                         vm_object_clear_flag(source,
1949                                                              OBJ_ONEMAPPING);
1950                                 }
1951                                 vm_object_drop(source);
1952                                 return;
1953                         }
1954                         vm_object_reference_locked(source);
1955                         vm_object_clear_flag(source, OBJ_ONEMAPPING);
1956                 } else {
1957                         vm_object_reference_quick(source);
1958                         vm_object_clear_flag(source, OBJ_ONEMAPPING);
1959                 }
1960         }
1961
1962         /*
1963          * Allocate a new object with the given length.  The new object
1964          * is returned referenced but we may have to add another one.
1965          * If we are adding a second reference we must clear OBJ_ONEMAPPING.
1966          * (typically because the caller is about to clone a vm_map_entry).
1967          *
1968          * The source object currently has an extra reference to prevent
1969          * collapses into it while we mess with its shadow list, which
1970          * we will remove later in this routine.
1971          *
1972          * The target object may require a second reference if asked for one
1973          * by the caller.
1974          */
1975         result = vm_object_allocate(OBJT_DEFAULT, length);
1976         if (result == NULL)
1977                 panic("vm_object_shadow: no object for shadowing");
1978         vm_object_hold(result);
1979         if (addref) {
1980                 vm_object_reference_locked(result);
1981                 vm_object_clear_flag(result, OBJ_ONEMAPPING);
1982         }
1983
1984         /*
1985          * The new object shadows the source object.
1986          *
1987          * Try to optimize the result object's page color when shadowing
1988          * in order to maintain page coloring consistency in the combined 
1989          * shadowed object.
1990          *
1991          * The backing_object reference to source requires adding a ref to
1992          * source.  We simply inherit the ref from the original *objectp
1993          * (which we are replacing) so no additional refs need to be added.
1994          * (we must still clean up the extra ref we had to prevent collapse
1995          * races).
1996          *
1997          * SHADOWING IS NOT APPLICABLE TO OBJT_VNODE OBJECTS
1998          */
1999         KKASSERT(result->backing_object == NULL);
2000         result->backing_object = source;
2001         if (source) {
2002                 if (useshadowlist) {
2003                         vm_object_chain_wait(source, 0);
2004                         atomic_add_int(&source->generation, 1);
2005                         vm_object_set_flag(result, OBJ_ONSHADOW);
2006                 }
2007                 /* cpu localization twist */
2008                 result->pg_color = vm_quickcolor();
2009         }
2010
2011         /*
2012          * Adjust the return storage.  Drop the ref on source before
2013          * returning.
2014          */
2015         result->backing_object_offset = *offset;
2016         vm_object_drop(result);
2017         *offset = 0;
2018         if (source) {
2019                 if (useshadowlist) {
2020                         vm_object_deallocate_locked(source);
2021                         vm_object_drop(source);
2022                 } else {
2023                         vm_object_deallocate(source);
2024                 }
2025         }
2026
2027         /*
2028          * Return the new things
2029          */
2030         *objectp = result;
2031 }
2032
2033 #define OBSC_TEST_ALL_SHADOWED  0x0001
2034 #define OBSC_COLLAPSE_NOWAIT    0x0002
2035 #define OBSC_COLLAPSE_WAIT      0x0004
2036
2037 static int vm_object_backing_scan_callback(vm_page_t p, void *data);
2038
2039 /*
2040  * The caller must hold the object.
2041  */
2042 static __inline int
2043 vm_object_backing_scan(vm_object_t object, vm_object_t backing_object, int op)
2044 {
2045         struct rb_vm_page_scan_info info;
2046         struct vm_object_hash *hash;
2047
2048         vm_object_assert_held(object);
2049         vm_object_assert_held(backing_object);
2050
2051         KKASSERT(backing_object == object->backing_object);
2052         info.backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
2053
2054         /*
2055          * Initial conditions
2056          */
2057         if (op & OBSC_TEST_ALL_SHADOWED) {
2058                 /*
2059                  * We do not want to have to test for the existence of
2060                  * swap pages in the backing object.  XXX but with the
2061                  * new swapper this would be pretty easy to do.
2062                  *
2063                  * XXX what about anonymous MAP_SHARED memory that hasn't
2064                  * been ZFOD faulted yet?  If we do not test for this, the
2065                  * shadow test may succeed! XXX
2066                  */
2067                 if (backing_object->type != OBJT_DEFAULT)
2068                         return(0);
2069         }
2070         if (op & OBSC_COLLAPSE_WAIT) {
2071                 KKASSERT((backing_object->flags & OBJ_DEAD) == 0);
2072                 vm_object_set_flag(backing_object, OBJ_DEAD);
2073
2074                 hash = vmobj_hash(backing_object);
2075                 lwkt_gettoken(&hash->token);
2076                 TAILQ_REMOVE(&hash->list, backing_object, object_list);
2077                 lwkt_reltoken(&hash->token);
2078         }
2079
2080         /*
2081          * Our scan.   We have to retry if a negative error code is returned,
2082          * otherwise 0 or 1 will be returned in info.error.  0 Indicates that
2083          * the scan had to be stopped because the parent does not completely
2084          * shadow the child.
2085          */
2086         info.object = object;
2087         info.backing_object = backing_object;
2088         info.limit = op;
2089         info.count = 0;
2090         do {
2091                 info.error = 1;
2092                 vm_page_rb_tree_RB_SCAN(&backing_object->rb_memq, NULL,
2093                                         vm_object_backing_scan_callback,
2094                                         &info);
2095         } while (info.error < 0);
2096
2097         return(info.error);
2098 }
2099
2100 /*
2101  * The caller must hold the object.
2102  */
2103 static int
2104 vm_object_backing_scan_callback(vm_page_t p, void *data)
2105 {
2106         struct rb_vm_page_scan_info *info = data;
2107         vm_object_t backing_object;
2108         vm_object_t object;
2109         vm_pindex_t pindex;
2110         vm_pindex_t new_pindex;
2111         vm_pindex_t backing_offset_index;
2112         int op;
2113
2114         pindex = p->pindex;
2115         new_pindex = pindex - info->backing_offset_index;
2116         op = info->limit;
2117         object = info->object;
2118         backing_object = info->backing_object;
2119         backing_offset_index = info->backing_offset_index;
2120
2121         if (op & OBSC_TEST_ALL_SHADOWED) {
2122                 vm_page_t pp;
2123
2124                 /*
2125                  * Ignore pages outside the parent object's range
2126                  * and outside the parent object's mapping of the 
2127                  * backing object.
2128                  *
2129                  * note that we do not busy the backing object's
2130                  * page.
2131                  */
2132                 if (pindex < backing_offset_index ||
2133                     new_pindex >= object->size
2134                 ) {
2135                         return(0);
2136                 }
2137
2138                 /*
2139                  * See if the parent has the page or if the parent's
2140                  * object pager has the page.  If the parent has the
2141                  * page but the page is not valid, the parent's
2142                  * object pager must have the page.
2143                  *
2144                  * If this fails, the parent does not completely shadow
2145                  * the object and we might as well give up now.
2146                  */
2147                 pp = vm_page_lookup(object, new_pindex);
2148                 if ((pp == NULL || pp->valid == 0) &&
2149                     !vm_pager_has_page(object, new_pindex)
2150                 ) {
2151                         info->error = 0;        /* problemo */
2152                         return(-1);             /* stop the scan */
2153                 }
2154         }
2155
2156         /*
2157          * Check for busy page.  Note that we may have lost (p) when we
2158          * possibly blocked above.
2159          */
2160         if (op & (OBSC_COLLAPSE_WAIT | OBSC_COLLAPSE_NOWAIT)) {
2161                 vm_page_t pp;
2162
2163                 if (vm_page_busy_try(p, TRUE)) {
2164                         if (op & OBSC_COLLAPSE_NOWAIT) {
2165                                 return(0);
2166                         } else {
2167                                 /*
2168                                  * If we slept, anything could have
2169                                  * happened.   Ask that the scan be restarted.
2170                                  *
2171                                  * Since the object is marked dead, the
2172                                  * backing offset should not have changed.  
2173                                  */
2174                                 vm_page_sleep_busy(p, TRUE, "vmocol");
2175                                 info->error = -1;
2176                                 return(-1);
2177                         }
2178                 }
2179
2180                 /*
2181                  * If (p) is no longer valid restart the scan.
2182                  */
2183                 if (p->object != backing_object || p->pindex != pindex) {
2184                         kprintf("vm_object_backing_scan: Warning: page "
2185                                 "%p ripped out from under us\n", p);
2186                         vm_page_wakeup(p);
2187                         info->error = -1;
2188                         return(-1);
2189                 }
2190
2191                 if (op & OBSC_COLLAPSE_NOWAIT) {
2192                         if (p->valid == 0 ||
2193                             p->wire_count ||
2194                             (p->flags & PG_NEED_COMMIT)) {
2195                                 vm_page_wakeup(p);
2196                                 return(0);
2197                         }
2198                 } else {
2199                         /* XXX what if p->valid == 0 , hold_count, etc? */
2200                 }
2201
2202                 KASSERT(
2203                     p->object == backing_object,
2204                     ("vm_object_qcollapse(): object mismatch")
2205                 );
2206
2207                 /*
2208                  * Destroy any associated swap
2209                  */
2210                 if (backing_object->type == OBJT_SWAP)
2211                         swap_pager_freespace(backing_object, p->pindex, 1);
2212
2213                 if (
2214                     p->pindex < backing_offset_index ||
2215                     new_pindex >= object->size
2216                 ) {
2217                         /*
2218                          * Page is out of the parent object's range, we 
2219                          * can simply destroy it. 
2220                          */
2221                         vm_page_protect(p, VM_PROT_NONE);
2222                         vm_page_free(p);
2223                         return(0);
2224                 }
2225
2226                 pp = vm_page_lookup(object, new_pindex);
2227                 if (pp != NULL || vm_pager_has_page(object, new_pindex)) {
2228                         /*
2229                          * page already exists in parent OR swap exists
2230                          * for this location in the parent.  Destroy 
2231                          * the original page from the backing object.
2232                          *
2233                          * Leave the parent's page alone
2234                          */
2235                         vm_page_protect(p, VM_PROT_NONE);
2236                         vm_page_free(p);
2237                         return(0);
2238                 }
2239
2240                 /*
2241                  * Page does not exist in parent, rename the
2242                  * page from the backing object to the main object. 
2243                  *
2244                  * If the page was mapped to a process, it can remain 
2245                  * mapped through the rename.
2246                  */
2247                 if ((p->queue - p->pc) == PQ_CACHE)
2248                         vm_page_deactivate(p);
2249
2250                 vm_page_rename(p, object, new_pindex);
2251                 vm_page_wakeup(p);
2252                 /* page automatically made dirty by rename */
2253         }
2254         return(0);
2255 }
2256
2257 /*
2258  * This version of collapse allows the operation to occur earlier and
2259  * when paging_in_progress is true for an object...  This is not a complete
2260  * operation, but should plug 99.9% of the rest of the leaks.
2261  *
2262  * The caller must hold the object and backing_object and both must be
2263  * chainlocked.
2264  *
2265  * (only called from vm_object_collapse)
2266  */
2267 static void
2268 vm_object_qcollapse(vm_object_t object, vm_object_t backing_object)
2269 {
2270         if (backing_object->ref_count == 1) {
2271                 atomic_add_int(&backing_object->ref_count, 2);
2272 #if defined(DEBUG_LOCKS)
2273                 debugvm_object_add(backing_object, "qcollapse", 1, 2);
2274 #endif
2275                 vm_object_backing_scan(object, backing_object,
2276                                        OBSC_COLLAPSE_NOWAIT);
2277                 atomic_add_int(&backing_object->ref_count, -2);
2278 #if defined(DEBUG_LOCKS)
2279                 debugvm_object_add(backing_object, "qcollapse", 2, -2);
2280 #endif
2281         }
2282 }
2283
2284 /*
2285  * Collapse an object with the object backing it.  Pages in the backing
2286  * object are moved into the parent, and the backing object is deallocated.
2287  * Any conflict is resolved in favor of the parent's existing pages.
2288  *
2289  * object must be held and chain-locked on call.
2290  *
2291  * The caller must have an extra ref on object to prevent a race from
2292  * destroying it during the collapse.
2293  */
2294 void
2295 vm_object_collapse(vm_object_t object, struct vm_object_dealloc_list **dlistp)
2296 {
2297         struct vm_object_dealloc_list *dlist = NULL;
2298         vm_object_t backing_object;
2299
2300         /*
2301          * Only one thread is attempting a collapse at any given moment.
2302          * There are few restrictions for (object) that callers of this
2303          * function check so reentrancy is likely.
2304          */
2305         KKASSERT(object != NULL);
2306         vm_object_assert_held(object);
2307         KKASSERT(object->chainlk & (CHAINLK_MASK | CHAINLK_EXCL));
2308
2309         for (;;) {
2310                 vm_object_t bbobj;
2311                 int dodealloc;
2312
2313                 /*
2314                  * We can only collapse a DEFAULT/SWAP object with a
2315                  * DEFAULT/SWAP object.
2316                  */
2317                 if (object->type != OBJT_DEFAULT && object->type != OBJT_SWAP) {
2318                         backing_object = NULL;
2319                         break;
2320                 }
2321
2322                 backing_object = object->backing_object;
2323                 if (backing_object == NULL)
2324                         break;
2325                 if (backing_object->type != OBJT_DEFAULT &&
2326                     backing_object->type != OBJT_SWAP) {
2327                         backing_object = NULL;
2328                         break;
2329                 }
2330
2331                 /*
2332                  * Hold (token lock) the backing_object and retest conditions.
2333                  */
2334                 vm_object_hold(backing_object);
2335                 if (backing_object != object->backing_object ||
2336                     (backing_object->type != OBJT_DEFAULT &&
2337                      backing_object->type != OBJT_SWAP)) {
2338                         vm_object_drop(backing_object);
2339                         continue;
2340                 }
2341
2342                 /*
2343                  * Chain-lock the backing object too because if we
2344                  * successfully merge its pages into the top object we
2345                  * will collapse backing_object->backing_object as the
2346                  * new backing_object.  Re-check that it is still our
2347                  * backing object.
2348                  */
2349                 vm_object_chain_acquire(backing_object, 0);
2350                 if (backing_object != object->backing_object) {
2351                         vm_object_chain_release(backing_object);
2352                         vm_object_drop(backing_object);
2353                         continue;
2354                 }
2355
2356                 /*
2357                  * We check the backing object first, because it is most
2358                  * likely not collapsable.
2359                  */
2360                 if (backing_object->handle != NULL ||
2361                     (backing_object->type != OBJT_DEFAULT &&
2362                      backing_object->type != OBJT_SWAP) ||
2363                     (backing_object->flags & OBJ_DEAD) ||
2364                     object->handle != NULL ||
2365                     (object->type != OBJT_DEFAULT &&
2366                      object->type != OBJT_SWAP) ||
2367                     (object->flags & OBJ_DEAD)) {
2368                         break;
2369                 }
2370
2371                 /*
2372                  * If paging is in progress we can't do a normal collapse.
2373                  */
2374                 if (object->paging_in_progress != 0 ||
2375                     backing_object->paging_in_progress != 0
2376                 ) {
2377                         vm_object_qcollapse(object, backing_object);
2378                         break;
2379                 }
2380
2381                 /*
2382                  * We know that we can either collapse the backing object (if
2383                  * the parent is the only reference to it) or (perhaps) have
2384                  * the parent bypass the object if the parent happens to shadow
2385                  * all the resident pages in the entire backing object.
2386                  *
2387                  * This is ignoring pager-backed pages such as swap pages.
2388                  * vm_object_backing_scan fails the shadowing test in this
2389                  * case.
2390                  */
2391                 if (backing_object->ref_count == 1) {
2392                         /*
2393                          * If there is exactly one reference to the backing
2394                          * object, we can collapse it into the parent.  
2395                          */
2396                         KKASSERT(object->backing_object == backing_object);
2397                         vm_object_backing_scan(object, backing_object,
2398                                                OBSC_COLLAPSE_WAIT);
2399
2400                         /*
2401                          * Move the pager from backing_object to object.
2402                          */
2403                         if (backing_object->type == OBJT_SWAP) {
2404                                 vm_object_pip_add(backing_object, 1);
2405
2406                                 /*
2407                                  * scrap the paging_offset junk and do a 
2408                                  * discrete copy.  This also removes major 
2409                                  * assumptions about how the swap-pager 
2410                                  * works from where it doesn't belong.  The
2411                                  * new swapper is able to optimize the
2412                                  * destroy-source case.
2413                                  */
2414                                 vm_object_pip_add(object, 1);
2415                                 swap_pager_copy(backing_object, object,
2416                                     OFF_TO_IDX(object->backing_object_offset),
2417                                     TRUE);
2418                                 vm_object_pip_wakeup(object);
2419                                 vm_object_pip_wakeup(backing_object);
2420                         }
2421
2422                         /*
2423                          * Object now shadows whatever backing_object did.
2424                          *
2425                          * Removing object from backing_objects shadow list
2426                          * requires releasing object, which we will do below.
2427                          */
2428                         KKASSERT(object->backing_object == backing_object);
2429                         if (object->flags & OBJ_ONSHADOW) {
2430                                 atomic_add_int(&backing_object->generation, 1);
2431                                 vm_object_clear_flag(object, OBJ_ONSHADOW);
2432                         }
2433
2434                         /*
2435                          * backing_object->backing_object moves from within
2436                          * backing_object to within object.
2437                          *
2438                          * OBJT_VNODE bbobj's should have empty shadow lists.
2439                          */
2440                         while ((bbobj = backing_object->backing_object) != NULL) {
2441                                 if (bbobj->type == OBJT_VNODE)
2442                                         vm_object_hold_shared(bbobj);
2443                                 else
2444                                         vm_object_hold(bbobj);
2445                                 if (bbobj == backing_object->backing_object)
2446                                         break;
2447                                 vm_object_drop(bbobj);
2448                         }
2449
2450                         /*
2451                          * We are removing backing_object from bbobj's
2452                          * shadow list and adding object to bbobj's shadow
2453                          * list, so the ref_count on bbobj is unchanged.
2454                          */
2455                         if (bbobj) {
2456                                 if (backing_object->flags & OBJ_ONSHADOW) {
2457                                         /* not locked exclusively if vnode */
2458                                         KKASSERT(bbobj->type != OBJT_VNODE);
2459                                         atomic_add_int(&bbobj->generation, 1);
2460                                         vm_object_clear_flag(backing_object,
2461                                                              OBJ_ONSHADOW);
2462                                 }
2463                                 backing_object->backing_object = NULL;
2464                         }
2465                         object->backing_object = bbobj;
2466                         if (bbobj) {
2467                                 if (bbobj->type != OBJT_VNODE) {
2468                                         atomic_add_int(&bbobj->generation, 1);
2469                                         vm_object_set_flag(object,
2470                                                            OBJ_ONSHADOW);
2471                                 }
2472                         }
2473
2474                         object->backing_object_offset +=
2475                                 backing_object->backing_object_offset;
2476
2477                         vm_object_drop(bbobj);
2478
2479                         /*
2480                          * Discard the old backing_object.  Nothing should be
2481                          * able to ref it, other than a vm_map_split(),
2482                          * and vm_map_split() will stall on our chain lock.
2483                          * And we control the parent so it shouldn't be
2484                          * possible for it to go away either.
2485                          *
2486                          * Since the backing object has no pages, no pager
2487                          * left, and no object references within it, all
2488                          * that is necessary is to dispose of it.
2489                          */
2490                         KASSERT(backing_object->ref_count == 1,
2491                                 ("backing_object %p was somehow "
2492                                  "re-referenced during collapse!",
2493                                  backing_object));
2494                         KASSERT(RB_EMPTY(&backing_object->rb_memq),
2495                                 ("backing_object %p somehow has left "
2496                                  "over pages during collapse!",
2497                                  backing_object));
2498
2499                         /*
2500                          * The object can be destroyed.
2501                          *
2502                          * XXX just fall through and dodealloc instead
2503                          *     of forcing destruction?
2504                          */
2505                         atomic_add_int(&backing_object->ref_count, -1);
2506 #if defined(DEBUG_LOCKS)
2507                         debugvm_object_add(backing_object, "collapse", 1, -1);
2508 #endif
2509                         if ((backing_object->flags & OBJ_DEAD) == 0)
2510                                 vm_object_terminate(backing_object);
2511                         object_collapses++;
2512                         dodealloc = 0;
2513                 } else {
2514                         /*
2515                          * If we do not entirely shadow the backing object,
2516                          * there is nothing we can do so we give up.
2517                          */
2518                         if (vm_object_backing_scan(object, backing_object,
2519                                                 OBSC_TEST_ALL_SHADOWED) == 0) {
2520                                 break;
2521                         }
2522
2523                         /*
2524                          * bbobj is backing_object->backing_object.  Since
2525                          * object completely shadows backing_object we can
2526                          * bypass it and become backed by bbobj instead.
2527                          *
2528                          * The shadow list for vnode backing objects is not
2529                          * used and a shared hold is allowed.
2530                          */
2531                         while ((bbobj = backing_object->backing_object) != NULL) {
2532                                 if (bbobj->type == OBJT_VNODE)
2533                                         vm_object_hold_shared(bbobj);
2534                                 else
2535                                         vm_object_hold(bbobj);
2536                                 if (bbobj == backing_object->backing_object)
2537                                         break;
2538                                 vm_object_drop(bbobj);
2539                         }
2540
2541                         /*
2542                          * Make object shadow bbobj instead of backing_object.
2543                          * Remove object from backing_object's shadow list.
2544                          *
2545                          * Deallocating backing_object will not remove
2546                          * it, since its reference count is at least 2.
2547                          *
2548                          * Removing object from backing_object's shadow
2549                          * list requires releasing a ref, which we do
2550                          * below by setting dodealloc to 1.
2551                          */
2552                         KKASSERT(object->backing_object == backing_object);
2553                         if (object->flags & OBJ_ONSHADOW) {
2554                                 atomic_add_int(&backing_object->generation, 1);
2555                                 vm_object_clear_flag(object, OBJ_ONSHADOW);
2556                         }
2557
2558                         /*
2559                          * Add a ref to bbobj, bbobj now shadows object.
2560                          *
2561                          * NOTE: backing_object->backing_object still points
2562                          *       to bbobj.  That relationship remains intact
2563                          *       because backing_object has > 1 ref, so
2564                          *       someone else is pointing to it (hence why
2565                          *       we can't collapse it into object and can
2566                          *       only handle the all-shadowed bypass case).
2567                          */
2568                         if (bbobj) {
2569                                 if (bbobj->type != OBJT_VNODE) {
2570                                         vm_object_chain_wait(bbobj, 0);
2571                                         vm_object_reference_locked(bbobj);
2572                                         atomic_add_int(&bbobj->generation, 1);
2573                                         vm_object_set_flag(object,
2574                                                            OBJ_ONSHADOW);
2575                                 } else {
2576                                         vm_object_reference_quick(bbobj);
2577                                 }
2578                                 object->backing_object_offset +=
2579                                         backing_object->backing_object_offset;
2580                                 object->backing_object = bbobj;
2581                                 vm_object_drop(bbobj);
2582                         } else {
2583                                 object->backing_object = NULL;
2584                         }
2585
2586                         /*
2587                          * Drop the reference count on backing_object.  To
2588                          * handle ref_count races properly we can't assume
2589                          * that the ref_count is still at least 2 so we
2590                          * have to actually call vm_object_deallocate()
2591                          * (after clearing the chainlock).
2592                          */
2593                         object_bypasses++;
2594                         dodealloc = 1;
2595                 }
2596
2597                 /*
2598                  * Ok, we want to loop on the new object->bbobj association,
2599                  * possibly collapsing it further.  However if dodealloc is
2600                  * non-zero we have to deallocate the backing_object which
2601                  * itself can potentially undergo a collapse, creating a
2602                  * recursion depth issue with the LWKT token subsystem.
2603                  *
2604                  * In the case where we must deallocate the backing_object
2605                  * it is possible now that the backing_object has a single
2606                  * shadow count on some other object (not represented here
2607                  * as yet), since it no longer shadows us.  Thus when we
2608                  * call vm_object_deallocate() it may attempt to collapse
2609                  * itself into its remaining parent.
2610                  */
2611                 if (dodealloc) {
2612                         struct vm_object_dealloc_list *dtmp;
2613
2614                         vm_object_chain_release(backing_object);
2615                         vm_object_unlock(backing_object);
2616                         /* backing_object remains held */
2617
2618                         /*
2619                          * Auto-deallocation list for caller convenience.
2620                          */
2621                         if (dlistp == NULL)
2622                                 dlistp = &dlist;
2623
2624                         dtmp = kmalloc(sizeof(*dtmp), M_TEMP, M_WAITOK);
2625                         dtmp->object = backing_object;
2626                         dtmp->next = *dlistp;
2627                         *dlistp = dtmp;
2628                 } else {
2629                         vm_object_chain_release(backing_object);
2630                         vm_object_drop(backing_object);
2631                 }
2632                 /* backing_object = NULL; not needed */
2633                 /* loop */
2634         }
2635
2636         /*
2637          * Clean up any left over backing_object
2638          */
2639         if (backing_object) {
2640                 vm_object_chain_release(backing_object);
2641                 vm_object_drop(backing_object);
2642         }
2643
2644         /*
2645          * Clean up any auto-deallocation list.  This is a convenience
2646          * for top-level callers so they don't have to pass &dlist.
2647          * Do not clean up any caller-passed dlistp, the caller will
2648          * do that.
2649          */
2650         if (dlist)
2651                 vm_object_deallocate_list(&dlist);
2652
2653 }
2654
2655 /*
2656  * vm_object_collapse() may collect additional objects in need of
2657  * deallocation.  This routine deallocates these objects.  The
2658  * deallocation itself can trigger additional collapses (which the
2659  * deallocate function takes care of).  This procedure is used to
2660  * reduce procedural recursion since these vm_object shadow chains
2661  * can become quite long.
2662  */
2663 void
2664 vm_object_deallocate_list(struct vm_object_dealloc_list **dlistp)
2665 {
2666         struct vm_object_dealloc_list *dlist;
2667
2668         while ((dlist = *dlistp) != NULL) {
2669                 *dlistp = dlist->next;
2670                 vm_object_lock(dlist->object);
2671                 vm_object_deallocate_locked(dlist->object);
2672                 vm_object_drop(dlist->object);
2673                 kfree(dlist, M_TEMP);
2674         }
2675 }
2676
2677 /*
2678  * Removes all physical pages in the specified object range from the
2679  * object's list of pages.
2680  *
2681  * No requirements.
2682  */
2683 static int vm_object_page_remove_callback(vm_page_t p, void *data);
2684
2685 void
2686 vm_object_page_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
2687                       boolean_t clean_only)
2688 {
2689         struct rb_vm_page_scan_info info;
2690         int all;
2691
2692         /*
2693          * Degenerate cases and assertions
2694          */
2695         vm_object_hold(object);
2696         if (object == NULL ||
2697             (object->resident_page_count == 0 && object->swblock_count == 0)) {
2698                 vm_object_drop(object);
2699                 return;
2700         }
2701         KASSERT(object->type != OBJT_PHYS, 
2702                 ("attempt to remove pages from a physical object"));
2703
2704         /*
2705          * Indicate that paging is occuring on the object
2706          */
2707         vm_object_pip_add(object, 1);
2708
2709         /*
2710          * Figure out the actual removal range and whether we are removing
2711          * the entire contents of the object or not.  If removing the entire
2712          * contents, be sure to get all pages, even those that might be 
2713          * beyond the end of the object.
2714          */
2715         info.object = object;
2716         info.start_pindex = start;
2717         if (end == 0)
2718                 info.end_pindex = (vm_pindex_t)-1;
2719         else
2720                 info.end_pindex = end - 1;
2721         info.limit = clean_only;
2722         info.count = 0;
2723         all = (start == 0 && info.end_pindex >= object->size - 1);
2724
2725         /*
2726          * Loop until we are sure we have gotten them all.
2727          */
2728         do {
2729                 info.error = 0;
2730                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
2731                                         vm_object_page_remove_callback, &info);
2732         } while (info.error);
2733
2734         /*
2735          * Remove any related swap if throwing away pages, or for
2736          * non-swap objects (the swap is a clean copy in that case).
2737          */
2738         if (object->type != OBJT_SWAP || clean_only == FALSE) {
2739                 if (all)
2740                         swap_pager_freespace_all(object);
2741                 else
2742                         swap_pager_freespace(object, info.start_pindex,
2743                              info.end_pindex - info.start_pindex + 1);
2744         }
2745
2746         /*
2747          * Cleanup
2748          */
2749         vm_object_pip_wakeup(object);
2750         vm_object_drop(object);
2751 }
2752
2753 /*
2754  * The caller must hold the object.
2755  *
2756  * NOTE: User yields are allowed when removing more than one page, but not
2757  *       allowed if only removing one page (the path for single page removals
2758  *       might hold a spinlock).
2759  */
2760 static int
2761 vm_object_page_remove_callback(vm_page_t p, void *data)
2762 {
2763         struct rb_vm_page_scan_info *info = data;
2764
2765         if (info->object != p->object ||
2766             p->pindex < info->start_pindex ||
2767             p->pindex > info->end_pindex) {
2768                 kprintf("vm_object_page_remove_callbackA: obj/pg race %p/%p\n",
2769                         info->object, p);
2770                 return(0);
2771         }
2772         if (vm_page_busy_try(p, TRUE)) {
2773                 vm_page_sleep_busy(p, TRUE, "vmopar");
2774                 info->error = 1;
2775                 return(0);
2776         }
2777         if (info->object != p->object) {
2778                 /* this should never happen */
2779                 kprintf("vm_object_page_remove_callbackB: obj/pg race %p/%p\n",
2780                         info->object, p);
2781                 vm_page_wakeup(p);
2782                 return(0);
2783         }
2784
2785         /*
2786          * Wired pages cannot be destroyed, but they can be invalidated
2787          * and we do so if clean_only (limit) is not set.
2788          *
2789          * WARNING!  The page may be wired due to being part of a buffer
2790          *           cache buffer, and the buffer might be marked B_CACHE.
2791          *           This is fine as part of a truncation but VFSs must be
2792          *           sure to fix the buffer up when re-extending the file.
2793          *
2794          * NOTE!     PG_NEED_COMMIT is ignored.
2795          */
2796         if (p->wire_count != 0) {
2797                 vm_page_protect(p, VM_PROT_NONE);
2798                 if (info->limit == 0)
2799                         p->valid = 0;
2800                 vm_page_wakeup(p);
2801                 goto done;
2802         }
2803
2804         /*
2805          * limit is our clean_only flag.  If set and the page is dirty or
2806          * requires a commit, do not free it.  If set and the page is being
2807          * held by someone, do not free it.
2808          */
2809         if (info->limit && p->valid) {
2810                 vm_page_test_dirty(p);
2811                 if ((p->valid & p->dirty) || (p->flags & PG_NEED_COMMIT)) {
2812                         vm_page_wakeup(p);
2813                         goto done;
2814                 }
2815         }
2816
2817         /*
2818          * Destroy the page
2819          */
2820         vm_page_protect(p, VM_PROT_NONE);
2821         vm_page_free(p);
2822
2823         /*
2824          * Must be at end to avoid SMP races, caller holds object token
2825          */
2826 done:
2827         if ((++info->count & 63) == 0)
2828                 lwkt_user_yield();
2829
2830         return(0);
2831 }
2832
2833 /*
2834  * Try to extend prev_object into an adjoining region of virtual
2835  * memory, return TRUE on success.
2836  *
2837  * The caller does not need to hold (prev_object) but must have a stable
2838  * pointer to it (typically by holding the vm_map locked).
2839  *
2840  * This function only works for anonymous memory objects which either
2841  * have (a) one reference or (b) we are extending the object's size.
2842  * Otherwise the related VM pages we want to use for the object might
2843  * be in use by another mapping.
2844  */
2845 boolean_t
2846 vm_object_coalesce(vm_object_t prev_object, vm_pindex_t prev_pindex,
2847                    vm_size_t prev_size, vm_size_t next_size)
2848 {
2849         vm_pindex_t next_pindex;
2850
2851         if (prev_object == NULL)
2852                 return (TRUE);
2853
2854         vm_object_hold(prev_object);
2855
2856         if (prev_object->type != OBJT_DEFAULT &&
2857             prev_object->type != OBJT_SWAP) {
2858                 vm_object_drop(prev_object);
2859                 return (FALSE);
2860         }
2861
2862         /*
2863          * Try to collapse the object first
2864          */
2865         vm_object_chain_acquire(prev_object, 0);
2866         vm_object_collapse(prev_object, NULL);
2867
2868         /*
2869          * We can't coalesce if we shadow another object (figuring out the
2870          * relationships become too complex).
2871          */
2872         if (prev_object->backing_object != NULL) {
2873                 vm_object_chain_release(prev_object);
2874                 vm_object_drop(prev_object);
2875                 return (FALSE);
2876         }
2877
2878         prev_size >>= PAGE_SHIFT;
2879         next_size >>= PAGE_SHIFT;
2880         next_pindex = prev_pindex + prev_size;
2881
2882         /*
2883          * We can't if the object has more than one ref count unless we
2884          * are extending it into newly minted space.
2885          */
2886         if (prev_object->ref_count > 1 &&
2887             prev_object->size != next_pindex) {
2888                 vm_object_chain_release(prev_object);
2889                 vm_object_drop(prev_object);
2890                 return (FALSE);
2891         }
2892
2893         /*
2894          * Remove any pages that may still be in the object from a previous
2895          * deallocation.
2896          */
2897         if (next_pindex < prev_object->size) {
2898                 vm_object_page_remove(prev_object,
2899                                       next_pindex,
2900                                       next_pindex + next_size, FALSE);
2901                 if (prev_object->type == OBJT_SWAP)
2902                         swap_pager_freespace(prev_object,
2903                                              next_pindex, next_size);
2904         }
2905
2906         /*
2907          * Extend the object if necessary.
2908          */
2909         if (next_pindex + next_size > prev_object->size)
2910                 prev_object->size = next_pindex + next_size;
2911         vm_object_chain_release(prev_object);
2912         vm_object_drop(prev_object);
2913
2914         return (TRUE);
2915 }
2916
2917 /*
2918  * Make the object writable and flag is being possibly dirty.
2919  *
2920  * The object might not be held (or might be held but held shared),
2921  * the related vnode is probably not held either.  Object and vnode are
2922  * stable by virtue of the vm_page busied by the caller preventing
2923  * destruction.
2924  *
2925  * If the related mount is flagged MNTK_THR_SYNC we need to call
2926  * vsetobjdirty().  Filesystems using this option usually shortcut
2927  * synchronization by only scanning the syncer list.
2928  */
2929 void
2930 vm_object_set_writeable_dirty(vm_object_t object)
2931 {
2932         struct vnode *vp;
2933
2934         /*vm_object_assert_held(object);*/
2935         /*
2936          * Avoid contention in vm fault path by checking the state before
2937          * issuing an atomic op on it.
2938          */
2939         if ((object->flags & (OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY)) !=
2940             (OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY)) {
2941                 vm_object_set_flag(object, OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
2942         }
2943         if (object->type == OBJT_VNODE &&
2944             (vp = (struct vnode *)object->handle) != NULL) {
2945                 if ((vp->v_flag & VOBJDIRTY) == 0) {
2946                         if (vp->v_mount &&
2947                             (vp->v_mount->mnt_kern_flag & MNTK_THR_SYNC)) {
2948                                 /*
2949                                  * New style THR_SYNC places vnodes on the
2950                                  * syncer list more deterministically.
2951                                  */
2952                                 vsetobjdirty(vp);
2953                         } else {
2954                                 /*
2955                                  * Old style scan would not necessarily place
2956                                  * a vnode on the syncer list when possibly
2957                                  * modified via mmap.
2958                                  */
2959                                 vsetflags(vp, VOBJDIRTY);
2960                         }
2961                 }
2962         }
2963 }
2964
2965 #include "opt_ddb.h"
2966 #ifdef DDB
2967 #include <sys/cons.h>
2968
2969 #include <ddb/ddb.h>
2970
2971 static int      _vm_object_in_map (vm_map_t map, vm_object_t object,
2972                                        vm_map_entry_t entry);
2973 static int      vm_object_in_map (vm_object_t object);
2974
2975 /*
2976  * The caller must hold the object.
2977  */
2978 static int
2979 _vm_object_in_map(vm_map_t map, vm_object_t object, vm_map_entry_t entry)
2980 {
2981         vm_map_t tmpm;
2982         vm_map_entry_t tmpe;
2983         vm_object_t obj, nobj;
2984         int entcount;
2985
2986         if (map == NULL)
2987                 return 0;
2988         if (entry == NULL) {
2989                 tmpe = RB_MIN(vm_map_rb_tree, &map->rb_root);
2990                 entcount = map->nentries;
2991                 while (entcount-- && tmpe) {
2992                         if( _vm_object_in_map(map, object, tmpe)) {
2993                                 return 1;
2994                         }
2995                         tmpe = vm_map_rb_tree_RB_NEXT(tmpe);
2996                 }
2997                 return (0);
2998         }
2999         switch(entry->maptype) {
3000         case VM_MAPTYPE_SUBMAP:
3001                 tmpm = entry->object.sub_map;
3002                 tmpe = RB_MIN(vm_map_rb_tree, &tmpm->rb_root);
3003                 entcount = tmpm->nentries;
3004                 while (entcount-- && tmpe) {
3005                         if( _vm_object_in_map(tmpm, object, tmpe)) {
3006                                 return 1;
3007                         }
3008                         tmpe = vm_map_rb_tree_RB_NEXT(tmpe);
3009                 }
3010                 break;
3011         case VM_MAPTYPE_NORMAL:
3012         case VM_MAPTYPE_VPAGETABLE:
3013                 obj = entry->object.vm_object;
3014                 while (obj) {
3015                         if (obj == object) {
3016                                 if (obj != entry->object.vm_object)
3017                                         vm_object_drop(obj);
3018                                 return 1;
3019                         }
3020                         while ((nobj = obj->backing_object) != NULL) {
3021                                 vm_object_hold(nobj);
3022                                 if (nobj == obj->backing_object)
3023                                         break;
3024                                 vm_object_drop(nobj);
3025                         }
3026                         if (obj != entry->object.vm_object) {
3027                                 if (nobj)
3028                                         vm_object_lock_swap();
3029                                 vm_object_drop(obj);
3030                         }
3031                         obj = nobj;
3032                 }
3033                 break;
3034         default:
3035                 break;
3036         }
3037         return 0;
3038 }
3039
3040 static int vm_object_in_map_callback(struct proc *p, void *data);
3041
3042 struct vm_object_in_map_info {
3043         vm_object_t object;
3044         int rv;
3045 };
3046
3047 /*
3048  * Debugging only
3049  */
3050 static int
3051 vm_object_in_map(vm_object_t object)
3052 {
3053         struct vm_object_in_map_info info;
3054
3055         info.rv = 0;
3056         info.object = object;
3057
3058         allproc_scan(vm_object_in_map_callback, &info, 0);
3059         if (info.rv)
3060                 return 1;
3061         if( _vm_object_in_map(&kernel_map, object, 0))
3062                 return 1;
3063         if( _vm_object_in_map(&pager_map, object, 0))
3064                 return 1;
3065         if( _vm_object_in_map(&buffer_map, object, 0))
3066                 return 1;
3067         return 0;
3068 }
3069
3070 /*
3071  * Debugging only
3072  */
3073 static int
3074 vm_object_in_map_callback(struct proc *p, void *data)
3075 {
3076         struct vm_object_in_map_info *info = data;
3077
3078         if (p->p_vmspace) {
3079                 if (_vm_object_in_map(&p->p_vmspace->vm_map, info->object, 0)) {
3080                         info->rv = 1;
3081                         return -1;
3082                 }
3083         }
3084         return (0);
3085 }
3086
3087 DB_SHOW_COMMAND(vmochk, vm_object_check)
3088 {
3089         struct vm_object_hash *hash;
3090         vm_object_t object;
3091         int n;
3092
3093         /*
3094          * make sure that internal objs are in a map somewhere
3095          * and none have zero ref counts.
3096          */
3097         for (n = 0; n < VMOBJ_HSIZE; ++n) {
3098                 hash = &vm_object_hash[n];
3099                 for (object = TAILQ_FIRST(&hash->list);
3100                                 object != NULL;
3101                                 object = TAILQ_NEXT(object, object_list)) {
3102                         if (object->type == OBJT_MARKER)
3103                                 continue;
3104                         if (object->handle != NULL ||
3105                             (object->type != OBJT_DEFAULT &&
3106                              object->type != OBJT_SWAP)) {
3107                                 continue;
3108                         }
3109                         if (object->ref_count == 0) {
3110                                 db_printf("vmochk: internal obj has "
3111                                           "zero ref count: %ld\n",
3112                                           (long)object->size);
3113                         }
3114                         if (vm_object_in_map(object))
3115                                 continue;
3116                         db_printf("vmochk: internal obj is not in a map: "
3117                                   "ref: %d, size: %lu: 0x%lx, "
3118                                   "backing_object: %p\n",
3119                                   object->ref_count, (u_long)object->size,
3120                                   (u_long)object->size,
3121                                   (void *)object->backing_object);
3122                 }
3123         }
3124 }
3125
3126 /*
3127  * Debugging only
3128  */
3129 DB_SHOW_COMMAND(object, vm_object_print_static)
3130 {
3131         /* XXX convert args. */
3132         vm_object_t object = (vm_object_t)addr;
3133         boolean_t full = have_addr;
3134
3135         vm_page_t p;
3136
3137         /* XXX count is an (unused) arg.  Avoid shadowing it. */
3138 #define count   was_count
3139
3140         int count;
3141
3142         if (object == NULL)
3143                 return;
3144
3145         db_iprintf(
3146             "Object %p: type=%d, size=0x%lx, res=%ld, ref=%d, flags=0x%x\n",
3147             object, (int)object->type, (u_long)object->size,
3148             object->resident_page_count, object->ref_count, object->flags);
3149         /*
3150          * XXX no %qd in kernel.  Truncate object->backing_object_offset.
3151          */
3152         db_iprintf(" backing_object(%d)=(%p)+0x%lx\n",
3153             (object->backing_object ? object->backing_object->ref_count : 0),
3154             object->backing_object,
3155             (long)object->backing_object_offset);
3156
3157         if (!full)
3158                 return;
3159
3160         db_indent += 2;
3161         count = 0;
3162         RB_FOREACH(p, vm_page_rb_tree, &object->rb_memq) {
3163                 if (count == 0)
3164                         db_iprintf("memory:=");
3165                 else if (count == 6) {
3166                         db_printf("\n");
3167                         db_iprintf(" ...");
3168                         count = 0;
3169                 } else
3170                         db_printf(",");
3171                 count++;
3172
3173                 db_printf("(off=0x%lx,page=0x%lx)",
3174                     (u_long) p->pindex, (u_long) VM_PAGE_TO_PHYS(p));
3175         }
3176         if (count != 0)
3177                 db_printf("\n");
3178         db_indent -= 2;
3179 }
3180
3181 /* XXX. */
3182 #undef count
3183
3184 /*
3185  * XXX need this non-static entry for calling from vm_map_print.
3186  *
3187  * Debugging only
3188  */
3189 void
3190 vm_object_print(/* db_expr_t */ long addr,
3191                 boolean_t have_addr,
3192                 /* db_expr_t */ long count,
3193                 char *modif)
3194 {
3195         vm_object_print_static(addr, have_addr, count, modif);
3196 }
3197
3198 /*
3199  * Debugging only
3200  */
3201 DB_SHOW_COMMAND(vmopag, vm_object_print_pages)
3202 {
3203         struct vm_object_hash *hash;
3204         vm_object_t object;
3205         int nl = 0;
3206         int c;
3207         int n;
3208
3209         for (n = 0; n < VMOBJ_HSIZE; ++n) {
3210                 hash = &vm_object_hash[n];
3211                 for (object = TAILQ_FIRST(&hash->list);
3212                                 object != NULL;
3213                                 object = TAILQ_NEXT(object, object_list)) {
3214                         vm_pindex_t idx, fidx;
3215                         vm_pindex_t osize;
3216                         vm_paddr_t pa = -1, padiff;
3217                         int rcount;
3218                         vm_page_t m;
3219
3220                         if (object->type == OBJT_MARKER)
3221                                 continue;
3222                         db_printf("new object: %p\n", (void *)object);
3223                         if ( nl > 18) {
3224                                 c = cngetc();
3225                                 if (c != ' ')
3226                                         return;
3227                                 nl = 0;
3228                         }
3229                         nl++;
3230                         rcount = 0;
3231                         fidx = 0;
3232                         osize = object->size;
3233                         if (osize > 128)
3234                                 osize = 128;
3235                         for (idx = 0; idx < osize; idx++) {
3236                                 m = vm_page_lookup(object, idx);
3237                                 if (m == NULL) {
3238                                         if (rcount) {
3239                                                 db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
3240                                                         (long)fidx, rcount, (long)pa);
3241                                                 if ( nl > 18) {
3242                                                         c = cngetc();
3243                                                         if (c != ' ')
3244                                                                 return;
3245                                                         nl = 0;
3246                                                 }
3247                                                 nl++;
3248                                                 rcount = 0;
3249                                         }
3250                                         continue;
3251                                 }
3252
3253                                 if (rcount &&
3254                                         (VM_PAGE_TO_PHYS(m) == pa + rcount * PAGE_SIZE)) {
3255                                         ++rcount;
3256                                         continue;
3257                                 }
3258                                 if (rcount) {
3259                                         padiff = pa + rcount * PAGE_SIZE - VM_PAGE_TO_PHYS(m);
3260                                         padiff >>= PAGE_SHIFT;
3261                                         padiff &= PQ_L2_MASK;
3262                                         if (padiff == 0) {
3263                                                 pa = VM_PAGE_TO_PHYS(m) - rcount * PAGE_SIZE;
3264                                                 ++rcount;
3265                                                 continue;
3266                                         }
3267                                         db_printf(" index(%ld)run(%d)pa(0x%lx)",
3268                                                 (long)fidx, rcount, (long)pa);
3269                                         db_printf("pd(%ld)\n", (long)padiff);
3270                                         if ( nl > 18) {
3271                                                 c = cngetc();
3272                                                 if (c != ' ')
3273                                                         return;
3274                                                 nl = 0;
3275                                         }
3276                                         nl++;
3277                                 }
3278                                 fidx = idx;
3279                                 pa = VM_PAGE_TO_PHYS(m);
3280                                 rcount = 1;
3281                         }
3282                         if (rcount) {
3283                                 db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
3284                                         (long)fidx, rcount, (long)pa);
3285                                 if ( nl > 18) {
3286                                         c = cngetc();
3287                                         if (c != ' ')
3288                                                 return;
3289                                         nl = 0;
3290                                 }
3291                                 nl++;
3292                         }
3293                 }
3294         }
3295 }
3296 #endif /* DDB */