kernel - Another huge HUGE VM performance improvement for many-cores
[dragonfly.git] / sys / vm / vm_page.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      from: @(#)vm_page.c     7.4 (Berkeley) 5/7/91
35  * $FreeBSD: src/sys/vm/vm_page.c,v 1.147.2.18 2002/03/10 05:03:19 alc Exp $
36  */
37
38 /*
39  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40  * All rights reserved.
41  *
42  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
43  *
44  * Permission to use, copy, modify and distribute this software and
45  * its documentation is hereby granted, provided that both the copyright
46  * notice and this permission notice appear in all copies of the
47  * software, derivative works or modified versions, and any portions
48  * thereof, and that both notices appear in supporting documentation.
49  *
50  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
53  *
54  * Carnegie Mellon requests users of this software to return to
55  *
56  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
57  *  School of Computer Science
58  *  Carnegie Mellon University
59  *  Pittsburgh PA 15213-3890
60  *
61  * any improvements or extensions that they make and grant Carnegie the
62  * rights to redistribute these changes.
63  */
64 /*
65  * Resident memory management module.  The module manipulates 'VM pages'.
66  * A VM page is the core building block for memory management.
67  */
68
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/malloc.h>
72 #include <sys/proc.h>
73 #include <sys/vmmeter.h>
74 #include <sys/vnode.h>
75 #include <sys/kernel.h>
76
77 #include <vm/vm.h>
78 #include <vm/vm_param.h>
79 #include <sys/lock.h>
80 #include <vm/vm_kern.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/vm_extern.h>
88 #include <vm/swap_pager.h>
89
90 #include <machine/inttypes.h>
91 #include <machine/md_var.h>
92
93 #include <vm/vm_page2.h>
94 #include <sys/spinlock2.h>
95
96 #define VMACTION_HSIZE  256
97 #define VMACTION_HMASK  (VMACTION_HSIZE - 1)
98
99 static void vm_page_queue_init(void);
100 static void vm_page_free_wakeup(void);
101 static vm_page_t vm_page_select_cache(u_short pg_color);
102 static vm_page_t _vm_page_list_find2(int basequeue, int index);
103 static void _vm_page_deactivate_locked(vm_page_t m, int athead);
104
105 /*
106  * Array of tailq lists
107  */
108 __cachealign struct vpgqueues vm_page_queues[PQ_COUNT];
109
110 LIST_HEAD(vm_page_action_list, vm_page_action);
111 struct vm_page_action_list      action_list[VMACTION_HSIZE];
112 static volatile int vm_pages_waiting;
113
114
115 RB_GENERATE2(vm_page_rb_tree, vm_page, rb_entry, rb_vm_page_compare,
116              vm_pindex_t, pindex);
117
118 static void
119 vm_page_queue_init(void) 
120 {
121         int i;
122
123         for (i = 0; i < PQ_L2_SIZE; i++)
124                 vm_page_queues[PQ_FREE+i].cnt = &vmstats.v_free_count;
125         for (i = 0; i < PQ_L2_SIZE; i++)
126                 vm_page_queues[PQ_CACHE+i].cnt = &vmstats.v_cache_count;
127         for (i = 0; i < PQ_L2_SIZE; i++)
128                 vm_page_queues[PQ_INACTIVE+i].cnt = &vmstats.v_inactive_count;
129         for (i = 0; i < PQ_L2_SIZE; i++)
130                 vm_page_queues[PQ_ACTIVE+i].cnt = &vmstats.v_active_count;
131         for (i = 0; i < PQ_L2_SIZE; i++)
132                 vm_page_queues[PQ_HOLD+i].cnt = &vmstats.v_active_count;
133         /* PQ_NONE has no queue */
134
135         for (i = 0; i < PQ_COUNT; i++) {
136                 TAILQ_INIT(&vm_page_queues[i].pl);
137                 spin_init(&vm_page_queues[i].spin);
138         }
139
140         for (i = 0; i < VMACTION_HSIZE; i++)
141                 LIST_INIT(&action_list[i]);
142 }
143
144 /*
145  * note: place in initialized data section?  Is this necessary?
146  */
147 long first_page = 0;
148 int vm_page_array_size = 0;
149 int vm_page_zero_count = 0;
150 vm_page_t vm_page_array = 0;
151
152 /*
153  * (low level boot)
154  *
155  * Sets the page size, perhaps based upon the memory size.
156  * Must be called before any use of page-size dependent functions.
157  */
158 void
159 vm_set_page_size(void)
160 {
161         if (vmstats.v_page_size == 0)
162                 vmstats.v_page_size = PAGE_SIZE;
163         if (((vmstats.v_page_size - 1) & vmstats.v_page_size) != 0)
164                 panic("vm_set_page_size: page size not a power of two");
165 }
166
167 /*
168  * (low level boot)
169  *
170  * Add a new page to the freelist for use by the system.  New pages
171  * are added to both the head and tail of the associated free page
172  * queue in a bottom-up fashion, so both zero'd and non-zero'd page
173  * requests pull 'recent' adds (higher physical addresses) first.
174  *
175  * Must be called in a critical section.
176  */
177 static vm_page_t
178 vm_add_new_page(vm_paddr_t pa)
179 {
180         struct vpgqueues *vpq;
181         vm_page_t m;
182
183         m = PHYS_TO_VM_PAGE(pa);
184         m->phys_addr = pa;
185         m->flags = 0;
186         m->pc = (pa >> PAGE_SHIFT) & PQ_L2_MASK;
187 #ifdef SMP
188         /*
189          * Twist for cpu localization instead of page coloring.
190          */
191         m->pc ^= ((pa >> PAGE_SHIFT) / PQ_L2_SIZE) & PQ_L2_MASK;
192         m->pc ^= ((pa >> PAGE_SHIFT) / (PQ_L2_SIZE * PQ_L2_SIZE)) & PQ_L2_MASK;
193 #endif
194         m->queue = m->pc + PQ_FREE;
195         KKASSERT(m->dirty == 0);
196
197         atomic_add_int(&vmstats.v_page_count, 1);
198         atomic_add_int(&vmstats.v_free_count, 1);
199         vpq = &vm_page_queues[m->queue];
200         if (vpq->flipflop)
201                 TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
202         else
203                 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
204         vpq->flipflop = 1 - vpq->flipflop;
205         ++vpq->lcnt;
206
207         return (m);
208 }
209
210 /*
211  * (low level boot)
212  *
213  * Initializes the resident memory module.
214  *
215  * Preallocates memory for critical VM structures and arrays prior to
216  * kernel_map becoming available.
217  *
218  * Memory is allocated from (virtual2_start, virtual2_end) if available,
219  * otherwise memory is allocated from (virtual_start, virtual_end).
220  *
221  * On x86-64 (virtual_start, virtual_end) is only 2GB and may not be
222  * large enough to hold vm_page_array & other structures for machines with
223  * large amounts of ram, so we want to use virtual2* when available.
224  */
225 void
226 vm_page_startup(void)
227 {
228         vm_offset_t vaddr = virtual2_start ? virtual2_start : virtual_start;
229         vm_offset_t mapped;
230         vm_size_t npages;
231         vm_paddr_t page_range;
232         vm_paddr_t new_end;
233         int i;
234         vm_paddr_t pa;
235         int nblocks;
236         vm_paddr_t last_pa;
237         vm_paddr_t end;
238         vm_paddr_t biggestone, biggestsize;
239         vm_paddr_t total;
240
241         total = 0;
242         biggestsize = 0;
243         biggestone = 0;
244         nblocks = 0;
245         vaddr = round_page(vaddr);
246
247         for (i = 0; phys_avail[i + 1]; i += 2) {
248                 phys_avail[i] = round_page64(phys_avail[i]);
249                 phys_avail[i + 1] = trunc_page64(phys_avail[i + 1]);
250         }
251
252         for (i = 0; phys_avail[i + 1]; i += 2) {
253                 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
254
255                 if (size > biggestsize) {
256                         biggestone = i;
257                         biggestsize = size;
258                 }
259                 ++nblocks;
260                 total += size;
261         }
262
263         end = phys_avail[biggestone+1];
264         end = trunc_page(end);
265
266         /*
267          * Initialize the queue headers for the free queue, the active queue
268          * and the inactive queue.
269          */
270
271         vm_page_queue_init();
272
273 #if !defined(_KERNEL_VIRTUAL)
274         /*
275          * VKERNELs don't support minidumps and as such don't need
276          * vm_page_dump
277          *
278          * Allocate a bitmap to indicate that a random physical page
279          * needs to be included in a minidump.
280          *
281          * The amd64 port needs this to indicate which direct map pages
282          * need to be dumped, via calls to dump_add_page()/dump_drop_page().
283          *
284          * However, i386 still needs this workspace internally within the
285          * minidump code.  In theory, they are not needed on i386, but are
286          * included should the sf_buf code decide to use them.
287          */
288         page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE;
289         vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
290         end -= vm_page_dump_size;
291         vm_page_dump = (void *)pmap_map(&vaddr, end, end + vm_page_dump_size,
292             VM_PROT_READ | VM_PROT_WRITE);
293         bzero((void *)vm_page_dump, vm_page_dump_size);
294 #endif
295
296         /*
297          * Compute the number of pages of memory that will be available for
298          * use (taking into account the overhead of a page structure per
299          * page).
300          */
301         first_page = phys_avail[0] / PAGE_SIZE;
302         page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
303         npages = (total - (page_range * sizeof(struct vm_page))) / PAGE_SIZE;
304
305         /*
306          * Initialize the mem entry structures now, and put them in the free
307          * queue.
308          */
309         new_end = trunc_page(end - page_range * sizeof(struct vm_page));
310         mapped = pmap_map(&vaddr, new_end, end,
311             VM_PROT_READ | VM_PROT_WRITE);
312         vm_page_array = (vm_page_t)mapped;
313
314 #if defined(__x86_64__) && !defined(_KERNEL_VIRTUAL)
315         /*
316          * since pmap_map on amd64 returns stuff out of a direct-map region,
317          * we have to manually add these pages to the minidump tracking so
318          * that they can be dumped, including the vm_page_array.
319          */
320         for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
321                 dump_add_page(pa);
322 #endif
323
324         /*
325          * Clear all of the page structures
326          */
327         bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
328         vm_page_array_size = page_range;
329
330         /*
331          * Construct the free queue(s) in ascending order (by physical
332          * address) so that the first 16MB of physical memory is allocated
333          * last rather than first.  On large-memory machines, this avoids
334          * the exhaustion of low physical memory before isa_dmainit has run.
335          */
336         vmstats.v_page_count = 0;
337         vmstats.v_free_count = 0;
338         for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
339                 pa = phys_avail[i];
340                 if (i == biggestone)
341                         last_pa = new_end;
342                 else
343                         last_pa = phys_avail[i + 1];
344                 while (pa < last_pa && npages-- > 0) {
345                         vm_add_new_page(pa);
346                         pa += PAGE_SIZE;
347                 }
348         }
349         if (virtual2_start)
350                 virtual2_start = vaddr;
351         else
352                 virtual_start = vaddr;
353 }
354
355 /*
356  * Scan comparison function for Red-Black tree scans.  An inclusive
357  * (start,end) is expected.  Other fields are not used.
358  */
359 int
360 rb_vm_page_scancmp(struct vm_page *p, void *data)
361 {
362         struct rb_vm_page_scan_info *info = data;
363
364         if (p->pindex < info->start_pindex)
365                 return(-1);
366         if (p->pindex > info->end_pindex)
367                 return(1);
368         return(0);
369 }
370
371 int
372 rb_vm_page_compare(struct vm_page *p1, struct vm_page *p2)
373 {
374         if (p1->pindex < p2->pindex)
375                 return(-1);
376         if (p1->pindex > p2->pindex)
377                 return(1);
378         return(0);
379 }
380
381 /*
382  * Each page queue has its own spin lock, which is fairly optimal for
383  * allocating and freeing pages at least.
384  *
385  * The caller must hold the vm_page_spin_lock() before locking a vm_page's
386  * queue spinlock via this function.  Also note that m->queue cannot change
387  * unless both the page and queue are locked.
388  */
389 static __inline
390 void
391 _vm_page_queue_spin_lock(vm_page_t m)
392 {
393         u_short queue;
394
395         queue = m->queue;
396         if (queue != PQ_NONE) {
397                 spin_lock(&vm_page_queues[queue].spin);
398                 KKASSERT(queue == m->queue);
399         }
400 }
401
402 static __inline
403 void
404 _vm_page_queue_spin_unlock(vm_page_t m)
405 {
406         u_short queue;
407
408         queue = m->queue;
409         cpu_ccfence();
410         if (queue != PQ_NONE)
411                 spin_unlock(&vm_page_queues[queue].spin);
412 }
413
414 static __inline
415 void
416 _vm_page_queues_spin_lock(u_short queue)
417 {
418         cpu_ccfence();
419         if (queue != PQ_NONE)
420                 spin_lock(&vm_page_queues[queue].spin);
421 }
422
423
424 static __inline
425 void
426 _vm_page_queues_spin_unlock(u_short queue)
427 {
428         cpu_ccfence();
429         if (queue != PQ_NONE)
430                 spin_unlock(&vm_page_queues[queue].spin);
431 }
432
433 void
434 vm_page_queue_spin_lock(vm_page_t m)
435 {
436         _vm_page_queue_spin_lock(m);
437 }
438
439 void
440 vm_page_queues_spin_lock(u_short queue)
441 {
442         _vm_page_queues_spin_lock(queue);
443 }
444
445 void
446 vm_page_queue_spin_unlock(vm_page_t m)
447 {
448         _vm_page_queue_spin_unlock(m);
449 }
450
451 void
452 vm_page_queues_spin_unlock(u_short queue)
453 {
454         _vm_page_queues_spin_unlock(queue);
455 }
456
457 /*
458  * This locks the specified vm_page and its queue in the proper order
459  * (page first, then queue).  The queue may change so the caller must
460  * recheck on return.
461  */
462 static __inline
463 void
464 _vm_page_and_queue_spin_lock(vm_page_t m)
465 {
466         vm_page_spin_lock(m);
467         _vm_page_queue_spin_lock(m);
468 }
469
470 static __inline
471 void
472 _vm_page_and_queue_spin_unlock(vm_page_t m)
473 {
474         _vm_page_queues_spin_unlock(m->queue);
475         vm_page_spin_unlock(m);
476 }
477
478 void
479 vm_page_and_queue_spin_unlock(vm_page_t m)
480 {
481         _vm_page_and_queue_spin_unlock(m);
482 }
483
484 void
485 vm_page_and_queue_spin_lock(vm_page_t m)
486 {
487         _vm_page_and_queue_spin_lock(m);
488 }
489
490 /*
491  * Helper function removes vm_page from its current queue.
492  * Returns the base queue the page used to be on.
493  *
494  * The vm_page and the queue must be spinlocked.
495  * This function will unlock the queue but leave the page spinlocked.
496  */
497 static __inline u_short
498 _vm_page_rem_queue_spinlocked(vm_page_t m)
499 {
500         struct vpgqueues *pq;
501         u_short queue;
502
503         queue = m->queue;
504         if (queue != PQ_NONE) {
505                 pq = &vm_page_queues[queue];
506                 TAILQ_REMOVE(&pq->pl, m, pageq);
507                 atomic_add_int(pq->cnt, -1);
508                 pq->lcnt--;
509                 m->queue = PQ_NONE;
510                 vm_page_queues_spin_unlock(queue);
511                 if ((queue - m->pc) == PQ_FREE && (m->flags & PG_ZERO))
512                         atomic_subtract_int(&vm_page_zero_count, 1);
513                 if ((queue - m->pc) == PQ_CACHE || (queue - m->pc) == PQ_FREE)
514                         return (queue - m->pc);
515         }
516         return queue;
517 }
518
519 /*
520  * Helper function places the vm_page on the specified queue.
521  *
522  * The vm_page must be spinlocked.
523  * This function will return with both the page and the queue locked.
524  */
525 static __inline void
526 _vm_page_add_queue_spinlocked(vm_page_t m, u_short queue, int athead)
527 {
528         struct vpgqueues *pq;
529
530         KKASSERT(m->queue == PQ_NONE);
531
532         if (queue != PQ_NONE) {
533                 vm_page_queues_spin_lock(queue);
534                 pq = &vm_page_queues[queue];
535                 ++pq->lcnt;
536                 atomic_add_int(pq->cnt, 1);
537                 m->queue = queue;
538
539                 /*
540                  * Put zero'd pages on the end ( where we look for zero'd pages
541                  * first ) and non-zerod pages at the head.
542                  */
543                 if (queue - m->pc == PQ_FREE) {
544                         if (m->flags & PG_ZERO) {
545                                 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
546                                 atomic_add_int(&vm_page_zero_count, 1);
547                         } else {
548                                 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
549                         }
550                 } else if (athead) {
551                         TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
552                 } else {
553                         TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
554                 }
555                 /* leave the queue spinlocked */
556         }
557 }
558
559 /*
560  * Wait until page is no longer PG_BUSY or (if also_m_busy is TRUE)
561  * m->busy is zero.  Returns TRUE if it had to sleep, FALSE if we
562  * did not.  Only one sleep call will be made before returning.
563  *
564  * This function does NOT busy the page and on return the page is not
565  * guaranteed to be available.
566  */
567 void
568 vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg)
569 {
570         u_int32_t flags;
571
572         for (;;) {
573                 flags = m->flags;
574                 cpu_ccfence();
575
576                 if ((flags & PG_BUSY) == 0 &&
577                     (also_m_busy == 0 || (flags & PG_SBUSY) == 0)) {
578                         break;
579                 }
580                 tsleep_interlock(m, 0);
581                 if (atomic_cmpset_int(&m->flags, flags,
582                                       flags | PG_WANTED | PG_REFERENCED)) {
583                         tsleep(m, PINTERLOCKED, msg, 0);
584                         break;
585                 }
586         }
587 }
588
589 /*
590  * Wait until PG_BUSY can be set, then set it.  If also_m_busy is TRUE we
591  * also wait for m->busy to become 0 before setting PG_BUSY.
592  */
593 void
594 VM_PAGE_DEBUG_EXT(vm_page_busy_wait)(vm_page_t m,
595                                      int also_m_busy, const char *msg
596                                      VM_PAGE_DEBUG_ARGS)
597 {
598         u_int32_t flags;
599
600         for (;;) {
601                 flags = m->flags;
602                 cpu_ccfence();
603                 if (flags & PG_BUSY) {
604                         tsleep_interlock(m, 0);
605                         if (atomic_cmpset_int(&m->flags, flags,
606                                           flags | PG_WANTED | PG_REFERENCED)) {
607                                 tsleep(m, PINTERLOCKED, msg, 0);
608                         }
609                 } else if (also_m_busy && (flags & PG_SBUSY)) {
610                         tsleep_interlock(m, 0);
611                         if (atomic_cmpset_int(&m->flags, flags,
612                                           flags | PG_WANTED | PG_REFERENCED)) {
613                                 tsleep(m, PINTERLOCKED, msg, 0);
614                         }
615                 } else {
616                         if (atomic_cmpset_int(&m->flags, flags,
617                                               flags | PG_BUSY)) {
618 #ifdef VM_PAGE_DEBUG
619                                 m->busy_func = func;
620                                 m->busy_line = lineno;
621 #endif
622                                 break;
623                         }
624                 }
625         }
626 }
627
628 /*
629  * Attempt to set PG_BUSY.  If also_m_busy is TRUE we only succeed if m->busy
630  * is also 0.
631  *
632  * Returns non-zero on failure.
633  */
634 int
635 VM_PAGE_DEBUG_EXT(vm_page_busy_try)(vm_page_t m, int also_m_busy
636                                     VM_PAGE_DEBUG_ARGS)
637 {
638         u_int32_t flags;
639
640         for (;;) {
641                 flags = m->flags;
642                 cpu_ccfence();
643                 if (flags & PG_BUSY)
644                         return TRUE;
645                 if (also_m_busy && (flags & PG_SBUSY))
646                         return TRUE;
647                 if (atomic_cmpset_int(&m->flags, flags, flags | PG_BUSY)) {
648 #ifdef VM_PAGE_DEBUG
649                                 m->busy_func = func;
650                                 m->busy_line = lineno;
651 #endif
652                         return FALSE;
653                 }
654         }
655 }
656
657 /*
658  * Clear the PG_BUSY flag and return non-zero to indicate to the caller
659  * that a wakeup() should be performed.
660  *
661  * The vm_page must be spinlocked and will remain spinlocked on return.
662  * The related queue must NOT be spinlocked (which could deadlock us).
663  *
664  * (inline version)
665  */
666 static __inline
667 int
668 _vm_page_wakeup(vm_page_t m)
669 {
670         u_int32_t flags;
671
672         for (;;) {
673                 flags = m->flags;
674                 cpu_ccfence();
675                 if (atomic_cmpset_int(&m->flags, flags,
676                                       flags & ~(PG_BUSY | PG_WANTED))) {
677                         break;
678                 }
679         }
680         return(flags & PG_WANTED);
681 }
682
683 /*
684  * Clear the PG_BUSY flag and wakeup anyone waiting for the page.  This
685  * is typically the last call you make on a page before moving onto
686  * other things.
687  */
688 void
689 vm_page_wakeup(vm_page_t m)
690 {
691         KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
692         vm_page_spin_lock(m);
693         if (_vm_page_wakeup(m)) {
694                 vm_page_spin_unlock(m);
695                 wakeup(m);
696         } else {
697                 vm_page_spin_unlock(m);
698         }
699 }
700
701 /*
702  * Holding a page keeps it from being reused.  Other parts of the system
703  * can still disassociate the page from its current object and free it, or
704  * perform read or write I/O on it and/or otherwise manipulate the page,
705  * but if the page is held the VM system will leave the page and its data
706  * intact and not reuse the page for other purposes until the last hold
707  * reference is released.  (see vm_page_wire() if you want to prevent the
708  * page from being disassociated from its object too).
709  *
710  * The caller must still validate the contents of the page and, if necessary,
711  * wait for any pending I/O (e.g. vm_page_sleep_busy() loop) to complete
712  * before manipulating the page.
713  *
714  * XXX get vm_page_spin_lock() here and move FREE->HOLD if necessary
715  */
716 void
717 vm_page_hold(vm_page_t m)
718 {
719         vm_page_spin_lock(m);
720         atomic_add_int(&m->hold_count, 1);
721         if (m->queue - m->pc == PQ_FREE) {
722                 _vm_page_queue_spin_lock(m);
723                 _vm_page_rem_queue_spinlocked(m);
724                 _vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
725                 _vm_page_queue_spin_unlock(m);
726         }
727         vm_page_spin_unlock(m);
728 }
729
730 /*
731  * The opposite of vm_page_hold().  A page can be freed while being held,
732  * which places it on the PQ_HOLD queue.  If we are able to busy the page
733  * after the hold count drops to zero we will move the page to the
734  * appropriate PQ_FREE queue by calling vm_page_free_toq().
735  */
736 void
737 vm_page_unhold(vm_page_t m)
738 {
739         vm_page_spin_lock(m);
740         atomic_add_int(&m->hold_count, -1);
741         if (m->hold_count == 0 && m->queue - m->pc == PQ_HOLD) {
742                 _vm_page_queue_spin_lock(m);
743                 _vm_page_rem_queue_spinlocked(m);
744                 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 0);
745                 _vm_page_queue_spin_unlock(m);
746         }
747         vm_page_spin_unlock(m);
748 }
749
750 /*
751  * Inserts the given vm_page into the object and object list.
752  *
753  * The pagetables are not updated but will presumably fault the page
754  * in if necessary, or if a kernel page the caller will at some point
755  * enter the page into the kernel's pmap.  We are not allowed to block
756  * here so we *can't* do this anyway.
757  *
758  * This routine may not block.
759  * This routine must be called with the vm_object held.
760  * This routine must be called with a critical section held.
761  *
762  * This routine returns TRUE if the page was inserted into the object
763  * successfully, and FALSE if the page already exists in the object.
764  */
765 int
766 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
767 {
768         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
769         if (m->object != NULL)
770                 panic("vm_page_insert: already inserted");
771
772         object->generation++;
773
774         /*
775          * Record the object/offset pair in this page and add the
776          * pv_list_count of the page to the object.
777          *
778          * The vm_page spin lock is required for interactions with the pmap.
779          */
780         vm_page_spin_lock(m);
781         m->object = object;
782         m->pindex = pindex;
783         if (vm_page_rb_tree_RB_INSERT(&object->rb_memq, m)) {
784                 m->object = NULL;
785                 m->pindex = 0;
786                 vm_page_spin_unlock(m);
787                 return FALSE;
788         }
789         object->resident_page_count++;
790         /* atomic_add_int(&object->agg_pv_list_count, m->md.pv_list_count); */
791         vm_page_spin_unlock(m);
792
793         /*
794          * Since we are inserting a new and possibly dirty page,
795          * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
796          */
797         if ((m->valid & m->dirty) || (m->flags & PG_WRITEABLE))
798                 vm_object_set_writeable_dirty(object);
799
800         /*
801          * Checks for a swap assignment and sets PG_SWAPPED if appropriate.
802          */
803         swap_pager_page_inserted(m);
804         return TRUE;
805 }
806
807 /*
808  * Removes the given vm_page_t from the (object,index) table
809  *
810  * The underlying pmap entry (if any) is NOT removed here.
811  * This routine may not block.
812  *
813  * The page must be BUSY and will remain BUSY on return.
814  * No other requirements.
815  *
816  * NOTE: FreeBSD side effect was to unbusy the page on return.  We leave
817  *       it busy.
818  */
819 void
820 vm_page_remove(vm_page_t m)
821 {
822         vm_object_t object;
823
824         if (m->object == NULL) {
825                 return;
826         }
827
828         if ((m->flags & PG_BUSY) == 0)
829                 panic("vm_page_remove: page not busy");
830
831         object = m->object;
832
833         vm_object_hold(object);
834
835         /*
836          * Remove the page from the object and update the object.
837          *
838          * The vm_page spin lock is required for interactions with the pmap.
839          */
840         vm_page_spin_lock(m);
841         vm_page_rb_tree_RB_REMOVE(&object->rb_memq, m);
842         object->resident_page_count--;
843         /* atomic_add_int(&object->agg_pv_list_count, -m->md.pv_list_count); */
844         m->object = NULL;
845         vm_page_spin_unlock(m);
846
847         object->generation++;
848
849         vm_object_drop(object);
850 }
851
852 /*
853  * Locate and return the page at (object, pindex), or NULL if the
854  * page could not be found.
855  *
856  * The caller must hold the vm_object token.
857  */
858 vm_page_t
859 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
860 {
861         vm_page_t m;
862
863         /*
864          * Search the hash table for this object/offset pair
865          */
866         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
867         m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
868         KKASSERT(m == NULL || (m->object == object && m->pindex == pindex));
869         return(m);
870 }
871
872 vm_page_t
873 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_wait)(struct vm_object *object,
874                                             vm_pindex_t pindex,
875                                             int also_m_busy, const char *msg
876                                             VM_PAGE_DEBUG_ARGS)
877 {
878         u_int32_t flags;
879         vm_page_t m;
880
881         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
882         m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
883         while (m) {
884                 KKASSERT(m->object == object && m->pindex == pindex);
885                 flags = m->flags;
886                 cpu_ccfence();
887                 if (flags & PG_BUSY) {
888                         tsleep_interlock(m, 0);
889                         if (atomic_cmpset_int(&m->flags, flags,
890                                           flags | PG_WANTED | PG_REFERENCED)) {
891                                 tsleep(m, PINTERLOCKED, msg, 0);
892                                 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
893                                                               pindex);
894                         }
895                 } else if (also_m_busy && (flags & PG_SBUSY)) {
896                         tsleep_interlock(m, 0);
897                         if (atomic_cmpset_int(&m->flags, flags,
898                                           flags | PG_WANTED | PG_REFERENCED)) {
899                                 tsleep(m, PINTERLOCKED, msg, 0);
900                                 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
901                                                               pindex);
902                         }
903                 } else if (atomic_cmpset_int(&m->flags, flags,
904                                              flags | PG_BUSY)) {
905 #ifdef VM_PAGE_DEBUG
906                         m->busy_func = func;
907                         m->busy_line = lineno;
908 #endif
909                         break;
910                 }
911         }
912         return m;
913 }
914
915 /*
916  * Attempt to lookup and busy a page.
917  *
918  * Returns NULL if the page could not be found
919  *
920  * Returns a vm_page and error == TRUE if the page exists but could not
921  * be busied.
922  *
923  * Returns a vm_page and error == FALSE on success.
924  */
925 vm_page_t
926 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_try)(struct vm_object *object,
927                                            vm_pindex_t pindex,
928                                            int also_m_busy, int *errorp
929                                            VM_PAGE_DEBUG_ARGS)
930 {
931         u_int32_t flags;
932         vm_page_t m;
933
934         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
935         m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
936         *errorp = FALSE;
937         while (m) {
938                 KKASSERT(m->object == object && m->pindex == pindex);
939                 flags = m->flags;
940                 cpu_ccfence();
941                 if (flags & PG_BUSY) {
942                         *errorp = TRUE;
943                         break;
944                 }
945                 if (also_m_busy && (flags & PG_SBUSY)) {
946                         *errorp = TRUE;
947                         break;
948                 }
949                 if (atomic_cmpset_int(&m->flags, flags, flags | PG_BUSY)) {
950 #ifdef VM_PAGE_DEBUG
951                         m->busy_func = func;
952                         m->busy_line = lineno;
953 #endif
954                         break;
955                 }
956         }
957         return m;
958 }
959
960 /*
961  * Caller must hold the related vm_object
962  */
963 vm_page_t
964 vm_page_next(vm_page_t m)
965 {
966         vm_page_t next;
967
968         next = vm_page_rb_tree_RB_NEXT(m);
969         if (next && next->pindex != m->pindex + 1)
970                 next = NULL;
971         return (next);
972 }
973
974 /*
975  * vm_page_rename()
976  *
977  * Move the given vm_page from its current object to the specified
978  * target object/offset.  The page must be busy and will remain so
979  * on return.
980  *
981  * new_object must be held.
982  * This routine might block. XXX ?
983  *
984  * NOTE: Swap associated with the page must be invalidated by the move.  We
985  *       have to do this for several reasons:  (1) we aren't freeing the
986  *       page, (2) we are dirtying the page, (3) the VM system is probably
987  *       moving the page from object A to B, and will then later move
988  *       the backing store from A to B and we can't have a conflict.
989  *
990  * NOTE: We *always* dirty the page.  It is necessary both for the
991  *       fact that we moved it, and because we may be invalidating
992  *       swap.  If the page is on the cache, we have to deactivate it
993  *       or vm_page_dirty() will panic.  Dirty pages are not allowed
994  *       on the cache.
995  */
996 void
997 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
998 {
999         KKASSERT(m->flags & PG_BUSY);
1000         ASSERT_LWKT_TOKEN_HELD(vm_object_token(new_object));
1001         if (m->object) {
1002                 ASSERT_LWKT_TOKEN_HELD(vm_object_token(m->object));
1003                 vm_page_remove(m);
1004         }
1005         if (vm_page_insert(m, new_object, new_pindex) == FALSE) {
1006                 panic("vm_page_rename: target exists (%p,%"PRIu64")",
1007                       new_object, new_pindex);
1008         }
1009         if (m->queue - m->pc == PQ_CACHE)
1010                 vm_page_deactivate(m);
1011         vm_page_dirty(m);
1012 }
1013
1014 /*
1015  * vm_page_unqueue() without any wakeup.  This routine is used when a page
1016  * is being moved between queues or otherwise is to remain BUSYied by the
1017  * caller.
1018  *
1019  * This routine may not block.
1020  */
1021 void
1022 vm_page_unqueue_nowakeup(vm_page_t m)
1023 {
1024         vm_page_and_queue_spin_lock(m);
1025         (void)_vm_page_rem_queue_spinlocked(m);
1026         vm_page_spin_unlock(m);
1027 }
1028
1029 /*
1030  * vm_page_unqueue() - Remove a page from its queue, wakeup the pagedemon
1031  * if necessary.
1032  *
1033  * This routine may not block.
1034  */
1035 void
1036 vm_page_unqueue(vm_page_t m)
1037 {
1038         u_short queue;
1039
1040         vm_page_and_queue_spin_lock(m);
1041         queue = _vm_page_rem_queue_spinlocked(m);
1042         if (queue == PQ_FREE || queue == PQ_CACHE) {
1043                 vm_page_spin_unlock(m);
1044                 pagedaemon_wakeup();
1045         } else {
1046                 vm_page_spin_unlock(m);
1047         }
1048 }
1049
1050 /*
1051  * vm_page_list_find()
1052  *
1053  * Find a page on the specified queue with color optimization.
1054  *
1055  * The page coloring optimization attempts to locate a page that does
1056  * not overload other nearby pages in the object in the cpu's L1 or L2
1057  * caches.  We need this optimization because cpu caches tend to be
1058  * physical caches, while object spaces tend to be virtual.
1059  *
1060  * On MP systems each PQ_FREE and PQ_CACHE color queue has its own spinlock
1061  * and the algorithm is adjusted to localize allocations on a per-core basis.
1062  * This is done by 'twisting' the colors.
1063  *
1064  * The page is returned spinlocked and removed from its queue (it will
1065  * be on PQ_NONE), or NULL. The page is not PG_BUSY'd.  The caller
1066  * is responsible for dealing with the busy-page case (usually by
1067  * deactivating the page and looping).
1068  *
1069  * NOTE:  This routine is carefully inlined.  A non-inlined version
1070  *        is available for outside callers but the only critical path is
1071  *        from within this source file.
1072  *
1073  * NOTE:  This routine assumes that the vm_pages found in PQ_CACHE and PQ_FREE
1074  *        represent stable storage, allowing us to order our locks vm_page
1075  *        first, then queue.
1076  */
1077 static __inline
1078 vm_page_t
1079 _vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
1080 {
1081         vm_page_t m;
1082
1083         for (;;) {
1084                 if (prefer_zero)
1085                         m = TAILQ_LAST(&vm_page_queues[basequeue+index].pl, pglist);
1086                 else
1087                         m = TAILQ_FIRST(&vm_page_queues[basequeue+index].pl);
1088                 if (m == NULL) {
1089                         m = _vm_page_list_find2(basequeue, index);
1090                         return(m);
1091                 }
1092                 vm_page_and_queue_spin_lock(m);
1093                 if (m->queue == basequeue + index) {
1094                         _vm_page_rem_queue_spinlocked(m);
1095                         /* vm_page_t spin held, no queue spin */
1096                         break;
1097                 }
1098                 vm_page_and_queue_spin_unlock(m);
1099         }
1100         return(m);
1101 }
1102
1103 static vm_page_t
1104 _vm_page_list_find2(int basequeue, int index)
1105 {
1106         int i;
1107         vm_page_t m = NULL;
1108         struct vpgqueues *pq;
1109
1110         pq = &vm_page_queues[basequeue];
1111
1112         /*
1113          * Note that for the first loop, index+i and index-i wind up at the
1114          * same place.  Even though this is not totally optimal, we've already
1115          * blown it by missing the cache case so we do not care.
1116          */
1117         for (i = PQ_L2_SIZE / 2; i > 0; --i) {
1118                 for (;;) {
1119                         m = TAILQ_FIRST(&pq[(index + i) & PQ_L2_MASK].pl);
1120                         if (m) {
1121                                 _vm_page_and_queue_spin_lock(m);
1122                                 if (m->queue ==
1123                                     basequeue + ((index + i) & PQ_L2_MASK)) {
1124                                         _vm_page_rem_queue_spinlocked(m);
1125                                         return(m);
1126                                 }
1127                                 _vm_page_and_queue_spin_unlock(m);
1128                                 continue;
1129                         }
1130                         m = TAILQ_FIRST(&pq[(index - i) & PQ_L2_MASK].pl);
1131                         if (m) {
1132                                 _vm_page_and_queue_spin_lock(m);
1133                                 if (m->queue ==
1134                                     basequeue + ((index - i) & PQ_L2_MASK)) {
1135                                         _vm_page_rem_queue_spinlocked(m);
1136                                         return(m);
1137                                 }
1138                                 _vm_page_and_queue_spin_unlock(m);
1139                                 continue;
1140                         }
1141                         break;  /* next i */
1142                 }
1143         }
1144         return(m);
1145 }
1146
1147 /*
1148  * Returns a vm_page candidate for allocation.  The page is not busied so
1149  * it can move around.  The caller must busy the page (and typically
1150  * deactivate it if it cannot be busied!)
1151  *
1152  * Returns a spinlocked vm_page that has been removed from its queue.
1153  */
1154 vm_page_t
1155 vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
1156 {
1157         return(_vm_page_list_find(basequeue, index, prefer_zero));
1158 }
1159
1160 /*
1161  * Find a page on the cache queue with color optimization, remove it
1162  * from the queue, and busy it.  The returned page will not be spinlocked.
1163  *
1164  * A candidate failure will be deactivated.  Candidates can fail due to
1165  * being busied by someone else, in which case they will be deactivated.
1166  *
1167  * This routine may not block.
1168  *
1169  */
1170 static vm_page_t
1171 vm_page_select_cache(u_short pg_color)
1172 {
1173         vm_page_t m;
1174
1175         for (;;) {
1176                 m = _vm_page_list_find(PQ_CACHE, pg_color & PQ_L2_MASK, FALSE);
1177                 if (m == NULL)
1178                         break;
1179                 /*
1180                  * (m) has been removed from its queue and spinlocked
1181                  */
1182                 if (vm_page_busy_try(m, TRUE)) {
1183                         _vm_page_deactivate_locked(m, 0);
1184                         vm_page_spin_unlock(m);
1185 #ifdef INVARIANTS
1186                         kprintf("Warning: busy page %p found in cache\n", m);
1187 #endif
1188                 } else {
1189                         /*
1190                          * We successfully busied the page
1191                          */
1192                         if ((m->flags & PG_UNMANAGED) == 0 &&
1193                             m->hold_count == 0 &&
1194                             m->wire_count == 0) {
1195                                 vm_page_spin_unlock(m);
1196                                 pagedaemon_wakeup();
1197                                 return(m);
1198                         }
1199                         _vm_page_deactivate_locked(m, 0);
1200                         if (_vm_page_wakeup(m)) {
1201                                 vm_page_spin_unlock(m);
1202                                 wakeup(m);
1203                         } else {
1204                                 vm_page_spin_unlock(m);
1205                         }
1206                 }
1207         }
1208         return (m);
1209 }
1210
1211 /*
1212  * Find a free or zero page, with specified preference.  We attempt to
1213  * inline the nominal case and fall back to _vm_page_select_free() 
1214  * otherwise.  A busied page is removed from the queue and returned.
1215  *
1216  * This routine may not block.
1217  */
1218 static __inline vm_page_t
1219 vm_page_select_free(u_short pg_color, boolean_t prefer_zero)
1220 {
1221         vm_page_t m;
1222
1223         for (;;) {
1224                 m = _vm_page_list_find(PQ_FREE, pg_color & PQ_L2_MASK,
1225                                        prefer_zero);
1226                 if (m == NULL)
1227                         break;
1228                 if (vm_page_busy_try(m, TRUE)) {
1229                         _vm_page_deactivate_locked(m, 0);
1230                         vm_page_spin_unlock(m);
1231 #ifdef INVARIANTS
1232                         kprintf("Warning: busy page %p found in cache\n", m);
1233 #endif
1234                 } else {
1235                         KKASSERT((m->flags & PG_UNMANAGED) == 0);
1236                         KKASSERT(m->hold_count == 0);
1237                         KKASSERT(m->wire_count == 0);
1238                         vm_page_spin_unlock(m);
1239                         pagedaemon_wakeup();
1240
1241                         /* return busied and removed page */
1242                         return(m);
1243                 }
1244         }
1245         return(m);
1246 }
1247
1248 /*
1249  * vm_page_alloc()
1250  *
1251  * Allocate and return a memory cell associated with this VM object/offset
1252  * pair.  If object is NULL an unassociated page will be allocated.
1253  *
1254  * The returned page will be busied and removed from its queues.  This
1255  * routine can block and may return NULL if a race occurs and the page
1256  * is found to already exist at the specified (object, pindex).
1257  *
1258  *      VM_ALLOC_NORMAL         allow use of cache pages, nominal free drain
1259  *      VM_ALLOC_QUICK          like normal but cannot use cache
1260  *      VM_ALLOC_SYSTEM         greater free drain
1261  *      VM_ALLOC_INTERRUPT      allow free list to be completely drained
1262  *      VM_ALLOC_ZERO           advisory request for pre-zero'd page only
1263  *      VM_ALLOC_FORCE_ZERO     advisory request for pre-zero'd page only
1264  *      VM_ALLOC_NULL_OK        ok to return NULL on insertion collision
1265  *                              (see vm_page_grab())
1266  * The object must be held if not NULL
1267  * This routine may not block
1268  *
1269  * Additional special handling is required when called from an interrupt
1270  * (VM_ALLOC_INTERRUPT).  We are not allowed to mess with the page cache
1271  * in this case.
1272  */
1273 vm_page_t
1274 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
1275 {
1276         vm_page_t m = NULL;
1277         u_short pg_color;
1278
1279 #ifdef SMP
1280         /*
1281          * Cpu twist - cpu localization algorithm
1282          */
1283         if (object) {
1284                 pg_color = mycpu->gd_cpuid + (pindex & ~ncpus_fit_mask) +
1285                            (object->pg_color & ~ncpus_fit_mask);
1286         } else {
1287                 pg_color = mycpu->gd_cpuid + (pindex & ~ncpus_fit_mask);
1288         }
1289 #else
1290         /*
1291          * Normal page coloring algorithm
1292          */
1293         if (object) {
1294                 pg_color = object->pg_color + pindex;
1295         } else {
1296                 pg_color = pindex;
1297         }
1298 #endif
1299         KKASSERT(page_req & 
1300                 (VM_ALLOC_NORMAL|VM_ALLOC_QUICK|
1301                  VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
1302
1303         /*
1304          * Certain system threads (pageout daemon, buf_daemon's) are
1305          * allowed to eat deeper into the free page list.
1306          */
1307         if (curthread->td_flags & TDF_SYSTHREAD)
1308                 page_req |= VM_ALLOC_SYSTEM;
1309
1310 loop:
1311         if (vmstats.v_free_count > vmstats.v_free_reserved ||
1312             ((page_req & VM_ALLOC_INTERRUPT) && vmstats.v_free_count > 0) ||
1313             ((page_req & VM_ALLOC_SYSTEM) && vmstats.v_cache_count == 0 &&
1314                 vmstats.v_free_count > vmstats.v_interrupt_free_min)
1315         ) {
1316                 /*
1317                  * The free queue has sufficient free pages to take one out.
1318                  */
1319                 if (page_req & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO))
1320                         m = vm_page_select_free(pg_color, TRUE);
1321                 else
1322                         m = vm_page_select_free(pg_color, FALSE);
1323         } else if (page_req & VM_ALLOC_NORMAL) {
1324                 /*
1325                  * Allocatable from the cache (non-interrupt only).  On
1326                  * success, we must free the page and try again, thus
1327                  * ensuring that vmstats.v_*_free_min counters are replenished.
1328                  */
1329 #ifdef INVARIANTS
1330                 if (curthread->td_preempted) {
1331                         kprintf("vm_page_alloc(): warning, attempt to allocate"
1332                                 " cache page from preempting interrupt\n");
1333                         m = NULL;
1334                 } else {
1335                         m = vm_page_select_cache(pg_color);
1336                 }
1337 #else
1338                 m = vm_page_select_cache(pg_color);
1339 #endif
1340                 /*
1341                  * On success move the page into the free queue and loop.
1342                  */
1343                 if (m != NULL) {
1344                         KASSERT(m->dirty == 0,
1345                                 ("Found dirty cache page %p", m));
1346                         vm_page_protect(m, VM_PROT_NONE);
1347                         vm_page_free(m);
1348                         goto loop;
1349                 }
1350
1351                 /*
1352                  * On failure return NULL
1353                  */
1354 #if defined(DIAGNOSTIC)
1355                 if (vmstats.v_cache_count > 0)
1356                         kprintf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", vmstats.v_cache_count);
1357 #endif
1358                 vm_pageout_deficit++;
1359                 pagedaemon_wakeup();
1360                 return (NULL);
1361         } else {
1362                 /*
1363                  * No pages available, wakeup the pageout daemon and give up.
1364                  */
1365                 vm_pageout_deficit++;
1366                 pagedaemon_wakeup();
1367                 return (NULL);
1368         }
1369
1370         /*
1371          * v_free_count can race so loop if we don't find the expected
1372          * page.
1373          */
1374         if (m == NULL)
1375                 goto loop;
1376
1377         /*
1378          * Good page found.  The page has already been busied for us and
1379          * removed from its queues.
1380          */
1381         KASSERT(m->dirty == 0,
1382                 ("vm_page_alloc: free/cache page %p was dirty", m));
1383         KKASSERT(m->queue == PQ_NONE);
1384
1385         /*
1386          * Initialize the structure, inheriting some flags but clearing
1387          * all the rest.  The page has already been busied for us.
1388          */
1389         vm_page_flag_clear(m, ~(PG_ZERO | PG_BUSY | PG_SBUSY));
1390         KKASSERT(m->wire_count == 0);
1391         KKASSERT(m->busy == 0);
1392         m->act_count = 0;
1393         m->valid = 0;
1394
1395         /*
1396          * Caller must be holding the object lock (asserted by
1397          * vm_page_insert()).
1398          *
1399          * NOTE: Inserting a page here does not insert it into any pmaps
1400          *       (which could cause us to block allocating memory).
1401          *
1402          * NOTE: If no object an unassociated page is allocated, m->pindex
1403          *       can be used by the caller for any purpose.
1404          */
1405         if (object) {
1406                 if (vm_page_insert(m, object, pindex) == FALSE) {
1407                         kprintf("PAGE RACE (%p:%d,%"PRIu64")\n",
1408                                 object, object->type, pindex);
1409                         vm_page_free(m);
1410                         m = NULL;
1411                         if ((page_req & VM_ALLOC_NULL_OK) == 0)
1412                                 panic("PAGE RACE");
1413                 }
1414         } else {
1415                 m->pindex = pindex;
1416         }
1417
1418         /*
1419          * Don't wakeup too often - wakeup the pageout daemon when
1420          * we would be nearly out of memory.
1421          */
1422         pagedaemon_wakeup();
1423
1424         /*
1425          * A PG_BUSY page is returned.
1426          */
1427         return (m);
1428 }
1429
1430 /*
1431  * Wait for sufficient free memory for nominal heavy memory use kernel
1432  * operations.
1433  */
1434 void
1435 vm_wait_nominal(void)
1436 {
1437         while (vm_page_count_min(0))
1438                 vm_wait(0);
1439 }
1440
1441 /*
1442  * Test if vm_wait_nominal() would block.
1443  */
1444 int
1445 vm_test_nominal(void)
1446 {
1447         if (vm_page_count_min(0))
1448                 return(1);
1449         return(0);
1450 }
1451
1452 /*
1453  * Block until free pages are available for allocation, called in various
1454  * places before memory allocations.
1455  *
1456  * The caller may loop if vm_page_count_min() == FALSE so we cannot be
1457  * more generous then that.
1458  */
1459 void
1460 vm_wait(int timo)
1461 {
1462         /*
1463          * never wait forever
1464          */
1465         if (timo == 0)
1466                 timo = hz;
1467         lwkt_gettoken(&vm_token);
1468
1469         if (curthread == pagethread) {
1470                 /*
1471                  * The pageout daemon itself needs pages, this is bad.
1472                  */
1473                 if (vm_page_count_min(0)) {
1474                         vm_pageout_pages_needed = 1;
1475                         tsleep(&vm_pageout_pages_needed, 0, "VMWait", timo);
1476                 }
1477         } else {
1478                 /*
1479                  * Wakeup the pageout daemon if necessary and wait.
1480                  */
1481                 if (vm_page_count_target()) {
1482                         if (vm_pages_needed == 0) {
1483                                 vm_pages_needed = 1;
1484                                 wakeup(&vm_pages_needed);
1485                         }
1486                         ++vm_pages_waiting;     /* SMP race ok */
1487                         tsleep(&vmstats.v_free_count, 0, "vmwait", timo);
1488                 }
1489         }
1490         lwkt_reltoken(&vm_token);
1491 }
1492
1493 /*
1494  * Block until free pages are available for allocation
1495  *
1496  * Called only from vm_fault so that processes page faulting can be
1497  * easily tracked.
1498  */
1499 void
1500 vm_waitpfault(void)
1501 {
1502         /*
1503          * Wakeup the pageout daemon if necessary and wait.
1504          */
1505         if (vm_page_count_target()) {
1506                 lwkt_gettoken(&vm_token);
1507                 if (vm_page_count_target()) {
1508                         if (vm_pages_needed == 0) {
1509                                 vm_pages_needed = 1;
1510                                 wakeup(&vm_pages_needed);
1511                         }
1512                         ++vm_pages_waiting;     /* SMP race ok */
1513                         tsleep(&vmstats.v_free_count, 0, "pfault", hz);
1514                 }
1515                 lwkt_reltoken(&vm_token);
1516         }
1517 }
1518
1519 /*
1520  * Put the specified page on the active list (if appropriate).  Ensure
1521  * that act_count is at least ACT_INIT but do not otherwise mess with it.
1522  *
1523  * The caller should be holding the page busied ? XXX
1524  * This routine may not block.
1525  */
1526 void
1527 vm_page_activate(vm_page_t m)
1528 {
1529         u_short oqueue;
1530
1531         vm_page_spin_lock(m);
1532         if (m->queue - m->pc != PQ_ACTIVE) {
1533                 _vm_page_queue_spin_lock(m);
1534                 oqueue = _vm_page_rem_queue_spinlocked(m);
1535                 /* page is left spinlocked, queue is unlocked */
1536
1537                 if (oqueue == PQ_CACHE)
1538                         mycpu->gd_cnt.v_reactivated++;
1539                 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1540                         if (m->act_count < ACT_INIT)
1541                                 m->act_count = ACT_INIT;
1542                         _vm_page_add_queue_spinlocked(m, PQ_ACTIVE + m->pc, 0);
1543                 }
1544                 _vm_page_and_queue_spin_unlock(m);
1545                 if (oqueue == PQ_CACHE || oqueue == PQ_FREE)
1546                         pagedaemon_wakeup();
1547         } else {
1548                 if (m->act_count < ACT_INIT)
1549                         m->act_count = ACT_INIT;
1550                 vm_page_spin_unlock(m);
1551         }
1552 }
1553
1554 /*
1555  * Helper routine for vm_page_free_toq() and vm_page_cache().  This
1556  * routine is called when a page has been added to the cache or free
1557  * queues.
1558  *
1559  * This routine may not block.
1560  */
1561 static __inline void
1562 vm_page_free_wakeup(void)
1563 {
1564         /*
1565          * If the pageout daemon itself needs pages, then tell it that
1566          * there are some free.
1567          */
1568         if (vm_pageout_pages_needed &&
1569             vmstats.v_cache_count + vmstats.v_free_count >= 
1570             vmstats.v_pageout_free_min
1571         ) {
1572                 wakeup(&vm_pageout_pages_needed);
1573                 vm_pageout_pages_needed = 0;
1574         }
1575
1576         /*
1577          * Wakeup processes that are waiting on memory.
1578          *
1579          * NOTE: vm_paging_target() is the pageout daemon's target, while
1580          *       vm_page_count_target() is somewhere inbetween.  We want
1581          *       to wake processes up prior to the pageout daemon reaching
1582          *       its target to provide some hysteresis.
1583          */
1584         if (vm_pages_waiting) {
1585                 if (!vm_page_count_target()) {
1586                         /*
1587                          * Plenty of pages are free, wakeup everyone.
1588                          */
1589                         vm_pages_waiting = 0;
1590                         wakeup(&vmstats.v_free_count);
1591                         ++mycpu->gd_cnt.v_ppwakeups;
1592                 } else if (!vm_page_count_min(0)) {
1593                         /*
1594                          * Some pages are free, wakeup someone.
1595                          */
1596                         int wcount = vm_pages_waiting;
1597                         if (wcount > 0)
1598                                 --wcount;
1599                         vm_pages_waiting = wcount;
1600                         wakeup_one(&vmstats.v_free_count);
1601                         ++mycpu->gd_cnt.v_ppwakeups;
1602                 }
1603         }
1604 }
1605
1606 /*
1607  * Returns the given page to the PQ_FREE or PQ_HOLD list and disassociates
1608  * it from its VM object.
1609  *
1610  * The vm_page must be PG_BUSY on entry.  PG_BUSY will be released on
1611  * return (the page will have been freed).
1612  */
1613 void
1614 vm_page_free_toq(vm_page_t m)
1615 {
1616         mycpu->gd_cnt.v_tfree++;
1617         KKASSERT((m->flags & PG_MAPPED) == 0);
1618         KKASSERT(m->flags & PG_BUSY);
1619
1620         if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
1621                 kprintf(
1622                 "vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1623                     (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1624                     m->hold_count);
1625                 if ((m->queue - m->pc) == PQ_FREE)
1626                         panic("vm_page_free: freeing free page");
1627                 else
1628                         panic("vm_page_free: freeing busy page");
1629         }
1630
1631         /*
1632          * Remove from object, spinlock the page and its queues and
1633          * remove from any queue.  No queue spinlock will be held
1634          * after this section (because the page was removed from any
1635          * queue).
1636          */
1637         vm_page_remove(m);
1638         vm_page_and_queue_spin_lock(m);
1639         _vm_page_rem_queue_spinlocked(m);
1640
1641         /*
1642          * No further management of fictitious pages occurs beyond object
1643          * and queue removal.
1644          */
1645         if ((m->flags & PG_FICTITIOUS) != 0) {
1646                 vm_page_spin_unlock(m);
1647                 vm_page_wakeup(m);
1648                 return;
1649         }
1650
1651         m->valid = 0;
1652         vm_page_undirty(m);
1653
1654         if (m->wire_count != 0) {
1655                 if (m->wire_count > 1) {
1656                     panic(
1657                         "vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1658                         m->wire_count, (long)m->pindex);
1659                 }
1660                 panic("vm_page_free: freeing wired page");
1661         }
1662
1663         /*
1664          * Clear the UNMANAGED flag when freeing an unmanaged page.
1665          */
1666         if (m->flags & PG_UNMANAGED) {
1667                 vm_page_flag_clear(m, PG_UNMANAGED);
1668         }
1669
1670         if (m->hold_count != 0) {
1671                 vm_page_flag_clear(m, PG_ZERO);
1672                 _vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
1673         } else {
1674                 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 0);
1675         }
1676
1677         /*
1678          * This sequence allows us to clear PG_BUSY while still holding
1679          * its spin lock, which reduces contention vs allocators.  We
1680          * must not leave the queue locked or _vm_page_wakeup() may
1681          * deadlock.
1682          */
1683         _vm_page_queue_spin_unlock(m);
1684         if (_vm_page_wakeup(m)) {
1685                 vm_page_spin_unlock(m);
1686                 wakeup(m);
1687         } else {
1688                 vm_page_spin_unlock(m);
1689         }
1690         vm_page_free_wakeup();
1691 }
1692
1693 /*
1694  * vm_page_free_fromq_fast()
1695  *
1696  * Remove a non-zero page from one of the free queues; the page is removed for
1697  * zeroing, so do not issue a wakeup.
1698  */
1699 vm_page_t
1700 vm_page_free_fromq_fast(void)
1701 {
1702         static int qi;
1703         vm_page_t m;
1704         int i;
1705
1706         for (i = 0; i < PQ_L2_SIZE; ++i) {
1707                 m = vm_page_list_find(PQ_FREE, qi, FALSE);
1708                 /* page is returned spinlocked and removed from its queue */
1709                 if (m) {
1710                         if (vm_page_busy_try(m, TRUE)) {
1711                                 /*
1712                                  * We were unable to busy the page, deactivate
1713                                  * it and loop.
1714                                  */
1715                                 _vm_page_deactivate_locked(m, 0);
1716                                 vm_page_spin_unlock(m);
1717                         } else if ((m->flags & PG_ZERO) == 0) {
1718                                 /*
1719                                  * The page is not PG_ZERO'd so return it.
1720                                  */
1721                                 vm_page_spin_unlock(m);
1722                                 break;
1723                         } else {
1724                                 /*
1725                                  * The page is PG_ZERO, requeue it and loop
1726                                  */
1727                                 _vm_page_add_queue_spinlocked(m,
1728                                                               PQ_FREE + m->pc,
1729                                                               0);
1730                                 vm_page_queue_spin_unlock(m);
1731                                 if (_vm_page_wakeup(m)) {
1732                                         vm_page_spin_unlock(m);
1733                                         wakeup(m);
1734                                 } else {
1735                                         vm_page_spin_unlock(m);
1736                                 }
1737                         }
1738                         m = NULL;
1739                 }
1740                 qi = (qi + PQ_PRIME2) & PQ_L2_MASK;
1741         }
1742         return (m);
1743 }
1744
1745 /*
1746  * vm_page_unmanage()
1747  *
1748  * Prevent PV management from being done on the page.  The page is
1749  * removed from the paging queues as if it were wired, and as a 
1750  * consequence of no longer being managed the pageout daemon will not
1751  * touch it (since there is no way to locate the pte mappings for the
1752  * page).  madvise() calls that mess with the pmap will also no longer
1753  * operate on the page.
1754  *
1755  * Beyond that the page is still reasonably 'normal'.  Freeing the page
1756  * will clear the flag.
1757  *
1758  * This routine is used by OBJT_PHYS objects - objects using unswappable
1759  * physical memory as backing store rather then swap-backed memory and
1760  * will eventually be extended to support 4MB unmanaged physical 
1761  * mappings.
1762  *
1763  * Caller must be holding the page busy.
1764  */
1765 void
1766 vm_page_unmanage(vm_page_t m)
1767 {
1768         KKASSERT(m->flags & PG_BUSY);
1769         if ((m->flags & PG_UNMANAGED) == 0) {
1770                 if (m->wire_count == 0)
1771                         vm_page_unqueue(m);
1772         }
1773         vm_page_flag_set(m, PG_UNMANAGED);
1774 }
1775
1776 /*
1777  * Mark this page as wired down by yet another map, removing it from
1778  * paging queues as necessary.
1779  *
1780  * Caller must be holding the page busy.
1781  */
1782 void
1783 vm_page_wire(vm_page_t m)
1784 {
1785         /*
1786          * Only bump the wire statistics if the page is not already wired,
1787          * and only unqueue the page if it is on some queue (if it is unmanaged
1788          * it is already off the queues).  Don't do anything with fictitious
1789          * pages because they are always wired.
1790          */
1791         KKASSERT(m->flags & PG_BUSY);
1792         if ((m->flags & PG_FICTITIOUS) == 0) {
1793                 if (atomic_fetchadd_int(&m->wire_count, 1) == 0) {
1794                         if ((m->flags & PG_UNMANAGED) == 0)
1795                                 vm_page_unqueue(m);
1796                         atomic_add_int(&vmstats.v_wire_count, 1);
1797                 }
1798                 KASSERT(m->wire_count != 0,
1799                         ("vm_page_wire: wire_count overflow m=%p", m));
1800         }
1801 }
1802
1803 /*
1804  * Release one wiring of this page, potentially enabling it to be paged again.
1805  *
1806  * Many pages placed on the inactive queue should actually go
1807  * into the cache, but it is difficult to figure out which.  What
1808  * we do instead, if the inactive target is well met, is to put
1809  * clean pages at the head of the inactive queue instead of the tail.
1810  * This will cause them to be moved to the cache more quickly and
1811  * if not actively re-referenced, freed more quickly.  If we just
1812  * stick these pages at the end of the inactive queue, heavy filesystem
1813  * meta-data accesses can cause an unnecessary paging load on memory bound 
1814  * processes.  This optimization causes one-time-use metadata to be
1815  * reused more quickly.
1816  *
1817  * BUT, if we are in a low-memory situation we have no choice but to
1818  * put clean pages on the cache queue.
1819  *
1820  * A number of routines use vm_page_unwire() to guarantee that the page
1821  * will go into either the inactive or active queues, and will NEVER
1822  * be placed in the cache - for example, just after dirtying a page.
1823  * dirty pages in the cache are not allowed.
1824  *
1825  * The page queues must be locked.
1826  * This routine may not block.
1827  */
1828 void
1829 vm_page_unwire(vm_page_t m, int activate)
1830 {
1831         KKASSERT(m->flags & PG_BUSY);
1832         if (m->flags & PG_FICTITIOUS) {
1833                 /* do nothing */
1834         } else if (m->wire_count <= 0) {
1835                 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1836         } else {
1837                 if (atomic_fetchadd_int(&m->wire_count, -1) == 1) {
1838                         atomic_add_int(&vmstats.v_wire_count, -1);
1839                         if (m->flags & PG_UNMANAGED) {
1840                                 ;
1841                         } else if (activate) {
1842                                 vm_page_spin_lock(m);
1843                                 _vm_page_add_queue_spinlocked(m,
1844                                                         PQ_ACTIVE + m->pc, 0);
1845                                 _vm_page_and_queue_spin_unlock(m);
1846                         } else {
1847                                 vm_page_spin_lock(m);
1848                                 vm_page_flag_clear(m, PG_WINATCFLS);
1849                                 _vm_page_add_queue_spinlocked(m,
1850                                                         PQ_INACTIVE + m->pc, 0);
1851                                 ++vm_swapcache_inactive_heuristic;
1852                                 _vm_page_and_queue_spin_unlock(m);
1853                         }
1854                 }
1855         }
1856 }
1857
1858 /*
1859  * Move the specified page to the inactive queue.  If the page has
1860  * any associated swap, the swap is deallocated.
1861  *
1862  * Normally athead is 0 resulting in LRU operation.  athead is set
1863  * to 1 if we want this page to be 'as if it were placed in the cache',
1864  * except without unmapping it from the process address space.
1865  *
1866  * vm_page's spinlock must be held on entry and will remain held on return.
1867  * This routine may not block.
1868  */
1869 static void
1870 _vm_page_deactivate_locked(vm_page_t m, int athead)
1871 {
1872         u_short oqueue;
1873
1874         /*
1875          * Ignore if already inactive.
1876          */
1877         if (m->queue - m->pc == PQ_INACTIVE)
1878                 return;
1879         _vm_page_queue_spin_lock(m);
1880         oqueue = _vm_page_rem_queue_spinlocked(m);
1881
1882         if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1883                 if (oqueue == PQ_CACHE)
1884                         mycpu->gd_cnt.v_reactivated++;
1885                 vm_page_flag_clear(m, PG_WINATCFLS);
1886                 _vm_page_add_queue_spinlocked(m, PQ_INACTIVE + m->pc, athead);
1887                 if (athead == 0)
1888                         ++vm_swapcache_inactive_heuristic;
1889         }
1890         _vm_page_queue_spin_unlock(m);
1891         /* leaves vm_page spinlocked */
1892 }
1893
1894 /*
1895  * Attempt to deactivate a page.
1896  *
1897  * No requirements.
1898  */
1899 void
1900 vm_page_deactivate(vm_page_t m)
1901 {
1902         vm_page_spin_lock(m);
1903         _vm_page_deactivate_locked(m, 0);
1904         vm_page_spin_unlock(m);
1905 }
1906
1907 void
1908 vm_page_deactivate_locked(vm_page_t m)
1909 {
1910         _vm_page_deactivate_locked(m, 0);
1911 }
1912
1913 /*
1914  * Attempt to move a page to PQ_CACHE.
1915  *
1916  * Returns 0 on failure, 1 on success
1917  *
1918  * The page should NOT be busied by the caller.  This function will validate
1919  * whether the page can be safely moved to the cache.
1920  */
1921 int
1922 vm_page_try_to_cache(vm_page_t m)
1923 {
1924         vm_page_spin_lock(m);
1925         if (vm_page_busy_try(m, TRUE)) {
1926                 vm_page_spin_unlock(m);
1927                 return(0);
1928         }
1929         if (m->dirty || m->hold_count || m->wire_count ||
1930             (m->flags & PG_UNMANAGED)) {
1931                 if (_vm_page_wakeup(m)) {
1932                         vm_page_spin_unlock(m);
1933                         wakeup(m);
1934                 } else {
1935                         vm_page_spin_unlock(m);
1936                 }
1937                 return(0);
1938         }
1939         vm_page_spin_unlock(m);
1940
1941         /*
1942          * Page busied by us and no longer spinlocked.  Dirty pages cannot
1943          * be moved to the cache.
1944          */
1945         vm_page_test_dirty(m);
1946         if (m->dirty) {
1947                 vm_page_wakeup(m);
1948                 return(0);
1949         }
1950         vm_page_cache(m);
1951         return(1);
1952 }
1953
1954 /*
1955  * Attempt to free the page.  If we cannot free it, we do nothing.
1956  * 1 is returned on success, 0 on failure.
1957  *
1958  * No requirements.
1959  */
1960 int
1961 vm_page_try_to_free(vm_page_t m)
1962 {
1963         vm_page_spin_lock(m);
1964         if (vm_page_busy_try(m, TRUE)) {
1965                 vm_page_spin_unlock(m);
1966                 return(0);
1967         }
1968         if (m->dirty || m->hold_count || m->wire_count ||
1969             (m->flags & PG_UNMANAGED)) {
1970                 if (_vm_page_wakeup(m)) {
1971                         vm_page_spin_unlock(m);
1972                         wakeup(m);
1973                 } else {
1974                         vm_page_spin_unlock(m);
1975                 }
1976                 return(0);
1977         }
1978         vm_page_spin_unlock(m);
1979
1980         /*
1981          * Page busied by us and no longer spinlocked.  Dirty pages will
1982          * not be freed by this function.    We have to re-test the
1983          * dirty bit after cleaning out the pmaps.
1984          */
1985         vm_page_test_dirty(m);
1986         if (m->dirty) {
1987                 vm_page_wakeup(m);
1988                 return(0);
1989         }
1990         vm_page_protect(m, VM_PROT_NONE);
1991         if (m->dirty) {
1992                 vm_page_wakeup(m);
1993                 return(0);
1994         }
1995         vm_page_free(m);
1996         return(1);
1997 }
1998
1999 /*
2000  * vm_page_cache
2001  *
2002  * Put the specified page onto the page cache queue (if appropriate).
2003  *
2004  * The page must be busy, and this routine will release the busy and
2005  * possibly even free the page.
2006  */
2007 void
2008 vm_page_cache(vm_page_t m)
2009 {
2010         if ((m->flags & PG_UNMANAGED) || m->busy ||
2011             m->wire_count || m->hold_count) {
2012                 kprintf("vm_page_cache: attempting to cache busy/held page\n");
2013                 vm_page_wakeup(m);
2014                 return;
2015         }
2016
2017         /*
2018          * Already in the cache (and thus not mapped)
2019          */
2020         if ((m->queue - m->pc) == PQ_CACHE) {
2021                 KKASSERT((m->flags & PG_MAPPED) == 0);
2022                 vm_page_wakeup(m);
2023                 return;
2024         }
2025
2026         /*
2027          * Caller is required to test m->dirty, but note that the act of
2028          * removing the page from its maps can cause it to become dirty
2029          * on an SMP system due to another cpu running in usermode.
2030          */
2031         if (m->dirty) {
2032                 panic("vm_page_cache: caching a dirty page, pindex: %ld",
2033                         (long)m->pindex);
2034         }
2035
2036         /*
2037          * Remove all pmaps and indicate that the page is not
2038          * writeable or mapped.  Our vm_page_protect() call may
2039          * have blocked (especially w/ VM_PROT_NONE), so recheck
2040          * everything.
2041          */
2042         vm_page_protect(m, VM_PROT_NONE);
2043         if ((m->flags & (PG_UNMANAGED|PG_MAPPED)) || m->busy ||
2044                         m->wire_count || m->hold_count) {
2045                 vm_page_wakeup(m);
2046         } else if (m->dirty) {
2047                 vm_page_deactivate(m);
2048                 vm_page_wakeup(m);
2049         } else {
2050                 _vm_page_and_queue_spin_lock(m);
2051                 _vm_page_rem_queue_spinlocked(m);
2052                 _vm_page_add_queue_spinlocked(m, PQ_CACHE + m->pc, 0);
2053                 _vm_page_queue_spin_unlock(m);
2054                 if (_vm_page_wakeup(m)) {
2055                         vm_page_spin_unlock(m);
2056                         wakeup(m);
2057                 } else {
2058                         vm_page_spin_unlock(m);
2059                 }
2060                 vm_page_free_wakeup();
2061         }
2062 }
2063
2064 /*
2065  * vm_page_dontneed()
2066  *
2067  * Cache, deactivate, or do nothing as appropriate.  This routine
2068  * is typically used by madvise() MADV_DONTNEED.
2069  *
2070  * Generally speaking we want to move the page into the cache so
2071  * it gets reused quickly.  However, this can result in a silly syndrome
2072  * due to the page recycling too quickly.  Small objects will not be
2073  * fully cached.  On the otherhand, if we move the page to the inactive
2074  * queue we wind up with a problem whereby very large objects 
2075  * unnecessarily blow away our inactive and cache queues.
2076  *
2077  * The solution is to move the pages based on a fixed weighting.  We
2078  * either leave them alone, deactivate them, or move them to the cache,
2079  * where moving them to the cache has the highest weighting.
2080  * By forcing some pages into other queues we eventually force the
2081  * system to balance the queues, potentially recovering other unrelated
2082  * space from active.  The idea is to not force this to happen too
2083  * often.
2084  *
2085  * The page must be busied.
2086  */
2087 void
2088 vm_page_dontneed(vm_page_t m)
2089 {
2090         static int dnweight;
2091         int dnw;
2092         int head;
2093
2094         dnw = ++dnweight;
2095
2096         /*
2097          * occassionally leave the page alone
2098          */
2099         if ((dnw & 0x01F0) == 0 ||
2100             m->queue - m->pc == PQ_INACTIVE ||
2101             m->queue - m->pc == PQ_CACHE
2102         ) {
2103                 if (m->act_count >= ACT_INIT)
2104                         --m->act_count;
2105                 return;
2106         }
2107
2108         /*
2109          * If vm_page_dontneed() is inactivating a page, it must clear
2110          * the referenced flag; otherwise the pagedaemon will see references
2111          * on the page in the inactive queue and reactivate it. Until the 
2112          * page can move to the cache queue, madvise's job is not done.
2113          */
2114         vm_page_flag_clear(m, PG_REFERENCED);
2115         pmap_clear_reference(m);
2116
2117         if (m->dirty == 0)
2118                 vm_page_test_dirty(m);
2119
2120         if (m->dirty || (dnw & 0x0070) == 0) {
2121                 /*
2122                  * Deactivate the page 3 times out of 32.
2123                  */
2124                 head = 0;
2125         } else {
2126                 /*
2127                  * Cache the page 28 times out of every 32.  Note that
2128                  * the page is deactivated instead of cached, but placed
2129                  * at the head of the queue instead of the tail.
2130                  */
2131                 head = 1;
2132         }
2133         vm_page_spin_lock(m);
2134         _vm_page_deactivate_locked(m, head);
2135         vm_page_spin_unlock(m);
2136 }
2137
2138 /*
2139  * These routines manipulate the 'soft busy' count for a page.  A soft busy
2140  * is almost like PG_BUSY except that it allows certain compatible operations
2141  * to occur on the page while it is busy.  For example, a page undergoing a
2142  * write can still be mapped read-only.
2143  *
2144  * Because vm_pages can overlap buffers m->busy can be > 1.  m->busy is only
2145  * adjusted while the vm_page is PG_BUSY so the flash will occur when the
2146  * busy bit is cleared.
2147  */
2148 void
2149 vm_page_io_start(vm_page_t m)
2150 {
2151         KASSERT(m->flags & PG_BUSY, ("vm_page_io_start: page not busy!!!"));
2152         atomic_add_char(&m->busy, 1);
2153         vm_page_flag_set(m, PG_SBUSY);
2154 }
2155
2156 void
2157 vm_page_io_finish(vm_page_t m)
2158 {
2159         KASSERT(m->flags & PG_BUSY, ("vm_page_io_finish: page not busy!!!"));
2160         atomic_subtract_char(&m->busy, 1);
2161         if (m->busy == 0)
2162                 vm_page_flag_clear(m, PG_SBUSY);
2163 }
2164
2165 /*
2166  * Grab a page, blocking if it is busy and allocating a page if necessary.
2167  * A busy page is returned or NULL.  The page may or may not be valid and
2168  * might not be on a queue (the caller is responsible for the disposition of
2169  * the page).
2170  *
2171  * If VM_ALLOC_ZERO is specified and the grab must allocate a new page, the
2172  * page will be zero'd and marked valid.
2173  *
2174  * If VM_ALLOC_FORCE_ZERO is specified the page will be zero'd and marked
2175  * valid even if it already exists.
2176  *
2177  * If VM_ALLOC_RETRY is specified this routine will never return NULL.  Also
2178  * note that VM_ALLOC_NORMAL must be specified if VM_ALLOC_RETRY is specified.
2179  *
2180  * This routine may block, but if VM_ALLOC_RETRY is not set then NULL is
2181  * always returned if we had blocked.  
2182  *
2183  * This routine may not be called from an interrupt.
2184  *
2185  * PG_ZERO is *ALWAYS* cleared by this routine.
2186  *
2187  * No other requirements.
2188  */
2189 vm_page_t
2190 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2191 {
2192         vm_page_t m;
2193         int error;
2194
2195         KKASSERT(allocflags &
2196                 (VM_ALLOC_NORMAL|VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
2197         vm_object_hold(object);
2198         for (;;) {
2199                 m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
2200                 if (error) {
2201                         vm_page_sleep_busy(m, TRUE, "pgrbwt");
2202                         if ((allocflags & VM_ALLOC_RETRY) == 0) {
2203                                 m = NULL;
2204                                 break;
2205                         }
2206                         /* retry */
2207                 } else if (m == NULL) {
2208                         m = vm_page_alloc(object, pindex,
2209                                           allocflags & ~VM_ALLOC_RETRY);
2210                         if (m)
2211                                 break;
2212                         vm_wait(0);
2213                         if ((allocflags & VM_ALLOC_RETRY) == 0)
2214                                 goto failed;
2215                 } else {
2216                         /* m found */
2217                         break;
2218                 }
2219         }
2220
2221         /*
2222          * If VM_ALLOC_ZERO an invalid page will be zero'd and set valid.
2223          *
2224          * If VM_ALLOC_FORCE_ZERO the page is unconditionally zero'd and set
2225          * valid even if already valid.
2226          */
2227         if (m->valid == 0) {
2228                 if (allocflags & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO)) {
2229                         if ((m->flags & PG_ZERO) == 0)
2230                                 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2231                         m->valid = VM_PAGE_BITS_ALL;
2232                 }
2233         } else if (allocflags & VM_ALLOC_FORCE_ZERO) {
2234                 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2235                 m->valid = VM_PAGE_BITS_ALL;
2236         }
2237         vm_page_flag_clear(m, PG_ZERO);
2238 failed:
2239         vm_object_drop(object);
2240         return(m);
2241 }
2242
2243 /*
2244  * Mapping function for valid bits or for dirty bits in
2245  * a page.  May not block.
2246  *
2247  * Inputs are required to range within a page.
2248  *
2249  * No requirements.
2250  * Non blocking.
2251  */
2252 int
2253 vm_page_bits(int base, int size)
2254 {
2255         int first_bit;
2256         int last_bit;
2257
2258         KASSERT(
2259             base + size <= PAGE_SIZE,
2260             ("vm_page_bits: illegal base/size %d/%d", base, size)
2261         );
2262
2263         if (size == 0)          /* handle degenerate case */
2264                 return(0);
2265
2266         first_bit = base >> DEV_BSHIFT;
2267         last_bit = (base + size - 1) >> DEV_BSHIFT;
2268
2269         return ((2 << last_bit) - (1 << first_bit));
2270 }
2271
2272 /*
2273  * Sets portions of a page valid and clean.  The arguments are expected
2274  * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2275  * of any partial chunks touched by the range.  The invalid portion of
2276  * such chunks will be zero'd.
2277  *
2278  * NOTE: When truncating a buffer vnode_pager_setsize() will automatically
2279  *       align base to DEV_BSIZE so as not to mark clean a partially
2280  *       truncated device block.  Otherwise the dirty page status might be
2281  *       lost.
2282  *
2283  * This routine may not block.
2284  *
2285  * (base + size) must be less then or equal to PAGE_SIZE.
2286  */
2287 static void
2288 _vm_page_zero_valid(vm_page_t m, int base, int size)
2289 {
2290         int frag;
2291         int endoff;
2292
2293         if (size == 0)  /* handle degenerate case */
2294                 return;
2295
2296         /*
2297          * If the base is not DEV_BSIZE aligned and the valid
2298          * bit is clear, we have to zero out a portion of the
2299          * first block.
2300          */
2301
2302         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2303             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
2304         ) {
2305                 pmap_zero_page_area(
2306                     VM_PAGE_TO_PHYS(m),
2307                     frag,
2308                     base - frag
2309                 );
2310         }
2311
2312         /*
2313          * If the ending offset is not DEV_BSIZE aligned and the 
2314          * valid bit is clear, we have to zero out a portion of
2315          * the last block.
2316          */
2317
2318         endoff = base + size;
2319
2320         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2321             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
2322         ) {
2323                 pmap_zero_page_area(
2324                     VM_PAGE_TO_PHYS(m),
2325                     endoff,
2326                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
2327                 );
2328         }
2329 }
2330
2331 /*
2332  * Set valid, clear dirty bits.  If validating the entire
2333  * page we can safely clear the pmap modify bit.  We also
2334  * use this opportunity to clear the PG_NOSYNC flag.  If a process
2335  * takes a write fault on a MAP_NOSYNC memory area the flag will
2336  * be set again.
2337  *
2338  * We set valid bits inclusive of any overlap, but we can only
2339  * clear dirty bits for DEV_BSIZE chunks that are fully within
2340  * the range.
2341  *
2342  * Page must be busied?
2343  * No other requirements.
2344  */
2345 void
2346 vm_page_set_valid(vm_page_t m, int base, int size)
2347 {
2348         _vm_page_zero_valid(m, base, size);
2349         m->valid |= vm_page_bits(base, size);
2350 }
2351
2352
2353 /*
2354  * Set valid bits and clear dirty bits.
2355  *
2356  * NOTE: This function does not clear the pmap modified bit.
2357  *       Also note that e.g. NFS may use a byte-granular base
2358  *       and size.
2359  *
2360  * WARNING: Page must be busied?  But vfs_clean_one_page() will call
2361  *          this without necessarily busying the page (via bdwrite()).
2362  *          So for now vm_token must also be held.
2363  *
2364  * No other requirements.
2365  */
2366 void
2367 vm_page_set_validclean(vm_page_t m, int base, int size)
2368 {
2369         int pagebits;
2370
2371         _vm_page_zero_valid(m, base, size);
2372         pagebits = vm_page_bits(base, size);
2373         m->valid |= pagebits;
2374         m->dirty &= ~pagebits;
2375         if (base == 0 && size == PAGE_SIZE) {
2376                 /*pmap_clear_modify(m);*/
2377                 vm_page_flag_clear(m, PG_NOSYNC);
2378         }
2379 }
2380
2381 /*
2382  * Set valid & dirty.  Used by buwrite()
2383  *
2384  * WARNING: Page must be busied?  But vfs_dirty_one_page() will
2385  *          call this function in buwrite() so for now vm_token must
2386  *          be held.
2387  *
2388  * No other requirements.
2389  */
2390 void
2391 vm_page_set_validdirty(vm_page_t m, int base, int size)
2392 {
2393         int pagebits;
2394
2395         pagebits = vm_page_bits(base, size);
2396         m->valid |= pagebits;
2397         m->dirty |= pagebits;
2398         if (m->object)
2399                 vm_object_set_writeable_dirty(m->object);
2400 }
2401
2402 /*
2403  * Clear dirty bits.
2404  *
2405  * NOTE: This function does not clear the pmap modified bit.
2406  *       Also note that e.g. NFS may use a byte-granular base
2407  *       and size.
2408  *
2409  * Page must be busied?
2410  * No other requirements.
2411  */
2412 void
2413 vm_page_clear_dirty(vm_page_t m, int base, int size)
2414 {
2415         m->dirty &= ~vm_page_bits(base, size);
2416         if (base == 0 && size == PAGE_SIZE) {
2417                 /*pmap_clear_modify(m);*/
2418                 vm_page_flag_clear(m, PG_NOSYNC);
2419         }
2420 }
2421
2422 /*
2423  * Make the page all-dirty.
2424  *
2425  * Also make sure the related object and vnode reflect the fact that the
2426  * object may now contain a dirty page.
2427  *
2428  * Page must be busied?
2429  * No other requirements.
2430  */
2431 void
2432 vm_page_dirty(vm_page_t m)
2433 {
2434 #ifdef INVARIANTS
2435         int pqtype = m->queue - m->pc;
2436 #endif
2437         KASSERT(pqtype != PQ_CACHE && pqtype != PQ_FREE,
2438                 ("vm_page_dirty: page in free/cache queue!"));
2439         if (m->dirty != VM_PAGE_BITS_ALL) {
2440                 m->dirty = VM_PAGE_BITS_ALL;
2441                 if (m->object)
2442                         vm_object_set_writeable_dirty(m->object);
2443         }
2444 }
2445
2446 /*
2447  * Invalidates DEV_BSIZE'd chunks within a page.  Both the
2448  * valid and dirty bits for the effected areas are cleared.
2449  *
2450  * Page must be busied?
2451  * Does not block.
2452  * No other requirements.
2453  */
2454 void
2455 vm_page_set_invalid(vm_page_t m, int base, int size)
2456 {
2457         int bits;
2458
2459         bits = vm_page_bits(base, size);
2460         m->valid &= ~bits;
2461         m->dirty &= ~bits;
2462         m->object->generation++;
2463 }
2464
2465 /*
2466  * The kernel assumes that the invalid portions of a page contain 
2467  * garbage, but such pages can be mapped into memory by user code.
2468  * When this occurs, we must zero out the non-valid portions of the
2469  * page so user code sees what it expects.
2470  *
2471  * Pages are most often semi-valid when the end of a file is mapped 
2472  * into memory and the file's size is not page aligned.
2473  *
2474  * Page must be busied?
2475  * No other requirements.
2476  */
2477 void
2478 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
2479 {
2480         int b;
2481         int i;
2482
2483         /*
2484          * Scan the valid bits looking for invalid sections that
2485          * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
2486          * valid bit may be set ) have already been zerod by
2487          * vm_page_set_validclean().
2488          */
2489         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
2490                 if (i == (PAGE_SIZE / DEV_BSIZE) || 
2491                     (m->valid & (1 << i))
2492                 ) {
2493                         if (i > b) {
2494                                 pmap_zero_page_area(
2495                                     VM_PAGE_TO_PHYS(m), 
2496                                     b << DEV_BSHIFT,
2497                                     (i - b) << DEV_BSHIFT
2498                                 );
2499                         }
2500                         b = i + 1;
2501                 }
2502         }
2503
2504         /*
2505          * setvalid is TRUE when we can safely set the zero'd areas
2506          * as being valid.  We can do this if there are no cache consistency
2507          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
2508          */
2509         if (setvalid)
2510                 m->valid = VM_PAGE_BITS_ALL;
2511 }
2512
2513 /*
2514  * Is a (partial) page valid?  Note that the case where size == 0
2515  * will return FALSE in the degenerate case where the page is entirely
2516  * invalid, and TRUE otherwise.
2517  *
2518  * Does not block.
2519  * No other requirements.
2520  */
2521 int
2522 vm_page_is_valid(vm_page_t m, int base, int size)
2523 {
2524         int bits = vm_page_bits(base, size);
2525
2526         if (m->valid && ((m->valid & bits) == bits))
2527                 return 1;
2528         else
2529                 return 0;
2530 }
2531
2532 /*
2533  * update dirty bits from pmap/mmu.  May not block.
2534  *
2535  * Caller must hold the page busy
2536  */
2537 void
2538 vm_page_test_dirty(vm_page_t m)
2539 {
2540         if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
2541                 vm_page_dirty(m);
2542         }
2543 }
2544
2545 /*
2546  * Register an action, associating it with its vm_page
2547  */
2548 void
2549 vm_page_register_action(vm_page_action_t action, vm_page_event_t event)
2550 {
2551         struct vm_page_action_list *list;
2552         int hv;
2553
2554         hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
2555         list = &action_list[hv];
2556
2557         lwkt_gettoken(&vm_token);
2558         vm_page_flag_set(action->m, PG_ACTIONLIST);
2559         action->event = event;
2560         LIST_INSERT_HEAD(list, action, entry);
2561         lwkt_reltoken(&vm_token);
2562 }
2563
2564 /*
2565  * Unregister an action, disassociating it from its related vm_page
2566  */
2567 void
2568 vm_page_unregister_action(vm_page_action_t action)
2569 {
2570         struct vm_page_action_list *list;
2571         int hv;
2572
2573         lwkt_gettoken(&vm_token);
2574         if (action->event != VMEVENT_NONE) {
2575                 action->event = VMEVENT_NONE;
2576                 LIST_REMOVE(action, entry);
2577
2578                 hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
2579                 list = &action_list[hv];
2580                 if (LIST_EMPTY(list))
2581                         vm_page_flag_clear(action->m, PG_ACTIONLIST);
2582         }
2583         lwkt_reltoken(&vm_token);
2584 }
2585
2586 /*
2587  * Issue an event on a VM page.  Corresponding action structures are
2588  * removed from the page's list and called.
2589  *
2590  * If the vm_page has no more pending action events we clear its
2591  * PG_ACTIONLIST flag.
2592  */
2593 void
2594 vm_page_event_internal(vm_page_t m, vm_page_event_t event)
2595 {
2596         struct vm_page_action_list *list;
2597         struct vm_page_action *scan;
2598         struct vm_page_action *next;
2599         int hv;
2600         int all;
2601
2602         hv = (int)((intptr_t)m >> 8) & VMACTION_HMASK;
2603         list = &action_list[hv];
2604         all = 1;
2605
2606         lwkt_gettoken(&vm_token);
2607         LIST_FOREACH_MUTABLE(scan, list, entry, next) {
2608                 if (scan->m == m) {
2609                         if (scan->event == event) {
2610                                 scan->event = VMEVENT_NONE;
2611                                 LIST_REMOVE(scan, entry);
2612                                 scan->func(m, scan);
2613                                 /* XXX */
2614                         } else {
2615                                 all = 0;
2616                         }
2617                 }
2618         }
2619         if (all)
2620                 vm_page_flag_clear(m, PG_ACTIONLIST);
2621         lwkt_reltoken(&vm_token);
2622 }
2623
2624 #include "opt_ddb.h"
2625 #ifdef DDB
2626 #include <sys/kernel.h>
2627
2628 #include <ddb/ddb.h>
2629
2630 DB_SHOW_COMMAND(page, vm_page_print_page_info)
2631 {
2632         db_printf("vmstats.v_free_count: %d\n", vmstats.v_free_count);
2633         db_printf("vmstats.v_cache_count: %d\n", vmstats.v_cache_count);
2634         db_printf("vmstats.v_inactive_count: %d\n", vmstats.v_inactive_count);
2635         db_printf("vmstats.v_active_count: %d\n", vmstats.v_active_count);
2636         db_printf("vmstats.v_wire_count: %d\n", vmstats.v_wire_count);
2637         db_printf("vmstats.v_free_reserved: %d\n", vmstats.v_free_reserved);
2638         db_printf("vmstats.v_free_min: %d\n", vmstats.v_free_min);
2639         db_printf("vmstats.v_free_target: %d\n", vmstats.v_free_target);
2640         db_printf("vmstats.v_cache_min: %d\n", vmstats.v_cache_min);
2641         db_printf("vmstats.v_inactive_target: %d\n", vmstats.v_inactive_target);
2642 }
2643
2644 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
2645 {
2646         int i;
2647         db_printf("PQ_FREE:");
2648         for(i=0;i<PQ_L2_SIZE;i++) {
2649                 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
2650         }
2651         db_printf("\n");
2652                 
2653         db_printf("PQ_CACHE:");
2654         for(i=0;i<PQ_L2_SIZE;i++) {
2655                 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
2656         }
2657         db_printf("\n");
2658
2659         db_printf("PQ_ACTIVE:");
2660         for(i=0;i<PQ_L2_SIZE;i++) {
2661                 db_printf(" %d", vm_page_queues[PQ_ACTIVE + i].lcnt);
2662         }
2663         db_printf("\n");
2664
2665         db_printf("PQ_INACTIVE:");
2666         for(i=0;i<PQ_L2_SIZE;i++) {
2667                 db_printf(" %d", vm_page_queues[PQ_INACTIVE + i].lcnt);
2668         }
2669         db_printf("\n");
2670 }
2671 #endif /* DDB */