xref: /titanic_41/usr/src/uts/common/vm/vm_anon.c (revision b02e9a2d4d2071d770e5aa9ae8f83f2bbe1f2ced)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
27 /*	  All Rights Reserved  	*/
28 
29 /*
30  * University Copyright- Copyright (c) 1982, 1986, 1988
31  * The Regents of the University of California
32  * All Rights Reserved
33  *
34  * University Acknowledgment- Portions of this document are derived from
35  * software developed by the University of California, Berkeley, and its
36  * contributors.
37  */
38 
39 #pragma ident	"%Z%%M%	%I%	%E% SMI"
40 
41 /*
42  * VM - anonymous pages.
43  *
44  * This layer sits immediately above the vm_swap layer.  It manages
45  * physical pages that have no permanent identity in the file system
46  * name space, using the services of the vm_swap layer to allocate
47  * backing storage for these pages.  Since these pages have no external
48  * identity, they are discarded when the last reference is removed.
49  *
50  * An important function of this layer is to manage low-level sharing
51  * of pages that are logically distinct but that happen to be
52  * physically identical (e.g., the corresponding pages of the processes
53  * resulting from a fork before one process or the other changes their
54  * contents).  This pseudo-sharing is present only as an optimization
55  * and is not to be confused with true sharing in which multiple
56  * address spaces deliberately contain references to the same object;
57  * such sharing is managed at a higher level.
58  *
59  * The key data structure here is the anon struct, which contains a
60  * reference count for its associated physical page and a hint about
61  * the identity of that page.  Anon structs typically live in arrays,
62  * with an instance's position in its array determining where the
63  * corresponding backing storage is allocated; however, the swap_xlate()
64  * routine abstracts away this representation information so that the
65  * rest of the anon layer need not know it.  (See the swap layer for
66  * more details on anon struct layout.)
67  *
68  * In the future versions of the system, the association between an
69  * anon struct and its position on backing store will change so that
70  * we don't require backing store all anonymous pages in the system.
71  * This is important for consideration for large memory systems.
72  * We can also use this technique to delay binding physical locations
73  * to anonymous pages until pageout/swapout time where we can make
74  * smarter allocation decisions to improve anonymous klustering.
75  *
76  * Many of the routines defined here take a (struct anon **) argument,
77  * which allows the code at this level to manage anon pages directly,
78  * so that callers can regard anon structs as opaque objects and not be
79  * concerned with assigning or inspecting their contents.
80  *
81  * Clients of this layer refer to anon pages indirectly.  That is, they
82  * maintain arrays of pointers to anon structs rather than maintaining
83  * anon structs themselves.  The (struct anon **) arguments mentioned
84  * above are pointers to entries in these arrays.  It is these arrays
85  * that capture the mapping between offsets within a given segment and
86  * the corresponding anonymous backing storage address.
87  */
88 
89 #ifdef DEBUG
90 #define	ANON_DEBUG
91 #endif
92 
93 #include <sys/types.h>
94 #include <sys/t_lock.h>
95 #include <sys/param.h>
96 #include <sys/systm.h>
97 #include <sys/mman.h>
98 #include <sys/cred.h>
99 #include <sys/thread.h>
100 #include <sys/vnode.h>
101 #include <sys/cpuvar.h>
102 #include <sys/swap.h>
103 #include <sys/cmn_err.h>
104 #include <sys/vtrace.h>
105 #include <sys/kmem.h>
106 #include <sys/sysmacros.h>
107 #include <sys/bitmap.h>
108 #include <sys/vmsystm.h>
109 #include <sys/debug.h>
110 #include <sys/fs/swapnode.h>
111 #include <sys/tnf_probe.h>
112 #include <sys/lgrp.h>
113 #include <sys/policy.h>
114 #include <sys/condvar_impl.h>
115 #include <sys/mutex_impl.h>
116 #include <sys/rctl.h>
117 
118 #include <vm/as.h>
119 #include <vm/hat.h>
120 #include <vm/anon.h>
121 #include <vm/page.h>
122 #include <vm/vpage.h>
123 #include <vm/seg.h>
124 #include <vm/rm.h>
125 
126 #include <fs/fs_subr.h>
127 
128 struct vnode *anon_vp;
129 
130 int anon_debug;
131 
132 kmutex_t	anoninfo_lock;
133 struct		k_anoninfo k_anoninfo;
134 ani_free_t	ani_free_pool[ANI_MAX_POOL];
135 pad_mutex_t	anon_array_lock[ANON_LOCKSIZE];
136 kcondvar_t	anon_array_cv[ANON_LOCKSIZE];
137 
138 /*
139  * Global hash table for (vp, off) -> anon slot
140  */
141 extern	int swap_maxcontig;
142 size_t	anon_hash_size;
143 struct anon **anon_hash;
144 
145 static struct kmem_cache *anon_cache;
146 static struct kmem_cache *anonmap_cache;
147 
148 #ifdef VM_STATS
149 static struct anonvmstats_str {
150 	ulong_t getpages[30];
151 	ulong_t privatepages[10];
152 	ulong_t demotepages[9];
153 	ulong_t decrefpages[9];
154 	ulong_t	dupfillholes[4];
155 	ulong_t freepages[1];
156 } anonvmstats;
157 #endif /* VM_STATS */
158 
159 
160 /*ARGSUSED*/
161 static int
162 anonmap_cache_constructor(void *buf, void *cdrarg, int kmflags)
163 {
164 	struct anon_map *amp = buf;
165 
166 	rw_init(&amp->a_rwlock, NULL, RW_DEFAULT, NULL);
167 	return (0);
168 }
169 
170 /*ARGSUSED1*/
171 static void
172 anonmap_cache_destructor(void *buf, void *cdrarg)
173 {
174 	struct anon_map *amp = buf;
175 
176 	rw_destroy(&amp->a_rwlock);
177 }
178 
179 kmutex_t	anonhash_lock[AH_LOCK_SIZE];
180 kmutex_t	anonpages_hash_lock[AH_LOCK_SIZE];
181 
182 void
183 anon_init(void)
184 {
185 	int i;
186 
187 	anon_hash_size = 1L << highbit(physmem / ANON_HASHAVELEN);
188 
189 	for (i = 0; i < AH_LOCK_SIZE; i++) {
190 		mutex_init(&anonhash_lock[i], NULL, MUTEX_DEFAULT, NULL);
191 		mutex_init(&anonpages_hash_lock[i], NULL, MUTEX_DEFAULT, NULL);
192 	}
193 
194 	for (i = 0; i < ANON_LOCKSIZE; i++) {
195 		mutex_init(&anon_array_lock[i].pad_mutex, NULL,
196 			MUTEX_DEFAULT, NULL);
197 		cv_init(&anon_array_cv[i], NULL, CV_DEFAULT, NULL);
198 	}
199 
200 	anon_hash = (struct anon **)
201 		kmem_zalloc(sizeof (struct anon *) * anon_hash_size, KM_SLEEP);
202 	anon_cache = kmem_cache_create("anon_cache", sizeof (struct anon),
203 		AN_CACHE_ALIGN, NULL, NULL, NULL, NULL, NULL, 0);
204 	anonmap_cache = kmem_cache_create("anonmap_cache",
205 		sizeof (struct anon_map), 0,
206 		anonmap_cache_constructor, anonmap_cache_destructor, NULL,
207 		NULL, NULL, 0);
208 	swap_maxcontig = (1024 * 1024) >> PAGESHIFT;	/* 1MB of pages */
209 
210 	anon_vp = vn_alloc(KM_SLEEP);
211 	vn_setops(anon_vp, swap_vnodeops);
212 	anon_vp->v_type = VREG;
213 	anon_vp->v_flag |= (VISSWAP|VISSWAPFS);
214 }
215 
216 /*
217  * Global anon slot hash table manipulation.
218  */
219 
220 static void
221 anon_addhash(struct anon *ap)
222 {
223 	int index;
224 
225 	ASSERT(MUTEX_HELD(&anonhash_lock[AH_LOCK(ap->an_vp, ap->an_off)]));
226 	index = ANON_HASH(ap->an_vp, ap->an_off);
227 	ap->an_hash = anon_hash[index];
228 	anon_hash[index] = ap;
229 }
230 
231 static void
232 anon_rmhash(struct anon *ap)
233 {
234 	struct anon **app;
235 
236 	ASSERT(MUTEX_HELD(&anonhash_lock[AH_LOCK(ap->an_vp, ap->an_off)]));
237 
238 	for (app = &anon_hash[ANON_HASH(ap->an_vp, ap->an_off)];
239 	    *app; app = &((*app)->an_hash)) {
240 		if (*app == ap) {
241 			*app = ap->an_hash;
242 			break;
243 		}
244 	}
245 }
246 
247 /*
248  * The anon array interfaces. Functions allocating,
249  * freeing array of pointers, and returning/setting
250  * entries in the array of pointers for a given offset.
251  *
252  * Create the list of pointers
253  */
254 struct anon_hdr *
255 anon_create(pgcnt_t npages, int flags)
256 {
257 	struct anon_hdr *ahp;
258 	ulong_t nchunks;
259 	int kmemflags = (flags & ANON_NOSLEEP) ? KM_NOSLEEP : KM_SLEEP;
260 
261 	if ((ahp = kmem_zalloc(sizeof (struct anon_hdr), kmemflags)) == NULL) {
262 		return (NULL);
263 	}
264 
265 	mutex_init(&ahp->serial_lock, NULL, MUTEX_DEFAULT, NULL);
266 	/*
267 	 * Single level case.
268 	 */
269 	ahp->size = npages;
270 	if (npages <= ANON_CHUNK_SIZE || (flags & ANON_ALLOC_FORCE)) {
271 
272 		if (flags & ANON_ALLOC_FORCE)
273 			ahp->flags |= ANON_ALLOC_FORCE;
274 
275 		ahp->array_chunk = kmem_zalloc(
276 		    ahp->size * sizeof (struct anon *), kmemflags);
277 
278 		if (ahp->array_chunk == NULL) {
279 			kmem_free(ahp, sizeof (struct anon_hdr));
280 			return (NULL);
281 		}
282 	} else {
283 		/*
284 		 * 2 Level case.
285 		 * anon hdr size needs to be rounded off  to be a multiple
286 		 * of ANON_CHUNK_SIZE. This is important as various anon
287 		 * related functions depend on this.
288 		 * NOTE -
289 		 * anon_grow()  makes anon hdr size a multiple of
290 		 * ANON_CHUNK_SIZE.
291 		 * amp size is <= anon hdr size.
292 		 * anon_index + seg_pgs <= anon hdr size.
293 		 */
294 		ahp->size = P2ROUNDUP(npages, ANON_CHUNK_SIZE);
295 		nchunks = ahp->size >> ANON_CHUNK_SHIFT;
296 
297 		ahp->array_chunk = kmem_zalloc(nchunks * sizeof (ulong_t *),
298 		    kmemflags);
299 
300 		if (ahp->array_chunk == NULL) {
301 			kmem_free(ahp, sizeof (struct anon_hdr));
302 			return (NULL);
303 		}
304 	}
305 	return (ahp);
306 }
307 
308 /*
309  * Free the array of pointers
310  */
311 void
312 anon_release(struct anon_hdr *ahp, pgcnt_t npages)
313 {
314 	ulong_t i;
315 	void **ppp;
316 	ulong_t nchunks;
317 
318 	ASSERT(npages <= ahp->size);
319 
320 	/*
321 	 * Single level case.
322 	 */
323 	if (npages <= ANON_CHUNK_SIZE || (ahp->flags & ANON_ALLOC_FORCE)) {
324 		kmem_free(ahp->array_chunk, ahp->size * sizeof (struct anon *));
325 	} else {
326 		/*
327 		 * 2 level case.
328 		 */
329 		nchunks = ahp->size >> ANON_CHUNK_SHIFT;
330 		for (i = 0; i < nchunks; i++) {
331 			ppp = &ahp->array_chunk[i];
332 			if (*ppp != NULL)
333 				kmem_free(*ppp, PAGESIZE);
334 		}
335 		kmem_free(ahp->array_chunk, nchunks * sizeof (ulong_t *));
336 	}
337 	mutex_destroy(&ahp->serial_lock);
338 	kmem_free(ahp, sizeof (struct anon_hdr));
339 }
340 
341 /*
342  * Return the pointer from the list for a
343  * specified anon index.
344  */
345 struct anon *
346 anon_get_ptr(struct anon_hdr *ahp, ulong_t an_idx)
347 {
348 	struct anon **app;
349 
350 	ASSERT(an_idx < ahp->size);
351 
352 	/*
353 	 * Single level case.
354 	 */
355 	if ((ahp->size <= ANON_CHUNK_SIZE) || (ahp->flags & ANON_ALLOC_FORCE)) {
356 		return ((struct anon *)
357 			((uintptr_t)ahp->array_chunk[an_idx] & ANON_PTRMASK));
358 	} else {
359 
360 		/*
361 		 * 2 level case.
362 		 */
363 		app = ahp->array_chunk[an_idx >> ANON_CHUNK_SHIFT];
364 		if (app) {
365 			return ((struct anon *)
366 				((uintptr_t)app[an_idx & ANON_CHUNK_OFF] &
367 					ANON_PTRMASK));
368 		} else {
369 			return (NULL);
370 		}
371 	}
372 }
373 
374 /*
375  * Return the anon pointer for the first valid entry in the anon list,
376  * starting from the given index.
377  */
378 struct anon *
379 anon_get_next_ptr(struct anon_hdr *ahp, ulong_t *index)
380 {
381 	struct anon *ap;
382 	struct anon **app;
383 	ulong_t chunkoff;
384 	ulong_t i;
385 	ulong_t j;
386 	pgcnt_t size;
387 
388 	i = *index;
389 	size = ahp->size;
390 
391 	ASSERT(i < size);
392 
393 	if ((size <= ANON_CHUNK_SIZE) || (ahp->flags & ANON_ALLOC_FORCE)) {
394 		/*
395 		 * 1 level case
396 		 */
397 		while (i < size) {
398 			ap = (struct anon *)
399 				((uintptr_t)ahp->array_chunk[i] & ANON_PTRMASK);
400 			if (ap) {
401 				*index = i;
402 				return (ap);
403 			}
404 			i++;
405 		}
406 	} else {
407 		/*
408 		 * 2 level case
409 		 */
410 		chunkoff = i & ANON_CHUNK_OFF;
411 		while (i < size) {
412 			app = ahp->array_chunk[i >> ANON_CHUNK_SHIFT];
413 			if (app)
414 				for (j = chunkoff; j < ANON_CHUNK_SIZE; j++) {
415 					ap = (struct anon *)
416 						((uintptr_t)app[j] &
417 							ANON_PTRMASK);
418 					if (ap) {
419 						*index = i + (j - chunkoff);
420 						return (ap);
421 					}
422 				}
423 			chunkoff = 0;
424 			i = (i + ANON_CHUNK_SIZE) & ~ANON_CHUNK_OFF;
425 		}
426 	}
427 	*index = size;
428 	return (NULL);
429 }
430 
431 /*
432  * Set list entry with a given pointer for a specified offset
433  */
434 int
435 anon_set_ptr(struct anon_hdr *ahp, ulong_t an_idx, struct anon *ap, int flags)
436 {
437 	void		**ppp;
438 	struct anon	**app;
439 	int kmemflags = (flags & ANON_NOSLEEP) ? KM_NOSLEEP : KM_SLEEP;
440 	uintptr_t	*ap_addr;
441 
442 	ASSERT(an_idx < ahp->size);
443 
444 	/*
445 	 * Single level case.
446 	 */
447 	if (ahp->size <= ANON_CHUNK_SIZE || (ahp->flags & ANON_ALLOC_FORCE)) {
448 		ap_addr = (uintptr_t *)&ahp->array_chunk[an_idx];
449 	} else {
450 
451 		/*
452 		 * 2 level case.
453 		 */
454 		ppp = &ahp->array_chunk[an_idx >> ANON_CHUNK_SHIFT];
455 
456 		ASSERT(ppp != NULL);
457 		if (*ppp == NULL) {
458 			mutex_enter(&ahp->serial_lock);
459 			ppp = &ahp->array_chunk[an_idx >> ANON_CHUNK_SHIFT];
460 			if (*ppp == NULL) {
461 				*ppp = kmem_zalloc(PAGESIZE, kmemflags);
462 				if (*ppp == NULL) {
463 					mutex_exit(&ahp->serial_lock);
464 					return (ENOMEM);
465 				}
466 			}
467 			mutex_exit(&ahp->serial_lock);
468 		}
469 		app = *ppp;
470 		ap_addr = (uintptr_t *)&app[an_idx & ANON_CHUNK_OFF];
471 	}
472 	*ap_addr = (*ap_addr & ~ANON_PTRMASK) | (uintptr_t)ap;
473 	return (0);
474 }
475 
476 /*
477  * Copy anon array into a given new anon array
478  */
479 int
480 anon_copy_ptr(struct anon_hdr *sahp, ulong_t s_idx,
481 	struct anon_hdr *dahp, ulong_t d_idx,
482 	pgcnt_t npages, int flags)
483 {
484 	void **sapp, **dapp;
485 	void *ap;
486 	int kmemflags = (flags & ANON_NOSLEEP) ? KM_NOSLEEP : KM_SLEEP;
487 
488 	ASSERT((s_idx < sahp->size) && (d_idx < dahp->size));
489 	ASSERT((npages <= sahp->size) && (npages <= dahp->size));
490 
491 	/*
492 	 * Both arrays are 1 level.
493 	 */
494 	if (((sahp->size <= ANON_CHUNK_SIZE) &&
495 	    (dahp->size <= ANON_CHUNK_SIZE)) ||
496 	    ((sahp->flags & ANON_ALLOC_FORCE) &&
497 	    (dahp->flags & ANON_ALLOC_FORCE))) {
498 
499 		bcopy(&sahp->array_chunk[s_idx], &dahp->array_chunk[d_idx],
500 		    npages * sizeof (struct anon *));
501 		return (0);
502 	}
503 
504 	/*
505 	 * Both arrays are 2 levels.
506 	 */
507 	if (sahp->size > ANON_CHUNK_SIZE &&
508 	    dahp->size > ANON_CHUNK_SIZE &&
509 	    ((sahp->flags & ANON_ALLOC_FORCE) == 0) &&
510 	    ((dahp->flags & ANON_ALLOC_FORCE) == 0)) {
511 
512 		ulong_t sapidx, dapidx;
513 		ulong_t *sap, *dap;
514 		ulong_t chknp;
515 
516 		while (npages != 0) {
517 
518 			sapidx = s_idx & ANON_CHUNK_OFF;
519 			dapidx = d_idx & ANON_CHUNK_OFF;
520 			chknp = ANON_CHUNK_SIZE - MAX(sapidx, dapidx);
521 			if (chknp > npages)
522 				chknp = npages;
523 
524 			sapp = &sahp->array_chunk[s_idx >> ANON_CHUNK_SHIFT];
525 			if ((sap = *sapp) != NULL) {
526 				dapp = &dahp->array_chunk[d_idx
527 							>> ANON_CHUNK_SHIFT];
528 				if ((dap = *dapp) == NULL) {
529 					*dapp = kmem_zalloc(PAGESIZE,
530 					    kmemflags);
531 					if ((dap = *dapp) == NULL)
532 						return (ENOMEM);
533 				}
534 				bcopy((sap + sapidx), (dap + dapidx),
535 				    chknp << ANON_PTRSHIFT);
536 			}
537 			s_idx += chknp;
538 			d_idx += chknp;
539 			npages -= chknp;
540 		}
541 		return (0);
542 	}
543 
544 	/*
545 	 * At least one of the arrays is 2 level.
546 	 */
547 	while (npages--) {
548 		if ((ap = anon_get_ptr(sahp, s_idx)) != NULL) {
549 			ASSERT(!ANON_ISBUSY(anon_get_slot(sahp, s_idx)));
550 			if (anon_set_ptr(dahp, d_idx, ap, flags) == ENOMEM)
551 					return (ENOMEM);
552 		}
553 		s_idx++;
554 		d_idx++;
555 	}
556 	return (0);
557 }
558 
559 
560 /*
561  * ANON_INITBUF is a convenience macro for anon_grow() below. It
562  * takes a buffer dst, which is at least as large as buffer src. It
563  * does a bcopy from src into dst, and then bzeros the extra bytes
564  * of dst. If tail is set, the data in src is tail aligned within
565  * dst instead of head aligned.
566  */
567 
568 #define	ANON_INITBUF(src, srclen, dst, dstsize, tail)			      \
569 	if (tail) {							      \
570 		bzero((dst), (dstsize) - (srclen));			      \
571 		bcopy((src), (char *)(dst) + (dstsize) - (srclen), (srclen)); \
572 	} else {							      \
573 		bcopy((src), (dst), (srclen));				      \
574 		bzero((char *)(dst) + (srclen), (dstsize) - (srclen));	      \
575 	}
576 
577 #define	ANON_1_LEVEL_INC	(ANON_CHUNK_SIZE / 8)
578 #define	ANON_2_LEVEL_INC	(ANON_1_LEVEL_INC * ANON_CHUNK_SIZE)
579 
580 /*
581  * anon_grow() is used to efficiently extend an existing anon array.
582  * startidx_p points to the index into the anon array of the first page
583  * that is in use. oldseg_pgs is the number of pages in use, starting at
584  * *startidx_p. newpages is the number of additional pages desired.
585  *
586  * If startidx_p == NULL, startidx is taken to be 0 and cannot be changed.
587  *
588  * The growth is done by creating a new top level of the anon array,
589  * and (if the array is 2-level) reusing the existing second level arrays.
590  *
591  * flags can be used to specify ANON_NOSLEEP and ANON_GROWDOWN.
592  *
593  * Returns the new number of pages in the anon array.
594  */
595 pgcnt_t
596 anon_grow(struct anon_hdr *ahp, ulong_t *startidx_p, pgcnt_t oldseg_pgs,
597     pgcnt_t newseg_pgs, int flags)
598 {
599 	ulong_t startidx = startidx_p ? *startidx_p : 0;
600 	pgcnt_t oldamp_pgs = ahp->size, newamp_pgs;
601 	pgcnt_t oelems, nelems, totpages;
602 	void **level1;
603 	int kmemflags = (flags & ANON_NOSLEEP) ? KM_NOSLEEP : KM_SLEEP;
604 	int growdown = (flags & ANON_GROWDOWN);
605 	size_t newarrsz, oldarrsz;
606 	void *level2;
607 
608 	ASSERT(!(startidx_p == NULL && growdown));
609 	ASSERT(startidx + oldseg_pgs <= ahp->size);
610 
611 	/*
612 	 * Determine the total number of pages needed in the new
613 	 * anon array. If growing down, totpages is all pages from
614 	 * startidx through the end of the array, plus <newseg_pgs>
615 	 * pages. If growing up, keep all pages from page 0 through
616 	 * the last page currently in use, plus <newseg_pgs> pages.
617 	 */
618 	if (growdown)
619 		totpages = oldamp_pgs - startidx + newseg_pgs;
620 	else
621 		totpages = startidx + oldseg_pgs + newseg_pgs;
622 
623 	/* If the array is already large enough, just return. */
624 
625 	if (oldamp_pgs >= totpages) {
626 		if (growdown)
627 			*startidx_p = oldamp_pgs - totpages;
628 		return (oldamp_pgs);
629 	}
630 
631 	/*
632 	 * oldamp_pgs/newamp_pgs are the total numbers of pages represented
633 	 * by the corresponding arrays.
634 	 * oelems/nelems are the number of pointers in the top level arrays
635 	 * which may be either level 1 or level 2.
636 	 * Will the new anon array be one level or two levels?
637 	 */
638 	if (totpages <= ANON_CHUNK_SIZE || (ahp->flags & ANON_ALLOC_FORCE)) {
639 		newamp_pgs = P2ROUNDUP(totpages, ANON_1_LEVEL_INC);
640 		oelems = oldamp_pgs;
641 		nelems = newamp_pgs;
642 	} else {
643 		newamp_pgs = P2ROUNDUP(totpages, ANON_2_LEVEL_INC);
644 		oelems = (oldamp_pgs + ANON_CHUNK_OFF) >> ANON_CHUNK_SHIFT;
645 		nelems = newamp_pgs >> ANON_CHUNK_SHIFT;
646 	}
647 
648 	newarrsz = nelems * sizeof (void *);
649 	level1 = kmem_alloc(newarrsz, kmemflags);
650 	if (level1 == NULL)
651 		return (0);
652 
653 	/* Are we converting from a one level to a two level anon array? */
654 
655 	if (newamp_pgs > ANON_CHUNK_SIZE && oldamp_pgs <= ANON_CHUNK_SIZE &&
656 	    !(ahp->flags & ANON_ALLOC_FORCE)) {
657 
658 		/*
659 		 * Yes, we're converting to a two level. Reuse old level 1
660 		 * as new level 2 if it is exactly PAGESIZE. Otherwise
661 		 * alloc a new level 2 and copy the old level 1 data into it.
662 		 */
663 		if (oldamp_pgs == ANON_CHUNK_SIZE) {
664 			level2 = (void *)ahp->array_chunk;
665 		} else {
666 			level2 = kmem_alloc(PAGESIZE, kmemflags);
667 			if (level2 == NULL) {
668 				kmem_free(level1, newarrsz);
669 				return (0);
670 			}
671 			oldarrsz = oldamp_pgs * sizeof (void *);
672 
673 			ANON_INITBUF(ahp->array_chunk, oldarrsz,
674 			    level2, PAGESIZE, growdown);
675 			kmem_free(ahp->array_chunk, oldarrsz);
676 		}
677 		bzero(level1, newarrsz);
678 		if (growdown)
679 			level1[nelems - 1] = level2;
680 		else
681 			level1[0] = level2;
682 	} else {
683 		oldarrsz = oelems * sizeof (void *);
684 
685 		ANON_INITBUF(ahp->array_chunk, oldarrsz,
686 		    level1, newarrsz, growdown);
687 		kmem_free(ahp->array_chunk, oldarrsz);
688 	}
689 
690 	ahp->array_chunk = level1;
691 	ahp->size = newamp_pgs;
692 	if (growdown)
693 		*startidx_p = newamp_pgs - totpages;
694 
695 	return (newamp_pgs);
696 }
697 
698 
699 /*
700  * Called from clock handler to sync ani_free value.
701  */
702 
703 void
704 set_anoninfo(void)
705 {
706 	int	ix;
707 	pgcnt_t	total = 0;
708 
709 	for (ix = 0; ix < ANI_MAX_POOL; ix++) {
710 		total += ani_free_pool[ix].ani_count;
711 	}
712 	k_anoninfo.ani_free = total;
713 }
714 
715 /*
716  * Reserve anon space.
717  *
718  * It's no longer simply a matter of incrementing ani_resv to
719  * reserve swap space, we need to check memory-based as well
720  * as disk-backed (physical) swap.  The following algorithm
721  * is used:
722  * 	Check the space on physical swap
723  * 		i.e. amount needed < ani_max - ani_phys_resv
724  * 	If we are swapping on swapfs check
725  *		amount needed < (availrmem - swapfs_minfree)
726  * Since the algorithm to check for the quantity of swap space is
727  * almost the same as that for reserving it, we'll just use anon_resvmem
728  * with a flag to decrement availrmem.
729  *
730  * Return non-zero on success.
731  */
732 int
733 anon_resvmem(size_t size, boolean_t takemem, zone_t *zone, int tryhard)
734 {
735 	pgcnt_t npages = btopr(size);
736 	pgcnt_t mswap_pages = 0;
737 	pgcnt_t pswap_pages = 0;
738 	proc_t *p = curproc;
739 
740 	if (zone != NULL && takemem) {
741 		/* test zone.max-swap resource control */
742 		mutex_enter(&p->p_lock);
743 		if (rctl_incr_swap(p, zone, ptob(npages)) != 0) {
744 			mutex_exit(&p->p_lock);
745 			return (0);
746 		}
747 		mutex_exit(&p->p_lock);
748 	}
749 	mutex_enter(&anoninfo_lock);
750 
751 	/*
752 	 * pswap_pages is the number of pages we can take from
753 	 * physical (i.e. disk-backed) swap.
754 	 */
755 	ASSERT(k_anoninfo.ani_max >= k_anoninfo.ani_phys_resv);
756 	pswap_pages = k_anoninfo.ani_max - k_anoninfo.ani_phys_resv;
757 
758 	ANON_PRINT(A_RESV,
759 	    ("anon_resvmem: npages %lu takemem %u pswap %lu caller %p\n",
760 	    npages, takemem, pswap_pages, (void *)caller()));
761 
762 	if (npages <= pswap_pages) {
763 		/*
764 		 * we have enough space on a physical swap
765 		 */
766 		if (takemem)
767 			k_anoninfo.ani_phys_resv += npages;
768 		mutex_exit(&anoninfo_lock);
769 		return (1);
770 	} else if (pswap_pages != 0) {
771 		/*
772 		 * we have some space on a physical swap
773 		 */
774 		if (takemem) {
775 			/*
776 			 * use up remainder of phys swap
777 			 */
778 			k_anoninfo.ani_phys_resv += pswap_pages;
779 			ASSERT(k_anoninfo.ani_phys_resv == k_anoninfo.ani_max);
780 		}
781 	}
782 	/*
783 	 * since (npages > pswap_pages) we need mem swap
784 	 * mswap_pages is the number of pages needed from availrmem
785 	 */
786 	ASSERT(npages > pswap_pages);
787 	mswap_pages = npages - pswap_pages;
788 
789 	ANON_PRINT(A_RESV, ("anon_resvmem: need %ld pages from memory\n",
790 	    mswap_pages));
791 
792 	/*
793 	 * priv processes can reserve memory as swap as long as availrmem
794 	 * remains greater than swapfs_minfree; in the case of non-priv
795 	 * processes, memory can be reserved as swap only if availrmem
796 	 * doesn't fall below (swapfs_minfree + swapfs_reserve). Thus,
797 	 * swapfs_reserve amount of memswap is not available to non-priv
798 	 * processes. This protects daemons such as automounter dying
799 	 * as a result of application processes eating away almost entire
800 	 * membased swap. This safeguard becomes useless if apps are run
801 	 * with root access.
802 	 *
803 	 * swapfs_reserve is minimum of 4Mb or 1/16 of physmem.
804 	 *
805 	 */
806 	if (tryhard) {
807 		mutex_exit(&anoninfo_lock);
808 		(void) page_reclaim_mem(mswap_pages,
809 		    swapfs_minfree + swapfs_reserve, 0);
810 		mutex_enter(&anoninfo_lock);
811 	}
812 
813 	mutex_enter(&freemem_lock);
814 	if (availrmem > (swapfs_minfree + swapfs_reserve + mswap_pages) ||
815 		(availrmem > (swapfs_minfree + mswap_pages) &&
816 		secpolicy_resource(CRED()) == 0)) {
817 
818 		if (takemem) {
819 			/*
820 			 * Take the memory from the rest of the system.
821 			 */
822 			availrmem -= mswap_pages;
823 			mutex_exit(&freemem_lock);
824 			k_anoninfo.ani_mem_resv += mswap_pages;
825 			ANI_ADD(mswap_pages);
826 			ANON_PRINT((A_RESV | A_MRESV),
827 				("anon_resvmem: took %ld pages of availrmem\n",
828 				mswap_pages));
829 		} else {
830 			mutex_exit(&freemem_lock);
831 		}
832 
833 		ASSERT(k_anoninfo.ani_max >= k_anoninfo.ani_phys_resv);
834 		mutex_exit(&anoninfo_lock);
835 		return (1);
836 
837 	} else {
838 		/*
839 		 * Fail if not enough memory
840 		 */
841 
842 		if (takemem) {
843 			k_anoninfo.ani_phys_resv -= pswap_pages;
844 		}
845 
846 		mutex_exit(&freemem_lock);
847 		mutex_exit(&anoninfo_lock);
848 		ANON_PRINT(A_RESV,
849 			("anon_resvmem: not enough space from swapfs\n"));
850 		if (zone != NULL && takemem)
851 			rctl_decr_swap(zone, ptob(npages));
852 		return (0);
853 	}
854 }
855 
856 /*
857  * Give back an anon reservation.
858  */
859 void
860 anon_unresvmem(size_t size, zone_t *zone)
861 {
862 	pgcnt_t npages = btopr(size);
863 	spgcnt_t mem_free_pages = 0;
864 	pgcnt_t phys_free_slots;
865 #ifdef	ANON_DEBUG
866 	pgcnt_t mem_resv;
867 #endif
868 	if (zone != NULL)
869 		rctl_decr_swap(zone, ptob(npages));
870 
871 	mutex_enter(&anoninfo_lock);
872 
873 	ASSERT(k_anoninfo.ani_mem_resv >= k_anoninfo.ani_locked_swap);
874 	/*
875 	 * If some of this reservation belonged to swapfs
876 	 * give it back to availrmem.
877 	 * ani_mem_resv is the amount of availrmem swapfs has reserved.
878 	 * but some of that memory could be locked by segspt so we can only
879 	 * return non locked ani_mem_resv back to availrmem
880 	 */
881 	if (k_anoninfo.ani_mem_resv > k_anoninfo.ani_locked_swap) {
882 		ANON_PRINT((A_RESV | A_MRESV),
883 		    ("anon_unresv: growing availrmem by %ld pages\n",
884 		    MIN(k_anoninfo.ani_mem_resv, npages)));
885 
886 		mem_free_pages = MIN((spgcnt_t)(k_anoninfo.ani_mem_resv -
887 		    k_anoninfo.ani_locked_swap), npages);
888 		mutex_enter(&freemem_lock);
889 		availrmem += mem_free_pages;
890 		mutex_exit(&freemem_lock);
891 		k_anoninfo.ani_mem_resv -= mem_free_pages;
892 
893 		ANI_ADD(-mem_free_pages);
894 	}
895 	/*
896 	 * The remainder of the pages is returned to phys swap
897 	 */
898 	ASSERT(npages >= mem_free_pages);
899 	phys_free_slots = npages - mem_free_pages;
900 
901 	if (phys_free_slots) {
902 	    k_anoninfo.ani_phys_resv -= phys_free_slots;
903 	}
904 
905 #ifdef	ANON_DEBUG
906 	mem_resv = k_anoninfo.ani_mem_resv;
907 #endif
908 
909 	ASSERT(k_anoninfo.ani_mem_resv >= k_anoninfo.ani_locked_swap);
910 	ASSERT(k_anoninfo.ani_max >= k_anoninfo.ani_phys_resv);
911 
912 	mutex_exit(&anoninfo_lock);
913 
914 	ANON_PRINT(A_RESV, ("anon_unresv: %lu, tot %lu, caller %p\n",
915 	    npages, mem_resv, (void *)caller()));
916 }
917 
918 /*
919  * Allocate an anon slot and return it with the lock held.
920  */
921 struct anon *
922 anon_alloc(struct vnode *vp, anoff_t off)
923 {
924 	struct anon	*ap;
925 	kmutex_t	*ahm;
926 
927 	ap = kmem_cache_alloc(anon_cache, KM_SLEEP);
928 	if (vp == NULL) {
929 		swap_alloc(ap);
930 	} else {
931 		ap->an_vp = vp;
932 		ap->an_off = off;
933 	}
934 	ap->an_refcnt = 1;
935 	ap->an_pvp = NULL;
936 	ap->an_poff = 0;
937 	ahm = &anonhash_lock[AH_LOCK(ap->an_vp, ap->an_off)];
938 	mutex_enter(ahm);
939 	anon_addhash(ap);
940 	mutex_exit(ahm);
941 	ANI_ADD(-1);
942 	ANON_PRINT(A_ANON, ("anon_alloc: returning ap %p, vp %p\n",
943 	    (void *)ap, (ap ? (void *)ap->an_vp : NULL)));
944 	return (ap);
945 }
946 
947 /*
948  * Decrement the reference count of an anon page.
949  * If reference count goes to zero, free it and
950  * its associated page (if any).
951  */
952 void
953 anon_decref(struct anon *ap)
954 {
955 	page_t *pp;
956 	struct vnode *vp;
957 	anoff_t off;
958 	kmutex_t *ahm;
959 
960 	ahm = &anonhash_lock[AH_LOCK(ap->an_vp, ap->an_off)];
961 	mutex_enter(ahm);
962 	ASSERT(ap->an_refcnt != 0);
963 	if (ap->an_refcnt == 0)
964 		panic("anon_decref: slot count 0");
965 	if (--ap->an_refcnt == 0) {
966 		swap_xlate(ap, &vp, &off);
967 		mutex_exit(ahm);
968 
969 		/*
970 		 * If there is a page for this anon slot we will need to
971 		 * call VN_DISPOSE to get rid of the vp association and
972 		 * put the page back on the free list as really free.
973 		 * Acquire the "exclusive" lock to ensure that any
974 		 * pending i/o always completes before the swap slot
975 		 * is freed.
976 		 */
977 		pp = page_lookup(vp, (u_offset_t)off, SE_EXCL);
978 
979 		/*
980 		 * If there was a page, we've synchronized on it (getting
981 		 * the exclusive lock is as good as gettting the iolock)
982 		 * so now we can free the physical backing store. Also, this
983 		 * is where we would free the name of the anonymous page
984 		 * (swap_free(ap)), a no-op in the current implementation.
985 		 */
986 		mutex_enter(ahm);
987 		ASSERT(ap->an_refcnt == 0);
988 		anon_rmhash(ap);
989 		if (ap->an_pvp)
990 			swap_phys_free(ap->an_pvp, ap->an_poff, PAGESIZE);
991 		mutex_exit(ahm);
992 
993 		if (pp != NULL) {
994 			/*LINTED: constant in conditional context */
995 			VN_DISPOSE(pp, B_INVAL, 0, kcred);
996 		}
997 		ANON_PRINT(A_ANON, ("anon_decref: free ap %p, vp %p\n",
998 		    (void *)ap, (void *)ap->an_vp));
999 		kmem_cache_free(anon_cache, ap);
1000 
1001 		ANI_ADD(1);
1002 	} else {
1003 		mutex_exit(ahm);
1004 	}
1005 }
1006 
1007 static int
1008 anon_share(struct anon_hdr *ahp, ulong_t anon_index, pgcnt_t nslots)
1009 {
1010 	struct anon *ap;
1011 
1012 	while (nslots-- > 0) {
1013 		if ((ap = anon_get_ptr(ahp, anon_index)) != NULL &&
1014 		    ap->an_refcnt > 1)
1015 			return (1);
1016 		anon_index++;
1017 	}
1018 
1019 	return (0);
1020 }
1021 
1022 static void
1023 anon_decref_pages(
1024 	struct anon_hdr *ahp,
1025 	ulong_t an_idx,
1026 	uint_t szc)
1027 {
1028 	struct anon *ap = anon_get_ptr(ahp, an_idx);
1029 	kmutex_t *ahmpages = NULL;
1030 	page_t *pp;
1031 	pgcnt_t pgcnt = page_get_pagecnt(szc);
1032 	pgcnt_t i;
1033 	struct vnode *vp;
1034 	anoff_t   off;
1035 	kmutex_t *ahm;
1036 #ifdef DEBUG
1037 	int refcnt = 1;
1038 #endif
1039 
1040 	ASSERT(szc != 0);
1041 	ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
1042 	ASSERT(IS_P2ALIGNED(an_idx, pgcnt));
1043 	ASSERT(an_idx < ahp->size);
1044 
1045 	if (ahp->size - an_idx < pgcnt) {
1046 		/*
1047 		 * In case of shared mappings total anon map size may not be
1048 		 * the largest page size aligned.
1049 		 */
1050 		pgcnt = ahp->size - an_idx;
1051 	}
1052 
1053 	VM_STAT_ADD(anonvmstats.decrefpages[0]);
1054 
1055 	if (ap != NULL) {
1056 		ahmpages = &anonpages_hash_lock[AH_LOCK(ap->an_vp, ap->an_off)];
1057 		mutex_enter(ahmpages);
1058 		ASSERT((refcnt = ap->an_refcnt) != 0);
1059 		VM_STAT_ADD(anonvmstats.decrefpages[1]);
1060 		if (ap->an_refcnt == 1) {
1061 			VM_STAT_ADD(anonvmstats.decrefpages[2]);
1062 			ASSERT(!anon_share(ahp, an_idx, pgcnt));
1063 			mutex_exit(ahmpages);
1064 			ahmpages = NULL;
1065 		}
1066 	}
1067 
1068 	i = 0;
1069 	while (i < pgcnt) {
1070 		if ((ap = anon_get_ptr(ahp, an_idx + i)) == NULL) {
1071 			ASSERT(refcnt == 1 && ahmpages == NULL);
1072 			i++;
1073 			continue;
1074 		}
1075 		ASSERT(ap->an_refcnt == refcnt);
1076 		ASSERT(ahmpages != NULL || ap->an_refcnt == 1);
1077 		ASSERT(ahmpages == NULL || ap->an_refcnt > 1);
1078 
1079 		if (ahmpages == NULL) {
1080 			swap_xlate(ap, &vp, &off);
1081 			pp = page_lookup(vp, (u_offset_t)off, SE_EXCL);
1082 			if (pp == NULL || pp->p_szc == 0) {
1083 				VM_STAT_ADD(anonvmstats.decrefpages[3]);
1084 				ahm = &anonhash_lock[AH_LOCK(ap->an_vp,
1085 				    ap->an_off)];
1086 				(void) anon_set_ptr(ahp, an_idx + i, NULL,
1087 				    ANON_SLEEP);
1088 				mutex_enter(ahm);
1089 				ap->an_refcnt--;
1090 				ASSERT(ap->an_refcnt == 0);
1091 				anon_rmhash(ap);
1092 				if (ap->an_pvp)
1093 					swap_phys_free(ap->an_pvp, ap->an_poff,
1094 					    PAGESIZE);
1095 				mutex_exit(ahm);
1096 				if (pp != NULL) {
1097 					VM_STAT_ADD(anonvmstats.decrefpages[4]);
1098 					/*LINTED*/
1099 					VN_DISPOSE(pp, B_INVAL, 0, kcred);
1100 				}
1101 				kmem_cache_free(anon_cache, ap);
1102 				ANI_ADD(1);
1103 				i++;
1104 			} else {
1105 				pgcnt_t j;
1106 				pgcnt_t curpgcnt =
1107 				    page_get_pagecnt(pp->p_szc);
1108 				size_t ppasize = curpgcnt * sizeof (page_t *);
1109 				page_t **ppa = kmem_alloc(ppasize, KM_SLEEP);
1110 				int dispose = 0;
1111 
1112 				VM_STAT_ADD(anonvmstats.decrefpages[5]);
1113 
1114 				ASSERT(pp->p_szc <= szc);
1115 				ASSERT(IS_P2ALIGNED(curpgcnt, curpgcnt));
1116 				ASSERT(IS_P2ALIGNED(i, curpgcnt));
1117 				ASSERT(i + curpgcnt <= pgcnt);
1118 				ASSERT(!(page_pptonum(pp) & (curpgcnt - 1)));
1119 				ppa[0] = pp;
1120 				for (j = i + 1; j < i + curpgcnt; j++) {
1121 					ap = anon_get_ptr(ahp, an_idx + j);
1122 					ASSERT(ap != NULL &&
1123 					    ap->an_refcnt == 1);
1124 					swap_xlate(ap, &vp, &off);
1125 					pp = page_lookup(vp, (u_offset_t)off,
1126 					    SE_EXCL);
1127 					if (pp == NULL)
1128 						panic("anon_decref_pages: "
1129 						    "no page");
1130 
1131 					(void) hat_pageunload(pp,
1132 					    HAT_FORCE_PGUNLOAD);
1133 					ASSERT(pp->p_szc == ppa[0]->p_szc);
1134 					ASSERT(page_pptonum(pp) - 1 ==
1135 					    page_pptonum(ppa[j - i - 1]));
1136 					ppa[j - i] = pp;
1137 					if (ap->an_pvp != NULL &&
1138 					    !vn_matchopval(ap->an_pvp,
1139 						VOPNAME_DISPOSE,
1140 						(fs_generic_func_p)fs_dispose))
1141 						dispose = 1;
1142 				}
1143 				if (!dispose) {
1144 					VM_STAT_ADD(anonvmstats.decrefpages[6]);
1145 					page_destroy_pages(ppa[0]);
1146 				} else {
1147 					VM_STAT_ADD(anonvmstats.decrefpages[7]);
1148 					for (j = 0; j < curpgcnt; j++) {
1149 						ASSERT(PAGE_EXCL(ppa[j]));
1150 						ppa[j]->p_szc = 0;
1151 					}
1152 					for (j = 0; j < curpgcnt; j++) {
1153 						ASSERT(!hat_page_is_mapped(
1154 						    ppa[j]));
1155 						/*LINTED*/
1156 						VN_DISPOSE(ppa[j], B_INVAL, 0,
1157 						    kcred);
1158 					}
1159 				}
1160 				kmem_free(ppa, ppasize);
1161 				for (j = i; j < i + curpgcnt; j++) {
1162 					ap = anon_get_ptr(ahp, an_idx + j);
1163 					ASSERT(ap != NULL &&
1164 					    ap->an_refcnt == 1);
1165 					ahm = &anonhash_lock[AH_LOCK(ap->an_vp,
1166 					    ap->an_off)];
1167 					(void) anon_set_ptr(ahp, an_idx + j,
1168 					    NULL, ANON_SLEEP);
1169 					mutex_enter(ahm);
1170 					ap->an_refcnt--;
1171 					ASSERT(ap->an_refcnt == 0);
1172 					anon_rmhash(ap);
1173 					if (ap->an_pvp)
1174 						swap_phys_free(ap->an_pvp,
1175 							ap->an_poff, PAGESIZE);
1176 					mutex_exit(ahm);
1177 					kmem_cache_free(anon_cache, ap);
1178 					ANI_ADD(1);
1179 				}
1180 				i += curpgcnt;
1181 			}
1182 		} else {
1183 			VM_STAT_ADD(anonvmstats.decrefpages[8]);
1184 			(void) anon_set_ptr(ahp, an_idx + i, NULL, ANON_SLEEP);
1185 			ahm = &anonhash_lock[AH_LOCK(ap->an_vp, ap->an_off)];
1186 			mutex_enter(ahm);
1187 			ap->an_refcnt--;
1188 			mutex_exit(ahm);
1189 			i++;
1190 		}
1191 	}
1192 
1193 	if (ahmpages != NULL) {
1194 		mutex_exit(ahmpages);
1195 	}
1196 }
1197 
1198 /*
1199  * Duplicate references to size bytes worth of anon pages.
1200  * Used when duplicating a segment that contains private anon pages.
1201  * This code assumes that procedure calling this one has already used
1202  * hat_chgprot() to disable write access to the range of addresses that
1203  * that *old actually refers to.
1204  */
1205 void
1206 anon_dup(struct anon_hdr *old, ulong_t old_idx, struct anon_hdr *new,
1207 			ulong_t new_idx, size_t size)
1208 {
1209 	spgcnt_t npages;
1210 	kmutex_t *ahm;
1211 	struct anon *ap;
1212 	ulong_t off;
1213 	ulong_t index;
1214 
1215 	npages = btopr(size);
1216 	while (npages > 0) {
1217 		index = old_idx;
1218 		if ((ap = anon_get_next_ptr(old, &index)) == NULL)
1219 			break;
1220 
1221 		ASSERT(!ANON_ISBUSY(anon_get_slot(old, index)));
1222 		off = index - old_idx;
1223 		npages -= off;
1224 		if (npages <= 0)
1225 			break;
1226 
1227 		(void) anon_set_ptr(new, new_idx + off, ap, ANON_SLEEP);
1228 		ahm = &anonhash_lock[AH_LOCK(ap->an_vp, ap->an_off)];
1229 
1230 		mutex_enter(ahm);
1231 		ap->an_refcnt++;
1232 		mutex_exit(ahm);
1233 
1234 		off++;
1235 		new_idx += off;
1236 		old_idx += off;
1237 		npages--;
1238 	}
1239 }
1240 
1241 /*
1242  * Just like anon_dup but also guarantees there are no holes (unallocated anon
1243  * slots) within any large page region. That means if a large page region is
1244  * empty in the old array it will skip it. If there are 1 or more valid slots
1245  * in the large page region of the old array it will make sure to fill in any
1246  * unallocated ones and also copy them to the new array. If noalloc is 1 large
1247  * page region should either have no valid anon slots or all slots should be
1248  * valid.
1249  */
1250 void
1251 anon_dup_fill_holes(
1252 	struct anon_hdr *old,
1253 	ulong_t old_idx,
1254 	struct anon_hdr *new,
1255 	ulong_t new_idx,
1256 	size_t size,
1257 	uint_t szc,
1258 	int noalloc)
1259 {
1260 	struct anon	*ap;
1261 	spgcnt_t	npages;
1262 	kmutex_t	*ahm, *ahmpages = NULL;
1263 	pgcnt_t		pgcnt, i;
1264 	ulong_t		index, off;
1265 #ifdef DEBUG
1266 	int		refcnt;
1267 #endif
1268 
1269 	ASSERT(szc != 0);
1270 	pgcnt = page_get_pagecnt(szc);
1271 	ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
1272 	npages = btopr(size);
1273 	ASSERT(IS_P2ALIGNED(npages, pgcnt));
1274 	ASSERT(IS_P2ALIGNED(old_idx, pgcnt));
1275 
1276 	VM_STAT_ADD(anonvmstats.dupfillholes[0]);
1277 
1278 	while (npages > 0) {
1279 		index = old_idx;
1280 
1281 		/*
1282 		 * Find the next valid slot.
1283 		 */
1284 		if (anon_get_next_ptr(old, &index) == NULL)
1285 			break;
1286 
1287 		ASSERT(!ANON_ISBUSY(anon_get_slot(old, index)));
1288 		/*
1289 		 * Now backup index to the beginning of the
1290 		 * current large page region of the old array.
1291 		 */
1292 		index = P2ALIGN(index, pgcnt);
1293 		off = index - old_idx;
1294 		ASSERT(IS_P2ALIGNED(off, pgcnt));
1295 		npages -= off;
1296 		if (npages <= 0)
1297 			break;
1298 
1299 		/*
1300 		 * Fill and copy a large page regions worth
1301 		 * of anon slots.
1302 		 */
1303 		for (i = 0; i < pgcnt; i++) {
1304 			if ((ap = anon_get_ptr(old, index + i)) == NULL) {
1305 				if (noalloc) {
1306 					panic("anon_dup_fill_holes: "
1307 					    "empty anon slot\n");
1308 				}
1309 				VM_STAT_ADD(anonvmstats.dupfillholes[1]);
1310 				ap = anon_alloc(NULL, 0);
1311 				(void) anon_set_ptr(old, index + i, ap,
1312 				    ANON_SLEEP);
1313 			} else if (i == 0) {
1314 				/*
1315 				 * make the increment of all refcnts of all
1316 				 * anon slots of a large page appear atomic by
1317 				 * getting an anonpages_hash_lock for the
1318 				 * first anon slot of a large page.
1319 				 */
1320 				int hash = AH_LOCK(ap->an_vp, ap->an_off);
1321 
1322 				VM_STAT_ADD(anonvmstats.dupfillholes[2]);
1323 
1324 				ahmpages = &anonpages_hash_lock[hash];
1325 				mutex_enter(ahmpages);
1326 				/*LINTED*/
1327 				ASSERT(refcnt = ap->an_refcnt);
1328 
1329 				VM_STAT_COND_ADD(ap->an_refcnt > 1,
1330 				    anonvmstats.dupfillholes[3]);
1331 			}
1332 			(void) anon_set_ptr(new, new_idx + off + i, ap,
1333 			    ANON_SLEEP);
1334 			ahm = &anonhash_lock[AH_LOCK(ap->an_vp, ap->an_off)];
1335 			mutex_enter(ahm);
1336 			ASSERT(ahmpages != NULL || ap->an_refcnt == 1);
1337 			ASSERT(i == 0 || ahmpages == NULL ||
1338 			    refcnt == ap->an_refcnt);
1339 			ap->an_refcnt++;
1340 			mutex_exit(ahm);
1341 		}
1342 		if (ahmpages != NULL) {
1343 			mutex_exit(ahmpages);
1344 			ahmpages = NULL;
1345 		}
1346 		off += pgcnt;
1347 		new_idx += off;
1348 		old_idx += off;
1349 		npages -= pgcnt;
1350 	}
1351 }
1352 
1353 /*
1354  * Used when a segment with a vnode changes szc. similarly to
1355  * anon_dup_fill_holes() makes sure each large page region either has no anon
1356  * slots or all of them. but new slots are created by COWing the file
1357  * pages. on entrance no anon slots should be shared.
1358  */
1359 int
1360 anon_fill_cow_holes(
1361 	struct seg *seg,
1362 	caddr_t addr,
1363 	struct anon_hdr *ahp,
1364 	ulong_t an_idx,
1365 	struct vnode *vp,
1366 	u_offset_t vp_off,
1367 	size_t size,
1368 	uint_t szc,
1369 	uint_t prot,
1370 	struct vpage vpage[],
1371 	struct cred *cred)
1372 {
1373 	struct anon	*ap;
1374 	spgcnt_t	npages;
1375 	pgcnt_t		pgcnt, i;
1376 	ulong_t		index, off;
1377 	int		err = 0;
1378 	int		pageflags = 0;
1379 
1380 	ASSERT(szc != 0);
1381 	pgcnt = page_get_pagecnt(szc);
1382 	ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
1383 	npages = btopr(size);
1384 	ASSERT(IS_P2ALIGNED(npages, pgcnt));
1385 	ASSERT(IS_P2ALIGNED(an_idx, pgcnt));
1386 
1387 	while (npages > 0) {
1388 		index = an_idx;
1389 
1390 		/*
1391 		 * Find the next valid slot.
1392 		 */
1393 		if (anon_get_next_ptr(ahp, &index) == NULL) {
1394 			break;
1395 		}
1396 
1397 		ASSERT(!ANON_ISBUSY(anon_get_slot(ahp, index)));
1398 		/*
1399 		 * Now backup index to the beginning of the
1400 		 * current large page region of the anon array.
1401 		 */
1402 		index = P2ALIGN(index, pgcnt);
1403 		off = index - an_idx;
1404 		ASSERT(IS_P2ALIGNED(off, pgcnt));
1405 		npages -= off;
1406 		if (npages <= 0)
1407 			break;
1408 		an_idx += off;
1409 		vp_off += ptob(off);
1410 		addr += ptob(off);
1411 		if (vpage != NULL) {
1412 			vpage += off;
1413 		}
1414 
1415 		for (i = 0; i < pgcnt; i++, an_idx++, vp_off += PAGESIZE) {
1416 			if ((ap = anon_get_ptr(ahp, an_idx)) == NULL) {
1417 				page_t *pl[1 + 1];
1418 				page_t *pp;
1419 
1420 				err = VOP_GETPAGE(vp, vp_off, PAGESIZE, NULL,
1421 				    pl, PAGESIZE, seg, addr, S_READ, cred,
1422 				    NULL);
1423 				if (err) {
1424 					break;
1425 				}
1426 				if (vpage != NULL) {
1427 					prot = VPP_PROT(vpage);
1428 					pageflags = VPP_ISPPLOCK(vpage) ?
1429 					    LOCK_PAGE : 0;
1430 				}
1431 				pp = anon_private(&ap, seg, addr, prot, pl[0],
1432 					pageflags, cred);
1433 				if (pp == NULL) {
1434 					err = ENOMEM;
1435 					break;
1436 				}
1437 				(void) anon_set_ptr(ahp, an_idx, ap,
1438 				    ANON_SLEEP);
1439 				page_unlock(pp);
1440 			}
1441 			ASSERT(ap->an_refcnt == 1);
1442 			addr += PAGESIZE;
1443 			if (vpage != NULL) {
1444 				vpage++;
1445 			}
1446 		}
1447 		npages -= pgcnt;
1448 	}
1449 
1450 	return (err);
1451 }
1452 
1453 /*
1454  * Free a group of "size" anon pages, size in bytes,
1455  * and clear out the pointers to the anon entries.
1456  */
1457 void
1458 anon_free(struct anon_hdr *ahp, ulong_t index, size_t size)
1459 {
1460 	spgcnt_t npages;
1461 	struct anon *ap;
1462 	ulong_t old;
1463 
1464 	npages = btopr(size);
1465 
1466 	while (npages > 0) {
1467 		old = index;
1468 		if ((ap = anon_get_next_ptr(ahp, &index)) == NULL)
1469 			break;
1470 
1471 		ASSERT(!ANON_ISBUSY(anon_get_slot(ahp, index)));
1472 		npages -= index - old;
1473 		if (npages <= 0)
1474 			break;
1475 
1476 		(void) anon_set_ptr(ahp, index, NULL, ANON_SLEEP);
1477 		anon_decref(ap);
1478 		/*
1479 		 * Bump index and decrement page count
1480 		 */
1481 		index++;
1482 		npages--;
1483 	}
1484 }
1485 
1486 void
1487 anon_free_pages(
1488 	struct anon_hdr *ahp,
1489 	ulong_t an_idx,
1490 	size_t size,
1491 	uint_t szc)
1492 {
1493 	spgcnt_t	npages;
1494 	pgcnt_t		pgcnt;
1495 	ulong_t		index, off;
1496 
1497 	ASSERT(szc != 0);
1498 	pgcnt = page_get_pagecnt(szc);
1499 	ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
1500 	npages = btopr(size);
1501 	ASSERT(IS_P2ALIGNED(npages, pgcnt));
1502 	ASSERT(IS_P2ALIGNED(an_idx, pgcnt));
1503 	ASSERT(an_idx < ahp->size);
1504 
1505 	VM_STAT_ADD(anonvmstats.freepages[0]);
1506 
1507 	while (npages > 0) {
1508 		index = an_idx;
1509 
1510 		/*
1511 		 * Find the next valid slot.
1512 		 */
1513 		if (anon_get_next_ptr(ahp, &index) == NULL)
1514 			break;
1515 
1516 		ASSERT(!ANON_ISBUSY(anon_get_slot(ahp, index)));
1517 		/*
1518 		 * Now backup index to the beginning of the
1519 		 * current large page region of the old array.
1520 		 */
1521 		index = P2ALIGN(index, pgcnt);
1522 		off = index - an_idx;
1523 		ASSERT(IS_P2ALIGNED(off, pgcnt));
1524 		npages -= off;
1525 		if (npages <= 0)
1526 			break;
1527 
1528 		anon_decref_pages(ahp, index, szc);
1529 
1530 		off += pgcnt;
1531 		an_idx += off;
1532 		npages -= pgcnt;
1533 	}
1534 }
1535 
1536 /*
1537  * Make anonymous pages discardable
1538  */
1539 void
1540 anon_disclaim(struct anon_map *amp, ulong_t index, size_t size)
1541 {
1542 	spgcnt_t npages = btopr(size);
1543 	struct anon *ap;
1544 	struct vnode *vp;
1545 	anoff_t off;
1546 	page_t *pp, *root_pp;
1547 	kmutex_t *ahm;
1548 	pgcnt_t pgcnt;
1549 	ulong_t old_idx, idx, i;
1550 	struct anon_hdr *ahp = amp->ahp;
1551 	anon_sync_obj_t cookie;
1552 
1553 	ASSERT(RW_READ_HELD(&amp->a_rwlock));
1554 	pgcnt = 1;
1555 	for (; npages > 0; index = (pgcnt == 1) ? index + 1 :
1556 	    P2ROUNDUP(index + 1, pgcnt), npages -= pgcnt) {
1557 
1558 		/*
1559 		 * get anon pointer and index for the first valid entry
1560 		 * in the anon list, starting from "index"
1561 		 */
1562 		old_idx = index;
1563 		if ((ap = anon_get_next_ptr(ahp, &index)) == NULL)
1564 			break;
1565 
1566 		/*
1567 		 * decrement npages by number of NULL anon slots we skipped
1568 		 */
1569 		npages -= index - old_idx;
1570 		if (npages <= 0)
1571 			break;
1572 
1573 		anon_array_enter(amp, index, &cookie);
1574 		ap = anon_get_ptr(ahp, index);
1575 		ASSERT(ap != NULL);
1576 
1577 		/*
1578 		 * Get anonymous page and try to lock it SE_EXCL;
1579 		 * if we couldn't grab the lock we skip to next page.
1580 		 */
1581 		swap_xlate(ap, &vp, &off);
1582 		pp = page_lookup_nowait(vp, (u_offset_t)off, SE_EXCL);
1583 		if (pp == NULL) {
1584 			segadvstat.MADV_FREE_miss.value.ul++;
1585 			pgcnt = 1;
1586 			anon_array_exit(&cookie);
1587 			continue;
1588 		}
1589 		pgcnt = page_get_pagecnt(pp->p_szc);
1590 
1591 		/*
1592 		 * we cannot free a page which is permanently locked.
1593 		 * The page_struct_lock need not be acquired to examine
1594 		 * these fields since the page has an "exclusive" lock.
1595 		 */
1596 		if (pp->p_lckcnt != 0 || pp->p_cowcnt != 0) {
1597 			page_unlock(pp);
1598 			segadvstat.MADV_FREE_miss.value.ul++;
1599 			anon_array_exit(&cookie);
1600 			continue;
1601 		}
1602 
1603 		ahm = &anonhash_lock[AH_LOCK(vp, off)];
1604 		mutex_enter(ahm);
1605 		ASSERT(ap->an_refcnt != 0);
1606 		/*
1607 		 * skip this one if copy-on-write is not yet broken.
1608 		 */
1609 		if (ap->an_refcnt > 1) {
1610 			mutex_exit(ahm);
1611 			page_unlock(pp);
1612 			segadvstat.MADV_FREE_miss.value.ul++;
1613 			anon_array_exit(&cookie);
1614 			continue;
1615 		}
1616 
1617 		if (pp->p_szc == 0) {
1618 			pgcnt = 1;
1619 
1620 			/*
1621 			 * free swap slot;
1622 			 */
1623 			if (ap->an_pvp) {
1624 				swap_phys_free(ap->an_pvp, ap->an_poff,
1625 				    PAGESIZE);
1626 				ap->an_pvp = NULL;
1627 				ap->an_poff = 0;
1628 			}
1629 			mutex_exit(ahm);
1630 			segadvstat.MADV_FREE_hit.value.ul++;
1631 
1632 			/*
1633 			 * while we are at it, unload all the translations
1634 			 * and attempt to free the page.
1635 			 */
1636 			(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
1637 			/*LINTED: constant in conditional context */
1638 			VN_DISPOSE(pp, B_FREE, 0, kcred);
1639 			anon_array_exit(&cookie);
1640 			continue;
1641 		}
1642 
1643 		pgcnt = page_get_pagecnt(pp->p_szc);
1644 		if (!IS_P2ALIGNED(index, pgcnt) || npages < pgcnt) {
1645 			if (!page_try_demote_pages(pp)) {
1646 				mutex_exit(ahm);
1647 				page_unlock(pp);
1648 				segadvstat.MADV_FREE_miss.value.ul++;
1649 				anon_array_exit(&cookie);
1650 				continue;
1651 			} else {
1652 				pgcnt = 1;
1653 				if (ap->an_pvp) {
1654 					swap_phys_free(ap->an_pvp,
1655 					    ap->an_poff, PAGESIZE);
1656 					ap->an_pvp = NULL;
1657 					ap->an_poff = 0;
1658 				}
1659 				mutex_exit(ahm);
1660 				(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
1661 				/*LINTED*/
1662 				VN_DISPOSE(pp, B_FREE, 0, kcred);
1663 				segadvstat.MADV_FREE_hit.value.ul++;
1664 				anon_array_exit(&cookie);
1665 				continue;
1666 			}
1667 		}
1668 		mutex_exit(ahm);
1669 		root_pp = pp;
1670 
1671 		/*
1672 		 * try to lock remaining pages
1673 		 */
1674 		for (idx = 1; idx < pgcnt; idx++) {
1675 			pp++;
1676 			if (!page_trylock(pp, SE_EXCL))
1677 				break;
1678 			if (pp->p_lckcnt != 0 || pp->p_cowcnt != 0) {
1679 				page_unlock(pp);
1680 				break;
1681 			}
1682 		}
1683 
1684 		if (idx == pgcnt) {
1685 			for (i = 0; i < pgcnt; i++) {
1686 				ap = anon_get_ptr(ahp, index + i);
1687 				if (ap == NULL)
1688 					break;
1689 				swap_xlate(ap, &vp, &off);
1690 				ahm = &anonhash_lock[AH_LOCK(vp, off)];
1691 				mutex_enter(ahm);
1692 				ASSERT(ap->an_refcnt != 0);
1693 
1694 				/*
1695 				 * skip this one if copy-on-write
1696 				 * is not yet broken.
1697 				 */
1698 				if (ap->an_refcnt > 1) {
1699 					mutex_exit(ahm);
1700 					goto skiplp;
1701 				}
1702 				if (ap->an_pvp) {
1703 					swap_phys_free(ap->an_pvp,
1704 					    ap->an_poff, PAGESIZE);
1705 					ap->an_pvp = NULL;
1706 					ap->an_poff = 0;
1707 				}
1708 				mutex_exit(ahm);
1709 			}
1710 			page_destroy_pages(root_pp);
1711 			segadvstat.MADV_FREE_hit.value.ul += pgcnt;
1712 			anon_array_exit(&cookie);
1713 			continue;
1714 		}
1715 skiplp:
1716 		segadvstat.MADV_FREE_miss.value.ul += pgcnt;
1717 		for (i = 0, pp = root_pp; i < idx; pp++, i++)
1718 			page_unlock(pp);
1719 		anon_array_exit(&cookie);
1720 	}
1721 }
1722 
1723 /*
1724  * Return the kept page(s) and protections back to the segment driver.
1725  */
1726 int
1727 anon_getpage(
1728 	struct anon **app,
1729 	uint_t *protp,
1730 	page_t *pl[],
1731 	size_t plsz,
1732 	struct seg *seg,
1733 	caddr_t addr,
1734 	enum seg_rw rw,
1735 	struct cred *cred)
1736 {
1737 	page_t *pp;
1738 	struct anon *ap = *app;
1739 	struct vnode *vp;
1740 	anoff_t off;
1741 	int err;
1742 	kmutex_t *ahm;
1743 
1744 	swap_xlate(ap, &vp, &off);
1745 
1746 	/*
1747 	 * Lookup the page. If page is being paged in,
1748 	 * wait for it to finish as we must return a list of
1749 	 * pages since this routine acts like the VOP_GETPAGE
1750 	 * routine does.
1751 	 */
1752 	if (pl != NULL && (pp = page_lookup(vp, (u_offset_t)off, SE_SHARED))) {
1753 		ahm = &anonhash_lock[AH_LOCK(ap->an_vp, ap->an_off)];
1754 		mutex_enter(ahm);
1755 		if (ap->an_refcnt == 1)
1756 			*protp = PROT_ALL;
1757 		else
1758 			*protp = PROT_ALL & ~PROT_WRITE;
1759 		mutex_exit(ahm);
1760 		pl[0] = pp;
1761 		pl[1] = NULL;
1762 		return (0);
1763 	}
1764 
1765 	/*
1766 	 * Simply treat it as a vnode fault on the anon vp.
1767 	 */
1768 
1769 	TRACE_3(TR_FAC_VM, TR_ANON_GETPAGE,
1770 		"anon_getpage:seg %x addr %x vp %x",
1771 		seg, addr, vp);
1772 
1773 	err = VOP_GETPAGE(vp, (u_offset_t)off, PAGESIZE, protp, pl, plsz,
1774 	    seg, addr, rw, cred, NULL);
1775 
1776 	if (err == 0 && pl != NULL) {
1777 		ahm = &anonhash_lock[AH_LOCK(ap->an_vp, ap->an_off)];
1778 		mutex_enter(ahm);
1779 		if (ap->an_refcnt != 1)
1780 			*protp &= ~PROT_WRITE;	/* make read-only */
1781 		mutex_exit(ahm);
1782 	}
1783 	return (err);
1784 }
1785 
1786 /*
1787  * Creates or returns kept pages to the segment driver.  returns -1 if a large
1788  * page cannot be allocated. returns -2 if some other process has allocated a
1789  * larger page.
1790  *
1791  * For cowfault it will allocate any size pages to fill the requested area to
1792  * avoid partially overwriting anon slots (i.e. sharing only some of the anon
1793  * slots within a large page with other processes). This policy greatly
1794  * simplifies large page freeing (which is only freed when all anon slot
1795  * refcnts are 0).
1796  */
1797 int
1798 anon_map_getpages(
1799 	struct anon_map *amp,
1800 	ulong_t	start_idx,
1801 	uint_t	szc,
1802 	struct seg *seg,
1803 	caddr_t	addr,
1804 	uint_t prot,
1805 	uint_t *protp,
1806 	page_t	*ppa[],
1807 	uint_t	*ppa_szc,
1808 	struct vpage vpage[],
1809 	enum seg_rw rw,
1810 	int brkcow,
1811 	int anypgsz,
1812 	int pgflags,
1813 	struct cred *cred)
1814 {
1815 	pgcnt_t		pgcnt;
1816 	struct anon	*ap;
1817 	struct vnode	*vp;
1818 	anoff_t		off;
1819 	page_t		*pp, *pl[2], *conpp = NULL;
1820 	caddr_t		vaddr;
1821 	ulong_t		pg_idx, an_idx, i;
1822 	spgcnt_t	nreloc = 0;
1823 	int		prealloc = 1;
1824 	int		err, slotcreate;
1825 	uint_t		vpprot;
1826 	int		upsize = (szc < seg->s_szc);
1827 
1828 #if !defined(__i386) && !defined(__amd64)
1829 	ASSERT(seg->s_szc != 0);
1830 #endif
1831 	ASSERT(szc <= seg->s_szc);
1832 	ASSERT(ppa_szc != NULL);
1833 	ASSERT(rw != S_CREATE);
1834 
1835 	*protp = PROT_ALL;
1836 
1837 	VM_STAT_ADD(anonvmstats.getpages[0]);
1838 
1839 	if (szc == 0) {
1840 		VM_STAT_ADD(anonvmstats.getpages[1]);
1841 		if ((ap = anon_get_ptr(amp->ahp, start_idx)) != NULL) {
1842 			err = anon_getpage(&ap, protp, pl, PAGESIZE, seg,
1843 			    addr, rw, cred);
1844 			if (err)
1845 				return (err);
1846 			ppa[0] = pl[0];
1847 			if (brkcow == 0 || (*protp & PROT_WRITE)) {
1848 				VM_STAT_ADD(anonvmstats.getpages[2]);
1849 				if (ppa[0]->p_szc != 0 && upsize) {
1850 					VM_STAT_ADD(anonvmstats.getpages[3]);
1851 					*ppa_szc = MIN(ppa[0]->p_szc,
1852 					    seg->s_szc);
1853 					page_unlock(ppa[0]);
1854 					return (-2);
1855 				}
1856 				return (0);
1857 			}
1858 			panic("anon_map_getpages: cowfault for szc 0");
1859 		} else {
1860 			VM_STAT_ADD(anonvmstats.getpages[4]);
1861 			ppa[0] = anon_zero(seg, addr, &ap, cred);
1862 			if (ppa[0] == NULL)
1863 				return (ENOMEM);
1864 			(void) anon_set_ptr(amp->ahp, start_idx, ap,
1865 			    ANON_SLEEP);
1866 			return (0);
1867 		}
1868 	}
1869 
1870 	pgcnt = page_get_pagecnt(szc);
1871 	ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
1872 	ASSERT(IS_P2ALIGNED(start_idx, pgcnt));
1873 
1874 	/*
1875 	 * First we check for the case that the requtested large
1876 	 * page or larger page already exists in the system.
1877 	 * Actually we only check if the first constituent page
1878 	 * exists and only preallocate if it's not found.
1879 	 */
1880 	ap = anon_get_ptr(amp->ahp, start_idx);
1881 	if (ap) {
1882 		uint_t pszc;
1883 		swap_xlate(ap, &vp, &off);
1884 		if (page_exists_forreal(vp, (u_offset_t)off, &pszc)) {
1885 			if (pszc > szc && upsize) {
1886 				*ppa_szc = MIN(pszc, seg->s_szc);
1887 				return (-2);
1888 			}
1889 			if (pszc >= szc) {
1890 				prealloc = 0;
1891 			}
1892 		}
1893 	}
1894 
1895 	VM_STAT_COND_ADD(prealloc == 0, anonvmstats.getpages[5]);
1896 	VM_STAT_COND_ADD(prealloc != 0, anonvmstats.getpages[6]);
1897 
1898 top:
1899 	/*
1900 	 * If a smaller page or no page at all was found,
1901 	 * grab a large page off the freelist.
1902 	 */
1903 	if (prealloc) {
1904 		ASSERT(conpp == NULL);
1905 		if (page_alloc_pages(anon_vp, seg, addr, NULL, ppa,
1906 		    szc, 0, pgflags) != 0) {
1907 			VM_STAT_ADD(anonvmstats.getpages[7]);
1908 			if (brkcow == 0 ||
1909 			    !anon_share(amp->ahp, start_idx, pgcnt)) {
1910 				/*
1911 				 * If the refcnt's of all anon slots are <= 1
1912 				 * they can't increase since we are holding
1913 				 * the address space's lock. So segvn can
1914 				 * safely decrease szc without risking to
1915 				 * generate a cow fault for the region smaller
1916 				 * than the segment's largest page size.
1917 				 */
1918 				VM_STAT_ADD(anonvmstats.getpages[8]);
1919 				return (-1);
1920 			}
1921 		docow:
1922 			/*
1923 			 * This is a cow fault. Copy away the entire 1 large
1924 			 * page region of this segment.
1925 			 */
1926 			if (szc != seg->s_szc)
1927 				panic("anon_map_getpages: cowfault for szc %d",
1928 				    szc);
1929 			vaddr = addr;
1930 			for (pg_idx = 0, an_idx = start_idx; pg_idx < pgcnt;
1931 			    pg_idx++, an_idx++, vaddr += PAGESIZE) {
1932 				if ((ap = anon_get_ptr(amp->ahp, an_idx)) !=
1933 				    NULL) {
1934 					err = anon_getpage(&ap, &vpprot, pl,
1935 					    PAGESIZE, seg, vaddr, rw, cred);
1936 					if (err) {
1937 						for (i = 0; i < pg_idx; i++) {
1938 							if ((pp = ppa[i]) !=
1939 							    NULL)
1940 								page_unlock(pp);
1941 						}
1942 						return (err);
1943 					}
1944 					ppa[pg_idx] = pl[0];
1945 				} else {
1946 					/*
1947 					 * Since this is a cowfault we know
1948 					 * that this address space has a
1949 					 * parent or children which means
1950 					 * anon_dup_fill_holes() has initialized
1951 					 * all anon slots within a large page
1952 					 * region that had at least one anon
1953 					 * slot at the time of fork().
1954 					 */
1955 					panic("anon_map_getpages: "
1956 					    "cowfault but anon slot is empty");
1957 				}
1958 			}
1959 			VM_STAT_ADD(anonvmstats.getpages[9]);
1960 			*protp = PROT_ALL;
1961 			return (anon_map_privatepages(amp, start_idx, szc, seg,
1962 			    addr, prot, ppa, vpage, anypgsz, pgflags, cred));
1963 		}
1964 	}
1965 
1966 	VM_STAT_ADD(anonvmstats.getpages[10]);
1967 
1968 	an_idx = start_idx;
1969 	pg_idx = 0;
1970 	vaddr = addr;
1971 	while (pg_idx < pgcnt) {
1972 		slotcreate = 0;
1973 		if ((ap = anon_get_ptr(amp->ahp, an_idx)) == NULL) {
1974 			VM_STAT_ADD(anonvmstats.getpages[11]);
1975 			/*
1976 			 * For us to have decided not to preallocate
1977 			 * would have meant that a large page
1978 			 * was found. Which also means that all of the
1979 			 * anon slots for that page would have been
1980 			 * already created for us.
1981 			 */
1982 			if (prealloc == 0)
1983 				panic("anon_map_getpages: prealloc = 0");
1984 
1985 			slotcreate = 1;
1986 			ap = anon_alloc(NULL, 0);
1987 		}
1988 		swap_xlate(ap, &vp, &off);
1989 
1990 		/*
1991 		 * Now setup our preallocated page to pass down
1992 		 * to swap_getpage().
1993 		 */
1994 		if (prealloc) {
1995 			ASSERT(ppa[pg_idx]->p_szc == szc);
1996 			conpp = ppa[pg_idx];
1997 		}
1998 		ASSERT(prealloc || conpp == NULL);
1999 
2000 		/*
2001 		 * If we just created this anon slot then call
2002 		 * with S_CREATE to prevent doing IO on the page.
2003 		 * Similar to the anon_zero case.
2004 		 */
2005 		err = swap_getconpage(vp, (u_offset_t)off, PAGESIZE,
2006 		    NULL, pl, PAGESIZE, conpp, ppa_szc, &nreloc, seg, vaddr,
2007 		    slotcreate == 1 ? S_CREATE : rw, cred);
2008 
2009 		if (err) {
2010 			ASSERT(err != -2 || upsize);
2011 			VM_STAT_ADD(anonvmstats.getpages[12]);
2012 			ASSERT(slotcreate == 0);
2013 			goto io_err;
2014 		}
2015 
2016 		pp = pl[0];
2017 
2018 		if (pp->p_szc < szc || (pp->p_szc > szc && upsize)) {
2019 			VM_STAT_ADD(anonvmstats.getpages[13]);
2020 			ASSERT(slotcreate == 0);
2021 			ASSERT(prealloc == 0);
2022 			ASSERT(pg_idx == 0);
2023 			if (pp->p_szc > szc) {
2024 				ASSERT(upsize);
2025 				*ppa_szc = MIN(pp->p_szc, seg->s_szc);
2026 				page_unlock(pp);
2027 				VM_STAT_ADD(anonvmstats.getpages[14]);
2028 				return (-2);
2029 			}
2030 			page_unlock(pp);
2031 			prealloc = 1;
2032 			goto top;
2033 		}
2034 
2035 		/*
2036 		 * If we decided to preallocate but VOP_GETPAGE
2037 		 * found a page in the system that satisfies our
2038 		 * request then free up our preallocated large page
2039 		 * and continue looping accross the existing large
2040 		 * page via VOP_GETPAGE.
2041 		 */
2042 		if (prealloc && pp != ppa[pg_idx]) {
2043 			VM_STAT_ADD(anonvmstats.getpages[15]);
2044 			ASSERT(slotcreate == 0);
2045 			ASSERT(pg_idx == 0);
2046 			conpp = NULL;
2047 			prealloc = 0;
2048 			page_free_pages(ppa[0]);
2049 		}
2050 
2051 		if (prealloc && nreloc > 1) {
2052 			/*
2053 			 * we have relocated out of a smaller large page.
2054 			 * skip npgs - 1 iterations and continue which will
2055 			 * increment by one the loop indices.
2056 			 */
2057 			spgcnt_t npgs = nreloc;
2058 
2059 			VM_STAT_ADD(anonvmstats.getpages[16]);
2060 
2061 			ASSERT(pp == ppa[pg_idx]);
2062 			ASSERT(slotcreate == 0);
2063 			ASSERT(pg_idx + npgs <= pgcnt);
2064 			if ((*protp & PROT_WRITE) &&
2065 			    anon_share(amp->ahp, an_idx, npgs)) {
2066 			    *protp &= ~PROT_WRITE;
2067 			}
2068 			pg_idx += npgs;
2069 			an_idx += npgs;
2070 			vaddr += PAGESIZE * npgs;
2071 			continue;
2072 		}
2073 
2074 		VM_STAT_ADD(anonvmstats.getpages[17]);
2075 
2076 		/*
2077 		 * Anon_zero case.
2078 		 */
2079 		if (slotcreate) {
2080 			ASSERT(prealloc);
2081 			pagezero(pp, 0, PAGESIZE);
2082 			CPU_STATS_ADD_K(vm, zfod, 1);
2083 			hat_setrefmod(pp);
2084 		}
2085 
2086 		ASSERT(prealloc == 0 || ppa[pg_idx] == pp);
2087 		ASSERT(prealloc != 0 || PAGE_SHARED(pp));
2088 		ASSERT(prealloc == 0 || PAGE_EXCL(pp));
2089 
2090 		if (pg_idx > 0 &&
2091 		    ((page_pptonum(pp) != page_pptonum(ppa[pg_idx - 1]) + 1) ||
2092 		    (pp->p_szc != ppa[pg_idx - 1]->p_szc))) {
2093 			panic("anon_map_getpages: unexpected page");
2094 		} else if (pg_idx == 0 && (page_pptonum(pp) & (pgcnt - 1))) {
2095 			panic("anon_map_getpages: unaligned page");
2096 		}
2097 
2098 		if (prealloc == 0) {
2099 			ppa[pg_idx] = pp;
2100 		}
2101 
2102 		if (ap->an_refcnt > 1) {
2103 			VM_STAT_ADD(anonvmstats.getpages[18]);
2104 			*protp &= ~PROT_WRITE;
2105 		}
2106 
2107 		/*
2108 		 * If this is a new anon slot then initialize
2109 		 * the anon array entry.
2110 		 */
2111 		if (slotcreate) {
2112 			(void) anon_set_ptr(amp->ahp, an_idx, ap, ANON_SLEEP);
2113 		}
2114 		pg_idx++;
2115 		an_idx++;
2116 		vaddr += PAGESIZE;
2117 	}
2118 
2119 	/*
2120 	 * Since preallocated pages come off the freelist
2121 	 * they are locked SE_EXCL. Simply downgrade and return.
2122 	 */
2123 	if (prealloc) {
2124 		VM_STAT_ADD(anonvmstats.getpages[19]);
2125 		conpp = NULL;
2126 		for (pg_idx = 0; pg_idx < pgcnt; pg_idx++) {
2127 			page_downgrade(ppa[pg_idx]);
2128 		}
2129 	}
2130 	ASSERT(conpp == NULL);
2131 
2132 	if (brkcow == 0 || (*protp & PROT_WRITE)) {
2133 		VM_STAT_ADD(anonvmstats.getpages[20]);
2134 		return (0);
2135 	}
2136 
2137 	if (szc < seg->s_szc)
2138 		panic("anon_map_getpages: cowfault for szc %d", szc);
2139 
2140 	VM_STAT_ADD(anonvmstats.getpages[21]);
2141 
2142 	*protp = PROT_ALL;
2143 	return (anon_map_privatepages(amp, start_idx, szc, seg, addr, prot,
2144 	    ppa, vpage, anypgsz, pgflags, cred));
2145 io_err:
2146 	/*
2147 	 * We got an IO error somewhere in our large page.
2148 	 * If we were using a preallocated page then just demote
2149 	 * all the constituent pages that we've succeeded with sofar
2150 	 * to PAGESIZE pages and leave them in the system
2151 	 * unlocked.
2152 	 */
2153 
2154 	ASSERT(err != -2 || ((pg_idx == 0) && upsize));
2155 
2156 	VM_STAT_COND_ADD(err > 0, anonvmstats.getpages[22]);
2157 	VM_STAT_COND_ADD(err == -1, anonvmstats.getpages[23]);
2158 	VM_STAT_COND_ADD(err == -2, anonvmstats.getpages[24]);
2159 
2160 	if (prealloc) {
2161 		conpp = NULL;
2162 		if (pg_idx > 0) {
2163 			VM_STAT_ADD(anonvmstats.getpages[25]);
2164 			for (i = 0; i < pgcnt; i++) {
2165 				pp = ppa[i];
2166 				ASSERT(PAGE_EXCL(pp));
2167 				ASSERT(pp->p_szc == szc);
2168 				pp->p_szc = 0;
2169 			}
2170 			for (i = 0; i < pg_idx; i++) {
2171 				ASSERT(!hat_page_is_mapped(ppa[i]));
2172 				page_unlock(ppa[i]);
2173 			}
2174 			/*
2175 			 * Now free up the remaining unused constituent
2176 			 * pages.
2177 			 */
2178 			while (pg_idx < pgcnt) {
2179 				ASSERT(!hat_page_is_mapped(ppa[pg_idx]));
2180 				page_free(ppa[pg_idx], 0);
2181 				pg_idx++;
2182 			}
2183 		} else {
2184 			VM_STAT_ADD(anonvmstats.getpages[26]);
2185 			page_free_pages(ppa[0]);
2186 		}
2187 	} else {
2188 		VM_STAT_ADD(anonvmstats.getpages[27]);
2189 		ASSERT(err > 0);
2190 		for (i = 0; i < pg_idx; i++)
2191 			page_unlock(ppa[i]);
2192 	}
2193 	ASSERT(conpp == NULL);
2194 	if (err != -1)
2195 		return (err);
2196 	/*
2197 	 * we are here because we failed to relocate.
2198 	 */
2199 	ASSERT(prealloc);
2200 	if (brkcow == 0 || !anon_share(amp->ahp, start_idx, pgcnt)) {
2201 		VM_STAT_ADD(anonvmstats.getpages[28]);
2202 		return (-1);
2203 	}
2204 	VM_STAT_ADD(anonvmstats.getpages[29]);
2205 	goto docow;
2206 }
2207 
2208 
2209 /*
2210  * Turn a reference to an object or shared anon page
2211  * into a private page with a copy of the data from the
2212  * original page which is always locked by the caller.
2213  * This routine unloads the translation and unlocks the
2214  * original page, if it isn't being stolen, before returning
2215  * to the caller.
2216  *
2217  * NOTE:  The original anon slot is not freed by this routine
2218  *	  It must be freed by the caller while holding the
2219  *	  "anon_map" lock to prevent races which can occur if
2220  *	  a process has multiple lwps in its address space.
2221  */
2222 page_t *
2223 anon_private(
2224 	struct anon **app,
2225 	struct seg *seg,
2226 	caddr_t addr,
2227 	uint_t	prot,
2228 	page_t *opp,
2229 	int oppflags,
2230 	struct cred *cred)
2231 {
2232 	struct anon *old = *app;
2233 	struct anon *new;
2234 	page_t *pp = NULL;
2235 	struct vnode *vp;
2236 	anoff_t off;
2237 	page_t *anon_pl[1 + 1];
2238 	int err;
2239 
2240 	if (oppflags & STEAL_PAGE)
2241 		ASSERT(PAGE_EXCL(opp));
2242 	else
2243 		ASSERT(PAGE_LOCKED(opp));
2244 
2245 	CPU_STATS_ADD_K(vm, cow_fault, 1);
2246 
2247 	/* Kernel probe */
2248 	TNF_PROBE_1(anon_private, "vm pagefault", /* CSTYLED */,
2249 		tnf_opaque,	address,	addr);
2250 
2251 	*app = new = anon_alloc(NULL, 0);
2252 	swap_xlate(new, &vp, &off);
2253 
2254 	if (oppflags & STEAL_PAGE) {
2255 		page_rename(opp, vp, (u_offset_t)off);
2256 		pp = opp;
2257 		TRACE_5(TR_FAC_VM, TR_ANON_PRIVATE,
2258 			"anon_private:seg %p addr %x pp %p vp %p off %lx",
2259 			seg, addr, pp, vp, off);
2260 		hat_setmod(pp);
2261 
2262 		/* bug 4026339 */
2263 		page_downgrade(pp);
2264 		return (pp);
2265 	}
2266 
2267 	/*
2268 	 * Call the VOP_GETPAGE routine to create the page, thereby
2269 	 * enabling the vnode driver to allocate any filesystem
2270 	 * space (e.g., disk block allocation for UFS).  This also
2271 	 * prevents more than one page from being added to the
2272 	 * vnode at the same time.
2273 	 */
2274 	err = VOP_GETPAGE(vp, (u_offset_t)off, PAGESIZE, NULL,
2275 	    anon_pl, PAGESIZE, seg, addr, S_CREATE, cred, NULL);
2276 	if (err)
2277 		goto out;
2278 
2279 	pp = anon_pl[0];
2280 
2281 	/*
2282 	 * If the original page was locked, we need to move the lock
2283 	 * to the new page by transfering 'cowcnt/lckcnt' of the original
2284 	 * page to 'cowcnt/lckcnt' of the new page.
2285 	 *
2286 	 * See Statement at the beginning of segvn_lockop() and
2287 	 * comments in page_pp_useclaim() regarding the way
2288 	 * cowcnts/lckcnts are handled.
2289 	 *
2290 	 * Also availrmem must be decremented up front for read only mapping
2291 	 * before calling page_pp_useclaim. page_pp_useclaim will bump it back
2292 	 * if availrmem did not need to be decremented after all.
2293 	 */
2294 	if (oppflags & LOCK_PAGE) {
2295 		if ((prot & PROT_WRITE) == 0) {
2296 			mutex_enter(&freemem_lock);
2297 			if (availrmem > pages_pp_maximum) {
2298 				availrmem--;
2299 				pages_useclaim++;
2300 			} else {
2301 				mutex_exit(&freemem_lock);
2302 				goto out;
2303 			}
2304 			mutex_exit(&freemem_lock);
2305 		}
2306 		page_pp_useclaim(opp, pp, prot & PROT_WRITE);
2307 	}
2308 
2309 	/*
2310 	 * Now copy the contents from the original page,
2311 	 * which is locked and loaded in the MMU by
2312 	 * the caller to prevent yet another page fault.
2313 	 */
2314 	/* XXX - should set mod bit in here */
2315 	if (ppcopy(opp, pp) == 0) {
2316 		/*
2317 		 * Before ppcopy could hanlde UE or other faults, we
2318 		 * would have panicked here, and still have no option
2319 		 * but to do so now.
2320 		 */
2321 		panic("anon_private, ppcopy failed, opp = 0x%p, pp = 0x%p",
2322 		    opp, pp);
2323 	}
2324 
2325 	hat_setrefmod(pp);		/* mark as modified */
2326 
2327 	/*
2328 	 * Unload the old translation.
2329 	 */
2330 	hat_unload(seg->s_as->a_hat, addr, PAGESIZE, HAT_UNLOAD);
2331 
2332 	/*
2333 	 * Free unmapped, unmodified original page.
2334 	 * or release the lock on the original page,
2335 	 * otherwise the process will sleep forever in
2336 	 * anon_decref() waiting for the "exclusive" lock
2337 	 * on the page.
2338 	 */
2339 	(void) page_release(opp, 1);
2340 
2341 	/*
2342 	 * we are done with page creation so downgrade the new
2343 	 * page's selock to shared, this helps when multiple
2344 	 * as_fault(...SOFTLOCK...) are done to the same
2345 	 * page(aio)
2346 	 */
2347 	page_downgrade(pp);
2348 
2349 	/*
2350 	 * NOTE:  The original anon slot must be freed by the
2351 	 * caller while holding the "anon_map" lock, if we
2352 	 * copied away from an anonymous page.
2353 	 */
2354 	return (pp);
2355 
2356 out:
2357 	*app = old;
2358 	if (pp)
2359 		page_unlock(pp);
2360 	anon_decref(new);
2361 	page_unlock(opp);
2362 	return ((page_t *)NULL);
2363 }
2364 
2365 int
2366 anon_map_privatepages(
2367 	struct anon_map *amp,
2368 	ulong_t	start_idx,
2369 	uint_t	szc,
2370 	struct seg *seg,
2371 	caddr_t addr,
2372 	uint_t	prot,
2373 	page_t	*ppa[],
2374 	struct vpage vpage[],
2375 	int anypgsz,
2376 	int pgflags,
2377 	struct cred *cred)
2378 {
2379 	pgcnt_t		pgcnt;
2380 	struct vnode	*vp;
2381 	anoff_t		off;
2382 	page_t		*pl[2], *conpp = NULL;
2383 	int		err;
2384 	int		prealloc = 1;
2385 	struct anon	*ap, *oldap;
2386 	caddr_t		vaddr;
2387 	page_t		*pplist, *pp;
2388 	ulong_t		pg_idx, an_idx;
2389 	spgcnt_t	nreloc = 0;
2390 	int		pagelock = 0;
2391 	kmutex_t	*ahmpages = NULL;
2392 #ifdef DEBUG
2393 	int		refcnt;
2394 #endif
2395 
2396 	ASSERT(szc != 0);
2397 	ASSERT(szc == seg->s_szc);
2398 
2399 	VM_STAT_ADD(anonvmstats.privatepages[0]);
2400 
2401 	pgcnt = page_get_pagecnt(szc);
2402 	ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
2403 	ASSERT(IS_P2ALIGNED(start_idx, pgcnt));
2404 
2405 	ASSERT(amp != NULL);
2406 	ap = anon_get_ptr(amp->ahp, start_idx);
2407 	ASSERT(ap == NULL || ap->an_refcnt >= 1);
2408 
2409 	VM_STAT_COND_ADD(ap == NULL, anonvmstats.privatepages[1]);
2410 
2411 	/*
2412 	 * Now try and allocate the large page. If we fail then just
2413 	 * let VOP_GETPAGE give us PAGESIZE pages. Normally we let
2414 	 * the caller make this decision but to avoid added complexity
2415 	 * it's simplier to handle that case here.
2416 	 */
2417 	if (anypgsz == -1) {
2418 		VM_STAT_ADD(anonvmstats.privatepages[2]);
2419 		prealloc = 0;
2420 	} else if (page_alloc_pages(anon_vp, seg, addr, &pplist, NULL, szc,
2421 	    anypgsz, pgflags) != 0) {
2422 		VM_STAT_ADD(anonvmstats.privatepages[3]);
2423 		prealloc = 0;
2424 	}
2425 
2426 	/*
2427 	 * make the decrement of all refcnts of all
2428 	 * anon slots of a large page appear atomic by
2429 	 * getting an anonpages_hash_lock for the
2430 	 * first anon slot of a large page.
2431 	 */
2432 	if (ap != NULL) {
2433 		ahmpages = &anonpages_hash_lock[AH_LOCK(ap->an_vp,
2434 		    ap->an_off)];
2435 		mutex_enter(ahmpages);
2436 		if (ap->an_refcnt == 1) {
2437 			VM_STAT_ADD(anonvmstats.privatepages[4]);
2438 			ASSERT(!anon_share(amp->ahp, start_idx, pgcnt));
2439 			mutex_exit(ahmpages);
2440 
2441 			if (prealloc) {
2442 				page_free_replacement_page(pplist);
2443 				page_create_putback(pgcnt);
2444 			}
2445 			ASSERT(ppa[0]->p_szc <= szc);
2446 			if (ppa[0]->p_szc == szc) {
2447 				VM_STAT_ADD(anonvmstats.privatepages[5]);
2448 				return (0);
2449 			}
2450 			for (pg_idx = 0; pg_idx < pgcnt; pg_idx++) {
2451 				ASSERT(ppa[pg_idx] != NULL);
2452 				page_unlock(ppa[pg_idx]);
2453 			}
2454 			return (-1);
2455 		}
2456 	}
2457 
2458 	/*
2459 	 * If we are passed in the vpage array and this is
2460 	 * not PROT_WRITE then we need to decrement availrmem
2461 	 * up front before we try anything. If we need to and
2462 	 * can't decrement availrmem then its better to fail now
2463 	 * than in the middle of processing the new large page.
2464 	 * page_pp_usclaim() on behalf of each constituent page
2465 	 * below will adjust availrmem back for the cases not needed.
2466 	 */
2467 	if (vpage != NULL && (prot & PROT_WRITE) == 0) {
2468 		for (pg_idx = 0; pg_idx < pgcnt; pg_idx++) {
2469 			if (VPP_ISPPLOCK(&vpage[pg_idx])) {
2470 				pagelock = 1;
2471 				break;
2472 			}
2473 		}
2474 		if (pagelock) {
2475 			VM_STAT_ADD(anonvmstats.privatepages[6]);
2476 			mutex_enter(&freemem_lock);
2477 			if (availrmem >= pages_pp_maximum + pgcnt) {
2478 				availrmem -= pgcnt;
2479 				pages_useclaim += pgcnt;
2480 			} else {
2481 				VM_STAT_ADD(anonvmstats.privatepages[7]);
2482 				mutex_exit(&freemem_lock);
2483 				if (ahmpages != NULL) {
2484 					mutex_exit(ahmpages);
2485 				}
2486 				if (prealloc) {
2487 					page_free_replacement_page(pplist);
2488 					page_create_putback(pgcnt);
2489 				}
2490 				for (pg_idx = 0; pg_idx < pgcnt; pg_idx++)
2491 					if (ppa[pg_idx] != NULL)
2492 						page_unlock(ppa[pg_idx]);
2493 				return (ENOMEM);
2494 			}
2495 			mutex_exit(&freemem_lock);
2496 		}
2497 	}
2498 
2499 	CPU_STATS_ADD_K(vm, cow_fault, pgcnt);
2500 
2501 	VM_STAT_ADD(anonvmstats.privatepages[8]);
2502 
2503 	an_idx = start_idx;
2504 	pg_idx = 0;
2505 	vaddr = addr;
2506 	for (; pg_idx < pgcnt; pg_idx++, an_idx++, vaddr += PAGESIZE) {
2507 		ASSERT(ppa[pg_idx] != NULL);
2508 		oldap = anon_get_ptr(amp->ahp, an_idx);
2509 		ASSERT(ahmpages != NULL || oldap == NULL);
2510 		ASSERT(ahmpages == NULL || oldap != NULL);
2511 		ASSERT(ahmpages == NULL || oldap->an_refcnt > 1);
2512 		ASSERT(ahmpages == NULL || pg_idx != 0 ||
2513 		    (refcnt = oldap->an_refcnt));
2514 		ASSERT(ahmpages == NULL || pg_idx == 0 ||
2515 		    refcnt == oldap->an_refcnt);
2516 
2517 		ap = anon_alloc(NULL, 0);
2518 
2519 		swap_xlate(ap, &vp, &off);
2520 
2521 		/*
2522 		 * Now setup our preallocated page to pass down to
2523 		 * swap_getpage().
2524 		 */
2525 		if (prealloc) {
2526 			pp = pplist;
2527 			page_sub(&pplist, pp);
2528 			conpp = pp;
2529 		}
2530 
2531 		err = swap_getconpage(vp, (u_offset_t)off, PAGESIZE, NULL, pl,
2532 			PAGESIZE, conpp, NULL, &nreloc, seg, vaddr,
2533 			S_CREATE, cred);
2534 
2535 		/*
2536 		 * Impossible to fail this is S_CREATE.
2537 		 */
2538 		if (err)
2539 			panic("anon_map_privatepages: VOP_GETPAGE failed");
2540 
2541 		ASSERT(prealloc ? pp == pl[0] : pl[0]->p_szc == 0);
2542 		ASSERT(prealloc == 0 || nreloc == 1);
2543 
2544 		pp = pl[0];
2545 
2546 		/*
2547 		 * If the original page was locked, we need to move
2548 		 * the lock to the new page by transfering
2549 		 * 'cowcnt/lckcnt' of the original page to 'cowcnt/lckcnt'
2550 		 * of the new page. pg_idx can be used to index
2551 		 * into the vpage array since the caller will guarentee
2552 		 * that vpage struct passed in corresponds to addr
2553 		 * and forward.
2554 		 */
2555 		if (vpage != NULL && VPP_ISPPLOCK(&vpage[pg_idx])) {
2556 			page_pp_useclaim(ppa[pg_idx], pp, prot & PROT_WRITE);
2557 		} else if (pagelock) {
2558 			mutex_enter(&freemem_lock);
2559 			availrmem++;
2560 			pages_useclaim--;
2561 			mutex_exit(&freemem_lock);
2562 		}
2563 
2564 		/*
2565 		 * Now copy the contents from the original page.
2566 		 */
2567 		if (ppcopy(ppa[pg_idx], pp) == 0) {
2568 			/*
2569 			 * Before ppcopy could hanlde UE or other faults, we
2570 			 * would have panicked here, and still have no option
2571 			 * but to do so now.
2572 			 */
2573 			panic("anon_map_privatepages, ppcopy failed");
2574 		}
2575 
2576 		hat_setrefmod(pp);		/* mark as modified */
2577 
2578 		/*
2579 		 * Release the lock on the original page,
2580 		 * derement the old slot, and down grade the lock
2581 		 * on the new copy.
2582 		 */
2583 		page_unlock(ppa[pg_idx]);
2584 
2585 		if (!prealloc)
2586 			page_downgrade(pp);
2587 
2588 		ppa[pg_idx] = pp;
2589 
2590 		/*
2591 		 * Now reflect the copy in the new anon array.
2592 		 */
2593 		ASSERT(ahmpages == NULL || oldap->an_refcnt > 1);
2594 		if (oldap != NULL)
2595 			anon_decref(oldap);
2596 		(void) anon_set_ptr(amp->ahp, an_idx, ap, ANON_SLEEP);
2597 	}
2598 	if (ahmpages != NULL) {
2599 		mutex_exit(ahmpages);
2600 	}
2601 	ASSERT(prealloc == 0 || pplist == NULL);
2602 	if (prealloc) {
2603 		VM_STAT_ADD(anonvmstats.privatepages[9]);
2604 		for (pg_idx = 0; pg_idx < pgcnt; pg_idx++) {
2605 			page_downgrade(ppa[pg_idx]);
2606 		}
2607 	}
2608 
2609 	/*
2610 	 * Unload the old large page translation.
2611 	 */
2612 	hat_unload(seg->s_as->a_hat, addr, pgcnt << PAGESHIFT, HAT_UNLOAD);
2613 	return (0);
2614 }
2615 
2616 /*
2617  * Allocate a private zero-filled anon page.
2618  */
2619 page_t *
2620 anon_zero(struct seg *seg, caddr_t addr, struct anon **app, struct cred *cred)
2621 {
2622 	struct anon *ap;
2623 	page_t *pp;
2624 	struct vnode *vp;
2625 	anoff_t off;
2626 	page_t *anon_pl[1 + 1];
2627 	int err;
2628 
2629 	/* Kernel probe */
2630 	TNF_PROBE_1(anon_zero, "vm pagefault", /* CSTYLED */,
2631 		tnf_opaque,	address,	addr);
2632 
2633 	*app = ap = anon_alloc(NULL, 0);
2634 	swap_xlate(ap, &vp, &off);
2635 
2636 	/*
2637 	 * Call the VOP_GETPAGE routine to create the page, thereby
2638 	 * enabling the vnode driver to allocate any filesystem
2639 	 * dependent structures (e.g., disk block allocation for UFS).
2640 	 * This also prevents more than on page from being added to
2641 	 * the vnode at the same time since it is locked.
2642 	 */
2643 	err = VOP_GETPAGE(vp, off, PAGESIZE, NULL,
2644 	    anon_pl, PAGESIZE, seg, addr, S_CREATE, cred, NULL);
2645 	if (err) {
2646 		*app = NULL;
2647 		anon_decref(ap);
2648 		return (NULL);
2649 	}
2650 	pp = anon_pl[0];
2651 
2652 	pagezero(pp, 0, PAGESIZE);	/* XXX - should set mod bit */
2653 	page_downgrade(pp);
2654 	CPU_STATS_ADD_K(vm, zfod, 1);
2655 	hat_setrefmod(pp);	/* mark as modified so pageout writes back */
2656 	return (pp);
2657 }
2658 
2659 
2660 /*
2661  * Allocate array of private zero-filled anon pages for empty slots
2662  * and kept pages for non empty slots within given range.
2663  *
2664  * NOTE: This rontine will try and use large pages
2665  *	if available and supported by underlying platform.
2666  */
2667 int
2668 anon_map_createpages(
2669 	struct anon_map *amp,
2670 	ulong_t start_index,
2671 	size_t len,
2672 	page_t *ppa[],
2673 	struct seg *seg,
2674 	caddr_t addr,
2675 	enum seg_rw rw,
2676 	struct cred *cred)
2677 {
2678 
2679 	struct anon	*ap;
2680 	struct vnode	*ap_vp;
2681 	page_t		*pp, *pplist, *anon_pl[1 + 1], *conpp = NULL;
2682 	int		err = 0;
2683 	ulong_t		p_index, index;
2684 	pgcnt_t		npgs, pg_cnt;
2685 	spgcnt_t	nreloc = 0;
2686 	uint_t		l_szc, szc, prot;
2687 	anoff_t		ap_off;
2688 	size_t		pgsz;
2689 	lgrp_t		*lgrp;
2690 	kmutex_t	*ahm;
2691 
2692 	/*
2693 	 * XXX For now only handle S_CREATE.
2694 	 */
2695 	ASSERT(rw == S_CREATE);
2696 
2697 	index	= start_index;
2698 	p_index	= 0;
2699 	npgs = btopr(len);
2700 
2701 	/*
2702 	 * If this platform supports multiple page sizes
2703 	 * then try and allocate directly from the free
2704 	 * list for pages larger than PAGESIZE.
2705 	 *
2706 	 * NOTE:When we have page_create_ru we can stop
2707 	 *	directly allocating from the freelist.
2708 	 */
2709 	l_szc  = seg->s_szc;
2710 	ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
2711 	while (npgs) {
2712 
2713 		/*
2714 		 * if anon slot already exists
2715 		 *   (means page has been created)
2716 		 * so 1) look up the page
2717 		 *    2) if the page is still in memory, get it.
2718 		 *    3) if not, create a page and
2719 		 *	  page in from physical swap device.
2720 		 * These are done in anon_getpage().
2721 		 */
2722 		ap = anon_get_ptr(amp->ahp, index);
2723 		if (ap) {
2724 			err = anon_getpage(&ap, &prot, anon_pl, PAGESIZE,
2725 			    seg, addr, S_READ, cred);
2726 			if (err) {
2727 				ANON_LOCK_EXIT(&amp->a_rwlock);
2728 				panic("anon_map_createpages: anon_getpage");
2729 			}
2730 			pp = anon_pl[0];
2731 			ppa[p_index++] = pp;
2732 
2733 			/*
2734 			 * an_pvp can become non-NULL after SysV's page was
2735 			 * paged out before ISM was attached to this SysV
2736 			 * shared memory segment. So free swap slot if needed.
2737 			 */
2738 			if (ap->an_pvp != NULL) {
2739 				page_io_lock(pp);
2740 				ahm = &anonhash_lock[AH_LOCK(ap->an_vp,
2741 					ap->an_off)];
2742 				mutex_enter(ahm);
2743 				if (ap->an_pvp != NULL) {
2744 					swap_phys_free(ap->an_pvp,
2745 					    ap->an_poff, PAGESIZE);
2746 					ap->an_pvp = NULL;
2747 					ap->an_poff = 0;
2748 					mutex_exit(ahm);
2749 					hat_setmod(pp);
2750 				} else {
2751 					mutex_exit(ahm);
2752 				}
2753 				page_io_unlock(pp);
2754 			}
2755 
2756 			addr += PAGESIZE;
2757 			index++;
2758 			npgs--;
2759 			continue;
2760 		}
2761 		/*
2762 		 * Now try and allocate the largest page possible
2763 		 * for the current address and range.
2764 		 * Keep dropping down in page size until:
2765 		 *
2766 		 *	1) Properly aligned
2767 		 *	2) Does not overlap existing anon pages
2768 		 *	3) Fits in remaining range.
2769 		 *	4) able to allocate one.
2770 		 *
2771 		 * NOTE: XXX When page_create_ru is completed this code
2772 		 *	 will change.
2773 		 */
2774 		szc    = l_szc;
2775 		pplist = NULL;
2776 		pg_cnt = 0;
2777 		while (szc) {
2778 			pgsz	= page_get_pagesize(szc);
2779 			pg_cnt	= pgsz >> PAGESHIFT;
2780 			if (IS_P2ALIGNED(addr, pgsz) && pg_cnt <= npgs &&
2781 				anon_pages(amp->ahp, index, pg_cnt) == 0) {
2782 				/*
2783 				 * XXX
2784 				 * Since we are faking page_create()
2785 				 * we also need to do the freemem and
2786 				 * pcf accounting.
2787 				 */
2788 				(void) page_create_wait(pg_cnt, PG_WAIT);
2789 
2790 				/*
2791 				 * Get lgroup to allocate next page of shared
2792 				 * memory from and use it to specify where to
2793 				 * allocate the physical memory
2794 				 */
2795 				lgrp = lgrp_mem_choose(seg, addr, pgsz);
2796 
2797 				pplist = page_get_freelist(
2798 				    anon_vp, (u_offset_t)0, seg,
2799 				    addr, pgsz, 0, lgrp);
2800 
2801 				if (pplist == NULL) {
2802 					page_create_putback(pg_cnt);
2803 				}
2804 
2805 				/*
2806 				 * If a request for a page of size
2807 				 * larger than PAGESIZE failed
2808 				 * then don't try that size anymore.
2809 				 */
2810 				if (pplist == NULL) {
2811 					l_szc = szc - 1;
2812 				} else {
2813 					break;
2814 				}
2815 			}
2816 			szc--;
2817 		}
2818 
2819 		/*
2820 		 * If just using PAGESIZE pages then don't
2821 		 * directly allocate from the free list.
2822 		 */
2823 		if (pplist == NULL) {
2824 			ASSERT(szc == 0);
2825 			pp = anon_zero(seg, addr, &ap, cred);
2826 			if (pp == NULL) {
2827 				ANON_LOCK_EXIT(&amp->a_rwlock);
2828 				panic("anon_map_createpages: anon_zero");
2829 			}
2830 			ppa[p_index++] = pp;
2831 
2832 			ASSERT(anon_get_ptr(amp->ahp, index) == NULL);
2833 			(void) anon_set_ptr(amp->ahp, index, ap, ANON_SLEEP);
2834 
2835 			addr += PAGESIZE;
2836 			index++;
2837 			npgs--;
2838 			continue;
2839 		}
2840 
2841 		/*
2842 		 * pplist is a list of pg_cnt PAGESIZE pages.
2843 		 * These pages are locked SE_EXCL since they
2844 		 * came directly off the free list.
2845 		 */
2846 		ASSERT(IS_P2ALIGNED(pg_cnt, pg_cnt));
2847 		ASSERT(IS_P2ALIGNED(index, pg_cnt));
2848 		ASSERT(conpp == NULL);
2849 		while (pg_cnt--) {
2850 
2851 			ap = anon_alloc(NULL, 0);
2852 			swap_xlate(ap, &ap_vp, &ap_off);
2853 
2854 			ASSERT(pplist != NULL);
2855 			pp = pplist;
2856 			page_sub(&pplist, pp);
2857 			PP_CLRFREE(pp);
2858 			PP_CLRAGED(pp);
2859 			conpp = pp;
2860 
2861 			err = swap_getconpage(ap_vp, ap_off, PAGESIZE,
2862 			    (uint_t *)NULL, anon_pl, PAGESIZE, conpp, NULL,
2863 			    &nreloc, seg, addr, S_CREATE, cred);
2864 
2865 			if (err) {
2866 				ANON_LOCK_EXIT(&amp->a_rwlock);
2867 				panic("anon_map_createpages: S_CREATE");
2868 			}
2869 
2870 			ASSERT(anon_pl[0] == pp);
2871 			ASSERT(nreloc == 1);
2872 			pagezero(pp, 0, PAGESIZE);
2873 			CPU_STATS_ADD_K(vm, zfod, 1);
2874 			hat_setrefmod(pp);
2875 
2876 			ASSERT(anon_get_ptr(amp->ahp, index) == NULL);
2877 			(void) anon_set_ptr(amp->ahp, index, ap, ANON_SLEEP);
2878 
2879 			ppa[p_index++] = pp;
2880 
2881 			addr += PAGESIZE;
2882 			index++;
2883 			npgs--;
2884 		}
2885 		conpp = NULL;
2886 		pg_cnt	= pgsz >> PAGESHIFT;
2887 		p_index = p_index - pg_cnt;
2888 		while (pg_cnt--) {
2889 			page_downgrade(ppa[p_index++]);
2890 		}
2891 	}
2892 	ANON_LOCK_EXIT(&amp->a_rwlock);
2893 	return (0);
2894 }
2895 
2896 static int
2897 anon_try_demote_pages(
2898 	struct anon_hdr *ahp,
2899 	ulong_t sidx,
2900 	uint_t szc,
2901 	page_t **ppa,
2902 	int private)
2903 {
2904 	struct anon	*ap;
2905 	pgcnt_t		pgcnt = page_get_pagecnt(szc);
2906 	page_t		*pp;
2907 	pgcnt_t		i;
2908 	kmutex_t	*ahmpages = NULL;
2909 	int		root = 0;
2910 	pgcnt_t		npgs;
2911 	pgcnt_t		curnpgs = 0;
2912 	size_t		ppasize = 0;
2913 
2914 	ASSERT(szc != 0);
2915 	ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
2916 	ASSERT(IS_P2ALIGNED(sidx, pgcnt));
2917 	ASSERT(sidx < ahp->size);
2918 
2919 	if (ppa == NULL) {
2920 		ppasize = pgcnt * sizeof (page_t *);
2921 		ppa = kmem_alloc(ppasize, KM_SLEEP);
2922 	}
2923 
2924 	ap = anon_get_ptr(ahp, sidx);
2925 	if (ap != NULL && private) {
2926 		VM_STAT_ADD(anonvmstats.demotepages[1]);
2927 		ahmpages = &anonpages_hash_lock[AH_LOCK(ap->an_vp, ap->an_off)];
2928 		mutex_enter(ahmpages);
2929 	}
2930 
2931 	if (ap != NULL && ap->an_refcnt > 1) {
2932 		if (ahmpages != NULL) {
2933 			VM_STAT_ADD(anonvmstats.demotepages[2]);
2934 			mutex_exit(ahmpages);
2935 		}
2936 		if (ppasize != 0) {
2937 			kmem_free(ppa, ppasize);
2938 		}
2939 		return (0);
2940 	}
2941 	if (ahmpages != NULL) {
2942 		mutex_exit(ahmpages);
2943 	}
2944 	if (ahp->size - sidx < pgcnt) {
2945 		ASSERT(private == 0);
2946 		pgcnt = ahp->size - sidx;
2947 	}
2948 	for (i = 0; i < pgcnt; i++, sidx++) {
2949 		ap = anon_get_ptr(ahp, sidx);
2950 		if (ap != NULL) {
2951 			if (ap->an_refcnt != 1) {
2952 				panic("anon_try_demote_pages: an_refcnt != 1");
2953 			}
2954 			pp = ppa[i] = page_lookup(ap->an_vp, ap->an_off,
2955 				SE_EXCL);
2956 			if (pp != NULL) {
2957 				(void) hat_pageunload(pp,
2958 					HAT_FORCE_PGUNLOAD);
2959 			}
2960 		} else {
2961 			ppa[i] = NULL;
2962 		}
2963 	}
2964 	for (i = 0; i < pgcnt; i++) {
2965 		if ((pp = ppa[i]) != NULL && pp->p_szc != 0) {
2966 			ASSERT(pp->p_szc <= szc);
2967 			if (!root) {
2968 				VM_STAT_ADD(anonvmstats.demotepages[3]);
2969 				if (curnpgs != 0)
2970 					panic("anon_try_demote_pages: "
2971 						"bad large page");
2972 
2973 				root = 1;
2974 				curnpgs = npgs =
2975 					page_get_pagecnt(pp->p_szc);
2976 
2977 				ASSERT(npgs <= pgcnt);
2978 				ASSERT(IS_P2ALIGNED(npgs, npgs));
2979 				ASSERT(!(page_pptonum(pp) &
2980 					(npgs - 1)));
2981 			} else {
2982 				ASSERT(i > 0);
2983 				ASSERT(page_pptonum(pp) - 1 ==
2984 					page_pptonum(ppa[i - 1]));
2985 				if ((page_pptonum(pp) & (npgs - 1)) ==
2986 					npgs - 1)
2987 					root = 0;
2988 			}
2989 			ASSERT(PAGE_EXCL(pp));
2990 			pp->p_szc = 0;
2991 			ASSERT(curnpgs > 0);
2992 			curnpgs--;
2993 		}
2994 	}
2995 	if (root != 0 || curnpgs != 0)
2996 		panic("anon_try_demote_pages: bad large page");
2997 
2998 	for (i = 0; i < pgcnt; i++) {
2999 		if ((pp = ppa[i]) != NULL) {
3000 			ASSERT(!hat_page_is_mapped(pp));
3001 			ASSERT(pp->p_szc == 0);
3002 			page_unlock(pp);
3003 		}
3004 	}
3005 	if (ppasize != 0) {
3006 		kmem_free(ppa, ppasize);
3007 	}
3008 	return (1);
3009 }
3010 
3011 /*
3012  * anon_map_demotepages() can only be called by MAP_PRIVATE segments.
3013  */
3014 int
3015 anon_map_demotepages(
3016 	struct anon_map *amp,
3017 	ulong_t	start_idx,
3018 	struct seg *seg,
3019 	caddr_t addr,
3020 	uint_t prot,
3021 	struct vpage vpage[],
3022 	struct cred *cred)
3023 {
3024 	struct anon	*ap;
3025 	uint_t		szc = seg->s_szc;
3026 	pgcnt_t		pgcnt = page_get_pagecnt(szc);
3027 	size_t		ppasize = pgcnt * sizeof (page_t *);
3028 	page_t		**ppa = kmem_alloc(ppasize, KM_SLEEP);
3029 	page_t		*pp;
3030 	page_t		*pl[2];
3031 	pgcnt_t		i, pg_idx;
3032 	ulong_t		an_idx;
3033 	caddr_t		vaddr;
3034 	int 		err;
3035 	int		retry = 0;
3036 	uint_t		vpprot;
3037 
3038 	ASSERT(RW_WRITE_HELD(&amp->a_rwlock));
3039 	ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
3040 	ASSERT(IS_P2ALIGNED(start_idx, pgcnt));
3041 	ASSERT(ppa != NULL);
3042 	ASSERT(szc != 0);
3043 	ASSERT(szc == amp->a_szc);
3044 
3045 	VM_STAT_ADD(anonvmstats.demotepages[0]);
3046 
3047 top:
3048 	if (anon_try_demote_pages(amp->ahp, start_idx, szc, ppa, 1)) {
3049 		kmem_free(ppa, ppasize);
3050 		return (0);
3051 	}
3052 
3053 	VM_STAT_ADD(anonvmstats.demotepages[4]);
3054 
3055 	ASSERT(retry == 0); /* we can be here only once */
3056 
3057 	vaddr = addr;
3058 	for (pg_idx = 0, an_idx = start_idx; pg_idx < pgcnt;
3059 	    pg_idx++, an_idx++, vaddr += PAGESIZE) {
3060 		ap = anon_get_ptr(amp->ahp, an_idx);
3061 		if (ap == NULL)
3062 			panic("anon_map_demotepages: no anon slot");
3063 		err = anon_getpage(&ap, &vpprot, pl, PAGESIZE, seg, vaddr,
3064 		    S_READ, cred);
3065 		if (err) {
3066 			for (i = 0; i < pg_idx; i++) {
3067 				if ((pp = ppa[i]) != NULL)
3068 					page_unlock(pp);
3069 			}
3070 			kmem_free(ppa, ppasize);
3071 			return (err);
3072 		}
3073 		ppa[pg_idx] = pl[0];
3074 	}
3075 
3076 	err = anon_map_privatepages(amp, start_idx, szc, seg, addr, prot, ppa,
3077 	    vpage, -1, 0, cred);
3078 	if (err > 0) {
3079 		VM_STAT_ADD(anonvmstats.demotepages[5]);
3080 		kmem_free(ppa, ppasize);
3081 		return (err);
3082 	}
3083 	ASSERT(err == 0 || err == -1);
3084 	if (err == -1) {
3085 		VM_STAT_ADD(anonvmstats.demotepages[6]);
3086 		retry = 1;
3087 		goto top;
3088 	}
3089 	for (i = 0; i < pgcnt; i++) {
3090 		ASSERT(ppa[i] != NULL);
3091 		if (ppa[i]->p_szc != 0)
3092 			retry = 1;
3093 		page_unlock(ppa[i]);
3094 	}
3095 	if (retry) {
3096 		VM_STAT_ADD(anonvmstats.demotepages[7]);
3097 		goto top;
3098 	}
3099 
3100 	VM_STAT_ADD(anonvmstats.demotepages[8]);
3101 
3102 	kmem_free(ppa, ppasize);
3103 
3104 	return (0);
3105 }
3106 
3107 /*
3108  * Free pages of shared anon map. It's assumed that anon maps don't share anon
3109  * structures with private anon maps. Therefore all anon structures should
3110  * have at most one reference at this point. This means underlying pages can
3111  * be exclusively locked and demoted or freed.  If not freeing the entire
3112  * large pages demote the ends of the region we free to be able to free
3113  * subpages. Page roots correspond to aligned index positions in anon map.
3114  */
3115 void
3116 anon_shmap_free_pages(struct anon_map *amp, ulong_t sidx, size_t len)
3117 {
3118 	ulong_t eidx = sidx + btopr(len);
3119 	pgcnt_t pages = page_get_pagecnt(amp->a_szc);
3120 	struct anon_hdr *ahp = amp->ahp;
3121 	ulong_t tidx;
3122 	size_t size;
3123 	ulong_t sidx_aligned;
3124 	ulong_t eidx_aligned;
3125 
3126 	ASSERT(RW_WRITE_HELD(&amp->a_rwlock));
3127 	ASSERT(amp->refcnt <= 1);
3128 	ASSERT(amp->a_szc > 0);
3129 	ASSERT(eidx <= ahp->size);
3130 	ASSERT(!anon_share(ahp, sidx, btopr(len)));
3131 
3132 	if (len == 0) {	/* XXX */
3133 		return;
3134 	}
3135 
3136 	sidx_aligned = P2ALIGN(sidx, pages);
3137 	if (sidx_aligned != sidx ||
3138 	    (eidx < sidx_aligned + pages && eidx < ahp->size)) {
3139 		if (!anon_try_demote_pages(ahp, sidx_aligned,
3140 		    amp->a_szc, NULL, 0)) {
3141 			panic("anon_shmap_free_pages: demote failed");
3142 		}
3143 		size = (eidx <= sidx_aligned + pages) ? (eidx - sidx) :
3144 		    P2NPHASE(sidx, pages);
3145 		size <<= PAGESHIFT;
3146 		anon_free(ahp, sidx, size);
3147 		sidx = sidx_aligned + pages;
3148 		if (eidx <= sidx) {
3149 			return;
3150 		}
3151 	}
3152 	eidx_aligned = P2ALIGN(eidx, pages);
3153 	if (sidx < eidx_aligned) {
3154 		anon_free_pages(ahp, sidx,
3155 		    (eidx_aligned - sidx) << PAGESHIFT,
3156 		    amp->a_szc);
3157 		sidx = eidx_aligned;
3158 	}
3159 	ASSERT(sidx == eidx_aligned);
3160 	if (eidx == eidx_aligned) {
3161 		return;
3162 	}
3163 	tidx = eidx;
3164 	if (eidx != ahp->size && anon_get_next_ptr(ahp, &tidx) != NULL &&
3165 	    tidx - sidx < pages) {
3166 		if (!anon_try_demote_pages(ahp, sidx, amp->a_szc, NULL, 0)) {
3167 			panic("anon_shmap_free_pages: demote failed");
3168 		}
3169 		size = (eidx - sidx) << PAGESHIFT;
3170 		anon_free(ahp, sidx, size);
3171 	} else {
3172 		anon_free_pages(ahp, sidx, pages << PAGESHIFT, amp->a_szc);
3173 	}
3174 }
3175 
3176 /*
3177  * Allocate and initialize an anon_map structure for seg
3178  * associating the given swap reservation with the new anon_map.
3179  */
3180 struct anon_map *
3181 anonmap_alloc(size_t size, size_t swresv, int flags)
3182 {
3183 	struct anon_map *amp;
3184 	int kmflags = (flags & ANON_NOSLEEP) ? KM_NOSLEEP : KM_SLEEP;
3185 
3186 	amp = kmem_cache_alloc(anonmap_cache, kmflags);
3187 	if (amp == NULL) {
3188 		ASSERT(kmflags == KM_NOSLEEP);
3189 		return (NULL);
3190 	}
3191 
3192 	amp->ahp = anon_create(btopr(size), flags);
3193 	if (amp->ahp == NULL) {
3194 		ASSERT(flags == ANON_NOSLEEP);
3195 		kmem_cache_free(anonmap_cache, amp);
3196 		return (NULL);
3197 	}
3198 	amp->refcnt = 1;
3199 	amp->size = size;
3200 	amp->swresv = swresv;
3201 	amp->locality = 0;
3202 	amp->a_szc = 0;
3203 	amp->a_sp = NULL;
3204 	return (amp);
3205 }
3206 
3207 void
3208 anonmap_free(struct anon_map *amp)
3209 {
3210 	ASSERT(amp->ahp);
3211 	ASSERT(amp->refcnt == 0);
3212 
3213 	lgrp_shm_policy_fini(amp, NULL);
3214 	anon_release(amp->ahp, btopr(amp->size));
3215 	kmem_cache_free(anonmap_cache, amp);
3216 }
3217 
3218 /*
3219  * Returns true if the app array has some empty slots.
3220  * The offp and lenp parameters are in/out parameters.  On entry
3221  * these values represent the starting offset and length of the
3222  * mapping.  When true is returned, these values may be modified
3223  * to be the largest range which includes empty slots.
3224  */
3225 int
3226 non_anon(struct anon_hdr *ahp, ulong_t anon_idx, u_offset_t *offp,
3227 				size_t *lenp)
3228 {
3229 	ulong_t i, el;
3230 	ssize_t low, high;
3231 	struct anon *ap;
3232 
3233 	low = -1;
3234 	for (i = 0, el = *lenp; i < el; i += PAGESIZE, anon_idx++) {
3235 		ap = anon_get_ptr(ahp, anon_idx);
3236 		if (ap == NULL) {
3237 			if (low == -1)
3238 				low = i;
3239 			high = i;
3240 		}
3241 	}
3242 	if (low != -1) {
3243 		/*
3244 		 * Found at least one non-anon page.
3245 		 * Set up the off and len return values.
3246 		 */
3247 		if (low != 0)
3248 			*offp += low;
3249 		*lenp = high - low + PAGESIZE;
3250 		return (1);
3251 	}
3252 	return (0);
3253 }
3254 
3255 /*
3256  * Return a count of the number of existing anon pages in the anon array
3257  * app in the range (off, off+len). The array and slots must be guaranteed
3258  * stable by the caller.
3259  */
3260 pgcnt_t
3261 anon_pages(struct anon_hdr *ahp, ulong_t anon_index, pgcnt_t nslots)
3262 {
3263 	pgcnt_t cnt = 0;
3264 
3265 	while (nslots-- > 0) {
3266 		if ((anon_get_ptr(ahp, anon_index)) != NULL)
3267 			cnt++;
3268 		anon_index++;
3269 	}
3270 	return (cnt);
3271 }
3272 
3273 /*
3274  * Move reserved phys swap into memory swap (unreserve phys swap
3275  * and reserve mem swap by the same amount).
3276  * Used by segspt when it needs to lock reserved swap npages in memory
3277  */
3278 int
3279 anon_swap_adjust(pgcnt_t npages)
3280 {
3281 	pgcnt_t unlocked_mem_swap;
3282 
3283 	mutex_enter(&anoninfo_lock);
3284 
3285 	ASSERT(k_anoninfo.ani_mem_resv >= k_anoninfo.ani_locked_swap);
3286 	ASSERT(k_anoninfo.ani_max >= k_anoninfo.ani_phys_resv);
3287 
3288 	unlocked_mem_swap = k_anoninfo.ani_mem_resv
3289 					- k_anoninfo.ani_locked_swap;
3290 	if (npages > unlocked_mem_swap) {
3291 		spgcnt_t adjusted_swap = npages - unlocked_mem_swap;
3292 
3293 		/*
3294 		 * if there is not enough unlocked mem swap we take missing
3295 		 * amount from phys swap and give it to mem swap
3296 		 */
3297 		if (!page_reclaim_mem(adjusted_swap, segspt_minfree, 1)) {
3298 			mutex_exit(&anoninfo_lock);
3299 			return (ENOMEM);
3300 		}
3301 
3302 		k_anoninfo.ani_mem_resv += adjusted_swap;
3303 		ASSERT(k_anoninfo.ani_phys_resv >= adjusted_swap);
3304 		k_anoninfo.ani_phys_resv -= adjusted_swap;
3305 
3306 		ANI_ADD(adjusted_swap);
3307 	}
3308 	k_anoninfo.ani_locked_swap += npages;
3309 
3310 	ASSERT(k_anoninfo.ani_mem_resv >= k_anoninfo.ani_locked_swap);
3311 	ASSERT(k_anoninfo.ani_max >= k_anoninfo.ani_phys_resv);
3312 
3313 	mutex_exit(&anoninfo_lock);
3314 
3315 	return (0);
3316 }
3317 
3318 /*
3319  * 'unlocked' reserved mem swap so when it is unreserved it
3320  * can be moved back phys (disk) swap
3321  */
3322 void
3323 anon_swap_restore(pgcnt_t npages)
3324 {
3325 	mutex_enter(&anoninfo_lock);
3326 
3327 	ASSERT(k_anoninfo.ani_locked_swap <= k_anoninfo.ani_mem_resv);
3328 
3329 	ASSERT(k_anoninfo.ani_locked_swap >= npages);
3330 	k_anoninfo.ani_locked_swap -= npages;
3331 
3332 	ASSERT(k_anoninfo.ani_locked_swap <= k_anoninfo.ani_mem_resv);
3333 
3334 	mutex_exit(&anoninfo_lock);
3335 }
3336 
3337 /*
3338  * Return the pointer from the list for a
3339  * specified anon index.
3340  */
3341 ulong_t *
3342 anon_get_slot(struct anon_hdr *ahp, ulong_t an_idx)
3343 {
3344 	struct anon	**app;
3345 	void 		**ppp;
3346 
3347 	ASSERT(an_idx < ahp->size);
3348 
3349 	/*
3350 	 * Single level case.
3351 	 */
3352 	if ((ahp->size <= ANON_CHUNK_SIZE) || (ahp->flags & ANON_ALLOC_FORCE)) {
3353 		return ((ulong_t *)&ahp->array_chunk[an_idx]);
3354 	} else {
3355 
3356 		/*
3357 		 * 2 level case.
3358 		 */
3359 		ppp = &ahp->array_chunk[an_idx >> ANON_CHUNK_SHIFT];
3360 		if (*ppp == NULL) {
3361 			mutex_enter(&ahp->serial_lock);
3362 			ppp = &ahp->array_chunk[an_idx >> ANON_CHUNK_SHIFT];
3363 			if (*ppp == NULL)
3364 				*ppp = kmem_zalloc(PAGESIZE, KM_SLEEP);
3365 			mutex_exit(&ahp->serial_lock);
3366 		}
3367 		app = *ppp;
3368 		return ((ulong_t *)&app[an_idx & ANON_CHUNK_OFF]);
3369 	}
3370 }
3371 
3372 void
3373 anon_array_enter(struct anon_map *amp, ulong_t an_idx, anon_sync_obj_t *sobj)
3374 {
3375 	ulong_t		*ap_slot;
3376 	kmutex_t	*mtx;
3377 	kcondvar_t	*cv;
3378 	int		hash;
3379 
3380 	/*
3381 	 * Use szc to determine anon slot(s) to appear atomic.
3382 	 * If szc = 0, then lock the anon slot and mark it busy.
3383 	 * If szc > 0, then lock the range of slots by getting the
3384 	 * anon_array_lock for the first anon slot, and mark only the
3385 	 * first anon slot busy to represent whole range being busy.
3386 	 */
3387 
3388 	ASSERT(RW_READ_HELD(&amp->a_rwlock));
3389 	an_idx = P2ALIGN(an_idx, page_get_pagecnt(amp->a_szc));
3390 	hash = ANON_ARRAY_HASH(amp, an_idx);
3391 	sobj->sync_mutex = mtx = &anon_array_lock[hash].pad_mutex;
3392 	sobj->sync_cv = cv = &anon_array_cv[hash];
3393 	mutex_enter(mtx);
3394 	ap_slot = anon_get_slot(amp->ahp, an_idx);
3395 	while (ANON_ISBUSY(ap_slot))
3396 		cv_wait(cv, mtx);
3397 	ANON_SETBUSY(ap_slot);
3398 	sobj->sync_data = ap_slot;
3399 	mutex_exit(mtx);
3400 }
3401 
3402 int
3403 anon_array_try_enter(struct anon_map *amp, ulong_t an_idx,
3404 			anon_sync_obj_t *sobj)
3405 {
3406 	ulong_t		*ap_slot;
3407 	kmutex_t	*mtx;
3408 	int		hash;
3409 
3410 	/*
3411 	 * Try to lock a range of anon slots.
3412 	 * Use szc to determine anon slot(s) to appear atomic.
3413 	 * If szc = 0, then lock the anon slot and mark it busy.
3414 	 * If szc > 0, then lock the range of slots by getting the
3415 	 * anon_array_lock for the first anon slot, and mark only the
3416 	 * first anon slot busy to represent whole range being busy.
3417 	 * Fail if the mutex or the anon_array are busy.
3418 	 */
3419 
3420 	ASSERT(RW_READ_HELD(&amp->a_rwlock));
3421 	an_idx = P2ALIGN(an_idx, page_get_pagecnt(amp->a_szc));
3422 	hash = ANON_ARRAY_HASH(amp, an_idx);
3423 	sobj->sync_mutex = mtx = &anon_array_lock[hash].pad_mutex;
3424 	sobj->sync_cv = &anon_array_cv[hash];
3425 	if (!mutex_tryenter(mtx)) {
3426 		return (EWOULDBLOCK);
3427 	}
3428 	ap_slot = anon_get_slot(amp->ahp, an_idx);
3429 	if (ANON_ISBUSY(ap_slot)) {
3430 		mutex_exit(mtx);
3431 		return (EWOULDBLOCK);
3432 	}
3433 	ANON_SETBUSY(ap_slot);
3434 	sobj->sync_data = ap_slot;
3435 	mutex_exit(mtx);
3436 	return (0);
3437 }
3438 
3439 void
3440 anon_array_exit(anon_sync_obj_t *sobj)
3441 {
3442 	mutex_enter(sobj->sync_mutex);
3443 	ASSERT(ANON_ISBUSY(sobj->sync_data));
3444 	ANON_CLRBUSY(sobj->sync_data);
3445 	if (CV_HAS_WAITERS(sobj->sync_cv))
3446 		cv_broadcast(sobj->sync_cv);
3447 	mutex_exit(sobj->sync_mutex);
3448 }
3449