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