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