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