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