xref: /titanic_52/usr/src/uts/common/vm/seg_vn.c (revision 9469b38fa64cb68eac7cc7f4b7595b0de1fb77d6)
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 2010 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 /*
40  * VM - shared or copy-on-write from a vnode/anonymous memory.
41  */
42 
43 #include <sys/types.h>
44 #include <sys/param.h>
45 #include <sys/t_lock.h>
46 #include <sys/errno.h>
47 #include <sys/systm.h>
48 #include <sys/mman.h>
49 #include <sys/debug.h>
50 #include <sys/cred.h>
51 #include <sys/vmsystm.h>
52 #include <sys/tuneable.h>
53 #include <sys/bitmap.h>
54 #include <sys/swap.h>
55 #include <sys/kmem.h>
56 #include <sys/sysmacros.h>
57 #include <sys/vtrace.h>
58 #include <sys/cmn_err.h>
59 #include <sys/callb.h>
60 #include <sys/vm.h>
61 #include <sys/dumphdr.h>
62 #include <sys/lgrp.h>
63 
64 #include <vm/hat.h>
65 #include <vm/as.h>
66 #include <vm/seg.h>
67 #include <vm/seg_vn.h>
68 #include <vm/pvn.h>
69 #include <vm/anon.h>
70 #include <vm/page.h>
71 #include <vm/vpage.h>
72 #include <sys/proc.h>
73 #include <sys/task.h>
74 #include <sys/project.h>
75 #include <sys/zone.h>
76 #include <sys/shm_impl.h>
77 /*
78  * Private seg op routines.
79  */
80 static int	segvn_dup(struct seg *seg, struct seg *newseg);
81 static int	segvn_unmap(struct seg *seg, caddr_t addr, size_t len);
82 static void	segvn_free(struct seg *seg);
83 static faultcode_t segvn_fault(struct hat *hat, struct seg *seg,
84 		    caddr_t addr, size_t len, enum fault_type type,
85 		    enum seg_rw rw);
86 static faultcode_t segvn_faulta(struct seg *seg, caddr_t addr);
87 static int	segvn_setprot(struct seg *seg, caddr_t addr,
88 		    size_t len, uint_t prot);
89 static int	segvn_checkprot(struct seg *seg, caddr_t addr,
90 		    size_t len, uint_t prot);
91 static int	segvn_kluster(struct seg *seg, caddr_t addr, ssize_t delta);
92 static size_t	segvn_swapout(struct seg *seg);
93 static int	segvn_sync(struct seg *seg, caddr_t addr, size_t len,
94 		    int attr, uint_t flags);
95 static size_t	segvn_incore(struct seg *seg, caddr_t addr, size_t len,
96 		    char *vec);
97 static int	segvn_lockop(struct seg *seg, caddr_t addr, size_t len,
98 		    int attr, int op, ulong_t *lockmap, size_t pos);
99 static int	segvn_getprot(struct seg *seg, caddr_t addr, size_t len,
100 		    uint_t *protv);
101 static u_offset_t	segvn_getoffset(struct seg *seg, caddr_t addr);
102 static int	segvn_gettype(struct seg *seg, caddr_t addr);
103 static int	segvn_getvp(struct seg *seg, caddr_t addr,
104 		    struct vnode **vpp);
105 static int	segvn_advise(struct seg *seg, caddr_t addr, size_t len,
106 		    uint_t behav);
107 static void	segvn_dump(struct seg *seg);
108 static int	segvn_pagelock(struct seg *seg, caddr_t addr, size_t len,
109 		    struct page ***ppp, enum lock_type type, enum seg_rw rw);
110 static int	segvn_setpagesize(struct seg *seg, caddr_t addr, size_t len,
111 		    uint_t szc);
112 static int	segvn_getmemid(struct seg *seg, caddr_t addr,
113 		    memid_t *memidp);
114 static lgrp_mem_policy_info_t	*segvn_getpolicy(struct seg *, caddr_t);
115 static int	segvn_capable(struct seg *seg, segcapability_t capable);
116 
117 struct	seg_ops segvn_ops = {
118 	segvn_dup,
119 	segvn_unmap,
120 	segvn_free,
121 	segvn_fault,
122 	segvn_faulta,
123 	segvn_setprot,
124 	segvn_checkprot,
125 	segvn_kluster,
126 	segvn_swapout,
127 	segvn_sync,
128 	segvn_incore,
129 	segvn_lockop,
130 	segvn_getprot,
131 	segvn_getoffset,
132 	segvn_gettype,
133 	segvn_getvp,
134 	segvn_advise,
135 	segvn_dump,
136 	segvn_pagelock,
137 	segvn_setpagesize,
138 	segvn_getmemid,
139 	segvn_getpolicy,
140 	segvn_capable,
141 };
142 
143 /*
144  * Common zfod structures, provided as a shorthand for others to use.
145  */
146 static segvn_crargs_t zfod_segvn_crargs =
147 	SEGVN_ZFOD_ARGS(PROT_ZFOD, PROT_ALL);
148 static segvn_crargs_t kzfod_segvn_crargs =
149 	SEGVN_ZFOD_ARGS(PROT_ZFOD & ~PROT_USER,
150 	PROT_ALL & ~PROT_USER);
151 static segvn_crargs_t stack_noexec_crargs =
152 	SEGVN_ZFOD_ARGS(PROT_ZFOD & ~PROT_EXEC, PROT_ALL);
153 
154 caddr_t	zfod_argsp = (caddr_t)&zfod_segvn_crargs;	/* user zfod argsp */
155 caddr_t	kzfod_argsp = (caddr_t)&kzfod_segvn_crargs;	/* kernel zfod argsp */
156 caddr_t	stack_exec_argsp = (caddr_t)&zfod_segvn_crargs;	/* executable stack */
157 caddr_t	stack_noexec_argsp = (caddr_t)&stack_noexec_crargs; /* noexec stack */
158 
159 #define	vpgtob(n)	((n) * sizeof (struct vpage))	/* For brevity */
160 
161 size_t	segvn_comb_thrshld = UINT_MAX;	/* patchable -- see 1196681 */
162 
163 size_t	segvn_pglock_comb_thrshld = (1UL << 16);	/* 64K */
164 size_t	segvn_pglock_comb_balign = (1UL << 16);		/* 64K */
165 uint_t	segvn_pglock_comb_bshift;
166 size_t	segvn_pglock_comb_palign;
167 
168 static int	segvn_concat(struct seg *, struct seg *, int);
169 static int	segvn_extend_prev(struct seg *, struct seg *,
170 		    struct segvn_crargs *, size_t);
171 static int	segvn_extend_next(struct seg *, struct seg *,
172 		    struct segvn_crargs *, size_t);
173 static void	segvn_softunlock(struct seg *, caddr_t, size_t, enum seg_rw);
174 static void	segvn_pagelist_rele(page_t **);
175 static void	segvn_setvnode_mpss(vnode_t *);
176 static void	segvn_relocate_pages(page_t **, page_t *);
177 static int	segvn_full_szcpages(page_t **, uint_t, int *, uint_t *);
178 static int	segvn_fill_vp_pages(struct segvn_data *, vnode_t *, u_offset_t,
179     uint_t, page_t **, page_t **, uint_t *, int *);
180 static faultcode_t segvn_fault_vnodepages(struct hat *, struct seg *, caddr_t,
181     caddr_t, enum fault_type, enum seg_rw, caddr_t, caddr_t, int);
182 static faultcode_t segvn_fault_anonpages(struct hat *, struct seg *, caddr_t,
183     caddr_t, enum fault_type, enum seg_rw, caddr_t, caddr_t, int);
184 static faultcode_t segvn_faultpage(struct hat *, struct seg *, caddr_t,
185     u_offset_t, struct vpage *, page_t **, uint_t,
186     enum fault_type, enum seg_rw, int);
187 static void	segvn_vpage(struct seg *);
188 static size_t	segvn_count_swap_by_vpages(struct seg *);
189 
190 static void segvn_purge(struct seg *seg);
191 static int segvn_reclaim(void *, caddr_t, size_t, struct page **,
192     enum seg_rw, int);
193 static int shamp_reclaim(void *, caddr_t, size_t, struct page **,
194     enum seg_rw, int);
195 
196 static int sameprot(struct seg *, caddr_t, size_t);
197 
198 static int segvn_demote_range(struct seg *, caddr_t, size_t, int, uint_t);
199 static int segvn_clrszc(struct seg *);
200 static struct seg *segvn_split_seg(struct seg *, caddr_t);
201 static int segvn_claim_pages(struct seg *, struct vpage *, u_offset_t,
202     ulong_t, uint_t);
203 
204 static void segvn_hat_rgn_unload_callback(caddr_t, caddr_t, caddr_t,
205     size_t, void *, u_offset_t);
206 
207 static struct kmem_cache *segvn_cache;
208 static struct kmem_cache **segvn_szc_cache;
209 
210 #ifdef VM_STATS
211 static struct segvnvmstats_str {
212 	ulong_t	fill_vp_pages[31];
213 	ulong_t fltvnpages[49];
214 	ulong_t	fullszcpages[10];
215 	ulong_t	relocatepages[3];
216 	ulong_t	fltanpages[17];
217 	ulong_t pagelock[2];
218 	ulong_t	demoterange[3];
219 } segvnvmstats;
220 #endif /* VM_STATS */
221 
222 #define	SDR_RANGE	1		/* demote entire range */
223 #define	SDR_END		2		/* demote non aligned ends only */
224 
225 #define	CALC_LPG_REGION(pgsz, seg, addr, len, lpgaddr, lpgeaddr) {	    \
226 		if ((len) != 0) { 		      	      		      \
227 			lpgaddr = (caddr_t)P2ALIGN((uintptr_t)(addr), pgsz);  \
228 			ASSERT(lpgaddr >= (seg)->s_base);	      	      \
229 			lpgeaddr = (caddr_t)P2ROUNDUP((uintptr_t)((addr) +    \
230 			    (len)), pgsz);				      \
231 			ASSERT(lpgeaddr > lpgaddr);		      	      \
232 			ASSERT(lpgeaddr <= (seg)->s_base + (seg)->s_size);    \
233 		} else {					      	      \
234 			lpgeaddr = lpgaddr = (addr);	      		      \
235 		}							      \
236 	}
237 
238 /*ARGSUSED*/
239 static int
240 segvn_cache_constructor(void *buf, void *cdrarg, int kmflags)
241 {
242 	struct segvn_data *svd = buf;
243 
244 	rw_init(&svd->lock, NULL, RW_DEFAULT, NULL);
245 	mutex_init(&svd->segfree_syncmtx, NULL, MUTEX_DEFAULT, NULL);
246 	svd->svn_trnext = svd->svn_trprev = NULL;
247 	return (0);
248 }
249 
250 /*ARGSUSED1*/
251 static void
252 segvn_cache_destructor(void *buf, void *cdrarg)
253 {
254 	struct segvn_data *svd = buf;
255 
256 	rw_destroy(&svd->lock);
257 	mutex_destroy(&svd->segfree_syncmtx);
258 }
259 
260 /*ARGSUSED*/
261 static int
262 svntr_cache_constructor(void *buf, void *cdrarg, int kmflags)
263 {
264 	bzero(buf, sizeof (svntr_t));
265 	return (0);
266 }
267 
268 /*
269  * Patching this variable to non-zero allows the system to run with
270  * stacks marked as "not executable".  It's a bit of a kludge, but is
271  * provided as a tweakable for platforms that export those ABIs
272  * (e.g. sparc V8) that have executable stacks enabled by default.
273  * There are also some restrictions for platforms that don't actually
274  * implement 'noexec' protections.
275  *
276  * Once enabled, the system is (therefore) unable to provide a fully
277  * ABI-compliant execution environment, though practically speaking,
278  * most everything works.  The exceptions are generally some interpreters
279  * and debuggers that create executable code on the stack and jump
280  * into it (without explicitly mprotecting the address range to include
281  * PROT_EXEC).
282  *
283  * One important class of applications that are disabled are those
284  * that have been transformed into malicious agents using one of the
285  * numerous "buffer overflow" attacks.  See 4007890.
286  */
287 int noexec_user_stack = 0;
288 int noexec_user_stack_log = 1;
289 
290 int segvn_lpg_disable = 0;
291 uint_t segvn_maxpgszc = 0;
292 
293 ulong_t segvn_vmpss_clrszc_cnt;
294 ulong_t segvn_vmpss_clrszc_err;
295 ulong_t segvn_fltvnpages_clrszc_cnt;
296 ulong_t segvn_fltvnpages_clrszc_err;
297 ulong_t segvn_setpgsz_align_err;
298 ulong_t segvn_setpgsz_anon_align_err;
299 ulong_t segvn_setpgsz_getattr_err;
300 ulong_t segvn_setpgsz_eof_err;
301 ulong_t segvn_faultvnmpss_align_err1;
302 ulong_t segvn_faultvnmpss_align_err2;
303 ulong_t segvn_faultvnmpss_align_err3;
304 ulong_t segvn_faultvnmpss_align_err4;
305 ulong_t segvn_faultvnmpss_align_err5;
306 ulong_t	segvn_vmpss_pageio_deadlk_err;
307 
308 int segvn_use_regions = 1;
309 
310 /*
311  * Segvn supports text replication optimization for NUMA platforms. Text
312  * replica's are represented by anon maps (amp). There's one amp per text file
313  * region per lgroup. A process chooses the amp for each of its text mappings
314  * based on the lgroup assignment of its main thread (t_tid = 1). All
315  * processes that want a replica on a particular lgroup for the same text file
316  * mapping share the same amp. amp's are looked up in svntr_hashtab hash table
317  * with vp,off,size,szc used as a key. Text replication segments are read only
318  * MAP_PRIVATE|MAP_TEXT segments that map vnode. Replication is achieved by
319  * forcing COW faults from vnode to amp and mapping amp pages instead of vnode
320  * pages. Replication amp is assigned to a segment when it gets its first
321  * pagefault. To handle main thread lgroup rehoming segvn_trasync_thread
322  * rechecks periodically if the process still maps an amp local to the main
323  * thread. If not async thread forces process to remap to an amp in the new
324  * home lgroup of the main thread. Current text replication implementation
325  * only provides the benefit to workloads that do most of their work in the
326  * main thread of a process or all the threads of a process run in the same
327  * lgroup. To extend text replication benefit to different types of
328  * multithreaded workloads further work would be needed in the hat layer to
329  * allow the same virtual address in the same hat to simultaneously map
330  * different physical addresses (i.e. page table replication would be needed
331  * for x86).
332  *
333  * amp pages are used instead of vnode pages as long as segment has a very
334  * simple life cycle.  It's created via segvn_create(), handles S_EXEC
335  * (S_READ) pagefaults and is fully unmapped.  If anything more complicated
336  * happens such as protection is changed, real COW fault happens, pagesize is
337  * changed, MC_LOCK is requested or segment is partially unmapped we turn off
338  * text replication by converting the segment back to vnode only segment
339  * (unmap segment's address range and set svd->amp to NULL).
340  *
341  * The original file can be changed after amp is inserted into
342  * svntr_hashtab. Processes that are launched after the file is already
343  * changed can't use the replica's created prior to the file change. To
344  * implement this functionality hash entries are timestamped. Replica's can
345  * only be used if current file modification time is the same as the timestamp
346  * saved when hash entry was created. However just timestamps alone are not
347  * sufficient to detect file modification via mmap(MAP_SHARED) mappings. We
348  * deal with file changes via MAP_SHARED mappings differently. When writable
349  * MAP_SHARED mappings are created to vnodes marked as executable we mark all
350  * existing replica's for this vnode as not usable for future text
351  * mappings. And we don't create new replica's for files that currently have
352  * potentially writable MAP_SHARED mappings (i.e. vn_is_mapped(V_WRITE) is
353  * true).
354  */
355 
356 #define	SEGVN_TEXTREPL_MAXBYTES_FACTOR	(20)
357 size_t	segvn_textrepl_max_bytes_factor = SEGVN_TEXTREPL_MAXBYTES_FACTOR;
358 
359 static ulong_t			svntr_hashtab_sz = 512;
360 static svntr_bucket_t		*svntr_hashtab = NULL;
361 static struct kmem_cache	*svntr_cache;
362 static svntr_stats_t		*segvn_textrepl_stats;
363 static ksema_t 			segvn_trasync_sem;
364 
365 int				segvn_disable_textrepl = 1;
366 size_t				textrepl_size_thresh = (size_t)-1;
367 size_t				segvn_textrepl_bytes = 0;
368 size_t				segvn_textrepl_max_bytes = 0;
369 clock_t				segvn_update_textrepl_interval = 0;
370 int				segvn_update_tr_time = 10;
371 int				segvn_disable_textrepl_update = 0;
372 
373 static void segvn_textrepl(struct seg *);
374 static void segvn_textunrepl(struct seg *, int);
375 static void segvn_inval_trcache(vnode_t *);
376 static void segvn_trasync_thread(void);
377 static void segvn_trupdate_wakeup(void *);
378 static void segvn_trupdate(void);
379 static void segvn_trupdate_seg(struct seg *, segvn_data_t *, svntr_t *,
380     ulong_t);
381 
382 /*
383  * Initialize segvn data structures
384  */
385 void
386 segvn_init(void)
387 {
388 	uint_t maxszc;
389 	uint_t szc;
390 	size_t pgsz;
391 
392 	segvn_cache = kmem_cache_create("segvn_cache",
393 	    sizeof (struct segvn_data), 0,
394 	    segvn_cache_constructor, segvn_cache_destructor, NULL,
395 	    NULL, NULL, 0);
396 
397 	if (segvn_lpg_disable == 0) {
398 		szc = maxszc = page_num_pagesizes() - 1;
399 		if (szc == 0) {
400 			segvn_lpg_disable = 1;
401 		}
402 		if (page_get_pagesize(0) != PAGESIZE) {
403 			panic("segvn_init: bad szc 0");
404 			/*NOTREACHED*/
405 		}
406 		while (szc != 0) {
407 			pgsz = page_get_pagesize(szc);
408 			if (pgsz <= PAGESIZE || !IS_P2ALIGNED(pgsz, pgsz)) {
409 				panic("segvn_init: bad szc %d", szc);
410 				/*NOTREACHED*/
411 			}
412 			szc--;
413 		}
414 		if (segvn_maxpgszc == 0 || segvn_maxpgszc > maxszc)
415 			segvn_maxpgszc = maxszc;
416 	}
417 
418 	if (segvn_maxpgszc) {
419 		segvn_szc_cache = (struct kmem_cache **)kmem_alloc(
420 		    (segvn_maxpgszc + 1) * sizeof (struct kmem_cache *),
421 		    KM_SLEEP);
422 	}
423 
424 	for (szc = 1; szc <= segvn_maxpgszc; szc++) {
425 		char	str[32];
426 
427 		(void) sprintf(str, "segvn_szc_cache%d", szc);
428 		segvn_szc_cache[szc] = kmem_cache_create(str,
429 		    page_get_pagecnt(szc) * sizeof (page_t *), 0,
430 		    NULL, NULL, NULL, NULL, NULL, KMC_NODEBUG);
431 	}
432 
433 
434 	if (segvn_use_regions && !hat_supported(HAT_SHARED_REGIONS, NULL))
435 		segvn_use_regions = 0;
436 
437 	/*
438 	 * For now shared regions and text replication segvn support
439 	 * are mutually exclusive. This is acceptable because
440 	 * currently significant benefit from text replication was
441 	 * only observed on AMD64 NUMA platforms (due to relatively
442 	 * small L2$ size) and currently we don't support shared
443 	 * regions on x86.
444 	 */
445 	if (segvn_use_regions && !segvn_disable_textrepl) {
446 		segvn_disable_textrepl = 1;
447 	}
448 
449 #if defined(_LP64)
450 	if (lgrp_optimizations() && textrepl_size_thresh != (size_t)-1 &&
451 	    !segvn_disable_textrepl) {
452 		ulong_t i;
453 		size_t hsz = svntr_hashtab_sz * sizeof (svntr_bucket_t);
454 
455 		svntr_cache = kmem_cache_create("svntr_cache",
456 		    sizeof (svntr_t), 0, svntr_cache_constructor, NULL,
457 		    NULL, NULL, NULL, 0);
458 		svntr_hashtab = kmem_zalloc(hsz, KM_SLEEP);
459 		for (i = 0; i < svntr_hashtab_sz; i++) {
460 			mutex_init(&svntr_hashtab[i].tr_lock,  NULL,
461 			    MUTEX_DEFAULT, NULL);
462 		}
463 		segvn_textrepl_max_bytes = ptob(physmem) /
464 		    segvn_textrepl_max_bytes_factor;
465 		segvn_textrepl_stats = kmem_zalloc(NCPU *
466 		    sizeof (svntr_stats_t), KM_SLEEP);
467 		sema_init(&segvn_trasync_sem, 0, NULL, SEMA_DEFAULT, NULL);
468 		(void) thread_create(NULL, 0, segvn_trasync_thread,
469 		    NULL, 0, &p0, TS_RUN, minclsyspri);
470 	}
471 #endif
472 
473 	if (!ISP2(segvn_pglock_comb_balign) ||
474 	    segvn_pglock_comb_balign < PAGESIZE) {
475 		segvn_pglock_comb_balign = 1UL << 16; /* 64K */
476 	}
477 	segvn_pglock_comb_bshift = highbit(segvn_pglock_comb_balign) - 1;
478 	segvn_pglock_comb_palign = btop(segvn_pglock_comb_balign);
479 }
480 
481 #define	SEGVN_PAGEIO	((void *)0x1)
482 #define	SEGVN_NOPAGEIO	((void *)0x2)
483 
484 static void
485 segvn_setvnode_mpss(vnode_t *vp)
486 {
487 	int err;
488 
489 	ASSERT(vp->v_mpssdata == NULL ||
490 	    vp->v_mpssdata == SEGVN_PAGEIO ||
491 	    vp->v_mpssdata == SEGVN_NOPAGEIO);
492 
493 	if (vp->v_mpssdata == NULL) {
494 		if (vn_vmpss_usepageio(vp)) {
495 			err = VOP_PAGEIO(vp, (page_t *)NULL,
496 			    (u_offset_t)0, 0, 0, CRED(), NULL);
497 		} else {
498 			err = ENOSYS;
499 		}
500 		/*
501 		 * set v_mpssdata just once per vnode life
502 		 * so that it never changes.
503 		 */
504 		mutex_enter(&vp->v_lock);
505 		if (vp->v_mpssdata == NULL) {
506 			if (err == EINVAL) {
507 				vp->v_mpssdata = SEGVN_PAGEIO;
508 			} else {
509 				vp->v_mpssdata = SEGVN_NOPAGEIO;
510 			}
511 		}
512 		mutex_exit(&vp->v_lock);
513 	}
514 }
515 
516 int
517 segvn_create(struct seg *seg, void *argsp)
518 {
519 	struct segvn_crargs *a = (struct segvn_crargs *)argsp;
520 	struct segvn_data *svd;
521 	size_t swresv = 0;
522 	struct cred *cred;
523 	struct anon_map *amp;
524 	int error = 0;
525 	size_t pgsz;
526 	lgrp_mem_policy_t mpolicy = LGRP_MEM_POLICY_DEFAULT;
527 	int use_rgn = 0;
528 	int trok = 0;
529 
530 	ASSERT(seg->s_as && AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
531 
532 	if (a->type != MAP_PRIVATE && a->type != MAP_SHARED) {
533 		panic("segvn_create type");
534 		/*NOTREACHED*/
535 	}
536 
537 	/*
538 	 * Check arguments.  If a shared anon structure is given then
539 	 * it is illegal to also specify a vp.
540 	 */
541 	if (a->amp != NULL && a->vp != NULL) {
542 		panic("segvn_create anon_map");
543 		/*NOTREACHED*/
544 	}
545 
546 	if (a->type == MAP_PRIVATE && (a->flags & MAP_TEXT) &&
547 	    a->vp != NULL && a->prot == (PROT_USER | PROT_READ | PROT_EXEC) &&
548 	    segvn_use_regions) {
549 		use_rgn = 1;
550 	}
551 
552 	/* MAP_NORESERVE on a MAP_SHARED segment is meaningless. */
553 	if (a->type == MAP_SHARED)
554 		a->flags &= ~MAP_NORESERVE;
555 
556 	if (a->szc != 0) {
557 		if (segvn_lpg_disable != 0 || (a->szc == AS_MAP_NO_LPOOB) ||
558 		    (a->amp != NULL && a->type == MAP_PRIVATE) ||
559 		    (a->flags & MAP_NORESERVE) || seg->s_as == &kas) {
560 			a->szc = 0;
561 		} else {
562 			if (a->szc > segvn_maxpgszc)
563 				a->szc = segvn_maxpgszc;
564 			pgsz = page_get_pagesize(a->szc);
565 			if (!IS_P2ALIGNED(seg->s_base, pgsz) ||
566 			    !IS_P2ALIGNED(seg->s_size, pgsz)) {
567 				a->szc = 0;
568 			} else if (a->vp != NULL) {
569 				if (IS_SWAPFSVP(a->vp) || VN_ISKAS(a->vp)) {
570 					/*
571 					 * paranoid check.
572 					 * hat_page_demote() is not supported
573 					 * on swapfs pages.
574 					 */
575 					a->szc = 0;
576 				} else if (map_addr_vacalign_check(seg->s_base,
577 				    a->offset & PAGEMASK)) {
578 					a->szc = 0;
579 				}
580 			} else if (a->amp != NULL) {
581 				pgcnt_t anum = btopr(a->offset);
582 				pgcnt_t pgcnt = page_get_pagecnt(a->szc);
583 				if (!IS_P2ALIGNED(anum, pgcnt)) {
584 					a->szc = 0;
585 				}
586 			}
587 		}
588 	}
589 
590 	/*
591 	 * If segment may need private pages, reserve them now.
592 	 */
593 	if (!(a->flags & MAP_NORESERVE) && ((a->vp == NULL && a->amp == NULL) ||
594 	    (a->type == MAP_PRIVATE && (a->prot & PROT_WRITE)))) {
595 		if (anon_resv_zone(seg->s_size,
596 		    seg->s_as->a_proc->p_zone) == 0)
597 			return (EAGAIN);
598 		swresv = seg->s_size;
599 		TRACE_3(TR_FAC_VM, TR_ANON_PROC, "anon proc:%p %lu %u",
600 		    seg, swresv, 1);
601 	}
602 
603 	/*
604 	 * Reserve any mapping structures that may be required.
605 	 *
606 	 * Don't do it for segments that may use regions. It's currently a
607 	 * noop in the hat implementations anyway.
608 	 */
609 	if (!use_rgn) {
610 		hat_map(seg->s_as->a_hat, seg->s_base, seg->s_size, HAT_MAP);
611 	}
612 
613 	if (a->cred) {
614 		cred = a->cred;
615 		crhold(cred);
616 	} else {
617 		crhold(cred = CRED());
618 	}
619 
620 	/* Inform the vnode of the new mapping */
621 	if (a->vp != NULL) {
622 		error = VOP_ADDMAP(a->vp, a->offset & PAGEMASK,
623 		    seg->s_as, seg->s_base, seg->s_size, a->prot,
624 		    a->maxprot, a->type, cred, NULL);
625 		if (error) {
626 			if (swresv != 0) {
627 				anon_unresv_zone(swresv,
628 				    seg->s_as->a_proc->p_zone);
629 				TRACE_3(TR_FAC_VM, TR_ANON_PROC,
630 				    "anon proc:%p %lu %u", seg, swresv, 0);
631 			}
632 			crfree(cred);
633 			if (!use_rgn) {
634 				hat_unload(seg->s_as->a_hat, seg->s_base,
635 				    seg->s_size, HAT_UNLOAD_UNMAP);
636 			}
637 			return (error);
638 		}
639 		/*
640 		 * svntr_hashtab will be NULL if we support shared regions.
641 		 */
642 		trok = ((a->flags & MAP_TEXT) &&
643 		    (seg->s_size > textrepl_size_thresh ||
644 		    (a->flags & _MAP_TEXTREPL)) &&
645 		    lgrp_optimizations() && svntr_hashtab != NULL &&
646 		    a->type == MAP_PRIVATE && swresv == 0 &&
647 		    !(a->flags & MAP_NORESERVE) &&
648 		    seg->s_as != &kas && a->vp->v_type == VREG);
649 
650 		ASSERT(!trok || !use_rgn);
651 	}
652 
653 	/*
654 	 * MAP_NORESERVE mappings don't count towards the VSZ of a process
655 	 * until we fault the pages in.
656 	 */
657 	if ((a->vp == NULL || a->vp->v_type != VREG) &&
658 	    a->flags & MAP_NORESERVE) {
659 		seg->s_as->a_resvsize -= seg->s_size;
660 	}
661 
662 	/*
663 	 * If more than one segment in the address space, and they're adjacent
664 	 * virtually, try to concatenate them.  Don't concatenate if an
665 	 * explicit anon_map structure was supplied (e.g., SystemV shared
666 	 * memory) or if we'll use text replication for this segment.
667 	 */
668 	if (a->amp == NULL && !use_rgn && !trok) {
669 		struct seg *pseg, *nseg;
670 		struct segvn_data *psvd, *nsvd;
671 		lgrp_mem_policy_t ppolicy, npolicy;
672 		uint_t	lgrp_mem_policy_flags = 0;
673 		extern lgrp_mem_policy_t lgrp_mem_default_policy;
674 
675 		/*
676 		 * Memory policy flags (lgrp_mem_policy_flags) is valid when
677 		 * extending stack/heap segments.
678 		 */
679 		if ((a->vp == NULL) && (a->type == MAP_PRIVATE) &&
680 		    !(a->flags & MAP_NORESERVE) && (seg->s_as != &kas)) {
681 			lgrp_mem_policy_flags = a->lgrp_mem_policy_flags;
682 		} else {
683 			/*
684 			 * Get policy when not extending it from another segment
685 			 */
686 			mpolicy = lgrp_mem_policy_default(seg->s_size, a->type);
687 		}
688 
689 		/*
690 		 * First, try to concatenate the previous and new segments
691 		 */
692 		pseg = AS_SEGPREV(seg->s_as, seg);
693 		if (pseg != NULL &&
694 		    pseg->s_base + pseg->s_size == seg->s_base &&
695 		    pseg->s_ops == &segvn_ops) {
696 			/*
697 			 * Get memory allocation policy from previous segment.
698 			 * When extension is specified (e.g. for heap) apply
699 			 * this policy to the new segment regardless of the
700 			 * outcome of segment concatenation.  Extension occurs
701 			 * for non-default policy otherwise default policy is
702 			 * used and is based on extended segment size.
703 			 */
704 			psvd = (struct segvn_data *)pseg->s_data;
705 			ppolicy = psvd->policy_info.mem_policy;
706 			if (lgrp_mem_policy_flags ==
707 			    LGRP_MP_FLAG_EXTEND_UP) {
708 				if (ppolicy != lgrp_mem_default_policy) {
709 					mpolicy = ppolicy;
710 				} else {
711 					mpolicy = lgrp_mem_policy_default(
712 					    pseg->s_size + seg->s_size,
713 					    a->type);
714 				}
715 			}
716 
717 			if (mpolicy == ppolicy &&
718 			    (pseg->s_size + seg->s_size <=
719 			    segvn_comb_thrshld || psvd->amp == NULL) &&
720 			    segvn_extend_prev(pseg, seg, a, swresv) == 0) {
721 				/*
722 				 * success! now try to concatenate
723 				 * with following seg
724 				 */
725 				crfree(cred);
726 				nseg = AS_SEGNEXT(pseg->s_as, pseg);
727 				if (nseg != NULL &&
728 				    nseg != pseg &&
729 				    nseg->s_ops == &segvn_ops &&
730 				    pseg->s_base + pseg->s_size ==
731 				    nseg->s_base)
732 					(void) segvn_concat(pseg, nseg, 0);
733 				ASSERT(pseg->s_szc == 0 ||
734 				    (a->szc == pseg->s_szc &&
735 				    IS_P2ALIGNED(pseg->s_base, pgsz) &&
736 				    IS_P2ALIGNED(pseg->s_size, pgsz)));
737 				return (0);
738 			}
739 		}
740 
741 		/*
742 		 * Failed, so try to concatenate with following seg
743 		 */
744 		nseg = AS_SEGNEXT(seg->s_as, seg);
745 		if (nseg != NULL &&
746 		    seg->s_base + seg->s_size == nseg->s_base &&
747 		    nseg->s_ops == &segvn_ops) {
748 			/*
749 			 * Get memory allocation policy from next segment.
750 			 * When extension is specified (e.g. for stack) apply
751 			 * this policy to the new segment regardless of the
752 			 * outcome of segment concatenation.  Extension occurs
753 			 * for non-default policy otherwise default policy is
754 			 * used and is based on extended segment size.
755 			 */
756 			nsvd = (struct segvn_data *)nseg->s_data;
757 			npolicy = nsvd->policy_info.mem_policy;
758 			if (lgrp_mem_policy_flags ==
759 			    LGRP_MP_FLAG_EXTEND_DOWN) {
760 				if (npolicy != lgrp_mem_default_policy) {
761 					mpolicy = npolicy;
762 				} else {
763 					mpolicy = lgrp_mem_policy_default(
764 					    nseg->s_size + seg->s_size,
765 					    a->type);
766 				}
767 			}
768 
769 			if (mpolicy == npolicy &&
770 			    segvn_extend_next(seg, nseg, a, swresv) == 0) {
771 				crfree(cred);
772 				ASSERT(nseg->s_szc == 0 ||
773 				    (a->szc == nseg->s_szc &&
774 				    IS_P2ALIGNED(nseg->s_base, pgsz) &&
775 				    IS_P2ALIGNED(nseg->s_size, pgsz)));
776 				return (0);
777 			}
778 		}
779 	}
780 
781 	if (a->vp != NULL) {
782 		VN_HOLD(a->vp);
783 		if (a->type == MAP_SHARED)
784 			lgrp_shm_policy_init(NULL, a->vp);
785 	}
786 	svd = kmem_cache_alloc(segvn_cache, KM_SLEEP);
787 
788 	seg->s_ops = &segvn_ops;
789 	seg->s_data = (void *)svd;
790 	seg->s_szc = a->szc;
791 
792 	svd->seg = seg;
793 	svd->vp = a->vp;
794 	/*
795 	 * Anonymous mappings have no backing file so the offset is meaningless.
796 	 */
797 	svd->offset = a->vp ? (a->offset & PAGEMASK) : 0;
798 	svd->prot = a->prot;
799 	svd->maxprot = a->maxprot;
800 	svd->pageprot = 0;
801 	svd->type = a->type;
802 	svd->vpage = NULL;
803 	svd->cred = cred;
804 	svd->advice = MADV_NORMAL;
805 	svd->pageadvice = 0;
806 	svd->flags = (ushort_t)a->flags;
807 	svd->softlockcnt = 0;
808 	svd->softlockcnt_sbase = 0;
809 	svd->softlockcnt_send = 0;
810 	svd->rcookie = HAT_INVALID_REGION_COOKIE;
811 	svd->pageswap = 0;
812 
813 	if (a->szc != 0 && a->vp != NULL) {
814 		segvn_setvnode_mpss(a->vp);
815 	}
816 	if (svd->type == MAP_SHARED && svd->vp != NULL &&
817 	    (svd->vp->v_flag & VVMEXEC) && (svd->prot & PROT_WRITE)) {
818 		ASSERT(vn_is_mapped(svd->vp, V_WRITE));
819 		segvn_inval_trcache(svd->vp);
820 	}
821 
822 	amp = a->amp;
823 	if ((svd->amp = amp) == NULL) {
824 		svd->anon_index = 0;
825 		if (svd->type == MAP_SHARED) {
826 			svd->swresv = 0;
827 			/*
828 			 * Shared mappings to a vp need no other setup.
829 			 * If we have a shared mapping to an anon_map object
830 			 * which hasn't been allocated yet,  allocate the
831 			 * struct now so that it will be properly shared
832 			 * by remembering the swap reservation there.
833 			 */
834 			if (a->vp == NULL) {
835 				svd->amp = anonmap_alloc(seg->s_size, swresv,
836 				    ANON_SLEEP);
837 				svd->amp->a_szc = seg->s_szc;
838 			}
839 		} else {
840 			/*
841 			 * Private mapping (with or without a vp).
842 			 * Allocate anon_map when needed.
843 			 */
844 			svd->swresv = swresv;
845 		}
846 	} else {
847 		pgcnt_t anon_num;
848 
849 		/*
850 		 * Mapping to an existing anon_map structure without a vp.
851 		 * For now we will insure that the segment size isn't larger
852 		 * than the size - offset gives us.  Later on we may wish to
853 		 * have the anon array dynamically allocated itself so that
854 		 * we don't always have to allocate all the anon pointer slots.
855 		 * This of course involves adding extra code to check that we
856 		 * aren't trying to use an anon pointer slot beyond the end
857 		 * of the currently allocated anon array.
858 		 */
859 		if ((amp->size - a->offset) < seg->s_size) {
860 			panic("segvn_create anon_map size");
861 			/*NOTREACHED*/
862 		}
863 
864 		anon_num = btopr(a->offset);
865 
866 		if (a->type == MAP_SHARED) {
867 			/*
868 			 * SHARED mapping to a given anon_map.
869 			 */
870 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
871 			amp->refcnt++;
872 			if (a->szc > amp->a_szc) {
873 				amp->a_szc = a->szc;
874 			}
875 			ANON_LOCK_EXIT(&amp->a_rwlock);
876 			svd->anon_index = anon_num;
877 			svd->swresv = 0;
878 		} else {
879 			/*
880 			 * PRIVATE mapping to a given anon_map.
881 			 * Make sure that all the needed anon
882 			 * structures are created (so that we will
883 			 * share the underlying pages if nothing
884 			 * is written by this mapping) and then
885 			 * duplicate the anon array as is done
886 			 * when a privately mapped segment is dup'ed.
887 			 */
888 			struct anon *ap;
889 			caddr_t addr;
890 			caddr_t eaddr;
891 			ulong_t	anon_idx;
892 			int hat_flag = HAT_LOAD;
893 
894 			if (svd->flags & MAP_TEXT) {
895 				hat_flag |= HAT_LOAD_TEXT;
896 			}
897 
898 			svd->amp = anonmap_alloc(seg->s_size, 0, ANON_SLEEP);
899 			svd->amp->a_szc = seg->s_szc;
900 			svd->anon_index = 0;
901 			svd->swresv = swresv;
902 
903 			/*
904 			 * Prevent 2 threads from allocating anon
905 			 * slots simultaneously.
906 			 */
907 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
908 			eaddr = seg->s_base + seg->s_size;
909 
910 			for (anon_idx = anon_num, addr = seg->s_base;
911 			    addr < eaddr; addr += PAGESIZE, anon_idx++) {
912 				page_t *pp;
913 
914 				if ((ap = anon_get_ptr(amp->ahp,
915 				    anon_idx)) != NULL)
916 					continue;
917 
918 				/*
919 				 * Allocate the anon struct now.
920 				 * Might as well load up translation
921 				 * to the page while we're at it...
922 				 */
923 				pp = anon_zero(seg, addr, &ap, cred);
924 				if (ap == NULL || pp == NULL) {
925 					panic("segvn_create anon_zero");
926 					/*NOTREACHED*/
927 				}
928 
929 				/*
930 				 * Re-acquire the anon_map lock and
931 				 * initialize the anon array entry.
932 				 */
933 				ASSERT(anon_get_ptr(amp->ahp,
934 				    anon_idx) == NULL);
935 				(void) anon_set_ptr(amp->ahp, anon_idx, ap,
936 				    ANON_SLEEP);
937 
938 				ASSERT(seg->s_szc == 0);
939 				ASSERT(!IS_VMODSORT(pp->p_vnode));
940 
941 				ASSERT(use_rgn == 0);
942 				hat_memload(seg->s_as->a_hat, addr, pp,
943 				    svd->prot & ~PROT_WRITE, hat_flag);
944 
945 				page_unlock(pp);
946 			}
947 			ASSERT(seg->s_szc == 0);
948 			anon_dup(amp->ahp, anon_num, svd->amp->ahp,
949 			    0, seg->s_size);
950 			ANON_LOCK_EXIT(&amp->a_rwlock);
951 		}
952 	}
953 
954 	/*
955 	 * Set default memory allocation policy for segment
956 	 *
957 	 * Always set policy for private memory at least for initialization
958 	 * even if this is a shared memory segment
959 	 */
960 	(void) lgrp_privm_policy_set(mpolicy, &svd->policy_info, seg->s_size);
961 
962 	if (svd->type == MAP_SHARED)
963 		(void) lgrp_shm_policy_set(mpolicy, svd->amp, svd->anon_index,
964 		    svd->vp, svd->offset, seg->s_size);
965 
966 	if (use_rgn) {
967 		ASSERT(!trok);
968 		ASSERT(svd->amp == NULL);
969 		svd->rcookie = hat_join_region(seg->s_as->a_hat, seg->s_base,
970 		    seg->s_size, (void *)svd->vp, svd->offset, svd->prot,
971 		    (uchar_t)seg->s_szc, segvn_hat_rgn_unload_callback,
972 		    HAT_REGION_TEXT);
973 	}
974 
975 	ASSERT(!trok || !(svd->prot & PROT_WRITE));
976 	svd->tr_state = trok ? SEGVN_TR_INIT : SEGVN_TR_OFF;
977 
978 	return (0);
979 }
980 
981 /*
982  * Concatenate two existing segments, if possible.
983  * Return 0 on success, -1 if two segments are not compatible
984  * or -2 on memory allocation failure.
985  * If amp_cat == 1 then try and concat segments with anon maps
986  */
987 static int
988 segvn_concat(struct seg *seg1, struct seg *seg2, int amp_cat)
989 {
990 	struct segvn_data *svd1 = seg1->s_data;
991 	struct segvn_data *svd2 = seg2->s_data;
992 	struct anon_map *amp1 = svd1->amp;
993 	struct anon_map *amp2 = svd2->amp;
994 	struct vpage *vpage1 = svd1->vpage;
995 	struct vpage *vpage2 = svd2->vpage, *nvpage = NULL;
996 	size_t size, nvpsize;
997 	pgcnt_t npages1, npages2;
998 
999 	ASSERT(seg1->s_as && seg2->s_as && seg1->s_as == seg2->s_as);
1000 	ASSERT(AS_WRITE_HELD(seg1->s_as, &seg1->s_as->a_lock));
1001 	ASSERT(seg1->s_ops == seg2->s_ops);
1002 
1003 	if (HAT_IS_REGION_COOKIE_VALID(svd1->rcookie) ||
1004 	    HAT_IS_REGION_COOKIE_VALID(svd2->rcookie)) {
1005 		return (-1);
1006 	}
1007 
1008 	/* both segments exist, try to merge them */
1009 #define	incompat(x)	(svd1->x != svd2->x)
1010 	if (incompat(vp) || incompat(maxprot) ||
1011 	    (!svd1->pageadvice && !svd2->pageadvice && incompat(advice)) ||
1012 	    (!svd1->pageprot && !svd2->pageprot && incompat(prot)) ||
1013 	    incompat(type) || incompat(cred) || incompat(flags) ||
1014 	    seg1->s_szc != seg2->s_szc || incompat(policy_info.mem_policy) ||
1015 	    (svd2->softlockcnt > 0) || svd1->softlockcnt_send > 0)
1016 		return (-1);
1017 #undef incompat
1018 
1019 	/*
1020 	 * vp == NULL implies zfod, offset doesn't matter
1021 	 */
1022 	if (svd1->vp != NULL &&
1023 	    svd1->offset + seg1->s_size != svd2->offset) {
1024 		return (-1);
1025 	}
1026 
1027 	/*
1028 	 * Don't concatenate if either segment uses text replication.
1029 	 */
1030 	if (svd1->tr_state != SEGVN_TR_OFF || svd2->tr_state != SEGVN_TR_OFF) {
1031 		return (-1);
1032 	}
1033 
1034 	/*
1035 	 * Fail early if we're not supposed to concatenate
1036 	 * segments with non NULL amp.
1037 	 */
1038 	if (amp_cat == 0 && (amp1 != NULL || amp2 != NULL)) {
1039 		return (-1);
1040 	}
1041 
1042 	if (svd1->vp == NULL && svd1->type == MAP_SHARED) {
1043 		if (amp1 != amp2) {
1044 			return (-1);
1045 		}
1046 		if (amp1 != NULL && svd1->anon_index + btop(seg1->s_size) !=
1047 		    svd2->anon_index) {
1048 			return (-1);
1049 		}
1050 		ASSERT(amp1 == NULL || amp1->refcnt >= 2);
1051 	}
1052 
1053 	/*
1054 	 * If either seg has vpages, create a new merged vpage array.
1055 	 */
1056 	if (vpage1 != NULL || vpage2 != NULL) {
1057 		struct vpage *vp, *evp;
1058 
1059 		npages1 = seg_pages(seg1);
1060 		npages2 = seg_pages(seg2);
1061 		nvpsize = vpgtob(npages1 + npages2);
1062 
1063 		if ((nvpage = kmem_zalloc(nvpsize, KM_NOSLEEP)) == NULL) {
1064 			return (-2);
1065 		}
1066 
1067 		if (vpage1 != NULL) {
1068 			bcopy(vpage1, nvpage, vpgtob(npages1));
1069 		} else {
1070 			evp = nvpage + npages1;
1071 			for (vp = nvpage; vp < evp; vp++) {
1072 				VPP_SETPROT(vp, svd1->prot);
1073 				VPP_SETADVICE(vp, svd1->advice);
1074 			}
1075 		}
1076 
1077 		if (vpage2 != NULL) {
1078 			bcopy(vpage2, nvpage + npages1, vpgtob(npages2));
1079 		} else {
1080 			evp = nvpage + npages1 + npages2;
1081 			for (vp = nvpage + npages1; vp < evp; vp++) {
1082 				VPP_SETPROT(vp, svd2->prot);
1083 				VPP_SETADVICE(vp, svd2->advice);
1084 			}
1085 		}
1086 
1087 		if (svd2->pageswap && (!svd1->pageswap && svd1->swresv)) {
1088 			ASSERT(svd1->swresv == seg1->s_size);
1089 			ASSERT(!(svd1->flags & MAP_NORESERVE));
1090 			ASSERT(!(svd2->flags & MAP_NORESERVE));
1091 			evp = nvpage + npages1;
1092 			for (vp = nvpage; vp < evp; vp++) {
1093 				VPP_SETSWAPRES(vp);
1094 			}
1095 		}
1096 
1097 		if (svd1->pageswap && (!svd2->pageswap && svd2->swresv)) {
1098 			ASSERT(svd2->swresv == seg2->s_size);
1099 			ASSERT(!(svd1->flags & MAP_NORESERVE));
1100 			ASSERT(!(svd2->flags & MAP_NORESERVE));
1101 			vp = nvpage + npages1;
1102 			evp = vp + npages2;
1103 			for (; vp < evp; vp++) {
1104 				VPP_SETSWAPRES(vp);
1105 			}
1106 		}
1107 	}
1108 	ASSERT((vpage1 != NULL || vpage2 != NULL) ||
1109 	    (svd1->pageswap == 0 && svd2->pageswap == 0));
1110 
1111 	/*
1112 	 * If either segment has private pages, create a new merged anon
1113 	 * array. If mergeing shared anon segments just decrement anon map's
1114 	 * refcnt.
1115 	 */
1116 	if (amp1 != NULL && svd1->type == MAP_SHARED) {
1117 		ASSERT(amp1 == amp2 && svd1->vp == NULL);
1118 		ANON_LOCK_ENTER(&amp1->a_rwlock, RW_WRITER);
1119 		ASSERT(amp1->refcnt >= 2);
1120 		amp1->refcnt--;
1121 		ANON_LOCK_EXIT(&amp1->a_rwlock);
1122 		svd2->amp = NULL;
1123 	} else if (amp1 != NULL || amp2 != NULL) {
1124 		struct anon_hdr *nahp;
1125 		struct anon_map *namp = NULL;
1126 		size_t asize;
1127 
1128 		ASSERT(svd1->type == MAP_PRIVATE);
1129 
1130 		asize = seg1->s_size + seg2->s_size;
1131 		if ((nahp = anon_create(btop(asize), ANON_NOSLEEP)) == NULL) {
1132 			if (nvpage != NULL) {
1133 				kmem_free(nvpage, nvpsize);
1134 			}
1135 			return (-2);
1136 		}
1137 		if (amp1 != NULL) {
1138 			/*
1139 			 * XXX anon rwlock is not really needed because
1140 			 * this is a private segment and we are writers.
1141 			 */
1142 			ANON_LOCK_ENTER(&amp1->a_rwlock, RW_WRITER);
1143 			ASSERT(amp1->refcnt == 1);
1144 			if (anon_copy_ptr(amp1->ahp, svd1->anon_index,
1145 			    nahp, 0, btop(seg1->s_size), ANON_NOSLEEP)) {
1146 				anon_release(nahp, btop(asize));
1147 				ANON_LOCK_EXIT(&amp1->a_rwlock);
1148 				if (nvpage != NULL) {
1149 					kmem_free(nvpage, nvpsize);
1150 				}
1151 				return (-2);
1152 			}
1153 		}
1154 		if (amp2 != NULL) {
1155 			ANON_LOCK_ENTER(&amp2->a_rwlock, RW_WRITER);
1156 			ASSERT(amp2->refcnt == 1);
1157 			if (anon_copy_ptr(amp2->ahp, svd2->anon_index,
1158 			    nahp, btop(seg1->s_size), btop(seg2->s_size),
1159 			    ANON_NOSLEEP)) {
1160 				anon_release(nahp, btop(asize));
1161 				ANON_LOCK_EXIT(&amp2->a_rwlock);
1162 				if (amp1 != NULL) {
1163 					ANON_LOCK_EXIT(&amp1->a_rwlock);
1164 				}
1165 				if (nvpage != NULL) {
1166 					kmem_free(nvpage, nvpsize);
1167 				}
1168 				return (-2);
1169 			}
1170 		}
1171 		if (amp1 != NULL) {
1172 			namp = amp1;
1173 			anon_release(amp1->ahp, btop(amp1->size));
1174 		}
1175 		if (amp2 != NULL) {
1176 			if (namp == NULL) {
1177 				ASSERT(amp1 == NULL);
1178 				namp = amp2;
1179 				anon_release(amp2->ahp, btop(amp2->size));
1180 			} else {
1181 				amp2->refcnt--;
1182 				ANON_LOCK_EXIT(&amp2->a_rwlock);
1183 				anonmap_free(amp2);
1184 			}
1185 			svd2->amp = NULL; /* needed for seg_free */
1186 		}
1187 		namp->ahp = nahp;
1188 		namp->size = asize;
1189 		svd1->amp = namp;
1190 		svd1->anon_index = 0;
1191 		ANON_LOCK_EXIT(&namp->a_rwlock);
1192 	}
1193 	/*
1194 	 * Now free the old vpage structures.
1195 	 */
1196 	if (nvpage != NULL) {
1197 		if (vpage1 != NULL) {
1198 			kmem_free(vpage1, vpgtob(npages1));
1199 		}
1200 		if (vpage2 != NULL) {
1201 			svd2->vpage = NULL;
1202 			kmem_free(vpage2, vpgtob(npages2));
1203 		}
1204 		if (svd2->pageprot) {
1205 			svd1->pageprot = 1;
1206 		}
1207 		if (svd2->pageadvice) {
1208 			svd1->pageadvice = 1;
1209 		}
1210 		if (svd2->pageswap) {
1211 			svd1->pageswap = 1;
1212 		}
1213 		svd1->vpage = nvpage;
1214 	}
1215 
1216 	/* all looks ok, merge segments */
1217 	svd1->swresv += svd2->swresv;
1218 	svd2->swresv = 0;  /* so seg_free doesn't release swap space */
1219 	size = seg2->s_size;
1220 	seg_free(seg2);
1221 	seg1->s_size += size;
1222 	return (0);
1223 }
1224 
1225 /*
1226  * Extend the previous segment (seg1) to include the
1227  * new segment (seg2 + a), if possible.
1228  * Return 0 on success.
1229  */
1230 static int
1231 segvn_extend_prev(seg1, seg2, a, swresv)
1232 	struct seg *seg1, *seg2;
1233 	struct segvn_crargs *a;
1234 	size_t swresv;
1235 {
1236 	struct segvn_data *svd1 = (struct segvn_data *)seg1->s_data;
1237 	size_t size;
1238 	struct anon_map *amp1;
1239 	struct vpage *new_vpage;
1240 
1241 	/*
1242 	 * We don't need any segment level locks for "segvn" data
1243 	 * since the address space is "write" locked.
1244 	 */
1245 	ASSERT(seg1->s_as && AS_WRITE_HELD(seg1->s_as, &seg1->s_as->a_lock));
1246 
1247 	if (HAT_IS_REGION_COOKIE_VALID(svd1->rcookie)) {
1248 		return (-1);
1249 	}
1250 
1251 	/* second segment is new, try to extend first */
1252 	/* XXX - should also check cred */
1253 	if (svd1->vp != a->vp || svd1->maxprot != a->maxprot ||
1254 	    (!svd1->pageprot && (svd1->prot != a->prot)) ||
1255 	    svd1->type != a->type || svd1->flags != a->flags ||
1256 	    seg1->s_szc != a->szc || svd1->softlockcnt_send > 0)
1257 		return (-1);
1258 
1259 	/* vp == NULL implies zfod, offset doesn't matter */
1260 	if (svd1->vp != NULL &&
1261 	    svd1->offset + seg1->s_size != (a->offset & PAGEMASK))
1262 		return (-1);
1263 
1264 	if (svd1->tr_state != SEGVN_TR_OFF) {
1265 		return (-1);
1266 	}
1267 
1268 	amp1 = svd1->amp;
1269 	if (amp1) {
1270 		pgcnt_t newpgs;
1271 
1272 		/*
1273 		 * Segment has private pages, can data structures
1274 		 * be expanded?
1275 		 *
1276 		 * Acquire the anon_map lock to prevent it from changing,
1277 		 * if it is shared.  This ensures that the anon_map
1278 		 * will not change while a thread which has a read/write
1279 		 * lock on an address space references it.
1280 		 * XXX - Don't need the anon_map lock at all if "refcnt"
1281 		 * is 1.
1282 		 *
1283 		 * Can't grow a MAP_SHARED segment with an anonmap because
1284 		 * there may be existing anon slots where we want to extend
1285 		 * the segment and we wouldn't know what to do with them
1286 		 * (e.g., for tmpfs right thing is to just leave them there,
1287 		 * for /dev/zero they should be cleared out).
1288 		 */
1289 		if (svd1->type == MAP_SHARED)
1290 			return (-1);
1291 
1292 		ANON_LOCK_ENTER(&amp1->a_rwlock, RW_WRITER);
1293 		if (amp1->refcnt > 1) {
1294 			ANON_LOCK_EXIT(&amp1->a_rwlock);
1295 			return (-1);
1296 		}
1297 		newpgs = anon_grow(amp1->ahp, &svd1->anon_index,
1298 		    btop(seg1->s_size), btop(seg2->s_size), ANON_NOSLEEP);
1299 
1300 		if (newpgs == 0) {
1301 			ANON_LOCK_EXIT(&amp1->a_rwlock);
1302 			return (-1);
1303 		}
1304 		amp1->size = ptob(newpgs);
1305 		ANON_LOCK_EXIT(&amp1->a_rwlock);
1306 	}
1307 	if (svd1->vpage != NULL) {
1308 		struct vpage *vp, *evp;
1309 		new_vpage =
1310 		    kmem_zalloc(vpgtob(seg_pages(seg1) + seg_pages(seg2)),
1311 			KM_NOSLEEP);
1312 		if (new_vpage == NULL)
1313 			return (-1);
1314 		bcopy(svd1->vpage, new_vpage, vpgtob(seg_pages(seg1)));
1315 		kmem_free(svd1->vpage, vpgtob(seg_pages(seg1)));
1316 		svd1->vpage = new_vpage;
1317 
1318 		vp = new_vpage + seg_pages(seg1);
1319 		evp = vp + seg_pages(seg2);
1320 		for (; vp < evp; vp++)
1321 			VPP_SETPROT(vp, a->prot);
1322 		if (svd1->pageswap && swresv) {
1323 			ASSERT(!(svd1->flags & MAP_NORESERVE));
1324 			ASSERT(swresv == seg2->s_size);
1325 			vp = new_vpage + seg_pages(seg1);
1326 			for (; vp < evp; vp++) {
1327 				VPP_SETSWAPRES(vp);
1328 			}
1329 		}
1330 	}
1331 	ASSERT(svd1->vpage != NULL || svd1->pageswap == 0);
1332 	size = seg2->s_size;
1333 	seg_free(seg2);
1334 	seg1->s_size += size;
1335 	svd1->swresv += swresv;
1336 	if (svd1->pageprot && (a->prot & PROT_WRITE) &&
1337 	    svd1->type == MAP_SHARED && svd1->vp != NULL &&
1338 	    (svd1->vp->v_flag & VVMEXEC)) {
1339 		ASSERT(vn_is_mapped(svd1->vp, V_WRITE));
1340 		segvn_inval_trcache(svd1->vp);
1341 	}
1342 	return (0);
1343 }
1344 
1345 /*
1346  * Extend the next segment (seg2) to include the
1347  * new segment (seg1 + a), if possible.
1348  * Return 0 on success.
1349  */
1350 static int
1351 segvn_extend_next(
1352 	struct seg *seg1,
1353 	struct seg *seg2,
1354 	struct segvn_crargs *a,
1355 	size_t swresv)
1356 {
1357 	struct segvn_data *svd2 = (struct segvn_data *)seg2->s_data;
1358 	size_t size;
1359 	struct anon_map *amp2;
1360 	struct vpage *new_vpage;
1361 
1362 	/*
1363 	 * We don't need any segment level locks for "segvn" data
1364 	 * since the address space is "write" locked.
1365 	 */
1366 	ASSERT(seg2->s_as && AS_WRITE_HELD(seg2->s_as, &seg2->s_as->a_lock));
1367 
1368 	if (HAT_IS_REGION_COOKIE_VALID(svd2->rcookie)) {
1369 		return (-1);
1370 	}
1371 
1372 	/* first segment is new, try to extend second */
1373 	/* XXX - should also check cred */
1374 	if (svd2->vp != a->vp || svd2->maxprot != a->maxprot ||
1375 	    (!svd2->pageprot && (svd2->prot != a->prot)) ||
1376 	    svd2->type != a->type || svd2->flags != a->flags ||
1377 	    seg2->s_szc != a->szc || svd2->softlockcnt_sbase > 0)
1378 		return (-1);
1379 	/* vp == NULL implies zfod, offset doesn't matter */
1380 	if (svd2->vp != NULL &&
1381 	    (a->offset & PAGEMASK) + seg1->s_size != svd2->offset)
1382 		return (-1);
1383 
1384 	if (svd2->tr_state != SEGVN_TR_OFF) {
1385 		return (-1);
1386 	}
1387 
1388 	amp2 = svd2->amp;
1389 	if (amp2) {
1390 		pgcnt_t newpgs;
1391 
1392 		/*
1393 		 * Segment has private pages, can data structures
1394 		 * be expanded?
1395 		 *
1396 		 * Acquire the anon_map lock to prevent it from changing,
1397 		 * if it is shared.  This ensures that the anon_map
1398 		 * will not change while a thread which has a read/write
1399 		 * lock on an address space references it.
1400 		 *
1401 		 * XXX - Don't need the anon_map lock at all if "refcnt"
1402 		 * is 1.
1403 		 */
1404 		if (svd2->type == MAP_SHARED)
1405 			return (-1);
1406 
1407 		ANON_LOCK_ENTER(&amp2->a_rwlock, RW_WRITER);
1408 		if (amp2->refcnt > 1) {
1409 			ANON_LOCK_EXIT(&amp2->a_rwlock);
1410 			return (-1);
1411 		}
1412 		newpgs = anon_grow(amp2->ahp, &svd2->anon_index,
1413 		    btop(seg2->s_size), btop(seg1->s_size),
1414 		    ANON_NOSLEEP | ANON_GROWDOWN);
1415 
1416 		if (newpgs == 0) {
1417 			ANON_LOCK_EXIT(&amp2->a_rwlock);
1418 			return (-1);
1419 		}
1420 		amp2->size = ptob(newpgs);
1421 		ANON_LOCK_EXIT(&amp2->a_rwlock);
1422 	}
1423 	if (svd2->vpage != NULL) {
1424 		struct vpage *vp, *evp;
1425 		new_vpage =
1426 		    kmem_zalloc(vpgtob(seg_pages(seg1) + seg_pages(seg2)),
1427 		    KM_NOSLEEP);
1428 		if (new_vpage == NULL) {
1429 			/* Not merging segments so adjust anon_index back */
1430 			if (amp2)
1431 				svd2->anon_index += seg_pages(seg1);
1432 			return (-1);
1433 		}
1434 		bcopy(svd2->vpage, new_vpage + seg_pages(seg1),
1435 		    vpgtob(seg_pages(seg2)));
1436 		kmem_free(svd2->vpage, vpgtob(seg_pages(seg2)));
1437 		svd2->vpage = new_vpage;
1438 
1439 		vp = new_vpage;
1440 		evp = vp + seg_pages(seg1);
1441 		for (; vp < evp; vp++)
1442 			VPP_SETPROT(vp, a->prot);
1443 		if (svd2->pageswap && swresv) {
1444 			ASSERT(!(svd2->flags & MAP_NORESERVE));
1445 			ASSERT(swresv == seg1->s_size);
1446 			vp = new_vpage;
1447 			for (; vp < evp; vp++) {
1448 				VPP_SETSWAPRES(vp);
1449 			}
1450 		}
1451 	}
1452 	ASSERT(svd2->vpage != NULL || svd2->pageswap == 0);
1453 	size = seg1->s_size;
1454 	seg_free(seg1);
1455 	seg2->s_size += size;
1456 	seg2->s_base -= size;
1457 	svd2->offset -= size;
1458 	svd2->swresv += swresv;
1459 	if (svd2->pageprot && (a->prot & PROT_WRITE) &&
1460 	    svd2->type == MAP_SHARED && svd2->vp != NULL &&
1461 	    (svd2->vp->v_flag & VVMEXEC)) {
1462 		ASSERT(vn_is_mapped(svd2->vp, V_WRITE));
1463 		segvn_inval_trcache(svd2->vp);
1464 	}
1465 	return (0);
1466 }
1467 
1468 static int
1469 segvn_dup(struct seg *seg, struct seg *newseg)
1470 {
1471 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
1472 	struct segvn_data *newsvd;
1473 	pgcnt_t npages = seg_pages(seg);
1474 	int error = 0;
1475 	uint_t prot;
1476 	size_t len;
1477 	struct anon_map *amp;
1478 
1479 	ASSERT(seg->s_as && AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
1480 	ASSERT(newseg->s_as->a_proc->p_parent == curproc);
1481 
1482 	/*
1483 	 * If segment has anon reserved, reserve more for the new seg.
1484 	 * For a MAP_NORESERVE segment swresv will be a count of all the
1485 	 * allocated anon slots; thus we reserve for the child as many slots
1486 	 * as the parent has allocated. This semantic prevents the child or
1487 	 * parent from dieing during a copy-on-write fault caused by trying
1488 	 * to write a shared pre-existing anon page.
1489 	 */
1490 	if ((len = svd->swresv) != 0) {
1491 		if (anon_resv(svd->swresv) == 0)
1492 			return (ENOMEM);
1493 
1494 		TRACE_3(TR_FAC_VM, TR_ANON_PROC, "anon proc:%p %lu %u",
1495 		    seg, len, 0);
1496 	}
1497 
1498 	newsvd = kmem_cache_alloc(segvn_cache, KM_SLEEP);
1499 
1500 	newseg->s_ops = &segvn_ops;
1501 	newseg->s_data = (void *)newsvd;
1502 	newseg->s_szc = seg->s_szc;
1503 
1504 	newsvd->seg = newseg;
1505 	if ((newsvd->vp = svd->vp) != NULL) {
1506 		VN_HOLD(svd->vp);
1507 		if (svd->type == MAP_SHARED)
1508 			lgrp_shm_policy_init(NULL, svd->vp);
1509 	}
1510 	newsvd->offset = svd->offset;
1511 	newsvd->prot = svd->prot;
1512 	newsvd->maxprot = svd->maxprot;
1513 	newsvd->pageprot = svd->pageprot;
1514 	newsvd->type = svd->type;
1515 	newsvd->cred = svd->cred;
1516 	crhold(newsvd->cred);
1517 	newsvd->advice = svd->advice;
1518 	newsvd->pageadvice = svd->pageadvice;
1519 	newsvd->swresv = svd->swresv;
1520 	newsvd->pageswap = svd->pageswap;
1521 	newsvd->flags = svd->flags;
1522 	newsvd->softlockcnt = 0;
1523 	newsvd->softlockcnt_sbase = 0;
1524 	newsvd->softlockcnt_send = 0;
1525 	newsvd->policy_info = svd->policy_info;
1526 	newsvd->rcookie = HAT_INVALID_REGION_COOKIE;
1527 
1528 	if ((amp = svd->amp) == NULL || svd->tr_state == SEGVN_TR_ON) {
1529 		/*
1530 		 * Not attaching to a shared anon object.
1531 		 */
1532 		ASSERT(!HAT_IS_REGION_COOKIE_VALID(svd->rcookie) ||
1533 		    svd->tr_state == SEGVN_TR_OFF);
1534 		if (svd->tr_state == SEGVN_TR_ON) {
1535 			ASSERT(newsvd->vp != NULL && amp != NULL);
1536 			newsvd->tr_state = SEGVN_TR_INIT;
1537 		} else {
1538 			newsvd->tr_state = svd->tr_state;
1539 		}
1540 		newsvd->amp = NULL;
1541 		newsvd->anon_index = 0;
1542 	} else {
1543 		/* regions for now are only used on pure vnode segments */
1544 		ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
1545 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
1546 		newsvd->tr_state = SEGVN_TR_OFF;
1547 		if (svd->type == MAP_SHARED) {
1548 			newsvd->amp = amp;
1549 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
1550 			amp->refcnt++;
1551 			ANON_LOCK_EXIT(&amp->a_rwlock);
1552 			newsvd->anon_index = svd->anon_index;
1553 		} else {
1554 			int reclaim = 1;
1555 
1556 			/*
1557 			 * Allocate and initialize new anon_map structure.
1558 			 */
1559 			newsvd->amp = anonmap_alloc(newseg->s_size, 0,
1560 			    ANON_SLEEP);
1561 			newsvd->amp->a_szc = newseg->s_szc;
1562 			newsvd->anon_index = 0;
1563 
1564 			/*
1565 			 * We don't have to acquire the anon_map lock
1566 			 * for the new segment (since it belongs to an
1567 			 * address space that is still not associated
1568 			 * with any process), or the segment in the old
1569 			 * address space (since all threads in it
1570 			 * are stopped while duplicating the address space).
1571 			 */
1572 
1573 			/*
1574 			 * The goal of the following code is to make sure that
1575 			 * softlocked pages do not end up as copy on write
1576 			 * pages.  This would cause problems where one
1577 			 * thread writes to a page that is COW and a different
1578 			 * thread in the same process has softlocked it.  The
1579 			 * softlock lock would move away from this process
1580 			 * because the write would cause this process to get
1581 			 * a copy (without the softlock).
1582 			 *
1583 			 * The strategy here is to just break the
1584 			 * sharing on pages that could possibly be
1585 			 * softlocked.
1586 			 */
1587 retry:
1588 			if (svd->softlockcnt) {
1589 				struct anon *ap, *newap;
1590 				size_t i;
1591 				uint_t vpprot;
1592 				page_t *anon_pl[1+1], *pp;
1593 				caddr_t addr;
1594 				ulong_t old_idx = svd->anon_index;
1595 				ulong_t new_idx = 0;
1596 
1597 				/*
1598 				 * The softlock count might be non zero
1599 				 * because some pages are still stuck in the
1600 				 * cache for lazy reclaim. Flush the cache
1601 				 * now. This should drop the count to zero.
1602 				 * [or there is really I/O going on to these
1603 				 * pages]. Note, we have the writers lock so
1604 				 * nothing gets inserted during the flush.
1605 				 */
1606 				if (reclaim == 1) {
1607 					segvn_purge(seg);
1608 					reclaim = 0;
1609 					goto retry;
1610 				}
1611 				i = btopr(seg->s_size);
1612 				addr = seg->s_base;
1613 				/*
1614 				 * XXX break cow sharing using PAGESIZE
1615 				 * pages. They will be relocated into larger
1616 				 * pages at fault time.
1617 				 */
1618 				while (i-- > 0) {
1619 					if (ap = anon_get_ptr(amp->ahp,
1620 					    old_idx)) {
1621 						error = anon_getpage(&ap,
1622 						    &vpprot, anon_pl, PAGESIZE,
1623 						    seg, addr, S_READ,
1624 						    svd->cred);
1625 						if (error) {
1626 							newsvd->vpage = NULL;
1627 							goto out;
1628 						}
1629 						/*
1630 						 * prot need not be computed
1631 						 * below 'cause anon_private is
1632 						 * going to ignore it anyway
1633 						 * as child doesn't inherit
1634 						 * pagelock from parent.
1635 						 */
1636 						prot = svd->pageprot ?
1637 						    VPP_PROT(
1638 						    &svd->vpage[
1639 						    seg_page(seg, addr)])
1640 						    : svd->prot;
1641 						pp = anon_private(&newap,
1642 						    newseg, addr, prot,
1643 						    anon_pl[0],	0,
1644 						    newsvd->cred);
1645 						if (pp == NULL) {
1646 							/* no mem abort */
1647 							newsvd->vpage = NULL;
1648 							error = ENOMEM;
1649 							goto out;
1650 						}
1651 						(void) anon_set_ptr(
1652 						    newsvd->amp->ahp, new_idx,
1653 						    newap, ANON_SLEEP);
1654 						page_unlock(pp);
1655 					}
1656 					addr += PAGESIZE;
1657 					old_idx++;
1658 					new_idx++;
1659 				}
1660 			} else {	/* common case */
1661 				if (seg->s_szc != 0) {
1662 					/*
1663 					 * If at least one of anon slots of a
1664 					 * large page exists then make sure
1665 					 * all anon slots of a large page
1666 					 * exist to avoid partial cow sharing
1667 					 * of a large page in the future.
1668 					 */
1669 					anon_dup_fill_holes(amp->ahp,
1670 					    svd->anon_index, newsvd->amp->ahp,
1671 					    0, seg->s_size, seg->s_szc,
1672 					    svd->vp != NULL);
1673 				} else {
1674 					anon_dup(amp->ahp, svd->anon_index,
1675 					    newsvd->amp->ahp, 0, seg->s_size);
1676 				}
1677 
1678 				hat_clrattr(seg->s_as->a_hat, seg->s_base,
1679 				    seg->s_size, PROT_WRITE);
1680 			}
1681 		}
1682 	}
1683 	/*
1684 	 * If necessary, create a vpage structure for the new segment.
1685 	 * Do not copy any page lock indications.
1686 	 */
1687 	if (svd->vpage != NULL) {
1688 		uint_t i;
1689 		struct vpage *ovp = svd->vpage;
1690 		struct vpage *nvp;
1691 
1692 		nvp = newsvd->vpage =
1693 		    kmem_alloc(vpgtob(npages), KM_SLEEP);
1694 		for (i = 0; i < npages; i++) {
1695 			*nvp = *ovp++;
1696 			VPP_CLRPPLOCK(nvp++);
1697 		}
1698 	} else
1699 		newsvd->vpage = NULL;
1700 
1701 	/* Inform the vnode of the new mapping */
1702 	if (newsvd->vp != NULL) {
1703 		error = VOP_ADDMAP(newsvd->vp, (offset_t)newsvd->offset,
1704 		    newseg->s_as, newseg->s_base, newseg->s_size, newsvd->prot,
1705 		    newsvd->maxprot, newsvd->type, newsvd->cred, NULL);
1706 	}
1707 out:
1708 	if (error == 0 && HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
1709 		ASSERT(newsvd->amp == NULL);
1710 		ASSERT(newsvd->tr_state == SEGVN_TR_OFF);
1711 		newsvd->rcookie = svd->rcookie;
1712 		hat_dup_region(newseg->s_as->a_hat, newsvd->rcookie);
1713 	}
1714 	return (error);
1715 }
1716 
1717 
1718 /*
1719  * callback function to invoke free_vp_pages() for only those pages actually
1720  * processed by the HAT when a shared region is destroyed.
1721  */
1722 extern int free_pages;
1723 
1724 static void
1725 segvn_hat_rgn_unload_callback(caddr_t saddr, caddr_t eaddr, caddr_t r_saddr,
1726     size_t r_size, void *r_obj, u_offset_t r_objoff)
1727 {
1728 	u_offset_t off;
1729 	size_t len;
1730 	vnode_t *vp = (vnode_t *)r_obj;
1731 
1732 	ASSERT(eaddr > saddr);
1733 	ASSERT(saddr >= r_saddr);
1734 	ASSERT(saddr < r_saddr + r_size);
1735 	ASSERT(eaddr > r_saddr);
1736 	ASSERT(eaddr <= r_saddr + r_size);
1737 	ASSERT(vp != NULL);
1738 
1739 	if (!free_pages) {
1740 		return;
1741 	}
1742 
1743 	len = eaddr - saddr;
1744 	off = (saddr - r_saddr) + r_objoff;
1745 	free_vp_pages(vp, off, len);
1746 }
1747 
1748 /*
1749  * callback function used by segvn_unmap to invoke free_vp_pages() for only
1750  * those pages actually processed by the HAT
1751  */
1752 static void
1753 segvn_hat_unload_callback(hat_callback_t *cb)
1754 {
1755 	struct seg		*seg = cb->hcb_data;
1756 	struct segvn_data	*svd = (struct segvn_data *)seg->s_data;
1757 	size_t			len;
1758 	u_offset_t		off;
1759 
1760 	ASSERT(svd->vp != NULL);
1761 	ASSERT(cb->hcb_end_addr > cb->hcb_start_addr);
1762 	ASSERT(cb->hcb_start_addr >= seg->s_base);
1763 
1764 	len = cb->hcb_end_addr - cb->hcb_start_addr;
1765 	off = cb->hcb_start_addr - seg->s_base;
1766 	free_vp_pages(svd->vp, svd->offset + off, len);
1767 }
1768 
1769 /*
1770  * This function determines the number of bytes of swap reserved by
1771  * a segment for which per-page accounting is present. It is used to
1772  * calculate the correct value of a segvn_data's swresv.
1773  */
1774 static size_t
1775 segvn_count_swap_by_vpages(struct seg *seg)
1776 {
1777 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
1778 	struct vpage *vp, *evp;
1779 	size_t nswappages = 0;
1780 
1781 	ASSERT(svd->pageswap);
1782 	ASSERT(svd->vpage != NULL);
1783 
1784 	evp = &svd->vpage[seg_page(seg, seg->s_base + seg->s_size)];
1785 
1786 	for (vp = svd->vpage; vp < evp; vp++) {
1787 		if (VPP_ISSWAPRES(vp))
1788 			nswappages++;
1789 	}
1790 
1791 	return (nswappages << PAGESHIFT);
1792 }
1793 
1794 static int
1795 segvn_unmap(struct seg *seg, caddr_t addr, size_t len)
1796 {
1797 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
1798 	struct segvn_data *nsvd;
1799 	struct seg *nseg;
1800 	struct anon_map *amp;
1801 	pgcnt_t	opages;		/* old segment size in pages */
1802 	pgcnt_t	npages;		/* new segment size in pages */
1803 	pgcnt_t	dpages;		/* pages being deleted (unmapped) */
1804 	hat_callback_t callback;	/* used for free_vp_pages() */
1805 	hat_callback_t *cbp = NULL;
1806 	caddr_t nbase;
1807 	size_t nsize;
1808 	size_t oswresv;
1809 	int reclaim = 1;
1810 
1811 	/*
1812 	 * We don't need any segment level locks for "segvn" data
1813 	 * since the address space is "write" locked.
1814 	 */
1815 	ASSERT(seg->s_as && AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
1816 
1817 	/*
1818 	 * Fail the unmap if pages are SOFTLOCKed through this mapping.
1819 	 * softlockcnt is protected from change by the as write lock.
1820 	 */
1821 retry:
1822 	if (svd->softlockcnt > 0) {
1823 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
1824 
1825 		/*
1826 		 * If this is shared segment non 0 softlockcnt
1827 		 * means locked pages are still in use.
1828 		 */
1829 		if (svd->type == MAP_SHARED) {
1830 			return (EAGAIN);
1831 		}
1832 
1833 		/*
1834 		 * since we do have the writers lock nobody can fill
1835 		 * the cache during the purge. The flush either succeeds
1836 		 * or we still have pending I/Os.
1837 		 */
1838 		if (reclaim == 1) {
1839 			segvn_purge(seg);
1840 			reclaim = 0;
1841 			goto retry;
1842 		}
1843 		return (EAGAIN);
1844 	}
1845 
1846 	/*
1847 	 * Check for bad sizes
1848 	 */
1849 	if (addr < seg->s_base || addr + len > seg->s_base + seg->s_size ||
1850 	    (len & PAGEOFFSET) || ((uintptr_t)addr & PAGEOFFSET)) {
1851 		panic("segvn_unmap");
1852 		/*NOTREACHED*/
1853 	}
1854 
1855 	if (seg->s_szc != 0) {
1856 		size_t pgsz = page_get_pagesize(seg->s_szc);
1857 		int err;
1858 		if (!IS_P2ALIGNED(addr, pgsz) || !IS_P2ALIGNED(len, pgsz)) {
1859 			ASSERT(seg->s_base != addr || seg->s_size != len);
1860 			if (HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
1861 				ASSERT(svd->amp == NULL);
1862 				ASSERT(svd->tr_state == SEGVN_TR_OFF);
1863 				hat_leave_region(seg->s_as->a_hat,
1864 				    svd->rcookie, HAT_REGION_TEXT);
1865 				svd->rcookie = HAT_INVALID_REGION_COOKIE;
1866 				/*
1867 				 * could pass a flag to segvn_demote_range()
1868 				 * below to tell it not to do any unloads but
1869 				 * this case is rare enough to not bother for
1870 				 * now.
1871 				 */
1872 			} else if (svd->tr_state == SEGVN_TR_INIT) {
1873 				svd->tr_state = SEGVN_TR_OFF;
1874 			} else if (svd->tr_state == SEGVN_TR_ON) {
1875 				ASSERT(svd->amp != NULL);
1876 				segvn_textunrepl(seg, 1);
1877 				ASSERT(svd->amp == NULL);
1878 				ASSERT(svd->tr_state == SEGVN_TR_OFF);
1879 			}
1880 			VM_STAT_ADD(segvnvmstats.demoterange[0]);
1881 			err = segvn_demote_range(seg, addr, len, SDR_END, 0);
1882 			if (err == 0) {
1883 				return (IE_RETRY);
1884 			}
1885 			return (err);
1886 		}
1887 	}
1888 
1889 	/* Inform the vnode of the unmapping. */
1890 	if (svd->vp) {
1891 		int error;
1892 
1893 		error = VOP_DELMAP(svd->vp,
1894 		    (offset_t)svd->offset + (uintptr_t)(addr - seg->s_base),
1895 		    seg->s_as, addr, len, svd->prot, svd->maxprot,
1896 		    svd->type, svd->cred, NULL);
1897 
1898 		if (error == EAGAIN)
1899 			return (error);
1900 	}
1901 
1902 	/*
1903 	 * Remove any page locks set through this mapping.
1904 	 * If text replication is not off no page locks could have been
1905 	 * established via this mapping.
1906 	 */
1907 	if (svd->tr_state == SEGVN_TR_OFF) {
1908 		(void) segvn_lockop(seg, addr, len, 0, MC_UNLOCK, NULL, 0);
1909 	}
1910 
1911 	if (HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
1912 		ASSERT(svd->amp == NULL);
1913 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
1914 		ASSERT(svd->type == MAP_PRIVATE);
1915 		hat_leave_region(seg->s_as->a_hat, svd->rcookie,
1916 		    HAT_REGION_TEXT);
1917 		svd->rcookie = HAT_INVALID_REGION_COOKIE;
1918 	} else if (svd->tr_state == SEGVN_TR_ON) {
1919 		ASSERT(svd->amp != NULL);
1920 		ASSERT(svd->pageprot == 0 && !(svd->prot & PROT_WRITE));
1921 		segvn_textunrepl(seg, 1);
1922 		ASSERT(svd->amp == NULL && svd->tr_state == SEGVN_TR_OFF);
1923 	} else {
1924 		if (svd->tr_state != SEGVN_TR_OFF) {
1925 			ASSERT(svd->tr_state == SEGVN_TR_INIT);
1926 			svd->tr_state = SEGVN_TR_OFF;
1927 		}
1928 		/*
1929 		 * Unload any hardware translations in the range to be taken
1930 		 * out. Use a callback to invoke free_vp_pages() effectively.
1931 		 */
1932 		if (svd->vp != NULL && free_pages != 0) {
1933 			callback.hcb_data = seg;
1934 			callback.hcb_function = segvn_hat_unload_callback;
1935 			cbp = &callback;
1936 		}
1937 		hat_unload_callback(seg->s_as->a_hat, addr, len,
1938 		    HAT_UNLOAD_UNMAP, cbp);
1939 
1940 		if (svd->type == MAP_SHARED && svd->vp != NULL &&
1941 		    (svd->vp->v_flag & VVMEXEC) &&
1942 		    ((svd->prot & PROT_WRITE) || svd->pageprot)) {
1943 			segvn_inval_trcache(svd->vp);
1944 		}
1945 	}
1946 
1947 	/*
1948 	 * Check for entire segment
1949 	 */
1950 	if (addr == seg->s_base && len == seg->s_size) {
1951 		seg_free(seg);
1952 		return (0);
1953 	}
1954 
1955 	opages = seg_pages(seg);
1956 	dpages = btop(len);
1957 	npages = opages - dpages;
1958 	amp = svd->amp;
1959 	ASSERT(amp == NULL || amp->a_szc >= seg->s_szc);
1960 
1961 	/*
1962 	 * Check for beginning of segment
1963 	 */
1964 	if (addr == seg->s_base) {
1965 		if (svd->vpage != NULL) {
1966 			size_t nbytes;
1967 			struct vpage *ovpage;
1968 
1969 			ovpage = svd->vpage;	/* keep pointer to vpage */
1970 
1971 			nbytes = vpgtob(npages);
1972 			svd->vpage = kmem_alloc(nbytes, KM_SLEEP);
1973 			bcopy(&ovpage[dpages], svd->vpage, nbytes);
1974 
1975 			/* free up old vpage */
1976 			kmem_free(ovpage, vpgtob(opages));
1977 		}
1978 		if (amp != NULL) {
1979 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
1980 			if (amp->refcnt == 1 || svd->type == MAP_PRIVATE) {
1981 				/*
1982 				 * Shared anon map is no longer in use. Before
1983 				 * freeing its pages purge all entries from
1984 				 * pcache that belong to this amp.
1985 				 */
1986 				if (svd->type == MAP_SHARED) {
1987 					ASSERT(amp->refcnt == 1);
1988 					ASSERT(svd->softlockcnt == 0);
1989 					anonmap_purge(amp);
1990 				}
1991 				/*
1992 				 * Free up now unused parts of anon_map array.
1993 				 */
1994 				if (amp->a_szc == seg->s_szc) {
1995 					if (seg->s_szc != 0) {
1996 						anon_free_pages(amp->ahp,
1997 						    svd->anon_index, len,
1998 						    seg->s_szc);
1999 					} else {
2000 						anon_free(amp->ahp,
2001 						    svd->anon_index,
2002 						    len);
2003 					}
2004 				} else {
2005 					ASSERT(svd->type == MAP_SHARED);
2006 					ASSERT(amp->a_szc > seg->s_szc);
2007 					anon_shmap_free_pages(amp,
2008 					    svd->anon_index, len);
2009 				}
2010 
2011 				/*
2012 				 * Unreserve swap space for the
2013 				 * unmapped chunk of this segment in
2014 				 * case it's MAP_SHARED
2015 				 */
2016 				if (svd->type == MAP_SHARED) {
2017 					anon_unresv_zone(len,
2018 					    seg->s_as->a_proc->p_zone);
2019 					amp->swresv -= len;
2020 				}
2021 			}
2022 			ANON_LOCK_EXIT(&amp->a_rwlock);
2023 			svd->anon_index += dpages;
2024 		}
2025 		if (svd->vp != NULL)
2026 			svd->offset += len;
2027 
2028 		seg->s_base += len;
2029 		seg->s_size -= len;
2030 
2031 		if (svd->swresv) {
2032 			if (svd->flags & MAP_NORESERVE) {
2033 				ASSERT(amp);
2034 				oswresv = svd->swresv;
2035 
2036 				svd->swresv = ptob(anon_pages(amp->ahp,
2037 				    svd->anon_index, npages));
2038 				anon_unresv_zone(oswresv - svd->swresv,
2039 				    seg->s_as->a_proc->p_zone);
2040 				if (SEG_IS_PARTIAL_RESV(seg))
2041 					seg->s_as->a_resvsize -= oswresv -
2042 					    svd->swresv;
2043 			} else {
2044 				size_t unlen;
2045 
2046 				if (svd->pageswap) {
2047 					oswresv = svd->swresv;
2048 					svd->swresv =
2049 					    segvn_count_swap_by_vpages(seg);
2050 					ASSERT(oswresv >= svd->swresv);
2051 					unlen = oswresv - svd->swresv;
2052 				} else {
2053 					svd->swresv -= len;
2054 					ASSERT(svd->swresv == seg->s_size);
2055 					unlen = len;
2056 				}
2057 				anon_unresv_zone(unlen,
2058 				    seg->s_as->a_proc->p_zone);
2059 			}
2060 			TRACE_3(TR_FAC_VM, TR_ANON_PROC, "anon proc:%p %lu %u",
2061 			    seg, len, 0);
2062 		}
2063 
2064 		return (0);
2065 	}
2066 
2067 	/*
2068 	 * Check for end of segment
2069 	 */
2070 	if (addr + len == seg->s_base + seg->s_size) {
2071 		if (svd->vpage != NULL) {
2072 			size_t nbytes;
2073 			struct vpage *ovpage;
2074 
2075 			ovpage = svd->vpage;	/* keep pointer to vpage */
2076 
2077 			nbytes = vpgtob(npages);
2078 			svd->vpage = kmem_alloc(nbytes, KM_SLEEP);
2079 			bcopy(ovpage, svd->vpage, nbytes);
2080 
2081 			/* free up old vpage */
2082 			kmem_free(ovpage, vpgtob(opages));
2083 
2084 		}
2085 		if (amp != NULL) {
2086 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
2087 			if (amp->refcnt == 1 || svd->type == MAP_PRIVATE) {
2088 				/*
2089 				 * Free up now unused parts of anon_map array.
2090 				 */
2091 				ulong_t an_idx = svd->anon_index + npages;
2092 
2093 				/*
2094 				 * Shared anon map is no longer in use. Before
2095 				 * freeing its pages purge all entries from
2096 				 * pcache that belong to this amp.
2097 				 */
2098 				if (svd->type == MAP_SHARED) {
2099 					ASSERT(amp->refcnt == 1);
2100 					ASSERT(svd->softlockcnt == 0);
2101 					anonmap_purge(amp);
2102 				}
2103 
2104 				if (amp->a_szc == seg->s_szc) {
2105 					if (seg->s_szc != 0) {
2106 						anon_free_pages(amp->ahp,
2107 						    an_idx, len,
2108 						    seg->s_szc);
2109 					} else {
2110 						anon_free(amp->ahp, an_idx,
2111 						    len);
2112 					}
2113 				} else {
2114 					ASSERT(svd->type == MAP_SHARED);
2115 					ASSERT(amp->a_szc > seg->s_szc);
2116 					anon_shmap_free_pages(amp,
2117 					    an_idx, len);
2118 				}
2119 
2120 				/*
2121 				 * Unreserve swap space for the
2122 				 * unmapped chunk of this segment in
2123 				 * case it's MAP_SHARED
2124 				 */
2125 				if (svd->type == MAP_SHARED) {
2126 					anon_unresv_zone(len,
2127 					    seg->s_as->a_proc->p_zone);
2128 					amp->swresv -= len;
2129 				}
2130 			}
2131 			ANON_LOCK_EXIT(&amp->a_rwlock);
2132 		}
2133 
2134 		seg->s_size -= len;
2135 
2136 		if (svd->swresv) {
2137 			if (svd->flags & MAP_NORESERVE) {
2138 				ASSERT(amp);
2139 				oswresv = svd->swresv;
2140 				svd->swresv = ptob(anon_pages(amp->ahp,
2141 				    svd->anon_index, npages));
2142 				anon_unresv_zone(oswresv - svd->swresv,
2143 				    seg->s_as->a_proc->p_zone);
2144 				if (SEG_IS_PARTIAL_RESV(seg))
2145 					seg->s_as->a_resvsize -= oswresv -
2146 					    svd->swresv;
2147 			} else {
2148 				size_t unlen;
2149 
2150 				if (svd->pageswap) {
2151 					oswresv = svd->swresv;
2152 					svd->swresv =
2153 					    segvn_count_swap_by_vpages(seg);
2154 					ASSERT(oswresv >= svd->swresv);
2155 					unlen = oswresv - svd->swresv;
2156 				} else {
2157 					svd->swresv -= len;
2158 					ASSERT(svd->swresv == seg->s_size);
2159 					unlen = len;
2160 				}
2161 				anon_unresv_zone(unlen,
2162 				    seg->s_as->a_proc->p_zone);
2163 			}
2164 			TRACE_3(TR_FAC_VM, TR_ANON_PROC,
2165 			    "anon proc:%p %lu %u", seg, len, 0);
2166 		}
2167 
2168 		return (0);
2169 	}
2170 
2171 	/*
2172 	 * The section to go is in the middle of the segment,
2173 	 * have to make it into two segments.  nseg is made for
2174 	 * the high end while seg is cut down at the low end.
2175 	 */
2176 	nbase = addr + len;				/* new seg base */
2177 	nsize = (seg->s_base + seg->s_size) - nbase;	/* new seg size */
2178 	seg->s_size = addr - seg->s_base;		/* shrink old seg */
2179 	nseg = seg_alloc(seg->s_as, nbase, nsize);
2180 	if (nseg == NULL) {
2181 		panic("segvn_unmap seg_alloc");
2182 		/*NOTREACHED*/
2183 	}
2184 	nseg->s_ops = seg->s_ops;
2185 	nsvd = kmem_cache_alloc(segvn_cache, KM_SLEEP);
2186 	nseg->s_data = (void *)nsvd;
2187 	nseg->s_szc = seg->s_szc;
2188 	*nsvd = *svd;
2189 	nsvd->seg = nseg;
2190 	nsvd->offset = svd->offset + (uintptr_t)(nseg->s_base - seg->s_base);
2191 	nsvd->swresv = 0;
2192 	nsvd->softlockcnt = 0;
2193 	nsvd->softlockcnt_sbase = 0;
2194 	nsvd->softlockcnt_send = 0;
2195 	ASSERT(nsvd->rcookie == HAT_INVALID_REGION_COOKIE);
2196 
2197 	if (svd->vp != NULL) {
2198 		VN_HOLD(nsvd->vp);
2199 		if (nsvd->type == MAP_SHARED)
2200 			lgrp_shm_policy_init(NULL, nsvd->vp);
2201 	}
2202 	crhold(svd->cred);
2203 
2204 	if (svd->vpage == NULL) {
2205 		nsvd->vpage = NULL;
2206 	} else {
2207 		/* need to split vpage into two arrays */
2208 		size_t nbytes;
2209 		struct vpage *ovpage;
2210 
2211 		ovpage = svd->vpage;		/* keep pointer to vpage */
2212 
2213 		npages = seg_pages(seg);	/* seg has shrunk */
2214 		nbytes = vpgtob(npages);
2215 		svd->vpage = kmem_alloc(nbytes, KM_SLEEP);
2216 
2217 		bcopy(ovpage, svd->vpage, nbytes);
2218 
2219 		npages = seg_pages(nseg);
2220 		nbytes = vpgtob(npages);
2221 		nsvd->vpage = kmem_alloc(nbytes, KM_SLEEP);
2222 
2223 		bcopy(&ovpage[opages - npages], nsvd->vpage, nbytes);
2224 
2225 		/* free up old vpage */
2226 		kmem_free(ovpage, vpgtob(opages));
2227 	}
2228 
2229 	if (amp == NULL) {
2230 		nsvd->amp = NULL;
2231 		nsvd->anon_index = 0;
2232 	} else {
2233 		/*
2234 		 * Need to create a new anon map for the new segment.
2235 		 * We'll also allocate a new smaller array for the old
2236 		 * smaller segment to save space.
2237 		 */
2238 		opages = btop((uintptr_t)(addr - seg->s_base));
2239 		ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
2240 		if (amp->refcnt == 1 || svd->type == MAP_PRIVATE) {
2241 			/*
2242 			 * Free up now unused parts of anon_map array.
2243 			 */
2244 			ulong_t an_idx = svd->anon_index + opages;
2245 
2246 			/*
2247 			 * Shared anon map is no longer in use. Before
2248 			 * freeing its pages purge all entries from
2249 			 * pcache that belong to this amp.
2250 			 */
2251 			if (svd->type == MAP_SHARED) {
2252 				ASSERT(amp->refcnt == 1);
2253 				ASSERT(svd->softlockcnt == 0);
2254 				anonmap_purge(amp);
2255 			}
2256 
2257 			if (amp->a_szc == seg->s_szc) {
2258 				if (seg->s_szc != 0) {
2259 					anon_free_pages(amp->ahp, an_idx, len,
2260 					    seg->s_szc);
2261 				} else {
2262 					anon_free(amp->ahp, an_idx,
2263 					    len);
2264 				}
2265 			} else {
2266 				ASSERT(svd->type == MAP_SHARED);
2267 				ASSERT(amp->a_szc > seg->s_szc);
2268 				anon_shmap_free_pages(amp, an_idx, len);
2269 			}
2270 
2271 			/*
2272 			 * Unreserve swap space for the
2273 			 * unmapped chunk of this segment in
2274 			 * case it's MAP_SHARED
2275 			 */
2276 			if (svd->type == MAP_SHARED) {
2277 				anon_unresv_zone(len,
2278 				    seg->s_as->a_proc->p_zone);
2279 				amp->swresv -= len;
2280 			}
2281 		}
2282 		nsvd->anon_index = svd->anon_index +
2283 		    btop((uintptr_t)(nseg->s_base - seg->s_base));
2284 		if (svd->type == MAP_SHARED) {
2285 			amp->refcnt++;
2286 			nsvd->amp = amp;
2287 		} else {
2288 			struct anon_map *namp;
2289 			struct anon_hdr *nahp;
2290 
2291 			ASSERT(svd->type == MAP_PRIVATE);
2292 			nahp = anon_create(btop(seg->s_size), ANON_SLEEP);
2293 			namp = anonmap_alloc(nseg->s_size, 0, ANON_SLEEP);
2294 			namp->a_szc = seg->s_szc;
2295 			(void) anon_copy_ptr(amp->ahp, svd->anon_index, nahp,
2296 			    0, btop(seg->s_size), ANON_SLEEP);
2297 			(void) anon_copy_ptr(amp->ahp, nsvd->anon_index,
2298 			    namp->ahp, 0, btop(nseg->s_size), ANON_SLEEP);
2299 			anon_release(amp->ahp, btop(amp->size));
2300 			svd->anon_index = 0;
2301 			nsvd->anon_index = 0;
2302 			amp->ahp = nahp;
2303 			amp->size = seg->s_size;
2304 			nsvd->amp = namp;
2305 		}
2306 		ANON_LOCK_EXIT(&amp->a_rwlock);
2307 	}
2308 	if (svd->swresv) {
2309 		if (svd->flags & MAP_NORESERVE) {
2310 			ASSERT(amp);
2311 			oswresv = svd->swresv;
2312 			svd->swresv = ptob(anon_pages(amp->ahp,
2313 			    svd->anon_index, btop(seg->s_size)));
2314 			nsvd->swresv = ptob(anon_pages(nsvd->amp->ahp,
2315 			    nsvd->anon_index, btop(nseg->s_size)));
2316 			ASSERT(oswresv >= (svd->swresv + nsvd->swresv));
2317 			anon_unresv_zone(oswresv - (svd->swresv + nsvd->swresv),
2318 			    seg->s_as->a_proc->p_zone);
2319 			if (SEG_IS_PARTIAL_RESV(seg))
2320 				seg->s_as->a_resvsize -= oswresv -
2321 				    (svd->swresv + nsvd->swresv);
2322 		} else {
2323 			size_t unlen;
2324 
2325 			if (svd->pageswap) {
2326 				oswresv = svd->swresv;
2327 				svd->swresv = segvn_count_swap_by_vpages(seg);
2328 				nsvd->swresv = segvn_count_swap_by_vpages(nseg);
2329 				ASSERT(oswresv >= (svd->swresv + nsvd->swresv));
2330 				unlen = oswresv - (svd->swresv + nsvd->swresv);
2331 			} else {
2332 				if (seg->s_size + nseg->s_size + len !=
2333 				    svd->swresv) {
2334 					panic("segvn_unmap: cannot split "
2335 					    "swap reservation");
2336 					/*NOTREACHED*/
2337 				}
2338 				svd->swresv = seg->s_size;
2339 				nsvd->swresv = nseg->s_size;
2340 				unlen = len;
2341 			}
2342 			anon_unresv_zone(unlen,
2343 			    seg->s_as->a_proc->p_zone);
2344 		}
2345 		TRACE_3(TR_FAC_VM, TR_ANON_PROC, "anon proc:%p %lu %u",
2346 		    seg, len, 0);
2347 	}
2348 
2349 	return (0);			/* I'm glad that's all over with! */
2350 }
2351 
2352 static void
2353 segvn_free(struct seg *seg)
2354 {
2355 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
2356 	pgcnt_t npages = seg_pages(seg);
2357 	struct anon_map *amp;
2358 	size_t len;
2359 
2360 	/*
2361 	 * We don't need any segment level locks for "segvn" data
2362 	 * since the address space is "write" locked.
2363 	 */
2364 	ASSERT(seg->s_as && AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
2365 	ASSERT(svd->tr_state == SEGVN_TR_OFF);
2366 
2367 	ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
2368 
2369 	/*
2370 	 * Be sure to unlock pages. XXX Why do things get free'ed instead
2371 	 * of unmapped? XXX
2372 	 */
2373 	(void) segvn_lockop(seg, seg->s_base, seg->s_size,
2374 	    0, MC_UNLOCK, NULL, 0);
2375 
2376 	/*
2377 	 * Deallocate the vpage and anon pointers if necessary and possible.
2378 	 */
2379 	if (svd->vpage != NULL) {
2380 		kmem_free(svd->vpage, vpgtob(npages));
2381 		svd->vpage = NULL;
2382 	}
2383 	if ((amp = svd->amp) != NULL) {
2384 		/*
2385 		 * If there are no more references to this anon_map
2386 		 * structure, then deallocate the structure after freeing
2387 		 * up all the anon slot pointers that we can.
2388 		 */
2389 		ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
2390 		ASSERT(amp->a_szc >= seg->s_szc);
2391 		if (--amp->refcnt == 0) {
2392 			if (svd->type == MAP_PRIVATE) {
2393 				/*
2394 				 * Private - we only need to anon_free
2395 				 * the part that this segment refers to.
2396 				 */
2397 				if (seg->s_szc != 0) {
2398 					anon_free_pages(amp->ahp,
2399 					    svd->anon_index, seg->s_size,
2400 					    seg->s_szc);
2401 				} else {
2402 					anon_free(amp->ahp, svd->anon_index,
2403 					    seg->s_size);
2404 				}
2405 			} else {
2406 
2407 				/*
2408 				 * Shared anon map is no longer in use. Before
2409 				 * freeing its pages purge all entries from
2410 				 * pcache that belong to this amp.
2411 				 */
2412 				ASSERT(svd->softlockcnt == 0);
2413 				anonmap_purge(amp);
2414 
2415 				/*
2416 				 * Shared - anon_free the entire
2417 				 * anon_map's worth of stuff and
2418 				 * release any swap reservation.
2419 				 */
2420 				if (amp->a_szc != 0) {
2421 					anon_shmap_free_pages(amp, 0,
2422 					    amp->size);
2423 				} else {
2424 					anon_free(amp->ahp, 0, amp->size);
2425 				}
2426 				if ((len = amp->swresv) != 0) {
2427 					anon_unresv_zone(len,
2428 					    seg->s_as->a_proc->p_zone);
2429 					TRACE_3(TR_FAC_VM, TR_ANON_PROC,
2430 					    "anon proc:%p %lu %u", seg, len, 0);
2431 				}
2432 			}
2433 			svd->amp = NULL;
2434 			ANON_LOCK_EXIT(&amp->a_rwlock);
2435 			anonmap_free(amp);
2436 		} else if (svd->type == MAP_PRIVATE) {
2437 			/*
2438 			 * We had a private mapping which still has
2439 			 * a held anon_map so just free up all the
2440 			 * anon slot pointers that we were using.
2441 			 */
2442 			if (seg->s_szc != 0) {
2443 				anon_free_pages(amp->ahp, svd->anon_index,
2444 				    seg->s_size, seg->s_szc);
2445 			} else {
2446 				anon_free(amp->ahp, svd->anon_index,
2447 				    seg->s_size);
2448 			}
2449 			ANON_LOCK_EXIT(&amp->a_rwlock);
2450 		} else {
2451 			ANON_LOCK_EXIT(&amp->a_rwlock);
2452 		}
2453 	}
2454 
2455 	/*
2456 	 * Release swap reservation.
2457 	 */
2458 	if ((len = svd->swresv) != 0) {
2459 		anon_unresv_zone(svd->swresv,
2460 		    seg->s_as->a_proc->p_zone);
2461 		TRACE_3(TR_FAC_VM, TR_ANON_PROC, "anon proc:%p %lu %u",
2462 		    seg, len, 0);
2463 		if (SEG_IS_PARTIAL_RESV(seg))
2464 			seg->s_as->a_resvsize -= svd->swresv;
2465 		svd->swresv = 0;
2466 	}
2467 	/*
2468 	 * Release claim on vnode, credentials, and finally free the
2469 	 * private data.
2470 	 */
2471 	if (svd->vp != NULL) {
2472 		if (svd->type == MAP_SHARED)
2473 			lgrp_shm_policy_fini(NULL, svd->vp);
2474 		VN_RELE(svd->vp);
2475 		svd->vp = NULL;
2476 	}
2477 	crfree(svd->cred);
2478 	svd->pageprot = 0;
2479 	svd->pageadvice = 0;
2480 	svd->pageswap = 0;
2481 	svd->cred = NULL;
2482 
2483 	/*
2484 	 * Take segfree_syncmtx lock to let segvn_reclaim() finish if it's
2485 	 * still working with this segment without holding as lock (in case
2486 	 * it's called by pcache async thread).
2487 	 */
2488 	ASSERT(svd->softlockcnt == 0);
2489 	mutex_enter(&svd->segfree_syncmtx);
2490 	mutex_exit(&svd->segfree_syncmtx);
2491 
2492 	seg->s_data = NULL;
2493 	kmem_cache_free(segvn_cache, svd);
2494 }
2495 
2496 /*
2497  * Do a F_SOFTUNLOCK call over the range requested.  The range must have
2498  * already been F_SOFTLOCK'ed.
2499  * Caller must always match addr and len of a softunlock with a previous
2500  * softlock with exactly the same addr and len.
2501  */
2502 static void
2503 segvn_softunlock(struct seg *seg, caddr_t addr, size_t len, enum seg_rw rw)
2504 {
2505 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
2506 	page_t *pp;
2507 	caddr_t adr;
2508 	struct vnode *vp;
2509 	u_offset_t offset;
2510 	ulong_t anon_index;
2511 	struct anon_map *amp;
2512 	struct anon *ap = NULL;
2513 
2514 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
2515 	ASSERT(SEGVN_LOCK_HELD(seg->s_as, &svd->lock));
2516 
2517 	if ((amp = svd->amp) != NULL)
2518 		anon_index = svd->anon_index + seg_page(seg, addr);
2519 
2520 	if (HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
2521 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
2522 		hat_unlock_region(seg->s_as->a_hat, addr, len, svd->rcookie);
2523 	} else {
2524 		hat_unlock(seg->s_as->a_hat, addr, len);
2525 	}
2526 	for (adr = addr; adr < addr + len; adr += PAGESIZE) {
2527 		if (amp != NULL) {
2528 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
2529 			if ((ap = anon_get_ptr(amp->ahp, anon_index++))
2530 			    != NULL) {
2531 				swap_xlate(ap, &vp, &offset);
2532 			} else {
2533 				vp = svd->vp;
2534 				offset = svd->offset +
2535 				    (uintptr_t)(adr - seg->s_base);
2536 			}
2537 			ANON_LOCK_EXIT(&amp->a_rwlock);
2538 		} else {
2539 			vp = svd->vp;
2540 			offset = svd->offset +
2541 			    (uintptr_t)(adr - seg->s_base);
2542 		}
2543 
2544 		/*
2545 		 * Use page_find() instead of page_lookup() to
2546 		 * find the page since we know that it is locked.
2547 		 */
2548 		pp = page_find(vp, offset);
2549 		if (pp == NULL) {
2550 			panic(
2551 			    "segvn_softunlock: addr %p, ap %p, vp %p, off %llx",
2552 			    (void *)adr, (void *)ap, (void *)vp, offset);
2553 			/*NOTREACHED*/
2554 		}
2555 
2556 		if (rw == S_WRITE) {
2557 			hat_setrefmod(pp);
2558 			if (seg->s_as->a_vbits)
2559 				hat_setstat(seg->s_as, adr, PAGESIZE,
2560 				    P_REF | P_MOD);
2561 		} else if (rw != S_OTHER) {
2562 			hat_setref(pp);
2563 			if (seg->s_as->a_vbits)
2564 				hat_setstat(seg->s_as, adr, PAGESIZE, P_REF);
2565 		}
2566 		TRACE_3(TR_FAC_VM, TR_SEGVN_FAULT,
2567 		    "segvn_fault:pp %p vp %p offset %llx", pp, vp, offset);
2568 		page_unlock(pp);
2569 	}
2570 	ASSERT(svd->softlockcnt >= btop(len));
2571 	if (!atomic_add_long_nv((ulong_t *)&svd->softlockcnt, -btop(len))) {
2572 		/*
2573 		 * All SOFTLOCKS are gone. Wakeup any waiting
2574 		 * unmappers so they can try again to unmap.
2575 		 * Check for waiters first without the mutex
2576 		 * held so we don't always grab the mutex on
2577 		 * softunlocks.
2578 		 */
2579 		if (AS_ISUNMAPWAIT(seg->s_as)) {
2580 			mutex_enter(&seg->s_as->a_contents);
2581 			if (AS_ISUNMAPWAIT(seg->s_as)) {
2582 				AS_CLRUNMAPWAIT(seg->s_as);
2583 				cv_broadcast(&seg->s_as->a_cv);
2584 			}
2585 			mutex_exit(&seg->s_as->a_contents);
2586 		}
2587 	}
2588 }
2589 
2590 #define	PAGE_HANDLED	((page_t *)-1)
2591 
2592 /*
2593  * Release all the pages in the NULL terminated ppp list
2594  * which haven't already been converted to PAGE_HANDLED.
2595  */
2596 static void
2597 segvn_pagelist_rele(page_t **ppp)
2598 {
2599 	for (; *ppp != NULL; ppp++) {
2600 		if (*ppp != PAGE_HANDLED)
2601 			page_unlock(*ppp);
2602 	}
2603 }
2604 
2605 static int stealcow = 1;
2606 
2607 /*
2608  * Workaround for viking chip bug.  See bug id 1220902.
2609  * To fix this down in pagefault() would require importing so
2610  * much as and segvn code as to be unmaintainable.
2611  */
2612 int enable_mbit_wa = 0;
2613 
2614 /*
2615  * Handles all the dirty work of getting the right
2616  * anonymous pages and loading up the translations.
2617  * This routine is called only from segvn_fault()
2618  * when looping over the range of addresses requested.
2619  *
2620  * The basic algorithm here is:
2621  * 	If this is an anon_zero case
2622  *		Call anon_zero to allocate page
2623  *		Load up translation
2624  *		Return
2625  *	endif
2626  *	If this is an anon page
2627  *		Use anon_getpage to get the page
2628  *	else
2629  *		Find page in pl[] list passed in
2630  *	endif
2631  *	If not a cow
2632  *		Load up the translation to the page
2633  *		return
2634  *	endif
2635  *	Call anon_private to handle cow
2636  *	Load up (writable) translation to new page
2637  */
2638 static faultcode_t
2639 segvn_faultpage(
2640 	struct hat *hat,		/* the hat to use for mapping */
2641 	struct seg *seg,		/* seg_vn of interest */
2642 	caddr_t addr,			/* address in as */
2643 	u_offset_t off,			/* offset in vp */
2644 	struct vpage *vpage,		/* pointer to vpage for vp, off */
2645 	page_t *pl[],			/* object source page pointer */
2646 	uint_t vpprot,			/* access allowed to object pages */
2647 	enum fault_type type,		/* type of fault */
2648 	enum seg_rw rw,			/* type of access at fault */
2649 	int brkcow)			/* we may need to break cow */
2650 {
2651 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
2652 	page_t *pp, **ppp;
2653 	uint_t pageflags = 0;
2654 	page_t *anon_pl[1 + 1];
2655 	page_t *opp = NULL;		/* original page */
2656 	uint_t prot;
2657 	int err;
2658 	int cow;
2659 	int claim;
2660 	int steal = 0;
2661 	ulong_t anon_index;
2662 	struct anon *ap, *oldap;
2663 	struct anon_map *amp;
2664 	int hat_flag = (type == F_SOFTLOCK) ? HAT_LOAD_LOCK : HAT_LOAD;
2665 	int anon_lock = 0;
2666 	anon_sync_obj_t cookie;
2667 
2668 	if (svd->flags & MAP_TEXT) {
2669 		hat_flag |= HAT_LOAD_TEXT;
2670 	}
2671 
2672 	ASSERT(SEGVN_READ_HELD(seg->s_as, &svd->lock));
2673 	ASSERT(seg->s_szc == 0);
2674 	ASSERT(svd->tr_state != SEGVN_TR_INIT);
2675 
2676 	/*
2677 	 * Initialize protection value for this page.
2678 	 * If we have per page protection values check it now.
2679 	 */
2680 	if (svd->pageprot) {
2681 		uint_t protchk;
2682 
2683 		switch (rw) {
2684 		case S_READ:
2685 			protchk = PROT_READ;
2686 			break;
2687 		case S_WRITE:
2688 			protchk = PROT_WRITE;
2689 			break;
2690 		case S_EXEC:
2691 			protchk = PROT_EXEC;
2692 			break;
2693 		case S_OTHER:
2694 		default:
2695 			protchk = PROT_READ | PROT_WRITE | PROT_EXEC;
2696 			break;
2697 		}
2698 
2699 		prot = VPP_PROT(vpage);
2700 		if ((prot & protchk) == 0)
2701 			return (FC_PROT);	/* illegal access type */
2702 	} else {
2703 		prot = svd->prot;
2704 	}
2705 
2706 	if (type == F_SOFTLOCK) {
2707 		atomic_add_long((ulong_t *)&svd->softlockcnt, 1);
2708 	}
2709 
2710 	/*
2711 	 * Always acquire the anon array lock to prevent 2 threads from
2712 	 * allocating separate anon slots for the same "addr".
2713 	 */
2714 
2715 	if ((amp = svd->amp) != NULL) {
2716 		ASSERT(RW_READ_HELD(&amp->a_rwlock));
2717 		anon_index = svd->anon_index + seg_page(seg, addr);
2718 		anon_array_enter(amp, anon_index, &cookie);
2719 		anon_lock = 1;
2720 	}
2721 
2722 	if (svd->vp == NULL && amp != NULL) {
2723 		if ((ap = anon_get_ptr(amp->ahp, anon_index)) == NULL) {
2724 			/*
2725 			 * Allocate a (normally) writable anonymous page of
2726 			 * zeroes. If no advance reservations, reserve now.
2727 			 */
2728 			if (svd->flags & MAP_NORESERVE) {
2729 				if (anon_resv_zone(ptob(1),
2730 				    seg->s_as->a_proc->p_zone)) {
2731 					atomic_add_long(&svd->swresv, ptob(1));
2732 					atomic_add_long(&seg->s_as->a_resvsize,
2733 					    ptob(1));
2734 				} else {
2735 					err = ENOMEM;
2736 					goto out;
2737 				}
2738 			}
2739 			if ((pp = anon_zero(seg, addr, &ap,
2740 			    svd->cred)) == NULL) {
2741 				err = ENOMEM;
2742 				goto out;	/* out of swap space */
2743 			}
2744 			/*
2745 			 * Re-acquire the anon_map lock and
2746 			 * initialize the anon array entry.
2747 			 */
2748 			(void) anon_set_ptr(amp->ahp, anon_index, ap,
2749 			    ANON_SLEEP);
2750 
2751 			ASSERT(pp->p_szc == 0);
2752 
2753 			/*
2754 			 * Handle pages that have been marked for migration
2755 			 */
2756 			if (lgrp_optimizations())
2757 				page_migrate(seg, addr, &pp, 1);
2758 
2759 			if (enable_mbit_wa) {
2760 				if (rw == S_WRITE)
2761 					hat_setmod(pp);
2762 				else if (!hat_ismod(pp))
2763 					prot &= ~PROT_WRITE;
2764 			}
2765 			/*
2766 			 * If AS_PAGLCK is set in a_flags (via memcntl(2)
2767 			 * with MC_LOCKAS, MCL_FUTURE) and this is a
2768 			 * MAP_NORESERVE segment, we may need to
2769 			 * permanently lock the page as it is being faulted
2770 			 * for the first time. The following text applies
2771 			 * only to MAP_NORESERVE segments:
2772 			 *
2773 			 * As per memcntl(2), if this segment was created
2774 			 * after MCL_FUTURE was applied (a "future"
2775 			 * segment), its pages must be locked.  If this
2776 			 * segment existed at MCL_FUTURE application (a
2777 			 * "past" segment), the interface is unclear.
2778 			 *
2779 			 * We decide to lock only if vpage is present:
2780 			 *
2781 			 * - "future" segments will have a vpage array (see
2782 			 *    as_map), and so will be locked as required
2783 			 *
2784 			 * - "past" segments may not have a vpage array,
2785 			 *    depending on whether events (such as
2786 			 *    mprotect) have occurred. Locking if vpage
2787 			 *    exists will preserve legacy behavior.  Not
2788 			 *    locking if vpage is absent, will not break
2789 			 *    the interface or legacy behavior.  Note that
2790 			 *    allocating vpage here if it's absent requires
2791 			 *    upgrading the segvn reader lock, the cost of
2792 			 *    which does not seem worthwhile.
2793 			 *
2794 			 * Usually testing and setting VPP_ISPPLOCK and
2795 			 * VPP_SETPPLOCK requires holding the segvn lock as
2796 			 * writer, but in this case all readers are
2797 			 * serializing on the anon array lock.
2798 			 */
2799 			if (AS_ISPGLCK(seg->s_as) && vpage != NULL &&
2800 			    (svd->flags & MAP_NORESERVE) &&
2801 			    !VPP_ISPPLOCK(vpage)) {
2802 				proc_t *p = seg->s_as->a_proc;
2803 				ASSERT(svd->type == MAP_PRIVATE);
2804 				mutex_enter(&p->p_lock);
2805 				if (rctl_incr_locked_mem(p, NULL, PAGESIZE,
2806 				    1) == 0) {
2807 					claim = VPP_PROT(vpage) & PROT_WRITE;
2808 					if (page_pp_lock(pp, claim, 0)) {
2809 						VPP_SETPPLOCK(vpage);
2810 					} else {
2811 						rctl_decr_locked_mem(p, NULL,
2812 						    PAGESIZE, 1);
2813 					}
2814 				}
2815 				mutex_exit(&p->p_lock);
2816 			}
2817 
2818 			ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
2819 			hat_memload(hat, addr, pp, prot, hat_flag);
2820 
2821 			if (!(hat_flag & HAT_LOAD_LOCK))
2822 				page_unlock(pp);
2823 
2824 			anon_array_exit(&cookie);
2825 			return (0);
2826 		}
2827 	}
2828 
2829 	/*
2830 	 * Obtain the page structure via anon_getpage() if it is
2831 	 * a private copy of an object (the result of a previous
2832 	 * copy-on-write).
2833 	 */
2834 	if (amp != NULL) {
2835 		if ((ap = anon_get_ptr(amp->ahp, anon_index)) != NULL) {
2836 			err = anon_getpage(&ap, &vpprot, anon_pl, PAGESIZE,
2837 			    seg, addr, rw, svd->cred);
2838 			if (err)
2839 				goto out;
2840 
2841 			if (svd->type == MAP_SHARED) {
2842 				/*
2843 				 * If this is a shared mapping to an
2844 				 * anon_map, then ignore the write
2845 				 * permissions returned by anon_getpage().
2846 				 * They apply to the private mappings
2847 				 * of this anon_map.
2848 				 */
2849 				vpprot |= PROT_WRITE;
2850 			}
2851 			opp = anon_pl[0];
2852 		}
2853 	}
2854 
2855 	/*
2856 	 * Search the pl[] list passed in if it is from the
2857 	 * original object (i.e., not a private copy).
2858 	 */
2859 	if (opp == NULL) {
2860 		/*
2861 		 * Find original page.  We must be bringing it in
2862 		 * from the list in pl[].
2863 		 */
2864 		for (ppp = pl; (opp = *ppp) != NULL; ppp++) {
2865 			if (opp == PAGE_HANDLED)
2866 				continue;
2867 			ASSERT(opp->p_vnode == svd->vp); /* XXX */
2868 			if (opp->p_offset == off)
2869 				break;
2870 		}
2871 		if (opp == NULL) {
2872 			panic("segvn_faultpage not found");
2873 			/*NOTREACHED*/
2874 		}
2875 		*ppp = PAGE_HANDLED;
2876 
2877 	}
2878 
2879 	ASSERT(PAGE_LOCKED(opp));
2880 
2881 	TRACE_3(TR_FAC_VM, TR_SEGVN_FAULT,
2882 	    "segvn_fault:pp %p vp %p offset %llx", opp, NULL, 0);
2883 
2884 	/*
2885 	 * The fault is treated as a copy-on-write fault if a
2886 	 * write occurs on a private segment and the object
2887 	 * page (i.e., mapping) is write protected.  We assume
2888 	 * that fatal protection checks have already been made.
2889 	 */
2890 
2891 	if (brkcow) {
2892 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
2893 		cow = !(vpprot & PROT_WRITE);
2894 	} else if (svd->tr_state == SEGVN_TR_ON) {
2895 		/*
2896 		 * If we are doing text replication COW on first touch.
2897 		 */
2898 		ASSERT(amp != NULL);
2899 		ASSERT(svd->vp != NULL);
2900 		ASSERT(rw != S_WRITE);
2901 		cow = (ap == NULL);
2902 	} else {
2903 		cow = 0;
2904 	}
2905 
2906 	/*
2907 	 * If not a copy-on-write case load the translation
2908 	 * and return.
2909 	 */
2910 	if (cow == 0) {
2911 
2912 		/*
2913 		 * Handle pages that have been marked for migration
2914 		 */
2915 		if (lgrp_optimizations())
2916 			page_migrate(seg, addr, &opp, 1);
2917 
2918 		if (IS_VMODSORT(opp->p_vnode) || enable_mbit_wa) {
2919 			if (rw == S_WRITE)
2920 				hat_setmod(opp);
2921 			else if (rw != S_OTHER && !hat_ismod(opp))
2922 				prot &= ~PROT_WRITE;
2923 		}
2924 
2925 		ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE ||
2926 		    (!svd->pageprot && svd->prot == (prot & vpprot)));
2927 		ASSERT(amp == NULL ||
2928 		    svd->rcookie == HAT_INVALID_REGION_COOKIE);
2929 		hat_memload_region(hat, addr, opp, prot & vpprot, hat_flag,
2930 		    svd->rcookie);
2931 
2932 		if (!(hat_flag & HAT_LOAD_LOCK))
2933 			page_unlock(opp);
2934 
2935 		if (anon_lock) {
2936 			anon_array_exit(&cookie);
2937 		}
2938 		return (0);
2939 	}
2940 
2941 	ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
2942 
2943 	hat_setref(opp);
2944 
2945 	ASSERT(amp != NULL && anon_lock);
2946 
2947 	/*
2948 	 * Steal the page only if it isn't a private page
2949 	 * since stealing a private page is not worth the effort.
2950 	 */
2951 	if ((ap = anon_get_ptr(amp->ahp, anon_index)) == NULL)
2952 		steal = 1;
2953 
2954 	/*
2955 	 * Steal the original page if the following conditions are true:
2956 	 *
2957 	 * We are low on memory, the page is not private, page is not large,
2958 	 * not shared, not modified, not `locked' or if we have it `locked'
2959 	 * (i.e., p_cowcnt == 1 and p_lckcnt == 0, which also implies
2960 	 * that the page is not shared) and if it doesn't have any
2961 	 * translations. page_struct_lock isn't needed to look at p_cowcnt
2962 	 * and p_lckcnt because we first get exclusive lock on page.
2963 	 */
2964 	(void) hat_pagesync(opp, HAT_SYNC_DONTZERO | HAT_SYNC_STOPON_MOD);
2965 
2966 	if (stealcow && freemem < minfree && steal && opp->p_szc == 0 &&
2967 	    page_tryupgrade(opp) && !hat_ismod(opp) &&
2968 	    ((opp->p_lckcnt == 0 && opp->p_cowcnt == 0) ||
2969 	    (opp->p_lckcnt == 0 && opp->p_cowcnt == 1 &&
2970 	    vpage != NULL && VPP_ISPPLOCK(vpage)))) {
2971 		/*
2972 		 * Check if this page has other translations
2973 		 * after unloading our translation.
2974 		 */
2975 		if (hat_page_is_mapped(opp)) {
2976 			ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
2977 			hat_unload(seg->s_as->a_hat, addr, PAGESIZE,
2978 			    HAT_UNLOAD);
2979 		}
2980 
2981 		/*
2982 		 * hat_unload() might sync back someone else's recent
2983 		 * modification, so check again.
2984 		 */
2985 		if (!hat_ismod(opp) && !hat_page_is_mapped(opp))
2986 			pageflags |= STEAL_PAGE;
2987 	}
2988 
2989 	/*
2990 	 * If we have a vpage pointer, see if it indicates that we have
2991 	 * ``locked'' the page we map -- if so, tell anon_private to
2992 	 * transfer the locking resource to the new page.
2993 	 *
2994 	 * See Statement at the beginning of segvn_lockop regarding
2995 	 * the way lockcnts/cowcnts are handled during COW.
2996 	 *
2997 	 */
2998 	if (vpage != NULL && VPP_ISPPLOCK(vpage))
2999 		pageflags |= LOCK_PAGE;
3000 
3001 	/*
3002 	 * Allocate a private page and perform the copy.
3003 	 * For MAP_NORESERVE reserve swap space now, unless this
3004 	 * is a cow fault on an existing anon page in which case
3005 	 * MAP_NORESERVE will have made advance reservations.
3006 	 */
3007 	if ((svd->flags & MAP_NORESERVE) && (ap == NULL)) {
3008 		if (anon_resv_zone(ptob(1), seg->s_as->a_proc->p_zone)) {
3009 			atomic_add_long(&svd->swresv, ptob(1));
3010 			atomic_add_long(&seg->s_as->a_resvsize, ptob(1));
3011 		} else {
3012 			page_unlock(opp);
3013 			err = ENOMEM;
3014 			goto out;
3015 		}
3016 	}
3017 	oldap = ap;
3018 	pp = anon_private(&ap, seg, addr, prot, opp, pageflags, svd->cred);
3019 	if (pp == NULL) {
3020 		err = ENOMEM;	/* out of swap space */
3021 		goto out;
3022 	}
3023 
3024 	/*
3025 	 * If we copied away from an anonymous page, then
3026 	 * we are one step closer to freeing up an anon slot.
3027 	 *
3028 	 * NOTE:  The original anon slot must be released while
3029 	 * holding the "anon_map" lock.  This is necessary to prevent
3030 	 * other threads from obtaining a pointer to the anon slot
3031 	 * which may be freed if its "refcnt" is 1.
3032 	 */
3033 	if (oldap != NULL)
3034 		anon_decref(oldap);
3035 
3036 	(void) anon_set_ptr(amp->ahp, anon_index, ap, ANON_SLEEP);
3037 
3038 	/*
3039 	 * Handle pages that have been marked for migration
3040 	 */
3041 	if (lgrp_optimizations())
3042 		page_migrate(seg, addr, &pp, 1);
3043 
3044 	ASSERT(pp->p_szc == 0);
3045 
3046 	ASSERT(!IS_VMODSORT(pp->p_vnode));
3047 	if (enable_mbit_wa) {
3048 		if (rw == S_WRITE)
3049 			hat_setmod(pp);
3050 		else if (!hat_ismod(pp))
3051 			prot &= ~PROT_WRITE;
3052 	}
3053 
3054 	ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
3055 	hat_memload(hat, addr, pp, prot, hat_flag);
3056 
3057 	if (!(hat_flag & HAT_LOAD_LOCK))
3058 		page_unlock(pp);
3059 
3060 	ASSERT(anon_lock);
3061 	anon_array_exit(&cookie);
3062 	return (0);
3063 out:
3064 	if (anon_lock)
3065 		anon_array_exit(&cookie);
3066 
3067 	if (type == F_SOFTLOCK) {
3068 		atomic_add_long((ulong_t *)&svd->softlockcnt, -1);
3069 	}
3070 	return (FC_MAKE_ERR(err));
3071 }
3072 
3073 /*
3074  * relocate a bunch of smaller targ pages into one large repl page. all targ
3075  * pages must be complete pages smaller than replacement pages.
3076  * it's assumed that no page's szc can change since they are all PAGESIZE or
3077  * complete large pages locked SHARED.
3078  */
3079 static void
3080 segvn_relocate_pages(page_t **targ, page_t *replacement)
3081 {
3082 	page_t *pp;
3083 	pgcnt_t repl_npgs, curnpgs;
3084 	pgcnt_t i;
3085 	uint_t repl_szc = replacement->p_szc;
3086 	page_t *first_repl = replacement;
3087 	page_t *repl;
3088 	spgcnt_t npgs;
3089 
3090 	VM_STAT_ADD(segvnvmstats.relocatepages[0]);
3091 
3092 	ASSERT(repl_szc != 0);
3093 	npgs = repl_npgs = page_get_pagecnt(repl_szc);
3094 
3095 	i = 0;
3096 	while (repl_npgs) {
3097 		spgcnt_t nreloc;
3098 		int err;
3099 		ASSERT(replacement != NULL);
3100 		pp = targ[i];
3101 		ASSERT(pp->p_szc < repl_szc);
3102 		ASSERT(PAGE_EXCL(pp));
3103 		ASSERT(!PP_ISFREE(pp));
3104 		curnpgs = page_get_pagecnt(pp->p_szc);
3105 		if (curnpgs == 1) {
3106 			VM_STAT_ADD(segvnvmstats.relocatepages[1]);
3107 			repl = replacement;
3108 			page_sub(&replacement, repl);
3109 			ASSERT(PAGE_EXCL(repl));
3110 			ASSERT(!PP_ISFREE(repl));
3111 			ASSERT(repl->p_szc == repl_szc);
3112 		} else {
3113 			page_t *repl_savepp;
3114 			int j;
3115 			VM_STAT_ADD(segvnvmstats.relocatepages[2]);
3116 			repl_savepp = replacement;
3117 			for (j = 0; j < curnpgs; j++) {
3118 				repl = replacement;
3119 				page_sub(&replacement, repl);
3120 				ASSERT(PAGE_EXCL(repl));
3121 				ASSERT(!PP_ISFREE(repl));
3122 				ASSERT(repl->p_szc == repl_szc);
3123 				ASSERT(page_pptonum(targ[i + j]) ==
3124 				    page_pptonum(targ[i]) + j);
3125 			}
3126 			repl = repl_savepp;
3127 			ASSERT(IS_P2ALIGNED(page_pptonum(repl), curnpgs));
3128 		}
3129 		err = page_relocate(&pp, &repl, 0, 1, &nreloc, NULL);
3130 		if (err || nreloc != curnpgs) {
3131 			panic("segvn_relocate_pages: "
3132 			    "page_relocate failed err=%d curnpgs=%ld "
3133 			    "nreloc=%ld", err, curnpgs, nreloc);
3134 		}
3135 		ASSERT(curnpgs <= repl_npgs);
3136 		repl_npgs -= curnpgs;
3137 		i += curnpgs;
3138 	}
3139 	ASSERT(replacement == NULL);
3140 
3141 	repl = first_repl;
3142 	repl_npgs = npgs;
3143 	for (i = 0; i < repl_npgs; i++) {
3144 		ASSERT(PAGE_EXCL(repl));
3145 		ASSERT(!PP_ISFREE(repl));
3146 		targ[i] = repl;
3147 		page_downgrade(targ[i]);
3148 		repl++;
3149 	}
3150 }
3151 
3152 /*
3153  * Check if all pages in ppa array are complete smaller than szc pages and
3154  * their roots will still be aligned relative to their current size if the
3155  * entire ppa array is relocated into one szc page. If these conditions are
3156  * not met return 0.
3157  *
3158  * If all pages are properly aligned attempt to upgrade their locks
3159  * to exclusive mode. If it fails set *upgrdfail to 1 and return 0.
3160  * upgrdfail was set to 0 by caller.
3161  *
3162  * Return 1 if all pages are aligned and locked exclusively.
3163  *
3164  * If all pages in ppa array happen to be physically contiguous to make one
3165  * szc page and all exclusive locks are successfully obtained promote the page
3166  * size to szc and set *pszc to szc. Return 1 with pages locked shared.
3167  */
3168 static int
3169 segvn_full_szcpages(page_t **ppa, uint_t szc, int *upgrdfail, uint_t *pszc)
3170 {
3171 	page_t *pp;
3172 	pfn_t pfn;
3173 	pgcnt_t totnpgs = page_get_pagecnt(szc);
3174 	pfn_t first_pfn;
3175 	int contig = 1;
3176 	pgcnt_t i;
3177 	pgcnt_t j;
3178 	uint_t curszc;
3179 	pgcnt_t curnpgs;
3180 	int root = 0;
3181 
3182 	ASSERT(szc > 0);
3183 
3184 	VM_STAT_ADD(segvnvmstats.fullszcpages[0]);
3185 
3186 	for (i = 0; i < totnpgs; i++) {
3187 		pp = ppa[i];
3188 		ASSERT(PAGE_SHARED(pp));
3189 		ASSERT(!PP_ISFREE(pp));
3190 		pfn = page_pptonum(pp);
3191 		if (i == 0) {
3192 			if (!IS_P2ALIGNED(pfn, totnpgs)) {
3193 				contig = 0;
3194 			} else {
3195 				first_pfn = pfn;
3196 			}
3197 		} else if (contig && pfn != first_pfn + i) {
3198 			contig = 0;
3199 		}
3200 		if (pp->p_szc == 0) {
3201 			if (root) {
3202 				VM_STAT_ADD(segvnvmstats.fullszcpages[1]);
3203 				return (0);
3204 			}
3205 		} else if (!root) {
3206 			if ((curszc = pp->p_szc) >= szc) {
3207 				VM_STAT_ADD(segvnvmstats.fullszcpages[2]);
3208 				return (0);
3209 			}
3210 			if (curszc == 0) {
3211 				/*
3212 				 * p_szc changed means we don't have all pages
3213 				 * locked. return failure.
3214 				 */
3215 				VM_STAT_ADD(segvnvmstats.fullszcpages[3]);
3216 				return (0);
3217 			}
3218 			curnpgs = page_get_pagecnt(curszc);
3219 			if (!IS_P2ALIGNED(pfn, curnpgs) ||
3220 			    !IS_P2ALIGNED(i, curnpgs)) {
3221 				VM_STAT_ADD(segvnvmstats.fullszcpages[4]);
3222 				return (0);
3223 			}
3224 			root = 1;
3225 		} else {
3226 			ASSERT(i > 0);
3227 			VM_STAT_ADD(segvnvmstats.fullszcpages[5]);
3228 			if (pp->p_szc != curszc) {
3229 				VM_STAT_ADD(segvnvmstats.fullszcpages[6]);
3230 				return (0);
3231 			}
3232 			if (pfn - 1 != page_pptonum(ppa[i - 1])) {
3233 				panic("segvn_full_szcpages: "
3234 				    "large page not physically contiguous");
3235 			}
3236 			if (P2PHASE(pfn, curnpgs) == curnpgs - 1) {
3237 				root = 0;
3238 			}
3239 		}
3240 	}
3241 
3242 	for (i = 0; i < totnpgs; i++) {
3243 		ASSERT(ppa[i]->p_szc < szc);
3244 		if (!page_tryupgrade(ppa[i])) {
3245 			for (j = 0; j < i; j++) {
3246 				page_downgrade(ppa[j]);
3247 			}
3248 			*pszc = ppa[i]->p_szc;
3249 			*upgrdfail = 1;
3250 			VM_STAT_ADD(segvnvmstats.fullszcpages[7]);
3251 			return (0);
3252 		}
3253 	}
3254 
3255 	/*
3256 	 * When a page is put a free cachelist its szc is set to 0.  if file
3257 	 * system reclaimed pages from cachelist targ pages will be physically
3258 	 * contiguous with 0 p_szc.  in this case just upgrade szc of targ
3259 	 * pages without any relocations.
3260 	 * To avoid any hat issues with previous small mappings
3261 	 * hat_pageunload() the target pages first.
3262 	 */
3263 	if (contig) {
3264 		VM_STAT_ADD(segvnvmstats.fullszcpages[8]);
3265 		for (i = 0; i < totnpgs; i++) {
3266 			(void) hat_pageunload(ppa[i], HAT_FORCE_PGUNLOAD);
3267 		}
3268 		for (i = 0; i < totnpgs; i++) {
3269 			ppa[i]->p_szc = szc;
3270 		}
3271 		for (i = 0; i < totnpgs; i++) {
3272 			ASSERT(PAGE_EXCL(ppa[i]));
3273 			page_downgrade(ppa[i]);
3274 		}
3275 		if (pszc != NULL) {
3276 			*pszc = szc;
3277 		}
3278 	}
3279 	VM_STAT_ADD(segvnvmstats.fullszcpages[9]);
3280 	return (1);
3281 }
3282 
3283 /*
3284  * Create physically contiguous pages for [vp, off] - [vp, off +
3285  * page_size(szc)) range and for private segment return them in ppa array.
3286  * Pages are created either via IO or relocations.
3287  *
3288  * Return 1 on success and 0 on failure.
3289  *
3290  * If physically contiguous pages already exist for this range return 1 without
3291  * filling ppa array. Caller initializes ppa[0] as NULL to detect that ppa
3292  * array wasn't filled. In this case caller fills ppa array via VOP_GETPAGE().
3293  */
3294 
3295 static int
3296 segvn_fill_vp_pages(struct segvn_data *svd, vnode_t *vp, u_offset_t off,
3297     uint_t szc, page_t **ppa, page_t **ppplist, uint_t *ret_pszc,
3298     int *downsize)
3299 
3300 {
3301 	page_t *pplist = *ppplist;
3302 	size_t pgsz = page_get_pagesize(szc);
3303 	pgcnt_t pages = btop(pgsz);
3304 	ulong_t start_off = off;
3305 	u_offset_t eoff = off + pgsz;
3306 	spgcnt_t nreloc;
3307 	u_offset_t io_off = off;
3308 	size_t io_len;
3309 	page_t *io_pplist = NULL;
3310 	page_t *done_pplist = NULL;
3311 	pgcnt_t pgidx = 0;
3312 	page_t *pp;
3313 	page_t *newpp;
3314 	page_t *targpp;
3315 	int io_err = 0;
3316 	int i;
3317 	pfn_t pfn;
3318 	ulong_t ppages;
3319 	page_t *targ_pplist = NULL;
3320 	page_t *repl_pplist = NULL;
3321 	page_t *tmp_pplist;
3322 	int nios = 0;
3323 	uint_t pszc;
3324 	struct vattr va;
3325 
3326 	VM_STAT_ADD(segvnvmstats.fill_vp_pages[0]);
3327 
3328 	ASSERT(szc != 0);
3329 	ASSERT(pplist->p_szc == szc);
3330 
3331 	/*
3332 	 * downsize will be set to 1 only if we fail to lock pages. this will
3333 	 * allow subsequent faults to try to relocate the page again. If we
3334 	 * fail due to misalignment don't downsize and let the caller map the
3335 	 * whole region with small mappings to avoid more faults into the area
3336 	 * where we can't get large pages anyway.
3337 	 */
3338 	*downsize = 0;
3339 
3340 	while (off < eoff) {
3341 		newpp = pplist;
3342 		ASSERT(newpp != NULL);
3343 		ASSERT(PAGE_EXCL(newpp));
3344 		ASSERT(!PP_ISFREE(newpp));
3345 		/*
3346 		 * we pass NULL for nrelocp to page_lookup_create()
3347 		 * so that it doesn't relocate. We relocate here
3348 		 * later only after we make sure we can lock all
3349 		 * pages in the range we handle and they are all
3350 		 * aligned.
3351 		 */
3352 		pp = page_lookup_create(vp, off, SE_SHARED, newpp, NULL, 0);
3353 		ASSERT(pp != NULL);
3354 		ASSERT(!PP_ISFREE(pp));
3355 		ASSERT(pp->p_vnode == vp);
3356 		ASSERT(pp->p_offset == off);
3357 		if (pp == newpp) {
3358 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[1]);
3359 			page_sub(&pplist, pp);
3360 			ASSERT(PAGE_EXCL(pp));
3361 			ASSERT(page_iolock_assert(pp));
3362 			page_list_concat(&io_pplist, &pp);
3363 			off += PAGESIZE;
3364 			continue;
3365 		}
3366 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[2]);
3367 		pfn = page_pptonum(pp);
3368 		pszc = pp->p_szc;
3369 		if (pszc >= szc && targ_pplist == NULL && io_pplist == NULL &&
3370 		    IS_P2ALIGNED(pfn, pages)) {
3371 			ASSERT(repl_pplist == NULL);
3372 			ASSERT(done_pplist == NULL);
3373 			ASSERT(pplist == *ppplist);
3374 			page_unlock(pp);
3375 			page_free_replacement_page(pplist);
3376 			page_create_putback(pages);
3377 			*ppplist = NULL;
3378 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[3]);
3379 			return (1);
3380 		}
3381 		if (pszc >= szc) {
3382 			page_unlock(pp);
3383 			segvn_faultvnmpss_align_err1++;
3384 			goto out;
3385 		}
3386 		ppages = page_get_pagecnt(pszc);
3387 		if (!IS_P2ALIGNED(pfn, ppages)) {
3388 			ASSERT(pszc > 0);
3389 			/*
3390 			 * sizing down to pszc won't help.
3391 			 */
3392 			page_unlock(pp);
3393 			segvn_faultvnmpss_align_err2++;
3394 			goto out;
3395 		}
3396 		pfn = page_pptonum(newpp);
3397 		if (!IS_P2ALIGNED(pfn, ppages)) {
3398 			ASSERT(pszc > 0);
3399 			/*
3400 			 * sizing down to pszc won't help.
3401 			 */
3402 			page_unlock(pp);
3403 			segvn_faultvnmpss_align_err3++;
3404 			goto out;
3405 		}
3406 		if (!PAGE_EXCL(pp)) {
3407 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[4]);
3408 			page_unlock(pp);
3409 			*downsize = 1;
3410 			*ret_pszc = pp->p_szc;
3411 			goto out;
3412 		}
3413 		targpp = pp;
3414 		if (io_pplist != NULL) {
3415 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[5]);
3416 			io_len = off - io_off;
3417 			/*
3418 			 * Some file systems like NFS don't check EOF
3419 			 * conditions in VOP_PAGEIO(). Check it here
3420 			 * now that pages are locked SE_EXCL. Any file
3421 			 * truncation will wait until the pages are
3422 			 * unlocked so no need to worry that file will
3423 			 * be truncated after we check its size here.
3424 			 * XXX fix NFS to remove this check.
3425 			 */
3426 			va.va_mask = AT_SIZE;
3427 			if (VOP_GETATTR(vp, &va, ATTR_HINT, svd->cred, NULL)) {
3428 				VM_STAT_ADD(segvnvmstats.fill_vp_pages[6]);
3429 				page_unlock(targpp);
3430 				goto out;
3431 			}
3432 			if (btopr(va.va_size) < btopr(io_off + io_len)) {
3433 				VM_STAT_ADD(segvnvmstats.fill_vp_pages[7]);
3434 				*downsize = 1;
3435 				*ret_pszc = 0;
3436 				page_unlock(targpp);
3437 				goto out;
3438 			}
3439 			io_err = VOP_PAGEIO(vp, io_pplist, io_off, io_len,
3440 				B_READ, svd->cred, NULL);
3441 			if (io_err) {
3442 				VM_STAT_ADD(segvnvmstats.fill_vp_pages[8]);
3443 				page_unlock(targpp);
3444 				if (io_err == EDEADLK) {
3445 					segvn_vmpss_pageio_deadlk_err++;
3446 				}
3447 				goto out;
3448 			}
3449 			nios++;
3450 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[9]);
3451 			while (io_pplist != NULL) {
3452 				pp = io_pplist;
3453 				page_sub(&io_pplist, pp);
3454 				ASSERT(page_iolock_assert(pp));
3455 				page_io_unlock(pp);
3456 				pgidx = (pp->p_offset - start_off) >>
3457 				    PAGESHIFT;
3458 				ASSERT(pgidx < pages);
3459 				ppa[pgidx] = pp;
3460 				page_list_concat(&done_pplist, &pp);
3461 			}
3462 		}
3463 		pp = targpp;
3464 		ASSERT(PAGE_EXCL(pp));
3465 		ASSERT(pp->p_szc <= pszc);
3466 		if (pszc != 0 && !group_page_trylock(pp, SE_EXCL)) {
3467 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[10]);
3468 			page_unlock(pp);
3469 			*downsize = 1;
3470 			*ret_pszc = pp->p_szc;
3471 			goto out;
3472 		}
3473 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[11]);
3474 		/*
3475 		 * page szc chould have changed before the entire group was
3476 		 * locked. reread page szc.
3477 		 */
3478 		pszc = pp->p_szc;
3479 		ppages = page_get_pagecnt(pszc);
3480 
3481 		/* link just the roots */
3482 		page_list_concat(&targ_pplist, &pp);
3483 		page_sub(&pplist, newpp);
3484 		page_list_concat(&repl_pplist, &newpp);
3485 		off += PAGESIZE;
3486 		while (--ppages != 0) {
3487 			newpp = pplist;
3488 			page_sub(&pplist, newpp);
3489 			off += PAGESIZE;
3490 		}
3491 		io_off = off;
3492 	}
3493 	if (io_pplist != NULL) {
3494 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[12]);
3495 		io_len = eoff - io_off;
3496 		va.va_mask = AT_SIZE;
3497 		if (VOP_GETATTR(vp, &va, ATTR_HINT, svd->cred, NULL) != 0) {
3498 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[13]);
3499 			goto out;
3500 		}
3501 		if (btopr(va.va_size) < btopr(io_off + io_len)) {
3502 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[14]);
3503 			*downsize = 1;
3504 			*ret_pszc = 0;
3505 			goto out;
3506 		}
3507 		io_err = VOP_PAGEIO(vp, io_pplist, io_off, io_len,
3508 		    B_READ, svd->cred, NULL);
3509 		if (io_err) {
3510 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[15]);
3511 			if (io_err == EDEADLK) {
3512 				segvn_vmpss_pageio_deadlk_err++;
3513 			}
3514 			goto out;
3515 		}
3516 		nios++;
3517 		while (io_pplist != NULL) {
3518 			pp = io_pplist;
3519 			page_sub(&io_pplist, pp);
3520 			ASSERT(page_iolock_assert(pp));
3521 			page_io_unlock(pp);
3522 			pgidx = (pp->p_offset - start_off) >> PAGESHIFT;
3523 			ASSERT(pgidx < pages);
3524 			ppa[pgidx] = pp;
3525 		}
3526 	}
3527 	/*
3528 	 * we're now bound to succeed or panic.
3529 	 * remove pages from done_pplist. it's not needed anymore.
3530 	 */
3531 	while (done_pplist != NULL) {
3532 		pp = done_pplist;
3533 		page_sub(&done_pplist, pp);
3534 	}
3535 	VM_STAT_ADD(segvnvmstats.fill_vp_pages[16]);
3536 	ASSERT(pplist == NULL);
3537 	*ppplist = NULL;
3538 	while (targ_pplist != NULL) {
3539 		int ret;
3540 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[17]);
3541 		ASSERT(repl_pplist);
3542 		pp = targ_pplist;
3543 		page_sub(&targ_pplist, pp);
3544 		pgidx = (pp->p_offset - start_off) >> PAGESHIFT;
3545 		newpp = repl_pplist;
3546 		page_sub(&repl_pplist, newpp);
3547 #ifdef DEBUG
3548 		pfn = page_pptonum(pp);
3549 		pszc = pp->p_szc;
3550 		ppages = page_get_pagecnt(pszc);
3551 		ASSERT(IS_P2ALIGNED(pfn, ppages));
3552 		pfn = page_pptonum(newpp);
3553 		ASSERT(IS_P2ALIGNED(pfn, ppages));
3554 		ASSERT(P2PHASE(pfn, pages) == pgidx);
3555 #endif
3556 		nreloc = 0;
3557 		ret = page_relocate(&pp, &newpp, 0, 1, &nreloc, NULL);
3558 		if (ret != 0 || nreloc == 0) {
3559 			panic("segvn_fill_vp_pages: "
3560 			    "page_relocate failed");
3561 		}
3562 		pp = newpp;
3563 		while (nreloc-- != 0) {
3564 			ASSERT(PAGE_EXCL(pp));
3565 			ASSERT(pp->p_vnode == vp);
3566 			ASSERT(pgidx ==
3567 			    ((pp->p_offset - start_off) >> PAGESHIFT));
3568 			ppa[pgidx++] = pp;
3569 			pp++;
3570 		}
3571 	}
3572 
3573 	if (svd->type == MAP_PRIVATE) {
3574 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[18]);
3575 		for (i = 0; i < pages; i++) {
3576 			ASSERT(ppa[i] != NULL);
3577 			ASSERT(PAGE_EXCL(ppa[i]));
3578 			ASSERT(ppa[i]->p_vnode == vp);
3579 			ASSERT(ppa[i]->p_offset ==
3580 			    start_off + (i << PAGESHIFT));
3581 			page_downgrade(ppa[i]);
3582 		}
3583 		ppa[pages] = NULL;
3584 	} else {
3585 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[19]);
3586 		/*
3587 		 * the caller will still call VOP_GETPAGE() for shared segments
3588 		 * to check FS write permissions. For private segments we map
3589 		 * file read only anyway.  so no VOP_GETPAGE is needed.
3590 		 */
3591 		for (i = 0; i < pages; i++) {
3592 			ASSERT(ppa[i] != NULL);
3593 			ASSERT(PAGE_EXCL(ppa[i]));
3594 			ASSERT(ppa[i]->p_vnode == vp);
3595 			ASSERT(ppa[i]->p_offset ==
3596 			    start_off + (i << PAGESHIFT));
3597 			page_unlock(ppa[i]);
3598 		}
3599 		ppa[0] = NULL;
3600 	}
3601 
3602 	return (1);
3603 out:
3604 	/*
3605 	 * Do the cleanup. Unlock target pages we didn't relocate. They are
3606 	 * linked on targ_pplist by root pages. reassemble unused replacement
3607 	 * and io pages back to pplist.
3608 	 */
3609 	if (io_pplist != NULL) {
3610 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[20]);
3611 		pp = io_pplist;
3612 		do {
3613 			ASSERT(pp->p_vnode == vp);
3614 			ASSERT(pp->p_offset == io_off);
3615 			ASSERT(page_iolock_assert(pp));
3616 			page_io_unlock(pp);
3617 			page_hashout(pp, NULL);
3618 			io_off += PAGESIZE;
3619 		} while ((pp = pp->p_next) != io_pplist);
3620 		page_list_concat(&io_pplist, &pplist);
3621 		pplist = io_pplist;
3622 	}
3623 	tmp_pplist = NULL;
3624 	while (targ_pplist != NULL) {
3625 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[21]);
3626 		pp = targ_pplist;
3627 		ASSERT(PAGE_EXCL(pp));
3628 		page_sub(&targ_pplist, pp);
3629 
3630 		pszc = pp->p_szc;
3631 		ppages = page_get_pagecnt(pszc);
3632 		ASSERT(IS_P2ALIGNED(page_pptonum(pp), ppages));
3633 
3634 		if (pszc != 0) {
3635 			group_page_unlock(pp);
3636 		}
3637 		page_unlock(pp);
3638 
3639 		pp = repl_pplist;
3640 		ASSERT(pp != NULL);
3641 		ASSERT(PAGE_EXCL(pp));
3642 		ASSERT(pp->p_szc == szc);
3643 		page_sub(&repl_pplist, pp);
3644 
3645 		ASSERT(IS_P2ALIGNED(page_pptonum(pp), ppages));
3646 
3647 		/* relink replacement page */
3648 		page_list_concat(&tmp_pplist, &pp);
3649 		while (--ppages != 0) {
3650 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[22]);
3651 			pp++;
3652 			ASSERT(PAGE_EXCL(pp));
3653 			ASSERT(pp->p_szc == szc);
3654 			page_list_concat(&tmp_pplist, &pp);
3655 		}
3656 	}
3657 	if (tmp_pplist != NULL) {
3658 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[23]);
3659 		page_list_concat(&tmp_pplist, &pplist);
3660 		pplist = tmp_pplist;
3661 	}
3662 	/*
3663 	 * at this point all pages are either on done_pplist or
3664 	 * pplist. They can't be all on done_pplist otherwise
3665 	 * we'd've been done.
3666 	 */
3667 	ASSERT(pplist != NULL);
3668 	if (nios != 0) {
3669 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[24]);
3670 		pp = pplist;
3671 		do {
3672 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[25]);
3673 			ASSERT(pp->p_szc == szc);
3674 			ASSERT(PAGE_EXCL(pp));
3675 			ASSERT(pp->p_vnode != vp);
3676 			pp->p_szc = 0;
3677 		} while ((pp = pp->p_next) != pplist);
3678 
3679 		pp = done_pplist;
3680 		do {
3681 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[26]);
3682 			ASSERT(pp->p_szc == szc);
3683 			ASSERT(PAGE_EXCL(pp));
3684 			ASSERT(pp->p_vnode == vp);
3685 			pp->p_szc = 0;
3686 		} while ((pp = pp->p_next) != done_pplist);
3687 
3688 		while (pplist != NULL) {
3689 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[27]);
3690 			pp = pplist;
3691 			page_sub(&pplist, pp);
3692 			page_free(pp, 0);
3693 		}
3694 
3695 		while (done_pplist != NULL) {
3696 			VM_STAT_ADD(segvnvmstats.fill_vp_pages[28]);
3697 			pp = done_pplist;
3698 			page_sub(&done_pplist, pp);
3699 			page_unlock(pp);
3700 		}
3701 		*ppplist = NULL;
3702 		return (0);
3703 	}
3704 	ASSERT(pplist == *ppplist);
3705 	if (io_err) {
3706 		VM_STAT_ADD(segvnvmstats.fill_vp_pages[29]);
3707 		/*
3708 		 * don't downsize on io error.
3709 		 * see if vop_getpage succeeds.
3710 		 * pplist may still be used in this case
3711 		 * for relocations.
3712 		 */
3713 		return (0);
3714 	}
3715 	VM_STAT_ADD(segvnvmstats.fill_vp_pages[30]);
3716 	page_free_replacement_page(pplist);
3717 	page_create_putback(pages);
3718 	*ppplist = NULL;
3719 	return (0);
3720 }
3721 
3722 int segvn_anypgsz = 0;
3723 
3724 #define	SEGVN_RESTORE_SOFTLOCK_VP(type, pages) 				\
3725 		if ((type) == F_SOFTLOCK) {				\
3726 			atomic_add_long((ulong_t *)&(svd)->softlockcnt, \
3727 			    -(pages));					\
3728 		}
3729 
3730 #define	SEGVN_UPDATE_MODBITS(ppa, pages, rw, prot, vpprot)		\
3731 		if (IS_VMODSORT((ppa)[0]->p_vnode)) {			\
3732 			if ((rw) == S_WRITE) {				\
3733 				for (i = 0; i < (pages); i++) {		\
3734 					ASSERT((ppa)[i]->p_vnode ==	\
3735 					    (ppa)[0]->p_vnode);		\
3736 					hat_setmod((ppa)[i]);		\
3737 				}					\
3738 			} else if ((rw) != S_OTHER &&			\
3739 			    ((prot) & (vpprot) & PROT_WRITE)) {		\
3740 				for (i = 0; i < (pages); i++) {		\
3741 					ASSERT((ppa)[i]->p_vnode ==	\
3742 					    (ppa)[0]->p_vnode);		\
3743 					if (!hat_ismod((ppa)[i])) {	\
3744 						prot &= ~PROT_WRITE;	\
3745 						break;			\
3746 					}				\
3747 				}					\
3748 			}						\
3749 		}
3750 
3751 #ifdef  VM_STATS
3752 
3753 #define	SEGVN_VMSTAT_FLTVNPAGES(idx)					\
3754 		VM_STAT_ADD(segvnvmstats.fltvnpages[(idx)]);
3755 
3756 #else /* VM_STATS */
3757 
3758 #define	SEGVN_VMSTAT_FLTVNPAGES(idx)
3759 
3760 #endif
3761 
3762 static faultcode_t
3763 segvn_fault_vnodepages(struct hat *hat, struct seg *seg, caddr_t lpgaddr,
3764     caddr_t lpgeaddr, enum fault_type type, enum seg_rw rw, caddr_t addr,
3765     caddr_t eaddr, int brkcow)
3766 {
3767 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
3768 	struct anon_map *amp = svd->amp;
3769 	uchar_t segtype = svd->type;
3770 	uint_t szc = seg->s_szc;
3771 	size_t pgsz = page_get_pagesize(szc);
3772 	size_t maxpgsz = pgsz;
3773 	pgcnt_t pages = btop(pgsz);
3774 	pgcnt_t maxpages = pages;
3775 	size_t ppasize = (pages + 1) * sizeof (page_t *);
3776 	caddr_t a = lpgaddr;
3777 	caddr_t	maxlpgeaddr = lpgeaddr;
3778 	u_offset_t off = svd->offset + (uintptr_t)(a - seg->s_base);
3779 	ulong_t aindx = svd->anon_index + seg_page(seg, a);
3780 	struct vpage *vpage = (svd->vpage != NULL) ?
3781 	    &svd->vpage[seg_page(seg, a)] : NULL;
3782 	vnode_t *vp = svd->vp;
3783 	page_t **ppa;
3784 	uint_t	pszc;
3785 	size_t	ppgsz;
3786 	pgcnt_t	ppages;
3787 	faultcode_t err = 0;
3788 	int ierr;
3789 	int vop_size_err = 0;
3790 	uint_t protchk, prot, vpprot;
3791 	ulong_t i;
3792 	int hat_flag = (type == F_SOFTLOCK) ? HAT_LOAD_LOCK : HAT_LOAD;
3793 	anon_sync_obj_t an_cookie;
3794 	enum seg_rw arw;
3795 	int alloc_failed = 0;
3796 	int adjszc_chk;
3797 	struct vattr va;
3798 	int xhat = 0;
3799 	page_t *pplist;
3800 	pfn_t pfn;
3801 	int physcontig;
3802 	int upgrdfail;
3803 	int segvn_anypgsz_vnode = 0; /* for now map vnode with 2 page sizes */
3804 	int tron = (svd->tr_state == SEGVN_TR_ON);
3805 
3806 	ASSERT(szc != 0);
3807 	ASSERT(vp != NULL);
3808 	ASSERT(brkcow == 0 || amp != NULL);
3809 	ASSERT(tron == 0 || amp != NULL);
3810 	ASSERT(enable_mbit_wa == 0); /* no mbit simulations with large pages */
3811 	ASSERT(!(svd->flags & MAP_NORESERVE));
3812 	ASSERT(type != F_SOFTUNLOCK);
3813 	ASSERT(IS_P2ALIGNED(a, maxpgsz));
3814 	ASSERT(amp == NULL || IS_P2ALIGNED(aindx, maxpages));
3815 	ASSERT(SEGVN_LOCK_HELD(seg->s_as, &svd->lock));
3816 	ASSERT(seg->s_szc < NBBY * sizeof (int));
3817 	ASSERT(type != F_SOFTLOCK || lpgeaddr - a == maxpgsz);
3818 	ASSERT(svd->tr_state != SEGVN_TR_INIT);
3819 
3820 	VM_STAT_COND_ADD(type == F_SOFTLOCK, segvnvmstats.fltvnpages[0]);
3821 	VM_STAT_COND_ADD(type != F_SOFTLOCK, segvnvmstats.fltvnpages[1]);
3822 
3823 	if (svd->flags & MAP_TEXT) {
3824 		hat_flag |= HAT_LOAD_TEXT;
3825 	}
3826 
3827 	if (svd->pageprot) {
3828 		switch (rw) {
3829 		case S_READ:
3830 			protchk = PROT_READ;
3831 			break;
3832 		case S_WRITE:
3833 			protchk = PROT_WRITE;
3834 			break;
3835 		case S_EXEC:
3836 			protchk = PROT_EXEC;
3837 			break;
3838 		case S_OTHER:
3839 		default:
3840 			protchk = PROT_READ | PROT_WRITE | PROT_EXEC;
3841 			break;
3842 		}
3843 	} else {
3844 		prot = svd->prot;
3845 		/* caller has already done segment level protection check. */
3846 	}
3847 
3848 	if (seg->s_as->a_hat != hat) {
3849 		xhat = 1;
3850 	}
3851 
3852 	if (rw == S_WRITE && segtype == MAP_PRIVATE) {
3853 		SEGVN_VMSTAT_FLTVNPAGES(2);
3854 		arw = S_READ;
3855 	} else {
3856 		arw = rw;
3857 	}
3858 
3859 	ppa = kmem_alloc(ppasize, KM_SLEEP);
3860 
3861 	VM_STAT_COND_ADD(amp != NULL, segvnvmstats.fltvnpages[3]);
3862 
3863 	for (;;) {
3864 		adjszc_chk = 0;
3865 		for (; a < lpgeaddr; a += pgsz, off += pgsz, aindx += pages) {
3866 			if (adjszc_chk) {
3867 				while (szc < seg->s_szc) {
3868 					uintptr_t e;
3869 					uint_t tszc;
3870 					tszc = segvn_anypgsz_vnode ? szc + 1 :
3871 					    seg->s_szc;
3872 					ppgsz = page_get_pagesize(tszc);
3873 					if (!IS_P2ALIGNED(a, ppgsz) ||
3874 					    ((alloc_failed >> tszc) & 0x1)) {
3875 						break;
3876 					}
3877 					SEGVN_VMSTAT_FLTVNPAGES(4);
3878 					szc = tszc;
3879 					pgsz = ppgsz;
3880 					pages = btop(pgsz);
3881 					e = P2ROUNDUP((uintptr_t)eaddr, pgsz);
3882 					lpgeaddr = (caddr_t)e;
3883 				}
3884 			}
3885 
3886 		again:
3887 			if (IS_P2ALIGNED(a, maxpgsz) && amp != NULL) {
3888 				ASSERT(IS_P2ALIGNED(aindx, maxpages));
3889 				ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
3890 				anon_array_enter(amp, aindx, &an_cookie);
3891 				if (anon_get_ptr(amp->ahp, aindx) != NULL) {
3892 					SEGVN_VMSTAT_FLTVNPAGES(5);
3893 					ASSERT(anon_pages(amp->ahp, aindx,
3894 					    maxpages) == maxpages);
3895 					anon_array_exit(&an_cookie);
3896 					ANON_LOCK_EXIT(&amp->a_rwlock);
3897 					err = segvn_fault_anonpages(hat, seg,
3898 					    a, a + maxpgsz, type, rw,
3899 					    MAX(a, addr),
3900 					    MIN(a + maxpgsz, eaddr), brkcow);
3901 					if (err != 0) {
3902 						SEGVN_VMSTAT_FLTVNPAGES(6);
3903 						goto out;
3904 					}
3905 					if (szc < seg->s_szc) {
3906 						szc = seg->s_szc;
3907 						pgsz = maxpgsz;
3908 						pages = maxpages;
3909 						lpgeaddr = maxlpgeaddr;
3910 					}
3911 					goto next;
3912 				} else {
3913 					ASSERT(anon_pages(amp->ahp, aindx,
3914 					    maxpages) == 0);
3915 					SEGVN_VMSTAT_FLTVNPAGES(7);
3916 					anon_array_exit(&an_cookie);
3917 					ANON_LOCK_EXIT(&amp->a_rwlock);
3918 				}
3919 			}
3920 			ASSERT(!brkcow || IS_P2ALIGNED(a, maxpgsz));
3921 			ASSERT(!tron || IS_P2ALIGNED(a, maxpgsz));
3922 
3923 			if (svd->pageprot != 0 && IS_P2ALIGNED(a, maxpgsz)) {
3924 				ASSERT(vpage != NULL);
3925 				prot = VPP_PROT(vpage);
3926 				ASSERT(sameprot(seg, a, maxpgsz));
3927 				if ((prot & protchk) == 0) {
3928 					SEGVN_VMSTAT_FLTVNPAGES(8);
3929 					err = FC_PROT;
3930 					goto out;
3931 				}
3932 			}
3933 			if (type == F_SOFTLOCK) {
3934 				atomic_add_long((ulong_t *)&svd->softlockcnt,
3935 				    pages);
3936 			}
3937 
3938 			pplist = NULL;
3939 			physcontig = 0;
3940 			ppa[0] = NULL;
3941 			if (!brkcow && !tron && szc &&
3942 			    !page_exists_physcontig(vp, off, szc,
3943 			    segtype == MAP_PRIVATE ? ppa : NULL)) {
3944 				SEGVN_VMSTAT_FLTVNPAGES(9);
3945 				if (page_alloc_pages(vp, seg, a, &pplist, NULL,
3946 				    szc, 0, 0) && type != F_SOFTLOCK) {
3947 					SEGVN_VMSTAT_FLTVNPAGES(10);
3948 					pszc = 0;
3949 					ierr = -1;
3950 					alloc_failed |= (1 << szc);
3951 					break;
3952 				}
3953 				if (pplist != NULL &&
3954 				    vp->v_mpssdata == SEGVN_PAGEIO) {
3955 					int downsize;
3956 					SEGVN_VMSTAT_FLTVNPAGES(11);
3957 					physcontig = segvn_fill_vp_pages(svd,
3958 					    vp, off, szc, ppa, &pplist,
3959 					    &pszc, &downsize);
3960 					ASSERT(!physcontig || pplist == NULL);
3961 					if (!physcontig && downsize &&
3962 					    type != F_SOFTLOCK) {
3963 						ASSERT(pplist == NULL);
3964 						SEGVN_VMSTAT_FLTVNPAGES(12);
3965 						ierr = -1;
3966 						break;
3967 					}
3968 					ASSERT(!physcontig ||
3969 					    segtype == MAP_PRIVATE ||
3970 					    ppa[0] == NULL);
3971 					if (physcontig && ppa[0] == NULL) {
3972 						physcontig = 0;
3973 					}
3974 				}
3975 			} else if (!brkcow && !tron && szc && ppa[0] != NULL) {
3976 				SEGVN_VMSTAT_FLTVNPAGES(13);
3977 				ASSERT(segtype == MAP_PRIVATE);
3978 				physcontig = 1;
3979 			}
3980 
3981 			if (!physcontig) {
3982 				SEGVN_VMSTAT_FLTVNPAGES(14);
3983 				ppa[0] = NULL;
3984 				ierr = VOP_GETPAGE(vp, (offset_t)off, pgsz,
3985 				    &vpprot, ppa, pgsz, seg, a, arw,
3986 				    svd->cred, NULL);
3987 #ifdef DEBUG
3988 				if (ierr == 0) {
3989 					for (i = 0; i < pages; i++) {
3990 						ASSERT(PAGE_LOCKED(ppa[i]));
3991 						ASSERT(!PP_ISFREE(ppa[i]));
3992 						ASSERT(ppa[i]->p_vnode == vp);
3993 						ASSERT(ppa[i]->p_offset ==
3994 						    off + (i << PAGESHIFT));
3995 					}
3996 				}
3997 #endif /* DEBUG */
3998 				if (segtype == MAP_PRIVATE) {
3999 					SEGVN_VMSTAT_FLTVNPAGES(15);
4000 					vpprot &= ~PROT_WRITE;
4001 				}
4002 			} else {
4003 				ASSERT(segtype == MAP_PRIVATE);
4004 				SEGVN_VMSTAT_FLTVNPAGES(16);
4005 				vpprot = PROT_ALL & ~PROT_WRITE;
4006 				ierr = 0;
4007 			}
4008 
4009 			if (ierr != 0) {
4010 				SEGVN_VMSTAT_FLTVNPAGES(17);
4011 				if (pplist != NULL) {
4012 					SEGVN_VMSTAT_FLTVNPAGES(18);
4013 					page_free_replacement_page(pplist);
4014 					page_create_putback(pages);
4015 				}
4016 				SEGVN_RESTORE_SOFTLOCK_VP(type, pages);
4017 				if (a + pgsz <= eaddr) {
4018 					SEGVN_VMSTAT_FLTVNPAGES(19);
4019 					err = FC_MAKE_ERR(ierr);
4020 					goto out;
4021 				}
4022 				va.va_mask = AT_SIZE;
4023 				if (VOP_GETATTR(vp, &va, 0, svd->cred, NULL)) {
4024 					SEGVN_VMSTAT_FLTVNPAGES(20);
4025 					err = FC_MAKE_ERR(EIO);
4026 					goto out;
4027 				}
4028 				if (btopr(va.va_size) >= btopr(off + pgsz)) {
4029 					SEGVN_VMSTAT_FLTVNPAGES(21);
4030 					err = FC_MAKE_ERR(ierr);
4031 					goto out;
4032 				}
4033 				if (btopr(va.va_size) <
4034 				    btopr(off + (eaddr - a))) {
4035 					SEGVN_VMSTAT_FLTVNPAGES(22);
4036 					err = FC_MAKE_ERR(ierr);
4037 					goto out;
4038 				}
4039 				if (brkcow || tron || type == F_SOFTLOCK) {
4040 					/* can't reduce map area */
4041 					SEGVN_VMSTAT_FLTVNPAGES(23);
4042 					vop_size_err = 1;
4043 					goto out;
4044 				}
4045 				SEGVN_VMSTAT_FLTVNPAGES(24);
4046 				ASSERT(szc != 0);
4047 				pszc = 0;
4048 				ierr = -1;
4049 				break;
4050 			}
4051 
4052 			if (amp != NULL) {
4053 				ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
4054 				anon_array_enter(amp, aindx, &an_cookie);
4055 			}
4056 			if (amp != NULL &&
4057 			    anon_get_ptr(amp->ahp, aindx) != NULL) {
4058 				ulong_t taindx = P2ALIGN(aindx, maxpages);
4059 
4060 				SEGVN_VMSTAT_FLTVNPAGES(25);
4061 				ASSERT(anon_pages(amp->ahp, taindx,
4062 				    maxpages) == maxpages);
4063 				for (i = 0; i < pages; i++) {
4064 					page_unlock(ppa[i]);
4065 				}
4066 				anon_array_exit(&an_cookie);
4067 				ANON_LOCK_EXIT(&amp->a_rwlock);
4068 				if (pplist != NULL) {
4069 					page_free_replacement_page(pplist);
4070 					page_create_putback(pages);
4071 				}
4072 				SEGVN_RESTORE_SOFTLOCK_VP(type, pages);
4073 				if (szc < seg->s_szc) {
4074 					SEGVN_VMSTAT_FLTVNPAGES(26);
4075 					/*
4076 					 * For private segments SOFTLOCK
4077 					 * either always breaks cow (any rw
4078 					 * type except S_READ_NOCOW) or
4079 					 * address space is locked as writer
4080 					 * (S_READ_NOCOW case) and anon slots
4081 					 * can't show up on second check.
4082 					 * Therefore if we are here for
4083 					 * SOFTLOCK case it must be a cow
4084 					 * break but cow break never reduces
4085 					 * szc. text replication (tron) in
4086 					 * this case works as cow break.
4087 					 * Thus the assert below.
4088 					 */
4089 					ASSERT(!brkcow && !tron &&
4090 					    type != F_SOFTLOCK);
4091 					pszc = seg->s_szc;
4092 					ierr = -2;
4093 					break;
4094 				}
4095 				ASSERT(IS_P2ALIGNED(a, maxpgsz));
4096 				goto again;
4097 			}
4098 #ifdef DEBUG
4099 			if (amp != NULL) {
4100 				ulong_t taindx = P2ALIGN(aindx, maxpages);
4101 				ASSERT(!anon_pages(amp->ahp, taindx, maxpages));
4102 			}
4103 #endif /* DEBUG */
4104 
4105 			if (brkcow || tron) {
4106 				ASSERT(amp != NULL);
4107 				ASSERT(pplist == NULL);
4108 				ASSERT(szc == seg->s_szc);
4109 				ASSERT(IS_P2ALIGNED(a, maxpgsz));
4110 				ASSERT(IS_P2ALIGNED(aindx, maxpages));
4111 				SEGVN_VMSTAT_FLTVNPAGES(27);
4112 				ierr = anon_map_privatepages(amp, aindx, szc,
4113 				    seg, a, prot, ppa, vpage, segvn_anypgsz,
4114 				    tron ? PG_LOCAL : 0, svd->cred);
4115 				if (ierr != 0) {
4116 					SEGVN_VMSTAT_FLTVNPAGES(28);
4117 					anon_array_exit(&an_cookie);
4118 					ANON_LOCK_EXIT(&amp->a_rwlock);
4119 					SEGVN_RESTORE_SOFTLOCK_VP(type, pages);
4120 					err = FC_MAKE_ERR(ierr);
4121 					goto out;
4122 				}
4123 
4124 				ASSERT(!IS_VMODSORT(ppa[0]->p_vnode));
4125 				/*
4126 				 * p_szc can't be changed for locked
4127 				 * swapfs pages.
4128 				 */
4129 				ASSERT(svd->rcookie ==
4130 				    HAT_INVALID_REGION_COOKIE);
4131 				hat_memload_array(hat, a, pgsz, ppa, prot,
4132 				    hat_flag);
4133 
4134 				if (!(hat_flag & HAT_LOAD_LOCK)) {
4135 					SEGVN_VMSTAT_FLTVNPAGES(29);
4136 					for (i = 0; i < pages; i++) {
4137 						page_unlock(ppa[i]);
4138 					}
4139 				}
4140 				anon_array_exit(&an_cookie);
4141 				ANON_LOCK_EXIT(&amp->a_rwlock);
4142 				goto next;
4143 			}
4144 
4145 			ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE ||
4146 			    (!svd->pageprot && svd->prot == (prot & vpprot)));
4147 
4148 			pfn = page_pptonum(ppa[0]);
4149 			/*
4150 			 * hat_page_demote() needs an SE_EXCL lock on one of
4151 			 * constituent page_t's and it decreases root's p_szc
4152 			 * last. This means if root's p_szc is equal szc and
4153 			 * all its constituent pages are locked
4154 			 * hat_page_demote() that could have changed p_szc to
4155 			 * szc is already done and no new have page_demote()
4156 			 * can start for this large page.
4157 			 */
4158 
4159 			/*
4160 			 * we need to make sure same mapping size is used for
4161 			 * the same address range if there's a possibility the
4162 			 * adddress is already mapped because hat layer panics
4163 			 * when translation is loaded for the range already
4164 			 * mapped with a different page size.  We achieve it
4165 			 * by always using largest page size possible subject
4166 			 * to the constraints of page size, segment page size
4167 			 * and page alignment.  Since mappings are invalidated
4168 			 * when those constraints change and make it
4169 			 * impossible to use previously used mapping size no
4170 			 * mapping size conflicts should happen.
4171 			 */
4172 
4173 		chkszc:
4174 			if ((pszc = ppa[0]->p_szc) == szc &&
4175 			    IS_P2ALIGNED(pfn, pages)) {
4176 
4177 				SEGVN_VMSTAT_FLTVNPAGES(30);
4178 #ifdef DEBUG
4179 				for (i = 0; i < pages; i++) {
4180 					ASSERT(PAGE_LOCKED(ppa[i]));
4181 					ASSERT(!PP_ISFREE(ppa[i]));
4182 					ASSERT(page_pptonum(ppa[i]) ==
4183 					    pfn + i);
4184 					ASSERT(ppa[i]->p_szc == szc);
4185 					ASSERT(ppa[i]->p_vnode == vp);
4186 					ASSERT(ppa[i]->p_offset ==
4187 					    off + (i << PAGESHIFT));
4188 				}
4189 #endif /* DEBUG */
4190 				/*
4191 				 * All pages are of szc we need and they are
4192 				 * all locked so they can't change szc. load
4193 				 * translations.
4194 				 *
4195 				 * if page got promoted since last check
4196 				 * we don't need pplist.
4197 				 */
4198 				if (pplist != NULL) {
4199 					page_free_replacement_page(pplist);
4200 					page_create_putback(pages);
4201 				}
4202 				if (PP_ISMIGRATE(ppa[0])) {
4203 					page_migrate(seg, a, ppa, pages);
4204 				}
4205 				SEGVN_UPDATE_MODBITS(ppa, pages, rw,
4206 				    prot, vpprot);
4207 				if (!xhat) {
4208 					hat_memload_array_region(hat, a, pgsz,
4209 					    ppa, prot & vpprot, hat_flag,
4210 					    svd->rcookie);
4211 				} else {
4212 					/*
4213 					 * avoid large xhat mappings to FS
4214 					 * pages so that hat_page_demote()
4215 					 * doesn't need to check for xhat
4216 					 * large mappings.
4217 					 * Don't use regions with xhats.
4218 					 */
4219 					for (i = 0; i < pages; i++) {
4220 						hat_memload(hat,
4221 						    a + (i << PAGESHIFT),
4222 						    ppa[i], prot & vpprot,
4223 						    hat_flag);
4224 					}
4225 				}
4226 
4227 				if (!(hat_flag & HAT_LOAD_LOCK)) {
4228 					for (i = 0; i < pages; i++) {
4229 						page_unlock(ppa[i]);
4230 					}
4231 				}
4232 				if (amp != NULL) {
4233 					anon_array_exit(&an_cookie);
4234 					ANON_LOCK_EXIT(&amp->a_rwlock);
4235 				}
4236 				goto next;
4237 			}
4238 
4239 			/*
4240 			 * See if upsize is possible.
4241 			 */
4242 			if (pszc > szc && szc < seg->s_szc &&
4243 			    (segvn_anypgsz_vnode || pszc >= seg->s_szc)) {
4244 				pgcnt_t aphase;
4245 				uint_t pszc1 = MIN(pszc, seg->s_szc);
4246 				ppgsz = page_get_pagesize(pszc1);
4247 				ppages = btop(ppgsz);
4248 				aphase = btop(P2PHASE((uintptr_t)a, ppgsz));
4249 
4250 				ASSERT(type != F_SOFTLOCK);
4251 
4252 				SEGVN_VMSTAT_FLTVNPAGES(31);
4253 				if (aphase != P2PHASE(pfn, ppages)) {
4254 					segvn_faultvnmpss_align_err4++;
4255 				} else {
4256 					SEGVN_VMSTAT_FLTVNPAGES(32);
4257 					if (pplist != NULL) {
4258 						page_t *pl = pplist;
4259 						page_free_replacement_page(pl);
4260 						page_create_putback(pages);
4261 					}
4262 					for (i = 0; i < pages; i++) {
4263 						page_unlock(ppa[i]);
4264 					}
4265 					if (amp != NULL) {
4266 						anon_array_exit(&an_cookie);
4267 						ANON_LOCK_EXIT(&amp->a_rwlock);
4268 					}
4269 					pszc = pszc1;
4270 					ierr = -2;
4271 					break;
4272 				}
4273 			}
4274 
4275 			/*
4276 			 * check if we should use smallest mapping size.
4277 			 */
4278 			upgrdfail = 0;
4279 			if (szc == 0 || xhat ||
4280 			    (pszc >= szc &&
4281 			    !IS_P2ALIGNED(pfn, pages)) ||
4282 			    (pszc < szc &&
4283 			    !segvn_full_szcpages(ppa, szc, &upgrdfail,
4284 			    &pszc))) {
4285 
4286 				if (upgrdfail && type != F_SOFTLOCK) {
4287 					/*
4288 					 * segvn_full_szcpages failed to lock
4289 					 * all pages EXCL. Size down.
4290 					 */
4291 					ASSERT(pszc < szc);
4292 
4293 					SEGVN_VMSTAT_FLTVNPAGES(33);
4294 
4295 					if (pplist != NULL) {
4296 						page_t *pl = pplist;
4297 						page_free_replacement_page(pl);
4298 						page_create_putback(pages);
4299 					}
4300 
4301 					for (i = 0; i < pages; i++) {
4302 						page_unlock(ppa[i]);
4303 					}
4304 					if (amp != NULL) {
4305 						anon_array_exit(&an_cookie);
4306 						ANON_LOCK_EXIT(&amp->a_rwlock);
4307 					}
4308 					ierr = -1;
4309 					break;
4310 				}
4311 				if (szc != 0 && !xhat && !upgrdfail) {
4312 					segvn_faultvnmpss_align_err5++;
4313 				}
4314 				SEGVN_VMSTAT_FLTVNPAGES(34);
4315 				if (pplist != NULL) {
4316 					page_free_replacement_page(pplist);
4317 					page_create_putback(pages);
4318 				}
4319 				SEGVN_UPDATE_MODBITS(ppa, pages, rw,
4320 				    prot, vpprot);
4321 				if (upgrdfail && segvn_anypgsz_vnode) {
4322 					/* SOFTLOCK case */
4323 					hat_memload_array_region(hat, a, pgsz,
4324 					    ppa, prot & vpprot, hat_flag,
4325 					    svd->rcookie);
4326 				} else {
4327 					for (i = 0; i < pages; i++) {
4328 						hat_memload_region(hat,
4329 						    a + (i << PAGESHIFT),
4330 						    ppa[i], prot & vpprot,
4331 						    hat_flag, svd->rcookie);
4332 					}
4333 				}
4334 				if (!(hat_flag & HAT_LOAD_LOCK)) {
4335 					for (i = 0; i < pages; i++) {
4336 						page_unlock(ppa[i]);
4337 					}
4338 				}
4339 				if (amp != NULL) {
4340 					anon_array_exit(&an_cookie);
4341 					ANON_LOCK_EXIT(&amp->a_rwlock);
4342 				}
4343 				goto next;
4344 			}
4345 
4346 			if (pszc == szc) {
4347 				/*
4348 				 * segvn_full_szcpages() upgraded pages szc.
4349 				 */
4350 				ASSERT(pszc == ppa[0]->p_szc);
4351 				ASSERT(IS_P2ALIGNED(pfn, pages));
4352 				goto chkszc;
4353 			}
4354 
4355 			if (pszc > szc) {
4356 				kmutex_t *szcmtx;
4357 				SEGVN_VMSTAT_FLTVNPAGES(35);
4358 				/*
4359 				 * p_szc of ppa[0] can change since we haven't
4360 				 * locked all constituent pages. Call
4361 				 * page_lock_szc() to prevent szc changes.
4362 				 * This should be a rare case that happens when
4363 				 * multiple segments use a different page size
4364 				 * to map the same file offsets.
4365 				 */
4366 				szcmtx = page_szc_lock(ppa[0]);
4367 				pszc = ppa[0]->p_szc;
4368 				ASSERT(szcmtx != NULL || pszc == 0);
4369 				ASSERT(ppa[0]->p_szc <= pszc);
4370 				if (pszc <= szc) {
4371 					SEGVN_VMSTAT_FLTVNPAGES(36);
4372 					if (szcmtx != NULL) {
4373 						mutex_exit(szcmtx);
4374 					}
4375 					goto chkszc;
4376 				}
4377 				if (pplist != NULL) {
4378 					/*
4379 					 * page got promoted since last check.
4380 					 * we don't need preaalocated large
4381 					 * page.
4382 					 */
4383 					SEGVN_VMSTAT_FLTVNPAGES(37);
4384 					page_free_replacement_page(pplist);
4385 					page_create_putback(pages);
4386 				}
4387 				SEGVN_UPDATE_MODBITS(ppa, pages, rw,
4388 				    prot, vpprot);
4389 				hat_memload_array_region(hat, a, pgsz, ppa,
4390 				    prot & vpprot, hat_flag, svd->rcookie);
4391 				mutex_exit(szcmtx);
4392 				if (!(hat_flag & HAT_LOAD_LOCK)) {
4393 					for (i = 0; i < pages; i++) {
4394 						page_unlock(ppa[i]);
4395 					}
4396 				}
4397 				if (amp != NULL) {
4398 					anon_array_exit(&an_cookie);
4399 					ANON_LOCK_EXIT(&amp->a_rwlock);
4400 				}
4401 				goto next;
4402 			}
4403 
4404 			/*
4405 			 * if page got demoted since last check
4406 			 * we could have not allocated larger page.
4407 			 * allocate now.
4408 			 */
4409 			if (pplist == NULL &&
4410 			    page_alloc_pages(vp, seg, a, &pplist, NULL,
4411 			    szc, 0, 0) && type != F_SOFTLOCK) {
4412 				SEGVN_VMSTAT_FLTVNPAGES(38);
4413 				for (i = 0; i < pages; i++) {
4414 					page_unlock(ppa[i]);
4415 				}
4416 				if (amp != NULL) {
4417 					anon_array_exit(&an_cookie);
4418 					ANON_LOCK_EXIT(&amp->a_rwlock);
4419 				}
4420 				ierr = -1;
4421 				alloc_failed |= (1 << szc);
4422 				break;
4423 			}
4424 
4425 			SEGVN_VMSTAT_FLTVNPAGES(39);
4426 
4427 			if (pplist != NULL) {
4428 				segvn_relocate_pages(ppa, pplist);
4429 #ifdef DEBUG
4430 			} else {
4431 				ASSERT(type == F_SOFTLOCK);
4432 				SEGVN_VMSTAT_FLTVNPAGES(40);
4433 #endif /* DEBUG */
4434 			}
4435 
4436 			SEGVN_UPDATE_MODBITS(ppa, pages, rw, prot, vpprot);
4437 
4438 			if (pplist == NULL && segvn_anypgsz_vnode == 0) {
4439 				ASSERT(type == F_SOFTLOCK);
4440 				for (i = 0; i < pages; i++) {
4441 					ASSERT(ppa[i]->p_szc < szc);
4442 					hat_memload_region(hat,
4443 					    a + (i << PAGESHIFT),
4444 					    ppa[i], prot & vpprot, hat_flag,
4445 					    svd->rcookie);
4446 				}
4447 			} else {
4448 				ASSERT(pplist != NULL || type == F_SOFTLOCK);
4449 				hat_memload_array_region(hat, a, pgsz, ppa,
4450 				    prot & vpprot, hat_flag, svd->rcookie);
4451 			}
4452 			if (!(hat_flag & HAT_LOAD_LOCK)) {
4453 				for (i = 0; i < pages; i++) {
4454 					ASSERT(PAGE_SHARED(ppa[i]));
4455 					page_unlock(ppa[i]);
4456 				}
4457 			}
4458 			if (amp != NULL) {
4459 				anon_array_exit(&an_cookie);
4460 				ANON_LOCK_EXIT(&amp->a_rwlock);
4461 			}
4462 
4463 		next:
4464 			if (vpage != NULL) {
4465 				vpage += pages;
4466 			}
4467 			adjszc_chk = 1;
4468 		}
4469 		if (a == lpgeaddr)
4470 			break;
4471 		ASSERT(a < lpgeaddr);
4472 
4473 		ASSERT(!brkcow && !tron && type != F_SOFTLOCK);
4474 
4475 		/*
4476 		 * ierr == -1 means we failed to map with a large page.
4477 		 * (either due to allocation/relocation failures or
4478 		 * misalignment with other mappings to this file.
4479 		 *
4480 		 * ierr == -2 means some other thread allocated a large page
4481 		 * after we gave up tp map with a large page.  retry with
4482 		 * larger mapping.
4483 		 */
4484 		ASSERT(ierr == -1 || ierr == -2);
4485 		ASSERT(ierr == -2 || szc != 0);
4486 		ASSERT(ierr == -1 || szc < seg->s_szc);
4487 		if (ierr == -2) {
4488 			SEGVN_VMSTAT_FLTVNPAGES(41);
4489 			ASSERT(pszc > szc && pszc <= seg->s_szc);
4490 			szc = pszc;
4491 		} else if (segvn_anypgsz_vnode) {
4492 			SEGVN_VMSTAT_FLTVNPAGES(42);
4493 			szc--;
4494 		} else {
4495 			SEGVN_VMSTAT_FLTVNPAGES(43);
4496 			ASSERT(pszc < szc);
4497 			/*
4498 			 * other process created pszc large page.
4499 			 * but we still have to drop to 0 szc.
4500 			 */
4501 			szc = 0;
4502 		}
4503 
4504 		pgsz = page_get_pagesize(szc);
4505 		pages = btop(pgsz);
4506 		if (ierr == -2) {
4507 			/*
4508 			 * Size up case. Note lpgaddr may only be needed for
4509 			 * softlock case so we don't adjust it here.
4510 			 */
4511 			a = (caddr_t)P2ALIGN((uintptr_t)a, pgsz);
4512 			ASSERT(a >= lpgaddr);
4513 			lpgeaddr = (caddr_t)P2ROUNDUP((uintptr_t)eaddr, pgsz);
4514 			off = svd->offset + (uintptr_t)(a - seg->s_base);
4515 			aindx = svd->anon_index + seg_page(seg, a);
4516 			vpage = (svd->vpage != NULL) ?
4517 			    &svd->vpage[seg_page(seg, a)] : NULL;
4518 		} else {
4519 			/*
4520 			 * Size down case. Note lpgaddr may only be needed for
4521 			 * softlock case so we don't adjust it here.
4522 			 */
4523 			ASSERT(IS_P2ALIGNED(a, pgsz));
4524 			ASSERT(IS_P2ALIGNED(lpgeaddr, pgsz));
4525 			lpgeaddr = (caddr_t)P2ROUNDUP((uintptr_t)eaddr, pgsz);
4526 			ASSERT(a < lpgeaddr);
4527 			if (a < addr) {
4528 				SEGVN_VMSTAT_FLTVNPAGES(44);
4529 				/*
4530 				 * The beginning of the large page region can
4531 				 * be pulled to the right to make a smaller
4532 				 * region. We haven't yet faulted a single
4533 				 * page.
4534 				 */
4535 				a = (caddr_t)P2ALIGN((uintptr_t)addr, pgsz);
4536 				ASSERT(a >= lpgaddr);
4537 				off = svd->offset +
4538 				    (uintptr_t)(a - seg->s_base);
4539 				aindx = svd->anon_index + seg_page(seg, a);
4540 				vpage = (svd->vpage != NULL) ?
4541 				    &svd->vpage[seg_page(seg, a)] : NULL;
4542 			}
4543 		}
4544 	}
4545 out:
4546 	kmem_free(ppa, ppasize);
4547 	if (!err && !vop_size_err) {
4548 		SEGVN_VMSTAT_FLTVNPAGES(45);
4549 		return (0);
4550 	}
4551 	if (type == F_SOFTLOCK && a > lpgaddr) {
4552 		SEGVN_VMSTAT_FLTVNPAGES(46);
4553 		segvn_softunlock(seg, lpgaddr, a - lpgaddr, S_OTHER);
4554 	}
4555 	if (!vop_size_err) {
4556 		SEGVN_VMSTAT_FLTVNPAGES(47);
4557 		return (err);
4558 	}
4559 	ASSERT(brkcow || tron || type == F_SOFTLOCK);
4560 	/*
4561 	 * Large page end is mapped beyond the end of file and it's a cow
4562 	 * fault (can be a text replication induced cow) or softlock so we can't
4563 	 * reduce the map area.  For now just demote the segment. This should
4564 	 * really only happen if the end of the file changed after the mapping
4565 	 * was established since when large page segments are created we make
4566 	 * sure they don't extend beyond the end of the file.
4567 	 */
4568 	SEGVN_VMSTAT_FLTVNPAGES(48);
4569 
4570 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
4571 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_WRITER);
4572 	err = 0;
4573 	if (seg->s_szc != 0) {
4574 		segvn_fltvnpages_clrszc_cnt++;
4575 		ASSERT(svd->softlockcnt == 0);
4576 		err = segvn_clrszc(seg);
4577 		if (err != 0) {
4578 			segvn_fltvnpages_clrszc_err++;
4579 		}
4580 	}
4581 	ASSERT(err || seg->s_szc == 0);
4582 	SEGVN_LOCK_DOWNGRADE(seg->s_as, &svd->lock);
4583 	/* segvn_fault will do its job as if szc had been zero to begin with */
4584 	return (err == 0 ? IE_RETRY : FC_MAKE_ERR(err));
4585 }
4586 
4587 /*
4588  * This routine will attempt to fault in one large page.
4589  * it will use smaller pages if that fails.
4590  * It should only be called for pure anonymous segments.
4591  */
4592 static faultcode_t
4593 segvn_fault_anonpages(struct hat *hat, struct seg *seg, caddr_t lpgaddr,
4594     caddr_t lpgeaddr, enum fault_type type, enum seg_rw rw, caddr_t addr,
4595     caddr_t eaddr, int brkcow)
4596 {
4597 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
4598 	struct anon_map *amp = svd->amp;
4599 	uchar_t segtype = svd->type;
4600 	uint_t szc = seg->s_szc;
4601 	size_t pgsz = page_get_pagesize(szc);
4602 	size_t maxpgsz = pgsz;
4603 	pgcnt_t pages = btop(pgsz);
4604 	uint_t ppaszc = szc;
4605 	caddr_t a = lpgaddr;
4606 	ulong_t aindx = svd->anon_index + seg_page(seg, a);
4607 	struct vpage *vpage = (svd->vpage != NULL) ?
4608 	    &svd->vpage[seg_page(seg, a)] : NULL;
4609 	page_t **ppa;
4610 	uint_t	ppa_szc;
4611 	faultcode_t err;
4612 	int ierr;
4613 	uint_t protchk, prot, vpprot;
4614 	ulong_t i;
4615 	int hat_flag = (type == F_SOFTLOCK) ? HAT_LOAD_LOCK : HAT_LOAD;
4616 	anon_sync_obj_t cookie;
4617 	int adjszc_chk;
4618 	int pgflags = (svd->tr_state == SEGVN_TR_ON) ? PG_LOCAL : 0;
4619 
4620 	ASSERT(szc != 0);
4621 	ASSERT(amp != NULL);
4622 	ASSERT(enable_mbit_wa == 0); /* no mbit simulations with large pages */
4623 	ASSERT(!(svd->flags & MAP_NORESERVE));
4624 	ASSERT(type != F_SOFTUNLOCK);
4625 	ASSERT(IS_P2ALIGNED(a, maxpgsz));
4626 	ASSERT(!brkcow || svd->tr_state == SEGVN_TR_OFF);
4627 	ASSERT(svd->tr_state != SEGVN_TR_INIT);
4628 
4629 	ASSERT(SEGVN_LOCK_HELD(seg->s_as, &svd->lock));
4630 
4631 	VM_STAT_COND_ADD(type == F_SOFTLOCK, segvnvmstats.fltanpages[0]);
4632 	VM_STAT_COND_ADD(type != F_SOFTLOCK, segvnvmstats.fltanpages[1]);
4633 
4634 	if (svd->flags & MAP_TEXT) {
4635 		hat_flag |= HAT_LOAD_TEXT;
4636 	}
4637 
4638 	if (svd->pageprot) {
4639 		switch (rw) {
4640 		case S_READ:
4641 			protchk = PROT_READ;
4642 			break;
4643 		case S_WRITE:
4644 			protchk = PROT_WRITE;
4645 			break;
4646 		case S_EXEC:
4647 			protchk = PROT_EXEC;
4648 			break;
4649 		case S_OTHER:
4650 		default:
4651 			protchk = PROT_READ | PROT_WRITE | PROT_EXEC;
4652 			break;
4653 		}
4654 		VM_STAT_ADD(segvnvmstats.fltanpages[2]);
4655 	} else {
4656 		prot = svd->prot;
4657 		/* caller has already done segment level protection check. */
4658 	}
4659 
4660 	ppa = kmem_cache_alloc(segvn_szc_cache[ppaszc], KM_SLEEP);
4661 	ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
4662 	for (;;) {
4663 		adjszc_chk = 0;
4664 		for (; a < lpgeaddr; a += pgsz, aindx += pages) {
4665 			if (svd->pageprot != 0 && IS_P2ALIGNED(a, maxpgsz)) {
4666 				VM_STAT_ADD(segvnvmstats.fltanpages[3]);
4667 				ASSERT(vpage != NULL);
4668 				prot = VPP_PROT(vpage);
4669 				ASSERT(sameprot(seg, a, maxpgsz));
4670 				if ((prot & protchk) == 0) {
4671 					err = FC_PROT;
4672 					goto error;
4673 				}
4674 			}
4675 			if (adjszc_chk && IS_P2ALIGNED(a, maxpgsz) &&
4676 			    pgsz < maxpgsz) {
4677 				ASSERT(a > lpgaddr);
4678 				szc = seg->s_szc;
4679 				pgsz = maxpgsz;
4680 				pages = btop(pgsz);
4681 				ASSERT(IS_P2ALIGNED(aindx, pages));
4682 				lpgeaddr = (caddr_t)P2ROUNDUP((uintptr_t)eaddr,
4683 				    pgsz);
4684 			}
4685 			if (type == F_SOFTLOCK) {
4686 				atomic_add_long((ulong_t *)&svd->softlockcnt,
4687 				    pages);
4688 			}
4689 			anon_array_enter(amp, aindx, &cookie);
4690 			ppa_szc = (uint_t)-1;
4691 			ierr = anon_map_getpages(amp, aindx, szc, seg, a,
4692 			    prot, &vpprot, ppa, &ppa_szc, vpage, rw, brkcow,
4693 			    segvn_anypgsz, pgflags, svd->cred);
4694 			if (ierr != 0) {
4695 				anon_array_exit(&cookie);
4696 				VM_STAT_ADD(segvnvmstats.fltanpages[4]);
4697 				if (type == F_SOFTLOCK) {
4698 					atomic_add_long(
4699 					    (ulong_t *)&svd->softlockcnt,
4700 					    -pages);
4701 				}
4702 				if (ierr > 0) {
4703 					VM_STAT_ADD(segvnvmstats.fltanpages[6]);
4704 					err = FC_MAKE_ERR(ierr);
4705 					goto error;
4706 				}
4707 				break;
4708 			}
4709 
4710 			ASSERT(!IS_VMODSORT(ppa[0]->p_vnode));
4711 
4712 			ASSERT(segtype == MAP_SHARED ||
4713 			    ppa[0]->p_szc <= szc);
4714 			ASSERT(segtype == MAP_PRIVATE ||
4715 			    ppa[0]->p_szc >= szc);
4716 
4717 			/*
4718 			 * Handle pages that have been marked for migration
4719 			 */
4720 			if (lgrp_optimizations())
4721 				page_migrate(seg, a, ppa, pages);
4722 
4723 			ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
4724 
4725 			if (segtype == MAP_SHARED) {
4726 				vpprot |= PROT_WRITE;
4727 			}
4728 
4729 			hat_memload_array(hat, a, pgsz, ppa,
4730 			    prot & vpprot, hat_flag);
4731 
4732 			if (hat_flag & HAT_LOAD_LOCK) {
4733 				VM_STAT_ADD(segvnvmstats.fltanpages[7]);
4734 			} else {
4735 				VM_STAT_ADD(segvnvmstats.fltanpages[8]);
4736 				for (i = 0; i < pages; i++)
4737 					page_unlock(ppa[i]);
4738 			}
4739 			if (vpage != NULL)
4740 				vpage += pages;
4741 
4742 			anon_array_exit(&cookie);
4743 			adjszc_chk = 1;
4744 		}
4745 		if (a == lpgeaddr)
4746 			break;
4747 		ASSERT(a < lpgeaddr);
4748 		/*
4749 		 * ierr == -1 means we failed to allocate a large page.
4750 		 * so do a size down operation.
4751 		 *
4752 		 * ierr == -2 means some other process that privately shares
4753 		 * pages with this process has allocated a larger page and we
4754 		 * need to retry with larger pages. So do a size up
4755 		 * operation. This relies on the fact that large pages are
4756 		 * never partially shared i.e. if we share any constituent
4757 		 * page of a large page with another process we must share the
4758 		 * entire large page. Note this cannot happen for SOFTLOCK
4759 		 * case, unless current address (a) is at the beginning of the
4760 		 * next page size boundary because the other process couldn't
4761 		 * have relocated locked pages.
4762 		 */
4763 		ASSERT(ierr == -1 || ierr == -2);
4764 
4765 		if (segvn_anypgsz) {
4766 			ASSERT(ierr == -2 || szc != 0);
4767 			ASSERT(ierr == -1 || szc < seg->s_szc);
4768 			szc = (ierr == -1) ? szc - 1 : szc + 1;
4769 		} else {
4770 			/*
4771 			 * For non COW faults and segvn_anypgsz == 0
4772 			 * we need to be careful not to loop forever
4773 			 * if existing page is found with szc other
4774 			 * than 0 or seg->s_szc. This could be due
4775 			 * to page relocations on behalf of DR or
4776 			 * more likely large page creation. For this
4777 			 * case simply re-size to existing page's szc
4778 			 * if returned by anon_map_getpages().
4779 			 */
4780 			if (ppa_szc == (uint_t)-1) {
4781 				szc = (ierr == -1) ? 0 : seg->s_szc;
4782 			} else {
4783 				ASSERT(ppa_szc <= seg->s_szc);
4784 				ASSERT(ierr == -2 || ppa_szc < szc);
4785 				ASSERT(ierr == -1 || ppa_szc > szc);
4786 				szc = ppa_szc;
4787 			}
4788 		}
4789 
4790 		pgsz = page_get_pagesize(szc);
4791 		pages = btop(pgsz);
4792 		ASSERT(type != F_SOFTLOCK || ierr == -1 ||
4793 		    (IS_P2ALIGNED(a, pgsz) && IS_P2ALIGNED(lpgeaddr, pgsz)));
4794 		if (type == F_SOFTLOCK) {
4795 			/*
4796 			 * For softlocks we cannot reduce the fault area
4797 			 * (calculated based on the largest page size for this
4798 			 * segment) for size down and a is already next
4799 			 * page size aligned as assertted above for size
4800 			 * ups. Therefore just continue in case of softlock.
4801 			 */
4802 			VM_STAT_ADD(segvnvmstats.fltanpages[9]);
4803 			continue; /* keep lint happy */
4804 		} else if (ierr == -2) {
4805 
4806 			/*
4807 			 * Size up case. Note lpgaddr may only be needed for
4808 			 * softlock case so we don't adjust it here.
4809 			 */
4810 			VM_STAT_ADD(segvnvmstats.fltanpages[10]);
4811 			a = (caddr_t)P2ALIGN((uintptr_t)a, pgsz);
4812 			ASSERT(a >= lpgaddr);
4813 			lpgeaddr = (caddr_t)P2ROUNDUP((uintptr_t)eaddr, pgsz);
4814 			aindx = svd->anon_index + seg_page(seg, a);
4815 			vpage = (svd->vpage != NULL) ?
4816 			    &svd->vpage[seg_page(seg, a)] : NULL;
4817 		} else {
4818 			/*
4819 			 * Size down case. Note lpgaddr may only be needed for
4820 			 * softlock case so we don't adjust it here.
4821 			 */
4822 			VM_STAT_ADD(segvnvmstats.fltanpages[11]);
4823 			ASSERT(IS_P2ALIGNED(a, pgsz));
4824 			ASSERT(IS_P2ALIGNED(lpgeaddr, pgsz));
4825 			lpgeaddr = (caddr_t)P2ROUNDUP((uintptr_t)eaddr, pgsz);
4826 			ASSERT(a < lpgeaddr);
4827 			if (a < addr) {
4828 				/*
4829 				 * The beginning of the large page region can
4830 				 * be pulled to the right to make a smaller
4831 				 * region. We haven't yet faulted a single
4832 				 * page.
4833 				 */
4834 				VM_STAT_ADD(segvnvmstats.fltanpages[12]);
4835 				a = (caddr_t)P2ALIGN((uintptr_t)addr, pgsz);
4836 				ASSERT(a >= lpgaddr);
4837 				aindx = svd->anon_index + seg_page(seg, a);
4838 				vpage = (svd->vpage != NULL) ?
4839 				    &svd->vpage[seg_page(seg, a)] : NULL;
4840 			}
4841 		}
4842 	}
4843 	VM_STAT_ADD(segvnvmstats.fltanpages[13]);
4844 	ANON_LOCK_EXIT(&amp->a_rwlock);
4845 	kmem_cache_free(segvn_szc_cache[ppaszc], ppa);
4846 	return (0);
4847 error:
4848 	VM_STAT_ADD(segvnvmstats.fltanpages[14]);
4849 	ANON_LOCK_EXIT(&amp->a_rwlock);
4850 	kmem_cache_free(segvn_szc_cache[ppaszc], ppa);
4851 	if (type == F_SOFTLOCK && a > lpgaddr) {
4852 		VM_STAT_ADD(segvnvmstats.fltanpages[15]);
4853 		segvn_softunlock(seg, lpgaddr, a - lpgaddr, S_OTHER);
4854 	}
4855 	return (err);
4856 }
4857 
4858 int fltadvice = 1;	/* set to free behind pages for sequential access */
4859 
4860 /*
4861  * This routine is called via a machine specific fault handling routine.
4862  * It is also called by software routines wishing to lock or unlock
4863  * a range of addresses.
4864  *
4865  * Here is the basic algorithm:
4866  *	If unlocking
4867  *		Call segvn_softunlock
4868  *		Return
4869  *	endif
4870  *	Checking and set up work
4871  *	If we will need some non-anonymous pages
4872  *		Call VOP_GETPAGE over the range of non-anonymous pages
4873  *	endif
4874  *	Loop over all addresses requested
4875  *		Call segvn_faultpage passing in page list
4876  *		    to load up translations and handle anonymous pages
4877  *	endloop
4878  *	Load up translation to any additional pages in page list not
4879  *	    already handled that fit into this segment
4880  */
4881 static faultcode_t
4882 segvn_fault(struct hat *hat, struct seg *seg, caddr_t addr, size_t len,
4883     enum fault_type type, enum seg_rw rw)
4884 {
4885 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
4886 	page_t **plp, **ppp, *pp;
4887 	u_offset_t off;
4888 	caddr_t a;
4889 	struct vpage *vpage;
4890 	uint_t vpprot, prot;
4891 	int err;
4892 	page_t *pl[PVN_GETPAGE_NUM + 1];
4893 	size_t plsz, pl_alloc_sz;
4894 	size_t page;
4895 	ulong_t anon_index;
4896 	struct anon_map *amp;
4897 	int dogetpage = 0;
4898 	caddr_t	lpgaddr, lpgeaddr;
4899 	size_t pgsz;
4900 	anon_sync_obj_t cookie;
4901 	int brkcow = BREAK_COW_SHARE(rw, type, svd->type);
4902 
4903 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
4904 	ASSERT(svd->amp == NULL || svd->rcookie == HAT_INVALID_REGION_COOKIE);
4905 
4906 	/*
4907 	 * First handle the easy stuff
4908 	 */
4909 	if (type == F_SOFTUNLOCK) {
4910 		if (rw == S_READ_NOCOW) {
4911 			rw = S_READ;
4912 			ASSERT(AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
4913 		}
4914 		SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
4915 		pgsz = (seg->s_szc == 0) ? PAGESIZE :
4916 		    page_get_pagesize(seg->s_szc);
4917 		VM_STAT_COND_ADD(pgsz > PAGESIZE, segvnvmstats.fltanpages[16]);
4918 		CALC_LPG_REGION(pgsz, seg, addr, len, lpgaddr, lpgeaddr);
4919 		segvn_softunlock(seg, lpgaddr, lpgeaddr - lpgaddr, rw);
4920 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
4921 		return (0);
4922 	}
4923 
4924 	ASSERT(svd->tr_state == SEGVN_TR_OFF ||
4925 	    !HAT_IS_REGION_COOKIE_VALID(svd->rcookie));
4926 	if (brkcow == 0) {
4927 		if (svd->tr_state == SEGVN_TR_INIT) {
4928 			SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_WRITER);
4929 			if (svd->tr_state == SEGVN_TR_INIT) {
4930 				ASSERT(svd->vp != NULL && svd->amp == NULL);
4931 				ASSERT(svd->flags & MAP_TEXT);
4932 				ASSERT(svd->type == MAP_PRIVATE);
4933 				segvn_textrepl(seg);
4934 				ASSERT(svd->tr_state != SEGVN_TR_INIT);
4935 				ASSERT(svd->tr_state != SEGVN_TR_ON ||
4936 				    svd->amp != NULL);
4937 			}
4938 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
4939 		}
4940 	} else if (svd->tr_state != SEGVN_TR_OFF) {
4941 		SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_WRITER);
4942 
4943 		if (rw == S_WRITE && svd->tr_state != SEGVN_TR_OFF) {
4944 			ASSERT(!svd->pageprot && !(svd->prot & PROT_WRITE));
4945 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
4946 			return (FC_PROT);
4947 		}
4948 
4949 		if (svd->tr_state == SEGVN_TR_ON) {
4950 			ASSERT(svd->vp != NULL && svd->amp != NULL);
4951 			segvn_textunrepl(seg, 0);
4952 			ASSERT(svd->amp == NULL &&
4953 			    svd->tr_state == SEGVN_TR_OFF);
4954 		} else if (svd->tr_state != SEGVN_TR_OFF) {
4955 			svd->tr_state = SEGVN_TR_OFF;
4956 		}
4957 		ASSERT(svd->amp == NULL && svd->tr_state == SEGVN_TR_OFF);
4958 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
4959 	}
4960 
4961 top:
4962 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
4963 
4964 	/*
4965 	 * If we have the same protections for the entire segment,
4966 	 * insure that the access being attempted is legitimate.
4967 	 */
4968 
4969 	if (svd->pageprot == 0) {
4970 		uint_t protchk;
4971 
4972 		switch (rw) {
4973 		case S_READ:
4974 		case S_READ_NOCOW:
4975 			protchk = PROT_READ;
4976 			break;
4977 		case S_WRITE:
4978 			protchk = PROT_WRITE;
4979 			break;
4980 		case S_EXEC:
4981 			protchk = PROT_EXEC;
4982 			break;
4983 		case S_OTHER:
4984 		default:
4985 			protchk = PROT_READ | PROT_WRITE | PROT_EXEC;
4986 			break;
4987 		}
4988 
4989 		if ((svd->prot & protchk) == 0) {
4990 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
4991 			return (FC_PROT);	/* illegal access type */
4992 		}
4993 	}
4994 
4995 	if (brkcow && HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
4996 		/* this must be SOFTLOCK S_READ fault */
4997 		ASSERT(svd->amp == NULL);
4998 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
4999 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5000 		SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_WRITER);
5001 		if (HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
5002 			/*
5003 			 * this must be the first ever non S_READ_NOCOW
5004 			 * softlock for this segment.
5005 			 */
5006 			ASSERT(svd->softlockcnt == 0);
5007 			hat_leave_region(seg->s_as->a_hat, svd->rcookie,
5008 			    HAT_REGION_TEXT);
5009 			svd->rcookie = HAT_INVALID_REGION_COOKIE;
5010 		}
5011 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5012 		goto top;
5013 	}
5014 
5015 	/*
5016 	 * We can't allow the long term use of softlocks for vmpss segments,
5017 	 * because in some file truncation cases we should be able to demote
5018 	 * the segment, which requires that there are no softlocks.  The
5019 	 * only case where it's ok to allow a SOFTLOCK fault against a vmpss
5020 	 * segment is S_READ_NOCOW, where the caller holds the address space
5021 	 * locked as writer and calls softunlock before dropping the as lock.
5022 	 * S_READ_NOCOW is used by /proc to read memory from another user.
5023 	 *
5024 	 * Another deadlock between SOFTLOCK and file truncation can happen
5025 	 * because segvn_fault_vnodepages() calls the FS one pagesize at
5026 	 * a time. A second VOP_GETPAGE() call by segvn_fault_vnodepages()
5027 	 * can cause a deadlock because the first set of page_t's remain
5028 	 * locked SE_SHARED.  To avoid this, we demote segments on a first
5029 	 * SOFTLOCK if they have a length greater than the segment's
5030 	 * page size.
5031 	 *
5032 	 * So for now, we only avoid demoting a segment on a SOFTLOCK when
5033 	 * the access type is S_READ_NOCOW and the fault length is less than
5034 	 * or equal to the segment's page size. While this is quite restrictive,
5035 	 * it should be the most common case of SOFTLOCK against a vmpss
5036 	 * segment.
5037 	 *
5038 	 * For S_READ_NOCOW, it's safe not to do a copy on write because the
5039 	 * caller makes sure no COW will be caused by another thread for a
5040 	 * softlocked page.
5041 	 */
5042 	if (type == F_SOFTLOCK && svd->vp != NULL && seg->s_szc != 0) {
5043 		int demote = 0;
5044 
5045 		if (rw != S_READ_NOCOW) {
5046 			demote = 1;
5047 		}
5048 		if (!demote && len > PAGESIZE) {
5049 			pgsz = page_get_pagesize(seg->s_szc);
5050 			CALC_LPG_REGION(pgsz, seg, addr, len, lpgaddr,
5051 			    lpgeaddr);
5052 			if (lpgeaddr - lpgaddr > pgsz) {
5053 				demote = 1;
5054 			}
5055 		}
5056 
5057 		ASSERT(demote || AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
5058 
5059 		if (demote) {
5060 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5061 			SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_WRITER);
5062 			if (seg->s_szc != 0) {
5063 				segvn_vmpss_clrszc_cnt++;
5064 				ASSERT(svd->softlockcnt == 0);
5065 				err = segvn_clrszc(seg);
5066 				if (err) {
5067 					segvn_vmpss_clrszc_err++;
5068 					SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5069 					return (FC_MAKE_ERR(err));
5070 				}
5071 			}
5072 			ASSERT(seg->s_szc == 0);
5073 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5074 			goto top;
5075 		}
5076 	}
5077 
5078 	/*
5079 	 * Check to see if we need to allocate an anon_map structure.
5080 	 */
5081 	if (svd->amp == NULL && (svd->vp == NULL || brkcow)) {
5082 		ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
5083 		/*
5084 		 * Drop the "read" lock on the segment and acquire
5085 		 * the "write" version since we have to allocate the
5086 		 * anon_map.
5087 		 */
5088 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5089 		SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_WRITER);
5090 
5091 		if (svd->amp == NULL) {
5092 			svd->amp = anonmap_alloc(seg->s_size, 0, ANON_SLEEP);
5093 			svd->amp->a_szc = seg->s_szc;
5094 		}
5095 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5096 
5097 		/*
5098 		 * Start all over again since segment protections
5099 		 * may have changed after we dropped the "read" lock.
5100 		 */
5101 		goto top;
5102 	}
5103 
5104 	/*
5105 	 * S_READ_NOCOW vs S_READ distinction was
5106 	 * only needed for the code above. After
5107 	 * that we treat it as S_READ.
5108 	 */
5109 	if (rw == S_READ_NOCOW) {
5110 		ASSERT(type == F_SOFTLOCK);
5111 		ASSERT(AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
5112 		rw = S_READ;
5113 	}
5114 
5115 	amp = svd->amp;
5116 
5117 	/*
5118 	 * MADV_SEQUENTIAL work is ignored for large page segments.
5119 	 */
5120 	if (seg->s_szc != 0) {
5121 		pgsz = page_get_pagesize(seg->s_szc);
5122 		ASSERT(SEGVN_LOCK_HELD(seg->s_as, &svd->lock));
5123 		CALC_LPG_REGION(pgsz, seg, addr, len, lpgaddr, lpgeaddr);
5124 		if (svd->vp == NULL) {
5125 			err = segvn_fault_anonpages(hat, seg, lpgaddr,
5126 			    lpgeaddr, type, rw, addr, addr + len, brkcow);
5127 		} else {
5128 			err = segvn_fault_vnodepages(hat, seg, lpgaddr,
5129 			    lpgeaddr, type, rw, addr, addr + len, brkcow);
5130 			if (err == IE_RETRY) {
5131 				ASSERT(seg->s_szc == 0);
5132 				ASSERT(SEGVN_READ_HELD(seg->s_as, &svd->lock));
5133 				SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5134 				goto top;
5135 			}
5136 		}
5137 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5138 		return (err);
5139 	}
5140 
5141 	page = seg_page(seg, addr);
5142 	if (amp != NULL) {
5143 		ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
5144 		anon_index = svd->anon_index + page;
5145 
5146 		if (type == F_PROT && rw == S_READ &&
5147 		    svd->tr_state == SEGVN_TR_OFF &&
5148 		    svd->type == MAP_PRIVATE && svd->pageprot == 0) {
5149 			size_t index = anon_index;
5150 			struct anon *ap;
5151 
5152 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
5153 			/*
5154 			 * The fast path could apply to S_WRITE also, except
5155 			 * that the protection fault could be caused by lazy
5156 			 * tlb flush when ro->rw. In this case, the pte is
5157 			 * RW already. But RO in the other cpu's tlb causes
5158 			 * the fault. Since hat_chgprot won't do anything if
5159 			 * pte doesn't change, we may end up faulting
5160 			 * indefinitely until the RO tlb entry gets replaced.
5161 			 */
5162 			for (a = addr; a < addr + len; a += PAGESIZE, index++) {
5163 				anon_array_enter(amp, index, &cookie);
5164 				ap = anon_get_ptr(amp->ahp, index);
5165 				anon_array_exit(&cookie);
5166 				if ((ap == NULL) || (ap->an_refcnt != 1)) {
5167 					ANON_LOCK_EXIT(&amp->a_rwlock);
5168 					goto slow;
5169 				}
5170 			}
5171 			hat_chgprot(seg->s_as->a_hat, addr, len, svd->prot);
5172 			ANON_LOCK_EXIT(&amp->a_rwlock);
5173 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5174 			return (0);
5175 		}
5176 	}
5177 slow:
5178 
5179 	if (svd->vpage == NULL)
5180 		vpage = NULL;
5181 	else
5182 		vpage = &svd->vpage[page];
5183 
5184 	off = svd->offset + (uintptr_t)(addr - seg->s_base);
5185 
5186 	/*
5187 	 * If MADV_SEQUENTIAL has been set for the particular page we
5188 	 * are faulting on, free behind all pages in the segment and put
5189 	 * them on the free list.
5190 	 */
5191 
5192 	if ((page != 0) && fltadvice && svd->tr_state != SEGVN_TR_ON) {
5193 		struct vpage *vpp;
5194 		ulong_t fanon_index;
5195 		size_t fpage;
5196 		u_offset_t pgoff, fpgoff;
5197 		struct vnode *fvp;
5198 		struct anon *fap = NULL;
5199 
5200 		if (svd->advice == MADV_SEQUENTIAL ||
5201 		    (svd->pageadvice &&
5202 		    VPP_ADVICE(vpage) == MADV_SEQUENTIAL)) {
5203 			pgoff = off - PAGESIZE;
5204 			fpage = page - 1;
5205 			if (vpage != NULL)
5206 				vpp = &svd->vpage[fpage];
5207 			if (amp != NULL)
5208 				fanon_index = svd->anon_index + fpage;
5209 
5210 			while (pgoff > svd->offset) {
5211 				if (svd->advice != MADV_SEQUENTIAL &&
5212 				    (!svd->pageadvice || (vpage &&
5213 				    VPP_ADVICE(vpp) != MADV_SEQUENTIAL)))
5214 					break;
5215 
5216 				/*
5217 				 * If this is an anon page, we must find the
5218 				 * correct <vp, offset> for it
5219 				 */
5220 				fap = NULL;
5221 				if (amp != NULL) {
5222 					ANON_LOCK_ENTER(&amp->a_rwlock,
5223 					    RW_READER);
5224 					anon_array_enter(amp, fanon_index,
5225 					    &cookie);
5226 					fap = anon_get_ptr(amp->ahp,
5227 					    fanon_index);
5228 					if (fap != NULL) {
5229 						swap_xlate(fap, &fvp, &fpgoff);
5230 					} else {
5231 						fpgoff = pgoff;
5232 						fvp = svd->vp;
5233 					}
5234 					anon_array_exit(&cookie);
5235 					ANON_LOCK_EXIT(&amp->a_rwlock);
5236 				} else {
5237 					fpgoff = pgoff;
5238 					fvp = svd->vp;
5239 				}
5240 				if (fvp == NULL)
5241 					break;	/* XXX */
5242 				/*
5243 				 * Skip pages that are free or have an
5244 				 * "exclusive" lock.
5245 				 */
5246 				pp = page_lookup_nowait(fvp, fpgoff, SE_SHARED);
5247 				if (pp == NULL)
5248 					break;
5249 				/*
5250 				 * We don't need the page_struct_lock to test
5251 				 * as this is only advisory; even if we
5252 				 * acquire it someone might race in and lock
5253 				 * the page after we unlock and before the
5254 				 * PUTPAGE, then VOP_PUTPAGE will do nothing.
5255 				 */
5256 				if (pp->p_lckcnt == 0 && pp->p_cowcnt == 0) {
5257 					/*
5258 					 * Hold the vnode before releasing
5259 					 * the page lock to prevent it from
5260 					 * being freed and re-used by some
5261 					 * other thread.
5262 					 */
5263 					VN_HOLD(fvp);
5264 					page_unlock(pp);
5265 					/*
5266 					 * We should build a page list
5267 					 * to kluster putpages XXX
5268 					 */
5269 					(void) VOP_PUTPAGE(fvp,
5270 					    (offset_t)fpgoff, PAGESIZE,
5271 					    (B_DONTNEED|B_FREE|B_ASYNC),
5272 					    svd->cred, NULL);
5273 					VN_RELE(fvp);
5274 				} else {
5275 					/*
5276 					 * XXX - Should the loop terminate if
5277 					 * the page is `locked'?
5278 					 */
5279 					page_unlock(pp);
5280 				}
5281 				--vpp;
5282 				--fanon_index;
5283 				pgoff -= PAGESIZE;
5284 			}
5285 		}
5286 	}
5287 
5288 	plp = pl;
5289 	*plp = NULL;
5290 	pl_alloc_sz = 0;
5291 
5292 	/*
5293 	 * See if we need to call VOP_GETPAGE for
5294 	 * *any* of the range being faulted on.
5295 	 * We can skip all of this work if there
5296 	 * was no original vnode.
5297 	 */
5298 	if (svd->vp != NULL) {
5299 		u_offset_t vp_off;
5300 		size_t vp_len;
5301 		struct anon *ap;
5302 		vnode_t *vp;
5303 
5304 		vp_off = off;
5305 		vp_len = len;
5306 
5307 		if (amp == NULL)
5308 			dogetpage = 1;
5309 		else {
5310 			/*
5311 			 * Only acquire reader lock to prevent amp->ahp
5312 			 * from being changed.  It's ok to miss pages,
5313 			 * hence we don't do anon_array_enter
5314 			 */
5315 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
5316 			ap = anon_get_ptr(amp->ahp, anon_index);
5317 
5318 			if (len <= PAGESIZE)
5319 				/* inline non_anon() */
5320 				dogetpage = (ap == NULL);
5321 			else
5322 				dogetpage = non_anon(amp->ahp, anon_index,
5323 				    &vp_off, &vp_len);
5324 			ANON_LOCK_EXIT(&amp->a_rwlock);
5325 		}
5326 
5327 		if (dogetpage) {
5328 			enum seg_rw arw;
5329 			struct as *as = seg->s_as;
5330 
5331 			if (len > ptob((sizeof (pl) / sizeof (pl[0])) - 1)) {
5332 				/*
5333 				 * Page list won't fit in local array,
5334 				 * allocate one of the needed size.
5335 				 */
5336 				pl_alloc_sz =
5337 				    (btop(len) + 1) * sizeof (page_t *);
5338 				plp = kmem_alloc(pl_alloc_sz, KM_SLEEP);
5339 				plp[0] = NULL;
5340 				plsz = len;
5341 			} else if (rw == S_WRITE && svd->type == MAP_PRIVATE ||
5342 			    svd->tr_state == SEGVN_TR_ON || rw == S_OTHER ||
5343 			    (((size_t)(addr + PAGESIZE) <
5344 			    (size_t)(seg->s_base + seg->s_size)) &&
5345 			    hat_probe(as->a_hat, addr + PAGESIZE))) {
5346 				/*
5347 				 * Ask VOP_GETPAGE to return the exact number
5348 				 * of pages if
5349 				 * (a) this is a COW fault, or
5350 				 * (b) this is a software fault, or
5351 				 * (c) next page is already mapped.
5352 				 */
5353 				plsz = len;
5354 			} else {
5355 				/*
5356 				 * Ask VOP_GETPAGE to return adjacent pages
5357 				 * within the segment.
5358 				 */
5359 				plsz = MIN((size_t)PVN_GETPAGE_SZ, (size_t)
5360 				    ((seg->s_base + seg->s_size) - addr));
5361 				ASSERT((addr + plsz) <=
5362 				    (seg->s_base + seg->s_size));
5363 			}
5364 
5365 			/*
5366 			 * Need to get some non-anonymous pages.
5367 			 * We need to make only one call to GETPAGE to do
5368 			 * this to prevent certain deadlocking conditions
5369 			 * when we are doing locking.  In this case
5370 			 * non_anon() should have picked up the smallest
5371 			 * range which includes all the non-anonymous
5372 			 * pages in the requested range.  We have to
5373 			 * be careful regarding which rw flag to pass in
5374 			 * because on a private mapping, the underlying
5375 			 * object is never allowed to be written.
5376 			 */
5377 			if (rw == S_WRITE && svd->type == MAP_PRIVATE) {
5378 				arw = S_READ;
5379 			} else {
5380 				arw = rw;
5381 			}
5382 			vp = svd->vp;
5383 			TRACE_3(TR_FAC_VM, TR_SEGVN_GETPAGE,
5384 			    "segvn_getpage:seg %p addr %p vp %p",
5385 			    seg, addr, vp);
5386 			err = VOP_GETPAGE(vp, (offset_t)vp_off, vp_len,
5387 			    &vpprot, plp, plsz, seg, addr + (vp_off - off), arw,
5388 			    svd->cred, NULL);
5389 			if (err) {
5390 				SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5391 				segvn_pagelist_rele(plp);
5392 				if (pl_alloc_sz)
5393 					kmem_free(plp, pl_alloc_sz);
5394 				return (FC_MAKE_ERR(err));
5395 			}
5396 			if (svd->type == MAP_PRIVATE)
5397 				vpprot &= ~PROT_WRITE;
5398 		}
5399 	}
5400 
5401 	/*
5402 	 * N.B. at this time the plp array has all the needed non-anon
5403 	 * pages in addition to (possibly) having some adjacent pages.
5404 	 */
5405 
5406 	/*
5407 	 * Always acquire the anon_array_lock to prevent
5408 	 * 2 threads from allocating separate anon slots for
5409 	 * the same "addr".
5410 	 *
5411 	 * If this is a copy-on-write fault and we don't already
5412 	 * have the anon_array_lock, acquire it to prevent the
5413 	 * fault routine from handling multiple copy-on-write faults
5414 	 * on the same "addr" in the same address space.
5415 	 *
5416 	 * Only one thread should deal with the fault since after
5417 	 * it is handled, the other threads can acquire a translation
5418 	 * to the newly created private page.  This prevents two or
5419 	 * more threads from creating different private pages for the
5420 	 * same fault.
5421 	 *
5422 	 * We grab "serialization" lock here if this is a MAP_PRIVATE segment
5423 	 * to prevent deadlock between this thread and another thread
5424 	 * which has soft-locked this page and wants to acquire serial_lock.
5425 	 * ( bug 4026339 )
5426 	 *
5427 	 * The fix for bug 4026339 becomes unnecessary when using the
5428 	 * locking scheme with per amp rwlock and a global set of hash
5429 	 * lock, anon_array_lock.  If we steal a vnode page when low
5430 	 * on memory and upgrad the page lock through page_rename,
5431 	 * then the page is PAGE_HANDLED, nothing needs to be done
5432 	 * for this page after returning from segvn_faultpage.
5433 	 *
5434 	 * But really, the page lock should be downgraded after
5435 	 * the stolen page is page_rename'd.
5436 	 */
5437 
5438 	if (amp != NULL)
5439 		ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
5440 
5441 	/*
5442 	 * Ok, now loop over the address range and handle faults
5443 	 */
5444 	for (a = addr; a < addr + len; a += PAGESIZE, off += PAGESIZE) {
5445 		err = segvn_faultpage(hat, seg, a, off, vpage, plp, vpprot,
5446 		    type, rw, brkcow);
5447 		if (err) {
5448 			if (amp != NULL)
5449 				ANON_LOCK_EXIT(&amp->a_rwlock);
5450 			if (type == F_SOFTLOCK && a > addr) {
5451 				segvn_softunlock(seg, addr, (a - addr),
5452 				    S_OTHER);
5453 			}
5454 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5455 			segvn_pagelist_rele(plp);
5456 			if (pl_alloc_sz)
5457 				kmem_free(plp, pl_alloc_sz);
5458 			return (err);
5459 		}
5460 		if (vpage) {
5461 			vpage++;
5462 		} else if (svd->vpage) {
5463 			page = seg_page(seg, addr);
5464 			vpage = &svd->vpage[++page];
5465 		}
5466 	}
5467 
5468 	/* Didn't get pages from the underlying fs so we're done */
5469 	if (!dogetpage)
5470 		goto done;
5471 
5472 	/*
5473 	 * Now handle any other pages in the list returned.
5474 	 * If the page can be used, load up the translations now.
5475 	 * Note that the for loop will only be entered if "plp"
5476 	 * is pointing to a non-NULL page pointer which means that
5477 	 * VOP_GETPAGE() was called and vpprot has been initialized.
5478 	 */
5479 	if (svd->pageprot == 0)
5480 		prot = svd->prot & vpprot;
5481 
5482 
5483 	/*
5484 	 * Large Files: diff should be unsigned value because we started
5485 	 * supporting > 2GB segment sizes from 2.5.1 and when a
5486 	 * large file of size > 2GB gets mapped to address space
5487 	 * the diff value can be > 2GB.
5488 	 */
5489 
5490 	for (ppp = plp; (pp = *ppp) != NULL; ppp++) {
5491 		size_t diff;
5492 		struct anon *ap;
5493 		int anon_index;
5494 		anon_sync_obj_t cookie;
5495 		int hat_flag = HAT_LOAD_ADV;
5496 
5497 		if (svd->flags & MAP_TEXT) {
5498 			hat_flag |= HAT_LOAD_TEXT;
5499 		}
5500 
5501 		if (pp == PAGE_HANDLED)
5502 			continue;
5503 
5504 		if (svd->tr_state != SEGVN_TR_ON &&
5505 		    pp->p_offset >=  svd->offset &&
5506 		    pp->p_offset < svd->offset + seg->s_size) {
5507 
5508 			diff = pp->p_offset - svd->offset;
5509 
5510 			/*
5511 			 * Large Files: Following is the assertion
5512 			 * validating the above cast.
5513 			 */
5514 			ASSERT(svd->vp == pp->p_vnode);
5515 
5516 			page = btop(diff);
5517 			if (svd->pageprot)
5518 				prot = VPP_PROT(&svd->vpage[page]) & vpprot;
5519 
5520 			/*
5521 			 * Prevent other threads in the address space from
5522 			 * creating private pages (i.e., allocating anon slots)
5523 			 * while we are in the process of loading translations
5524 			 * to additional pages returned by the underlying
5525 			 * object.
5526 			 */
5527 			if (amp != NULL) {
5528 				anon_index = svd->anon_index + page;
5529 				anon_array_enter(amp, anon_index, &cookie);
5530 				ap = anon_get_ptr(amp->ahp, anon_index);
5531 			}
5532 			if ((amp == NULL) || (ap == NULL)) {
5533 				if (IS_VMODSORT(pp->p_vnode) ||
5534 				    enable_mbit_wa) {
5535 					if (rw == S_WRITE)
5536 						hat_setmod(pp);
5537 					else if (rw != S_OTHER &&
5538 					    !hat_ismod(pp))
5539 						prot &= ~PROT_WRITE;
5540 				}
5541 				/*
5542 				 * Skip mapping read ahead pages marked
5543 				 * for migration, so they will get migrated
5544 				 * properly on fault
5545 				 */
5546 				ASSERT(amp == NULL ||
5547 				    svd->rcookie == HAT_INVALID_REGION_COOKIE);
5548 				if ((prot & PROT_READ) && !PP_ISMIGRATE(pp)) {
5549 					hat_memload_region(hat,
5550 					    seg->s_base + diff,
5551 					    pp, prot, hat_flag,
5552 					    svd->rcookie);
5553 				}
5554 			}
5555 			if (amp != NULL)
5556 				anon_array_exit(&cookie);
5557 		}
5558 		page_unlock(pp);
5559 	}
5560 done:
5561 	if (amp != NULL)
5562 		ANON_LOCK_EXIT(&amp->a_rwlock);
5563 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5564 	if (pl_alloc_sz)
5565 		kmem_free(plp, pl_alloc_sz);
5566 	return (0);
5567 }
5568 
5569 /*
5570  * This routine is used to start I/O on pages asynchronously.  XXX it will
5571  * only create PAGESIZE pages. At fault time they will be relocated into
5572  * larger pages.
5573  */
5574 static faultcode_t
5575 segvn_faulta(struct seg *seg, caddr_t addr)
5576 {
5577 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
5578 	int err;
5579 	struct anon_map *amp;
5580 	vnode_t *vp;
5581 
5582 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
5583 
5584 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
5585 	if ((amp = svd->amp) != NULL) {
5586 		struct anon *ap;
5587 
5588 		/*
5589 		 * Reader lock to prevent amp->ahp from being changed.
5590 		 * This is advisory, it's ok to miss a page, so
5591 		 * we don't do anon_array_enter lock.
5592 		 */
5593 		ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
5594 		if ((ap = anon_get_ptr(amp->ahp,
5595 		    svd->anon_index + seg_page(seg, addr))) != NULL) {
5596 
5597 			err = anon_getpage(&ap, NULL, NULL,
5598 			    0, seg, addr, S_READ, svd->cred);
5599 
5600 			ANON_LOCK_EXIT(&amp->a_rwlock);
5601 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5602 			if (err)
5603 				return (FC_MAKE_ERR(err));
5604 			return (0);
5605 		}
5606 		ANON_LOCK_EXIT(&amp->a_rwlock);
5607 	}
5608 
5609 	if (svd->vp == NULL) {
5610 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5611 		return (0);			/* zfod page - do nothing now */
5612 	}
5613 
5614 	vp = svd->vp;
5615 	TRACE_3(TR_FAC_VM, TR_SEGVN_GETPAGE,
5616 	    "segvn_getpage:seg %p addr %p vp %p", seg, addr, vp);
5617 	err = VOP_GETPAGE(vp,
5618 	    (offset_t)(svd->offset + (uintptr_t)(addr - seg->s_base)),
5619 	    PAGESIZE, NULL, NULL, 0, seg, addr,
5620 	    S_OTHER, svd->cred, NULL);
5621 
5622 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5623 	if (err)
5624 		return (FC_MAKE_ERR(err));
5625 	return (0);
5626 }
5627 
5628 static int
5629 segvn_setprot(struct seg *seg, caddr_t addr, size_t len, uint_t prot)
5630 {
5631 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
5632 	struct vpage *cvp, *svp, *evp;
5633 	struct vnode *vp;
5634 	size_t pgsz;
5635 	pgcnt_t pgcnt;
5636 	anon_sync_obj_t cookie;
5637 	int unload_done = 0;
5638 
5639 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
5640 
5641 	if ((svd->maxprot & prot) != prot)
5642 		return (EACCES);			/* violated maxprot */
5643 
5644 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_WRITER);
5645 
5646 	/* return if prot is the same */
5647 	if (!svd->pageprot && svd->prot == prot) {
5648 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5649 		return (0);
5650 	}
5651 
5652 	/*
5653 	 * Since we change protections we first have to flush the cache.
5654 	 * This makes sure all the pagelock calls have to recheck
5655 	 * protections.
5656 	 */
5657 	if (svd->softlockcnt > 0) {
5658 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
5659 
5660 		/*
5661 		 * If this is shared segment non 0 softlockcnt
5662 		 * means locked pages are still in use.
5663 		 */
5664 		if (svd->type == MAP_SHARED) {
5665 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5666 			return (EAGAIN);
5667 		}
5668 
5669 		/*
5670 		 * Since we do have the segvn writers lock nobody can fill
5671 		 * the cache with entries belonging to this seg during
5672 		 * the purge. The flush either succeeds or we still have
5673 		 * pending I/Os.
5674 		 */
5675 		segvn_purge(seg);
5676 		if (svd->softlockcnt > 0) {
5677 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5678 			return (EAGAIN);
5679 		}
5680 	}
5681 
5682 	if (HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
5683 		ASSERT(svd->amp == NULL);
5684 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
5685 		hat_leave_region(seg->s_as->a_hat, svd->rcookie,
5686 		    HAT_REGION_TEXT);
5687 		svd->rcookie = HAT_INVALID_REGION_COOKIE;
5688 		unload_done = 1;
5689 	} else if (svd->tr_state == SEGVN_TR_INIT) {
5690 		svd->tr_state = SEGVN_TR_OFF;
5691 	} else if (svd->tr_state == SEGVN_TR_ON) {
5692 		ASSERT(svd->amp != NULL);
5693 		segvn_textunrepl(seg, 0);
5694 		ASSERT(svd->amp == NULL && svd->tr_state == SEGVN_TR_OFF);
5695 		unload_done = 1;
5696 	}
5697 
5698 	if ((prot & PROT_WRITE) && svd->type == MAP_SHARED &&
5699 	    svd->vp != NULL && (svd->vp->v_flag & VVMEXEC)) {
5700 		ASSERT(vn_is_mapped(svd->vp, V_WRITE));
5701 		segvn_inval_trcache(svd->vp);
5702 	}
5703 	if (seg->s_szc != 0) {
5704 		int err;
5705 		pgsz = page_get_pagesize(seg->s_szc);
5706 		pgcnt = pgsz >> PAGESHIFT;
5707 		ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
5708 		if (!IS_P2ALIGNED(addr, pgsz) || !IS_P2ALIGNED(len, pgsz)) {
5709 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5710 			ASSERT(seg->s_base != addr || seg->s_size != len);
5711 			/*
5712 			 * If we are holding the as lock as a reader then
5713 			 * we need to return IE_RETRY and let the as
5714 			 * layer drop and re-acquire the lock as a writer.
5715 			 */
5716 			if (AS_READ_HELD(seg->s_as, &seg->s_as->a_lock))
5717 				return (IE_RETRY);
5718 			VM_STAT_ADD(segvnvmstats.demoterange[1]);
5719 			if (svd->type == MAP_PRIVATE || svd->vp != NULL) {
5720 				err = segvn_demote_range(seg, addr, len,
5721 				    SDR_END, 0);
5722 			} else {
5723 				uint_t szcvec = map_pgszcvec(seg->s_base,
5724 				    pgsz, (uintptr_t)seg->s_base,
5725 				    (svd->flags & MAP_TEXT), MAPPGSZC_SHM, 0);
5726 				err = segvn_demote_range(seg, addr, len,
5727 				    SDR_END, szcvec);
5728 			}
5729 			if (err == 0)
5730 				return (IE_RETRY);
5731 			if (err == ENOMEM)
5732 				return (IE_NOMEM);
5733 			return (err);
5734 		}
5735 	}
5736 
5737 
5738 	/*
5739 	 * If it's a private mapping and we're making it writable then we
5740 	 * may have to reserve the additional swap space now. If we are
5741 	 * making writable only a part of the segment then we use its vpage
5742 	 * array to keep a record of the pages for which we have reserved
5743 	 * swap. In this case we set the pageswap field in the segment's
5744 	 * segvn structure to record this.
5745 	 *
5746 	 * If it's a private mapping to a file (i.e., vp != NULL) and we're
5747 	 * removing write permission on the entire segment and we haven't
5748 	 * modified any pages, we can release the swap space.
5749 	 */
5750 	if (svd->type == MAP_PRIVATE) {
5751 		if (prot & PROT_WRITE) {
5752 			if (!(svd->flags & MAP_NORESERVE) &&
5753 			    !(svd->swresv && svd->pageswap == 0)) {
5754 				size_t sz = 0;
5755 
5756 				/*
5757 				 * Start by determining how much swap
5758 				 * space is required.
5759 				 */
5760 				if (addr == seg->s_base &&
5761 				    len == seg->s_size &&
5762 				    svd->pageswap == 0) {
5763 					/* The whole segment */
5764 					sz = seg->s_size;
5765 				} else {
5766 					/*
5767 					 * Make sure that the vpage array
5768 					 * exists, and make a note of the
5769 					 * range of elements corresponding
5770 					 * to len.
5771 					 */
5772 					segvn_vpage(seg);
5773 					svp = &svd->vpage[seg_page(seg, addr)];
5774 					evp = &svd->vpage[seg_page(seg,
5775 					    addr + len)];
5776 
5777 					if (svd->pageswap == 0) {
5778 						/*
5779 						 * This is the first time we've
5780 						 * asked for a part of this
5781 						 * segment, so we need to
5782 						 * reserve everything we've
5783 						 * been asked for.
5784 						 */
5785 						sz = len;
5786 					} else {
5787 						/*
5788 						 * We have to count the number
5789 						 * of pages required.
5790 						 */
5791 						for (cvp = svp;  cvp < evp;
5792 						    cvp++) {
5793 							if (!VPP_ISSWAPRES(cvp))
5794 								sz++;
5795 						}
5796 						sz <<= PAGESHIFT;
5797 					}
5798 				}
5799 
5800 				/* Try to reserve the necessary swap. */
5801 				if (anon_resv_zone(sz,
5802 				    seg->s_as->a_proc->p_zone) == 0) {
5803 					SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5804 					return (IE_NOMEM);
5805 				}
5806 
5807 				/*
5808 				 * Make a note of how much swap space
5809 				 * we've reserved.
5810 				 */
5811 				if (svd->pageswap == 0 && sz == seg->s_size) {
5812 					svd->swresv = sz;
5813 				} else {
5814 					ASSERT(svd->vpage != NULL);
5815 					svd->swresv += sz;
5816 					svd->pageswap = 1;
5817 					for (cvp = svp; cvp < evp; cvp++) {
5818 						if (!VPP_ISSWAPRES(cvp))
5819 							VPP_SETSWAPRES(cvp);
5820 					}
5821 				}
5822 			}
5823 		} else {
5824 			/*
5825 			 * Swap space is released only if this segment
5826 			 * does not map anonymous memory, since read faults
5827 			 * on such segments still need an anon slot to read
5828 			 * in the data.
5829 			 */
5830 			if (svd->swresv != 0 && svd->vp != NULL &&
5831 			    svd->amp == NULL && addr == seg->s_base &&
5832 			    len == seg->s_size && svd->pageprot == 0) {
5833 				ASSERT(svd->pageswap == 0);
5834 				anon_unresv_zone(svd->swresv,
5835 				    seg->s_as->a_proc->p_zone);
5836 				svd->swresv = 0;
5837 				TRACE_3(TR_FAC_VM, TR_ANON_PROC,
5838 				    "anon proc:%p %lu %u", seg, 0, 0);
5839 			}
5840 		}
5841 	}
5842 
5843 	if (addr == seg->s_base && len == seg->s_size && svd->vpage == NULL) {
5844 		if (svd->prot == prot) {
5845 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5846 			return (0);			/* all done */
5847 		}
5848 		svd->prot = (uchar_t)prot;
5849 	} else if (svd->type == MAP_PRIVATE) {
5850 		struct anon *ap = NULL;
5851 		page_t *pp;
5852 		u_offset_t offset, off;
5853 		struct anon_map *amp;
5854 		ulong_t anon_idx = 0;
5855 
5856 		/*
5857 		 * A vpage structure exists or else the change does not
5858 		 * involve the entire segment.  Establish a vpage structure
5859 		 * if none is there.  Then, for each page in the range,
5860 		 * adjust its individual permissions.  Note that write-
5861 		 * enabling a MAP_PRIVATE page can affect the claims for
5862 		 * locked down memory.  Overcommitting memory terminates
5863 		 * the operation.
5864 		 */
5865 		segvn_vpage(seg);
5866 		svd->pageprot = 1;
5867 		if ((amp = svd->amp) != NULL) {
5868 			anon_idx = svd->anon_index + seg_page(seg, addr);
5869 			ASSERT(seg->s_szc == 0 ||
5870 			    IS_P2ALIGNED(anon_idx, pgcnt));
5871 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
5872 		}
5873 
5874 		offset = svd->offset + (uintptr_t)(addr - seg->s_base);
5875 		evp = &svd->vpage[seg_page(seg, addr + len)];
5876 
5877 		/*
5878 		 * See Statement at the beginning of segvn_lockop regarding
5879 		 * the way cowcnts and lckcnts are handled.
5880 		 */
5881 		for (svp = &svd->vpage[seg_page(seg, addr)]; svp < evp; svp++) {
5882 
5883 			if (seg->s_szc != 0) {
5884 				if (amp != NULL) {
5885 					anon_array_enter(amp, anon_idx,
5886 					    &cookie);
5887 				}
5888 				if (IS_P2ALIGNED(anon_idx, pgcnt) &&
5889 				    !segvn_claim_pages(seg, svp, offset,
5890 				    anon_idx, prot)) {
5891 					if (amp != NULL) {
5892 						anon_array_exit(&cookie);
5893 					}
5894 					break;
5895 				}
5896 				if (amp != NULL) {
5897 					anon_array_exit(&cookie);
5898 				}
5899 				anon_idx++;
5900 			} else {
5901 				if (amp != NULL) {
5902 					anon_array_enter(amp, anon_idx,
5903 					    &cookie);
5904 					ap = anon_get_ptr(amp->ahp, anon_idx++);
5905 				}
5906 
5907 				if (VPP_ISPPLOCK(svp) &&
5908 				    VPP_PROT(svp) != prot) {
5909 
5910 					if (amp == NULL || ap == NULL) {
5911 						vp = svd->vp;
5912 						off = offset;
5913 					} else
5914 						swap_xlate(ap, &vp, &off);
5915 					if (amp != NULL)
5916 						anon_array_exit(&cookie);
5917 
5918 					if ((pp = page_lookup(vp, off,
5919 					    SE_SHARED)) == NULL) {
5920 						panic("segvn_setprot: no page");
5921 						/*NOTREACHED*/
5922 					}
5923 					ASSERT(seg->s_szc == 0);
5924 					if ((VPP_PROT(svp) ^ prot) &
5925 					    PROT_WRITE) {
5926 						if (prot & PROT_WRITE) {
5927 							if (!page_addclaim(
5928 							    pp)) {
5929 								page_unlock(pp);
5930 								break;
5931 							}
5932 						} else {
5933 							if (!page_subclaim(
5934 							    pp)) {
5935 								page_unlock(pp);
5936 								break;
5937 							}
5938 						}
5939 					}
5940 					page_unlock(pp);
5941 				} else if (amp != NULL)
5942 					anon_array_exit(&cookie);
5943 			}
5944 			VPP_SETPROT(svp, prot);
5945 			offset += PAGESIZE;
5946 		}
5947 		if (amp != NULL)
5948 			ANON_LOCK_EXIT(&amp->a_rwlock);
5949 
5950 		/*
5951 		 * Did we terminate prematurely?  If so, simply unload
5952 		 * the translations to the things we've updated so far.
5953 		 */
5954 		if (svp != evp) {
5955 			if (unload_done) {
5956 				SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5957 				return (IE_NOMEM);
5958 			}
5959 			len = (svp - &svd->vpage[seg_page(seg, addr)]) *
5960 			    PAGESIZE;
5961 			ASSERT(seg->s_szc == 0 || IS_P2ALIGNED(len, pgsz));
5962 			if (len != 0)
5963 				hat_unload(seg->s_as->a_hat, addr,
5964 				    len, HAT_UNLOAD);
5965 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5966 			return (IE_NOMEM);
5967 		}
5968 	} else {
5969 		segvn_vpage(seg);
5970 		svd->pageprot = 1;
5971 		evp = &svd->vpage[seg_page(seg, addr + len)];
5972 		for (svp = &svd->vpage[seg_page(seg, addr)]; svp < evp; svp++) {
5973 			VPP_SETPROT(svp, prot);
5974 		}
5975 	}
5976 
5977 	if (unload_done) {
5978 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
5979 		return (0);
5980 	}
5981 
5982 	if (((prot & PROT_WRITE) != 0 &&
5983 	    (svd->vp != NULL || svd->type == MAP_PRIVATE)) ||
5984 	    (prot & ~PROT_USER) == PROT_NONE) {
5985 		/*
5986 		 * Either private or shared data with write access (in
5987 		 * which case we need to throw out all former translations
5988 		 * so that we get the right translations set up on fault
5989 		 * and we don't allow write access to any copy-on-write pages
5990 		 * that might be around or to prevent write access to pages
5991 		 * representing holes in a file), or we don't have permission
5992 		 * to access the memory at all (in which case we have to
5993 		 * unload any current translations that might exist).
5994 		 */
5995 		hat_unload(seg->s_as->a_hat, addr, len, HAT_UNLOAD);
5996 	} else {
5997 		/*
5998 		 * A shared mapping or a private mapping in which write
5999 		 * protection is going to be denied - just change all the
6000 		 * protections over the range of addresses in question.
6001 		 * segvn does not support any other attributes other
6002 		 * than prot so we can use hat_chgattr.
6003 		 */
6004 		hat_chgattr(seg->s_as->a_hat, addr, len, prot);
6005 	}
6006 
6007 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
6008 
6009 	return (0);
6010 }
6011 
6012 /*
6013  * segvn_setpagesize is called via SEGOP_SETPAGESIZE from as_setpagesize,
6014  * to determine if the seg is capable of mapping the requested szc.
6015  */
6016 static int
6017 segvn_setpagesize(struct seg *seg, caddr_t addr, size_t len, uint_t szc)
6018 {
6019 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6020 	struct segvn_data *nsvd;
6021 	struct anon_map *amp = svd->amp;
6022 	struct seg *nseg;
6023 	caddr_t eaddr = addr + len, a;
6024 	size_t pgsz = page_get_pagesize(szc);
6025 	pgcnt_t pgcnt = page_get_pagecnt(szc);
6026 	int err;
6027 	u_offset_t off = svd->offset + (uintptr_t)(addr - seg->s_base);
6028 
6029 	ASSERT(seg->s_as && AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
6030 	ASSERT(addr >= seg->s_base && eaddr <= seg->s_base + seg->s_size);
6031 
6032 	if (seg->s_szc == szc || segvn_lpg_disable != 0) {
6033 		return (0);
6034 	}
6035 
6036 	/*
6037 	 * addr should always be pgsz aligned but eaddr may be misaligned if
6038 	 * it's at the end of the segment.
6039 	 *
6040 	 * XXX we should assert this condition since as_setpagesize() logic
6041 	 * guarantees it.
6042 	 */
6043 	if (!IS_P2ALIGNED(addr, pgsz) ||
6044 	    (!IS_P2ALIGNED(eaddr, pgsz) &&
6045 	    eaddr != seg->s_base + seg->s_size)) {
6046 
6047 		segvn_setpgsz_align_err++;
6048 		return (EINVAL);
6049 	}
6050 
6051 	if (amp != NULL && svd->type == MAP_SHARED) {
6052 		ulong_t an_idx = svd->anon_index + seg_page(seg, addr);
6053 		if (!IS_P2ALIGNED(an_idx, pgcnt)) {
6054 
6055 			segvn_setpgsz_anon_align_err++;
6056 			return (EINVAL);
6057 		}
6058 	}
6059 
6060 	if ((svd->flags & MAP_NORESERVE) || seg->s_as == &kas ||
6061 	    szc > segvn_maxpgszc) {
6062 		return (EINVAL);
6063 	}
6064 
6065 	/* paranoid check */
6066 	if (svd->vp != NULL &&
6067 	    (IS_SWAPFSVP(svd->vp) || VN_ISKAS(svd->vp))) {
6068 		return (EINVAL);
6069 	}
6070 
6071 	if (seg->s_szc == 0 && svd->vp != NULL &&
6072 	    map_addr_vacalign_check(addr, off)) {
6073 		return (EINVAL);
6074 	}
6075 
6076 	/*
6077 	 * Check that protections are the same within new page
6078 	 * size boundaries.
6079 	 */
6080 	if (svd->pageprot) {
6081 		for (a = addr; a < eaddr; a += pgsz) {
6082 			if ((a + pgsz) > eaddr) {
6083 				if (!sameprot(seg, a, eaddr - a)) {
6084 					return (EINVAL);
6085 				}
6086 			} else {
6087 				if (!sameprot(seg, a, pgsz)) {
6088 					return (EINVAL);
6089 				}
6090 			}
6091 		}
6092 	}
6093 
6094 	/*
6095 	 * Since we are changing page size we first have to flush
6096 	 * the cache. This makes sure all the pagelock calls have
6097 	 * to recheck protections.
6098 	 */
6099 	if (svd->softlockcnt > 0) {
6100 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
6101 
6102 		/*
6103 		 * If this is shared segment non 0 softlockcnt
6104 		 * means locked pages are still in use.
6105 		 */
6106 		if (svd->type == MAP_SHARED) {
6107 			return (EAGAIN);
6108 		}
6109 
6110 		/*
6111 		 * Since we do have the segvn writers lock nobody can fill
6112 		 * the cache with entries belonging to this seg during
6113 		 * the purge. The flush either succeeds or we still have
6114 		 * pending I/Os.
6115 		 */
6116 		segvn_purge(seg);
6117 		if (svd->softlockcnt > 0) {
6118 			return (EAGAIN);
6119 		}
6120 	}
6121 
6122 	if (HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
6123 		ASSERT(svd->amp == NULL);
6124 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
6125 		hat_leave_region(seg->s_as->a_hat, svd->rcookie,
6126 		    HAT_REGION_TEXT);
6127 		svd->rcookie = HAT_INVALID_REGION_COOKIE;
6128 	} else if (svd->tr_state == SEGVN_TR_INIT) {
6129 		svd->tr_state = SEGVN_TR_OFF;
6130 	} else if (svd->tr_state == SEGVN_TR_ON) {
6131 		ASSERT(svd->amp != NULL);
6132 		segvn_textunrepl(seg, 1);
6133 		ASSERT(svd->amp == NULL && svd->tr_state == SEGVN_TR_OFF);
6134 		amp = NULL;
6135 	}
6136 
6137 	/*
6138 	 * Operation for sub range of existing segment.
6139 	 */
6140 	if (addr != seg->s_base || eaddr != (seg->s_base + seg->s_size)) {
6141 		if (szc < seg->s_szc) {
6142 			VM_STAT_ADD(segvnvmstats.demoterange[2]);
6143 			err = segvn_demote_range(seg, addr, len, SDR_RANGE, 0);
6144 			if (err == 0) {
6145 				return (IE_RETRY);
6146 			}
6147 			if (err == ENOMEM) {
6148 				return (IE_NOMEM);
6149 			}
6150 			return (err);
6151 		}
6152 		if (addr != seg->s_base) {
6153 			nseg = segvn_split_seg(seg, addr);
6154 			if (eaddr != (nseg->s_base + nseg->s_size)) {
6155 				/* eaddr is szc aligned */
6156 				(void) segvn_split_seg(nseg, eaddr);
6157 			}
6158 			return (IE_RETRY);
6159 		}
6160 		if (eaddr != (seg->s_base + seg->s_size)) {
6161 			/* eaddr is szc aligned */
6162 			(void) segvn_split_seg(seg, eaddr);
6163 		}
6164 		return (IE_RETRY);
6165 	}
6166 
6167 	/*
6168 	 * Break any low level sharing and reset seg->s_szc to 0.
6169 	 */
6170 	if ((err = segvn_clrszc(seg)) != 0) {
6171 		if (err == ENOMEM) {
6172 			err = IE_NOMEM;
6173 		}
6174 		return (err);
6175 	}
6176 	ASSERT(seg->s_szc == 0);
6177 
6178 	/*
6179 	 * If the end of the current segment is not pgsz aligned
6180 	 * then attempt to concatenate with the next segment.
6181 	 */
6182 	if (!IS_P2ALIGNED(eaddr, pgsz)) {
6183 		nseg = AS_SEGNEXT(seg->s_as, seg);
6184 		if (nseg == NULL || nseg == seg || eaddr != nseg->s_base) {
6185 			return (ENOMEM);
6186 		}
6187 		if (nseg->s_ops != &segvn_ops) {
6188 			return (EINVAL);
6189 		}
6190 		nsvd = (struct segvn_data *)nseg->s_data;
6191 		if (nsvd->softlockcnt > 0) {
6192 			/*
6193 			 * If this is shared segment non 0 softlockcnt
6194 			 * means locked pages are still in use.
6195 			 */
6196 			if (nsvd->type == MAP_SHARED) {
6197 				return (EAGAIN);
6198 			}
6199 			segvn_purge(nseg);
6200 			if (nsvd->softlockcnt > 0) {
6201 				return (EAGAIN);
6202 			}
6203 		}
6204 		err = segvn_clrszc(nseg);
6205 		if (err == ENOMEM) {
6206 			err = IE_NOMEM;
6207 		}
6208 		if (err != 0) {
6209 			return (err);
6210 		}
6211 		ASSERT(nsvd->rcookie == HAT_INVALID_REGION_COOKIE);
6212 		err = segvn_concat(seg, nseg, 1);
6213 		if (err == -1) {
6214 			return (EINVAL);
6215 		}
6216 		if (err == -2) {
6217 			return (IE_NOMEM);
6218 		}
6219 		return (IE_RETRY);
6220 	}
6221 
6222 	/*
6223 	 * May need to re-align anon array to
6224 	 * new szc.
6225 	 */
6226 	if (amp != NULL) {
6227 		if (!IS_P2ALIGNED(svd->anon_index, pgcnt)) {
6228 			struct anon_hdr *nahp;
6229 
6230 			ASSERT(svd->type == MAP_PRIVATE);
6231 
6232 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
6233 			ASSERT(amp->refcnt == 1);
6234 			nahp = anon_create(btop(amp->size), ANON_NOSLEEP);
6235 			if (nahp == NULL) {
6236 				ANON_LOCK_EXIT(&amp->a_rwlock);
6237 				return (IE_NOMEM);
6238 			}
6239 			if (anon_copy_ptr(amp->ahp, svd->anon_index,
6240 			    nahp, 0, btop(seg->s_size), ANON_NOSLEEP)) {
6241 				anon_release(nahp, btop(amp->size));
6242 				ANON_LOCK_EXIT(&amp->a_rwlock);
6243 				return (IE_NOMEM);
6244 			}
6245 			anon_release(amp->ahp, btop(amp->size));
6246 			amp->ahp = nahp;
6247 			svd->anon_index = 0;
6248 			ANON_LOCK_EXIT(&amp->a_rwlock);
6249 		}
6250 	}
6251 	if (svd->vp != NULL && szc != 0) {
6252 		struct vattr va;
6253 		u_offset_t eoffpage = svd->offset;
6254 		va.va_mask = AT_SIZE;
6255 		eoffpage += seg->s_size;
6256 		eoffpage = btopr(eoffpage);
6257 		if (VOP_GETATTR(svd->vp, &va, 0, svd->cred, NULL) != 0) {
6258 			segvn_setpgsz_getattr_err++;
6259 			return (EINVAL);
6260 		}
6261 		if (btopr(va.va_size) < eoffpage) {
6262 			segvn_setpgsz_eof_err++;
6263 			return (EINVAL);
6264 		}
6265 		if (amp != NULL) {
6266 			/*
6267 			 * anon_fill_cow_holes() may call VOP_GETPAGE().
6268 			 * don't take anon map lock here to avoid holding it
6269 			 * across VOP_GETPAGE() calls that may call back into
6270 			 * segvn for klsutering checks. We don't really need
6271 			 * anon map lock here since it's a private segment and
6272 			 * we hold as level lock as writers.
6273 			 */
6274 			if ((err = anon_fill_cow_holes(seg, seg->s_base,
6275 			    amp->ahp, svd->anon_index, svd->vp, svd->offset,
6276 			    seg->s_size, szc, svd->prot, svd->vpage,
6277 			    svd->cred)) != 0) {
6278 				return (EINVAL);
6279 			}
6280 		}
6281 		segvn_setvnode_mpss(svd->vp);
6282 	}
6283 
6284 	if (amp != NULL) {
6285 		ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
6286 		if (svd->type == MAP_PRIVATE) {
6287 			amp->a_szc = szc;
6288 		} else if (szc > amp->a_szc) {
6289 			amp->a_szc = szc;
6290 		}
6291 		ANON_LOCK_EXIT(&amp->a_rwlock);
6292 	}
6293 
6294 	seg->s_szc = szc;
6295 
6296 	return (0);
6297 }
6298 
6299 static int
6300 segvn_clrszc(struct seg *seg)
6301 {
6302 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6303 	struct anon_map *amp = svd->amp;
6304 	size_t pgsz;
6305 	pgcnt_t pages;
6306 	int err = 0;
6307 	caddr_t a = seg->s_base;
6308 	caddr_t ea = a + seg->s_size;
6309 	ulong_t an_idx = svd->anon_index;
6310 	vnode_t *vp = svd->vp;
6311 	struct vpage *vpage = svd->vpage;
6312 	page_t *anon_pl[1 + 1], *pp;
6313 	struct anon *ap, *oldap;
6314 	uint_t prot = svd->prot, vpprot;
6315 	int pageflag = 0;
6316 
6317 	ASSERT(AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock) ||
6318 	    SEGVN_WRITE_HELD(seg->s_as, &svd->lock));
6319 	ASSERT(svd->softlockcnt == 0);
6320 
6321 	if (vp == NULL && amp == NULL) {
6322 		ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
6323 		seg->s_szc = 0;
6324 		return (0);
6325 	}
6326 
6327 	if (HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
6328 		ASSERT(svd->amp == NULL);
6329 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
6330 		hat_leave_region(seg->s_as->a_hat, svd->rcookie,
6331 		    HAT_REGION_TEXT);
6332 		svd->rcookie = HAT_INVALID_REGION_COOKIE;
6333 	} else if (svd->tr_state == SEGVN_TR_ON) {
6334 		ASSERT(svd->amp != NULL);
6335 		segvn_textunrepl(seg, 1);
6336 		ASSERT(svd->amp == NULL && svd->tr_state == SEGVN_TR_OFF);
6337 		amp = NULL;
6338 	} else {
6339 		if (svd->tr_state != SEGVN_TR_OFF) {
6340 			ASSERT(svd->tr_state == SEGVN_TR_INIT);
6341 			svd->tr_state = SEGVN_TR_OFF;
6342 		}
6343 
6344 		/*
6345 		 * do HAT_UNLOAD_UNMAP since we are changing the pagesize.
6346 		 * unload argument is 0 when we are freeing the segment
6347 		 * and unload was already done.
6348 		 */
6349 		hat_unload(seg->s_as->a_hat, seg->s_base, seg->s_size,
6350 		    HAT_UNLOAD_UNMAP);
6351 	}
6352 
6353 	if (amp == NULL || svd->type == MAP_SHARED) {
6354 		seg->s_szc = 0;
6355 		return (0);
6356 	}
6357 
6358 	pgsz = page_get_pagesize(seg->s_szc);
6359 	pages = btop(pgsz);
6360 
6361 	/*
6362 	 * XXX anon rwlock is not really needed because this is a
6363 	 * private segment and we are writers.
6364 	 */
6365 	ANON_LOCK_ENTER(&amp->a_rwlock, RW_WRITER);
6366 
6367 	for (; a < ea; a += pgsz, an_idx += pages) {
6368 		if ((oldap = anon_get_ptr(amp->ahp, an_idx)) != NULL) {
6369 			ASSERT(vpage != NULL || svd->pageprot == 0);
6370 			if (vpage != NULL) {
6371 				ASSERT(sameprot(seg, a, pgsz));
6372 				prot = VPP_PROT(vpage);
6373 				pageflag = VPP_ISPPLOCK(vpage) ? LOCK_PAGE : 0;
6374 			}
6375 			if (seg->s_szc != 0) {
6376 				ASSERT(vp == NULL || anon_pages(amp->ahp,
6377 				    an_idx, pages) == pages);
6378 				if ((err = anon_map_demotepages(amp, an_idx,
6379 				    seg, a, prot, vpage, svd->cred)) != 0) {
6380 					goto out;
6381 				}
6382 			} else {
6383 				if (oldap->an_refcnt == 1) {
6384 					continue;
6385 				}
6386 				if ((err = anon_getpage(&oldap, &vpprot,
6387 				    anon_pl, PAGESIZE, seg, a, S_READ,
6388 				    svd->cred))) {
6389 					goto out;
6390 				}
6391 				if ((pp = anon_private(&ap, seg, a, prot,
6392 				    anon_pl[0], pageflag, svd->cred)) == NULL) {
6393 					err = ENOMEM;
6394 					goto out;
6395 				}
6396 				anon_decref(oldap);
6397 				(void) anon_set_ptr(amp->ahp, an_idx, ap,
6398 				    ANON_SLEEP);
6399 				page_unlock(pp);
6400 			}
6401 		}
6402 		vpage = (vpage == NULL) ? NULL : vpage + pages;
6403 	}
6404 
6405 	amp->a_szc = 0;
6406 	seg->s_szc = 0;
6407 out:
6408 	ANON_LOCK_EXIT(&amp->a_rwlock);
6409 	return (err);
6410 }
6411 
6412 static int
6413 segvn_claim_pages(
6414 	struct seg *seg,
6415 	struct vpage *svp,
6416 	u_offset_t off,
6417 	ulong_t anon_idx,
6418 	uint_t prot)
6419 {
6420 	pgcnt_t	pgcnt = page_get_pagecnt(seg->s_szc);
6421 	size_t ppasize = (pgcnt + 1) * sizeof (page_t *);
6422 	page_t	**ppa;
6423 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6424 	struct anon_map *amp = svd->amp;
6425 	struct vpage *evp = svp + pgcnt;
6426 	caddr_t addr = ((uintptr_t)(svp - svd->vpage) << PAGESHIFT)
6427 	    + seg->s_base;
6428 	struct anon *ap;
6429 	struct vnode *vp = svd->vp;
6430 	page_t *pp;
6431 	pgcnt_t pg_idx, i;
6432 	int err = 0;
6433 	anoff_t aoff;
6434 	int anon = (amp != NULL) ? 1 : 0;
6435 
6436 	ASSERT(svd->type == MAP_PRIVATE);
6437 	ASSERT(svd->vpage != NULL);
6438 	ASSERT(seg->s_szc != 0);
6439 	ASSERT(IS_P2ALIGNED(pgcnt, pgcnt));
6440 	ASSERT(amp == NULL || IS_P2ALIGNED(anon_idx, pgcnt));
6441 	ASSERT(sameprot(seg, addr, pgcnt << PAGESHIFT));
6442 
6443 	if (VPP_PROT(svp) == prot)
6444 		return (1);
6445 	if (!((VPP_PROT(svp) ^ prot) & PROT_WRITE))
6446 		return (1);
6447 
6448 	ppa = kmem_alloc(ppasize, KM_SLEEP);
6449 	if (anon && vp != NULL) {
6450 		if (anon_get_ptr(amp->ahp, anon_idx) == NULL) {
6451 			anon = 0;
6452 			ASSERT(!anon_pages(amp->ahp, anon_idx, pgcnt));
6453 		}
6454 		ASSERT(!anon ||
6455 		    anon_pages(amp->ahp, anon_idx, pgcnt) == pgcnt);
6456 	}
6457 
6458 	for (*ppa = NULL, pg_idx = 0; svp < evp; svp++, anon_idx++) {
6459 		if (!VPP_ISPPLOCK(svp))
6460 			continue;
6461 		if (anon) {
6462 			ap = anon_get_ptr(amp->ahp, anon_idx);
6463 			if (ap == NULL) {
6464 				panic("segvn_claim_pages: no anon slot");
6465 			}
6466 			swap_xlate(ap, &vp, &aoff);
6467 			off = (u_offset_t)aoff;
6468 		}
6469 		ASSERT(vp != NULL);
6470 		if ((pp = page_lookup(vp,
6471 		    (u_offset_t)off, SE_SHARED)) == NULL) {
6472 			panic("segvn_claim_pages: no page");
6473 		}
6474 		ppa[pg_idx++] = pp;
6475 		off += PAGESIZE;
6476 	}
6477 
6478 	if (ppa[0] == NULL) {
6479 		kmem_free(ppa, ppasize);
6480 		return (1);
6481 	}
6482 
6483 	ASSERT(pg_idx <= pgcnt);
6484 	ppa[pg_idx] = NULL;
6485 
6486 	if (prot & PROT_WRITE)
6487 		err = page_addclaim_pages(ppa);
6488 	else
6489 		err = page_subclaim_pages(ppa);
6490 
6491 	for (i = 0; i < pg_idx; i++) {
6492 		ASSERT(ppa[i] != NULL);
6493 		page_unlock(ppa[i]);
6494 	}
6495 
6496 	kmem_free(ppa, ppasize);
6497 	return (err);
6498 }
6499 
6500 /*
6501  * Returns right (upper address) segment if split occurred.
6502  * If the address is equal to the beginning or end of its segment it returns
6503  * the current segment.
6504  */
6505 static struct seg *
6506 segvn_split_seg(struct seg *seg, caddr_t addr)
6507 {
6508 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6509 	struct seg *nseg;
6510 	size_t nsize;
6511 	struct segvn_data *nsvd;
6512 
6513 	ASSERT(AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
6514 	ASSERT(svd->tr_state == SEGVN_TR_OFF);
6515 
6516 	ASSERT(addr >= seg->s_base);
6517 	ASSERT(addr <= seg->s_base + seg->s_size);
6518 	ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
6519 
6520 	if (addr == seg->s_base || addr == seg->s_base + seg->s_size)
6521 		return (seg);
6522 
6523 	nsize = seg->s_base + seg->s_size - addr;
6524 	seg->s_size = addr - seg->s_base;
6525 	nseg = seg_alloc(seg->s_as, addr, nsize);
6526 	ASSERT(nseg != NULL);
6527 	nseg->s_ops = seg->s_ops;
6528 	nsvd = kmem_cache_alloc(segvn_cache, KM_SLEEP);
6529 	nseg->s_data = (void *)nsvd;
6530 	nseg->s_szc = seg->s_szc;
6531 	*nsvd = *svd;
6532 	ASSERT(nsvd->rcookie == HAT_INVALID_REGION_COOKIE);
6533 	nsvd->seg = nseg;
6534 	rw_init(&nsvd->lock, NULL, RW_DEFAULT, NULL);
6535 
6536 	if (nsvd->vp != NULL) {
6537 		VN_HOLD(nsvd->vp);
6538 		nsvd->offset = svd->offset +
6539 		    (uintptr_t)(nseg->s_base - seg->s_base);
6540 		if (nsvd->type == MAP_SHARED)
6541 			lgrp_shm_policy_init(NULL, nsvd->vp);
6542 	} else {
6543 		/*
6544 		 * The offset for an anonymous segment has no signifigance in
6545 		 * terms of an offset into a file. If we were to use the above
6546 		 * calculation instead, the structures read out of
6547 		 * /proc/<pid>/xmap would be more difficult to decipher since
6548 		 * it would be unclear whether two seemingly contiguous
6549 		 * prxmap_t structures represented different segments or a
6550 		 * single segment that had been split up into multiple prxmap_t
6551 		 * structures (e.g. if some part of the segment had not yet
6552 		 * been faulted in).
6553 		 */
6554 		nsvd->offset = 0;
6555 	}
6556 
6557 	ASSERT(svd->softlockcnt == 0);
6558 	ASSERT(svd->softlockcnt_sbase == 0);
6559 	ASSERT(svd->softlockcnt_send == 0);
6560 	crhold(svd->cred);
6561 
6562 	if (svd->vpage != NULL) {
6563 		size_t bytes = vpgtob(seg_pages(seg));
6564 		size_t nbytes = vpgtob(seg_pages(nseg));
6565 		struct vpage *ovpage = svd->vpage;
6566 
6567 		svd->vpage = kmem_alloc(bytes, KM_SLEEP);
6568 		bcopy(ovpage, svd->vpage, bytes);
6569 		nsvd->vpage = kmem_alloc(nbytes, KM_SLEEP);
6570 		bcopy(ovpage + seg_pages(seg), nsvd->vpage, nbytes);
6571 		kmem_free(ovpage, bytes + nbytes);
6572 	}
6573 	if (svd->amp != NULL && svd->type == MAP_PRIVATE) {
6574 		struct anon_map *oamp = svd->amp, *namp;
6575 		struct anon_hdr *nahp;
6576 
6577 		ANON_LOCK_ENTER(&oamp->a_rwlock, RW_WRITER);
6578 		ASSERT(oamp->refcnt == 1);
6579 		nahp = anon_create(btop(seg->s_size), ANON_SLEEP);
6580 		(void) anon_copy_ptr(oamp->ahp, svd->anon_index,
6581 		    nahp, 0, btop(seg->s_size), ANON_SLEEP);
6582 
6583 		namp = anonmap_alloc(nseg->s_size, 0, ANON_SLEEP);
6584 		namp->a_szc = nseg->s_szc;
6585 		(void) anon_copy_ptr(oamp->ahp,
6586 		    svd->anon_index + btop(seg->s_size),
6587 		    namp->ahp, 0, btop(nseg->s_size), ANON_SLEEP);
6588 		anon_release(oamp->ahp, btop(oamp->size));
6589 		oamp->ahp = nahp;
6590 		oamp->size = seg->s_size;
6591 		svd->anon_index = 0;
6592 		nsvd->amp = namp;
6593 		nsvd->anon_index = 0;
6594 		ANON_LOCK_EXIT(&oamp->a_rwlock);
6595 	} else if (svd->amp != NULL) {
6596 		pgcnt_t pgcnt = page_get_pagecnt(seg->s_szc);
6597 		ASSERT(svd->amp == nsvd->amp);
6598 		ASSERT(seg->s_szc <= svd->amp->a_szc);
6599 		nsvd->anon_index = svd->anon_index + seg_pages(seg);
6600 		ASSERT(IS_P2ALIGNED(nsvd->anon_index, pgcnt));
6601 		ANON_LOCK_ENTER(&svd->amp->a_rwlock, RW_WRITER);
6602 		svd->amp->refcnt++;
6603 		ANON_LOCK_EXIT(&svd->amp->a_rwlock);
6604 	}
6605 
6606 	/*
6607 	 * Split the amount of swap reserved.
6608 	 */
6609 	if (svd->swresv) {
6610 		/*
6611 		 * For MAP_NORESERVE, only allocate swap reserve for pages
6612 		 * being used.  Other segments get enough to cover whole
6613 		 * segment.
6614 		 */
6615 		if (svd->flags & MAP_NORESERVE) {
6616 			size_t	oswresv;
6617 
6618 			ASSERT(svd->amp);
6619 			oswresv = svd->swresv;
6620 			svd->swresv = ptob(anon_pages(svd->amp->ahp,
6621 			    svd->anon_index, btop(seg->s_size)));
6622 			nsvd->swresv = ptob(anon_pages(nsvd->amp->ahp,
6623 			    nsvd->anon_index, btop(nseg->s_size)));
6624 			ASSERT(oswresv >= (svd->swresv + nsvd->swresv));
6625 		} else {
6626 			if (svd->pageswap) {
6627 				svd->swresv = segvn_count_swap_by_vpages(seg);
6628 				ASSERT(nsvd->swresv >= svd->swresv);
6629 				nsvd->swresv -= svd->swresv;
6630 			} else {
6631 				ASSERT(svd->swresv == seg->s_size +
6632 				    nseg->s_size);
6633 				svd->swresv = seg->s_size;
6634 				nsvd->swresv = nseg->s_size;
6635 			}
6636 		}
6637 	}
6638 
6639 	return (nseg);
6640 }
6641 
6642 /*
6643  * called on memory operations (unmap, setprot, setpagesize) for a subset
6644  * of a large page segment to either demote the memory range (SDR_RANGE)
6645  * or the ends (SDR_END) by addr/len.
6646  *
6647  * returns 0 on success. returns errno, including ENOMEM, on failure.
6648  */
6649 static int
6650 segvn_demote_range(
6651 	struct seg *seg,
6652 	caddr_t addr,
6653 	size_t len,
6654 	int flag,
6655 	uint_t szcvec)
6656 {
6657 	caddr_t eaddr = addr + len;
6658 	caddr_t lpgaddr, lpgeaddr;
6659 	struct seg *nseg;
6660 	struct seg *badseg1 = NULL;
6661 	struct seg *badseg2 = NULL;
6662 	size_t pgsz;
6663 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6664 	int err;
6665 	uint_t szc = seg->s_szc;
6666 	uint_t tszcvec;
6667 
6668 	ASSERT(AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock));
6669 	ASSERT(svd->tr_state == SEGVN_TR_OFF);
6670 	ASSERT(szc != 0);
6671 	pgsz = page_get_pagesize(szc);
6672 	ASSERT(seg->s_base != addr || seg->s_size != len);
6673 	ASSERT(addr >= seg->s_base && eaddr <= seg->s_base + seg->s_size);
6674 	ASSERT(svd->softlockcnt == 0);
6675 	ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
6676 	ASSERT(szcvec == 0 || (flag == SDR_END && svd->type == MAP_SHARED));
6677 
6678 	CALC_LPG_REGION(pgsz, seg, addr, len, lpgaddr, lpgeaddr);
6679 	ASSERT(flag == SDR_RANGE || eaddr < lpgeaddr || addr > lpgaddr);
6680 	if (flag == SDR_RANGE) {
6681 		/* demote entire range */
6682 		badseg1 = nseg = segvn_split_seg(seg, lpgaddr);
6683 		(void) segvn_split_seg(nseg, lpgeaddr);
6684 		ASSERT(badseg1->s_base == lpgaddr);
6685 		ASSERT(badseg1->s_size == lpgeaddr - lpgaddr);
6686 	} else if (addr != lpgaddr) {
6687 		ASSERT(flag == SDR_END);
6688 		badseg1 = nseg = segvn_split_seg(seg, lpgaddr);
6689 		if (eaddr != lpgeaddr && eaddr > lpgaddr + pgsz &&
6690 		    eaddr < lpgaddr + 2 * pgsz) {
6691 			(void) segvn_split_seg(nseg, lpgeaddr);
6692 			ASSERT(badseg1->s_base == lpgaddr);
6693 			ASSERT(badseg1->s_size == 2 * pgsz);
6694 		} else {
6695 			nseg = segvn_split_seg(nseg, lpgaddr + pgsz);
6696 			ASSERT(badseg1->s_base == lpgaddr);
6697 			ASSERT(badseg1->s_size == pgsz);
6698 			if (eaddr != lpgeaddr && eaddr > lpgaddr + pgsz) {
6699 				ASSERT(lpgeaddr - lpgaddr > 2 * pgsz);
6700 				nseg = segvn_split_seg(nseg, lpgeaddr - pgsz);
6701 				badseg2 = nseg;
6702 				(void) segvn_split_seg(nseg, lpgeaddr);
6703 				ASSERT(badseg2->s_base == lpgeaddr - pgsz);
6704 				ASSERT(badseg2->s_size == pgsz);
6705 			}
6706 		}
6707 	} else {
6708 		ASSERT(flag == SDR_END);
6709 		ASSERT(eaddr < lpgeaddr);
6710 		badseg1 = nseg = segvn_split_seg(seg, lpgeaddr - pgsz);
6711 		(void) segvn_split_seg(nseg, lpgeaddr);
6712 		ASSERT(badseg1->s_base == lpgeaddr - pgsz);
6713 		ASSERT(badseg1->s_size == pgsz);
6714 	}
6715 
6716 	ASSERT(badseg1 != NULL);
6717 	ASSERT(badseg1->s_szc == szc);
6718 	ASSERT(flag == SDR_RANGE || badseg1->s_size == pgsz ||
6719 	    badseg1->s_size == 2 * pgsz);
6720 	ASSERT(sameprot(badseg1, badseg1->s_base, pgsz));
6721 	ASSERT(badseg1->s_size == pgsz ||
6722 	    sameprot(badseg1, badseg1->s_base + pgsz, pgsz));
6723 	if (err = segvn_clrszc(badseg1)) {
6724 		return (err);
6725 	}
6726 	ASSERT(badseg1->s_szc == 0);
6727 
6728 	if (szc > 1 && (tszcvec = P2PHASE(szcvec, 1 << szc)) > 1) {
6729 		uint_t tszc = highbit(tszcvec) - 1;
6730 		caddr_t ta = MAX(addr, badseg1->s_base);
6731 		caddr_t te;
6732 		size_t tpgsz = page_get_pagesize(tszc);
6733 
6734 		ASSERT(svd->type == MAP_SHARED);
6735 		ASSERT(flag == SDR_END);
6736 		ASSERT(tszc < szc && tszc > 0);
6737 
6738 		if (eaddr > badseg1->s_base + badseg1->s_size) {
6739 			te = badseg1->s_base + badseg1->s_size;
6740 		} else {
6741 			te = eaddr;
6742 		}
6743 
6744 		ASSERT(ta <= te);
6745 		badseg1->s_szc = tszc;
6746 		if (!IS_P2ALIGNED(ta, tpgsz) || !IS_P2ALIGNED(te, tpgsz)) {
6747 			if (badseg2 != NULL) {
6748 				err = segvn_demote_range(badseg1, ta, te - ta,
6749 				    SDR_END, tszcvec);
6750 				if (err != 0) {
6751 					return (err);
6752 				}
6753 			} else {
6754 				return (segvn_demote_range(badseg1, ta,
6755 				    te - ta, SDR_END, tszcvec));
6756 			}
6757 		}
6758 	}
6759 
6760 	if (badseg2 == NULL)
6761 		return (0);
6762 	ASSERT(badseg2->s_szc == szc);
6763 	ASSERT(badseg2->s_size == pgsz);
6764 	ASSERT(sameprot(badseg2, badseg2->s_base, badseg2->s_size));
6765 	if (err = segvn_clrszc(badseg2)) {
6766 		return (err);
6767 	}
6768 	ASSERT(badseg2->s_szc == 0);
6769 
6770 	if (szc > 1 && (tszcvec = P2PHASE(szcvec, 1 << szc)) > 1) {
6771 		uint_t tszc = highbit(tszcvec) - 1;
6772 		size_t tpgsz = page_get_pagesize(tszc);
6773 
6774 		ASSERT(svd->type == MAP_SHARED);
6775 		ASSERT(flag == SDR_END);
6776 		ASSERT(tszc < szc && tszc > 0);
6777 		ASSERT(badseg2->s_base > addr);
6778 		ASSERT(eaddr > badseg2->s_base);
6779 		ASSERT(eaddr < badseg2->s_base + badseg2->s_size);
6780 
6781 		badseg2->s_szc = tszc;
6782 		if (!IS_P2ALIGNED(eaddr, tpgsz)) {
6783 			return (segvn_demote_range(badseg2, badseg2->s_base,
6784 			    eaddr - badseg2->s_base, SDR_END, tszcvec));
6785 		}
6786 	}
6787 
6788 	return (0);
6789 }
6790 
6791 static int
6792 segvn_checkprot(struct seg *seg, caddr_t addr, size_t len, uint_t prot)
6793 {
6794 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6795 	struct vpage *vp, *evp;
6796 
6797 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
6798 
6799 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
6800 	/*
6801 	 * If segment protection can be used, simply check against them.
6802 	 */
6803 	if (svd->pageprot == 0) {
6804 		int err;
6805 
6806 		err = ((svd->prot & prot) != prot) ? EACCES : 0;
6807 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
6808 		return (err);
6809 	}
6810 
6811 	/*
6812 	 * Have to check down to the vpage level.
6813 	 */
6814 	evp = &svd->vpage[seg_page(seg, addr + len)];
6815 	for (vp = &svd->vpage[seg_page(seg, addr)]; vp < evp; vp++) {
6816 		if ((VPP_PROT(vp) & prot) != prot) {
6817 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
6818 			return (EACCES);
6819 		}
6820 	}
6821 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
6822 	return (0);
6823 }
6824 
6825 static int
6826 segvn_getprot(struct seg *seg, caddr_t addr, size_t len, uint_t *protv)
6827 {
6828 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6829 	size_t pgno = seg_page(seg, addr + len) - seg_page(seg, addr) + 1;
6830 
6831 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
6832 
6833 	if (pgno != 0) {
6834 		SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
6835 		if (svd->pageprot == 0) {
6836 			do {
6837 				protv[--pgno] = svd->prot;
6838 			} while (pgno != 0);
6839 		} else {
6840 			size_t pgoff = seg_page(seg, addr);
6841 
6842 			do {
6843 				pgno--;
6844 				protv[pgno] = VPP_PROT(&svd->vpage[pgno+pgoff]);
6845 			} while (pgno != 0);
6846 		}
6847 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
6848 	}
6849 	return (0);
6850 }
6851 
6852 static u_offset_t
6853 segvn_getoffset(struct seg *seg, caddr_t addr)
6854 {
6855 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6856 
6857 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
6858 
6859 	return (svd->offset + (uintptr_t)(addr - seg->s_base));
6860 }
6861 
6862 /*ARGSUSED*/
6863 static int
6864 segvn_gettype(struct seg *seg, caddr_t addr)
6865 {
6866 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6867 
6868 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
6869 
6870 	return (svd->type | (svd->flags & (MAP_NORESERVE | MAP_TEXT |
6871 	    MAP_INITDATA)));
6872 }
6873 
6874 /*ARGSUSED*/
6875 static int
6876 segvn_getvp(struct seg *seg, caddr_t addr, struct vnode **vpp)
6877 {
6878 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6879 
6880 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
6881 
6882 	*vpp = svd->vp;
6883 	return (0);
6884 }
6885 
6886 /*
6887  * Check to see if it makes sense to do kluster/read ahead to
6888  * addr + delta relative to the mapping at addr.  We assume here
6889  * that delta is a signed PAGESIZE'd multiple (which can be negative).
6890  *
6891  * For segvn, we currently "approve" of the action if we are
6892  * still in the segment and it maps from the same vp/off,
6893  * or if the advice stored in segvn_data or vpages allows it.
6894  * Currently, klustering is not allowed only if MADV_RANDOM is set.
6895  */
6896 static int
6897 segvn_kluster(struct seg *seg, caddr_t addr, ssize_t delta)
6898 {
6899 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
6900 	struct anon *oap, *ap;
6901 	ssize_t pd;
6902 	size_t page;
6903 	struct vnode *vp1, *vp2;
6904 	u_offset_t off1, off2;
6905 	struct anon_map *amp;
6906 
6907 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
6908 	ASSERT(AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock) ||
6909 	    SEGVN_LOCK_HELD(seg->s_as, &svd->lock));
6910 
6911 	if (addr + delta < seg->s_base ||
6912 	    addr + delta >= (seg->s_base + seg->s_size))
6913 		return (-1);		/* exceeded segment bounds */
6914 
6915 	pd = delta / (ssize_t)PAGESIZE;	/* divide to preserve sign bit */
6916 	page = seg_page(seg, addr);
6917 
6918 	/*
6919 	 * Check to see if either of the pages addr or addr + delta
6920 	 * have advice set that prevents klustering (if MADV_RANDOM advice
6921 	 * is set for entire segment, or MADV_SEQUENTIAL is set and delta
6922 	 * is negative).
6923 	 */
6924 	if (svd->advice == MADV_RANDOM ||
6925 	    svd->advice == MADV_SEQUENTIAL && delta < 0)
6926 		return (-1);
6927 	else if (svd->pageadvice && svd->vpage) {
6928 		struct vpage *bvpp, *evpp;
6929 
6930 		bvpp = &svd->vpage[page];
6931 		evpp = &svd->vpage[page + pd];
6932 		if (VPP_ADVICE(bvpp) == MADV_RANDOM ||
6933 		    VPP_ADVICE(evpp) == MADV_SEQUENTIAL && delta < 0)
6934 			return (-1);
6935 		if (VPP_ADVICE(bvpp) != VPP_ADVICE(evpp) &&
6936 		    VPP_ADVICE(evpp) == MADV_RANDOM)
6937 			return (-1);
6938 	}
6939 
6940 	if (svd->type == MAP_SHARED)
6941 		return (0);		/* shared mapping - all ok */
6942 
6943 	if ((amp = svd->amp) == NULL)
6944 		return (0);		/* off original vnode */
6945 
6946 	page += svd->anon_index;
6947 
6948 	ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
6949 
6950 	oap = anon_get_ptr(amp->ahp, page);
6951 	ap = anon_get_ptr(amp->ahp, page + pd);
6952 
6953 	ANON_LOCK_EXIT(&amp->a_rwlock);
6954 
6955 	if ((oap == NULL && ap != NULL) || (oap != NULL && ap == NULL)) {
6956 		return (-1);		/* one with and one without an anon */
6957 	}
6958 
6959 	if (oap == NULL) {		/* implies that ap == NULL */
6960 		return (0);		/* off original vnode */
6961 	}
6962 
6963 	/*
6964 	 * Now we know we have two anon pointers - check to
6965 	 * see if they happen to be properly allocated.
6966 	 */
6967 
6968 	/*
6969 	 * XXX We cheat here and don't lock the anon slots. We can't because
6970 	 * we may have been called from the anon layer which might already
6971 	 * have locked them. We are holding a refcnt on the slots so they
6972 	 * can't disappear. The worst that will happen is we'll get the wrong
6973 	 * names (vp, off) for the slots and make a poor klustering decision.
6974 	 */
6975 	swap_xlate(ap, &vp1, &off1);
6976 	swap_xlate(oap, &vp2, &off2);
6977 
6978 
6979 	if (!VOP_CMP(vp1, vp2, NULL) || off1 - off2 != delta)
6980 		return (-1);
6981 	return (0);
6982 }
6983 
6984 /*
6985  * Swap the pages of seg out to secondary storage, returning the
6986  * number of bytes of storage freed.
6987  *
6988  * The basic idea is first to unload all translations and then to call
6989  * VOP_PUTPAGE() for all newly-unmapped pages, to push them out to the
6990  * swap device.  Pages to which other segments have mappings will remain
6991  * mapped and won't be swapped.  Our caller (as_swapout) has already
6992  * performed the unloading step.
6993  *
6994  * The value returned is intended to correlate well with the process's
6995  * memory requirements.  However, there are some caveats:
6996  * 1)	When given a shared segment as argument, this routine will
6997  *	only succeed in swapping out pages for the last sharer of the
6998  *	segment.  (Previous callers will only have decremented mapping
6999  *	reference counts.)
7000  * 2)	We assume that the hat layer maintains a large enough translation
7001  *	cache to capture process reference patterns.
7002  */
7003 static size_t
7004 segvn_swapout(struct seg *seg)
7005 {
7006 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
7007 	struct anon_map *amp;
7008 	pgcnt_t pgcnt = 0;
7009 	pgcnt_t npages;
7010 	pgcnt_t page;
7011 	ulong_t anon_index;
7012 
7013 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
7014 
7015 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
7016 	/*
7017 	 * Find pages unmapped by our caller and force them
7018 	 * out to the virtual swap device.
7019 	 */
7020 	if ((amp = svd->amp) != NULL)
7021 		anon_index = svd->anon_index;
7022 	npages = seg->s_size >> PAGESHIFT;
7023 	for (page = 0; page < npages; page++) {
7024 		page_t *pp;
7025 		struct anon *ap;
7026 		struct vnode *vp;
7027 		u_offset_t off;
7028 		anon_sync_obj_t cookie;
7029 
7030 		/*
7031 		 * Obtain <vp, off> pair for the page, then look it up.
7032 		 *
7033 		 * Note that this code is willing to consider regular
7034 		 * pages as well as anon pages.  Is this appropriate here?
7035 		 */
7036 		ap = NULL;
7037 		if (amp != NULL) {
7038 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
7039 			if (anon_array_try_enter(amp, anon_index + page,
7040 			    &cookie)) {
7041 				ANON_LOCK_EXIT(&amp->a_rwlock);
7042 				continue;
7043 			}
7044 			ap = anon_get_ptr(amp->ahp, anon_index + page);
7045 			if (ap != NULL) {
7046 				swap_xlate(ap, &vp, &off);
7047 			} else {
7048 				vp = svd->vp;
7049 				off = svd->offset + ptob(page);
7050 			}
7051 			anon_array_exit(&cookie);
7052 			ANON_LOCK_EXIT(&amp->a_rwlock);
7053 		} else {
7054 			vp = svd->vp;
7055 			off = svd->offset + ptob(page);
7056 		}
7057 		if (vp == NULL) {		/* untouched zfod page */
7058 			ASSERT(ap == NULL);
7059 			continue;
7060 		}
7061 
7062 		pp = page_lookup_nowait(vp, off, SE_SHARED);
7063 		if (pp == NULL)
7064 			continue;
7065 
7066 
7067 		/*
7068 		 * Examine the page to see whether it can be tossed out,
7069 		 * keeping track of how many we've found.
7070 		 */
7071 		if (!page_tryupgrade(pp)) {
7072 			/*
7073 			 * If the page has an i/o lock and no mappings,
7074 			 * it's very likely that the page is being
7075 			 * written out as a result of klustering.
7076 			 * Assume this is so and take credit for it here.
7077 			 */
7078 			if (!page_io_trylock(pp)) {
7079 				if (!hat_page_is_mapped(pp))
7080 					pgcnt++;
7081 			} else {
7082 				page_io_unlock(pp);
7083 			}
7084 			page_unlock(pp);
7085 			continue;
7086 		}
7087 		ASSERT(!page_iolock_assert(pp));
7088 
7089 
7090 		/*
7091 		 * Skip if page is locked or has mappings.
7092 		 * We don't need the page_struct_lock to look at lckcnt
7093 		 * and cowcnt because the page is exclusive locked.
7094 		 */
7095 		if (pp->p_lckcnt != 0 || pp->p_cowcnt != 0 ||
7096 		    hat_page_is_mapped(pp)) {
7097 			page_unlock(pp);
7098 			continue;
7099 		}
7100 
7101 		/*
7102 		 * dispose skips large pages so try to demote first.
7103 		 */
7104 		if (pp->p_szc != 0 && !page_try_demote_pages(pp)) {
7105 			page_unlock(pp);
7106 			/*
7107 			 * XXX should skip the remaining page_t's of this
7108 			 * large page.
7109 			 */
7110 			continue;
7111 		}
7112 
7113 		ASSERT(pp->p_szc == 0);
7114 
7115 		/*
7116 		 * No longer mapped -- we can toss it out.  How
7117 		 * we do so depends on whether or not it's dirty.
7118 		 */
7119 		if (hat_ismod(pp) && pp->p_vnode) {
7120 			/*
7121 			 * We must clean the page before it can be
7122 			 * freed.  Setting B_FREE will cause pvn_done
7123 			 * to free the page when the i/o completes.
7124 			 * XXX:	This also causes it to be accounted
7125 			 *	as a pageout instead of a swap: need
7126 			 *	B_SWAPOUT bit to use instead of B_FREE.
7127 			 *
7128 			 * Hold the vnode before releasing the page lock
7129 			 * to prevent it from being freed and re-used by
7130 			 * some other thread.
7131 			 */
7132 			VN_HOLD(vp);
7133 			page_unlock(pp);
7134 
7135 			/*
7136 			 * Queue all i/o requests for the pageout thread
7137 			 * to avoid saturating the pageout devices.
7138 			 */
7139 			if (!queue_io_request(vp, off))
7140 				VN_RELE(vp);
7141 		} else {
7142 			/*
7143 			 * The page was clean, free it.
7144 			 *
7145 			 * XXX:	Can we ever encounter modified pages
7146 			 *	with no associated vnode here?
7147 			 */
7148 			ASSERT(pp->p_vnode != NULL);
7149 			/*LINTED: constant in conditional context*/
7150 			VN_DISPOSE(pp, B_FREE, 0, kcred);
7151 		}
7152 
7153 		/*
7154 		 * Credit now even if i/o is in progress.
7155 		 */
7156 		pgcnt++;
7157 	}
7158 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7159 
7160 	/*
7161 	 * Wakeup pageout to initiate i/o on all queued requests.
7162 	 */
7163 	cv_signal_pageout();
7164 	return (ptob(pgcnt));
7165 }
7166 
7167 /*
7168  * Synchronize primary storage cache with real object in virtual memory.
7169  *
7170  * XXX - Anonymous pages should not be sync'ed out at all.
7171  */
7172 static int
7173 segvn_sync(struct seg *seg, caddr_t addr, size_t len, int attr, uint_t flags)
7174 {
7175 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
7176 	struct vpage *vpp;
7177 	page_t *pp;
7178 	u_offset_t offset;
7179 	struct vnode *vp;
7180 	u_offset_t off;
7181 	caddr_t eaddr;
7182 	int bflags;
7183 	int err = 0;
7184 	int segtype;
7185 	int pageprot;
7186 	int prot;
7187 	ulong_t anon_index;
7188 	struct anon_map *amp;
7189 	struct anon *ap;
7190 	anon_sync_obj_t cookie;
7191 
7192 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
7193 
7194 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
7195 
7196 	if (svd->softlockcnt > 0) {
7197 		/*
7198 		 * If this is shared segment non 0 softlockcnt
7199 		 * means locked pages are still in use.
7200 		 */
7201 		if (svd->type == MAP_SHARED) {
7202 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7203 			return (EAGAIN);
7204 		}
7205 
7206 		/*
7207 		 * flush all pages from seg cache
7208 		 * otherwise we may deadlock in swap_putpage
7209 		 * for B_INVAL page (4175402).
7210 		 *
7211 		 * Even if we grab segvn WRITER's lock
7212 		 * here, there might be another thread which could've
7213 		 * successfully performed lookup/insert just before
7214 		 * we acquired the lock here.  So, grabbing either
7215 		 * lock here is of not much use.  Until we devise
7216 		 * a strategy at upper layers to solve the
7217 		 * synchronization issues completely, we expect
7218 		 * applications to handle this appropriately.
7219 		 */
7220 		segvn_purge(seg);
7221 		if (svd->softlockcnt > 0) {
7222 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7223 			return (EAGAIN);
7224 		}
7225 	} else if (svd->type == MAP_SHARED && svd->amp != NULL &&
7226 	    svd->amp->a_softlockcnt > 0) {
7227 		/*
7228 		 * Try to purge this amp's entries from pcache. It will
7229 		 * succeed only if other segments that share the amp have no
7230 		 * outstanding softlock's.
7231 		 */
7232 		segvn_purge(seg);
7233 		if (svd->amp->a_softlockcnt > 0 || svd->softlockcnt > 0) {
7234 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7235 			return (EAGAIN);
7236 		}
7237 	}
7238 
7239 	vpp = svd->vpage;
7240 	offset = svd->offset + (uintptr_t)(addr - seg->s_base);
7241 	bflags = ((flags & MS_ASYNC) ? B_ASYNC : 0) |
7242 	    ((flags & MS_INVALIDATE) ? B_INVAL : 0);
7243 
7244 	if (attr) {
7245 		pageprot = attr & ~(SHARED|PRIVATE);
7246 		segtype = (attr & SHARED) ? MAP_SHARED : MAP_PRIVATE;
7247 
7248 		/*
7249 		 * We are done if the segment types don't match
7250 		 * or if we have segment level protections and
7251 		 * they don't match.
7252 		 */
7253 		if (svd->type != segtype) {
7254 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7255 			return (0);
7256 		}
7257 		if (vpp == NULL) {
7258 			if (svd->prot != pageprot) {
7259 				SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7260 				return (0);
7261 			}
7262 			prot = svd->prot;
7263 		} else
7264 			vpp = &svd->vpage[seg_page(seg, addr)];
7265 
7266 	} else if (svd->vp && svd->amp == NULL &&
7267 	    (flags & MS_INVALIDATE) == 0) {
7268 
7269 		/*
7270 		 * No attributes, no anonymous pages and MS_INVALIDATE flag
7271 		 * is not on, just use one big request.
7272 		 */
7273 		err = VOP_PUTPAGE(svd->vp, (offset_t)offset, len,
7274 		    bflags, svd->cred, NULL);
7275 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7276 		return (err);
7277 	}
7278 
7279 	if ((amp = svd->amp) != NULL)
7280 		anon_index = svd->anon_index + seg_page(seg, addr);
7281 
7282 	for (eaddr = addr + len; addr < eaddr; addr += PAGESIZE) {
7283 		ap = NULL;
7284 		if (amp != NULL) {
7285 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
7286 			anon_array_enter(amp, anon_index, &cookie);
7287 			ap = anon_get_ptr(amp->ahp, anon_index++);
7288 			if (ap != NULL) {
7289 				swap_xlate(ap, &vp, &off);
7290 			} else {
7291 				vp = svd->vp;
7292 				off = offset;
7293 			}
7294 			anon_array_exit(&cookie);
7295 			ANON_LOCK_EXIT(&amp->a_rwlock);
7296 		} else {
7297 			vp = svd->vp;
7298 			off = offset;
7299 		}
7300 		offset += PAGESIZE;
7301 
7302 		if (vp == NULL)		/* untouched zfod page */
7303 			continue;
7304 
7305 		if (attr) {
7306 			if (vpp) {
7307 				prot = VPP_PROT(vpp);
7308 				vpp++;
7309 			}
7310 			if (prot != pageprot) {
7311 				continue;
7312 			}
7313 		}
7314 
7315 		/*
7316 		 * See if any of these pages are locked --  if so, then we
7317 		 * will have to truncate an invalidate request at the first
7318 		 * locked one. We don't need the page_struct_lock to test
7319 		 * as this is only advisory; even if we acquire it someone
7320 		 * might race in and lock the page after we unlock and before
7321 		 * we do the PUTPAGE, then PUTPAGE simply does nothing.
7322 		 */
7323 		if (flags & MS_INVALIDATE) {
7324 			if ((pp = page_lookup(vp, off, SE_SHARED)) != NULL) {
7325 				if (pp->p_lckcnt != 0 || pp->p_cowcnt != 0) {
7326 					page_unlock(pp);
7327 					SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7328 					return (EBUSY);
7329 				}
7330 				if (ap != NULL && pp->p_szc != 0 &&
7331 				    page_tryupgrade(pp)) {
7332 					if (pp->p_lckcnt == 0 &&
7333 					    pp->p_cowcnt == 0) {
7334 						/*
7335 						 * swapfs VN_DISPOSE() won't
7336 						 * invalidate large pages.
7337 						 * Attempt to demote.
7338 						 * XXX can't help it if it
7339 						 * fails. But for swapfs
7340 						 * pages it is no big deal.
7341 						 */
7342 						(void) page_try_demote_pages(
7343 						    pp);
7344 					}
7345 				}
7346 				page_unlock(pp);
7347 			}
7348 		} else if (svd->type == MAP_SHARED && amp != NULL) {
7349 			/*
7350 			 * Avoid writing out to disk ISM's large pages
7351 			 * because segspt_free_pages() relies on NULL an_pvp
7352 			 * of anon slots of such pages.
7353 			 */
7354 
7355 			ASSERT(svd->vp == NULL);
7356 			/*
7357 			 * swapfs uses page_lookup_nowait if not freeing or
7358 			 * invalidating and skips a page if
7359 			 * page_lookup_nowait returns NULL.
7360 			 */
7361 			pp = page_lookup_nowait(vp, off, SE_SHARED);
7362 			if (pp == NULL) {
7363 				continue;
7364 			}
7365 			if (pp->p_szc != 0) {
7366 				page_unlock(pp);
7367 				continue;
7368 			}
7369 
7370 			/*
7371 			 * Note ISM pages are created large so (vp, off)'s
7372 			 * page cannot suddenly become large after we unlock
7373 			 * pp.
7374 			 */
7375 			page_unlock(pp);
7376 		}
7377 		/*
7378 		 * XXX - Should ultimately try to kluster
7379 		 * calls to VOP_PUTPAGE() for performance.
7380 		 */
7381 		VN_HOLD(vp);
7382 		err = VOP_PUTPAGE(vp, (offset_t)off, PAGESIZE,
7383 		    (bflags | (IS_SWAPFSVP(vp) ? B_PAGE_NOWAIT : 0)),
7384 		    svd->cred, NULL);
7385 
7386 		VN_RELE(vp);
7387 		if (err)
7388 			break;
7389 	}
7390 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7391 	return (err);
7392 }
7393 
7394 /*
7395  * Determine if we have data corresponding to pages in the
7396  * primary storage virtual memory cache (i.e., "in core").
7397  */
7398 static size_t
7399 segvn_incore(struct seg *seg, caddr_t addr, size_t len, char *vec)
7400 {
7401 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
7402 	struct vnode *vp, *avp;
7403 	u_offset_t offset, aoffset;
7404 	size_t p, ep;
7405 	int ret;
7406 	struct vpage *vpp;
7407 	page_t *pp;
7408 	uint_t start;
7409 	struct anon_map *amp;		/* XXX - for locknest */
7410 	struct anon *ap;
7411 	uint_t attr;
7412 	anon_sync_obj_t cookie;
7413 
7414 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
7415 
7416 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
7417 	if (svd->amp == NULL && svd->vp == NULL) {
7418 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7419 		bzero(vec, btopr(len));
7420 		return (len);	/* no anonymous pages created yet */
7421 	}
7422 
7423 	p = seg_page(seg, addr);
7424 	ep = seg_page(seg, addr + len);
7425 	start = svd->vp ? SEG_PAGE_VNODEBACKED : 0;
7426 
7427 	amp = svd->amp;
7428 	for (; p < ep; p++, addr += PAGESIZE) {
7429 		vpp = (svd->vpage) ? &svd->vpage[p]: NULL;
7430 		ret = start;
7431 		ap = NULL;
7432 		avp = NULL;
7433 		/* Grab the vnode/offset for the anon slot */
7434 		if (amp != NULL) {
7435 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
7436 			anon_array_enter(amp, svd->anon_index + p, &cookie);
7437 			ap = anon_get_ptr(amp->ahp, svd->anon_index + p);
7438 			if (ap != NULL) {
7439 				swap_xlate(ap, &avp, &aoffset);
7440 			}
7441 			anon_array_exit(&cookie);
7442 			ANON_LOCK_EXIT(&amp->a_rwlock);
7443 		}
7444 		if ((avp != NULL) && page_exists(avp, aoffset)) {
7445 			/* A page exists for the anon slot */
7446 			ret |= SEG_PAGE_INCORE;
7447 
7448 			/*
7449 			 * If page is mapped and writable
7450 			 */
7451 			attr = (uint_t)0;
7452 			if ((hat_getattr(seg->s_as->a_hat, addr,
7453 			    &attr) != -1) && (attr & PROT_WRITE)) {
7454 				ret |= SEG_PAGE_ANON;
7455 			}
7456 			/*
7457 			 * Don't get page_struct lock for lckcnt and cowcnt,
7458 			 * since this is purely advisory.
7459 			 */
7460 			if ((pp = page_lookup_nowait(avp, aoffset,
7461 			    SE_SHARED)) != NULL) {
7462 				if (pp->p_lckcnt)
7463 					ret |= SEG_PAGE_SOFTLOCK;
7464 				if (pp->p_cowcnt)
7465 					ret |= SEG_PAGE_HASCOW;
7466 				page_unlock(pp);
7467 			}
7468 		}
7469 
7470 		/* Gather vnode statistics */
7471 		vp = svd->vp;
7472 		offset = svd->offset + (uintptr_t)(addr - seg->s_base);
7473 
7474 		if (vp != NULL) {
7475 			/*
7476 			 * Try to obtain a "shared" lock on the page
7477 			 * without blocking.  If this fails, determine
7478 			 * if the page is in memory.
7479 			 */
7480 			pp = page_lookup_nowait(vp, offset, SE_SHARED);
7481 			if ((pp == NULL) && (page_exists(vp, offset))) {
7482 				/* Page is incore, and is named */
7483 				ret |= (SEG_PAGE_INCORE | SEG_PAGE_VNODE);
7484 			}
7485 			/*
7486 			 * Don't get page_struct lock for lckcnt and cowcnt,
7487 			 * since this is purely advisory.
7488 			 */
7489 			if (pp != NULL) {
7490 				ret |= (SEG_PAGE_INCORE | SEG_PAGE_VNODE);
7491 				if (pp->p_lckcnt)
7492 					ret |= SEG_PAGE_SOFTLOCK;
7493 				if (pp->p_cowcnt)
7494 					ret |= SEG_PAGE_HASCOW;
7495 				page_unlock(pp);
7496 			}
7497 		}
7498 
7499 		/* Gather virtual page information */
7500 		if (vpp) {
7501 			if (VPP_ISPPLOCK(vpp))
7502 				ret |= SEG_PAGE_LOCKED;
7503 			vpp++;
7504 		}
7505 
7506 		*vec++ = (char)ret;
7507 	}
7508 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7509 	return (len);
7510 }
7511 
7512 /*
7513  * Statement for p_cowcnts/p_lckcnts.
7514  *
7515  * p_cowcnt is updated while mlock/munlocking MAP_PRIVATE and PROT_WRITE region
7516  * irrespective of the following factors or anything else:
7517  *
7518  *	(1) anon slots are populated or not
7519  *	(2) cow is broken or not
7520  *	(3) refcnt on ap is 1 or greater than 1
7521  *
7522  * If it's not MAP_PRIVATE and PROT_WRITE, p_lckcnt is updated during mlock
7523  * and munlock.
7524  *
7525  *
7526  * Handling p_cowcnts/p_lckcnts during copy-on-write fault:
7527  *
7528  *	if vpage has PROT_WRITE
7529  *		transfer cowcnt on the oldpage -> cowcnt on the newpage
7530  *	else
7531  *		transfer lckcnt on the oldpage -> lckcnt on the newpage
7532  *
7533  *	During copy-on-write, decrement p_cowcnt on the oldpage and increment
7534  *	p_cowcnt on the newpage *if* the corresponding vpage has PROT_WRITE.
7535  *
7536  *	We may also break COW if softlocking on read access in the physio case.
7537  *	In this case, vpage may not have PROT_WRITE. So, we need to decrement
7538  *	p_lckcnt on the oldpage and increment p_lckcnt on the newpage *if* the
7539  *	vpage doesn't have PROT_WRITE.
7540  *
7541  *
7542  * Handling p_cowcnts/p_lckcnts during mprotect on mlocked region:
7543  *
7544  * 	If a MAP_PRIVATE region loses PROT_WRITE, we decrement p_cowcnt and
7545  *	increment p_lckcnt by calling page_subclaim() which takes care of
7546  * 	availrmem accounting and p_lckcnt overflow.
7547  *
7548  *	If a MAP_PRIVATE region gains PROT_WRITE, we decrement p_lckcnt and
7549  *	increment p_cowcnt by calling page_addclaim() which takes care of
7550  *	availrmem availability and p_cowcnt overflow.
7551  */
7552 
7553 /*
7554  * Lock down (or unlock) pages mapped by this segment.
7555  *
7556  * XXX only creates PAGESIZE pages if anon slots are not initialized.
7557  * At fault time they will be relocated into larger pages.
7558  */
7559 static int
7560 segvn_lockop(struct seg *seg, caddr_t addr, size_t len,
7561     int attr, int op, ulong_t *lockmap, size_t pos)
7562 {
7563 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
7564 	struct vpage *vpp;
7565 	struct vpage *evp;
7566 	page_t *pp;
7567 	u_offset_t offset;
7568 	u_offset_t off;
7569 	int segtype;
7570 	int pageprot;
7571 	int claim;
7572 	struct vnode *vp;
7573 	ulong_t anon_index;
7574 	struct anon_map *amp;
7575 	struct anon *ap;
7576 	struct vattr va;
7577 	anon_sync_obj_t cookie;
7578 	struct kshmid *sp = NULL;
7579 	struct proc	*p = curproc;
7580 	kproject_t	*proj = NULL;
7581 	int chargeproc = 1;
7582 	size_t locked_bytes = 0;
7583 	size_t unlocked_bytes = 0;
7584 	int err = 0;
7585 
7586 	/*
7587 	 * Hold write lock on address space because may split or concatenate
7588 	 * segments
7589 	 */
7590 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
7591 
7592 	/*
7593 	 * If this is a shm, use shm's project and zone, else use
7594 	 * project and zone of calling process
7595 	 */
7596 
7597 	/* Determine if this segment backs a sysV shm */
7598 	if (svd->amp != NULL && svd->amp->a_sp != NULL) {
7599 		ASSERT(svd->type == MAP_SHARED);
7600 		ASSERT(svd->tr_state == SEGVN_TR_OFF);
7601 		sp = svd->amp->a_sp;
7602 		proj = sp->shm_perm.ipc_proj;
7603 		chargeproc = 0;
7604 	}
7605 
7606 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_WRITER);
7607 	if (attr) {
7608 		pageprot = attr & ~(SHARED|PRIVATE);
7609 		segtype = attr & SHARED ? MAP_SHARED : MAP_PRIVATE;
7610 
7611 		/*
7612 		 * We are done if the segment types don't match
7613 		 * or if we have segment level protections and
7614 		 * they don't match.
7615 		 */
7616 		if (svd->type != segtype) {
7617 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7618 			return (0);
7619 		}
7620 		if (svd->pageprot == 0 && svd->prot != pageprot) {
7621 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7622 			return (0);
7623 		}
7624 	}
7625 
7626 	if (op == MC_LOCK) {
7627 		if (svd->tr_state == SEGVN_TR_INIT) {
7628 			svd->tr_state = SEGVN_TR_OFF;
7629 		} else if (svd->tr_state == SEGVN_TR_ON) {
7630 			ASSERT(svd->amp != NULL);
7631 			segvn_textunrepl(seg, 0);
7632 			ASSERT(svd->amp == NULL &&
7633 			    svd->tr_state == SEGVN_TR_OFF);
7634 		}
7635 	}
7636 
7637 	/*
7638 	 * If we're locking, then we must create a vpage structure if
7639 	 * none exists.  If we're unlocking, then check to see if there
7640 	 * is a vpage --  if not, then we could not have locked anything.
7641 	 */
7642 
7643 	if ((vpp = svd->vpage) == NULL) {
7644 		if (op == MC_LOCK)
7645 			segvn_vpage(seg);
7646 		else {
7647 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7648 			return (0);
7649 		}
7650 	}
7651 
7652 	/*
7653 	 * The anonymous data vector (i.e., previously
7654 	 * unreferenced mapping to swap space) can be allocated
7655 	 * by lazily testing for its existence.
7656 	 */
7657 	if (op == MC_LOCK && svd->amp == NULL && svd->vp == NULL) {
7658 		ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
7659 		svd->amp = anonmap_alloc(seg->s_size, 0, ANON_SLEEP);
7660 		svd->amp->a_szc = seg->s_szc;
7661 	}
7662 
7663 	if ((amp = svd->amp) != NULL) {
7664 		anon_index = svd->anon_index + seg_page(seg, addr);
7665 	}
7666 
7667 	offset = svd->offset + (uintptr_t)(addr - seg->s_base);
7668 	evp = &svd->vpage[seg_page(seg, addr + len)];
7669 
7670 	if (sp != NULL)
7671 		mutex_enter(&sp->shm_mlock);
7672 
7673 	/* determine number of unlocked bytes in range for lock operation */
7674 	if (op == MC_LOCK) {
7675 
7676 		if (sp == NULL) {
7677 			for (vpp = &svd->vpage[seg_page(seg, addr)]; vpp < evp;
7678 			    vpp++) {
7679 				if (!VPP_ISPPLOCK(vpp))
7680 					unlocked_bytes += PAGESIZE;
7681 			}
7682 		} else {
7683 			ulong_t		i_idx, i_edx;
7684 			anon_sync_obj_t	i_cookie;
7685 			struct anon	*i_ap;
7686 			struct vnode	*i_vp;
7687 			u_offset_t	i_off;
7688 
7689 			/* Only count sysV pages once for locked memory */
7690 			i_edx = svd->anon_index + seg_page(seg, addr + len);
7691 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
7692 			for (i_idx = anon_index; i_idx < i_edx; i_idx++) {
7693 				anon_array_enter(amp, i_idx, &i_cookie);
7694 				i_ap = anon_get_ptr(amp->ahp, i_idx);
7695 				if (i_ap == NULL) {
7696 					unlocked_bytes += PAGESIZE;
7697 					anon_array_exit(&i_cookie);
7698 					continue;
7699 				}
7700 				swap_xlate(i_ap, &i_vp, &i_off);
7701 				anon_array_exit(&i_cookie);
7702 				pp = page_lookup(i_vp, i_off, SE_SHARED);
7703 				if (pp == NULL) {
7704 					unlocked_bytes += PAGESIZE;
7705 					continue;
7706 				} else if (pp->p_lckcnt == 0)
7707 					unlocked_bytes += PAGESIZE;
7708 				page_unlock(pp);
7709 			}
7710 			ANON_LOCK_EXIT(&amp->a_rwlock);
7711 		}
7712 
7713 		mutex_enter(&p->p_lock);
7714 		err = rctl_incr_locked_mem(p, proj, unlocked_bytes,
7715 		    chargeproc);
7716 		mutex_exit(&p->p_lock);
7717 
7718 		if (err) {
7719 			if (sp != NULL)
7720 				mutex_exit(&sp->shm_mlock);
7721 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7722 			return (err);
7723 		}
7724 	}
7725 	/*
7726 	 * Loop over all pages in the range.  Process if we're locking and
7727 	 * page has not already been locked in this mapping; or if we're
7728 	 * unlocking and the page has been locked.
7729 	 */
7730 	for (vpp = &svd->vpage[seg_page(seg, addr)]; vpp < evp;
7731 	    vpp++, pos++, addr += PAGESIZE, offset += PAGESIZE, anon_index++) {
7732 		if ((attr == 0 || VPP_PROT(vpp) == pageprot) &&
7733 		    ((op == MC_LOCK && !VPP_ISPPLOCK(vpp)) ||
7734 		    (op == MC_UNLOCK && VPP_ISPPLOCK(vpp)))) {
7735 
7736 			if (amp != NULL)
7737 				ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
7738 			/*
7739 			 * If this isn't a MAP_NORESERVE segment and
7740 			 * we're locking, allocate anon slots if they
7741 			 * don't exist.  The page is brought in later on.
7742 			 */
7743 			if (op == MC_LOCK && svd->vp == NULL &&
7744 			    ((svd->flags & MAP_NORESERVE) == 0) &&
7745 			    amp != NULL &&
7746 			    ((ap = anon_get_ptr(amp->ahp, anon_index))
7747 			    == NULL)) {
7748 				anon_array_enter(amp, anon_index, &cookie);
7749 
7750 				if ((ap = anon_get_ptr(amp->ahp,
7751 				    anon_index)) == NULL) {
7752 					pp = anon_zero(seg, addr, &ap,
7753 					    svd->cred);
7754 					if (pp == NULL) {
7755 						anon_array_exit(&cookie);
7756 						ANON_LOCK_EXIT(&amp->a_rwlock);
7757 						err = ENOMEM;
7758 						goto out;
7759 					}
7760 					ASSERT(anon_get_ptr(amp->ahp,
7761 					    anon_index) == NULL);
7762 					(void) anon_set_ptr(amp->ahp,
7763 					    anon_index, ap, ANON_SLEEP);
7764 					page_unlock(pp);
7765 				}
7766 				anon_array_exit(&cookie);
7767 			}
7768 
7769 			/*
7770 			 * Get name for page, accounting for
7771 			 * existence of private copy.
7772 			 */
7773 			ap = NULL;
7774 			if (amp != NULL) {
7775 				anon_array_enter(amp, anon_index, &cookie);
7776 				ap = anon_get_ptr(amp->ahp, anon_index);
7777 				if (ap != NULL) {
7778 					swap_xlate(ap, &vp, &off);
7779 				} else {
7780 					if (svd->vp == NULL &&
7781 					    (svd->flags & MAP_NORESERVE)) {
7782 						anon_array_exit(&cookie);
7783 						ANON_LOCK_EXIT(&amp->a_rwlock);
7784 						continue;
7785 					}
7786 					vp = svd->vp;
7787 					off = offset;
7788 				}
7789 				if (op != MC_LOCK || ap == NULL) {
7790 					anon_array_exit(&cookie);
7791 					ANON_LOCK_EXIT(&amp->a_rwlock);
7792 				}
7793 			} else {
7794 				vp = svd->vp;
7795 				off = offset;
7796 			}
7797 
7798 			/*
7799 			 * Get page frame.  It's ok if the page is
7800 			 * not available when we're unlocking, as this
7801 			 * may simply mean that a page we locked got
7802 			 * truncated out of existence after we locked it.
7803 			 *
7804 			 * Invoke VOP_GETPAGE() to obtain the page struct
7805 			 * since we may need to read it from disk if its
7806 			 * been paged out.
7807 			 */
7808 			if (op != MC_LOCK)
7809 				pp = page_lookup(vp, off, SE_SHARED);
7810 			else {
7811 				page_t *pl[1 + 1];
7812 				int error;
7813 
7814 				ASSERT(vp != NULL);
7815 
7816 				error = VOP_GETPAGE(vp, (offset_t)off, PAGESIZE,
7817 				    (uint_t *)NULL, pl, PAGESIZE, seg, addr,
7818 				    S_OTHER, svd->cred, NULL);
7819 
7820 				if (error && ap != NULL) {
7821 					anon_array_exit(&cookie);
7822 					ANON_LOCK_EXIT(&amp->a_rwlock);
7823 				}
7824 
7825 				/*
7826 				 * If the error is EDEADLK then we must bounce
7827 				 * up and drop all vm subsystem locks and then
7828 				 * retry the operation later
7829 				 * This behavior is a temporary measure because
7830 				 * ufs/sds logging is badly designed and will
7831 				 * deadlock if we don't allow this bounce to
7832 				 * happen.  The real solution is to re-design
7833 				 * the logging code to work properly.  See bug
7834 				 * 4125102 for details of the problem.
7835 				 */
7836 				if (error == EDEADLK) {
7837 					err = error;
7838 					goto out;
7839 				}
7840 				/*
7841 				 * Quit if we fail to fault in the page.  Treat
7842 				 * the failure as an error, unless the addr
7843 				 * is mapped beyond the end of a file.
7844 				 */
7845 				if (error && svd->vp) {
7846 					va.va_mask = AT_SIZE;
7847 					if (VOP_GETATTR(svd->vp, &va, 0,
7848 					    svd->cred, NULL) != 0) {
7849 						err = EIO;
7850 						goto out;
7851 					}
7852 					if (btopr(va.va_size) >=
7853 					    btopr(off + 1)) {
7854 						err = EIO;
7855 						goto out;
7856 					}
7857 					goto out;
7858 
7859 				} else if (error) {
7860 					err = EIO;
7861 					goto out;
7862 				}
7863 				pp = pl[0];
7864 				ASSERT(pp != NULL);
7865 			}
7866 
7867 			/*
7868 			 * See Statement at the beginning of this routine.
7869 			 *
7870 			 * claim is always set if MAP_PRIVATE and PROT_WRITE
7871 			 * irrespective of following factors:
7872 			 *
7873 			 * (1) anon slots are populated or not
7874 			 * (2) cow is broken or not
7875 			 * (3) refcnt on ap is 1 or greater than 1
7876 			 *
7877 			 * See 4140683 for details
7878 			 */
7879 			claim = ((VPP_PROT(vpp) & PROT_WRITE) &&
7880 			    (svd->type == MAP_PRIVATE));
7881 
7882 			/*
7883 			 * Perform page-level operation appropriate to
7884 			 * operation.  If locking, undo the SOFTLOCK
7885 			 * performed to bring the page into memory
7886 			 * after setting the lock.  If unlocking,
7887 			 * and no page was found, account for the claim
7888 			 * separately.
7889 			 */
7890 			if (op == MC_LOCK) {
7891 				int ret = 1;	/* Assume success */
7892 
7893 				ASSERT(!VPP_ISPPLOCK(vpp));
7894 
7895 				ret = page_pp_lock(pp, claim, 0);
7896 				if (ap != NULL) {
7897 					if (ap->an_pvp != NULL) {
7898 						anon_swap_free(ap, pp);
7899 					}
7900 					anon_array_exit(&cookie);
7901 					ANON_LOCK_EXIT(&amp->a_rwlock);
7902 				}
7903 				if (ret == 0) {
7904 					/* locking page failed */
7905 					page_unlock(pp);
7906 					err = EAGAIN;
7907 					goto out;
7908 				}
7909 				VPP_SETPPLOCK(vpp);
7910 				if (sp != NULL) {
7911 					if (pp->p_lckcnt == 1)
7912 						locked_bytes += PAGESIZE;
7913 				} else
7914 					locked_bytes += PAGESIZE;
7915 
7916 				if (lockmap != (ulong_t *)NULL)
7917 					BT_SET(lockmap, pos);
7918 
7919 				page_unlock(pp);
7920 			} else {
7921 				ASSERT(VPP_ISPPLOCK(vpp));
7922 				if (pp != NULL) {
7923 					/* sysV pages should be locked */
7924 					ASSERT(sp == NULL || pp->p_lckcnt > 0);
7925 					page_pp_unlock(pp, claim, 0);
7926 					if (sp != NULL) {
7927 						if (pp->p_lckcnt == 0)
7928 							unlocked_bytes
7929 							    += PAGESIZE;
7930 					} else
7931 						unlocked_bytes += PAGESIZE;
7932 					page_unlock(pp);
7933 				} else {
7934 					ASSERT(sp == NULL);
7935 					unlocked_bytes += PAGESIZE;
7936 				}
7937 				VPP_CLRPPLOCK(vpp);
7938 			}
7939 		}
7940 	}
7941 out:
7942 	if (op == MC_LOCK) {
7943 		/* Credit back bytes that did not get locked */
7944 		if ((unlocked_bytes - locked_bytes) > 0) {
7945 			if (proj == NULL)
7946 				mutex_enter(&p->p_lock);
7947 			rctl_decr_locked_mem(p, proj,
7948 			    (unlocked_bytes - locked_bytes), chargeproc);
7949 			if (proj == NULL)
7950 				mutex_exit(&p->p_lock);
7951 		}
7952 
7953 	} else {
7954 		/* Account bytes that were unlocked */
7955 		if (unlocked_bytes > 0) {
7956 			if (proj == NULL)
7957 				mutex_enter(&p->p_lock);
7958 			rctl_decr_locked_mem(p, proj, unlocked_bytes,
7959 			    chargeproc);
7960 			if (proj == NULL)
7961 				mutex_exit(&p->p_lock);
7962 		}
7963 	}
7964 	if (sp != NULL)
7965 		mutex_exit(&sp->shm_mlock);
7966 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
7967 
7968 	return (err);
7969 }
7970 
7971 /*
7972  * Set advice from user for specified pages
7973  * There are 5 types of advice:
7974  *	MADV_NORMAL	- Normal (default) behavior (whatever that is)
7975  *	MADV_RANDOM	- Random page references
7976  *				do not allow readahead or 'klustering'
7977  *	MADV_SEQUENTIAL	- Sequential page references
7978  *				Pages previous to the one currently being
7979  *				accessed (determined by fault) are 'not needed'
7980  *				and are freed immediately
7981  *	MADV_WILLNEED	- Pages are likely to be used (fault ahead in mctl)
7982  *	MADV_DONTNEED	- Pages are not needed (synced out in mctl)
7983  *	MADV_FREE	- Contents can be discarded
7984  *	MADV_ACCESS_DEFAULT- Default access
7985  *	MADV_ACCESS_LWP	- Next LWP will access heavily
7986  *	MADV_ACCESS_MANY- Many LWPs or processes will access heavily
7987  */
7988 static int
7989 segvn_advise(struct seg *seg, caddr_t addr, size_t len, uint_t behav)
7990 {
7991 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
7992 	size_t page;
7993 	int err = 0;
7994 	int already_set;
7995 	struct anon_map *amp;
7996 	ulong_t anon_index;
7997 	struct seg *next;
7998 	lgrp_mem_policy_t policy;
7999 	struct seg *prev;
8000 	struct vnode *vp;
8001 
8002 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
8003 
8004 	/*
8005 	 * In case of MADV_FREE, we won't be modifying any segment private
8006 	 * data structures; so, we only need to grab READER's lock
8007 	 */
8008 	if (behav != MADV_FREE) {
8009 		SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_WRITER);
8010 		if (svd->tr_state != SEGVN_TR_OFF) {
8011 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8012 			return (0);
8013 		}
8014 	} else {
8015 		SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
8016 	}
8017 
8018 	/*
8019 	 * Large pages are assumed to be only turned on when accesses to the
8020 	 * segment's address range have spatial and temporal locality. That
8021 	 * justifies ignoring MADV_SEQUENTIAL for large page segments.
8022 	 * Also, ignore advice affecting lgroup memory allocation
8023 	 * if don't need to do lgroup optimizations on this system
8024 	 */
8025 
8026 	if ((behav == MADV_SEQUENTIAL &&
8027 	    (seg->s_szc != 0 || HAT_IS_REGION_COOKIE_VALID(svd->rcookie))) ||
8028 	    (!lgrp_optimizations() && (behav == MADV_ACCESS_DEFAULT ||
8029 	    behav == MADV_ACCESS_LWP || behav == MADV_ACCESS_MANY))) {
8030 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8031 		return (0);
8032 	}
8033 
8034 	if (behav == MADV_SEQUENTIAL || behav == MADV_ACCESS_DEFAULT ||
8035 	    behav == MADV_ACCESS_LWP || behav == MADV_ACCESS_MANY) {
8036 		/*
8037 		 * Since we are going to unload hat mappings
8038 		 * we first have to flush the cache. Otherwise
8039 		 * this might lead to system panic if another
8040 		 * thread is doing physio on the range whose
8041 		 * mappings are unloaded by madvise(3C).
8042 		 */
8043 		if (svd->softlockcnt > 0) {
8044 			/*
8045 			 * If this is shared segment non 0 softlockcnt
8046 			 * means locked pages are still in use.
8047 			 */
8048 			if (svd->type == MAP_SHARED) {
8049 				SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8050 				return (EAGAIN);
8051 			}
8052 			/*
8053 			 * Since we do have the segvn writers lock
8054 			 * nobody can fill the cache with entries
8055 			 * belonging to this seg during the purge.
8056 			 * The flush either succeeds or we still
8057 			 * have pending I/Os. In the later case,
8058 			 * madvise(3C) fails.
8059 			 */
8060 			segvn_purge(seg);
8061 			if (svd->softlockcnt > 0) {
8062 				/*
8063 				 * Since madvise(3C) is advisory and
8064 				 * it's not part of UNIX98, madvise(3C)
8065 				 * failure here doesn't cause any hardship.
8066 				 * Note that we don't block in "as" layer.
8067 				 */
8068 				SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8069 				return (EAGAIN);
8070 			}
8071 		} else if (svd->type == MAP_SHARED && svd->amp != NULL &&
8072 		    svd->amp->a_softlockcnt > 0) {
8073 			/*
8074 			 * Try to purge this amp's entries from pcache. It
8075 			 * will succeed only if other segments that share the
8076 			 * amp have no outstanding softlock's.
8077 			 */
8078 			segvn_purge(seg);
8079 		}
8080 	}
8081 
8082 	amp = svd->amp;
8083 	vp = svd->vp;
8084 	if (behav == MADV_FREE) {
8085 		/*
8086 		 * MADV_FREE is not supported for segments with
8087 		 * underlying object; if anonmap is NULL, anon slots
8088 		 * are not yet populated and there is nothing for
8089 		 * us to do. As MADV_FREE is advisory, we don't
8090 		 * return error in either case.
8091 		 */
8092 		if (vp != NULL || amp == NULL) {
8093 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8094 			return (0);
8095 		}
8096 
8097 		segvn_purge(seg);
8098 
8099 		page = seg_page(seg, addr);
8100 		ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
8101 		anon_disclaim(amp, svd->anon_index + page, len);
8102 		ANON_LOCK_EXIT(&amp->a_rwlock);
8103 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8104 		return (0);
8105 	}
8106 
8107 	/*
8108 	 * If advice is to be applied to entire segment,
8109 	 * use advice field in seg_data structure
8110 	 * otherwise use appropriate vpage entry.
8111 	 */
8112 	if ((addr == seg->s_base) && (len == seg->s_size)) {
8113 		switch (behav) {
8114 		case MADV_ACCESS_LWP:
8115 		case MADV_ACCESS_MANY:
8116 		case MADV_ACCESS_DEFAULT:
8117 			/*
8118 			 * Set memory allocation policy for this segment
8119 			 */
8120 			policy = lgrp_madv_to_policy(behav, len, svd->type);
8121 			if (svd->type == MAP_SHARED)
8122 				already_set = lgrp_shm_policy_set(policy, amp,
8123 				    svd->anon_index, vp, svd->offset, len);
8124 			else {
8125 				/*
8126 				 * For private memory, need writers lock on
8127 				 * address space because the segment may be
8128 				 * split or concatenated when changing policy
8129 				 */
8130 				if (AS_READ_HELD(seg->s_as,
8131 				    &seg->s_as->a_lock)) {
8132 					SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8133 					return (IE_RETRY);
8134 				}
8135 
8136 				already_set = lgrp_privm_policy_set(policy,
8137 				    &svd->policy_info, len);
8138 			}
8139 
8140 			/*
8141 			 * If policy set already and it shouldn't be reapplied,
8142 			 * don't do anything.
8143 			 */
8144 			if (already_set &&
8145 			    !LGRP_MEM_POLICY_REAPPLICABLE(policy))
8146 				break;
8147 
8148 			/*
8149 			 * Mark any existing pages in given range for
8150 			 * migration
8151 			 */
8152 			page_mark_migrate(seg, addr, len, amp, svd->anon_index,
8153 			    vp, svd->offset, 1);
8154 
8155 			/*
8156 			 * If same policy set already or this is a shared
8157 			 * memory segment, don't need to try to concatenate
8158 			 * segment with adjacent ones.
8159 			 */
8160 			if (already_set || svd->type == MAP_SHARED)
8161 				break;
8162 
8163 			/*
8164 			 * Try to concatenate this segment with previous
8165 			 * one and next one, since we changed policy for
8166 			 * this one and it may be compatible with adjacent
8167 			 * ones now.
8168 			 */
8169 			prev = AS_SEGPREV(seg->s_as, seg);
8170 			next = AS_SEGNEXT(seg->s_as, seg);
8171 
8172 			if (next && next->s_ops == &segvn_ops &&
8173 			    addr + len == next->s_base)
8174 				(void) segvn_concat(seg, next, 1);
8175 
8176 			if (prev && prev->s_ops == &segvn_ops &&
8177 			    addr == prev->s_base + prev->s_size) {
8178 				/*
8179 				 * Drop lock for private data of current
8180 				 * segment before concatenating (deleting) it
8181 				 * and return IE_REATTACH to tell as_ctl() that
8182 				 * current segment has changed
8183 				 */
8184 				SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8185 				if (!segvn_concat(prev, seg, 1))
8186 					err = IE_REATTACH;
8187 
8188 				return (err);
8189 			}
8190 			break;
8191 
8192 		case MADV_SEQUENTIAL:
8193 			/*
8194 			 * unloading mapping guarantees
8195 			 * detection in segvn_fault
8196 			 */
8197 			ASSERT(seg->s_szc == 0);
8198 			ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
8199 			hat_unload(seg->s_as->a_hat, addr, len,
8200 			    HAT_UNLOAD);
8201 			/* FALLTHROUGH */
8202 		case MADV_NORMAL:
8203 		case MADV_RANDOM:
8204 			svd->advice = (uchar_t)behav;
8205 			svd->pageadvice = 0;
8206 			break;
8207 		case MADV_WILLNEED:	/* handled in memcntl */
8208 		case MADV_DONTNEED:	/* handled in memcntl */
8209 		case MADV_FREE:		/* handled above */
8210 			break;
8211 		default:
8212 			err = EINVAL;
8213 		}
8214 	} else {
8215 		caddr_t			eaddr;
8216 		struct seg		*new_seg;
8217 		struct segvn_data	*new_svd;
8218 		u_offset_t		off;
8219 		caddr_t			oldeaddr;
8220 
8221 		page = seg_page(seg, addr);
8222 
8223 		segvn_vpage(seg);
8224 
8225 		switch (behav) {
8226 			struct vpage *bvpp, *evpp;
8227 
8228 		case MADV_ACCESS_LWP:
8229 		case MADV_ACCESS_MANY:
8230 		case MADV_ACCESS_DEFAULT:
8231 			/*
8232 			 * Set memory allocation policy for portion of this
8233 			 * segment
8234 			 */
8235 
8236 			/*
8237 			 * Align address and length of advice to page
8238 			 * boundaries for large pages
8239 			 */
8240 			if (seg->s_szc != 0) {
8241 				size_t	pgsz;
8242 
8243 				pgsz = page_get_pagesize(seg->s_szc);
8244 				addr = (caddr_t)P2ALIGN((uintptr_t)addr, pgsz);
8245 				len = P2ROUNDUP(len, pgsz);
8246 			}
8247 
8248 			/*
8249 			 * Check to see whether policy is set already
8250 			 */
8251 			policy = lgrp_madv_to_policy(behav, len, svd->type);
8252 
8253 			anon_index = svd->anon_index + page;
8254 			off = svd->offset + (uintptr_t)(addr - seg->s_base);
8255 
8256 			if (svd->type == MAP_SHARED)
8257 				already_set = lgrp_shm_policy_set(policy, amp,
8258 				    anon_index, vp, off, len);
8259 			else
8260 				already_set =
8261 				    (policy == svd->policy_info.mem_policy);
8262 
8263 			/*
8264 			 * If policy set already and it shouldn't be reapplied,
8265 			 * don't do anything.
8266 			 */
8267 			if (already_set &&
8268 			    !LGRP_MEM_POLICY_REAPPLICABLE(policy))
8269 				break;
8270 
8271 			/*
8272 			 * For private memory, need writers lock on
8273 			 * address space because the segment may be
8274 			 * split or concatenated when changing policy
8275 			 */
8276 			if (svd->type == MAP_PRIVATE &&
8277 			    AS_READ_HELD(seg->s_as, &seg->s_as->a_lock)) {
8278 				SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8279 				return (IE_RETRY);
8280 			}
8281 
8282 			/*
8283 			 * Mark any existing pages in given range for
8284 			 * migration
8285 			 */
8286 			page_mark_migrate(seg, addr, len, amp, svd->anon_index,
8287 			    vp, svd->offset, 1);
8288 
8289 			/*
8290 			 * Don't need to try to split or concatenate
8291 			 * segments, since policy is same or this is a shared
8292 			 * memory segment
8293 			 */
8294 			if (already_set || svd->type == MAP_SHARED)
8295 				break;
8296 
8297 			if (HAT_IS_REGION_COOKIE_VALID(svd->rcookie)) {
8298 				ASSERT(svd->amp == NULL);
8299 				ASSERT(svd->tr_state == SEGVN_TR_OFF);
8300 				ASSERT(svd->softlockcnt == 0);
8301 				hat_leave_region(seg->s_as->a_hat, svd->rcookie,
8302 				    HAT_REGION_TEXT);
8303 				svd->rcookie = HAT_INVALID_REGION_COOKIE;
8304 			}
8305 
8306 			/*
8307 			 * Split off new segment if advice only applies to a
8308 			 * portion of existing segment starting in middle
8309 			 */
8310 			new_seg = NULL;
8311 			eaddr = addr + len;
8312 			oldeaddr = seg->s_base + seg->s_size;
8313 			if (addr > seg->s_base) {
8314 				/*
8315 				 * Must flush I/O page cache
8316 				 * before splitting segment
8317 				 */
8318 				if (svd->softlockcnt > 0)
8319 					segvn_purge(seg);
8320 
8321 				/*
8322 				 * Split segment and return IE_REATTACH to tell
8323 				 * as_ctl() that current segment changed
8324 				 */
8325 				new_seg = segvn_split_seg(seg, addr);
8326 				new_svd = (struct segvn_data *)new_seg->s_data;
8327 				err = IE_REATTACH;
8328 
8329 				/*
8330 				 * If new segment ends where old one
8331 				 * did, try to concatenate the new
8332 				 * segment with next one.
8333 				 */
8334 				if (eaddr == oldeaddr) {
8335 					/*
8336 					 * Set policy for new segment
8337 					 */
8338 					(void) lgrp_privm_policy_set(policy,
8339 					    &new_svd->policy_info,
8340 					    new_seg->s_size);
8341 
8342 					next = AS_SEGNEXT(new_seg->s_as,
8343 					    new_seg);
8344 
8345 					if (next &&
8346 					    next->s_ops == &segvn_ops &&
8347 					    eaddr == next->s_base)
8348 						(void) segvn_concat(new_seg,
8349 						    next, 1);
8350 				}
8351 			}
8352 
8353 			/*
8354 			 * Split off end of existing segment if advice only
8355 			 * applies to a portion of segment ending before
8356 			 * end of the existing segment
8357 			 */
8358 			if (eaddr < oldeaddr) {
8359 				/*
8360 				 * Must flush I/O page cache
8361 				 * before splitting segment
8362 				 */
8363 				if (svd->softlockcnt > 0)
8364 					segvn_purge(seg);
8365 
8366 				/*
8367 				 * If beginning of old segment was already
8368 				 * split off, use new segment to split end off
8369 				 * from.
8370 				 */
8371 				if (new_seg != NULL && new_seg != seg) {
8372 					/*
8373 					 * Split segment
8374 					 */
8375 					(void) segvn_split_seg(new_seg, eaddr);
8376 
8377 					/*
8378 					 * Set policy for new segment
8379 					 */
8380 					(void) lgrp_privm_policy_set(policy,
8381 					    &new_svd->policy_info,
8382 					    new_seg->s_size);
8383 				} else {
8384 					/*
8385 					 * Split segment and return IE_REATTACH
8386 					 * to tell as_ctl() that current
8387 					 * segment changed
8388 					 */
8389 					(void) segvn_split_seg(seg, eaddr);
8390 					err = IE_REATTACH;
8391 
8392 					(void) lgrp_privm_policy_set(policy,
8393 					    &svd->policy_info, seg->s_size);
8394 
8395 					/*
8396 					 * If new segment starts where old one
8397 					 * did, try to concatenate it with
8398 					 * previous segment.
8399 					 */
8400 					if (addr == seg->s_base) {
8401 						prev = AS_SEGPREV(seg->s_as,
8402 						    seg);
8403 
8404 						/*
8405 						 * Drop lock for private data
8406 						 * of current segment before
8407 						 * concatenating (deleting) it
8408 						 */
8409 						if (prev &&
8410 						    prev->s_ops ==
8411 						    &segvn_ops &&
8412 						    addr == prev->s_base +
8413 						    prev->s_size) {
8414 							SEGVN_LOCK_EXIT(
8415 							    seg->s_as,
8416 							    &svd->lock);
8417 							(void) segvn_concat(
8418 							    prev, seg, 1);
8419 							return (err);
8420 						}
8421 					}
8422 				}
8423 			}
8424 			break;
8425 		case MADV_SEQUENTIAL:
8426 			ASSERT(seg->s_szc == 0);
8427 			ASSERT(svd->rcookie == HAT_INVALID_REGION_COOKIE);
8428 			hat_unload(seg->s_as->a_hat, addr, len, HAT_UNLOAD);
8429 			/* FALLTHROUGH */
8430 		case MADV_NORMAL:
8431 		case MADV_RANDOM:
8432 			bvpp = &svd->vpage[page];
8433 			evpp = &svd->vpage[page + (len >> PAGESHIFT)];
8434 			for (; bvpp < evpp; bvpp++)
8435 				VPP_SETADVICE(bvpp, behav);
8436 			svd->advice = MADV_NORMAL;
8437 			break;
8438 		case MADV_WILLNEED:	/* handled in memcntl */
8439 		case MADV_DONTNEED:	/* handled in memcntl */
8440 		case MADV_FREE:		/* handled above */
8441 			break;
8442 		default:
8443 			err = EINVAL;
8444 		}
8445 	}
8446 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8447 	return (err);
8448 }
8449 
8450 /*
8451  * Create a vpage structure for this seg.
8452  */
8453 static void
8454 segvn_vpage(struct seg *seg)
8455 {
8456 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
8457 	struct vpage *vp, *evp;
8458 
8459 	ASSERT(SEGVN_WRITE_HELD(seg->s_as, &svd->lock));
8460 
8461 	/*
8462 	 * If no vpage structure exists, allocate one.  Copy the protections
8463 	 * and the advice from the segment itself to the individual pages.
8464 	 */
8465 	if (svd->vpage == NULL) {
8466 		svd->pageadvice = 1;
8467 		svd->vpage = kmem_zalloc(seg_pages(seg) * sizeof (struct vpage),
8468 		    KM_SLEEP);
8469 		evp = &svd->vpage[seg_page(seg, seg->s_base + seg->s_size)];
8470 		for (vp = svd->vpage; vp < evp; vp++) {
8471 			VPP_SETPROT(vp, svd->prot);
8472 			VPP_SETADVICE(vp, svd->advice);
8473 		}
8474 	}
8475 }
8476 
8477 /*
8478  * Dump the pages belonging to this segvn segment.
8479  */
8480 static void
8481 segvn_dump(struct seg *seg)
8482 {
8483 	struct segvn_data *svd;
8484 	page_t *pp;
8485 	struct anon_map *amp;
8486 	ulong_t	anon_index;
8487 	struct vnode *vp;
8488 	u_offset_t off, offset;
8489 	pfn_t pfn;
8490 	pgcnt_t page, npages;
8491 	caddr_t addr;
8492 
8493 	npages = seg_pages(seg);
8494 	svd = (struct segvn_data *)seg->s_data;
8495 	vp = svd->vp;
8496 	off = offset = svd->offset;
8497 	addr = seg->s_base;
8498 
8499 	if ((amp = svd->amp) != NULL) {
8500 		anon_index = svd->anon_index;
8501 		ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
8502 	}
8503 
8504 	for (page = 0; page < npages; page++, offset += PAGESIZE) {
8505 		struct anon *ap;
8506 		int we_own_it = 0;
8507 
8508 		if (amp && (ap = anon_get_ptr(svd->amp->ahp, anon_index++))) {
8509 			swap_xlate_nopanic(ap, &vp, &off);
8510 		} else {
8511 			vp = svd->vp;
8512 			off = offset;
8513 		}
8514 
8515 		/*
8516 		 * If pp == NULL, the page either does not exist
8517 		 * or is exclusively locked.  So determine if it
8518 		 * exists before searching for it.
8519 		 */
8520 
8521 		if ((pp = page_lookup_nowait(vp, off, SE_SHARED)))
8522 			we_own_it = 1;
8523 		else
8524 			pp = page_exists(vp, off);
8525 
8526 		if (pp) {
8527 			pfn = page_pptonum(pp);
8528 			dump_addpage(seg->s_as, addr, pfn);
8529 			if (we_own_it)
8530 				page_unlock(pp);
8531 		}
8532 		addr += PAGESIZE;
8533 		dump_timeleft = dump_timeout;
8534 	}
8535 
8536 	if (amp != NULL)
8537 		ANON_LOCK_EXIT(&amp->a_rwlock);
8538 }
8539 
8540 #ifdef DEBUG
8541 static uint32_t segvn_pglock_mtbf = 0;
8542 #endif
8543 
8544 #define	PCACHE_SHWLIST		((page_t *)-2)
8545 #define	NOPCACHE_SHWLIST	((page_t *)-1)
8546 
8547 /*
8548  * Lock/Unlock anon pages over a given range. Return shadow list. This routine
8549  * uses global segment pcache to cache shadow lists (i.e. pp arrays) of pages
8550  * to avoid the overhead of per page locking, unlocking for subsequent IOs to
8551  * the same parts of the segment. Currently shadow list creation is only
8552  * supported for pure anon segments. MAP_PRIVATE segment pcache entries are
8553  * tagged with segment pointer, starting virtual address and length. This
8554  * approach for MAP_SHARED segments may add many pcache entries for the same
8555  * set of pages and lead to long hash chains that decrease pcache lookup
8556  * performance. To avoid this issue for shared segments shared anon map and
8557  * starting anon index are used for pcache entry tagging. This allows all
8558  * segments to share pcache entries for the same anon range and reduces pcache
8559  * chain's length as well as memory overhead from duplicate shadow lists and
8560  * pcache entries.
8561  *
8562  * softlockcnt field in segvn_data structure counts the number of F_SOFTLOCK'd
8563  * pages via segvn_fault() and pagelock'd pages via this routine. But pagelock
8564  * part of softlockcnt accounting is done differently for private and shared
8565  * segments. In private segment case softlock is only incremented when a new
8566  * shadow list is created but not when an existing one is found via
8567  * seg_plookup(). pcache entries have reference count incremented/decremented
8568  * by each seg_plookup()/seg_pinactive() operation. Only entries that have 0
8569  * reference count can be purged (and purging is needed before segment can be
8570  * freed). When a private segment pcache entry is purged segvn_reclaim() will
8571  * decrement softlockcnt. Since in private segment case each of its pcache
8572  * entries only belongs to this segment we can expect that when
8573  * segvn_pagelock(L_PAGEUNLOCK) was called for all outstanding IOs in this
8574  * segment purge will succeed and softlockcnt will drop to 0. In shared
8575  * segment case reference count in pcache entry counts active locks from many
8576  * different segments so we can't expect segment purging to succeed even when
8577  * segvn_pagelock(L_PAGEUNLOCK) was called for all outstanding IOs in this
8578  * segment. To be able to determine when there're no pending pagelocks in
8579  * shared segment case we don't rely on purging to make softlockcnt drop to 0
8580  * but instead softlockcnt is incremented and decremented for every
8581  * segvn_pagelock(L_PAGELOCK/L_PAGEUNLOCK) call regardless if a new shadow
8582  * list was created or an existing one was found. When softlockcnt drops to 0
8583  * this segment no longer has any claims for pcached shadow lists and the
8584  * segment can be freed even if there're still active pcache entries
8585  * shared by this segment anon map. Shared segment pcache entries belong to
8586  * anon map and are typically removed when anon map is freed after all
8587  * processes destroy the segments that use this anon map.
8588  */
8589 static int
8590 segvn_pagelock(struct seg *seg, caddr_t addr, size_t len, struct page ***ppp,
8591     enum lock_type type, enum seg_rw rw)
8592 {
8593 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
8594 	size_t np;
8595 	pgcnt_t adjustpages;
8596 	pgcnt_t npages;
8597 	ulong_t anon_index;
8598 	uint_t protchk = (rw == S_READ) ? PROT_READ : PROT_WRITE;
8599 	uint_t error;
8600 	struct anon_map *amp;
8601 	pgcnt_t anpgcnt;
8602 	struct page **pplist, **pl, *pp;
8603 	caddr_t a;
8604 	size_t page;
8605 	caddr_t lpgaddr, lpgeaddr;
8606 	anon_sync_obj_t cookie;
8607 	int anlock;
8608 	struct anon_map *pamp;
8609 	caddr_t paddr;
8610 	seg_preclaim_cbfunc_t preclaim_callback;
8611 	size_t pgsz;
8612 	int use_pcache;
8613 	size_t wlen;
8614 	uint_t pflags = 0;
8615 	int sftlck_sbase = 0;
8616 	int sftlck_send = 0;
8617 
8618 #ifdef DEBUG
8619 	if (type == L_PAGELOCK && segvn_pglock_mtbf) {
8620 		hrtime_t ts = gethrtime();
8621 		if ((ts % segvn_pglock_mtbf) == 0) {
8622 			return (ENOTSUP);
8623 		}
8624 		if ((ts % segvn_pglock_mtbf) == 1) {
8625 			return (EFAULT);
8626 		}
8627 	}
8628 #endif
8629 
8630 	TRACE_2(TR_FAC_PHYSIO, TR_PHYSIO_SEGVN_START,
8631 	    "segvn_pagelock: start seg %p addr %p", seg, addr);
8632 
8633 	ASSERT(seg->s_as && AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
8634 	ASSERT(type == L_PAGELOCK || type == L_PAGEUNLOCK);
8635 
8636 	SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
8637 
8638 	/*
8639 	 * for now we only support pagelock to anon memory. We would have to
8640 	 * check protections for vnode objects and call into the vnode driver.
8641 	 * That's too much for a fast path. Let the fault entry point handle
8642 	 * it.
8643 	 */
8644 	if (svd->vp != NULL) {
8645 		if (type == L_PAGELOCK) {
8646 			error = ENOTSUP;
8647 			goto out;
8648 		}
8649 		panic("segvn_pagelock(L_PAGEUNLOCK): vp != NULL");
8650 	}
8651 	if ((amp = svd->amp) == NULL) {
8652 		if (type == L_PAGELOCK) {
8653 			error = EFAULT;
8654 			goto out;
8655 		}
8656 		panic("segvn_pagelock(L_PAGEUNLOCK): amp == NULL");
8657 	}
8658 	if (rw != S_READ && rw != S_WRITE) {
8659 		if (type == L_PAGELOCK) {
8660 			error = ENOTSUP;
8661 			goto out;
8662 		}
8663 		panic("segvn_pagelock(L_PAGEUNLOCK): bad rw");
8664 	}
8665 
8666 	if (seg->s_szc != 0) {
8667 		/*
8668 		 * We are adjusting the pagelock region to the large page size
8669 		 * boundary because the unlocked part of a large page cannot
8670 		 * be freed anyway unless all constituent pages of a large
8671 		 * page are locked. Bigger regions reduce pcache chain length
8672 		 * and improve lookup performance. The tradeoff is that the
8673 		 * very first segvn_pagelock() call for a given page is more
8674 		 * expensive if only 1 page_t is needed for IO. This is only
8675 		 * an issue if pcache entry doesn't get reused by several
8676 		 * subsequent calls. We optimize here for the case when pcache
8677 		 * is heavily used by repeated IOs to the same address range.
8678 		 *
8679 		 * Note segment's page size cannot change while we are holding
8680 		 * as lock.  And then it cannot change while softlockcnt is
8681 		 * not 0. This will allow us to correctly recalculate large
8682 		 * page size region for the matching pageunlock/reclaim call
8683 		 * since as_pageunlock() caller must always match
8684 		 * as_pagelock() call's addr and len.
8685 		 *
8686 		 * For pageunlock *ppp points to the pointer of page_t that
8687 		 * corresponds to the real unadjusted start address. Similar
8688 		 * for pagelock *ppp must point to the pointer of page_t that
8689 		 * corresponds to the real unadjusted start address.
8690 		 */
8691 		pgsz = page_get_pagesize(seg->s_szc);
8692 		CALC_LPG_REGION(pgsz, seg, addr, len, lpgaddr, lpgeaddr);
8693 		adjustpages = btop((uintptr_t)(addr - lpgaddr));
8694 	} else if (len < segvn_pglock_comb_thrshld) {
8695 		lpgaddr = addr;
8696 		lpgeaddr = addr + len;
8697 		adjustpages = 0;
8698 		pgsz = PAGESIZE;
8699 	} else {
8700 		/*
8701 		 * Align the address range of large enough requests to allow
8702 		 * combining of different shadow lists into 1 to reduce memory
8703 		 * overhead from potentially overlapping large shadow lists
8704 		 * (worst case is we have a 1MB IO into buffers with start
8705 		 * addresses separated by 4K).  Alignment is only possible if
8706 		 * padded chunks have sufficient access permissions. Note
8707 		 * permissions won't change between L_PAGELOCK and
8708 		 * L_PAGEUNLOCK calls since non 0 softlockcnt will force
8709 		 * segvn_setprot() to wait until softlockcnt drops to 0. This
8710 		 * allows us to determine in L_PAGEUNLOCK the same range we
8711 		 * computed in L_PAGELOCK.
8712 		 *
8713 		 * If alignment is limited by segment ends set
8714 		 * sftlck_sbase/sftlck_send flags. In L_PAGELOCK case when
8715 		 * these flags are set bump softlockcnt_sbase/softlockcnt_send
8716 		 * per segment counters. In L_PAGEUNLOCK case decrease
8717 		 * softlockcnt_sbase/softlockcnt_send counters if
8718 		 * sftlck_sbase/sftlck_send flags are set.  When
8719 		 * softlockcnt_sbase/softlockcnt_send are non 0
8720 		 * segvn_concat()/segvn_extend_prev()/segvn_extend_next()
8721 		 * won't merge the segments. This restriction combined with
8722 		 * restriction on segment unmapping and splitting for segments
8723 		 * that have non 0 softlockcnt allows L_PAGEUNLOCK to
8724 		 * correctly determine the same range that was previously
8725 		 * locked by matching L_PAGELOCK.
8726 		 */
8727 		pflags = SEGP_PSHIFT | (segvn_pglock_comb_bshift << 16);
8728 		pgsz = PAGESIZE;
8729 		if (svd->type == MAP_PRIVATE) {
8730 			lpgaddr = (caddr_t)P2ALIGN((uintptr_t)addr,
8731 			    segvn_pglock_comb_balign);
8732 			if (lpgaddr < seg->s_base) {
8733 				lpgaddr = seg->s_base;
8734 				sftlck_sbase = 1;
8735 			}
8736 		} else {
8737 			ulong_t aix = svd->anon_index + seg_page(seg, addr);
8738 			ulong_t aaix = P2ALIGN(aix, segvn_pglock_comb_palign);
8739 			if (aaix < svd->anon_index) {
8740 				lpgaddr = seg->s_base;
8741 				sftlck_sbase = 1;
8742 			} else {
8743 				lpgaddr = addr - ptob(aix - aaix);
8744 				ASSERT(lpgaddr >= seg->s_base);
8745 			}
8746 		}
8747 		if (svd->pageprot && lpgaddr != addr) {
8748 			struct vpage *vp = &svd->vpage[seg_page(seg, lpgaddr)];
8749 			struct vpage *evp = &svd->vpage[seg_page(seg, addr)];
8750 			while (vp < evp) {
8751 				if ((VPP_PROT(vp) & protchk) == 0) {
8752 					break;
8753 				}
8754 				vp++;
8755 			}
8756 			if (vp < evp) {
8757 				lpgaddr = addr;
8758 				pflags = 0;
8759 			}
8760 		}
8761 		lpgeaddr = addr + len;
8762 		if (pflags) {
8763 			if (svd->type == MAP_PRIVATE) {
8764 				lpgeaddr = (caddr_t)P2ROUNDUP(
8765 				    (uintptr_t)lpgeaddr,
8766 				    segvn_pglock_comb_balign);
8767 			} else {
8768 				ulong_t aix = svd->anon_index +
8769 				    seg_page(seg, lpgeaddr);
8770 				ulong_t aaix = P2ROUNDUP(aix,
8771 				    segvn_pglock_comb_palign);
8772 				if (aaix < aix) {
8773 					lpgeaddr = 0;
8774 				} else {
8775 					lpgeaddr += ptob(aaix - aix);
8776 				}
8777 			}
8778 			if (lpgeaddr == 0 ||
8779 			    lpgeaddr > seg->s_base + seg->s_size) {
8780 				lpgeaddr = seg->s_base + seg->s_size;
8781 				sftlck_send = 1;
8782 			}
8783 		}
8784 		if (svd->pageprot && lpgeaddr != addr + len) {
8785 			struct vpage *vp;
8786 			struct vpage *evp;
8787 
8788 			vp = &svd->vpage[seg_page(seg, addr + len)];
8789 			evp = &svd->vpage[seg_page(seg, lpgeaddr)];
8790 
8791 			while (vp < evp) {
8792 				if ((VPP_PROT(vp) & protchk) == 0) {
8793 					break;
8794 				}
8795 				vp++;
8796 			}
8797 			if (vp < evp) {
8798 				lpgeaddr = addr + len;
8799 			}
8800 		}
8801 		adjustpages = btop((uintptr_t)(addr - lpgaddr));
8802 	}
8803 
8804 	/*
8805 	 * For MAP_SHARED segments we create pcache entries tagged by amp and
8806 	 * anon index so that we can share pcache entries with other segments
8807 	 * that map this amp.  For private segments pcache entries are tagged
8808 	 * with segment and virtual address.
8809 	 */
8810 	if (svd->type == MAP_SHARED) {
8811 		pamp = amp;
8812 		paddr = (caddr_t)((lpgaddr - seg->s_base) +
8813 		    ptob(svd->anon_index));
8814 		preclaim_callback = shamp_reclaim;
8815 	} else {
8816 		pamp = NULL;
8817 		paddr = lpgaddr;
8818 		preclaim_callback = segvn_reclaim;
8819 	}
8820 
8821 	if (type == L_PAGEUNLOCK) {
8822 		VM_STAT_ADD(segvnvmstats.pagelock[0]);
8823 
8824 		/*
8825 		 * update hat ref bits for /proc. We need to make sure
8826 		 * that threads tracing the ref and mod bits of the
8827 		 * address space get the right data.
8828 		 * Note: page ref and mod bits are updated at reclaim time
8829 		 */
8830 		if (seg->s_as->a_vbits) {
8831 			for (a = addr; a < addr + len; a += PAGESIZE) {
8832 				if (rw == S_WRITE) {
8833 					hat_setstat(seg->s_as, a,
8834 					    PAGESIZE, P_REF | P_MOD);
8835 				} else {
8836 					hat_setstat(seg->s_as, a,
8837 					    PAGESIZE, P_REF);
8838 				}
8839 			}
8840 		}
8841 
8842 		/*
8843 		 * Check the shadow list entry after the last page used in
8844 		 * this IO request. If it's NOPCACHE_SHWLIST the shadow list
8845 		 * was not inserted into pcache and is not large page
8846 		 * adjusted.  In this case call reclaim callback directly and
8847 		 * don't adjust the shadow list start and size for large
8848 		 * pages.
8849 		 */
8850 		npages = btop(len);
8851 		if ((*ppp)[npages] == NOPCACHE_SHWLIST) {
8852 			void *ptag;
8853 			if (pamp != NULL) {
8854 				ASSERT(svd->type == MAP_SHARED);
8855 				ptag = (void *)pamp;
8856 				paddr = (caddr_t)((addr - seg->s_base) +
8857 				    ptob(svd->anon_index));
8858 			} else {
8859 				ptag = (void *)seg;
8860 				paddr = addr;
8861 			}
8862 			(*preclaim_callback)(ptag, paddr, len, *ppp, rw, 0);
8863 		} else {
8864 			ASSERT((*ppp)[npages] == PCACHE_SHWLIST ||
8865 			    IS_SWAPFSVP((*ppp)[npages]->p_vnode));
8866 			len = lpgeaddr - lpgaddr;
8867 			npages = btop(len);
8868 			seg_pinactive(seg, pamp, paddr, len,
8869 			    *ppp - adjustpages, rw, pflags, preclaim_callback);
8870 		}
8871 
8872 		if (pamp != NULL) {
8873 			ASSERT(svd->type == MAP_SHARED);
8874 			ASSERT(svd->softlockcnt >= npages);
8875 			atomic_add_long((ulong_t *)&svd->softlockcnt, -npages);
8876 		}
8877 
8878 		if (sftlck_sbase) {
8879 			ASSERT(svd->softlockcnt_sbase > 0);
8880 			atomic_add_long((ulong_t *)&svd->softlockcnt_sbase, -1);
8881 		}
8882 		if (sftlck_send) {
8883 			ASSERT(svd->softlockcnt_send > 0);
8884 			atomic_add_long((ulong_t *)&svd->softlockcnt_send, -1);
8885 		}
8886 
8887 		/*
8888 		 * If someone is blocked while unmapping, we purge
8889 		 * segment page cache and thus reclaim pplist synchronously
8890 		 * without waiting for seg_pasync_thread. This speeds up
8891 		 * unmapping in cases where munmap(2) is called, while
8892 		 * raw async i/o is still in progress or where a thread
8893 		 * exits on data fault in a multithreaded application.
8894 		 */
8895 		if (AS_ISUNMAPWAIT(seg->s_as)) {
8896 			if (svd->softlockcnt == 0) {
8897 				mutex_enter(&seg->s_as->a_contents);
8898 				if (AS_ISUNMAPWAIT(seg->s_as)) {
8899 					AS_CLRUNMAPWAIT(seg->s_as);
8900 					cv_broadcast(&seg->s_as->a_cv);
8901 				}
8902 				mutex_exit(&seg->s_as->a_contents);
8903 			} else if (pamp == NULL) {
8904 				/*
8905 				 * softlockcnt is not 0 and this is a
8906 				 * MAP_PRIVATE segment. Try to purge its
8907 				 * pcache entries to reduce softlockcnt.
8908 				 * If it drops to 0 segvn_reclaim()
8909 				 * will wake up a thread waiting on
8910 				 * unmapwait flag.
8911 				 *
8912 				 * We don't purge MAP_SHARED segments with non
8913 				 * 0 softlockcnt since IO is still in progress
8914 				 * for such segments.
8915 				 */
8916 				ASSERT(svd->type == MAP_PRIVATE);
8917 				segvn_purge(seg);
8918 			}
8919 		}
8920 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8921 		TRACE_2(TR_FAC_PHYSIO, TR_PHYSIO_SEGVN_UNLOCK_END,
8922 		    "segvn_pagelock: unlock seg %p addr %p", seg, addr);
8923 		return (0);
8924 	}
8925 
8926 	/* The L_PAGELOCK case ... */
8927 
8928 	VM_STAT_ADD(segvnvmstats.pagelock[1]);
8929 
8930 	/*
8931 	 * For MAP_SHARED segments we have to check protections before
8932 	 * seg_plookup() since pcache entries may be shared by many segments
8933 	 * with potentially different page protections.
8934 	 */
8935 	if (pamp != NULL) {
8936 		ASSERT(svd->type == MAP_SHARED);
8937 		if (svd->pageprot == 0) {
8938 			if ((svd->prot & protchk) == 0) {
8939 				error = EACCES;
8940 				goto out;
8941 			}
8942 		} else {
8943 			/*
8944 			 * check page protections
8945 			 */
8946 			caddr_t ea;
8947 
8948 			if (seg->s_szc) {
8949 				a = lpgaddr;
8950 				ea = lpgeaddr;
8951 			} else {
8952 				a = addr;
8953 				ea = addr + len;
8954 			}
8955 			for (; a < ea; a += pgsz) {
8956 				struct vpage *vp;
8957 
8958 				ASSERT(seg->s_szc == 0 ||
8959 				    sameprot(seg, a, pgsz));
8960 				vp = &svd->vpage[seg_page(seg, a)];
8961 				if ((VPP_PROT(vp) & protchk) == 0) {
8962 					error = EACCES;
8963 					goto out;
8964 				}
8965 			}
8966 		}
8967 	}
8968 
8969 	/*
8970 	 * try to find pages in segment page cache
8971 	 */
8972 	pplist = seg_plookup(seg, pamp, paddr, lpgeaddr - lpgaddr, rw, pflags);
8973 	if (pplist != NULL) {
8974 		if (pamp != NULL) {
8975 			npages = btop((uintptr_t)(lpgeaddr - lpgaddr));
8976 			ASSERT(svd->type == MAP_SHARED);
8977 			atomic_add_long((ulong_t *)&svd->softlockcnt,
8978 			    npages);
8979 		}
8980 		if (sftlck_sbase) {
8981 			atomic_add_long((ulong_t *)&svd->softlockcnt_sbase, 1);
8982 		}
8983 		if (sftlck_send) {
8984 			atomic_add_long((ulong_t *)&svd->softlockcnt_send, 1);
8985 		}
8986 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
8987 		*ppp = pplist + adjustpages;
8988 		TRACE_2(TR_FAC_PHYSIO, TR_PHYSIO_SEGVN_HIT_END,
8989 		    "segvn_pagelock: cache hit seg %p addr %p", seg, addr);
8990 		return (0);
8991 	}
8992 
8993 	/*
8994 	 * For MAP_SHARED segments we already verified above that segment
8995 	 * protections allow this pagelock operation.
8996 	 */
8997 	if (pamp == NULL) {
8998 		ASSERT(svd->type == MAP_PRIVATE);
8999 		if (svd->pageprot == 0) {
9000 			if ((svd->prot & protchk) == 0) {
9001 				error = EACCES;
9002 				goto out;
9003 			}
9004 			if (svd->prot & PROT_WRITE) {
9005 				wlen = lpgeaddr - lpgaddr;
9006 			} else {
9007 				wlen = 0;
9008 				ASSERT(rw == S_READ);
9009 			}
9010 		} else {
9011 			int wcont = 1;
9012 			/*
9013 			 * check page protections
9014 			 */
9015 			for (a = lpgaddr, wlen = 0; a < lpgeaddr; a += pgsz) {
9016 				struct vpage *vp;
9017 
9018 				ASSERT(seg->s_szc == 0 ||
9019 				    sameprot(seg, a, pgsz));
9020 				vp = &svd->vpage[seg_page(seg, a)];
9021 				if ((VPP_PROT(vp) & protchk) == 0) {
9022 					error = EACCES;
9023 					goto out;
9024 				}
9025 				if (wcont && (VPP_PROT(vp) & PROT_WRITE)) {
9026 					wlen += pgsz;
9027 				} else {
9028 					wcont = 0;
9029 					ASSERT(rw == S_READ);
9030 				}
9031 			}
9032 		}
9033 		ASSERT(rw == S_READ || wlen == lpgeaddr - lpgaddr);
9034 		ASSERT(rw == S_WRITE || wlen <= lpgeaddr - lpgaddr);
9035 	}
9036 
9037 	/*
9038 	 * Only build large page adjusted shadow list if we expect to insert
9039 	 * it into pcache. For large enough pages it's a big overhead to
9040 	 * create a shadow list of the entire large page. But this overhead
9041 	 * should be amortized over repeated pcache hits on subsequent reuse
9042 	 * of this shadow list (IO into any range within this shadow list will
9043 	 * find it in pcache since we large page align the request for pcache
9044 	 * lookups). pcache performance is improved with bigger shadow lists
9045 	 * as it reduces the time to pcache the entire big segment and reduces
9046 	 * pcache chain length.
9047 	 */
9048 	if (seg_pinsert_check(seg, pamp, paddr,
9049 	    lpgeaddr - lpgaddr, pflags) == SEGP_SUCCESS) {
9050 		addr = lpgaddr;
9051 		len = lpgeaddr - lpgaddr;
9052 		use_pcache = 1;
9053 	} else {
9054 		use_pcache = 0;
9055 		/*
9056 		 * Since this entry will not be inserted into the pcache, we
9057 		 * will not do any adjustments to the starting address or
9058 		 * size of the memory to be locked.
9059 		 */
9060 		adjustpages = 0;
9061 	}
9062 	npages = btop(len);
9063 
9064 	pplist = kmem_alloc(sizeof (page_t *) * (npages + 1), KM_SLEEP);
9065 	pl = pplist;
9066 	*ppp = pplist + adjustpages;
9067 	/*
9068 	 * If use_pcache is 0 this shadow list is not large page adjusted.
9069 	 * Record this info in the last entry of shadow array so that
9070 	 * L_PAGEUNLOCK can determine if it should large page adjust the
9071 	 * address range to find the real range that was locked.
9072 	 */
9073 	pl[npages] = use_pcache ? PCACHE_SHWLIST : NOPCACHE_SHWLIST;
9074 
9075 	page = seg_page(seg, addr);
9076 	anon_index = svd->anon_index + page;
9077 
9078 	anlock = 0;
9079 	ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
9080 	ASSERT(amp->a_szc >= seg->s_szc);
9081 	anpgcnt = page_get_pagecnt(amp->a_szc);
9082 	for (a = addr; a < addr + len; a += PAGESIZE, anon_index++) {
9083 		struct anon *ap;
9084 		struct vnode *vp;
9085 		u_offset_t off;
9086 
9087 		/*
9088 		 * Lock and unlock anon array only once per large page.
9089 		 * anon_array_enter() locks the root anon slot according to
9090 		 * a_szc which can't change while anon map is locked.  We lock
9091 		 * anon the first time through this loop and each time we
9092 		 * reach anon index that corresponds to a root of a large
9093 		 * page.
9094 		 */
9095 		if (a == addr || P2PHASE(anon_index, anpgcnt) == 0) {
9096 			ASSERT(anlock == 0);
9097 			anon_array_enter(amp, anon_index, &cookie);
9098 			anlock = 1;
9099 		}
9100 		ap = anon_get_ptr(amp->ahp, anon_index);
9101 
9102 		/*
9103 		 * We must never use seg_pcache for COW pages
9104 		 * because we might end up with original page still
9105 		 * lying in seg_pcache even after private page is
9106 		 * created. This leads to data corruption as
9107 		 * aio_write refers to the page still in cache
9108 		 * while all other accesses refer to the private
9109 		 * page.
9110 		 */
9111 		if (ap == NULL || ap->an_refcnt != 1) {
9112 			struct vpage *vpage;
9113 
9114 			if (seg->s_szc) {
9115 				error = EFAULT;
9116 				break;
9117 			}
9118 			if (svd->vpage != NULL) {
9119 				vpage = &svd->vpage[seg_page(seg, a)];
9120 			} else {
9121 				vpage = NULL;
9122 			}
9123 			ASSERT(anlock);
9124 			anon_array_exit(&cookie);
9125 			anlock = 0;
9126 			pp = NULL;
9127 			error = segvn_faultpage(seg->s_as->a_hat, seg, a, 0,
9128 			    vpage, &pp, 0, F_INVAL, rw, 1);
9129 			if (error) {
9130 				error = fc_decode(error);
9131 				break;
9132 			}
9133 			anon_array_enter(amp, anon_index, &cookie);
9134 			anlock = 1;
9135 			ap = anon_get_ptr(amp->ahp, anon_index);
9136 			if (ap == NULL || ap->an_refcnt != 1) {
9137 				error = EFAULT;
9138 				break;
9139 			}
9140 		}
9141 		swap_xlate(ap, &vp, &off);
9142 		pp = page_lookup_nowait(vp, off, SE_SHARED);
9143 		if (pp == NULL) {
9144 			error = EFAULT;
9145 			break;
9146 		}
9147 		if (ap->an_pvp != NULL) {
9148 			anon_swap_free(ap, pp);
9149 		}
9150 		/*
9151 		 * Unlock anon if this is the last slot in a large page.
9152 		 */
9153 		if (P2PHASE(anon_index, anpgcnt) == anpgcnt - 1) {
9154 			ASSERT(anlock);
9155 			anon_array_exit(&cookie);
9156 			anlock = 0;
9157 		}
9158 		*pplist++ = pp;
9159 	}
9160 	if (anlock) {		/* Ensure the lock is dropped */
9161 		anon_array_exit(&cookie);
9162 	}
9163 	ANON_LOCK_EXIT(&amp->a_rwlock);
9164 
9165 	if (a >= addr + len) {
9166 		atomic_add_long((ulong_t *)&svd->softlockcnt, npages);
9167 		if (pamp != NULL) {
9168 			ASSERT(svd->type == MAP_SHARED);
9169 			atomic_add_long((ulong_t *)&pamp->a_softlockcnt,
9170 			    npages);
9171 			wlen = len;
9172 		}
9173 		if (sftlck_sbase) {
9174 			atomic_add_long((ulong_t *)&svd->softlockcnt_sbase, 1);
9175 		}
9176 		if (sftlck_send) {
9177 			atomic_add_long((ulong_t *)&svd->softlockcnt_send, 1);
9178 		}
9179 		if (use_pcache) {
9180 			(void) seg_pinsert(seg, pamp, paddr, len, wlen, pl,
9181 			    rw, pflags, preclaim_callback);
9182 		}
9183 		SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
9184 		TRACE_2(TR_FAC_PHYSIO, TR_PHYSIO_SEGVN_FILL_END,
9185 		    "segvn_pagelock: cache fill seg %p addr %p", seg, addr);
9186 		return (0);
9187 	}
9188 
9189 	pplist = pl;
9190 	np = ((uintptr_t)(a - addr)) >> PAGESHIFT;
9191 	while (np > (uint_t)0) {
9192 		ASSERT(PAGE_LOCKED(*pplist));
9193 		page_unlock(*pplist);
9194 		np--;
9195 		pplist++;
9196 	}
9197 	kmem_free(pl, sizeof (page_t *) * (npages + 1));
9198 out:
9199 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
9200 	*ppp = NULL;
9201 	TRACE_2(TR_FAC_PHYSIO, TR_PHYSIO_SEGVN_MISS_END,
9202 	    "segvn_pagelock: cache miss seg %p addr %p", seg, addr);
9203 	return (error);
9204 }
9205 
9206 /*
9207  * purge any cached pages in the I/O page cache
9208  */
9209 static void
9210 segvn_purge(struct seg *seg)
9211 {
9212 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
9213 
9214 	/*
9215 	 * pcache is only used by pure anon segments.
9216 	 */
9217 	if (svd->amp == NULL || svd->vp != NULL) {
9218 		return;
9219 	}
9220 
9221 	/*
9222 	 * For MAP_SHARED segments non 0 segment's softlockcnt means
9223 	 * active IO is still in progress via this segment. So we only
9224 	 * purge MAP_SHARED segments when their softlockcnt is 0.
9225 	 */
9226 	if (svd->type == MAP_PRIVATE) {
9227 		if (svd->softlockcnt) {
9228 			seg_ppurge(seg, NULL, 0);
9229 		}
9230 	} else if (svd->softlockcnt == 0 && svd->amp->a_softlockcnt != 0) {
9231 		seg_ppurge(seg, svd->amp, 0);
9232 	}
9233 }
9234 
9235 /*
9236  * If async argument is not 0 we are called from pcache async thread and don't
9237  * hold AS lock.
9238  */
9239 
9240 /*ARGSUSED*/
9241 static int
9242 segvn_reclaim(void *ptag, caddr_t addr, size_t len, struct page **pplist,
9243 	enum seg_rw rw, int async)
9244 {
9245 	struct seg *seg = (struct seg *)ptag;
9246 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
9247 	pgcnt_t np, npages;
9248 	struct page **pl;
9249 
9250 	npages = np = btop(len);
9251 	ASSERT(npages);
9252 
9253 	ASSERT(svd->vp == NULL && svd->amp != NULL);
9254 	ASSERT(svd->softlockcnt >= npages);
9255 	ASSERT(async || AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
9256 
9257 	pl = pplist;
9258 
9259 	ASSERT(pl[np] == NOPCACHE_SHWLIST || pl[np] == PCACHE_SHWLIST);
9260 	ASSERT(!async || pl[np] == PCACHE_SHWLIST);
9261 
9262 	while (np > (uint_t)0) {
9263 		if (rw == S_WRITE) {
9264 			hat_setrefmod(*pplist);
9265 		} else {
9266 			hat_setref(*pplist);
9267 		}
9268 		page_unlock(*pplist);
9269 		np--;
9270 		pplist++;
9271 	}
9272 
9273 	kmem_free(pl, sizeof (page_t *) * (npages + 1));
9274 
9275 	/*
9276 	 * If we are pcache async thread we don't hold AS lock. This means if
9277 	 * softlockcnt drops to 0 after the decrement below address space may
9278 	 * get freed. We can't allow it since after softlock derement to 0 we
9279 	 * still need to access as structure for possible wakeup of unmap
9280 	 * waiters. To prevent the disappearance of as we take this segment
9281 	 * segfree_syncmtx. segvn_free() also takes this mutex as a barrier to
9282 	 * make sure this routine completes before segment is freed.
9283 	 *
9284 	 * The second complication we have to deal with in async case is a
9285 	 * possibility of missed wake up of unmap wait thread. When we don't
9286 	 * hold as lock here we may take a_contents lock before unmap wait
9287 	 * thread that was first to see softlockcnt was still not 0. As a
9288 	 * result we'll fail to wake up an unmap wait thread. To avoid this
9289 	 * race we set nounmapwait flag in as structure if we drop softlockcnt
9290 	 * to 0 when we were called by pcache async thread.  unmapwait thread
9291 	 * will not block if this flag is set.
9292 	 */
9293 	if (async) {
9294 		mutex_enter(&svd->segfree_syncmtx);
9295 	}
9296 
9297 	if (!atomic_add_long_nv((ulong_t *)&svd->softlockcnt, -npages)) {
9298 		if (async || AS_ISUNMAPWAIT(seg->s_as)) {
9299 			mutex_enter(&seg->s_as->a_contents);
9300 			if (async) {
9301 				AS_SETNOUNMAPWAIT(seg->s_as);
9302 			}
9303 			if (AS_ISUNMAPWAIT(seg->s_as)) {
9304 				AS_CLRUNMAPWAIT(seg->s_as);
9305 				cv_broadcast(&seg->s_as->a_cv);
9306 			}
9307 			mutex_exit(&seg->s_as->a_contents);
9308 		}
9309 	}
9310 
9311 	if (async) {
9312 		mutex_exit(&svd->segfree_syncmtx);
9313 	}
9314 	return (0);
9315 }
9316 
9317 /*ARGSUSED*/
9318 static int
9319 shamp_reclaim(void *ptag, caddr_t addr, size_t len, struct page **pplist,
9320 	enum seg_rw rw, int async)
9321 {
9322 	amp_t *amp = (amp_t *)ptag;
9323 	pgcnt_t np, npages;
9324 	struct page **pl;
9325 
9326 	npages = np = btop(len);
9327 	ASSERT(npages);
9328 	ASSERT(amp->a_softlockcnt >= npages);
9329 
9330 	pl = pplist;
9331 
9332 	ASSERT(pl[np] == NOPCACHE_SHWLIST || pl[np] == PCACHE_SHWLIST);
9333 	ASSERT(!async || pl[np] == PCACHE_SHWLIST);
9334 
9335 	while (np > (uint_t)0) {
9336 		if (rw == S_WRITE) {
9337 			hat_setrefmod(*pplist);
9338 		} else {
9339 			hat_setref(*pplist);
9340 		}
9341 		page_unlock(*pplist);
9342 		np--;
9343 		pplist++;
9344 	}
9345 
9346 	kmem_free(pl, sizeof (page_t *) * (npages + 1));
9347 
9348 	/*
9349 	 * If somebody sleeps in anonmap_purge() wake them up if a_softlockcnt
9350 	 * drops to 0. anon map can't be freed until a_softlockcnt drops to 0
9351 	 * and anonmap_purge() acquires a_purgemtx.
9352 	 */
9353 	mutex_enter(&amp->a_purgemtx);
9354 	if (!atomic_add_long_nv((ulong_t *)&amp->a_softlockcnt, -npages) &&
9355 	    amp->a_purgewait) {
9356 		amp->a_purgewait = 0;
9357 		cv_broadcast(&amp->a_purgecv);
9358 	}
9359 	mutex_exit(&amp->a_purgemtx);
9360 	return (0);
9361 }
9362 
9363 /*
9364  * get a memory ID for an addr in a given segment
9365  *
9366  * XXX only creates PAGESIZE pages if anon slots are not initialized.
9367  * At fault time they will be relocated into larger pages.
9368  */
9369 static int
9370 segvn_getmemid(struct seg *seg, caddr_t addr, memid_t *memidp)
9371 {
9372 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
9373 	struct anon 	*ap = NULL;
9374 	ulong_t		anon_index;
9375 	struct anon_map	*amp;
9376 	anon_sync_obj_t cookie;
9377 
9378 	if (svd->type == MAP_PRIVATE) {
9379 		memidp->val[0] = (uintptr_t)seg->s_as;
9380 		memidp->val[1] = (uintptr_t)addr;
9381 		return (0);
9382 	}
9383 
9384 	if (svd->type == MAP_SHARED) {
9385 		if (svd->vp) {
9386 			memidp->val[0] = (uintptr_t)svd->vp;
9387 			memidp->val[1] = (u_longlong_t)svd->offset +
9388 			    (uintptr_t)(addr - seg->s_base);
9389 			return (0);
9390 		} else {
9391 
9392 			SEGVN_LOCK_ENTER(seg->s_as, &svd->lock, RW_READER);
9393 			if ((amp = svd->amp) != NULL) {
9394 				anon_index = svd->anon_index +
9395 				    seg_page(seg, addr);
9396 			}
9397 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
9398 
9399 			ASSERT(amp != NULL);
9400 
9401 			ANON_LOCK_ENTER(&amp->a_rwlock, RW_READER);
9402 			anon_array_enter(amp, anon_index, &cookie);
9403 			ap = anon_get_ptr(amp->ahp, anon_index);
9404 			if (ap == NULL) {
9405 				page_t		*pp;
9406 
9407 				pp = anon_zero(seg, addr, &ap, svd->cred);
9408 				if (pp == NULL) {
9409 					anon_array_exit(&cookie);
9410 					ANON_LOCK_EXIT(&amp->a_rwlock);
9411 					return (ENOMEM);
9412 				}
9413 				ASSERT(anon_get_ptr(amp->ahp, anon_index)
9414 				    == NULL);
9415 				(void) anon_set_ptr(amp->ahp, anon_index,
9416 				    ap, ANON_SLEEP);
9417 				page_unlock(pp);
9418 			}
9419 
9420 			anon_array_exit(&cookie);
9421 			ANON_LOCK_EXIT(&amp->a_rwlock);
9422 
9423 			memidp->val[0] = (uintptr_t)ap;
9424 			memidp->val[1] = (uintptr_t)addr & PAGEOFFSET;
9425 			return (0);
9426 		}
9427 	}
9428 	return (EINVAL);
9429 }
9430 
9431 static int
9432 sameprot(struct seg *seg, caddr_t a, size_t len)
9433 {
9434 	struct segvn_data *svd = (struct segvn_data *)seg->s_data;
9435 	struct vpage *vpage;
9436 	spgcnt_t pages = btop(len);
9437 	uint_t prot;
9438 
9439 	if (svd->pageprot == 0)
9440 		return (1);
9441 
9442 	ASSERT(svd->vpage != NULL);
9443 
9444 	vpage = &svd->vpage[seg_page(seg, a)];
9445 	prot = VPP_PROT(vpage);
9446 	vpage++;
9447 	pages--;
9448 	while (pages-- > 0) {
9449 		if (prot != VPP_PROT(vpage))
9450 			return (0);
9451 		vpage++;
9452 	}
9453 	return (1);
9454 }
9455 
9456 /*
9457  * Get memory allocation policy info for specified address in given segment
9458  */
9459 static lgrp_mem_policy_info_t *
9460 segvn_getpolicy(struct seg *seg, caddr_t addr)
9461 {
9462 	struct anon_map		*amp;
9463 	ulong_t			anon_index;
9464 	lgrp_mem_policy_info_t	*policy_info;
9465 	struct segvn_data	*svn_data;
9466 	u_offset_t		vn_off;
9467 	vnode_t			*vp;
9468 
9469 	ASSERT(seg != NULL);
9470 
9471 	svn_data = (struct segvn_data *)seg->s_data;
9472 	if (svn_data == NULL)
9473 		return (NULL);
9474 
9475 	/*
9476 	 * Get policy info for private or shared memory
9477 	 */
9478 	if (svn_data->type != MAP_SHARED) {
9479 		if (svn_data->tr_state != SEGVN_TR_ON) {
9480 			policy_info = &svn_data->policy_info;
9481 		} else {
9482 			policy_info = &svn_data->tr_policy_info;
9483 			ASSERT(policy_info->mem_policy ==
9484 			    LGRP_MEM_POLICY_NEXT_SEG);
9485 		}
9486 	} else {
9487 		amp = svn_data->amp;
9488 		anon_index = svn_data->anon_index + seg_page(seg, addr);
9489 		vp = svn_data->vp;
9490 		vn_off = svn_data->offset + (uintptr_t)(addr - seg->s_base);
9491 		policy_info = lgrp_shm_policy_get(amp, anon_index, vp, vn_off);
9492 	}
9493 
9494 	return (policy_info);
9495 }
9496 
9497 /*ARGSUSED*/
9498 static int
9499 segvn_capable(struct seg *seg, segcapability_t capability)
9500 {
9501 	return (0);
9502 }
9503 
9504 /*
9505  * Bind text vnode segment to an amp. If we bind successfully mappings will be
9506  * established to per vnode mapping per lgroup amp pages instead of to vnode
9507  * pages. There's one amp per vnode text mapping per lgroup. Many processes
9508  * may share the same text replication amp. If a suitable amp doesn't already
9509  * exist in svntr hash table create a new one.  We may fail to bind to amp if
9510  * segment is not eligible for text replication.  Code below first checks for
9511  * these conditions. If binding is successful segment tr_state is set to on
9512  * and svd->amp points to the amp to use. Otherwise tr_state is set to off and
9513  * svd->amp remains as NULL.
9514  */
9515 static void
9516 segvn_textrepl(struct seg *seg)
9517 {
9518 	struct segvn_data	*svd = (struct segvn_data *)seg->s_data;
9519 	vnode_t			*vp = svd->vp;
9520 	u_offset_t		off = svd->offset;
9521 	size_t			size = seg->s_size;
9522 	u_offset_t		eoff = off + size;
9523 	uint_t			szc = seg->s_szc;
9524 	ulong_t			hash = SVNTR_HASH_FUNC(vp);
9525 	svntr_t			*svntrp;
9526 	struct vattr		va;
9527 	proc_t			*p = seg->s_as->a_proc;
9528 	lgrp_id_t		lgrp_id;
9529 	lgrp_id_t		olid;
9530 	int			first;
9531 	struct anon_map		*amp;
9532 
9533 	ASSERT(AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
9534 	ASSERT(SEGVN_WRITE_HELD(seg->s_as, &svd->lock));
9535 	ASSERT(p != NULL);
9536 	ASSERT(svd->tr_state == SEGVN_TR_INIT);
9537 	ASSERT(!HAT_IS_REGION_COOKIE_VALID(svd->rcookie));
9538 	ASSERT(svd->flags & MAP_TEXT);
9539 	ASSERT(svd->type == MAP_PRIVATE);
9540 	ASSERT(vp != NULL && svd->amp == NULL);
9541 	ASSERT(!svd->pageprot && !(svd->prot & PROT_WRITE));
9542 	ASSERT(!(svd->flags & MAP_NORESERVE) && svd->swresv == 0);
9543 	ASSERT(seg->s_as != &kas);
9544 	ASSERT(off < eoff);
9545 	ASSERT(svntr_hashtab != NULL);
9546 
9547 	/*
9548 	 * If numa optimizations are no longer desired bail out.
9549 	 */
9550 	if (!lgrp_optimizations()) {
9551 		svd->tr_state = SEGVN_TR_OFF;
9552 		return;
9553 	}
9554 
9555 	/*
9556 	 * Avoid creating anon maps with size bigger than the file size.
9557 	 * If VOP_GETATTR() call fails bail out.
9558 	 */
9559 	va.va_mask = AT_SIZE | AT_MTIME | AT_CTIME;
9560 	if (VOP_GETATTR(vp, &va, 0, svd->cred, NULL) != 0) {
9561 		svd->tr_state = SEGVN_TR_OFF;
9562 		SEGVN_TR_ADDSTAT(gaerr);
9563 		return;
9564 	}
9565 	if (btopr(va.va_size) < btopr(eoff)) {
9566 		svd->tr_state = SEGVN_TR_OFF;
9567 		SEGVN_TR_ADDSTAT(overmap);
9568 		return;
9569 	}
9570 
9571 	/*
9572 	 * VVMEXEC may not be set yet if exec() prefaults text segment. Set
9573 	 * this flag now before vn_is_mapped(V_WRITE) so that MAP_SHARED
9574 	 * mapping that checks if trcache for this vnode needs to be
9575 	 * invalidated can't miss us.
9576 	 */
9577 	if (!(vp->v_flag & VVMEXEC)) {
9578 		mutex_enter(&vp->v_lock);
9579 		vp->v_flag |= VVMEXEC;
9580 		mutex_exit(&vp->v_lock);
9581 	}
9582 	mutex_enter(&svntr_hashtab[hash].tr_lock);
9583 	/*
9584 	 * Bail out if potentially MAP_SHARED writable mappings exist to this
9585 	 * vnode.  We don't want to use old file contents from existing
9586 	 * replicas if this mapping was established after the original file
9587 	 * was changed.
9588 	 */
9589 	if (vn_is_mapped(vp, V_WRITE)) {
9590 		mutex_exit(&svntr_hashtab[hash].tr_lock);
9591 		svd->tr_state = SEGVN_TR_OFF;
9592 		SEGVN_TR_ADDSTAT(wrcnt);
9593 		return;
9594 	}
9595 	svntrp = svntr_hashtab[hash].tr_head;
9596 	for (; svntrp != NULL; svntrp = svntrp->tr_next) {
9597 		ASSERT(svntrp->tr_refcnt != 0);
9598 		if (svntrp->tr_vp != vp) {
9599 			continue;
9600 		}
9601 
9602 		/*
9603 		 * Bail out if the file or its attributes were changed after
9604 		 * this replication entry was created since we need to use the
9605 		 * latest file contents. Note that mtime test alone is not
9606 		 * sufficient because a user can explicitly change mtime via
9607 		 * utimes(2) interfaces back to the old value after modifiying
9608 		 * the file contents. To detect this case we also have to test
9609 		 * ctime which among other things records the time of the last
9610 		 * mtime change by utimes(2). ctime is not changed when the file
9611 		 * is only read or executed so we expect that typically existing
9612 		 * replication amp's can be used most of the time.
9613 		 */
9614 		if (!svntrp->tr_valid ||
9615 		    svntrp->tr_mtime.tv_sec != va.va_mtime.tv_sec ||
9616 		    svntrp->tr_mtime.tv_nsec != va.va_mtime.tv_nsec ||
9617 		    svntrp->tr_ctime.tv_sec != va.va_ctime.tv_sec ||
9618 		    svntrp->tr_ctime.tv_nsec != va.va_ctime.tv_nsec) {
9619 			mutex_exit(&svntr_hashtab[hash].tr_lock);
9620 			svd->tr_state = SEGVN_TR_OFF;
9621 			SEGVN_TR_ADDSTAT(stale);
9622 			return;
9623 		}
9624 		/*
9625 		 * if off, eoff and szc match current segment we found the
9626 		 * existing entry we can use.
9627 		 */
9628 		if (svntrp->tr_off == off && svntrp->tr_eoff == eoff &&
9629 		    svntrp->tr_szc == szc) {
9630 			break;
9631 		}
9632 		/*
9633 		 * Don't create different but overlapping in file offsets
9634 		 * entries to avoid replication of the same file pages more
9635 		 * than once per lgroup.
9636 		 */
9637 		if ((off >= svntrp->tr_off && off < svntrp->tr_eoff) ||
9638 		    (eoff > svntrp->tr_off && eoff <= svntrp->tr_eoff)) {
9639 			mutex_exit(&svntr_hashtab[hash].tr_lock);
9640 			svd->tr_state = SEGVN_TR_OFF;
9641 			SEGVN_TR_ADDSTAT(overlap);
9642 			return;
9643 		}
9644 	}
9645 	/*
9646 	 * If we didn't find existing entry create a new one.
9647 	 */
9648 	if (svntrp == NULL) {
9649 		svntrp = kmem_cache_alloc(svntr_cache, KM_NOSLEEP);
9650 		if (svntrp == NULL) {
9651 			mutex_exit(&svntr_hashtab[hash].tr_lock);
9652 			svd->tr_state = SEGVN_TR_OFF;
9653 			SEGVN_TR_ADDSTAT(nokmem);
9654 			return;
9655 		}
9656 #ifdef DEBUG
9657 		{
9658 			lgrp_id_t i;
9659 			for (i = 0; i < NLGRPS_MAX; i++) {
9660 				ASSERT(svntrp->tr_amp[i] == NULL);
9661 			}
9662 		}
9663 #endif /* DEBUG */
9664 		svntrp->tr_vp = vp;
9665 		svntrp->tr_off = off;
9666 		svntrp->tr_eoff = eoff;
9667 		svntrp->tr_szc = szc;
9668 		svntrp->tr_valid = 1;
9669 		svntrp->tr_mtime = va.va_mtime;
9670 		svntrp->tr_ctime = va.va_ctime;
9671 		svntrp->tr_refcnt = 0;
9672 		svntrp->tr_next = svntr_hashtab[hash].tr_head;
9673 		svntr_hashtab[hash].tr_head = svntrp;
9674 	}
9675 	first = 1;
9676 again:
9677 	/*
9678 	 * We want to pick a replica with pages on main thread's (t_tid = 1,
9679 	 * aka T1) lgrp. Currently text replication is only optimized for
9680 	 * workloads that either have all threads of a process on the same
9681 	 * lgrp or execute their large text primarily on main thread.
9682 	 */
9683 	lgrp_id = p->p_t1_lgrpid;
9684 	if (lgrp_id == LGRP_NONE) {
9685 		/*
9686 		 * In case exec() prefaults text on non main thread use
9687 		 * current thread lgrpid.  It will become main thread anyway
9688 		 * soon.
9689 		 */
9690 		lgrp_id = lgrp_home_id(curthread);
9691 	}
9692 	/*
9693 	 * Set p_tr_lgrpid to lgrpid if it hasn't been set yet.  Otherwise
9694 	 * just set it to NLGRPS_MAX if it's different from current process T1
9695 	 * home lgrp.  p_tr_lgrpid is used to detect if process uses text
9696 	 * replication and T1 new home is different from lgrp used for text
9697 	 * replication. When this happens asyncronous segvn thread rechecks if
9698 	 * segments should change lgrps used for text replication.  If we fail
9699 	 * to set p_tr_lgrpid with cas32 then set it to NLGRPS_MAX without cas
9700 	 * if it's not already NLGRPS_MAX and not equal lgrp_id we want to
9701 	 * use.  We don't need to use cas in this case because another thread
9702 	 * that races in between our non atomic check and set may only change
9703 	 * p_tr_lgrpid to NLGRPS_MAX at this point.
9704 	 */
9705 	ASSERT(lgrp_id != LGRP_NONE && lgrp_id < NLGRPS_MAX);
9706 	olid = p->p_tr_lgrpid;
9707 	if (lgrp_id != olid && olid != NLGRPS_MAX) {
9708 		lgrp_id_t nlid = (olid == LGRP_NONE) ? lgrp_id : NLGRPS_MAX;
9709 		if (cas32((uint32_t *)&p->p_tr_lgrpid, olid, nlid) != olid) {
9710 			olid = p->p_tr_lgrpid;
9711 			ASSERT(olid != LGRP_NONE);
9712 			if (olid != lgrp_id && olid != NLGRPS_MAX) {
9713 				p->p_tr_lgrpid = NLGRPS_MAX;
9714 			}
9715 		}
9716 		ASSERT(p->p_tr_lgrpid != LGRP_NONE);
9717 		membar_producer();
9718 		/*
9719 		 * lgrp_move_thread() won't schedule async recheck after
9720 		 * p->p_t1_lgrpid update unless p->p_tr_lgrpid is not
9721 		 * LGRP_NONE. Recheck p_t1_lgrpid once now that p->p_tr_lgrpid
9722 		 * is not LGRP_NONE.
9723 		 */
9724 		if (first && p->p_t1_lgrpid != LGRP_NONE &&
9725 		    p->p_t1_lgrpid != lgrp_id) {
9726 			first = 0;
9727 			goto again;
9728 		}
9729 	}
9730 	/*
9731 	 * If no amp was created yet for lgrp_id create a new one as long as
9732 	 * we have enough memory to afford it.
9733 	 */
9734 	if ((amp = svntrp->tr_amp[lgrp_id]) == NULL) {
9735 		size_t trmem = atomic_add_long_nv(&segvn_textrepl_bytes, size);
9736 		if (trmem > segvn_textrepl_max_bytes) {
9737 			SEGVN_TR_ADDSTAT(normem);
9738 			goto fail;
9739 		}
9740 		if (anon_try_resv_zone(size, NULL) == 0) {
9741 			SEGVN_TR_ADDSTAT(noanon);
9742 			goto fail;
9743 		}
9744 		amp = anonmap_alloc(size, size, ANON_NOSLEEP);
9745 		if (amp == NULL) {
9746 			anon_unresv_zone(size, NULL);
9747 			SEGVN_TR_ADDSTAT(nokmem);
9748 			goto fail;
9749 		}
9750 		ASSERT(amp->refcnt == 1);
9751 		amp->a_szc = szc;
9752 		svntrp->tr_amp[lgrp_id] = amp;
9753 		SEGVN_TR_ADDSTAT(newamp);
9754 	}
9755 	svntrp->tr_refcnt++;
9756 	ASSERT(svd->svn_trnext == NULL);
9757 	ASSERT(svd->svn_trprev == NULL);
9758 	svd->svn_trnext = svntrp->tr_svnhead;
9759 	svd->svn_trprev = NULL;
9760 	if (svntrp->tr_svnhead != NULL) {
9761 		svntrp->tr_svnhead->svn_trprev = svd;
9762 	}
9763 	svntrp->tr_svnhead = svd;
9764 	ASSERT(amp->a_szc == szc && amp->size == size && amp->swresv == size);
9765 	ASSERT(amp->refcnt >= 1);
9766 	svd->amp = amp;
9767 	svd->anon_index = 0;
9768 	svd->tr_policy_info.mem_policy = LGRP_MEM_POLICY_NEXT_SEG;
9769 	svd->tr_policy_info.mem_lgrpid = lgrp_id;
9770 	svd->tr_state = SEGVN_TR_ON;
9771 	mutex_exit(&svntr_hashtab[hash].tr_lock);
9772 	SEGVN_TR_ADDSTAT(repl);
9773 	return;
9774 fail:
9775 	ASSERT(segvn_textrepl_bytes >= size);
9776 	atomic_add_long(&segvn_textrepl_bytes, -size);
9777 	ASSERT(svntrp != NULL);
9778 	ASSERT(svntrp->tr_amp[lgrp_id] == NULL);
9779 	if (svntrp->tr_refcnt == 0) {
9780 		ASSERT(svntrp == svntr_hashtab[hash].tr_head);
9781 		svntr_hashtab[hash].tr_head = svntrp->tr_next;
9782 		mutex_exit(&svntr_hashtab[hash].tr_lock);
9783 		kmem_cache_free(svntr_cache, svntrp);
9784 	} else {
9785 		mutex_exit(&svntr_hashtab[hash].tr_lock);
9786 	}
9787 	svd->tr_state = SEGVN_TR_OFF;
9788 }
9789 
9790 /*
9791  * Convert seg back to regular vnode mapping seg by unbinding it from its text
9792  * replication amp.  This routine is most typically called when segment is
9793  * unmapped but can also be called when segment no longer qualifies for text
9794  * replication (e.g. due to protection changes). If unload_unmap is set use
9795  * HAT_UNLOAD_UNMAP flag in hat_unload_callback().  If we are the last user of
9796  * svntr free all its anon maps and remove it from the hash table.
9797  */
9798 static void
9799 segvn_textunrepl(struct seg *seg, int unload_unmap)
9800 {
9801 	struct segvn_data	*svd = (struct segvn_data *)seg->s_data;
9802 	vnode_t			*vp = svd->vp;
9803 	u_offset_t		off = svd->offset;
9804 	size_t			size = seg->s_size;
9805 	u_offset_t		eoff = off + size;
9806 	uint_t			szc = seg->s_szc;
9807 	ulong_t			hash = SVNTR_HASH_FUNC(vp);
9808 	svntr_t			*svntrp;
9809 	svntr_t			**prv_svntrp;
9810 	lgrp_id_t		lgrp_id = svd->tr_policy_info.mem_lgrpid;
9811 	lgrp_id_t		i;
9812 
9813 	ASSERT(AS_LOCK_HELD(seg->s_as, &seg->s_as->a_lock));
9814 	ASSERT(AS_WRITE_HELD(seg->s_as, &seg->s_as->a_lock) ||
9815 	    SEGVN_WRITE_HELD(seg->s_as, &svd->lock));
9816 	ASSERT(svd->tr_state == SEGVN_TR_ON);
9817 	ASSERT(!HAT_IS_REGION_COOKIE_VALID(svd->rcookie));
9818 	ASSERT(svd->amp != NULL);
9819 	ASSERT(svd->amp->refcnt >= 1);
9820 	ASSERT(svd->anon_index == 0);
9821 	ASSERT(lgrp_id != LGRP_NONE && lgrp_id < NLGRPS_MAX);
9822 	ASSERT(svntr_hashtab != NULL);
9823 
9824 	mutex_enter(&svntr_hashtab[hash].tr_lock);
9825 	prv_svntrp = &svntr_hashtab[hash].tr_head;
9826 	for (; (svntrp = *prv_svntrp) != NULL; prv_svntrp = &svntrp->tr_next) {
9827 		ASSERT(svntrp->tr_refcnt != 0);
9828 		if (svntrp->tr_vp == vp && svntrp->tr_off == off &&
9829 		    svntrp->tr_eoff == eoff && svntrp->tr_szc == szc) {
9830 			break;
9831 		}
9832 	}
9833 	if (svntrp == NULL) {
9834 		panic("segvn_textunrepl: svntr record not found");
9835 	}
9836 	if (svntrp->tr_amp[lgrp_id] != svd->amp) {
9837 		panic("segvn_textunrepl: amp mismatch");
9838 	}
9839 	svd->tr_state = SEGVN_TR_OFF;
9840 	svd->amp = NULL;
9841 	if (svd->svn_trprev == NULL) {
9842 		ASSERT(svntrp->tr_svnhead == svd);
9843 		svntrp->tr_svnhead = svd->svn_trnext;
9844 		if (svntrp->tr_svnhead != NULL) {
9845 			svntrp->tr_svnhead->svn_trprev = NULL;
9846 		}
9847 		svd->svn_trnext = NULL;
9848 	} else {
9849 		svd->svn_trprev->svn_trnext = svd->svn_trnext;
9850 		if (svd->svn_trnext != NULL) {
9851 			svd->svn_trnext->svn_trprev = svd->svn_trprev;
9852 			svd->svn_trnext = NULL;
9853 		}
9854 		svd->svn_trprev = NULL;
9855 	}
9856 	if (--svntrp->tr_refcnt) {
9857 		mutex_exit(&svntr_hashtab[hash].tr_lock);
9858 		goto done;
9859 	}
9860 	*prv_svntrp = svntrp->tr_next;
9861 	mutex_exit(&svntr_hashtab[hash].tr_lock);
9862 	for (i = 0; i < NLGRPS_MAX; i++) {
9863 		struct anon_map *amp = svntrp->tr_amp[i];
9864 		if (amp == NULL) {
9865 			continue;
9866 		}
9867 		ASSERT(amp->refcnt == 1);
9868 		ASSERT(amp->swresv == size);
9869 		ASSERT(amp->size == size);
9870 		ASSERT(amp->a_szc == szc);
9871 		if (amp->a_szc != 0) {
9872 			anon_free_pages(amp->ahp, 0, size, szc);
9873 		} else {
9874 			anon_free(amp->ahp, 0, size);
9875 		}
9876 		svntrp->tr_amp[i] = NULL;
9877 		ASSERT(segvn_textrepl_bytes >= size);
9878 		atomic_add_long(&segvn_textrepl_bytes, -size);
9879 		anon_unresv_zone(amp->swresv, NULL);
9880 		amp->refcnt = 0;
9881 		anonmap_free(amp);
9882 	}
9883 	kmem_cache_free(svntr_cache, svntrp);
9884 done:
9885 	hat_unload_callback(seg->s_as->a_hat, seg->s_base, size,
9886 	    unload_unmap ? HAT_UNLOAD_UNMAP : 0, NULL);
9887 }
9888 
9889 /*
9890  * This is called when a MAP_SHARED writable mapping is created to a vnode
9891  * that is currently used for execution (VVMEXEC flag is set). In this case we
9892  * need to prevent further use of existing replicas.
9893  */
9894 static void
9895 segvn_inval_trcache(vnode_t *vp)
9896 {
9897 	ulong_t			hash = SVNTR_HASH_FUNC(vp);
9898 	svntr_t			*svntrp;
9899 
9900 	ASSERT(vp->v_flag & VVMEXEC);
9901 
9902 	if (svntr_hashtab == NULL) {
9903 		return;
9904 	}
9905 
9906 	mutex_enter(&svntr_hashtab[hash].tr_lock);
9907 	svntrp = svntr_hashtab[hash].tr_head;
9908 	for (; svntrp != NULL; svntrp = svntrp->tr_next) {
9909 		ASSERT(svntrp->tr_refcnt != 0);
9910 		if (svntrp->tr_vp == vp && svntrp->tr_valid) {
9911 			svntrp->tr_valid = 0;
9912 		}
9913 	}
9914 	mutex_exit(&svntr_hashtab[hash].tr_lock);
9915 }
9916 
9917 static void
9918 segvn_trasync_thread(void)
9919 {
9920 	callb_cpr_t cpr_info;
9921 	kmutex_t cpr_lock;	/* just for CPR stuff */
9922 
9923 	mutex_init(&cpr_lock, NULL, MUTEX_DEFAULT, NULL);
9924 
9925 	CALLB_CPR_INIT(&cpr_info, &cpr_lock,
9926 	    callb_generic_cpr, "segvn_async");
9927 
9928 	if (segvn_update_textrepl_interval == 0) {
9929 		segvn_update_textrepl_interval = segvn_update_tr_time * hz;
9930 	} else {
9931 		segvn_update_textrepl_interval *= hz;
9932 	}
9933 	(void) timeout(segvn_trupdate_wakeup, NULL,
9934 	    segvn_update_textrepl_interval);
9935 
9936 	for (;;) {
9937 		mutex_enter(&cpr_lock);
9938 		CALLB_CPR_SAFE_BEGIN(&cpr_info);
9939 		mutex_exit(&cpr_lock);
9940 		sema_p(&segvn_trasync_sem);
9941 		mutex_enter(&cpr_lock);
9942 		CALLB_CPR_SAFE_END(&cpr_info, &cpr_lock);
9943 		mutex_exit(&cpr_lock);
9944 		segvn_trupdate();
9945 	}
9946 }
9947 
9948 static uint64_t segvn_lgrp_trthr_migrs_snpsht = 0;
9949 
9950 static void
9951 segvn_trupdate_wakeup(void *dummy)
9952 {
9953 	uint64_t cur_lgrp_trthr_migrs = lgrp_get_trthr_migrations();
9954 
9955 	if (cur_lgrp_trthr_migrs != segvn_lgrp_trthr_migrs_snpsht) {
9956 		segvn_lgrp_trthr_migrs_snpsht = cur_lgrp_trthr_migrs;
9957 		sema_v(&segvn_trasync_sem);
9958 	}
9959 
9960 	if (!segvn_disable_textrepl_update &&
9961 	    segvn_update_textrepl_interval != 0) {
9962 		(void) timeout(segvn_trupdate_wakeup, dummy,
9963 		    segvn_update_textrepl_interval);
9964 	}
9965 }
9966 
9967 static void
9968 segvn_trupdate(void)
9969 {
9970 	ulong_t		hash;
9971 	svntr_t		*svntrp;
9972 	segvn_data_t	*svd;
9973 
9974 	ASSERT(svntr_hashtab != NULL);
9975 
9976 	for (hash = 0; hash < svntr_hashtab_sz; hash++) {
9977 		mutex_enter(&svntr_hashtab[hash].tr_lock);
9978 		svntrp = svntr_hashtab[hash].tr_head;
9979 		for (; svntrp != NULL; svntrp = svntrp->tr_next) {
9980 			ASSERT(svntrp->tr_refcnt != 0);
9981 			svd = svntrp->tr_svnhead;
9982 			for (; svd != NULL; svd = svd->svn_trnext) {
9983 				segvn_trupdate_seg(svd->seg, svd, svntrp,
9984 				    hash);
9985 			}
9986 		}
9987 		mutex_exit(&svntr_hashtab[hash].tr_lock);
9988 	}
9989 }
9990 
9991 static void
9992 segvn_trupdate_seg(struct seg *seg,
9993 	segvn_data_t *svd,
9994 	svntr_t *svntrp,
9995 	ulong_t hash)
9996 {
9997 	proc_t			*p;
9998 	lgrp_id_t		lgrp_id;
9999 	struct as		*as;
10000 	size_t			size;
10001 	struct anon_map		*amp;
10002 
10003 	ASSERT(svd->vp != NULL);
10004 	ASSERT(svd->vp == svntrp->tr_vp);
10005 	ASSERT(svd->offset == svntrp->tr_off);
10006 	ASSERT(svd->offset + seg->s_size == svntrp->tr_eoff);
10007 	ASSERT(seg != NULL);
10008 	ASSERT(svd->seg == seg);
10009 	ASSERT(seg->s_data == (void *)svd);
10010 	ASSERT(seg->s_szc == svntrp->tr_szc);
10011 	ASSERT(svd->tr_state == SEGVN_TR_ON);
10012 	ASSERT(!HAT_IS_REGION_COOKIE_VALID(svd->rcookie));
10013 	ASSERT(svd->amp != NULL);
10014 	ASSERT(svd->tr_policy_info.mem_policy == LGRP_MEM_POLICY_NEXT_SEG);
10015 	ASSERT(svd->tr_policy_info.mem_lgrpid != LGRP_NONE);
10016 	ASSERT(svd->tr_policy_info.mem_lgrpid < NLGRPS_MAX);
10017 	ASSERT(svntrp->tr_amp[svd->tr_policy_info.mem_lgrpid] == svd->amp);
10018 	ASSERT(svntrp->tr_refcnt != 0);
10019 	ASSERT(mutex_owned(&svntr_hashtab[hash].tr_lock));
10020 
10021 	as = seg->s_as;
10022 	ASSERT(as != NULL && as != &kas);
10023 	p = as->a_proc;
10024 	ASSERT(p != NULL);
10025 	ASSERT(p->p_tr_lgrpid != LGRP_NONE);
10026 	lgrp_id = p->p_t1_lgrpid;
10027 	if (lgrp_id == LGRP_NONE) {
10028 		return;
10029 	}
10030 	ASSERT(lgrp_id < NLGRPS_MAX);
10031 	if (svd->tr_policy_info.mem_lgrpid == lgrp_id) {
10032 		return;
10033 	}
10034 
10035 	/*
10036 	 * Use tryenter locking since we are locking as/seg and svntr hash
10037 	 * lock in reverse from syncrounous thread order.
10038 	 */
10039 	if (!AS_LOCK_TRYENTER(as, &as->a_lock, RW_READER)) {
10040 		SEGVN_TR_ADDSTAT(nolock);
10041 		if (segvn_lgrp_trthr_migrs_snpsht) {
10042 			segvn_lgrp_trthr_migrs_snpsht = 0;
10043 		}
10044 		return;
10045 	}
10046 	if (!SEGVN_LOCK_TRYENTER(seg->s_as, &svd->lock, RW_WRITER)) {
10047 		AS_LOCK_EXIT(as, &as->a_lock);
10048 		SEGVN_TR_ADDSTAT(nolock);
10049 		if (segvn_lgrp_trthr_migrs_snpsht) {
10050 			segvn_lgrp_trthr_migrs_snpsht = 0;
10051 		}
10052 		return;
10053 	}
10054 	size = seg->s_size;
10055 	if (svntrp->tr_amp[lgrp_id] == NULL) {
10056 		size_t trmem = atomic_add_long_nv(&segvn_textrepl_bytes, size);
10057 		if (trmem > segvn_textrepl_max_bytes) {
10058 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
10059 			AS_LOCK_EXIT(as, &as->a_lock);
10060 			atomic_add_long(&segvn_textrepl_bytes, -size);
10061 			SEGVN_TR_ADDSTAT(normem);
10062 			return;
10063 		}
10064 		if (anon_try_resv_zone(size, NULL) == 0) {
10065 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
10066 			AS_LOCK_EXIT(as, &as->a_lock);
10067 			atomic_add_long(&segvn_textrepl_bytes, -size);
10068 			SEGVN_TR_ADDSTAT(noanon);
10069 			return;
10070 		}
10071 		amp = anonmap_alloc(size, size, KM_NOSLEEP);
10072 		if (amp == NULL) {
10073 			SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
10074 			AS_LOCK_EXIT(as, &as->a_lock);
10075 			atomic_add_long(&segvn_textrepl_bytes, -size);
10076 			anon_unresv_zone(size, NULL);
10077 			SEGVN_TR_ADDSTAT(nokmem);
10078 			return;
10079 		}
10080 		ASSERT(amp->refcnt == 1);
10081 		amp->a_szc = seg->s_szc;
10082 		svntrp->tr_amp[lgrp_id] = amp;
10083 	}
10084 	/*
10085 	 * We don't need to drop the bucket lock but here we give other
10086 	 * threads a chance.  svntr and svd can't be unlinked as long as
10087 	 * segment lock is held as a writer and AS held as well.  After we
10088 	 * retake bucket lock we'll continue from where we left. We'll be able
10089 	 * to reach the end of either list since new entries are always added
10090 	 * to the beginning of the lists.
10091 	 */
10092 	mutex_exit(&svntr_hashtab[hash].tr_lock);
10093 	hat_unload_callback(as->a_hat, seg->s_base, size, 0, NULL);
10094 	mutex_enter(&svntr_hashtab[hash].tr_lock);
10095 
10096 	ASSERT(svd->tr_state == SEGVN_TR_ON);
10097 	ASSERT(svd->amp != NULL);
10098 	ASSERT(svd->tr_policy_info.mem_policy == LGRP_MEM_POLICY_NEXT_SEG);
10099 	ASSERT(svd->tr_policy_info.mem_lgrpid != lgrp_id);
10100 	ASSERT(svd->amp != svntrp->tr_amp[lgrp_id]);
10101 
10102 	svd->tr_policy_info.mem_lgrpid = lgrp_id;
10103 	svd->amp = svntrp->tr_amp[lgrp_id];
10104 	p->p_tr_lgrpid = NLGRPS_MAX;
10105 	SEGVN_LOCK_EXIT(seg->s_as, &svd->lock);
10106 	AS_LOCK_EXIT(as, &as->a_lock);
10107 
10108 	ASSERT(svntrp->tr_refcnt != 0);
10109 	ASSERT(svd->vp == svntrp->tr_vp);
10110 	ASSERT(svd->tr_policy_info.mem_lgrpid == lgrp_id);
10111 	ASSERT(svd->amp != NULL && svd->amp == svntrp->tr_amp[lgrp_id]);
10112 	ASSERT(svd->seg == seg);
10113 	ASSERT(svd->tr_state == SEGVN_TR_ON);
10114 
10115 	SEGVN_TR_ADDSTAT(asyncrepl);
10116 }
10117