xref: /titanic_52/usr/src/uts/common/vm/vm_page.c (revision 87ba907dbdcf5c1692d70a9b22fe1d0e718d9896)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989  AT&T	*/
27 /*	  All Rights Reserved  	*/
28 
29 /*
30  * University Copyright- Copyright (c) 1982, 1986, 1988
31  * The Regents of the University of California
32  * All Rights Reserved
33  *
34  * University Acknowledgment- Portions of this document are derived from
35  * software developed by the University of California, Berkeley, and its
36  * contributors.
37  */
38 
39 #pragma ident	"%Z%%M%	%I%	%E% SMI"
40 
41 /*
42  * VM - physical page management.
43  */
44 
45 #include <sys/types.h>
46 #include <sys/t_lock.h>
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/errno.h>
50 #include <sys/time.h>
51 #include <sys/vnode.h>
52 #include <sys/vm.h>
53 #include <sys/vtrace.h>
54 #include <sys/swap.h>
55 #include <sys/cmn_err.h>
56 #include <sys/tuneable.h>
57 #include <sys/sysmacros.h>
58 #include <sys/cpuvar.h>
59 #include <sys/callb.h>
60 #include <sys/debug.h>
61 #include <sys/tnf_probe.h>
62 #include <sys/condvar_impl.h>
63 #include <sys/mem_config.h>
64 #include <sys/mem_cage.h>
65 #include <sys/kmem.h>
66 #include <sys/atomic.h>
67 #include <sys/strlog.h>
68 #include <sys/mman.h>
69 #include <sys/ontrap.h>
70 #include <sys/lgrp.h>
71 #include <sys/vfs.h>
72 
73 #include <vm/hat.h>
74 #include <vm/anon.h>
75 #include <vm/page.h>
76 #include <vm/seg.h>
77 #include <vm/pvn.h>
78 #include <vm/seg_kmem.h>
79 #include <vm/vm_dep.h>
80 #include <sys/vm_usage.h>
81 #include <fs/fs_subr.h>
82 #include <sys/ddi.h>
83 #include <sys/modctl.h>
84 
85 static int nopageage = 0;
86 
87 static pgcnt_t max_page_get;	/* max page_get request size in pages */
88 pgcnt_t total_pages = 0;	/* total number of pages (used by /proc) */
89 
90 /*
91  * freemem_lock protects all freemem variables:
92  * availrmem. Also this lock protects the globals which track the
93  * availrmem changes for accurate kernel footprint calculation.
94  * See below for an explanation of these
95  * globals.
96  */
97 kmutex_t freemem_lock;
98 pgcnt_t availrmem;
99 pgcnt_t availrmem_initial;
100 
101 /*
102  * These globals track availrmem changes to get a more accurate
103  * estimate of tke kernel size. Historically pp_kernel is used for
104  * kernel size and is based on availrmem. But availrmem is adjusted for
105  * locked pages in the system not just for kernel locked pages.
106  * These new counters will track the pages locked through segvn and
107  * by explicit user locking.
108  *
109  * segvn_pages_locked : This keeps track on a global basis how many pages
110  * are currently locked because of I/O.
111  *
112  * pages_locked : How many pages are locked because of user specified
113  * locking through mlock or plock.
114  *
115  * pages_useclaim,pages_claimed : These two variables track the
116  * claim adjustments because of the protection changes on a segvn segment.
117  *
118  * All these globals are protected by the same lock which protects availrmem.
119  */
120 pgcnt_t segvn_pages_locked;
121 pgcnt_t pages_locked;
122 pgcnt_t pages_useclaim;
123 pgcnt_t pages_claimed;
124 
125 
126 /*
127  * new_freemem_lock protects freemem, freemem_wait & freemem_cv.
128  */
129 static kmutex_t	new_freemem_lock;
130 static uint_t	freemem_wait;	/* someone waiting for freemem */
131 static kcondvar_t freemem_cv;
132 
133 /*
134  * The logical page free list is maintained as two lists, the 'free'
135  * and the 'cache' lists.
136  * The free list contains those pages that should be reused first.
137  *
138  * The implementation of the lists is machine dependent.
139  * page_get_freelist(), page_get_cachelist(),
140  * page_list_sub(), and page_list_add()
141  * form the interface to the machine dependent implementation.
142  *
143  * Pages with p_free set are on the cache list.
144  * Pages with p_free and p_age set are on the free list,
145  *
146  * A page may be locked while on either list.
147  */
148 
149 /*
150  * free list accounting stuff.
151  *
152  *
153  * Spread out the value for the number of pages on the
154  * page free and page cache lists.  If there is just one
155  * value, then it must be under just one lock.
156  * The lock contention and cache traffic are a real bother.
157  *
158  * When we acquire and then drop a single pcf lock
159  * we can start in the middle of the array of pcf structures.
160  * If we acquire more than one pcf lock at a time, we need to
161  * start at the front to avoid deadlocking.
162  *
163  * pcf_count holds the number of pages in each pool.
164  *
165  * pcf_block is set when page_create_get_something() has asked the
166  * PSM page freelist and page cachelist routines without specifying
167  * a color and nothing came back.  This is used to block anything
168  * else from moving pages from one list to the other while the
169  * lists are searched again.  If a page is freeed while pcf_block is
170  * set, then pcf_reserve is incremented.  pcgs_unblock() takes care
171  * of clearning pcf_block, doing the wakeups, etc.
172  */
173 
174 #if NCPU <= 4
175 #define	PAD	2
176 #define	PCF_FANOUT	4
177 static	uint_t	pcf_mask = PCF_FANOUT - 1;
178 #else
179 #define	PAD	10
180 #ifdef sun4v
181 #define	PCF_FANOUT	32
182 #else
183 #define	PCF_FANOUT	128
184 #endif
185 static	uint_t	pcf_mask = PCF_FANOUT - 1;
186 #endif
187 
188 struct pcf {
189 	kmutex_t	pcf_lock;	/* protects the structure */
190 	uint_t		pcf_count;	/* page count */
191 	uint_t		pcf_wait;	/* number of waiters */
192 	uint_t		pcf_block; 	/* pcgs flag to page_free() */
193 	uint_t		pcf_reserve; 	/* pages freed after pcf_block set */
194 	uint_t		pcf_fill[PAD];	/* to line up on the caches */
195 };
196 
197 static struct	pcf	pcf[PCF_FANOUT];
198 #define	PCF_INDEX()	((CPU->cpu_id) & (pcf_mask))
199 
200 kmutex_t	pcgs_lock;		/* serializes page_create_get_ */
201 kmutex_t	pcgs_cagelock;		/* serializes NOSLEEP cage allocs */
202 kmutex_t	pcgs_wait_lock;		/* used for delay in pcgs */
203 static kcondvar_t	pcgs_cv;	/* cv for delay in pcgs */
204 
205 #ifdef VM_STATS
206 
207 /*
208  * No locks, but so what, they are only statistics.
209  */
210 
211 static struct page_tcnt {
212 	int	pc_free_cache;		/* free's into cache list */
213 	int	pc_free_dontneed;	/* free's with dontneed */
214 	int	pc_free_pageout;	/* free's from pageout */
215 	int	pc_free_free;		/* free's into free list */
216 	int	pc_free_pages;		/* free's into large page free list */
217 	int	pc_destroy_pages;	/* large page destroy's */
218 	int	pc_get_cache;		/* get's from cache list */
219 	int	pc_get_free;		/* get's from free list */
220 	int	pc_reclaim;		/* reclaim's */
221 	int	pc_abortfree;		/* abort's of free pages */
222 	int	pc_find_hit;		/* find's that find page */
223 	int	pc_find_miss;		/* find's that don't find page */
224 	int	pc_destroy_free;	/* # of free pages destroyed */
225 #define	PC_HASH_CNT	(4*PAGE_HASHAVELEN)
226 	int	pc_find_hashlen[PC_HASH_CNT+1];
227 	int	pc_addclaim_pages;
228 	int	pc_subclaim_pages;
229 	int	pc_free_replacement_page[2];
230 	int	pc_try_demote_pages[6];
231 	int	pc_demote_pages[2];
232 } pagecnt;
233 
234 uint_t	hashin_count;
235 uint_t	hashin_not_held;
236 uint_t	hashin_already;
237 
238 uint_t	hashout_count;
239 uint_t	hashout_not_held;
240 
241 uint_t	page_create_count;
242 uint_t	page_create_not_enough;
243 uint_t	page_create_not_enough_again;
244 uint_t	page_create_zero;
245 uint_t	page_create_hashout;
246 uint_t	page_create_page_lock_failed;
247 uint_t	page_create_trylock_failed;
248 uint_t	page_create_found_one;
249 uint_t	page_create_hashin_failed;
250 uint_t	page_create_dropped_phm;
251 
252 uint_t	page_create_new;
253 uint_t	page_create_exists;
254 uint_t	page_create_putbacks;
255 uint_t	page_create_overshoot;
256 
257 uint_t	page_reclaim_zero;
258 uint_t	page_reclaim_zero_locked;
259 
260 uint_t	page_rename_exists;
261 uint_t	page_rename_count;
262 
263 uint_t	page_lookup_cnt[20];
264 uint_t	page_lookup_nowait_cnt[10];
265 uint_t	page_find_cnt;
266 uint_t	page_exists_cnt;
267 uint_t	page_exists_forreal_cnt;
268 uint_t	page_lookup_dev_cnt;
269 uint_t	get_cachelist_cnt;
270 uint_t	page_create_cnt[10];
271 uint_t	alloc_pages[9];
272 uint_t	page_exphcontg[19];
273 uint_t  page_create_large_cnt[10];
274 
275 /*
276  * Collects statistics.
277  */
278 #define	PAGE_HASH_SEARCH(index, pp, vp, off) { \
279 	uint_t	mylen = 0; \
280 			\
281 	for ((pp) = page_hash[(index)]; (pp); (pp) = (pp)->p_hash, mylen++) { \
282 		if ((pp)->p_vnode == (vp) && (pp)->p_offset == (off)) \
283 			break; \
284 	} \
285 	if ((pp) != NULL) \
286 		pagecnt.pc_find_hit++; \
287 	else \
288 		pagecnt.pc_find_miss++; \
289 	if (mylen > PC_HASH_CNT) \
290 		mylen = PC_HASH_CNT; \
291 	pagecnt.pc_find_hashlen[mylen]++; \
292 }
293 
294 #else	/* VM_STATS */
295 
296 /*
297  * Don't collect statistics
298  */
299 #define	PAGE_HASH_SEARCH(index, pp, vp, off) { \
300 	for ((pp) = page_hash[(index)]; (pp); (pp) = (pp)->p_hash) { \
301 		if ((pp)->p_vnode == (vp) && (pp)->p_offset == (off)) \
302 			break; \
303 	} \
304 }
305 
306 #endif	/* VM_STATS */
307 
308 
309 
310 #ifdef DEBUG
311 #define	MEMSEG_SEARCH_STATS
312 #endif
313 
314 #ifdef MEMSEG_SEARCH_STATS
315 struct memseg_stats {
316     uint_t nsearch;
317     uint_t nlastwon;
318     uint_t nhashwon;
319     uint_t nnotfound;
320 } memseg_stats;
321 
322 #define	MEMSEG_STAT_INCR(v) \
323 	atomic_add_32(&memseg_stats.v, 1)
324 #else
325 #define	MEMSEG_STAT_INCR(x)
326 #endif
327 
328 struct memseg *memsegs;		/* list of memory segments */
329 
330 
331 static void page_init_mem_config(void);
332 static int page_do_hashin(page_t *, vnode_t *, u_offset_t);
333 static void page_do_hashout(page_t *);
334 static void page_capture_init();
335 int page_capture_take_action(page_t *, uint_t, void *);
336 
337 static void page_demote_vp_pages(page_t *);
338 
339 /*
340  * vm subsystem related initialization
341  */
342 void
343 vm_init(void)
344 {
345 	boolean_t callb_vm_cpr(void *, int);
346 
347 	(void) callb_add(callb_vm_cpr, 0, CB_CL_CPR_VM, "vm");
348 	page_init_mem_config();
349 	page_retire_init();
350 	vm_usage_init();
351 	page_capture_init();
352 }
353 
354 /*
355  * This function is called at startup and when memory is added or deleted.
356  */
357 void
358 init_pages_pp_maximum()
359 {
360 	static pgcnt_t p_min;
361 	static pgcnt_t pages_pp_maximum_startup;
362 	static pgcnt_t avrmem_delta;
363 	static int init_done;
364 	static int user_set;	/* true if set in /etc/system */
365 
366 	if (init_done == 0) {
367 
368 		/* If the user specified a value, save it */
369 		if (pages_pp_maximum != 0) {
370 			user_set = 1;
371 			pages_pp_maximum_startup = pages_pp_maximum;
372 		}
373 
374 		/*
375 		 * Setting of pages_pp_maximum is based first time
376 		 * on the value of availrmem just after the start-up
377 		 * allocations. To preserve this relationship at run
378 		 * time, use a delta from availrmem_initial.
379 		 */
380 		ASSERT(availrmem_initial >= availrmem);
381 		avrmem_delta = availrmem_initial - availrmem;
382 
383 		/* The allowable floor of pages_pp_maximum */
384 		p_min = tune.t_minarmem + 100;
385 
386 		/* Make sure we don't come through here again. */
387 		init_done = 1;
388 	}
389 	/*
390 	 * Determine pages_pp_maximum, the number of currently available
391 	 * pages (availrmem) that can't be `locked'. If not set by
392 	 * the user, we set it to 4% of the currently available memory
393 	 * plus 4MB.
394 	 * But we also insist that it be greater than tune.t_minarmem;
395 	 * otherwise a process could lock down a lot of memory, get swapped
396 	 * out, and never have enough to get swapped back in.
397 	 */
398 	if (user_set)
399 		pages_pp_maximum = pages_pp_maximum_startup;
400 	else
401 		pages_pp_maximum = ((availrmem_initial - avrmem_delta) / 25)
402 		    + btop(4 * 1024 * 1024);
403 
404 	if (pages_pp_maximum <= p_min) {
405 		pages_pp_maximum = p_min;
406 	}
407 }
408 
409 void
410 set_max_page_get(pgcnt_t target_total_pages)
411 {
412 	max_page_get = target_total_pages / 2;
413 }
414 
415 static pgcnt_t pending_delete;
416 
417 /*ARGSUSED*/
418 static void
419 page_mem_config_post_add(
420 	void *arg,
421 	pgcnt_t delta_pages)
422 {
423 	set_max_page_get(total_pages - pending_delete);
424 	init_pages_pp_maximum();
425 }
426 
427 /*ARGSUSED*/
428 static int
429 page_mem_config_pre_del(
430 	void *arg,
431 	pgcnt_t delta_pages)
432 {
433 	pgcnt_t nv;
434 
435 	nv = atomic_add_long_nv(&pending_delete, (spgcnt_t)delta_pages);
436 	set_max_page_get(total_pages - nv);
437 	return (0);
438 }
439 
440 /*ARGSUSED*/
441 static void
442 page_mem_config_post_del(
443 	void *arg,
444 	pgcnt_t delta_pages,
445 	int cancelled)
446 {
447 	pgcnt_t nv;
448 
449 	nv = atomic_add_long_nv(&pending_delete, -(spgcnt_t)delta_pages);
450 	set_max_page_get(total_pages - nv);
451 	if (!cancelled)
452 		init_pages_pp_maximum();
453 }
454 
455 static kphysm_setup_vector_t page_mem_config_vec = {
456 	KPHYSM_SETUP_VECTOR_VERSION,
457 	page_mem_config_post_add,
458 	page_mem_config_pre_del,
459 	page_mem_config_post_del,
460 };
461 
462 static void
463 page_init_mem_config(void)
464 {
465 	int ret;
466 
467 	ret = kphysm_setup_func_register(&page_mem_config_vec, (void *)NULL);
468 	ASSERT(ret == 0);
469 }
470 
471 /*
472  * Evenly spread out the PCF counters for large free pages
473  */
474 static void
475 page_free_large_ctr(pgcnt_t npages)
476 {
477 	static struct pcf	*p = pcf;
478 	pgcnt_t			lump;
479 
480 	freemem += npages;
481 
482 	lump = roundup(npages, PCF_FANOUT) / PCF_FANOUT;
483 
484 	while (npages > 0) {
485 
486 		ASSERT(!p->pcf_block);
487 
488 		if (lump < npages) {
489 			p->pcf_count += (uint_t)lump;
490 			npages -= lump;
491 		} else {
492 			p->pcf_count += (uint_t)npages;
493 			npages = 0;
494 		}
495 
496 		ASSERT(!p->pcf_wait);
497 
498 		if (++p > &pcf[PCF_FANOUT - 1])
499 			p = pcf;
500 	}
501 
502 	ASSERT(npages == 0);
503 }
504 
505 /*
506  * Add a physical chunk of memory to the system free lists during startup.
507  * Platform specific startup() allocates the memory for the page structs.
508  *
509  * num	- number of page structures
510  * base - page number (pfn) to be associated with the first page.
511  *
512  * Since we are doing this during startup (ie. single threaded), we will
513  * use shortcut routines to avoid any locking overhead while putting all
514  * these pages on the freelists.
515  *
516  * NOTE: Any changes performed to page_free(), must also be performed to
517  *	 add_physmem() since this is how we initialize all page_t's at
518  *	 boot time.
519  */
520 void
521 add_physmem(
522 	page_t	*pp,
523 	pgcnt_t	num,
524 	pfn_t	pnum)
525 {
526 	page_t	*root = NULL;
527 	uint_t	szc = page_num_pagesizes() - 1;
528 	pgcnt_t	large = page_get_pagecnt(szc);
529 	pgcnt_t	cnt = 0;
530 
531 	TRACE_2(TR_FAC_VM, TR_PAGE_INIT,
532 	    "add_physmem:pp %p num %lu", pp, num);
533 
534 	/*
535 	 * Arbitrarily limit the max page_get request
536 	 * to 1/2 of the page structs we have.
537 	 */
538 	total_pages += num;
539 	set_max_page_get(total_pages);
540 
541 	PLCNT_MODIFY_MAX(pnum, (long)num);
542 
543 	/*
544 	 * The physical space for the pages array
545 	 * representing ram pages has already been
546 	 * allocated.  Here we initialize each lock
547 	 * in the page structure, and put each on
548 	 * the free list
549 	 */
550 	for (; num; pp++, pnum++, num--) {
551 
552 		/*
553 		 * this needs to fill in the page number
554 		 * and do any other arch specific initialization
555 		 */
556 		add_physmem_cb(pp, pnum);
557 
558 		pp->p_lckcnt = 0;
559 		pp->p_cowcnt = 0;
560 		pp->p_slckcnt = 0;
561 
562 		/*
563 		 * Initialize the page lock as unlocked, since nobody
564 		 * can see or access this page yet.
565 		 */
566 		pp->p_selock = 0;
567 
568 		/*
569 		 * Initialize IO lock
570 		 */
571 		page_iolock_init(pp);
572 
573 		/*
574 		 * initialize other fields in the page_t
575 		 */
576 		PP_SETFREE(pp);
577 		page_clr_all_props(pp);
578 		PP_SETAGED(pp);
579 		pp->p_offset = (u_offset_t)-1;
580 		pp->p_next = pp;
581 		pp->p_prev = pp;
582 
583 		/*
584 		 * Simple case: System doesn't support large pages.
585 		 */
586 		if (szc == 0) {
587 			pp->p_szc = 0;
588 			page_free_at_startup(pp);
589 			continue;
590 		}
591 
592 		/*
593 		 * Handle unaligned pages, we collect them up onto
594 		 * the root page until we have a full large page.
595 		 */
596 		if (!IS_P2ALIGNED(pnum, large)) {
597 
598 			/*
599 			 * If not in a large page,
600 			 * just free as small page.
601 			 */
602 			if (root == NULL) {
603 				pp->p_szc = 0;
604 				page_free_at_startup(pp);
605 				continue;
606 			}
607 
608 			/*
609 			 * Link a constituent page into the large page.
610 			 */
611 			pp->p_szc = szc;
612 			page_list_concat(&root, &pp);
613 
614 			/*
615 			 * When large page is fully formed, free it.
616 			 */
617 			if (++cnt == large) {
618 				page_free_large_ctr(cnt);
619 				page_list_add_pages(root, PG_LIST_ISINIT);
620 				root = NULL;
621 				cnt = 0;
622 			}
623 			continue;
624 		}
625 
626 		/*
627 		 * At this point we have a page number which
628 		 * is aligned. We assert that we aren't already
629 		 * in a different large page.
630 		 */
631 		ASSERT(IS_P2ALIGNED(pnum, large));
632 		ASSERT(root == NULL && cnt == 0);
633 
634 		/*
635 		 * If insufficient number of pages left to form
636 		 * a large page, just free the small page.
637 		 */
638 		if (num < large) {
639 			pp->p_szc = 0;
640 			page_free_at_startup(pp);
641 			continue;
642 		}
643 
644 		/*
645 		 * Otherwise start a new large page.
646 		 */
647 		pp->p_szc = szc;
648 		cnt++;
649 		root = pp;
650 	}
651 	ASSERT(root == NULL && cnt == 0);
652 }
653 
654 /*
655  * Find a page representing the specified [vp, offset].
656  * If we find the page but it is intransit coming in,
657  * it will have an "exclusive" lock and we wait for
658  * the i/o to complete.  A page found on the free list
659  * is always reclaimed and then locked.  On success, the page
660  * is locked, its data is valid and it isn't on the free
661  * list, while a NULL is returned if the page doesn't exist.
662  */
663 page_t *
664 page_lookup(vnode_t *vp, u_offset_t off, se_t se)
665 {
666 	return (page_lookup_create(vp, off, se, NULL, NULL, 0));
667 }
668 
669 /*
670  * Find a page representing the specified [vp, offset].
671  * We either return the one we found or, if passed in,
672  * create one with identity of [vp, offset] of the
673  * pre-allocated page. If we find existing page but it is
674  * intransit coming in, it will have an "exclusive" lock
675  * and we wait for the i/o to complete.  A page found on
676  * the free list is always reclaimed and then locked.
677  * On success, the page is locked, its data is valid and
678  * it isn't on the free list, while a NULL is returned
679  * if the page doesn't exist and newpp is NULL;
680  */
681 page_t *
682 page_lookup_create(
683 	vnode_t *vp,
684 	u_offset_t off,
685 	se_t se,
686 	page_t *newpp,
687 	spgcnt_t *nrelocp,
688 	int flags)
689 {
690 	page_t		*pp;
691 	kmutex_t	*phm;
692 	ulong_t		index;
693 	uint_t		hash_locked;
694 	uint_t		es;
695 
696 	ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(vp)));
697 	VM_STAT_ADD(page_lookup_cnt[0]);
698 	ASSERT(newpp ? PAGE_EXCL(newpp) : 1);
699 
700 	/*
701 	 * Acquire the appropriate page hash lock since
702 	 * we have to search the hash list.  Pages that
703 	 * hash to this list can't change identity while
704 	 * this lock is held.
705 	 */
706 	hash_locked = 0;
707 	index = PAGE_HASH_FUNC(vp, off);
708 	phm = NULL;
709 top:
710 	PAGE_HASH_SEARCH(index, pp, vp, off);
711 	if (pp != NULL) {
712 		VM_STAT_ADD(page_lookup_cnt[1]);
713 		es = (newpp != NULL) ? 1 : 0;
714 		es |= flags;
715 		if (!hash_locked) {
716 			VM_STAT_ADD(page_lookup_cnt[2]);
717 			if (!page_try_reclaim_lock(pp, se, es)) {
718 				/*
719 				 * On a miss, acquire the phm.  Then
720 				 * next time, page_lock() will be called,
721 				 * causing a wait if the page is busy.
722 				 * just looping with page_trylock() would
723 				 * get pretty boring.
724 				 */
725 				VM_STAT_ADD(page_lookup_cnt[3]);
726 				phm = PAGE_HASH_MUTEX(index);
727 				mutex_enter(phm);
728 				hash_locked = 1;
729 				goto top;
730 			}
731 		} else {
732 			VM_STAT_ADD(page_lookup_cnt[4]);
733 			if (!page_lock_es(pp, se, phm, P_RECLAIM, es)) {
734 				VM_STAT_ADD(page_lookup_cnt[5]);
735 				goto top;
736 			}
737 		}
738 
739 		/*
740 		 * Since `pp' is locked it can not change identity now.
741 		 * Reconfirm we locked the correct page.
742 		 *
743 		 * Both the p_vnode and p_offset *must* be cast volatile
744 		 * to force a reload of their values: The PAGE_HASH_SEARCH
745 		 * macro will have stuffed p_vnode and p_offset into
746 		 * registers before calling page_trylock(); another thread,
747 		 * actually holding the hash lock, could have changed the
748 		 * page's identity in memory, but our registers would not
749 		 * be changed, fooling the reconfirmation.  If the hash
750 		 * lock was held during the search, the casting would
751 		 * not be needed.
752 		 */
753 		VM_STAT_ADD(page_lookup_cnt[6]);
754 		if (((volatile struct vnode *)(pp->p_vnode) != vp) ||
755 		    ((volatile u_offset_t)(pp->p_offset) != off)) {
756 			VM_STAT_ADD(page_lookup_cnt[7]);
757 			if (hash_locked) {
758 				panic("page_lookup_create: lost page %p",
759 				    (void *)pp);
760 				/*NOTREACHED*/
761 			}
762 			page_unlock(pp);
763 			phm = PAGE_HASH_MUTEX(index);
764 			mutex_enter(phm);
765 			hash_locked = 1;
766 			goto top;
767 		}
768 
769 		/*
770 		 * If page_trylock() was called, then pp may still be on
771 		 * the cachelist (can't be on the free list, it would not
772 		 * have been found in the search).  If it is on the
773 		 * cachelist it must be pulled now. To pull the page from
774 		 * the cachelist, it must be exclusively locked.
775 		 *
776 		 * The other big difference between page_trylock() and
777 		 * page_lock(), is that page_lock() will pull the
778 		 * page from whatever free list (the cache list in this
779 		 * case) the page is on.  If page_trylock() was used
780 		 * above, then we have to do the reclaim ourselves.
781 		 */
782 		if ((!hash_locked) && (PP_ISFREE(pp))) {
783 			ASSERT(PP_ISAGED(pp) == 0);
784 			VM_STAT_ADD(page_lookup_cnt[8]);
785 
786 			/*
787 			 * page_relcaim will insure that we
788 			 * have this page exclusively
789 			 */
790 
791 			if (!page_reclaim(pp, NULL)) {
792 				/*
793 				 * Page_reclaim dropped whatever lock
794 				 * we held.
795 				 */
796 				VM_STAT_ADD(page_lookup_cnt[9]);
797 				phm = PAGE_HASH_MUTEX(index);
798 				mutex_enter(phm);
799 				hash_locked = 1;
800 				goto top;
801 			} else if (se == SE_SHARED && newpp == NULL) {
802 				VM_STAT_ADD(page_lookup_cnt[10]);
803 				page_downgrade(pp);
804 			}
805 		}
806 
807 		if (hash_locked) {
808 			mutex_exit(phm);
809 		}
810 
811 		if (newpp != NULL && pp->p_szc < newpp->p_szc &&
812 		    PAGE_EXCL(pp) && nrelocp != NULL) {
813 			ASSERT(nrelocp != NULL);
814 			(void) page_relocate(&pp, &newpp, 1, 1, nrelocp,
815 			    NULL);
816 			if (*nrelocp > 0) {
817 				VM_STAT_COND_ADD(*nrelocp == 1,
818 				    page_lookup_cnt[11]);
819 				VM_STAT_COND_ADD(*nrelocp > 1,
820 				    page_lookup_cnt[12]);
821 				pp = newpp;
822 				se = SE_EXCL;
823 			} else {
824 				if (se == SE_SHARED) {
825 					page_downgrade(pp);
826 				}
827 				VM_STAT_ADD(page_lookup_cnt[13]);
828 			}
829 		} else if (newpp != NULL && nrelocp != NULL) {
830 			if (PAGE_EXCL(pp) && se == SE_SHARED) {
831 				page_downgrade(pp);
832 			}
833 			VM_STAT_COND_ADD(pp->p_szc < newpp->p_szc,
834 			    page_lookup_cnt[14]);
835 			VM_STAT_COND_ADD(pp->p_szc == newpp->p_szc,
836 			    page_lookup_cnt[15]);
837 			VM_STAT_COND_ADD(pp->p_szc > newpp->p_szc,
838 			    page_lookup_cnt[16]);
839 		} else if (newpp != NULL && PAGE_EXCL(pp)) {
840 			se = SE_EXCL;
841 		}
842 	} else if (!hash_locked) {
843 		VM_STAT_ADD(page_lookup_cnt[17]);
844 		phm = PAGE_HASH_MUTEX(index);
845 		mutex_enter(phm);
846 		hash_locked = 1;
847 		goto top;
848 	} else if (newpp != NULL) {
849 		/*
850 		 * If we have a preallocated page then
851 		 * insert it now and basically behave like
852 		 * page_create.
853 		 */
854 		VM_STAT_ADD(page_lookup_cnt[18]);
855 		/*
856 		 * Since we hold the page hash mutex and
857 		 * just searched for this page, page_hashin
858 		 * had better not fail.  If it does, that
859 		 * means some thread did not follow the
860 		 * page hash mutex rules.  Panic now and
861 		 * get it over with.  As usual, go down
862 		 * holding all the locks.
863 		 */
864 		ASSERT(MUTEX_HELD(phm));
865 		if (!page_hashin(newpp, vp, off, phm)) {
866 			ASSERT(MUTEX_HELD(phm));
867 			panic("page_lookup_create: hashin failed %p %p %llx %p",
868 			    (void *)newpp, (void *)vp, off, (void *)phm);
869 			/*NOTREACHED*/
870 		}
871 		ASSERT(MUTEX_HELD(phm));
872 		mutex_exit(phm);
873 		phm = NULL;
874 		page_set_props(newpp, P_REF);
875 		page_io_lock(newpp);
876 		pp = newpp;
877 		se = SE_EXCL;
878 	} else {
879 		VM_STAT_ADD(page_lookup_cnt[19]);
880 		mutex_exit(phm);
881 	}
882 
883 	ASSERT(pp ? PAGE_LOCKED_SE(pp, se) : 1);
884 
885 	ASSERT(pp ? ((PP_ISFREE(pp) == 0) && (PP_ISAGED(pp) == 0)) : 1);
886 
887 	return (pp);
888 }
889 
890 /*
891  * Search the hash list for the page representing the
892  * specified [vp, offset] and return it locked.  Skip
893  * free pages and pages that cannot be locked as requested.
894  * Used while attempting to kluster pages.
895  */
896 page_t *
897 page_lookup_nowait(vnode_t *vp, u_offset_t off, se_t se)
898 {
899 	page_t		*pp;
900 	kmutex_t	*phm;
901 	ulong_t		index;
902 	uint_t		locked;
903 
904 	ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(vp)));
905 	VM_STAT_ADD(page_lookup_nowait_cnt[0]);
906 
907 	index = PAGE_HASH_FUNC(vp, off);
908 	PAGE_HASH_SEARCH(index, pp, vp, off);
909 	locked = 0;
910 	if (pp == NULL) {
911 top:
912 		VM_STAT_ADD(page_lookup_nowait_cnt[1]);
913 		locked = 1;
914 		phm = PAGE_HASH_MUTEX(index);
915 		mutex_enter(phm);
916 		PAGE_HASH_SEARCH(index, pp, vp, off);
917 	}
918 
919 	if (pp == NULL || PP_ISFREE(pp)) {
920 		VM_STAT_ADD(page_lookup_nowait_cnt[2]);
921 		pp = NULL;
922 	} else {
923 		if (!page_trylock(pp, se)) {
924 			VM_STAT_ADD(page_lookup_nowait_cnt[3]);
925 			pp = NULL;
926 		} else {
927 			VM_STAT_ADD(page_lookup_nowait_cnt[4]);
928 			/*
929 			 * See the comment in page_lookup()
930 			 */
931 			if (((volatile struct vnode *)(pp->p_vnode) != vp) ||
932 			    ((u_offset_t)(pp->p_offset) != off)) {
933 				VM_STAT_ADD(page_lookup_nowait_cnt[5]);
934 				if (locked) {
935 					panic("page_lookup_nowait %p",
936 					    (void *)pp);
937 					/*NOTREACHED*/
938 				}
939 				page_unlock(pp);
940 				goto top;
941 			}
942 			if (PP_ISFREE(pp)) {
943 				VM_STAT_ADD(page_lookup_nowait_cnt[6]);
944 				page_unlock(pp);
945 				pp = NULL;
946 			}
947 		}
948 	}
949 	if (locked) {
950 		VM_STAT_ADD(page_lookup_nowait_cnt[7]);
951 		mutex_exit(phm);
952 	}
953 
954 	ASSERT(pp ? PAGE_LOCKED_SE(pp, se) : 1);
955 
956 	return (pp);
957 }
958 
959 /*
960  * Search the hash list for a page with the specified [vp, off]
961  * that is known to exist and is already locked.  This routine
962  * is typically used by segment SOFTUNLOCK routines.
963  */
964 page_t *
965 page_find(vnode_t *vp, u_offset_t off)
966 {
967 	page_t		*pp;
968 	kmutex_t	*phm;
969 	ulong_t		index;
970 
971 	ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(vp)));
972 	VM_STAT_ADD(page_find_cnt);
973 
974 	index = PAGE_HASH_FUNC(vp, off);
975 	phm = PAGE_HASH_MUTEX(index);
976 
977 	mutex_enter(phm);
978 	PAGE_HASH_SEARCH(index, pp, vp, off);
979 	mutex_exit(phm);
980 
981 	ASSERT(pp == NULL || PAGE_LOCKED(pp) || panicstr);
982 	return (pp);
983 }
984 
985 /*
986  * Determine whether a page with the specified [vp, off]
987  * currently exists in the system.  Obviously this should
988  * only be considered as a hint since nothing prevents the
989  * page from disappearing or appearing immediately after
990  * the return from this routine. Subsequently, we don't
991  * even bother to lock the list.
992  */
993 page_t *
994 page_exists(vnode_t *vp, u_offset_t off)
995 {
996 	page_t	*pp;
997 	ulong_t		index;
998 
999 	ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(vp)));
1000 	VM_STAT_ADD(page_exists_cnt);
1001 
1002 	index = PAGE_HASH_FUNC(vp, off);
1003 	PAGE_HASH_SEARCH(index, pp, vp, off);
1004 
1005 	return (pp);
1006 }
1007 
1008 /*
1009  * Determine if physically contiguous pages exist for [vp, off] - [vp, off +
1010  * page_size(szc)) range.  if they exist and ppa is not NULL fill ppa array
1011  * with these pages locked SHARED. If necessary reclaim pages from
1012  * freelist. Return 1 if contiguous pages exist and 0 otherwise.
1013  *
1014  * If we fail to lock pages still return 1 if pages exist and contiguous.
1015  * But in this case return value is just a hint. ppa array won't be filled.
1016  * Caller should initialize ppa[0] as NULL to distinguish return value.
1017  *
1018  * Returns 0 if pages don't exist or not physically contiguous.
1019  *
1020  * This routine doesn't work for anonymous(swapfs) pages.
1021  */
1022 int
1023 page_exists_physcontig(vnode_t *vp, u_offset_t off, uint_t szc, page_t *ppa[])
1024 {
1025 	pgcnt_t pages;
1026 	pfn_t pfn;
1027 	page_t *rootpp;
1028 	pgcnt_t i;
1029 	pgcnt_t j;
1030 	u_offset_t save_off = off;
1031 	ulong_t index;
1032 	kmutex_t *phm;
1033 	page_t *pp;
1034 	uint_t pszc;
1035 	int loopcnt = 0;
1036 
1037 	ASSERT(szc != 0);
1038 	ASSERT(vp != NULL);
1039 	ASSERT(!IS_SWAPFSVP(vp));
1040 	ASSERT(!VN_ISKAS(vp));
1041 
1042 again:
1043 	if (++loopcnt > 3) {
1044 		VM_STAT_ADD(page_exphcontg[0]);
1045 		return (0);
1046 	}
1047 
1048 	index = PAGE_HASH_FUNC(vp, off);
1049 	phm = PAGE_HASH_MUTEX(index);
1050 
1051 	mutex_enter(phm);
1052 	PAGE_HASH_SEARCH(index, pp, vp, off);
1053 	mutex_exit(phm);
1054 
1055 	VM_STAT_ADD(page_exphcontg[1]);
1056 
1057 	if (pp == NULL) {
1058 		VM_STAT_ADD(page_exphcontg[2]);
1059 		return (0);
1060 	}
1061 
1062 	pages = page_get_pagecnt(szc);
1063 	rootpp = pp;
1064 	pfn = rootpp->p_pagenum;
1065 
1066 	if ((pszc = pp->p_szc) >= szc && ppa != NULL) {
1067 		VM_STAT_ADD(page_exphcontg[3]);
1068 		if (!page_trylock(pp, SE_SHARED)) {
1069 			VM_STAT_ADD(page_exphcontg[4]);
1070 			return (1);
1071 		}
1072 		if (pp->p_szc != pszc || pp->p_vnode != vp ||
1073 		    pp->p_offset != off) {
1074 			VM_STAT_ADD(page_exphcontg[5]);
1075 			page_unlock(pp);
1076 			off = save_off;
1077 			goto again;
1078 		}
1079 		/*
1080 		 * szc was non zero and vnode and offset matched after we
1081 		 * locked the page it means it can't become free on us.
1082 		 */
1083 		ASSERT(!PP_ISFREE(pp));
1084 		if (!IS_P2ALIGNED(pfn, pages)) {
1085 			page_unlock(pp);
1086 			return (0);
1087 		}
1088 		ppa[0] = pp;
1089 		pp++;
1090 		off += PAGESIZE;
1091 		pfn++;
1092 		for (i = 1; i < pages; i++, pp++, off += PAGESIZE, pfn++) {
1093 			if (!page_trylock(pp, SE_SHARED)) {
1094 				VM_STAT_ADD(page_exphcontg[6]);
1095 				pp--;
1096 				while (i-- > 0) {
1097 					page_unlock(pp);
1098 					pp--;
1099 				}
1100 				ppa[0] = NULL;
1101 				return (1);
1102 			}
1103 			if (pp->p_szc != pszc) {
1104 				VM_STAT_ADD(page_exphcontg[7]);
1105 				page_unlock(pp);
1106 				pp--;
1107 				while (i-- > 0) {
1108 					page_unlock(pp);
1109 					pp--;
1110 				}
1111 				ppa[0] = NULL;
1112 				off = save_off;
1113 				goto again;
1114 			}
1115 			/*
1116 			 * szc the same as for previous already locked pages
1117 			 * with right identity. Since this page had correct
1118 			 * szc after we locked it can't get freed or destroyed
1119 			 * and therefore must have the expected identity.
1120 			 */
1121 			ASSERT(!PP_ISFREE(pp));
1122 			if (pp->p_vnode != vp ||
1123 			    pp->p_offset != off) {
1124 				panic("page_exists_physcontig: "
1125 				    "large page identity doesn't match");
1126 			}
1127 			ppa[i] = pp;
1128 			ASSERT(pp->p_pagenum == pfn);
1129 		}
1130 		VM_STAT_ADD(page_exphcontg[8]);
1131 		ppa[pages] = NULL;
1132 		return (1);
1133 	} else if (pszc >= szc) {
1134 		VM_STAT_ADD(page_exphcontg[9]);
1135 		if (!IS_P2ALIGNED(pfn, pages)) {
1136 			return (0);
1137 		}
1138 		return (1);
1139 	}
1140 
1141 	if (!IS_P2ALIGNED(pfn, pages)) {
1142 		VM_STAT_ADD(page_exphcontg[10]);
1143 		return (0);
1144 	}
1145 
1146 	if (page_numtomemseg_nolock(pfn) !=
1147 	    page_numtomemseg_nolock(pfn + pages - 1)) {
1148 		VM_STAT_ADD(page_exphcontg[11]);
1149 		return (0);
1150 	}
1151 
1152 	/*
1153 	 * We loop up 4 times across pages to promote page size.
1154 	 * We're extra cautious to promote page size atomically with respect
1155 	 * to everybody else.  But we can probably optimize into 1 loop if
1156 	 * this becomes an issue.
1157 	 */
1158 
1159 	for (i = 0; i < pages; i++, pp++, off += PAGESIZE, pfn++) {
1160 		ASSERT(pp->p_pagenum == pfn);
1161 		if (!page_trylock(pp, SE_EXCL)) {
1162 			VM_STAT_ADD(page_exphcontg[12]);
1163 			break;
1164 		}
1165 		if (pp->p_vnode != vp ||
1166 		    pp->p_offset != off) {
1167 			VM_STAT_ADD(page_exphcontg[13]);
1168 			page_unlock(pp);
1169 			break;
1170 		}
1171 		if (pp->p_szc >= szc) {
1172 			ASSERT(i == 0);
1173 			page_unlock(pp);
1174 			off = save_off;
1175 			goto again;
1176 		}
1177 	}
1178 
1179 	if (i != pages) {
1180 		VM_STAT_ADD(page_exphcontg[14]);
1181 		--pp;
1182 		while (i-- > 0) {
1183 			page_unlock(pp);
1184 			--pp;
1185 		}
1186 		return (0);
1187 	}
1188 
1189 	pp = rootpp;
1190 	for (i = 0; i < pages; i++, pp++) {
1191 		if (PP_ISFREE(pp)) {
1192 			VM_STAT_ADD(page_exphcontg[15]);
1193 			ASSERT(!PP_ISAGED(pp));
1194 			ASSERT(pp->p_szc == 0);
1195 			if (!page_reclaim(pp, NULL)) {
1196 				break;
1197 			}
1198 		} else {
1199 			ASSERT(pp->p_szc < szc);
1200 			VM_STAT_ADD(page_exphcontg[16]);
1201 			(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
1202 		}
1203 	}
1204 	if (i < pages) {
1205 		VM_STAT_ADD(page_exphcontg[17]);
1206 		/*
1207 		 * page_reclaim failed because we were out of memory.
1208 		 * drop the rest of the locks and return because this page
1209 		 * must be already reallocated anyway.
1210 		 */
1211 		pp = rootpp;
1212 		for (j = 0; j < pages; j++, pp++) {
1213 			if (j != i) {
1214 				page_unlock(pp);
1215 			}
1216 		}
1217 		return (0);
1218 	}
1219 
1220 	off = save_off;
1221 	pp = rootpp;
1222 	for (i = 0; i < pages; i++, pp++, off += PAGESIZE) {
1223 		ASSERT(PAGE_EXCL(pp));
1224 		ASSERT(!PP_ISFREE(pp));
1225 		ASSERT(!hat_page_is_mapped(pp));
1226 		ASSERT(pp->p_vnode == vp);
1227 		ASSERT(pp->p_offset == off);
1228 		pp->p_szc = szc;
1229 	}
1230 	pp = rootpp;
1231 	for (i = 0; i < pages; i++, pp++) {
1232 		if (ppa == NULL) {
1233 			page_unlock(pp);
1234 		} else {
1235 			ppa[i] = pp;
1236 			page_downgrade(ppa[i]);
1237 		}
1238 	}
1239 	if (ppa != NULL) {
1240 		ppa[pages] = NULL;
1241 	}
1242 	VM_STAT_ADD(page_exphcontg[18]);
1243 	ASSERT(vp->v_pages != NULL);
1244 	return (1);
1245 }
1246 
1247 /*
1248  * Determine whether a page with the specified [vp, off]
1249  * currently exists in the system and if so return its
1250  * size code. Obviously this should only be considered as
1251  * a hint since nothing prevents the page from disappearing
1252  * or appearing immediately after the return from this routine.
1253  */
1254 int
1255 page_exists_forreal(vnode_t *vp, u_offset_t off, uint_t *szc)
1256 {
1257 	page_t		*pp;
1258 	kmutex_t	*phm;
1259 	ulong_t		index;
1260 	int		rc = 0;
1261 
1262 	ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(vp)));
1263 	ASSERT(szc != NULL);
1264 	VM_STAT_ADD(page_exists_forreal_cnt);
1265 
1266 	index = PAGE_HASH_FUNC(vp, off);
1267 	phm = PAGE_HASH_MUTEX(index);
1268 
1269 	mutex_enter(phm);
1270 	PAGE_HASH_SEARCH(index, pp, vp, off);
1271 	if (pp != NULL) {
1272 		*szc = pp->p_szc;
1273 		rc = 1;
1274 	}
1275 	mutex_exit(phm);
1276 	return (rc);
1277 }
1278 
1279 /* wakeup threads waiting for pages in page_create_get_something() */
1280 void
1281 wakeup_pcgs(void)
1282 {
1283 	if (!CV_HAS_WAITERS(&pcgs_cv))
1284 		return;
1285 	cv_broadcast(&pcgs_cv);
1286 }
1287 
1288 /*
1289  * 'freemem' is used all over the kernel as an indication of how many
1290  * pages are free (either on the cache list or on the free page list)
1291  * in the system.  In very few places is a really accurate 'freemem'
1292  * needed.  To avoid contention of the lock protecting a the
1293  * single freemem, it was spread out into NCPU buckets.  Set_freemem
1294  * sets freemem to the total of all NCPU buckets.  It is called from
1295  * clock() on each TICK.
1296  */
1297 void
1298 set_freemem()
1299 {
1300 	struct pcf	*p;
1301 	ulong_t		t;
1302 	uint_t		i;
1303 
1304 	t = 0;
1305 	p = pcf;
1306 	for (i = 0;  i < PCF_FANOUT; i++) {
1307 		t += p->pcf_count;
1308 		p++;
1309 	}
1310 	freemem = t;
1311 
1312 	/*
1313 	 * Don't worry about grabbing mutex.  It's not that
1314 	 * critical if we miss a tick or two.  This is
1315 	 * where we wakeup possible delayers in
1316 	 * page_create_get_something().
1317 	 */
1318 	wakeup_pcgs();
1319 }
1320 
1321 ulong_t
1322 get_freemem()
1323 {
1324 	struct pcf	*p;
1325 	ulong_t		t;
1326 	uint_t		i;
1327 
1328 	t = 0;
1329 	p = pcf;
1330 	for (i = 0; i < PCF_FANOUT; i++) {
1331 		t += p->pcf_count;
1332 		p++;
1333 	}
1334 	/*
1335 	 * We just calculated it, might as well set it.
1336 	 */
1337 	freemem = t;
1338 	return (t);
1339 }
1340 
1341 /*
1342  * Acquire all of the page cache & free (pcf) locks.
1343  */
1344 void
1345 pcf_acquire_all()
1346 {
1347 	struct pcf	*p;
1348 	uint_t		i;
1349 
1350 	p = pcf;
1351 	for (i = 0; i < PCF_FANOUT; i++) {
1352 		mutex_enter(&p->pcf_lock);
1353 		p++;
1354 	}
1355 }
1356 
1357 /*
1358  * Release all the pcf_locks.
1359  */
1360 void
1361 pcf_release_all()
1362 {
1363 	struct pcf	*p;
1364 	uint_t		i;
1365 
1366 	p = pcf;
1367 	for (i = 0; i < PCF_FANOUT; i++) {
1368 		mutex_exit(&p->pcf_lock);
1369 		p++;
1370 	}
1371 }
1372 
1373 /*
1374  * Inform the VM system that we need some pages freed up.
1375  * Calls must be symmetric, e.g.:
1376  *
1377  *	page_needfree(100);
1378  *	wait a bit;
1379  *	page_needfree(-100);
1380  */
1381 void
1382 page_needfree(spgcnt_t npages)
1383 {
1384 	mutex_enter(&new_freemem_lock);
1385 	needfree += npages;
1386 	mutex_exit(&new_freemem_lock);
1387 }
1388 
1389 /*
1390  * Throttle for page_create(): try to prevent freemem from dropping
1391  * below throttlefree.  We can't provide a 100% guarantee because
1392  * KM_NOSLEEP allocations, page_reclaim(), and various other things
1393  * nibble away at the freelist.  However, we can block all PG_WAIT
1394  * allocations until memory becomes available.  The motivation is
1395  * that several things can fall apart when there's no free memory:
1396  *
1397  * (1) If pageout() needs memory to push a page, the system deadlocks.
1398  *
1399  * (2) By (broken) specification, timeout(9F) can neither fail nor
1400  *     block, so it has no choice but to panic the system if it
1401  *     cannot allocate a callout structure.
1402  *
1403  * (3) Like timeout(), ddi_set_callback() cannot fail and cannot block;
1404  *     it panics if it cannot allocate a callback structure.
1405  *
1406  * (4) Untold numbers of third-party drivers have not yet been hardened
1407  *     against KM_NOSLEEP and/or allocb() failures; they simply assume
1408  *     success and panic the system with a data fault on failure.
1409  *     (The long-term solution to this particular problem is to ship
1410  *     hostile fault-injecting DEBUG kernels with the DDK.)
1411  *
1412  * It is theoretically impossible to guarantee success of non-blocking
1413  * allocations, but in practice, this throttle is very hard to break.
1414  */
1415 static int
1416 page_create_throttle(pgcnt_t npages, int flags)
1417 {
1418 	ulong_t	fm;
1419 	uint_t	i;
1420 	pgcnt_t tf;	/* effective value of throttlefree */
1421 
1422 	/*
1423 	 * Never deny pages when:
1424 	 * - it's a thread that cannot block [NOMEMWAIT()]
1425 	 * - the allocation cannot block and must not fail
1426 	 * - the allocation cannot block and is pageout dispensated
1427 	 */
1428 	if (NOMEMWAIT() ||
1429 	    ((flags & (PG_WAIT | PG_PANIC)) == PG_PANIC) ||
1430 	    ((flags & (PG_WAIT | PG_PUSHPAGE)) == PG_PUSHPAGE))
1431 		return (1);
1432 
1433 	/*
1434 	 * If the allocation can't block, we look favorably upon it
1435 	 * unless we're below pageout_reserve.  In that case we fail
1436 	 * the allocation because we want to make sure there are a few
1437 	 * pages available for pageout.
1438 	 */
1439 	if ((flags & PG_WAIT) == 0)
1440 		return (freemem >= npages + pageout_reserve);
1441 
1442 	/* Calculate the effective throttlefree value */
1443 	tf = throttlefree -
1444 	    ((flags & PG_PUSHPAGE) ? pageout_reserve : 0);
1445 
1446 	cv_signal(&proc_pageout->p_cv);
1447 
1448 	for (;;) {
1449 		fm = 0;
1450 		pcf_acquire_all();
1451 		mutex_enter(&new_freemem_lock);
1452 		for (i = 0; i < PCF_FANOUT; i++) {
1453 			fm += pcf[i].pcf_count;
1454 			pcf[i].pcf_wait++;
1455 			mutex_exit(&pcf[i].pcf_lock);
1456 		}
1457 		freemem = fm;
1458 		if (freemem >= npages + tf) {
1459 			mutex_exit(&new_freemem_lock);
1460 			break;
1461 		}
1462 		needfree += npages;
1463 		freemem_wait++;
1464 		cv_wait(&freemem_cv, &new_freemem_lock);
1465 		freemem_wait--;
1466 		needfree -= npages;
1467 		mutex_exit(&new_freemem_lock);
1468 	}
1469 	return (1);
1470 }
1471 
1472 /*
1473  * page_create_wait() is called to either coalesce pages from the
1474  * different pcf buckets or to wait because there simply are not
1475  * enough pages to satisfy the caller's request.
1476  *
1477  * Sadly, this is called from platform/vm/vm_machdep.c
1478  */
1479 int
1480 page_create_wait(size_t npages, uint_t flags)
1481 {
1482 	pgcnt_t		total;
1483 	uint_t		i;
1484 	struct pcf	*p;
1485 
1486 	/*
1487 	 * Wait until there are enough free pages to satisfy our
1488 	 * entire request.
1489 	 * We set needfree += npages before prodding pageout, to make sure
1490 	 * it does real work when npages > lotsfree > freemem.
1491 	 */
1492 	VM_STAT_ADD(page_create_not_enough);
1493 
1494 	ASSERT(!kcage_on ? !(flags & PG_NORELOC) : 1);
1495 checkagain:
1496 	if ((flags & PG_NORELOC) &&
1497 	    kcage_freemem < kcage_throttlefree + npages)
1498 		(void) kcage_create_throttle(npages, flags);
1499 
1500 	if (freemem < npages + throttlefree)
1501 		if (!page_create_throttle(npages, flags))
1502 			return (0);
1503 
1504 	/*
1505 	 * Since page_create_va() looked at every
1506 	 * bucket, assume we are going to have to wait.
1507 	 * Get all of the pcf locks.
1508 	 */
1509 	total = 0;
1510 	p = pcf;
1511 	for (i = 0; i < PCF_FANOUT; i++) {
1512 		mutex_enter(&p->pcf_lock);
1513 		total += p->pcf_count;
1514 		if (total >= npages) {
1515 			/*
1516 			 * Wow!  There are enough pages laying around
1517 			 * to satisfy the request.  Do the accounting,
1518 			 * drop the locks we acquired, and go back.
1519 			 *
1520 			 * freemem is not protected by any lock. So,
1521 			 * we cannot have any assertion containing
1522 			 * freemem.
1523 			 */
1524 			freemem -= npages;
1525 
1526 			while (p >= pcf) {
1527 				if (p->pcf_count <= npages) {
1528 					npages -= p->pcf_count;
1529 					p->pcf_count = 0;
1530 				} else {
1531 					p->pcf_count -= (uint_t)npages;
1532 					npages = 0;
1533 				}
1534 				mutex_exit(&p->pcf_lock);
1535 				p--;
1536 			}
1537 			ASSERT(npages == 0);
1538 			return (1);
1539 		}
1540 		p++;
1541 	}
1542 
1543 	/*
1544 	 * All of the pcf locks are held, there are not enough pages
1545 	 * to satisfy the request (npages < total).
1546 	 * Be sure to acquire the new_freemem_lock before dropping
1547 	 * the pcf locks.  This prevents dropping wakeups in page_free().
1548 	 * The order is always pcf_lock then new_freemem_lock.
1549 	 *
1550 	 * Since we hold all the pcf locks, it is a good time to set freemem.
1551 	 *
1552 	 * If the caller does not want to wait, return now.
1553 	 * Else turn the pageout daemon loose to find something
1554 	 * and wait till it does.
1555 	 *
1556 	 */
1557 	freemem = total;
1558 
1559 	if ((flags & PG_WAIT) == 0) {
1560 		pcf_release_all();
1561 
1562 		TRACE_2(TR_FAC_VM, TR_PAGE_CREATE_NOMEM,
1563 		"page_create_nomem:npages %ld freemem %ld", npages, freemem);
1564 		return (0);
1565 	}
1566 
1567 	ASSERT(proc_pageout != NULL);
1568 	cv_signal(&proc_pageout->p_cv);
1569 
1570 	TRACE_2(TR_FAC_VM, TR_PAGE_CREATE_SLEEP_START,
1571 	    "page_create_sleep_start: freemem %ld needfree %ld",
1572 	    freemem, needfree);
1573 
1574 	/*
1575 	 * We are going to wait.
1576 	 * We currently hold all of the pcf_locks,
1577 	 * get the new_freemem_lock (it protects freemem_wait),
1578 	 * before dropping the pcf_locks.
1579 	 */
1580 	mutex_enter(&new_freemem_lock);
1581 
1582 	p = pcf;
1583 	for (i = 0; i < PCF_FANOUT; i++) {
1584 		p->pcf_wait++;
1585 		mutex_exit(&p->pcf_lock);
1586 		p++;
1587 	}
1588 
1589 	needfree += npages;
1590 	freemem_wait++;
1591 
1592 	cv_wait(&freemem_cv, &new_freemem_lock);
1593 
1594 	freemem_wait--;
1595 	needfree -= npages;
1596 
1597 	mutex_exit(&new_freemem_lock);
1598 
1599 	TRACE_2(TR_FAC_VM, TR_PAGE_CREATE_SLEEP_END,
1600 	    "page_create_sleep_end: freemem %ld needfree %ld",
1601 	    freemem, needfree);
1602 
1603 	VM_STAT_ADD(page_create_not_enough_again);
1604 	goto checkagain;
1605 }
1606 
1607 /*
1608  * A routine to do the opposite of page_create_wait().
1609  */
1610 void
1611 page_create_putback(spgcnt_t npages)
1612 {
1613 	struct pcf	*p;
1614 	pgcnt_t		lump;
1615 	uint_t		*which;
1616 
1617 	/*
1618 	 * When a contiguous lump is broken up, we have to
1619 	 * deal with lots of pages (min 64) so lets spread
1620 	 * the wealth around.
1621 	 */
1622 	lump = roundup(npages, PCF_FANOUT) / PCF_FANOUT;
1623 	freemem += npages;
1624 
1625 	for (p = pcf; (npages > 0) && (p < &pcf[PCF_FANOUT]); p++) {
1626 		which = &p->pcf_count;
1627 
1628 		mutex_enter(&p->pcf_lock);
1629 
1630 		if (p->pcf_block) {
1631 			which = &p->pcf_reserve;
1632 		}
1633 
1634 		if (lump < npages) {
1635 			*which += (uint_t)lump;
1636 			npages -= lump;
1637 		} else {
1638 			*which += (uint_t)npages;
1639 			npages = 0;
1640 		}
1641 
1642 		if (p->pcf_wait) {
1643 			mutex_enter(&new_freemem_lock);
1644 			/*
1645 			 * Check to see if some other thread
1646 			 * is actually waiting.  Another bucket
1647 			 * may have woken it up by now.  If there
1648 			 * are no waiters, then set our pcf_wait
1649 			 * count to zero to avoid coming in here
1650 			 * next time.
1651 			 */
1652 			if (freemem_wait) {
1653 				if (npages > 1) {
1654 					cv_broadcast(&freemem_cv);
1655 				} else {
1656 					cv_signal(&freemem_cv);
1657 				}
1658 				p->pcf_wait--;
1659 			} else {
1660 				p->pcf_wait = 0;
1661 			}
1662 			mutex_exit(&new_freemem_lock);
1663 		}
1664 		mutex_exit(&p->pcf_lock);
1665 	}
1666 	ASSERT(npages == 0);
1667 }
1668 
1669 /*
1670  * A helper routine for page_create_get_something.
1671  * The indenting got to deep down there.
1672  * Unblock the pcf counters.  Any pages freed after
1673  * pcf_block got set are moved to pcf_count and
1674  * wakeups (cv_broadcast() or cv_signal()) are done as needed.
1675  */
1676 static void
1677 pcgs_unblock(void)
1678 {
1679 	int		i;
1680 	struct pcf	*p;
1681 
1682 	/* Update freemem while we're here. */
1683 	freemem = 0;
1684 	p = pcf;
1685 	for (i = 0; i < PCF_FANOUT; i++) {
1686 		mutex_enter(&p->pcf_lock);
1687 		ASSERT(p->pcf_count == 0);
1688 		p->pcf_count = p->pcf_reserve;
1689 		p->pcf_block = 0;
1690 		freemem += p->pcf_count;
1691 		if (p->pcf_wait) {
1692 			mutex_enter(&new_freemem_lock);
1693 			if (freemem_wait) {
1694 				if (p->pcf_reserve > 1) {
1695 					cv_broadcast(&freemem_cv);
1696 					p->pcf_wait = 0;
1697 				} else {
1698 					cv_signal(&freemem_cv);
1699 					p->pcf_wait--;
1700 				}
1701 			} else {
1702 				p->pcf_wait = 0;
1703 			}
1704 			mutex_exit(&new_freemem_lock);
1705 		}
1706 		p->pcf_reserve = 0;
1707 		mutex_exit(&p->pcf_lock);
1708 		p++;
1709 	}
1710 }
1711 
1712 /*
1713  * Called from page_create_va() when both the cache and free lists
1714  * have been checked once.
1715  *
1716  * Either returns a page or panics since the accounting was done
1717  * way before we got here.
1718  *
1719  * We don't come here often, so leave the accounting on permanently.
1720  */
1721 
1722 #define	MAX_PCGS	100
1723 
1724 #ifdef	DEBUG
1725 #define	PCGS_TRIES	100
1726 #else	/* DEBUG */
1727 #define	PCGS_TRIES	10
1728 #endif	/* DEBUG */
1729 
1730 #ifdef	VM_STATS
1731 uint_t	pcgs_counts[PCGS_TRIES];
1732 uint_t	pcgs_too_many;
1733 uint_t	pcgs_entered;
1734 uint_t	pcgs_entered_noreloc;
1735 uint_t	pcgs_locked;
1736 uint_t	pcgs_cagelocked;
1737 #endif	/* VM_STATS */
1738 
1739 static page_t *
1740 page_create_get_something(vnode_t *vp, u_offset_t off, struct seg *seg,
1741     caddr_t vaddr, uint_t flags)
1742 {
1743 	uint_t		count;
1744 	page_t		*pp;
1745 	uint_t		locked, i;
1746 	struct	pcf	*p;
1747 	lgrp_t		*lgrp;
1748 	int		cagelocked = 0;
1749 
1750 	VM_STAT_ADD(pcgs_entered);
1751 
1752 	/*
1753 	 * Tap any reserve freelists: if we fail now, we'll die
1754 	 * since the page(s) we're looking for have already been
1755 	 * accounted for.
1756 	 */
1757 	flags |= PG_PANIC;
1758 
1759 	if ((flags & PG_NORELOC) != 0) {
1760 		VM_STAT_ADD(pcgs_entered_noreloc);
1761 		/*
1762 		 * Requests for free pages from critical threads
1763 		 * such as pageout still won't throttle here, but
1764 		 * we must try again, to give the cageout thread
1765 		 * another chance to catch up. Since we already
1766 		 * accounted for the pages, we had better get them
1767 		 * this time.
1768 		 *
1769 		 * N.B. All non-critical threads acquire the pcgs_cagelock
1770 		 * to serialize access to the freelists. This implements a
1771 		 * turnstile-type synchornization to avoid starvation of
1772 		 * critical requests for PG_NORELOC memory by non-critical
1773 		 * threads: all non-critical threads must acquire a 'ticket'
1774 		 * before passing through, which entails making sure
1775 		 * kcage_freemem won't fall below minfree prior to grabbing
1776 		 * pages from the freelists.
1777 		 */
1778 		if (kcage_create_throttle(1, flags) == KCT_NONCRIT) {
1779 			mutex_enter(&pcgs_cagelock);
1780 			cagelocked = 1;
1781 			VM_STAT_ADD(pcgs_cagelocked);
1782 		}
1783 	}
1784 
1785 	/*
1786 	 * Time to get serious.
1787 	 * We failed to get a `correctly colored' page from both the
1788 	 * free and cache lists.
1789 	 * We escalate in stage.
1790 	 *
1791 	 * First try both lists without worring about color.
1792 	 *
1793 	 * Then, grab all page accounting locks (ie. pcf[]) and
1794 	 * steal any pages that they have and set the pcf_block flag to
1795 	 * stop deletions from the lists.  This will help because
1796 	 * a page can get added to the free list while we are looking
1797 	 * at the cache list, then another page could be added to the cache
1798 	 * list allowing the page on the free list to be removed as we
1799 	 * move from looking at the cache list to the free list. This
1800 	 * could happen over and over. We would never find the page
1801 	 * we have accounted for.
1802 	 *
1803 	 * Noreloc pages are a subset of the global (relocatable) page pool.
1804 	 * They are not tracked separately in the pcf bins, so it is
1805 	 * impossible to know when doing pcf accounting if the available
1806 	 * page(s) are noreloc pages or not. When looking for a noreloc page
1807 	 * it is quite easy to end up here even if the global (relocatable)
1808 	 * page pool has plenty of free pages but the noreloc pool is empty.
1809 	 *
1810 	 * When the noreloc pool is empty (or low), additional noreloc pages
1811 	 * are created by converting pages from the global page pool. This
1812 	 * process will stall during pcf accounting if the pcf bins are
1813 	 * already locked. Such is the case when a noreloc allocation is
1814 	 * looping here in page_create_get_something waiting for more noreloc
1815 	 * pages to appear.
1816 	 *
1817 	 * Short of adding a new field to the pcf bins to accurately track
1818 	 * the number of free noreloc pages, we instead do not grab the
1819 	 * pcgs_lock, do not set the pcf blocks and do not timeout when
1820 	 * allocating a noreloc page. This allows noreloc allocations to
1821 	 * loop without blocking global page pool allocations.
1822 	 *
1823 	 * NOTE: the behaviour of page_create_get_something has not changed
1824 	 * for the case of global page pool allocations.
1825 	 */
1826 
1827 	flags &= ~PG_MATCH_COLOR;
1828 	locked = 0;
1829 #if defined(__i386) || defined(__amd64)
1830 	flags = page_create_update_flags_x86(flags);
1831 #endif
1832 
1833 	lgrp = lgrp_mem_choose(seg, vaddr, PAGESIZE);
1834 
1835 	for (count = 0; kcage_on || count < MAX_PCGS; count++) {
1836 		pp = page_get_freelist(vp, off, seg, vaddr, PAGESIZE,
1837 		    flags, lgrp);
1838 		if (pp == NULL) {
1839 			pp = page_get_cachelist(vp, off, seg, vaddr,
1840 			    flags, lgrp);
1841 		}
1842 		if (pp == NULL) {
1843 			/*
1844 			 * Serialize.  Don't fight with other pcgs().
1845 			 */
1846 			if (!locked && (!kcage_on || !(flags & PG_NORELOC))) {
1847 				mutex_enter(&pcgs_lock);
1848 				VM_STAT_ADD(pcgs_locked);
1849 				locked = 1;
1850 				p = pcf;
1851 				for (i = 0; i < PCF_FANOUT; i++) {
1852 					mutex_enter(&p->pcf_lock);
1853 					ASSERT(p->pcf_block == 0);
1854 					p->pcf_block = 1;
1855 					p->pcf_reserve = p->pcf_count;
1856 					p->pcf_count = 0;
1857 					mutex_exit(&p->pcf_lock);
1858 					p++;
1859 				}
1860 				freemem = 0;
1861 			}
1862 
1863 			if (count) {
1864 				/*
1865 				 * Since page_free() puts pages on
1866 				 * a list then accounts for it, we
1867 				 * just have to wait for page_free()
1868 				 * to unlock any page it was working
1869 				 * with. The page_lock()-page_reclaim()
1870 				 * path falls in the same boat.
1871 				 *
1872 				 * We don't need to check on the
1873 				 * PG_WAIT flag, we have already
1874 				 * accounted for the page we are
1875 				 * looking for in page_create_va().
1876 				 *
1877 				 * We just wait a moment to let any
1878 				 * locked pages on the lists free up,
1879 				 * then continue around and try again.
1880 				 *
1881 				 * Will be awakened by set_freemem().
1882 				 */
1883 				mutex_enter(&pcgs_wait_lock);
1884 				cv_wait(&pcgs_cv, &pcgs_wait_lock);
1885 				mutex_exit(&pcgs_wait_lock);
1886 			}
1887 		} else {
1888 #ifdef VM_STATS
1889 			if (count >= PCGS_TRIES) {
1890 				VM_STAT_ADD(pcgs_too_many);
1891 			} else {
1892 				VM_STAT_ADD(pcgs_counts[count]);
1893 			}
1894 #endif
1895 			if (locked) {
1896 				pcgs_unblock();
1897 				mutex_exit(&pcgs_lock);
1898 			}
1899 			if (cagelocked)
1900 				mutex_exit(&pcgs_cagelock);
1901 			return (pp);
1902 		}
1903 	}
1904 	/*
1905 	 * we go down holding the pcf locks.
1906 	 */
1907 	panic("no %spage found %d",
1908 	    ((flags & PG_NORELOC) ? "non-reloc " : ""), count);
1909 	/*NOTREACHED*/
1910 }
1911 
1912 /*
1913  * Create enough pages for "bytes" worth of data starting at
1914  * "off" in "vp".
1915  *
1916  *	Where flag must be one of:
1917  *
1918  *		PG_EXCL:	Exclusive create (fail if any page already
1919  *				exists in the page cache) which does not
1920  *				wait for memory to become available.
1921  *
1922  *		PG_WAIT:	Non-exclusive create which can wait for
1923  *				memory to become available.
1924  *
1925  *		PG_PHYSCONTIG:	Allocate physically contiguous pages.
1926  *				(Not Supported)
1927  *
1928  * A doubly linked list of pages is returned to the caller.  Each page
1929  * on the list has the "exclusive" (p_selock) lock and "iolock" (p_iolock)
1930  * lock.
1931  *
1932  * Unable to change the parameters to page_create() in a minor release,
1933  * we renamed page_create() to page_create_va(), changed all known calls
1934  * from page_create() to page_create_va(), and created this wrapper.
1935  *
1936  * Upon a major release, we should break compatibility by deleting this
1937  * wrapper, and replacing all the strings "page_create_va", with "page_create".
1938  *
1939  * NOTE: There is a copy of this interface as page_create_io() in
1940  *	 i86/vm/vm_machdep.c. Any bugs fixed here should be applied
1941  *	 there.
1942  */
1943 page_t *
1944 page_create(vnode_t *vp, u_offset_t off, size_t bytes, uint_t flags)
1945 {
1946 	caddr_t random_vaddr;
1947 	struct seg kseg;
1948 
1949 #ifdef DEBUG
1950 	cmn_err(CE_WARN, "Using deprecated interface page_create: caller %p",
1951 	    (void *)caller());
1952 #endif
1953 
1954 	random_vaddr = (caddr_t)(((uintptr_t)vp >> 7) ^
1955 	    (uintptr_t)(off >> PAGESHIFT));
1956 	kseg.s_as = &kas;
1957 
1958 	return (page_create_va(vp, off, bytes, flags, &kseg, random_vaddr));
1959 }
1960 
1961 #ifdef DEBUG
1962 uint32_t pg_alloc_pgs_mtbf = 0;
1963 #endif
1964 
1965 /*
1966  * Used for large page support. It will attempt to allocate
1967  * a large page(s) off the freelist.
1968  *
1969  * Returns non zero on failure.
1970  */
1971 int
1972 page_alloc_pages(struct vnode *vp, struct seg *seg, caddr_t addr,
1973     page_t **basepp, page_t *ppa[], uint_t szc, int anypgsz, int pgflags)
1974 {
1975 	pgcnt_t		npgs, curnpgs, totpgs;
1976 	size_t		pgsz;
1977 	page_t		*pplist = NULL, *pp;
1978 	int		err = 0;
1979 	lgrp_t		*lgrp;
1980 
1981 	ASSERT(szc != 0 && szc <= (page_num_pagesizes() - 1));
1982 	ASSERT(pgflags == 0 || pgflags == PG_LOCAL);
1983 
1984 	VM_STAT_ADD(alloc_pages[0]);
1985 
1986 #ifdef DEBUG
1987 	if (pg_alloc_pgs_mtbf && !(gethrtime() % pg_alloc_pgs_mtbf)) {
1988 		return (ENOMEM);
1989 	}
1990 #endif
1991 
1992 	/*
1993 	 * One must be NULL but not both.
1994 	 * And one must be non NULL but not both.
1995 	 */
1996 	ASSERT(basepp != NULL || ppa != NULL);
1997 	ASSERT(basepp == NULL || ppa == NULL);
1998 
1999 #if defined(__i386) || defined(__amd64)
2000 	while (page_chk_freelist(szc) == 0) {
2001 		VM_STAT_ADD(alloc_pages[8]);
2002 		if (anypgsz == 0 || --szc == 0)
2003 			return (ENOMEM);
2004 	}
2005 #endif
2006 
2007 	pgsz = page_get_pagesize(szc);
2008 	totpgs = curnpgs = npgs = pgsz >> PAGESHIFT;
2009 
2010 	ASSERT(((uintptr_t)addr & (pgsz - 1)) == 0);
2011 
2012 	(void) page_create_wait(npgs, PG_WAIT);
2013 
2014 	while (npgs && szc) {
2015 		lgrp = lgrp_mem_choose(seg, addr, pgsz);
2016 		if (pgflags == PG_LOCAL) {
2017 			pp = page_get_freelist(vp, 0, seg, addr, pgsz,
2018 			    pgflags, lgrp);
2019 			if (pp == NULL) {
2020 				pp = page_get_freelist(vp, 0, seg, addr, pgsz,
2021 				    0, lgrp);
2022 			}
2023 		} else {
2024 			pp = page_get_freelist(vp, 0, seg, addr, pgsz,
2025 			    0, lgrp);
2026 		}
2027 		if (pp != NULL) {
2028 			VM_STAT_ADD(alloc_pages[1]);
2029 			page_list_concat(&pplist, &pp);
2030 			ASSERT(npgs >= curnpgs);
2031 			npgs -= curnpgs;
2032 		} else if (anypgsz) {
2033 			VM_STAT_ADD(alloc_pages[2]);
2034 			szc--;
2035 			pgsz = page_get_pagesize(szc);
2036 			curnpgs = pgsz >> PAGESHIFT;
2037 		} else {
2038 			VM_STAT_ADD(alloc_pages[3]);
2039 			ASSERT(npgs == totpgs);
2040 			page_create_putback(npgs);
2041 			return (ENOMEM);
2042 		}
2043 	}
2044 	if (szc == 0) {
2045 		VM_STAT_ADD(alloc_pages[4]);
2046 		ASSERT(npgs != 0);
2047 		page_create_putback(npgs);
2048 		err = ENOMEM;
2049 	} else if (basepp != NULL) {
2050 		ASSERT(npgs == 0);
2051 		ASSERT(ppa == NULL);
2052 		*basepp = pplist;
2053 	}
2054 
2055 	npgs = totpgs - npgs;
2056 	pp = pplist;
2057 
2058 	/*
2059 	 * Clear the free and age bits. Also if we were passed in a ppa then
2060 	 * fill it in with all the constituent pages from the large page. But
2061 	 * if we failed to allocate all the pages just free what we got.
2062 	 */
2063 	while (npgs != 0) {
2064 		ASSERT(PP_ISFREE(pp));
2065 		ASSERT(PP_ISAGED(pp));
2066 		if (ppa != NULL || err != 0) {
2067 			if (err == 0) {
2068 				VM_STAT_ADD(alloc_pages[5]);
2069 				PP_CLRFREE(pp);
2070 				PP_CLRAGED(pp);
2071 				page_sub(&pplist, pp);
2072 				*ppa++ = pp;
2073 				npgs--;
2074 			} else {
2075 				VM_STAT_ADD(alloc_pages[6]);
2076 				ASSERT(pp->p_szc != 0);
2077 				curnpgs = page_get_pagecnt(pp->p_szc);
2078 				page_list_break(&pp, &pplist, curnpgs);
2079 				page_list_add_pages(pp, 0);
2080 				page_create_putback(curnpgs);
2081 				ASSERT(npgs >= curnpgs);
2082 				npgs -= curnpgs;
2083 			}
2084 			pp = pplist;
2085 		} else {
2086 			VM_STAT_ADD(alloc_pages[7]);
2087 			PP_CLRFREE(pp);
2088 			PP_CLRAGED(pp);
2089 			pp = pp->p_next;
2090 			npgs--;
2091 		}
2092 	}
2093 	return (err);
2094 }
2095 
2096 /*
2097  * Get a single large page off of the freelists, and set it up for use.
2098  * Number of bytes requested must be a supported page size.
2099  *
2100  * Note that this call may fail even if there is sufficient
2101  * memory available or PG_WAIT is set, so the caller must
2102  * be willing to fallback on page_create_va(), block and retry,
2103  * or fail the requester.
2104  */
2105 page_t *
2106 page_create_va_large(vnode_t *vp, u_offset_t off, size_t bytes, uint_t flags,
2107     struct seg *seg, caddr_t vaddr, void *arg)
2108 {
2109 	pgcnt_t		npages, pcftotal;
2110 	page_t		*pp;
2111 	page_t		*rootpp;
2112 	lgrp_t		*lgrp;
2113 	uint_t		enough;
2114 	uint_t		pcf_index;
2115 	uint_t		i;
2116 	struct pcf	*p;
2117 	struct pcf	*q;
2118 	lgrp_id_t	*lgrpid = (lgrp_id_t *)arg;
2119 
2120 	ASSERT(vp != NULL);
2121 
2122 	ASSERT((flags & ~(PG_EXCL | PG_WAIT |
2123 	    PG_NORELOC | PG_PANIC | PG_PUSHPAGE)) == 0);
2124 	/* but no others */
2125 
2126 	ASSERT((flags & PG_EXCL) == PG_EXCL);
2127 
2128 	npages = btop(bytes);
2129 
2130 	if (!kcage_on || panicstr) {
2131 		/*
2132 		 * Cage is OFF, or we are single threaded in
2133 		 * panic, so make everything a RELOC request.
2134 		 */
2135 		flags &= ~PG_NORELOC;
2136 	}
2137 
2138 	/*
2139 	 * Make sure there's adequate physical memory available.
2140 	 * Note: PG_WAIT is ignored here.
2141 	 */
2142 	if (freemem <= throttlefree + npages) {
2143 		VM_STAT_ADD(page_create_large_cnt[1]);
2144 		return (NULL);
2145 	}
2146 
2147 	/*
2148 	 * If cage is on, dampen draw from cage when available
2149 	 * cage space is low.
2150 	 */
2151 	if ((flags & (PG_NORELOC | PG_WAIT)) ==  (PG_NORELOC | PG_WAIT) &&
2152 	    kcage_freemem < kcage_throttlefree + npages) {
2153 
2154 		/*
2155 		 * The cage is on, the caller wants PG_NORELOC
2156 		 * pages and available cage memory is very low.
2157 		 * Call kcage_create_throttle() to attempt to
2158 		 * control demand on the cage.
2159 		 */
2160 		if (kcage_create_throttle(npages, flags) == KCT_FAILURE) {
2161 			VM_STAT_ADD(page_create_large_cnt[2]);
2162 			return (NULL);
2163 		}
2164 	}
2165 
2166 	enough = 0;
2167 	pcf_index = PCF_INDEX();
2168 	p = &pcf[pcf_index];
2169 	q = &pcf[PCF_FANOUT];
2170 	for (pcftotal = 0, i = 0; i < PCF_FANOUT; i++) {
2171 		if (p->pcf_count > npages) {
2172 			/*
2173 			 * a good one to try.
2174 			 */
2175 			mutex_enter(&p->pcf_lock);
2176 			if (p->pcf_count > npages) {
2177 				p->pcf_count -= (uint_t)npages;
2178 				/*
2179 				 * freemem is not protected by any lock.
2180 				 * Thus, we cannot have any assertion
2181 				 * containing freemem here.
2182 				 */
2183 				freemem -= npages;
2184 				enough = 1;
2185 				mutex_exit(&p->pcf_lock);
2186 				break;
2187 			}
2188 			mutex_exit(&p->pcf_lock);
2189 		}
2190 		pcftotal += p->pcf_count;
2191 		p++;
2192 		if (p >= q) {
2193 			p = pcf;
2194 		}
2195 	}
2196 
2197 	if (!enough) {
2198 		/* If there isn't enough memory available, give up. */
2199 		if (pcftotal < npages) {
2200 			VM_STAT_ADD(page_create_large_cnt[3]);
2201 			return (NULL);
2202 		}
2203 
2204 		/* try to collect pages from several pcf bins */
2205 		for (p = pcf, pcftotal = 0, i = 0; i < PCF_FANOUT; i++) {
2206 			mutex_enter(&p->pcf_lock);
2207 			pcftotal += p->pcf_count;
2208 			if (pcftotal >= npages) {
2209 				/*
2210 				 * Wow!  There are enough pages laying around
2211 				 * to satisfy the request.  Do the accounting,
2212 				 * drop the locks we acquired, and go back.
2213 				 *
2214 				 * freemem is not protected by any lock. So,
2215 				 * we cannot have any assertion containing
2216 				 * freemem.
2217 				 */
2218 				pgcnt_t	tpages = npages;
2219 				freemem -= npages;
2220 				while (p >= pcf) {
2221 					if (p->pcf_count <= tpages) {
2222 						tpages -= p->pcf_count;
2223 						p->pcf_count = 0;
2224 					} else {
2225 						p->pcf_count -= (uint_t)tpages;
2226 						tpages = 0;
2227 					}
2228 					mutex_exit(&p->pcf_lock);
2229 					p--;
2230 				}
2231 				ASSERT(tpages == 0);
2232 				break;
2233 			}
2234 			p++;
2235 		}
2236 		if (i == PCF_FANOUT) {
2237 			/* failed to collect pages - release the locks */
2238 			while (--p >= pcf) {
2239 				mutex_exit(&p->pcf_lock);
2240 			}
2241 			VM_STAT_ADD(page_create_large_cnt[4]);
2242 			return (NULL);
2243 		}
2244 	}
2245 
2246 	/*
2247 	 * This is where this function behaves fundamentally differently
2248 	 * than page_create_va(); since we're intending to map the page
2249 	 * with a single TTE, we have to get it as a physically contiguous
2250 	 * hardware pagesize chunk.  If we can't, we fail.
2251 	 */
2252 	if (lgrpid != NULL && *lgrpid >= 0 && *lgrpid <= lgrp_alloc_max &&
2253 	    LGRP_EXISTS(lgrp_table[*lgrpid]))
2254 		lgrp = lgrp_table[*lgrpid];
2255 	else
2256 		lgrp = lgrp_mem_choose(seg, vaddr, bytes);
2257 
2258 	if ((rootpp = page_get_freelist(&kvp, off, seg, vaddr,
2259 	    bytes, flags & ~PG_MATCH_COLOR, lgrp)) == NULL) {
2260 		page_create_putback(npages);
2261 		VM_STAT_ADD(page_create_large_cnt[5]);
2262 		return (NULL);
2263 	}
2264 
2265 	/*
2266 	 * if we got the page with the wrong mtype give it back this is a
2267 	 * workaround for CR 6249718. When CR 6249718 is fixed we never get
2268 	 * inside "if" and the workaround becomes just a nop
2269 	 */
2270 	if (kcage_on && (flags & PG_NORELOC) && !PP_ISNORELOC(rootpp)) {
2271 		page_list_add_pages(rootpp, 0);
2272 		page_create_putback(npages);
2273 		VM_STAT_ADD(page_create_large_cnt[6]);
2274 		return (NULL);
2275 	}
2276 
2277 	/*
2278 	 * If satisfying this request has left us with too little
2279 	 * memory, start the wheels turning to get some back.  The
2280 	 * first clause of the test prevents waking up the pageout
2281 	 * daemon in situations where it would decide that there's
2282 	 * nothing to do.
2283 	 */
2284 	if (nscan < desscan && freemem < minfree) {
2285 		TRACE_1(TR_FAC_VM, TR_PAGEOUT_CV_SIGNAL,
2286 		    "pageout_cv_signal:freemem %ld", freemem);
2287 		cv_signal(&proc_pageout->p_cv);
2288 	}
2289 
2290 	pp = rootpp;
2291 	while (npages--) {
2292 		ASSERT(PAGE_EXCL(pp));
2293 		ASSERT(pp->p_vnode == NULL);
2294 		ASSERT(!hat_page_is_mapped(pp));
2295 		PP_CLRFREE(pp);
2296 		PP_CLRAGED(pp);
2297 		if (!page_hashin(pp, vp, off, NULL))
2298 			panic("page_create_large: hashin failed: page %p",
2299 			    (void *)pp);
2300 		page_io_lock(pp);
2301 		off += PAGESIZE;
2302 		pp = pp->p_next;
2303 	}
2304 
2305 	VM_STAT_ADD(page_create_large_cnt[0]);
2306 	return (rootpp);
2307 }
2308 
2309 page_t *
2310 page_create_va(vnode_t *vp, u_offset_t off, size_t bytes, uint_t flags,
2311     struct seg *seg, caddr_t vaddr)
2312 {
2313 	page_t		*plist = NULL;
2314 	pgcnt_t		npages;
2315 	pgcnt_t		found_on_free = 0;
2316 	pgcnt_t		pages_req;
2317 	page_t		*npp = NULL;
2318 	uint_t		enough;
2319 	uint_t		i;
2320 	uint_t		pcf_index;
2321 	struct pcf	*p;
2322 	struct pcf	*q;
2323 	lgrp_t		*lgrp;
2324 
2325 	TRACE_4(TR_FAC_VM, TR_PAGE_CREATE_START,
2326 	    "page_create_start:vp %p off %llx bytes %lu flags %x",
2327 	    vp, off, bytes, flags);
2328 
2329 	ASSERT(bytes != 0 && vp != NULL);
2330 
2331 	if ((flags & PG_EXCL) == 0 && (flags & PG_WAIT) == 0) {
2332 		panic("page_create: invalid flags");
2333 		/*NOTREACHED*/
2334 	}
2335 	ASSERT((flags & ~(PG_EXCL | PG_WAIT |
2336 	    PG_NORELOC | PG_PANIC | PG_PUSHPAGE)) == 0);
2337 	    /* but no others */
2338 
2339 	pages_req = npages = btopr(bytes);
2340 	/*
2341 	 * Try to see whether request is too large to *ever* be
2342 	 * satisfied, in order to prevent deadlock.  We arbitrarily
2343 	 * decide to limit maximum size requests to max_page_get.
2344 	 */
2345 	if (npages >= max_page_get) {
2346 		if ((flags & PG_WAIT) == 0) {
2347 			TRACE_4(TR_FAC_VM, TR_PAGE_CREATE_TOOBIG,
2348 			    "page_create_toobig:vp %p off %llx npages "
2349 			    "%lu max_page_get %lu",
2350 			    vp, off, npages, max_page_get);
2351 			return (NULL);
2352 		} else {
2353 			cmn_err(CE_WARN,
2354 			    "Request for too much kernel memory "
2355 			    "(%lu bytes), will hang forever", bytes);
2356 			for (;;)
2357 				delay(1000000000);
2358 		}
2359 	}
2360 
2361 	if (!kcage_on || panicstr) {
2362 		/*
2363 		 * Cage is OFF, or we are single threaded in
2364 		 * panic, so make everything a RELOC request.
2365 		 */
2366 		flags &= ~PG_NORELOC;
2367 	}
2368 
2369 	if (freemem <= throttlefree + npages)
2370 		if (!page_create_throttle(npages, flags))
2371 			return (NULL);
2372 
2373 	/*
2374 	 * If cage is on, dampen draw from cage when available
2375 	 * cage space is low.
2376 	 */
2377 	if ((flags & PG_NORELOC) &&
2378 	    kcage_freemem < kcage_throttlefree + npages) {
2379 
2380 		/*
2381 		 * The cage is on, the caller wants PG_NORELOC
2382 		 * pages and available cage memory is very low.
2383 		 * Call kcage_create_throttle() to attempt to
2384 		 * control demand on the cage.
2385 		 */
2386 		if (kcage_create_throttle(npages, flags) == KCT_FAILURE)
2387 			return (NULL);
2388 	}
2389 
2390 	VM_STAT_ADD(page_create_cnt[0]);
2391 
2392 	enough = 0;
2393 	pcf_index = PCF_INDEX();
2394 
2395 	p = &pcf[pcf_index];
2396 	q = &pcf[PCF_FANOUT];
2397 	for (i = 0; i < PCF_FANOUT; i++) {
2398 		if (p->pcf_count > npages) {
2399 			/*
2400 			 * a good one to try.
2401 			 */
2402 			mutex_enter(&p->pcf_lock);
2403 			if (p->pcf_count > npages) {
2404 				p->pcf_count -= (uint_t)npages;
2405 				/*
2406 				 * freemem is not protected by any lock.
2407 				 * Thus, we cannot have any assertion
2408 				 * containing freemem here.
2409 				 */
2410 				freemem -= npages;
2411 				enough = 1;
2412 				mutex_exit(&p->pcf_lock);
2413 				break;
2414 			}
2415 			mutex_exit(&p->pcf_lock);
2416 		}
2417 		p++;
2418 		if (p >= q) {
2419 			p = pcf;
2420 		}
2421 	}
2422 
2423 	if (!enough) {
2424 		/*
2425 		 * Have to look harder.  If npages is greater than
2426 		 * one, then we might have to coalesce the counters.
2427 		 *
2428 		 * Go wait.  We come back having accounted
2429 		 * for the memory.
2430 		 */
2431 		VM_STAT_ADD(page_create_cnt[1]);
2432 		if (!page_create_wait(npages, flags)) {
2433 			VM_STAT_ADD(page_create_cnt[2]);
2434 			return (NULL);
2435 		}
2436 	}
2437 
2438 	TRACE_2(TR_FAC_VM, TR_PAGE_CREATE_SUCCESS,
2439 	    "page_create_success:vp %p off %llx", vp, off);
2440 
2441 	/*
2442 	 * If satisfying this request has left us with too little
2443 	 * memory, start the wheels turning to get some back.  The
2444 	 * first clause of the test prevents waking up the pageout
2445 	 * daemon in situations where it would decide that there's
2446 	 * nothing to do.
2447 	 */
2448 	if (nscan < desscan && freemem < minfree) {
2449 		TRACE_1(TR_FAC_VM, TR_PAGEOUT_CV_SIGNAL,
2450 		    "pageout_cv_signal:freemem %ld", freemem);
2451 		cv_signal(&proc_pageout->p_cv);
2452 	}
2453 
2454 	/*
2455 	 * Loop around collecting the requested number of pages.
2456 	 * Most of the time, we have to `create' a new page. With
2457 	 * this in mind, pull the page off the free list before
2458 	 * getting the hash lock.  This will minimize the hash
2459 	 * lock hold time, nesting, and the like.  If it turns
2460 	 * out we don't need the page, we put it back at the end.
2461 	 */
2462 	while (npages--) {
2463 		page_t		*pp;
2464 		kmutex_t	*phm = NULL;
2465 		ulong_t		index;
2466 
2467 		index = PAGE_HASH_FUNC(vp, off);
2468 top:
2469 		ASSERT(phm == NULL);
2470 		ASSERT(index == PAGE_HASH_FUNC(vp, off));
2471 		ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(vp)));
2472 
2473 		if (npp == NULL) {
2474 			/*
2475 			 * Try to get a page from the freelist (ie,
2476 			 * a page with no [vp, off] tag).  If that
2477 			 * fails, use the cachelist.
2478 			 *
2479 			 * During the first attempt at both the free
2480 			 * and cache lists we try for the correct color.
2481 			 */
2482 			/*
2483 			 * XXXX-how do we deal with virtual indexed
2484 			 * caches and and colors?
2485 			 */
2486 			VM_STAT_ADD(page_create_cnt[4]);
2487 			/*
2488 			 * Get lgroup to allocate next page of shared memory
2489 			 * from and use it to specify where to allocate
2490 			 * the physical memory
2491 			 */
2492 			lgrp = lgrp_mem_choose(seg, vaddr, PAGESIZE);
2493 			npp = page_get_freelist(vp, off, seg, vaddr, PAGESIZE,
2494 			    flags | PG_MATCH_COLOR, lgrp);
2495 			if (npp == NULL) {
2496 				npp = page_get_cachelist(vp, off, seg,
2497 				    vaddr, flags | PG_MATCH_COLOR, lgrp);
2498 				if (npp == NULL) {
2499 					npp = page_create_get_something(vp,
2500 					    off, seg, vaddr,
2501 					    flags & ~PG_MATCH_COLOR);
2502 				}
2503 
2504 				if (PP_ISAGED(npp) == 0) {
2505 					/*
2506 					 * Since this page came from the
2507 					 * cachelist, we must destroy the
2508 					 * old vnode association.
2509 					 */
2510 					page_hashout(npp, NULL);
2511 				}
2512 			}
2513 		}
2514 
2515 		/*
2516 		 * We own this page!
2517 		 */
2518 		ASSERT(PAGE_EXCL(npp));
2519 		ASSERT(npp->p_vnode == NULL);
2520 		ASSERT(!hat_page_is_mapped(npp));
2521 		PP_CLRFREE(npp);
2522 		PP_CLRAGED(npp);
2523 
2524 		/*
2525 		 * Here we have a page in our hot little mits and are
2526 		 * just waiting to stuff it on the appropriate lists.
2527 		 * Get the mutex and check to see if it really does
2528 		 * not exist.
2529 		 */
2530 		phm = PAGE_HASH_MUTEX(index);
2531 		mutex_enter(phm);
2532 		PAGE_HASH_SEARCH(index, pp, vp, off);
2533 		if (pp == NULL) {
2534 			VM_STAT_ADD(page_create_new);
2535 			pp = npp;
2536 			npp = NULL;
2537 			if (!page_hashin(pp, vp, off, phm)) {
2538 				/*
2539 				 * Since we hold the page hash mutex and
2540 				 * just searched for this page, page_hashin
2541 				 * had better not fail.  If it does, that
2542 				 * means somethread did not follow the
2543 				 * page hash mutex rules.  Panic now and
2544 				 * get it over with.  As usual, go down
2545 				 * holding all the locks.
2546 				 */
2547 				ASSERT(MUTEX_HELD(phm));
2548 				panic("page_create: "
2549 				    "hashin failed %p %p %llx %p",
2550 				    (void *)pp, (void *)vp, off, (void *)phm);
2551 				/*NOTREACHED*/
2552 			}
2553 			ASSERT(MUTEX_HELD(phm));
2554 			mutex_exit(phm);
2555 			phm = NULL;
2556 
2557 			/*
2558 			 * Hat layer locking need not be done to set
2559 			 * the following bits since the page is not hashed
2560 			 * and was on the free list (i.e., had no mappings).
2561 			 *
2562 			 * Set the reference bit to protect
2563 			 * against immediate pageout
2564 			 *
2565 			 * XXXmh modify freelist code to set reference
2566 			 * bit so we don't have to do it here.
2567 			 */
2568 			page_set_props(pp, P_REF);
2569 			found_on_free++;
2570 		} else {
2571 			VM_STAT_ADD(page_create_exists);
2572 			if (flags & PG_EXCL) {
2573 				/*
2574 				 * Found an existing page, and the caller
2575 				 * wanted all new pages.  Undo all of the work
2576 				 * we have done.
2577 				 */
2578 				mutex_exit(phm);
2579 				phm = NULL;
2580 				while (plist != NULL) {
2581 					pp = plist;
2582 					page_sub(&plist, pp);
2583 					page_io_unlock(pp);
2584 					/* large pages should not end up here */
2585 					ASSERT(pp->p_szc == 0);
2586 					/*LINTED: constant in conditional ctx*/
2587 					VN_DISPOSE(pp, B_INVAL, 0, kcred);
2588 				}
2589 				VM_STAT_ADD(page_create_found_one);
2590 				goto fail;
2591 			}
2592 			ASSERT(flags & PG_WAIT);
2593 			if (!page_lock(pp, SE_EXCL, phm, P_NO_RECLAIM)) {
2594 				/*
2595 				 * Start all over again if we blocked trying
2596 				 * to lock the page.
2597 				 */
2598 				mutex_exit(phm);
2599 				VM_STAT_ADD(page_create_page_lock_failed);
2600 				phm = NULL;
2601 				goto top;
2602 			}
2603 			mutex_exit(phm);
2604 			phm = NULL;
2605 
2606 			if (PP_ISFREE(pp)) {
2607 				ASSERT(PP_ISAGED(pp) == 0);
2608 				VM_STAT_ADD(pagecnt.pc_get_cache);
2609 				page_list_sub(pp, PG_CACHE_LIST);
2610 				PP_CLRFREE(pp);
2611 				found_on_free++;
2612 			}
2613 		}
2614 
2615 		/*
2616 		 * Got a page!  It is locked.  Acquire the i/o
2617 		 * lock since we are going to use the p_next and
2618 		 * p_prev fields to link the requested pages together.
2619 		 */
2620 		page_io_lock(pp);
2621 		page_add(&plist, pp);
2622 		plist = plist->p_next;
2623 		off += PAGESIZE;
2624 		vaddr += PAGESIZE;
2625 	}
2626 
2627 	ASSERT((flags & PG_EXCL) ? (found_on_free == pages_req) : 1);
2628 fail:
2629 	if (npp != NULL) {
2630 		/*
2631 		 * Did not need this page after all.
2632 		 * Put it back on the free list.
2633 		 */
2634 		VM_STAT_ADD(page_create_putbacks);
2635 		PP_SETFREE(npp);
2636 		PP_SETAGED(npp);
2637 		npp->p_offset = (u_offset_t)-1;
2638 		page_list_add(npp, PG_FREE_LIST | PG_LIST_TAIL);
2639 		page_unlock(npp);
2640 
2641 	}
2642 
2643 	ASSERT(pages_req >= found_on_free);
2644 
2645 	{
2646 		uint_t overshoot = (uint_t)(pages_req - found_on_free);
2647 
2648 		if (overshoot) {
2649 			VM_STAT_ADD(page_create_overshoot);
2650 			p = &pcf[pcf_index];
2651 			mutex_enter(&p->pcf_lock);
2652 			if (p->pcf_block) {
2653 				p->pcf_reserve += overshoot;
2654 			} else {
2655 				p->pcf_count += overshoot;
2656 				if (p->pcf_wait) {
2657 					mutex_enter(&new_freemem_lock);
2658 					if (freemem_wait) {
2659 						cv_signal(&freemem_cv);
2660 						p->pcf_wait--;
2661 					} else {
2662 						p->pcf_wait = 0;
2663 					}
2664 					mutex_exit(&new_freemem_lock);
2665 				}
2666 			}
2667 			mutex_exit(&p->pcf_lock);
2668 			/* freemem is approximate, so this test OK */
2669 			if (!p->pcf_block)
2670 				freemem += overshoot;
2671 		}
2672 	}
2673 
2674 	return (plist);
2675 }
2676 
2677 /*
2678  * One or more constituent pages of this large page has been marked
2679  * toxic. Simply demote the large page to PAGESIZE pages and let
2680  * page_free() handle it. This routine should only be called by
2681  * large page free routines (page_free_pages() and page_destroy_pages().
2682  * All pages are locked SE_EXCL and have already been marked free.
2683  */
2684 static void
2685 page_free_toxic_pages(page_t *rootpp)
2686 {
2687 	page_t	*tpp;
2688 	pgcnt_t	i, pgcnt = page_get_pagecnt(rootpp->p_szc);
2689 	uint_t	szc = rootpp->p_szc;
2690 
2691 	for (i = 0, tpp = rootpp; i < pgcnt; i++, tpp = tpp->p_next) {
2692 		ASSERT(tpp->p_szc == szc);
2693 		ASSERT((PAGE_EXCL(tpp) &&
2694 		    !page_iolock_assert(tpp)) || panicstr);
2695 		tpp->p_szc = 0;
2696 	}
2697 
2698 	while (rootpp != NULL) {
2699 		tpp = rootpp;
2700 		page_sub(&rootpp, tpp);
2701 		ASSERT(PP_ISFREE(tpp));
2702 		PP_CLRFREE(tpp);
2703 		page_free(tpp, 1);
2704 	}
2705 }
2706 
2707 /*
2708  * Put page on the "free" list.
2709  * The free list is really two lists maintained by
2710  * the PSM of whatever machine we happen to be on.
2711  */
2712 void
2713 page_free(page_t *pp, int dontneed)
2714 {
2715 	struct pcf	*p;
2716 	uint_t		pcf_index;
2717 
2718 	ASSERT((PAGE_EXCL(pp) &&
2719 	    !page_iolock_assert(pp)) || panicstr);
2720 
2721 	if (PP_ISFREE(pp)) {
2722 		panic("page_free: page %p is free", (void *)pp);
2723 	}
2724 
2725 	if (pp->p_szc != 0) {
2726 		if (pp->p_vnode == NULL || IS_SWAPFSVP(pp->p_vnode) ||
2727 		    PP_ISKAS(pp)) {
2728 			panic("page_free: anon or kernel "
2729 			    "or no vnode large page %p", (void *)pp);
2730 		}
2731 		page_demote_vp_pages(pp);
2732 		ASSERT(pp->p_szc == 0);
2733 	}
2734 
2735 	/*
2736 	 * The page_struct_lock need not be acquired to examine these
2737 	 * fields since the page has an "exclusive" lock.
2738 	 */
2739 	if (hat_page_is_mapped(pp) || pp->p_lckcnt != 0 || pp->p_cowcnt != 0 ||
2740 	    pp->p_slckcnt != 0) {
2741 		panic("page_free pp=%p, pfn=%lx, lckcnt=%d, cowcnt=%d "
2742 		    "slckcnt = %d", pp, page_pptonum(pp), pp->p_lckcnt,
2743 		    pp->p_cowcnt, pp->p_slckcnt);
2744 		/*NOTREACHED*/
2745 	}
2746 
2747 	ASSERT(!hat_page_getshare(pp));
2748 
2749 	PP_SETFREE(pp);
2750 	ASSERT(pp->p_vnode == NULL || !IS_VMODSORT(pp->p_vnode) ||
2751 	    !hat_ismod(pp));
2752 	page_clr_all_props(pp);
2753 	ASSERT(!hat_page_getshare(pp));
2754 
2755 	/*
2756 	 * Now we add the page to the head of the free list.
2757 	 * But if this page is associated with a paged vnode
2758 	 * then we adjust the head forward so that the page is
2759 	 * effectively at the end of the list.
2760 	 */
2761 	if (pp->p_vnode == NULL) {
2762 		/*
2763 		 * Page has no identity, put it on the free list.
2764 		 */
2765 		PP_SETAGED(pp);
2766 		pp->p_offset = (u_offset_t)-1;
2767 		page_list_add(pp, PG_FREE_LIST | PG_LIST_TAIL);
2768 		VM_STAT_ADD(pagecnt.pc_free_free);
2769 		TRACE_1(TR_FAC_VM, TR_PAGE_FREE_FREE,
2770 		    "page_free_free:pp %p", pp);
2771 	} else {
2772 		PP_CLRAGED(pp);
2773 
2774 		if (!dontneed || nopageage) {
2775 			/* move it to the tail of the list */
2776 			page_list_add(pp, PG_CACHE_LIST | PG_LIST_TAIL);
2777 
2778 			VM_STAT_ADD(pagecnt.pc_free_cache);
2779 			TRACE_1(TR_FAC_VM, TR_PAGE_FREE_CACHE_TAIL,
2780 			    "page_free_cache_tail:pp %p", pp);
2781 		} else {
2782 			page_list_add(pp, PG_CACHE_LIST | PG_LIST_HEAD);
2783 
2784 			VM_STAT_ADD(pagecnt.pc_free_dontneed);
2785 			TRACE_1(TR_FAC_VM, TR_PAGE_FREE_CACHE_HEAD,
2786 			    "page_free_cache_head:pp %p", pp);
2787 		}
2788 	}
2789 	page_unlock(pp);
2790 
2791 	/*
2792 	 * Now do the `freemem' accounting.
2793 	 */
2794 	pcf_index = PCF_INDEX();
2795 	p = &pcf[pcf_index];
2796 
2797 	mutex_enter(&p->pcf_lock);
2798 	if (p->pcf_block) {
2799 		p->pcf_reserve += 1;
2800 	} else {
2801 		p->pcf_count += 1;
2802 		if (p->pcf_wait) {
2803 			mutex_enter(&new_freemem_lock);
2804 			/*
2805 			 * Check to see if some other thread
2806 			 * is actually waiting.  Another bucket
2807 			 * may have woken it up by now.  If there
2808 			 * are no waiters, then set our pcf_wait
2809 			 * count to zero to avoid coming in here
2810 			 * next time.  Also, since only one page
2811 			 * was put on the free list, just wake
2812 			 * up one waiter.
2813 			 */
2814 			if (freemem_wait) {
2815 				cv_signal(&freemem_cv);
2816 				p->pcf_wait--;
2817 			} else {
2818 				p->pcf_wait = 0;
2819 			}
2820 			mutex_exit(&new_freemem_lock);
2821 		}
2822 	}
2823 	mutex_exit(&p->pcf_lock);
2824 
2825 	/* freemem is approximate, so this test OK */
2826 	if (!p->pcf_block)
2827 		freemem += 1;
2828 }
2829 
2830 /*
2831  * Put page on the "free" list during intial startup.
2832  * This happens during initial single threaded execution.
2833  */
2834 void
2835 page_free_at_startup(page_t *pp)
2836 {
2837 	struct pcf	*p;
2838 	uint_t		pcf_index;
2839 
2840 	page_list_add(pp, PG_FREE_LIST | PG_LIST_HEAD | PG_LIST_ISINIT);
2841 	VM_STAT_ADD(pagecnt.pc_free_free);
2842 
2843 	/*
2844 	 * Now do the `freemem' accounting.
2845 	 */
2846 	pcf_index = PCF_INDEX();
2847 	p = &pcf[pcf_index];
2848 
2849 	ASSERT(p->pcf_block == 0);
2850 	ASSERT(p->pcf_wait == 0);
2851 	p->pcf_count += 1;
2852 
2853 	/* freemem is approximate, so this is OK */
2854 	freemem += 1;
2855 }
2856 
2857 void
2858 page_free_pages(page_t *pp)
2859 {
2860 	page_t	*tpp, *rootpp = NULL;
2861 	pgcnt_t	pgcnt = page_get_pagecnt(pp->p_szc);
2862 	pgcnt_t	i;
2863 	uint_t	szc = pp->p_szc;
2864 
2865 	VM_STAT_ADD(pagecnt.pc_free_pages);
2866 	TRACE_1(TR_FAC_VM, TR_PAGE_FREE_FREE,
2867 	    "page_free_free:pp %p", pp);
2868 
2869 	ASSERT(pp->p_szc != 0 && pp->p_szc < page_num_pagesizes());
2870 	if ((page_pptonum(pp) & (pgcnt - 1)) != 0) {
2871 		panic("page_free_pages: not root page %p", (void *)pp);
2872 		/*NOTREACHED*/
2873 	}
2874 
2875 	for (i = 0, tpp = pp; i < pgcnt; i++, tpp++) {
2876 		ASSERT((PAGE_EXCL(tpp) &&
2877 		    !page_iolock_assert(tpp)) || panicstr);
2878 		if (PP_ISFREE(tpp)) {
2879 			panic("page_free_pages: page %p is free", (void *)tpp);
2880 			/*NOTREACHED*/
2881 		}
2882 		if (hat_page_is_mapped(tpp) || tpp->p_lckcnt != 0 ||
2883 		    tpp->p_cowcnt != 0 || tpp->p_slckcnt != 0) {
2884 			panic("page_free_pages %p", (void *)tpp);
2885 			/*NOTREACHED*/
2886 		}
2887 
2888 		ASSERT(!hat_page_getshare(tpp));
2889 		ASSERT(tpp->p_vnode == NULL);
2890 		ASSERT(tpp->p_szc == szc);
2891 
2892 		PP_SETFREE(tpp);
2893 		page_clr_all_props(tpp);
2894 		PP_SETAGED(tpp);
2895 		tpp->p_offset = (u_offset_t)-1;
2896 		ASSERT(tpp->p_next == tpp);
2897 		ASSERT(tpp->p_prev == tpp);
2898 		page_list_concat(&rootpp, &tpp);
2899 	}
2900 	ASSERT(rootpp == pp);
2901 
2902 	page_list_add_pages(rootpp, 0);
2903 	page_create_putback(pgcnt);
2904 }
2905 
2906 int free_pages = 1;
2907 
2908 /*
2909  * This routine attempts to return pages to the cachelist via page_release().
2910  * It does not *have* to be successful in all cases, since the pageout scanner
2911  * will catch any pages it misses.  It does need to be fast and not introduce
2912  * too much overhead.
2913  *
2914  * If a page isn't found on the unlocked sweep of the page_hash bucket, we
2915  * don't lock and retry.  This is ok, since the page scanner will eventually
2916  * find any page we miss in free_vp_pages().
2917  */
2918 void
2919 free_vp_pages(vnode_t *vp, u_offset_t off, size_t len)
2920 {
2921 	page_t *pp;
2922 	u_offset_t eoff;
2923 	extern int swap_in_range(vnode_t *, u_offset_t, size_t);
2924 
2925 	eoff = off + len;
2926 
2927 	if (free_pages == 0)
2928 		return;
2929 	if (swap_in_range(vp, off, len))
2930 		return;
2931 
2932 	for (; off < eoff; off += PAGESIZE) {
2933 
2934 		/*
2935 		 * find the page using a fast, but inexact search. It'll be OK
2936 		 * if a few pages slip through the cracks here.
2937 		 */
2938 		pp = page_exists(vp, off);
2939 
2940 		/*
2941 		 * If we didn't find the page (it may not exist), the page
2942 		 * is free, looks still in use (shared), or we can't lock it,
2943 		 * just give up.
2944 		 */
2945 		if (pp == NULL ||
2946 		    PP_ISFREE(pp) ||
2947 		    page_share_cnt(pp) > 0 ||
2948 		    !page_trylock(pp, SE_EXCL))
2949 			continue;
2950 
2951 		/*
2952 		 * Once we have locked pp, verify that it's still the
2953 		 * correct page and not already free
2954 		 */
2955 		ASSERT(PAGE_LOCKED_SE(pp, SE_EXCL));
2956 		if (pp->p_vnode != vp || pp->p_offset != off || PP_ISFREE(pp)) {
2957 			page_unlock(pp);
2958 			continue;
2959 		}
2960 
2961 		/*
2962 		 * try to release the page...
2963 		 */
2964 		(void) page_release(pp, 1);
2965 	}
2966 }
2967 
2968 /*
2969  * Reclaim the given page from the free list.
2970  * If pp is part of a large pages, only the given constituent page is reclaimed
2971  * and the large page it belonged to will be demoted.  This can only happen
2972  * if the page is not on the cachelist.
2973  *
2974  * Returns 1 on success or 0 on failure.
2975  *
2976  * The page is unlocked if it can't be reclaimed (when freemem == 0).
2977  * If `lock' is non-null, it will be dropped and re-acquired if
2978  * the routine must wait while freemem is 0.
2979  *
2980  * As it turns out, boot_getpages() does this.  It picks a page,
2981  * based on where OBP mapped in some address, gets its pfn, searches
2982  * the memsegs, locks the page, then pulls it off the free list!
2983  */
2984 int
2985 page_reclaim(page_t *pp, kmutex_t *lock)
2986 {
2987 	struct pcf	*p;
2988 	uint_t		pcf_index;
2989 	struct cpu	*cpup;
2990 	int		enough;
2991 	uint_t		i;
2992 
2993 	ASSERT(lock != NULL ? MUTEX_HELD(lock) : 1);
2994 	ASSERT(PAGE_EXCL(pp) && PP_ISFREE(pp));
2995 
2996 	/*
2997 	 * If `freemem' is 0, we cannot reclaim this page from the
2998 	 * freelist, so release every lock we might hold: the page,
2999 	 * and the `lock' before blocking.
3000 	 *
3001 	 * The only way `freemem' can become 0 while there are pages
3002 	 * marked free (have their p->p_free bit set) is when the
3003 	 * system is low on memory and doing a page_create().  In
3004 	 * order to guarantee that once page_create() starts acquiring
3005 	 * pages it will be able to get all that it needs since `freemem'
3006 	 * was decreased by the requested amount.  So, we need to release
3007 	 * this page, and let page_create() have it.
3008 	 *
3009 	 * Since `freemem' being zero is not supposed to happen, just
3010 	 * use the usual hash stuff as a starting point.  If that bucket
3011 	 * is empty, then assume the worst, and start at the beginning
3012 	 * of the pcf array.  If we always start at the beginning
3013 	 * when acquiring more than one pcf lock, there won't be any
3014 	 * deadlock problems.
3015 	 */
3016 
3017 	/* TODO: Do we need to test kcage_freemem if PG_NORELOC(pp)? */
3018 
3019 	if (freemem <= throttlefree && !page_create_throttle(1l, 0)) {
3020 		pcf_acquire_all();
3021 		goto page_reclaim_nomem;
3022 	}
3023 
3024 	enough = 0;
3025 	pcf_index = PCF_INDEX();
3026 	p = &pcf[pcf_index];
3027 	mutex_enter(&p->pcf_lock);
3028 	if (p->pcf_count >= 1) {
3029 		enough = 1;
3030 		p->pcf_count--;
3031 	}
3032 	mutex_exit(&p->pcf_lock);
3033 
3034 	if (!enough) {
3035 		VM_STAT_ADD(page_reclaim_zero);
3036 		/*
3037 		 * Check again. Its possible that some other thread
3038 		 * could have been right behind us, and added one
3039 		 * to a list somewhere.  Acquire each of the pcf locks
3040 		 * until we find a page.
3041 		 */
3042 		p = pcf;
3043 		for (i = 0; i < PCF_FANOUT; i++) {
3044 			mutex_enter(&p->pcf_lock);
3045 			if (p->pcf_count >= 1) {
3046 				p->pcf_count -= 1;
3047 				enough = 1;
3048 				break;
3049 			}
3050 			p++;
3051 		}
3052 
3053 		if (!enough) {
3054 page_reclaim_nomem:
3055 			/*
3056 			 * We really can't have page `pp'.
3057 			 * Time for the no-memory dance with
3058 			 * page_free().  This is just like
3059 			 * page_create_wait().  Plus the added
3060 			 * attraction of releasing whatever mutex
3061 			 * we held when we were called with in `lock'.
3062 			 * Page_unlock() will wakeup any thread
3063 			 * waiting around for this page.
3064 			 */
3065 			if (lock) {
3066 				VM_STAT_ADD(page_reclaim_zero_locked);
3067 				mutex_exit(lock);
3068 			}
3069 			page_unlock(pp);
3070 
3071 			/*
3072 			 * get this before we drop all the pcf locks.
3073 			 */
3074 			mutex_enter(&new_freemem_lock);
3075 
3076 			p = pcf;
3077 			for (i = 0; i < PCF_FANOUT; i++) {
3078 				p->pcf_wait++;
3079 				mutex_exit(&p->pcf_lock);
3080 				p++;
3081 			}
3082 
3083 			freemem_wait++;
3084 			cv_wait(&freemem_cv, &new_freemem_lock);
3085 			freemem_wait--;
3086 
3087 			mutex_exit(&new_freemem_lock);
3088 
3089 			if (lock) {
3090 				mutex_enter(lock);
3091 			}
3092 			return (0);
3093 		}
3094 
3095 		/*
3096 		 * The pcf accounting has been done,
3097 		 * though none of the pcf_wait flags have been set,
3098 		 * drop the locks and continue on.
3099 		 */
3100 		while (p >= pcf) {
3101 			mutex_exit(&p->pcf_lock);
3102 			p--;
3103 		}
3104 	}
3105 
3106 	/*
3107 	 * freemem is not protected by any lock. Thus, we cannot
3108 	 * have any assertion containing freemem here.
3109 	 */
3110 	freemem -= 1;
3111 
3112 	VM_STAT_ADD(pagecnt.pc_reclaim);
3113 
3114 	/*
3115 	 * page_list_sub will handle the case where pp is a large page.
3116 	 * It's possible that the page was promoted while on the freelist
3117 	 */
3118 	if (PP_ISAGED(pp)) {
3119 		page_list_sub(pp, PG_FREE_LIST);
3120 		TRACE_1(TR_FAC_VM, TR_PAGE_UNFREE_FREE,
3121 		    "page_reclaim_free:pp %p", pp);
3122 	} else {
3123 		page_list_sub(pp, PG_CACHE_LIST);
3124 		TRACE_1(TR_FAC_VM, TR_PAGE_UNFREE_CACHE,
3125 		    "page_reclaim_cache:pp %p", pp);
3126 	}
3127 
3128 	/*
3129 	 * clear the p_free & p_age bits since this page is no longer
3130 	 * on the free list.  Notice that there was a brief time where
3131 	 * a page is marked as free, but is not on the list.
3132 	 *
3133 	 * Set the reference bit to protect against immediate pageout.
3134 	 */
3135 	PP_CLRFREE(pp);
3136 	PP_CLRAGED(pp);
3137 	page_set_props(pp, P_REF);
3138 
3139 	CPU_STATS_ENTER_K();
3140 	cpup = CPU;	/* get cpup now that CPU cannot change */
3141 	CPU_STATS_ADDQ(cpup, vm, pgrec, 1);
3142 	CPU_STATS_ADDQ(cpup, vm, pgfrec, 1);
3143 	CPU_STATS_EXIT_K();
3144 	ASSERT(pp->p_szc == 0);
3145 
3146 	return (1);
3147 }
3148 
3149 /*
3150  * Destroy identity of the page and put it back on
3151  * the page free list.  Assumes that the caller has
3152  * acquired the "exclusive" lock on the page.
3153  */
3154 void
3155 page_destroy(page_t *pp, int dontfree)
3156 {
3157 	ASSERT((PAGE_EXCL(pp) &&
3158 	    !page_iolock_assert(pp)) || panicstr);
3159 	ASSERT(pp->p_slckcnt == 0 || panicstr);
3160 
3161 	if (pp->p_szc != 0) {
3162 		if (pp->p_vnode == NULL || IS_SWAPFSVP(pp->p_vnode) ||
3163 		    PP_ISKAS(pp)) {
3164 			panic("page_destroy: anon or kernel or no vnode "
3165 			    "large page %p", (void *)pp);
3166 		}
3167 		page_demote_vp_pages(pp);
3168 		ASSERT(pp->p_szc == 0);
3169 	}
3170 
3171 	TRACE_1(TR_FAC_VM, TR_PAGE_DESTROY, "page_destroy:pp %p", pp);
3172 
3173 	/*
3174 	 * Unload translations, if any, then hash out the
3175 	 * page to erase its identity.
3176 	 */
3177 	(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
3178 	page_hashout(pp, NULL);
3179 
3180 	if (!dontfree) {
3181 		/*
3182 		 * Acquire the "freemem_lock" for availrmem.
3183 		 * The page_struct_lock need not be acquired for lckcnt
3184 		 * and cowcnt since the page has an "exclusive" lock.
3185 		 */
3186 		if ((pp->p_lckcnt != 0) || (pp->p_cowcnt != 0)) {
3187 			mutex_enter(&freemem_lock);
3188 			if (pp->p_lckcnt != 0) {
3189 				availrmem++;
3190 				pp->p_lckcnt = 0;
3191 			}
3192 			if (pp->p_cowcnt != 0) {
3193 				availrmem += pp->p_cowcnt;
3194 				pp->p_cowcnt = 0;
3195 			}
3196 			mutex_exit(&freemem_lock);
3197 		}
3198 		/*
3199 		 * Put the page on the "free" list.
3200 		 */
3201 		page_free(pp, 0);
3202 	}
3203 }
3204 
3205 void
3206 page_destroy_pages(page_t *pp)
3207 {
3208 
3209 	page_t	*tpp, *rootpp = NULL;
3210 	pgcnt_t	pgcnt = page_get_pagecnt(pp->p_szc);
3211 	pgcnt_t	i, pglcks = 0;
3212 	uint_t	szc = pp->p_szc;
3213 
3214 	ASSERT(pp->p_szc != 0 && pp->p_szc < page_num_pagesizes());
3215 
3216 	VM_STAT_ADD(pagecnt.pc_destroy_pages);
3217 
3218 	TRACE_1(TR_FAC_VM, TR_PAGE_DESTROY, "page_destroy_pages:pp %p", pp);
3219 
3220 	if ((page_pptonum(pp) & (pgcnt - 1)) != 0) {
3221 		panic("page_destroy_pages: not root page %p", (void *)pp);
3222 		/*NOTREACHED*/
3223 	}
3224 
3225 	for (i = 0, tpp = pp; i < pgcnt; i++, tpp++) {
3226 		ASSERT((PAGE_EXCL(tpp) &&
3227 		    !page_iolock_assert(tpp)) || panicstr);
3228 		ASSERT(tpp->p_slckcnt == 0 || panicstr);
3229 		(void) hat_pageunload(tpp, HAT_FORCE_PGUNLOAD);
3230 		page_hashout(tpp, NULL);
3231 		ASSERT(tpp->p_offset == (u_offset_t)-1);
3232 		if (tpp->p_lckcnt != 0) {
3233 			pglcks++;
3234 			tpp->p_lckcnt = 0;
3235 		} else if (tpp->p_cowcnt != 0) {
3236 			pglcks += tpp->p_cowcnt;
3237 			tpp->p_cowcnt = 0;
3238 		}
3239 		ASSERT(!hat_page_getshare(tpp));
3240 		ASSERT(tpp->p_vnode == NULL);
3241 		ASSERT(tpp->p_szc == szc);
3242 
3243 		PP_SETFREE(tpp);
3244 		page_clr_all_props(tpp);
3245 		PP_SETAGED(tpp);
3246 		ASSERT(tpp->p_next == tpp);
3247 		ASSERT(tpp->p_prev == tpp);
3248 		page_list_concat(&rootpp, &tpp);
3249 	}
3250 
3251 	ASSERT(rootpp == pp);
3252 	if (pglcks != 0) {
3253 		mutex_enter(&freemem_lock);
3254 		availrmem += pglcks;
3255 		mutex_exit(&freemem_lock);
3256 	}
3257 
3258 	page_list_add_pages(rootpp, 0);
3259 	page_create_putback(pgcnt);
3260 }
3261 
3262 /*
3263  * Similar to page_destroy(), but destroys pages which are
3264  * locked and known to be on the page free list.  Since
3265  * the page is known to be free and locked, no one can access
3266  * it.
3267  *
3268  * Also, the number of free pages does not change.
3269  */
3270 void
3271 page_destroy_free(page_t *pp)
3272 {
3273 	ASSERT(PAGE_EXCL(pp));
3274 	ASSERT(PP_ISFREE(pp));
3275 	ASSERT(pp->p_vnode);
3276 	ASSERT(hat_page_getattr(pp, P_MOD | P_REF | P_RO) == 0);
3277 	ASSERT(!hat_page_is_mapped(pp));
3278 	ASSERT(PP_ISAGED(pp) == 0);
3279 	ASSERT(pp->p_szc == 0);
3280 
3281 	VM_STAT_ADD(pagecnt.pc_destroy_free);
3282 	page_list_sub(pp, PG_CACHE_LIST);
3283 
3284 	page_hashout(pp, NULL);
3285 	ASSERT(pp->p_vnode == NULL);
3286 	ASSERT(pp->p_offset == (u_offset_t)-1);
3287 	ASSERT(pp->p_hash == NULL);
3288 
3289 	PP_SETAGED(pp);
3290 	page_list_add(pp, PG_FREE_LIST | PG_LIST_TAIL);
3291 	page_unlock(pp);
3292 
3293 	mutex_enter(&new_freemem_lock);
3294 	if (freemem_wait) {
3295 		cv_signal(&freemem_cv);
3296 	}
3297 	mutex_exit(&new_freemem_lock);
3298 }
3299 
3300 /*
3301  * Rename the page "opp" to have an identity specified
3302  * by [vp, off].  If a page already exists with this name
3303  * it is locked and destroyed.  Note that the page's
3304  * translations are not unloaded during the rename.
3305  *
3306  * This routine is used by the anon layer to "steal" the
3307  * original page and is not unlike destroying a page and
3308  * creating a new page using the same page frame.
3309  *
3310  * XXX -- Could deadlock if caller 1 tries to rename A to B while
3311  * caller 2 tries to rename B to A.
3312  */
3313 void
3314 page_rename(page_t *opp, vnode_t *vp, u_offset_t off)
3315 {
3316 	page_t		*pp;
3317 	int		olckcnt = 0;
3318 	int		ocowcnt = 0;
3319 	kmutex_t	*phm;
3320 	ulong_t		index;
3321 
3322 	ASSERT(PAGE_EXCL(opp) && !page_iolock_assert(opp));
3323 	ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(vp)));
3324 	ASSERT(PP_ISFREE(opp) == 0);
3325 
3326 	VM_STAT_ADD(page_rename_count);
3327 
3328 	TRACE_3(TR_FAC_VM, TR_PAGE_RENAME,
3329 	    "page rename:pp %p vp %p off %llx", opp, vp, off);
3330 
3331 	/*
3332 	 * CacheFS may call page_rename for a large NFS page
3333 	 * when both CacheFS and NFS mount points are used
3334 	 * by applications. Demote this large page before
3335 	 * renaming it, to ensure that there are no "partial"
3336 	 * large pages left lying around.
3337 	 */
3338 	if (opp->p_szc != 0) {
3339 		vnode_t *ovp = opp->p_vnode;
3340 		ASSERT(ovp != NULL);
3341 		ASSERT(!IS_SWAPFSVP(ovp));
3342 		ASSERT(!VN_ISKAS(ovp));
3343 		page_demote_vp_pages(opp);
3344 		ASSERT(opp->p_szc == 0);
3345 	}
3346 
3347 	page_hashout(opp, NULL);
3348 	PP_CLRAGED(opp);
3349 
3350 	/*
3351 	 * Acquire the appropriate page hash lock, since
3352 	 * we're going to rename the page.
3353 	 */
3354 	index = PAGE_HASH_FUNC(vp, off);
3355 	phm = PAGE_HASH_MUTEX(index);
3356 	mutex_enter(phm);
3357 top:
3358 	/*
3359 	 * Look for an existing page with this name and destroy it if found.
3360 	 * By holding the page hash lock all the way to the page_hashin()
3361 	 * call, we are assured that no page can be created with this
3362 	 * identity.  In the case when the phm lock is dropped to undo any
3363 	 * hat layer mappings, the existing page is held with an "exclusive"
3364 	 * lock, again preventing another page from being created with
3365 	 * this identity.
3366 	 */
3367 	PAGE_HASH_SEARCH(index, pp, vp, off);
3368 	if (pp != NULL) {
3369 		VM_STAT_ADD(page_rename_exists);
3370 
3371 		/*
3372 		 * As it turns out, this is one of only two places where
3373 		 * page_lock() needs to hold the passed in lock in the
3374 		 * successful case.  In all of the others, the lock could
3375 		 * be dropped as soon as the attempt is made to lock
3376 		 * the page.  It is tempting to add yet another arguement,
3377 		 * PL_KEEP or PL_DROP, to let page_lock know what to do.
3378 		 */
3379 		if (!page_lock(pp, SE_EXCL, phm, P_RECLAIM)) {
3380 			/*
3381 			 * Went to sleep because the page could not
3382 			 * be locked.  We were woken up when the page
3383 			 * was unlocked, or when the page was destroyed.
3384 			 * In either case, `phm' was dropped while we
3385 			 * slept.  Hence we should not just roar through
3386 			 * this loop.
3387 			 */
3388 			goto top;
3389 		}
3390 
3391 		/*
3392 		 * If an existing page is a large page, then demote
3393 		 * it to ensure that no "partial" large pages are
3394 		 * "created" after page_rename. An existing page
3395 		 * can be a CacheFS page, and can't belong to swapfs.
3396 		 */
3397 		if (hat_page_is_mapped(pp)) {
3398 			/*
3399 			 * Unload translations.  Since we hold the
3400 			 * exclusive lock on this page, the page
3401 			 * can not be changed while we drop phm.
3402 			 * This is also not a lock protocol violation,
3403 			 * but rather the proper way to do things.
3404 			 */
3405 			mutex_exit(phm);
3406 			(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
3407 			if (pp->p_szc != 0) {
3408 				ASSERT(!IS_SWAPFSVP(vp));
3409 				ASSERT(!VN_ISKAS(vp));
3410 				page_demote_vp_pages(pp);
3411 				ASSERT(pp->p_szc == 0);
3412 			}
3413 			mutex_enter(phm);
3414 		} else if (pp->p_szc != 0) {
3415 			ASSERT(!IS_SWAPFSVP(vp));
3416 			ASSERT(!VN_ISKAS(vp));
3417 			mutex_exit(phm);
3418 			page_demote_vp_pages(pp);
3419 			ASSERT(pp->p_szc == 0);
3420 			mutex_enter(phm);
3421 		}
3422 		page_hashout(pp, phm);
3423 	}
3424 	/*
3425 	 * Hash in the page with the new identity.
3426 	 */
3427 	if (!page_hashin(opp, vp, off, phm)) {
3428 		/*
3429 		 * We were holding phm while we searched for [vp, off]
3430 		 * and only dropped phm if we found and locked a page.
3431 		 * If we can't create this page now, then some thing
3432 		 * is really broken.
3433 		 */
3434 		panic("page_rename: Can't hash in page: %p", (void *)pp);
3435 		/*NOTREACHED*/
3436 	}
3437 
3438 	ASSERT(MUTEX_HELD(phm));
3439 	mutex_exit(phm);
3440 
3441 	/*
3442 	 * Now that we have dropped phm, lets get around to finishing up
3443 	 * with pp.
3444 	 */
3445 	if (pp != NULL) {
3446 		ASSERT(!hat_page_is_mapped(pp));
3447 		/* for now large pages should not end up here */
3448 		ASSERT(pp->p_szc == 0);
3449 		/*
3450 		 * Save the locks for transfer to the new page and then
3451 		 * clear them so page_free doesn't think they're important.
3452 		 * The page_struct_lock need not be acquired for lckcnt and
3453 		 * cowcnt since the page has an "exclusive" lock.
3454 		 */
3455 		olckcnt = pp->p_lckcnt;
3456 		ocowcnt = pp->p_cowcnt;
3457 		pp->p_lckcnt = pp->p_cowcnt = 0;
3458 
3459 		/*
3460 		 * Put the page on the "free" list after we drop
3461 		 * the lock.  The less work under the lock the better.
3462 		 */
3463 		/*LINTED: constant in conditional context*/
3464 		VN_DISPOSE(pp, B_FREE, 0, kcred);
3465 	}
3466 
3467 	/*
3468 	 * Transfer the lock count from the old page (if any).
3469 	 * The page_struct_lock need not be acquired for lckcnt and
3470 	 * cowcnt since the page has an "exclusive" lock.
3471 	 */
3472 	opp->p_lckcnt += olckcnt;
3473 	opp->p_cowcnt += ocowcnt;
3474 }
3475 
3476 /*
3477  * low level routine to add page `pp' to the hash and vp chains for [vp, offset]
3478  *
3479  * Pages are normally inserted at the start of a vnode's v_pages list.
3480  * If the vnode is VMODSORT and the page is modified, it goes at the end.
3481  * This can happen when a modified page is relocated for DR.
3482  *
3483  * Returns 1 on success and 0 on failure.
3484  */
3485 static int
3486 page_do_hashin(page_t *pp, vnode_t *vp, u_offset_t offset)
3487 {
3488 	page_t		**listp;
3489 	page_t		*tp;
3490 	ulong_t		index;
3491 
3492 	ASSERT(PAGE_EXCL(pp));
3493 	ASSERT(vp != NULL);
3494 	ASSERT(MUTEX_HELD(page_vnode_mutex(vp)));
3495 
3496 	/*
3497 	 * Be sure to set these up before the page is inserted on the hash
3498 	 * list.  As soon as the page is placed on the list some other
3499 	 * thread might get confused and wonder how this page could
3500 	 * possibly hash to this list.
3501 	 */
3502 	pp->p_vnode = vp;
3503 	pp->p_offset = offset;
3504 
3505 	/*
3506 	 * record if this page is on a swap vnode
3507 	 */
3508 	if ((vp->v_flag & VISSWAP) != 0)
3509 		PP_SETSWAP(pp);
3510 
3511 	index = PAGE_HASH_FUNC(vp, offset);
3512 	ASSERT(MUTEX_HELD(PAGE_HASH_MUTEX(index)));
3513 	listp = &page_hash[index];
3514 
3515 	/*
3516 	 * If this page is already hashed in, fail this attempt to add it.
3517 	 */
3518 	for (tp = *listp; tp != NULL; tp = tp->p_hash) {
3519 		if (tp->p_vnode == vp && tp->p_offset == offset) {
3520 			pp->p_vnode = NULL;
3521 			pp->p_offset = (u_offset_t)(-1);
3522 			return (0);
3523 		}
3524 	}
3525 	pp->p_hash = *listp;
3526 	*listp = pp;
3527 
3528 	/*
3529 	 * Add the page to the vnode's list of pages
3530 	 */
3531 	if (vp->v_pages != NULL && IS_VMODSORT(vp) && hat_ismod(pp))
3532 		listp = &vp->v_pages->p_vpprev->p_vpnext;
3533 	else
3534 		listp = &vp->v_pages;
3535 
3536 	page_vpadd(listp, pp);
3537 
3538 	return (1);
3539 }
3540 
3541 /*
3542  * Add page `pp' to both the hash and vp chains for [vp, offset].
3543  *
3544  * Returns 1 on success and 0 on failure.
3545  * If hold is passed in, it is not dropped.
3546  */
3547 int
3548 page_hashin(page_t *pp, vnode_t *vp, u_offset_t offset, kmutex_t *hold)
3549 {
3550 	kmutex_t	*phm = NULL;
3551 	kmutex_t	*vphm;
3552 	int		rc;
3553 
3554 	ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(vp)));
3555 
3556 	TRACE_3(TR_FAC_VM, TR_PAGE_HASHIN,
3557 	    "page_hashin:pp %p vp %p offset %llx",
3558 	    pp, vp, offset);
3559 
3560 	VM_STAT_ADD(hashin_count);
3561 
3562 	if (hold != NULL)
3563 		phm = hold;
3564 	else {
3565 		VM_STAT_ADD(hashin_not_held);
3566 		phm = PAGE_HASH_MUTEX(PAGE_HASH_FUNC(vp, offset));
3567 		mutex_enter(phm);
3568 	}
3569 
3570 	vphm = page_vnode_mutex(vp);
3571 	mutex_enter(vphm);
3572 	rc = page_do_hashin(pp, vp, offset);
3573 	mutex_exit(vphm);
3574 	if (hold == NULL)
3575 		mutex_exit(phm);
3576 	if (rc == 0)
3577 		VM_STAT_ADD(hashin_already);
3578 	return (rc);
3579 }
3580 
3581 /*
3582  * Remove page ``pp'' from the hash and vp chains and remove vp association.
3583  * All mutexes must be held
3584  */
3585 static void
3586 page_do_hashout(page_t *pp)
3587 {
3588 	page_t	**hpp;
3589 	page_t	*hp;
3590 	vnode_t	*vp = pp->p_vnode;
3591 
3592 	ASSERT(vp != NULL);
3593 	ASSERT(MUTEX_HELD(page_vnode_mutex(vp)));
3594 
3595 	/*
3596 	 * First, take pp off of its hash chain.
3597 	 */
3598 	hpp = &page_hash[PAGE_HASH_FUNC(vp, pp->p_offset)];
3599 
3600 	for (;;) {
3601 		hp = *hpp;
3602 		if (hp == pp)
3603 			break;
3604 		if (hp == NULL) {
3605 			panic("page_do_hashout");
3606 			/*NOTREACHED*/
3607 		}
3608 		hpp = &hp->p_hash;
3609 	}
3610 	*hpp = pp->p_hash;
3611 
3612 	/*
3613 	 * Now remove it from its associated vnode.
3614 	 */
3615 	if (vp->v_pages)
3616 		page_vpsub(&vp->v_pages, pp);
3617 
3618 	pp->p_hash = NULL;
3619 	page_clr_all_props(pp);
3620 	PP_CLRSWAP(pp);
3621 	pp->p_vnode = NULL;
3622 	pp->p_offset = (u_offset_t)-1;
3623 }
3624 
3625 /*
3626  * Remove page ``pp'' from the hash and vp chains and remove vp association.
3627  *
3628  * When `phm' is non-NULL it contains the address of the mutex protecting the
3629  * hash list pp is on.  It is not dropped.
3630  */
3631 void
3632 page_hashout(page_t *pp, kmutex_t *phm)
3633 {
3634 	vnode_t		*vp;
3635 	ulong_t		index;
3636 	kmutex_t	*nphm;
3637 	kmutex_t	*vphm;
3638 	kmutex_t	*sep;
3639 
3640 	ASSERT(phm != NULL ? MUTEX_HELD(phm) : 1);
3641 	ASSERT(pp->p_vnode != NULL);
3642 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
3643 	ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(pp->p_vnode)));
3644 
3645 	vp = pp->p_vnode;
3646 
3647 	TRACE_2(TR_FAC_VM, TR_PAGE_HASHOUT,
3648 	    "page_hashout:pp %p vp %p", pp, vp);
3649 
3650 	/* Kernel probe */
3651 	TNF_PROBE_2(page_unmap, "vm pagefault", /* CSTYLED */,
3652 	    tnf_opaque, vnode, vp,
3653 	    tnf_offset, offset, pp->p_offset);
3654 
3655 	/*
3656 	 *
3657 	 */
3658 	VM_STAT_ADD(hashout_count);
3659 	index = PAGE_HASH_FUNC(vp, pp->p_offset);
3660 	if (phm == NULL) {
3661 		VM_STAT_ADD(hashout_not_held);
3662 		nphm = PAGE_HASH_MUTEX(index);
3663 		mutex_enter(nphm);
3664 	}
3665 	ASSERT(phm ? phm == PAGE_HASH_MUTEX(index) : 1);
3666 
3667 
3668 	/*
3669 	 * grab page vnode mutex and remove it...
3670 	 */
3671 	vphm = page_vnode_mutex(vp);
3672 	mutex_enter(vphm);
3673 
3674 	page_do_hashout(pp);
3675 
3676 	mutex_exit(vphm);
3677 	if (phm == NULL)
3678 		mutex_exit(nphm);
3679 
3680 	/*
3681 	 * Wake up processes waiting for this page.  The page's
3682 	 * identity has been changed, and is probably not the
3683 	 * desired page any longer.
3684 	 */
3685 	sep = page_se_mutex(pp);
3686 	mutex_enter(sep);
3687 	pp->p_selock &= ~SE_EWANTED;
3688 	if (CV_HAS_WAITERS(&pp->p_cv))
3689 		cv_broadcast(&pp->p_cv);
3690 	mutex_exit(sep);
3691 }
3692 
3693 /*
3694  * Add the page to the front of a linked list of pages
3695  * using the p_next & p_prev pointers for the list.
3696  * The caller is responsible for protecting the list pointers.
3697  */
3698 void
3699 page_add(page_t **ppp, page_t *pp)
3700 {
3701 	ASSERT(PAGE_EXCL(pp) || (PAGE_SHARED(pp) && page_iolock_assert(pp)));
3702 
3703 	page_add_common(ppp, pp);
3704 }
3705 
3706 
3707 
3708 /*
3709  *  Common code for page_add() and mach_page_add()
3710  */
3711 void
3712 page_add_common(page_t **ppp, page_t *pp)
3713 {
3714 	if (*ppp == NULL) {
3715 		pp->p_next = pp->p_prev = pp;
3716 	} else {
3717 		pp->p_next = *ppp;
3718 		pp->p_prev = (*ppp)->p_prev;
3719 		(*ppp)->p_prev = pp;
3720 		pp->p_prev->p_next = pp;
3721 	}
3722 	*ppp = pp;
3723 }
3724 
3725 
3726 /*
3727  * Remove this page from a linked list of pages
3728  * using the p_next & p_prev pointers for the list.
3729  *
3730  * The caller is responsible for protecting the list pointers.
3731  */
3732 void
3733 page_sub(page_t **ppp, page_t *pp)
3734 {
3735 	ASSERT((PP_ISFREE(pp)) ? 1 :
3736 	    (PAGE_EXCL(pp)) || (PAGE_SHARED(pp) && page_iolock_assert(pp)));
3737 
3738 	if (*ppp == NULL || pp == NULL) {
3739 		panic("page_sub: bad arg(s): pp %p, *ppp %p",
3740 		    (void *)pp, (void *)(*ppp));
3741 		/*NOTREACHED*/
3742 	}
3743 
3744 	page_sub_common(ppp, pp);
3745 }
3746 
3747 
3748 /*
3749  *  Common code for page_sub() and mach_page_sub()
3750  */
3751 void
3752 page_sub_common(page_t **ppp, page_t *pp)
3753 {
3754 	if (*ppp == pp)
3755 		*ppp = pp->p_next;		/* go to next page */
3756 
3757 	if (*ppp == pp)
3758 		*ppp = NULL;			/* page list is gone */
3759 	else {
3760 		pp->p_prev->p_next = pp->p_next;
3761 		pp->p_next->p_prev = pp->p_prev;
3762 	}
3763 	pp->p_prev = pp->p_next = pp;		/* make pp a list of one */
3764 }
3765 
3766 
3767 /*
3768  * Break page list cppp into two lists with npages in the first list.
3769  * The tail is returned in nppp.
3770  */
3771 void
3772 page_list_break(page_t **oppp, page_t **nppp, pgcnt_t npages)
3773 {
3774 	page_t *s1pp = *oppp;
3775 	page_t *s2pp;
3776 	page_t *e1pp, *e2pp;
3777 	long n = 0;
3778 
3779 	if (s1pp == NULL) {
3780 		*nppp = NULL;
3781 		return;
3782 	}
3783 	if (npages == 0) {
3784 		*nppp = s1pp;
3785 		*oppp = NULL;
3786 		return;
3787 	}
3788 	for (n = 0, s2pp = *oppp; n < npages; n++) {
3789 		s2pp = s2pp->p_next;
3790 	}
3791 	/* Fix head and tail of new lists */
3792 	e1pp = s2pp->p_prev;
3793 	e2pp = s1pp->p_prev;
3794 	s1pp->p_prev = e1pp;
3795 	e1pp->p_next = s1pp;
3796 	s2pp->p_prev = e2pp;
3797 	e2pp->p_next = s2pp;
3798 
3799 	/* second list empty */
3800 	if (s2pp == s1pp) {
3801 		*oppp = s1pp;
3802 		*nppp = NULL;
3803 	} else {
3804 		*oppp = s1pp;
3805 		*nppp = s2pp;
3806 	}
3807 }
3808 
3809 /*
3810  * Concatenate page list nppp onto the end of list ppp.
3811  */
3812 void
3813 page_list_concat(page_t **ppp, page_t **nppp)
3814 {
3815 	page_t *s1pp, *s2pp, *e1pp, *e2pp;
3816 
3817 	if (*nppp == NULL) {
3818 		return;
3819 	}
3820 	if (*ppp == NULL) {
3821 		*ppp = *nppp;
3822 		return;
3823 	}
3824 	s1pp = *ppp;
3825 	e1pp =  s1pp->p_prev;
3826 	s2pp = *nppp;
3827 	e2pp = s2pp->p_prev;
3828 	s1pp->p_prev = e2pp;
3829 	e2pp->p_next = s1pp;
3830 	e1pp->p_next = s2pp;
3831 	s2pp->p_prev = e1pp;
3832 }
3833 
3834 /*
3835  * return the next page in the page list
3836  */
3837 page_t *
3838 page_list_next(page_t *pp)
3839 {
3840 	return (pp->p_next);
3841 }
3842 
3843 
3844 /*
3845  * Add the page to the front of the linked list of pages
3846  * using p_vpnext/p_vpprev pointers for the list.
3847  *
3848  * The caller is responsible for protecting the lists.
3849  */
3850 void
3851 page_vpadd(page_t **ppp, page_t *pp)
3852 {
3853 	if (*ppp == NULL) {
3854 		pp->p_vpnext = pp->p_vpprev = pp;
3855 	} else {
3856 		pp->p_vpnext = *ppp;
3857 		pp->p_vpprev = (*ppp)->p_vpprev;
3858 		(*ppp)->p_vpprev = pp;
3859 		pp->p_vpprev->p_vpnext = pp;
3860 	}
3861 	*ppp = pp;
3862 }
3863 
3864 /*
3865  * Remove this page from the linked list of pages
3866  * using p_vpnext/p_vpprev pointers for the list.
3867  *
3868  * The caller is responsible for protecting the lists.
3869  */
3870 void
3871 page_vpsub(page_t **ppp, page_t *pp)
3872 {
3873 	if (*ppp == NULL || pp == NULL) {
3874 		panic("page_vpsub: bad arg(s): pp %p, *ppp %p",
3875 		    (void *)pp, (void *)(*ppp));
3876 		/*NOTREACHED*/
3877 	}
3878 
3879 	if (*ppp == pp)
3880 		*ppp = pp->p_vpnext;		/* go to next page */
3881 
3882 	if (*ppp == pp)
3883 		*ppp = NULL;			/* page list is gone */
3884 	else {
3885 		pp->p_vpprev->p_vpnext = pp->p_vpnext;
3886 		pp->p_vpnext->p_vpprev = pp->p_vpprev;
3887 	}
3888 	pp->p_vpprev = pp->p_vpnext = pp;	/* make pp a list of one */
3889 }
3890 
3891 /*
3892  * Lock a physical page into memory "long term".  Used to support "lock
3893  * in memory" functions.  Accepts the page to be locked, and a cow variable
3894  * to indicate whether a the lock will travel to the new page during
3895  * a potential copy-on-write.
3896  */
3897 int
3898 page_pp_lock(
3899 	page_t *pp,			/* page to be locked */
3900 	int cow,			/* cow lock */
3901 	int kernel)			/* must succeed -- ignore checking */
3902 {
3903 	int r = 0;			/* result -- assume failure */
3904 
3905 	ASSERT(PAGE_LOCKED(pp));
3906 
3907 	page_struct_lock(pp);
3908 	/*
3909 	 * Acquire the "freemem_lock" for availrmem.
3910 	 */
3911 	if (cow) {
3912 		mutex_enter(&freemem_lock);
3913 		if ((availrmem > pages_pp_maximum) &&
3914 		    (pp->p_cowcnt < (ushort_t)PAGE_LOCK_MAXIMUM)) {
3915 			availrmem--;
3916 			pages_locked++;
3917 			mutex_exit(&freemem_lock);
3918 			r = 1;
3919 			if (++pp->p_cowcnt == (ushort_t)PAGE_LOCK_MAXIMUM) {
3920 				cmn_err(CE_WARN,
3921 				    "COW lock limit reached on pfn 0x%lx",
3922 				    page_pptonum(pp));
3923 			}
3924 		} else
3925 			mutex_exit(&freemem_lock);
3926 	} else {
3927 		if (pp->p_lckcnt) {
3928 			if (pp->p_lckcnt < (ushort_t)PAGE_LOCK_MAXIMUM) {
3929 				r = 1;
3930 				if (++pp->p_lckcnt ==
3931 				    (ushort_t)PAGE_LOCK_MAXIMUM) {
3932 					cmn_err(CE_WARN, "Page lock limit "
3933 					    "reached on pfn 0x%lx",
3934 					    page_pptonum(pp));
3935 				}
3936 			}
3937 		} else {
3938 			if (kernel) {
3939 				/* availrmem accounting done by caller */
3940 				++pp->p_lckcnt;
3941 				r = 1;
3942 			} else {
3943 				mutex_enter(&freemem_lock);
3944 				if (availrmem > pages_pp_maximum) {
3945 					availrmem--;
3946 					pages_locked++;
3947 					++pp->p_lckcnt;
3948 					r = 1;
3949 				}
3950 				mutex_exit(&freemem_lock);
3951 			}
3952 		}
3953 	}
3954 	page_struct_unlock(pp);
3955 	return (r);
3956 }
3957 
3958 /*
3959  * Decommit a lock on a physical page frame.  Account for cow locks if
3960  * appropriate.
3961  */
3962 void
3963 page_pp_unlock(
3964 	page_t *pp,			/* page to be unlocked */
3965 	int cow,			/* expect cow lock */
3966 	int kernel)			/* this was a kernel lock */
3967 {
3968 	ASSERT(PAGE_LOCKED(pp));
3969 
3970 	page_struct_lock(pp);
3971 	/*
3972 	 * Acquire the "freemem_lock" for availrmem.
3973 	 * If cowcnt or lcknt is already 0 do nothing; i.e., we
3974 	 * could be called to unlock even if nothing is locked. This could
3975 	 * happen if locked file pages were truncated (removing the lock)
3976 	 * and the file was grown again and new pages faulted in; the new
3977 	 * pages are unlocked but the segment still thinks they're locked.
3978 	 */
3979 	if (cow) {
3980 		if (pp->p_cowcnt) {
3981 			mutex_enter(&freemem_lock);
3982 			pp->p_cowcnt--;
3983 			availrmem++;
3984 			pages_locked--;
3985 			mutex_exit(&freemem_lock);
3986 		}
3987 	} else {
3988 		if (pp->p_lckcnt && --pp->p_lckcnt == 0) {
3989 			if (!kernel) {
3990 				mutex_enter(&freemem_lock);
3991 				availrmem++;
3992 				pages_locked--;
3993 				mutex_exit(&freemem_lock);
3994 			}
3995 		}
3996 	}
3997 	page_struct_unlock(pp);
3998 }
3999 
4000 /*
4001  * This routine reserves availrmem for npages;
4002  * 	flags: KM_NOSLEEP or KM_SLEEP
4003  * 	returns 1 on success or 0 on failure
4004  */
4005 int
4006 page_resv(pgcnt_t npages, uint_t flags)
4007 {
4008 	mutex_enter(&freemem_lock);
4009 	while (availrmem < tune.t_minarmem + npages) {
4010 		if (flags & KM_NOSLEEP) {
4011 			mutex_exit(&freemem_lock);
4012 			return (0);
4013 		}
4014 		mutex_exit(&freemem_lock);
4015 		page_needfree(npages);
4016 		kmem_reap();
4017 		delay(hz >> 2);
4018 		page_needfree(-(spgcnt_t)npages);
4019 		mutex_enter(&freemem_lock);
4020 	}
4021 	availrmem -= npages;
4022 	mutex_exit(&freemem_lock);
4023 	return (1);
4024 }
4025 
4026 /*
4027  * This routine unreserves availrmem for npages;
4028  */
4029 void
4030 page_unresv(pgcnt_t npages)
4031 {
4032 	mutex_enter(&freemem_lock);
4033 	availrmem += npages;
4034 	mutex_exit(&freemem_lock);
4035 }
4036 
4037 /*
4038  * See Statement at the beginning of segvn_lockop() regarding
4039  * the way we handle cowcnts and lckcnts.
4040  *
4041  * Transfer cowcnt on 'opp' to cowcnt on 'npp' if the vpage
4042  * that breaks COW has PROT_WRITE.
4043  *
4044  * Note that, we may also break COW in case we are softlocking
4045  * on read access during physio;
4046  * in this softlock case, the vpage may not have PROT_WRITE.
4047  * So, we need to transfer lckcnt on 'opp' to lckcnt on 'npp'
4048  * if the vpage doesn't have PROT_WRITE.
4049  *
4050  * This routine is never called if we are stealing a page
4051  * in anon_private.
4052  *
4053  * The caller subtracted from availrmem for read only mapping.
4054  * if lckcnt is 1 increment availrmem.
4055  */
4056 void
4057 page_pp_useclaim(
4058 	page_t *opp,		/* original page frame losing lock */
4059 	page_t *npp,		/* new page frame gaining lock */
4060 	uint_t	write_perm) 	/* set if vpage has PROT_WRITE */
4061 {
4062 	int payback = 0;
4063 
4064 	ASSERT(PAGE_LOCKED(opp));
4065 	ASSERT(PAGE_LOCKED(npp));
4066 
4067 	page_struct_lock(opp);
4068 
4069 	ASSERT(npp->p_cowcnt == 0);
4070 	ASSERT(npp->p_lckcnt == 0);
4071 
4072 	/* Don't use claim if nothing is locked (see page_pp_unlock above) */
4073 	if ((write_perm && opp->p_cowcnt != 0) ||
4074 	    (!write_perm && opp->p_lckcnt != 0)) {
4075 
4076 		if (write_perm) {
4077 			npp->p_cowcnt++;
4078 			ASSERT(opp->p_cowcnt != 0);
4079 			opp->p_cowcnt--;
4080 		} else {
4081 
4082 			ASSERT(opp->p_lckcnt != 0);
4083 
4084 			/*
4085 			 * We didn't need availrmem decremented if p_lckcnt on
4086 			 * original page is 1. Here, we are unlocking
4087 			 * read-only copy belonging to original page and
4088 			 * are locking a copy belonging to new page.
4089 			 */
4090 			if (opp->p_lckcnt == 1)
4091 				payback = 1;
4092 
4093 			npp->p_lckcnt++;
4094 			opp->p_lckcnt--;
4095 		}
4096 	}
4097 	if (payback) {
4098 		mutex_enter(&freemem_lock);
4099 		availrmem++;
4100 		pages_useclaim--;
4101 		mutex_exit(&freemem_lock);
4102 	}
4103 	page_struct_unlock(opp);
4104 }
4105 
4106 /*
4107  * Simple claim adjust functions -- used to support changes in
4108  * claims due to changes in access permissions.  Used by segvn_setprot().
4109  */
4110 int
4111 page_addclaim(page_t *pp)
4112 {
4113 	int r = 0;			/* result */
4114 
4115 	ASSERT(PAGE_LOCKED(pp));
4116 
4117 	page_struct_lock(pp);
4118 	ASSERT(pp->p_lckcnt != 0);
4119 
4120 	if (pp->p_lckcnt == 1) {
4121 		if (pp->p_cowcnt < (ushort_t)PAGE_LOCK_MAXIMUM) {
4122 			--pp->p_lckcnt;
4123 			r = 1;
4124 			if (++pp->p_cowcnt == (ushort_t)PAGE_LOCK_MAXIMUM) {
4125 				cmn_err(CE_WARN,
4126 				    "COW lock limit reached on pfn 0x%lx",
4127 				    page_pptonum(pp));
4128 			}
4129 		}
4130 	} else {
4131 		mutex_enter(&freemem_lock);
4132 		if ((availrmem > pages_pp_maximum) &&
4133 		    (pp->p_cowcnt < (ushort_t)PAGE_LOCK_MAXIMUM)) {
4134 			--availrmem;
4135 			++pages_claimed;
4136 			mutex_exit(&freemem_lock);
4137 			--pp->p_lckcnt;
4138 			r = 1;
4139 			if (++pp->p_cowcnt == (ushort_t)PAGE_LOCK_MAXIMUM) {
4140 				cmn_err(CE_WARN,
4141 				    "COW lock limit reached on pfn 0x%lx",
4142 				    page_pptonum(pp));
4143 			}
4144 		} else
4145 			mutex_exit(&freemem_lock);
4146 	}
4147 	page_struct_unlock(pp);
4148 	return (r);
4149 }
4150 
4151 int
4152 page_subclaim(page_t *pp)
4153 {
4154 	int r = 0;
4155 
4156 	ASSERT(PAGE_LOCKED(pp));
4157 
4158 	page_struct_lock(pp);
4159 	ASSERT(pp->p_cowcnt != 0);
4160 
4161 	if (pp->p_lckcnt) {
4162 		if (pp->p_lckcnt < (ushort_t)PAGE_LOCK_MAXIMUM) {
4163 			r = 1;
4164 			/*
4165 			 * for availrmem
4166 			 */
4167 			mutex_enter(&freemem_lock);
4168 			availrmem++;
4169 			pages_claimed--;
4170 			mutex_exit(&freemem_lock);
4171 
4172 			pp->p_cowcnt--;
4173 
4174 			if (++pp->p_lckcnt == (ushort_t)PAGE_LOCK_MAXIMUM) {
4175 				cmn_err(CE_WARN,
4176 				    "Page lock limit reached on pfn 0x%lx",
4177 				    page_pptonum(pp));
4178 			}
4179 		}
4180 	} else {
4181 		r = 1;
4182 		pp->p_cowcnt--;
4183 		pp->p_lckcnt++;
4184 	}
4185 	page_struct_unlock(pp);
4186 	return (r);
4187 }
4188 
4189 int
4190 page_addclaim_pages(page_t  **ppa)
4191 {
4192 
4193 	pgcnt_t	lckpgs = 0, pg_idx;
4194 
4195 	VM_STAT_ADD(pagecnt.pc_addclaim_pages);
4196 
4197 	mutex_enter(&page_llock);
4198 	for (pg_idx = 0; ppa[pg_idx] != NULL; pg_idx++) {
4199 
4200 		ASSERT(PAGE_LOCKED(ppa[pg_idx]));
4201 		ASSERT(ppa[pg_idx]->p_lckcnt != 0);
4202 		if (ppa[pg_idx]->p_cowcnt == (ushort_t)PAGE_LOCK_MAXIMUM) {
4203 			mutex_exit(&page_llock);
4204 			return (0);
4205 		}
4206 		if (ppa[pg_idx]->p_lckcnt > 1)
4207 			lckpgs++;
4208 	}
4209 
4210 	if (lckpgs != 0) {
4211 		mutex_enter(&freemem_lock);
4212 		if (availrmem >= pages_pp_maximum + lckpgs) {
4213 			availrmem -= lckpgs;
4214 			pages_claimed += lckpgs;
4215 		} else {
4216 			mutex_exit(&freemem_lock);
4217 			mutex_exit(&page_llock);
4218 			return (0);
4219 		}
4220 		mutex_exit(&freemem_lock);
4221 	}
4222 
4223 	for (pg_idx = 0; ppa[pg_idx] != NULL; pg_idx++) {
4224 		ppa[pg_idx]->p_lckcnt--;
4225 		ppa[pg_idx]->p_cowcnt++;
4226 	}
4227 	mutex_exit(&page_llock);
4228 	return (1);
4229 }
4230 
4231 int
4232 page_subclaim_pages(page_t  **ppa)
4233 {
4234 	pgcnt_t	ulckpgs = 0, pg_idx;
4235 
4236 	VM_STAT_ADD(pagecnt.pc_subclaim_pages);
4237 
4238 	mutex_enter(&page_llock);
4239 	for (pg_idx = 0; ppa[pg_idx] != NULL; pg_idx++) {
4240 
4241 		ASSERT(PAGE_LOCKED(ppa[pg_idx]));
4242 		ASSERT(ppa[pg_idx]->p_cowcnt != 0);
4243 		if (ppa[pg_idx]->p_lckcnt == (ushort_t)PAGE_LOCK_MAXIMUM) {
4244 			mutex_exit(&page_llock);
4245 			return (0);
4246 		}
4247 		if (ppa[pg_idx]->p_lckcnt != 0)
4248 			ulckpgs++;
4249 	}
4250 
4251 	if (ulckpgs != 0) {
4252 		mutex_enter(&freemem_lock);
4253 		availrmem += ulckpgs;
4254 		pages_claimed -= ulckpgs;
4255 		mutex_exit(&freemem_lock);
4256 	}
4257 
4258 	for (pg_idx = 0; ppa[pg_idx] != NULL; pg_idx++) {
4259 		ppa[pg_idx]->p_cowcnt--;
4260 		ppa[pg_idx]->p_lckcnt++;
4261 
4262 	}
4263 	mutex_exit(&page_llock);
4264 	return (1);
4265 }
4266 
4267 page_t *
4268 page_numtopp(pfn_t pfnum, se_t se)
4269 {
4270 	page_t *pp;
4271 
4272 retry:
4273 	pp = page_numtopp_nolock(pfnum);
4274 	if (pp == NULL) {
4275 		return ((page_t *)NULL);
4276 	}
4277 
4278 	/*
4279 	 * Acquire the appropriate lock on the page.
4280 	 */
4281 	while (!page_lock(pp, se, (kmutex_t *)NULL, P_RECLAIM)) {
4282 		if (page_pptonum(pp) != pfnum)
4283 			goto retry;
4284 		continue;
4285 	}
4286 
4287 	if (page_pptonum(pp) != pfnum) {
4288 		page_unlock(pp);
4289 		goto retry;
4290 	}
4291 
4292 	return (pp);
4293 }
4294 
4295 page_t *
4296 page_numtopp_noreclaim(pfn_t pfnum, se_t se)
4297 {
4298 	page_t *pp;
4299 
4300 retry:
4301 	pp = page_numtopp_nolock(pfnum);
4302 	if (pp == NULL) {
4303 		return ((page_t *)NULL);
4304 	}
4305 
4306 	/*
4307 	 * Acquire the appropriate lock on the page.
4308 	 */
4309 	while (!page_lock(pp, se, (kmutex_t *)NULL, P_NO_RECLAIM)) {
4310 		if (page_pptonum(pp) != pfnum)
4311 			goto retry;
4312 		continue;
4313 	}
4314 
4315 	if (page_pptonum(pp) != pfnum) {
4316 		page_unlock(pp);
4317 		goto retry;
4318 	}
4319 
4320 	return (pp);
4321 }
4322 
4323 /*
4324  * This routine is like page_numtopp, but will only return page structs
4325  * for pages which are ok for loading into hardware using the page struct.
4326  */
4327 page_t *
4328 page_numtopp_nowait(pfn_t pfnum, se_t se)
4329 {
4330 	page_t *pp;
4331 
4332 retry:
4333 	pp = page_numtopp_nolock(pfnum);
4334 	if (pp == NULL) {
4335 		return ((page_t *)NULL);
4336 	}
4337 
4338 	/*
4339 	 * Try to acquire the appropriate lock on the page.
4340 	 */
4341 	if (PP_ISFREE(pp))
4342 		pp = NULL;
4343 	else {
4344 		if (!page_trylock(pp, se))
4345 			pp = NULL;
4346 		else {
4347 			if (page_pptonum(pp) != pfnum) {
4348 				page_unlock(pp);
4349 				goto retry;
4350 			}
4351 			if (PP_ISFREE(pp)) {
4352 				page_unlock(pp);
4353 				pp = NULL;
4354 			}
4355 		}
4356 	}
4357 	return (pp);
4358 }
4359 
4360 /*
4361  * Returns a count of dirty pages that are in the process
4362  * of being written out.  If 'cleanit' is set, try to push the page.
4363  */
4364 pgcnt_t
4365 page_busy(int cleanit)
4366 {
4367 	page_t *page0 = page_first();
4368 	page_t *pp = page0;
4369 	pgcnt_t nppbusy = 0;
4370 	u_offset_t off;
4371 
4372 	do {
4373 		vnode_t *vp = pp->p_vnode;
4374 
4375 		/*
4376 		 * A page is a candidate for syncing if it is:
4377 		 *
4378 		 * (a)	On neither the freelist nor the cachelist
4379 		 * (b)	Hashed onto a vnode
4380 		 * (c)	Not a kernel page
4381 		 * (d)	Dirty
4382 		 * (e)	Not part of a swapfile
4383 		 * (f)	a page which belongs to a real vnode; eg has a non-null
4384 		 *	v_vfsp pointer.
4385 		 * (g)	Backed by a filesystem which doesn't have a
4386 		 *	stubbed-out sync operation
4387 		 */
4388 		if (!PP_ISFREE(pp) && vp != NULL && !VN_ISKAS(vp) &&
4389 		    hat_ismod(pp) && !IS_SWAPVP(vp) && vp->v_vfsp != NULL &&
4390 		    vfs_can_sync(vp->v_vfsp)) {
4391 			nppbusy++;
4392 			vfs_syncprogress();
4393 
4394 			if (!cleanit)
4395 				continue;
4396 			if (!page_trylock(pp, SE_EXCL))
4397 				continue;
4398 
4399 			if (PP_ISFREE(pp) || vp == NULL || IS_SWAPVP(vp) ||
4400 			    pp->p_lckcnt != 0 || pp->p_cowcnt != 0 ||
4401 			    !(hat_pagesync(pp,
4402 			    HAT_SYNC_DONTZERO | HAT_SYNC_STOPON_MOD) & P_MOD)) {
4403 				page_unlock(pp);
4404 				continue;
4405 			}
4406 			off = pp->p_offset;
4407 			VN_HOLD(vp);
4408 			page_unlock(pp);
4409 			(void) VOP_PUTPAGE(vp, off, PAGESIZE,
4410 			    B_ASYNC | B_FREE, kcred, NULL);
4411 			VN_RELE(vp);
4412 		}
4413 	} while ((pp = page_next(pp)) != page0);
4414 
4415 	return (nppbusy);
4416 }
4417 
4418 void page_invalidate_pages(void);
4419 
4420 /*
4421  * callback handler to vm sub-system
4422  *
4423  * callers make sure no recursive entries to this func.
4424  */
4425 /*ARGSUSED*/
4426 boolean_t
4427 callb_vm_cpr(void *arg, int code)
4428 {
4429 	if (code == CB_CODE_CPR_CHKPT)
4430 		page_invalidate_pages();
4431 	return (B_TRUE);
4432 }
4433 
4434 /*
4435  * Invalidate all pages of the system.
4436  * It shouldn't be called until all user page activities are all stopped.
4437  */
4438 void
4439 page_invalidate_pages()
4440 {
4441 	page_t *pp;
4442 	page_t *page0;
4443 	pgcnt_t nbusypages;
4444 	int retry = 0;
4445 	const int MAXRETRIES = 4;
4446 #if defined(__sparc)
4447 	extern struct vnode prom_ppages;
4448 #endif /* __sparc */
4449 
4450 top:
4451 	/*
4452 	 * Flush dirty pages and destroy the clean ones.
4453 	 */
4454 	nbusypages = 0;
4455 
4456 	pp = page0 = page_first();
4457 	do {
4458 		struct vnode	*vp;
4459 		u_offset_t	offset;
4460 		int		mod;
4461 
4462 		/*
4463 		 * skip the page if it has no vnode or the page associated
4464 		 * with the kernel vnode or prom allocated kernel mem.
4465 		 */
4466 #if defined(__sparc)
4467 		if ((vp = pp->p_vnode) == NULL || VN_ISKAS(vp) ||
4468 		    vp == &prom_ppages)
4469 #else /* x86 doesn't have prom or prom_ppage */
4470 		if ((vp = pp->p_vnode) == NULL || VN_ISKAS(vp))
4471 #endif /* __sparc */
4472 			continue;
4473 
4474 		/*
4475 		 * skip the page which is already free invalidated.
4476 		 */
4477 		if (PP_ISFREE(pp) && PP_ISAGED(pp))
4478 			continue;
4479 
4480 		/*
4481 		 * skip pages that are already locked or can't be "exclusively"
4482 		 * locked or are already free.  After we lock the page, check
4483 		 * the free and age bits again to be sure it's not destroied
4484 		 * yet.
4485 		 * To achieve max. parallelization, we use page_trylock instead
4486 		 * of page_lock so that we don't get block on individual pages
4487 		 * while we have thousands of other pages to process.
4488 		 */
4489 		if (!page_trylock(pp, SE_EXCL)) {
4490 			nbusypages++;
4491 			continue;
4492 		} else if (PP_ISFREE(pp)) {
4493 			if (!PP_ISAGED(pp)) {
4494 				page_destroy_free(pp);
4495 			} else {
4496 				page_unlock(pp);
4497 			}
4498 			continue;
4499 		}
4500 		/*
4501 		 * Is this page involved in some I/O? shared?
4502 		 *
4503 		 * The page_struct_lock need not be acquired to
4504 		 * examine these fields since the page has an
4505 		 * "exclusive" lock.
4506 		 */
4507 		if (pp->p_lckcnt != 0 || pp->p_cowcnt != 0) {
4508 			page_unlock(pp);
4509 			continue;
4510 		}
4511 
4512 		if (vp->v_type == VCHR) {
4513 			panic("vp->v_type == VCHR");
4514 			/*NOTREACHED*/
4515 		}
4516 
4517 		if (!page_try_demote_pages(pp)) {
4518 			page_unlock(pp);
4519 			continue;
4520 		}
4521 
4522 		/*
4523 		 * Check the modified bit. Leave the bits alone in hardware
4524 		 * (they will be modified if we do the putpage).
4525 		 */
4526 		mod = (hat_pagesync(pp, HAT_SYNC_DONTZERO | HAT_SYNC_STOPON_MOD)
4527 		    & P_MOD);
4528 		if (mod) {
4529 			offset = pp->p_offset;
4530 			/*
4531 			 * Hold the vnode before releasing the page lock
4532 			 * to prevent it from being freed and re-used by
4533 			 * some other thread.
4534 			 */
4535 			VN_HOLD(vp);
4536 			page_unlock(pp);
4537 			/*
4538 			 * No error return is checked here. Callers such as
4539 			 * cpr deals with the dirty pages at the dump time
4540 			 * if this putpage fails.
4541 			 */
4542 			(void) VOP_PUTPAGE(vp, offset, PAGESIZE, B_INVAL,
4543 			    kcred, NULL);
4544 			VN_RELE(vp);
4545 		} else {
4546 			page_destroy(pp, 0);
4547 		}
4548 	} while ((pp = page_next(pp)) != page0);
4549 	if (nbusypages && retry++ < MAXRETRIES) {
4550 		delay(1);
4551 		goto top;
4552 	}
4553 }
4554 
4555 /*
4556  * Replace the page "old" with the page "new" on the page hash and vnode lists
4557  *
4558  * the replacement must be done in place, ie the equivalent sequence:
4559  *
4560  *	vp = old->p_vnode;
4561  *	off = old->p_offset;
4562  *	page_do_hashout(old)
4563  *	page_do_hashin(new, vp, off)
4564  *
4565  * doesn't work, since
4566  *  1) if old is the only page on the vnode, the v_pages list has a window
4567  *     where it looks empty. This will break file system assumptions.
4568  * and
4569  *  2) pvn_vplist_dirty() can't deal with pages moving on the v_pages list.
4570  */
4571 static void
4572 page_do_relocate_hash(page_t *new, page_t *old)
4573 {
4574 	page_t	**hash_list;
4575 	vnode_t	*vp = old->p_vnode;
4576 	kmutex_t *sep;
4577 
4578 	ASSERT(PAGE_EXCL(old));
4579 	ASSERT(PAGE_EXCL(new));
4580 	ASSERT(vp != NULL);
4581 	ASSERT(MUTEX_HELD(page_vnode_mutex(vp)));
4582 	ASSERT(MUTEX_HELD(PAGE_HASH_MUTEX(PAGE_HASH_FUNC(vp, old->p_offset))));
4583 
4584 	/*
4585 	 * First find old page on the page hash list
4586 	 */
4587 	hash_list = &page_hash[PAGE_HASH_FUNC(vp, old->p_offset)];
4588 
4589 	for (;;) {
4590 		if (*hash_list == old)
4591 			break;
4592 		if (*hash_list == NULL) {
4593 			panic("page_do_hashout");
4594 			/*NOTREACHED*/
4595 		}
4596 		hash_list = &(*hash_list)->p_hash;
4597 	}
4598 
4599 	/*
4600 	 * update new and replace old with new on the page hash list
4601 	 */
4602 	new->p_vnode = old->p_vnode;
4603 	new->p_offset = old->p_offset;
4604 	new->p_hash = old->p_hash;
4605 	*hash_list = new;
4606 
4607 	if ((new->p_vnode->v_flag & VISSWAP) != 0)
4608 		PP_SETSWAP(new);
4609 
4610 	/*
4611 	 * replace old with new on the vnode's page list
4612 	 */
4613 	if (old->p_vpnext == old) {
4614 		new->p_vpnext = new;
4615 		new->p_vpprev = new;
4616 	} else {
4617 		new->p_vpnext = old->p_vpnext;
4618 		new->p_vpprev = old->p_vpprev;
4619 		new->p_vpnext->p_vpprev = new;
4620 		new->p_vpprev->p_vpnext = new;
4621 	}
4622 	if (vp->v_pages == old)
4623 		vp->v_pages = new;
4624 
4625 	/*
4626 	 * clear out the old page
4627 	 */
4628 	old->p_hash = NULL;
4629 	old->p_vpnext = NULL;
4630 	old->p_vpprev = NULL;
4631 	old->p_vnode = NULL;
4632 	PP_CLRSWAP(old);
4633 	old->p_offset = (u_offset_t)-1;
4634 	page_clr_all_props(old);
4635 
4636 	/*
4637 	 * Wake up processes waiting for this page.  The page's
4638 	 * identity has been changed, and is probably not the
4639 	 * desired page any longer.
4640 	 */
4641 	sep = page_se_mutex(old);
4642 	mutex_enter(sep);
4643 	old->p_selock &= ~SE_EWANTED;
4644 	if (CV_HAS_WAITERS(&old->p_cv))
4645 		cv_broadcast(&old->p_cv);
4646 	mutex_exit(sep);
4647 }
4648 
4649 /*
4650  * This function moves the identity of page "pp_old" to page "pp_new".
4651  * Both pages must be locked on entry.  "pp_new" is free, has no identity,
4652  * and need not be hashed out from anywhere.
4653  */
4654 void
4655 page_relocate_hash(page_t *pp_new, page_t *pp_old)
4656 {
4657 	vnode_t *vp = pp_old->p_vnode;
4658 	u_offset_t off = pp_old->p_offset;
4659 	kmutex_t *phm, *vphm;
4660 
4661 	/*
4662 	 * Rehash two pages
4663 	 */
4664 	ASSERT(PAGE_EXCL(pp_old));
4665 	ASSERT(PAGE_EXCL(pp_new));
4666 	ASSERT(vp != NULL);
4667 	ASSERT(pp_new->p_vnode == NULL);
4668 
4669 	/*
4670 	 * hashout then hashin while holding the mutexes
4671 	 */
4672 	phm = PAGE_HASH_MUTEX(PAGE_HASH_FUNC(vp, off));
4673 	mutex_enter(phm);
4674 	vphm = page_vnode_mutex(vp);
4675 	mutex_enter(vphm);
4676 
4677 	page_do_relocate_hash(pp_new, pp_old);
4678 
4679 	mutex_exit(vphm);
4680 	mutex_exit(phm);
4681 
4682 	/*
4683 	 * The page_struct_lock need not be acquired for lckcnt and
4684 	 * cowcnt since the page has an "exclusive" lock.
4685 	 */
4686 	ASSERT(pp_new->p_lckcnt == 0);
4687 	ASSERT(pp_new->p_cowcnt == 0);
4688 	pp_new->p_lckcnt = pp_old->p_lckcnt;
4689 	pp_new->p_cowcnt = pp_old->p_cowcnt;
4690 	pp_old->p_lckcnt = pp_old->p_cowcnt = 0;
4691 
4692 	/* The following comment preserved from page_flip(). */
4693 	/* XXX - Do we need to protect fsdata? */
4694 	pp_new->p_fsdata = pp_old->p_fsdata;
4695 }
4696 
4697 /*
4698  * Helper routine used to lock all remaining members of a
4699  * large page. The caller is responsible for passing in a locked
4700  * pp. If pp is a large page, then it succeeds in locking all the
4701  * remaining constituent pages or it returns with only the
4702  * original page locked.
4703  *
4704  * Returns 1 on success, 0 on failure.
4705  *
4706  * If success is returned this routine guarantees p_szc for all constituent
4707  * pages of a large page pp belongs to can't change. To achieve this we
4708  * recheck szc of pp after locking all constituent pages and retry if szc
4709  * changed (it could only decrease). Since hat_page_demote() needs an EXCL
4710  * lock on one of constituent pages it can't be running after all constituent
4711  * pages are locked.  hat_page_demote() with a lock on a constituent page
4712  * outside of this large page (i.e. pp belonged to a larger large page) is
4713  * already done with all constituent pages of pp since the root's p_szc is
4714  * changed last. Therefore no need to synchronize with hat_page_demote() that
4715  * locked a constituent page outside of pp's current large page.
4716  */
4717 #ifdef DEBUG
4718 uint32_t gpg_trylock_mtbf = 0;
4719 #endif
4720 
4721 int
4722 group_page_trylock(page_t *pp, se_t se)
4723 {
4724 	page_t  *tpp;
4725 	pgcnt_t	npgs, i, j;
4726 	uint_t pszc = pp->p_szc;
4727 
4728 #ifdef DEBUG
4729 	if (gpg_trylock_mtbf && !(gethrtime() % gpg_trylock_mtbf)) {
4730 		return (0);
4731 	}
4732 #endif
4733 
4734 	if (pp != PP_GROUPLEADER(pp, pszc)) {
4735 		return (0);
4736 	}
4737 
4738 retry:
4739 	ASSERT(PAGE_LOCKED_SE(pp, se));
4740 	ASSERT(!PP_ISFREE(pp));
4741 	if (pszc == 0) {
4742 		return (1);
4743 	}
4744 	npgs = page_get_pagecnt(pszc);
4745 	tpp = pp + 1;
4746 	for (i = 1; i < npgs; i++, tpp++) {
4747 		if (!page_trylock(tpp, se)) {
4748 			tpp = pp + 1;
4749 			for (j = 1; j < i; j++, tpp++) {
4750 				page_unlock(tpp);
4751 			}
4752 			return (0);
4753 		}
4754 	}
4755 	if (pp->p_szc != pszc) {
4756 		ASSERT(pp->p_szc < pszc);
4757 		ASSERT(pp->p_vnode != NULL && !PP_ISKAS(pp) &&
4758 		    !IS_SWAPFSVP(pp->p_vnode));
4759 		tpp = pp + 1;
4760 		for (i = 1; i < npgs; i++, tpp++) {
4761 			page_unlock(tpp);
4762 		}
4763 		pszc = pp->p_szc;
4764 		goto retry;
4765 	}
4766 	return (1);
4767 }
4768 
4769 void
4770 group_page_unlock(page_t *pp)
4771 {
4772 	page_t *tpp;
4773 	pgcnt_t	npgs, i;
4774 
4775 	ASSERT(PAGE_LOCKED(pp));
4776 	ASSERT(!PP_ISFREE(pp));
4777 	ASSERT(pp == PP_PAGEROOT(pp));
4778 	npgs = page_get_pagecnt(pp->p_szc);
4779 	for (i = 1, tpp = pp + 1; i < npgs; i++, tpp++) {
4780 		page_unlock(tpp);
4781 	}
4782 }
4783 
4784 /*
4785  * returns
4786  * 0 		: on success and *nrelocp is number of relocated PAGESIZE pages
4787  * ERANGE	: this is not a base page
4788  * EBUSY	: failure to get locks on the page/pages
4789  * ENOMEM	: failure to obtain replacement pages
4790  * EAGAIN	: OBP has not yet completed its boot-time handoff to the kernel
4791  * EIO		: An error occurred while trying to copy the page data
4792  *
4793  * Return with all constituent members of target and replacement
4794  * SE_EXCL locked. It is the callers responsibility to drop the
4795  * locks.
4796  */
4797 int
4798 do_page_relocate(
4799 	page_t **target,
4800 	page_t **replacement,
4801 	int grouplock,
4802 	spgcnt_t *nrelocp,
4803 	lgrp_t *lgrp)
4804 {
4805 	page_t *first_repl;
4806 	page_t *repl;
4807 	page_t *targ;
4808 	page_t *pl = NULL;
4809 	uint_t ppattr;
4810 	pfn_t   pfn, repl_pfn;
4811 	uint_t	szc;
4812 	spgcnt_t npgs, i;
4813 	int repl_contig = 0;
4814 	uint_t flags = 0;
4815 	spgcnt_t dofree = 0;
4816 
4817 	*nrelocp = 0;
4818 
4819 #if defined(__sparc)
4820 	/*
4821 	 * We need to wait till OBP has completed
4822 	 * its boot-time handoff of its resources to the kernel
4823 	 * before we allow page relocation
4824 	 */
4825 	if (page_relocate_ready == 0) {
4826 		return (EAGAIN);
4827 	}
4828 #endif
4829 
4830 	/*
4831 	 * If this is not a base page,
4832 	 * just return with 0x0 pages relocated.
4833 	 */
4834 	targ = *target;
4835 	ASSERT(PAGE_EXCL(targ));
4836 	ASSERT(!PP_ISFREE(targ));
4837 	szc = targ->p_szc;
4838 	ASSERT(szc < mmu_page_sizes);
4839 	VM_STAT_ADD(vmm_vmstats.ppr_reloc[szc]);
4840 	pfn = targ->p_pagenum;
4841 	if (pfn != PFN_BASE(pfn, szc)) {
4842 		VM_STAT_ADD(vmm_vmstats.ppr_relocnoroot[szc]);
4843 		return (ERANGE);
4844 	}
4845 
4846 	if ((repl = *replacement) != NULL && repl->p_szc >= szc) {
4847 		repl_pfn = repl->p_pagenum;
4848 		if (repl_pfn != PFN_BASE(repl_pfn, szc)) {
4849 			VM_STAT_ADD(vmm_vmstats.ppr_reloc_replnoroot[szc]);
4850 			return (ERANGE);
4851 		}
4852 		repl_contig = 1;
4853 	}
4854 
4855 	/*
4856 	 * We must lock all members of this large page or we cannot
4857 	 * relocate any part of it.
4858 	 */
4859 	if (grouplock != 0 && !group_page_trylock(targ, SE_EXCL)) {
4860 		VM_STAT_ADD(vmm_vmstats.ppr_relocnolock[targ->p_szc]);
4861 		return (EBUSY);
4862 	}
4863 
4864 	/*
4865 	 * reread szc it could have been decreased before
4866 	 * group_page_trylock() was done.
4867 	 */
4868 	szc = targ->p_szc;
4869 	ASSERT(szc < mmu_page_sizes);
4870 	VM_STAT_ADD(vmm_vmstats.ppr_reloc[szc]);
4871 	ASSERT(pfn == PFN_BASE(pfn, szc));
4872 
4873 	npgs = page_get_pagecnt(targ->p_szc);
4874 
4875 	if (repl == NULL) {
4876 		dofree = npgs;		/* Size of target page in MMU pages */
4877 		if (!page_create_wait(dofree, 0)) {
4878 			if (grouplock != 0) {
4879 				group_page_unlock(targ);
4880 			}
4881 			VM_STAT_ADD(vmm_vmstats.ppr_relocnomem[szc]);
4882 			return (ENOMEM);
4883 		}
4884 
4885 		/*
4886 		 * seg kmem pages require that the target and replacement
4887 		 * page be the same pagesize.
4888 		 */
4889 		flags = (VN_ISKAS(targ->p_vnode)) ? PGR_SAMESZC : 0;
4890 		repl = page_get_replacement_page(targ, lgrp, flags);
4891 		if (repl == NULL) {
4892 			if (grouplock != 0) {
4893 				group_page_unlock(targ);
4894 			}
4895 			page_create_putback(dofree);
4896 			VM_STAT_ADD(vmm_vmstats.ppr_relocnomem[szc]);
4897 			return (ENOMEM);
4898 		}
4899 	}
4900 #ifdef DEBUG
4901 	else {
4902 		ASSERT(PAGE_LOCKED(repl));
4903 	}
4904 #endif /* DEBUG */
4905 
4906 #if defined(__sparc)
4907 	/*
4908 	 * Let hat_page_relocate() complete the relocation if it's kernel page
4909 	 */
4910 	if (VN_ISKAS(targ->p_vnode)) {
4911 		*replacement = repl;
4912 		if (hat_page_relocate(target, replacement, nrelocp) != 0) {
4913 			if (grouplock != 0) {
4914 				group_page_unlock(targ);
4915 			}
4916 			if (dofree) {
4917 				*replacement = NULL;
4918 				page_free_replacement_page(repl);
4919 				page_create_putback(dofree);
4920 			}
4921 			VM_STAT_ADD(vmm_vmstats.ppr_krelocfail[szc]);
4922 			return (EAGAIN);
4923 		}
4924 		VM_STAT_ADD(vmm_vmstats.ppr_relocok[szc]);
4925 		return (0);
4926 	}
4927 #else
4928 #if defined(lint)
4929 	dofree = dofree;
4930 #endif
4931 #endif
4932 
4933 	first_repl = repl;
4934 
4935 	for (i = 0; i < npgs; i++) {
4936 		ASSERT(PAGE_EXCL(targ));
4937 		ASSERT(targ->p_slckcnt == 0);
4938 		ASSERT(repl->p_slckcnt == 0);
4939 
4940 		(void) hat_pageunload(targ, HAT_FORCE_PGUNLOAD);
4941 
4942 		ASSERT(hat_page_getshare(targ) == 0);
4943 		ASSERT(!PP_ISFREE(targ));
4944 		ASSERT(targ->p_pagenum == (pfn + i));
4945 		ASSERT(repl_contig == 0 ||
4946 		    repl->p_pagenum == (repl_pfn + i));
4947 
4948 		/*
4949 		 * Copy the page contents and attributes then
4950 		 * relocate the page in the page hash.
4951 		 */
4952 		if (ppcopy(targ, repl) == 0) {
4953 			targ = *target;
4954 			repl = first_repl;
4955 			VM_STAT_ADD(vmm_vmstats.ppr_copyfail);
4956 			if (grouplock != 0) {
4957 				group_page_unlock(targ);
4958 			}
4959 			if (dofree) {
4960 				*replacement = NULL;
4961 				page_free_replacement_page(repl);
4962 				page_create_putback(dofree);
4963 			}
4964 			return (EIO);
4965 		}
4966 
4967 		targ++;
4968 		if (repl_contig != 0) {
4969 			repl++;
4970 		} else {
4971 			repl = repl->p_next;
4972 		}
4973 	}
4974 
4975 	repl = first_repl;
4976 	targ = *target;
4977 
4978 	for (i = 0; i < npgs; i++) {
4979 		ppattr = hat_page_getattr(targ, (P_MOD | P_REF | P_RO));
4980 		page_clr_all_props(repl);
4981 		page_set_props(repl, ppattr);
4982 		page_relocate_hash(repl, targ);
4983 
4984 		ASSERT(hat_page_getshare(targ) == 0);
4985 		ASSERT(hat_page_getshare(repl) == 0);
4986 		/*
4987 		 * Now clear the props on targ, after the
4988 		 * page_relocate_hash(), they no longer
4989 		 * have any meaning.
4990 		 */
4991 		page_clr_all_props(targ);
4992 		ASSERT(targ->p_next == targ);
4993 		ASSERT(targ->p_prev == targ);
4994 		page_list_concat(&pl, &targ);
4995 
4996 		targ++;
4997 		if (repl_contig != 0) {
4998 			repl++;
4999 		} else {
5000 			repl = repl->p_next;
5001 		}
5002 	}
5003 	/* assert that we have come full circle with repl */
5004 	ASSERT(repl_contig == 1 || first_repl == repl);
5005 
5006 	*target = pl;
5007 	if (*replacement == NULL) {
5008 		ASSERT(first_repl == repl);
5009 		*replacement = repl;
5010 	}
5011 	VM_STAT_ADD(vmm_vmstats.ppr_relocok[szc]);
5012 	*nrelocp = npgs;
5013 	return (0);
5014 }
5015 /*
5016  * On success returns 0 and *nrelocp the number of PAGESIZE pages relocated.
5017  */
5018 int
5019 page_relocate(
5020 	page_t **target,
5021 	page_t **replacement,
5022 	int grouplock,
5023 	int freetarget,
5024 	spgcnt_t *nrelocp,
5025 	lgrp_t *lgrp)
5026 {
5027 	spgcnt_t ret;
5028 
5029 	/* do_page_relocate returns 0 on success or errno value */
5030 	ret = do_page_relocate(target, replacement, grouplock, nrelocp, lgrp);
5031 
5032 	if (ret != 0 || freetarget == 0) {
5033 		return (ret);
5034 	}
5035 	if (*nrelocp == 1) {
5036 		ASSERT(*target != NULL);
5037 		page_free(*target, 1);
5038 	} else {
5039 		page_t *tpp = *target;
5040 		uint_t szc = tpp->p_szc;
5041 		pgcnt_t npgs = page_get_pagecnt(szc);
5042 		ASSERT(npgs > 1);
5043 		ASSERT(szc != 0);
5044 		do {
5045 			ASSERT(PAGE_EXCL(tpp));
5046 			ASSERT(!hat_page_is_mapped(tpp));
5047 			ASSERT(tpp->p_szc == szc);
5048 			PP_SETFREE(tpp);
5049 			PP_SETAGED(tpp);
5050 			npgs--;
5051 		} while ((tpp = tpp->p_next) != *target);
5052 		ASSERT(npgs == 0);
5053 		page_list_add_pages(*target, 0);
5054 		npgs = page_get_pagecnt(szc);
5055 		page_create_putback(npgs);
5056 	}
5057 	return (ret);
5058 }
5059 
5060 /*
5061  * it is up to the caller to deal with pcf accounting.
5062  */
5063 void
5064 page_free_replacement_page(page_t *pplist)
5065 {
5066 	page_t *pp;
5067 
5068 	while (pplist != NULL) {
5069 		/*
5070 		 * pp_targ is a linked list.
5071 		 */
5072 		pp = pplist;
5073 		if (pp->p_szc == 0) {
5074 			page_sub(&pplist, pp);
5075 			page_clr_all_props(pp);
5076 			PP_SETFREE(pp);
5077 			PP_SETAGED(pp);
5078 			page_list_add(pp, PG_FREE_LIST | PG_LIST_TAIL);
5079 			page_unlock(pp);
5080 			VM_STAT_ADD(pagecnt.pc_free_replacement_page[0]);
5081 		} else {
5082 			spgcnt_t curnpgs = page_get_pagecnt(pp->p_szc);
5083 			page_t *tpp;
5084 			page_list_break(&pp, &pplist, curnpgs);
5085 			tpp = pp;
5086 			do {
5087 				ASSERT(PAGE_EXCL(tpp));
5088 				ASSERT(!hat_page_is_mapped(tpp));
5089 				page_clr_all_props(pp);
5090 				PP_SETFREE(tpp);
5091 				PP_SETAGED(tpp);
5092 			} while ((tpp = tpp->p_next) != pp);
5093 			page_list_add_pages(pp, 0);
5094 			VM_STAT_ADD(pagecnt.pc_free_replacement_page[1]);
5095 		}
5096 	}
5097 }
5098 
5099 /*
5100  * Relocate target to non-relocatable replacement page.
5101  */
5102 int
5103 page_relocate_cage(page_t **target, page_t **replacement)
5104 {
5105 	page_t *tpp, *rpp;
5106 	spgcnt_t pgcnt, npgs;
5107 	int result;
5108 
5109 	tpp = *target;
5110 
5111 	ASSERT(PAGE_EXCL(tpp));
5112 	ASSERT(tpp->p_szc == 0);
5113 
5114 	pgcnt = btop(page_get_pagesize(tpp->p_szc));
5115 
5116 	do {
5117 		(void) page_create_wait(pgcnt, PG_WAIT | PG_NORELOC);
5118 		rpp = page_get_replacement_page(tpp, NULL, PGR_NORELOC);
5119 		if (rpp == NULL) {
5120 			page_create_putback(pgcnt);
5121 			kcage_cageout_wakeup();
5122 		}
5123 	} while (rpp == NULL);
5124 
5125 	ASSERT(PP_ISNORELOC(rpp));
5126 
5127 	result = page_relocate(&tpp, &rpp, 0, 1, &npgs, NULL);
5128 
5129 	if (result == 0) {
5130 		*replacement = rpp;
5131 		if (pgcnt != npgs)
5132 			panic("page_relocate_cage: partial relocation");
5133 	}
5134 
5135 	return (result);
5136 }
5137 
5138 /*
5139  * Release the page lock on a page, place on cachelist
5140  * tail if no longer mapped. Caller can let us know if
5141  * the page is known to be clean.
5142  */
5143 int
5144 page_release(page_t *pp, int checkmod)
5145 {
5146 	int status;
5147 
5148 	ASSERT(PAGE_LOCKED(pp) && !PP_ISFREE(pp) &&
5149 	    (pp->p_vnode != NULL));
5150 
5151 	if (!hat_page_is_mapped(pp) && !IS_SWAPVP(pp->p_vnode) &&
5152 	    ((PAGE_SHARED(pp) && page_tryupgrade(pp)) || PAGE_EXCL(pp)) &&
5153 	    pp->p_lckcnt == 0 && pp->p_cowcnt == 0 &&
5154 	    !hat_page_is_mapped(pp)) {
5155 
5156 		/*
5157 		 * If page is modified, unlock it
5158 		 *
5159 		 * (p_nrm & P_MOD) bit has the latest stuff because:
5160 		 * (1) We found that this page doesn't have any mappings
5161 		 *	_after_ holding SE_EXCL and
5162 		 * (2) We didn't drop SE_EXCL lock after the check in (1)
5163 		 */
5164 		if (checkmod && hat_ismod(pp)) {
5165 			page_unlock(pp);
5166 			status = PGREL_MOD;
5167 		} else {
5168 			/*LINTED: constant in conditional context*/
5169 			VN_DISPOSE(pp, B_FREE, 0, kcred);
5170 			status = PGREL_CLEAN;
5171 		}
5172 	} else {
5173 		page_unlock(pp);
5174 		status = PGREL_NOTREL;
5175 	}
5176 	return (status);
5177 }
5178 
5179 /*
5180  * Given a constituent page, try to demote the large page on the freelist.
5181  *
5182  * Returns nonzero if the page could be demoted successfully. Returns with
5183  * the constituent page still locked.
5184  */
5185 int
5186 page_try_demote_free_pages(page_t *pp)
5187 {
5188 	page_t *rootpp = pp;
5189 	pfn_t	pfn = page_pptonum(pp);
5190 	spgcnt_t npgs;
5191 	uint_t	szc = pp->p_szc;
5192 
5193 	ASSERT(PP_ISFREE(pp));
5194 	ASSERT(PAGE_EXCL(pp));
5195 
5196 	/*
5197 	 * Adjust rootpp and lock it, if `pp' is not the base
5198 	 * constituent page.
5199 	 */
5200 	npgs = page_get_pagecnt(pp->p_szc);
5201 	if (npgs == 1) {
5202 		return (0);
5203 	}
5204 
5205 	if (!IS_P2ALIGNED(pfn, npgs)) {
5206 		pfn = P2ALIGN(pfn, npgs);
5207 		rootpp = page_numtopp_nolock(pfn);
5208 	}
5209 
5210 	if (pp != rootpp && !page_trylock(rootpp, SE_EXCL)) {
5211 		return (0);
5212 	}
5213 
5214 	if (rootpp->p_szc != szc) {
5215 		if (pp != rootpp)
5216 			page_unlock(rootpp);
5217 		return (0);
5218 	}
5219 
5220 	page_demote_free_pages(rootpp);
5221 
5222 	if (pp != rootpp)
5223 		page_unlock(rootpp);
5224 
5225 	ASSERT(PP_ISFREE(pp));
5226 	ASSERT(PAGE_EXCL(pp));
5227 	return (1);
5228 }
5229 
5230 /*
5231  * Given a constituent page, try to demote the large page.
5232  *
5233  * Returns nonzero if the page could be demoted successfully. Returns with
5234  * the constituent page still locked.
5235  */
5236 int
5237 page_try_demote_pages(page_t *pp)
5238 {
5239 	page_t *tpp, *rootpp = pp;
5240 	pfn_t	pfn = page_pptonum(pp);
5241 	spgcnt_t i, npgs;
5242 	uint_t	szc = pp->p_szc;
5243 	vnode_t *vp = pp->p_vnode;
5244 
5245 	ASSERT(PAGE_EXCL(pp));
5246 
5247 	VM_STAT_ADD(pagecnt.pc_try_demote_pages[0]);
5248 
5249 	if (pp->p_szc == 0) {
5250 		VM_STAT_ADD(pagecnt.pc_try_demote_pages[1]);
5251 		return (1);
5252 	}
5253 
5254 	if (vp != NULL && !IS_SWAPFSVP(vp) && !VN_ISKAS(vp)) {
5255 		VM_STAT_ADD(pagecnt.pc_try_demote_pages[2]);
5256 		page_demote_vp_pages(pp);
5257 		ASSERT(pp->p_szc == 0);
5258 		return (1);
5259 	}
5260 
5261 	/*
5262 	 * Adjust rootpp if passed in is not the base
5263 	 * constituent page.
5264 	 */
5265 	npgs = page_get_pagecnt(pp->p_szc);
5266 	ASSERT(npgs > 1);
5267 	if (!IS_P2ALIGNED(pfn, npgs)) {
5268 		pfn = P2ALIGN(pfn, npgs);
5269 		rootpp = page_numtopp_nolock(pfn);
5270 		VM_STAT_ADD(pagecnt.pc_try_demote_pages[3]);
5271 		ASSERT(rootpp->p_vnode != NULL);
5272 		ASSERT(rootpp->p_szc == szc);
5273 	}
5274 
5275 	/*
5276 	 * We can't demote kernel pages since we can't hat_unload()
5277 	 * the mappings.
5278 	 */
5279 	if (VN_ISKAS(rootpp->p_vnode))
5280 		return (0);
5281 
5282 	/*
5283 	 * Attempt to lock all constituent pages except the page passed
5284 	 * in since it's already locked.
5285 	 */
5286 	for (tpp = rootpp, i = 0; i < npgs; i++, tpp++) {
5287 		ASSERT(!PP_ISFREE(tpp));
5288 		ASSERT(tpp->p_vnode != NULL);
5289 
5290 		if (tpp != pp && !page_trylock(tpp, SE_EXCL))
5291 			break;
5292 		ASSERT(tpp->p_szc == rootpp->p_szc);
5293 		ASSERT(page_pptonum(tpp) == page_pptonum(rootpp) + i);
5294 	}
5295 
5296 	/*
5297 	 * If we failed to lock them all then unlock what we have
5298 	 * locked so far and bail.
5299 	 */
5300 	if (i < npgs) {
5301 		tpp = rootpp;
5302 		while (i-- > 0) {
5303 			if (tpp != pp)
5304 				page_unlock(tpp);
5305 			tpp++;
5306 		}
5307 		VM_STAT_ADD(pagecnt.pc_try_demote_pages[4]);
5308 		return (0);
5309 	}
5310 
5311 	for (tpp = rootpp, i = 0; i < npgs; i++, tpp++) {
5312 		ASSERT(PAGE_EXCL(tpp));
5313 		ASSERT(tpp->p_slckcnt == 0);
5314 		(void) hat_pageunload(tpp, HAT_FORCE_PGUNLOAD);
5315 		tpp->p_szc = 0;
5316 	}
5317 
5318 	/*
5319 	 * Unlock all pages except the page passed in.
5320 	 */
5321 	for (tpp = rootpp, i = 0; i < npgs; i++, tpp++) {
5322 		ASSERT(!hat_page_is_mapped(tpp));
5323 		if (tpp != pp)
5324 			page_unlock(tpp);
5325 	}
5326 
5327 	VM_STAT_ADD(pagecnt.pc_try_demote_pages[5]);
5328 	return (1);
5329 }
5330 
5331 /*
5332  * Called by page_free() and page_destroy() to demote the page size code
5333  * (p_szc) to 0 (since we can't just put a single PAGESIZE page with non zero
5334  * p_szc on free list, neither can we just clear p_szc of a single page_t
5335  * within a large page since it will break other code that relies on p_szc
5336  * being the same for all page_t's of a large page). Anonymous pages should
5337  * never end up here because anon_map_getpages() cannot deal with p_szc
5338  * changes after a single constituent page is locked.  While anonymous or
5339  * kernel large pages are demoted or freed the entire large page at a time
5340  * with all constituent pages locked EXCL for the file system pages we
5341  * have to be able to demote a large page (i.e. decrease all constituent pages
5342  * p_szc) with only just an EXCL lock on one of constituent pages. The reason
5343  * we can easily deal with anonymous page demotion the entire large page at a
5344  * time is that those operation originate at address space level and concern
5345  * the entire large page region with actual demotion only done when pages are
5346  * not shared with any other processes (therefore we can always get EXCL lock
5347  * on all anonymous constituent pages after clearing segment page
5348  * cache). However file system pages can be truncated or invalidated at a
5349  * PAGESIZE level from the file system side and end up in page_free() or
5350  * page_destroy() (we also allow only part of the large page to be SOFTLOCKed
5351  * and therefore pageout should be able to demote a large page by EXCL locking
5352  * any constituent page that is not under SOFTLOCK). In those cases we cannot
5353  * rely on being able to lock EXCL all constituent pages.
5354  *
5355  * To prevent szc changes on file system pages one has to lock all constituent
5356  * pages at least SHARED (or call page_szc_lock()). The only subsystem that
5357  * doesn't rely on locking all constituent pages (or using page_szc_lock()) to
5358  * prevent szc changes is hat layer that uses its own page level mlist
5359  * locks. hat assumes that szc doesn't change after mlist lock for a page is
5360  * taken. Therefore we need to change szc under hat level locks if we only
5361  * have an EXCL lock on a single constituent page and hat still references any
5362  * of constituent pages.  (Note we can't "ignore" hat layer by simply
5363  * hat_pageunload() all constituent pages without having EXCL locks on all of
5364  * constituent pages). We use hat_page_demote() call to safely demote szc of
5365  * all constituent pages under hat locks when we only have an EXCL lock on one
5366  * of constituent pages.
5367  *
5368  * This routine calls page_szc_lock() before calling hat_page_demote() to
5369  * allow segvn in one special case not to lock all constituent pages SHARED
5370  * before calling hat_memload_array() that relies on p_szc not changing even
5371  * before hat level mlist lock is taken.  In that case segvn uses
5372  * page_szc_lock() to prevent hat_page_demote() changing p_szc values.
5373  *
5374  * Anonymous or kernel page demotion still has to lock all pages exclusively
5375  * and do hat_pageunload() on all constituent pages before demoting the page
5376  * therefore there's no need for anonymous or kernel page demotion to use
5377  * hat_page_demote() mechanism.
5378  *
5379  * hat_page_demote() removes all large mappings that map pp and then decreases
5380  * p_szc starting from the last constituent page of the large page. By working
5381  * from the tail of a large page in pfn decreasing order allows one looking at
5382  * the root page to know that hat_page_demote() is done for root's szc area.
5383  * e.g. if a root page has szc 1 one knows it only has to lock all constituent
5384  * pages within szc 1 area to prevent szc changes because hat_page_demote()
5385  * that started on this page when it had szc > 1 is done for this szc 1 area.
5386  *
5387  * We are guaranteed that all constituent pages of pp's large page belong to
5388  * the same vnode with the consecutive offsets increasing in the direction of
5389  * the pfn i.e. the identity of constituent pages can't change until their
5390  * p_szc is decreased. Therefore it's safe for hat_page_demote() to remove
5391  * large mappings to pp even though we don't lock any constituent page except
5392  * pp (i.e. we won't unload e.g. kernel locked page).
5393  */
5394 static void
5395 page_demote_vp_pages(page_t *pp)
5396 {
5397 	kmutex_t *mtx;
5398 
5399 	ASSERT(PAGE_EXCL(pp));
5400 	ASSERT(!PP_ISFREE(pp));
5401 	ASSERT(pp->p_vnode != NULL);
5402 	ASSERT(!IS_SWAPFSVP(pp->p_vnode));
5403 	ASSERT(!PP_ISKAS(pp));
5404 
5405 	VM_STAT_ADD(pagecnt.pc_demote_pages[0]);
5406 
5407 	mtx = page_szc_lock(pp);
5408 	if (mtx != NULL) {
5409 		hat_page_demote(pp);
5410 		mutex_exit(mtx);
5411 	}
5412 	ASSERT(pp->p_szc == 0);
5413 }
5414 
5415 /*
5416  * Mark any existing pages for migration in the given range
5417  */
5418 void
5419 page_mark_migrate(struct seg *seg, caddr_t addr, size_t len,
5420     struct anon_map *amp, ulong_t anon_index, vnode_t *vp,
5421     u_offset_t vnoff, int rflag)
5422 {
5423 	struct anon	*ap;
5424 	vnode_t		*curvp;
5425 	lgrp_t		*from;
5426 	pgcnt_t		i;
5427 	pgcnt_t		nlocked;
5428 	u_offset_t	off;
5429 	pfn_t		pfn;
5430 	size_t		pgsz;
5431 	size_t		segpgsz;
5432 	pgcnt_t		pages;
5433 	uint_t		pszc;
5434 	page_t		**ppa;
5435 	pgcnt_t		ppa_nentries;
5436 	page_t		*pp;
5437 	caddr_t		va;
5438 	ulong_t		an_idx;
5439 	anon_sync_obj_t	cookie;
5440 
5441 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
5442 
5443 	/*
5444 	 * Don't do anything if don't need to do lgroup optimizations
5445 	 * on this system
5446 	 */
5447 	if (!lgrp_optimizations())
5448 		return;
5449 
5450 	/*
5451 	 * Align address and length to (potentially large) page boundary
5452 	 */
5453 	segpgsz = page_get_pagesize(seg->s_szc);
5454 	addr = (caddr_t)P2ALIGN((uintptr_t)addr, segpgsz);
5455 	if (rflag)
5456 		len = P2ROUNDUP(len, segpgsz);
5457 
5458 	/*
5459 	 * Allocate page array to accommodate largest page size
5460 	 */
5461 	pgsz = page_get_pagesize(page_num_pagesizes() - 1);
5462 	ppa_nentries = btop(pgsz);
5463 	ppa = kmem_zalloc(ppa_nentries * sizeof (page_t *), KM_SLEEP);
5464 
5465 	/*
5466 	 * Do one (large) page at a time
5467 	 */
5468 	va = addr;
5469 	while (va < addr + len) {
5470 		/*
5471 		 * Lookup (root) page for vnode and offset corresponding to
5472 		 * this virtual address
5473 		 * Try anonmap first since there may be copy-on-write
5474 		 * pages, but initialize vnode pointer and offset using
5475 		 * vnode arguments just in case there isn't an amp.
5476 		 */
5477 		curvp = vp;
5478 		off = vnoff + va - seg->s_base;
5479 		if (amp) {
5480 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
5481 			an_idx = anon_index + seg_page(seg, va);
5482 			anon_array_enter(amp, an_idx, &cookie);
5483 			ap = anon_get_ptr(amp->ahp, an_idx);
5484 			if (ap)
5485 				swap_xlate(ap, &curvp, &off);
5486 			anon_array_exit(&cookie);
5487 			ANON_LOCK_EXIT(&amp->a_rwlock);
5488 		}
5489 
5490 		pp = NULL;
5491 		if (curvp)
5492 			pp = page_lookup(curvp, off, SE_SHARED);
5493 
5494 		/*
5495 		 * If there isn't a page at this virtual address,
5496 		 * skip to next page
5497 		 */
5498 		if (pp == NULL) {
5499 			va += PAGESIZE;
5500 			continue;
5501 		}
5502 
5503 		/*
5504 		 * Figure out which lgroup this page is in for kstats
5505 		 */
5506 		pfn = page_pptonum(pp);
5507 		from = lgrp_pfn_to_lgrp(pfn);
5508 
5509 		/*
5510 		 * Get page size, and round up and skip to next page boundary
5511 		 * if unaligned address
5512 		 */
5513 		pszc = pp->p_szc;
5514 		pgsz = page_get_pagesize(pszc);
5515 		pages = btop(pgsz);
5516 		if (!IS_P2ALIGNED(va, pgsz) ||
5517 		    !IS_P2ALIGNED(pfn, pages) ||
5518 		    pgsz > segpgsz) {
5519 			pgsz = MIN(pgsz, segpgsz);
5520 			page_unlock(pp);
5521 			i = btop(P2END((uintptr_t)va, pgsz) -
5522 			    (uintptr_t)va);
5523 			va = (caddr_t)P2END((uintptr_t)va, pgsz);
5524 			lgrp_stat_add(from->lgrp_id, LGRP_PMM_FAIL_PGS, i);
5525 			continue;
5526 		}
5527 
5528 		/*
5529 		 * Upgrade to exclusive lock on page
5530 		 */
5531 		if (!page_tryupgrade(pp)) {
5532 			page_unlock(pp);
5533 			va += pgsz;
5534 			lgrp_stat_add(from->lgrp_id, LGRP_PMM_FAIL_PGS,
5535 			    btop(pgsz));
5536 			continue;
5537 		}
5538 
5539 		/*
5540 		 * Remember pages locked exclusively and how many
5541 		 */
5542 		ppa[0] = pp;
5543 		nlocked = 1;
5544 
5545 		/*
5546 		 * Lock constituent pages if this is large page
5547 		 */
5548 		if (pages > 1) {
5549 			/*
5550 			 * Lock all constituents except root page, since it
5551 			 * should be locked already.
5552 			 */
5553 			for (i = 1; i < pages; i++) {
5554 				pp++;
5555 				if (!page_trylock(pp, SE_EXCL)) {
5556 					break;
5557 				}
5558 				if (PP_ISFREE(pp) ||
5559 				    pp->p_szc != pszc) {
5560 					/*
5561 					 * hat_page_demote() raced in with us.
5562 					 */
5563 					ASSERT(!IS_SWAPFSVP(curvp));
5564 					page_unlock(pp);
5565 					break;
5566 				}
5567 				ppa[nlocked] = pp;
5568 				nlocked++;
5569 			}
5570 		}
5571 
5572 		/*
5573 		 * If all constituent pages couldn't be locked,
5574 		 * unlock pages locked so far and skip to next page.
5575 		 */
5576 		if (nlocked != pages) {
5577 			for (i = 0; i < nlocked; i++)
5578 				page_unlock(ppa[i]);
5579 			va += pgsz;
5580 			lgrp_stat_add(from->lgrp_id, LGRP_PMM_FAIL_PGS,
5581 			    btop(pgsz));
5582 			continue;
5583 		}
5584 
5585 		/*
5586 		 * hat_page_demote() can no longer happen
5587 		 * since last cons page had the right p_szc after
5588 		 * all cons pages were locked. all cons pages
5589 		 * should now have the same p_szc.
5590 		 */
5591 
5592 		/*
5593 		 * All constituent pages locked successfully, so mark
5594 		 * large page for migration and unload the mappings of
5595 		 * constituent pages, so a fault will occur on any part of the
5596 		 * large page
5597 		 */
5598 		PP_SETMIGRATE(ppa[0]);
5599 		for (i = 0; i < nlocked; i++) {
5600 			pp = ppa[i];
5601 			(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
5602 			ASSERT(hat_page_getshare(pp) == 0);
5603 			page_unlock(pp);
5604 		}
5605 		lgrp_stat_add(from->lgrp_id, LGRP_PMM_PGS, nlocked);
5606 
5607 		va += pgsz;
5608 	}
5609 	kmem_free(ppa, ppa_nentries * sizeof (page_t *));
5610 }
5611 
5612 /*
5613  * Migrate any pages that have been marked for migration in the given range
5614  */
5615 void
5616 page_migrate(
5617 	struct seg	*seg,
5618 	caddr_t		addr,
5619 	page_t		**ppa,
5620 	pgcnt_t		npages)
5621 {
5622 	lgrp_t		*from;
5623 	lgrp_t		*to;
5624 	page_t		*newpp;
5625 	page_t		*pp;
5626 	pfn_t		pfn;
5627 	size_t		pgsz;
5628 	spgcnt_t	page_cnt;
5629 	spgcnt_t	i;
5630 	uint_t		pszc;
5631 
5632 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
5633 
5634 	while (npages > 0) {
5635 		pp = *ppa;
5636 		pszc = pp->p_szc;
5637 		pgsz = page_get_pagesize(pszc);
5638 		page_cnt = btop(pgsz);
5639 
5640 		/*
5641 		 * Check to see whether this page is marked for migration
5642 		 *
5643 		 * Assume that root page of large page is marked for
5644 		 * migration and none of the other constituent pages
5645 		 * are marked.  This really simplifies clearing the
5646 		 * migrate bit by not having to clear it from each
5647 		 * constituent page.
5648 		 *
5649 		 * note we don't want to relocate an entire large page if
5650 		 * someone is only using one subpage.
5651 		 */
5652 		if (npages < page_cnt)
5653 			break;
5654 
5655 		/*
5656 		 * Is it marked for migration?
5657 		 */
5658 		if (!PP_ISMIGRATE(pp))
5659 			goto next;
5660 
5661 		/*
5662 		 * Determine lgroups that page is being migrated between
5663 		 */
5664 		pfn = page_pptonum(pp);
5665 		if (!IS_P2ALIGNED(pfn, page_cnt)) {
5666 			break;
5667 		}
5668 		from = lgrp_pfn_to_lgrp(pfn);
5669 		to = lgrp_mem_choose(seg, addr, pgsz);
5670 
5671 		/*
5672 		 * Check to see whether we are trying to migrate page to lgroup
5673 		 * where it is allocated already
5674 		 */
5675 		if (to == from) {
5676 			PP_CLRMIGRATE(pp);
5677 			goto next;
5678 		}
5679 
5680 		/*
5681 		 * Need to get exclusive lock's to migrate
5682 		 */
5683 		for (i = 0; i < page_cnt; i++) {
5684 			ASSERT(PAGE_LOCKED(ppa[i]));
5685 			if (page_pptonum(ppa[i]) != pfn + i ||
5686 			    ppa[i]->p_szc != pszc) {
5687 				break;
5688 			}
5689 			if (!page_tryupgrade(ppa[i])) {
5690 				lgrp_stat_add(from->lgrp_id,
5691 				    LGRP_PM_FAIL_LOCK_PGS,
5692 				    page_cnt);
5693 				break;
5694 			}
5695 		}
5696 		if (i != page_cnt) {
5697 			while (--i != -1) {
5698 				page_downgrade(ppa[i]);
5699 			}
5700 			goto next;
5701 		}
5702 
5703 		(void) page_create_wait(page_cnt, PG_WAIT);
5704 		newpp = page_get_replacement_page(pp, to, PGR_SAMESZC);
5705 		if (newpp == NULL) {
5706 			page_create_putback(page_cnt);
5707 			for (i = 0; i < page_cnt; i++) {
5708 				page_downgrade(ppa[i]);
5709 			}
5710 			lgrp_stat_add(to->lgrp_id, LGRP_PM_FAIL_ALLOC_PGS,
5711 			    page_cnt);
5712 			goto next;
5713 		}
5714 		ASSERT(newpp->p_szc == pszc);
5715 		/*
5716 		 * Clear migrate bit and relocate page
5717 		 */
5718 		PP_CLRMIGRATE(pp);
5719 		if (page_relocate(&pp, &newpp, 0, 1, &page_cnt, to)) {
5720 			panic("page_migrate: page_relocate failed");
5721 		}
5722 		ASSERT(page_cnt * PAGESIZE == pgsz);
5723 
5724 		/*
5725 		 * Keep stats for number of pages migrated from and to
5726 		 * each lgroup
5727 		 */
5728 		lgrp_stat_add(from->lgrp_id, LGRP_PM_SRC_PGS, page_cnt);
5729 		lgrp_stat_add(to->lgrp_id, LGRP_PM_DEST_PGS, page_cnt);
5730 		/*
5731 		 * update the page_t array we were passed in and
5732 		 * unlink constituent pages of a large page.
5733 		 */
5734 		for (i = 0; i < page_cnt; ++i, ++pp) {
5735 			ASSERT(PAGE_EXCL(newpp));
5736 			ASSERT(newpp->p_szc == pszc);
5737 			ppa[i] = newpp;
5738 			pp = newpp;
5739 			page_sub(&newpp, pp);
5740 			page_downgrade(pp);
5741 		}
5742 		ASSERT(newpp == NULL);
5743 next:
5744 		addr += pgsz;
5745 		ppa += page_cnt;
5746 		npages -= page_cnt;
5747 	}
5748 }
5749 
5750 ulong_t mem_waiters 	= 0;
5751 ulong_t	max_count 	= 20;
5752 #define	MAX_DELAY	0x1ff
5753 
5754 /*
5755  * Check if enough memory is available to proceed.
5756  * Depending on system configuration and how much memory is
5757  * reserved for swap we need to check against two variables.
5758  * e.g. on systems with little physical swap availrmem can be
5759  * more reliable indicator of how much memory is available.
5760  * On systems with large phys swap freemem can be better indicator.
5761  * If freemem drops below threshold level don't return an error
5762  * immediately but wake up pageout to free memory and block.
5763  * This is done number of times. If pageout is not able to free
5764  * memory within certain time return an error.
5765  * The same applies for availrmem but kmem_reap is used to
5766  * free memory.
5767  */
5768 int
5769 page_mem_avail(pgcnt_t npages)
5770 {
5771 	ulong_t count;
5772 
5773 #if defined(__i386)
5774 	if (freemem > desfree + npages &&
5775 	    availrmem > swapfs_reserve + npages &&
5776 	    btop(vmem_size(heap_arena, VMEM_FREE)) > tune.t_minarmem +
5777 	    npages)
5778 		return (1);
5779 #else
5780 	if (freemem > desfree + npages &&
5781 	    availrmem > swapfs_reserve + npages)
5782 		return (1);
5783 #endif
5784 
5785 	count = max_count;
5786 	atomic_add_long(&mem_waiters, 1);
5787 
5788 	while (freemem < desfree + npages && --count) {
5789 		cv_signal(&proc_pageout->p_cv);
5790 		if (delay_sig(hz + (mem_waiters & MAX_DELAY))) {
5791 			atomic_add_long(&mem_waiters, -1);
5792 			return (0);
5793 		}
5794 	}
5795 	if (count == 0) {
5796 		atomic_add_long(&mem_waiters, -1);
5797 		return (0);
5798 	}
5799 
5800 	count = max_count;
5801 	while (availrmem < swapfs_reserve + npages && --count) {
5802 		kmem_reap();
5803 		if (delay_sig(hz + (mem_waiters & MAX_DELAY))) {
5804 			atomic_add_long(&mem_waiters, -1);
5805 			return (0);
5806 		}
5807 	}
5808 	atomic_add_long(&mem_waiters, -1);
5809 	if (count == 0)
5810 		return (0);
5811 
5812 #if defined(__i386)
5813 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
5814 	    tune.t_minarmem + npages)
5815 		return (0);
5816 #endif
5817 	return (1);
5818 }
5819 
5820 #define	MAX_CNT	60	/* max num of iterations */
5821 /*
5822  * Reclaim/reserve availrmem for npages.
5823  * If there is not enough memory start reaping seg, kmem caches.
5824  * Start pageout scanner (via page_needfree()).
5825  * Exit after ~ MAX_CNT s regardless of how much memory has been released.
5826  * Note: There is no guarantee that any availrmem will be freed as
5827  * this memory typically is locked (kernel heap) or reserved for swap.
5828  * Also due to memory fragmentation kmem allocator may not be able
5829  * to free any memory (single user allocated buffer will prevent
5830  * freeing slab or a page).
5831  */
5832 int
5833 page_reclaim_mem(pgcnt_t npages, pgcnt_t epages, int adjust)
5834 {
5835 	int	i = 0;
5836 	int	ret = 0;
5837 	pgcnt_t	deficit;
5838 	pgcnt_t old_availrmem;
5839 
5840 	mutex_enter(&freemem_lock);
5841 	old_availrmem = availrmem - 1;
5842 	while ((availrmem < tune.t_minarmem + npages + epages) &&
5843 	    (old_availrmem < availrmem) && (i++ < MAX_CNT)) {
5844 		old_availrmem = availrmem;
5845 		deficit = tune.t_minarmem + npages + epages - availrmem;
5846 		mutex_exit(&freemem_lock);
5847 		page_needfree(deficit);
5848 		seg_preap();
5849 		kmem_reap();
5850 		delay(hz);
5851 		page_needfree(-(spgcnt_t)deficit);
5852 		mutex_enter(&freemem_lock);
5853 	}
5854 
5855 	if (adjust && (availrmem >= tune.t_minarmem + npages + epages)) {
5856 		availrmem -= npages;
5857 		ret = 1;
5858 	}
5859 
5860 	mutex_exit(&freemem_lock);
5861 
5862 	return (ret);
5863 }
5864 
5865 /*
5866  * Search the memory segments to locate the desired page.  Within a
5867  * segment, pages increase linearly with one page structure per
5868  * physical page frame (size PAGESIZE).  The search begins
5869  * with the segment that was accessed last, to take advantage of locality.
5870  * If the hint misses, we start from the beginning of the sorted memseg list
5871  */
5872 
5873 
5874 /*
5875  * Some data structures for pfn to pp lookup.
5876  */
5877 ulong_t mhash_per_slot;
5878 struct memseg *memseg_hash[N_MEM_SLOTS];
5879 
5880 page_t *
5881 page_numtopp_nolock(pfn_t pfnum)
5882 {
5883 	struct memseg *seg;
5884 	page_t *pp;
5885 	vm_cpu_data_t *vc = CPU->cpu_vm_data;
5886 
5887 	ASSERT(vc != NULL);
5888 
5889 	MEMSEG_STAT_INCR(nsearch);
5890 
5891 	/* Try last winner first */
5892 	if (((seg = vc->vc_pnum_memseg) != NULL) &&
5893 	    (pfnum >= seg->pages_base) && (pfnum < seg->pages_end)) {
5894 		MEMSEG_STAT_INCR(nlastwon);
5895 		pp = seg->pages + (pfnum - seg->pages_base);
5896 		if (pp->p_pagenum == pfnum)
5897 			return ((page_t *)pp);
5898 	}
5899 
5900 	/* Else Try hash */
5901 	if (((seg = memseg_hash[MEMSEG_PFN_HASH(pfnum)]) != NULL) &&
5902 	    (pfnum >= seg->pages_base) && (pfnum < seg->pages_end)) {
5903 		MEMSEG_STAT_INCR(nhashwon);
5904 		vc->vc_pnum_memseg = seg;
5905 		pp = seg->pages + (pfnum - seg->pages_base);
5906 		if (pp->p_pagenum == pfnum)
5907 			return ((page_t *)pp);
5908 	}
5909 
5910 	/* Else Brute force */
5911 	for (seg = memsegs; seg != NULL; seg = seg->next) {
5912 		if (pfnum >= seg->pages_base && pfnum < seg->pages_end) {
5913 			vc->vc_pnum_memseg = seg;
5914 			pp = seg->pages + (pfnum - seg->pages_base);
5915 			return ((page_t *)pp);
5916 		}
5917 	}
5918 	vc->vc_pnum_memseg = NULL;
5919 	MEMSEG_STAT_INCR(nnotfound);
5920 	return ((page_t *)NULL);
5921 
5922 }
5923 
5924 struct memseg *
5925 page_numtomemseg_nolock(pfn_t pfnum)
5926 {
5927 	struct memseg *seg;
5928 	page_t *pp;
5929 
5930 	/* Try hash */
5931 	if (((seg = memseg_hash[MEMSEG_PFN_HASH(pfnum)]) != NULL) &&
5932 	    (pfnum >= seg->pages_base) && (pfnum < seg->pages_end)) {
5933 		pp = seg->pages + (pfnum - seg->pages_base);
5934 		if (pp->p_pagenum == pfnum)
5935 			return (seg);
5936 	}
5937 
5938 	/* Else Brute force */
5939 	for (seg = memsegs; seg != NULL; seg = seg->next) {
5940 		if (pfnum >= seg->pages_base && pfnum < seg->pages_end) {
5941 			return (seg);
5942 		}
5943 	}
5944 	return ((struct memseg *)NULL);
5945 }
5946 
5947 /*
5948  * Given a page and a count return the page struct that is
5949  * n structs away from the current one in the global page
5950  * list.
5951  *
5952  * This function wraps to the first page upon
5953  * reaching the end of the memseg list.
5954  */
5955 page_t *
5956 page_nextn(page_t *pp, ulong_t n)
5957 {
5958 	struct memseg *seg;
5959 	page_t *ppn;
5960 	vm_cpu_data_t *vc = (vm_cpu_data_t *)CPU->cpu_vm_data;
5961 
5962 	ASSERT(vc != NULL);
5963 
5964 	if (((seg = vc->vc_pnext_memseg) == NULL) ||
5965 	    (seg->pages_base == seg->pages_end) ||
5966 	    !(pp >= seg->pages && pp < seg->epages)) {
5967 
5968 		for (seg = memsegs; seg; seg = seg->next) {
5969 			if (pp >= seg->pages && pp < seg->epages)
5970 				break;
5971 		}
5972 
5973 		if (seg == NULL) {
5974 			/* Memory delete got in, return something valid. */
5975 			/* TODO: fix me. */
5976 			seg = memsegs;
5977 			pp = seg->pages;
5978 		}
5979 	}
5980 
5981 	/* check for wraparound - possible if n is large */
5982 	while ((ppn = (pp + n)) >= seg->epages || ppn < pp) {
5983 		n -= seg->epages - pp;
5984 		seg = seg->next;
5985 		if (seg == NULL)
5986 			seg = memsegs;
5987 		pp = seg->pages;
5988 	}
5989 	vc->vc_pnext_memseg = seg;
5990 	return (ppn);
5991 }
5992 
5993 /*
5994  * Initialize for a loop using page_next_scan_large().
5995  */
5996 page_t *
5997 page_next_scan_init(void **cookie)
5998 {
5999 	ASSERT(cookie != NULL);
6000 	*cookie = (void *)memsegs;
6001 	return ((page_t *)memsegs->pages);
6002 }
6003 
6004 /*
6005  * Return the next page in a scan of page_t's, assuming we want
6006  * to skip over sub-pages within larger page sizes.
6007  *
6008  * The cookie is used to keep track of the current memseg.
6009  */
6010 page_t *
6011 page_next_scan_large(
6012 	page_t		*pp,
6013 	ulong_t		*n,
6014 	void		**cookie)
6015 {
6016 	struct memseg	*seg = (struct memseg *)*cookie;
6017 	page_t		*new_pp;
6018 	ulong_t		cnt;
6019 	pfn_t		pfn;
6020 
6021 
6022 	/*
6023 	 * get the count of page_t's to skip based on the page size
6024 	 */
6025 	ASSERT(pp != NULL);
6026 	if (pp->p_szc == 0) {
6027 		cnt = 1;
6028 	} else {
6029 		pfn = page_pptonum(pp);
6030 		cnt = page_get_pagecnt(pp->p_szc);
6031 		cnt -= pfn & (cnt - 1);
6032 	}
6033 	*n += cnt;
6034 	new_pp = pp + cnt;
6035 
6036 	/*
6037 	 * Catch if we went past the end of the current memory segment. If so,
6038 	 * just move to the next segment with pages.
6039 	 */
6040 	if (new_pp >= seg->epages) {
6041 		do {
6042 			seg = seg->next;
6043 			if (seg == NULL)
6044 				seg = memsegs;
6045 		} while (seg->pages == seg->epages);
6046 		new_pp = seg->pages;
6047 		*cookie = (void *)seg;
6048 	}
6049 
6050 	return (new_pp);
6051 }
6052 
6053 
6054 /*
6055  * Returns next page in list. Note: this function wraps
6056  * to the first page in the list upon reaching the end
6057  * of the list. Callers should be aware of this fact.
6058  */
6059 
6060 /* We should change this be a #define */
6061 
6062 page_t *
6063 page_next(page_t *pp)
6064 {
6065 	return (page_nextn(pp, 1));
6066 }
6067 
6068 page_t *
6069 page_first()
6070 {
6071 	return ((page_t *)memsegs->pages);
6072 }
6073 
6074 
6075 /*
6076  * This routine is called at boot with the initial memory configuration
6077  * and when memory is added or removed.
6078  */
6079 void
6080 build_pfn_hash()
6081 {
6082 	pfn_t cur;
6083 	pgcnt_t index;
6084 	struct memseg *pseg;
6085 	int	i;
6086 
6087 	/*
6088 	 * Clear memseg_hash array.
6089 	 * Since memory add/delete is designed to operate concurrently
6090 	 * with normal operation, the hash rebuild must be able to run
6091 	 * concurrently with page_numtopp_nolock(). To support this
6092 	 * functionality, assignments to memseg_hash array members must
6093 	 * be done atomically.
6094 	 *
6095 	 * NOTE: bzero() does not currently guarantee this for kernel
6096 	 * threads, and cannot be used here.
6097 	 */
6098 	for (i = 0; i < N_MEM_SLOTS; i++)
6099 		memseg_hash[i] = NULL;
6100 
6101 	hat_kpm_mseghash_clear(N_MEM_SLOTS);
6102 
6103 	/*
6104 	 * Physmax is the last valid pfn.
6105 	 */
6106 	mhash_per_slot = (physmax + 1) >> MEM_HASH_SHIFT;
6107 	for (pseg = memsegs; pseg != NULL; pseg = pseg->next) {
6108 		index = MEMSEG_PFN_HASH(pseg->pages_base);
6109 		cur = pseg->pages_base;
6110 		do {
6111 			if (index >= N_MEM_SLOTS)
6112 				index = MEMSEG_PFN_HASH(cur);
6113 
6114 			if (memseg_hash[index] == NULL ||
6115 			    memseg_hash[index]->pages_base > pseg->pages_base) {
6116 				memseg_hash[index] = pseg;
6117 				hat_kpm_mseghash_update(index, pseg);
6118 			}
6119 			cur += mhash_per_slot;
6120 			index++;
6121 		} while (cur < pseg->pages_end);
6122 	}
6123 }
6124 
6125 /*
6126  * Return the pagenum for the pp
6127  */
6128 pfn_t
6129 page_pptonum(page_t *pp)
6130 {
6131 	return (pp->p_pagenum);
6132 }
6133 
6134 /*
6135  * interface to the referenced and modified etc bits
6136  * in the PSM part of the page struct
6137  * when no locking is desired.
6138  */
6139 void
6140 page_set_props(page_t *pp, uint_t flags)
6141 {
6142 	ASSERT((flags & ~(P_MOD | P_REF | P_RO)) == 0);
6143 	pp->p_nrm |= (uchar_t)flags;
6144 }
6145 
6146 void
6147 page_clr_all_props(page_t *pp)
6148 {
6149 	pp->p_nrm = 0;
6150 }
6151 
6152 /*
6153  * Clear p_lckcnt and p_cowcnt, adjusting freemem if required.
6154  */
6155 int
6156 page_clear_lck_cow(page_t *pp, int adjust)
6157 {
6158 	int	f_amount;
6159 
6160 	ASSERT(PAGE_EXCL(pp));
6161 
6162 	/*
6163 	 * The page_struct_lock need not be acquired here since
6164 	 * we require the caller hold the page exclusively locked.
6165 	 */
6166 	f_amount = 0;
6167 	if (pp->p_lckcnt) {
6168 		f_amount = 1;
6169 		pp->p_lckcnt = 0;
6170 	}
6171 	if (pp->p_cowcnt) {
6172 		f_amount += pp->p_cowcnt;
6173 		pp->p_cowcnt = 0;
6174 	}
6175 
6176 	if (adjust && f_amount) {
6177 		mutex_enter(&freemem_lock);
6178 		availrmem += f_amount;
6179 		mutex_exit(&freemem_lock);
6180 	}
6181 
6182 	return (f_amount);
6183 }
6184 
6185 /*
6186  * The following functions is called from free_vp_pages()
6187  * for an inexact estimate of a newly free'd page...
6188  */
6189 ulong_t
6190 page_share_cnt(page_t *pp)
6191 {
6192 	return (hat_page_getshare(pp));
6193 }
6194 
6195 int
6196 page_isshared(page_t *pp)
6197 {
6198 	return (hat_page_checkshare(pp, 1));
6199 }
6200 
6201 int
6202 page_isfree(page_t *pp)
6203 {
6204 	return (PP_ISFREE(pp));
6205 }
6206 
6207 int
6208 page_isref(page_t *pp)
6209 {
6210 	return (hat_page_getattr(pp, P_REF));
6211 }
6212 
6213 int
6214 page_ismod(page_t *pp)
6215 {
6216 	return (hat_page_getattr(pp, P_MOD));
6217 }
6218 
6219 /*
6220  * The following code all currently relates to the page capture logic:
6221  *
6222  * This logic is used for cases where there is a desire to claim a certain
6223  * physical page in the system for the caller.  As it may not be possible
6224  * to capture the page immediately, the p_toxic bits are used in the page
6225  * structure to indicate that someone wants to capture this page.  When the
6226  * page gets unlocked, the toxic flag will be noted and an attempt to capture
6227  * the page will be made.  If it is successful, the original callers callback
6228  * will be called with the page to do with it what they please.
6229  *
6230  * There is also an async thread which wakes up to attempt to capture
6231  * pages occasionally which have the capture bit set.  All of the pages which
6232  * need to be captured asynchronously have been inserted into the
6233  * page_capture_hash and thus this thread walks that hash list.  Items in the
6234  * hash have an expiration time so this thread handles that as well by removing
6235  * the item from the hash if it has expired.
6236  *
6237  * Some important things to note are:
6238  * - if the PR_CAPTURE bit is set on a page, then the page is in the
6239  *   page_capture_hash.  The page_capture_hash_head.pchh_mutex is needed
6240  *   to set and clear this bit, and while the lock is held is the only time
6241  *   you can add or remove an entry from the hash.
6242  * - the PR_CAPTURE bit can only be set and cleared while holding the
6243  *   page_capture_hash_head.pchh_mutex
6244  * - the t_flag field of the thread struct is used with the T_CAPTURING
6245  *   flag to prevent recursion while dealing with large pages.
6246  * - pages which need to be retired never expire on the page_capture_hash.
6247  */
6248 
6249 static void page_capture_thread(void);
6250 static kthread_t *pc_thread_id;
6251 kcondvar_t pc_cv;
6252 static kmutex_t pc_thread_mutex;
6253 static clock_t pc_thread_shortwait;
6254 static clock_t pc_thread_longwait;
6255 static int pc_thread_ism_retry;
6256 
6257 struct page_capture_callback pc_cb[PC_NUM_CALLBACKS];
6258 
6259 /* Note that this is a circular linked list */
6260 typedef struct page_capture_hash_bucket {
6261 	page_t *pp;
6262 	uint_t szc;
6263 	uint_t flags;
6264 	clock_t expires;	/* lbolt at which this request expires. */
6265 	void *datap;		/* Cached data passed in for callback */
6266 	struct page_capture_hash_bucket *next;
6267 	struct page_capture_hash_bucket *prev;
6268 } page_capture_hash_bucket_t;
6269 
6270 /*
6271  * Each hash bucket will have it's own mutex and two lists which are:
6272  * active (0):	represents requests which have not been processed by
6273  *		the page_capture async thread yet.
6274  * walked (1):	represents requests which have been processed by the
6275  *		page_capture async thread within it's given walk of this bucket.
6276  *
6277  * These are all needed so that we can synchronize all async page_capture
6278  * events.  When the async thread moves to a new bucket, it will append the
6279  * walked list to the active list and walk each item one at a time, moving it
6280  * from the active list to the walked list.  Thus if there is an async request
6281  * outstanding for a given page, it will always be in one of the two lists.
6282  * New requests will always be added to the active list.
6283  * If we were not able to capture a page before the request expired, we'd free
6284  * up the request structure which would indicate to page_capture that there is
6285  * no longer a need for the given page, and clear the PR_CAPTURE flag if
6286  * possible.
6287  */
6288 typedef struct page_capture_hash_head {
6289 	kmutex_t pchh_mutex;
6290 	uint_t num_pages;
6291 	page_capture_hash_bucket_t lists[2]; /* sentinel nodes */
6292 } page_capture_hash_head_t;
6293 
6294 #ifdef DEBUG
6295 #define	NUM_PAGE_CAPTURE_BUCKETS 4
6296 #else
6297 #define	NUM_PAGE_CAPTURE_BUCKETS 64
6298 #endif
6299 
6300 page_capture_hash_head_t page_capture_hash[NUM_PAGE_CAPTURE_BUCKETS];
6301 
6302 /* for now use a very simple hash based upon the size of a page struct */
6303 #define	PAGE_CAPTURE_HASH(pp)	\
6304 	((int)(((uintptr_t)pp >> 7) & (NUM_PAGE_CAPTURE_BUCKETS - 1)))
6305 
6306 extern pgcnt_t swapfs_minfree;
6307 
6308 int page_trycapture(page_t *pp, uint_t szc, uint_t flags, void *datap);
6309 
6310 /*
6311  * a callback function is required for page capture requests.
6312  */
6313 void
6314 page_capture_register_callback(uint_t index, clock_t duration,
6315     int (*cb_func)(page_t *, void *, uint_t))
6316 {
6317 	ASSERT(pc_cb[index].cb_active == 0);
6318 	ASSERT(cb_func != NULL);
6319 	rw_enter(&pc_cb[index].cb_rwlock, RW_WRITER);
6320 	pc_cb[index].duration = duration;
6321 	pc_cb[index].cb_func = cb_func;
6322 	pc_cb[index].cb_active = 1;
6323 	rw_exit(&pc_cb[index].cb_rwlock);
6324 }
6325 
6326 void
6327 page_capture_unregister_callback(uint_t index)
6328 {
6329 	int i, j;
6330 	struct page_capture_hash_bucket *bp1;
6331 	struct page_capture_hash_bucket *bp2;
6332 	struct page_capture_hash_bucket *head = NULL;
6333 	uint_t flags = (1 << index);
6334 
6335 	rw_enter(&pc_cb[index].cb_rwlock, RW_WRITER);
6336 	ASSERT(pc_cb[index].cb_active == 1);
6337 	pc_cb[index].duration = 0;	/* Paranoia */
6338 	pc_cb[index].cb_func = NULL;	/* Paranoia */
6339 	pc_cb[index].cb_active = 0;
6340 	rw_exit(&pc_cb[index].cb_rwlock);
6341 
6342 	/*
6343 	 * Just move all the entries to a private list which we can walk
6344 	 * through without the need to hold any locks.
6345 	 * No more requests can get added to the hash lists for this consumer
6346 	 * as the cb_active field for the callback has been cleared.
6347 	 */
6348 	for (i = 0; i < NUM_PAGE_CAPTURE_BUCKETS; i++) {
6349 		mutex_enter(&page_capture_hash[i].pchh_mutex);
6350 		for (j = 0; j < 2; j++) {
6351 			bp1 = page_capture_hash[i].lists[j].next;
6352 			/* walk through all but first (sentinel) element */
6353 			while (bp1 != &page_capture_hash[i].lists[j]) {
6354 				bp2 = bp1;
6355 				if (bp2->flags & flags) {
6356 					bp1 = bp2->next;
6357 					bp1->prev = bp2->prev;
6358 					bp2->prev->next = bp1;
6359 					bp2->next = head;
6360 					head = bp2;
6361 					/*
6362 					 * Clear the PR_CAPTURE bit as we
6363 					 * hold appropriate locks here.
6364 					 */
6365 					page_clrtoxic(head->pp, PR_CAPTURE);
6366 					page_capture_hash[i].num_pages--;
6367 					continue;
6368 				}
6369 				bp1 = bp1->next;
6370 			}
6371 		}
6372 		mutex_exit(&page_capture_hash[i].pchh_mutex);
6373 	}
6374 
6375 	while (head != NULL) {
6376 		bp1 = head;
6377 		head = head->next;
6378 		kmem_free(bp1, sizeof (*bp1));
6379 	}
6380 }
6381 
6382 
6383 /*
6384  * Find pp in the active list and move it to the walked list if it
6385  * exists.
6386  * Note that most often pp should be at the front of the active list
6387  * as it is currently used and thus there is no other sort of optimization
6388  * being done here as this is a linked list data structure.
6389  * Returns 1 on successful move or 0 if page could not be found.
6390  */
6391 static int
6392 page_capture_move_to_walked(page_t *pp)
6393 {
6394 	page_capture_hash_bucket_t *bp;
6395 	int index;
6396 
6397 	index = PAGE_CAPTURE_HASH(pp);
6398 
6399 	mutex_enter(&page_capture_hash[index].pchh_mutex);
6400 	bp = page_capture_hash[index].lists[0].next;
6401 	while (bp != &page_capture_hash[index].lists[0]) {
6402 		if (bp->pp == pp) {
6403 			/* Remove from old list */
6404 			bp->next->prev = bp->prev;
6405 			bp->prev->next = bp->next;
6406 
6407 			/* Add to new list */
6408 			bp->next = page_capture_hash[index].lists[1].next;
6409 			bp->prev = &page_capture_hash[index].lists[1];
6410 			page_capture_hash[index].lists[1].next = bp;
6411 			bp->next->prev = bp;
6412 			mutex_exit(&page_capture_hash[index].pchh_mutex);
6413 
6414 			return (1);
6415 		}
6416 		bp = bp->next;
6417 	}
6418 	mutex_exit(&page_capture_hash[index].pchh_mutex);
6419 	return (0);
6420 }
6421 
6422 /*
6423  * Add a new entry to the page capture hash.  The only case where a new
6424  * entry is not added is when the page capture consumer is no longer registered.
6425  * In this case, we'll silently not add the page to the hash.  We know that
6426  * page retire will always be registered for the case where we are currently
6427  * unretiring a page and thus there are no conflicts.
6428  */
6429 static void
6430 page_capture_add_hash(page_t *pp, uint_t szc, uint_t flags, void *datap)
6431 {
6432 	page_capture_hash_bucket_t *bp1;
6433 	page_capture_hash_bucket_t *bp2;
6434 	int index;
6435 	int cb_index;
6436 	int i;
6437 #ifdef DEBUG
6438 	page_capture_hash_bucket_t *tp1;
6439 	int l;
6440 #endif
6441 
6442 	ASSERT(!(flags & CAPTURE_ASYNC));
6443 
6444 	bp1 = kmem_alloc(sizeof (struct page_capture_hash_bucket), KM_SLEEP);
6445 
6446 	bp1->pp = pp;
6447 	bp1->szc = szc;
6448 	bp1->flags = flags;
6449 	bp1->datap = datap;
6450 
6451 	for (cb_index = 0; cb_index < PC_NUM_CALLBACKS; cb_index++) {
6452 		if ((flags >> cb_index) & 1) {
6453 			break;
6454 		}
6455 	}
6456 
6457 	ASSERT(cb_index != PC_NUM_CALLBACKS);
6458 
6459 	rw_enter(&pc_cb[cb_index].cb_rwlock, RW_READER);
6460 	if (pc_cb[cb_index].cb_active) {
6461 		if (pc_cb[cb_index].duration == -1) {
6462 			bp1->expires = (clock_t)-1;
6463 		} else {
6464 			bp1->expires = lbolt + pc_cb[cb_index].duration;
6465 		}
6466 	} else {
6467 		/* There's no callback registered so don't add to the hash */
6468 		rw_exit(&pc_cb[cb_index].cb_rwlock);
6469 		kmem_free(bp1, sizeof (*bp1));
6470 		return;
6471 	}
6472 
6473 	index = PAGE_CAPTURE_HASH(pp);
6474 
6475 	/*
6476 	 * Only allow capture flag to be modified under this mutex.
6477 	 * Prevents multiple entries for same page getting added.
6478 	 */
6479 	mutex_enter(&page_capture_hash[index].pchh_mutex);
6480 
6481 	/*
6482 	 * if not already on the hash, set capture bit and add to the hash
6483 	 */
6484 	if (!(pp->p_toxic & PR_CAPTURE)) {
6485 #ifdef DEBUG
6486 		/* Check for duplicate entries */
6487 		for (l = 0; l < 2; l++) {
6488 			tp1 = page_capture_hash[index].lists[l].next;
6489 			while (tp1 != &page_capture_hash[index].lists[l]) {
6490 				if (tp1->pp == pp) {
6491 					panic("page pp 0x%p already on hash "
6492 					    "at 0x%p\n", pp, tp1);
6493 				}
6494 				tp1 = tp1->next;
6495 			}
6496 		}
6497 
6498 #endif
6499 		page_settoxic(pp, PR_CAPTURE);
6500 		bp1->next = page_capture_hash[index].lists[0].next;
6501 		bp1->prev = &page_capture_hash[index].lists[0];
6502 		bp1->next->prev = bp1;
6503 		page_capture_hash[index].lists[0].next = bp1;
6504 		page_capture_hash[index].num_pages++;
6505 		if (flags & CAPTURE_RETIRE) {
6506 			page_retire_incr_pend_count();
6507 		}
6508 		mutex_exit(&page_capture_hash[index].pchh_mutex);
6509 		rw_exit(&pc_cb[cb_index].cb_rwlock);
6510 		cv_signal(&pc_cv);
6511 		return;
6512 	}
6513 
6514 	/*
6515 	 * A page retire request will replace any other request.
6516 	 * A second physmem request which is for a different process than
6517 	 * the currently registered one will be dropped as there is
6518 	 * no way to hold the private data for both calls.
6519 	 * In the future, once there are more callers, this will have to
6520 	 * be worked out better as there needs to be private storage for
6521 	 * at least each type of caller (maybe have datap be an array of
6522 	 * *void's so that we can index based upon callers index).
6523 	 */
6524 
6525 	/* walk hash list to update expire time */
6526 	for (i = 0; i < 2; i++) {
6527 		bp2 = page_capture_hash[index].lists[i].next;
6528 		while (bp2 != &page_capture_hash[index].lists[i]) {
6529 			if (bp2->pp == pp) {
6530 				if (flags & CAPTURE_RETIRE) {
6531 					if (!(bp2->flags & CAPTURE_RETIRE)) {
6532 						page_retire_incr_pend_count();
6533 						bp2->flags = flags;
6534 						bp2->expires = bp1->expires;
6535 						bp2->datap = datap;
6536 					}
6537 				} else {
6538 					ASSERT(flags & CAPTURE_PHYSMEM);
6539 					if (!(bp2->flags & CAPTURE_RETIRE) &&
6540 					    (datap == bp2->datap)) {
6541 						bp2->expires = bp1->expires;
6542 					}
6543 				}
6544 				mutex_exit(&page_capture_hash[index].
6545 				    pchh_mutex);
6546 				rw_exit(&pc_cb[cb_index].cb_rwlock);
6547 				kmem_free(bp1, sizeof (*bp1));
6548 				return;
6549 			}
6550 			bp2 = bp2->next;
6551 		}
6552 	}
6553 
6554 	/*
6555 	 * the PR_CAPTURE flag is protected by the page_capture_hash mutexes
6556 	 * and thus it either has to be set or not set and can't change
6557 	 * while holding the mutex above.
6558 	 */
6559 	panic("page_capture_add_hash, PR_CAPTURE flag set on pp %p\n", pp);
6560 }
6561 
6562 /*
6563  * We have a page in our hands, lets try and make it ours by turning
6564  * it into a clean page like it had just come off the freelists.
6565  *
6566  * Returns 0 on success, with the page still EXCL locked.
6567  * On failure, the page will be unlocked, and returns EAGAIN
6568  */
6569 static int
6570 page_capture_clean_page(page_t *pp)
6571 {
6572 	page_t *newpp;
6573 	int skip_unlock = 0;
6574 	spgcnt_t count;
6575 	page_t *tpp;
6576 	int ret = 0;
6577 	int extra;
6578 
6579 	ASSERT(PAGE_EXCL(pp));
6580 	ASSERT(!PP_RETIRED(pp));
6581 	ASSERT(curthread->t_flag & T_CAPTURING);
6582 
6583 	if (PP_ISFREE(pp)) {
6584 		if (!page_reclaim(pp, NULL)) {
6585 			skip_unlock = 1;
6586 			ret = EAGAIN;
6587 			goto cleanup;
6588 		}
6589 		ASSERT(pp->p_szc == 0);
6590 		if (pp->p_vnode != NULL) {
6591 			/*
6592 			 * Since this page came from the
6593 			 * cachelist, we must destroy the
6594 			 * old vnode association.
6595 			 */
6596 			page_hashout(pp, NULL);
6597 		}
6598 		goto cleanup;
6599 	}
6600 
6601 	/*
6602 	 * If we know page_relocate will fail, skip it
6603 	 * It could still fail due to a UE on another page but we
6604 	 * can't do anything about that.
6605 	 */
6606 	if (pp->p_toxic & PR_UE) {
6607 		goto skip_relocate;
6608 	}
6609 
6610 	/*
6611 	 * It's possible that pages can not have a vnode as fsflush comes
6612 	 * through and cleans up these pages.  It's ugly but that's how it is.
6613 	 */
6614 	if (pp->p_vnode == NULL) {
6615 		goto skip_relocate;
6616 	}
6617 
6618 	/*
6619 	 * Page was not free, so lets try to relocate it.
6620 	 * page_relocate only works with root pages, so if this is not a root
6621 	 * page, we need to demote it to try and relocate it.
6622 	 * Unfortunately this is the best we can do right now.
6623 	 */
6624 	newpp = NULL;
6625 	if ((pp->p_szc > 0) && (pp != PP_PAGEROOT(pp))) {
6626 		if (page_try_demote_pages(pp) == 0) {
6627 			ret = EAGAIN;
6628 			goto cleanup;
6629 		}
6630 	}
6631 	ret = page_relocate(&pp, &newpp, 1, 0, &count, NULL);
6632 	if (ret == 0) {
6633 		page_t *npp;
6634 		/* unlock the new page(s) */
6635 		while (count-- > 0) {
6636 			ASSERT(newpp != NULL);
6637 			npp = newpp;
6638 			page_sub(&newpp, npp);
6639 			page_unlock(npp);
6640 		}
6641 		ASSERT(newpp == NULL);
6642 		/*
6643 		 * Check to see if the page we have is too large.
6644 		 * If so, demote it freeing up the extra pages.
6645 		 */
6646 		if (pp->p_szc > 0) {
6647 			/* For now demote extra pages to szc == 0 */
6648 			extra = page_get_pagecnt(pp->p_szc) - 1;
6649 			while (extra > 0) {
6650 				tpp = pp->p_next;
6651 				page_sub(&pp, tpp);
6652 				tpp->p_szc = 0;
6653 				page_free(tpp, 1);
6654 				extra--;
6655 			}
6656 			/* Make sure to set our page to szc 0 as well */
6657 			ASSERT(pp->p_next == pp && pp->p_prev == pp);
6658 			pp->p_szc = 0;
6659 		}
6660 		goto cleanup;
6661 	} else if (ret == EIO) {
6662 		ret = EAGAIN;
6663 		goto cleanup;
6664 	} else {
6665 		/*
6666 		 * Need to reset return type as we failed to relocate the page
6667 		 * but that does not mean that some of the next steps will not
6668 		 * work.
6669 		 */
6670 		ret = 0;
6671 	}
6672 
6673 skip_relocate:
6674 
6675 	if (pp->p_szc > 0) {
6676 		if (page_try_demote_pages(pp) == 0) {
6677 			ret = EAGAIN;
6678 			goto cleanup;
6679 		}
6680 	}
6681 
6682 	ASSERT(pp->p_szc == 0);
6683 
6684 	if (hat_ismod(pp)) {
6685 		ret = EAGAIN;
6686 		goto cleanup;
6687 	}
6688 	if (PP_ISKAS(pp)) {
6689 		ret = EAGAIN;
6690 		goto cleanup;
6691 	}
6692 	if (pp->p_lckcnt || pp->p_cowcnt) {
6693 		ret = EAGAIN;
6694 		goto cleanup;
6695 	}
6696 
6697 	(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
6698 	ASSERT(!hat_page_is_mapped(pp));
6699 
6700 	if (hat_ismod(pp)) {
6701 		/*
6702 		 * This is a semi-odd case as the page is now modified but not
6703 		 * mapped as we just unloaded the mappings above.
6704 		 */
6705 		ret = EAGAIN;
6706 		goto cleanup;
6707 	}
6708 	if (pp->p_vnode != NULL) {
6709 		page_hashout(pp, NULL);
6710 	}
6711 
6712 	/*
6713 	 * At this point, the page should be in a clean state and
6714 	 * we can do whatever we want with it.
6715 	 */
6716 
6717 cleanup:
6718 	if (ret != 0) {
6719 		if (!skip_unlock) {
6720 			page_unlock(pp);
6721 		}
6722 	} else {
6723 		ASSERT(pp->p_szc == 0);
6724 		ASSERT(PAGE_EXCL(pp));
6725 
6726 		pp->p_next = pp;
6727 		pp->p_prev = pp;
6728 	}
6729 	return (ret);
6730 }
6731 
6732 /*
6733  * Various callers of page_trycapture() can have different restrictions upon
6734  * what memory they have access to.
6735  * Returns 0 on success, with the following error codes on failure:
6736  *      EPERM - The requested page is long term locked, and thus repeated
6737  *              requests to capture this page will likely fail.
6738  *      ENOMEM - There was not enough free memory in the system to safely
6739  *              map the requested page.
6740  *      ENOENT - The requested page was inside the kernel cage, and the
6741  *              PHYSMEM_CAGE flag was not set.
6742  */
6743 int
6744 page_capture_pre_checks(page_t *pp, uint_t flags)
6745 {
6746 #if defined(__sparc)
6747 	extern struct vnode prom_ppages;
6748 #endif /* __sparc */
6749 
6750 	ASSERT(pp != NULL);
6751 
6752 	/* only physmem currently has restrictions */
6753 	if (!(flags & CAPTURE_PHYSMEM)) {
6754 		return (0);
6755 	}
6756 
6757 #if defined(__sparc)
6758 	if (pp->p_vnode == &prom_ppages) {
6759 		return (EPERM);
6760 	}
6761 
6762 	if (PP_ISNORELOC(pp) && !(flags & CAPTURE_GET_CAGE)) {
6763 		return (ENOENT);
6764 	}
6765 
6766 	if (PP_ISNORELOCKERNEL(pp)) {
6767 		return (EPERM);
6768 	}
6769 #else
6770 	if (PP_ISKAS(pp)) {
6771 		return (EPERM);
6772 	}
6773 #endif /* __sparc */
6774 
6775 	if (availrmem < swapfs_minfree) {
6776 		/*
6777 		 * We won't try to capture this page as we are
6778 		 * running low on memory.
6779 		 */
6780 		return (ENOMEM);
6781 	}
6782 	return (0);
6783 }
6784 
6785 /*
6786  * Once we have a page in our mits, go ahead and complete the capture
6787  * operation.
6788  * Returns 1 on failure where page is no longer needed
6789  * Returns 0 on success
6790  * Returns -1 if there was a transient failure.
6791  * Failure cases must release the SE_EXCL lock on pp (usually via page_free).
6792  */
6793 int
6794 page_capture_take_action(page_t *pp, uint_t flags, void *datap)
6795 {
6796 	int cb_index;
6797 	int ret = 0;
6798 	page_capture_hash_bucket_t *bp1;
6799 	page_capture_hash_bucket_t *bp2;
6800 	int index;
6801 	int found = 0;
6802 	int i;
6803 
6804 	ASSERT(PAGE_EXCL(pp));
6805 	ASSERT(curthread->t_flag & T_CAPTURING);
6806 
6807 	for (cb_index = 0; cb_index < PC_NUM_CALLBACKS; cb_index++) {
6808 		if ((flags >> cb_index) & 1) {
6809 			break;
6810 		}
6811 	}
6812 	ASSERT(cb_index < PC_NUM_CALLBACKS);
6813 
6814 	/*
6815 	 * Remove the entry from the page_capture hash, but don't free it yet
6816 	 * as we may need to put it back.
6817 	 * Since we own the page at this point in time, we should find it
6818 	 * in the hash if this is an ASYNC call.  If we don't it's likely
6819 	 * that the page_capture_async() thread decided that this request
6820 	 * had expired, in which case we just continue on.
6821 	 */
6822 	if (flags & CAPTURE_ASYNC) {
6823 
6824 		index = PAGE_CAPTURE_HASH(pp);
6825 
6826 		mutex_enter(&page_capture_hash[index].pchh_mutex);
6827 		for (i = 0; i < 2 && !found; i++) {
6828 			bp1 = page_capture_hash[index].lists[i].next;
6829 			while (bp1 != &page_capture_hash[index].lists[i]) {
6830 				if (bp1->pp == pp) {
6831 					bp1->next->prev = bp1->prev;
6832 					bp1->prev->next = bp1->next;
6833 					page_capture_hash[index].num_pages--;
6834 					page_clrtoxic(pp, PR_CAPTURE);
6835 					found = 1;
6836 					break;
6837 				}
6838 				bp1 = bp1->next;
6839 			}
6840 		}
6841 		mutex_exit(&page_capture_hash[index].pchh_mutex);
6842 	}
6843 
6844 	/* Synchronize with the unregister func. */
6845 	rw_enter(&pc_cb[cb_index].cb_rwlock, RW_READER);
6846 	if (!pc_cb[cb_index].cb_active) {
6847 		page_free(pp, 1);
6848 		rw_exit(&pc_cb[cb_index].cb_rwlock);
6849 		if (found) {
6850 			kmem_free(bp1, sizeof (*bp1));
6851 		}
6852 		return (1);
6853 	}
6854 
6855 	/*
6856 	 * We need to remove the entry from the page capture hash and turn off
6857 	 * the PR_CAPTURE bit before calling the callback.  We'll need to cache
6858 	 * the entry here, and then based upon the return value, cleanup
6859 	 * appropriately or re-add it to the hash, making sure that someone else
6860 	 * hasn't already done so.
6861 	 * It should be rare for the callback to fail and thus it's ok for
6862 	 * the failure path to be a bit complicated as the success path is
6863 	 * cleaner and the locking rules are easier to follow.
6864 	 */
6865 
6866 	ret = pc_cb[cb_index].cb_func(pp, datap, flags);
6867 
6868 	rw_exit(&pc_cb[cb_index].cb_rwlock);
6869 
6870 	/*
6871 	 * If this was an ASYNC request, we need to cleanup the hash if the
6872 	 * callback was successful or if the request was no longer valid.
6873 	 * For non-ASYNC requests, we return failure to map and the caller
6874 	 * will take care of adding the request to the hash.
6875 	 * Note also that the callback itself is responsible for the page
6876 	 * at this point in time in terms of locking ...  The most common
6877 	 * case for the failure path should just be a page_free.
6878 	 */
6879 	if (ret >= 0) {
6880 		if (found) {
6881 			if (bp1->flags & CAPTURE_RETIRE) {
6882 				page_retire_decr_pend_count();
6883 			}
6884 			kmem_free(bp1, sizeof (*bp1));
6885 		}
6886 		return (ret);
6887 	}
6888 	if (!found) {
6889 		return (ret);
6890 	}
6891 
6892 	ASSERT(flags & CAPTURE_ASYNC);
6893 
6894 	/*
6895 	 * Check for expiration time first as we can just free it up if it's
6896 	 * expired.
6897 	 */
6898 	if (lbolt > bp1->expires && bp1->expires != -1) {
6899 		kmem_free(bp1, sizeof (*bp1));
6900 		return (ret);
6901 	}
6902 
6903 	/*
6904 	 * The callback failed and there used to be an entry in the hash for
6905 	 * this page, so we need to add it back to the hash.
6906 	 */
6907 	mutex_enter(&page_capture_hash[index].pchh_mutex);
6908 	if (!(pp->p_toxic & PR_CAPTURE)) {
6909 		/* just add bp1 back to head of walked list */
6910 		page_settoxic(pp, PR_CAPTURE);
6911 		bp1->next = page_capture_hash[index].lists[1].next;
6912 		bp1->prev = &page_capture_hash[index].lists[1];
6913 		bp1->next->prev = bp1;
6914 		page_capture_hash[index].lists[1].next = bp1;
6915 		page_capture_hash[index].num_pages++;
6916 		mutex_exit(&page_capture_hash[index].pchh_mutex);
6917 		return (ret);
6918 	}
6919 
6920 	/*
6921 	 * Otherwise there was a new capture request added to list
6922 	 * Need to make sure that our original data is represented if
6923 	 * appropriate.
6924 	 */
6925 	for (i = 0; i < 2; i++) {
6926 		bp2 = page_capture_hash[index].lists[i].next;
6927 		while (bp2 != &page_capture_hash[index].lists[i]) {
6928 			if (bp2->pp == pp) {
6929 				if (bp1->flags & CAPTURE_RETIRE) {
6930 					if (!(bp2->flags & CAPTURE_RETIRE)) {
6931 						bp2->szc = bp1->szc;
6932 						bp2->flags = bp1->flags;
6933 						bp2->expires = bp1->expires;
6934 						bp2->datap = bp1->datap;
6935 					}
6936 				} else {
6937 					ASSERT(bp1->flags & CAPTURE_PHYSMEM);
6938 					if (!(bp2->flags & CAPTURE_RETIRE)) {
6939 						bp2->szc = bp1->szc;
6940 						bp2->flags = bp1->flags;
6941 						bp2->expires = bp1->expires;
6942 						bp2->datap = bp1->datap;
6943 					}
6944 				}
6945 				mutex_exit(&page_capture_hash[index].
6946 				    pchh_mutex);
6947 				kmem_free(bp1, sizeof (*bp1));
6948 				return (ret);
6949 			}
6950 			bp2 = bp2->next;
6951 		}
6952 	}
6953 	panic("PR_CAPTURE set but not on hash for pp 0x%p\n", pp);
6954 	/*NOTREACHED*/
6955 }
6956 
6957 /*
6958  * Try to capture the given page for the caller specified in the flags
6959  * parameter.  The page will either be captured and handed over to the
6960  * appropriate callback, or will be queued up in the page capture hash
6961  * to be captured asynchronously.
6962  * If the current request is due to an async capture, the page must be
6963  * exclusively locked before calling this function.
6964  * Currently szc must be 0 but in the future this should be expandable to
6965  * other page sizes.
6966  * Returns 0 on success, with the following error codes on failure:
6967  *      EPERM - The requested page is long term locked, and thus repeated
6968  *              requests to capture this page will likely fail.
6969  *      ENOMEM - There was not enough free memory in the system to safely
6970  *              map the requested page.
6971  *      ENOENT - The requested page was inside the kernel cage, and the
6972  *              CAPTURE_GET_CAGE flag was not set.
6973  *	EAGAIN - The requested page could not be capturead at this point in
6974  *		time but future requests will likely work.
6975  *	EBUSY - The requested page is retired and the CAPTURE_GET_RETIRED flag
6976  *		was not set.
6977  */
6978 int
6979 page_itrycapture(page_t *pp, uint_t szc, uint_t flags, void *datap)
6980 {
6981 	int ret;
6982 	int cb_index;
6983 
6984 	if (flags & CAPTURE_ASYNC) {
6985 		ASSERT(PAGE_EXCL(pp));
6986 		goto async;
6987 	}
6988 
6989 	/* Make sure there's enough availrmem ... */
6990 	ret = page_capture_pre_checks(pp, flags);
6991 	if (ret != 0) {
6992 		return (ret);
6993 	}
6994 
6995 	if (!page_trylock(pp, SE_EXCL)) {
6996 		for (cb_index = 0; cb_index < PC_NUM_CALLBACKS; cb_index++) {
6997 			if ((flags >> cb_index) & 1) {
6998 				break;
6999 			}
7000 		}
7001 		ASSERT(cb_index < PC_NUM_CALLBACKS);
7002 		ret = EAGAIN;
7003 		/* Special case for retired pages */
7004 		if (PP_RETIRED(pp)) {
7005 			if (flags & CAPTURE_GET_RETIRED) {
7006 				if (!page_unretire_pp(pp, PR_UNR_TEMP)) {
7007 					/*
7008 					 * Need to set capture bit and add to
7009 					 * hash so that the page will be
7010 					 * retired when freed.
7011 					 */
7012 					page_capture_add_hash(pp, szc,
7013 					    CAPTURE_RETIRE, NULL);
7014 					ret = 0;
7015 					goto own_page;
7016 				}
7017 			} else {
7018 				return (EBUSY);
7019 			}
7020 		}
7021 		page_capture_add_hash(pp, szc, flags, datap);
7022 		return (ret);
7023 	}
7024 
7025 async:
7026 	ASSERT(PAGE_EXCL(pp));
7027 
7028 	/* Need to check for physmem async requests that availrmem is sane */
7029 	if ((flags & (CAPTURE_ASYNC | CAPTURE_PHYSMEM)) ==
7030 	    (CAPTURE_ASYNC | CAPTURE_PHYSMEM) &&
7031 	    (availrmem < swapfs_minfree)) {
7032 		page_unlock(pp);
7033 		return (ENOMEM);
7034 	}
7035 
7036 	ret = page_capture_clean_page(pp);
7037 
7038 	if (ret != 0) {
7039 		/* We failed to get the page, so lets add it to the hash */
7040 		if (!(flags & CAPTURE_ASYNC)) {
7041 			page_capture_add_hash(pp, szc, flags, datap);
7042 		}
7043 		return (ret);
7044 	}
7045 
7046 own_page:
7047 	ASSERT(PAGE_EXCL(pp));
7048 	ASSERT(pp->p_szc == 0);
7049 
7050 	/* Call the callback */
7051 	ret = page_capture_take_action(pp, flags, datap);
7052 
7053 	if (ret == 0) {
7054 		return (0);
7055 	}
7056 
7057 	/*
7058 	 * Note that in the failure cases from page_capture_take_action, the
7059 	 * EXCL lock will have already been dropped.
7060 	 */
7061 	if ((ret == -1) && (!(flags & CAPTURE_ASYNC))) {
7062 		page_capture_add_hash(pp, szc, flags, datap);
7063 	}
7064 	return (EAGAIN);
7065 }
7066 
7067 int
7068 page_trycapture(page_t *pp, uint_t szc, uint_t flags, void *datap)
7069 {
7070 	int ret;
7071 
7072 	curthread->t_flag |= T_CAPTURING;
7073 	ret = page_itrycapture(pp, szc, flags, datap);
7074 	curthread->t_flag &= ~T_CAPTURING; /* xor works as we know its set */
7075 	return (ret);
7076 }
7077 
7078 /*
7079  * When unlocking a page which has the PR_CAPTURE bit set, this routine
7080  * gets called to try and capture the page.
7081  */
7082 void
7083 page_unlock_capture(page_t *pp)
7084 {
7085 	page_capture_hash_bucket_t *bp;
7086 	int index;
7087 	int i;
7088 	uint_t szc;
7089 	uint_t flags = 0;
7090 	void *datap;
7091 	kmutex_t *mp;
7092 	extern vnode_t retired_pages;
7093 
7094 	/*
7095 	 * We need to protect against a possible deadlock here where we own
7096 	 * the vnode page hash mutex and want to acquire it again as there
7097 	 * are locations in the code, where we unlock a page while holding
7098 	 * the mutex which can lead to the page being captured and eventually
7099 	 * end up here.  As we may be hashing out the old page and hashing into
7100 	 * the retire vnode, we need to make sure we don't own them.
7101 	 * Other callbacks who do hash operations also need to make sure that
7102 	 * before they hashin to a vnode that they do not currently own the
7103 	 * vphm mutex otherwise there will be a panic.
7104 	 */
7105 	if (mutex_owned(page_vnode_mutex(&retired_pages))) {
7106 		page_unlock_nocapture(pp);
7107 		return;
7108 	}
7109 	if (pp->p_vnode != NULL && mutex_owned(page_vnode_mutex(pp->p_vnode))) {
7110 		page_unlock_nocapture(pp);
7111 		return;
7112 	}
7113 
7114 	index = PAGE_CAPTURE_HASH(pp);
7115 
7116 	mp = &page_capture_hash[index].pchh_mutex;
7117 	mutex_enter(mp);
7118 	for (i = 0; i < 2; i++) {
7119 		bp = page_capture_hash[index].lists[i].next;
7120 		while (bp != &page_capture_hash[index].lists[i]) {
7121 			if (bp->pp == pp) {
7122 				szc = bp->szc;
7123 				flags = bp->flags | CAPTURE_ASYNC;
7124 				datap = bp->datap;
7125 				mutex_exit(mp);
7126 				(void) page_trycapture(pp, szc, flags, datap);
7127 				return;
7128 			}
7129 			bp = bp->next;
7130 		}
7131 	}
7132 
7133 	/* Failed to find page in hash so clear flags and unlock it. */
7134 	page_clrtoxic(pp, PR_CAPTURE);
7135 	page_unlock(pp);
7136 
7137 	mutex_exit(mp);
7138 }
7139 
7140 void
7141 page_capture_init()
7142 {
7143 	int i;
7144 	for (i = 0; i < NUM_PAGE_CAPTURE_BUCKETS; i++) {
7145 		page_capture_hash[i].lists[0].next =
7146 		    &page_capture_hash[i].lists[0];
7147 		page_capture_hash[i].lists[0].prev =
7148 		    &page_capture_hash[i].lists[0];
7149 		page_capture_hash[i].lists[1].next =
7150 		    &page_capture_hash[i].lists[1];
7151 		page_capture_hash[i].lists[1].prev =
7152 		    &page_capture_hash[i].lists[1];
7153 	}
7154 
7155 	pc_thread_shortwait = 23 * hz;
7156 	pc_thread_longwait = 1201 * hz;
7157 	pc_thread_ism_retry = 3;
7158 	mutex_init(&pc_thread_mutex, NULL, MUTEX_DEFAULT, NULL);
7159 	cv_init(&pc_cv, NULL, CV_DEFAULT, NULL);
7160 	pc_thread_id = thread_create(NULL, 0, page_capture_thread, NULL, 0, &p0,
7161 	    TS_RUN, minclsyspri);
7162 }
7163 
7164 /*
7165  * It is necessary to scrub any failing pages prior to reboot in order to
7166  * prevent a latent error trap from occurring on the next boot.
7167  */
7168 void
7169 page_retire_mdboot()
7170 {
7171 	page_t *pp;
7172 	int i, j;
7173 	page_capture_hash_bucket_t *bp;
7174 
7175 	/* walk lists looking for pages to scrub */
7176 	for (i = 0; i < NUM_PAGE_CAPTURE_BUCKETS; i++) {
7177 		if (page_capture_hash[i].num_pages == 0)
7178 			continue;
7179 
7180 		mutex_enter(&page_capture_hash[i].pchh_mutex);
7181 
7182 		for (j = 0; j < 2; j++) {
7183 			bp = page_capture_hash[i].lists[j].next;
7184 			while (bp != &page_capture_hash[i].lists[j]) {
7185 				pp = bp->pp;
7186 				if (!PP_ISKAS(pp) && PP_TOXIC(pp)) {
7187 					pp->p_selock = -1;  /* pacify ASSERTs */
7188 					PP_CLRFREE(pp);
7189 					pagescrub(pp, 0, PAGESIZE);
7190 					pp->p_selock = 0;
7191 				}
7192 				bp = bp->next;
7193 			}
7194 		}
7195 		mutex_exit(&page_capture_hash[i].pchh_mutex);
7196 	}
7197 }
7198 
7199 /*
7200  * Walk the page_capture_hash trying to capture pages and also cleanup old
7201  * entries which have expired.
7202  */
7203 void
7204 page_capture_async()
7205 {
7206 	page_t *pp;
7207 	int i;
7208 	int ret;
7209 	page_capture_hash_bucket_t *bp1, *bp2;
7210 	uint_t szc;
7211 	uint_t flags;
7212 	void *datap;
7213 
7214 	/* If there are outstanding pages to be captured, get to work */
7215 	for (i = 0; i < NUM_PAGE_CAPTURE_BUCKETS; i++) {
7216 		if (page_capture_hash[i].num_pages == 0)
7217 			continue;
7218 		/* Append list 1 to list 0 and then walk through list 0 */
7219 		mutex_enter(&page_capture_hash[i].pchh_mutex);
7220 		bp1 = &page_capture_hash[i].lists[1];
7221 		bp2 = bp1->next;
7222 		if (bp1 != bp2) {
7223 			bp1->prev->next = page_capture_hash[i].lists[0].next;
7224 			bp2->prev = &page_capture_hash[i].lists[0];
7225 			page_capture_hash[i].lists[0].next->prev = bp1->prev;
7226 			page_capture_hash[i].lists[0].next = bp2;
7227 			bp1->next = bp1;
7228 			bp1->prev = bp1;
7229 		}
7230 
7231 		/* list[1] will be empty now */
7232 
7233 		bp1 = page_capture_hash[i].lists[0].next;
7234 		while (bp1 != &page_capture_hash[i].lists[0]) {
7235 			/* Check expiration time */
7236 			if ((lbolt > bp1->expires && bp1->expires != -1) ||
7237 			    page_deleted(bp1->pp)) {
7238 				page_capture_hash[i].lists[0].next = bp1->next;
7239 				bp1->next->prev =
7240 				    &page_capture_hash[i].lists[0];
7241 				page_capture_hash[i].num_pages--;
7242 
7243 				/*
7244 				 * We can safely remove the PR_CAPTURE bit
7245 				 * without holding the EXCL lock on the page
7246 				 * as the PR_CAPTURE bit requres that the
7247 				 * page_capture_hash[].pchh_mutex be held
7248 				 * to modify it.
7249 				 */
7250 				page_clrtoxic(bp1->pp, PR_CAPTURE);
7251 				mutex_exit(&page_capture_hash[i].pchh_mutex);
7252 				kmem_free(bp1, sizeof (*bp1));
7253 				mutex_enter(&page_capture_hash[i].pchh_mutex);
7254 				bp1 = page_capture_hash[i].lists[0].next;
7255 				continue;
7256 			}
7257 			pp = bp1->pp;
7258 			szc = bp1->szc;
7259 			flags = bp1->flags;
7260 			datap = bp1->datap;
7261 			mutex_exit(&page_capture_hash[i].pchh_mutex);
7262 			if (page_trylock(pp, SE_EXCL)) {
7263 				ret = page_trycapture(pp, szc,
7264 				    flags | CAPTURE_ASYNC, datap);
7265 			} else {
7266 				ret = 1;	/* move to walked hash */
7267 			}
7268 
7269 			if (ret != 0) {
7270 				/* Move to walked hash */
7271 				(void) page_capture_move_to_walked(pp);
7272 			}
7273 			mutex_enter(&page_capture_hash[i].pchh_mutex);
7274 			bp1 = page_capture_hash[i].lists[0].next;
7275 		}
7276 
7277 		mutex_exit(&page_capture_hash[i].pchh_mutex);
7278 	}
7279 }
7280 
7281 /*
7282  * This function is called by the page_capture_thread, and is needed in
7283  * in order to initiate aio cleanup, so that pages used in aio
7284  * will be unlocked and subsequently retired by page_capture_thread.
7285  */
7286 static int
7287 do_aio_cleanup(void)
7288 {
7289 	proc_t *procp;
7290 	int (*aio_cleanup_dr_delete_memory)(proc_t *);
7291 	int cleaned = 0;
7292 
7293 	if (modload("sys", "kaio") == -1) {
7294 		cmn_err(CE_WARN, "do_aio_cleanup: cannot load kaio");
7295 		return (0);
7296 	}
7297 	/*
7298 	 * We use the aio_cleanup_dr_delete_memory function to
7299 	 * initiate the actual clean up; this function will wake
7300 	 * up the per-process aio_cleanup_thread.
7301 	 */
7302 	aio_cleanup_dr_delete_memory = (int (*)(proc_t *))
7303 	    modgetsymvalue("aio_cleanup_dr_delete_memory", 0);
7304 	if (aio_cleanup_dr_delete_memory == NULL) {
7305 		cmn_err(CE_WARN,
7306 	    "aio_cleanup_dr_delete_memory not found in kaio");
7307 		return (0);
7308 	}
7309 	mutex_enter(&pidlock);
7310 	for (procp = practive; (procp != NULL); procp = procp->p_next) {
7311 		mutex_enter(&procp->p_lock);
7312 		if (procp->p_aio != NULL) {
7313 			/* cleanup proc's outstanding kaio */
7314 			cleaned += (*aio_cleanup_dr_delete_memory)(procp);
7315 		}
7316 		mutex_exit(&procp->p_lock);
7317 	}
7318 	mutex_exit(&pidlock);
7319 	return (cleaned);
7320 }
7321 
7322 /*
7323  * helper function for page_capture_thread
7324  */
7325 static void
7326 page_capture_handle_outstanding(void)
7327 {
7328 	extern size_t spt_used;
7329 	int ntry;
7330 
7331 	if (!page_retire_pend_count()) {
7332 		/*
7333 		 * Do we really want to be this aggressive
7334 		 * for things other than page_retire?
7335 		 * Maybe have a counter for each callback
7336 		 * type to guide how aggressive we should
7337 		 * be here.  Thus if there's at least one
7338 		 * page for page_retire we go ahead and reap
7339 		 * like this.
7340 		 */
7341 		kmem_reap();
7342 		seg_preap();
7343 		page_capture_async();
7344 	} else {
7345 		/*
7346 		 * There are pages pending retirement, so
7347 		 * we reap prior to attempting to capture.
7348 		 */
7349 		kmem_reap();
7350 		/*
7351 		 * When ISM is in use, we need to disable and
7352 		 * purge the seg_pcache, and initiate aio
7353 		 * cleanup in order to release page locks and
7354 		 * subsquently retire pages in need of
7355 		 * retirement.
7356 		 */
7357 		if (spt_used) {
7358 			/* disable and purge seg_pcache */
7359 			(void) seg_p_disable();
7360 			for (ntry = 0; ntry < pc_thread_ism_retry; ntry++) {
7361 				if (!page_retire_pend_count())
7362 					break;
7363 				if (do_aio_cleanup()) {
7364 					/*
7365 					 * allow the apps cleanup threads
7366 					 * to run
7367 					 */
7368 					delay(pc_thread_shortwait);
7369 				}
7370 				page_capture_async();
7371 			}
7372 			/* reenable seg_pcache */
7373 			seg_p_enable();
7374 		} else {
7375 			seg_preap();
7376 			page_capture_async();
7377 		}
7378 	}
7379 }
7380 
7381 /*
7382  * The page_capture_thread loops forever, looking to see if there are
7383  * pages still waiting to be captured.
7384  */
7385 static void
7386 page_capture_thread(void)
7387 {
7388 	callb_cpr_t c;
7389 	int outstanding;
7390 	int i;
7391 
7392 	CALLB_CPR_INIT(&c, &pc_thread_mutex, callb_generic_cpr, "page_capture");
7393 
7394 	mutex_enter(&pc_thread_mutex);
7395 	for (;;) {
7396 		outstanding = 0;
7397 		for (i = 0; i < NUM_PAGE_CAPTURE_BUCKETS; i++)
7398 			outstanding += page_capture_hash[i].num_pages;
7399 		if (outstanding) {
7400 			page_capture_handle_outstanding();
7401 			CALLB_CPR_SAFE_BEGIN(&c);
7402 			(void) cv_timedwait(&pc_cv, &pc_thread_mutex,
7403 			    lbolt + pc_thread_shortwait);
7404 			CALLB_CPR_SAFE_END(&c, &pc_thread_mutex);
7405 		} else {
7406 			CALLB_CPR_SAFE_BEGIN(&c);
7407 			(void) cv_timedwait(&pc_cv, &pc_thread_mutex,
7408 			    lbolt + pc_thread_longwait);
7409 			CALLB_CPR_SAFE_END(&c, &pc_thread_mutex);
7410 		}
7411 	}
7412 	/*NOTREACHED*/
7413 }
7414