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