xref: /titanic_41/usr/src/uts/sfmmu/vm/hat_sfmmu.c (revision c1ecd8b9404ee0d96d93f02e82c441b9bb149a3d)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * VM - Hardware Address Translation management for Spitfire MMU.
30  *
31  * This file implements the machine specific hardware translation
32  * needed by the VM system.  The machine independent interface is
33  * described in <vm/hat.h> while the machine dependent interface
34  * and data structures are described in <vm/hat_sfmmu.h>.
35  *
36  * The hat layer manages the address translation hardware as a cache
37  * driven by calls from the higher levels in the VM system.
38  */
39 
40 #include <sys/types.h>
41 #include <sys/kstat.h>
42 #include <vm/hat.h>
43 #include <vm/hat_sfmmu.h>
44 #include <vm/page.h>
45 #include <sys/pte.h>
46 #include <sys/systm.h>
47 #include <sys/mman.h>
48 #include <sys/sysmacros.h>
49 #include <sys/machparam.h>
50 #include <sys/vtrace.h>
51 #include <sys/kmem.h>
52 #include <sys/mmu.h>
53 #include <sys/cmn_err.h>
54 #include <sys/cpu.h>
55 #include <sys/cpuvar.h>
56 #include <sys/debug.h>
57 #include <sys/lgrp.h>
58 #include <sys/archsystm.h>
59 #include <sys/machsystm.h>
60 #include <sys/vmsystm.h>
61 #include <vm/as.h>
62 #include <vm/seg.h>
63 #include <vm/seg_kp.h>
64 #include <vm/seg_kmem.h>
65 #include <vm/seg_kpm.h>
66 #include <vm/rm.h>
67 #include <sys/t_lock.h>
68 #include <sys/obpdefs.h>
69 #include <sys/vm_machparam.h>
70 #include <sys/var.h>
71 #include <sys/trap.h>
72 #include <sys/machtrap.h>
73 #include <sys/scb.h>
74 #include <sys/bitmap.h>
75 #include <sys/machlock.h>
76 #include <sys/membar.h>
77 #include <sys/atomic.h>
78 #include <sys/cpu_module.h>
79 #include <sys/prom_debug.h>
80 #include <sys/ksynch.h>
81 #include <sys/mem_config.h>
82 #include <sys/mem_cage.h>
83 #include <vm/vm_dep.h>
84 #include <vm/xhat_sfmmu.h>
85 #include <sys/fpu/fpusystm.h>
86 #include <vm/mach_kpm.h>
87 #include <sys/callb.h>
88 
89 #ifdef	DEBUG
90 #define	SFMMU_VALIDATE_HMERID(hat, rid, saddr, len)			\
91 	if (SFMMU_IS_SHMERID_VALID(rid)) {				\
92 		caddr_t _eaddr = (saddr) + (len);			\
93 		sf_srd_t *_srdp;					\
94 		sf_region_t *_rgnp;					\
95 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			\
96 		ASSERT(SF_RGNMAP_TEST(hat->sfmmu_hmeregion_map, rid));	\
97 		ASSERT((hat) != ksfmmup);				\
98 		_srdp = (hat)->sfmmu_srdp;				\
99 		ASSERT(_srdp != NULL);					\
100 		ASSERT(_srdp->srd_refcnt != 0);				\
101 		_rgnp = _srdp->srd_hmergnp[(rid)];			\
102 		ASSERT(_rgnp != NULL && _rgnp->rgn_id == rid);		\
103 		ASSERT(_rgnp->rgn_refcnt != 0);				\
104 		ASSERT(!(_rgnp->rgn_flags & SFMMU_REGION_FREE));	\
105 		ASSERT((_rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	\
106 		    SFMMU_REGION_HME);					\
107 		ASSERT((saddr) >= _rgnp->rgn_saddr);			\
108 		ASSERT((saddr) < _rgnp->rgn_saddr + _rgnp->rgn_size);	\
109 		ASSERT(_eaddr > _rgnp->rgn_saddr);			\
110 		ASSERT(_eaddr <= _rgnp->rgn_saddr + _rgnp->rgn_size);	\
111 	}
112 
113 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid) 	 	 \
114 {						 			 \
115 		caddr_t _hsva;						 \
116 		caddr_t _heva;						 \
117 		caddr_t _rsva;					 	 \
118 		caddr_t _reva;					 	 \
119 		int	_ttesz = get_hblk_ttesz(hmeblkp);		 \
120 		int	_flagtte;					 \
121 		ASSERT((srdp)->srd_refcnt != 0);			 \
122 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			 \
123 		ASSERT((rgnp)->rgn_id == rid);				 \
124 		ASSERT(!((rgnp)->rgn_flags & SFMMU_REGION_FREE));	 \
125 		ASSERT(((rgnp)->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	 \
126 		    SFMMU_REGION_HME);					 \
127 		ASSERT(_ttesz <= (rgnp)->rgn_pgszc);			 \
128 		_hsva = (caddr_t)get_hblk_base(hmeblkp);		 \
129 		_heva = get_hblk_endaddr(hmeblkp);			 \
130 		_rsva = (caddr_t)P2ALIGN(				 \
131 		    (uintptr_t)(rgnp)->rgn_saddr, HBLK_MIN_BYTES);	 \
132 		_reva = (caddr_t)P2ROUNDUP(				 \
133 		    (uintptr_t)((rgnp)->rgn_saddr + (rgnp)->rgn_size),	 \
134 		    HBLK_MIN_BYTES);					 \
135 		ASSERT(_hsva >= _rsva);				 	 \
136 		ASSERT(_hsva < _reva);				 	 \
137 		ASSERT(_heva > _rsva);				 	 \
138 		ASSERT(_heva <= _reva);				 	 \
139 		_flagtte = (_ttesz < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ :  \
140 			_ttesz;						 \
141 		ASSERT(rgnp->rgn_hmeflags & (0x1 << _flagtte));		 \
142 }
143 
144 #else /* DEBUG */
145 #define	SFMMU_VALIDATE_HMERID(hat, rid, addr, len)
146 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid)
147 #endif /* DEBUG */
148 
149 #if defined(SF_ERRATA_57)
150 extern caddr_t errata57_limit;
151 #endif
152 
153 #define	HME8BLK_SZ_RND		((roundup(HME8BLK_SZ, sizeof (int64_t))) /  \
154 				(sizeof (int64_t)))
155 #define	HBLK_RESERVE		((struct hme_blk *)hblk_reserve)
156 
157 #define	HBLK_RESERVE_CNT	128
158 #define	HBLK_RESERVE_MIN	20
159 
160 static struct hme_blk		*freehblkp;
161 static kmutex_t			freehblkp_lock;
162 static int			freehblkcnt;
163 
164 static int64_t			hblk_reserve[HME8BLK_SZ_RND];
165 static kmutex_t			hblk_reserve_lock;
166 static kthread_t		*hblk_reserve_thread;
167 
168 static nucleus_hblk8_info_t	nucleus_hblk8;
169 static nucleus_hblk1_info_t	nucleus_hblk1;
170 
171 /*
172  * SFMMU specific hat functions
173  */
174 void	hat_pagecachectl(struct page *, int);
175 
176 /* flags for hat_pagecachectl */
177 #define	HAT_CACHE	0x1
178 #define	HAT_UNCACHE	0x2
179 #define	HAT_TMPNC	0x4
180 
181 /*
182  * Flag to allow the creation of non-cacheable translations
183  * to system memory. It is off by default. At the moment this
184  * flag is used by the ecache error injector. The error injector
185  * will turn it on when creating such a translation then shut it
186  * off when it's finished.
187  */
188 
189 int	sfmmu_allow_nc_trans = 0;
190 
191 /*
192  * Flag to disable large page support.
193  * 	value of 1 => disable all large pages.
194  *	bits 1, 2, and 3 are to disable 64K, 512K and 4M pages respectively.
195  *
196  * For example, use the value 0x4 to disable 512K pages.
197  *
198  */
199 #define	LARGE_PAGES_OFF		0x1
200 
201 /*
202  * The disable_large_pages and disable_ism_large_pages variables control
203  * hat_memload_array and the page sizes to be used by ISM and the kernel.
204  *
205  * The disable_auto_data_large_pages and disable_auto_text_large_pages variables
206  * are only used to control which OOB pages to use at upper VM segment creation
207  * time, and are set in hat_init_pagesizes and used in the map_pgsz* routines.
208  * Their values may come from platform or CPU specific code to disable page
209  * sizes that should not be used.
210  *
211  * WARNING: 512K pages are currently not supported for ISM/DISM.
212  */
213 uint_t	disable_large_pages = 0;
214 uint_t	disable_ism_large_pages = (1 << TTE512K);
215 uint_t	disable_auto_data_large_pages = 0;
216 uint_t	disable_auto_text_large_pages = 0;
217 
218 /*
219  * Private sfmmu data structures for hat management
220  */
221 static struct kmem_cache *sfmmuid_cache;
222 static struct kmem_cache *mmuctxdom_cache;
223 
224 /*
225  * Private sfmmu data structures for tsb management
226  */
227 static struct kmem_cache *sfmmu_tsbinfo_cache;
228 static struct kmem_cache *sfmmu_tsb8k_cache;
229 static struct kmem_cache *sfmmu_tsb_cache[NLGRPS_MAX];
230 static vmem_t *kmem_bigtsb_arena;
231 static vmem_t *kmem_tsb_arena;
232 
233 /*
234  * sfmmu static variables for hmeblk resource management.
235  */
236 static vmem_t *hat_memload1_arena; /* HAT translation arena for sfmmu1_cache */
237 static struct kmem_cache *sfmmu8_cache;
238 static struct kmem_cache *sfmmu1_cache;
239 static struct kmem_cache *pa_hment_cache;
240 
241 static kmutex_t 	ism_mlist_lock;	/* mutex for ism mapping list */
242 /*
243  * private data for ism
244  */
245 static struct kmem_cache *ism_blk_cache;
246 static struct kmem_cache *ism_ment_cache;
247 #define	ISMID_STARTADDR	NULL
248 
249 /*
250  * Region management data structures and function declarations.
251  */
252 
253 static void	sfmmu_leave_srd(sfmmu_t *);
254 static int	sfmmu_srdcache_constructor(void *, void *, int);
255 static void	sfmmu_srdcache_destructor(void *, void *);
256 static int	sfmmu_rgncache_constructor(void *, void *, int);
257 static void	sfmmu_rgncache_destructor(void *, void *);
258 static int	sfrgnmap_isnull(sf_region_map_t *);
259 static int	sfhmergnmap_isnull(sf_hmeregion_map_t *);
260 static int	sfmmu_scdcache_constructor(void *, void *, int);
261 static void	sfmmu_scdcache_destructor(void *, void *);
262 static void	sfmmu_rgn_cb_noop(caddr_t, caddr_t, caddr_t,
263     size_t, void *, u_offset_t);
264 
265 static uint_t srd_hashmask = SFMMU_MAX_SRD_BUCKETS - 1;
266 static sf_srd_bucket_t *srd_buckets;
267 static struct kmem_cache *srd_cache;
268 static uint_t srd_rgn_hashmask = SFMMU_MAX_REGION_BUCKETS - 1;
269 static struct kmem_cache *region_cache;
270 static struct kmem_cache *scd_cache;
271 
272 #ifdef sun4v
273 int use_bigtsb_arena = 1;
274 #else
275 int use_bigtsb_arena = 0;
276 #endif
277 
278 /* External /etc/system tunable, for turning on&off the shctx support */
279 int disable_shctx = 0;
280 /* Internal variable, set by MD if the HW supports shctx feature */
281 int shctx_on = 0;
282 
283 #ifdef DEBUG
284 static void check_scd_sfmmu_list(sfmmu_t **, sfmmu_t *, int);
285 #endif
286 static void sfmmu_to_scd_list(sfmmu_t **, sfmmu_t *);
287 static void sfmmu_from_scd_list(sfmmu_t **, sfmmu_t *);
288 
289 static sf_scd_t *sfmmu_alloc_scd(sf_srd_t *, sf_region_map_t *);
290 static void sfmmu_find_scd(sfmmu_t *);
291 static void sfmmu_join_scd(sf_scd_t *, sfmmu_t *);
292 static void sfmmu_finish_join_scd(sfmmu_t *);
293 static void sfmmu_leave_scd(sfmmu_t *, uchar_t);
294 static void sfmmu_destroy_scd(sf_srd_t *, sf_scd_t *, sf_region_map_t *);
295 static int sfmmu_alloc_scd_tsbs(sf_srd_t *, sf_scd_t *);
296 static void sfmmu_free_scd_tsbs(sfmmu_t *);
297 static void sfmmu_tsb_inv_ctx(sfmmu_t *);
298 static int find_ism_rid(sfmmu_t *, sfmmu_t *, caddr_t, uint_t *);
299 static void sfmmu_ism_hatflags(sfmmu_t *, int);
300 static int sfmmu_srd_lock_held(sf_srd_t *);
301 static void sfmmu_remove_scd(sf_scd_t **, sf_scd_t *);
302 static void sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *);
303 static void sfmmu_link_scd_to_regions(sf_srd_t *, sf_scd_t *);
304 static void sfmmu_unlink_scd_from_regions(sf_srd_t *, sf_scd_t *);
305 static void sfmmu_link_to_hmeregion(sfmmu_t *, sf_region_t *);
306 static void sfmmu_unlink_from_hmeregion(sfmmu_t *, sf_region_t *);
307 
308 /*
309  * ``hat_lock'' is a hashed mutex lock for protecting sfmmu TSB lists,
310  * HAT flags, synchronizing TLB/TSB coherency, and context management.
311  * The lock is hashed on the sfmmup since the case where we need to lock
312  * all processes is rare but does occur (e.g. we need to unload a shared
313  * mapping from all processes using the mapping).  We have a lot of buckets,
314  * and each slab of sfmmu_t's can use about a quarter of them, giving us
315  * a fairly good distribution without wasting too much space and overhead
316  * when we have to grab them all.
317  */
318 #define	SFMMU_NUM_LOCK	128		/* must be power of two */
319 hatlock_t	hat_lock[SFMMU_NUM_LOCK];
320 
321 /*
322  * Hash algorithm optimized for a small number of slabs.
323  *  7 is (highbit((sizeof sfmmu_t)) - 1)
324  * This hash algorithm is based upon the knowledge that sfmmu_t's come from a
325  * kmem_cache, and thus they will be sequential within that cache.  In
326  * addition, each new slab will have a different "color" up to cache_maxcolor
327  * which will skew the hashing for each successive slab which is allocated.
328  * If the size of sfmmu_t changed to a larger size, this algorithm may need
329  * to be revisited.
330  */
331 #define	TSB_HASH_SHIFT_BITS (7)
332 #define	PTR_HASH(x) ((uintptr_t)x >> TSB_HASH_SHIFT_BITS)
333 
334 #ifdef DEBUG
335 int tsb_hash_debug = 0;
336 #define	TSB_HASH(sfmmup)	\
337 	(tsb_hash_debug ? &hat_lock[0] : \
338 	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)])
339 #else	/* DEBUG */
340 #define	TSB_HASH(sfmmup)	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)]
341 #endif	/* DEBUG */
342 
343 
344 /* sfmmu_replace_tsb() return codes. */
345 typedef enum tsb_replace_rc {
346 	TSB_SUCCESS,
347 	TSB_ALLOCFAIL,
348 	TSB_LOSTRACE,
349 	TSB_ALREADY_SWAPPED,
350 	TSB_CANTGROW
351 } tsb_replace_rc_t;
352 
353 /*
354  * Flags for TSB allocation routines.
355  */
356 #define	TSB_ALLOC	0x01
357 #define	TSB_FORCEALLOC	0x02
358 #define	TSB_GROW	0x04
359 #define	TSB_SHRINK	0x08
360 #define	TSB_SWAPIN	0x10
361 
362 /*
363  * Support for HAT callbacks.
364  */
365 #define	SFMMU_MAX_RELOC_CALLBACKS	10
366 int sfmmu_max_cb_id = SFMMU_MAX_RELOC_CALLBACKS;
367 static id_t sfmmu_cb_nextid = 0;
368 static id_t sfmmu_tsb_cb_id;
369 struct sfmmu_callback *sfmmu_cb_table;
370 
371 /*
372  * Kernel page relocation is enabled by default for non-caged
373  * kernel pages.  This has little effect unless segkmem_reloc is
374  * set, since by default kernel memory comes from inside the
375  * kernel cage.
376  */
377 int hat_kpr_enabled = 1;
378 
379 kmutex_t	kpr_mutex;
380 kmutex_t	kpr_suspendlock;
381 kthread_t	*kreloc_thread;
382 
383 /*
384  * Enable VA->PA translation sanity checking on DEBUG kernels.
385  * Disabled by default.  This is incompatible with some
386  * drivers (error injector, RSM) so if it breaks you get
387  * to keep both pieces.
388  */
389 int hat_check_vtop = 0;
390 
391 /*
392  * Private sfmmu routines (prototypes)
393  */
394 static struct hme_blk *sfmmu_shadow_hcreate(sfmmu_t *, caddr_t, int, uint_t);
395 static struct 	hme_blk *sfmmu_hblk_alloc(sfmmu_t *, caddr_t,
396 			struct hmehash_bucket *, uint_t, hmeblk_tag, uint_t,
397 			uint_t);
398 static caddr_t	sfmmu_hblk_unload(struct hat *, struct hme_blk *, caddr_t,
399 			caddr_t, demap_range_t *, uint_t);
400 static caddr_t	sfmmu_hblk_sync(struct hat *, struct hme_blk *, caddr_t,
401 			caddr_t, int);
402 static void	sfmmu_hblk_free(struct hmehash_bucket *, struct hme_blk *,
403 			uint64_t, struct hme_blk **);
404 static void	sfmmu_hblks_list_purge(struct hme_blk **);
405 static uint_t	sfmmu_get_free_hblk(struct hme_blk **, uint_t);
406 static uint_t	sfmmu_put_free_hblk(struct hme_blk *, uint_t);
407 static struct hme_blk *sfmmu_hblk_steal(int);
408 static int	sfmmu_steal_this_hblk(struct hmehash_bucket *,
409 			struct hme_blk *, uint64_t, uint64_t,
410 			struct hme_blk *);
411 static caddr_t	sfmmu_hblk_unlock(struct hme_blk *, caddr_t, caddr_t);
412 
413 static void	hat_do_memload_array(struct hat *, caddr_t, size_t,
414 		    struct page **, uint_t, uint_t, uint_t);
415 static void	hat_do_memload(struct hat *, caddr_t, struct page *,
416 		    uint_t, uint_t, uint_t);
417 static void	sfmmu_memload_batchsmall(struct hat *, caddr_t, page_t **,
418 		    uint_t, uint_t, pgcnt_t, uint_t);
419 void		sfmmu_tteload(struct hat *, tte_t *, caddr_t, page_t *,
420 			uint_t);
421 static int	sfmmu_tteload_array(sfmmu_t *, tte_t *, caddr_t, page_t **,
422 			uint_t, uint_t);
423 static struct hmehash_bucket *sfmmu_tteload_acquire_hashbucket(sfmmu_t *,
424 					caddr_t, int, uint_t);
425 static struct hme_blk *sfmmu_tteload_find_hmeblk(sfmmu_t *,
426 			struct hmehash_bucket *, caddr_t, uint_t, uint_t,
427 			uint_t);
428 static int	sfmmu_tteload_addentry(sfmmu_t *, struct hme_blk *, tte_t *,
429 			caddr_t, page_t **, uint_t, uint_t);
430 static void	sfmmu_tteload_release_hashbucket(struct hmehash_bucket *);
431 
432 static int	sfmmu_pagearray_setup(caddr_t, page_t **, tte_t *, int);
433 static pfn_t	sfmmu_uvatopfn(caddr_t, sfmmu_t *, tte_t *);
434 void		sfmmu_memtte(tte_t *, pfn_t, uint_t, int);
435 #ifdef VAC
436 static void	sfmmu_vac_conflict(struct hat *, caddr_t, page_t *);
437 static int	sfmmu_vacconflict_array(caddr_t, page_t *, int *);
438 int	tst_tnc(page_t *pp, pgcnt_t);
439 void	conv_tnc(page_t *pp, int);
440 #endif
441 
442 static void	sfmmu_get_ctx(sfmmu_t *);
443 static void	sfmmu_free_sfmmu(sfmmu_t *);
444 
445 static void	sfmmu_ttesync(struct hat *, caddr_t, tte_t *, page_t *);
446 static void	sfmmu_chgattr(struct hat *, caddr_t, size_t, uint_t, int);
447 
448 cpuset_t	sfmmu_pageunload(page_t *, struct sf_hment *, int);
449 static void	hat_pagereload(struct page *, struct page *);
450 static cpuset_t	sfmmu_pagesync(page_t *, struct sf_hment *, uint_t);
451 #ifdef VAC
452 void	sfmmu_page_cache_array(page_t *, int, int, pgcnt_t);
453 static void	sfmmu_page_cache(page_t *, int, int, int);
454 #endif
455 
456 cpuset_t	sfmmu_rgntlb_demap(caddr_t, sf_region_t *,
457     struct hme_blk *, int);
458 static void	sfmmu_tlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
459 			pfn_t, int, int, int, int);
460 static void	sfmmu_ismtlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
461 			pfn_t, int);
462 static void	sfmmu_tlb_demap(caddr_t, sfmmu_t *, struct hme_blk *, int, int);
463 static void	sfmmu_tlb_range_demap(demap_range_t *);
464 static void	sfmmu_invalidate_ctx(sfmmu_t *);
465 static void	sfmmu_sync_mmustate(sfmmu_t *);
466 
467 static void 	sfmmu_tsbinfo_setup_phys(struct tsb_info *, pfn_t);
468 static int	sfmmu_tsbinfo_alloc(struct tsb_info **, int, int, uint_t,
469 			sfmmu_t *);
470 static void	sfmmu_tsb_free(struct tsb_info *);
471 static void	sfmmu_tsbinfo_free(struct tsb_info *);
472 static int	sfmmu_init_tsbinfo(struct tsb_info *, int, int, uint_t,
473 			sfmmu_t *);
474 static void	sfmmu_tsb_chk_reloc(sfmmu_t *, hatlock_t *);
475 static void	sfmmu_tsb_swapin(sfmmu_t *, hatlock_t *);
476 static int	sfmmu_select_tsb_szc(pgcnt_t);
477 static void	sfmmu_mod_tsb(sfmmu_t *, caddr_t, tte_t *, int);
478 #define		sfmmu_load_tsb(sfmmup, vaddr, tte, szc) \
479 	sfmmu_mod_tsb(sfmmup, vaddr, tte, szc)
480 #define		sfmmu_unload_tsb(sfmmup, vaddr, szc)    \
481 	sfmmu_mod_tsb(sfmmup, vaddr, NULL, szc)
482 static void	sfmmu_copy_tsb(struct tsb_info *, struct tsb_info *);
483 static tsb_replace_rc_t sfmmu_replace_tsb(sfmmu_t *, struct tsb_info *, uint_t,
484     hatlock_t *, uint_t);
485 static void	sfmmu_size_tsb(sfmmu_t *, int, uint64_t, uint64_t, int);
486 
487 #ifdef VAC
488 void	sfmmu_cache_flush(pfn_t, int);
489 void	sfmmu_cache_flushcolor(int, pfn_t);
490 #endif
491 static caddr_t	sfmmu_hblk_chgattr(sfmmu_t *, struct hme_blk *, caddr_t,
492 			caddr_t, demap_range_t *, uint_t, int);
493 
494 static uint64_t	sfmmu_vtop_attr(uint_t, int mode, tte_t *);
495 static uint_t	sfmmu_ptov_attr(tte_t *);
496 static caddr_t	sfmmu_hblk_chgprot(sfmmu_t *, struct hme_blk *, caddr_t,
497 			caddr_t, demap_range_t *, uint_t);
498 static uint_t	sfmmu_vtop_prot(uint_t, uint_t *);
499 static int	sfmmu_idcache_constructor(void *, void *, int);
500 static void	sfmmu_idcache_destructor(void *, void *);
501 static int	sfmmu_hblkcache_constructor(void *, void *, int);
502 static void	sfmmu_hblkcache_destructor(void *, void *);
503 static void	sfmmu_hblkcache_reclaim(void *);
504 static void	sfmmu_shadow_hcleanup(sfmmu_t *, struct hme_blk *,
505 			struct hmehash_bucket *);
506 static void	sfmmu_free_hblks(sfmmu_t *, caddr_t, caddr_t, int);
507 static void	sfmmu_cleanup_rhblk(sf_srd_t *, caddr_t, uint_t, int);
508 static void	sfmmu_unload_hmeregion_va(sf_srd_t *, uint_t, caddr_t, caddr_t,
509 			int, caddr_t *);
510 static void	sfmmu_unload_hmeregion(sf_srd_t *, sf_region_t *);
511 
512 static void	sfmmu_rm_large_mappings(page_t *, int);
513 
514 static void	hat_lock_init(void);
515 static void	hat_kstat_init(void);
516 static int	sfmmu_kstat_percpu_update(kstat_t *ksp, int rw);
517 static void	sfmmu_set_scd_rttecnt(sf_srd_t *, sf_scd_t *);
518 static	int	sfmmu_is_rgnva(sf_srd_t *, caddr_t, ulong_t, ulong_t);
519 static void	sfmmu_check_page_sizes(sfmmu_t *, int);
520 int	fnd_mapping_sz(page_t *);
521 static void	iment_add(struct ism_ment *,  struct hat *);
522 static void	iment_sub(struct ism_ment *, struct hat *);
523 static pgcnt_t	ism_tsb_entries(sfmmu_t *, int szc);
524 extern void	sfmmu_setup_tsbinfo(sfmmu_t *);
525 extern void	sfmmu_clear_utsbinfo(void);
526 
527 static void	sfmmu_ctx_wrap_around(mmu_ctx_t *);
528 
529 /* kpm globals */
530 #ifdef	DEBUG
531 /*
532  * Enable trap level tsbmiss handling
533  */
534 int	kpm_tsbmtl = 1;
535 
536 /*
537  * Flush the TLB on kpm mapout. Note: Xcalls are used (again) for the
538  * required TLB shootdowns in this case, so handle w/ care. Off by default.
539  */
540 int	kpm_tlb_flush;
541 #endif	/* DEBUG */
542 
543 static void	*sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *, size_t, int);
544 
545 #ifdef DEBUG
546 static void	sfmmu_check_hblk_flist();
547 #endif
548 
549 /*
550  * Semi-private sfmmu data structures.  Some of them are initialize in
551  * startup or in hat_init. Some of them are private but accessed by
552  * assembly code or mach_sfmmu.c
553  */
554 struct hmehash_bucket *uhme_hash;	/* user hmeblk hash table */
555 struct hmehash_bucket *khme_hash;	/* kernel hmeblk hash table */
556 uint64_t	uhme_hash_pa;		/* PA of uhme_hash */
557 uint64_t	khme_hash_pa;		/* PA of khme_hash */
558 int 		uhmehash_num;		/* # of buckets in user hash table */
559 int 		khmehash_num;		/* # of buckets in kernel hash table */
560 
561 uint_t		max_mmu_ctxdoms = 0;	/* max context domains in the system */
562 mmu_ctx_t	**mmu_ctxs_tbl;		/* global array of context domains */
563 uint64_t	mmu_saved_gnum = 0;	/* to init incoming MMUs' gnums */
564 
565 #define	DEFAULT_NUM_CTXS_PER_MMU 8192
566 static uint_t	nctxs = DEFAULT_NUM_CTXS_PER_MMU;
567 
568 int		cache;			/* describes system cache */
569 
570 caddr_t		ktsb_base;		/* kernel 8k-indexed tsb base address */
571 uint64_t	ktsb_pbase;		/* kernel 8k-indexed tsb phys address */
572 int		ktsb_szcode;		/* kernel 8k-indexed tsb size code */
573 int		ktsb_sz;		/* kernel 8k-indexed tsb size */
574 
575 caddr_t		ktsb4m_base;		/* kernel 4m-indexed tsb base address */
576 uint64_t	ktsb4m_pbase;		/* kernel 4m-indexed tsb phys address */
577 int		ktsb4m_szcode;		/* kernel 4m-indexed tsb size code */
578 int		ktsb4m_sz;		/* kernel 4m-indexed tsb size */
579 
580 uint64_t	kpm_tsbbase;		/* kernel seg_kpm 4M TSB base address */
581 int		kpm_tsbsz;		/* kernel seg_kpm 4M TSB size code */
582 uint64_t	kpmsm_tsbbase;		/* kernel seg_kpm 8K TSB base address */
583 int		kpmsm_tsbsz;		/* kernel seg_kpm 8K TSB size code */
584 
585 #ifndef sun4v
586 int		utsb_dtlb_ttenum = -1;	/* index in TLB for utsb locked TTE */
587 int		utsb4m_dtlb_ttenum = -1; /* index in TLB for 4M TSB TTE */
588 int		dtlb_resv_ttenum;	/* index in TLB of first reserved TTE */
589 caddr_t		utsb_vabase;		/* reserved kernel virtual memory */
590 caddr_t		utsb4m_vabase;		/* for trap handler TSB accesses */
591 #endif /* sun4v */
592 uint64_t	tsb_alloc_bytes = 0;	/* bytes allocated to TSBs */
593 vmem_t		*kmem_tsb_default_arena[NLGRPS_MAX];	/* For dynamic TSBs */
594 vmem_t		*kmem_bigtsb_default_arena[NLGRPS_MAX]; /* dynamic 256M TSBs */
595 
596 /*
597  * Size to use for TSB slabs.  Future platforms that support page sizes
598  * larger than 4M may wish to change these values, and provide their own
599  * assembly macros for building and decoding the TSB base register contents.
600  * Note disable_large_pages will override the value set here.
601  */
602 static	uint_t tsb_slab_ttesz = TTE4M;
603 size_t	tsb_slab_size = MMU_PAGESIZE4M;
604 uint_t	tsb_slab_shift = MMU_PAGESHIFT4M;
605 /* PFN mask for TTE */
606 size_t	tsb_slab_mask = MMU_PAGEOFFSET4M >> MMU_PAGESHIFT;
607 
608 /*
609  * Size to use for TSB slabs.  These are used only when 256M tsb arenas
610  * exist.
611  */
612 static uint_t	bigtsb_slab_ttesz = TTE256M;
613 static size_t	bigtsb_slab_size = MMU_PAGESIZE256M;
614 static uint_t	bigtsb_slab_shift = MMU_PAGESHIFT256M;
615 /* 256M page alignment for 8K pfn */
616 static size_t	bigtsb_slab_mask = MMU_PAGEOFFSET256M >> MMU_PAGESHIFT;
617 
618 /* largest TSB size to grow to, will be smaller on smaller memory systems */
619 static int	tsb_max_growsize = 0;
620 
621 /*
622  * Tunable parameters dealing with TSB policies.
623  */
624 
625 /*
626  * This undocumented tunable forces all 8K TSBs to be allocated from
627  * the kernel heap rather than from the kmem_tsb_default_arena arenas.
628  */
629 #ifdef	DEBUG
630 int	tsb_forceheap = 0;
631 #endif	/* DEBUG */
632 
633 /*
634  * Decide whether to use per-lgroup arenas, or one global set of
635  * TSB arenas.  The default is not to break up per-lgroup, since
636  * most platforms don't recognize any tangible benefit from it.
637  */
638 int	tsb_lgrp_affinity = 0;
639 
640 /*
641  * Used for growing the TSB based on the process RSS.
642  * tsb_rss_factor is based on the smallest TSB, and is
643  * shifted by the TSB size to determine if we need to grow.
644  * The default will grow the TSB if the number of TTEs for
645  * this page size exceeds 75% of the number of TSB entries,
646  * which should _almost_ eliminate all conflict misses
647  * (at the expense of using up lots and lots of memory).
648  */
649 #define	TSB_RSS_FACTOR		(TSB_ENTRIES(TSB_MIN_SZCODE) * 0.75)
650 #define	SFMMU_RSS_TSBSIZE(tsbszc)	(tsb_rss_factor << tsbszc)
651 #define	SELECT_TSB_SIZECODE(pgcnt) ( \
652 	(enable_tsb_rss_sizing)? sfmmu_select_tsb_szc(pgcnt) : \
653 	default_tsb_size)
654 #define	TSB_OK_SHRINK()	\
655 	(tsb_alloc_bytes > tsb_alloc_hiwater || freemem < desfree)
656 #define	TSB_OK_GROW()	\
657 	(tsb_alloc_bytes < tsb_alloc_hiwater && freemem > desfree)
658 
659 int	enable_tsb_rss_sizing = 1;
660 int	tsb_rss_factor	= (int)TSB_RSS_FACTOR;
661 
662 /* which TSB size code to use for new address spaces or if rss sizing off */
663 int default_tsb_size = TSB_8K_SZCODE;
664 
665 static uint64_t tsb_alloc_hiwater; /* limit TSB reserved memory */
666 uint64_t tsb_alloc_hiwater_factor; /* tsb_alloc_hiwater = physmem / this */
667 #define	TSB_ALLOC_HIWATER_FACTOR_DEFAULT	32
668 
669 #ifdef DEBUG
670 static int tsb_random_size = 0;	/* set to 1 to test random tsb sizes on alloc */
671 static int tsb_grow_stress = 0;	/* if set to 1, keep replacing TSB w/ random */
672 static int tsb_alloc_mtbf = 0;	/* fail allocation every n attempts */
673 static int tsb_alloc_fail_mtbf = 0;
674 static int tsb_alloc_count = 0;
675 #endif /* DEBUG */
676 
677 /* if set to 1, will remap valid TTEs when growing TSB. */
678 int tsb_remap_ttes = 1;
679 
680 /*
681  * If we have more than this many mappings, allocate a second TSB.
682  * This default is chosen because the I/D fully associative TLBs are
683  * assumed to have at least 8 available entries. Platforms with a
684  * larger fully-associative TLB could probably override the default.
685  */
686 
687 #ifdef sun4v
688 int tsb_sectsb_threshold = 0;
689 #else
690 int tsb_sectsb_threshold = 8;
691 #endif
692 
693 /*
694  * kstat data
695  */
696 struct sfmmu_global_stat sfmmu_global_stat;
697 struct sfmmu_tsbsize_stat sfmmu_tsbsize_stat;
698 
699 /*
700  * Global data
701  */
702 sfmmu_t 	*ksfmmup;		/* kernel's hat id */
703 
704 #ifdef DEBUG
705 static void	chk_tte(tte_t *, tte_t *, tte_t *, struct hme_blk *);
706 #endif
707 
708 /* sfmmu locking operations */
709 static kmutex_t *sfmmu_mlspl_enter(struct page *, int);
710 static int	sfmmu_mlspl_held(struct page *, int);
711 
712 kmutex_t *sfmmu_page_enter(page_t *);
713 void	sfmmu_page_exit(kmutex_t *);
714 int	sfmmu_page_spl_held(struct page *);
715 
716 /* sfmmu internal locking operations - accessed directly */
717 static void	sfmmu_mlist_reloc_enter(page_t *, page_t *,
718 				kmutex_t **, kmutex_t **);
719 static void	sfmmu_mlist_reloc_exit(kmutex_t *, kmutex_t *);
720 static hatlock_t *
721 		sfmmu_hat_enter(sfmmu_t *);
722 static hatlock_t *
723 		sfmmu_hat_tryenter(sfmmu_t *);
724 static void	sfmmu_hat_exit(hatlock_t *);
725 static void	sfmmu_hat_lock_all(void);
726 static void	sfmmu_hat_unlock_all(void);
727 static void	sfmmu_ismhat_enter(sfmmu_t *, int);
728 static void	sfmmu_ismhat_exit(sfmmu_t *, int);
729 
730 /*
731  * Array of mutexes protecting a page's mapping list and p_nrm field.
732  *
733  * The hash function looks complicated, but is made up so that:
734  *
735  * "pp" not shifted, so adjacent pp values will hash to different cache lines
736  *  (8 byte alignment * 8 bytes/mutes == 64 byte coherency subblock)
737  *
738  * "pp" >> mml_shift, incorporates more source bits into the hash result
739  *
740  *  "& (mml_table_size - 1), should be faster than using remainder "%"
741  *
742  * Hopefully, mml_table, mml_table_size and mml_shift are all in the same
743  * cacheline, since they get declared next to each other below. We'll trust
744  * ld not to do something random.
745  */
746 #ifdef	DEBUG
747 int mlist_hash_debug = 0;
748 #define	MLIST_HASH(pp)	(mlist_hash_debug ? &mml_table[0] : \
749 	&mml_table[((uintptr_t)(pp) + \
750 	((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)])
751 #else	/* !DEBUG */
752 #define	MLIST_HASH(pp)   &mml_table[ \
753 	((uintptr_t)(pp) + ((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)]
754 #endif	/* !DEBUG */
755 
756 kmutex_t		*mml_table;
757 uint_t			mml_table_sz;	/* must be a power of 2 */
758 uint_t			mml_shift;	/* log2(mml_table_sz) + 3 for align */
759 
760 kpm_hlk_t	*kpmp_table;
761 uint_t		kpmp_table_sz;	/* must be a power of 2 */
762 uchar_t		kpmp_shift;
763 
764 kpm_shlk_t	*kpmp_stable;
765 uint_t		kpmp_stable_sz;	/* must be a power of 2 */
766 
767 /*
768  * SPL_HASH was improved to avoid false cache line sharing
769  */
770 #define	SPL_TABLE_SIZE	128
771 #define	SPL_MASK	(SPL_TABLE_SIZE - 1)
772 #define	SPL_SHIFT	7		/* log2(SPL_TABLE_SIZE) */
773 
774 #define	SPL_INDEX(pp) \
775 	((((uintptr_t)(pp) >> SPL_SHIFT) ^ \
776 	((uintptr_t)(pp) >> (SPL_SHIFT << 1))) & \
777 	(SPL_TABLE_SIZE - 1))
778 
779 #define	SPL_HASH(pp)    \
780 	(&sfmmu_page_lock[SPL_INDEX(pp) & SPL_MASK].pad_mutex)
781 
782 static	pad_mutex_t	sfmmu_page_lock[SPL_TABLE_SIZE];
783 
784 
785 /*
786  * hat_unload_callback() will group together callbacks in order
787  * to avoid xt_sync() calls.  This is the maximum size of the group.
788  */
789 #define	MAX_CB_ADDR	32
790 
791 tte_t	hw_tte;
792 static ulong_t sfmmu_dmr_maxbit = DMR_MAXBIT;
793 
794 static char	*mmu_ctx_kstat_names[] = {
795 	"mmu_ctx_tsb_exceptions",
796 	"mmu_ctx_tsb_raise_exception",
797 	"mmu_ctx_wrap_around",
798 };
799 
800 /*
801  * Wrapper for vmem_xalloc since vmem_create only allows limited
802  * parameters for vm_source_alloc functions.  This function allows us
803  * to specify alignment consistent with the size of the object being
804  * allocated.
805  */
806 static void *
807 sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *vmp, size_t size, int vmflag)
808 {
809 	return (vmem_xalloc(vmp, size, size, 0, 0, NULL, NULL, vmflag));
810 }
811 
812 /* Common code for setting tsb_alloc_hiwater. */
813 #define	SFMMU_SET_TSB_ALLOC_HIWATER(pages)	tsb_alloc_hiwater = \
814 		ptob(pages) / tsb_alloc_hiwater_factor
815 
816 /*
817  * Set tsb_max_growsize to allow at most all of physical memory to be mapped by
818  * a single TSB.  physmem is the number of physical pages so we need physmem 8K
819  * TTEs to represent all those physical pages.  We round this up by using
820  * 1<<highbit().  To figure out which size code to use, remember that the size
821  * code is just an amount to shift the smallest TSB size to get the size of
822  * this TSB.  So we subtract that size, TSB_START_SIZE, from highbit() (or
823  * highbit() - 1) to get the size code for the smallest TSB that can represent
824  * all of physical memory, while erring on the side of too much.
825  *
826  * Restrict tsb_max_growsize to make sure that:
827  *	1) TSBs can't grow larger than the TSB slab size
828  *	2) TSBs can't grow larger than UTSB_MAX_SZCODE.
829  */
830 #define	SFMMU_SET_TSB_MAX_GROWSIZE(pages) {				\
831 	int	_i, _szc, _slabszc, _tsbszc;				\
832 									\
833 	_i = highbit(pages);						\
834 	if ((1 << (_i - 1)) == (pages))					\
835 		_i--;		/* 2^n case, round down */              \
836 	_szc = _i - TSB_START_SIZE;					\
837 	_slabszc = bigtsb_slab_shift - (TSB_START_SIZE + TSB_ENTRY_SHIFT); \
838 	_tsbszc = MIN(_szc, _slabszc);                                  \
839 	tsb_max_growsize = MIN(_tsbszc, UTSB_MAX_SZCODE);               \
840 }
841 
842 /*
843  * Given a pointer to an sfmmu and a TTE size code, return a pointer to the
844  * tsb_info which handles that TTE size.
845  */
846 #define	SFMMU_GET_TSBINFO(tsbinfop, sfmmup, tte_szc) {			\
847 	(tsbinfop) = (sfmmup)->sfmmu_tsb;				\
848 	ASSERT(((tsbinfop)->tsb_flags & TSB_SHAREDCTX) ||		\
849 	    sfmmu_hat_lock_held(sfmmup));				\
850 	if ((tte_szc) >= TTE4M)	{					\
851 		ASSERT((tsbinfop) != NULL);				\
852 		(tsbinfop) = (tsbinfop)->tsb_next;			\
853 	}								\
854 }
855 
856 /*
857  * Macro to use to unload entries from the TSB.
858  * It has knowledge of which page sizes get replicated in the TSB
859  * and will call the appropriate unload routine for the appropriate size.
860  */
861 #define	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, ismhat)		\
862 {									\
863 	int ttesz = get_hblk_ttesz(hmeblkp);				\
864 	if (ttesz == TTE8K || ttesz == TTE4M) {				\
865 		sfmmu_unload_tsb(sfmmup, addr, ttesz);			\
866 	} else {							\
867 		caddr_t sva = ismhat ? addr : 				\
868 		    (caddr_t)get_hblk_base(hmeblkp);			\
869 		caddr_t eva = sva + get_hblk_span(hmeblkp);		\
870 		ASSERT(addr >= sva && addr < eva);			\
871 		sfmmu_unload_tsb_range(sfmmup, sva, eva, ttesz);	\
872 	}								\
873 }
874 
875 
876 /* Update tsb_alloc_hiwater after memory is configured. */
877 /*ARGSUSED*/
878 static void
879 sfmmu_update_post_add(void *arg, pgcnt_t delta_pages)
880 {
881 	/* Assumes physmem has already been updated. */
882 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
883 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
884 }
885 
886 /*
887  * Update tsb_alloc_hiwater before memory is deleted.  We'll do nothing here
888  * and update tsb_alloc_hiwater and tsb_max_growsize after the memory is
889  * deleted.
890  */
891 /*ARGSUSED*/
892 static int
893 sfmmu_update_pre_del(void *arg, pgcnt_t delta_pages)
894 {
895 	return (0);
896 }
897 
898 /* Update tsb_alloc_hiwater after memory fails to be unconfigured. */
899 /*ARGSUSED*/
900 static void
901 sfmmu_update_post_del(void *arg, pgcnt_t delta_pages, int cancelled)
902 {
903 	/*
904 	 * Whether the delete was cancelled or not, just go ahead and update
905 	 * tsb_alloc_hiwater and tsb_max_growsize.
906 	 */
907 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
908 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
909 }
910 
911 static kphysm_setup_vector_t sfmmu_update_vec = {
912 	KPHYSM_SETUP_VECTOR_VERSION,	/* version */
913 	sfmmu_update_post_add,		/* post_add */
914 	sfmmu_update_pre_del,		/* pre_del */
915 	sfmmu_update_post_del		/* post_del */
916 };
917 
918 
919 /*
920  * HME_BLK HASH PRIMITIVES
921  */
922 
923 /*
924  * Enter a hme on the mapping list for page pp.
925  * When large pages are more prevalent in the system we might want to
926  * keep the mapping list in ascending order by the hment size. For now,
927  * small pages are more frequent, so don't slow it down.
928  */
929 #define	HME_ADD(hme, pp)					\
930 {								\
931 	ASSERT(sfmmu_mlist_held(pp));				\
932 								\
933 	hme->hme_prev = NULL;					\
934 	hme->hme_next = pp->p_mapping;				\
935 	hme->hme_page = pp;					\
936 	if (pp->p_mapping) {					\
937 		((struct sf_hment *)(pp->p_mapping))->hme_prev = hme;\
938 		ASSERT(pp->p_share > 0);			\
939 	} else  {						\
940 		/* EMPTY */					\
941 		ASSERT(pp->p_share == 0);			\
942 	}							\
943 	pp->p_mapping = hme;					\
944 	pp->p_share++;						\
945 }
946 
947 /*
948  * Enter a hme on the mapping list for page pp.
949  * If we are unmapping a large translation, we need to make sure that the
950  * change is reflect in the corresponding bit of the p_index field.
951  */
952 #define	HME_SUB(hme, pp)					\
953 {								\
954 	ASSERT(sfmmu_mlist_held(pp));				\
955 	ASSERT(hme->hme_page == pp || IS_PAHME(hme));		\
956 								\
957 	if (pp->p_mapping == NULL) {				\
958 		panic("hme_remove - no mappings");		\
959 	}							\
960 								\
961 	membar_stst();	/* ensure previous stores finish */	\
962 								\
963 	ASSERT(pp->p_share > 0);				\
964 	pp->p_share--;						\
965 								\
966 	if (hme->hme_prev) {					\
967 		ASSERT(pp->p_mapping != hme);			\
968 		ASSERT(hme->hme_prev->hme_page == pp ||		\
969 			IS_PAHME(hme->hme_prev));		\
970 		hme->hme_prev->hme_next = hme->hme_next;	\
971 	} else {						\
972 		ASSERT(pp->p_mapping == hme);			\
973 		pp->p_mapping = hme->hme_next;			\
974 		ASSERT((pp->p_mapping == NULL) ?		\
975 			(pp->p_share == 0) : 1);		\
976 	}							\
977 								\
978 	if (hme->hme_next) {					\
979 		ASSERT(hme->hme_next->hme_page == pp ||		\
980 			IS_PAHME(hme->hme_next));		\
981 		hme->hme_next->hme_prev = hme->hme_prev;	\
982 	}							\
983 								\
984 	/* zero out the entry */				\
985 	hme->hme_next = NULL;					\
986 	hme->hme_prev = NULL;					\
987 	hme->hme_page = NULL;					\
988 								\
989 	if (hme_size(hme) > TTE8K) {				\
990 		/* remove mappings for remainder of large pg */	\
991 		sfmmu_rm_large_mappings(pp, hme_size(hme));	\
992 	}							\
993 }
994 
995 /*
996  * This function returns the hment given the hme_blk and a vaddr.
997  * It assumes addr has already been checked to belong to hme_blk's
998  * range.
999  */
1000 #define	HBLKTOHME(hment, hmeblkp, addr)					\
1001 {									\
1002 	int index;							\
1003 	HBLKTOHME_IDX(hment, hmeblkp, addr, index)			\
1004 }
1005 
1006 /*
1007  * Version of HBLKTOHME that also returns the index in hmeblkp
1008  * of the hment.
1009  */
1010 #define	HBLKTOHME_IDX(hment, hmeblkp, addr, idx)			\
1011 {									\
1012 	ASSERT(in_hblk_range((hmeblkp), (addr)));			\
1013 									\
1014 	if (get_hblk_ttesz(hmeblkp) == TTE8K) {				\
1015 		idx = (((uintptr_t)(addr) >> MMU_PAGESHIFT) & (NHMENTS-1)); \
1016 	} else								\
1017 		idx = 0;						\
1018 									\
1019 	(hment) = &(hmeblkp)->hblk_hme[idx];				\
1020 }
1021 
1022 /*
1023  * Disable any page sizes not supported by the CPU
1024  */
1025 void
1026 hat_init_pagesizes()
1027 {
1028 	int 		i;
1029 
1030 	mmu_exported_page_sizes = 0;
1031 	for (i = TTE8K; i < max_mmu_page_sizes; i++) {
1032 
1033 		szc_2_userszc[i] = (uint_t)-1;
1034 		userszc_2_szc[i] = (uint_t)-1;
1035 
1036 		if ((mmu_exported_pagesize_mask & (1 << i)) == 0) {
1037 			disable_large_pages |= (1 << i);
1038 		} else {
1039 			szc_2_userszc[i] = mmu_exported_page_sizes;
1040 			userszc_2_szc[mmu_exported_page_sizes] = i;
1041 			mmu_exported_page_sizes++;
1042 		}
1043 	}
1044 
1045 	disable_ism_large_pages |= disable_large_pages;
1046 	disable_auto_data_large_pages = disable_large_pages;
1047 	disable_auto_text_large_pages = disable_large_pages;
1048 
1049 	/*
1050 	 * Initialize mmu-specific large page sizes.
1051 	 */
1052 	if (&mmu_large_pages_disabled) {
1053 		disable_large_pages |= mmu_large_pages_disabled(HAT_LOAD);
1054 		disable_ism_large_pages |=
1055 		    mmu_large_pages_disabled(HAT_LOAD_SHARE);
1056 		disable_auto_data_large_pages |=
1057 		    mmu_large_pages_disabled(HAT_AUTO_DATA);
1058 		disable_auto_text_large_pages |=
1059 		    mmu_large_pages_disabled(HAT_AUTO_TEXT);
1060 	}
1061 }
1062 
1063 /*
1064  * Initialize the hardware address translation structures.
1065  */
1066 void
1067 hat_init(void)
1068 {
1069 	int 		i;
1070 	uint_t		sz;
1071 	size_t		size;
1072 
1073 	hat_lock_init();
1074 	hat_kstat_init();
1075 
1076 	/*
1077 	 * Hardware-only bits in a TTE
1078 	 */
1079 	MAKE_TTE_MASK(&hw_tte);
1080 
1081 	hat_init_pagesizes();
1082 
1083 	/* Initialize the hash locks */
1084 	for (i = 0; i < khmehash_num; i++) {
1085 		mutex_init(&khme_hash[i].hmehash_mutex, NULL,
1086 		    MUTEX_DEFAULT, NULL);
1087 	}
1088 	for (i = 0; i < uhmehash_num; i++) {
1089 		mutex_init(&uhme_hash[i].hmehash_mutex, NULL,
1090 		    MUTEX_DEFAULT, NULL);
1091 	}
1092 	khmehash_num--;		/* make sure counter starts from 0 */
1093 	uhmehash_num--;		/* make sure counter starts from 0 */
1094 
1095 	/*
1096 	 * Allocate context domain structures.
1097 	 *
1098 	 * A platform may choose to modify max_mmu_ctxdoms in
1099 	 * set_platform_defaults(). If a platform does not define
1100 	 * a set_platform_defaults() or does not choose to modify
1101 	 * max_mmu_ctxdoms, it gets one MMU context domain for every CPU.
1102 	 *
1103 	 * For sun4v, there will be one global context domain, this is to
1104 	 * avoid the ldom cpu substitution problem.
1105 	 *
1106 	 * For all platforms that have CPUs sharing MMUs, this
1107 	 * value must be defined.
1108 	 */
1109 	if (max_mmu_ctxdoms == 0) {
1110 #ifndef sun4v
1111 		max_mmu_ctxdoms = max_ncpus;
1112 #else /* sun4v */
1113 		max_mmu_ctxdoms = 1;
1114 #endif /* sun4v */
1115 	}
1116 
1117 	size = max_mmu_ctxdoms * sizeof (mmu_ctx_t *);
1118 	mmu_ctxs_tbl = kmem_zalloc(size, KM_SLEEP);
1119 
1120 	/* mmu_ctx_t is 64 bytes aligned */
1121 	mmuctxdom_cache = kmem_cache_create("mmuctxdom_cache",
1122 	    sizeof (mmu_ctx_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
1123 	/*
1124 	 * MMU context domain initialization for the Boot CPU.
1125 	 * This needs the context domains array allocated above.
1126 	 */
1127 	mutex_enter(&cpu_lock);
1128 	sfmmu_cpu_init(CPU);
1129 	mutex_exit(&cpu_lock);
1130 
1131 	/*
1132 	 * Intialize ism mapping list lock.
1133 	 */
1134 
1135 	mutex_init(&ism_mlist_lock, NULL, MUTEX_DEFAULT, NULL);
1136 
1137 	/*
1138 	 * Each sfmmu structure carries an array of MMU context info
1139 	 * structures, one per context domain. The size of this array depends
1140 	 * on the maximum number of context domains. So, the size of the
1141 	 * sfmmu structure varies per platform.
1142 	 *
1143 	 * sfmmu is allocated from static arena, because trap
1144 	 * handler at TL > 0 is not allowed to touch kernel relocatable
1145 	 * memory. sfmmu's alignment is changed to 64 bytes from
1146 	 * default 8 bytes, as the lower 6 bits will be used to pass
1147 	 * pgcnt to vtag_flush_pgcnt_tl1.
1148 	 */
1149 	size = sizeof (sfmmu_t) + sizeof (sfmmu_ctx_t) * (max_mmu_ctxdoms - 1);
1150 
1151 	sfmmuid_cache = kmem_cache_create("sfmmuid_cache", size,
1152 	    64, sfmmu_idcache_constructor, sfmmu_idcache_destructor,
1153 	    NULL, NULL, static_arena, 0);
1154 
1155 	sfmmu_tsbinfo_cache = kmem_cache_create("sfmmu_tsbinfo_cache",
1156 	    sizeof (struct tsb_info), 0, NULL, NULL, NULL, NULL, NULL, 0);
1157 
1158 	/*
1159 	 * Since we only use the tsb8k cache to "borrow" pages for TSBs
1160 	 * from the heap when low on memory or when TSB_FORCEALLOC is
1161 	 * specified, don't use magazines to cache them--we want to return
1162 	 * them to the system as quickly as possible.
1163 	 */
1164 	sfmmu_tsb8k_cache = kmem_cache_create("sfmmu_tsb8k_cache",
1165 	    MMU_PAGESIZE, MMU_PAGESIZE, NULL, NULL, NULL, NULL,
1166 	    static_arena, KMC_NOMAGAZINE);
1167 
1168 	/*
1169 	 * Set tsb_alloc_hiwater to 1/tsb_alloc_hiwater_factor of physical
1170 	 * memory, which corresponds to the old static reserve for TSBs.
1171 	 * tsb_alloc_hiwater_factor defaults to 32.  This caps the amount of
1172 	 * memory we'll allocate for TSB slabs; beyond this point TSB
1173 	 * allocations will be taken from the kernel heap (via
1174 	 * sfmmu_tsb8k_cache) and will be throttled as would any other kmem
1175 	 * consumer.
1176 	 */
1177 	if (tsb_alloc_hiwater_factor == 0) {
1178 		tsb_alloc_hiwater_factor = TSB_ALLOC_HIWATER_FACTOR_DEFAULT;
1179 	}
1180 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
1181 
1182 	for (sz = tsb_slab_ttesz; sz > 0; sz--) {
1183 		if (!(disable_large_pages & (1 << sz)))
1184 			break;
1185 	}
1186 
1187 	if (sz < tsb_slab_ttesz) {
1188 		tsb_slab_ttesz = sz;
1189 		tsb_slab_shift = MMU_PAGESHIFT + (sz << 1) + sz;
1190 		tsb_slab_size = 1 << tsb_slab_shift;
1191 		tsb_slab_mask = (1 << (tsb_slab_shift - MMU_PAGESHIFT)) - 1;
1192 		use_bigtsb_arena = 0;
1193 	} else if (use_bigtsb_arena &&
1194 	    (disable_large_pages & (1 << bigtsb_slab_ttesz))) {
1195 		use_bigtsb_arena = 0;
1196 	}
1197 
1198 	if (!use_bigtsb_arena) {
1199 		bigtsb_slab_shift = tsb_slab_shift;
1200 	}
1201 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
1202 
1203 	/*
1204 	 * On smaller memory systems, allocate TSB memory in smaller chunks
1205 	 * than the default 4M slab size. We also honor disable_large_pages
1206 	 * here.
1207 	 *
1208 	 * The trap handlers need to be patched with the final slab shift,
1209 	 * since they need to be able to construct the TSB pointer at runtime.
1210 	 */
1211 	if ((tsb_max_growsize <= TSB_512K_SZCODE) &&
1212 	    !(disable_large_pages & (1 << TTE512K))) {
1213 		tsb_slab_ttesz = TTE512K;
1214 		tsb_slab_shift = MMU_PAGESHIFT512K;
1215 		tsb_slab_size = MMU_PAGESIZE512K;
1216 		tsb_slab_mask = MMU_PAGEOFFSET512K >> MMU_PAGESHIFT;
1217 		use_bigtsb_arena = 0;
1218 	}
1219 
1220 	if (!use_bigtsb_arena) {
1221 		bigtsb_slab_ttesz = tsb_slab_ttesz;
1222 		bigtsb_slab_shift = tsb_slab_shift;
1223 		bigtsb_slab_size = tsb_slab_size;
1224 		bigtsb_slab_mask = tsb_slab_mask;
1225 	}
1226 
1227 
1228 	/*
1229 	 * Set up memory callback to update tsb_alloc_hiwater and
1230 	 * tsb_max_growsize.
1231 	 */
1232 	i = kphysm_setup_func_register(&sfmmu_update_vec, (void *) 0);
1233 	ASSERT(i == 0);
1234 
1235 	/*
1236 	 * kmem_tsb_arena is the source from which large TSB slabs are
1237 	 * drawn.  The quantum of this arena corresponds to the largest
1238 	 * TSB size we can dynamically allocate for user processes.
1239 	 * Currently it must also be a supported page size since we
1240 	 * use exactly one translation entry to map each slab page.
1241 	 *
1242 	 * The per-lgroup kmem_tsb_default_arena arenas are the arenas from
1243 	 * which most TSBs are allocated.  Since most TSB allocations are
1244 	 * typically 8K we have a kmem cache we stack on top of each
1245 	 * kmem_tsb_default_arena to speed up those allocations.
1246 	 *
1247 	 * Note the two-level scheme of arenas is required only
1248 	 * because vmem_create doesn't allow us to specify alignment
1249 	 * requirements.  If this ever changes the code could be
1250 	 * simplified to use only one level of arenas.
1251 	 *
1252 	 * If 256M page support exists on sun4v, 256MB kmem_bigtsb_arena
1253 	 * will be provided in addition to the 4M kmem_tsb_arena.
1254 	 */
1255 	if (use_bigtsb_arena) {
1256 		kmem_bigtsb_arena = vmem_create("kmem_bigtsb", NULL, 0,
1257 		    bigtsb_slab_size, sfmmu_vmem_xalloc_aligned_wrapper,
1258 		    vmem_xfree, heap_arena, 0, VM_SLEEP);
1259 	}
1260 
1261 	kmem_tsb_arena = vmem_create("kmem_tsb", NULL, 0, tsb_slab_size,
1262 	    sfmmu_vmem_xalloc_aligned_wrapper,
1263 	    vmem_xfree, heap_arena, 0, VM_SLEEP);
1264 
1265 	if (tsb_lgrp_affinity) {
1266 		char s[50];
1267 		for (i = 0; i < NLGRPS_MAX; i++) {
1268 			if (use_bigtsb_arena) {
1269 				(void) sprintf(s, "kmem_bigtsb_lgrp%d", i);
1270 				kmem_bigtsb_default_arena[i] = vmem_create(s,
1271 				    NULL, 0, 2 * tsb_slab_size,
1272 				    sfmmu_tsb_segkmem_alloc,
1273 				    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena,
1274 				    0, VM_SLEEP | VM_BESTFIT);
1275 			}
1276 
1277 			(void) sprintf(s, "kmem_tsb_lgrp%d", i);
1278 			kmem_tsb_default_arena[i] = vmem_create(s,
1279 			    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1280 			    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1281 			    VM_SLEEP | VM_BESTFIT);
1282 
1283 			(void) sprintf(s, "sfmmu_tsb_lgrp%d_cache", i);
1284 			sfmmu_tsb_cache[i] = kmem_cache_create(s,
1285 			    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1286 			    kmem_tsb_default_arena[i], 0);
1287 		}
1288 	} else {
1289 		if (use_bigtsb_arena) {
1290 			kmem_bigtsb_default_arena[0] =
1291 			    vmem_create("kmem_bigtsb_default", NULL, 0,
1292 			    2 * tsb_slab_size, sfmmu_tsb_segkmem_alloc,
1293 			    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena, 0,
1294 			    VM_SLEEP | VM_BESTFIT);
1295 		}
1296 
1297 		kmem_tsb_default_arena[0] = vmem_create("kmem_tsb_default",
1298 		    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1299 		    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1300 		    VM_SLEEP | VM_BESTFIT);
1301 		sfmmu_tsb_cache[0] = kmem_cache_create("sfmmu_tsb_cache",
1302 		    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1303 		    kmem_tsb_default_arena[0], 0);
1304 	}
1305 
1306 	sfmmu8_cache = kmem_cache_create("sfmmu8_cache", HME8BLK_SZ,
1307 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1308 	    sfmmu_hblkcache_destructor,
1309 	    sfmmu_hblkcache_reclaim, (void *)HME8BLK_SZ,
1310 	    hat_memload_arena, KMC_NOHASH);
1311 
1312 	hat_memload1_arena = vmem_create("hat_memload1", NULL, 0, PAGESIZE,
1313 	    segkmem_alloc_permanent, segkmem_free, heap_arena, 0, VM_SLEEP);
1314 
1315 	sfmmu1_cache = kmem_cache_create("sfmmu1_cache", HME1BLK_SZ,
1316 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1317 	    sfmmu_hblkcache_destructor,
1318 	    NULL, (void *)HME1BLK_SZ,
1319 	    hat_memload1_arena, KMC_NOHASH);
1320 
1321 	pa_hment_cache = kmem_cache_create("pa_hment_cache", PAHME_SZ,
1322 	    0, NULL, NULL, NULL, NULL, static_arena, KMC_NOHASH);
1323 
1324 	ism_blk_cache = kmem_cache_create("ism_blk_cache",
1325 	    sizeof (ism_blk_t), ecache_alignsize, NULL, NULL,
1326 	    NULL, NULL, static_arena, KMC_NOHASH);
1327 
1328 	ism_ment_cache = kmem_cache_create("ism_ment_cache",
1329 	    sizeof (ism_ment_t), 0, NULL, NULL,
1330 	    NULL, NULL, NULL, 0);
1331 
1332 	/*
1333 	 * We grab the first hat for the kernel,
1334 	 */
1335 	AS_LOCK_ENTER(&kas, &kas.a_lock, RW_WRITER);
1336 	kas.a_hat = hat_alloc(&kas);
1337 	AS_LOCK_EXIT(&kas, &kas.a_lock);
1338 
1339 	/*
1340 	 * Initialize hblk_reserve.
1341 	 */
1342 	((struct hme_blk *)hblk_reserve)->hblk_nextpa =
1343 	    va_to_pa((caddr_t)hblk_reserve);
1344 
1345 #ifndef UTSB_PHYS
1346 	/*
1347 	 * Reserve some kernel virtual address space for the locked TTEs
1348 	 * that allow us to probe the TSB from TL>0.
1349 	 */
1350 	utsb_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1351 	    0, 0, NULL, NULL, VM_SLEEP);
1352 	utsb4m_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1353 	    0, 0, NULL, NULL, VM_SLEEP);
1354 #endif
1355 
1356 #ifdef VAC
1357 	/*
1358 	 * The big page VAC handling code assumes VAC
1359 	 * will not be bigger than the smallest big
1360 	 * page- which is 64K.
1361 	 */
1362 	if (TTEPAGES(TTE64K) < CACHE_NUM_COLOR) {
1363 		cmn_err(CE_PANIC, "VAC too big!");
1364 	}
1365 #endif
1366 
1367 	(void) xhat_init();
1368 
1369 	uhme_hash_pa = va_to_pa(uhme_hash);
1370 	khme_hash_pa = va_to_pa(khme_hash);
1371 
1372 	/*
1373 	 * Initialize relocation locks. kpr_suspendlock is held
1374 	 * at PIL_MAX to prevent interrupts from pinning the holder
1375 	 * of a suspended TTE which may access it leading to a
1376 	 * deadlock condition.
1377 	 */
1378 	mutex_init(&kpr_mutex, NULL, MUTEX_DEFAULT, NULL);
1379 	mutex_init(&kpr_suspendlock, NULL, MUTEX_SPIN, (void *)PIL_MAX);
1380 
1381 	/*
1382 	 * If Shared context support is disabled via /etc/system
1383 	 * set shctx_on to 0 here if it was set to 1 earlier in boot
1384 	 * sequence by cpu module initialization code.
1385 	 */
1386 	if (shctx_on && disable_shctx) {
1387 		shctx_on = 0;
1388 	}
1389 
1390 	if (shctx_on) {
1391 		srd_buckets = kmem_zalloc(SFMMU_MAX_SRD_BUCKETS *
1392 		    sizeof (srd_buckets[0]), KM_SLEEP);
1393 		for (i = 0; i < SFMMU_MAX_SRD_BUCKETS; i++) {
1394 			mutex_init(&srd_buckets[i].srdb_lock, NULL,
1395 			    MUTEX_DEFAULT, NULL);
1396 		}
1397 
1398 		srd_cache = kmem_cache_create("srd_cache", sizeof (sf_srd_t),
1399 		    0, sfmmu_srdcache_constructor, sfmmu_srdcache_destructor,
1400 		    NULL, NULL, NULL, 0);
1401 		region_cache = kmem_cache_create("region_cache",
1402 		    sizeof (sf_region_t), 0, sfmmu_rgncache_constructor,
1403 		    sfmmu_rgncache_destructor, NULL, NULL, NULL, 0);
1404 		scd_cache = kmem_cache_create("scd_cache", sizeof (sf_scd_t),
1405 		    0, sfmmu_scdcache_constructor,  sfmmu_scdcache_destructor,
1406 		    NULL, NULL, NULL, 0);
1407 	}
1408 
1409 	/*
1410 	 * Pre-allocate hrm_hashtab before enabling the collection of
1411 	 * refmod statistics.  Allocating on the fly would mean us
1412 	 * running the risk of suffering recursive mutex enters or
1413 	 * deadlocks.
1414 	 */
1415 	hrm_hashtab = kmem_zalloc(HRM_HASHSIZE * sizeof (struct hrmstat *),
1416 	    KM_SLEEP);
1417 }
1418 
1419 /*
1420  * Initialize locking for the hat layer, called early during boot.
1421  */
1422 static void
1423 hat_lock_init()
1424 {
1425 	int i;
1426 
1427 	/*
1428 	 * initialize the array of mutexes protecting a page's mapping
1429 	 * list and p_nrm field.
1430 	 */
1431 	for (i = 0; i < mml_table_sz; i++)
1432 		mutex_init(&mml_table[i], NULL, MUTEX_DEFAULT, NULL);
1433 
1434 	if (kpm_enable) {
1435 		for (i = 0; i < kpmp_table_sz; i++) {
1436 			mutex_init(&kpmp_table[i].khl_mutex, NULL,
1437 			    MUTEX_DEFAULT, NULL);
1438 		}
1439 	}
1440 
1441 	/*
1442 	 * Initialize array of mutex locks that protects sfmmu fields and
1443 	 * TSB lists.
1444 	 */
1445 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
1446 		mutex_init(HATLOCK_MUTEXP(&hat_lock[i]), NULL, MUTEX_DEFAULT,
1447 		    NULL);
1448 }
1449 
1450 #define	SFMMU_KERNEL_MAXVA \
1451 	(kmem64_base ? (uintptr_t)kmem64_end : (SYSLIMIT))
1452 
1453 /*
1454  * Allocate a hat structure.
1455  * Called when an address space first uses a hat.
1456  */
1457 struct hat *
1458 hat_alloc(struct as *as)
1459 {
1460 	sfmmu_t *sfmmup;
1461 	int i;
1462 	uint64_t cnum;
1463 	extern uint_t get_color_start(struct as *);
1464 
1465 	ASSERT(AS_WRITE_HELD(as, &as->a_lock));
1466 	sfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
1467 	sfmmup->sfmmu_as = as;
1468 	sfmmup->sfmmu_flags = 0;
1469 	sfmmup->sfmmu_tteflags = 0;
1470 	sfmmup->sfmmu_rtteflags = 0;
1471 	LOCK_INIT_CLEAR(&sfmmup->sfmmu_ctx_lock);
1472 
1473 	if (as == &kas) {
1474 		ksfmmup = sfmmup;
1475 		sfmmup->sfmmu_cext = 0;
1476 		cnum = KCONTEXT;
1477 
1478 		sfmmup->sfmmu_clrstart = 0;
1479 		sfmmup->sfmmu_tsb = NULL;
1480 		/*
1481 		 * hat_kern_setup() will call sfmmu_init_ktsbinfo()
1482 		 * to setup tsb_info for ksfmmup.
1483 		 */
1484 	} else {
1485 
1486 		/*
1487 		 * Just set to invalid ctx. When it faults, it will
1488 		 * get a valid ctx. This would avoid the situation
1489 		 * where we get a ctx, but it gets stolen and then
1490 		 * we fault when we try to run and so have to get
1491 		 * another ctx.
1492 		 */
1493 		sfmmup->sfmmu_cext = 0;
1494 		cnum = INVALID_CONTEXT;
1495 
1496 		/* initialize original physical page coloring bin */
1497 		sfmmup->sfmmu_clrstart = get_color_start(as);
1498 #ifdef DEBUG
1499 		if (tsb_random_size) {
1500 			uint32_t randval = (uint32_t)gettick() >> 4;
1501 			int size = randval % (tsb_max_growsize + 1);
1502 
1503 			/* chose a random tsb size for stress testing */
1504 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb, size,
1505 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1506 		} else
1507 #endif /* DEBUG */
1508 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb,
1509 			    default_tsb_size,
1510 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1511 		sfmmup->sfmmu_flags = HAT_SWAPPED | HAT_ALLCTX_INVALID;
1512 		ASSERT(sfmmup->sfmmu_tsb != NULL);
1513 	}
1514 
1515 	ASSERT(max_mmu_ctxdoms > 0);
1516 	for (i = 0; i < max_mmu_ctxdoms; i++) {
1517 		sfmmup->sfmmu_ctxs[i].cnum = cnum;
1518 		sfmmup->sfmmu_ctxs[i].gnum = 0;
1519 	}
1520 
1521 	for (i = 0; i < max_mmu_page_sizes; i++) {
1522 		sfmmup->sfmmu_ttecnt[i] = 0;
1523 		sfmmup->sfmmu_scdrttecnt[i] = 0;
1524 		sfmmup->sfmmu_ismttecnt[i] = 0;
1525 		sfmmup->sfmmu_scdismttecnt[i] = 0;
1526 		sfmmup->sfmmu_pgsz[i] = TTE8K;
1527 	}
1528 	sfmmup->sfmmu_tsb0_4minflcnt = 0;
1529 	sfmmup->sfmmu_iblk = NULL;
1530 	sfmmup->sfmmu_ismhat = 0;
1531 	sfmmup->sfmmu_scdhat = 0;
1532 	sfmmup->sfmmu_ismblkpa = (uint64_t)-1;
1533 	if (sfmmup == ksfmmup) {
1534 		CPUSET_ALL(sfmmup->sfmmu_cpusran);
1535 	} else {
1536 		CPUSET_ZERO(sfmmup->sfmmu_cpusran);
1537 	}
1538 	sfmmup->sfmmu_free = 0;
1539 	sfmmup->sfmmu_rmstat = 0;
1540 	sfmmup->sfmmu_clrbin = sfmmup->sfmmu_clrstart;
1541 	sfmmup->sfmmu_xhat_provider = NULL;
1542 	cv_init(&sfmmup->sfmmu_tsb_cv, NULL, CV_DEFAULT, NULL);
1543 	sfmmup->sfmmu_srdp = NULL;
1544 	SF_RGNMAP_ZERO(sfmmup->sfmmu_region_map);
1545 	bzero(sfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
1546 	sfmmup->sfmmu_scdp = NULL;
1547 	sfmmup->sfmmu_scd_link.next = NULL;
1548 	sfmmup->sfmmu_scd_link.prev = NULL;
1549 	return (sfmmup);
1550 }
1551 
1552 /*
1553  * Create per-MMU context domain kstats for a given MMU ctx.
1554  */
1555 static void
1556 sfmmu_mmu_kstat_create(mmu_ctx_t *mmu_ctxp)
1557 {
1558 	mmu_ctx_stat_t	stat;
1559 	kstat_t		*mmu_kstat;
1560 
1561 	ASSERT(MUTEX_HELD(&cpu_lock));
1562 	ASSERT(mmu_ctxp->mmu_kstat == NULL);
1563 
1564 	mmu_kstat = kstat_create("unix", mmu_ctxp->mmu_idx, "mmu_ctx",
1565 	    "hat", KSTAT_TYPE_NAMED, MMU_CTX_NUM_STATS, KSTAT_FLAG_VIRTUAL);
1566 
1567 	if (mmu_kstat == NULL) {
1568 		cmn_err(CE_WARN, "kstat_create for MMU %d failed",
1569 		    mmu_ctxp->mmu_idx);
1570 	} else {
1571 		mmu_kstat->ks_data = mmu_ctxp->mmu_kstat_data;
1572 		for (stat = 0; stat < MMU_CTX_NUM_STATS; stat++)
1573 			kstat_named_init(&mmu_ctxp->mmu_kstat_data[stat],
1574 			    mmu_ctx_kstat_names[stat], KSTAT_DATA_INT64);
1575 		mmu_ctxp->mmu_kstat = mmu_kstat;
1576 		kstat_install(mmu_kstat);
1577 	}
1578 }
1579 
1580 /*
1581  * plat_cpuid_to_mmu_ctx_info() is a platform interface that returns MMU
1582  * context domain information for a given CPU. If a platform does not
1583  * specify that interface, then the function below is used instead to return
1584  * default information. The defaults are as follows:
1585  *
1586  *	- For sun4u systems there's one MMU context domain per CPU.
1587  *	  This default is used by all sun4u systems except OPL. OPL systems
1588  *	  provide platform specific interface to map CPU ids to MMU ids
1589  *	  because on OPL more than 1 CPU shares a single MMU.
1590  *        Note that on sun4v, there is one global context domain for
1591  *	  the entire system. This is to avoid running into potential problem
1592  *	  with ldom physical cpu substitution feature.
1593  *	- The number of MMU context IDs supported on any CPU in the
1594  *	  system is 8K.
1595  */
1596 /*ARGSUSED*/
1597 static void
1598 sfmmu_cpuid_to_mmu_ctx_info(processorid_t cpuid, mmu_ctx_info_t *infop)
1599 {
1600 	infop->mmu_nctxs = nctxs;
1601 #ifndef sun4v
1602 	infop->mmu_idx = cpu[cpuid]->cpu_seqid;
1603 #else /* sun4v */
1604 	infop->mmu_idx = 0;
1605 #endif /* sun4v */
1606 }
1607 
1608 /*
1609  * Called during CPU initialization to set the MMU context-related information
1610  * for a CPU.
1611  *
1612  * cpu_lock serializes accesses to mmu_ctxs and mmu_saved_gnum.
1613  */
1614 void
1615 sfmmu_cpu_init(cpu_t *cp)
1616 {
1617 	mmu_ctx_info_t	info;
1618 	mmu_ctx_t	*mmu_ctxp;
1619 
1620 	ASSERT(MUTEX_HELD(&cpu_lock));
1621 
1622 	if (&plat_cpuid_to_mmu_ctx_info == NULL)
1623 		sfmmu_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1624 	else
1625 		plat_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1626 
1627 	ASSERT(info.mmu_idx < max_mmu_ctxdoms);
1628 
1629 	if ((mmu_ctxp = mmu_ctxs_tbl[info.mmu_idx]) == NULL) {
1630 		/* Each mmu_ctx is cacheline aligned. */
1631 		mmu_ctxp = kmem_cache_alloc(mmuctxdom_cache, KM_SLEEP);
1632 		bzero(mmu_ctxp, sizeof (mmu_ctx_t));
1633 
1634 		mutex_init(&mmu_ctxp->mmu_lock, NULL, MUTEX_SPIN,
1635 		    (void *)ipltospl(DISP_LEVEL));
1636 		mmu_ctxp->mmu_idx = info.mmu_idx;
1637 		mmu_ctxp->mmu_nctxs = info.mmu_nctxs;
1638 		/*
1639 		 * Globally for lifetime of a system,
1640 		 * gnum must always increase.
1641 		 * mmu_saved_gnum is protected by the cpu_lock.
1642 		 */
1643 		mmu_ctxp->mmu_gnum = mmu_saved_gnum + 1;
1644 		mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
1645 
1646 		sfmmu_mmu_kstat_create(mmu_ctxp);
1647 
1648 		mmu_ctxs_tbl[info.mmu_idx] = mmu_ctxp;
1649 	} else {
1650 		ASSERT(mmu_ctxp->mmu_idx == info.mmu_idx);
1651 	}
1652 
1653 	/*
1654 	 * The mmu_lock is acquired here to prevent races with
1655 	 * the wrap-around code.
1656 	 */
1657 	mutex_enter(&mmu_ctxp->mmu_lock);
1658 
1659 
1660 	mmu_ctxp->mmu_ncpus++;
1661 	CPUSET_ADD(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1662 	CPU_MMU_IDX(cp) = info.mmu_idx;
1663 	CPU_MMU_CTXP(cp) = mmu_ctxp;
1664 
1665 	mutex_exit(&mmu_ctxp->mmu_lock);
1666 }
1667 
1668 /*
1669  * Called to perform MMU context-related cleanup for a CPU.
1670  */
1671 void
1672 sfmmu_cpu_cleanup(cpu_t *cp)
1673 {
1674 	mmu_ctx_t	*mmu_ctxp;
1675 
1676 	ASSERT(MUTEX_HELD(&cpu_lock));
1677 
1678 	mmu_ctxp = CPU_MMU_CTXP(cp);
1679 	ASSERT(mmu_ctxp != NULL);
1680 
1681 	/*
1682 	 * The mmu_lock is acquired here to prevent races with
1683 	 * the wrap-around code.
1684 	 */
1685 	mutex_enter(&mmu_ctxp->mmu_lock);
1686 
1687 	CPU_MMU_CTXP(cp) = NULL;
1688 
1689 	CPUSET_DEL(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1690 	if (--mmu_ctxp->mmu_ncpus == 0) {
1691 		mmu_ctxs_tbl[mmu_ctxp->mmu_idx] = NULL;
1692 		mutex_exit(&mmu_ctxp->mmu_lock);
1693 		mutex_destroy(&mmu_ctxp->mmu_lock);
1694 
1695 		if (mmu_ctxp->mmu_kstat)
1696 			kstat_delete(mmu_ctxp->mmu_kstat);
1697 
1698 		/* mmu_saved_gnum is protected by the cpu_lock. */
1699 		if (mmu_saved_gnum < mmu_ctxp->mmu_gnum)
1700 			mmu_saved_gnum = mmu_ctxp->mmu_gnum;
1701 
1702 		kmem_cache_free(mmuctxdom_cache, mmu_ctxp);
1703 
1704 		return;
1705 	}
1706 
1707 	mutex_exit(&mmu_ctxp->mmu_lock);
1708 }
1709 
1710 /*
1711  * Hat_setup, makes an address space context the current active one.
1712  * In sfmmu this translates to setting the secondary context with the
1713  * corresponding context.
1714  */
1715 void
1716 hat_setup(struct hat *sfmmup, int allocflag)
1717 {
1718 	hatlock_t *hatlockp;
1719 
1720 	/* Init needs some special treatment. */
1721 	if (allocflag == HAT_INIT) {
1722 		/*
1723 		 * Make sure that we have
1724 		 * 1. a TSB
1725 		 * 2. a valid ctx that doesn't get stolen after this point.
1726 		 */
1727 		hatlockp = sfmmu_hat_enter(sfmmup);
1728 
1729 		/*
1730 		 * Swap in the TSB.  hat_init() allocates tsbinfos without
1731 		 * TSBs, but we need one for init, since the kernel does some
1732 		 * special things to set up its stack and needs the TSB to
1733 		 * resolve page faults.
1734 		 */
1735 		sfmmu_tsb_swapin(sfmmup, hatlockp);
1736 
1737 		sfmmu_get_ctx(sfmmup);
1738 
1739 		sfmmu_hat_exit(hatlockp);
1740 	} else {
1741 		ASSERT(allocflag == HAT_ALLOC);
1742 
1743 		hatlockp = sfmmu_hat_enter(sfmmup);
1744 		kpreempt_disable();
1745 
1746 		CPUSET_ADD(sfmmup->sfmmu_cpusran, CPU->cpu_id);
1747 		/*
1748 		 * sfmmu_setctx_sec takes <pgsz|cnum> as a parameter,
1749 		 * pagesize bits don't matter in this case since we are passing
1750 		 * INVALID_CONTEXT to it.
1751 		 * Compatibility Note: hw takes care of MMU_SCONTEXT1
1752 		 */
1753 		sfmmu_setctx_sec(INVALID_CONTEXT);
1754 		sfmmu_clear_utsbinfo();
1755 
1756 		kpreempt_enable();
1757 		sfmmu_hat_exit(hatlockp);
1758 	}
1759 }
1760 
1761 /*
1762  * Free all the translation resources for the specified address space.
1763  * Called from as_free when an address space is being destroyed.
1764  */
1765 void
1766 hat_free_start(struct hat *sfmmup)
1767 {
1768 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
1769 	ASSERT(sfmmup != ksfmmup);
1770 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1771 
1772 	sfmmup->sfmmu_free = 1;
1773 	if (sfmmup->sfmmu_scdp != NULL) {
1774 		sfmmu_leave_scd(sfmmup, 0);
1775 	}
1776 
1777 	ASSERT(sfmmup->sfmmu_scdp == NULL);
1778 }
1779 
1780 void
1781 hat_free_end(struct hat *sfmmup)
1782 {
1783 	int i;
1784 
1785 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1786 	ASSERT(sfmmup->sfmmu_free == 1);
1787 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
1788 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
1789 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
1790 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
1791 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
1792 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
1793 
1794 	if (sfmmup->sfmmu_rmstat) {
1795 		hat_freestat(sfmmup->sfmmu_as, NULL);
1796 	}
1797 
1798 	while (sfmmup->sfmmu_tsb != NULL) {
1799 		struct tsb_info *next = sfmmup->sfmmu_tsb->tsb_next;
1800 		sfmmu_tsbinfo_free(sfmmup->sfmmu_tsb);
1801 		sfmmup->sfmmu_tsb = next;
1802 	}
1803 
1804 	if (sfmmup->sfmmu_srdp != NULL) {
1805 		sfmmu_leave_srd(sfmmup);
1806 		ASSERT(sfmmup->sfmmu_srdp == NULL);
1807 		for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1808 			if (sfmmup->sfmmu_hmeregion_links[i] != NULL) {
1809 				kmem_free(sfmmup->sfmmu_hmeregion_links[i],
1810 				    SFMMU_L2_HMERLINKS_SIZE);
1811 				sfmmup->sfmmu_hmeregion_links[i] = NULL;
1812 			}
1813 		}
1814 	}
1815 	sfmmu_free_sfmmu(sfmmup);
1816 
1817 #ifdef DEBUG
1818 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1819 		ASSERT(sfmmup->sfmmu_hmeregion_links[i] == NULL);
1820 	}
1821 #endif
1822 
1823 	kmem_cache_free(sfmmuid_cache, sfmmup);
1824 }
1825 
1826 /*
1827  * Set up any translation structures, for the specified address space,
1828  * that are needed or preferred when the process is being swapped in.
1829  */
1830 /* ARGSUSED */
1831 void
1832 hat_swapin(struct hat *hat)
1833 {
1834 	ASSERT(hat->sfmmu_xhat_provider == NULL);
1835 }
1836 
1837 /*
1838  * Free all of the translation resources, for the specified address space,
1839  * that can be freed while the process is swapped out. Called from as_swapout.
1840  * Also, free up the ctx that this process was using.
1841  */
1842 void
1843 hat_swapout(struct hat *sfmmup)
1844 {
1845 	struct hmehash_bucket *hmebp;
1846 	struct hme_blk *hmeblkp;
1847 	struct hme_blk *pr_hblk = NULL;
1848 	struct hme_blk *nx_hblk;
1849 	int i;
1850 	uint64_t hblkpa, prevpa, nx_pa;
1851 	struct hme_blk *list = NULL;
1852 	hatlock_t *hatlockp;
1853 	struct tsb_info *tsbinfop;
1854 	struct free_tsb {
1855 		struct free_tsb *next;
1856 		struct tsb_info *tsbinfop;
1857 	};			/* free list of TSBs */
1858 	struct free_tsb *freelist, *last, *next;
1859 
1860 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1861 	SFMMU_STAT(sf_swapout);
1862 
1863 	/*
1864 	 * There is no way to go from an as to all its translations in sfmmu.
1865 	 * Here is one of the times when we take the big hit and traverse
1866 	 * the hash looking for hme_blks to free up.  Not only do we free up
1867 	 * this as hme_blks but all those that are free.  We are obviously
1868 	 * swapping because we need memory so let's free up as much
1869 	 * as we can.
1870 	 *
1871 	 * Note that we don't flush TLB/TSB here -- it's not necessary
1872 	 * because:
1873 	 *  1) we free the ctx we're using and throw away the TSB(s);
1874 	 *  2) processes aren't runnable while being swapped out.
1875 	 */
1876 	ASSERT(sfmmup != KHATID);
1877 	for (i = 0; i <= UHMEHASH_SZ; i++) {
1878 		hmebp = &uhme_hash[i];
1879 		SFMMU_HASH_LOCK(hmebp);
1880 		hmeblkp = hmebp->hmeblkp;
1881 		hblkpa = hmebp->hmeh_nextpa;
1882 		prevpa = 0;
1883 		pr_hblk = NULL;
1884 		while (hmeblkp) {
1885 
1886 			ASSERT(!hmeblkp->hblk_xhat_bit);
1887 
1888 			if ((hmeblkp->hblk_tag.htag_id == sfmmup) &&
1889 			    !hmeblkp->hblk_shw_bit && !hmeblkp->hblk_lckcnt) {
1890 				ASSERT(!hmeblkp->hblk_shared);
1891 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
1892 				    (caddr_t)get_hblk_base(hmeblkp),
1893 				    get_hblk_endaddr(hmeblkp),
1894 				    NULL, HAT_UNLOAD);
1895 			}
1896 			nx_hblk = hmeblkp->hblk_next;
1897 			nx_pa = hmeblkp->hblk_nextpa;
1898 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
1899 				ASSERT(!hmeblkp->hblk_lckcnt);
1900 				sfmmu_hblk_hash_rm(hmebp, hmeblkp,
1901 				    prevpa, pr_hblk);
1902 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
1903 			} else {
1904 				pr_hblk = hmeblkp;
1905 				prevpa = hblkpa;
1906 			}
1907 			hmeblkp = nx_hblk;
1908 			hblkpa = nx_pa;
1909 		}
1910 		SFMMU_HASH_UNLOCK(hmebp);
1911 	}
1912 
1913 	sfmmu_hblks_list_purge(&list);
1914 
1915 	/*
1916 	 * Now free up the ctx so that others can reuse it.
1917 	 */
1918 	hatlockp = sfmmu_hat_enter(sfmmup);
1919 
1920 	sfmmu_invalidate_ctx(sfmmup);
1921 
1922 	/*
1923 	 * Free TSBs, but not tsbinfos, and set SWAPPED flag.
1924 	 * If TSBs were never swapped in, just return.
1925 	 * This implies that we don't support partial swapping
1926 	 * of TSBs -- either all are swapped out, or none are.
1927 	 *
1928 	 * We must hold the HAT lock here to prevent racing with another
1929 	 * thread trying to unmap TTEs from the TSB or running the post-
1930 	 * relocator after relocating the TSB's memory.  Unfortunately, we
1931 	 * can't free memory while holding the HAT lock or we could
1932 	 * deadlock, so we build a list of TSBs to be freed after marking
1933 	 * the tsbinfos as swapped out and free them after dropping the
1934 	 * lock.
1935 	 */
1936 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
1937 		sfmmu_hat_exit(hatlockp);
1938 		return;
1939 	}
1940 
1941 	SFMMU_FLAGS_SET(sfmmup, HAT_SWAPPED);
1942 	last = freelist = NULL;
1943 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
1944 	    tsbinfop = tsbinfop->tsb_next) {
1945 		ASSERT((tsbinfop->tsb_flags & TSB_SWAPPED) == 0);
1946 
1947 		/*
1948 		 * Cast the TSB into a struct free_tsb and put it on the free
1949 		 * list.
1950 		 */
1951 		if (freelist == NULL) {
1952 			last = freelist = (struct free_tsb *)tsbinfop->tsb_va;
1953 		} else {
1954 			last->next = (struct free_tsb *)tsbinfop->tsb_va;
1955 			last = last->next;
1956 		}
1957 		last->next = NULL;
1958 		last->tsbinfop = tsbinfop;
1959 		tsbinfop->tsb_flags |= TSB_SWAPPED;
1960 		/*
1961 		 * Zero out the TTE to clear the valid bit.
1962 		 * Note we can't use a value like 0xbad because we want to
1963 		 * ensure diagnostic bits are NEVER set on TTEs that might
1964 		 * be loaded.  The intent is to catch any invalid access
1965 		 * to the swapped TSB, such as a thread running with a valid
1966 		 * context without first calling sfmmu_tsb_swapin() to
1967 		 * allocate TSB memory.
1968 		 */
1969 		tsbinfop->tsb_tte.ll = 0;
1970 	}
1971 
1972 	/* Now we can drop the lock and free the TSB memory. */
1973 	sfmmu_hat_exit(hatlockp);
1974 	for (; freelist != NULL; freelist = next) {
1975 		next = freelist->next;
1976 		sfmmu_tsb_free(freelist->tsbinfop);
1977 	}
1978 }
1979 
1980 /*
1981  * Duplicate the translations of an as into another newas
1982  */
1983 /* ARGSUSED */
1984 int
1985 hat_dup(struct hat *hat, struct hat *newhat, caddr_t addr, size_t len,
1986 	uint_t flag)
1987 {
1988 	sf_srd_t *srdp;
1989 	sf_scd_t *scdp;
1990 	int i;
1991 	extern uint_t get_color_start(struct as *);
1992 
1993 	ASSERT(hat->sfmmu_xhat_provider == NULL);
1994 	ASSERT((flag == 0) || (flag == HAT_DUP_ALL) || (flag == HAT_DUP_COW) ||
1995 	    (flag == HAT_DUP_SRD));
1996 	ASSERT(hat != ksfmmup);
1997 	ASSERT(newhat != ksfmmup);
1998 	ASSERT(flag != HAT_DUP_ALL || hat->sfmmu_srdp == newhat->sfmmu_srdp);
1999 
2000 	if (flag == HAT_DUP_COW) {
2001 		panic("hat_dup: HAT_DUP_COW not supported");
2002 	}
2003 
2004 	if (flag == HAT_DUP_SRD && ((srdp = hat->sfmmu_srdp) != NULL)) {
2005 		ASSERT(srdp->srd_evp != NULL);
2006 		VN_HOLD(srdp->srd_evp);
2007 		ASSERT(srdp->srd_refcnt > 0);
2008 		newhat->sfmmu_srdp = srdp;
2009 		atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
2010 	}
2011 
2012 	/*
2013 	 * HAT_DUP_ALL flag is used after as duplication is done.
2014 	 */
2015 	if (flag == HAT_DUP_ALL && ((srdp = newhat->sfmmu_srdp) != NULL)) {
2016 		ASSERT(newhat->sfmmu_srdp->srd_refcnt >= 2);
2017 		newhat->sfmmu_rtteflags = hat->sfmmu_rtteflags;
2018 		if (hat->sfmmu_flags & HAT_4MTEXT_FLAG) {
2019 			newhat->sfmmu_flags |= HAT_4MTEXT_FLAG;
2020 		}
2021 
2022 		/* check if need to join scd */
2023 		if ((scdp = hat->sfmmu_scdp) != NULL &&
2024 		    newhat->sfmmu_scdp != scdp) {
2025 			int ret;
2026 			SF_RGNMAP_IS_SUBSET(&newhat->sfmmu_region_map,
2027 			    &scdp->scd_region_map, ret);
2028 			ASSERT(ret);
2029 			sfmmu_join_scd(scdp, newhat);
2030 			ASSERT(newhat->sfmmu_scdp == scdp &&
2031 			    scdp->scd_refcnt >= 2);
2032 			for (i = 0; i < max_mmu_page_sizes; i++) {
2033 				newhat->sfmmu_ismttecnt[i] =
2034 				    hat->sfmmu_ismttecnt[i];
2035 				newhat->sfmmu_scdismttecnt[i] =
2036 				    hat->sfmmu_scdismttecnt[i];
2037 			}
2038 		}
2039 
2040 		sfmmu_check_page_sizes(newhat, 1);
2041 	}
2042 
2043 	if (flag == HAT_DUP_ALL && consistent_coloring == 0 &&
2044 	    update_proc_pgcolorbase_after_fork != 0) {
2045 		hat->sfmmu_clrbin = get_color_start(hat->sfmmu_as);
2046 	}
2047 	return (0);
2048 }
2049 
2050 void
2051 hat_memload(struct hat *hat, caddr_t addr, struct page *pp,
2052 	uint_t attr, uint_t flags)
2053 {
2054 	hat_do_memload(hat, addr, pp, attr, flags,
2055 	    SFMMU_INVALID_SHMERID);
2056 }
2057 
2058 void
2059 hat_memload_region(struct hat *hat, caddr_t addr, struct page *pp,
2060 	uint_t attr, uint_t flags, hat_region_cookie_t rcookie)
2061 {
2062 	uint_t rid;
2063 	if (rcookie == HAT_INVALID_REGION_COOKIE ||
2064 	    hat->sfmmu_xhat_provider != NULL) {
2065 		hat_do_memload(hat, addr, pp, attr, flags,
2066 		    SFMMU_INVALID_SHMERID);
2067 		return;
2068 	}
2069 	rid = (uint_t)((uint64_t)rcookie);
2070 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2071 	hat_do_memload(hat, addr, pp, attr, flags, rid);
2072 }
2073 
2074 /*
2075  * Set up addr to map to page pp with protection prot.
2076  * As an optimization we also load the TSB with the
2077  * corresponding tte but it is no big deal if  the tte gets kicked out.
2078  */
2079 static void
2080 hat_do_memload(struct hat *hat, caddr_t addr, struct page *pp,
2081 	uint_t attr, uint_t flags, uint_t rid)
2082 {
2083 	tte_t tte;
2084 
2085 
2086 	ASSERT(hat != NULL);
2087 	ASSERT(PAGE_LOCKED(pp));
2088 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2089 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2090 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2091 	SFMMU_VALIDATE_HMERID(hat, rid, addr, MMU_PAGESIZE);
2092 
2093 	if (PP_ISFREE(pp)) {
2094 		panic("hat_memload: loading a mapping to free page %p",
2095 		    (void *)pp);
2096 	}
2097 
2098 	if (hat->sfmmu_xhat_provider) {
2099 		/* no regions for xhats */
2100 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
2101 		XHAT_MEMLOAD(hat, addr, pp, attr, flags);
2102 		return;
2103 	}
2104 
2105 	ASSERT((hat == ksfmmup) ||
2106 	    AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
2107 
2108 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2109 		cmn_err(CE_NOTE, "hat_memload: unsupported flags %d",
2110 		    flags & ~SFMMU_LOAD_ALLFLAG);
2111 
2112 	if (hat->sfmmu_rmstat)
2113 		hat_resvstat(MMU_PAGESIZE, hat->sfmmu_as, addr);
2114 
2115 #if defined(SF_ERRATA_57)
2116 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2117 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2118 	    !(flags & HAT_LOAD_SHARE)) {
2119 		cmn_err(CE_WARN, "hat_memload: illegal attempt to make user "
2120 		    " page executable");
2121 		attr &= ~PROT_EXEC;
2122 	}
2123 #endif
2124 
2125 	sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2126 	(void) sfmmu_tteload_array(hat, &tte, addr, &pp, flags, rid);
2127 
2128 	/*
2129 	 * Check TSB and TLB page sizes.
2130 	 */
2131 	if ((flags & HAT_LOAD_SHARE) == 0) {
2132 		sfmmu_check_page_sizes(hat, 1);
2133 	}
2134 }
2135 
2136 /*
2137  * hat_devload can be called to map real memory (e.g.
2138  * /dev/kmem) and even though hat_devload will determine pf is
2139  * for memory, it will be unable to get a shared lock on the
2140  * page (because someone else has it exclusively) and will
2141  * pass dp = NULL.  If tteload doesn't get a non-NULL
2142  * page pointer it can't cache memory.
2143  */
2144 void
2145 hat_devload(struct hat *hat, caddr_t addr, size_t len, pfn_t pfn,
2146 	uint_t attr, int flags)
2147 {
2148 	tte_t tte;
2149 	struct page *pp = NULL;
2150 	int use_lgpg = 0;
2151 
2152 	ASSERT(hat != NULL);
2153 
2154 	if (hat->sfmmu_xhat_provider) {
2155 		XHAT_DEVLOAD(hat, addr, len, pfn, attr, flags);
2156 		return;
2157 	}
2158 
2159 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2160 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2161 	ASSERT((hat == ksfmmup) ||
2162 	    AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
2163 	if (len == 0)
2164 		panic("hat_devload: zero len");
2165 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2166 		cmn_err(CE_NOTE, "hat_devload: unsupported flags %d",
2167 		    flags & ~SFMMU_LOAD_ALLFLAG);
2168 
2169 #if defined(SF_ERRATA_57)
2170 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2171 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2172 	    !(flags & HAT_LOAD_SHARE)) {
2173 		cmn_err(CE_WARN, "hat_devload: illegal attempt to make user "
2174 		    " page executable");
2175 		attr &= ~PROT_EXEC;
2176 	}
2177 #endif
2178 
2179 	/*
2180 	 * If it's a memory page find its pp
2181 	 */
2182 	if (!(flags & HAT_LOAD_NOCONSIST) && pf_is_memory(pfn)) {
2183 		pp = page_numtopp_nolock(pfn);
2184 		if (pp == NULL) {
2185 			flags |= HAT_LOAD_NOCONSIST;
2186 		} else {
2187 			if (PP_ISFREE(pp)) {
2188 				panic("hat_memload: loading "
2189 				    "a mapping to free page %p",
2190 				    (void *)pp);
2191 			}
2192 			if (!PAGE_LOCKED(pp) && !PP_ISNORELOC(pp)) {
2193 				panic("hat_memload: loading a mapping "
2194 				    "to unlocked relocatable page %p",
2195 				    (void *)pp);
2196 			}
2197 			ASSERT(len == MMU_PAGESIZE);
2198 		}
2199 	}
2200 
2201 	if (hat->sfmmu_rmstat)
2202 		hat_resvstat(len, hat->sfmmu_as, addr);
2203 
2204 	if (flags & HAT_LOAD_NOCONSIST) {
2205 		attr |= SFMMU_UNCACHEVTTE;
2206 		use_lgpg = 1;
2207 	}
2208 	if (!pf_is_memory(pfn)) {
2209 		attr |= SFMMU_UNCACHEPTTE | HAT_NOSYNC;
2210 		use_lgpg = 1;
2211 		switch (attr & HAT_ORDER_MASK) {
2212 			case HAT_STRICTORDER:
2213 			case HAT_UNORDERED_OK:
2214 				/*
2215 				 * we set the side effect bit for all non
2216 				 * memory mappings unless merging is ok
2217 				 */
2218 				attr |= SFMMU_SIDEFFECT;
2219 				break;
2220 			case HAT_MERGING_OK:
2221 			case HAT_LOADCACHING_OK:
2222 			case HAT_STORECACHING_OK:
2223 				break;
2224 			default:
2225 				panic("hat_devload: bad attr");
2226 				break;
2227 		}
2228 	}
2229 	while (len) {
2230 		if (!use_lgpg) {
2231 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2232 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2233 			    flags, SFMMU_INVALID_SHMERID);
2234 			len -= MMU_PAGESIZE;
2235 			addr += MMU_PAGESIZE;
2236 			pfn++;
2237 			continue;
2238 		}
2239 		/*
2240 		 *  try to use large pages, check va/pa alignments
2241 		 *  Note that 32M/256M page sizes are not (yet) supported.
2242 		 */
2243 		if ((len >= MMU_PAGESIZE4M) &&
2244 		    !((uintptr_t)addr & MMU_PAGEOFFSET4M) &&
2245 		    !(disable_large_pages & (1 << TTE4M)) &&
2246 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET4M)) {
2247 			sfmmu_memtte(&tte, pfn, attr, TTE4M);
2248 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2249 			    flags, SFMMU_INVALID_SHMERID);
2250 			len -= MMU_PAGESIZE4M;
2251 			addr += MMU_PAGESIZE4M;
2252 			pfn += MMU_PAGESIZE4M / MMU_PAGESIZE;
2253 		} else if ((len >= MMU_PAGESIZE512K) &&
2254 		    !((uintptr_t)addr & MMU_PAGEOFFSET512K) &&
2255 		    !(disable_large_pages & (1 << TTE512K)) &&
2256 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET512K)) {
2257 			sfmmu_memtte(&tte, pfn, attr, TTE512K);
2258 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2259 			    flags, SFMMU_INVALID_SHMERID);
2260 			len -= MMU_PAGESIZE512K;
2261 			addr += MMU_PAGESIZE512K;
2262 			pfn += MMU_PAGESIZE512K / MMU_PAGESIZE;
2263 		} else if ((len >= MMU_PAGESIZE64K) &&
2264 		    !((uintptr_t)addr & MMU_PAGEOFFSET64K) &&
2265 		    !(disable_large_pages & (1 << TTE64K)) &&
2266 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET64K)) {
2267 			sfmmu_memtte(&tte, pfn, attr, TTE64K);
2268 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2269 			    flags, SFMMU_INVALID_SHMERID);
2270 			len -= MMU_PAGESIZE64K;
2271 			addr += MMU_PAGESIZE64K;
2272 			pfn += MMU_PAGESIZE64K / MMU_PAGESIZE;
2273 		} else {
2274 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2275 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2276 			    flags, SFMMU_INVALID_SHMERID);
2277 			len -= MMU_PAGESIZE;
2278 			addr += MMU_PAGESIZE;
2279 			pfn++;
2280 		}
2281 	}
2282 
2283 	/*
2284 	 * Check TSB and TLB page sizes.
2285 	 */
2286 	if ((flags & HAT_LOAD_SHARE) == 0) {
2287 		sfmmu_check_page_sizes(hat, 1);
2288 	}
2289 }
2290 
2291 void
2292 hat_memload_array(struct hat *hat, caddr_t addr, size_t len,
2293 	struct page **pps, uint_t attr, uint_t flags)
2294 {
2295 	hat_do_memload_array(hat, addr, len, pps, attr, flags,
2296 	    SFMMU_INVALID_SHMERID);
2297 }
2298 
2299 void
2300 hat_memload_array_region(struct hat *hat, caddr_t addr, size_t len,
2301 	struct page **pps, uint_t attr, uint_t flags,
2302 	hat_region_cookie_t rcookie)
2303 {
2304 	uint_t rid;
2305 	if (rcookie == HAT_INVALID_REGION_COOKIE ||
2306 	    hat->sfmmu_xhat_provider != NULL) {
2307 		hat_do_memload_array(hat, addr, len, pps, attr, flags,
2308 		    SFMMU_INVALID_SHMERID);
2309 		return;
2310 	}
2311 	rid = (uint_t)((uint64_t)rcookie);
2312 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2313 	hat_do_memload_array(hat, addr, len, pps, attr, flags, rid);
2314 }
2315 
2316 /*
2317  * Map the largest extend possible out of the page array. The array may NOT
2318  * be in order.  The largest possible mapping a page can have
2319  * is specified in the p_szc field.  The p_szc field
2320  * cannot change as long as there any mappings (large or small)
2321  * to any of the pages that make up the large page. (ie. any
2322  * promotion/demotion of page size is not up to the hat but up to
2323  * the page free list manager).  The array
2324  * should consist of properly aligned contigous pages that are
2325  * part of a big page for a large mapping to be created.
2326  */
2327 static void
2328 hat_do_memload_array(struct hat *hat, caddr_t addr, size_t len,
2329 	struct page **pps, uint_t attr, uint_t flags, uint_t rid)
2330 {
2331 	int  ttesz;
2332 	size_t mapsz;
2333 	pgcnt_t	numpg, npgs;
2334 	tte_t tte;
2335 	page_t *pp;
2336 	uint_t large_pages_disable;
2337 
2338 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2339 	SFMMU_VALIDATE_HMERID(hat, rid, addr, len);
2340 
2341 	if (hat->sfmmu_xhat_provider) {
2342 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
2343 		XHAT_MEMLOAD_ARRAY(hat, addr, len, pps, attr, flags);
2344 		return;
2345 	}
2346 
2347 	if (hat->sfmmu_rmstat)
2348 		hat_resvstat(len, hat->sfmmu_as, addr);
2349 
2350 #if defined(SF_ERRATA_57)
2351 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2352 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2353 	    !(flags & HAT_LOAD_SHARE)) {
2354 		cmn_err(CE_WARN, "hat_memload_array: illegal attempt to make "
2355 		    "user page executable");
2356 		attr &= ~PROT_EXEC;
2357 	}
2358 #endif
2359 
2360 	/* Get number of pages */
2361 	npgs = len >> MMU_PAGESHIFT;
2362 
2363 	if (flags & HAT_LOAD_SHARE) {
2364 		large_pages_disable = disable_ism_large_pages;
2365 	} else {
2366 		large_pages_disable = disable_large_pages;
2367 	}
2368 
2369 	if (npgs < NHMENTS || large_pages_disable == LARGE_PAGES_OFF) {
2370 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2371 		    rid);
2372 		return;
2373 	}
2374 
2375 	while (npgs >= NHMENTS) {
2376 		pp = *pps;
2377 		for (ttesz = pp->p_szc; ttesz != TTE8K; ttesz--) {
2378 			/*
2379 			 * Check if this page size is disabled.
2380 			 */
2381 			if (large_pages_disable & (1 << ttesz))
2382 				continue;
2383 
2384 			numpg = TTEPAGES(ttesz);
2385 			mapsz = numpg << MMU_PAGESHIFT;
2386 			if ((npgs >= numpg) &&
2387 			    IS_P2ALIGNED(addr, mapsz) &&
2388 			    IS_P2ALIGNED(pp->p_pagenum, numpg)) {
2389 				/*
2390 				 * At this point we have enough pages and
2391 				 * we know the virtual address and the pfn
2392 				 * are properly aligned.  We still need
2393 				 * to check for physical contiguity but since
2394 				 * it is very likely that this is the case
2395 				 * we will assume they are so and undo
2396 				 * the request if necessary.  It would
2397 				 * be great if we could get a hint flag
2398 				 * like HAT_CONTIG which would tell us
2399 				 * the pages are contigous for sure.
2400 				 */
2401 				sfmmu_memtte(&tte, (*pps)->p_pagenum,
2402 				    attr, ttesz);
2403 				if (!sfmmu_tteload_array(hat, &tte, addr,
2404 				    pps, flags, rid)) {
2405 					break;
2406 				}
2407 			}
2408 		}
2409 		if (ttesz == TTE8K) {
2410 			/*
2411 			 * We were not able to map array using a large page
2412 			 * batch a hmeblk or fraction at a time.
2413 			 */
2414 			numpg = ((uintptr_t)addr >> MMU_PAGESHIFT)
2415 			    & (NHMENTS-1);
2416 			numpg = NHMENTS - numpg;
2417 			ASSERT(numpg <= npgs);
2418 			mapsz = numpg * MMU_PAGESIZE;
2419 			sfmmu_memload_batchsmall(hat, addr, pps, attr, flags,
2420 			    numpg, rid);
2421 		}
2422 		addr += mapsz;
2423 		npgs -= numpg;
2424 		pps += numpg;
2425 	}
2426 
2427 	if (npgs) {
2428 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2429 		    rid);
2430 	}
2431 
2432 	/*
2433 	 * Check TSB and TLB page sizes.
2434 	 */
2435 	if ((flags & HAT_LOAD_SHARE) == 0) {
2436 		sfmmu_check_page_sizes(hat, 1);
2437 	}
2438 }
2439 
2440 /*
2441  * Function tries to batch 8K pages into the same hme blk.
2442  */
2443 static void
2444 sfmmu_memload_batchsmall(struct hat *hat, caddr_t vaddr, page_t **pps,
2445 		    uint_t attr, uint_t flags, pgcnt_t npgs, uint_t rid)
2446 {
2447 	tte_t	tte;
2448 	page_t *pp;
2449 	struct hmehash_bucket *hmebp;
2450 	struct hme_blk *hmeblkp;
2451 	int	index;
2452 
2453 	while (npgs) {
2454 		/*
2455 		 * Acquire the hash bucket.
2456 		 */
2457 		hmebp = sfmmu_tteload_acquire_hashbucket(hat, vaddr, TTE8K,
2458 		    rid);
2459 		ASSERT(hmebp);
2460 
2461 		/*
2462 		 * Find the hment block.
2463 		 */
2464 		hmeblkp = sfmmu_tteload_find_hmeblk(hat, hmebp, vaddr,
2465 		    TTE8K, flags, rid);
2466 		ASSERT(hmeblkp);
2467 
2468 		do {
2469 			/*
2470 			 * Make the tte.
2471 			 */
2472 			pp = *pps;
2473 			sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2474 
2475 			/*
2476 			 * Add the translation.
2477 			 */
2478 			(void) sfmmu_tteload_addentry(hat, hmeblkp, &tte,
2479 			    vaddr, pps, flags, rid);
2480 
2481 			/*
2482 			 * Goto next page.
2483 			 */
2484 			pps++;
2485 			npgs--;
2486 
2487 			/*
2488 			 * Goto next address.
2489 			 */
2490 			vaddr += MMU_PAGESIZE;
2491 
2492 			/*
2493 			 * Don't crossover into a different hmentblk.
2494 			 */
2495 			index = (int)(((uintptr_t)vaddr >> MMU_PAGESHIFT) &
2496 			    (NHMENTS-1));
2497 
2498 		} while (index != 0 && npgs != 0);
2499 
2500 		/*
2501 		 * Release the hash bucket.
2502 		 */
2503 
2504 		sfmmu_tteload_release_hashbucket(hmebp);
2505 	}
2506 }
2507 
2508 /*
2509  * Construct a tte for a page:
2510  *
2511  * tte_valid = 1
2512  * tte_size2 = size & TTE_SZ2_BITS (Panther and Olympus-C only)
2513  * tte_size = size
2514  * tte_nfo = attr & HAT_NOFAULT
2515  * tte_ie = attr & HAT_STRUCTURE_LE
2516  * tte_hmenum = hmenum
2517  * tte_pahi = pp->p_pagenum >> TTE_PASHIFT;
2518  * tte_palo = pp->p_pagenum & TTE_PALOMASK;
2519  * tte_ref = 1 (optimization)
2520  * tte_wr_perm = attr & PROT_WRITE;
2521  * tte_no_sync = attr & HAT_NOSYNC
2522  * tte_lock = attr & SFMMU_LOCKTTE
2523  * tte_cp = !(attr & SFMMU_UNCACHEPTTE)
2524  * tte_cv = !(attr & SFMMU_UNCACHEVTTE)
2525  * tte_e = attr & SFMMU_SIDEFFECT
2526  * tte_priv = !(attr & PROT_USER)
2527  * tte_hwwr = if nosync is set and it is writable we set the mod bit (opt)
2528  * tte_glb = 0
2529  */
2530 void
2531 sfmmu_memtte(tte_t *ttep, pfn_t pfn, uint_t attr, int tte_sz)
2532 {
2533 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2534 
2535 	ttep->tte_inthi = MAKE_TTE_INTHI(pfn, attr, tte_sz, 0 /* hmenum */);
2536 	ttep->tte_intlo = MAKE_TTE_INTLO(pfn, attr, tte_sz, 0 /* hmenum */);
2537 
2538 	if (TTE_IS_NOSYNC(ttep)) {
2539 		TTE_SET_REF(ttep);
2540 		if (TTE_IS_WRITABLE(ttep)) {
2541 			TTE_SET_MOD(ttep);
2542 		}
2543 	}
2544 	if (TTE_IS_NFO(ttep) && TTE_IS_EXECUTABLE(ttep)) {
2545 		panic("sfmmu_memtte: can't set both NFO and EXEC bits");
2546 	}
2547 }
2548 
2549 /*
2550  * This function will add a translation to the hme_blk and allocate the
2551  * hme_blk if one does not exist.
2552  * If a page structure is specified then it will add the
2553  * corresponding hment to the mapping list.
2554  * It will also update the hmenum field for the tte.
2555  *
2556  * Currently this function is only used for kernel mappings.
2557  * So pass invalid region to sfmmu_tteload_array().
2558  */
2559 void
2560 sfmmu_tteload(struct hat *sfmmup, tte_t *ttep, caddr_t vaddr, page_t *pp,
2561 	uint_t flags)
2562 {
2563 	ASSERT(sfmmup == ksfmmup);
2564 	(void) sfmmu_tteload_array(sfmmup, ttep, vaddr, &pp, flags,
2565 	    SFMMU_INVALID_SHMERID);
2566 }
2567 
2568 /*
2569  * Load (ttep != NULL) or unload (ttep == NULL) one entry in the TSB.
2570  * Assumes that a particular page size may only be resident in one TSB.
2571  */
2572 static void
2573 sfmmu_mod_tsb(sfmmu_t *sfmmup, caddr_t vaddr, tte_t *ttep, int ttesz)
2574 {
2575 	struct tsb_info *tsbinfop = NULL;
2576 	uint64_t tag;
2577 	struct tsbe *tsbe_addr;
2578 	uint64_t tsb_base;
2579 	uint_t tsb_size;
2580 	int vpshift = MMU_PAGESHIFT;
2581 	int phys = 0;
2582 
2583 	if (sfmmup == ksfmmup) { /* No support for 32/256M ksfmmu pages */
2584 		phys = ktsb_phys;
2585 		if (ttesz >= TTE4M) {
2586 #ifndef sun4v
2587 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2588 #endif
2589 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2590 			tsb_size = ktsb4m_szcode;
2591 		} else {
2592 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2593 			tsb_size = ktsb_szcode;
2594 		}
2595 	} else {
2596 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2597 
2598 		/*
2599 		 * If there isn't a TSB for this page size, or the TSB is
2600 		 * swapped out, there is nothing to do.  Note that the latter
2601 		 * case seems impossible but can occur if hat_pageunload()
2602 		 * is called on an ISM mapping while the process is swapped
2603 		 * out.
2604 		 */
2605 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2606 			return;
2607 
2608 		/*
2609 		 * If another thread is in the middle of relocating a TSB
2610 		 * we can't unload the entry so set a flag so that the
2611 		 * TSB will be flushed before it can be accessed by the
2612 		 * process.
2613 		 */
2614 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2615 			if (ttep == NULL)
2616 				tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2617 			return;
2618 		}
2619 #if defined(UTSB_PHYS)
2620 		phys = 1;
2621 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2622 #else
2623 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2624 #endif
2625 		tsb_size = tsbinfop->tsb_szc;
2626 	}
2627 	if (ttesz >= TTE4M)
2628 		vpshift = MMU_PAGESHIFT4M;
2629 
2630 	tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2631 	tag = sfmmu_make_tsbtag(vaddr);
2632 
2633 	if (ttep == NULL) {
2634 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2635 	} else {
2636 		if (ttesz >= TTE4M) {
2637 			SFMMU_STAT(sf_tsb_load4m);
2638 		} else {
2639 			SFMMU_STAT(sf_tsb_load8k);
2640 		}
2641 
2642 		sfmmu_load_tsbe(tsbe_addr, tag, ttep, phys);
2643 	}
2644 }
2645 
2646 /*
2647  * Unmap all entries from [start, end) matching the given page size.
2648  *
2649  * This function is used primarily to unmap replicated 64K or 512K entries
2650  * from the TSB that are inserted using the base page size TSB pointer, but
2651  * it may also be called to unmap a range of addresses from the TSB.
2652  */
2653 void
2654 sfmmu_unload_tsb_range(sfmmu_t *sfmmup, caddr_t start, caddr_t end, int ttesz)
2655 {
2656 	struct tsb_info *tsbinfop;
2657 	uint64_t tag;
2658 	struct tsbe *tsbe_addr;
2659 	caddr_t vaddr;
2660 	uint64_t tsb_base;
2661 	int vpshift, vpgsz;
2662 	uint_t tsb_size;
2663 	int phys = 0;
2664 
2665 	/*
2666 	 * Assumptions:
2667 	 *  If ttesz == 8K, 64K or 512K, we walk through the range 8K
2668 	 *  at a time shooting down any valid entries we encounter.
2669 	 *
2670 	 *  If ttesz >= 4M we walk the range 4M at a time shooting
2671 	 *  down any valid mappings we find.
2672 	 */
2673 	if (sfmmup == ksfmmup) {
2674 		phys = ktsb_phys;
2675 		if (ttesz >= TTE4M) {
2676 #ifndef sun4v
2677 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2678 #endif
2679 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2680 			tsb_size = ktsb4m_szcode;
2681 		} else {
2682 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2683 			tsb_size = ktsb_szcode;
2684 		}
2685 	} else {
2686 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2687 
2688 		/*
2689 		 * If there isn't a TSB for this page size, or the TSB is
2690 		 * swapped out, there is nothing to do.  Note that the latter
2691 		 * case seems impossible but can occur if hat_pageunload()
2692 		 * is called on an ISM mapping while the process is swapped
2693 		 * out.
2694 		 */
2695 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2696 			return;
2697 
2698 		/*
2699 		 * If another thread is in the middle of relocating a TSB
2700 		 * we can't unload the entry so set a flag so that the
2701 		 * TSB will be flushed before it can be accessed by the
2702 		 * process.
2703 		 */
2704 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2705 			tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2706 			return;
2707 		}
2708 #if defined(UTSB_PHYS)
2709 		phys = 1;
2710 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2711 #else
2712 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2713 #endif
2714 		tsb_size = tsbinfop->tsb_szc;
2715 	}
2716 	if (ttesz >= TTE4M) {
2717 		vpshift = MMU_PAGESHIFT4M;
2718 		vpgsz = MMU_PAGESIZE4M;
2719 	} else {
2720 		vpshift = MMU_PAGESHIFT;
2721 		vpgsz = MMU_PAGESIZE;
2722 	}
2723 
2724 	for (vaddr = start; vaddr < end; vaddr += vpgsz) {
2725 		tag = sfmmu_make_tsbtag(vaddr);
2726 		tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2727 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2728 	}
2729 }
2730 
2731 /*
2732  * Select the optimum TSB size given the number of mappings
2733  * that need to be cached.
2734  */
2735 static int
2736 sfmmu_select_tsb_szc(pgcnt_t pgcnt)
2737 {
2738 	int szc = 0;
2739 
2740 #ifdef DEBUG
2741 	if (tsb_grow_stress) {
2742 		uint32_t randval = (uint32_t)gettick() >> 4;
2743 		return (randval % (tsb_max_growsize + 1));
2744 	}
2745 #endif	/* DEBUG */
2746 
2747 	while ((szc < tsb_max_growsize) && (pgcnt > SFMMU_RSS_TSBSIZE(szc)))
2748 		szc++;
2749 	return (szc);
2750 }
2751 
2752 /*
2753  * This function will add a translation to the hme_blk and allocate the
2754  * hme_blk if one does not exist.
2755  * If a page structure is specified then it will add the
2756  * corresponding hment to the mapping list.
2757  * It will also update the hmenum field for the tte.
2758  * Furthermore, it attempts to create a large page translation
2759  * for <addr,hat> at page array pps.  It assumes addr and first
2760  * pp is correctly aligned.  It returns 0 if successful and 1 otherwise.
2761  */
2762 static int
2763 sfmmu_tteload_array(sfmmu_t *sfmmup, tte_t *ttep, caddr_t vaddr,
2764 	page_t **pps, uint_t flags, uint_t rid)
2765 {
2766 	struct hmehash_bucket *hmebp;
2767 	struct hme_blk *hmeblkp;
2768 	int 	ret;
2769 	uint_t	size;
2770 
2771 	/*
2772 	 * Get mapping size.
2773 	 */
2774 	size = TTE_CSZ(ttep);
2775 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
2776 
2777 	/*
2778 	 * Acquire the hash bucket.
2779 	 */
2780 	hmebp = sfmmu_tteload_acquire_hashbucket(sfmmup, vaddr, size, rid);
2781 	ASSERT(hmebp);
2782 
2783 	/*
2784 	 * Find the hment block.
2785 	 */
2786 	hmeblkp = sfmmu_tteload_find_hmeblk(sfmmup, hmebp, vaddr, size, flags,
2787 	    rid);
2788 	ASSERT(hmeblkp);
2789 
2790 	/*
2791 	 * Add the translation.
2792 	 */
2793 	ret = sfmmu_tteload_addentry(sfmmup, hmeblkp, ttep, vaddr, pps, flags,
2794 	    rid);
2795 
2796 	/*
2797 	 * Release the hash bucket.
2798 	 */
2799 	sfmmu_tteload_release_hashbucket(hmebp);
2800 
2801 	return (ret);
2802 }
2803 
2804 /*
2805  * Function locks and returns a pointer to the hash bucket for vaddr and size.
2806  */
2807 static struct hmehash_bucket *
2808 sfmmu_tteload_acquire_hashbucket(sfmmu_t *sfmmup, caddr_t vaddr, int size,
2809     uint_t rid)
2810 {
2811 	struct hmehash_bucket *hmebp;
2812 	int hmeshift;
2813 	void *htagid = sfmmutohtagid(sfmmup, rid);
2814 
2815 	ASSERT(htagid != NULL);
2816 
2817 	hmeshift = HME_HASH_SHIFT(size);
2818 
2819 	hmebp = HME_HASH_FUNCTION(htagid, vaddr, hmeshift);
2820 
2821 	SFMMU_HASH_LOCK(hmebp);
2822 
2823 	return (hmebp);
2824 }
2825 
2826 /*
2827  * Function returns a pointer to an hmeblk in the hash bucket, hmebp. If the
2828  * hmeblk doesn't exists for the [sfmmup, vaddr & size] signature, a hmeblk is
2829  * allocated.
2830  */
2831 static struct hme_blk *
2832 sfmmu_tteload_find_hmeblk(sfmmu_t *sfmmup, struct hmehash_bucket *hmebp,
2833 	caddr_t vaddr, uint_t size, uint_t flags, uint_t rid)
2834 {
2835 	hmeblk_tag hblktag;
2836 	int hmeshift;
2837 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
2838 	uint64_t hblkpa, prevpa;
2839 	struct kmem_cache *sfmmu_cache;
2840 	uint_t forcefree;
2841 
2842 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
2843 
2844 	hblktag.htag_id = sfmmutohtagid(sfmmup, rid);
2845 	ASSERT(hblktag.htag_id != NULL);
2846 	hmeshift = HME_HASH_SHIFT(size);
2847 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
2848 	hblktag.htag_rehash = HME_HASH_REHASH(size);
2849 	hblktag.htag_rid = rid;
2850 
2851 ttearray_realloc:
2852 
2853 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa,
2854 	    pr_hblk, prevpa, &list);
2855 
2856 	/*
2857 	 * We block until hblk_reserve_lock is released; it's held by
2858 	 * the thread, temporarily using hblk_reserve, until hblk_reserve is
2859 	 * replaced by a hblk from sfmmu8_cache.
2860 	 */
2861 	if (hmeblkp == (struct hme_blk *)hblk_reserve &&
2862 	    hblk_reserve_thread != curthread) {
2863 		SFMMU_HASH_UNLOCK(hmebp);
2864 		mutex_enter(&hblk_reserve_lock);
2865 		mutex_exit(&hblk_reserve_lock);
2866 		SFMMU_STAT(sf_hblk_reserve_hit);
2867 		SFMMU_HASH_LOCK(hmebp);
2868 		goto ttearray_realloc;
2869 	}
2870 
2871 	if (hmeblkp == NULL) {
2872 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
2873 		    hblktag, flags, rid);
2874 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
2875 		ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
2876 	} else {
2877 		/*
2878 		 * It is possible for 8k and 64k hblks to collide since they
2879 		 * have the same rehash value. This is because we
2880 		 * lazily free hblks and 8K/64K blks could be lingering.
2881 		 * If we find size mismatch we free the block and & try again.
2882 		 */
2883 		if (get_hblk_ttesz(hmeblkp) != size) {
2884 			ASSERT(!hmeblkp->hblk_vcnt);
2885 			ASSERT(!hmeblkp->hblk_hmecnt);
2886 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
2887 			sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
2888 			goto ttearray_realloc;
2889 		}
2890 		if (hmeblkp->hblk_shw_bit) {
2891 			/*
2892 			 * if the hblk was previously used as a shadow hblk then
2893 			 * we will change it to a normal hblk
2894 			 */
2895 			ASSERT(!hmeblkp->hblk_shared);
2896 			if (hmeblkp->hblk_shw_mask) {
2897 				sfmmu_shadow_hcleanup(sfmmup, hmeblkp, hmebp);
2898 				ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
2899 				goto ttearray_realloc;
2900 			} else {
2901 				hmeblkp->hblk_shw_bit = 0;
2902 			}
2903 		}
2904 		SFMMU_STAT(sf_hblk_hit);
2905 	}
2906 
2907 	/*
2908 	 * hat_memload() should never call kmem_cache_free(); see block
2909 	 * comment showing the stacktrace in sfmmu_hblk_alloc();
2910 	 * enqueue each hblk in the list to reserve list if it's created
2911 	 * from sfmmu8_cache *and* sfmmup == KHATID.
2912 	 */
2913 	forcefree = (sfmmup == KHATID) ? 1 : 0;
2914 	while ((pr_hblk = list) != NULL) {
2915 		list = pr_hblk->hblk_next;
2916 		sfmmu_cache = get_hblk_cache(pr_hblk);
2917 		if ((sfmmu_cache == sfmmu8_cache) &&
2918 		    sfmmu_put_free_hblk(pr_hblk, forcefree))
2919 			continue;
2920 
2921 		ASSERT(sfmmup != KHATID);
2922 		kmem_cache_free(sfmmu_cache, pr_hblk);
2923 	}
2924 
2925 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
2926 	ASSERT(!hmeblkp->hblk_shw_bit);
2927 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
2928 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
2929 	ASSERT(hmeblkp->hblk_tag.htag_rid == rid);
2930 
2931 	return (hmeblkp);
2932 }
2933 
2934 /*
2935  * Function adds a tte entry into the hmeblk. It returns 0 if successful and 1
2936  * otherwise.
2937  */
2938 static int
2939 sfmmu_tteload_addentry(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, tte_t *ttep,
2940 	caddr_t vaddr, page_t **pps, uint_t flags, uint_t rid)
2941 {
2942 	page_t *pp = *pps;
2943 	int hmenum, size, remap;
2944 	tte_t tteold, flush_tte;
2945 #ifdef DEBUG
2946 	tte_t orig_old;
2947 #endif /* DEBUG */
2948 	struct sf_hment *sfhme;
2949 	kmutex_t *pml, *pmtx;
2950 	hatlock_t *hatlockp;
2951 	int myflt;
2952 
2953 	/*
2954 	 * remove this panic when we decide to let user virtual address
2955 	 * space be >= USERLIMIT.
2956 	 */
2957 	if (!TTE_IS_PRIVILEGED(ttep) && vaddr >= (caddr_t)USERLIMIT)
2958 		panic("user addr %p in kernel space", (void *)vaddr);
2959 #if defined(TTE_IS_GLOBAL)
2960 	if (TTE_IS_GLOBAL(ttep))
2961 		panic("sfmmu_tteload: creating global tte");
2962 #endif
2963 
2964 #ifdef DEBUG
2965 	if (pf_is_memory(sfmmu_ttetopfn(ttep, vaddr)) &&
2966 	    !TTE_IS_PCACHEABLE(ttep) && !sfmmu_allow_nc_trans)
2967 		panic("sfmmu_tteload: non cacheable memory tte");
2968 #endif /* DEBUG */
2969 
2970 	/* don't simulate dirty bit for writeable ISM/DISM mappings */
2971 	if ((flags & HAT_LOAD_SHARE) && TTE_IS_WRITABLE(ttep)) {
2972 		TTE_SET_REF(ttep);
2973 		TTE_SET_MOD(ttep);
2974 	}
2975 
2976 	if ((flags & HAT_LOAD_SHARE) || !TTE_IS_REF(ttep) ||
2977 	    !TTE_IS_MOD(ttep)) {
2978 		/*
2979 		 * Don't load TSB for dummy as in ISM.  Also don't preload
2980 		 * the TSB if the TTE isn't writable since we're likely to
2981 		 * fault on it again -- preloading can be fairly expensive.
2982 		 */
2983 		flags |= SFMMU_NO_TSBLOAD;
2984 	}
2985 
2986 	size = TTE_CSZ(ttep);
2987 	switch (size) {
2988 	case TTE8K:
2989 		SFMMU_STAT(sf_tteload8k);
2990 		break;
2991 	case TTE64K:
2992 		SFMMU_STAT(sf_tteload64k);
2993 		break;
2994 	case TTE512K:
2995 		SFMMU_STAT(sf_tteload512k);
2996 		break;
2997 	case TTE4M:
2998 		SFMMU_STAT(sf_tteload4m);
2999 		break;
3000 	case (TTE32M):
3001 		SFMMU_STAT(sf_tteload32m);
3002 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3003 		break;
3004 	case (TTE256M):
3005 		SFMMU_STAT(sf_tteload256m);
3006 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3007 		break;
3008 	}
3009 
3010 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
3011 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
3012 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3013 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3014 
3015 	HBLKTOHME_IDX(sfhme, hmeblkp, vaddr, hmenum);
3016 
3017 	/*
3018 	 * Need to grab mlist lock here so that pageunload
3019 	 * will not change tte behind us.
3020 	 */
3021 	if (pp) {
3022 		pml = sfmmu_mlist_enter(pp);
3023 	}
3024 
3025 	sfmmu_copytte(&sfhme->hme_tte, &tteold);
3026 	/*
3027 	 * Look for corresponding hment and if valid verify
3028 	 * pfns are equal.
3029 	 */
3030 	remap = TTE_IS_VALID(&tteold);
3031 	if (remap) {
3032 		pfn_t	new_pfn, old_pfn;
3033 
3034 		old_pfn = TTE_TO_PFN(vaddr, &tteold);
3035 		new_pfn = TTE_TO_PFN(vaddr, ttep);
3036 
3037 		if (flags & HAT_LOAD_REMAP) {
3038 			/* make sure we are remapping same type of pages */
3039 			if (pf_is_memory(old_pfn) != pf_is_memory(new_pfn)) {
3040 				panic("sfmmu_tteload - tte remap io<->memory");
3041 			}
3042 			if (old_pfn != new_pfn &&
3043 			    (pp != NULL || sfhme->hme_page != NULL)) {
3044 				panic("sfmmu_tteload - tte remap pp != NULL");
3045 			}
3046 		} else if (old_pfn != new_pfn) {
3047 			panic("sfmmu_tteload - tte remap, hmeblkp 0x%p",
3048 			    (void *)hmeblkp);
3049 		}
3050 		ASSERT(TTE_CSZ(&tteold) == TTE_CSZ(ttep));
3051 	}
3052 
3053 	if (pp) {
3054 		if (size == TTE8K) {
3055 #ifdef VAC
3056 			/*
3057 			 * Handle VAC consistency
3058 			 */
3059 			if (!remap && (cache & CACHE_VAC) && !PP_ISNC(pp)) {
3060 				sfmmu_vac_conflict(sfmmup, vaddr, pp);
3061 			}
3062 #endif
3063 
3064 			if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3065 				pmtx = sfmmu_page_enter(pp);
3066 				PP_CLRRO(pp);
3067 				sfmmu_page_exit(pmtx);
3068 			} else if (!PP_ISMAPPED(pp) &&
3069 			    (!TTE_IS_WRITABLE(ttep)) && !(PP_ISMOD(pp))) {
3070 				pmtx = sfmmu_page_enter(pp);
3071 				if (!(PP_ISMOD(pp))) {
3072 					PP_SETRO(pp);
3073 				}
3074 				sfmmu_page_exit(pmtx);
3075 			}
3076 
3077 		} else if (sfmmu_pagearray_setup(vaddr, pps, ttep, remap)) {
3078 			/*
3079 			 * sfmmu_pagearray_setup failed so return
3080 			 */
3081 			sfmmu_mlist_exit(pml);
3082 			return (1);
3083 		}
3084 	}
3085 
3086 	/*
3087 	 * Make sure hment is not on a mapping list.
3088 	 */
3089 	ASSERT(remap || (sfhme->hme_page == NULL));
3090 
3091 	/* if it is not a remap then hme->next better be NULL */
3092 	ASSERT((!remap) ? sfhme->hme_next == NULL : 1);
3093 
3094 	if (flags & HAT_LOAD_LOCK) {
3095 		if ((hmeblkp->hblk_lckcnt + 1) >= MAX_HBLK_LCKCNT) {
3096 			panic("too high lckcnt-hmeblk %p",
3097 			    (void *)hmeblkp);
3098 		}
3099 		atomic_add_32(&hmeblkp->hblk_lckcnt, 1);
3100 
3101 		HBLK_STACK_TRACE(hmeblkp, HBLK_LOCK);
3102 	}
3103 
3104 #ifdef VAC
3105 	if (pp && PP_ISNC(pp)) {
3106 		/*
3107 		 * If the physical page is marked to be uncacheable, like
3108 		 * by a vac conflict, make sure the new mapping is also
3109 		 * uncacheable.
3110 		 */
3111 		TTE_CLR_VCACHEABLE(ttep);
3112 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
3113 	}
3114 #endif
3115 	ttep->tte_hmenum = hmenum;
3116 
3117 #ifdef DEBUG
3118 	orig_old = tteold;
3119 #endif /* DEBUG */
3120 
3121 	while (sfmmu_modifytte_try(&tteold, ttep, &sfhme->hme_tte) < 0) {
3122 		if ((sfmmup == KHATID) &&
3123 		    (flags & (HAT_LOAD_LOCK | HAT_LOAD_REMAP))) {
3124 			sfmmu_copytte(&sfhme->hme_tte, &tteold);
3125 		}
3126 #ifdef DEBUG
3127 		chk_tte(&orig_old, &tteold, ttep, hmeblkp);
3128 #endif /* DEBUG */
3129 	}
3130 	ASSERT(TTE_IS_VALID(&sfhme->hme_tte));
3131 
3132 	if (!TTE_IS_VALID(&tteold)) {
3133 
3134 		atomic_add_16(&hmeblkp->hblk_vcnt, 1);
3135 		if (rid == SFMMU_INVALID_SHMERID) {
3136 			atomic_add_long(&sfmmup->sfmmu_ttecnt[size], 1);
3137 		} else {
3138 			sf_srd_t *srdp = sfmmup->sfmmu_srdp;
3139 			sf_region_t *rgnp = srdp->srd_hmergnp[rid];
3140 			/*
3141 			 * We already accounted for region ttecnt's in sfmmu
3142 			 * during hat_join_region() processing. Here we
3143 			 * only update ttecnt's in region struture.
3144 			 */
3145 			atomic_add_long(&rgnp->rgn_ttecnt[size], 1);
3146 		}
3147 	}
3148 
3149 	myflt = (astosfmmu(curthread->t_procp->p_as) == sfmmup);
3150 	if (size > TTE8K && (flags & HAT_LOAD_SHARE) == 0 &&
3151 	    sfmmup != ksfmmup) {
3152 		uchar_t tteflag = 1 << size;
3153 		if (rid == SFMMU_INVALID_SHMERID) {
3154 			if (!(sfmmup->sfmmu_tteflags & tteflag)) {
3155 				hatlockp = sfmmu_hat_enter(sfmmup);
3156 				sfmmup->sfmmu_tteflags |= tteflag;
3157 				sfmmu_hat_exit(hatlockp);
3158 			}
3159 		} else if (!(sfmmup->sfmmu_rtteflags & tteflag)) {
3160 			hatlockp = sfmmu_hat_enter(sfmmup);
3161 			sfmmup->sfmmu_rtteflags |= tteflag;
3162 			sfmmu_hat_exit(hatlockp);
3163 		}
3164 		/*
3165 		 * Update the current CPU tsbmiss area, so the current thread
3166 		 * won't need to take the tsbmiss for the new pagesize.
3167 		 * The other threads in the process will update their tsb
3168 		 * miss area lazily in sfmmu_tsbmiss_exception() when they
3169 		 * fail to find the translation for a newly added pagesize.
3170 		 */
3171 		if (size > TTE64K && myflt) {
3172 			struct tsbmiss *tsbmp;
3173 			kpreempt_disable();
3174 			tsbmp = &tsbmiss_area[CPU->cpu_id];
3175 			if (rid == SFMMU_INVALID_SHMERID) {
3176 				if (!(tsbmp->uhat_tteflags & tteflag)) {
3177 					tsbmp->uhat_tteflags |= tteflag;
3178 				}
3179 			} else {
3180 				if (!(tsbmp->uhat_rtteflags & tteflag)) {
3181 					tsbmp->uhat_rtteflags |= tteflag;
3182 				}
3183 			}
3184 			kpreempt_enable();
3185 		}
3186 	}
3187 
3188 	if (size >= TTE4M && (flags & HAT_LOAD_TEXT) &&
3189 	    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
3190 		hatlockp = sfmmu_hat_enter(sfmmup);
3191 		SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
3192 		sfmmu_hat_exit(hatlockp);
3193 	}
3194 
3195 	flush_tte.tte_intlo = (tteold.tte_intlo ^ ttep->tte_intlo) &
3196 	    hw_tte.tte_intlo;
3197 	flush_tte.tte_inthi = (tteold.tte_inthi ^ ttep->tte_inthi) &
3198 	    hw_tte.tte_inthi;
3199 
3200 	if (remap && (flush_tte.tte_inthi || flush_tte.tte_intlo)) {
3201 		/*
3202 		 * If remap and new tte differs from old tte we need
3203 		 * to sync the mod bit and flush TLB/TSB.  We don't
3204 		 * need to sync ref bit because we currently always set
3205 		 * ref bit in tteload.
3206 		 */
3207 		ASSERT(TTE_IS_REF(ttep));
3208 		if (TTE_IS_MOD(&tteold)) {
3209 			sfmmu_ttesync(sfmmup, vaddr, &tteold, pp);
3210 		}
3211 		/*
3212 		 * hwtte bits shouldn't change for SRD hmeblks as long as SRD
3213 		 * hmes are only used for read only text. Adding this code for
3214 		 * completeness and future use of shared hmeblks with writable
3215 		 * mappings of VMODSORT vnodes.
3216 		 */
3217 		if (hmeblkp->hblk_shared) {
3218 			cpuset_t cpuset = sfmmu_rgntlb_demap(vaddr,
3219 			    sfmmup->sfmmu_srdp->srd_hmergnp[rid], hmeblkp, 1);
3220 			xt_sync(cpuset);
3221 			SFMMU_STAT_ADD(sf_region_remap_demap, 1);
3222 		} else {
3223 			sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 0);
3224 			xt_sync(sfmmup->sfmmu_cpusran);
3225 		}
3226 	}
3227 
3228 	if ((flags & SFMMU_NO_TSBLOAD) == 0) {
3229 		/*
3230 		 * We only preload 8K and 4M mappings into the TSB, since
3231 		 * 64K and 512K mappings are replicated and hence don't
3232 		 * have a single, unique TSB entry. Ditto for 32M/256M.
3233 		 */
3234 		if (size == TTE8K || size == TTE4M) {
3235 			sf_scd_t *scdp;
3236 			hatlockp = sfmmu_hat_enter(sfmmup);
3237 			/*
3238 			 * Don't preload private TSB if the mapping is used
3239 			 * by the shctx in the SCD.
3240 			 */
3241 			scdp = sfmmup->sfmmu_scdp;
3242 			if (rid == SFMMU_INVALID_SHMERID || scdp == NULL ||
3243 			    !SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
3244 				sfmmu_load_tsb(sfmmup, vaddr, &sfhme->hme_tte,
3245 				    size);
3246 			}
3247 			sfmmu_hat_exit(hatlockp);
3248 		}
3249 	}
3250 	if (pp) {
3251 		if (!remap) {
3252 			HME_ADD(sfhme, pp);
3253 			atomic_add_16(&hmeblkp->hblk_hmecnt, 1);
3254 			ASSERT(hmeblkp->hblk_hmecnt > 0);
3255 
3256 			/*
3257 			 * Cannot ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
3258 			 * see pageunload() for comment.
3259 			 */
3260 		}
3261 		sfmmu_mlist_exit(pml);
3262 	}
3263 
3264 	return (0);
3265 }
3266 /*
3267  * Function unlocks hash bucket.
3268  */
3269 static void
3270 sfmmu_tteload_release_hashbucket(struct hmehash_bucket *hmebp)
3271 {
3272 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3273 	SFMMU_HASH_UNLOCK(hmebp);
3274 }
3275 
3276 /*
3277  * function which checks and sets up page array for a large
3278  * translation.  Will set p_vcolor, p_index, p_ro fields.
3279  * Assumes addr and pfnum of first page are properly aligned.
3280  * Will check for physical contiguity. If check fails it return
3281  * non null.
3282  */
3283 static int
3284 sfmmu_pagearray_setup(caddr_t addr, page_t **pps, tte_t *ttep, int remap)
3285 {
3286 	int 	i, index, ttesz;
3287 	pfn_t	pfnum;
3288 	pgcnt_t	npgs;
3289 	page_t *pp, *pp1;
3290 	kmutex_t *pmtx;
3291 #ifdef VAC
3292 	int osz;
3293 	int cflags = 0;
3294 	int vac_err = 0;
3295 #endif
3296 	int newidx = 0;
3297 
3298 	ttesz = TTE_CSZ(ttep);
3299 
3300 	ASSERT(ttesz > TTE8K);
3301 
3302 	npgs = TTEPAGES(ttesz);
3303 	index = PAGESZ_TO_INDEX(ttesz);
3304 
3305 	pfnum = (*pps)->p_pagenum;
3306 	ASSERT(IS_P2ALIGNED(pfnum, npgs));
3307 
3308 	/*
3309 	 * Save the first pp so we can do HAT_TMPNC at the end.
3310 	 */
3311 	pp1 = *pps;
3312 #ifdef VAC
3313 	osz = fnd_mapping_sz(pp1);
3314 #endif
3315 
3316 	for (i = 0; i < npgs; i++, pps++) {
3317 		pp = *pps;
3318 		ASSERT(PAGE_LOCKED(pp));
3319 		ASSERT(pp->p_szc >= ttesz);
3320 		ASSERT(pp->p_szc == pp1->p_szc);
3321 		ASSERT(sfmmu_mlist_held(pp));
3322 
3323 		/*
3324 		 * XXX is it possible to maintain P_RO on the root only?
3325 		 */
3326 		if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3327 			pmtx = sfmmu_page_enter(pp);
3328 			PP_CLRRO(pp);
3329 			sfmmu_page_exit(pmtx);
3330 		} else if (!PP_ISMAPPED(pp) && !TTE_IS_WRITABLE(ttep) &&
3331 		    !PP_ISMOD(pp)) {
3332 			pmtx = sfmmu_page_enter(pp);
3333 			if (!(PP_ISMOD(pp))) {
3334 				PP_SETRO(pp);
3335 			}
3336 			sfmmu_page_exit(pmtx);
3337 		}
3338 
3339 		/*
3340 		 * If this is a remap we skip vac & contiguity checks.
3341 		 */
3342 		if (remap)
3343 			continue;
3344 
3345 		/*
3346 		 * set p_vcolor and detect any vac conflicts.
3347 		 */
3348 #ifdef VAC
3349 		if (vac_err == 0) {
3350 			vac_err = sfmmu_vacconflict_array(addr, pp, &cflags);
3351 
3352 		}
3353 #endif
3354 
3355 		/*
3356 		 * Save current index in case we need to undo it.
3357 		 * Note: "PAGESZ_TO_INDEX(sz)	(1 << (sz))"
3358 		 *	"SFMMU_INDEX_SHIFT	6"
3359 		 *	 "SFMMU_INDEX_MASK	((1 << SFMMU_INDEX_SHIFT) - 1)"
3360 		 *	 "PP_MAPINDEX(p_index)	(p_index & SFMMU_INDEX_MASK)"
3361 		 *
3362 		 * So:	index = PAGESZ_TO_INDEX(ttesz);
3363 		 *	if ttesz == 1 then index = 0x2
3364 		 *		    2 then index = 0x4
3365 		 *		    3 then index = 0x8
3366 		 *		    4 then index = 0x10
3367 		 *		    5 then index = 0x20
3368 		 * The code below checks if it's a new pagesize (ie, newidx)
3369 		 * in case we need to take it back out of p_index,
3370 		 * and then or's the new index into the existing index.
3371 		 */
3372 		if ((PP_MAPINDEX(pp) & index) == 0)
3373 			newidx = 1;
3374 		pp->p_index = (PP_MAPINDEX(pp) | index);
3375 
3376 		/*
3377 		 * contiguity check
3378 		 */
3379 		if (pp->p_pagenum != pfnum) {
3380 			/*
3381 			 * If we fail the contiguity test then
3382 			 * the only thing we need to fix is the p_index field.
3383 			 * We might get a few extra flushes but since this
3384 			 * path is rare that is ok.  The p_ro field will
3385 			 * get automatically fixed on the next tteload to
3386 			 * the page.  NO TNC bit is set yet.
3387 			 */
3388 			while (i >= 0) {
3389 				pp = *pps;
3390 				if (newidx)
3391 					pp->p_index = (PP_MAPINDEX(pp) &
3392 					    ~index);
3393 				pps--;
3394 				i--;
3395 			}
3396 			return (1);
3397 		}
3398 		pfnum++;
3399 		addr += MMU_PAGESIZE;
3400 	}
3401 
3402 #ifdef VAC
3403 	if (vac_err) {
3404 		if (ttesz > osz) {
3405 			/*
3406 			 * There are some smaller mappings that causes vac
3407 			 * conflicts. Convert all existing small mappings to
3408 			 * TNC.
3409 			 */
3410 			SFMMU_STAT_ADD(sf_uncache_conflict, npgs);
3411 			sfmmu_page_cache_array(pp1, HAT_TMPNC, CACHE_FLUSH,
3412 			    npgs);
3413 		} else {
3414 			/* EMPTY */
3415 			/*
3416 			 * If there exists an big page mapping,
3417 			 * that means the whole existing big page
3418 			 * has TNC setting already. No need to covert to
3419 			 * TNC again.
3420 			 */
3421 			ASSERT(PP_ISTNC(pp1));
3422 		}
3423 	}
3424 #endif	/* VAC */
3425 
3426 	return (0);
3427 }
3428 
3429 #ifdef VAC
3430 /*
3431  * Routine that detects vac consistency for a large page. It also
3432  * sets virtual color for all pp's for this big mapping.
3433  */
3434 static int
3435 sfmmu_vacconflict_array(caddr_t addr, page_t *pp, int *cflags)
3436 {
3437 	int vcolor, ocolor;
3438 
3439 	ASSERT(sfmmu_mlist_held(pp));
3440 
3441 	if (PP_ISNC(pp)) {
3442 		return (HAT_TMPNC);
3443 	}
3444 
3445 	vcolor = addr_to_vcolor(addr);
3446 	if (PP_NEWPAGE(pp)) {
3447 		PP_SET_VCOLOR(pp, vcolor);
3448 		return (0);
3449 	}
3450 
3451 	ocolor = PP_GET_VCOLOR(pp);
3452 	if (ocolor == vcolor) {
3453 		return (0);
3454 	}
3455 
3456 	if (!PP_ISMAPPED(pp)) {
3457 		/*
3458 		 * Previous user of page had a differnet color
3459 		 * but since there are no current users
3460 		 * we just flush the cache and change the color.
3461 		 * As an optimization for large pages we flush the
3462 		 * entire cache of that color and set a flag.
3463 		 */
3464 		SFMMU_STAT(sf_pgcolor_conflict);
3465 		if (!CacheColor_IsFlushed(*cflags, ocolor)) {
3466 			CacheColor_SetFlushed(*cflags, ocolor);
3467 			sfmmu_cache_flushcolor(ocolor, pp->p_pagenum);
3468 		}
3469 		PP_SET_VCOLOR(pp, vcolor);
3470 		return (0);
3471 	}
3472 
3473 	/*
3474 	 * We got a real conflict with a current mapping.
3475 	 * set flags to start unencaching all mappings
3476 	 * and return failure so we restart looping
3477 	 * the pp array from the beginning.
3478 	 */
3479 	return (HAT_TMPNC);
3480 }
3481 #endif	/* VAC */
3482 
3483 /*
3484  * creates a large page shadow hmeblk for a tte.
3485  * The purpose of this routine is to allow us to do quick unloads because
3486  * the vm layer can easily pass a very large but sparsely populated range.
3487  */
3488 static struct hme_blk *
3489 sfmmu_shadow_hcreate(sfmmu_t *sfmmup, caddr_t vaddr, int ttesz, uint_t flags)
3490 {
3491 	struct hmehash_bucket *hmebp;
3492 	hmeblk_tag hblktag;
3493 	int hmeshift, size, vshift;
3494 	uint_t shw_mask, newshw_mask;
3495 	struct hme_blk *hmeblkp;
3496 
3497 	ASSERT(sfmmup != KHATID);
3498 	if (mmu_page_sizes == max_mmu_page_sizes) {
3499 		ASSERT(ttesz < TTE256M);
3500 	} else {
3501 		ASSERT(ttesz < TTE4M);
3502 		ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
3503 		ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
3504 	}
3505 
3506 	if (ttesz == TTE8K) {
3507 		size = TTE512K;
3508 	} else {
3509 		size = ++ttesz;
3510 	}
3511 
3512 	hblktag.htag_id = sfmmup;
3513 	hmeshift = HME_HASH_SHIFT(size);
3514 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
3515 	hblktag.htag_rehash = HME_HASH_REHASH(size);
3516 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3517 	hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
3518 
3519 	SFMMU_HASH_LOCK(hmebp);
3520 
3521 	HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
3522 	ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
3523 	if (hmeblkp == NULL) {
3524 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
3525 		    hblktag, flags, SFMMU_INVALID_SHMERID);
3526 	}
3527 	ASSERT(hmeblkp);
3528 	if (!hmeblkp->hblk_shw_mask) {
3529 		/*
3530 		 * if this is a unused hblk it was just allocated or could
3531 		 * potentially be a previous large page hblk so we need to
3532 		 * set the shadow bit.
3533 		 */
3534 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3535 		hmeblkp->hblk_shw_bit = 1;
3536 	} else if (hmeblkp->hblk_shw_bit == 0) {
3537 		panic("sfmmu_shadow_hcreate: shw bit not set in hmeblkp 0x%p",
3538 		    (void *)hmeblkp);
3539 	}
3540 	ASSERT(hmeblkp->hblk_shw_bit == 1);
3541 	ASSERT(!hmeblkp->hblk_shared);
3542 	vshift = vaddr_to_vshift(hblktag, vaddr, size);
3543 	ASSERT(vshift < 8);
3544 	/*
3545 	 * Atomically set shw mask bit
3546 	 */
3547 	do {
3548 		shw_mask = hmeblkp->hblk_shw_mask;
3549 		newshw_mask = shw_mask | (1 << vshift);
3550 		newshw_mask = cas32(&hmeblkp->hblk_shw_mask, shw_mask,
3551 		    newshw_mask);
3552 	} while (newshw_mask != shw_mask);
3553 
3554 	SFMMU_HASH_UNLOCK(hmebp);
3555 
3556 	return (hmeblkp);
3557 }
3558 
3559 /*
3560  * This routine cleanup a previous shadow hmeblk and changes it to
3561  * a regular hblk.  This happens rarely but it is possible
3562  * when a process wants to use large pages and there are hblks still
3563  * lying around from the previous as that used these hmeblks.
3564  * The alternative was to cleanup the shadow hblks at unload time
3565  * but since so few user processes actually use large pages, it is
3566  * better to be lazy and cleanup at this time.
3567  */
3568 static void
3569 sfmmu_shadow_hcleanup(sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
3570 	struct hmehash_bucket *hmebp)
3571 {
3572 	caddr_t addr, endaddr;
3573 	int hashno, size;
3574 
3575 	ASSERT(hmeblkp->hblk_shw_bit);
3576 	ASSERT(!hmeblkp->hblk_shared);
3577 
3578 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3579 
3580 	if (!hmeblkp->hblk_shw_mask) {
3581 		hmeblkp->hblk_shw_bit = 0;
3582 		return;
3583 	}
3584 	addr = (caddr_t)get_hblk_base(hmeblkp);
3585 	endaddr = get_hblk_endaddr(hmeblkp);
3586 	size = get_hblk_ttesz(hmeblkp);
3587 	hashno = size - 1;
3588 	ASSERT(hashno > 0);
3589 	SFMMU_HASH_UNLOCK(hmebp);
3590 
3591 	sfmmu_free_hblks(sfmmup, addr, endaddr, hashno);
3592 
3593 	SFMMU_HASH_LOCK(hmebp);
3594 }
3595 
3596 static void
3597 sfmmu_free_hblks(sfmmu_t *sfmmup, caddr_t addr, caddr_t endaddr,
3598 	int hashno)
3599 {
3600 	int hmeshift, shadow = 0;
3601 	hmeblk_tag hblktag;
3602 	struct hmehash_bucket *hmebp;
3603 	struct hme_blk *hmeblkp;
3604 	struct hme_blk *nx_hblk, *pr_hblk, *list = NULL;
3605 	uint64_t hblkpa, prevpa, nx_pa;
3606 
3607 	ASSERT(hashno > 0);
3608 	hblktag.htag_id = sfmmup;
3609 	hblktag.htag_rehash = hashno;
3610 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3611 
3612 	hmeshift = HME_HASH_SHIFT(hashno);
3613 
3614 	while (addr < endaddr) {
3615 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3616 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3617 		SFMMU_HASH_LOCK(hmebp);
3618 		/* inline HME_HASH_SEARCH */
3619 		hmeblkp = hmebp->hmeblkp;
3620 		hblkpa = hmebp->hmeh_nextpa;
3621 		prevpa = 0;
3622 		pr_hblk = NULL;
3623 		while (hmeblkp) {
3624 			ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
3625 			if (HTAGS_EQ(hmeblkp->hblk_tag, hblktag)) {
3626 				/* found hme_blk */
3627 				ASSERT(!hmeblkp->hblk_shared);
3628 				if (hmeblkp->hblk_shw_bit) {
3629 					if (hmeblkp->hblk_shw_mask) {
3630 						shadow = 1;
3631 						sfmmu_shadow_hcleanup(sfmmup,
3632 						    hmeblkp, hmebp);
3633 						break;
3634 					} else {
3635 						hmeblkp->hblk_shw_bit = 0;
3636 					}
3637 				}
3638 
3639 				/*
3640 				 * Hblk_hmecnt and hblk_vcnt could be non zero
3641 				 * since hblk_unload() does not gurantee that.
3642 				 *
3643 				 * XXX - this could cause tteload() to spin
3644 				 * where sfmmu_shadow_hcleanup() is called.
3645 				 */
3646 			}
3647 
3648 			nx_hblk = hmeblkp->hblk_next;
3649 			nx_pa = hmeblkp->hblk_nextpa;
3650 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
3651 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa,
3652 				    pr_hblk);
3653 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
3654 			} else {
3655 				pr_hblk = hmeblkp;
3656 				prevpa = hblkpa;
3657 			}
3658 			hmeblkp = nx_hblk;
3659 			hblkpa = nx_pa;
3660 		}
3661 
3662 		SFMMU_HASH_UNLOCK(hmebp);
3663 
3664 		if (shadow) {
3665 			/*
3666 			 * We found another shadow hblk so cleaned its
3667 			 * children.  We need to go back and cleanup
3668 			 * the original hblk so we don't change the
3669 			 * addr.
3670 			 */
3671 			shadow = 0;
3672 		} else {
3673 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
3674 			    (1 << hmeshift));
3675 		}
3676 	}
3677 	sfmmu_hblks_list_purge(&list);
3678 }
3679 
3680 /*
3681  * This routine's job is to delete stale invalid shared hmeregions hmeblks that
3682  * may still linger on after pageunload.
3683  */
3684 static void
3685 sfmmu_cleanup_rhblk(sf_srd_t *srdp, caddr_t addr, uint_t rid, int ttesz)
3686 {
3687 	int hmeshift;
3688 	hmeblk_tag hblktag;
3689 	struct hmehash_bucket *hmebp;
3690 	struct hme_blk *hmeblkp;
3691 	struct hme_blk *pr_hblk;
3692 	struct hme_blk *list = NULL;
3693 	uint64_t hblkpa, prevpa;
3694 
3695 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3696 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3697 
3698 	hmeshift = HME_HASH_SHIFT(ttesz);
3699 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3700 	hblktag.htag_rehash = ttesz;
3701 	hblktag.htag_rid = rid;
3702 	hblktag.htag_id = srdp;
3703 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3704 
3705 	SFMMU_HASH_LOCK(hmebp);
3706 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa, pr_hblk,
3707 	    prevpa, &list);
3708 	if (hmeblkp != NULL) {
3709 		ASSERT(hmeblkp->hblk_shared);
3710 		ASSERT(!hmeblkp->hblk_shw_bit);
3711 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3712 			panic("sfmmu_cleanup_rhblk: valid hmeblk");
3713 		}
3714 		ASSERT(!hmeblkp->hblk_lckcnt);
3715 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
3716 		sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
3717 	}
3718 	SFMMU_HASH_UNLOCK(hmebp);
3719 	sfmmu_hblks_list_purge(&list);
3720 }
3721 
3722 /* ARGSUSED */
3723 static void
3724 sfmmu_rgn_cb_noop(caddr_t saddr, caddr_t eaddr, caddr_t r_saddr,
3725     size_t r_size, void *r_obj, u_offset_t r_objoff)
3726 {
3727 }
3728 
3729 /*
3730  * Searches for an hmeblk which maps addr, then unloads this mapping
3731  * and updates *eaddrp, if the hmeblk is found.
3732  */
3733 static void
3734 sfmmu_unload_hmeregion_va(sf_srd_t *srdp, uint_t rid, caddr_t addr,
3735     caddr_t eaddr, int ttesz, caddr_t *eaddrp)
3736 {
3737 	int hmeshift;
3738 	hmeblk_tag hblktag;
3739 	struct hmehash_bucket *hmebp;
3740 	struct hme_blk *hmeblkp;
3741 	struct hme_blk *pr_hblk;
3742 	struct hme_blk *list = NULL;
3743 	uint64_t hblkpa, prevpa;
3744 
3745 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3746 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3747 	ASSERT(ttesz >= HBLK_MIN_TTESZ);
3748 
3749 	hmeshift = HME_HASH_SHIFT(ttesz);
3750 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3751 	hblktag.htag_rehash = ttesz;
3752 	hblktag.htag_rid = rid;
3753 	hblktag.htag_id = srdp;
3754 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3755 
3756 	SFMMU_HASH_LOCK(hmebp);
3757 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa, pr_hblk,
3758 	    prevpa, &list);
3759 	if (hmeblkp != NULL) {
3760 		ASSERT(hmeblkp->hblk_shared);
3761 		ASSERT(!hmeblkp->hblk_lckcnt);
3762 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3763 			*eaddrp = sfmmu_hblk_unload(NULL, hmeblkp, addr,
3764 			    eaddr, NULL, HAT_UNLOAD);
3765 			ASSERT(*eaddrp > addr);
3766 		}
3767 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3768 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
3769 		sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
3770 	}
3771 	SFMMU_HASH_UNLOCK(hmebp);
3772 	sfmmu_hblks_list_purge(&list);
3773 }
3774 
3775 static void
3776 sfmmu_unload_hmeregion(sf_srd_t *srdp, sf_region_t *rgnp)
3777 {
3778 	int ttesz = rgnp->rgn_pgszc;
3779 	size_t rsz = rgnp->rgn_size;
3780 	caddr_t rsaddr = rgnp->rgn_saddr;
3781 	caddr_t readdr = rsaddr + rsz;
3782 	caddr_t rhsaddr;
3783 	caddr_t va;
3784 	uint_t rid = rgnp->rgn_id;
3785 	caddr_t cbsaddr;
3786 	caddr_t cbeaddr;
3787 	hat_rgn_cb_func_t rcbfunc;
3788 	ulong_t cnt;
3789 
3790 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3791 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3792 
3793 	ASSERT(IS_P2ALIGNED(rsaddr, TTEBYTES(ttesz)));
3794 	ASSERT(IS_P2ALIGNED(rsz, TTEBYTES(ttesz)));
3795 	if (ttesz < HBLK_MIN_TTESZ) {
3796 		ttesz = HBLK_MIN_TTESZ;
3797 		rhsaddr = (caddr_t)P2ALIGN((uintptr_t)rsaddr, HBLK_MIN_BYTES);
3798 	} else {
3799 		rhsaddr = rsaddr;
3800 	}
3801 
3802 	if ((rcbfunc = rgnp->rgn_cb_function) == NULL) {
3803 		rcbfunc = sfmmu_rgn_cb_noop;
3804 	}
3805 
3806 	while (ttesz >= HBLK_MIN_TTESZ) {
3807 		cbsaddr = rsaddr;
3808 		cbeaddr = rsaddr;
3809 		if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
3810 			ttesz--;
3811 			continue;
3812 		}
3813 		cnt = 0;
3814 		va = rsaddr;
3815 		while (va < readdr) {
3816 			ASSERT(va >= rhsaddr);
3817 			if (va != cbeaddr) {
3818 				if (cbeaddr != cbsaddr) {
3819 					ASSERT(cbeaddr > cbsaddr);
3820 					(*rcbfunc)(cbsaddr, cbeaddr,
3821 					    rsaddr, rsz, rgnp->rgn_obj,
3822 					    rgnp->rgn_objoff);
3823 				}
3824 				cbsaddr = va;
3825 				cbeaddr = va;
3826 			}
3827 			sfmmu_unload_hmeregion_va(srdp, rid, va, readdr,
3828 			    ttesz, &cbeaddr);
3829 			cnt++;
3830 			va = rhsaddr + (cnt << TTE_PAGE_SHIFT(ttesz));
3831 		}
3832 		if (cbeaddr != cbsaddr) {
3833 			ASSERT(cbeaddr > cbsaddr);
3834 			(*rcbfunc)(cbsaddr, cbeaddr, rsaddr,
3835 			    rsz, rgnp->rgn_obj,
3836 			    rgnp->rgn_objoff);
3837 		}
3838 		ttesz--;
3839 	}
3840 }
3841 
3842 /*
3843  * Release one hardware address translation lock on the given address range.
3844  */
3845 void
3846 hat_unlock(struct hat *sfmmup, caddr_t addr, size_t len)
3847 {
3848 	struct hmehash_bucket *hmebp;
3849 	hmeblk_tag hblktag;
3850 	int hmeshift, hashno = 1;
3851 	struct hme_blk *hmeblkp, *list = NULL;
3852 	caddr_t endaddr;
3853 
3854 	ASSERT(sfmmup != NULL);
3855 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
3856 
3857 	ASSERT((sfmmup == ksfmmup) ||
3858 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
3859 	ASSERT((len & MMU_PAGEOFFSET) == 0);
3860 	endaddr = addr + len;
3861 	hblktag.htag_id = sfmmup;
3862 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3863 
3864 	/*
3865 	 * Spitfire supports 4 page sizes.
3866 	 * Most pages are expected to be of the smallest page size (8K) and
3867 	 * these will not need to be rehashed. 64K pages also don't need to be
3868 	 * rehashed because an hmeblk spans 64K of address space. 512K pages
3869 	 * might need 1 rehash and and 4M pages might need 2 rehashes.
3870 	 */
3871 	while (addr < endaddr) {
3872 		hmeshift = HME_HASH_SHIFT(hashno);
3873 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3874 		hblktag.htag_rehash = hashno;
3875 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3876 
3877 		SFMMU_HASH_LOCK(hmebp);
3878 
3879 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
3880 		if (hmeblkp != NULL) {
3881 			ASSERT(!hmeblkp->hblk_shared);
3882 			/*
3883 			 * If we encounter a shadow hmeblk then
3884 			 * we know there are no valid hmeblks mapping
3885 			 * this address at this size or larger.
3886 			 * Just increment address by the smallest
3887 			 * page size.
3888 			 */
3889 			if (hmeblkp->hblk_shw_bit) {
3890 				addr += MMU_PAGESIZE;
3891 			} else {
3892 				addr = sfmmu_hblk_unlock(hmeblkp, addr,
3893 				    endaddr);
3894 			}
3895 			SFMMU_HASH_UNLOCK(hmebp);
3896 			hashno = 1;
3897 			continue;
3898 		}
3899 		SFMMU_HASH_UNLOCK(hmebp);
3900 
3901 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
3902 			/*
3903 			 * We have traversed the whole list and rehashed
3904 			 * if necessary without finding the address to unlock
3905 			 * which should never happen.
3906 			 */
3907 			panic("sfmmu_unlock: addr not found. "
3908 			    "addr %p hat %p", (void *)addr, (void *)sfmmup);
3909 		} else {
3910 			hashno++;
3911 		}
3912 	}
3913 
3914 	sfmmu_hblks_list_purge(&list);
3915 }
3916 
3917 void
3918 hat_unlock_region(struct hat *sfmmup, caddr_t addr, size_t len,
3919     hat_region_cookie_t rcookie)
3920 {
3921 	sf_srd_t *srdp;
3922 	sf_region_t *rgnp;
3923 	int ttesz;
3924 	uint_t rid;
3925 	caddr_t eaddr;
3926 	caddr_t va;
3927 	int hmeshift;
3928 	hmeblk_tag hblktag;
3929 	struct hmehash_bucket *hmebp;
3930 	struct hme_blk *hmeblkp;
3931 	struct hme_blk *pr_hblk;
3932 	struct hme_blk *list;
3933 	uint64_t hblkpa, prevpa;
3934 
3935 	if (rcookie == HAT_INVALID_REGION_COOKIE) {
3936 		hat_unlock(sfmmup, addr, len);
3937 		return;
3938 	}
3939 
3940 	ASSERT(sfmmup != NULL);
3941 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
3942 	ASSERT(sfmmup != ksfmmup);
3943 
3944 	srdp = sfmmup->sfmmu_srdp;
3945 	rid = (uint_t)((uint64_t)rcookie);
3946 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3947 	eaddr = addr + len;
3948 	va = addr;
3949 	list = NULL;
3950 	rgnp = srdp->srd_hmergnp[rid];
3951 	SFMMU_VALIDATE_HMERID(sfmmup, rid, addr, len);
3952 
3953 	ASSERT(IS_P2ALIGNED(addr, TTEBYTES(rgnp->rgn_pgszc)));
3954 	ASSERT(IS_P2ALIGNED(len, TTEBYTES(rgnp->rgn_pgszc)));
3955 	if (rgnp->rgn_pgszc < HBLK_MIN_TTESZ) {
3956 		ttesz = HBLK_MIN_TTESZ;
3957 	} else {
3958 		ttesz = rgnp->rgn_pgszc;
3959 	}
3960 	while (va < eaddr) {
3961 		while (ttesz < rgnp->rgn_pgszc &&
3962 		    IS_P2ALIGNED(va, TTEBYTES(ttesz + 1))) {
3963 			ttesz++;
3964 		}
3965 		while (ttesz >= HBLK_MIN_TTESZ) {
3966 			if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
3967 				ttesz--;
3968 				continue;
3969 			}
3970 			hmeshift = HME_HASH_SHIFT(ttesz);
3971 			hblktag.htag_bspage = HME_HASH_BSPAGE(va, hmeshift);
3972 			hblktag.htag_rehash = ttesz;
3973 			hblktag.htag_rid = rid;
3974 			hblktag.htag_id = srdp;
3975 			hmebp = HME_HASH_FUNCTION(srdp, va, hmeshift);
3976 			SFMMU_HASH_LOCK(hmebp);
3977 			HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa,
3978 			    pr_hblk, prevpa, &list);
3979 			if (hmeblkp == NULL) {
3980 				SFMMU_HASH_UNLOCK(hmebp);
3981 				ttesz--;
3982 				continue;
3983 			}
3984 			ASSERT(hmeblkp->hblk_shared);
3985 			va = sfmmu_hblk_unlock(hmeblkp, va, eaddr);
3986 			ASSERT(va >= eaddr ||
3987 			    IS_P2ALIGNED((uintptr_t)va, TTEBYTES(ttesz)));
3988 			SFMMU_HASH_UNLOCK(hmebp);
3989 			break;
3990 		}
3991 		if (ttesz < HBLK_MIN_TTESZ) {
3992 			panic("hat_unlock_region: addr not found "
3993 			    "addr %p hat %p", (void *)va, (void *)sfmmup);
3994 		}
3995 	}
3996 	sfmmu_hblks_list_purge(&list);
3997 }
3998 
3999 /*
4000  * Function to unlock a range of addresses in an hmeblk.  It returns the
4001  * next address that needs to be unlocked.
4002  * Should be called with the hash lock held.
4003  */
4004 static caddr_t
4005 sfmmu_hblk_unlock(struct hme_blk *hmeblkp, caddr_t addr, caddr_t endaddr)
4006 {
4007 	struct sf_hment *sfhme;
4008 	tte_t tteold, ttemod;
4009 	int ttesz, ret;
4010 
4011 	ASSERT(in_hblk_range(hmeblkp, addr));
4012 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4013 
4014 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4015 	ttesz = get_hblk_ttesz(hmeblkp);
4016 
4017 	HBLKTOHME(sfhme, hmeblkp, addr);
4018 	while (addr < endaddr) {
4019 readtte:
4020 		sfmmu_copytte(&sfhme->hme_tte, &tteold);
4021 		if (TTE_IS_VALID(&tteold)) {
4022 
4023 			ttemod = tteold;
4024 
4025 			ret = sfmmu_modifytte_try(&tteold, &ttemod,
4026 			    &sfhme->hme_tte);
4027 
4028 			if (ret < 0)
4029 				goto readtte;
4030 
4031 			if (hmeblkp->hblk_lckcnt == 0)
4032 				panic("zero hblk lckcnt");
4033 
4034 			if (((uintptr_t)addr + TTEBYTES(ttesz)) >
4035 			    (uintptr_t)endaddr)
4036 				panic("can't unlock large tte");
4037 
4038 			ASSERT(hmeblkp->hblk_lckcnt > 0);
4039 			atomic_add_32(&hmeblkp->hblk_lckcnt, -1);
4040 			HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
4041 		} else {
4042 			panic("sfmmu_hblk_unlock: invalid tte");
4043 		}
4044 		addr += TTEBYTES(ttesz);
4045 		sfhme++;
4046 	}
4047 	return (addr);
4048 }
4049 
4050 /*
4051  * Physical Address Mapping Framework
4052  *
4053  * General rules:
4054  *
4055  * (1) Applies only to seg_kmem memory pages. To make things easier,
4056  *     seg_kpm addresses are also accepted by the routines, but nothing
4057  *     is done with them since by definition their PA mappings are static.
4058  * (2) hat_add_callback() may only be called while holding the page lock
4059  *     SE_SHARED or SE_EXCL of the underlying page (e.g., as_pagelock()),
4060  *     or passing HAC_PAGELOCK flag.
4061  * (3) prehandler() and posthandler() may not call hat_add_callback() or
4062  *     hat_delete_callback(), nor should they allocate memory. Post quiesce
4063  *     callbacks may not sleep or acquire adaptive mutex locks.
4064  * (4) Either prehandler() or posthandler() (but not both) may be specified
4065  *     as being NULL.  Specifying an errhandler() is optional.
4066  *
4067  * Details of using the framework:
4068  *
4069  * registering a callback (hat_register_callback())
4070  *
4071  *	Pass prehandler, posthandler, errhandler addresses
4072  *	as described below. If capture_cpus argument is nonzero,
4073  *	suspend callback to the prehandler will occur with CPUs
4074  *	captured and executing xc_loop() and CPUs will remain
4075  *	captured until after the posthandler suspend callback
4076  *	occurs.
4077  *
4078  * adding a callback (hat_add_callback())
4079  *
4080  *      as_pagelock();
4081  *	hat_add_callback();
4082  *      save returned pfn in private data structures or program registers;
4083  *      as_pageunlock();
4084  *
4085  * prehandler()
4086  *
4087  *	Stop all accesses by physical address to this memory page.
4088  *	Called twice: the first, PRESUSPEND, is a context safe to acquire
4089  *	adaptive locks. The second, SUSPEND, is called at high PIL with
4090  *	CPUs captured so adaptive locks may NOT be acquired (and all spin
4091  *	locks must be XCALL_PIL or higher locks).
4092  *
4093  *	May return the following errors:
4094  *		EIO:	A fatal error has occurred. This will result in panic.
4095  *		EAGAIN:	The page cannot be suspended. This will fail the
4096  *			relocation.
4097  *		0:	Success.
4098  *
4099  * posthandler()
4100  *
4101  *      Save new pfn in private data structures or program registers;
4102  *	not allowed to fail (non-zero return values will result in panic).
4103  *
4104  * errhandler()
4105  *
4106  *	called when an error occurs related to the callback.  Currently
4107  *	the only such error is HAT_CB_ERR_LEAKED which indicates that
4108  *	a page is being freed, but there are still outstanding callback(s)
4109  *	registered on the page.
4110  *
4111  * removing a callback (hat_delete_callback(); e.g., prior to freeing memory)
4112  *
4113  *	stop using physical address
4114  *	hat_delete_callback();
4115  *
4116  */
4117 
4118 /*
4119  * Register a callback class.  Each subsystem should do this once and
4120  * cache the id_t returned for use in setting up and tearing down callbacks.
4121  *
4122  * There is no facility for removing callback IDs once they are created;
4123  * the "key" should be unique for each module, so in case a module is unloaded
4124  * and subsequently re-loaded, we can recycle the module's previous entry.
4125  */
4126 id_t
4127 hat_register_callback(int key,
4128 	int (*prehandler)(caddr_t, uint_t, uint_t, void *),
4129 	int (*posthandler)(caddr_t, uint_t, uint_t, void *, pfn_t),
4130 	int (*errhandler)(caddr_t, uint_t, uint_t, void *),
4131 	int capture_cpus)
4132 {
4133 	id_t id;
4134 
4135 	/*
4136 	 * Search the table for a pre-existing callback associated with
4137 	 * the identifier "key".  If one exists, we re-use that entry in
4138 	 * the table for this instance, otherwise we assign the next
4139 	 * available table slot.
4140 	 */
4141 	for (id = 0; id < sfmmu_max_cb_id; id++) {
4142 		if (sfmmu_cb_table[id].key == key)
4143 			break;
4144 	}
4145 
4146 	if (id == sfmmu_max_cb_id) {
4147 		id = sfmmu_cb_nextid++;
4148 		if (id >= sfmmu_max_cb_id)
4149 			panic("hat_register_callback: out of callback IDs");
4150 	}
4151 
4152 	ASSERT(prehandler != NULL || posthandler != NULL);
4153 
4154 	sfmmu_cb_table[id].key = key;
4155 	sfmmu_cb_table[id].prehandler = prehandler;
4156 	sfmmu_cb_table[id].posthandler = posthandler;
4157 	sfmmu_cb_table[id].errhandler = errhandler;
4158 	sfmmu_cb_table[id].capture_cpus = capture_cpus;
4159 
4160 	return (id);
4161 }
4162 
4163 #define	HAC_COOKIE_NONE	(void *)-1
4164 
4165 /*
4166  * Add relocation callbacks to the specified addr/len which will be called
4167  * when relocating the associated page. See the description of pre and
4168  * posthandler above for more details.
4169  *
4170  * If HAC_PAGELOCK is included in flags, the underlying memory page is
4171  * locked internally so the caller must be able to deal with the callback
4172  * running even before this function has returned.  If HAC_PAGELOCK is not
4173  * set, it is assumed that the underlying memory pages are locked.
4174  *
4175  * Since the caller must track the individual page boundaries anyway,
4176  * we only allow a callback to be added to a single page (large
4177  * or small).  Thus [addr, addr + len) MUST be contained within a single
4178  * page.
4179  *
4180  * Registering multiple callbacks on the same [addr, addr+len) is supported,
4181  * _provided_that_ a unique parameter is specified for each callback.
4182  * If multiple callbacks are registered on the same range the callback will
4183  * be invoked with each unique parameter. Registering the same callback with
4184  * the same argument more than once will result in corrupted kernel state.
4185  *
4186  * Returns the pfn of the underlying kernel page in *rpfn
4187  * on success, or PFN_INVALID on failure.
4188  *
4189  * cookiep (if passed) provides storage space for an opaque cookie
4190  * to return later to hat_delete_callback(). This cookie makes the callback
4191  * deletion significantly quicker by avoiding a potentially lengthy hash
4192  * search.
4193  *
4194  * Returns values:
4195  *    0:      success
4196  *    ENOMEM: memory allocation failure (e.g. flags was passed as HAC_NOSLEEP)
4197  *    EINVAL: callback ID is not valid
4198  *    ENXIO:  ["vaddr", "vaddr" + len) is not mapped in the kernel's address
4199  *            space
4200  *    ERANGE: ["vaddr", "vaddr" + len) crosses a page boundary
4201  */
4202 int
4203 hat_add_callback(id_t callback_id, caddr_t vaddr, uint_t len, uint_t flags,
4204 	void *pvt, pfn_t *rpfn, void **cookiep)
4205 {
4206 	struct 		hmehash_bucket *hmebp;
4207 	hmeblk_tag 	hblktag;
4208 	struct hme_blk	*hmeblkp;
4209 	int 		hmeshift, hashno;
4210 	caddr_t 	saddr, eaddr, baseaddr;
4211 	struct pa_hment *pahmep;
4212 	struct sf_hment *sfhmep, *osfhmep;
4213 	kmutex_t	*pml;
4214 	tte_t   	tte;
4215 	page_t		*pp;
4216 	vnode_t		*vp;
4217 	u_offset_t	off;
4218 	pfn_t		pfn;
4219 	int		kmflags = (flags & HAC_SLEEP)? KM_SLEEP : KM_NOSLEEP;
4220 	int		locked = 0;
4221 
4222 	/*
4223 	 * For KPM mappings, just return the physical address since we
4224 	 * don't need to register any callbacks.
4225 	 */
4226 	if (IS_KPM_ADDR(vaddr)) {
4227 		uint64_t paddr;
4228 		SFMMU_KPM_VTOP(vaddr, paddr);
4229 		*rpfn = btop(paddr);
4230 		if (cookiep != NULL)
4231 			*cookiep = HAC_COOKIE_NONE;
4232 		return (0);
4233 	}
4234 
4235 	if (callback_id < (id_t)0 || callback_id >= sfmmu_cb_nextid) {
4236 		*rpfn = PFN_INVALID;
4237 		return (EINVAL);
4238 	}
4239 
4240 	if ((pahmep = kmem_cache_alloc(pa_hment_cache, kmflags)) == NULL) {
4241 		*rpfn = PFN_INVALID;
4242 		return (ENOMEM);
4243 	}
4244 
4245 	sfhmep = &pahmep->sfment;
4246 
4247 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4248 	eaddr = saddr + len;
4249 
4250 rehash:
4251 	/* Find the mapping(s) for this page */
4252 	for (hashno = TTE64K, hmeblkp = NULL;
4253 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4254 	    hashno++) {
4255 		hmeshift = HME_HASH_SHIFT(hashno);
4256 		hblktag.htag_id = ksfmmup;
4257 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4258 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4259 		hblktag.htag_rehash = hashno;
4260 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4261 
4262 		SFMMU_HASH_LOCK(hmebp);
4263 
4264 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4265 
4266 		if (hmeblkp == NULL)
4267 			SFMMU_HASH_UNLOCK(hmebp);
4268 	}
4269 
4270 	if (hmeblkp == NULL) {
4271 		kmem_cache_free(pa_hment_cache, pahmep);
4272 		*rpfn = PFN_INVALID;
4273 		return (ENXIO);
4274 	}
4275 
4276 	ASSERT(!hmeblkp->hblk_shared);
4277 
4278 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4279 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4280 
4281 	if (!TTE_IS_VALID(&tte)) {
4282 		SFMMU_HASH_UNLOCK(hmebp);
4283 		kmem_cache_free(pa_hment_cache, pahmep);
4284 		*rpfn = PFN_INVALID;
4285 		return (ENXIO);
4286 	}
4287 
4288 	/*
4289 	 * Make sure the boundaries for the callback fall within this
4290 	 * single mapping.
4291 	 */
4292 	baseaddr = (caddr_t)get_hblk_base(hmeblkp);
4293 	ASSERT(saddr >= baseaddr);
4294 	if (eaddr > saddr + TTEBYTES(TTE_CSZ(&tte))) {
4295 		SFMMU_HASH_UNLOCK(hmebp);
4296 		kmem_cache_free(pa_hment_cache, pahmep);
4297 		*rpfn = PFN_INVALID;
4298 		return (ERANGE);
4299 	}
4300 
4301 	pfn = sfmmu_ttetopfn(&tte, vaddr);
4302 
4303 	/*
4304 	 * The pfn may not have a page_t underneath in which case we
4305 	 * just return it. This can happen if we are doing I/O to a
4306 	 * static portion of the kernel's address space, for instance.
4307 	 */
4308 	pp = osfhmep->hme_page;
4309 	if (pp == NULL) {
4310 		SFMMU_HASH_UNLOCK(hmebp);
4311 		kmem_cache_free(pa_hment_cache, pahmep);
4312 		*rpfn = pfn;
4313 		if (cookiep)
4314 			*cookiep = HAC_COOKIE_NONE;
4315 		return (0);
4316 	}
4317 	ASSERT(pp == PP_PAGEROOT(pp));
4318 
4319 	vp = pp->p_vnode;
4320 	off = pp->p_offset;
4321 
4322 	pml = sfmmu_mlist_enter(pp);
4323 
4324 	if (flags & HAC_PAGELOCK) {
4325 		if (!page_trylock(pp, SE_SHARED)) {
4326 			/*
4327 			 * Somebody is holding SE_EXCL lock. Might
4328 			 * even be hat_page_relocate(). Drop all
4329 			 * our locks, lookup the page in &kvp, and
4330 			 * retry. If it doesn't exist in &kvp and &zvp,
4331 			 * then we must be dealing with a kernel mapped
4332 			 * page which doesn't actually belong to
4333 			 * segkmem so we punt.
4334 			 */
4335 			sfmmu_mlist_exit(pml);
4336 			SFMMU_HASH_UNLOCK(hmebp);
4337 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4338 
4339 			/* check zvp before giving up */
4340 			if (pp == NULL)
4341 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4342 				    SE_SHARED);
4343 
4344 			/* Okay, we didn't find it, give up */
4345 			if (pp == NULL) {
4346 				kmem_cache_free(pa_hment_cache, pahmep);
4347 				*rpfn = pfn;
4348 				if (cookiep)
4349 					*cookiep = HAC_COOKIE_NONE;
4350 				return (0);
4351 			}
4352 			page_unlock(pp);
4353 			goto rehash;
4354 		}
4355 		locked = 1;
4356 	}
4357 
4358 	if (!PAGE_LOCKED(pp) && !panicstr)
4359 		panic("hat_add_callback: page 0x%p not locked", (void *)pp);
4360 
4361 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4362 	    pp->p_offset != off) {
4363 		/*
4364 		 * The page moved before we got our hands on it.  Drop
4365 		 * all the locks and try again.
4366 		 */
4367 		ASSERT((flags & HAC_PAGELOCK) != 0);
4368 		sfmmu_mlist_exit(pml);
4369 		SFMMU_HASH_UNLOCK(hmebp);
4370 		page_unlock(pp);
4371 		locked = 0;
4372 		goto rehash;
4373 	}
4374 
4375 	if (!VN_ISKAS(vp)) {
4376 		/*
4377 		 * This is not a segkmem page but another page which
4378 		 * has been kernel mapped. It had better have at least
4379 		 * a share lock on it. Return the pfn.
4380 		 */
4381 		sfmmu_mlist_exit(pml);
4382 		SFMMU_HASH_UNLOCK(hmebp);
4383 		if (locked)
4384 			page_unlock(pp);
4385 		kmem_cache_free(pa_hment_cache, pahmep);
4386 		ASSERT(PAGE_LOCKED(pp));
4387 		*rpfn = pfn;
4388 		if (cookiep)
4389 			*cookiep = HAC_COOKIE_NONE;
4390 		return (0);
4391 	}
4392 
4393 	/*
4394 	 * Setup this pa_hment and link its embedded dummy sf_hment into
4395 	 * the mapping list.
4396 	 */
4397 	pp->p_share++;
4398 	pahmep->cb_id = callback_id;
4399 	pahmep->addr = vaddr;
4400 	pahmep->len = len;
4401 	pahmep->refcnt = 1;
4402 	pahmep->flags = 0;
4403 	pahmep->pvt = pvt;
4404 
4405 	sfhmep->hme_tte.ll = 0;
4406 	sfhmep->hme_data = pahmep;
4407 	sfhmep->hme_prev = osfhmep;
4408 	sfhmep->hme_next = osfhmep->hme_next;
4409 
4410 	if (osfhmep->hme_next)
4411 		osfhmep->hme_next->hme_prev = sfhmep;
4412 
4413 	osfhmep->hme_next = sfhmep;
4414 
4415 	sfmmu_mlist_exit(pml);
4416 	SFMMU_HASH_UNLOCK(hmebp);
4417 
4418 	if (locked)
4419 		page_unlock(pp);
4420 
4421 	*rpfn = pfn;
4422 	if (cookiep)
4423 		*cookiep = (void *)pahmep;
4424 
4425 	return (0);
4426 }
4427 
4428 /*
4429  * Remove the relocation callbacks from the specified addr/len.
4430  */
4431 void
4432 hat_delete_callback(caddr_t vaddr, uint_t len, void *pvt, uint_t flags,
4433 	void *cookie)
4434 {
4435 	struct		hmehash_bucket *hmebp;
4436 	hmeblk_tag	hblktag;
4437 	struct hme_blk	*hmeblkp;
4438 	int		hmeshift, hashno;
4439 	caddr_t		saddr;
4440 	struct pa_hment	*pahmep;
4441 	struct sf_hment	*sfhmep, *osfhmep;
4442 	kmutex_t	*pml;
4443 	tte_t		tte;
4444 	page_t		*pp;
4445 	vnode_t		*vp;
4446 	u_offset_t	off;
4447 	int		locked = 0;
4448 
4449 	/*
4450 	 * If the cookie is HAC_COOKIE_NONE then there is no pa_hment to
4451 	 * remove so just return.
4452 	 */
4453 	if (cookie == HAC_COOKIE_NONE || IS_KPM_ADDR(vaddr))
4454 		return;
4455 
4456 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4457 
4458 rehash:
4459 	/* Find the mapping(s) for this page */
4460 	for (hashno = TTE64K, hmeblkp = NULL;
4461 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4462 	    hashno++) {
4463 		hmeshift = HME_HASH_SHIFT(hashno);
4464 		hblktag.htag_id = ksfmmup;
4465 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4466 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4467 		hblktag.htag_rehash = hashno;
4468 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4469 
4470 		SFMMU_HASH_LOCK(hmebp);
4471 
4472 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4473 
4474 		if (hmeblkp == NULL)
4475 			SFMMU_HASH_UNLOCK(hmebp);
4476 	}
4477 
4478 	if (hmeblkp == NULL)
4479 		return;
4480 
4481 	ASSERT(!hmeblkp->hblk_shared);
4482 
4483 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4484 
4485 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4486 	if (!TTE_IS_VALID(&tte)) {
4487 		SFMMU_HASH_UNLOCK(hmebp);
4488 		return;
4489 	}
4490 
4491 	pp = osfhmep->hme_page;
4492 	if (pp == NULL) {
4493 		SFMMU_HASH_UNLOCK(hmebp);
4494 		ASSERT(cookie == NULL);
4495 		return;
4496 	}
4497 
4498 	vp = pp->p_vnode;
4499 	off = pp->p_offset;
4500 
4501 	pml = sfmmu_mlist_enter(pp);
4502 
4503 	if (flags & HAC_PAGELOCK) {
4504 		if (!page_trylock(pp, SE_SHARED)) {
4505 			/*
4506 			 * Somebody is holding SE_EXCL lock. Might
4507 			 * even be hat_page_relocate(). Drop all
4508 			 * our locks, lookup the page in &kvp, and
4509 			 * retry. If it doesn't exist in &kvp and &zvp,
4510 			 * then we must be dealing with a kernel mapped
4511 			 * page which doesn't actually belong to
4512 			 * segkmem so we punt.
4513 			 */
4514 			sfmmu_mlist_exit(pml);
4515 			SFMMU_HASH_UNLOCK(hmebp);
4516 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4517 			/* check zvp before giving up */
4518 			if (pp == NULL)
4519 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4520 				    SE_SHARED);
4521 
4522 			if (pp == NULL) {
4523 				ASSERT(cookie == NULL);
4524 				return;
4525 			}
4526 			page_unlock(pp);
4527 			goto rehash;
4528 		}
4529 		locked = 1;
4530 	}
4531 
4532 	ASSERT(PAGE_LOCKED(pp));
4533 
4534 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4535 	    pp->p_offset != off) {
4536 		/*
4537 		 * The page moved before we got our hands on it.  Drop
4538 		 * all the locks and try again.
4539 		 */
4540 		ASSERT((flags & HAC_PAGELOCK) != 0);
4541 		sfmmu_mlist_exit(pml);
4542 		SFMMU_HASH_UNLOCK(hmebp);
4543 		page_unlock(pp);
4544 		locked = 0;
4545 		goto rehash;
4546 	}
4547 
4548 	if (!VN_ISKAS(vp)) {
4549 		/*
4550 		 * This is not a segkmem page but another page which
4551 		 * has been kernel mapped.
4552 		 */
4553 		sfmmu_mlist_exit(pml);
4554 		SFMMU_HASH_UNLOCK(hmebp);
4555 		if (locked)
4556 			page_unlock(pp);
4557 		ASSERT(cookie == NULL);
4558 		return;
4559 	}
4560 
4561 	if (cookie != NULL) {
4562 		pahmep = (struct pa_hment *)cookie;
4563 		sfhmep = &pahmep->sfment;
4564 	} else {
4565 		for (sfhmep = pp->p_mapping; sfhmep != NULL;
4566 		    sfhmep = sfhmep->hme_next) {
4567 
4568 			/*
4569 			 * skip va<->pa mappings
4570 			 */
4571 			if (!IS_PAHME(sfhmep))
4572 				continue;
4573 
4574 			pahmep = sfhmep->hme_data;
4575 			ASSERT(pahmep != NULL);
4576 
4577 			/*
4578 			 * if pa_hment matches, remove it
4579 			 */
4580 			if ((pahmep->pvt == pvt) &&
4581 			    (pahmep->addr == vaddr) &&
4582 			    (pahmep->len == len)) {
4583 				break;
4584 			}
4585 		}
4586 	}
4587 
4588 	if (sfhmep == NULL) {
4589 		if (!panicstr) {
4590 			panic("hat_delete_callback: pa_hment not found, pp %p",
4591 			    (void *)pp);
4592 		}
4593 		return;
4594 	}
4595 
4596 	/*
4597 	 * Note: at this point a valid kernel mapping must still be
4598 	 * present on this page.
4599 	 */
4600 	pp->p_share--;
4601 	if (pp->p_share <= 0)
4602 		panic("hat_delete_callback: zero p_share");
4603 
4604 	if (--pahmep->refcnt == 0) {
4605 		if (pahmep->flags != 0)
4606 			panic("hat_delete_callback: pa_hment is busy");
4607 
4608 		/*
4609 		 * Remove sfhmep from the mapping list for the page.
4610 		 */
4611 		if (sfhmep->hme_prev) {
4612 			sfhmep->hme_prev->hme_next = sfhmep->hme_next;
4613 		} else {
4614 			pp->p_mapping = sfhmep->hme_next;
4615 		}
4616 
4617 		if (sfhmep->hme_next)
4618 			sfhmep->hme_next->hme_prev = sfhmep->hme_prev;
4619 
4620 		sfmmu_mlist_exit(pml);
4621 		SFMMU_HASH_UNLOCK(hmebp);
4622 
4623 		if (locked)
4624 			page_unlock(pp);
4625 
4626 		kmem_cache_free(pa_hment_cache, pahmep);
4627 		return;
4628 	}
4629 
4630 	sfmmu_mlist_exit(pml);
4631 	SFMMU_HASH_UNLOCK(hmebp);
4632 	if (locked)
4633 		page_unlock(pp);
4634 }
4635 
4636 /*
4637  * hat_probe returns 1 if the translation for the address 'addr' is
4638  * loaded, zero otherwise.
4639  *
4640  * hat_probe should be used only for advisorary purposes because it may
4641  * occasionally return the wrong value. The implementation must guarantee that
4642  * returning the wrong value is a very rare event. hat_probe is used
4643  * to implement optimizations in the segment drivers.
4644  *
4645  */
4646 int
4647 hat_probe(struct hat *sfmmup, caddr_t addr)
4648 {
4649 	pfn_t pfn;
4650 	tte_t tte;
4651 
4652 	ASSERT(sfmmup != NULL);
4653 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4654 
4655 	ASSERT((sfmmup == ksfmmup) ||
4656 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4657 
4658 	if (sfmmup == ksfmmup) {
4659 		while ((pfn = sfmmu_vatopfn(addr, sfmmup, &tte))
4660 		    == PFN_SUSPENDED) {
4661 			sfmmu_vatopfn_suspended(addr, sfmmup, &tte);
4662 		}
4663 	} else {
4664 		pfn = sfmmu_uvatopfn(addr, sfmmup, NULL);
4665 	}
4666 
4667 	if (pfn != PFN_INVALID)
4668 		return (1);
4669 	else
4670 		return (0);
4671 }
4672 
4673 ssize_t
4674 hat_getpagesize(struct hat *sfmmup, caddr_t addr)
4675 {
4676 	tte_t tte;
4677 
4678 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4679 
4680 	if (sfmmup == ksfmmup) {
4681 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4682 			return (-1);
4683 		}
4684 	} else {
4685 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4686 			return (-1);
4687 		}
4688 	}
4689 
4690 	ASSERT(TTE_IS_VALID(&tte));
4691 	return (TTEBYTES(TTE_CSZ(&tte)));
4692 }
4693 
4694 uint_t
4695 hat_getattr(struct hat *sfmmup, caddr_t addr, uint_t *attr)
4696 {
4697 	tte_t tte;
4698 
4699 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4700 
4701 	if (sfmmup == ksfmmup) {
4702 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4703 			tte.ll = 0;
4704 		}
4705 	} else {
4706 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4707 			tte.ll = 0;
4708 		}
4709 	}
4710 	if (TTE_IS_VALID(&tte)) {
4711 		*attr = sfmmu_ptov_attr(&tte);
4712 		return (0);
4713 	}
4714 	*attr = 0;
4715 	return ((uint_t)0xffffffff);
4716 }
4717 
4718 /*
4719  * Enables more attributes on specified address range (ie. logical OR)
4720  */
4721 void
4722 hat_setattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4723 {
4724 	if (hat->sfmmu_xhat_provider) {
4725 		XHAT_SETATTR(hat, addr, len, attr);
4726 		return;
4727 	} else {
4728 		/*
4729 		 * This must be a CPU HAT. If the address space has
4730 		 * XHATs attached, change attributes for all of them,
4731 		 * just in case
4732 		 */
4733 		ASSERT(hat->sfmmu_as != NULL);
4734 		if (hat->sfmmu_as->a_xhat != NULL)
4735 			xhat_setattr_all(hat->sfmmu_as, addr, len, attr);
4736 	}
4737 
4738 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_SETATTR);
4739 }
4740 
4741 /*
4742  * Assigns attributes to the specified address range.  All the attributes
4743  * are specified.
4744  */
4745 void
4746 hat_chgattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4747 {
4748 	if (hat->sfmmu_xhat_provider) {
4749 		XHAT_CHGATTR(hat, addr, len, attr);
4750 		return;
4751 	} else {
4752 		/*
4753 		 * This must be a CPU HAT. If the address space has
4754 		 * XHATs attached, change attributes for all of them,
4755 		 * just in case
4756 		 */
4757 		ASSERT(hat->sfmmu_as != NULL);
4758 		if (hat->sfmmu_as->a_xhat != NULL)
4759 			xhat_chgattr_all(hat->sfmmu_as, addr, len, attr);
4760 	}
4761 
4762 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CHGATTR);
4763 }
4764 
4765 /*
4766  * Remove attributes on the specified address range (ie. loginal NAND)
4767  */
4768 void
4769 hat_clrattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4770 {
4771 	if (hat->sfmmu_xhat_provider) {
4772 		XHAT_CLRATTR(hat, addr, len, attr);
4773 		return;
4774 	} else {
4775 		/*
4776 		 * This must be a CPU HAT. If the address space has
4777 		 * XHATs attached, change attributes for all of them,
4778 		 * just in case
4779 		 */
4780 		ASSERT(hat->sfmmu_as != NULL);
4781 		if (hat->sfmmu_as->a_xhat != NULL)
4782 			xhat_clrattr_all(hat->sfmmu_as, addr, len, attr);
4783 	}
4784 
4785 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CLRATTR);
4786 }
4787 
4788 /*
4789  * Change attributes on an address range to that specified by attr and mode.
4790  */
4791 static void
4792 sfmmu_chgattr(struct hat *sfmmup, caddr_t addr, size_t len, uint_t attr,
4793 	int mode)
4794 {
4795 	struct hmehash_bucket *hmebp;
4796 	hmeblk_tag hblktag;
4797 	int hmeshift, hashno = 1;
4798 	struct hme_blk *hmeblkp, *list = NULL;
4799 	caddr_t endaddr;
4800 	cpuset_t cpuset;
4801 	demap_range_t dmr;
4802 
4803 	CPUSET_ZERO(cpuset);
4804 
4805 	ASSERT((sfmmup == ksfmmup) ||
4806 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4807 	ASSERT((len & MMU_PAGEOFFSET) == 0);
4808 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
4809 
4810 	if ((attr & PROT_USER) && (mode != SFMMU_CLRATTR) &&
4811 	    ((addr + len) > (caddr_t)USERLIMIT)) {
4812 		panic("user addr %p in kernel space",
4813 		    (void *)addr);
4814 	}
4815 
4816 	endaddr = addr + len;
4817 	hblktag.htag_id = sfmmup;
4818 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4819 	DEMAP_RANGE_INIT(sfmmup, &dmr);
4820 
4821 	while (addr < endaddr) {
4822 		hmeshift = HME_HASH_SHIFT(hashno);
4823 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
4824 		hblktag.htag_rehash = hashno;
4825 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
4826 
4827 		SFMMU_HASH_LOCK(hmebp);
4828 
4829 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
4830 		if (hmeblkp != NULL) {
4831 			ASSERT(!hmeblkp->hblk_shared);
4832 			/*
4833 			 * We've encountered a shadow hmeblk so skip the range
4834 			 * of the next smaller mapping size.
4835 			 */
4836 			if (hmeblkp->hblk_shw_bit) {
4837 				ASSERT(sfmmup != ksfmmup);
4838 				ASSERT(hashno > 1);
4839 				addr = (caddr_t)P2END((uintptr_t)addr,
4840 				    TTEBYTES(hashno - 1));
4841 			} else {
4842 				addr = sfmmu_hblk_chgattr(sfmmup,
4843 				    hmeblkp, addr, endaddr, &dmr, attr, mode);
4844 			}
4845 			SFMMU_HASH_UNLOCK(hmebp);
4846 			hashno = 1;
4847 			continue;
4848 		}
4849 		SFMMU_HASH_UNLOCK(hmebp);
4850 
4851 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
4852 			/*
4853 			 * We have traversed the whole list and rehashed
4854 			 * if necessary without finding the address to chgattr.
4855 			 * This is ok, so we increment the address by the
4856 			 * smallest hmeblk range for kernel mappings or for
4857 			 * user mappings with no large pages, and the largest
4858 			 * hmeblk range, to account for shadow hmeblks, for
4859 			 * user mappings with large pages and continue.
4860 			 */
4861 			if (sfmmup == ksfmmup)
4862 				addr = (caddr_t)P2END((uintptr_t)addr,
4863 				    TTEBYTES(1));
4864 			else
4865 				addr = (caddr_t)P2END((uintptr_t)addr,
4866 				    TTEBYTES(hashno));
4867 			hashno = 1;
4868 		} else {
4869 			hashno++;
4870 		}
4871 	}
4872 
4873 	sfmmu_hblks_list_purge(&list);
4874 	DEMAP_RANGE_FLUSH(&dmr);
4875 	cpuset = sfmmup->sfmmu_cpusran;
4876 	xt_sync(cpuset);
4877 }
4878 
4879 /*
4880  * This function chgattr on a range of addresses in an hmeblk.  It returns the
4881  * next addres that needs to be chgattr.
4882  * It should be called with the hash lock held.
4883  * XXX It should be possible to optimize chgattr by not flushing every time but
4884  * on the other hand:
4885  * 1. do one flush crosscall.
4886  * 2. only flush if we are increasing permissions (make sure this will work)
4887  */
4888 static caddr_t
4889 sfmmu_hblk_chgattr(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
4890 	caddr_t endaddr, demap_range_t *dmrp, uint_t attr, int mode)
4891 {
4892 	tte_t tte, tteattr, tteflags, ttemod;
4893 	struct sf_hment *sfhmep;
4894 	int ttesz;
4895 	struct page *pp = NULL;
4896 	kmutex_t *pml, *pmtx;
4897 	int ret;
4898 	int use_demap_range;
4899 #if defined(SF_ERRATA_57)
4900 	int check_exec;
4901 #endif
4902 
4903 	ASSERT(in_hblk_range(hmeblkp, addr));
4904 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4905 	ASSERT(!hmeblkp->hblk_shared);
4906 
4907 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4908 	ttesz = get_hblk_ttesz(hmeblkp);
4909 
4910 	/*
4911 	 * Flush the current demap region if addresses have been
4912 	 * skipped or the page size doesn't match.
4913 	 */
4914 	use_demap_range = (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp));
4915 	if (use_demap_range) {
4916 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
4917 	} else {
4918 		DEMAP_RANGE_FLUSH(dmrp);
4919 	}
4920 
4921 	tteattr.ll = sfmmu_vtop_attr(attr, mode, &tteflags);
4922 #if defined(SF_ERRATA_57)
4923 	check_exec = (sfmmup != ksfmmup) &&
4924 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
4925 	    TTE_IS_EXECUTABLE(&tteattr);
4926 #endif
4927 	HBLKTOHME(sfhmep, hmeblkp, addr);
4928 	while (addr < endaddr) {
4929 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
4930 		if (TTE_IS_VALID(&tte)) {
4931 			if ((tte.ll & tteflags.ll) == tteattr.ll) {
4932 				/*
4933 				 * if the new attr is the same as old
4934 				 * continue
4935 				 */
4936 				goto next_addr;
4937 			}
4938 			if (!TTE_IS_WRITABLE(&tteattr)) {
4939 				/*
4940 				 * make sure we clear hw modify bit if we
4941 				 * removing write protections
4942 				 */
4943 				tteflags.tte_intlo |= TTE_HWWR_INT;
4944 			}
4945 
4946 			pml = NULL;
4947 			pp = sfhmep->hme_page;
4948 			if (pp) {
4949 				pml = sfmmu_mlist_enter(pp);
4950 			}
4951 
4952 			if (pp != sfhmep->hme_page) {
4953 				/*
4954 				 * tte must have been unloaded.
4955 				 */
4956 				ASSERT(pml);
4957 				sfmmu_mlist_exit(pml);
4958 				continue;
4959 			}
4960 
4961 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
4962 
4963 			ttemod = tte;
4964 			ttemod.ll = (ttemod.ll & ~tteflags.ll) | tteattr.ll;
4965 			ASSERT(TTE_TO_TTEPFN(&ttemod) == TTE_TO_TTEPFN(&tte));
4966 
4967 #if defined(SF_ERRATA_57)
4968 			if (check_exec && addr < errata57_limit)
4969 				ttemod.tte_exec_perm = 0;
4970 #endif
4971 			ret = sfmmu_modifytte_try(&tte, &ttemod,
4972 			    &sfhmep->hme_tte);
4973 
4974 			if (ret < 0) {
4975 				/* tte changed underneath us */
4976 				if (pml) {
4977 					sfmmu_mlist_exit(pml);
4978 				}
4979 				continue;
4980 			}
4981 
4982 			if (tteflags.tte_intlo & TTE_HWWR_INT) {
4983 				/*
4984 				 * need to sync if we are clearing modify bit.
4985 				 */
4986 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
4987 			}
4988 
4989 			if (pp && PP_ISRO(pp)) {
4990 				if (tteattr.tte_intlo & TTE_WRPRM_INT) {
4991 					pmtx = sfmmu_page_enter(pp);
4992 					PP_CLRRO(pp);
4993 					sfmmu_page_exit(pmtx);
4994 				}
4995 			}
4996 
4997 			if (ret > 0 && use_demap_range) {
4998 				DEMAP_RANGE_MARKPG(dmrp, addr);
4999 			} else if (ret > 0) {
5000 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
5001 			}
5002 
5003 			if (pml) {
5004 				sfmmu_mlist_exit(pml);
5005 			}
5006 		}
5007 next_addr:
5008 		addr += TTEBYTES(ttesz);
5009 		sfhmep++;
5010 		DEMAP_RANGE_NEXTPG(dmrp);
5011 	}
5012 	return (addr);
5013 }
5014 
5015 /*
5016  * This routine converts virtual attributes to physical ones.  It will
5017  * update the tteflags field with the tte mask corresponding to the attributes
5018  * affected and it returns the new attributes.  It will also clear the modify
5019  * bit if we are taking away write permission.  This is necessary since the
5020  * modify bit is the hardware permission bit and we need to clear it in order
5021  * to detect write faults.
5022  */
5023 static uint64_t
5024 sfmmu_vtop_attr(uint_t attr, int mode, tte_t *ttemaskp)
5025 {
5026 	tte_t ttevalue;
5027 
5028 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
5029 
5030 	switch (mode) {
5031 	case SFMMU_CHGATTR:
5032 		/* all attributes specified */
5033 		ttevalue.tte_inthi = MAKE_TTEATTR_INTHI(attr);
5034 		ttevalue.tte_intlo = MAKE_TTEATTR_INTLO(attr);
5035 		ttemaskp->tte_inthi = TTEINTHI_ATTR;
5036 		ttemaskp->tte_intlo = TTEINTLO_ATTR;
5037 		break;
5038 	case SFMMU_SETATTR:
5039 		ASSERT(!(attr & ~HAT_PROT_MASK));
5040 		ttemaskp->ll = 0;
5041 		ttevalue.ll = 0;
5042 		/*
5043 		 * a valid tte implies exec and read for sfmmu
5044 		 * so no need to do anything about them.
5045 		 * since priviledged access implies user access
5046 		 * PROT_USER doesn't make sense either.
5047 		 */
5048 		if (attr & PROT_WRITE) {
5049 			ttemaskp->tte_intlo |= TTE_WRPRM_INT;
5050 			ttevalue.tte_intlo |= TTE_WRPRM_INT;
5051 		}
5052 		break;
5053 	case SFMMU_CLRATTR:
5054 		/* attributes will be nand with current ones */
5055 		if (attr & ~(PROT_WRITE | PROT_USER)) {
5056 			panic("sfmmu: attr %x not supported", attr);
5057 		}
5058 		ttemaskp->ll = 0;
5059 		ttevalue.ll = 0;
5060 		if (attr & PROT_WRITE) {
5061 			/* clear both writable and modify bit */
5062 			ttemaskp->tte_intlo |= TTE_WRPRM_INT | TTE_HWWR_INT;
5063 		}
5064 		if (attr & PROT_USER) {
5065 			ttemaskp->tte_intlo |= TTE_PRIV_INT;
5066 			ttevalue.tte_intlo |= TTE_PRIV_INT;
5067 		}
5068 		break;
5069 	default:
5070 		panic("sfmmu_vtop_attr: bad mode %x", mode);
5071 	}
5072 	ASSERT(TTE_TO_TTEPFN(&ttevalue) == 0);
5073 	return (ttevalue.ll);
5074 }
5075 
5076 static uint_t
5077 sfmmu_ptov_attr(tte_t *ttep)
5078 {
5079 	uint_t attr;
5080 
5081 	ASSERT(TTE_IS_VALID(ttep));
5082 
5083 	attr = PROT_READ;
5084 
5085 	if (TTE_IS_WRITABLE(ttep)) {
5086 		attr |= PROT_WRITE;
5087 	}
5088 	if (TTE_IS_EXECUTABLE(ttep)) {
5089 		attr |= PROT_EXEC;
5090 	}
5091 	if (!TTE_IS_PRIVILEGED(ttep)) {
5092 		attr |= PROT_USER;
5093 	}
5094 	if (TTE_IS_NFO(ttep)) {
5095 		attr |= HAT_NOFAULT;
5096 	}
5097 	if (TTE_IS_NOSYNC(ttep)) {
5098 		attr |= HAT_NOSYNC;
5099 	}
5100 	if (TTE_IS_SIDEFFECT(ttep)) {
5101 		attr |= SFMMU_SIDEFFECT;
5102 	}
5103 	if (!TTE_IS_VCACHEABLE(ttep)) {
5104 		attr |= SFMMU_UNCACHEVTTE;
5105 	}
5106 	if (!TTE_IS_PCACHEABLE(ttep)) {
5107 		attr |= SFMMU_UNCACHEPTTE;
5108 	}
5109 	return (attr);
5110 }
5111 
5112 /*
5113  * hat_chgprot is a deprecated hat call.  New segment drivers
5114  * should store all attributes and use hat_*attr calls.
5115  *
5116  * Change the protections in the virtual address range
5117  * given to the specified virtual protection.  If vprot is ~PROT_WRITE,
5118  * then remove write permission, leaving the other
5119  * permissions unchanged.  If vprot is ~PROT_USER, remove user permissions.
5120  *
5121  */
5122 void
5123 hat_chgprot(struct hat *sfmmup, caddr_t addr, size_t len, uint_t vprot)
5124 {
5125 	struct hmehash_bucket *hmebp;
5126 	hmeblk_tag hblktag;
5127 	int hmeshift, hashno = 1;
5128 	struct hme_blk *hmeblkp, *list = NULL;
5129 	caddr_t endaddr;
5130 	cpuset_t cpuset;
5131 	demap_range_t dmr;
5132 
5133 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5134 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
5135 
5136 	if (sfmmup->sfmmu_xhat_provider) {
5137 		XHAT_CHGPROT(sfmmup, addr, len, vprot);
5138 		return;
5139 	} else {
5140 		/*
5141 		 * This must be a CPU HAT. If the address space has
5142 		 * XHATs attached, change attributes for all of them,
5143 		 * just in case
5144 		 */
5145 		ASSERT(sfmmup->sfmmu_as != NULL);
5146 		if (sfmmup->sfmmu_as->a_xhat != NULL)
5147 			xhat_chgprot_all(sfmmup->sfmmu_as, addr, len, vprot);
5148 	}
5149 
5150 	CPUSET_ZERO(cpuset);
5151 
5152 	if ((vprot != (uint_t)~PROT_WRITE) && (vprot & PROT_USER) &&
5153 	    ((addr + len) > (caddr_t)USERLIMIT)) {
5154 		panic("user addr %p vprot %x in kernel space",
5155 		    (void *)addr, vprot);
5156 	}
5157 	endaddr = addr + len;
5158 	hblktag.htag_id = sfmmup;
5159 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5160 	DEMAP_RANGE_INIT(sfmmup, &dmr);
5161 
5162 	while (addr < endaddr) {
5163 		hmeshift = HME_HASH_SHIFT(hashno);
5164 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5165 		hblktag.htag_rehash = hashno;
5166 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5167 
5168 		SFMMU_HASH_LOCK(hmebp);
5169 
5170 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
5171 		if (hmeblkp != NULL) {
5172 			ASSERT(!hmeblkp->hblk_shared);
5173 			/*
5174 			 * We've encountered a shadow hmeblk so skip the range
5175 			 * of the next smaller mapping size.
5176 			 */
5177 			if (hmeblkp->hblk_shw_bit) {
5178 				ASSERT(sfmmup != ksfmmup);
5179 				ASSERT(hashno > 1);
5180 				addr = (caddr_t)P2END((uintptr_t)addr,
5181 				    TTEBYTES(hashno - 1));
5182 			} else {
5183 				addr = sfmmu_hblk_chgprot(sfmmup, hmeblkp,
5184 				    addr, endaddr, &dmr, vprot);
5185 			}
5186 			SFMMU_HASH_UNLOCK(hmebp);
5187 			hashno = 1;
5188 			continue;
5189 		}
5190 		SFMMU_HASH_UNLOCK(hmebp);
5191 
5192 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
5193 			/*
5194 			 * We have traversed the whole list and rehashed
5195 			 * if necessary without finding the address to chgprot.
5196 			 * This is ok so we increment the address by the
5197 			 * smallest hmeblk range for kernel mappings and the
5198 			 * largest hmeblk range, to account for shadow hmeblks,
5199 			 * for user mappings and continue.
5200 			 */
5201 			if (sfmmup == ksfmmup)
5202 				addr = (caddr_t)P2END((uintptr_t)addr,
5203 				    TTEBYTES(1));
5204 			else
5205 				addr = (caddr_t)P2END((uintptr_t)addr,
5206 				    TTEBYTES(hashno));
5207 			hashno = 1;
5208 		} else {
5209 			hashno++;
5210 		}
5211 	}
5212 
5213 	sfmmu_hblks_list_purge(&list);
5214 	DEMAP_RANGE_FLUSH(&dmr);
5215 	cpuset = sfmmup->sfmmu_cpusran;
5216 	xt_sync(cpuset);
5217 }
5218 
5219 /*
5220  * This function chgprots a range of addresses in an hmeblk.  It returns the
5221  * next addres that needs to be chgprot.
5222  * It should be called with the hash lock held.
5223  * XXX It shold be possible to optimize chgprot by not flushing every time but
5224  * on the other hand:
5225  * 1. do one flush crosscall.
5226  * 2. only flush if we are increasing permissions (make sure this will work)
5227  */
5228 static caddr_t
5229 sfmmu_hblk_chgprot(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5230 	caddr_t endaddr, demap_range_t *dmrp, uint_t vprot)
5231 {
5232 	uint_t pprot;
5233 	tte_t tte, ttemod;
5234 	struct sf_hment *sfhmep;
5235 	uint_t tteflags;
5236 	int ttesz;
5237 	struct page *pp = NULL;
5238 	kmutex_t *pml, *pmtx;
5239 	int ret;
5240 	int use_demap_range;
5241 #if defined(SF_ERRATA_57)
5242 	int check_exec;
5243 #endif
5244 
5245 	ASSERT(in_hblk_range(hmeblkp, addr));
5246 	ASSERT(hmeblkp->hblk_shw_bit == 0);
5247 	ASSERT(!hmeblkp->hblk_shared);
5248 
5249 #ifdef DEBUG
5250 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5251 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5252 		panic("sfmmu_hblk_chgprot: partial chgprot of large page");
5253 	}
5254 #endif /* DEBUG */
5255 
5256 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5257 	ttesz = get_hblk_ttesz(hmeblkp);
5258 
5259 	pprot = sfmmu_vtop_prot(vprot, &tteflags);
5260 #if defined(SF_ERRATA_57)
5261 	check_exec = (sfmmup != ksfmmup) &&
5262 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
5263 	    ((vprot & PROT_EXEC) == PROT_EXEC);
5264 #endif
5265 	HBLKTOHME(sfhmep, hmeblkp, addr);
5266 
5267 	/*
5268 	 * Flush the current demap region if addresses have been
5269 	 * skipped or the page size doesn't match.
5270 	 */
5271 	use_demap_range = (TTEBYTES(ttesz) == MMU_PAGESIZE);
5272 	if (use_demap_range) {
5273 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5274 	} else {
5275 		DEMAP_RANGE_FLUSH(dmrp);
5276 	}
5277 
5278 	while (addr < endaddr) {
5279 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5280 		if (TTE_IS_VALID(&tte)) {
5281 			if (TTE_GET_LOFLAGS(&tte, tteflags) == pprot) {
5282 				/*
5283 				 * if the new protection is the same as old
5284 				 * continue
5285 				 */
5286 				goto next_addr;
5287 			}
5288 			pml = NULL;
5289 			pp = sfhmep->hme_page;
5290 			if (pp) {
5291 				pml = sfmmu_mlist_enter(pp);
5292 			}
5293 			if (pp != sfhmep->hme_page) {
5294 				/*
5295 				 * tte most have been unloaded
5296 				 * underneath us.  Recheck
5297 				 */
5298 				ASSERT(pml);
5299 				sfmmu_mlist_exit(pml);
5300 				continue;
5301 			}
5302 
5303 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5304 
5305 			ttemod = tte;
5306 			TTE_SET_LOFLAGS(&ttemod, tteflags, pprot);
5307 #if defined(SF_ERRATA_57)
5308 			if (check_exec && addr < errata57_limit)
5309 				ttemod.tte_exec_perm = 0;
5310 #endif
5311 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5312 			    &sfhmep->hme_tte);
5313 
5314 			if (ret < 0) {
5315 				/* tte changed underneath us */
5316 				if (pml) {
5317 					sfmmu_mlist_exit(pml);
5318 				}
5319 				continue;
5320 			}
5321 
5322 			if (tteflags & TTE_HWWR_INT) {
5323 				/*
5324 				 * need to sync if we are clearing modify bit.
5325 				 */
5326 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
5327 			}
5328 
5329 			if (pp && PP_ISRO(pp)) {
5330 				if (pprot & TTE_WRPRM_INT) {
5331 					pmtx = sfmmu_page_enter(pp);
5332 					PP_CLRRO(pp);
5333 					sfmmu_page_exit(pmtx);
5334 				}
5335 			}
5336 
5337 			if (ret > 0 && use_demap_range) {
5338 				DEMAP_RANGE_MARKPG(dmrp, addr);
5339 			} else if (ret > 0) {
5340 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
5341 			}
5342 
5343 			if (pml) {
5344 				sfmmu_mlist_exit(pml);
5345 			}
5346 		}
5347 next_addr:
5348 		addr += TTEBYTES(ttesz);
5349 		sfhmep++;
5350 		DEMAP_RANGE_NEXTPG(dmrp);
5351 	}
5352 	return (addr);
5353 }
5354 
5355 /*
5356  * This routine is deprecated and should only be used by hat_chgprot.
5357  * The correct routine is sfmmu_vtop_attr.
5358  * This routine converts virtual page protections to physical ones.  It will
5359  * update the tteflags field with the tte mask corresponding to the protections
5360  * affected and it returns the new protections.  It will also clear the modify
5361  * bit if we are taking away write permission.  This is necessary since the
5362  * modify bit is the hardware permission bit and we need to clear it in order
5363  * to detect write faults.
5364  * It accepts the following special protections:
5365  * ~PROT_WRITE = remove write permissions.
5366  * ~PROT_USER = remove user permissions.
5367  */
5368 static uint_t
5369 sfmmu_vtop_prot(uint_t vprot, uint_t *tteflagsp)
5370 {
5371 	if (vprot == (uint_t)~PROT_WRITE) {
5372 		*tteflagsp = TTE_WRPRM_INT | TTE_HWWR_INT;
5373 		return (0);		/* will cause wrprm to be cleared */
5374 	}
5375 	if (vprot == (uint_t)~PROT_USER) {
5376 		*tteflagsp = TTE_PRIV_INT;
5377 		return (0);		/* will cause privprm to be cleared */
5378 	}
5379 	if ((vprot == 0) || (vprot == PROT_USER) ||
5380 	    ((vprot & PROT_ALL) != vprot)) {
5381 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5382 	}
5383 
5384 	switch (vprot) {
5385 	case (PROT_READ):
5386 	case (PROT_EXEC):
5387 	case (PROT_EXEC | PROT_READ):
5388 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5389 		return (TTE_PRIV_INT); 		/* set prv and clr wrt */
5390 	case (PROT_WRITE):
5391 	case (PROT_WRITE | PROT_READ):
5392 	case (PROT_EXEC | PROT_WRITE):
5393 	case (PROT_EXEC | PROT_WRITE | PROT_READ):
5394 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5395 		return (TTE_PRIV_INT | TTE_WRPRM_INT); 	/* set prv and wrt */
5396 	case (PROT_USER | PROT_READ):
5397 	case (PROT_USER | PROT_EXEC):
5398 	case (PROT_USER | PROT_EXEC | PROT_READ):
5399 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5400 		return (0); 			/* clr prv and wrt */
5401 	case (PROT_USER | PROT_WRITE):
5402 	case (PROT_USER | PROT_WRITE | PROT_READ):
5403 	case (PROT_USER | PROT_EXEC | PROT_WRITE):
5404 	case (PROT_USER | PROT_EXEC | PROT_WRITE | PROT_READ):
5405 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5406 		return (TTE_WRPRM_INT); 	/* clr prv and set wrt */
5407 	default:
5408 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5409 	}
5410 	return (0);
5411 }
5412 
5413 /*
5414  * Alternate unload for very large virtual ranges. With a true 64 bit VA,
5415  * the normal algorithm would take too long for a very large VA range with
5416  * few real mappings. This routine just walks thru all HMEs in the global
5417  * hash table to find and remove mappings.
5418  */
5419 static void
5420 hat_unload_large_virtual(
5421 	struct hat		*sfmmup,
5422 	caddr_t			startaddr,
5423 	size_t			len,
5424 	uint_t			flags,
5425 	hat_callback_t		*callback)
5426 {
5427 	struct hmehash_bucket *hmebp;
5428 	struct hme_blk *hmeblkp;
5429 	struct hme_blk *pr_hblk = NULL;
5430 	struct hme_blk *nx_hblk;
5431 	struct hme_blk *list = NULL;
5432 	int i;
5433 	uint64_t hblkpa, prevpa, nx_pa;
5434 	demap_range_t dmr, *dmrp;
5435 	cpuset_t cpuset;
5436 	caddr_t	endaddr = startaddr + len;
5437 	caddr_t	sa;
5438 	caddr_t	ea;
5439 	caddr_t	cb_sa[MAX_CB_ADDR];
5440 	caddr_t	cb_ea[MAX_CB_ADDR];
5441 	int	addr_cnt = 0;
5442 	int	a = 0;
5443 
5444 	if (sfmmup->sfmmu_free) {
5445 		dmrp = NULL;
5446 	} else {
5447 		dmrp = &dmr;
5448 		DEMAP_RANGE_INIT(sfmmup, dmrp);
5449 	}
5450 
5451 	/*
5452 	 * Loop through all the hash buckets of HME blocks looking for matches.
5453 	 */
5454 	for (i = 0; i <= UHMEHASH_SZ; i++) {
5455 		hmebp = &uhme_hash[i];
5456 		SFMMU_HASH_LOCK(hmebp);
5457 		hmeblkp = hmebp->hmeblkp;
5458 		hblkpa = hmebp->hmeh_nextpa;
5459 		prevpa = 0;
5460 		pr_hblk = NULL;
5461 		while (hmeblkp) {
5462 			nx_hblk = hmeblkp->hblk_next;
5463 			nx_pa = hmeblkp->hblk_nextpa;
5464 
5465 			/*
5466 			 * skip if not this context, if a shadow block or
5467 			 * if the mapping is not in the requested range
5468 			 */
5469 			if (hmeblkp->hblk_tag.htag_id != sfmmup ||
5470 			    hmeblkp->hblk_shw_bit ||
5471 			    (sa = (caddr_t)get_hblk_base(hmeblkp)) >= endaddr ||
5472 			    (ea = get_hblk_endaddr(hmeblkp)) <= startaddr) {
5473 				pr_hblk = hmeblkp;
5474 				prevpa = hblkpa;
5475 				goto next_block;
5476 			}
5477 
5478 			ASSERT(!hmeblkp->hblk_shared);
5479 			/*
5480 			 * unload if there are any current valid mappings
5481 			 */
5482 			if (hmeblkp->hblk_vcnt != 0 ||
5483 			    hmeblkp->hblk_hmecnt != 0)
5484 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
5485 				    sa, ea, dmrp, flags);
5486 
5487 			/*
5488 			 * on unmap we also release the HME block itself, once
5489 			 * all mappings are gone.
5490 			 */
5491 			if ((flags & HAT_UNLOAD_UNMAP) != 0 &&
5492 			    !hmeblkp->hblk_vcnt &&
5493 			    !hmeblkp->hblk_hmecnt) {
5494 				ASSERT(!hmeblkp->hblk_lckcnt);
5495 				sfmmu_hblk_hash_rm(hmebp, hmeblkp,
5496 				    prevpa, pr_hblk);
5497 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
5498 			} else {
5499 				pr_hblk = hmeblkp;
5500 				prevpa = hblkpa;
5501 			}
5502 
5503 			if (callback == NULL)
5504 				goto next_block;
5505 
5506 			/*
5507 			 * HME blocks may span more than one page, but we may be
5508 			 * unmapping only one page, so check for a smaller range
5509 			 * for the callback
5510 			 */
5511 			if (sa < startaddr)
5512 				sa = startaddr;
5513 			if (--ea > endaddr)
5514 				ea = endaddr - 1;
5515 
5516 			cb_sa[addr_cnt] = sa;
5517 			cb_ea[addr_cnt] = ea;
5518 			if (++addr_cnt == MAX_CB_ADDR) {
5519 				if (dmrp != NULL) {
5520 					DEMAP_RANGE_FLUSH(dmrp);
5521 					cpuset = sfmmup->sfmmu_cpusran;
5522 					xt_sync(cpuset);
5523 				}
5524 
5525 				for (a = 0; a < MAX_CB_ADDR; ++a) {
5526 					callback->hcb_start_addr = cb_sa[a];
5527 					callback->hcb_end_addr = cb_ea[a];
5528 					callback->hcb_function(callback);
5529 				}
5530 				addr_cnt = 0;
5531 			}
5532 
5533 next_block:
5534 			hmeblkp = nx_hblk;
5535 			hblkpa = nx_pa;
5536 		}
5537 		SFMMU_HASH_UNLOCK(hmebp);
5538 	}
5539 
5540 	sfmmu_hblks_list_purge(&list);
5541 	if (dmrp != NULL) {
5542 		DEMAP_RANGE_FLUSH(dmrp);
5543 		cpuset = sfmmup->sfmmu_cpusran;
5544 		xt_sync(cpuset);
5545 	}
5546 
5547 	for (a = 0; a < addr_cnt; ++a) {
5548 		callback->hcb_start_addr = cb_sa[a];
5549 		callback->hcb_end_addr = cb_ea[a];
5550 		callback->hcb_function(callback);
5551 	}
5552 
5553 	/*
5554 	 * Check TSB and TLB page sizes if the process isn't exiting.
5555 	 */
5556 	if (!sfmmup->sfmmu_free)
5557 		sfmmu_check_page_sizes(sfmmup, 0);
5558 }
5559 
5560 /*
5561  * Unload all the mappings in the range [addr..addr+len). addr and len must
5562  * be MMU_PAGESIZE aligned.
5563  */
5564 
5565 extern struct seg *segkmap;
5566 #define	ISSEGKMAP(sfmmup, addr) (sfmmup == ksfmmup && \
5567 segkmap->s_base <= (addr) && (addr) < (segkmap->s_base + segkmap->s_size))
5568 
5569 
5570 void
5571 hat_unload_callback(
5572 	struct hat *sfmmup,
5573 	caddr_t addr,
5574 	size_t len,
5575 	uint_t flags,
5576 	hat_callback_t *callback)
5577 {
5578 	struct hmehash_bucket *hmebp;
5579 	hmeblk_tag hblktag;
5580 	int hmeshift, hashno, iskernel;
5581 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
5582 	caddr_t endaddr;
5583 	cpuset_t cpuset;
5584 	uint64_t hblkpa, prevpa;
5585 	int addr_count = 0;
5586 	int a;
5587 	caddr_t cb_start_addr[MAX_CB_ADDR];
5588 	caddr_t cb_end_addr[MAX_CB_ADDR];
5589 	int issegkmap = ISSEGKMAP(sfmmup, addr);
5590 	demap_range_t dmr, *dmrp;
5591 
5592 	if (sfmmup->sfmmu_xhat_provider) {
5593 		XHAT_UNLOAD_CALLBACK(sfmmup, addr, len, flags, callback);
5594 		return;
5595 	} else {
5596 		/*
5597 		 * This must be a CPU HAT. If the address space has
5598 		 * XHATs attached, unload the mappings for all of them,
5599 		 * just in case
5600 		 */
5601 		ASSERT(sfmmup->sfmmu_as != NULL);
5602 		if (sfmmup->sfmmu_as->a_xhat != NULL)
5603 			xhat_unload_callback_all(sfmmup->sfmmu_as, addr,
5604 			    len, flags, callback);
5605 	}
5606 
5607 	ASSERT((sfmmup == ksfmmup) || (flags & HAT_UNLOAD_OTHER) || \
5608 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
5609 
5610 	ASSERT(sfmmup != NULL);
5611 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5612 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
5613 
5614 	/*
5615 	 * Probing through a large VA range (say 63 bits) will be slow, even
5616 	 * at 4 Meg steps between the probes. So, when the virtual address range
5617 	 * is very large, search the HME entries for what to unload.
5618 	 *
5619 	 *	len >> TTE_PAGE_SHIFT(TTE4M) is the # of 4Meg probes we'd need
5620 	 *
5621 	 *	UHMEHASH_SZ is number of hash buckets to examine
5622 	 *
5623 	 */
5624 	if (sfmmup != KHATID && (len >> TTE_PAGE_SHIFT(TTE4M)) > UHMEHASH_SZ) {
5625 		hat_unload_large_virtual(sfmmup, addr, len, flags, callback);
5626 		return;
5627 	}
5628 
5629 	CPUSET_ZERO(cpuset);
5630 
5631 	/*
5632 	 * If the process is exiting, we can save a lot of fuss since
5633 	 * we'll flush the TLB when we free the ctx anyway.
5634 	 */
5635 	if (sfmmup->sfmmu_free)
5636 		dmrp = NULL;
5637 	else
5638 		dmrp = &dmr;
5639 
5640 	DEMAP_RANGE_INIT(sfmmup, dmrp);
5641 	endaddr = addr + len;
5642 	hblktag.htag_id = sfmmup;
5643 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5644 
5645 	/*
5646 	 * It is likely for the vm to call unload over a wide range of
5647 	 * addresses that are actually very sparsely populated by
5648 	 * translations.  In order to speed this up the sfmmu hat supports
5649 	 * the concept of shadow hmeblks. Dummy large page hmeblks that
5650 	 * correspond to actual small translations are allocated at tteload
5651 	 * time and are referred to as shadow hmeblks.  Now, during unload
5652 	 * time, we first check if we have a shadow hmeblk for that
5653 	 * translation.  The absence of one means the corresponding address
5654 	 * range is empty and can be skipped.
5655 	 *
5656 	 * The kernel is an exception to above statement and that is why
5657 	 * we don't use shadow hmeblks and hash starting from the smallest
5658 	 * page size.
5659 	 */
5660 	if (sfmmup == KHATID) {
5661 		iskernel = 1;
5662 		hashno = TTE64K;
5663 	} else {
5664 		iskernel = 0;
5665 		if (mmu_page_sizes == max_mmu_page_sizes) {
5666 			hashno = TTE256M;
5667 		} else {
5668 			hashno = TTE4M;
5669 		}
5670 	}
5671 	while (addr < endaddr) {
5672 		hmeshift = HME_HASH_SHIFT(hashno);
5673 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5674 		hblktag.htag_rehash = hashno;
5675 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5676 
5677 		SFMMU_HASH_LOCK(hmebp);
5678 
5679 		HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa, pr_hblk,
5680 		    prevpa, &list);
5681 		if (hmeblkp == NULL) {
5682 			/*
5683 			 * didn't find an hmeblk. skip the appropiate
5684 			 * address range.
5685 			 */
5686 			SFMMU_HASH_UNLOCK(hmebp);
5687 			if (iskernel) {
5688 				if (hashno < mmu_hashcnt) {
5689 					hashno++;
5690 					continue;
5691 				} else {
5692 					hashno = TTE64K;
5693 					addr = (caddr_t)roundup((uintptr_t)addr
5694 					    + 1, MMU_PAGESIZE64K);
5695 					continue;
5696 				}
5697 			}
5698 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5699 			    (1 << hmeshift));
5700 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5701 				ASSERT(hashno == TTE64K);
5702 				continue;
5703 			}
5704 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5705 				hashno = TTE512K;
5706 				continue;
5707 			}
5708 			if (mmu_page_sizes == max_mmu_page_sizes) {
5709 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5710 					hashno = TTE4M;
5711 					continue;
5712 				}
5713 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5714 					hashno = TTE32M;
5715 					continue;
5716 				}
5717 				hashno = TTE256M;
5718 				continue;
5719 			} else {
5720 				hashno = TTE4M;
5721 				continue;
5722 			}
5723 		}
5724 		ASSERT(hmeblkp);
5725 		ASSERT(!hmeblkp->hblk_shared);
5726 		if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5727 			/*
5728 			 * If the valid count is zero we can skip the range
5729 			 * mapped by this hmeblk.
5730 			 * We free hblks in the case of HAT_UNMAP.  HAT_UNMAP
5731 			 * is used by segment drivers as a hint
5732 			 * that the mapping resource won't be used any longer.
5733 			 * The best example of this is during exit().
5734 			 */
5735 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5736 			    get_hblk_span(hmeblkp));
5737 			if ((flags & HAT_UNLOAD_UNMAP) ||
5738 			    (iskernel && !issegkmap)) {
5739 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa,
5740 				    pr_hblk);
5741 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
5742 			}
5743 			SFMMU_HASH_UNLOCK(hmebp);
5744 
5745 			if (iskernel) {
5746 				hashno = TTE64K;
5747 				continue;
5748 			}
5749 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5750 				ASSERT(hashno == TTE64K);
5751 				continue;
5752 			}
5753 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5754 				hashno = TTE512K;
5755 				continue;
5756 			}
5757 			if (mmu_page_sizes == max_mmu_page_sizes) {
5758 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5759 					hashno = TTE4M;
5760 					continue;
5761 				}
5762 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5763 					hashno = TTE32M;
5764 					continue;
5765 				}
5766 				hashno = TTE256M;
5767 				continue;
5768 			} else {
5769 				hashno = TTE4M;
5770 				continue;
5771 			}
5772 		}
5773 		if (hmeblkp->hblk_shw_bit) {
5774 			/*
5775 			 * If we encounter a shadow hmeblk we know there is
5776 			 * smaller sized hmeblks mapping the same address space.
5777 			 * Decrement the hash size and rehash.
5778 			 */
5779 			ASSERT(sfmmup != KHATID);
5780 			hashno--;
5781 			SFMMU_HASH_UNLOCK(hmebp);
5782 			continue;
5783 		}
5784 
5785 		/*
5786 		 * track callback address ranges.
5787 		 * only start a new range when it's not contiguous
5788 		 */
5789 		if (callback != NULL) {
5790 			if (addr_count > 0 &&
5791 			    addr == cb_end_addr[addr_count - 1])
5792 				--addr_count;
5793 			else
5794 				cb_start_addr[addr_count] = addr;
5795 		}
5796 
5797 		addr = sfmmu_hblk_unload(sfmmup, hmeblkp, addr, endaddr,
5798 		    dmrp, flags);
5799 
5800 		if (callback != NULL)
5801 			cb_end_addr[addr_count++] = addr;
5802 
5803 		if (((flags & HAT_UNLOAD_UNMAP) || (iskernel && !issegkmap)) &&
5804 		    !hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5805 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa,
5806 			    pr_hblk);
5807 			sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
5808 		}
5809 		SFMMU_HASH_UNLOCK(hmebp);
5810 
5811 		/*
5812 		 * Notify our caller as to exactly which pages
5813 		 * have been unloaded. We do these in clumps,
5814 		 * to minimize the number of xt_sync()s that need to occur.
5815 		 */
5816 		if (callback != NULL && addr_count == MAX_CB_ADDR) {
5817 			DEMAP_RANGE_FLUSH(dmrp);
5818 			if (dmrp != NULL) {
5819 				cpuset = sfmmup->sfmmu_cpusran;
5820 				xt_sync(cpuset);
5821 			}
5822 
5823 			for (a = 0; a < MAX_CB_ADDR; ++a) {
5824 				callback->hcb_start_addr = cb_start_addr[a];
5825 				callback->hcb_end_addr = cb_end_addr[a];
5826 				callback->hcb_function(callback);
5827 			}
5828 			addr_count = 0;
5829 		}
5830 		if (iskernel) {
5831 			hashno = TTE64K;
5832 			continue;
5833 		}
5834 		if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5835 			ASSERT(hashno == TTE64K);
5836 			continue;
5837 		}
5838 		if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5839 			hashno = TTE512K;
5840 			continue;
5841 		}
5842 		if (mmu_page_sizes == max_mmu_page_sizes) {
5843 			if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5844 				hashno = TTE4M;
5845 				continue;
5846 			}
5847 			if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5848 				hashno = TTE32M;
5849 				continue;
5850 			}
5851 			hashno = TTE256M;
5852 		} else {
5853 			hashno = TTE4M;
5854 		}
5855 	}
5856 
5857 	sfmmu_hblks_list_purge(&list);
5858 	DEMAP_RANGE_FLUSH(dmrp);
5859 	if (dmrp != NULL) {
5860 		cpuset = sfmmup->sfmmu_cpusran;
5861 		xt_sync(cpuset);
5862 	}
5863 	if (callback && addr_count != 0) {
5864 		for (a = 0; a < addr_count; ++a) {
5865 			callback->hcb_start_addr = cb_start_addr[a];
5866 			callback->hcb_end_addr = cb_end_addr[a];
5867 			callback->hcb_function(callback);
5868 		}
5869 	}
5870 
5871 	/*
5872 	 * Check TSB and TLB page sizes if the process isn't exiting.
5873 	 */
5874 	if (!sfmmup->sfmmu_free)
5875 		sfmmu_check_page_sizes(sfmmup, 0);
5876 }
5877 
5878 /*
5879  * Unload all the mappings in the range [addr..addr+len). addr and len must
5880  * be MMU_PAGESIZE aligned.
5881  */
5882 void
5883 hat_unload(struct hat *sfmmup, caddr_t addr, size_t len, uint_t flags)
5884 {
5885 	if (sfmmup->sfmmu_xhat_provider) {
5886 		XHAT_UNLOAD(sfmmup, addr, len, flags);
5887 		return;
5888 	}
5889 	hat_unload_callback(sfmmup, addr, len, flags, NULL);
5890 }
5891 
5892 
5893 /*
5894  * Find the largest mapping size for this page.
5895  */
5896 int
5897 fnd_mapping_sz(page_t *pp)
5898 {
5899 	int sz;
5900 	int p_index;
5901 
5902 	p_index = PP_MAPINDEX(pp);
5903 
5904 	sz = 0;
5905 	p_index >>= 1;	/* don't care about 8K bit */
5906 	for (; p_index; p_index >>= 1) {
5907 		sz++;
5908 	}
5909 
5910 	return (sz);
5911 }
5912 
5913 /*
5914  * This function unloads a range of addresses for an hmeblk.
5915  * It returns the next address to be unloaded.
5916  * It should be called with the hash lock held.
5917  */
5918 static caddr_t
5919 sfmmu_hblk_unload(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5920 	caddr_t endaddr, demap_range_t *dmrp, uint_t flags)
5921 {
5922 	tte_t	tte, ttemod;
5923 	struct	sf_hment *sfhmep;
5924 	int	ttesz;
5925 	long	ttecnt;
5926 	page_t *pp;
5927 	kmutex_t *pml;
5928 	int ret;
5929 	int use_demap_range;
5930 
5931 	ASSERT(in_hblk_range(hmeblkp, addr));
5932 	ASSERT(!hmeblkp->hblk_shw_bit);
5933 	ASSERT(sfmmup != NULL || hmeblkp->hblk_shared);
5934 	ASSERT(sfmmup == NULL || !hmeblkp->hblk_shared);
5935 	ASSERT(dmrp == NULL || !hmeblkp->hblk_shared);
5936 
5937 #ifdef DEBUG
5938 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5939 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5940 		panic("sfmmu_hblk_unload: partial unload of large page");
5941 	}
5942 #endif /* DEBUG */
5943 
5944 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5945 	ttesz = get_hblk_ttesz(hmeblkp);
5946 
5947 	use_demap_range = ((dmrp == NULL) ||
5948 	    (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp)));
5949 
5950 	if (use_demap_range) {
5951 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5952 	} else {
5953 		DEMAP_RANGE_FLUSH(dmrp);
5954 	}
5955 	ttecnt = 0;
5956 	HBLKTOHME(sfhmep, hmeblkp, addr);
5957 
5958 	while (addr < endaddr) {
5959 		pml = NULL;
5960 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5961 		if (TTE_IS_VALID(&tte)) {
5962 			pp = sfhmep->hme_page;
5963 			if (pp != NULL) {
5964 				pml = sfmmu_mlist_enter(pp);
5965 			}
5966 
5967 			/*
5968 			 * Verify if hme still points to 'pp' now that
5969 			 * we have p_mapping lock.
5970 			 */
5971 			if (sfhmep->hme_page != pp) {
5972 				if (pp != NULL && sfhmep->hme_page != NULL) {
5973 					ASSERT(pml != NULL);
5974 					sfmmu_mlist_exit(pml);
5975 					/* Re-start this iteration. */
5976 					continue;
5977 				}
5978 				ASSERT((pp != NULL) &&
5979 				    (sfhmep->hme_page == NULL));
5980 				goto tte_unloaded;
5981 			}
5982 
5983 			/*
5984 			 * This point on we have both HASH and p_mapping
5985 			 * lock.
5986 			 */
5987 			ASSERT(pp == sfhmep->hme_page);
5988 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5989 
5990 			/*
5991 			 * We need to loop on modify tte because it is
5992 			 * possible for pagesync to come along and
5993 			 * change the software bits beneath us.
5994 			 *
5995 			 * Page_unload can also invalidate the tte after
5996 			 * we read tte outside of p_mapping lock.
5997 			 */
5998 again:
5999 			ttemod = tte;
6000 
6001 			TTE_SET_INVALID(&ttemod);
6002 			ret = sfmmu_modifytte_try(&tte, &ttemod,
6003 			    &sfhmep->hme_tte);
6004 
6005 			if (ret <= 0) {
6006 				if (TTE_IS_VALID(&tte)) {
6007 					ASSERT(ret < 0);
6008 					goto again;
6009 				}
6010 				if (pp != NULL) {
6011 					panic("sfmmu_hblk_unload: pp = 0x%p "
6012 					    "tte became invalid under mlist"
6013 					    " lock = 0x%p", (void *)pp,
6014 					    (void *)pml);
6015 				}
6016 				continue;
6017 			}
6018 
6019 			if (!(flags & HAT_UNLOAD_NOSYNC)) {
6020 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
6021 			}
6022 
6023 			/*
6024 			 * Ok- we invalidated the tte. Do the rest of the job.
6025 			 */
6026 			ttecnt++;
6027 
6028 			if (flags & HAT_UNLOAD_UNLOCK) {
6029 				ASSERT(hmeblkp->hblk_lckcnt > 0);
6030 				atomic_add_32(&hmeblkp->hblk_lckcnt, -1);
6031 				HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
6032 			}
6033 
6034 			/*
6035 			 * Normally we would need to flush the page
6036 			 * from the virtual cache at this point in
6037 			 * order to prevent a potential cache alias
6038 			 * inconsistency.
6039 			 * The particular scenario we need to worry
6040 			 * about is:
6041 			 * Given:  va1 and va2 are two virtual address
6042 			 * that alias and map the same physical
6043 			 * address.
6044 			 * 1.   mapping exists from va1 to pa and data
6045 			 * has been read into the cache.
6046 			 * 2.   unload va1.
6047 			 * 3.   load va2 and modify data using va2.
6048 			 * 4    unload va2.
6049 			 * 5.   load va1 and reference data.  Unless we
6050 			 * flush the data cache when we unload we will
6051 			 * get stale data.
6052 			 * Fortunately, page coloring eliminates the
6053 			 * above scenario by remembering the color a
6054 			 * physical page was last or is currently
6055 			 * mapped to.  Now, we delay the flush until
6056 			 * the loading of translations.  Only when the
6057 			 * new translation is of a different color
6058 			 * are we forced to flush.
6059 			 */
6060 			if (use_demap_range) {
6061 				/*
6062 				 * Mark this page as needing a demap.
6063 				 */
6064 				DEMAP_RANGE_MARKPG(dmrp, addr);
6065 			} else {
6066 				ASSERT(sfmmup != NULL);
6067 				ASSERT(!hmeblkp->hblk_shared);
6068 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
6069 				    sfmmup->sfmmu_free, 0);
6070 			}
6071 
6072 			if (pp) {
6073 				/*
6074 				 * Remove the hment from the mapping list
6075 				 */
6076 				ASSERT(hmeblkp->hblk_hmecnt > 0);
6077 
6078 				/*
6079 				 * Again, we cannot
6080 				 * ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS);
6081 				 */
6082 				HME_SUB(sfhmep, pp);
6083 				membar_stst();
6084 				atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
6085 			}
6086 
6087 			ASSERT(hmeblkp->hblk_vcnt > 0);
6088 			atomic_add_16(&hmeblkp->hblk_vcnt, -1);
6089 
6090 			ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
6091 			    !hmeblkp->hblk_lckcnt);
6092 
6093 #ifdef VAC
6094 			if (pp && (pp->p_nrm & (P_KPMC | P_KPMS | P_TNC))) {
6095 				if (PP_ISTNC(pp)) {
6096 					/*
6097 					 * If page was temporary
6098 					 * uncached, try to recache
6099 					 * it. Note that HME_SUB() was
6100 					 * called above so p_index and
6101 					 * mlist had been updated.
6102 					 */
6103 					conv_tnc(pp, ttesz);
6104 				} else if (pp->p_mapping == NULL) {
6105 					ASSERT(kpm_enable);
6106 					/*
6107 					 * Page is marked to be in VAC conflict
6108 					 * to an existing kpm mapping and/or is
6109 					 * kpm mapped using only the regular
6110 					 * pagesize.
6111 					 */
6112 					sfmmu_kpm_hme_unload(pp);
6113 				}
6114 			}
6115 #endif	/* VAC */
6116 		} else if ((pp = sfhmep->hme_page) != NULL) {
6117 				/*
6118 				 * TTE is invalid but the hme
6119 				 * still exists. let pageunload
6120 				 * complete its job.
6121 				 */
6122 				ASSERT(pml == NULL);
6123 				pml = sfmmu_mlist_enter(pp);
6124 				if (sfhmep->hme_page != NULL) {
6125 					sfmmu_mlist_exit(pml);
6126 					continue;
6127 				}
6128 				ASSERT(sfhmep->hme_page == NULL);
6129 		} else if (hmeblkp->hblk_hmecnt != 0) {
6130 			/*
6131 			 * pageunload may have not finished decrementing
6132 			 * hblk_vcnt and hblk_hmecnt. Find page_t if any and
6133 			 * wait for pageunload to finish. Rely on pageunload
6134 			 * to decrement hblk_hmecnt after hblk_vcnt.
6135 			 */
6136 			pfn_t pfn = TTE_TO_TTEPFN(&tte);
6137 			ASSERT(pml == NULL);
6138 			if (pf_is_memory(pfn)) {
6139 				pp = page_numtopp_nolock(pfn);
6140 				if (pp != NULL) {
6141 					pml = sfmmu_mlist_enter(pp);
6142 					sfmmu_mlist_exit(pml);
6143 					pml = NULL;
6144 				}
6145 			}
6146 		}
6147 
6148 tte_unloaded:
6149 		/*
6150 		 * At this point, the tte we are looking at
6151 		 * should be unloaded, and hme has been unlinked
6152 		 * from page too. This is important because in
6153 		 * pageunload, it does ttesync() then HME_SUB.
6154 		 * We need to make sure HME_SUB has been completed
6155 		 * so we know ttesync() has been completed. Otherwise,
6156 		 * at exit time, after return from hat layer, VM will
6157 		 * release as structure which hat_setstat() (called
6158 		 * by ttesync()) needs.
6159 		 */
6160 #ifdef DEBUG
6161 		{
6162 			tte_t	dtte;
6163 
6164 			ASSERT(sfhmep->hme_page == NULL);
6165 
6166 			sfmmu_copytte(&sfhmep->hme_tte, &dtte);
6167 			ASSERT(!TTE_IS_VALID(&dtte));
6168 		}
6169 #endif
6170 
6171 		if (pml) {
6172 			sfmmu_mlist_exit(pml);
6173 		}
6174 
6175 		addr += TTEBYTES(ttesz);
6176 		sfhmep++;
6177 		DEMAP_RANGE_NEXTPG(dmrp);
6178 	}
6179 	/*
6180 	 * For shared hmeblks this routine is only called when region is freed
6181 	 * and no longer referenced.  So no need to decrement ttecnt
6182 	 * in the region structure here.
6183 	 */
6184 	if (ttecnt > 0 && sfmmup != NULL) {
6185 		atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -ttecnt);
6186 	}
6187 	return (addr);
6188 }
6189 
6190 /*
6191  * Synchronize all the mappings in the range [addr..addr+len).
6192  * Can be called with clearflag having two states:
6193  * HAT_SYNC_DONTZERO means just return the rm stats
6194  * HAT_SYNC_ZERORM means zero rm bits in the tte and return the stats
6195  */
6196 void
6197 hat_sync(struct hat *sfmmup, caddr_t addr, size_t len, uint_t clearflag)
6198 {
6199 	struct hmehash_bucket *hmebp;
6200 	hmeblk_tag hblktag;
6201 	int hmeshift, hashno = 1;
6202 	struct hme_blk *hmeblkp, *list = NULL;
6203 	caddr_t endaddr;
6204 	cpuset_t cpuset;
6205 
6206 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
6207 	ASSERT((sfmmup == ksfmmup) ||
6208 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
6209 	ASSERT((len & MMU_PAGEOFFSET) == 0);
6210 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
6211 	    (clearflag == HAT_SYNC_ZERORM));
6212 
6213 	CPUSET_ZERO(cpuset);
6214 
6215 	endaddr = addr + len;
6216 	hblktag.htag_id = sfmmup;
6217 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
6218 
6219 	/*
6220 	 * Spitfire supports 4 page sizes.
6221 	 * Most pages are expected to be of the smallest page
6222 	 * size (8K) and these will not need to be rehashed. 64K
6223 	 * pages also don't need to be rehashed because the an hmeblk
6224 	 * spans 64K of address space. 512K pages might need 1 rehash and
6225 	 * and 4M pages 2 rehashes.
6226 	 */
6227 	while (addr < endaddr) {
6228 		hmeshift = HME_HASH_SHIFT(hashno);
6229 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
6230 		hblktag.htag_rehash = hashno;
6231 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
6232 
6233 		SFMMU_HASH_LOCK(hmebp);
6234 
6235 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
6236 		if (hmeblkp != NULL) {
6237 			ASSERT(!hmeblkp->hblk_shared);
6238 			/*
6239 			 * We've encountered a shadow hmeblk so skip the range
6240 			 * of the next smaller mapping size.
6241 			 */
6242 			if (hmeblkp->hblk_shw_bit) {
6243 				ASSERT(sfmmup != ksfmmup);
6244 				ASSERT(hashno > 1);
6245 				addr = (caddr_t)P2END((uintptr_t)addr,
6246 				    TTEBYTES(hashno - 1));
6247 			} else {
6248 				addr = sfmmu_hblk_sync(sfmmup, hmeblkp,
6249 				    addr, endaddr, clearflag);
6250 			}
6251 			SFMMU_HASH_UNLOCK(hmebp);
6252 			hashno = 1;
6253 			continue;
6254 		}
6255 		SFMMU_HASH_UNLOCK(hmebp);
6256 
6257 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
6258 			/*
6259 			 * We have traversed the whole list and rehashed
6260 			 * if necessary without finding the address to sync.
6261 			 * This is ok so we increment the address by the
6262 			 * smallest hmeblk range for kernel mappings and the
6263 			 * largest hmeblk range, to account for shadow hmeblks,
6264 			 * for user mappings and continue.
6265 			 */
6266 			if (sfmmup == ksfmmup)
6267 				addr = (caddr_t)P2END((uintptr_t)addr,
6268 				    TTEBYTES(1));
6269 			else
6270 				addr = (caddr_t)P2END((uintptr_t)addr,
6271 				    TTEBYTES(hashno));
6272 			hashno = 1;
6273 		} else {
6274 			hashno++;
6275 		}
6276 	}
6277 	sfmmu_hblks_list_purge(&list);
6278 	cpuset = sfmmup->sfmmu_cpusran;
6279 	xt_sync(cpuset);
6280 }
6281 
6282 static caddr_t
6283 sfmmu_hblk_sync(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
6284 	caddr_t endaddr, int clearflag)
6285 {
6286 	tte_t	tte, ttemod;
6287 	struct sf_hment *sfhmep;
6288 	int ttesz;
6289 	struct page *pp;
6290 	kmutex_t *pml;
6291 	int ret;
6292 
6293 	ASSERT(hmeblkp->hblk_shw_bit == 0);
6294 	ASSERT(!hmeblkp->hblk_shared);
6295 
6296 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
6297 
6298 	ttesz = get_hblk_ttesz(hmeblkp);
6299 	HBLKTOHME(sfhmep, hmeblkp, addr);
6300 
6301 	while (addr < endaddr) {
6302 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6303 		if (TTE_IS_VALID(&tte)) {
6304 			pml = NULL;
6305 			pp = sfhmep->hme_page;
6306 			if (pp) {
6307 				pml = sfmmu_mlist_enter(pp);
6308 			}
6309 			if (pp != sfhmep->hme_page) {
6310 				/*
6311 				 * tte most have been unloaded
6312 				 * underneath us.  Recheck
6313 				 */
6314 				ASSERT(pml);
6315 				sfmmu_mlist_exit(pml);
6316 				continue;
6317 			}
6318 
6319 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
6320 
6321 			if (clearflag == HAT_SYNC_ZERORM) {
6322 				ttemod = tte;
6323 				TTE_CLR_RM(&ttemod);
6324 				ret = sfmmu_modifytte_try(&tte, &ttemod,
6325 				    &sfhmep->hme_tte);
6326 				if (ret < 0) {
6327 					if (pml) {
6328 						sfmmu_mlist_exit(pml);
6329 					}
6330 					continue;
6331 				}
6332 
6333 				if (ret > 0) {
6334 					sfmmu_tlb_demap(addr, sfmmup,
6335 					    hmeblkp, 0, 0);
6336 				}
6337 			}
6338 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
6339 			if (pml) {
6340 				sfmmu_mlist_exit(pml);
6341 			}
6342 		}
6343 		addr += TTEBYTES(ttesz);
6344 		sfhmep++;
6345 	}
6346 	return (addr);
6347 }
6348 
6349 /*
6350  * This function will sync a tte to the page struct and it will
6351  * update the hat stats. Currently it allows us to pass a NULL pp
6352  * and we will simply update the stats.  We may want to change this
6353  * so we only keep stats for pages backed by pp's.
6354  */
6355 static void
6356 sfmmu_ttesync(struct hat *sfmmup, caddr_t addr, tte_t *ttep, page_t *pp)
6357 {
6358 	uint_t rm = 0;
6359 	int   	sz;
6360 	pgcnt_t	npgs;
6361 
6362 	ASSERT(TTE_IS_VALID(ttep));
6363 
6364 	if (TTE_IS_NOSYNC(ttep)) {
6365 		return;
6366 	}
6367 
6368 	if (TTE_IS_REF(ttep))  {
6369 		rm = P_REF;
6370 	}
6371 	if (TTE_IS_MOD(ttep))  {
6372 		rm |= P_MOD;
6373 	}
6374 
6375 	if (rm == 0) {
6376 		return;
6377 	}
6378 
6379 	sz = TTE_CSZ(ttep);
6380 	if (sfmmup != NULL && sfmmup->sfmmu_rmstat) {
6381 		int i;
6382 		caddr_t	vaddr = addr;
6383 
6384 		for (i = 0; i < TTEPAGES(sz); i++, vaddr += MMU_PAGESIZE) {
6385 			hat_setstat(sfmmup->sfmmu_as, vaddr, MMU_PAGESIZE, rm);
6386 		}
6387 
6388 	}
6389 
6390 	/*
6391 	 * XXX I want to use cas to update nrm bits but they
6392 	 * currently belong in common/vm and not in hat where
6393 	 * they should be.
6394 	 * The nrm bits are protected by the same mutex as
6395 	 * the one that protects the page's mapping list.
6396 	 */
6397 	if (!pp)
6398 		return;
6399 	ASSERT(sfmmu_mlist_held(pp));
6400 	/*
6401 	 * If the tte is for a large page, we need to sync all the
6402 	 * pages covered by the tte.
6403 	 */
6404 	if (sz != TTE8K) {
6405 		ASSERT(pp->p_szc != 0);
6406 		pp = PP_GROUPLEADER(pp, sz);
6407 		ASSERT(sfmmu_mlist_held(pp));
6408 	}
6409 
6410 	/* Get number of pages from tte size. */
6411 	npgs = TTEPAGES(sz);
6412 
6413 	do {
6414 		ASSERT(pp);
6415 		ASSERT(sfmmu_mlist_held(pp));
6416 		if (((rm & P_REF) != 0 && !PP_ISREF(pp)) ||
6417 		    ((rm & P_MOD) != 0 && !PP_ISMOD(pp)))
6418 			hat_page_setattr(pp, rm);
6419 
6420 		/*
6421 		 * Are we done? If not, we must have a large mapping.
6422 		 * For large mappings we need to sync the rest of the pages
6423 		 * covered by this tte; goto the next page.
6424 		 */
6425 	} while (--npgs > 0 && (pp = PP_PAGENEXT(pp)));
6426 }
6427 
6428 /*
6429  * Execute pre-callback handler of each pa_hment linked to pp
6430  *
6431  * Inputs:
6432  *   flag: either HAT_PRESUSPEND or HAT_SUSPEND.
6433  *   capture_cpus: pointer to return value (below)
6434  *
6435  * Returns:
6436  *   Propagates the subsystem callback return values back to the caller;
6437  *   returns 0 on success.  If capture_cpus is non-NULL, the value returned
6438  *   is zero if all of the pa_hments are of a type that do not require
6439  *   capturing CPUs prior to suspending the mapping, else it is 1.
6440  */
6441 static int
6442 hat_pageprocess_precallbacks(struct page *pp, uint_t flag, int *capture_cpus)
6443 {
6444 	struct sf_hment	*sfhmep;
6445 	struct pa_hment *pahmep;
6446 	int (*f)(caddr_t, uint_t, uint_t, void *);
6447 	int		ret;
6448 	id_t		id;
6449 	int		locked = 0;
6450 	kmutex_t	*pml;
6451 
6452 	ASSERT(PAGE_EXCL(pp));
6453 	if (!sfmmu_mlist_held(pp)) {
6454 		pml = sfmmu_mlist_enter(pp);
6455 		locked = 1;
6456 	}
6457 
6458 	if (capture_cpus)
6459 		*capture_cpus = 0;
6460 
6461 top:
6462 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6463 		/*
6464 		 * skip sf_hments corresponding to VA<->PA mappings;
6465 		 * for pa_hment's, hme_tte.ll is zero
6466 		 */
6467 		if (!IS_PAHME(sfhmep))
6468 			continue;
6469 
6470 		pahmep = sfhmep->hme_data;
6471 		ASSERT(pahmep != NULL);
6472 
6473 		/*
6474 		 * skip if pre-handler has been called earlier in this loop
6475 		 */
6476 		if (pahmep->flags & flag)
6477 			continue;
6478 
6479 		id = pahmep->cb_id;
6480 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6481 		if (capture_cpus && sfmmu_cb_table[id].capture_cpus != 0)
6482 			*capture_cpus = 1;
6483 		if ((f = sfmmu_cb_table[id].prehandler) == NULL) {
6484 			pahmep->flags |= flag;
6485 			continue;
6486 		}
6487 
6488 		/*
6489 		 * Drop the mapping list lock to avoid locking order issues.
6490 		 */
6491 		if (locked)
6492 			sfmmu_mlist_exit(pml);
6493 
6494 		ret = f(pahmep->addr, pahmep->len, flag, pahmep->pvt);
6495 		if (ret != 0)
6496 			return (ret);	/* caller must do the cleanup */
6497 
6498 		if (locked) {
6499 			pml = sfmmu_mlist_enter(pp);
6500 			pahmep->flags |= flag;
6501 			goto top;
6502 		}
6503 
6504 		pahmep->flags |= flag;
6505 	}
6506 
6507 	if (locked)
6508 		sfmmu_mlist_exit(pml);
6509 
6510 	return (0);
6511 }
6512 
6513 /*
6514  * Execute post-callback handler of each pa_hment linked to pp
6515  *
6516  * Same overall assumptions and restrictions apply as for
6517  * hat_pageprocess_precallbacks().
6518  */
6519 static void
6520 hat_pageprocess_postcallbacks(struct page *pp, uint_t flag)
6521 {
6522 	pfn_t pgpfn = pp->p_pagenum;
6523 	pfn_t pgmask = btop(page_get_pagesize(pp->p_szc)) - 1;
6524 	pfn_t newpfn;
6525 	struct sf_hment *sfhmep;
6526 	struct pa_hment *pahmep;
6527 	int (*f)(caddr_t, uint_t, uint_t, void *, pfn_t);
6528 	id_t	id;
6529 	int	locked = 0;
6530 	kmutex_t *pml;
6531 
6532 	ASSERT(PAGE_EXCL(pp));
6533 	if (!sfmmu_mlist_held(pp)) {
6534 		pml = sfmmu_mlist_enter(pp);
6535 		locked = 1;
6536 	}
6537 
6538 top:
6539 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6540 		/*
6541 		 * skip sf_hments corresponding to VA<->PA mappings;
6542 		 * for pa_hment's, hme_tte.ll is zero
6543 		 */
6544 		if (!IS_PAHME(sfhmep))
6545 			continue;
6546 
6547 		pahmep = sfhmep->hme_data;
6548 		ASSERT(pahmep != NULL);
6549 
6550 		if ((pahmep->flags & flag) == 0)
6551 			continue;
6552 
6553 		pahmep->flags &= ~flag;
6554 
6555 		id = pahmep->cb_id;
6556 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6557 		if ((f = sfmmu_cb_table[id].posthandler) == NULL)
6558 			continue;
6559 
6560 		/*
6561 		 * Convert the base page PFN into the constituent PFN
6562 		 * which is needed by the callback handler.
6563 		 */
6564 		newpfn = pgpfn | (btop((uintptr_t)pahmep->addr) & pgmask);
6565 
6566 		/*
6567 		 * Drop the mapping list lock to avoid locking order issues.
6568 		 */
6569 		if (locked)
6570 			sfmmu_mlist_exit(pml);
6571 
6572 		if (f(pahmep->addr, pahmep->len, flag, pahmep->pvt, newpfn)
6573 		    != 0)
6574 			panic("sfmmu: posthandler failed");
6575 
6576 		if (locked) {
6577 			pml = sfmmu_mlist_enter(pp);
6578 			goto top;
6579 		}
6580 	}
6581 
6582 	if (locked)
6583 		sfmmu_mlist_exit(pml);
6584 }
6585 
6586 /*
6587  * Suspend locked kernel mapping
6588  */
6589 void
6590 hat_pagesuspend(struct page *pp)
6591 {
6592 	struct sf_hment *sfhmep;
6593 	sfmmu_t *sfmmup;
6594 	tte_t tte, ttemod;
6595 	struct hme_blk *hmeblkp;
6596 	caddr_t addr;
6597 	int index, cons;
6598 	cpuset_t cpuset;
6599 
6600 	ASSERT(PAGE_EXCL(pp));
6601 	ASSERT(sfmmu_mlist_held(pp));
6602 
6603 	mutex_enter(&kpr_suspendlock);
6604 
6605 	/*
6606 	 * We're about to suspend a kernel mapping so mark this thread as
6607 	 * non-traceable by DTrace. This prevents us from running into issues
6608 	 * with probe context trying to touch a suspended page
6609 	 * in the relocation codepath itself.
6610 	 */
6611 	curthread->t_flag |= T_DONTDTRACE;
6612 
6613 	index = PP_MAPINDEX(pp);
6614 	cons = TTE8K;
6615 
6616 retry:
6617 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6618 
6619 		if (IS_PAHME(sfhmep))
6620 			continue;
6621 
6622 		if (get_hblk_ttesz(sfmmu_hmetohblk(sfhmep)) != cons)
6623 			continue;
6624 
6625 		/*
6626 		 * Loop until we successfully set the suspend bit in
6627 		 * the TTE.
6628 		 */
6629 again:
6630 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6631 		ASSERT(TTE_IS_VALID(&tte));
6632 
6633 		ttemod = tte;
6634 		TTE_SET_SUSPEND(&ttemod);
6635 		if (sfmmu_modifytte_try(&tte, &ttemod,
6636 		    &sfhmep->hme_tte) < 0)
6637 			goto again;
6638 
6639 		/*
6640 		 * Invalidate TSB entry
6641 		 */
6642 		hmeblkp = sfmmu_hmetohblk(sfhmep);
6643 
6644 		sfmmup = hblktosfmmu(hmeblkp);
6645 		ASSERT(sfmmup == ksfmmup);
6646 		ASSERT(!hmeblkp->hblk_shared);
6647 
6648 		addr = tte_to_vaddr(hmeblkp, tte);
6649 
6650 		/*
6651 		 * No need to make sure that the TSB for this sfmmu is
6652 		 * not being relocated since it is ksfmmup and thus it
6653 		 * will never be relocated.
6654 		 */
6655 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
6656 
6657 		/*
6658 		 * Update xcall stats
6659 		 */
6660 		cpuset = cpu_ready_set;
6661 		CPUSET_DEL(cpuset, CPU->cpu_id);
6662 
6663 		/* LINTED: constant in conditional context */
6664 		SFMMU_XCALL_STATS(ksfmmup);
6665 
6666 		/*
6667 		 * Flush TLB entry on remote CPU's
6668 		 */
6669 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
6670 		    (uint64_t)ksfmmup);
6671 		xt_sync(cpuset);
6672 
6673 		/*
6674 		 * Flush TLB entry on local CPU
6675 		 */
6676 		vtag_flushpage(addr, (uint64_t)ksfmmup);
6677 	}
6678 
6679 	while (index != 0) {
6680 		index = index >> 1;
6681 		if (index != 0)
6682 			cons++;
6683 		if (index & 0x1) {
6684 			pp = PP_GROUPLEADER(pp, cons);
6685 			goto retry;
6686 		}
6687 	}
6688 }
6689 
6690 #ifdef	DEBUG
6691 
6692 #define	N_PRLE	1024
6693 struct prle {
6694 	page_t *targ;
6695 	page_t *repl;
6696 	int status;
6697 	int pausecpus;
6698 	hrtime_t whence;
6699 };
6700 
6701 static struct prle page_relocate_log[N_PRLE];
6702 static int prl_entry;
6703 static kmutex_t prl_mutex;
6704 
6705 #define	PAGE_RELOCATE_LOG(t, r, s, p)					\
6706 	mutex_enter(&prl_mutex);					\
6707 	page_relocate_log[prl_entry].targ = *(t);			\
6708 	page_relocate_log[prl_entry].repl = *(r);			\
6709 	page_relocate_log[prl_entry].status = (s);			\
6710 	page_relocate_log[prl_entry].pausecpus = (p);			\
6711 	page_relocate_log[prl_entry].whence = gethrtime();		\
6712 	prl_entry = (prl_entry == (N_PRLE - 1))? 0 : prl_entry + 1;	\
6713 	mutex_exit(&prl_mutex);
6714 
6715 #else	/* !DEBUG */
6716 #define	PAGE_RELOCATE_LOG(t, r, s, p)
6717 #endif
6718 
6719 /*
6720  * Core Kernel Page Relocation Algorithm
6721  *
6722  * Input:
6723  *
6724  * target : 	constituent pages are SE_EXCL locked.
6725  * replacement:	constituent pages are SE_EXCL locked.
6726  *
6727  * Output:
6728  *
6729  * nrelocp:	number of pages relocated
6730  */
6731 int
6732 hat_page_relocate(page_t **target, page_t **replacement, spgcnt_t *nrelocp)
6733 {
6734 	page_t		*targ, *repl;
6735 	page_t		*tpp, *rpp;
6736 	kmutex_t	*low, *high;
6737 	spgcnt_t	npages, i;
6738 	page_t		*pl = NULL;
6739 	int		old_pil;
6740 	cpuset_t	cpuset;
6741 	int		cap_cpus;
6742 	int		ret;
6743 
6744 	if (hat_kpr_enabled == 0 || !kcage_on || PP_ISNORELOC(*target)) {
6745 		PAGE_RELOCATE_LOG(target, replacement, EAGAIN, -1);
6746 		return (EAGAIN);
6747 	}
6748 
6749 	mutex_enter(&kpr_mutex);
6750 	kreloc_thread = curthread;
6751 
6752 	targ = *target;
6753 	repl = *replacement;
6754 	ASSERT(repl != NULL);
6755 	ASSERT(targ->p_szc == repl->p_szc);
6756 
6757 	npages = page_get_pagecnt(targ->p_szc);
6758 
6759 	/*
6760 	 * unload VA<->PA mappings that are not locked
6761 	 */
6762 	tpp = targ;
6763 	for (i = 0; i < npages; i++) {
6764 		(void) hat_pageunload(tpp, SFMMU_KERNEL_RELOC);
6765 		tpp++;
6766 	}
6767 
6768 	/*
6769 	 * Do "presuspend" callbacks, in a context from which we can still
6770 	 * block as needed. Note that we don't hold the mapping list lock
6771 	 * of "targ" at this point due to potential locking order issues;
6772 	 * we assume that between the hat_pageunload() above and holding
6773 	 * the SE_EXCL lock that the mapping list *cannot* change at this
6774 	 * point.
6775 	 */
6776 	ret = hat_pageprocess_precallbacks(targ, HAT_PRESUSPEND, &cap_cpus);
6777 	if (ret != 0) {
6778 		/*
6779 		 * EIO translates to fatal error, for all others cleanup
6780 		 * and return EAGAIN.
6781 		 */
6782 		ASSERT(ret != EIO);
6783 		hat_pageprocess_postcallbacks(targ, HAT_POSTUNSUSPEND);
6784 		PAGE_RELOCATE_LOG(target, replacement, ret, -1);
6785 		kreloc_thread = NULL;
6786 		mutex_exit(&kpr_mutex);
6787 		return (EAGAIN);
6788 	}
6789 
6790 	/*
6791 	 * acquire p_mapping list lock for both the target and replacement
6792 	 * root pages.
6793 	 *
6794 	 * low and high refer to the need to grab the mlist locks in a
6795 	 * specific order in order to prevent race conditions.  Thus the
6796 	 * lower lock must be grabbed before the higher lock.
6797 	 *
6798 	 * This will block hat_unload's accessing p_mapping list.  Since
6799 	 * we have SE_EXCL lock, hat_memload and hat_pageunload will be
6800 	 * blocked.  Thus, no one else will be accessing the p_mapping list
6801 	 * while we suspend and reload the locked mapping below.
6802 	 */
6803 	tpp = targ;
6804 	rpp = repl;
6805 	sfmmu_mlist_reloc_enter(tpp, rpp, &low, &high);
6806 
6807 	kpreempt_disable();
6808 
6809 #ifdef VAC
6810 	/*
6811 	 * If the replacement page is of a different virtual color
6812 	 * than the page it is replacing, we need to handle the VAC
6813 	 * consistency for it just as we would if we were setting up
6814 	 * a new mapping to a page.
6815 	 */
6816 	if ((tpp->p_szc == 0) && (PP_GET_VCOLOR(rpp) != NO_VCOLOR)) {
6817 		if (tpp->p_vcolor != rpp->p_vcolor) {
6818 			sfmmu_cache_flushcolor(PP_GET_VCOLOR(rpp),
6819 			    rpp->p_pagenum);
6820 		}
6821 	}
6822 #endif
6823 
6824 	/*
6825 	 * We raise our PIL to 13 so that we don't get captured by
6826 	 * another CPU or pinned by an interrupt thread.  We can't go to
6827 	 * PIL 14 since the nexus driver(s) may need to interrupt at
6828 	 * that level in the case of IOMMU pseudo mappings.
6829 	 */
6830 	cpuset = cpu_ready_set;
6831 	CPUSET_DEL(cpuset, CPU->cpu_id);
6832 	if (!cap_cpus || CPUSET_ISNULL(cpuset)) {
6833 		old_pil = splr(XCALL_PIL);
6834 	} else {
6835 		old_pil = -1;
6836 		xc_attention(cpuset);
6837 	}
6838 	ASSERT(getpil() == XCALL_PIL);
6839 
6840 	/*
6841 	 * Now do suspend callbacks. In the case of an IOMMU mapping
6842 	 * this will suspend all DMA activity to the page while it is
6843 	 * being relocated. Since we are well above LOCK_LEVEL and CPUs
6844 	 * may be captured at this point we should have acquired any needed
6845 	 * locks in the presuspend callback.
6846 	 */
6847 	ret = hat_pageprocess_precallbacks(targ, HAT_SUSPEND, NULL);
6848 	if (ret != 0) {
6849 		repl = targ;
6850 		goto suspend_fail;
6851 	}
6852 
6853 	/*
6854 	 * Raise the PIL yet again, this time to block all high-level
6855 	 * interrupts on this CPU. This is necessary to prevent an
6856 	 * interrupt routine from pinning the thread which holds the
6857 	 * mapping suspended and then touching the suspended page.
6858 	 *
6859 	 * Once the page is suspended we also need to be careful to
6860 	 * avoid calling any functions which touch any seg_kmem memory
6861 	 * since that memory may be backed by the very page we are
6862 	 * relocating in here!
6863 	 */
6864 	hat_pagesuspend(targ);
6865 
6866 	/*
6867 	 * Now that we are confident everybody has stopped using this page,
6868 	 * copy the page contents.  Note we use a physical copy to prevent
6869 	 * locking issues and to avoid fpRAS because we can't handle it in
6870 	 * this context.
6871 	 */
6872 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6873 		/*
6874 		 * Copy the contents of the page.
6875 		 */
6876 		ppcopy_kernel(tpp, rpp);
6877 	}
6878 
6879 	tpp = targ;
6880 	rpp = repl;
6881 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6882 		/*
6883 		 * Copy attributes.  VAC consistency was handled above,
6884 		 * if required.
6885 		 */
6886 		rpp->p_nrm = tpp->p_nrm;
6887 		tpp->p_nrm = 0;
6888 		rpp->p_index = tpp->p_index;
6889 		tpp->p_index = 0;
6890 #ifdef VAC
6891 		rpp->p_vcolor = tpp->p_vcolor;
6892 #endif
6893 	}
6894 
6895 	/*
6896 	 * First, unsuspend the page, if we set the suspend bit, and transfer
6897 	 * the mapping list from the target page to the replacement page.
6898 	 * Next process postcallbacks; since pa_hment's are linked only to the
6899 	 * p_mapping list of root page, we don't iterate over the constituent
6900 	 * pages.
6901 	 */
6902 	hat_pagereload(targ, repl);
6903 
6904 suspend_fail:
6905 	hat_pageprocess_postcallbacks(repl, HAT_UNSUSPEND);
6906 
6907 	/*
6908 	 * Now lower our PIL and release any captured CPUs since we
6909 	 * are out of the "danger zone".  After this it will again be
6910 	 * safe to acquire adaptive mutex locks, or to drop them...
6911 	 */
6912 	if (old_pil != -1) {
6913 		splx(old_pil);
6914 	} else {
6915 		xc_dismissed(cpuset);
6916 	}
6917 
6918 	kpreempt_enable();
6919 
6920 	sfmmu_mlist_reloc_exit(low, high);
6921 
6922 	/*
6923 	 * Postsuspend callbacks should drop any locks held across
6924 	 * the suspend callbacks.  As before, we don't hold the mapping
6925 	 * list lock at this point.. our assumption is that the mapping
6926 	 * list still can't change due to our holding SE_EXCL lock and
6927 	 * there being no unlocked mappings left. Hence the restriction
6928 	 * on calling context to hat_delete_callback()
6929 	 */
6930 	hat_pageprocess_postcallbacks(repl, HAT_POSTUNSUSPEND);
6931 	if (ret != 0) {
6932 		/*
6933 		 * The second presuspend call failed: we got here through
6934 		 * the suspend_fail label above.
6935 		 */
6936 		ASSERT(ret != EIO);
6937 		PAGE_RELOCATE_LOG(target, replacement, ret, cap_cpus);
6938 		kreloc_thread = NULL;
6939 		mutex_exit(&kpr_mutex);
6940 		return (EAGAIN);
6941 	}
6942 
6943 	/*
6944 	 * Now that we're out of the performance critical section we can
6945 	 * take care of updating the hash table, since we still
6946 	 * hold all the pages locked SE_EXCL at this point we
6947 	 * needn't worry about things changing out from under us.
6948 	 */
6949 	tpp = targ;
6950 	rpp = repl;
6951 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6952 
6953 		/*
6954 		 * replace targ with replacement in page_hash table
6955 		 */
6956 		targ = tpp;
6957 		page_relocate_hash(rpp, targ);
6958 
6959 		/*
6960 		 * concatenate target; caller of platform_page_relocate()
6961 		 * expects target to be concatenated after returning.
6962 		 */
6963 		ASSERT(targ->p_next == targ);
6964 		ASSERT(targ->p_prev == targ);
6965 		page_list_concat(&pl, &targ);
6966 	}
6967 
6968 	ASSERT(*target == pl);
6969 	*nrelocp = npages;
6970 	PAGE_RELOCATE_LOG(target, replacement, 0, cap_cpus);
6971 	kreloc_thread = NULL;
6972 	mutex_exit(&kpr_mutex);
6973 	return (0);
6974 }
6975 
6976 /*
6977  * Called when stray pa_hments are found attached to a page which is
6978  * being freed.  Notify the subsystem which attached the pa_hment of
6979  * the error if it registered a suitable handler, else panic.
6980  */
6981 static void
6982 sfmmu_pahment_leaked(struct pa_hment *pahmep)
6983 {
6984 	id_t cb_id = pahmep->cb_id;
6985 
6986 	ASSERT(cb_id >= (id_t)0 && cb_id < sfmmu_cb_nextid);
6987 	if (sfmmu_cb_table[cb_id].errhandler != NULL) {
6988 		if (sfmmu_cb_table[cb_id].errhandler(pahmep->addr, pahmep->len,
6989 		    HAT_CB_ERR_LEAKED, pahmep->pvt) == 0)
6990 			return;		/* non-fatal */
6991 	}
6992 	panic("pa_hment leaked: 0x%p", (void *)pahmep);
6993 }
6994 
6995 /*
6996  * Remove all mappings to page 'pp'.
6997  */
6998 int
6999 hat_pageunload(struct page *pp, uint_t forceflag)
7000 {
7001 	struct page *origpp = pp;
7002 	struct sf_hment *sfhme, *tmphme;
7003 	struct hme_blk *hmeblkp;
7004 	kmutex_t *pml;
7005 #ifdef VAC
7006 	kmutex_t *pmtx;
7007 #endif
7008 	cpuset_t cpuset, tset;
7009 	int index, cons;
7010 	int xhme_blks;
7011 	int pa_hments;
7012 
7013 	ASSERT(PAGE_EXCL(pp));
7014 
7015 retry_xhat:
7016 	tmphme = NULL;
7017 	xhme_blks = 0;
7018 	pa_hments = 0;
7019 	CPUSET_ZERO(cpuset);
7020 
7021 	pml = sfmmu_mlist_enter(pp);
7022 
7023 #ifdef VAC
7024 	if (pp->p_kpmref)
7025 		sfmmu_kpm_pageunload(pp);
7026 	ASSERT(!PP_ISMAPPED_KPM(pp));
7027 #endif
7028 
7029 	index = PP_MAPINDEX(pp);
7030 	cons = TTE8K;
7031 retry:
7032 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7033 		tmphme = sfhme->hme_next;
7034 
7035 		if (IS_PAHME(sfhme)) {
7036 			ASSERT(sfhme->hme_data != NULL);
7037 			pa_hments++;
7038 			continue;
7039 		}
7040 
7041 		hmeblkp = sfmmu_hmetohblk(sfhme);
7042 		if (hmeblkp->hblk_xhat_bit) {
7043 			struct xhat_hme_blk *xblk =
7044 			    (struct xhat_hme_blk *)hmeblkp;
7045 
7046 			(void) XHAT_PAGEUNLOAD(xblk->xhat_hme_blk_hat,
7047 			    pp, forceflag, XBLK2PROVBLK(xblk));
7048 
7049 			xhme_blks = 1;
7050 			continue;
7051 		}
7052 
7053 		/*
7054 		 * If there are kernel mappings don't unload them, they will
7055 		 * be suspended.
7056 		 */
7057 		if (forceflag == SFMMU_KERNEL_RELOC && hmeblkp->hblk_lckcnt &&
7058 		    hmeblkp->hblk_tag.htag_id == ksfmmup)
7059 			continue;
7060 
7061 		tset = sfmmu_pageunload(pp, sfhme, cons);
7062 		CPUSET_OR(cpuset, tset);
7063 	}
7064 
7065 	while (index != 0) {
7066 		index = index >> 1;
7067 		if (index != 0)
7068 			cons++;
7069 		if (index & 0x1) {
7070 			/* Go to leading page */
7071 			pp = PP_GROUPLEADER(pp, cons);
7072 			ASSERT(sfmmu_mlist_held(pp));
7073 			goto retry;
7074 		}
7075 	}
7076 
7077 	/*
7078 	 * cpuset may be empty if the page was only mapped by segkpm,
7079 	 * in which case we won't actually cross-trap.
7080 	 */
7081 	xt_sync(cpuset);
7082 
7083 	/*
7084 	 * The page should have no mappings at this point, unless
7085 	 * we were called from hat_page_relocate() in which case we
7086 	 * leave the locked mappings which will be suspended later.
7087 	 */
7088 	ASSERT(!PP_ISMAPPED(origpp) || xhme_blks || pa_hments ||
7089 	    (forceflag == SFMMU_KERNEL_RELOC));
7090 
7091 #ifdef VAC
7092 	if (PP_ISTNC(pp)) {
7093 		if (cons == TTE8K) {
7094 			pmtx = sfmmu_page_enter(pp);
7095 			PP_CLRTNC(pp);
7096 			sfmmu_page_exit(pmtx);
7097 		} else {
7098 			conv_tnc(pp, cons);
7099 		}
7100 	}
7101 #endif	/* VAC */
7102 
7103 	if (pa_hments && forceflag != SFMMU_KERNEL_RELOC) {
7104 		/*
7105 		 * Unlink any pa_hments and free them, calling back
7106 		 * the responsible subsystem to notify it of the error.
7107 		 * This can occur in situations such as drivers leaking
7108 		 * DMA handles: naughty, but common enough that we'd like
7109 		 * to keep the system running rather than bringing it
7110 		 * down with an obscure error like "pa_hment leaked"
7111 		 * which doesn't aid the user in debugging their driver.
7112 		 */
7113 		for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7114 			tmphme = sfhme->hme_next;
7115 			if (IS_PAHME(sfhme)) {
7116 				struct pa_hment *pahmep = sfhme->hme_data;
7117 				sfmmu_pahment_leaked(pahmep);
7118 				HME_SUB(sfhme, pp);
7119 				kmem_cache_free(pa_hment_cache, pahmep);
7120 			}
7121 		}
7122 
7123 		ASSERT(!PP_ISMAPPED(origpp) || xhme_blks);
7124 	}
7125 
7126 	sfmmu_mlist_exit(pml);
7127 
7128 	/*
7129 	 * XHAT may not have finished unloading pages
7130 	 * because some other thread was waiting for
7131 	 * mlist lock and XHAT_PAGEUNLOAD let it do
7132 	 * the job.
7133 	 */
7134 	if (xhme_blks) {
7135 		pp = origpp;
7136 		goto retry_xhat;
7137 	}
7138 
7139 	return (0);
7140 }
7141 
7142 cpuset_t
7143 sfmmu_pageunload(page_t *pp, struct sf_hment *sfhme, int cons)
7144 {
7145 	struct hme_blk *hmeblkp;
7146 	sfmmu_t *sfmmup;
7147 	tte_t tte, ttemod;
7148 #ifdef DEBUG
7149 	tte_t orig_old;
7150 #endif /* DEBUG */
7151 	caddr_t addr;
7152 	int ttesz;
7153 	int ret;
7154 	cpuset_t cpuset;
7155 
7156 	ASSERT(pp != NULL);
7157 	ASSERT(sfmmu_mlist_held(pp));
7158 	ASSERT(!PP_ISKAS(pp));
7159 
7160 	CPUSET_ZERO(cpuset);
7161 
7162 	hmeblkp = sfmmu_hmetohblk(sfhme);
7163 
7164 readtte:
7165 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7166 	if (TTE_IS_VALID(&tte)) {
7167 		sfmmup = hblktosfmmu(hmeblkp);
7168 		ttesz = get_hblk_ttesz(hmeblkp);
7169 		/*
7170 		 * Only unload mappings of 'cons' size.
7171 		 */
7172 		if (ttesz != cons)
7173 			return (cpuset);
7174 
7175 		/*
7176 		 * Note that we have p_mapping lock, but no hash lock here.
7177 		 * hblk_unload() has to have both hash lock AND p_mapping
7178 		 * lock before it tries to modify tte. So, the tte could
7179 		 * not become invalid in the sfmmu_modifytte_try() below.
7180 		 */
7181 		ttemod = tte;
7182 #ifdef DEBUG
7183 		orig_old = tte;
7184 #endif /* DEBUG */
7185 
7186 		TTE_SET_INVALID(&ttemod);
7187 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7188 		if (ret < 0) {
7189 #ifdef DEBUG
7190 			/* only R/M bits can change. */
7191 			chk_tte(&orig_old, &tte, &ttemod, hmeblkp);
7192 #endif /* DEBUG */
7193 			goto readtte;
7194 		}
7195 
7196 		if (ret == 0) {
7197 			panic("pageunload: cas failed?");
7198 		}
7199 
7200 		addr = tte_to_vaddr(hmeblkp, tte);
7201 
7202 		if (hmeblkp->hblk_shared) {
7203 			sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7204 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
7205 			sf_region_t *rgnp;
7206 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7207 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7208 			ASSERT(srdp != NULL);
7209 			rgnp = srdp->srd_hmergnp[rid];
7210 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
7211 			cpuset = sfmmu_rgntlb_demap(addr, rgnp, hmeblkp, 1);
7212 			sfmmu_ttesync(NULL, addr, &tte, pp);
7213 			ASSERT(rgnp->rgn_ttecnt[ttesz] > 0);
7214 			atomic_add_long(&rgnp->rgn_ttecnt[ttesz], -1);
7215 		} else {
7216 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
7217 			atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -1);
7218 
7219 			/*
7220 			 * We need to flush the page from the virtual cache
7221 			 * in order to prevent a virtual cache alias
7222 			 * inconsistency. The particular scenario we need
7223 			 * to worry about is:
7224 			 * Given:  va1 and va2 are two virtual address that
7225 			 * alias and will map the same physical address.
7226 			 * 1.   mapping exists from va1 to pa and data has
7227 			 *	been read into the cache.
7228 			 * 2.   unload va1.
7229 			 * 3.   load va2 and modify data using va2.
7230 			 * 4    unload va2.
7231 			 * 5.   load va1 and reference data.  Unless we flush
7232 			 *	the data cache when we unload we will get
7233 			 *	stale data.
7234 			 * This scenario is taken care of by using virtual
7235 			 * page coloring.
7236 			 */
7237 			if (sfmmup->sfmmu_ismhat) {
7238 				/*
7239 				 * Flush TSBs, TLBs and caches
7240 				 * of every process
7241 				 * sharing this ism segment.
7242 				 */
7243 				sfmmu_hat_lock_all();
7244 				mutex_enter(&ism_mlist_lock);
7245 				kpreempt_disable();
7246 				sfmmu_ismtlbcache_demap(addr, sfmmup, hmeblkp,
7247 				    pp->p_pagenum, CACHE_NO_FLUSH);
7248 				kpreempt_enable();
7249 				mutex_exit(&ism_mlist_lock);
7250 				sfmmu_hat_unlock_all();
7251 				cpuset = cpu_ready_set;
7252 			} else {
7253 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7254 				cpuset = sfmmup->sfmmu_cpusran;
7255 			}
7256 		}
7257 
7258 		/*
7259 		 * Hme_sub has to run after ttesync() and a_rss update.
7260 		 * See hblk_unload().
7261 		 */
7262 		HME_SUB(sfhme, pp);
7263 		membar_stst();
7264 
7265 		/*
7266 		 * We can not make ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
7267 		 * since pteload may have done a HME_ADD() right after
7268 		 * we did the HME_SUB() above. Hmecnt is now maintained
7269 		 * by cas only. no lock guranteed its value. The only
7270 		 * gurantee we have is the hmecnt should not be less than
7271 		 * what it should be so the hblk will not be taken away.
7272 		 * It's also important that we decremented the hmecnt after
7273 		 * we are done with hmeblkp so that this hmeblk won't be
7274 		 * stolen.
7275 		 */
7276 		ASSERT(hmeblkp->hblk_hmecnt > 0);
7277 		ASSERT(hmeblkp->hblk_vcnt > 0);
7278 		atomic_add_16(&hmeblkp->hblk_vcnt, -1);
7279 		atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
7280 		/*
7281 		 * This is bug 4063182.
7282 		 * XXX: fixme
7283 		 * ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
7284 		 *	!hmeblkp->hblk_lckcnt);
7285 		 */
7286 	} else {
7287 		panic("invalid tte? pp %p &tte %p",
7288 		    (void *)pp, (void *)&tte);
7289 	}
7290 
7291 	return (cpuset);
7292 }
7293 
7294 /*
7295  * While relocating a kernel page, this function will move the mappings
7296  * from tpp to dpp and modify any associated data with these mappings.
7297  * It also unsuspends the suspended kernel mapping.
7298  */
7299 static void
7300 hat_pagereload(struct page *tpp, struct page *dpp)
7301 {
7302 	struct sf_hment *sfhme;
7303 	tte_t tte, ttemod;
7304 	int index, cons;
7305 
7306 	ASSERT(getpil() == PIL_MAX);
7307 	ASSERT(sfmmu_mlist_held(tpp));
7308 	ASSERT(sfmmu_mlist_held(dpp));
7309 
7310 	index = PP_MAPINDEX(tpp);
7311 	cons = TTE8K;
7312 
7313 	/* Update real mappings to the page */
7314 retry:
7315 	for (sfhme = tpp->p_mapping; sfhme != NULL; sfhme = sfhme->hme_next) {
7316 		if (IS_PAHME(sfhme))
7317 			continue;
7318 		sfmmu_copytte(&sfhme->hme_tte, &tte);
7319 		ttemod = tte;
7320 
7321 		/*
7322 		 * replace old pfn with new pfn in TTE
7323 		 */
7324 		PFN_TO_TTE(ttemod, dpp->p_pagenum);
7325 
7326 		/*
7327 		 * clear suspend bit
7328 		 */
7329 		ASSERT(TTE_IS_SUSPEND(&ttemod));
7330 		TTE_CLR_SUSPEND(&ttemod);
7331 
7332 		if (sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte) < 0)
7333 			panic("hat_pagereload(): sfmmu_modifytte_try() failed");
7334 
7335 		/*
7336 		 * set hme_page point to new page
7337 		 */
7338 		sfhme->hme_page = dpp;
7339 	}
7340 
7341 	/*
7342 	 * move p_mapping list from old page to new page
7343 	 */
7344 	dpp->p_mapping = tpp->p_mapping;
7345 	tpp->p_mapping = NULL;
7346 	dpp->p_share = tpp->p_share;
7347 	tpp->p_share = 0;
7348 
7349 	while (index != 0) {
7350 		index = index >> 1;
7351 		if (index != 0)
7352 			cons++;
7353 		if (index & 0x1) {
7354 			tpp = PP_GROUPLEADER(tpp, cons);
7355 			dpp = PP_GROUPLEADER(dpp, cons);
7356 			goto retry;
7357 		}
7358 	}
7359 
7360 	curthread->t_flag &= ~T_DONTDTRACE;
7361 	mutex_exit(&kpr_suspendlock);
7362 }
7363 
7364 uint_t
7365 hat_pagesync(struct page *pp, uint_t clearflag)
7366 {
7367 	struct sf_hment *sfhme, *tmphme = NULL;
7368 	struct hme_blk *hmeblkp;
7369 	kmutex_t *pml;
7370 	cpuset_t cpuset, tset;
7371 	int	index, cons;
7372 	extern	ulong_t po_share;
7373 	page_t	*save_pp = pp;
7374 	int	stop_on_sh = 0;
7375 	uint_t	shcnt;
7376 
7377 	CPUSET_ZERO(cpuset);
7378 
7379 	if (PP_ISRO(pp) && (clearflag & HAT_SYNC_STOPON_MOD)) {
7380 		return (PP_GENERIC_ATTR(pp));
7381 	}
7382 
7383 	if ((clearflag & HAT_SYNC_ZERORM) == 0) {
7384 		if ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(pp)) {
7385 			return (PP_GENERIC_ATTR(pp));
7386 		}
7387 		if ((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(pp)) {
7388 			return (PP_GENERIC_ATTR(pp));
7389 		}
7390 		if (clearflag & HAT_SYNC_STOPON_SHARED) {
7391 			if (pp->p_share > po_share) {
7392 				hat_page_setattr(pp, P_REF);
7393 				return (PP_GENERIC_ATTR(pp));
7394 			}
7395 			stop_on_sh = 1;
7396 			shcnt = 0;
7397 		}
7398 	}
7399 
7400 	clearflag &= ~HAT_SYNC_STOPON_SHARED;
7401 	pml = sfmmu_mlist_enter(pp);
7402 	index = PP_MAPINDEX(pp);
7403 	cons = TTE8K;
7404 retry:
7405 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7406 		/*
7407 		 * We need to save the next hment on the list since
7408 		 * it is possible for pagesync to remove an invalid hment
7409 		 * from the list.
7410 		 */
7411 		tmphme = sfhme->hme_next;
7412 		if (IS_PAHME(sfhme))
7413 			continue;
7414 		/*
7415 		 * If we are looking for large mappings and this hme doesn't
7416 		 * reach the range we are seeking, just ignore it.
7417 		 */
7418 		hmeblkp = sfmmu_hmetohblk(sfhme);
7419 		if (hmeblkp->hblk_xhat_bit)
7420 			continue;
7421 
7422 		if (hme_size(sfhme) < cons)
7423 			continue;
7424 
7425 		if (stop_on_sh) {
7426 			if (hmeblkp->hblk_shared) {
7427 				sf_srd_t *srdp = hblktosrd(hmeblkp);
7428 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7429 				sf_region_t *rgnp;
7430 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7431 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7432 				ASSERT(srdp != NULL);
7433 				rgnp = srdp->srd_hmergnp[rid];
7434 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
7435 				    rgnp, rid);
7436 				shcnt += rgnp->rgn_refcnt;
7437 			} else {
7438 				shcnt++;
7439 			}
7440 			if (shcnt > po_share) {
7441 				/*
7442 				 * tell the pager to spare the page this time
7443 				 * around.
7444 				 */
7445 				hat_page_setattr(save_pp, P_REF);
7446 				index = 0;
7447 				break;
7448 			}
7449 		}
7450 		tset = sfmmu_pagesync(pp, sfhme,
7451 		    clearflag & ~HAT_SYNC_STOPON_RM);
7452 		CPUSET_OR(cpuset, tset);
7453 
7454 		/*
7455 		 * If clearflag is HAT_SYNC_DONTZERO, break out as soon
7456 		 * as the "ref" or "mod" is set or share cnt exceeds po_share.
7457 		 */
7458 		if ((clearflag & ~HAT_SYNC_STOPON_RM) == HAT_SYNC_DONTZERO &&
7459 		    (((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(save_pp)) ||
7460 		    ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(save_pp)))) {
7461 			index = 0;
7462 			break;
7463 		}
7464 	}
7465 
7466 	while (index) {
7467 		index = index >> 1;
7468 		cons++;
7469 		if (index & 0x1) {
7470 			/* Go to leading page */
7471 			pp = PP_GROUPLEADER(pp, cons);
7472 			goto retry;
7473 		}
7474 	}
7475 
7476 	xt_sync(cpuset);
7477 	sfmmu_mlist_exit(pml);
7478 	return (PP_GENERIC_ATTR(save_pp));
7479 }
7480 
7481 /*
7482  * Get all the hardware dependent attributes for a page struct
7483  */
7484 static cpuset_t
7485 sfmmu_pagesync(struct page *pp, struct sf_hment *sfhme,
7486 	uint_t clearflag)
7487 {
7488 	caddr_t addr;
7489 	tte_t tte, ttemod;
7490 	struct hme_blk *hmeblkp;
7491 	int ret;
7492 	sfmmu_t *sfmmup;
7493 	cpuset_t cpuset;
7494 
7495 	ASSERT(pp != NULL);
7496 	ASSERT(sfmmu_mlist_held(pp));
7497 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
7498 	    (clearflag == HAT_SYNC_ZERORM));
7499 
7500 	SFMMU_STAT(sf_pagesync);
7501 
7502 	CPUSET_ZERO(cpuset);
7503 
7504 sfmmu_pagesync_retry:
7505 
7506 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7507 	if (TTE_IS_VALID(&tte)) {
7508 		hmeblkp = sfmmu_hmetohblk(sfhme);
7509 		sfmmup = hblktosfmmu(hmeblkp);
7510 		addr = tte_to_vaddr(hmeblkp, tte);
7511 		if (clearflag == HAT_SYNC_ZERORM) {
7512 			ttemod = tte;
7513 			TTE_CLR_RM(&ttemod);
7514 			ret = sfmmu_modifytte_try(&tte, &ttemod,
7515 			    &sfhme->hme_tte);
7516 			if (ret < 0) {
7517 				/*
7518 				 * cas failed and the new value is not what
7519 				 * we want.
7520 				 */
7521 				goto sfmmu_pagesync_retry;
7522 			}
7523 
7524 			if (ret > 0) {
7525 				/* we win the cas */
7526 				if (hmeblkp->hblk_shared) {
7527 					sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7528 					uint_t rid =
7529 					    hmeblkp->hblk_tag.htag_rid;
7530 					sf_region_t *rgnp;
7531 					ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7532 					ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7533 					ASSERT(srdp != NULL);
7534 					rgnp = srdp->srd_hmergnp[rid];
7535 					SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7536 					    srdp, rgnp, rid);
7537 					cpuset = sfmmu_rgntlb_demap(addr,
7538 					    rgnp, hmeblkp, 1);
7539 				} else {
7540 					sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
7541 					    0, 0);
7542 					cpuset = sfmmup->sfmmu_cpusran;
7543 				}
7544 			}
7545 		}
7546 		sfmmu_ttesync(hmeblkp->hblk_shared ? NULL : sfmmup, addr,
7547 		    &tte, pp);
7548 	}
7549 	return (cpuset);
7550 }
7551 
7552 /*
7553  * Remove write permission from a mappings to a page, so that
7554  * we can detect the next modification of it. This requires modifying
7555  * the TTE then invalidating (demap) any TLB entry using that TTE.
7556  * This code is similar to sfmmu_pagesync().
7557  */
7558 static cpuset_t
7559 sfmmu_pageclrwrt(struct page *pp, struct sf_hment *sfhme)
7560 {
7561 	caddr_t addr;
7562 	tte_t tte;
7563 	tte_t ttemod;
7564 	struct hme_blk *hmeblkp;
7565 	int ret;
7566 	sfmmu_t *sfmmup;
7567 	cpuset_t cpuset;
7568 
7569 	ASSERT(pp != NULL);
7570 	ASSERT(sfmmu_mlist_held(pp));
7571 
7572 	CPUSET_ZERO(cpuset);
7573 	SFMMU_STAT(sf_clrwrt);
7574 
7575 retry:
7576 
7577 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7578 	if (TTE_IS_VALID(&tte) && TTE_IS_WRITABLE(&tte)) {
7579 		hmeblkp = sfmmu_hmetohblk(sfhme);
7580 
7581 		/*
7582 		 * xhat mappings should never be to a VMODSORT page.
7583 		 */
7584 		ASSERT(hmeblkp->hblk_xhat_bit == 0);
7585 
7586 		sfmmup = hblktosfmmu(hmeblkp);
7587 		addr = tte_to_vaddr(hmeblkp, tte);
7588 
7589 		ttemod = tte;
7590 		TTE_CLR_WRT(&ttemod);
7591 		TTE_CLR_MOD(&ttemod);
7592 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7593 
7594 		/*
7595 		 * if cas failed and the new value is not what
7596 		 * we want retry
7597 		 */
7598 		if (ret < 0)
7599 			goto retry;
7600 
7601 		/* we win the cas */
7602 		if (ret > 0) {
7603 			if (hmeblkp->hblk_shared) {
7604 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7605 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7606 				sf_region_t *rgnp;
7607 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7608 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7609 				ASSERT(srdp != NULL);
7610 				rgnp = srdp->srd_hmergnp[rid];
7611 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7612 				    srdp, rgnp, rid);
7613 				cpuset = sfmmu_rgntlb_demap(addr,
7614 				    rgnp, hmeblkp, 1);
7615 			} else {
7616 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7617 				cpuset = sfmmup->sfmmu_cpusran;
7618 			}
7619 		}
7620 	}
7621 
7622 	return (cpuset);
7623 }
7624 
7625 /*
7626  * Walk all mappings of a page, removing write permission and clearing the
7627  * ref/mod bits. This code is similar to hat_pagesync()
7628  */
7629 static void
7630 hat_page_clrwrt(page_t *pp)
7631 {
7632 	struct sf_hment *sfhme;
7633 	struct sf_hment *tmphme = NULL;
7634 	kmutex_t *pml;
7635 	cpuset_t cpuset;
7636 	cpuset_t tset;
7637 	int	index;
7638 	int	 cons;
7639 
7640 	CPUSET_ZERO(cpuset);
7641 
7642 	pml = sfmmu_mlist_enter(pp);
7643 	index = PP_MAPINDEX(pp);
7644 	cons = TTE8K;
7645 retry:
7646 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7647 		tmphme = sfhme->hme_next;
7648 
7649 		/*
7650 		 * If we are looking for large mappings and this hme doesn't
7651 		 * reach the range we are seeking, just ignore its.
7652 		 */
7653 
7654 		if (hme_size(sfhme) < cons)
7655 			continue;
7656 
7657 		tset = sfmmu_pageclrwrt(pp, sfhme);
7658 		CPUSET_OR(cpuset, tset);
7659 	}
7660 
7661 	while (index) {
7662 		index = index >> 1;
7663 		cons++;
7664 		if (index & 0x1) {
7665 			/* Go to leading page */
7666 			pp = PP_GROUPLEADER(pp, cons);
7667 			goto retry;
7668 		}
7669 	}
7670 
7671 	xt_sync(cpuset);
7672 	sfmmu_mlist_exit(pml);
7673 }
7674 
7675 /*
7676  * Set the given REF/MOD/RO bits for the given page.
7677  * For a vnode with a sorted v_pages list, we need to change
7678  * the attributes and the v_pages list together under page_vnode_mutex.
7679  */
7680 void
7681 hat_page_setattr(page_t *pp, uint_t flag)
7682 {
7683 	vnode_t		*vp = pp->p_vnode;
7684 	page_t		**listp;
7685 	kmutex_t	*pmtx;
7686 	kmutex_t	*vphm = NULL;
7687 	int		noshuffle;
7688 
7689 	noshuffle = flag & P_NSH;
7690 	flag &= ~P_NSH;
7691 
7692 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7693 
7694 	/*
7695 	 * nothing to do if attribute already set
7696 	 */
7697 	if ((pp->p_nrm & flag) == flag)
7698 		return;
7699 
7700 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp) &&
7701 	    !noshuffle) {
7702 		vphm = page_vnode_mutex(vp);
7703 		mutex_enter(vphm);
7704 	}
7705 
7706 	pmtx = sfmmu_page_enter(pp);
7707 	pp->p_nrm |= flag;
7708 	sfmmu_page_exit(pmtx);
7709 
7710 	if (vphm != NULL) {
7711 		/*
7712 		 * Some File Systems examine v_pages for NULL w/o
7713 		 * grabbing the vphm mutex. Must not let it become NULL when
7714 		 * pp is the only page on the list.
7715 		 */
7716 		if (pp->p_vpnext != pp) {
7717 			page_vpsub(&vp->v_pages, pp);
7718 			if (vp->v_pages != NULL)
7719 				listp = &vp->v_pages->p_vpprev->p_vpnext;
7720 			else
7721 				listp = &vp->v_pages;
7722 			page_vpadd(listp, pp);
7723 		}
7724 		mutex_exit(vphm);
7725 	}
7726 }
7727 
7728 void
7729 hat_page_clrattr(page_t *pp, uint_t flag)
7730 {
7731 	vnode_t		*vp = pp->p_vnode;
7732 	kmutex_t	*pmtx;
7733 
7734 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7735 
7736 	pmtx = sfmmu_page_enter(pp);
7737 
7738 	/*
7739 	 * Caller is expected to hold page's io lock for VMODSORT to work
7740 	 * correctly with pvn_vplist_dirty() and pvn_getdirty() when mod
7741 	 * bit is cleared.
7742 	 * We don't have assert to avoid tripping some existing third party
7743 	 * code. The dirty page is moved back to top of the v_page list
7744 	 * after IO is done in pvn_write_done().
7745 	 */
7746 	pp->p_nrm &= ~flag;
7747 	sfmmu_page_exit(pmtx);
7748 
7749 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
7750 
7751 		/*
7752 		 * VMODSORT works by removing write permissions and getting
7753 		 * a fault when a page is made dirty. At this point
7754 		 * we need to remove write permission from all mappings
7755 		 * to this page.
7756 		 */
7757 		hat_page_clrwrt(pp);
7758 	}
7759 }
7760 
7761 uint_t
7762 hat_page_getattr(page_t *pp, uint_t flag)
7763 {
7764 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7765 	return ((uint_t)(pp->p_nrm & flag));
7766 }
7767 
7768 /*
7769  * DEBUG kernels: verify that a kernel va<->pa translation
7770  * is safe by checking the underlying page_t is in a page
7771  * relocation-safe state.
7772  */
7773 #ifdef	DEBUG
7774 void
7775 sfmmu_check_kpfn(pfn_t pfn)
7776 {
7777 	page_t *pp;
7778 	int index, cons;
7779 
7780 	if (hat_check_vtop == 0)
7781 		return;
7782 
7783 	if (hat_kpr_enabled == 0 || kvseg.s_base == NULL || panicstr)
7784 		return;
7785 
7786 	pp = page_numtopp_nolock(pfn);
7787 	if (!pp)
7788 		return;
7789 
7790 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7791 		return;
7792 
7793 	/*
7794 	 * Handed a large kernel page, we dig up the root page since we
7795 	 * know the root page might have the lock also.
7796 	 */
7797 	if (pp->p_szc != 0) {
7798 		index = PP_MAPINDEX(pp);
7799 		cons = TTE8K;
7800 again:
7801 		while (index != 0) {
7802 			index >>= 1;
7803 			if (index != 0)
7804 				cons++;
7805 			if (index & 0x1) {
7806 				pp = PP_GROUPLEADER(pp, cons);
7807 				goto again;
7808 			}
7809 		}
7810 	}
7811 
7812 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7813 		return;
7814 
7815 	/*
7816 	 * Pages need to be locked or allocated "permanent" (either from
7817 	 * static_arena arena or explicitly setting PG_NORELOC when calling
7818 	 * page_create_va()) for VA->PA translations to be valid.
7819 	 */
7820 	if (!PP_ISNORELOC(pp))
7821 		panic("Illegal VA->PA translation, pp 0x%p not permanent",
7822 		    (void *)pp);
7823 	else
7824 		panic("Illegal VA->PA translation, pp 0x%p not locked",
7825 		    (void *)pp);
7826 }
7827 #endif	/* DEBUG */
7828 
7829 /*
7830  * Returns a page frame number for a given virtual address.
7831  * Returns PFN_INVALID to indicate an invalid mapping
7832  */
7833 pfn_t
7834 hat_getpfnum(struct hat *hat, caddr_t addr)
7835 {
7836 	pfn_t pfn;
7837 	tte_t tte;
7838 
7839 	/*
7840 	 * We would like to
7841 	 * ASSERT(AS_LOCK_HELD(as, &as->a_lock));
7842 	 * but we can't because the iommu driver will call this
7843 	 * routine at interrupt time and it can't grab the as lock
7844 	 * or it will deadlock: A thread could have the as lock
7845 	 * and be waiting for io.  The io can't complete
7846 	 * because the interrupt thread is blocked trying to grab
7847 	 * the as lock.
7848 	 */
7849 
7850 	ASSERT(hat->sfmmu_xhat_provider == NULL);
7851 
7852 	if (hat == ksfmmup) {
7853 		if (IS_KMEM_VA_LARGEPAGE(addr)) {
7854 			ASSERT(segkmem_lpszc > 0);
7855 			pfn = sfmmu_kvaszc2pfn(addr, segkmem_lpszc);
7856 			if (pfn != PFN_INVALID) {
7857 				sfmmu_check_kpfn(pfn);
7858 				return (pfn);
7859 			}
7860 		} else if (segkpm && IS_KPM_ADDR(addr)) {
7861 			return (sfmmu_kpm_vatopfn(addr));
7862 		}
7863 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7864 		    == PFN_SUSPENDED) {
7865 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7866 		}
7867 		sfmmu_check_kpfn(pfn);
7868 		return (pfn);
7869 	} else {
7870 		return (sfmmu_uvatopfn(addr, hat, NULL));
7871 	}
7872 }
7873 
7874 /*
7875  * hat_getkpfnum() is an obsolete DDI routine, and its use is discouraged.
7876  * Use hat_getpfnum(kas.a_hat, ...) instead.
7877  *
7878  * We'd like to return PFN_INVALID if the mappings have underlying page_t's
7879  * but can't right now due to the fact that some software has grown to use
7880  * this interface incorrectly. So for now when the interface is misused,
7881  * return a warning to the user that in the future it won't work in the
7882  * way they're abusing it, and carry on (after disabling page relocation).
7883  */
7884 pfn_t
7885 hat_getkpfnum(caddr_t addr)
7886 {
7887 	pfn_t pfn;
7888 	tte_t tte;
7889 	int badcaller = 0;
7890 	extern int segkmem_reloc;
7891 
7892 	if (segkpm && IS_KPM_ADDR(addr)) {
7893 		badcaller = 1;
7894 		pfn = sfmmu_kpm_vatopfn(addr);
7895 	} else {
7896 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7897 		    == PFN_SUSPENDED) {
7898 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7899 		}
7900 		badcaller = pf_is_memory(pfn);
7901 	}
7902 
7903 	if (badcaller) {
7904 		/*
7905 		 * We can't return PFN_INVALID or the caller may panic
7906 		 * or corrupt the system.  The only alternative is to
7907 		 * disable page relocation at this point for all kernel
7908 		 * memory.  This will impact any callers of page_relocate()
7909 		 * such as FMA or DR.
7910 		 *
7911 		 * RFE: Add junk here to spit out an ereport so the sysadmin
7912 		 * can be advised that he should upgrade his device driver
7913 		 * so that this doesn't happen.
7914 		 */
7915 		hat_getkpfnum_badcall(caller());
7916 		if (hat_kpr_enabled && segkmem_reloc) {
7917 			hat_kpr_enabled = 0;
7918 			segkmem_reloc = 0;
7919 			cmn_err(CE_WARN, "Kernel Page Relocation is DISABLED");
7920 		}
7921 	}
7922 	return (pfn);
7923 }
7924 
7925 /*
7926  * This routine will return both pfn and tte for the vaddr.
7927  */
7928 static pfn_t
7929 sfmmu_uvatopfn(caddr_t vaddr, struct hat *sfmmup, tte_t *ttep)
7930 {
7931 	struct hmehash_bucket *hmebp;
7932 	hmeblk_tag hblktag;
7933 	int hmeshift, hashno = 1;
7934 	struct hme_blk *hmeblkp = NULL;
7935 	tte_t tte;
7936 
7937 	struct sf_hment *sfhmep;
7938 	pfn_t pfn;
7939 
7940 	/* support for ISM */
7941 	ism_map_t	*ism_map;
7942 	ism_blk_t	*ism_blkp;
7943 	int		i;
7944 	sfmmu_t *ism_hatid = NULL;
7945 	sfmmu_t *locked_hatid = NULL;
7946 	sfmmu_t	*sv_sfmmup = sfmmup;
7947 	caddr_t	sv_vaddr = vaddr;
7948 	sf_srd_t *srdp;
7949 
7950 	if (ttep == NULL) {
7951 		ttep = &tte;
7952 	} else {
7953 		ttep->ll = 0;
7954 	}
7955 
7956 	ASSERT(sfmmup != ksfmmup);
7957 	SFMMU_STAT(sf_user_vtop);
7958 	/*
7959 	 * Set ism_hatid if vaddr falls in a ISM segment.
7960 	 */
7961 	ism_blkp = sfmmup->sfmmu_iblk;
7962 	if (ism_blkp != NULL) {
7963 		sfmmu_ismhat_enter(sfmmup, 0);
7964 		locked_hatid = sfmmup;
7965 	}
7966 	while (ism_blkp != NULL && ism_hatid == NULL) {
7967 		ism_map = ism_blkp->iblk_maps;
7968 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
7969 			if (vaddr >= ism_start(ism_map[i]) &&
7970 			    vaddr < ism_end(ism_map[i])) {
7971 				sfmmup = ism_hatid = ism_map[i].imap_ismhat;
7972 				vaddr = (caddr_t)(vaddr -
7973 				    ism_start(ism_map[i]));
7974 				break;
7975 			}
7976 		}
7977 		ism_blkp = ism_blkp->iblk_next;
7978 	}
7979 	if (locked_hatid) {
7980 		sfmmu_ismhat_exit(locked_hatid, 0);
7981 	}
7982 
7983 	hblktag.htag_id = sfmmup;
7984 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
7985 	do {
7986 		hmeshift = HME_HASH_SHIFT(hashno);
7987 		hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
7988 		hblktag.htag_rehash = hashno;
7989 		hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
7990 
7991 		SFMMU_HASH_LOCK(hmebp);
7992 
7993 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
7994 		if (hmeblkp != NULL) {
7995 			ASSERT(!hmeblkp->hblk_shared);
7996 			HBLKTOHME(sfhmep, hmeblkp, vaddr);
7997 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
7998 			SFMMU_HASH_UNLOCK(hmebp);
7999 			if (TTE_IS_VALID(ttep)) {
8000 				pfn = TTE_TO_PFN(vaddr, ttep);
8001 				return (pfn);
8002 			}
8003 			break;
8004 		}
8005 		SFMMU_HASH_UNLOCK(hmebp);
8006 		hashno++;
8007 	} while (HME_REHASH(sfmmup) && (hashno <= mmu_hashcnt));
8008 
8009 	if (SF_HMERGNMAP_ISNULL(sv_sfmmup)) {
8010 		return (PFN_INVALID);
8011 	}
8012 	srdp = sv_sfmmup->sfmmu_srdp;
8013 	ASSERT(srdp != NULL);
8014 	ASSERT(srdp->srd_refcnt != 0);
8015 	hblktag.htag_id = srdp;
8016 	hashno = 1;
8017 	do {
8018 		hmeshift = HME_HASH_SHIFT(hashno);
8019 		hblktag.htag_bspage = HME_HASH_BSPAGE(sv_vaddr, hmeshift);
8020 		hblktag.htag_rehash = hashno;
8021 		hmebp = HME_HASH_FUNCTION(srdp, sv_vaddr, hmeshift);
8022 
8023 		SFMMU_HASH_LOCK(hmebp);
8024 		for (hmeblkp = hmebp->hmeblkp; hmeblkp != NULL;
8025 		    hmeblkp = hmeblkp->hblk_next) {
8026 			uint_t rid;
8027 			sf_region_t *rgnp;
8028 			caddr_t rsaddr;
8029 			caddr_t readdr;
8030 
8031 			if (!HTAGS_EQ_SHME(hmeblkp->hblk_tag, hblktag,
8032 			    sv_sfmmup->sfmmu_hmeregion_map)) {
8033 				continue;
8034 			}
8035 			ASSERT(hmeblkp->hblk_shared);
8036 			rid = hmeblkp->hblk_tag.htag_rid;
8037 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8038 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8039 			rgnp = srdp->srd_hmergnp[rid];
8040 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
8041 			HBLKTOHME(sfhmep, hmeblkp, sv_vaddr);
8042 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
8043 			rsaddr = rgnp->rgn_saddr;
8044 			readdr = rsaddr + rgnp->rgn_size;
8045 #ifdef DEBUG
8046 			if (TTE_IS_VALID(ttep) ||
8047 			    get_hblk_ttesz(hmeblkp) > TTE8K) {
8048 				caddr_t eva = tte_to_evaddr(hmeblkp, ttep);
8049 				ASSERT(eva > sv_vaddr);
8050 				ASSERT(sv_vaddr >= rsaddr);
8051 				ASSERT(sv_vaddr < readdr);
8052 				ASSERT(eva <= readdr);
8053 			}
8054 #endif /* DEBUG */
8055 			/*
8056 			 * Continue the search if we
8057 			 * found an invalid 8K tte outside of the area
8058 			 * covered by this hmeblk's region.
8059 			 */
8060 			if (TTE_IS_VALID(ttep)) {
8061 				SFMMU_HASH_UNLOCK(hmebp);
8062 				pfn = TTE_TO_PFN(sv_vaddr, ttep);
8063 				return (pfn);
8064 			} else if (get_hblk_ttesz(hmeblkp) > TTE8K ||
8065 			    (sv_vaddr >= rsaddr && sv_vaddr < readdr)) {
8066 				SFMMU_HASH_UNLOCK(hmebp);
8067 				pfn = PFN_INVALID;
8068 				return (pfn);
8069 			}
8070 		}
8071 		SFMMU_HASH_UNLOCK(hmebp);
8072 		hashno++;
8073 	} while (hashno <= mmu_hashcnt);
8074 	return (PFN_INVALID);
8075 }
8076 
8077 
8078 /*
8079  * For compatability with AT&T and later optimizations
8080  */
8081 /* ARGSUSED */
8082 void
8083 hat_map(struct hat *hat, caddr_t addr, size_t len, uint_t flags)
8084 {
8085 	ASSERT(hat != NULL);
8086 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8087 }
8088 
8089 /*
8090  * Return the number of mappings to a particular page.  This number is an
8091  * approximation of the number of people sharing the page.
8092  *
8093  * shared hmeblks or ism hmeblks are counted as 1 mapping here.
8094  * hat_page_checkshare() can be used to compare threshold to share
8095  * count that reflects the number of region sharers albeit at higher cost.
8096  */
8097 ulong_t
8098 hat_page_getshare(page_t *pp)
8099 {
8100 	page_t *spp = pp;	/* start page */
8101 	kmutex_t *pml;
8102 	ulong_t	cnt;
8103 	int index, sz = TTE64K;
8104 
8105 	/*
8106 	 * We need to grab the mlist lock to make sure any outstanding
8107 	 * load/unloads complete.  Otherwise we could return zero
8108 	 * even though the unload(s) hasn't finished yet.
8109 	 */
8110 	pml = sfmmu_mlist_enter(spp);
8111 	cnt = spp->p_share;
8112 
8113 #ifdef VAC
8114 	if (kpm_enable)
8115 		cnt += spp->p_kpmref;
8116 #endif
8117 
8118 	/*
8119 	 * If we have any large mappings, we count the number of
8120 	 * mappings that this large page is part of.
8121 	 */
8122 	index = PP_MAPINDEX(spp);
8123 	index >>= 1;
8124 	while (index) {
8125 		pp = PP_GROUPLEADER(spp, sz);
8126 		if ((index & 0x1) && pp != spp) {
8127 			cnt += pp->p_share;
8128 			spp = pp;
8129 		}
8130 		index >>= 1;
8131 		sz++;
8132 	}
8133 	sfmmu_mlist_exit(pml);
8134 	return (cnt);
8135 }
8136 
8137 /*
8138  * Return 1 if the number of mappings exceeds sh_thresh. Return 0
8139  * otherwise. Count shared hmeblks by region's refcnt.
8140  */
8141 int
8142 hat_page_checkshare(page_t *pp, ulong_t sh_thresh)
8143 {
8144 	kmutex_t *pml;
8145 	ulong_t	cnt = 0;
8146 	int index, sz = TTE8K;
8147 	struct sf_hment *sfhme, *tmphme = NULL;
8148 	struct hme_blk *hmeblkp;
8149 
8150 	pml = sfmmu_mlist_enter(pp);
8151 
8152 	if (kpm_enable)
8153 		cnt = pp->p_kpmref;
8154 
8155 	if (pp->p_share + cnt > sh_thresh) {
8156 		sfmmu_mlist_exit(pml);
8157 		return (1);
8158 	}
8159 
8160 	index = PP_MAPINDEX(pp);
8161 
8162 again:
8163 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
8164 		tmphme = sfhme->hme_next;
8165 		if (IS_PAHME(sfhme)) {
8166 			continue;
8167 		}
8168 
8169 		hmeblkp = sfmmu_hmetohblk(sfhme);
8170 		if (hmeblkp->hblk_xhat_bit) {
8171 			cnt++;
8172 			if (cnt > sh_thresh) {
8173 				sfmmu_mlist_exit(pml);
8174 				return (1);
8175 			}
8176 			continue;
8177 		}
8178 		if (hme_size(sfhme) != sz) {
8179 			continue;
8180 		}
8181 
8182 		if (hmeblkp->hblk_shared) {
8183 			sf_srd_t *srdp = hblktosrd(hmeblkp);
8184 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
8185 			sf_region_t *rgnp;
8186 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8187 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8188 			ASSERT(srdp != NULL);
8189 			rgnp = srdp->srd_hmergnp[rid];
8190 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
8191 			    rgnp, rid);
8192 			cnt += rgnp->rgn_refcnt;
8193 		} else {
8194 			cnt++;
8195 		}
8196 		if (cnt > sh_thresh) {
8197 			sfmmu_mlist_exit(pml);
8198 			return (1);
8199 		}
8200 	}
8201 
8202 	index >>= 1;
8203 	sz++;
8204 	while (index) {
8205 		pp = PP_GROUPLEADER(pp, sz);
8206 		ASSERT(sfmmu_mlist_held(pp));
8207 		if (index & 0x1) {
8208 			goto again;
8209 		}
8210 		index >>= 1;
8211 		sz++;
8212 	}
8213 	sfmmu_mlist_exit(pml);
8214 	return (0);
8215 }
8216 
8217 /*
8218  * Unload all large mappings to the pp and reset the p_szc field of every
8219  * constituent page according to the remaining mappings.
8220  *
8221  * pp must be locked SE_EXCL. Even though no other constituent pages are
8222  * locked it's legal to unload the large mappings to the pp because all
8223  * constituent pages of large locked mappings have to be locked SE_SHARED.
8224  * This means if we have SE_EXCL lock on one of constituent pages none of the
8225  * large mappings to pp are locked.
8226  *
8227  * Decrease p_szc field starting from the last constituent page and ending
8228  * with the root page. This method is used because other threads rely on the
8229  * root's p_szc to find the lock to syncronize on. After a root page_t's p_szc
8230  * is demoted then other threads will succeed in sfmmu_mlspl_enter(). This
8231  * ensures that p_szc changes of the constituent pages appears atomic for all
8232  * threads that use sfmmu_mlspl_enter() to examine p_szc field.
8233  *
8234  * This mechanism is only used for file system pages where it's not always
8235  * possible to get SE_EXCL locks on all constituent pages to demote the size
8236  * code (as is done for anonymous or kernel large pages).
8237  *
8238  * See more comments in front of sfmmu_mlspl_enter().
8239  */
8240 void
8241 hat_page_demote(page_t *pp)
8242 {
8243 	int index;
8244 	int sz;
8245 	cpuset_t cpuset;
8246 	int sync = 0;
8247 	page_t *rootpp;
8248 	struct sf_hment *sfhme;
8249 	struct sf_hment *tmphme = NULL;
8250 	struct hme_blk *hmeblkp;
8251 	uint_t pszc;
8252 	page_t *lastpp;
8253 	cpuset_t tset;
8254 	pgcnt_t npgs;
8255 	kmutex_t *pml;
8256 	kmutex_t *pmtx = NULL;
8257 
8258 	ASSERT(PAGE_EXCL(pp));
8259 	ASSERT(!PP_ISFREE(pp));
8260 	ASSERT(!PP_ISKAS(pp));
8261 	ASSERT(page_szc_lock_assert(pp));
8262 	pml = sfmmu_mlist_enter(pp);
8263 
8264 	pszc = pp->p_szc;
8265 	if (pszc == 0) {
8266 		goto out;
8267 	}
8268 
8269 	index = PP_MAPINDEX(pp) >> 1;
8270 
8271 	if (index) {
8272 		CPUSET_ZERO(cpuset);
8273 		sz = TTE64K;
8274 		sync = 1;
8275 	}
8276 
8277 	while (index) {
8278 		if (!(index & 0x1)) {
8279 			index >>= 1;
8280 			sz++;
8281 			continue;
8282 		}
8283 		ASSERT(sz <= pszc);
8284 		rootpp = PP_GROUPLEADER(pp, sz);
8285 		for (sfhme = rootpp->p_mapping; sfhme; sfhme = tmphme) {
8286 			tmphme = sfhme->hme_next;
8287 			ASSERT(!IS_PAHME(sfhme));
8288 			hmeblkp = sfmmu_hmetohblk(sfhme);
8289 			if (hme_size(sfhme) != sz) {
8290 				continue;
8291 			}
8292 			if (hmeblkp->hblk_xhat_bit) {
8293 				cmn_err(CE_PANIC,
8294 				    "hat_page_demote: xhat hmeblk");
8295 			}
8296 			tset = sfmmu_pageunload(rootpp, sfhme, sz);
8297 			CPUSET_OR(cpuset, tset);
8298 		}
8299 		if (index >>= 1) {
8300 			sz++;
8301 		}
8302 	}
8303 
8304 	ASSERT(!PP_ISMAPPED_LARGE(pp));
8305 
8306 	if (sync) {
8307 		xt_sync(cpuset);
8308 #ifdef VAC
8309 		if (PP_ISTNC(pp)) {
8310 			conv_tnc(rootpp, sz);
8311 		}
8312 #endif	/* VAC */
8313 	}
8314 
8315 	pmtx = sfmmu_page_enter(pp);
8316 
8317 	ASSERT(pp->p_szc == pszc);
8318 	rootpp = PP_PAGEROOT(pp);
8319 	ASSERT(rootpp->p_szc == pszc);
8320 	lastpp = PP_PAGENEXT_N(rootpp, TTEPAGES(pszc) - 1);
8321 
8322 	while (lastpp != rootpp) {
8323 		sz = PP_MAPINDEX(lastpp) ? fnd_mapping_sz(lastpp) : 0;
8324 		ASSERT(sz < pszc);
8325 		npgs = (sz == 0) ? 1 : TTEPAGES(sz);
8326 		ASSERT(P2PHASE(lastpp->p_pagenum, npgs) == npgs - 1);
8327 		while (--npgs > 0) {
8328 			lastpp->p_szc = (uchar_t)sz;
8329 			lastpp = PP_PAGEPREV(lastpp);
8330 		}
8331 		if (sz) {
8332 			/*
8333 			 * make sure before current root's pszc
8334 			 * is updated all updates to constituent pages pszc
8335 			 * fields are globally visible.
8336 			 */
8337 			membar_producer();
8338 		}
8339 		lastpp->p_szc = sz;
8340 		ASSERT(IS_P2ALIGNED(lastpp->p_pagenum, TTEPAGES(sz)));
8341 		if (lastpp != rootpp) {
8342 			lastpp = PP_PAGEPREV(lastpp);
8343 		}
8344 	}
8345 	if (sz == 0) {
8346 		/* the loop above doesn't cover this case */
8347 		rootpp->p_szc = 0;
8348 	}
8349 out:
8350 	ASSERT(pp->p_szc == 0);
8351 	if (pmtx != NULL) {
8352 		sfmmu_page_exit(pmtx);
8353 	}
8354 	sfmmu_mlist_exit(pml);
8355 }
8356 
8357 /*
8358  * Refresh the HAT ismttecnt[] element for size szc.
8359  * Caller must have set ISM busy flag to prevent mapping
8360  * lists from changing while we're traversing them.
8361  */
8362 pgcnt_t
8363 ism_tsb_entries(sfmmu_t *sfmmup, int szc)
8364 {
8365 	ism_blk_t	*ism_blkp = sfmmup->sfmmu_iblk;
8366 	ism_map_t	*ism_map;
8367 	pgcnt_t		npgs = 0;
8368 	pgcnt_t		npgs_scd = 0;
8369 	int		j;
8370 	sf_scd_t	*scdp;
8371 	uchar_t		rid;
8372 
8373 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
8374 	scdp = sfmmup->sfmmu_scdp;
8375 
8376 	for (; ism_blkp != NULL; ism_blkp = ism_blkp->iblk_next) {
8377 		ism_map = ism_blkp->iblk_maps;
8378 		for (j = 0; ism_map[j].imap_ismhat && j < ISM_MAP_SLOTS; j++) {
8379 			rid = ism_map[j].imap_rid;
8380 			ASSERT(rid == SFMMU_INVALID_ISMRID ||
8381 			    rid < sfmmup->sfmmu_srdp->srd_next_ismrid);
8382 
8383 			if (scdp != NULL && rid != SFMMU_INVALID_ISMRID &&
8384 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
8385 				/* ISM is in sfmmup's SCD */
8386 				npgs_scd +=
8387 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8388 			} else {
8389 				/* ISMs is not in SCD */
8390 				npgs +=
8391 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8392 			}
8393 		}
8394 	}
8395 	sfmmup->sfmmu_ismttecnt[szc] = npgs;
8396 	sfmmup->sfmmu_scdismttecnt[szc] = npgs_scd;
8397 	return (npgs);
8398 }
8399 
8400 /*
8401  * Yield the memory claim requirement for an address space.
8402  *
8403  * This is currently implemented as the number of bytes that have active
8404  * hardware translations that have page structures.  Therefore, it can
8405  * underestimate the traditional resident set size, eg, if the
8406  * physical page is present and the hardware translation is missing;
8407  * and it can overestimate the rss, eg, if there are active
8408  * translations to a frame buffer with page structs.
8409  * Also, it does not take sharing into account.
8410  *
8411  * Note that we don't acquire locks here since this function is most often
8412  * called from the clock thread.
8413  */
8414 size_t
8415 hat_get_mapped_size(struct hat *hat)
8416 {
8417 	size_t		assize = 0;
8418 	int 		i;
8419 
8420 	if (hat == NULL)
8421 		return (0);
8422 
8423 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8424 
8425 	for (i = 0; i < mmu_page_sizes; i++)
8426 		assize += ((pgcnt_t)hat->sfmmu_ttecnt[i] +
8427 		    (pgcnt_t)hat->sfmmu_scdrttecnt[i]) * TTEBYTES(i);
8428 
8429 	if (hat->sfmmu_iblk == NULL)
8430 		return (assize);
8431 
8432 	for (i = 0; i < mmu_page_sizes; i++)
8433 		assize += ((pgcnt_t)hat->sfmmu_ismttecnt[i] +
8434 		    (pgcnt_t)hat->sfmmu_scdismttecnt[i]) * TTEBYTES(i);
8435 
8436 	return (assize);
8437 }
8438 
8439 int
8440 hat_stats_enable(struct hat *hat)
8441 {
8442 	hatlock_t	*hatlockp;
8443 
8444 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8445 
8446 	hatlockp = sfmmu_hat_enter(hat);
8447 	hat->sfmmu_rmstat++;
8448 	sfmmu_hat_exit(hatlockp);
8449 	return (1);
8450 }
8451 
8452 void
8453 hat_stats_disable(struct hat *hat)
8454 {
8455 	hatlock_t	*hatlockp;
8456 
8457 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8458 
8459 	hatlockp = sfmmu_hat_enter(hat);
8460 	hat->sfmmu_rmstat--;
8461 	sfmmu_hat_exit(hatlockp);
8462 }
8463 
8464 /*
8465  * Routines for entering or removing  ourselves from the
8466  * ism_hat's mapping list. This is used for both private and
8467  * SCD hats.
8468  */
8469 static void
8470 iment_add(struct ism_ment *iment,  struct hat *ism_hat)
8471 {
8472 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8473 
8474 	iment->iment_prev = NULL;
8475 	iment->iment_next = ism_hat->sfmmu_iment;
8476 	if (ism_hat->sfmmu_iment) {
8477 		ism_hat->sfmmu_iment->iment_prev = iment;
8478 	}
8479 	ism_hat->sfmmu_iment = iment;
8480 }
8481 
8482 static void
8483 iment_sub(struct ism_ment *iment, struct hat *ism_hat)
8484 {
8485 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8486 
8487 	if (ism_hat->sfmmu_iment == NULL) {
8488 		panic("ism map entry remove - no entries");
8489 	}
8490 
8491 	if (iment->iment_prev) {
8492 		ASSERT(ism_hat->sfmmu_iment != iment);
8493 		iment->iment_prev->iment_next = iment->iment_next;
8494 	} else {
8495 		ASSERT(ism_hat->sfmmu_iment == iment);
8496 		ism_hat->sfmmu_iment = iment->iment_next;
8497 	}
8498 
8499 	if (iment->iment_next) {
8500 		iment->iment_next->iment_prev = iment->iment_prev;
8501 	}
8502 
8503 	/*
8504 	 * zero out the entry
8505 	 */
8506 	iment->iment_next = NULL;
8507 	iment->iment_prev = NULL;
8508 	iment->iment_hat =  NULL;
8509 }
8510 
8511 /*
8512  * Hat_share()/unshare() return an (non-zero) error
8513  * when saddr and daddr are not properly aligned.
8514  *
8515  * The top level mapping element determines the alignment
8516  * requirement for saddr and daddr, depending on different
8517  * architectures.
8518  *
8519  * When hat_share()/unshare() are not supported,
8520  * HATOP_SHARE()/UNSHARE() return 0
8521  */
8522 int
8523 hat_share(struct hat *sfmmup, caddr_t addr,
8524 	struct hat *ism_hatid, caddr_t sptaddr, size_t len, uint_t ismszc)
8525 {
8526 	ism_blk_t	*ism_blkp;
8527 	ism_blk_t	*new_iblk;
8528 	ism_map_t 	*ism_map;
8529 	ism_ment_t	*ism_ment;
8530 	int		i, added;
8531 	hatlock_t	*hatlockp;
8532 	int		reload_mmu = 0;
8533 	uint_t		ismshift = page_get_shift(ismszc);
8534 	size_t		ismpgsz = page_get_pagesize(ismszc);
8535 	uint_t		ismmask = (uint_t)ismpgsz - 1;
8536 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8537 	ushort_t	ismhatflag;
8538 	hat_region_cookie_t rcookie;
8539 	sf_scd_t	*old_scdp;
8540 
8541 #ifdef DEBUG
8542 	caddr_t		eaddr = addr + len;
8543 #endif /* DEBUG */
8544 
8545 	ASSERT(ism_hatid != NULL && sfmmup != NULL);
8546 	ASSERT(sptaddr == ISMID_STARTADDR);
8547 	/*
8548 	 * Check the alignment.
8549 	 */
8550 	if (!ISM_ALIGNED(ismshift, addr) || !ISM_ALIGNED(ismshift, sptaddr))
8551 		return (EINVAL);
8552 
8553 	/*
8554 	 * Check size alignment.
8555 	 */
8556 	if (!ISM_ALIGNED(ismshift, len))
8557 		return (EINVAL);
8558 
8559 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
8560 
8561 	/*
8562 	 * Allocate ism_ment for the ism_hat's mapping list, and an
8563 	 * ism map blk in case we need one.  We must do our
8564 	 * allocations before acquiring locks to prevent a deadlock
8565 	 * in the kmem allocator on the mapping list lock.
8566 	 */
8567 	new_iblk = kmem_cache_alloc(ism_blk_cache, KM_SLEEP);
8568 	ism_ment = kmem_cache_alloc(ism_ment_cache, KM_SLEEP);
8569 
8570 	/*
8571 	 * Serialize ISM mappings with the ISM busy flag, and also the
8572 	 * trap handlers.
8573 	 */
8574 	sfmmu_ismhat_enter(sfmmup, 0);
8575 
8576 	/*
8577 	 * Allocate an ism map blk if necessary.
8578 	 */
8579 	if (sfmmup->sfmmu_iblk == NULL) {
8580 		sfmmup->sfmmu_iblk = new_iblk;
8581 		bzero(new_iblk, sizeof (*new_iblk));
8582 		new_iblk->iblk_nextpa = (uint64_t)-1;
8583 		membar_stst();	/* make sure next ptr visible to all CPUs */
8584 		sfmmup->sfmmu_ismblkpa = va_to_pa((caddr_t)new_iblk);
8585 		reload_mmu = 1;
8586 		new_iblk = NULL;
8587 	}
8588 
8589 #ifdef DEBUG
8590 	/*
8591 	 * Make sure mapping does not already exist.
8592 	 */
8593 	ism_blkp = sfmmup->sfmmu_iblk;
8594 	while (ism_blkp != NULL) {
8595 		ism_map = ism_blkp->iblk_maps;
8596 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
8597 			if ((addr >= ism_start(ism_map[i]) &&
8598 			    addr < ism_end(ism_map[i])) ||
8599 			    eaddr > ism_start(ism_map[i]) &&
8600 			    eaddr <= ism_end(ism_map[i])) {
8601 				panic("sfmmu_share: Already mapped!");
8602 			}
8603 		}
8604 		ism_blkp = ism_blkp->iblk_next;
8605 	}
8606 #endif /* DEBUG */
8607 
8608 	ASSERT(ismszc >= TTE4M);
8609 	if (ismszc == TTE4M) {
8610 		ismhatflag = HAT_4M_FLAG;
8611 	} else if (ismszc == TTE32M) {
8612 		ismhatflag = HAT_32M_FLAG;
8613 	} else if (ismszc == TTE256M) {
8614 		ismhatflag = HAT_256M_FLAG;
8615 	}
8616 	/*
8617 	 * Add mapping to first available mapping slot.
8618 	 */
8619 	ism_blkp = sfmmup->sfmmu_iblk;
8620 	added = 0;
8621 	while (!added) {
8622 		ism_map = ism_blkp->iblk_maps;
8623 		for (i = 0; i < ISM_MAP_SLOTS; i++)  {
8624 			if (ism_map[i].imap_ismhat == NULL) {
8625 
8626 				ism_map[i].imap_ismhat = ism_hatid;
8627 				ism_map[i].imap_vb_shift = (uchar_t)ismshift;
8628 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8629 				ism_map[i].imap_hatflags = ismhatflag;
8630 				ism_map[i].imap_sz_mask = ismmask;
8631 				/*
8632 				 * imap_seg is checked in ISM_CHECK to see if
8633 				 * non-NULL, then other info assumed valid.
8634 				 */
8635 				membar_stst();
8636 				ism_map[i].imap_seg = (uintptr_t)addr | sh_size;
8637 				ism_map[i].imap_ment = ism_ment;
8638 
8639 				/*
8640 				 * Now add ourselves to the ism_hat's
8641 				 * mapping list.
8642 				 */
8643 				ism_ment->iment_hat = sfmmup;
8644 				ism_ment->iment_base_va = addr;
8645 				ism_hatid->sfmmu_ismhat = 1;
8646 				mutex_enter(&ism_mlist_lock);
8647 				iment_add(ism_ment, ism_hatid);
8648 				mutex_exit(&ism_mlist_lock);
8649 				added = 1;
8650 				break;
8651 			}
8652 		}
8653 		if (!added && ism_blkp->iblk_next == NULL) {
8654 			ism_blkp->iblk_next = new_iblk;
8655 			new_iblk = NULL;
8656 			bzero(ism_blkp->iblk_next,
8657 			    sizeof (*ism_blkp->iblk_next));
8658 			ism_blkp->iblk_next->iblk_nextpa = (uint64_t)-1;
8659 			membar_stst();
8660 			ism_blkp->iblk_nextpa =
8661 			    va_to_pa((caddr_t)ism_blkp->iblk_next);
8662 		}
8663 		ism_blkp = ism_blkp->iblk_next;
8664 	}
8665 
8666 	/*
8667 	 * After calling hat_join_region, sfmmup may join a new SCD or
8668 	 * move from the old scd to a new scd, in which case, we want to
8669 	 * shrink the sfmmup's private tsb size, i.e., pass shrink to
8670 	 * sfmmu_check_page_sizes at the end of this routine.
8671 	 */
8672 	old_scdp = sfmmup->sfmmu_scdp;
8673 
8674 	rcookie = hat_join_region(sfmmup, addr, len, (void *)ism_hatid, 0,
8675 	    PROT_ALL, ismszc, NULL, HAT_REGION_ISM);
8676 	if (rcookie != HAT_INVALID_REGION_COOKIE) {
8677 		ism_map[i].imap_rid = (uchar_t)((uint64_t)rcookie);
8678 	}
8679 	/*
8680 	 * Update our counters for this sfmmup's ism mappings.
8681 	 */
8682 	for (i = 0; i <= ismszc; i++) {
8683 		if (!(disable_ism_large_pages & (1 << i)))
8684 			(void) ism_tsb_entries(sfmmup, i);
8685 	}
8686 
8687 	/*
8688 	 * For ISM and DISM we do not support 512K pages, so we only only
8689 	 * search the 4M and 8K/64K hashes for 4 pagesize cpus, and search the
8690 	 * 256M or 32M, and 4M and 8K/64K hashes for 6 pagesize cpus.
8691 	 *
8692 	 * Need to set 32M/256M ISM flags to make sure
8693 	 * sfmmu_check_page_sizes() enables them on Panther.
8694 	 */
8695 	ASSERT((disable_ism_large_pages & (1 << TTE512K)) != 0);
8696 
8697 	switch (ismszc) {
8698 	case TTE256M:
8699 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_256M_ISM)) {
8700 			hatlockp = sfmmu_hat_enter(sfmmup);
8701 			SFMMU_FLAGS_SET(sfmmup, HAT_256M_ISM);
8702 			sfmmu_hat_exit(hatlockp);
8703 		}
8704 		break;
8705 	case TTE32M:
8706 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_32M_ISM)) {
8707 			hatlockp = sfmmu_hat_enter(sfmmup);
8708 			SFMMU_FLAGS_SET(sfmmup, HAT_32M_ISM);
8709 			sfmmu_hat_exit(hatlockp);
8710 		}
8711 		break;
8712 	default:
8713 		break;
8714 	}
8715 
8716 	/*
8717 	 * If we updated the ismblkpa for this HAT we must make
8718 	 * sure all CPUs running this process reload their tsbmiss area.
8719 	 * Otherwise they will fail to load the mappings in the tsbmiss
8720 	 * handler and will loop calling pagefault().
8721 	 */
8722 	if (reload_mmu) {
8723 		hatlockp = sfmmu_hat_enter(sfmmup);
8724 		sfmmu_sync_mmustate(sfmmup);
8725 		sfmmu_hat_exit(hatlockp);
8726 	}
8727 
8728 	sfmmu_ismhat_exit(sfmmup, 0);
8729 
8730 	/*
8731 	 * Free up ismblk if we didn't use it.
8732 	 */
8733 	if (new_iblk != NULL)
8734 		kmem_cache_free(ism_blk_cache, new_iblk);
8735 
8736 	/*
8737 	 * Check TSB and TLB page sizes.
8738 	 */
8739 	if (sfmmup->sfmmu_scdp != NULL && old_scdp != sfmmup->sfmmu_scdp) {
8740 		sfmmu_check_page_sizes(sfmmup, 0);
8741 	} else {
8742 		sfmmu_check_page_sizes(sfmmup, 1);
8743 	}
8744 	return (0);
8745 }
8746 
8747 /*
8748  * hat_unshare removes exactly one ism_map from
8749  * this process's as.  It expects multiple calls
8750  * to hat_unshare for multiple shm segments.
8751  */
8752 void
8753 hat_unshare(struct hat *sfmmup, caddr_t addr, size_t len, uint_t ismszc)
8754 {
8755 	ism_map_t 	*ism_map;
8756 	ism_ment_t	*free_ment = NULL;
8757 	ism_blk_t	*ism_blkp;
8758 	struct hat	*ism_hatid;
8759 	int 		found, i;
8760 	hatlock_t	*hatlockp;
8761 	struct tsb_info	*tsbinfo;
8762 	uint_t		ismshift = page_get_shift(ismszc);
8763 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8764 	uchar_t		ism_rid;
8765 	sf_scd_t	*old_scdp;
8766 
8767 	ASSERT(ISM_ALIGNED(ismshift, addr));
8768 	ASSERT(ISM_ALIGNED(ismshift, len));
8769 	ASSERT(sfmmup != NULL);
8770 	ASSERT(sfmmup != ksfmmup);
8771 
8772 	if (sfmmup->sfmmu_xhat_provider) {
8773 		XHAT_UNSHARE(sfmmup, addr, len);
8774 		return;
8775 	} else {
8776 		/*
8777 		 * This must be a CPU HAT. If the address space has
8778 		 * XHATs attached, inform all XHATs that ISM segment
8779 		 * is going away
8780 		 */
8781 		ASSERT(sfmmup->sfmmu_as != NULL);
8782 		if (sfmmup->sfmmu_as->a_xhat != NULL)
8783 			xhat_unshare_all(sfmmup->sfmmu_as, addr, len);
8784 	}
8785 
8786 	/*
8787 	 * Make sure that during the entire time ISM mappings are removed,
8788 	 * the trap handlers serialize behind us, and that no one else
8789 	 * can be mucking with ISM mappings.  This also lets us get away
8790 	 * with not doing expensive cross calls to flush the TLB -- we
8791 	 * just discard the context, flush the entire TSB, and call it
8792 	 * a day.
8793 	 */
8794 	sfmmu_ismhat_enter(sfmmup, 0);
8795 
8796 	/*
8797 	 * Remove the mapping.
8798 	 *
8799 	 * We can't have any holes in the ism map.
8800 	 * The tsb miss code while searching the ism map will
8801 	 * stop on an empty map slot.  So we must move
8802 	 * everyone past the hole up 1 if any.
8803 	 *
8804 	 * Also empty ism map blks are not freed until the
8805 	 * process exits. This is to prevent a MT race condition
8806 	 * between sfmmu_unshare() and sfmmu_tsbmiss_exception().
8807 	 */
8808 	found = 0;
8809 	ism_blkp = sfmmup->sfmmu_iblk;
8810 	while (!found && ism_blkp != NULL) {
8811 		ism_map = ism_blkp->iblk_maps;
8812 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
8813 			if (addr == ism_start(ism_map[i]) &&
8814 			    sh_size == (size_t)(ism_size(ism_map[i]))) {
8815 				found = 1;
8816 				break;
8817 			}
8818 		}
8819 		if (!found)
8820 			ism_blkp = ism_blkp->iblk_next;
8821 	}
8822 
8823 	if (found) {
8824 		ism_hatid = ism_map[i].imap_ismhat;
8825 		ism_rid = ism_map[i].imap_rid;
8826 		ASSERT(ism_hatid != NULL);
8827 		ASSERT(ism_hatid->sfmmu_ismhat == 1);
8828 
8829 		/*
8830 		 * After hat_leave_region, the sfmmup may leave SCD,
8831 		 * in which case, we want to grow the private tsb size when
8832 		 * calling sfmmu_check_page_sizes at the end of the routine.
8833 		 */
8834 		old_scdp = sfmmup->sfmmu_scdp;
8835 		/*
8836 		 * Then remove ourselves from the region.
8837 		 */
8838 		if (ism_rid != SFMMU_INVALID_ISMRID) {
8839 			hat_leave_region(sfmmup, (void *)((uint64_t)ism_rid),
8840 			    HAT_REGION_ISM);
8841 		}
8842 
8843 		/*
8844 		 * And now guarantee that any other cpu
8845 		 * that tries to process an ISM miss
8846 		 * will go to tl=0.
8847 		 */
8848 		hatlockp = sfmmu_hat_enter(sfmmup);
8849 		sfmmu_invalidate_ctx(sfmmup);
8850 		sfmmu_hat_exit(hatlockp);
8851 
8852 		/*
8853 		 * Remove ourselves from the ism mapping list.
8854 		 */
8855 		mutex_enter(&ism_mlist_lock);
8856 		iment_sub(ism_map[i].imap_ment, ism_hatid);
8857 		mutex_exit(&ism_mlist_lock);
8858 		free_ment = ism_map[i].imap_ment;
8859 
8860 		/*
8861 		 * We delete the ism map by copying
8862 		 * the next map over the current one.
8863 		 * We will take the next one in the maps
8864 		 * array or from the next ism_blk.
8865 		 */
8866 		while (ism_blkp != NULL) {
8867 			ism_map = ism_blkp->iblk_maps;
8868 			while (i < (ISM_MAP_SLOTS - 1)) {
8869 				ism_map[i] = ism_map[i + 1];
8870 				i++;
8871 			}
8872 			/* i == (ISM_MAP_SLOTS - 1) */
8873 			ism_blkp = ism_blkp->iblk_next;
8874 			if (ism_blkp != NULL) {
8875 				ism_map[i] = ism_blkp->iblk_maps[0];
8876 				i = 0;
8877 			} else {
8878 				ism_map[i].imap_seg = 0;
8879 				ism_map[i].imap_vb_shift = 0;
8880 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8881 				ism_map[i].imap_hatflags = 0;
8882 				ism_map[i].imap_sz_mask = 0;
8883 				ism_map[i].imap_ismhat = NULL;
8884 				ism_map[i].imap_ment = NULL;
8885 			}
8886 		}
8887 
8888 		/*
8889 		 * Now flush entire TSB for the process, since
8890 		 * demapping page by page can be too expensive.
8891 		 * We don't have to flush the TLB here anymore
8892 		 * since we switch to a new TLB ctx instead.
8893 		 * Also, there is no need to flush if the process
8894 		 * is exiting since the TSB will be freed later.
8895 		 */
8896 		if (!sfmmup->sfmmu_free) {
8897 			hatlockp = sfmmu_hat_enter(sfmmup);
8898 			for (tsbinfo = sfmmup->sfmmu_tsb; tsbinfo != NULL;
8899 			    tsbinfo = tsbinfo->tsb_next) {
8900 				if (tsbinfo->tsb_flags & TSB_SWAPPED)
8901 					continue;
8902 				if (tsbinfo->tsb_flags & TSB_RELOC_FLAG) {
8903 					tsbinfo->tsb_flags |=
8904 					    TSB_FLUSH_NEEDED;
8905 					continue;
8906 				}
8907 
8908 				sfmmu_inv_tsb(tsbinfo->tsb_va,
8909 				    TSB_BYTES(tsbinfo->tsb_szc));
8910 			}
8911 			sfmmu_hat_exit(hatlockp);
8912 		}
8913 	}
8914 
8915 	/*
8916 	 * Update our counters for this sfmmup's ism mappings.
8917 	 */
8918 	for (i = 0; i <= ismszc; i++) {
8919 		if (!(disable_ism_large_pages & (1 << i)))
8920 			(void) ism_tsb_entries(sfmmup, i);
8921 	}
8922 
8923 	sfmmu_ismhat_exit(sfmmup, 0);
8924 
8925 	/*
8926 	 * We must do our freeing here after dropping locks
8927 	 * to prevent a deadlock in the kmem allocator on the
8928 	 * mapping list lock.
8929 	 */
8930 	if (free_ment != NULL)
8931 		kmem_cache_free(ism_ment_cache, free_ment);
8932 
8933 	/*
8934 	 * Check TSB and TLB page sizes if the process isn't exiting.
8935 	 */
8936 	if (!sfmmup->sfmmu_free) {
8937 		if (found && old_scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
8938 			sfmmu_check_page_sizes(sfmmup, 1);
8939 		} else {
8940 			sfmmu_check_page_sizes(sfmmup, 0);
8941 		}
8942 	}
8943 }
8944 
8945 /* ARGSUSED */
8946 static int
8947 sfmmu_idcache_constructor(void *buf, void *cdrarg, int kmflags)
8948 {
8949 	/* void *buf is sfmmu_t pointer */
8950 	bzero(buf, sizeof (sfmmu_t));
8951 
8952 	return (0);
8953 }
8954 
8955 /* ARGSUSED */
8956 static void
8957 sfmmu_idcache_destructor(void *buf, void *cdrarg)
8958 {
8959 	/* void *buf is sfmmu_t pointer */
8960 }
8961 
8962 /*
8963  * setup kmem hmeblks by bzeroing all members and initializing the nextpa
8964  * field to be the pa of this hmeblk
8965  */
8966 /* ARGSUSED */
8967 static int
8968 sfmmu_hblkcache_constructor(void *buf, void *cdrarg, int kmflags)
8969 {
8970 	struct hme_blk *hmeblkp;
8971 
8972 	bzero(buf, (size_t)cdrarg);
8973 	hmeblkp = (struct hme_blk *)buf;
8974 	hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
8975 
8976 #ifdef	HBLK_TRACE
8977 	mutex_init(&hmeblkp->hblk_audit_lock, NULL, MUTEX_DEFAULT, NULL);
8978 #endif	/* HBLK_TRACE */
8979 
8980 	return (0);
8981 }
8982 
8983 /* ARGSUSED */
8984 static void
8985 sfmmu_hblkcache_destructor(void *buf, void *cdrarg)
8986 {
8987 
8988 #ifdef	HBLK_TRACE
8989 
8990 	struct hme_blk *hmeblkp;
8991 
8992 	hmeblkp = (struct hme_blk *)buf;
8993 	mutex_destroy(&hmeblkp->hblk_audit_lock);
8994 
8995 #endif	/* HBLK_TRACE */
8996 }
8997 
8998 #define	SFMMU_CACHE_RECLAIM_SCAN_RATIO 8
8999 static int sfmmu_cache_reclaim_scan_ratio = SFMMU_CACHE_RECLAIM_SCAN_RATIO;
9000 /*
9001  * The kmem allocator will callback into our reclaim routine when the system
9002  * is running low in memory.  We traverse the hash and free up all unused but
9003  * still cached hme_blks.  We also traverse the free list and free them up
9004  * as well.
9005  */
9006 /*ARGSUSED*/
9007 static void
9008 sfmmu_hblkcache_reclaim(void *cdrarg)
9009 {
9010 	int i;
9011 	uint64_t hblkpa, prevpa, nx_pa;
9012 	struct hmehash_bucket *hmebp;
9013 	struct hme_blk *hmeblkp, *nx_hblk, *pr_hblk = NULL;
9014 	static struct hmehash_bucket *uhmehash_reclaim_hand;
9015 	static struct hmehash_bucket *khmehash_reclaim_hand;
9016 	struct hme_blk *list = NULL;
9017 
9018 	hmebp = uhmehash_reclaim_hand;
9019 	if (hmebp == NULL || hmebp > &uhme_hash[UHMEHASH_SZ])
9020 		uhmehash_reclaim_hand = hmebp = uhme_hash;
9021 	uhmehash_reclaim_hand += UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9022 
9023 	for (i = UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9024 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9025 			hmeblkp = hmebp->hmeblkp;
9026 			hblkpa = hmebp->hmeh_nextpa;
9027 			prevpa = 0;
9028 			pr_hblk = NULL;
9029 			while (hmeblkp) {
9030 				nx_hblk = hmeblkp->hblk_next;
9031 				nx_pa = hmeblkp->hblk_nextpa;
9032 				if (!hmeblkp->hblk_vcnt &&
9033 				    !hmeblkp->hblk_hmecnt) {
9034 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9035 					    prevpa, pr_hblk);
9036 					sfmmu_hblk_free(hmebp, hmeblkp,
9037 					    hblkpa, &list);
9038 				} else {
9039 					pr_hblk = hmeblkp;
9040 					prevpa = hblkpa;
9041 				}
9042 				hmeblkp = nx_hblk;
9043 				hblkpa = nx_pa;
9044 			}
9045 			SFMMU_HASH_UNLOCK(hmebp);
9046 		}
9047 		if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
9048 			hmebp = uhme_hash;
9049 	}
9050 
9051 	hmebp = khmehash_reclaim_hand;
9052 	if (hmebp == NULL || hmebp > &khme_hash[KHMEHASH_SZ])
9053 		khmehash_reclaim_hand = hmebp = khme_hash;
9054 	khmehash_reclaim_hand += KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9055 
9056 	for (i = KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9057 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9058 			hmeblkp = hmebp->hmeblkp;
9059 			hblkpa = hmebp->hmeh_nextpa;
9060 			prevpa = 0;
9061 			pr_hblk = NULL;
9062 			while (hmeblkp) {
9063 				nx_hblk = hmeblkp->hblk_next;
9064 				nx_pa = hmeblkp->hblk_nextpa;
9065 				if (!hmeblkp->hblk_vcnt &&
9066 				    !hmeblkp->hblk_hmecnt) {
9067 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9068 					    prevpa, pr_hblk);
9069 					sfmmu_hblk_free(hmebp, hmeblkp,
9070 					    hblkpa, &list);
9071 				} else {
9072 					pr_hblk = hmeblkp;
9073 					prevpa = hblkpa;
9074 				}
9075 				hmeblkp = nx_hblk;
9076 				hblkpa = nx_pa;
9077 			}
9078 			SFMMU_HASH_UNLOCK(hmebp);
9079 		}
9080 		if (hmebp++ == &khme_hash[KHMEHASH_SZ])
9081 			hmebp = khme_hash;
9082 	}
9083 	sfmmu_hblks_list_purge(&list);
9084 }
9085 
9086 /*
9087  * sfmmu_get_ppvcolor should become a vm_machdep or hatop interface.
9088  * same goes for sfmmu_get_addrvcolor().
9089  *
9090  * This function will return the virtual color for the specified page. The
9091  * virtual color corresponds to this page current mapping or its last mapping.
9092  * It is used by memory allocators to choose addresses with the correct
9093  * alignment so vac consistency is automatically maintained.  If the page
9094  * has no color it returns -1.
9095  */
9096 /*ARGSUSED*/
9097 int
9098 sfmmu_get_ppvcolor(struct page *pp)
9099 {
9100 #ifdef VAC
9101 	int color;
9102 
9103 	if (!(cache & CACHE_VAC) || PP_NEWPAGE(pp)) {
9104 		return (-1);
9105 	}
9106 	color = PP_GET_VCOLOR(pp);
9107 	ASSERT(color < mmu_btop(shm_alignment));
9108 	return (color);
9109 #else
9110 	return (-1);
9111 #endif	/* VAC */
9112 }
9113 
9114 /*
9115  * This function will return the desired alignment for vac consistency
9116  * (vac color) given a virtual address.  If no vac is present it returns -1.
9117  */
9118 /*ARGSUSED*/
9119 int
9120 sfmmu_get_addrvcolor(caddr_t vaddr)
9121 {
9122 #ifdef VAC
9123 	if (cache & CACHE_VAC) {
9124 		return (addr_to_vcolor(vaddr));
9125 	} else {
9126 		return (-1);
9127 	}
9128 #else
9129 	return (-1);
9130 #endif	/* VAC */
9131 }
9132 
9133 #ifdef VAC
9134 /*
9135  * Check for conflicts.
9136  * A conflict exists if the new and existent mappings do not match in
9137  * their "shm_alignment fields. If conflicts exist, the existant mappings
9138  * are flushed unless one of them is locked. If one of them is locked, then
9139  * the mappings are flushed and converted to non-cacheable mappings.
9140  */
9141 static void
9142 sfmmu_vac_conflict(struct hat *hat, caddr_t addr, page_t *pp)
9143 {
9144 	struct hat *tmphat;
9145 	struct sf_hment *sfhmep, *tmphme = NULL;
9146 	struct hme_blk *hmeblkp;
9147 	int vcolor;
9148 	tte_t tte;
9149 
9150 	ASSERT(sfmmu_mlist_held(pp));
9151 	ASSERT(!PP_ISNC(pp));		/* page better be cacheable */
9152 
9153 	vcolor = addr_to_vcolor(addr);
9154 	if (PP_NEWPAGE(pp)) {
9155 		PP_SET_VCOLOR(pp, vcolor);
9156 		return;
9157 	}
9158 
9159 	if (PP_GET_VCOLOR(pp) == vcolor) {
9160 		return;
9161 	}
9162 
9163 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
9164 		/*
9165 		 * Previous user of page had a different color
9166 		 * but since there are no current users
9167 		 * we just flush the cache and change the color.
9168 		 */
9169 		SFMMU_STAT(sf_pgcolor_conflict);
9170 		sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9171 		PP_SET_VCOLOR(pp, vcolor);
9172 		return;
9173 	}
9174 
9175 	/*
9176 	 * If we get here we have a vac conflict with a current
9177 	 * mapping.  VAC conflict policy is as follows.
9178 	 * - The default is to unload the other mappings unless:
9179 	 * - If we have a large mapping we uncache the page.
9180 	 * We need to uncache the rest of the large page too.
9181 	 * - If any of the mappings are locked we uncache the page.
9182 	 * - If the requested mapping is inconsistent
9183 	 * with another mapping and that mapping
9184 	 * is in the same address space we have to
9185 	 * make it non-cached.  The default thing
9186 	 * to do is unload the inconsistent mapping
9187 	 * but if they are in the same address space
9188 	 * we run the risk of unmapping the pc or the
9189 	 * stack which we will use as we return to the user,
9190 	 * in which case we can then fault on the thing
9191 	 * we just unloaded and get into an infinite loop.
9192 	 */
9193 	if (PP_ISMAPPED_LARGE(pp)) {
9194 		int sz;
9195 
9196 		/*
9197 		 * Existing mapping is for big pages. We don't unload
9198 		 * existing big mappings to satisfy new mappings.
9199 		 * Always convert all mappings to TNC.
9200 		 */
9201 		sz = fnd_mapping_sz(pp);
9202 		pp = PP_GROUPLEADER(pp, sz);
9203 		SFMMU_STAT_ADD(sf_uncache_conflict, TTEPAGES(sz));
9204 		sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH,
9205 		    TTEPAGES(sz));
9206 
9207 		return;
9208 	}
9209 
9210 	/*
9211 	 * check if any mapping is in same as or if it is locked
9212 	 * since in that case we need to uncache.
9213 	 */
9214 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9215 		tmphme = sfhmep->hme_next;
9216 		if (IS_PAHME(sfhmep))
9217 			continue;
9218 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9219 		if (hmeblkp->hblk_xhat_bit)
9220 			continue;
9221 		tmphat = hblktosfmmu(hmeblkp);
9222 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
9223 		ASSERT(TTE_IS_VALID(&tte));
9224 		if (hmeblkp->hblk_shared || tmphat == hat ||
9225 		    hmeblkp->hblk_lckcnt) {
9226 			/*
9227 			 * We have an uncache conflict
9228 			 */
9229 			SFMMU_STAT(sf_uncache_conflict);
9230 			sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH, 1);
9231 			return;
9232 		}
9233 	}
9234 
9235 	/*
9236 	 * We have an unload conflict
9237 	 * We have already checked for LARGE mappings, therefore
9238 	 * the remaining mapping(s) must be TTE8K.
9239 	 */
9240 	SFMMU_STAT(sf_unload_conflict);
9241 
9242 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9243 		tmphme = sfhmep->hme_next;
9244 		if (IS_PAHME(sfhmep))
9245 			continue;
9246 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9247 		if (hmeblkp->hblk_xhat_bit)
9248 			continue;
9249 		ASSERT(!hmeblkp->hblk_shared);
9250 		(void) sfmmu_pageunload(pp, sfhmep, TTE8K);
9251 	}
9252 
9253 	if (PP_ISMAPPED_KPM(pp))
9254 		sfmmu_kpm_vac_unload(pp, addr);
9255 
9256 	/*
9257 	 * Unloads only do TLB flushes so we need to flush the
9258 	 * cache here.
9259 	 */
9260 	sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9261 	PP_SET_VCOLOR(pp, vcolor);
9262 }
9263 
9264 /*
9265  * Whenever a mapping is unloaded and the page is in TNC state,
9266  * we see if the page can be made cacheable again. 'pp' is
9267  * the page that we just unloaded a mapping from, the size
9268  * of mapping that was unloaded is 'ottesz'.
9269  * Remark:
9270  * The recache policy for mpss pages can leave a performance problem
9271  * under the following circumstances:
9272  * . A large page in uncached mode has just been unmapped.
9273  * . All constituent pages are TNC due to a conflicting small mapping.
9274  * . There are many other, non conflicting, small mappings around for
9275  *   a lot of the constituent pages.
9276  * . We're called w/ the "old" groupleader page and the old ottesz,
9277  *   but this is irrelevant, since we're no more "PP_ISMAPPED_LARGE", so
9278  *   we end up w/ TTE8K or npages == 1.
9279  * . We call tst_tnc w/ the old groupleader only, and if there is no
9280  *   conflict, we re-cache only this page.
9281  * . All other small mappings are not checked and will be left in TNC mode.
9282  * The problem is not very serious because:
9283  * . mpss is actually only defined for heap and stack, so the probability
9284  *   is not very high that a large page mapping exists in parallel to a small
9285  *   one (this is possible, but seems to be bad programming style in the
9286  *   appl).
9287  * . The problem gets a little bit more serious, when those TNC pages
9288  *   have to be mapped into kernel space, e.g. for networking.
9289  * . When VAC alias conflicts occur in applications, this is regarded
9290  *   as an application bug. So if kstat's show them, the appl should
9291  *   be changed anyway.
9292  */
9293 void
9294 conv_tnc(page_t *pp, int ottesz)
9295 {
9296 	int cursz, dosz;
9297 	pgcnt_t curnpgs, dopgs;
9298 	pgcnt_t pg64k;
9299 	page_t *pp2;
9300 
9301 	/*
9302 	 * Determine how big a range we check for TNC and find
9303 	 * leader page. cursz is the size of the biggest
9304 	 * mapping that still exist on 'pp'.
9305 	 */
9306 	if (PP_ISMAPPED_LARGE(pp)) {
9307 		cursz = fnd_mapping_sz(pp);
9308 	} else {
9309 		cursz = TTE8K;
9310 	}
9311 
9312 	if (ottesz >= cursz) {
9313 		dosz = ottesz;
9314 		pp2 = pp;
9315 	} else {
9316 		dosz = cursz;
9317 		pp2 = PP_GROUPLEADER(pp, dosz);
9318 	}
9319 
9320 	pg64k = TTEPAGES(TTE64K);
9321 	dopgs = TTEPAGES(dosz);
9322 
9323 	ASSERT(dopgs == 1 || ((dopgs & (pg64k - 1)) == 0));
9324 
9325 	while (dopgs != 0) {
9326 		curnpgs = TTEPAGES(cursz);
9327 		if (tst_tnc(pp2, curnpgs)) {
9328 			SFMMU_STAT_ADD(sf_recache, curnpgs);
9329 			sfmmu_page_cache_array(pp2, HAT_CACHE, CACHE_NO_FLUSH,
9330 			    curnpgs);
9331 		}
9332 
9333 		ASSERT(dopgs >= curnpgs);
9334 		dopgs -= curnpgs;
9335 
9336 		if (dopgs == 0) {
9337 			break;
9338 		}
9339 
9340 		pp2 = PP_PAGENEXT_N(pp2, curnpgs);
9341 		if (((dopgs & (pg64k - 1)) == 0) && PP_ISMAPPED_LARGE(pp2)) {
9342 			cursz = fnd_mapping_sz(pp2);
9343 		} else {
9344 			cursz = TTE8K;
9345 		}
9346 	}
9347 }
9348 
9349 /*
9350  * Returns 1 if page(s) can be converted from TNC to cacheable setting,
9351  * returns 0 otherwise. Note that oaddr argument is valid for only
9352  * 8k pages.
9353  */
9354 int
9355 tst_tnc(page_t *pp, pgcnt_t npages)
9356 {
9357 	struct	sf_hment *sfhme;
9358 	struct	hme_blk *hmeblkp;
9359 	tte_t	tte;
9360 	caddr_t	vaddr;
9361 	int	clr_valid = 0;
9362 	int 	color, color1, bcolor;
9363 	int	i, ncolors;
9364 
9365 	ASSERT(pp != NULL);
9366 	ASSERT(!(cache & CACHE_WRITEBACK));
9367 
9368 	if (npages > 1) {
9369 		ncolors = CACHE_NUM_COLOR;
9370 	}
9371 
9372 	for (i = 0; i < npages; i++) {
9373 		ASSERT(sfmmu_mlist_held(pp));
9374 		ASSERT(PP_ISTNC(pp));
9375 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
9376 
9377 		if (PP_ISPNC(pp)) {
9378 			return (0);
9379 		}
9380 
9381 		clr_valid = 0;
9382 		if (PP_ISMAPPED_KPM(pp)) {
9383 			caddr_t kpmvaddr;
9384 
9385 			ASSERT(kpm_enable);
9386 			kpmvaddr = hat_kpm_page2va(pp, 1);
9387 			ASSERT(!(npages > 1 && IS_KPM_ALIAS_RANGE(kpmvaddr)));
9388 			color1 = addr_to_vcolor(kpmvaddr);
9389 			clr_valid = 1;
9390 		}
9391 
9392 		for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9393 			if (IS_PAHME(sfhme))
9394 				continue;
9395 			hmeblkp = sfmmu_hmetohblk(sfhme);
9396 			if (hmeblkp->hblk_xhat_bit)
9397 				continue;
9398 
9399 			sfmmu_copytte(&sfhme->hme_tte, &tte);
9400 			ASSERT(TTE_IS_VALID(&tte));
9401 
9402 			vaddr = tte_to_vaddr(hmeblkp, tte);
9403 			color = addr_to_vcolor(vaddr);
9404 
9405 			if (npages > 1) {
9406 				/*
9407 				 * If there is a big mapping, make sure
9408 				 * 8K mapping is consistent with the big
9409 				 * mapping.
9410 				 */
9411 				bcolor = i % ncolors;
9412 				if (color != bcolor) {
9413 					return (0);
9414 				}
9415 			}
9416 			if (!clr_valid) {
9417 				clr_valid = 1;
9418 				color1 = color;
9419 			}
9420 
9421 			if (color1 != color) {
9422 				return (0);
9423 			}
9424 		}
9425 
9426 		pp = PP_PAGENEXT(pp);
9427 	}
9428 
9429 	return (1);
9430 }
9431 
9432 void
9433 sfmmu_page_cache_array(page_t *pp, int flags, int cache_flush_flag,
9434 	pgcnt_t npages)
9435 {
9436 	kmutex_t *pmtx;
9437 	int i, ncolors, bcolor;
9438 	kpm_hlk_t *kpmp;
9439 	cpuset_t cpuset;
9440 
9441 	ASSERT(pp != NULL);
9442 	ASSERT(!(cache & CACHE_WRITEBACK));
9443 
9444 	kpmp = sfmmu_kpm_kpmp_enter(pp, npages);
9445 	pmtx = sfmmu_page_enter(pp);
9446 
9447 	/*
9448 	 * Fast path caching single unmapped page
9449 	 */
9450 	if (npages == 1 && !PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp) &&
9451 	    flags == HAT_CACHE) {
9452 		PP_CLRTNC(pp);
9453 		PP_CLRPNC(pp);
9454 		sfmmu_page_exit(pmtx);
9455 		sfmmu_kpm_kpmp_exit(kpmp);
9456 		return;
9457 	}
9458 
9459 	/*
9460 	 * We need to capture all cpus in order to change cacheability
9461 	 * because we can't allow one cpu to access the same physical
9462 	 * page using a cacheable and a non-cachebale mapping at the same
9463 	 * time. Since we may end up walking the ism mapping list
9464 	 * have to grab it's lock now since we can't after all the
9465 	 * cpus have been captured.
9466 	 */
9467 	sfmmu_hat_lock_all();
9468 	mutex_enter(&ism_mlist_lock);
9469 	kpreempt_disable();
9470 	cpuset = cpu_ready_set;
9471 	xc_attention(cpuset);
9472 
9473 	if (npages > 1) {
9474 		/*
9475 		 * Make sure all colors are flushed since the
9476 		 * sfmmu_page_cache() only flushes one color-
9477 		 * it does not know big pages.
9478 		 */
9479 		ncolors = CACHE_NUM_COLOR;
9480 		if (flags & HAT_TMPNC) {
9481 			for (i = 0; i < ncolors; i++) {
9482 				sfmmu_cache_flushcolor(i, pp->p_pagenum);
9483 			}
9484 			cache_flush_flag = CACHE_NO_FLUSH;
9485 		}
9486 	}
9487 
9488 	for (i = 0; i < npages; i++) {
9489 
9490 		ASSERT(sfmmu_mlist_held(pp));
9491 
9492 		if (!(flags == HAT_TMPNC && PP_ISTNC(pp))) {
9493 
9494 			if (npages > 1) {
9495 				bcolor = i % ncolors;
9496 			} else {
9497 				bcolor = NO_VCOLOR;
9498 			}
9499 
9500 			sfmmu_page_cache(pp, flags, cache_flush_flag,
9501 			    bcolor);
9502 		}
9503 
9504 		pp = PP_PAGENEXT(pp);
9505 	}
9506 
9507 	xt_sync(cpuset);
9508 	xc_dismissed(cpuset);
9509 	mutex_exit(&ism_mlist_lock);
9510 	sfmmu_hat_unlock_all();
9511 	sfmmu_page_exit(pmtx);
9512 	sfmmu_kpm_kpmp_exit(kpmp);
9513 	kpreempt_enable();
9514 }
9515 
9516 /*
9517  * This function changes the virtual cacheability of all mappings to a
9518  * particular page.  When changing from uncache to cacheable the mappings will
9519  * only be changed if all of them have the same virtual color.
9520  * We need to flush the cache in all cpus.  It is possible that
9521  * a process referenced a page as cacheable but has sinced exited
9522  * and cleared the mapping list.  We still to flush it but have no
9523  * state so all cpus is the only alternative.
9524  */
9525 static void
9526 sfmmu_page_cache(page_t *pp, int flags, int cache_flush_flag, int bcolor)
9527 {
9528 	struct	sf_hment *sfhme;
9529 	struct	hme_blk *hmeblkp;
9530 	sfmmu_t *sfmmup;
9531 	tte_t	tte, ttemod;
9532 	caddr_t	vaddr;
9533 	int	ret, color;
9534 	pfn_t	pfn;
9535 
9536 	color = bcolor;
9537 	pfn = pp->p_pagenum;
9538 
9539 	for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9540 
9541 		if (IS_PAHME(sfhme))
9542 			continue;
9543 		hmeblkp = sfmmu_hmetohblk(sfhme);
9544 
9545 		if (hmeblkp->hblk_xhat_bit)
9546 			continue;
9547 
9548 		sfmmu_copytte(&sfhme->hme_tte, &tte);
9549 		ASSERT(TTE_IS_VALID(&tte));
9550 		vaddr = tte_to_vaddr(hmeblkp, tte);
9551 		color = addr_to_vcolor(vaddr);
9552 
9553 #ifdef DEBUG
9554 		if ((flags & HAT_CACHE) && bcolor != NO_VCOLOR) {
9555 			ASSERT(color == bcolor);
9556 		}
9557 #endif
9558 
9559 		ASSERT(flags != HAT_TMPNC || color == PP_GET_VCOLOR(pp));
9560 
9561 		ttemod = tte;
9562 		if (flags & (HAT_UNCACHE | HAT_TMPNC)) {
9563 			TTE_CLR_VCACHEABLE(&ttemod);
9564 		} else {	/* flags & HAT_CACHE */
9565 			TTE_SET_VCACHEABLE(&ttemod);
9566 		}
9567 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
9568 		if (ret < 0) {
9569 			/*
9570 			 * Since all cpus are captured modifytte should not
9571 			 * fail.
9572 			 */
9573 			panic("sfmmu_page_cache: write to tte failed");
9574 		}
9575 
9576 		sfmmup = hblktosfmmu(hmeblkp);
9577 		if (cache_flush_flag == CACHE_FLUSH) {
9578 			/*
9579 			 * Flush TSBs, TLBs and caches
9580 			 */
9581 			if (hmeblkp->hblk_shared) {
9582 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9583 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9584 				sf_region_t *rgnp;
9585 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9586 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9587 				ASSERT(srdp != NULL);
9588 				rgnp = srdp->srd_hmergnp[rid];
9589 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9590 				    srdp, rgnp, rid);
9591 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9592 				    hmeblkp, 0);
9593 				sfmmu_cache_flush(pfn, addr_to_vcolor(vaddr));
9594 			} else if (sfmmup->sfmmu_ismhat) {
9595 				if (flags & HAT_CACHE) {
9596 					SFMMU_STAT(sf_ism_recache);
9597 				} else {
9598 					SFMMU_STAT(sf_ism_uncache);
9599 				}
9600 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9601 				    pfn, CACHE_FLUSH);
9602 			} else {
9603 				sfmmu_tlbcache_demap(vaddr, sfmmup, hmeblkp,
9604 				    pfn, 0, FLUSH_ALL_CPUS, CACHE_FLUSH, 1);
9605 			}
9606 
9607 			/*
9608 			 * all cache entries belonging to this pfn are
9609 			 * now flushed.
9610 			 */
9611 			cache_flush_flag = CACHE_NO_FLUSH;
9612 		} else {
9613 			/*
9614 			 * Flush only TSBs and TLBs.
9615 			 */
9616 			if (hmeblkp->hblk_shared) {
9617 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9618 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9619 				sf_region_t *rgnp;
9620 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9621 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9622 				ASSERT(srdp != NULL);
9623 				rgnp = srdp->srd_hmergnp[rid];
9624 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9625 				    srdp, rgnp, rid);
9626 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9627 				    hmeblkp, 0);
9628 			} else if (sfmmup->sfmmu_ismhat) {
9629 				if (flags & HAT_CACHE) {
9630 					SFMMU_STAT(sf_ism_recache);
9631 				} else {
9632 					SFMMU_STAT(sf_ism_uncache);
9633 				}
9634 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9635 				    pfn, CACHE_NO_FLUSH);
9636 			} else {
9637 				sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 1);
9638 			}
9639 		}
9640 	}
9641 
9642 	if (PP_ISMAPPED_KPM(pp))
9643 		sfmmu_kpm_page_cache(pp, flags, cache_flush_flag);
9644 
9645 	switch (flags) {
9646 
9647 		default:
9648 			panic("sfmmu_pagecache: unknown flags");
9649 			break;
9650 
9651 		case HAT_CACHE:
9652 			PP_CLRTNC(pp);
9653 			PP_CLRPNC(pp);
9654 			PP_SET_VCOLOR(pp, color);
9655 			break;
9656 
9657 		case HAT_TMPNC:
9658 			PP_SETTNC(pp);
9659 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9660 			break;
9661 
9662 		case HAT_UNCACHE:
9663 			PP_SETPNC(pp);
9664 			PP_CLRTNC(pp);
9665 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9666 			break;
9667 	}
9668 }
9669 #endif	/* VAC */
9670 
9671 
9672 /*
9673  * Wrapper routine used to return a context.
9674  *
9675  * It's the responsibility of the caller to guarantee that the
9676  * process serializes on calls here by taking the HAT lock for
9677  * the hat.
9678  *
9679  */
9680 static void
9681 sfmmu_get_ctx(sfmmu_t *sfmmup)
9682 {
9683 	mmu_ctx_t *mmu_ctxp;
9684 	uint_t pstate_save;
9685 	int ret;
9686 
9687 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9688 	ASSERT(sfmmup != ksfmmup);
9689 
9690 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID)) {
9691 		sfmmu_setup_tsbinfo(sfmmup);
9692 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ALLCTX_INVALID);
9693 	}
9694 
9695 	kpreempt_disable();
9696 
9697 	mmu_ctxp = CPU_MMU_CTXP(CPU);
9698 	ASSERT(mmu_ctxp);
9699 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
9700 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
9701 
9702 	/*
9703 	 * Do a wrap-around if cnum reaches the max # cnum supported by a MMU.
9704 	 */
9705 	if (mmu_ctxp->mmu_cnum == mmu_ctxp->mmu_nctxs)
9706 		sfmmu_ctx_wrap_around(mmu_ctxp);
9707 
9708 	/*
9709 	 * Let the MMU set up the page sizes to use for
9710 	 * this context in the TLB. Don't program 2nd dtlb for ism hat.
9711 	 */
9712 	if ((&mmu_set_ctx_page_sizes) && (sfmmup->sfmmu_ismhat == 0)) {
9713 		mmu_set_ctx_page_sizes(sfmmup);
9714 	}
9715 
9716 	/*
9717 	 * sfmmu_alloc_ctx and sfmmu_load_mmustate will be performed with
9718 	 * interrupts disabled to prevent race condition with wrap-around
9719 	 * ctx invalidatation. In sun4v, ctx invalidation also involves
9720 	 * a HV call to set the number of TSBs to 0. If interrupts are not
9721 	 * disabled until after sfmmu_load_mmustate is complete TSBs may
9722 	 * become assigned to INVALID_CONTEXT. This is not allowed.
9723 	 */
9724 	pstate_save = sfmmu_disable_intrs();
9725 
9726 	if (sfmmu_alloc_ctx(sfmmup, 1, CPU, SFMMU_PRIVATE) &&
9727 	    sfmmup->sfmmu_scdp != NULL) {
9728 		sf_scd_t *scdp = sfmmup->sfmmu_scdp;
9729 		sfmmu_t *scsfmmup = scdp->scd_sfmmup;
9730 		ret = sfmmu_alloc_ctx(scsfmmup, 1, CPU, SFMMU_SHARED);
9731 		/* debug purpose only */
9732 		ASSERT(!ret || scsfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
9733 		    != INVALID_CONTEXT);
9734 	}
9735 	sfmmu_load_mmustate(sfmmup);
9736 
9737 	sfmmu_enable_intrs(pstate_save);
9738 
9739 	kpreempt_enable();
9740 }
9741 
9742 /*
9743  * When all cnums are used up in a MMU, cnum will wrap around to the
9744  * next generation and start from 2.
9745  */
9746 static void
9747 sfmmu_ctx_wrap_around(mmu_ctx_t *mmu_ctxp)
9748 {
9749 
9750 	/* caller must have disabled the preemption */
9751 	ASSERT(curthread->t_preempt >= 1);
9752 	ASSERT(mmu_ctxp != NULL);
9753 
9754 	/* acquire Per-MMU (PM) spin lock */
9755 	mutex_enter(&mmu_ctxp->mmu_lock);
9756 
9757 	/* re-check to see if wrap-around is needed */
9758 	if (mmu_ctxp->mmu_cnum < mmu_ctxp->mmu_nctxs)
9759 		goto done;
9760 
9761 	SFMMU_MMU_STAT(mmu_wrap_around);
9762 
9763 	/* update gnum */
9764 	ASSERT(mmu_ctxp->mmu_gnum != 0);
9765 	mmu_ctxp->mmu_gnum++;
9766 	if (mmu_ctxp->mmu_gnum == 0 ||
9767 	    mmu_ctxp->mmu_gnum > MAX_SFMMU_GNUM_VAL) {
9768 		cmn_err(CE_PANIC, "mmu_gnum of mmu_ctx 0x%p is out of bound.",
9769 		    (void *)mmu_ctxp);
9770 	}
9771 
9772 	if (mmu_ctxp->mmu_ncpus > 1) {
9773 		cpuset_t cpuset;
9774 
9775 		membar_enter(); /* make sure updated gnum visible */
9776 
9777 		SFMMU_XCALL_STATS(NULL);
9778 
9779 		/* xcall to others on the same MMU to invalidate ctx */
9780 		cpuset = mmu_ctxp->mmu_cpuset;
9781 		ASSERT(CPU_IN_SET(cpuset, CPU->cpu_id));
9782 		CPUSET_DEL(cpuset, CPU->cpu_id);
9783 		CPUSET_AND(cpuset, cpu_ready_set);
9784 
9785 		/*
9786 		 * Pass in INVALID_CONTEXT as the first parameter to
9787 		 * sfmmu_raise_tsb_exception, which invalidates the context
9788 		 * of any process running on the CPUs in the MMU.
9789 		 */
9790 		xt_some(cpuset, sfmmu_raise_tsb_exception,
9791 		    INVALID_CONTEXT, INVALID_CONTEXT);
9792 		xt_sync(cpuset);
9793 
9794 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
9795 	}
9796 
9797 	if (sfmmu_getctx_sec() != INVALID_CONTEXT) {
9798 		sfmmu_setctx_sec(INVALID_CONTEXT);
9799 		sfmmu_clear_utsbinfo();
9800 	}
9801 
9802 	/*
9803 	 * No xcall is needed here. For sun4u systems all CPUs in context
9804 	 * domain share a single physical MMU therefore it's enough to flush
9805 	 * TLB on local CPU. On sun4v systems we use 1 global context
9806 	 * domain and flush all remote TLBs in sfmmu_raise_tsb_exception
9807 	 * handler. Note that vtag_flushall_uctxs() is called
9808 	 * for Ultra II machine, where the equivalent flushall functionality
9809 	 * is implemented in SW, and only user ctx TLB entries are flushed.
9810 	 */
9811 	if (&vtag_flushall_uctxs != NULL) {
9812 		vtag_flushall_uctxs();
9813 	} else {
9814 		vtag_flushall();
9815 	}
9816 
9817 	/* reset mmu cnum, skips cnum 0 and 1 */
9818 	mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
9819 
9820 done:
9821 	mutex_exit(&mmu_ctxp->mmu_lock);
9822 }
9823 
9824 
9825 /*
9826  * For multi-threaded process, set the process context to INVALID_CONTEXT
9827  * so that it faults and reloads the MMU state from TL=0. For single-threaded
9828  * process, we can just load the MMU state directly without having to
9829  * set context invalid. Caller must hold the hat lock since we don't
9830  * acquire it here.
9831  */
9832 static void
9833 sfmmu_sync_mmustate(sfmmu_t *sfmmup)
9834 {
9835 	uint_t cnum;
9836 	uint_t pstate_save;
9837 
9838 	ASSERT(sfmmup != ksfmmup);
9839 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9840 
9841 	kpreempt_disable();
9842 
9843 	/*
9844 	 * We check whether the pass'ed-in sfmmup is the same as the
9845 	 * current running proc. This is to makes sure the current proc
9846 	 * stays single-threaded if it already is.
9847 	 */
9848 	if ((sfmmup == curthread->t_procp->p_as->a_hat) &&
9849 	    (curthread->t_procp->p_lwpcnt == 1)) {
9850 		/* single-thread */
9851 		cnum = sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum;
9852 		if (cnum != INVALID_CONTEXT) {
9853 			uint_t curcnum;
9854 			/*
9855 			 * Disable interrupts to prevent race condition
9856 			 * with sfmmu_ctx_wrap_around ctx invalidation.
9857 			 * In sun4v, ctx invalidation involves setting
9858 			 * TSB to NULL, hence, interrupts should be disabled
9859 			 * untill after sfmmu_load_mmustate is completed.
9860 			 */
9861 			pstate_save = sfmmu_disable_intrs();
9862 			curcnum = sfmmu_getctx_sec();
9863 			if (curcnum == cnum)
9864 				sfmmu_load_mmustate(sfmmup);
9865 			sfmmu_enable_intrs(pstate_save);
9866 			ASSERT(curcnum == cnum || curcnum == INVALID_CONTEXT);
9867 		}
9868 	} else {
9869 		/*
9870 		 * multi-thread
9871 		 * or when sfmmup is not the same as the curproc.
9872 		 */
9873 		sfmmu_invalidate_ctx(sfmmup);
9874 	}
9875 
9876 	kpreempt_enable();
9877 }
9878 
9879 
9880 /*
9881  * Replace the specified TSB with a new TSB.  This function gets called when
9882  * we grow, shrink or swapin a TSB.  When swapping in a TSB (TSB_SWAPIN), the
9883  * TSB_FORCEALLOC flag may be used to force allocation of a minimum-sized TSB
9884  * (8K).
9885  *
9886  * Caller must hold the HAT lock, but should assume any tsb_info
9887  * pointers it has are no longer valid after calling this function.
9888  *
9889  * Return values:
9890  *	TSB_ALLOCFAIL	Failed to allocate a TSB, due to memory constraints
9891  *	TSB_LOSTRACE	HAT is busy, i.e. another thread is already doing
9892  *			something to this tsbinfo/TSB
9893  *	TSB_SUCCESS	Operation succeeded
9894  */
9895 static tsb_replace_rc_t
9896 sfmmu_replace_tsb(sfmmu_t *sfmmup, struct tsb_info *old_tsbinfo, uint_t szc,
9897     hatlock_t *hatlockp, uint_t flags)
9898 {
9899 	struct tsb_info *new_tsbinfo = NULL;
9900 	struct tsb_info *curtsb, *prevtsb;
9901 	uint_t tte_sz_mask;
9902 	int i;
9903 
9904 	ASSERT(sfmmup != ksfmmup);
9905 	ASSERT(sfmmup->sfmmu_ismhat == 0);
9906 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9907 	ASSERT(szc <= tsb_max_growsize);
9908 
9909 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_BUSY))
9910 		return (TSB_LOSTRACE);
9911 
9912 	/*
9913 	 * Find the tsb_info ahead of this one in the list, and
9914 	 * also make sure that the tsb_info passed in really
9915 	 * exists!
9916 	 */
9917 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9918 	    curtsb != old_tsbinfo && curtsb != NULL;
9919 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
9920 		;
9921 	ASSERT(curtsb != NULL);
9922 
9923 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9924 		/*
9925 		 * The process is swapped out, so just set the new size
9926 		 * code.  When it swaps back in, we'll allocate a new one
9927 		 * of the new chosen size.
9928 		 */
9929 		curtsb->tsb_szc = szc;
9930 		return (TSB_SUCCESS);
9931 	}
9932 	SFMMU_FLAGS_SET(sfmmup, HAT_BUSY);
9933 
9934 	tte_sz_mask = old_tsbinfo->tsb_ttesz_mask;
9935 
9936 	/*
9937 	 * All initialization is done inside of sfmmu_tsbinfo_alloc().
9938 	 * If we fail to allocate a TSB, exit.
9939 	 *
9940 	 * If tsb grows with new tsb size > 4M and old tsb size < 4M,
9941 	 * then try 4M slab after the initial alloc fails.
9942 	 *
9943 	 * If tsb swapin with tsb size > 4M, then try 4M after the
9944 	 * initial alloc fails.
9945 	 */
9946 	sfmmu_hat_exit(hatlockp);
9947 	if (sfmmu_tsbinfo_alloc(&new_tsbinfo, szc,
9948 	    tte_sz_mask, flags, sfmmup) &&
9949 	    (!(flags & (TSB_GROW | TSB_SWAPIN)) || (szc <= TSB_4M_SZCODE) ||
9950 	    (!(flags & TSB_SWAPIN) &&
9951 	    (old_tsbinfo->tsb_szc >= TSB_4M_SZCODE)) ||
9952 	    sfmmu_tsbinfo_alloc(&new_tsbinfo, TSB_4M_SZCODE,
9953 	    tte_sz_mask, flags, sfmmup))) {
9954 		(void) sfmmu_hat_enter(sfmmup);
9955 		if (!(flags & TSB_SWAPIN))
9956 			SFMMU_STAT(sf_tsb_resize_failures);
9957 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9958 		return (TSB_ALLOCFAIL);
9959 	}
9960 	(void) sfmmu_hat_enter(sfmmup);
9961 
9962 	/*
9963 	 * Re-check to make sure somebody else didn't muck with us while we
9964 	 * didn't hold the HAT lock.  If the process swapped out, fine, just
9965 	 * exit; this can happen if we try to shrink the TSB from the context
9966 	 * of another process (such as on an ISM unmap), though it is rare.
9967 	 */
9968 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9969 		SFMMU_STAT(sf_tsb_resize_failures);
9970 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9971 		sfmmu_hat_exit(hatlockp);
9972 		sfmmu_tsbinfo_free(new_tsbinfo);
9973 		(void) sfmmu_hat_enter(sfmmup);
9974 		return (TSB_LOSTRACE);
9975 	}
9976 
9977 #ifdef	DEBUG
9978 	/* Reverify that the tsb_info still exists.. for debugging only */
9979 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9980 	    curtsb != old_tsbinfo && curtsb != NULL;
9981 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
9982 		;
9983 	ASSERT(curtsb != NULL);
9984 #endif	/* DEBUG */
9985 
9986 	/*
9987 	 * Quiesce any CPUs running this process on their next TLB miss
9988 	 * so they atomically see the new tsb_info.  We temporarily set the
9989 	 * context to invalid context so new threads that come on processor
9990 	 * after we do the xcall to cpusran will also serialize behind the
9991 	 * HAT lock on TLB miss and will see the new TSB.  Since this short
9992 	 * race with a new thread coming on processor is relatively rare,
9993 	 * this synchronization mechanism should be cheaper than always
9994 	 * pausing all CPUs for the duration of the setup, which is what
9995 	 * the old implementation did.  This is particuarly true if we are
9996 	 * copying a huge chunk of memory around during that window.
9997 	 *
9998 	 * The memory barriers are to make sure things stay consistent
9999 	 * with resume() since it does not hold the HAT lock while
10000 	 * walking the list of tsb_info structures.
10001 	 */
10002 	if ((flags & TSB_SWAPIN) != TSB_SWAPIN) {
10003 		/* The TSB is either growing or shrinking. */
10004 		sfmmu_invalidate_ctx(sfmmup);
10005 	} else {
10006 		/*
10007 		 * It is illegal to swap in TSBs from a process other
10008 		 * than a process being swapped in.  This in turn
10009 		 * implies we do not have a valid MMU context here
10010 		 * since a process needs one to resolve translation
10011 		 * misses.
10012 		 */
10013 		ASSERT(curthread->t_procp->p_as->a_hat == sfmmup);
10014 	}
10015 
10016 #ifdef DEBUG
10017 	ASSERT(max_mmu_ctxdoms > 0);
10018 
10019 	/*
10020 	 * Process should have INVALID_CONTEXT on all MMUs
10021 	 */
10022 	for (i = 0; i < max_mmu_ctxdoms; i++) {
10023 
10024 		ASSERT(sfmmup->sfmmu_ctxs[i].cnum == INVALID_CONTEXT);
10025 	}
10026 #endif
10027 
10028 	new_tsbinfo->tsb_next = old_tsbinfo->tsb_next;
10029 	membar_stst();	/* strict ordering required */
10030 	if (prevtsb)
10031 		prevtsb->tsb_next = new_tsbinfo;
10032 	else
10033 		sfmmup->sfmmu_tsb = new_tsbinfo;
10034 	membar_enter();	/* make sure new TSB globally visible */
10035 
10036 	/*
10037 	 * We need to migrate TSB entries from the old TSB to the new TSB
10038 	 * if tsb_remap_ttes is set and the TSB is growing.
10039 	 */
10040 	if (tsb_remap_ttes && ((flags & TSB_GROW) == TSB_GROW))
10041 		sfmmu_copy_tsb(old_tsbinfo, new_tsbinfo);
10042 
10043 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
10044 
10045 	/*
10046 	 * Drop the HAT lock to free our old tsb_info.
10047 	 */
10048 	sfmmu_hat_exit(hatlockp);
10049 
10050 	if ((flags & TSB_GROW) == TSB_GROW) {
10051 		SFMMU_STAT(sf_tsb_grow);
10052 	} else if ((flags & TSB_SHRINK) == TSB_SHRINK) {
10053 		SFMMU_STAT(sf_tsb_shrink);
10054 	}
10055 
10056 	sfmmu_tsbinfo_free(old_tsbinfo);
10057 
10058 	(void) sfmmu_hat_enter(sfmmup);
10059 	return (TSB_SUCCESS);
10060 }
10061 
10062 /*
10063  * This function will re-program hat pgsz array, and invalidate the
10064  * process' context, forcing the process to switch to another
10065  * context on the next TLB miss, and therefore start using the
10066  * TLB that is reprogrammed for the new page sizes.
10067  */
10068 void
10069 sfmmu_reprog_pgsz_arr(sfmmu_t *sfmmup, uint8_t *tmp_pgsz)
10070 {
10071 	int i;
10072 	hatlock_t *hatlockp = NULL;
10073 
10074 	hatlockp = sfmmu_hat_enter(sfmmup);
10075 	/* USIII+-IV+ optimization, requires hat lock */
10076 	if (tmp_pgsz) {
10077 		for (i = 0; i < mmu_page_sizes; i++)
10078 			sfmmup->sfmmu_pgsz[i] = tmp_pgsz[i];
10079 	}
10080 	SFMMU_STAT(sf_tlb_reprog_pgsz);
10081 
10082 	sfmmu_invalidate_ctx(sfmmup);
10083 
10084 	sfmmu_hat_exit(hatlockp);
10085 }
10086 
10087 /*
10088  * The scd_rttecnt field in the SCD must be updated to take account of the
10089  * regions which it contains.
10090  */
10091 static void
10092 sfmmu_set_scd_rttecnt(sf_srd_t *srdp, sf_scd_t *scdp)
10093 {
10094 	uint_t rid;
10095 	uint_t i, j;
10096 	ulong_t w;
10097 	sf_region_t *rgnp;
10098 
10099 	ASSERT(srdp != NULL);
10100 
10101 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
10102 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
10103 			continue;
10104 		}
10105 
10106 		j = 0;
10107 		while (w) {
10108 			if (!(w & 0x1)) {
10109 				j++;
10110 				w >>= 1;
10111 				continue;
10112 			}
10113 			rid = (i << BT_ULSHIFT) | j;
10114 			j++;
10115 			w >>= 1;
10116 
10117 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
10118 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
10119 			rgnp = srdp->srd_hmergnp[rid];
10120 			ASSERT(rgnp->rgn_refcnt > 0);
10121 			ASSERT(rgnp->rgn_id == rid);
10122 
10123 			scdp->scd_rttecnt[rgnp->rgn_pgszc] +=
10124 			    rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
10125 
10126 			/*
10127 			 * Maintain the tsb0 inflation cnt for the regions
10128 			 * in the SCD.
10129 			 */
10130 			if (rgnp->rgn_pgszc >= TTE4M) {
10131 				scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt +=
10132 				    rgnp->rgn_size >>
10133 				    (TTE_PAGE_SHIFT(TTE8K) + 2);
10134 			}
10135 		}
10136 	}
10137 }
10138 
10139 /*
10140  * This function assumes that there are either four or six supported page
10141  * sizes and at most two programmable TLBs, so we need to decide which
10142  * page sizes are most important and then tell the MMU layer so it
10143  * can adjust the TLB page sizes accordingly (if supported).
10144  *
10145  * If these assumptions change, this function will need to be
10146  * updated to support whatever the new limits are.
10147  *
10148  * The growing flag is nonzero if we are growing the address space,
10149  * and zero if it is shrinking.  This allows us to decide whether
10150  * to grow or shrink our TSB, depending upon available memory
10151  * conditions.
10152  */
10153 static void
10154 sfmmu_check_page_sizes(sfmmu_t *sfmmup, int growing)
10155 {
10156 	uint64_t ttecnt[MMU_PAGE_SIZES];
10157 	uint64_t tte8k_cnt, tte4m_cnt;
10158 	uint8_t i;
10159 	int sectsb_thresh;
10160 
10161 	/*
10162 	 * Kernel threads, processes with small address spaces not using
10163 	 * large pages, and dummy ISM HATs need not apply.
10164 	 */
10165 	if (sfmmup == ksfmmup || sfmmup->sfmmu_ismhat != NULL)
10166 		return;
10167 
10168 	if (!SFMMU_LGPGS_INUSE(sfmmup) &&
10169 	    sfmmup->sfmmu_ttecnt[TTE8K] <= tsb_rss_factor)
10170 		return;
10171 
10172 	for (i = 0; i < mmu_page_sizes; i++) {
10173 		ttecnt[i] = sfmmup->sfmmu_ttecnt[i] +
10174 		    sfmmup->sfmmu_ismttecnt[i];
10175 	}
10176 
10177 	/* Check pagesizes in use, and possibly reprogram DTLB. */
10178 	if (&mmu_check_page_sizes)
10179 		mmu_check_page_sizes(sfmmup, ttecnt);
10180 
10181 	/*
10182 	 * Calculate the number of 8k ttes to represent the span of these
10183 	 * pages.
10184 	 */
10185 	tte8k_cnt = ttecnt[TTE8K] +
10186 	    (ttecnt[TTE64K] << (MMU_PAGESHIFT64K - MMU_PAGESHIFT)) +
10187 	    (ttecnt[TTE512K] << (MMU_PAGESHIFT512K - MMU_PAGESHIFT));
10188 	if (mmu_page_sizes == max_mmu_page_sizes) {
10189 		tte4m_cnt = ttecnt[TTE4M] +
10190 		    (ttecnt[TTE32M] << (MMU_PAGESHIFT32M - MMU_PAGESHIFT4M)) +
10191 		    (ttecnt[TTE256M] << (MMU_PAGESHIFT256M - MMU_PAGESHIFT4M));
10192 	} else {
10193 		tte4m_cnt = ttecnt[TTE4M];
10194 	}
10195 
10196 	/*
10197 	 * Inflate tte8k_cnt to allow for region large page allocation failure.
10198 	 */
10199 	tte8k_cnt += sfmmup->sfmmu_tsb0_4minflcnt;
10200 
10201 	/*
10202 	 * Inflate TSB sizes by a factor of 2 if this process
10203 	 * uses 4M text pages to minimize extra conflict misses
10204 	 * in the first TSB since without counting text pages
10205 	 * 8K TSB may become too small.
10206 	 *
10207 	 * Also double the size of the second TSB to minimize
10208 	 * extra conflict misses due to competition between 4M text pages
10209 	 * and data pages.
10210 	 *
10211 	 * We need to adjust the second TSB allocation threshold by the
10212 	 * inflation factor, since there is no point in creating a second
10213 	 * TSB when we know all the mappings can fit in the I/D TLBs.
10214 	 */
10215 	sectsb_thresh = tsb_sectsb_threshold;
10216 	if (sfmmup->sfmmu_flags & HAT_4MTEXT_FLAG) {
10217 		tte8k_cnt <<= 1;
10218 		tte4m_cnt <<= 1;
10219 		sectsb_thresh <<= 1;
10220 	}
10221 
10222 	/*
10223 	 * Check to see if our TSB is the right size; we may need to
10224 	 * grow or shrink it.  If the process is small, our work is
10225 	 * finished at this point.
10226 	 */
10227 	if (tte8k_cnt <= tsb_rss_factor && tte4m_cnt <= sectsb_thresh) {
10228 		return;
10229 	}
10230 	sfmmu_size_tsb(sfmmup, growing, tte8k_cnt, tte4m_cnt, sectsb_thresh);
10231 }
10232 
10233 static void
10234 sfmmu_size_tsb(sfmmu_t *sfmmup, int growing, uint64_t tte8k_cnt,
10235 	uint64_t tte4m_cnt, int sectsb_thresh)
10236 {
10237 	int tsb_bits;
10238 	uint_t tsb_szc;
10239 	struct tsb_info *tsbinfop;
10240 	hatlock_t *hatlockp = NULL;
10241 
10242 	hatlockp = sfmmu_hat_enter(sfmmup);
10243 	ASSERT(hatlockp != NULL);
10244 	tsbinfop = sfmmup->sfmmu_tsb;
10245 	ASSERT(tsbinfop != NULL);
10246 
10247 	/*
10248 	 * If we're growing, select the size based on RSS.  If we're
10249 	 * shrinking, leave some room so we don't have to turn around and
10250 	 * grow again immediately.
10251 	 */
10252 	if (growing)
10253 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
10254 	else
10255 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt << 1);
10256 
10257 	if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10258 	    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10259 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10260 		    hatlockp, TSB_SHRINK);
10261 	} else if (growing && tsb_szc > tsbinfop->tsb_szc && TSB_OK_GROW()) {
10262 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10263 		    hatlockp, TSB_GROW);
10264 	}
10265 	tsbinfop = sfmmup->sfmmu_tsb;
10266 
10267 	/*
10268 	 * With the TLB and first TSB out of the way, we need to see if
10269 	 * we need a second TSB for 4M pages.  If we managed to reprogram
10270 	 * the TLB page sizes above, the process will start using this new
10271 	 * TSB right away; otherwise, it will start using it on the next
10272 	 * context switch.  Either way, it's no big deal so there's no
10273 	 * synchronization with the trap handlers here unless we grow the
10274 	 * TSB (in which case it's required to prevent using the old one
10275 	 * after it's freed). Note: second tsb is required for 32M/256M
10276 	 * page sizes.
10277 	 */
10278 	if (tte4m_cnt > sectsb_thresh) {
10279 		/*
10280 		 * If we're growing, select the size based on RSS.  If we're
10281 		 * shrinking, leave some room so we don't have to turn
10282 		 * around and grow again immediately.
10283 		 */
10284 		if (growing)
10285 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
10286 		else
10287 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt << 1);
10288 		if (tsbinfop->tsb_next == NULL) {
10289 			struct tsb_info *newtsb;
10290 			int allocflags = SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)?
10291 			    0 : TSB_ALLOC;
10292 
10293 			sfmmu_hat_exit(hatlockp);
10294 
10295 			/*
10296 			 * Try to allocate a TSB for 4[32|256]M pages.  If we
10297 			 * can't get the size we want, retry w/a minimum sized
10298 			 * TSB.  If that still didn't work, give up; we can
10299 			 * still run without one.
10300 			 */
10301 			tsb_bits = (mmu_page_sizes == max_mmu_page_sizes)?
10302 			    TSB4M|TSB32M|TSB256M:TSB4M;
10303 			if ((sfmmu_tsbinfo_alloc(&newtsb, tsb_szc, tsb_bits,
10304 			    allocflags, sfmmup)) &&
10305 			    (tsb_szc <= TSB_4M_SZCODE ||
10306 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
10307 			    tsb_bits, allocflags, sfmmup)) &&
10308 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_MIN_SZCODE,
10309 			    tsb_bits, allocflags, sfmmup)) {
10310 				return;
10311 			}
10312 
10313 			hatlockp = sfmmu_hat_enter(sfmmup);
10314 
10315 			sfmmu_invalidate_ctx(sfmmup);
10316 
10317 			if (sfmmup->sfmmu_tsb->tsb_next == NULL) {
10318 				sfmmup->sfmmu_tsb->tsb_next = newtsb;
10319 				SFMMU_STAT(sf_tsb_sectsb_create);
10320 				sfmmu_hat_exit(hatlockp);
10321 				return;
10322 			} else {
10323 				/*
10324 				 * It's annoying, but possible for us
10325 				 * to get here.. we dropped the HAT lock
10326 				 * because of locking order in the kmem
10327 				 * allocator, and while we were off getting
10328 				 * our memory, some other thread decided to
10329 				 * do us a favor and won the race to get a
10330 				 * second TSB for this process.  Sigh.
10331 				 */
10332 				sfmmu_hat_exit(hatlockp);
10333 				sfmmu_tsbinfo_free(newtsb);
10334 				return;
10335 			}
10336 		}
10337 
10338 		/*
10339 		 * We have a second TSB, see if it's big enough.
10340 		 */
10341 		tsbinfop = tsbinfop->tsb_next;
10342 
10343 		/*
10344 		 * Check to see if our second TSB is the right size;
10345 		 * we may need to grow or shrink it.
10346 		 * To prevent thrashing (e.g. growing the TSB on a
10347 		 * subsequent map operation), only try to shrink if
10348 		 * the TSB reach exceeds twice the virtual address
10349 		 * space size.
10350 		 */
10351 		if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10352 		    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10353 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10354 			    tsb_szc, hatlockp, TSB_SHRINK);
10355 		} else if (growing && tsb_szc > tsbinfop->tsb_szc &&
10356 		    TSB_OK_GROW()) {
10357 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10358 			    tsb_szc, hatlockp, TSB_GROW);
10359 		}
10360 	}
10361 
10362 	sfmmu_hat_exit(hatlockp);
10363 }
10364 
10365 /*
10366  * Free up a sfmmu
10367  * Since the sfmmu is currently embedded in the hat struct we simply zero
10368  * out our fields and free up the ism map blk list if any.
10369  */
10370 static void
10371 sfmmu_free_sfmmu(sfmmu_t *sfmmup)
10372 {
10373 	ism_blk_t	*blkp, *nx_blkp;
10374 #ifdef	DEBUG
10375 	ism_map_t	*map;
10376 	int 		i;
10377 #endif
10378 
10379 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
10380 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
10381 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
10382 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
10383 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
10384 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
10385 	ASSERT(SF_RGNMAP_ISNULL(sfmmup));
10386 
10387 	sfmmup->sfmmu_free = 0;
10388 	sfmmup->sfmmu_ismhat = 0;
10389 
10390 	blkp = sfmmup->sfmmu_iblk;
10391 	sfmmup->sfmmu_iblk = NULL;
10392 
10393 	while (blkp) {
10394 #ifdef	DEBUG
10395 		map = blkp->iblk_maps;
10396 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
10397 			ASSERT(map[i].imap_seg == 0);
10398 			ASSERT(map[i].imap_ismhat == NULL);
10399 			ASSERT(map[i].imap_ment == NULL);
10400 		}
10401 #endif
10402 		nx_blkp = blkp->iblk_next;
10403 		blkp->iblk_next = NULL;
10404 		blkp->iblk_nextpa = (uint64_t)-1;
10405 		kmem_cache_free(ism_blk_cache, blkp);
10406 		blkp = nx_blkp;
10407 	}
10408 }
10409 
10410 /*
10411  * Locking primitves accessed by HATLOCK macros
10412  */
10413 
10414 #define	SFMMU_SPL_MTX	(0x0)
10415 #define	SFMMU_ML_MTX	(0x1)
10416 
10417 #define	SFMMU_MLSPL_MTX(type, pg)	(((type) == SFMMU_SPL_MTX) ? \
10418 					    SPL_HASH(pg) : MLIST_HASH(pg))
10419 
10420 kmutex_t *
10421 sfmmu_page_enter(struct page *pp)
10422 {
10423 	return (sfmmu_mlspl_enter(pp, SFMMU_SPL_MTX));
10424 }
10425 
10426 void
10427 sfmmu_page_exit(kmutex_t *spl)
10428 {
10429 	mutex_exit(spl);
10430 }
10431 
10432 int
10433 sfmmu_page_spl_held(struct page *pp)
10434 {
10435 	return (sfmmu_mlspl_held(pp, SFMMU_SPL_MTX));
10436 }
10437 
10438 kmutex_t *
10439 sfmmu_mlist_enter(struct page *pp)
10440 {
10441 	return (sfmmu_mlspl_enter(pp, SFMMU_ML_MTX));
10442 }
10443 
10444 void
10445 sfmmu_mlist_exit(kmutex_t *mml)
10446 {
10447 	mutex_exit(mml);
10448 }
10449 
10450 int
10451 sfmmu_mlist_held(struct page *pp)
10452 {
10453 
10454 	return (sfmmu_mlspl_held(pp, SFMMU_ML_MTX));
10455 }
10456 
10457 /*
10458  * Common code for sfmmu_mlist_enter() and sfmmu_page_enter().  For
10459  * sfmmu_mlist_enter() case mml_table lock array is used and for
10460  * sfmmu_page_enter() sfmmu_page_lock lock array is used.
10461  *
10462  * The lock is taken on a root page so that it protects an operation on all
10463  * constituent pages of a large page pp belongs to.
10464  *
10465  * The routine takes a lock from the appropriate array. The lock is determined
10466  * by hashing the root page. After taking the lock this routine checks if the
10467  * root page has the same size code that was used to determine the root (i.e
10468  * that root hasn't changed).  If root page has the expected p_szc field we
10469  * have the right lock and it's returned to the caller. If root's p_szc
10470  * decreased we release the lock and retry from the beginning.  This case can
10471  * happen due to hat_page_demote() decreasing p_szc between our load of p_szc
10472  * value and taking the lock. The number of retries due to p_szc decrease is
10473  * limited by the maximum p_szc value. If p_szc is 0 we return the lock
10474  * determined by hashing pp itself.
10475  *
10476  * If our caller doesn't hold a SE_SHARED or SE_EXCL lock on pp it's also
10477  * possible that p_szc can increase. To increase p_szc a thread has to lock
10478  * all constituent pages EXCL and do hat_pageunload() on all of them. All the
10479  * callers that don't hold a page locked recheck if hmeblk through which pp
10480  * was found still maps this pp.  If it doesn't map it anymore returned lock
10481  * is immediately dropped. Therefore if sfmmu_mlspl_enter() hits the case of
10482  * p_szc increase after taking the lock it returns this lock without further
10483  * retries because in this case the caller doesn't care about which lock was
10484  * taken. The caller will drop it right away.
10485  *
10486  * After the routine returns it's guaranteed that hat_page_demote() can't
10487  * change p_szc field of any of constituent pages of a large page pp belongs
10488  * to as long as pp was either locked at least SHARED prior to this call or
10489  * the caller finds that hment that pointed to this pp still references this
10490  * pp (this also assumes that the caller holds hme hash bucket lock so that
10491  * the same pp can't be remapped into the same hmeblk after it was unmapped by
10492  * hat_pageunload()).
10493  */
10494 static kmutex_t *
10495 sfmmu_mlspl_enter(struct page *pp, int type)
10496 {
10497 	kmutex_t	*mtx;
10498 	uint_t		prev_rszc = UINT_MAX;
10499 	page_t		*rootpp;
10500 	uint_t		szc;
10501 	uint_t		rszc;
10502 	uint_t		pszc = pp->p_szc;
10503 
10504 	ASSERT(pp != NULL);
10505 
10506 again:
10507 	if (pszc == 0) {
10508 		mtx = SFMMU_MLSPL_MTX(type, pp);
10509 		mutex_enter(mtx);
10510 		return (mtx);
10511 	}
10512 
10513 	/* The lock lives in the root page */
10514 	rootpp = PP_GROUPLEADER(pp, pszc);
10515 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10516 	mutex_enter(mtx);
10517 
10518 	/*
10519 	 * Return mml in the following 3 cases:
10520 	 *
10521 	 * 1) If pp itself is root since if its p_szc decreased before we took
10522 	 * the lock pp is still the root of smaller szc page. And if its p_szc
10523 	 * increased it doesn't matter what lock we return (see comment in
10524 	 * front of this routine).
10525 	 *
10526 	 * 2) If pp's not root but rootpp is the root of a rootpp->p_szc size
10527 	 * large page we have the right lock since any previous potential
10528 	 * hat_page_demote() is done demoting from greater than current root's
10529 	 * p_szc because hat_page_demote() changes root's p_szc last. No
10530 	 * further hat_page_demote() can start or be in progress since it
10531 	 * would need the same lock we currently hold.
10532 	 *
10533 	 * 3) If rootpp's p_szc increased since previous iteration it doesn't
10534 	 * matter what lock we return (see comment in front of this routine).
10535 	 */
10536 	if (pp == rootpp || (rszc = rootpp->p_szc) == pszc ||
10537 	    rszc >= prev_rszc) {
10538 		return (mtx);
10539 	}
10540 
10541 	/*
10542 	 * hat_page_demote() could have decreased root's p_szc.
10543 	 * In this case pp's p_szc must also be smaller than pszc.
10544 	 * Retry.
10545 	 */
10546 	if (rszc < pszc) {
10547 		szc = pp->p_szc;
10548 		if (szc < pszc) {
10549 			mutex_exit(mtx);
10550 			pszc = szc;
10551 			goto again;
10552 		}
10553 		/*
10554 		 * pp's p_szc increased after it was decreased.
10555 		 * page cannot be mapped. Return current lock. The caller
10556 		 * will drop it right away.
10557 		 */
10558 		return (mtx);
10559 	}
10560 
10561 	/*
10562 	 * root's p_szc is greater than pp's p_szc.
10563 	 * hat_page_demote() is not done with all pages
10564 	 * yet. Wait for it to complete.
10565 	 */
10566 	mutex_exit(mtx);
10567 	rootpp = PP_GROUPLEADER(rootpp, rszc);
10568 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10569 	mutex_enter(mtx);
10570 	mutex_exit(mtx);
10571 	prev_rszc = rszc;
10572 	goto again;
10573 }
10574 
10575 static int
10576 sfmmu_mlspl_held(struct page *pp, int type)
10577 {
10578 	kmutex_t	*mtx;
10579 
10580 	ASSERT(pp != NULL);
10581 	/* The lock lives in the root page */
10582 	pp = PP_PAGEROOT(pp);
10583 	ASSERT(pp != NULL);
10584 
10585 	mtx = SFMMU_MLSPL_MTX(type, pp);
10586 	return (MUTEX_HELD(mtx));
10587 }
10588 
10589 static uint_t
10590 sfmmu_get_free_hblk(struct hme_blk **hmeblkpp, uint_t critical)
10591 {
10592 	struct  hme_blk *hblkp;
10593 
10594 	if (freehblkp != NULL) {
10595 		mutex_enter(&freehblkp_lock);
10596 		if (freehblkp != NULL) {
10597 			/*
10598 			 * If the current thread is owning hblk_reserve OR
10599 			 * critical request from sfmmu_hblk_steal()
10600 			 * let it succeed even if freehblkcnt is really low.
10601 			 */
10602 			if (freehblkcnt <= HBLK_RESERVE_MIN && !critical) {
10603 				SFMMU_STAT(sf_get_free_throttle);
10604 				mutex_exit(&freehblkp_lock);
10605 				return (0);
10606 			}
10607 			freehblkcnt--;
10608 			*hmeblkpp = freehblkp;
10609 			hblkp = *hmeblkpp;
10610 			freehblkp = hblkp->hblk_next;
10611 			mutex_exit(&freehblkp_lock);
10612 			hblkp->hblk_next = NULL;
10613 			SFMMU_STAT(sf_get_free_success);
10614 			return (1);
10615 		}
10616 		mutex_exit(&freehblkp_lock);
10617 	}
10618 	SFMMU_STAT(sf_get_free_fail);
10619 	return (0);
10620 }
10621 
10622 static uint_t
10623 sfmmu_put_free_hblk(struct hme_blk *hmeblkp, uint_t critical)
10624 {
10625 	struct  hme_blk *hblkp;
10626 
10627 	/*
10628 	 * If the current thread is mapping into kernel space,
10629 	 * let it succede even if freehblkcnt is max
10630 	 * so that it will avoid freeing it to kmem.
10631 	 * This will prevent stack overflow due to
10632 	 * possible recursion since kmem_cache_free()
10633 	 * might require creation of a slab which
10634 	 * in turn needs an hmeblk to map that slab;
10635 	 * let's break this vicious chain at the first
10636 	 * opportunity.
10637 	 */
10638 	if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10639 		mutex_enter(&freehblkp_lock);
10640 		if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10641 			SFMMU_STAT(sf_put_free_success);
10642 			freehblkcnt++;
10643 			hmeblkp->hblk_next = freehblkp;
10644 			freehblkp = hmeblkp;
10645 			mutex_exit(&freehblkp_lock);
10646 			return (1);
10647 		}
10648 		mutex_exit(&freehblkp_lock);
10649 	}
10650 
10651 	/*
10652 	 * Bring down freehblkcnt to HBLK_RESERVE_CNT. We are here
10653 	 * only if freehblkcnt is at least HBLK_RESERVE_CNT *and*
10654 	 * we are not in the process of mapping into kernel space.
10655 	 */
10656 	ASSERT(!critical);
10657 	while (freehblkcnt > HBLK_RESERVE_CNT) {
10658 		mutex_enter(&freehblkp_lock);
10659 		if (freehblkcnt > HBLK_RESERVE_CNT) {
10660 			freehblkcnt--;
10661 			hblkp = freehblkp;
10662 			freehblkp = hblkp->hblk_next;
10663 			mutex_exit(&freehblkp_lock);
10664 			ASSERT(get_hblk_cache(hblkp) == sfmmu8_cache);
10665 			kmem_cache_free(sfmmu8_cache, hblkp);
10666 			continue;
10667 		}
10668 		mutex_exit(&freehblkp_lock);
10669 	}
10670 	SFMMU_STAT(sf_put_free_fail);
10671 	return (0);
10672 }
10673 
10674 static void
10675 sfmmu_hblk_swap(struct hme_blk *new)
10676 {
10677 	struct hme_blk *old, *hblkp, *prev;
10678 	uint64_t hblkpa, prevpa, newpa;
10679 	caddr_t	base, vaddr, endaddr;
10680 	struct hmehash_bucket *hmebp;
10681 	struct sf_hment *osfhme, *nsfhme;
10682 	page_t *pp;
10683 	kmutex_t *pml;
10684 	tte_t tte;
10685 
10686 #ifdef	DEBUG
10687 	hmeblk_tag		hblktag;
10688 	struct hme_blk		*found;
10689 #endif
10690 	old = HBLK_RESERVE;
10691 	ASSERT(!old->hblk_shared);
10692 
10693 	/*
10694 	 * save pa before bcopy clobbers it
10695 	 */
10696 	newpa = new->hblk_nextpa;
10697 
10698 	base = (caddr_t)get_hblk_base(old);
10699 	endaddr = base + get_hblk_span(old);
10700 
10701 	/*
10702 	 * acquire hash bucket lock.
10703 	 */
10704 	hmebp = sfmmu_tteload_acquire_hashbucket(ksfmmup, base, TTE8K,
10705 	    SFMMU_INVALID_SHMERID);
10706 
10707 	/*
10708 	 * copy contents from old to new
10709 	 */
10710 	bcopy((void *)old, (void *)new, HME8BLK_SZ);
10711 
10712 	/*
10713 	 * add new to hash chain
10714 	 */
10715 	sfmmu_hblk_hash_add(hmebp, new, newpa);
10716 
10717 	/*
10718 	 * search hash chain for hblk_reserve; this needs to be performed
10719 	 * after adding new, otherwise prevpa and prev won't correspond
10720 	 * to the hblk which is prior to old in hash chain when we call
10721 	 * sfmmu_hblk_hash_rm to remove old later.
10722 	 */
10723 	for (prevpa = 0, prev = NULL,
10724 	    hblkpa = hmebp->hmeh_nextpa, hblkp = hmebp->hmeblkp;
10725 	    hblkp != NULL && hblkp != old;
10726 	    prevpa = hblkpa, prev = hblkp,
10727 	    hblkpa = hblkp->hblk_nextpa, hblkp = hblkp->hblk_next)
10728 		;
10729 
10730 	if (hblkp != old)
10731 		panic("sfmmu_hblk_swap: hblk_reserve not found");
10732 
10733 	/*
10734 	 * p_mapping list is still pointing to hments in hblk_reserve;
10735 	 * fix up p_mapping list so that they point to hments in new.
10736 	 *
10737 	 * Since all these mappings are created by hblk_reserve_thread
10738 	 * on the way and it's using at least one of the buffers from each of
10739 	 * the newly minted slabs, there is no danger of any of these
10740 	 * mappings getting unloaded by another thread.
10741 	 *
10742 	 * tsbmiss could only modify ref/mod bits of hments in old/new.
10743 	 * Since all of these hments hold mappings established by segkmem
10744 	 * and mappings in segkmem are setup with HAT_NOSYNC, ref/mod bits
10745 	 * have no meaning for the mappings in hblk_reserve.  hments in
10746 	 * old and new are identical except for ref/mod bits.
10747 	 */
10748 	for (vaddr = base; vaddr < endaddr; vaddr += TTEBYTES(TTE8K)) {
10749 
10750 		HBLKTOHME(osfhme, old, vaddr);
10751 		sfmmu_copytte(&osfhme->hme_tte, &tte);
10752 
10753 		if (TTE_IS_VALID(&tte)) {
10754 			if ((pp = osfhme->hme_page) == NULL)
10755 				panic("sfmmu_hblk_swap: page not mapped");
10756 
10757 			pml = sfmmu_mlist_enter(pp);
10758 
10759 			if (pp != osfhme->hme_page)
10760 				panic("sfmmu_hblk_swap: mapping changed");
10761 
10762 			HBLKTOHME(nsfhme, new, vaddr);
10763 
10764 			HME_ADD(nsfhme, pp);
10765 			HME_SUB(osfhme, pp);
10766 
10767 			sfmmu_mlist_exit(pml);
10768 		}
10769 	}
10770 
10771 	/*
10772 	 * remove old from hash chain
10773 	 */
10774 	sfmmu_hblk_hash_rm(hmebp, old, prevpa, prev);
10775 
10776 #ifdef	DEBUG
10777 
10778 	hblktag.htag_id = ksfmmup;
10779 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
10780 	hblktag.htag_bspage = HME_HASH_BSPAGE(base, HME_HASH_SHIFT(TTE8K));
10781 	hblktag.htag_rehash = HME_HASH_REHASH(TTE8K);
10782 	HME_HASH_FAST_SEARCH(hmebp, hblktag, found);
10783 
10784 	if (found != new)
10785 		panic("sfmmu_hblk_swap: new hblk not found");
10786 #endif
10787 
10788 	SFMMU_HASH_UNLOCK(hmebp);
10789 
10790 	/*
10791 	 * Reset hblk_reserve
10792 	 */
10793 	bzero((void *)old, HME8BLK_SZ);
10794 	old->hblk_nextpa = va_to_pa((caddr_t)old);
10795 }
10796 
10797 /*
10798  * Grab the mlist mutex for both pages passed in.
10799  *
10800  * low and high will be returned as pointers to the mutexes for these pages.
10801  * low refers to the mutex residing in the lower bin of the mlist hash, while
10802  * high refers to the mutex residing in the higher bin of the mlist hash.  This
10803  * is due to the locking order restrictions on the same thread grabbing
10804  * multiple mlist mutexes.  The low lock must be acquired before the high lock.
10805  *
10806  * If both pages hash to the same mutex, only grab that single mutex, and
10807  * high will be returned as NULL
10808  * If the pages hash to different bins in the hash, grab the lower addressed
10809  * lock first and then the higher addressed lock in order to follow the locking
10810  * rules involved with the same thread grabbing multiple mlist mutexes.
10811  * low and high will both have non-NULL values.
10812  */
10813 static void
10814 sfmmu_mlist_reloc_enter(struct page *targ, struct page *repl,
10815     kmutex_t **low, kmutex_t **high)
10816 {
10817 	kmutex_t	*mml_targ, *mml_repl;
10818 
10819 	/*
10820 	 * no need to do the dance around szc as in sfmmu_mlist_enter()
10821 	 * because this routine is only called by hat_page_relocate() and all
10822 	 * targ and repl pages are already locked EXCL so szc can't change.
10823 	 */
10824 
10825 	mml_targ = MLIST_HASH(PP_PAGEROOT(targ));
10826 	mml_repl = MLIST_HASH(PP_PAGEROOT(repl));
10827 
10828 	if (mml_targ == mml_repl) {
10829 		*low = mml_targ;
10830 		*high = NULL;
10831 	} else {
10832 		if (mml_targ < mml_repl) {
10833 			*low = mml_targ;
10834 			*high = mml_repl;
10835 		} else {
10836 			*low = mml_repl;
10837 			*high = mml_targ;
10838 		}
10839 	}
10840 
10841 	mutex_enter(*low);
10842 	if (*high)
10843 		mutex_enter(*high);
10844 }
10845 
10846 static void
10847 sfmmu_mlist_reloc_exit(kmutex_t *low, kmutex_t *high)
10848 {
10849 	if (high)
10850 		mutex_exit(high);
10851 	mutex_exit(low);
10852 }
10853 
10854 static hatlock_t *
10855 sfmmu_hat_enter(sfmmu_t *sfmmup)
10856 {
10857 	hatlock_t	*hatlockp;
10858 
10859 	if (sfmmup != ksfmmup) {
10860 		hatlockp = TSB_HASH(sfmmup);
10861 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
10862 		return (hatlockp);
10863 	}
10864 	return (NULL);
10865 }
10866 
10867 static hatlock_t *
10868 sfmmu_hat_tryenter(sfmmu_t *sfmmup)
10869 {
10870 	hatlock_t	*hatlockp;
10871 
10872 	if (sfmmup != ksfmmup) {
10873 		hatlockp = TSB_HASH(sfmmup);
10874 		if (mutex_tryenter(HATLOCK_MUTEXP(hatlockp)) == 0)
10875 			return (NULL);
10876 		return (hatlockp);
10877 	}
10878 	return (NULL);
10879 }
10880 
10881 static void
10882 sfmmu_hat_exit(hatlock_t *hatlockp)
10883 {
10884 	if (hatlockp != NULL)
10885 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
10886 }
10887 
10888 static void
10889 sfmmu_hat_lock_all(void)
10890 {
10891 	int i;
10892 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
10893 		mutex_enter(HATLOCK_MUTEXP(&hat_lock[i]));
10894 }
10895 
10896 static void
10897 sfmmu_hat_unlock_all(void)
10898 {
10899 	int i;
10900 	for (i = SFMMU_NUM_LOCK - 1; i >= 0; i--)
10901 		mutex_exit(HATLOCK_MUTEXP(&hat_lock[i]));
10902 }
10903 
10904 int
10905 sfmmu_hat_lock_held(sfmmu_t *sfmmup)
10906 {
10907 	ASSERT(sfmmup != ksfmmup);
10908 	return (MUTEX_HELD(HATLOCK_MUTEXP(TSB_HASH(sfmmup))));
10909 }
10910 
10911 /*
10912  * Locking primitives to provide consistency between ISM unmap
10913  * and other operations.  Since ISM unmap can take a long time, we
10914  * use HAT_ISMBUSY flag (protected by the hatlock) to avoid creating
10915  * contention on the hatlock buckets while ISM segments are being
10916  * unmapped.  The tradeoff is that the flags don't prevent priority
10917  * inversion from occurring, so we must request kernel priority in
10918  * case we have to sleep to keep from getting buried while holding
10919  * the HAT_ISMBUSY flag set, which in turn could block other kernel
10920  * threads from running (for example, in sfmmu_uvatopfn()).
10921  */
10922 static void
10923 sfmmu_ismhat_enter(sfmmu_t *sfmmup, int hatlock_held)
10924 {
10925 	hatlock_t *hatlockp;
10926 
10927 	THREAD_KPRI_REQUEST();
10928 	if (!hatlock_held)
10929 		hatlockp = sfmmu_hat_enter(sfmmup);
10930 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY))
10931 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
10932 	SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
10933 	if (!hatlock_held)
10934 		sfmmu_hat_exit(hatlockp);
10935 }
10936 
10937 static void
10938 sfmmu_ismhat_exit(sfmmu_t *sfmmup, int hatlock_held)
10939 {
10940 	hatlock_t *hatlockp;
10941 
10942 	if (!hatlock_held)
10943 		hatlockp = sfmmu_hat_enter(sfmmup);
10944 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
10945 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
10946 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
10947 	if (!hatlock_held)
10948 		sfmmu_hat_exit(hatlockp);
10949 	THREAD_KPRI_RELEASE();
10950 }
10951 
10952 /*
10953  *
10954  * Algorithm:
10955  *
10956  * (1) if segkmem is not ready, allocate hblk from an array of pre-alloc'ed
10957  *	hblks.
10958  *
10959  * (2) if we are allocating an hblk for mapping a slab in sfmmu_cache,
10960  *
10961  * 		(a) try to return an hblk from reserve pool of free hblks;
10962  *		(b) if the reserve pool is empty, acquire hblk_reserve_lock
10963  *		    and return hblk_reserve.
10964  *
10965  * (3) call kmem_cache_alloc() to allocate hblk;
10966  *
10967  *		(a) if hblk_reserve_lock is held by the current thread,
10968  *		    atomically replace hblk_reserve by the hblk that is
10969  *		    returned by kmem_cache_alloc; release hblk_reserve_lock
10970  *		    and call kmem_cache_alloc() again.
10971  *		(b) if reserve pool is not full, add the hblk that is
10972  *		    returned by kmem_cache_alloc to reserve pool and
10973  *		    call kmem_cache_alloc again.
10974  *
10975  */
10976 static struct hme_blk *
10977 sfmmu_hblk_alloc(sfmmu_t *sfmmup, caddr_t vaddr,
10978 	struct hmehash_bucket *hmebp, uint_t size, hmeblk_tag hblktag,
10979 	uint_t flags, uint_t rid)
10980 {
10981 	struct hme_blk *hmeblkp = NULL;
10982 	struct hme_blk *newhblkp;
10983 	struct hme_blk *shw_hblkp = NULL;
10984 	struct kmem_cache *sfmmu_cache = NULL;
10985 	uint64_t hblkpa;
10986 	ulong_t index;
10987 	uint_t owner;		/* set to 1 if using hblk_reserve */
10988 	uint_t forcefree;
10989 	int sleep;
10990 	sf_srd_t *srdp;
10991 	sf_region_t *rgnp;
10992 
10993 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
10994 	ASSERT(hblktag.htag_rid == rid);
10995 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
10996 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
10997 	    IS_P2ALIGNED(vaddr, TTEBYTES(size)));
10998 
10999 	/*
11000 	 * If segkmem is not created yet, allocate from static hmeblks
11001 	 * created at the end of startup_modules().  See the block comment
11002 	 * in startup_modules() describing how we estimate the number of
11003 	 * static hmeblks that will be needed during re-map.
11004 	 */
11005 	if (!hblk_alloc_dynamic) {
11006 
11007 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11008 
11009 		if (size == TTE8K) {
11010 			index = nucleus_hblk8.index;
11011 			if (index >= nucleus_hblk8.len) {
11012 				/*
11013 				 * If we panic here, see startup_modules() to
11014 				 * make sure that we are calculating the
11015 				 * number of hblk8's that we need correctly.
11016 				 */
11017 				prom_panic("no nucleus hblk8 to allocate");
11018 			}
11019 			hmeblkp =
11020 			    (struct hme_blk *)&nucleus_hblk8.list[index];
11021 			nucleus_hblk8.index++;
11022 			SFMMU_STAT(sf_hblk8_nalloc);
11023 		} else {
11024 			index = nucleus_hblk1.index;
11025 			if (nucleus_hblk1.index >= nucleus_hblk1.len) {
11026 				/*
11027 				 * If we panic here, see startup_modules().
11028 				 * Most likely you need to update the
11029 				 * calculation of the number of hblk1 elements
11030 				 * that the kernel needs to boot.
11031 				 */
11032 				prom_panic("no nucleus hblk1 to allocate");
11033 			}
11034 			hmeblkp =
11035 			    (struct hme_blk *)&nucleus_hblk1.list[index];
11036 			nucleus_hblk1.index++;
11037 			SFMMU_STAT(sf_hblk1_nalloc);
11038 		}
11039 
11040 		goto hblk_init;
11041 	}
11042 
11043 	SFMMU_HASH_UNLOCK(hmebp);
11044 
11045 	if (sfmmup != KHATID && !SFMMU_IS_SHMERID_VALID(rid)) {
11046 		if (mmu_page_sizes == max_mmu_page_sizes) {
11047 			if (size < TTE256M)
11048 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11049 				    size, flags);
11050 		} else {
11051 			if (size < TTE4M)
11052 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11053 				    size, flags);
11054 		}
11055 	} else if (SFMMU_IS_SHMERID_VALID(rid)) {
11056 		/*
11057 		 * Shared hmes use per region bitmaps in rgn_hmeflag
11058 		 * rather than shadow hmeblks to keep track of the
11059 		 * mapping sizes which have been allocated for the region.
11060 		 * Here we cleanup old invalid hmeblks with this rid,
11061 		 * which may be left around by pageunload().
11062 		 */
11063 		int ttesz;
11064 		caddr_t va;
11065 		caddr_t	eva = vaddr + TTEBYTES(size);
11066 
11067 		ASSERT(sfmmup != KHATID);
11068 
11069 		srdp = sfmmup->sfmmu_srdp;
11070 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11071 		rgnp = srdp->srd_hmergnp[rid];
11072 		ASSERT(rgnp != NULL && rgnp->rgn_id == rid);
11073 		ASSERT(rgnp->rgn_refcnt != 0);
11074 		ASSERT(size <= rgnp->rgn_pgszc);
11075 
11076 		ttesz = HBLK_MIN_TTESZ;
11077 		do {
11078 			if (!(rgnp->rgn_hmeflags & (0x1 << ttesz))) {
11079 				continue;
11080 			}
11081 
11082 			if (ttesz > size && ttesz != HBLK_MIN_TTESZ) {
11083 				sfmmu_cleanup_rhblk(srdp, vaddr, rid, ttesz);
11084 			} else if (ttesz < size) {
11085 				for (va = vaddr; va < eva;
11086 				    va += TTEBYTES(ttesz)) {
11087 					sfmmu_cleanup_rhblk(srdp, va, rid,
11088 					    ttesz);
11089 				}
11090 			}
11091 		} while (++ttesz <= rgnp->rgn_pgszc);
11092 	}
11093 
11094 fill_hblk:
11095 	owner = (hblk_reserve_thread == curthread) ? 1 : 0;
11096 
11097 	if (owner && size == TTE8K) {
11098 
11099 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11100 		/*
11101 		 * We are really in a tight spot. We already own
11102 		 * hblk_reserve and we need another hblk.  In anticipation
11103 		 * of this kind of scenario, we specifically set aside
11104 		 * HBLK_RESERVE_MIN number of hblks to be used exclusively
11105 		 * by owner of hblk_reserve.
11106 		 */
11107 		SFMMU_STAT(sf_hblk_recurse_cnt);
11108 
11109 		if (!sfmmu_get_free_hblk(&hmeblkp, 1))
11110 			panic("sfmmu_hblk_alloc: reserve list is empty");
11111 
11112 		goto hblk_verify;
11113 	}
11114 
11115 	ASSERT(!owner);
11116 
11117 	if ((flags & HAT_NO_KALLOC) == 0) {
11118 
11119 		sfmmu_cache = ((size == TTE8K) ? sfmmu8_cache : sfmmu1_cache);
11120 		sleep = ((sfmmup == KHATID) ? KM_NOSLEEP : KM_SLEEP);
11121 
11122 		if ((hmeblkp = kmem_cache_alloc(sfmmu_cache, sleep)) == NULL) {
11123 			hmeblkp = sfmmu_hblk_steal(size);
11124 		} else {
11125 			/*
11126 			 * if we are the owner of hblk_reserve,
11127 			 * swap hblk_reserve with hmeblkp and
11128 			 * start a fresh life.  Hope things go
11129 			 * better this time.
11130 			 */
11131 			if (hblk_reserve_thread == curthread) {
11132 				ASSERT(sfmmu_cache == sfmmu8_cache);
11133 				sfmmu_hblk_swap(hmeblkp);
11134 				hblk_reserve_thread = NULL;
11135 				mutex_exit(&hblk_reserve_lock);
11136 				goto fill_hblk;
11137 			}
11138 			/*
11139 			 * let's donate this hblk to our reserve list if
11140 			 * we are not mapping kernel range
11141 			 */
11142 			if (size == TTE8K && sfmmup != KHATID)
11143 				if (sfmmu_put_free_hblk(hmeblkp, 0))
11144 					goto fill_hblk;
11145 		}
11146 	} else {
11147 		/*
11148 		 * We are here to map the slab in sfmmu8_cache; let's
11149 		 * check if we could tap our reserve list; if successful,
11150 		 * this will avoid the pain of going thru sfmmu_hblk_swap
11151 		 */
11152 		SFMMU_STAT(sf_hblk_slab_cnt);
11153 		if (!sfmmu_get_free_hblk(&hmeblkp, 0)) {
11154 			/*
11155 			 * let's start hblk_reserve dance
11156 			 */
11157 			SFMMU_STAT(sf_hblk_reserve_cnt);
11158 			owner = 1;
11159 			mutex_enter(&hblk_reserve_lock);
11160 			hmeblkp = HBLK_RESERVE;
11161 			hblk_reserve_thread = curthread;
11162 		}
11163 	}
11164 
11165 hblk_verify:
11166 	ASSERT(hmeblkp != NULL);
11167 	set_hblk_sz(hmeblkp, size);
11168 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
11169 	SFMMU_HASH_LOCK(hmebp);
11170 	HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11171 	if (newhblkp != NULL) {
11172 		SFMMU_HASH_UNLOCK(hmebp);
11173 		if (hmeblkp != HBLK_RESERVE) {
11174 			/*
11175 			 * This is really tricky!
11176 			 *
11177 			 * vmem_alloc(vmem_seg_arena)
11178 			 *  vmem_alloc(vmem_internal_arena)
11179 			 *   segkmem_alloc(heap_arena)
11180 			 *    vmem_alloc(heap_arena)
11181 			 *    page_create()
11182 			 *    hat_memload()
11183 			 *	kmem_cache_free()
11184 			 *	 kmem_cache_alloc()
11185 			 *	  kmem_slab_create()
11186 			 *	   vmem_alloc(kmem_internal_arena)
11187 			 *	    segkmem_alloc(heap_arena)
11188 			 *		vmem_alloc(heap_arena)
11189 			 *		page_create()
11190 			 *		hat_memload()
11191 			 *		  kmem_cache_free()
11192 			 *		...
11193 			 *
11194 			 * Thus, hat_memload() could call kmem_cache_free
11195 			 * for enough number of times that we could easily
11196 			 * hit the bottom of the stack or run out of reserve
11197 			 * list of vmem_seg structs.  So, we must donate
11198 			 * this hblk to reserve list if it's allocated
11199 			 * from sfmmu8_cache *and* mapping kernel range.
11200 			 * We don't need to worry about freeing hmeblk1's
11201 			 * to kmem since they don't map any kmem slabs.
11202 			 *
11203 			 * Note: When segkmem supports largepages, we must
11204 			 * free hmeblk1's to reserve list as well.
11205 			 */
11206 			forcefree = (sfmmup == KHATID) ? 1 : 0;
11207 			if (size == TTE8K &&
11208 			    sfmmu_put_free_hblk(hmeblkp, forcefree)) {
11209 				goto re_verify;
11210 			}
11211 			ASSERT(sfmmup != KHATID);
11212 			kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
11213 		} else {
11214 			/*
11215 			 * Hey! we don't need hblk_reserve any more.
11216 			 */
11217 			ASSERT(owner);
11218 			hblk_reserve_thread = NULL;
11219 			mutex_exit(&hblk_reserve_lock);
11220 			owner = 0;
11221 		}
11222 re_verify:
11223 		/*
11224 		 * let's check if the goodies are still present
11225 		 */
11226 		SFMMU_HASH_LOCK(hmebp);
11227 		HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11228 		if (newhblkp != NULL) {
11229 			/*
11230 			 * return newhblkp if it's not hblk_reserve;
11231 			 * if newhblkp is hblk_reserve, return it
11232 			 * _only if_ we are the owner of hblk_reserve.
11233 			 */
11234 			if (newhblkp != HBLK_RESERVE || owner) {
11235 				ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11236 				    newhblkp->hblk_shared);
11237 				ASSERT(SFMMU_IS_SHMERID_VALID(rid) ||
11238 				    !newhblkp->hblk_shared);
11239 				return (newhblkp);
11240 			} else {
11241 				/*
11242 				 * we just hit hblk_reserve in the hash and
11243 				 * we are not the owner of that;
11244 				 *
11245 				 * block until hblk_reserve_thread completes
11246 				 * swapping hblk_reserve and try the dance
11247 				 * once again.
11248 				 */
11249 				SFMMU_HASH_UNLOCK(hmebp);
11250 				mutex_enter(&hblk_reserve_lock);
11251 				mutex_exit(&hblk_reserve_lock);
11252 				SFMMU_STAT(sf_hblk_reserve_hit);
11253 				goto fill_hblk;
11254 			}
11255 		} else {
11256 			/*
11257 			 * it's no more! try the dance once again.
11258 			 */
11259 			SFMMU_HASH_UNLOCK(hmebp);
11260 			goto fill_hblk;
11261 		}
11262 	}
11263 
11264 hblk_init:
11265 	if (SFMMU_IS_SHMERID_VALID(rid)) {
11266 		uint16_t tteflag = 0x1 <<
11267 		    ((size < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ : size);
11268 
11269 		if (!(rgnp->rgn_hmeflags & tteflag)) {
11270 			atomic_or_16(&rgnp->rgn_hmeflags, tteflag);
11271 		}
11272 		hmeblkp->hblk_shared = 1;
11273 	} else {
11274 		hmeblkp->hblk_shared = 0;
11275 	}
11276 	set_hblk_sz(hmeblkp, size);
11277 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11278 	hmeblkp->hblk_next = (struct hme_blk *)NULL;
11279 	hmeblkp->hblk_tag = hblktag;
11280 	hmeblkp->hblk_shadow = shw_hblkp;
11281 	hblkpa = hmeblkp->hblk_nextpa;
11282 	hmeblkp->hblk_nextpa = 0;
11283 
11284 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
11285 	ASSERT(get_hblk_span(hmeblkp) == HMEBLK_SPAN(size));
11286 	ASSERT(hmeblkp->hblk_hmecnt == 0);
11287 	ASSERT(hmeblkp->hblk_vcnt == 0);
11288 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11289 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
11290 	sfmmu_hblk_hash_add(hmebp, hmeblkp, hblkpa);
11291 	return (hmeblkp);
11292 }
11293 
11294 /*
11295  * This function performs any cleanup required on the hme_blk
11296  * and returns it to the free list.
11297  */
11298 /* ARGSUSED */
11299 static void
11300 sfmmu_hblk_free(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
11301 	uint64_t hblkpa, struct hme_blk **listp)
11302 {
11303 	int shw_size, vshift;
11304 	struct hme_blk *shw_hblkp;
11305 	uint_t		shw_mask, newshw_mask;
11306 	caddr_t		vaddr;
11307 	int		size;
11308 	uint_t		critical;
11309 
11310 	ASSERT(hmeblkp);
11311 	ASSERT(!hmeblkp->hblk_hmecnt);
11312 	ASSERT(!hmeblkp->hblk_vcnt);
11313 	ASSERT(!hmeblkp->hblk_lckcnt);
11314 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
11315 	ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
11316 
11317 	critical = (hblktosfmmu(hmeblkp) == KHATID) ? 1 : 0;
11318 
11319 	size = get_hblk_ttesz(hmeblkp);
11320 	shw_hblkp = hmeblkp->hblk_shadow;
11321 	if (shw_hblkp) {
11322 		ASSERT(hblktosfmmu(hmeblkp) != KHATID);
11323 		ASSERT(!hmeblkp->hblk_shared);
11324 		if (mmu_page_sizes == max_mmu_page_sizes) {
11325 			ASSERT(size < TTE256M);
11326 		} else {
11327 			ASSERT(size < TTE4M);
11328 		}
11329 
11330 		shw_size = get_hblk_ttesz(shw_hblkp);
11331 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11332 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
11333 		ASSERT(vshift < 8);
11334 		/*
11335 		 * Atomically clear shadow mask bit
11336 		 */
11337 		do {
11338 			shw_mask = shw_hblkp->hblk_shw_mask;
11339 			ASSERT(shw_mask & (1 << vshift));
11340 			newshw_mask = shw_mask & ~(1 << vshift);
11341 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
11342 			    shw_mask, newshw_mask);
11343 		} while (newshw_mask != shw_mask);
11344 		hmeblkp->hblk_shadow = NULL;
11345 	}
11346 	hmeblkp->hblk_next = NULL;
11347 	hmeblkp->hblk_nextpa = hblkpa;
11348 	hmeblkp->hblk_shw_bit = 0;
11349 
11350 	if (hmeblkp->hblk_shared) {
11351 		sf_srd_t	*srdp;
11352 		sf_region_t	*rgnp;
11353 		uint_t		rid;
11354 
11355 		srdp = hblktosrd(hmeblkp);
11356 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11357 		rid = hmeblkp->hblk_tag.htag_rid;
11358 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11359 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11360 		rgnp = srdp->srd_hmergnp[rid];
11361 		ASSERT(rgnp != NULL);
11362 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
11363 		hmeblkp->hblk_shared = 0;
11364 	}
11365 
11366 	if (hmeblkp->hblk_nuc_bit == 0) {
11367 
11368 		if (size == TTE8K && sfmmu_put_free_hblk(hmeblkp, critical))
11369 			return;
11370 
11371 		hmeblkp->hblk_next = *listp;
11372 		*listp = hmeblkp;
11373 	}
11374 }
11375 
11376 static void
11377 sfmmu_hblks_list_purge(struct hme_blk **listp)
11378 {
11379 	struct hme_blk	*hmeblkp;
11380 
11381 	while ((hmeblkp = *listp) != NULL) {
11382 		*listp = hmeblkp->hblk_next;
11383 		kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
11384 	}
11385 }
11386 
11387 #define	BUCKETS_TO_SEARCH_BEFORE_UNLOAD	30
11388 #define	SFMMU_HBLK_STEAL_THRESHOLD 5
11389 
11390 static uint_t sfmmu_hblk_steal_twice;
11391 static uint_t sfmmu_hblk_steal_count, sfmmu_hblk_steal_unload_count;
11392 
11393 /*
11394  * Steal a hmeblk from user or kernel hme hash lists.
11395  * For 8K tte grab one from reserve pool (freehblkp) before proceeding to
11396  * steal and if we fail to steal after SFMMU_HBLK_STEAL_THRESHOLD attempts
11397  * tap into critical reserve of freehblkp.
11398  * Note: We remain looping in this routine until we find one.
11399  */
11400 static struct hme_blk *
11401 sfmmu_hblk_steal(int size)
11402 {
11403 	static struct hmehash_bucket *uhmehash_steal_hand = NULL;
11404 	struct hmehash_bucket *hmebp;
11405 	struct hme_blk *hmeblkp = NULL, *pr_hblk;
11406 	uint64_t hblkpa, prevpa;
11407 	int i;
11408 	uint_t loop_cnt = 0, critical;
11409 
11410 	for (;;) {
11411 		if (size == TTE8K) {
11412 			critical =
11413 			    (++loop_cnt > SFMMU_HBLK_STEAL_THRESHOLD) ? 1 : 0;
11414 			if (sfmmu_get_free_hblk(&hmeblkp, critical))
11415 				return (hmeblkp);
11416 		}
11417 
11418 		hmebp = (uhmehash_steal_hand == NULL) ? uhme_hash :
11419 		    uhmehash_steal_hand;
11420 		ASSERT(hmebp >= uhme_hash && hmebp <= &uhme_hash[UHMEHASH_SZ]);
11421 
11422 		for (i = 0; hmeblkp == NULL && i <= UHMEHASH_SZ +
11423 		    BUCKETS_TO_SEARCH_BEFORE_UNLOAD; i++) {
11424 			SFMMU_HASH_LOCK(hmebp);
11425 			hmeblkp = hmebp->hmeblkp;
11426 			hblkpa = hmebp->hmeh_nextpa;
11427 			prevpa = 0;
11428 			pr_hblk = NULL;
11429 			while (hmeblkp) {
11430 				/*
11431 				 * check if it is a hmeblk that is not locked
11432 				 * and not shared. skip shadow hmeblks with
11433 				 * shadow_mask set i.e valid count non zero.
11434 				 */
11435 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11436 				    (hmeblkp->hblk_shw_bit == 0 ||
11437 				    hmeblkp->hblk_vcnt == 0) &&
11438 				    (hmeblkp->hblk_lckcnt == 0)) {
11439 					/*
11440 					 * there is a high probability that we
11441 					 * will find a free one. search some
11442 					 * buckets for a free hmeblk initially
11443 					 * before unloading a valid hmeblk.
11444 					 */
11445 					if ((hmeblkp->hblk_vcnt == 0 &&
11446 					    hmeblkp->hblk_hmecnt == 0) || (i >=
11447 					    BUCKETS_TO_SEARCH_BEFORE_UNLOAD)) {
11448 						if (sfmmu_steal_this_hblk(hmebp,
11449 						    hmeblkp, hblkpa, prevpa,
11450 						    pr_hblk)) {
11451 							/*
11452 							 * Hblk is unloaded
11453 							 * successfully
11454 							 */
11455 							break;
11456 						}
11457 					}
11458 				}
11459 				pr_hblk = hmeblkp;
11460 				prevpa = hblkpa;
11461 				hblkpa = hmeblkp->hblk_nextpa;
11462 				hmeblkp = hmeblkp->hblk_next;
11463 			}
11464 
11465 			SFMMU_HASH_UNLOCK(hmebp);
11466 			if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
11467 				hmebp = uhme_hash;
11468 		}
11469 		uhmehash_steal_hand = hmebp;
11470 
11471 		if (hmeblkp != NULL)
11472 			break;
11473 
11474 		/*
11475 		 * in the worst case, look for a free one in the kernel
11476 		 * hash table.
11477 		 */
11478 		for (i = 0, hmebp = khme_hash; i <= KHMEHASH_SZ; i++) {
11479 			SFMMU_HASH_LOCK(hmebp);
11480 			hmeblkp = hmebp->hmeblkp;
11481 			hblkpa = hmebp->hmeh_nextpa;
11482 			prevpa = 0;
11483 			pr_hblk = NULL;
11484 			while (hmeblkp) {
11485 				/*
11486 				 * check if it is free hmeblk
11487 				 */
11488 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11489 				    (hmeblkp->hblk_lckcnt == 0) &&
11490 				    (hmeblkp->hblk_vcnt == 0) &&
11491 				    (hmeblkp->hblk_hmecnt == 0)) {
11492 					if (sfmmu_steal_this_hblk(hmebp,
11493 					    hmeblkp, hblkpa, prevpa, pr_hblk)) {
11494 						break;
11495 					} else {
11496 						/*
11497 						 * Cannot fail since we have
11498 						 * hash lock.
11499 						 */
11500 						panic("fail to steal?");
11501 					}
11502 				}
11503 
11504 				pr_hblk = hmeblkp;
11505 				prevpa = hblkpa;
11506 				hblkpa = hmeblkp->hblk_nextpa;
11507 				hmeblkp = hmeblkp->hblk_next;
11508 			}
11509 
11510 			SFMMU_HASH_UNLOCK(hmebp);
11511 			if (hmebp++ == &khme_hash[KHMEHASH_SZ])
11512 				hmebp = khme_hash;
11513 		}
11514 
11515 		if (hmeblkp != NULL)
11516 			break;
11517 		sfmmu_hblk_steal_twice++;
11518 	}
11519 	return (hmeblkp);
11520 }
11521 
11522 /*
11523  * This routine does real work to prepare a hblk to be "stolen" by
11524  * unloading the mappings, updating shadow counts ....
11525  * It returns 1 if the block is ready to be reused (stolen), or 0
11526  * means the block cannot be stolen yet- pageunload is still working
11527  * on this hblk.
11528  */
11529 static int
11530 sfmmu_steal_this_hblk(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
11531 	uint64_t hblkpa, uint64_t prevpa, struct hme_blk *pr_hblk)
11532 {
11533 	int shw_size, vshift;
11534 	struct hme_blk *shw_hblkp;
11535 	caddr_t vaddr;
11536 	uint_t shw_mask, newshw_mask;
11537 
11538 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11539 
11540 	/*
11541 	 * check if the hmeblk is free, unload if necessary
11542 	 */
11543 	if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11544 		sfmmu_t *sfmmup;
11545 		demap_range_t dmr;
11546 
11547 		sfmmup = hblktosfmmu(hmeblkp);
11548 		if (hmeblkp->hblk_shared || sfmmup->sfmmu_ismhat) {
11549 			return (0);
11550 		}
11551 		DEMAP_RANGE_INIT(sfmmup, &dmr);
11552 		(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
11553 		    (caddr_t)get_hblk_base(hmeblkp),
11554 		    get_hblk_endaddr(hmeblkp), &dmr, HAT_UNLOAD);
11555 		DEMAP_RANGE_FLUSH(&dmr);
11556 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11557 			/*
11558 			 * Pageunload is working on the same hblk.
11559 			 */
11560 			return (0);
11561 		}
11562 
11563 		sfmmu_hblk_steal_unload_count++;
11564 	}
11565 
11566 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11567 	ASSERT(hmeblkp->hblk_vcnt == 0 && hmeblkp->hblk_hmecnt == 0);
11568 
11569 	sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
11570 	hmeblkp->hblk_nextpa = hblkpa;
11571 
11572 	shw_hblkp = hmeblkp->hblk_shadow;
11573 	if (shw_hblkp) {
11574 		ASSERT(!hmeblkp->hblk_shared);
11575 		shw_size = get_hblk_ttesz(shw_hblkp);
11576 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11577 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
11578 		ASSERT(vshift < 8);
11579 		/*
11580 		 * Atomically clear shadow mask bit
11581 		 */
11582 		do {
11583 			shw_mask = shw_hblkp->hblk_shw_mask;
11584 			ASSERT(shw_mask & (1 << vshift));
11585 			newshw_mask = shw_mask & ~(1 << vshift);
11586 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
11587 			    shw_mask, newshw_mask);
11588 		} while (newshw_mask != shw_mask);
11589 		hmeblkp->hblk_shadow = NULL;
11590 	}
11591 
11592 	/*
11593 	 * remove shadow bit if we are stealing an unused shadow hmeblk.
11594 	 * sfmmu_hblk_alloc needs it that way, will set shadow bit later if
11595 	 * we are indeed allocating a shadow hmeblk.
11596 	 */
11597 	hmeblkp->hblk_shw_bit = 0;
11598 
11599 	if (hmeblkp->hblk_shared) {
11600 		sf_srd_t	*srdp;
11601 		sf_region_t	*rgnp;
11602 		uint_t		rid;
11603 
11604 		srdp = hblktosrd(hmeblkp);
11605 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11606 		rid = hmeblkp->hblk_tag.htag_rid;
11607 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11608 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11609 		rgnp = srdp->srd_hmergnp[rid];
11610 		ASSERT(rgnp != NULL);
11611 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
11612 		hmeblkp->hblk_shared = 0;
11613 	}
11614 
11615 	sfmmu_hblk_steal_count++;
11616 	SFMMU_STAT(sf_steal_count);
11617 
11618 	return (1);
11619 }
11620 
11621 struct hme_blk *
11622 sfmmu_hmetohblk(struct sf_hment *sfhme)
11623 {
11624 	struct hme_blk *hmeblkp;
11625 	struct sf_hment *sfhme0;
11626 	struct hme_blk *hblk_dummy = 0;
11627 
11628 	/*
11629 	 * No dummy sf_hments, please.
11630 	 */
11631 	ASSERT(sfhme->hme_tte.ll != 0);
11632 
11633 	sfhme0 = sfhme - sfhme->hme_tte.tte_hmenum;
11634 	hmeblkp = (struct hme_blk *)((uintptr_t)sfhme0 -
11635 	    (uintptr_t)&hblk_dummy->hblk_hme[0]);
11636 
11637 	return (hmeblkp);
11638 }
11639 
11640 /*
11641  * On swapin, get appropriately sized TSB(s) and clear the HAT_SWAPPED flag.
11642  * If we can't get appropriately sized TSB(s), try for 8K TSB(s) using
11643  * KM_SLEEP allocation.
11644  *
11645  * Return 0 on success, -1 otherwise.
11646  */
11647 static void
11648 sfmmu_tsb_swapin(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11649 {
11650 	struct tsb_info *tsbinfop, *next;
11651 	tsb_replace_rc_t rc;
11652 	boolean_t gotfirst = B_FALSE;
11653 
11654 	ASSERT(sfmmup != ksfmmup);
11655 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11656 
11657 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPIN)) {
11658 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
11659 	}
11660 
11661 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11662 		SFMMU_FLAGS_SET(sfmmup, HAT_SWAPIN);
11663 	} else {
11664 		return;
11665 	}
11666 
11667 	ASSERT(sfmmup->sfmmu_tsb != NULL);
11668 
11669 	/*
11670 	 * Loop over all tsbinfo's replacing them with ones that actually have
11671 	 * a TSB.  If any of the replacements ever fail, bail out of the loop.
11672 	 */
11673 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL; tsbinfop = next) {
11674 		ASSERT(tsbinfop->tsb_flags & TSB_SWAPPED);
11675 		next = tsbinfop->tsb_next;
11676 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, tsbinfop->tsb_szc,
11677 		    hatlockp, TSB_SWAPIN);
11678 		if (rc != TSB_SUCCESS) {
11679 			break;
11680 		}
11681 		gotfirst = B_TRUE;
11682 	}
11683 
11684 	switch (rc) {
11685 	case TSB_SUCCESS:
11686 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11687 		cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11688 		return;
11689 	case TSB_LOSTRACE:
11690 		break;
11691 	case TSB_ALLOCFAIL:
11692 		break;
11693 	default:
11694 		panic("sfmmu_replace_tsb returned unrecognized failure code "
11695 		    "%d", rc);
11696 	}
11697 
11698 	/*
11699 	 * In this case, we failed to get one of our TSBs.  If we failed to
11700 	 * get the first TSB, get one of minimum size (8KB).  Walk the list
11701 	 * and throw away the tsbinfos, starting where the allocation failed;
11702 	 * we can get by with just one TSB as long as we don't leave the
11703 	 * SWAPPED tsbinfo structures lying around.
11704 	 */
11705 	tsbinfop = sfmmup->sfmmu_tsb;
11706 	next = tsbinfop->tsb_next;
11707 	tsbinfop->tsb_next = NULL;
11708 
11709 	sfmmu_hat_exit(hatlockp);
11710 	for (tsbinfop = next; tsbinfop != NULL; tsbinfop = next) {
11711 		next = tsbinfop->tsb_next;
11712 		sfmmu_tsbinfo_free(tsbinfop);
11713 	}
11714 	hatlockp = sfmmu_hat_enter(sfmmup);
11715 
11716 	/*
11717 	 * If we don't have any TSBs, get a single 8K TSB for 8K, 64K and 512K
11718 	 * pages.
11719 	 */
11720 	if (!gotfirst) {
11721 		tsbinfop = sfmmup->sfmmu_tsb;
11722 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, TSB_MIN_SZCODE,
11723 		    hatlockp, TSB_SWAPIN | TSB_FORCEALLOC);
11724 		ASSERT(rc == TSB_SUCCESS);
11725 	}
11726 
11727 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11728 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11729 }
11730 
11731 static int
11732 sfmmu_is_rgnva(sf_srd_t *srdp, caddr_t addr, ulong_t w, ulong_t bmw)
11733 {
11734 	ulong_t bix = 0;
11735 	uint_t rid;
11736 	sf_region_t *rgnp;
11737 
11738 	ASSERT(srdp != NULL);
11739 	ASSERT(srdp->srd_refcnt != 0);
11740 
11741 	w <<= BT_ULSHIFT;
11742 	while (bmw) {
11743 		if (!(bmw & 0x1)) {
11744 			bix++;
11745 			bmw >>= 1;
11746 			continue;
11747 		}
11748 		rid = w | bix;
11749 		rgnp = srdp->srd_hmergnp[rid];
11750 		ASSERT(rgnp->rgn_refcnt > 0);
11751 		ASSERT(rgnp->rgn_id == rid);
11752 		if (addr < rgnp->rgn_saddr ||
11753 		    addr >= (rgnp->rgn_saddr + rgnp->rgn_size)) {
11754 			bix++;
11755 			bmw >>= 1;
11756 		} else {
11757 			return (1);
11758 		}
11759 	}
11760 	return (0);
11761 }
11762 
11763 /*
11764  * Handle exceptions for low level tsb_handler.
11765  *
11766  * There are many scenarios that could land us here:
11767  *
11768  * If the context is invalid we land here. The context can be invalid
11769  * for 3 reasons: 1) we couldn't allocate a new context and now need to
11770  * perform a wrap around operation in order to allocate a new context.
11771  * 2) Context was invalidated to change pagesize programming 3) ISMs or
11772  * TSBs configuration is changeing for this process and we are forced into
11773  * here to do a syncronization operation. If the context is valid we can
11774  * be here from window trap hanlder. In this case just call trap to handle
11775  * the fault.
11776  *
11777  * Note that the process will run in INVALID_CONTEXT before
11778  * faulting into here and subsequently loading the MMU registers
11779  * (including the TSB base register) associated with this process.
11780  * For this reason, the trap handlers must all test for
11781  * INVALID_CONTEXT before attempting to access any registers other
11782  * than the context registers.
11783  */
11784 void
11785 sfmmu_tsbmiss_exception(struct regs *rp, uintptr_t tagaccess, uint_t traptype)
11786 {
11787 	sfmmu_t *sfmmup, *shsfmmup;
11788 	uint_t ctxtype;
11789 	klwp_id_t lwp;
11790 	char lwp_save_state;
11791 	hatlock_t *hatlockp, *shatlockp;
11792 	struct tsb_info *tsbinfop;
11793 	struct tsbmiss *tsbmp;
11794 	sf_scd_t *scdp;
11795 
11796 	SFMMU_STAT(sf_tsb_exceptions);
11797 	SFMMU_MMU_STAT(mmu_tsb_exceptions);
11798 	sfmmup = astosfmmu(curthread->t_procp->p_as);
11799 	/*
11800 	 * note that in sun4u, tagacces register contains ctxnum
11801 	 * while sun4v passes ctxtype in the tagaccess register.
11802 	 */
11803 	ctxtype = tagaccess & TAGACC_CTX_MASK;
11804 
11805 	ASSERT(sfmmup != ksfmmup && ctxtype != KCONTEXT);
11806 	ASSERT(sfmmup->sfmmu_ismhat == 0);
11807 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED) ||
11808 	    ctxtype == INVALID_CONTEXT);
11809 
11810 	if (ctxtype != INVALID_CONTEXT && traptype != T_DATA_PROT) {
11811 		/*
11812 		 * We may land here because shme bitmap and pagesize
11813 		 * flags are updated lazily in tsbmiss area on other cpus.
11814 		 * If we detect here that tsbmiss area is out of sync with
11815 		 * sfmmu update it and retry the trapped instruction.
11816 		 * Otherwise call trap().
11817 		 */
11818 		int ret = 0;
11819 		uchar_t tteflag_mask = (1 << TTE64K) | (1 << TTE8K);
11820 		caddr_t addr = (caddr_t)(tagaccess & TAGACC_VADDR_MASK);
11821 
11822 		/*
11823 		 * Must set lwp state to LWP_SYS before
11824 		 * trying to acquire any adaptive lock
11825 		 */
11826 		lwp = ttolwp(curthread);
11827 		ASSERT(lwp);
11828 		lwp_save_state = lwp->lwp_state;
11829 		lwp->lwp_state = LWP_SYS;
11830 
11831 		hatlockp = sfmmu_hat_enter(sfmmup);
11832 		kpreempt_disable();
11833 		tsbmp = &tsbmiss_area[CPU->cpu_id];
11834 		ASSERT(sfmmup == tsbmp->usfmmup);
11835 		if (((tsbmp->uhat_tteflags ^ sfmmup->sfmmu_tteflags) &
11836 		    ~tteflag_mask) ||
11837 		    ((tsbmp->uhat_rtteflags ^  sfmmup->sfmmu_rtteflags) &
11838 		    ~tteflag_mask)) {
11839 			tsbmp->uhat_tteflags = sfmmup->sfmmu_tteflags;
11840 			tsbmp->uhat_rtteflags = sfmmup->sfmmu_rtteflags;
11841 			ret = 1;
11842 		}
11843 		if (sfmmup->sfmmu_srdp != NULL) {
11844 			ulong_t *sm = sfmmup->sfmmu_hmeregion_map.bitmap;
11845 			ulong_t *tm = tsbmp->shmermap;
11846 			ulong_t i;
11847 			for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
11848 				ulong_t d = tm[i] ^ sm[i];
11849 				if (d) {
11850 					if (d & sm[i]) {
11851 						if (!ret && sfmmu_is_rgnva(
11852 						    sfmmup->sfmmu_srdp,
11853 						    addr, i, d & sm[i])) {
11854 							ret = 1;
11855 						}
11856 					}
11857 					tm[i] = sm[i];
11858 				}
11859 			}
11860 		}
11861 		kpreempt_enable();
11862 		sfmmu_hat_exit(hatlockp);
11863 		lwp->lwp_state = lwp_save_state;
11864 		if (ret) {
11865 			return;
11866 		}
11867 	} else if (ctxtype == INVALID_CONTEXT) {
11868 		/*
11869 		 * First, make sure we come out of here with a valid ctx,
11870 		 * since if we don't get one we'll simply loop on the
11871 		 * faulting instruction.
11872 		 *
11873 		 * If the ISM mappings are changing, the TSB is relocated,
11874 		 * the process is swapped, the process is joining SCD or
11875 		 * leaving SCD or shared regions we serialize behind the
11876 		 * controlling thread with hat lock, sfmmu_flags and
11877 		 * sfmmu_tsb_cv condition variable.
11878 		 */
11879 
11880 		/*
11881 		 * Must set lwp state to LWP_SYS before
11882 		 * trying to acquire any adaptive lock
11883 		 */
11884 		lwp = ttolwp(curthread);
11885 		ASSERT(lwp);
11886 		lwp_save_state = lwp->lwp_state;
11887 		lwp->lwp_state = LWP_SYS;
11888 
11889 		hatlockp = sfmmu_hat_enter(sfmmup);
11890 retry:
11891 		if ((scdp = sfmmup->sfmmu_scdp) != NULL) {
11892 			shsfmmup = scdp->scd_sfmmup;
11893 			ASSERT(shsfmmup != NULL);
11894 
11895 			for (tsbinfop = shsfmmup->sfmmu_tsb; tsbinfop != NULL;
11896 			    tsbinfop = tsbinfop->tsb_next) {
11897 				if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11898 					/* drop the private hat lock */
11899 					sfmmu_hat_exit(hatlockp);
11900 					/* acquire the shared hat lock */
11901 					shatlockp = sfmmu_hat_enter(shsfmmup);
11902 					/*
11903 					 * recheck to see if anything changed
11904 					 * after we drop the private hat lock.
11905 					 */
11906 					if (sfmmup->sfmmu_scdp == scdp &&
11907 					    shsfmmup == scdp->scd_sfmmup) {
11908 						sfmmu_tsb_chk_reloc(shsfmmup,
11909 						    shatlockp);
11910 					}
11911 					sfmmu_hat_exit(shatlockp);
11912 					hatlockp = sfmmu_hat_enter(sfmmup);
11913 					goto retry;
11914 				}
11915 			}
11916 		}
11917 
11918 		for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
11919 		    tsbinfop = tsbinfop->tsb_next) {
11920 			if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11921 				cv_wait(&sfmmup->sfmmu_tsb_cv,
11922 				    HATLOCK_MUTEXP(hatlockp));
11923 				goto retry;
11924 			}
11925 		}
11926 
11927 		/*
11928 		 * Wait for ISM maps to be updated.
11929 		 */
11930 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
11931 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11932 			    HATLOCK_MUTEXP(hatlockp));
11933 			goto retry;
11934 		}
11935 
11936 		/* Is this process joining an SCD? */
11937 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
11938 			/*
11939 			 * Flush private TSB and setup shared TSB.
11940 			 * sfmmu_finish_join_scd() does not drop the
11941 			 * hat lock.
11942 			 */
11943 			sfmmu_finish_join_scd(sfmmup);
11944 			SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
11945 		}
11946 
11947 		/*
11948 		 * If we're swapping in, get TSB(s).  Note that we must do
11949 		 * this before we get a ctx or load the MMU state.  Once
11950 		 * we swap in we have to recheck to make sure the TSB(s) and
11951 		 * ISM mappings didn't change while we slept.
11952 		 */
11953 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11954 			sfmmu_tsb_swapin(sfmmup, hatlockp);
11955 			goto retry;
11956 		}
11957 
11958 		sfmmu_get_ctx(sfmmup);
11959 
11960 		sfmmu_hat_exit(hatlockp);
11961 		/*
11962 		 * Must restore lwp_state if not calling
11963 		 * trap() for further processing. Restore
11964 		 * it anyway.
11965 		 */
11966 		lwp->lwp_state = lwp_save_state;
11967 		return;
11968 	}
11969 	trap(rp, (caddr_t)tagaccess, traptype, 0);
11970 }
11971 
11972 static void
11973 sfmmu_tsb_chk_reloc(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11974 {
11975 	struct tsb_info *tp;
11976 
11977 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11978 
11979 	for (tp = sfmmup->sfmmu_tsb; tp != NULL; tp = tp->tsb_next) {
11980 		if (tp->tsb_flags & TSB_RELOC_FLAG) {
11981 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11982 			    HATLOCK_MUTEXP(hatlockp));
11983 			break;
11984 		}
11985 	}
11986 }
11987 
11988 /*
11989  * sfmmu_vatopfn_suspended is called from GET_TTE when TL=0 and
11990  * TTE_SUSPENDED bit set in tte we block on aquiring a page lock
11991  * rather than spinning to avoid send mondo timeouts with
11992  * interrupts enabled. When the lock is acquired it is immediately
11993  * released and we return back to sfmmu_vatopfn just after
11994  * the GET_TTE call.
11995  */
11996 void
11997 sfmmu_vatopfn_suspended(caddr_t vaddr, sfmmu_t *sfmmu, tte_t *ttep)
11998 {
11999 	struct page	**pp;
12000 
12001 	(void) as_pagelock(sfmmu->sfmmu_as, &pp, vaddr, TTE_CSZ(ttep), S_WRITE);
12002 	as_pageunlock(sfmmu->sfmmu_as, pp, vaddr, TTE_CSZ(ttep), S_WRITE);
12003 }
12004 
12005 /*
12006  * sfmmu_tsbmiss_suspended is called from GET_TTE when TL>0 and
12007  * TTE_SUSPENDED bit set in tte. We do this so that we can handle
12008  * cross traps which cannot be handled while spinning in the
12009  * trap handlers. Simply enter and exit the kpr_suspendlock spin
12010  * mutex, which is held by the holder of the suspend bit, and then
12011  * retry the trapped instruction after unwinding.
12012  */
12013 /*ARGSUSED*/
12014 void
12015 sfmmu_tsbmiss_suspended(struct regs *rp, uintptr_t tagacc, uint_t traptype)
12016 {
12017 	ASSERT(curthread != kreloc_thread);
12018 	mutex_enter(&kpr_suspendlock);
12019 	mutex_exit(&kpr_suspendlock);
12020 }
12021 
12022 /*
12023  * This routine could be optimized to reduce the number of xcalls by flushing
12024  * the entire TLBs if region reference count is above some threshold but the
12025  * tradeoff will depend on the size of the TLB. So for now flush the specific
12026  * page a context at a time.
12027  *
12028  * If uselocks is 0 then it's called after all cpus were captured and all the
12029  * hat locks were taken. In this case don't take the region lock by relying on
12030  * the order of list region update operations in hat_join_region(),
12031  * hat_leave_region() and hat_dup_region(). The ordering in those routines
12032  * guarantees that list is always forward walkable and reaches active sfmmus
12033  * regardless of where xc_attention() captures a cpu.
12034  */
12035 cpuset_t
12036 sfmmu_rgntlb_demap(caddr_t addr, sf_region_t *rgnp,
12037     struct hme_blk *hmeblkp, int uselocks)
12038 {
12039 	sfmmu_t	*sfmmup;
12040 	cpuset_t cpuset;
12041 	cpuset_t rcpuset;
12042 	hatlock_t *hatlockp;
12043 	uint_t rid = rgnp->rgn_id;
12044 	sf_rgn_link_t *rlink;
12045 	sf_scd_t *scdp;
12046 
12047 	ASSERT(hmeblkp->hblk_shared);
12048 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
12049 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
12050 
12051 	CPUSET_ZERO(rcpuset);
12052 	if (uselocks) {
12053 		mutex_enter(&rgnp->rgn_mutex);
12054 	}
12055 	sfmmup = rgnp->rgn_sfmmu_head;
12056 	while (sfmmup != NULL) {
12057 		if (uselocks) {
12058 			hatlockp = sfmmu_hat_enter(sfmmup);
12059 		}
12060 
12061 		/*
12062 		 * When an SCD is created the SCD hat is linked on the sfmmu
12063 		 * region lists for each hme region which is part of the
12064 		 * SCD. If we find an SCD hat, when walking these lists,
12065 		 * then we flush the shared TSBs, if we find a private hat,
12066 		 * which is part of an SCD, but where the region
12067 		 * is not part of the SCD then we flush the private TSBs.
12068 		 */
12069 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12070 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
12071 			scdp = sfmmup->sfmmu_scdp;
12072 			if (SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
12073 				if (uselocks) {
12074 					sfmmu_hat_exit(hatlockp);
12075 				}
12076 				goto next;
12077 			}
12078 		}
12079 
12080 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12081 
12082 		kpreempt_disable();
12083 		cpuset = sfmmup->sfmmu_cpusran;
12084 		CPUSET_AND(cpuset, cpu_ready_set);
12085 		CPUSET_DEL(cpuset, CPU->cpu_id);
12086 		SFMMU_XCALL_STATS(sfmmup);
12087 		xt_some(cpuset, vtag_flushpage_tl1,
12088 		    (uint64_t)addr, (uint64_t)sfmmup);
12089 		vtag_flushpage(addr, (uint64_t)sfmmup);
12090 		if (uselocks) {
12091 			sfmmu_hat_exit(hatlockp);
12092 		}
12093 		kpreempt_enable();
12094 		CPUSET_OR(rcpuset, cpuset);
12095 
12096 next:
12097 		/* LINTED: constant in conditional context */
12098 		SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
12099 		ASSERT(rlink != NULL);
12100 		sfmmup = rlink->next;
12101 	}
12102 	if (uselocks) {
12103 		mutex_exit(&rgnp->rgn_mutex);
12104 	}
12105 	return (rcpuset);
12106 }
12107 
12108 /*
12109  * This routine takes an sfmmu pointer and the va for an adddress in an
12110  * ISM region as input and returns the corresponding region id in ism_rid.
12111  * The return value of 1 indicates that a region has been found and ism_rid
12112  * is valid, otherwise 0 is returned.
12113  */
12114 static int
12115 find_ism_rid(sfmmu_t *sfmmup, sfmmu_t *ism_sfmmup, caddr_t va, uint_t *ism_rid)
12116 {
12117 	ism_blk_t	*ism_blkp;
12118 	int		i;
12119 	ism_map_t	*ism_map;
12120 #ifdef DEBUG
12121 	struct hat	*ism_hatid;
12122 #endif
12123 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12124 
12125 	ism_blkp = sfmmup->sfmmu_iblk;
12126 	while (ism_blkp != NULL) {
12127 		ism_map = ism_blkp->iblk_maps;
12128 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
12129 			if ((va >= ism_start(ism_map[i])) &&
12130 			    (va < ism_end(ism_map[i]))) {
12131 
12132 				*ism_rid = ism_map[i].imap_rid;
12133 #ifdef DEBUG
12134 				ism_hatid = ism_map[i].imap_ismhat;
12135 				ASSERT(ism_hatid == ism_sfmmup);
12136 				ASSERT(ism_hatid->sfmmu_ismhat);
12137 #endif
12138 				return (1);
12139 			}
12140 		}
12141 		ism_blkp = ism_blkp->iblk_next;
12142 	}
12143 	return (0);
12144 }
12145 
12146 /*
12147  * Special routine to flush out ism mappings- TSBs, TLBs and D-caches.
12148  * This routine may be called with all cpu's captured. Therefore, the
12149  * caller is responsible for holding all locks and disabling kernel
12150  * preemption.
12151  */
12152 /* ARGSUSED */
12153 static void
12154 sfmmu_ismtlbcache_demap(caddr_t addr, sfmmu_t *ism_sfmmup,
12155 	struct hme_blk *hmeblkp, pfn_t pfnum, int cache_flush_flag)
12156 {
12157 	cpuset_t 	cpuset;
12158 	caddr_t 	va;
12159 	ism_ment_t	*ment;
12160 	sfmmu_t		*sfmmup;
12161 #ifdef VAC
12162 	int 		vcolor;
12163 #endif
12164 
12165 	sf_scd_t	*scdp;
12166 	uint_t		ism_rid;
12167 
12168 	ASSERT(!hmeblkp->hblk_shared);
12169 	/*
12170 	 * Walk the ism_hat's mapping list and flush the page
12171 	 * from every hat sharing this ism_hat. This routine
12172 	 * may be called while all cpu's have been captured.
12173 	 * Therefore we can't attempt to grab any locks. For now
12174 	 * this means we will protect the ism mapping list under
12175 	 * a single lock which will be grabbed by the caller.
12176 	 * If hat_share/unshare scalibility becomes a performance
12177 	 * problem then we may need to re-think ism mapping list locking.
12178 	 */
12179 	ASSERT(ism_sfmmup->sfmmu_ismhat);
12180 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
12181 	addr = addr - ISMID_STARTADDR;
12182 
12183 	for (ment = ism_sfmmup->sfmmu_iment; ment; ment = ment->iment_next) {
12184 
12185 		sfmmup = ment->iment_hat;
12186 
12187 		va = ment->iment_base_va;
12188 		va = (caddr_t)((uintptr_t)va  + (uintptr_t)addr);
12189 
12190 		/*
12191 		 * When an SCD is created the SCD hat is linked on the ism
12192 		 * mapping lists for each ISM segment which is part of the
12193 		 * SCD. If we find an SCD hat, when walking these lists,
12194 		 * then we flush the shared TSBs, if we find a private hat,
12195 		 * which is part of an SCD, but where the region
12196 		 * corresponding to this va is not part of the SCD then we
12197 		 * flush the private TSBs.
12198 		 */
12199 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12200 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD) &&
12201 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
12202 			if (!find_ism_rid(sfmmup, ism_sfmmup, va,
12203 			    &ism_rid)) {
12204 				cmn_err(CE_PANIC,
12205 				    "can't find matching ISM rid!");
12206 			}
12207 
12208 			scdp = sfmmup->sfmmu_scdp;
12209 			if (SFMMU_IS_ISMRID_VALID(ism_rid) &&
12210 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map,
12211 			    ism_rid)) {
12212 				continue;
12213 			}
12214 		}
12215 		SFMMU_UNLOAD_TSB(va, sfmmup, hmeblkp, 1);
12216 
12217 		cpuset = sfmmup->sfmmu_cpusran;
12218 		CPUSET_AND(cpuset, cpu_ready_set);
12219 		CPUSET_DEL(cpuset, CPU->cpu_id);
12220 		SFMMU_XCALL_STATS(sfmmup);
12221 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)va,
12222 		    (uint64_t)sfmmup);
12223 		vtag_flushpage(va, (uint64_t)sfmmup);
12224 
12225 #ifdef VAC
12226 		/*
12227 		 * Flush D$
12228 		 * When flushing D$ we must flush all
12229 		 * cpu's. See sfmmu_cache_flush().
12230 		 */
12231 		if (cache_flush_flag == CACHE_FLUSH) {
12232 			cpuset = cpu_ready_set;
12233 			CPUSET_DEL(cpuset, CPU->cpu_id);
12234 
12235 			SFMMU_XCALL_STATS(sfmmup);
12236 			vcolor = addr_to_vcolor(va);
12237 			xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12238 			vac_flushpage(pfnum, vcolor);
12239 		}
12240 #endif	/* VAC */
12241 	}
12242 }
12243 
12244 /*
12245  * Demaps the TSB, CPU caches, and flushes all TLBs on all CPUs of
12246  * a particular virtual address and ctx.  If noflush is set we do not
12247  * flush the TLB/TSB.  This function may or may not be called with the
12248  * HAT lock held.
12249  */
12250 static void
12251 sfmmu_tlbcache_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12252 	pfn_t pfnum, int tlb_noflush, int cpu_flag, int cache_flush_flag,
12253 	int hat_lock_held)
12254 {
12255 #ifdef VAC
12256 	int vcolor;
12257 #endif
12258 	cpuset_t cpuset;
12259 	hatlock_t *hatlockp;
12260 
12261 	ASSERT(!hmeblkp->hblk_shared);
12262 
12263 #if defined(lint) && !defined(VAC)
12264 	pfnum = pfnum;
12265 	cpu_flag = cpu_flag;
12266 	cache_flush_flag = cache_flush_flag;
12267 #endif
12268 
12269 	/*
12270 	 * There is no longer a need to protect against ctx being
12271 	 * stolen here since we don't store the ctx in the TSB anymore.
12272 	 */
12273 #ifdef VAC
12274 	vcolor = addr_to_vcolor(addr);
12275 #endif
12276 
12277 	/*
12278 	 * We must hold the hat lock during the flush of TLB,
12279 	 * to avoid a race with sfmmu_invalidate_ctx(), where
12280 	 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12281 	 * causing TLB demap routine to skip flush on that MMU.
12282 	 * If the context on a MMU has already been set to
12283 	 * INVALID_CONTEXT, we just get an extra flush on
12284 	 * that MMU.
12285 	 */
12286 	if (!hat_lock_held && !tlb_noflush)
12287 		hatlockp = sfmmu_hat_enter(sfmmup);
12288 
12289 	kpreempt_disable();
12290 	if (!tlb_noflush) {
12291 		/*
12292 		 * Flush the TSB and TLB.
12293 		 */
12294 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12295 
12296 		cpuset = sfmmup->sfmmu_cpusran;
12297 		CPUSET_AND(cpuset, cpu_ready_set);
12298 		CPUSET_DEL(cpuset, CPU->cpu_id);
12299 
12300 		SFMMU_XCALL_STATS(sfmmup);
12301 
12302 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
12303 		    (uint64_t)sfmmup);
12304 
12305 		vtag_flushpage(addr, (uint64_t)sfmmup);
12306 	}
12307 
12308 	if (!hat_lock_held && !tlb_noflush)
12309 		sfmmu_hat_exit(hatlockp);
12310 
12311 #ifdef VAC
12312 	/*
12313 	 * Flush the D$
12314 	 *
12315 	 * Even if the ctx is stolen, we need to flush the
12316 	 * cache. Our ctx stealer only flushes the TLBs.
12317 	 */
12318 	if (cache_flush_flag == CACHE_FLUSH) {
12319 		if (cpu_flag & FLUSH_ALL_CPUS) {
12320 			cpuset = cpu_ready_set;
12321 		} else {
12322 			cpuset = sfmmup->sfmmu_cpusran;
12323 			CPUSET_AND(cpuset, cpu_ready_set);
12324 		}
12325 		CPUSET_DEL(cpuset, CPU->cpu_id);
12326 		SFMMU_XCALL_STATS(sfmmup);
12327 		xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12328 		vac_flushpage(pfnum, vcolor);
12329 	}
12330 #endif	/* VAC */
12331 	kpreempt_enable();
12332 }
12333 
12334 /*
12335  * Demaps the TSB and flushes all TLBs on all cpus for a particular virtual
12336  * address and ctx.  If noflush is set we do not currently do anything.
12337  * This function may or may not be called with the HAT lock held.
12338  */
12339 static void
12340 sfmmu_tlb_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12341 	int tlb_noflush, int hat_lock_held)
12342 {
12343 	cpuset_t cpuset;
12344 	hatlock_t *hatlockp;
12345 
12346 	ASSERT(!hmeblkp->hblk_shared);
12347 
12348 	/*
12349 	 * If the process is exiting we have nothing to do.
12350 	 */
12351 	if (tlb_noflush)
12352 		return;
12353 
12354 	/*
12355 	 * Flush TSB.
12356 	 */
12357 	if (!hat_lock_held)
12358 		hatlockp = sfmmu_hat_enter(sfmmup);
12359 	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12360 
12361 	kpreempt_disable();
12362 
12363 	cpuset = sfmmup->sfmmu_cpusran;
12364 	CPUSET_AND(cpuset, cpu_ready_set);
12365 	CPUSET_DEL(cpuset, CPU->cpu_id);
12366 
12367 	SFMMU_XCALL_STATS(sfmmup);
12368 	xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr, (uint64_t)sfmmup);
12369 
12370 	vtag_flushpage(addr, (uint64_t)sfmmup);
12371 
12372 	if (!hat_lock_held)
12373 		sfmmu_hat_exit(hatlockp);
12374 
12375 	kpreempt_enable();
12376 
12377 }
12378 
12379 /*
12380  * Special case of sfmmu_tlb_demap for MMU_PAGESIZE hblks. Use the xcall
12381  * call handler that can flush a range of pages to save on xcalls.
12382  */
12383 static int sfmmu_xcall_save;
12384 
12385 /*
12386  * this routine is never used for demaping addresses backed by SRD hmeblks.
12387  */
12388 static void
12389 sfmmu_tlb_range_demap(demap_range_t *dmrp)
12390 {
12391 	sfmmu_t *sfmmup = dmrp->dmr_sfmmup;
12392 	hatlock_t *hatlockp;
12393 	cpuset_t cpuset;
12394 	uint64_t sfmmu_pgcnt;
12395 	pgcnt_t pgcnt = 0;
12396 	int pgunload = 0;
12397 	int dirtypg = 0;
12398 	caddr_t addr = dmrp->dmr_addr;
12399 	caddr_t eaddr;
12400 	uint64_t bitvec = dmrp->dmr_bitvec;
12401 
12402 	ASSERT(bitvec & 1);
12403 
12404 	/*
12405 	 * Flush TSB and calculate number of pages to flush.
12406 	 */
12407 	while (bitvec != 0) {
12408 		dirtypg = 0;
12409 		/*
12410 		 * Find the first page to flush and then count how many
12411 		 * pages there are after it that also need to be flushed.
12412 		 * This way the number of TSB flushes is minimized.
12413 		 */
12414 		while ((bitvec & 1) == 0) {
12415 			pgcnt++;
12416 			addr += MMU_PAGESIZE;
12417 			bitvec >>= 1;
12418 		}
12419 		while (bitvec & 1) {
12420 			dirtypg++;
12421 			bitvec >>= 1;
12422 		}
12423 		eaddr = addr + ptob(dirtypg);
12424 		hatlockp = sfmmu_hat_enter(sfmmup);
12425 		sfmmu_unload_tsb_range(sfmmup, addr, eaddr, TTE8K);
12426 		sfmmu_hat_exit(hatlockp);
12427 		pgunload += dirtypg;
12428 		addr = eaddr;
12429 		pgcnt += dirtypg;
12430 	}
12431 
12432 	ASSERT((pgcnt<<MMU_PAGESHIFT) <= dmrp->dmr_endaddr - dmrp->dmr_addr);
12433 	if (sfmmup->sfmmu_free == 0) {
12434 		addr = dmrp->dmr_addr;
12435 		bitvec = dmrp->dmr_bitvec;
12436 
12437 		/*
12438 		 * make sure it has SFMMU_PGCNT_SHIFT bits only,
12439 		 * as it will be used to pack argument for xt_some
12440 		 */
12441 		ASSERT((pgcnt > 0) &&
12442 		    (pgcnt <= (1 << SFMMU_PGCNT_SHIFT)));
12443 
12444 		/*
12445 		 * Encode pgcnt as (pgcnt -1 ), and pass (pgcnt - 1) in
12446 		 * the low 6 bits of sfmmup. This is doable since pgcnt
12447 		 * always >= 1.
12448 		 */
12449 		ASSERT(!((uint64_t)sfmmup & SFMMU_PGCNT_MASK));
12450 		sfmmu_pgcnt = (uint64_t)sfmmup |
12451 		    ((pgcnt - 1) & SFMMU_PGCNT_MASK);
12452 
12453 		/*
12454 		 * We must hold the hat lock during the flush of TLB,
12455 		 * to avoid a race with sfmmu_invalidate_ctx(), where
12456 		 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12457 		 * causing TLB demap routine to skip flush on that MMU.
12458 		 * If the context on a MMU has already been set to
12459 		 * INVALID_CONTEXT, we just get an extra flush on
12460 		 * that MMU.
12461 		 */
12462 		hatlockp = sfmmu_hat_enter(sfmmup);
12463 		kpreempt_disable();
12464 
12465 		cpuset = sfmmup->sfmmu_cpusran;
12466 		CPUSET_AND(cpuset, cpu_ready_set);
12467 		CPUSET_DEL(cpuset, CPU->cpu_id);
12468 
12469 		SFMMU_XCALL_STATS(sfmmup);
12470 		xt_some(cpuset, vtag_flush_pgcnt_tl1, (uint64_t)addr,
12471 		    sfmmu_pgcnt);
12472 
12473 		for (; bitvec != 0; bitvec >>= 1) {
12474 			if (bitvec & 1)
12475 				vtag_flushpage(addr, (uint64_t)sfmmup);
12476 			addr += MMU_PAGESIZE;
12477 		}
12478 		kpreempt_enable();
12479 		sfmmu_hat_exit(hatlockp);
12480 
12481 		sfmmu_xcall_save += (pgunload-1);
12482 	}
12483 	dmrp->dmr_bitvec = 0;
12484 }
12485 
12486 /*
12487  * In cases where we need to synchronize with TLB/TSB miss trap
12488  * handlers, _and_ need to flush the TLB, it's a lot easier to
12489  * throw away the context from the process than to do a
12490  * special song and dance to keep things consistent for the
12491  * handlers.
12492  *
12493  * Since the process suddenly ends up without a context and our caller
12494  * holds the hat lock, threads that fault after this function is called
12495  * will pile up on the lock.  We can then do whatever we need to
12496  * atomically from the context of the caller.  The first blocked thread
12497  * to resume executing will get the process a new context, and the
12498  * process will resume executing.
12499  *
12500  * One added advantage of this approach is that on MMUs that
12501  * support a "flush all" operation, we will delay the flush until
12502  * cnum wrap-around, and then flush the TLB one time.  This
12503  * is rather rare, so it's a lot less expensive than making 8000
12504  * x-calls to flush the TLB 8000 times.
12505  *
12506  * A per-process (PP) lock is used to synchronize ctx allocations in
12507  * resume() and ctx invalidations here.
12508  */
12509 static void
12510 sfmmu_invalidate_ctx(sfmmu_t *sfmmup)
12511 {
12512 	cpuset_t cpuset;
12513 	int cnum, currcnum;
12514 	mmu_ctx_t *mmu_ctxp;
12515 	int i;
12516 	uint_t pstate_save;
12517 
12518 	SFMMU_STAT(sf_ctx_inv);
12519 
12520 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12521 	ASSERT(sfmmup != ksfmmup);
12522 
12523 	kpreempt_disable();
12524 
12525 	mmu_ctxp = CPU_MMU_CTXP(CPU);
12526 	ASSERT(mmu_ctxp);
12527 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
12528 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
12529 
12530 	currcnum = sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum;
12531 
12532 	pstate_save = sfmmu_disable_intrs();
12533 
12534 	lock_set(&sfmmup->sfmmu_ctx_lock);	/* acquire PP lock */
12535 	/* set HAT cnum invalid across all context domains. */
12536 	for (i = 0; i < max_mmu_ctxdoms; i++) {
12537 
12538 		cnum = 	sfmmup->sfmmu_ctxs[i].cnum;
12539 		if (cnum == INVALID_CONTEXT) {
12540 			continue;
12541 		}
12542 
12543 		sfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
12544 	}
12545 	membar_enter();	/* make sure globally visible to all CPUs */
12546 	lock_clear(&sfmmup->sfmmu_ctx_lock);	/* release PP lock */
12547 
12548 	sfmmu_enable_intrs(pstate_save);
12549 
12550 	cpuset = sfmmup->sfmmu_cpusran;
12551 	CPUSET_DEL(cpuset, CPU->cpu_id);
12552 	CPUSET_AND(cpuset, cpu_ready_set);
12553 	if (!CPUSET_ISNULL(cpuset)) {
12554 		SFMMU_XCALL_STATS(sfmmup);
12555 		xt_some(cpuset, sfmmu_raise_tsb_exception,
12556 		    (uint64_t)sfmmup, INVALID_CONTEXT);
12557 		xt_sync(cpuset);
12558 		SFMMU_STAT(sf_tsb_raise_exception);
12559 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
12560 	}
12561 
12562 	/*
12563 	 * If the hat to-be-invalidated is the same as the current
12564 	 * process on local CPU we need to invalidate
12565 	 * this CPU context as well.
12566 	 */
12567 	if ((sfmmu_getctx_sec() == currcnum) &&
12568 	    (currcnum != INVALID_CONTEXT)) {
12569 		/* sets shared context to INVALID too */
12570 		sfmmu_setctx_sec(INVALID_CONTEXT);
12571 		sfmmu_clear_utsbinfo();
12572 	}
12573 
12574 	SFMMU_FLAGS_SET(sfmmup, HAT_ALLCTX_INVALID);
12575 
12576 	kpreempt_enable();
12577 
12578 	/*
12579 	 * we hold the hat lock, so nobody should allocate a context
12580 	 * for us yet
12581 	 */
12582 	ASSERT(sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum == INVALID_CONTEXT);
12583 }
12584 
12585 #ifdef VAC
12586 /*
12587  * We need to flush the cache in all cpus.  It is possible that
12588  * a process referenced a page as cacheable but has sinced exited
12589  * and cleared the mapping list.  We still to flush it but have no
12590  * state so all cpus is the only alternative.
12591  */
12592 void
12593 sfmmu_cache_flush(pfn_t pfnum, int vcolor)
12594 {
12595 	cpuset_t cpuset;
12596 
12597 	kpreempt_disable();
12598 	cpuset = cpu_ready_set;
12599 	CPUSET_DEL(cpuset, CPU->cpu_id);
12600 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12601 	xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12602 	xt_sync(cpuset);
12603 	vac_flushpage(pfnum, vcolor);
12604 	kpreempt_enable();
12605 }
12606 
12607 void
12608 sfmmu_cache_flushcolor(int vcolor, pfn_t pfnum)
12609 {
12610 	cpuset_t cpuset;
12611 
12612 	ASSERT(vcolor >= 0);
12613 
12614 	kpreempt_disable();
12615 	cpuset = cpu_ready_set;
12616 	CPUSET_DEL(cpuset, CPU->cpu_id);
12617 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12618 	xt_some(cpuset, vac_flushcolor_tl1, vcolor, pfnum);
12619 	xt_sync(cpuset);
12620 	vac_flushcolor(vcolor, pfnum);
12621 	kpreempt_enable();
12622 }
12623 #endif	/* VAC */
12624 
12625 /*
12626  * We need to prevent processes from accessing the TSB using a cached physical
12627  * address.  It's alright if they try to access the TSB via virtual address
12628  * since they will just fault on that virtual address once the mapping has
12629  * been suspended.
12630  */
12631 #pragma weak sendmondo_in_recover
12632 
12633 /* ARGSUSED */
12634 static int
12635 sfmmu_tsb_pre_relocator(caddr_t va, uint_t tsbsz, uint_t flags, void *tsbinfo)
12636 {
12637 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12638 	sfmmu_t *sfmmup = tsbinfop->tsb_sfmmu;
12639 	hatlock_t *hatlockp;
12640 	sf_scd_t *scdp;
12641 
12642 	if (flags != HAT_PRESUSPEND)
12643 		return (0);
12644 
12645 	/*
12646 	 * If tsb is a shared TSB with TSB_SHAREDCTX set, sfmmup must
12647 	 * be a shared hat, then set SCD's tsbinfo's flag.
12648 	 * If tsb is not shared, sfmmup is a private hat, then set
12649 	 * its private tsbinfo's flag.
12650 	 */
12651 	hatlockp = sfmmu_hat_enter(sfmmup);
12652 	tsbinfop->tsb_flags |= TSB_RELOC_FLAG;
12653 
12654 	if (!(tsbinfop->tsb_flags & TSB_SHAREDCTX)) {
12655 		sfmmu_tsb_inv_ctx(sfmmup);
12656 		sfmmu_hat_exit(hatlockp);
12657 	} else {
12658 		/* release lock on the shared hat */
12659 		sfmmu_hat_exit(hatlockp);
12660 		/* sfmmup is a shared hat */
12661 		ASSERT(sfmmup->sfmmu_scdhat);
12662 		scdp = sfmmup->sfmmu_scdp;
12663 		ASSERT(scdp != NULL);
12664 		/* get private hat from the scd list */
12665 		mutex_enter(&scdp->scd_mutex);
12666 		sfmmup = scdp->scd_sf_list;
12667 		while (sfmmup != NULL) {
12668 			hatlockp = sfmmu_hat_enter(sfmmup);
12669 			/*
12670 			 * We do not call sfmmu_tsb_inv_ctx here because
12671 			 * sendmondo_in_recover check is only needed for
12672 			 * sun4u.
12673 			 */
12674 			sfmmu_invalidate_ctx(sfmmup);
12675 			sfmmu_hat_exit(hatlockp);
12676 			sfmmup = sfmmup->sfmmu_scd_link.next;
12677 
12678 		}
12679 		mutex_exit(&scdp->scd_mutex);
12680 	}
12681 	return (0);
12682 }
12683 
12684 static void
12685 sfmmu_tsb_inv_ctx(sfmmu_t *sfmmup)
12686 {
12687 	extern uint32_t sendmondo_in_recover;
12688 
12689 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12690 
12691 	/*
12692 	 * For Cheetah+ Erratum 25:
12693 	 * Wait for any active recovery to finish.  We can't risk
12694 	 * relocating the TSB of the thread running mondo_recover_proc()
12695 	 * since, if we did that, we would deadlock.  The scenario we are
12696 	 * trying to avoid is as follows:
12697 	 *
12698 	 * THIS CPU			RECOVER CPU
12699 	 * --------			-----------
12700 	 *				Begins recovery, walking through TSB
12701 	 * hat_pagesuspend() TSB TTE
12702 	 *				TLB miss on TSB TTE, spins at TL1
12703 	 * xt_sync()
12704 	 *	send_mondo_timeout()
12705 	 *	mondo_recover_proc()
12706 	 *	((deadlocked))
12707 	 *
12708 	 * The second half of the workaround is that mondo_recover_proc()
12709 	 * checks to see if the tsb_info has the RELOC flag set, and if it
12710 	 * does, it skips over that TSB without ever touching tsbinfop->tsb_va
12711 	 * and hence avoiding the TLB miss that could result in a deadlock.
12712 	 */
12713 	if (&sendmondo_in_recover) {
12714 		membar_enter();	/* make sure RELOC flag visible */
12715 		while (sendmondo_in_recover) {
12716 			drv_usecwait(1);
12717 			membar_consumer();
12718 		}
12719 	}
12720 
12721 	sfmmu_invalidate_ctx(sfmmup);
12722 }
12723 
12724 /* ARGSUSED */
12725 static int
12726 sfmmu_tsb_post_relocator(caddr_t va, uint_t tsbsz, uint_t flags,
12727 	void *tsbinfo, pfn_t newpfn)
12728 {
12729 	hatlock_t *hatlockp;
12730 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12731 	sfmmu_t	*sfmmup = tsbinfop->tsb_sfmmu;
12732 
12733 	if (flags != HAT_POSTUNSUSPEND)
12734 		return (0);
12735 
12736 	hatlockp = sfmmu_hat_enter(sfmmup);
12737 
12738 	SFMMU_STAT(sf_tsb_reloc);
12739 
12740 	/*
12741 	 * The process may have swapped out while we were relocating one
12742 	 * of its TSBs.  If so, don't bother doing the setup since the
12743 	 * process can't be using the memory anymore.
12744 	 */
12745 	if ((tsbinfop->tsb_flags & TSB_SWAPPED) == 0) {
12746 		ASSERT(va == tsbinfop->tsb_va);
12747 		sfmmu_tsbinfo_setup_phys(tsbinfop, newpfn);
12748 
12749 		if (tsbinfop->tsb_flags & TSB_FLUSH_NEEDED) {
12750 			sfmmu_inv_tsb(tsbinfop->tsb_va,
12751 			    TSB_BYTES(tsbinfop->tsb_szc));
12752 			tsbinfop->tsb_flags &= ~TSB_FLUSH_NEEDED;
12753 		}
12754 	}
12755 
12756 	membar_exit();
12757 	tsbinfop->tsb_flags &= ~TSB_RELOC_FLAG;
12758 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
12759 
12760 	sfmmu_hat_exit(hatlockp);
12761 
12762 	return (0);
12763 }
12764 
12765 /*
12766  * Allocate and initialize a tsb_info structure.  Note that we may or may not
12767  * allocate a TSB here, depending on the flags passed in.
12768  */
12769 static int
12770 sfmmu_tsbinfo_alloc(struct tsb_info **tsbinfopp, int tsb_szc, int tte_sz_mask,
12771 	uint_t flags, sfmmu_t *sfmmup)
12772 {
12773 	int err;
12774 
12775 	*tsbinfopp = (struct tsb_info *)kmem_cache_alloc(
12776 	    sfmmu_tsbinfo_cache, KM_SLEEP);
12777 
12778 	if ((err = sfmmu_init_tsbinfo(*tsbinfopp, tte_sz_mask,
12779 	    tsb_szc, flags, sfmmup)) != 0) {
12780 		kmem_cache_free(sfmmu_tsbinfo_cache, *tsbinfopp);
12781 		SFMMU_STAT(sf_tsb_allocfail);
12782 		*tsbinfopp = NULL;
12783 		return (err);
12784 	}
12785 	SFMMU_STAT(sf_tsb_alloc);
12786 
12787 	/*
12788 	 * Bump the TSB size counters for this TSB size.
12789 	 */
12790 	(*(((int *)&sfmmu_tsbsize_stat) + tsb_szc))++;
12791 	return (0);
12792 }
12793 
12794 static void
12795 sfmmu_tsb_free(struct tsb_info *tsbinfo)
12796 {
12797 	caddr_t tsbva = tsbinfo->tsb_va;
12798 	uint_t tsb_size = TSB_BYTES(tsbinfo->tsb_szc);
12799 	struct kmem_cache *kmem_cachep = tsbinfo->tsb_cache;
12800 	vmem_t	*vmp = tsbinfo->tsb_vmp;
12801 
12802 	/*
12803 	 * If we allocated this TSB from relocatable kernel memory, then we
12804 	 * need to uninstall the callback handler.
12805 	 */
12806 	if (tsbinfo->tsb_cache != sfmmu_tsb8k_cache) {
12807 		uintptr_t slab_mask;
12808 		caddr_t slab_vaddr;
12809 		page_t **ppl;
12810 		int ret;
12811 
12812 		ASSERT(tsb_size <= MMU_PAGESIZE4M || use_bigtsb_arena);
12813 		if (tsb_size > MMU_PAGESIZE4M)
12814 			slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12815 		else
12816 			slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12817 		slab_vaddr = (caddr_t)((uintptr_t)tsbva & slab_mask);
12818 
12819 		ret = as_pagelock(&kas, &ppl, slab_vaddr, PAGESIZE, S_WRITE);
12820 		ASSERT(ret == 0);
12821 		hat_delete_callback(tsbva, (uint_t)tsb_size, (void *)tsbinfo,
12822 		    0, NULL);
12823 		as_pageunlock(&kas, ppl, slab_vaddr, PAGESIZE, S_WRITE);
12824 	}
12825 
12826 	if (kmem_cachep != NULL) {
12827 		kmem_cache_free(kmem_cachep, tsbva);
12828 	} else {
12829 		vmem_xfree(vmp, (void *)tsbva, tsb_size);
12830 	}
12831 	tsbinfo->tsb_va = (caddr_t)0xbad00bad;
12832 	atomic_add_64(&tsb_alloc_bytes, -(int64_t)tsb_size);
12833 }
12834 
12835 static void
12836 sfmmu_tsbinfo_free(struct tsb_info *tsbinfo)
12837 {
12838 	if ((tsbinfo->tsb_flags & TSB_SWAPPED) == 0) {
12839 		sfmmu_tsb_free(tsbinfo);
12840 	}
12841 	kmem_cache_free(sfmmu_tsbinfo_cache, tsbinfo);
12842 
12843 }
12844 
12845 /*
12846  * Setup all the references to physical memory for this tsbinfo.
12847  * The underlying page(s) must be locked.
12848  */
12849 static void
12850 sfmmu_tsbinfo_setup_phys(struct tsb_info *tsbinfo, pfn_t pfn)
12851 {
12852 	ASSERT(pfn != PFN_INVALID);
12853 	ASSERT(pfn == va_to_pfn(tsbinfo->tsb_va));
12854 
12855 #ifndef sun4v
12856 	if (tsbinfo->tsb_szc == 0) {
12857 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn,
12858 		    PROT_WRITE|PROT_READ, TTE8K);
12859 	} else {
12860 		/*
12861 		 * Round down PA and use a large mapping; the handlers will
12862 		 * compute the TSB pointer at the correct offset into the
12863 		 * big virtual page.  NOTE: this assumes all TSBs larger
12864 		 * than 8K must come from physically contiguous slabs of
12865 		 * size tsb_slab_size.
12866 		 */
12867 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn & ~tsb_slab_mask,
12868 		    PROT_WRITE|PROT_READ, tsb_slab_ttesz);
12869 	}
12870 	tsbinfo->tsb_pa = ptob(pfn);
12871 
12872 	TTE_SET_LOCKED(&tsbinfo->tsb_tte); /* lock the tte into dtlb */
12873 	TTE_SET_MOD(&tsbinfo->tsb_tte);    /* enable writes */
12874 
12875 	ASSERT(TTE_IS_PRIVILEGED(&tsbinfo->tsb_tte));
12876 	ASSERT(TTE_IS_LOCKED(&tsbinfo->tsb_tte));
12877 #else /* sun4v */
12878 	tsbinfo->tsb_pa = ptob(pfn);
12879 #endif /* sun4v */
12880 }
12881 
12882 
12883 /*
12884  * Returns zero on success, ENOMEM if over the high water mark,
12885  * or EAGAIN if the caller needs to retry with a smaller TSB
12886  * size (or specify TSB_FORCEALLOC if the allocation can't fail).
12887  *
12888  * This call cannot fail to allocate a TSB if TSB_FORCEALLOC
12889  * is specified and the TSB requested is PAGESIZE, though it
12890  * may sleep waiting for memory if sufficient memory is not
12891  * available.
12892  */
12893 static int
12894 sfmmu_init_tsbinfo(struct tsb_info *tsbinfo, int tteszmask,
12895     int tsbcode, uint_t flags, sfmmu_t *sfmmup)
12896 {
12897 	caddr_t vaddr = NULL;
12898 	caddr_t slab_vaddr;
12899 	uintptr_t slab_mask;
12900 	int tsbbytes = TSB_BYTES(tsbcode);
12901 	int lowmem = 0;
12902 	struct kmem_cache *kmem_cachep = NULL;
12903 	vmem_t *vmp = NULL;
12904 	lgrp_id_t lgrpid = LGRP_NONE;
12905 	pfn_t pfn;
12906 	uint_t cbflags = HAC_SLEEP;
12907 	page_t **pplist;
12908 	int ret;
12909 
12910 	ASSERT(tsbbytes <= MMU_PAGESIZE4M || use_bigtsb_arena);
12911 	if (tsbbytes > MMU_PAGESIZE4M)
12912 		slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12913 	else
12914 		slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12915 
12916 	if (flags & (TSB_FORCEALLOC | TSB_SWAPIN | TSB_GROW | TSB_SHRINK))
12917 		flags |= TSB_ALLOC;
12918 
12919 	ASSERT((flags & TSB_FORCEALLOC) == 0 || tsbcode == TSB_MIN_SZCODE);
12920 
12921 	tsbinfo->tsb_sfmmu = sfmmup;
12922 
12923 	/*
12924 	 * If not allocating a TSB, set up the tsbinfo, set TSB_SWAPPED, and
12925 	 * return.
12926 	 */
12927 	if ((flags & TSB_ALLOC) == 0) {
12928 		tsbinfo->tsb_szc = tsbcode;
12929 		tsbinfo->tsb_ttesz_mask = tteszmask;
12930 		tsbinfo->tsb_va = (caddr_t)0xbadbadbeef;
12931 		tsbinfo->tsb_pa = -1;
12932 		tsbinfo->tsb_tte.ll = 0;
12933 		tsbinfo->tsb_next = NULL;
12934 		tsbinfo->tsb_flags = TSB_SWAPPED;
12935 		tsbinfo->tsb_cache = NULL;
12936 		tsbinfo->tsb_vmp = NULL;
12937 		return (0);
12938 	}
12939 
12940 #ifdef DEBUG
12941 	/*
12942 	 * For debugging:
12943 	 * Randomly force allocation failures every tsb_alloc_mtbf
12944 	 * tries if TSB_FORCEALLOC is not specified.  This will
12945 	 * return ENOMEM if tsb_alloc_mtbf is odd, or EAGAIN if
12946 	 * it is even, to allow testing of both failure paths...
12947 	 */
12948 	if (tsb_alloc_mtbf && ((flags & TSB_FORCEALLOC) == 0) &&
12949 	    (tsb_alloc_count++ == tsb_alloc_mtbf)) {
12950 		tsb_alloc_count = 0;
12951 		tsb_alloc_fail_mtbf++;
12952 		return ((tsb_alloc_mtbf & 1)? ENOMEM : EAGAIN);
12953 	}
12954 #endif	/* DEBUG */
12955 
12956 	/*
12957 	 * Enforce high water mark if we are not doing a forced allocation
12958 	 * and are not shrinking a process' TSB.
12959 	 */
12960 	if ((flags & TSB_SHRINK) == 0 &&
12961 	    (tsbbytes + tsb_alloc_bytes) > tsb_alloc_hiwater) {
12962 		if ((flags & TSB_FORCEALLOC) == 0)
12963 			return (ENOMEM);
12964 		lowmem = 1;
12965 	}
12966 
12967 	/*
12968 	 * Allocate from the correct location based upon the size of the TSB
12969 	 * compared to the base page size, and what memory conditions dictate.
12970 	 * Note we always do nonblocking allocations from the TSB arena since
12971 	 * we don't want memory fragmentation to cause processes to block
12972 	 * indefinitely waiting for memory; until the kernel algorithms that
12973 	 * coalesce large pages are improved this is our best option.
12974 	 *
12975 	 * Algorithm:
12976 	 *	If allocating a "large" TSB (>8K), allocate from the
12977 	 *		appropriate kmem_tsb_default_arena vmem arena
12978 	 *	else if low on memory or the TSB_FORCEALLOC flag is set or
12979 	 *	tsb_forceheap is set
12980 	 *		Allocate from kernel heap via sfmmu_tsb8k_cache with
12981 	 *		KM_SLEEP (never fails)
12982 	 *	else
12983 	 *		Allocate from appropriate sfmmu_tsb_cache with
12984 	 *		KM_NOSLEEP
12985 	 *	endif
12986 	 */
12987 	if (tsb_lgrp_affinity)
12988 		lgrpid = lgrp_home_id(curthread);
12989 	if (lgrpid == LGRP_NONE)
12990 		lgrpid = 0;	/* use lgrp of boot CPU */
12991 
12992 	if (tsbbytes > MMU_PAGESIZE) {
12993 		if (tsbbytes > MMU_PAGESIZE4M) {
12994 			vmp = kmem_bigtsb_default_arena[lgrpid];
12995 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
12996 			    0, 0, NULL, NULL, VM_NOSLEEP);
12997 		} else {
12998 			vmp = kmem_tsb_default_arena[lgrpid];
12999 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
13000 			    0, 0, NULL, NULL, VM_NOSLEEP);
13001 		}
13002 #ifdef	DEBUG
13003 	} else if (lowmem || (flags & TSB_FORCEALLOC) || tsb_forceheap) {
13004 #else	/* !DEBUG */
13005 	} else if (lowmem || (flags & TSB_FORCEALLOC)) {
13006 #endif	/* DEBUG */
13007 		kmem_cachep = sfmmu_tsb8k_cache;
13008 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_SLEEP);
13009 		ASSERT(vaddr != NULL);
13010 	} else {
13011 		kmem_cachep = sfmmu_tsb_cache[lgrpid];
13012 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_NOSLEEP);
13013 	}
13014 
13015 	tsbinfo->tsb_cache = kmem_cachep;
13016 	tsbinfo->tsb_vmp = vmp;
13017 
13018 	if (vaddr == NULL) {
13019 		return (EAGAIN);
13020 	}
13021 
13022 	atomic_add_64(&tsb_alloc_bytes, (int64_t)tsbbytes);
13023 	kmem_cachep = tsbinfo->tsb_cache;
13024 
13025 	/*
13026 	 * If we are allocating from outside the cage, then we need to
13027 	 * register a relocation callback handler.  Note that for now
13028 	 * since pseudo mappings always hang off of the slab's root page,
13029 	 * we need only lock the first 8K of the TSB slab.  This is a bit
13030 	 * hacky but it is good for performance.
13031 	 */
13032 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13033 		slab_vaddr = (caddr_t)((uintptr_t)vaddr & slab_mask);
13034 		ret = as_pagelock(&kas, &pplist, slab_vaddr, PAGESIZE, S_WRITE);
13035 		ASSERT(ret == 0);
13036 		ret = hat_add_callback(sfmmu_tsb_cb_id, vaddr, (uint_t)tsbbytes,
13037 		    cbflags, (void *)tsbinfo, &pfn, NULL);
13038 
13039 		/*
13040 		 * Need to free up resources if we could not successfully
13041 		 * add the callback function and return an error condition.
13042 		 */
13043 		if (ret != 0) {
13044 			if (kmem_cachep) {
13045 				kmem_cache_free(kmem_cachep, vaddr);
13046 			} else {
13047 				vmem_xfree(vmp, (void *)vaddr, tsbbytes);
13048 			}
13049 			as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE,
13050 			    S_WRITE);
13051 			return (EAGAIN);
13052 		}
13053 	} else {
13054 		/*
13055 		 * Since allocation of 8K TSBs from heap is rare and occurs
13056 		 * during memory pressure we allocate them from permanent
13057 		 * memory rather than using callbacks to get the PFN.
13058 		 */
13059 		pfn = hat_getpfnum(kas.a_hat, vaddr);
13060 	}
13061 
13062 	tsbinfo->tsb_va = vaddr;
13063 	tsbinfo->tsb_szc = tsbcode;
13064 	tsbinfo->tsb_ttesz_mask = tteszmask;
13065 	tsbinfo->tsb_next = NULL;
13066 	tsbinfo->tsb_flags = 0;
13067 
13068 	sfmmu_tsbinfo_setup_phys(tsbinfo, pfn);
13069 
13070 	sfmmu_inv_tsb(vaddr, tsbbytes);
13071 
13072 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13073 		as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE, S_WRITE);
13074 	}
13075 
13076 	return (0);
13077 }
13078 
13079 /*
13080  * Initialize per cpu tsb and per cpu tsbmiss_area
13081  */
13082 void
13083 sfmmu_init_tsbs(void)
13084 {
13085 	int i;
13086 	struct tsbmiss	*tsbmissp;
13087 	struct kpmtsbm	*kpmtsbmp;
13088 #ifndef sun4v
13089 	extern int	dcache_line_mask;
13090 #endif /* sun4v */
13091 	extern uint_t	vac_colors;
13092 
13093 	/*
13094 	 * Init. tsb miss area.
13095 	 */
13096 	tsbmissp = tsbmiss_area;
13097 
13098 	for (i = 0; i < NCPU; tsbmissp++, i++) {
13099 		/*
13100 		 * initialize the tsbmiss area.
13101 		 * Do this for all possible CPUs as some may be added
13102 		 * while the system is running. There is no cost to this.
13103 		 */
13104 		tsbmissp->ksfmmup = ksfmmup;
13105 #ifndef sun4v
13106 		tsbmissp->dcache_line_mask = (uint16_t)dcache_line_mask;
13107 #endif /* sun4v */
13108 		tsbmissp->khashstart =
13109 		    (struct hmehash_bucket *)va_to_pa((caddr_t)khme_hash);
13110 		tsbmissp->uhashstart =
13111 		    (struct hmehash_bucket *)va_to_pa((caddr_t)uhme_hash);
13112 		tsbmissp->khashsz = khmehash_num;
13113 		tsbmissp->uhashsz = uhmehash_num;
13114 	}
13115 
13116 	sfmmu_tsb_cb_id = hat_register_callback('T'<<16 | 'S' << 8 | 'B',
13117 	    sfmmu_tsb_pre_relocator, sfmmu_tsb_post_relocator, NULL, 0);
13118 
13119 	if (kpm_enable == 0)
13120 		return;
13121 
13122 	/* -- Begin KPM specific init -- */
13123 
13124 	if (kpm_smallpages) {
13125 		/*
13126 		 * If we're using base pagesize pages for seg_kpm
13127 		 * mappings, we use the kernel TSB since we can't afford
13128 		 * to allocate a second huge TSB for these mappings.
13129 		 */
13130 		kpm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13131 		kpm_tsbsz = ktsb_szcode;
13132 		kpmsm_tsbbase = kpm_tsbbase;
13133 		kpmsm_tsbsz = kpm_tsbsz;
13134 	} else {
13135 		/*
13136 		 * In VAC conflict case, just put the entries in the
13137 		 * kernel 8K indexed TSB for now so we can find them.
13138 		 * This could really be changed in the future if we feel
13139 		 * the need...
13140 		 */
13141 		kpmsm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13142 		kpmsm_tsbsz = ktsb_szcode;
13143 		kpm_tsbbase = ktsb_phys? ktsb4m_pbase : (uint64_t)ktsb4m_base;
13144 		kpm_tsbsz = ktsb4m_szcode;
13145 	}
13146 
13147 	kpmtsbmp = kpmtsbm_area;
13148 	for (i = 0; i < NCPU; kpmtsbmp++, i++) {
13149 		/*
13150 		 * Initialize the kpmtsbm area.
13151 		 * Do this for all possible CPUs as some may be added
13152 		 * while the system is running. There is no cost to this.
13153 		 */
13154 		kpmtsbmp->vbase = kpm_vbase;
13155 		kpmtsbmp->vend = kpm_vbase + kpm_size * vac_colors;
13156 		kpmtsbmp->sz_shift = kpm_size_shift;
13157 		kpmtsbmp->kpmp_shift = kpmp_shift;
13158 		kpmtsbmp->kpmp2pshft = (uchar_t)kpmp2pshft;
13159 		if (kpm_smallpages == 0) {
13160 			kpmtsbmp->kpmp_table_sz = kpmp_table_sz;
13161 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_table);
13162 		} else {
13163 			kpmtsbmp->kpmp_table_sz = kpmp_stable_sz;
13164 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_stable);
13165 		}
13166 		kpmtsbmp->msegphashpa = va_to_pa(memseg_phash);
13167 		kpmtsbmp->flags = KPMTSBM_ENABLE_FLAG;
13168 #ifdef	DEBUG
13169 		kpmtsbmp->flags |= (kpm_tsbmtl) ?  KPMTSBM_TLTSBM_FLAG : 0;
13170 #endif	/* DEBUG */
13171 		if (ktsb_phys)
13172 			kpmtsbmp->flags |= KPMTSBM_TSBPHYS_FLAG;
13173 	}
13174 
13175 	/* -- End KPM specific init -- */
13176 }
13177 
13178 /* Avoid using sfmmu_tsbinfo_alloc() to avoid kmem_alloc - no real reason */
13179 struct tsb_info ktsb_info[2];
13180 
13181 /*
13182  * Called from hat_kern_setup() to setup the tsb_info for ksfmmup.
13183  */
13184 void
13185 sfmmu_init_ktsbinfo()
13186 {
13187 	ASSERT(ksfmmup != NULL);
13188 	ASSERT(ksfmmup->sfmmu_tsb == NULL);
13189 	/*
13190 	 * Allocate tsbinfos for kernel and copy in data
13191 	 * to make debug easier and sun4v setup easier.
13192 	 */
13193 	ktsb_info[0].tsb_sfmmu = ksfmmup;
13194 	ktsb_info[0].tsb_szc = ktsb_szcode;
13195 	ktsb_info[0].tsb_ttesz_mask = TSB8K|TSB64K|TSB512K;
13196 	ktsb_info[0].tsb_va = ktsb_base;
13197 	ktsb_info[0].tsb_pa = ktsb_pbase;
13198 	ktsb_info[0].tsb_flags = 0;
13199 	ktsb_info[0].tsb_tte.ll = 0;
13200 	ktsb_info[0].tsb_cache = NULL;
13201 
13202 	ktsb_info[1].tsb_sfmmu = ksfmmup;
13203 	ktsb_info[1].tsb_szc = ktsb4m_szcode;
13204 	ktsb_info[1].tsb_ttesz_mask = TSB4M;
13205 	ktsb_info[1].tsb_va = ktsb4m_base;
13206 	ktsb_info[1].tsb_pa = ktsb4m_pbase;
13207 	ktsb_info[1].tsb_flags = 0;
13208 	ktsb_info[1].tsb_tte.ll = 0;
13209 	ktsb_info[1].tsb_cache = NULL;
13210 
13211 	/* Link them into ksfmmup. */
13212 	ktsb_info[0].tsb_next = &ktsb_info[1];
13213 	ktsb_info[1].tsb_next = NULL;
13214 	ksfmmup->sfmmu_tsb = &ktsb_info[0];
13215 
13216 	sfmmu_setup_tsbinfo(ksfmmup);
13217 }
13218 
13219 /*
13220  * Cache the last value returned from va_to_pa().  If the VA specified
13221  * in the current call to cached_va_to_pa() maps to the same Page (as the
13222  * previous call to cached_va_to_pa()), then compute the PA using
13223  * cached info, else call va_to_pa().
13224  *
13225  * Note: this function is neither MT-safe nor consistent in the presence
13226  * of multiple, interleaved threads.  This function was created to enable
13227  * an optimization used during boot (at a point when there's only one thread
13228  * executing on the "boot CPU", and before startup_vm() has been called).
13229  */
13230 static uint64_t
13231 cached_va_to_pa(void *vaddr)
13232 {
13233 	static uint64_t prev_vaddr_base = 0;
13234 	static uint64_t prev_pfn = 0;
13235 
13236 	if ((((uint64_t)vaddr) & MMU_PAGEMASK) == prev_vaddr_base) {
13237 		return (prev_pfn | ((uint64_t)vaddr & MMU_PAGEOFFSET));
13238 	} else {
13239 		uint64_t pa = va_to_pa(vaddr);
13240 
13241 		if (pa != ((uint64_t)-1)) {
13242 			/*
13243 			 * Computed physical address is valid.  Cache its
13244 			 * related info for the next cached_va_to_pa() call.
13245 			 */
13246 			prev_pfn = pa & MMU_PAGEMASK;
13247 			prev_vaddr_base = ((uint64_t)vaddr) & MMU_PAGEMASK;
13248 		}
13249 
13250 		return (pa);
13251 	}
13252 }
13253 
13254 /*
13255  * Carve up our nucleus hblk region.  We may allocate more hblks than
13256  * asked due to rounding errors but we are guaranteed to have at least
13257  * enough space to allocate the requested number of hblk8's and hblk1's.
13258  */
13259 void
13260 sfmmu_init_nucleus_hblks(caddr_t addr, size_t size, int nhblk8, int nhblk1)
13261 {
13262 	struct hme_blk *hmeblkp;
13263 	size_t hme8blk_sz, hme1blk_sz;
13264 	size_t i;
13265 	size_t hblk8_bound;
13266 	ulong_t j = 0, k = 0;
13267 
13268 	ASSERT(addr != NULL && size != 0);
13269 
13270 	/* Need to use proper structure alignment */
13271 	hme8blk_sz = roundup(HME8BLK_SZ, sizeof (int64_t));
13272 	hme1blk_sz = roundup(HME1BLK_SZ, sizeof (int64_t));
13273 
13274 	nucleus_hblk8.list = (void *)addr;
13275 	nucleus_hblk8.index = 0;
13276 
13277 	/*
13278 	 * Use as much memory as possible for hblk8's since we
13279 	 * expect all bop_alloc'ed memory to be allocated in 8k chunks.
13280 	 * We need to hold back enough space for the hblk1's which
13281 	 * we'll allocate next.
13282 	 */
13283 	hblk8_bound = size - (nhblk1 * hme1blk_sz) - hme8blk_sz;
13284 	for (i = 0; i <= hblk8_bound; i += hme8blk_sz, j++) {
13285 		hmeblkp = (struct hme_blk *)addr;
13286 		addr += hme8blk_sz;
13287 		hmeblkp->hblk_nuc_bit = 1;
13288 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13289 	}
13290 	nucleus_hblk8.len = j;
13291 	ASSERT(j >= nhblk8);
13292 	SFMMU_STAT_ADD(sf_hblk8_ncreate, j);
13293 
13294 	nucleus_hblk1.list = (void *)addr;
13295 	nucleus_hblk1.index = 0;
13296 	for (; i <= (size - hme1blk_sz); i += hme1blk_sz, k++) {
13297 		hmeblkp = (struct hme_blk *)addr;
13298 		addr += hme1blk_sz;
13299 		hmeblkp->hblk_nuc_bit = 1;
13300 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13301 	}
13302 	ASSERT(k >= nhblk1);
13303 	nucleus_hblk1.len = k;
13304 	SFMMU_STAT_ADD(sf_hblk1_ncreate, k);
13305 }
13306 
13307 /*
13308  * This function is currently not supported on this platform. For what
13309  * it's supposed to do, see hat.c and hat_srmmu.c
13310  */
13311 /* ARGSUSED */
13312 faultcode_t
13313 hat_softlock(struct hat *hat, caddr_t addr, size_t *lenp, page_t **ppp,
13314     uint_t flags)
13315 {
13316 	ASSERT(hat->sfmmu_xhat_provider == NULL);
13317 	return (FC_NOSUPPORT);
13318 }
13319 
13320 /*
13321  * Searchs the mapping list of the page for a mapping of the same size. If not
13322  * found the corresponding bit is cleared in the p_index field. When large
13323  * pages are more prevalent in the system, we can maintain the mapping list
13324  * in order and we don't have to traverse the list each time. Just check the
13325  * next and prev entries, and if both are of different size, we clear the bit.
13326  */
13327 static void
13328 sfmmu_rm_large_mappings(page_t *pp, int ttesz)
13329 {
13330 	struct sf_hment *sfhmep;
13331 	struct hme_blk *hmeblkp;
13332 	int	index;
13333 	pgcnt_t	npgs;
13334 
13335 	ASSERT(ttesz > TTE8K);
13336 
13337 	ASSERT(sfmmu_mlist_held(pp));
13338 
13339 	ASSERT(PP_ISMAPPED_LARGE(pp));
13340 
13341 	/*
13342 	 * Traverse mapping list looking for another mapping of same size.
13343 	 * since we only want to clear index field if all mappings of
13344 	 * that size are gone.
13345 	 */
13346 
13347 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
13348 		if (IS_PAHME(sfhmep))
13349 			continue;
13350 		hmeblkp = sfmmu_hmetohblk(sfhmep);
13351 		if (hmeblkp->hblk_xhat_bit)
13352 			continue;
13353 		if (hme_size(sfhmep) == ttesz) {
13354 			/*
13355 			 * another mapping of the same size. don't clear index.
13356 			 */
13357 			return;
13358 		}
13359 	}
13360 
13361 	/*
13362 	 * Clear the p_index bit for large page.
13363 	 */
13364 	index = PAGESZ_TO_INDEX(ttesz);
13365 	npgs = TTEPAGES(ttesz);
13366 	while (npgs-- > 0) {
13367 		ASSERT(pp->p_index & index);
13368 		pp->p_index &= ~index;
13369 		pp = PP_PAGENEXT(pp);
13370 	}
13371 }
13372 
13373 /*
13374  * return supported features
13375  */
13376 /* ARGSUSED */
13377 int
13378 hat_supported(enum hat_features feature, void *arg)
13379 {
13380 	switch (feature) {
13381 	case    HAT_SHARED_PT:
13382 	case	HAT_DYNAMIC_ISM_UNMAP:
13383 	case	HAT_VMODSORT:
13384 		return (1);
13385 	case	HAT_SHARED_REGIONS:
13386 		if (shctx_on)
13387 			return (1);
13388 		else
13389 			return (0);
13390 	default:
13391 		return (0);
13392 	}
13393 }
13394 
13395 void
13396 hat_enter(struct hat *hat)
13397 {
13398 	hatlock_t	*hatlockp;
13399 
13400 	if (hat != ksfmmup) {
13401 		hatlockp = TSB_HASH(hat);
13402 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
13403 	}
13404 }
13405 
13406 void
13407 hat_exit(struct hat *hat)
13408 {
13409 	hatlock_t	*hatlockp;
13410 
13411 	if (hat != ksfmmup) {
13412 		hatlockp = TSB_HASH(hat);
13413 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
13414 	}
13415 }
13416 
13417 /*ARGSUSED*/
13418 void
13419 hat_reserve(struct as *as, caddr_t addr, size_t len)
13420 {
13421 }
13422 
13423 static void
13424 hat_kstat_init(void)
13425 {
13426 	kstat_t *ksp;
13427 
13428 	ksp = kstat_create("unix", 0, "sfmmu_global_stat", "hat",
13429 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_global_stat),
13430 	    KSTAT_FLAG_VIRTUAL);
13431 	if (ksp) {
13432 		ksp->ks_data = (void *) &sfmmu_global_stat;
13433 		kstat_install(ksp);
13434 	}
13435 	ksp = kstat_create("unix", 0, "sfmmu_tsbsize_stat", "hat",
13436 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_tsbsize_stat),
13437 	    KSTAT_FLAG_VIRTUAL);
13438 	if (ksp) {
13439 		ksp->ks_data = (void *) &sfmmu_tsbsize_stat;
13440 		kstat_install(ksp);
13441 	}
13442 	ksp = kstat_create("unix", 0, "sfmmu_percpu_stat", "hat",
13443 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_percpu_stat) * NCPU,
13444 	    KSTAT_FLAG_WRITABLE);
13445 	if (ksp) {
13446 		ksp->ks_update = sfmmu_kstat_percpu_update;
13447 		kstat_install(ksp);
13448 	}
13449 }
13450 
13451 /* ARGSUSED */
13452 static int
13453 sfmmu_kstat_percpu_update(kstat_t *ksp, int rw)
13454 {
13455 	struct sfmmu_percpu_stat *cpu_kstat = ksp->ks_data;
13456 	struct tsbmiss *tsbm = tsbmiss_area;
13457 	struct kpmtsbm *kpmtsbm = kpmtsbm_area;
13458 	int i;
13459 
13460 	ASSERT(cpu_kstat);
13461 	if (rw == KSTAT_READ) {
13462 		for (i = 0; i < NCPU; cpu_kstat++, tsbm++, kpmtsbm++, i++) {
13463 			cpu_kstat->sf_itlb_misses = 0;
13464 			cpu_kstat->sf_dtlb_misses = 0;
13465 			cpu_kstat->sf_utsb_misses = tsbm->utsb_misses -
13466 			    tsbm->uprot_traps;
13467 			cpu_kstat->sf_ktsb_misses = tsbm->ktsb_misses +
13468 			    kpmtsbm->kpm_tsb_misses - tsbm->kprot_traps;
13469 			cpu_kstat->sf_tsb_hits = 0;
13470 			cpu_kstat->sf_umod_faults = tsbm->uprot_traps;
13471 			cpu_kstat->sf_kmod_faults = tsbm->kprot_traps;
13472 		}
13473 	} else {
13474 		/* KSTAT_WRITE is used to clear stats */
13475 		for (i = 0; i < NCPU; tsbm++, kpmtsbm++, i++) {
13476 			tsbm->utsb_misses = 0;
13477 			tsbm->ktsb_misses = 0;
13478 			tsbm->uprot_traps = 0;
13479 			tsbm->kprot_traps = 0;
13480 			kpmtsbm->kpm_dtlb_misses = 0;
13481 			kpmtsbm->kpm_tsb_misses = 0;
13482 		}
13483 	}
13484 	return (0);
13485 }
13486 
13487 #ifdef	DEBUG
13488 
13489 tte_t  *gorig[NCPU], *gcur[NCPU], *gnew[NCPU];
13490 
13491 /*
13492  * A tte checker. *orig_old is the value we read before cas.
13493  *	*cur is the value returned by cas.
13494  *	*new is the desired value when we do the cas.
13495  *
13496  *	*hmeblkp is currently unused.
13497  */
13498 
13499 /* ARGSUSED */
13500 void
13501 chk_tte(tte_t *orig_old, tte_t *cur, tte_t *new, struct hme_blk *hmeblkp)
13502 {
13503 	pfn_t i, j, k;
13504 	int cpuid = CPU->cpu_id;
13505 
13506 	gorig[cpuid] = orig_old;
13507 	gcur[cpuid] = cur;
13508 	gnew[cpuid] = new;
13509 
13510 #ifdef lint
13511 	hmeblkp = hmeblkp;
13512 #endif
13513 
13514 	if (TTE_IS_VALID(orig_old)) {
13515 		if (TTE_IS_VALID(cur)) {
13516 			i = TTE_TO_TTEPFN(orig_old);
13517 			j = TTE_TO_TTEPFN(cur);
13518 			k = TTE_TO_TTEPFN(new);
13519 			if (i != j) {
13520 				/* remap error? */
13521 				panic("chk_tte: bad pfn, 0x%lx, 0x%lx", i, j);
13522 			}
13523 
13524 			if (i != k) {
13525 				/* remap error? */
13526 				panic("chk_tte: bad pfn2, 0x%lx, 0x%lx", i, k);
13527 			}
13528 		} else {
13529 			if (TTE_IS_VALID(new)) {
13530 				panic("chk_tte: invalid cur? ");
13531 			}
13532 
13533 			i = TTE_TO_TTEPFN(orig_old);
13534 			k = TTE_TO_TTEPFN(new);
13535 			if (i != k) {
13536 				panic("chk_tte: bad pfn3, 0x%lx, 0x%lx", i, k);
13537 			}
13538 		}
13539 	} else {
13540 		if (TTE_IS_VALID(cur)) {
13541 			j = TTE_TO_TTEPFN(cur);
13542 			if (TTE_IS_VALID(new)) {
13543 				k = TTE_TO_TTEPFN(new);
13544 				if (j != k) {
13545 					panic("chk_tte: bad pfn4, 0x%lx, 0x%lx",
13546 					    j, k);
13547 				}
13548 			} else {
13549 				panic("chk_tte: why here?");
13550 			}
13551 		} else {
13552 			if (!TTE_IS_VALID(new)) {
13553 				panic("chk_tte: why here2 ?");
13554 			}
13555 		}
13556 	}
13557 }
13558 
13559 #endif /* DEBUG */
13560 
13561 extern void prefetch_tsbe_read(struct tsbe *);
13562 extern void prefetch_tsbe_write(struct tsbe *);
13563 
13564 
13565 /*
13566  * We want to prefetch 7 cache lines ahead for our read prefetch.  This gives
13567  * us optimal performance on Cheetah+.  You can only have 8 outstanding
13568  * prefetches at any one time, so we opted for 7 read prefetches and 1 write
13569  * prefetch to make the most utilization of the prefetch capability.
13570  */
13571 #define	TSBE_PREFETCH_STRIDE (7)
13572 
13573 void
13574 sfmmu_copy_tsb(struct tsb_info *old_tsbinfo, struct tsb_info *new_tsbinfo)
13575 {
13576 	int old_bytes = TSB_BYTES(old_tsbinfo->tsb_szc);
13577 	int new_bytes = TSB_BYTES(new_tsbinfo->tsb_szc);
13578 	int old_entries = TSB_ENTRIES(old_tsbinfo->tsb_szc);
13579 	int new_entries = TSB_ENTRIES(new_tsbinfo->tsb_szc);
13580 	struct tsbe *old;
13581 	struct tsbe *new;
13582 	struct tsbe *new_base = (struct tsbe *)new_tsbinfo->tsb_va;
13583 	uint64_t va;
13584 	int new_offset;
13585 	int i;
13586 	int vpshift;
13587 	int last_prefetch;
13588 
13589 	if (old_bytes == new_bytes) {
13590 		bcopy(old_tsbinfo->tsb_va, new_tsbinfo->tsb_va, new_bytes);
13591 	} else {
13592 
13593 		/*
13594 		 * A TSBE is 16 bytes which means there are four TSBE's per
13595 		 * P$ line (64 bytes), thus every 4 TSBE's we prefetch.
13596 		 */
13597 		old = (struct tsbe *)old_tsbinfo->tsb_va;
13598 		last_prefetch = old_entries - (4*(TSBE_PREFETCH_STRIDE+1));
13599 		for (i = 0; i < old_entries; i++, old++) {
13600 			if (((i & (4-1)) == 0) && (i < last_prefetch))
13601 				prefetch_tsbe_read(old);
13602 			if (!old->tte_tag.tag_invalid) {
13603 				/*
13604 				 * We have a valid TTE to remap.  Check the
13605 				 * size.  We won't remap 64K or 512K TTEs
13606 				 * because they span more than one TSB entry
13607 				 * and are indexed using an 8K virt. page.
13608 				 * Ditto for 32M and 256M TTEs.
13609 				 */
13610 				if (TTE_CSZ(&old->tte_data) == TTE64K ||
13611 				    TTE_CSZ(&old->tte_data) == TTE512K)
13612 					continue;
13613 				if (mmu_page_sizes == max_mmu_page_sizes) {
13614 					if (TTE_CSZ(&old->tte_data) == TTE32M ||
13615 					    TTE_CSZ(&old->tte_data) == TTE256M)
13616 						continue;
13617 				}
13618 
13619 				/* clear the lower 22 bits of the va */
13620 				va = *(uint64_t *)old << 22;
13621 				/* turn va into a virtual pfn */
13622 				va >>= 22 - TSB_START_SIZE;
13623 				/*
13624 				 * or in bits from the offset in the tsb
13625 				 * to get the real virtual pfn. These
13626 				 * correspond to bits [21:13] in the va
13627 				 */
13628 				vpshift =
13629 				    TTE_BSZS_SHIFT(TTE_CSZ(&old->tte_data)) &
13630 				    0x1ff;
13631 				va |= (i << vpshift);
13632 				va >>= vpshift;
13633 				new_offset = va & (new_entries - 1);
13634 				new = new_base + new_offset;
13635 				prefetch_tsbe_write(new);
13636 				*new = *old;
13637 			}
13638 		}
13639 	}
13640 }
13641 
13642 /*
13643  * unused in sfmmu
13644  */
13645 void
13646 hat_dump(void)
13647 {
13648 }
13649 
13650 /*
13651  * Called when a thread is exiting and we have switched to the kernel address
13652  * space.  Perform the same VM initialization resume() uses when switching
13653  * processes.
13654  *
13655  * Note that sfmmu_load_mmustate() is currently a no-op for kernel threads, but
13656  * we call it anyway in case the semantics change in the future.
13657  */
13658 /*ARGSUSED*/
13659 void
13660 hat_thread_exit(kthread_t *thd)
13661 {
13662 	uint_t pgsz_cnum;
13663 	uint_t pstate_save;
13664 
13665 	ASSERT(thd->t_procp->p_as == &kas);
13666 
13667 	pgsz_cnum = KCONTEXT;
13668 #ifdef sun4u
13669 	pgsz_cnum |= (ksfmmup->sfmmu_cext << CTXREG_EXT_SHIFT);
13670 #endif
13671 
13672 	/*
13673 	 * Note that sfmmu_load_mmustate() is currently a no-op for
13674 	 * kernel threads. We need to disable interrupts here,
13675 	 * simply because otherwise sfmmu_load_mmustate() would panic
13676 	 * if the caller does not disable interrupts.
13677 	 */
13678 	pstate_save = sfmmu_disable_intrs();
13679 
13680 	/* Compatibility Note: hw takes care of MMU_SCONTEXT1 */
13681 	sfmmu_setctx_sec(pgsz_cnum);
13682 	sfmmu_load_mmustate(ksfmmup);
13683 	sfmmu_enable_intrs(pstate_save);
13684 }
13685 
13686 
13687 /*
13688  * SRD support
13689  */
13690 #define	SRD_HASH_FUNCTION(vp)	(((((uintptr_t)(vp)) >> 4) ^ \
13691 				    (((uintptr_t)(vp)) >> 11)) & \
13692 				    srd_hashmask)
13693 
13694 /*
13695  * Attach the process to the srd struct associated with the exec vnode
13696  * from which the process is started.
13697  */
13698 void
13699 hat_join_srd(struct hat *sfmmup, vnode_t *evp)
13700 {
13701 	uint_t hash = SRD_HASH_FUNCTION(evp);
13702 	sf_srd_t *srdp;
13703 	sf_srd_t *newsrdp;
13704 
13705 	ASSERT(sfmmup != ksfmmup);
13706 	ASSERT(sfmmup->sfmmu_srdp == NULL);
13707 
13708 	if (!shctx_on) {
13709 		return;
13710 	}
13711 
13712 	VN_HOLD(evp);
13713 
13714 	if (srd_buckets[hash].srdb_srdp != NULL) {
13715 		mutex_enter(&srd_buckets[hash].srdb_lock);
13716 		for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13717 		    srdp = srdp->srd_hash) {
13718 			if (srdp->srd_evp == evp) {
13719 				ASSERT(srdp->srd_refcnt >= 0);
13720 				sfmmup->sfmmu_srdp = srdp;
13721 				atomic_add_32(
13722 				    (volatile uint_t *)&srdp->srd_refcnt, 1);
13723 				mutex_exit(&srd_buckets[hash].srdb_lock);
13724 				return;
13725 			}
13726 		}
13727 		mutex_exit(&srd_buckets[hash].srdb_lock);
13728 	}
13729 	newsrdp = kmem_cache_alloc(srd_cache, KM_SLEEP);
13730 	ASSERT(newsrdp->srd_next_ismrid == 0 && newsrdp->srd_next_hmerid == 0);
13731 
13732 	newsrdp->srd_evp = evp;
13733 	newsrdp->srd_refcnt = 1;
13734 	newsrdp->srd_hmergnfree = NULL;
13735 	newsrdp->srd_ismrgnfree = NULL;
13736 
13737 	mutex_enter(&srd_buckets[hash].srdb_lock);
13738 	for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13739 	    srdp = srdp->srd_hash) {
13740 		if (srdp->srd_evp == evp) {
13741 			ASSERT(srdp->srd_refcnt >= 0);
13742 			sfmmup->sfmmu_srdp = srdp;
13743 			atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
13744 			mutex_exit(&srd_buckets[hash].srdb_lock);
13745 			kmem_cache_free(srd_cache, newsrdp);
13746 			return;
13747 		}
13748 	}
13749 	newsrdp->srd_hash = srd_buckets[hash].srdb_srdp;
13750 	srd_buckets[hash].srdb_srdp = newsrdp;
13751 	sfmmup->sfmmu_srdp = newsrdp;
13752 
13753 	mutex_exit(&srd_buckets[hash].srdb_lock);
13754 
13755 }
13756 
13757 static void
13758 sfmmu_leave_srd(sfmmu_t *sfmmup)
13759 {
13760 	vnode_t *evp;
13761 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13762 	uint_t hash;
13763 	sf_srd_t **prev_srdpp;
13764 	sf_region_t *rgnp;
13765 	sf_region_t *nrgnp;
13766 #ifdef DEBUG
13767 	int rgns = 0;
13768 #endif
13769 	int i;
13770 
13771 	ASSERT(sfmmup != ksfmmup);
13772 	ASSERT(srdp != NULL);
13773 	ASSERT(srdp->srd_refcnt > 0);
13774 	ASSERT(sfmmup->sfmmu_scdp == NULL);
13775 	ASSERT(sfmmup->sfmmu_free == 1);
13776 
13777 	sfmmup->sfmmu_srdp = NULL;
13778 	evp = srdp->srd_evp;
13779 	ASSERT(evp != NULL);
13780 	if (atomic_add_32_nv(
13781 	    (volatile uint_t *)&srdp->srd_refcnt, -1)) {
13782 		VN_RELE(evp);
13783 		return;
13784 	}
13785 
13786 	hash = SRD_HASH_FUNCTION(evp);
13787 	mutex_enter(&srd_buckets[hash].srdb_lock);
13788 	for (prev_srdpp = &srd_buckets[hash].srdb_srdp;
13789 	    (srdp = *prev_srdpp) != NULL; prev_srdpp = &srdp->srd_hash) {
13790 		if (srdp->srd_evp == evp) {
13791 			break;
13792 		}
13793 	}
13794 	if (srdp == NULL || srdp->srd_refcnt) {
13795 		mutex_exit(&srd_buckets[hash].srdb_lock);
13796 		VN_RELE(evp);
13797 		return;
13798 	}
13799 	*prev_srdpp = srdp->srd_hash;
13800 	mutex_exit(&srd_buckets[hash].srdb_lock);
13801 
13802 	ASSERT(srdp->srd_refcnt == 0);
13803 	VN_RELE(evp);
13804 
13805 #ifdef DEBUG
13806 	for (i = 0; i < SFMMU_MAX_REGION_BUCKETS; i++) {
13807 		ASSERT(srdp->srd_rgnhash[i] == NULL);
13808 	}
13809 #endif /* DEBUG */
13810 
13811 	/* free each hme regions in the srd */
13812 	for (rgnp = srdp->srd_hmergnfree; rgnp != NULL; rgnp = nrgnp) {
13813 		nrgnp = rgnp->rgn_next;
13814 		ASSERT(rgnp->rgn_id < srdp->srd_next_hmerid);
13815 		ASSERT(rgnp->rgn_refcnt == 0);
13816 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13817 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13818 		ASSERT(rgnp->rgn_hmeflags == 0);
13819 		ASSERT(srdp->srd_hmergnp[rgnp->rgn_id] == rgnp);
13820 #ifdef DEBUG
13821 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13822 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13823 		}
13824 		rgns++;
13825 #endif /* DEBUG */
13826 		kmem_cache_free(region_cache, rgnp);
13827 	}
13828 	ASSERT(rgns == srdp->srd_next_hmerid);
13829 
13830 #ifdef DEBUG
13831 	rgns = 0;
13832 #endif
13833 	/* free each ism rgns in the srd */
13834 	for (rgnp = srdp->srd_ismrgnfree; rgnp != NULL; rgnp = nrgnp) {
13835 		nrgnp = rgnp->rgn_next;
13836 		ASSERT(rgnp->rgn_id < srdp->srd_next_ismrid);
13837 		ASSERT(rgnp->rgn_refcnt == 0);
13838 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13839 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13840 		ASSERT(srdp->srd_ismrgnp[rgnp->rgn_id] == rgnp);
13841 #ifdef DEBUG
13842 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13843 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13844 		}
13845 		rgns++;
13846 #endif /* DEBUG */
13847 		kmem_cache_free(region_cache, rgnp);
13848 	}
13849 	ASSERT(rgns == srdp->srd_next_ismrid);
13850 	ASSERT(srdp->srd_ismbusyrgns == 0);
13851 	ASSERT(srdp->srd_hmebusyrgns == 0);
13852 
13853 	srdp->srd_next_ismrid = 0;
13854 	srdp->srd_next_hmerid = 0;
13855 
13856 	bzero((void *)srdp->srd_ismrgnp,
13857 	    sizeof (sf_region_t *) * SFMMU_MAX_ISM_REGIONS);
13858 	bzero((void *)srdp->srd_hmergnp,
13859 	    sizeof (sf_region_t *) * SFMMU_MAX_HME_REGIONS);
13860 
13861 	ASSERT(srdp->srd_scdp == NULL);
13862 	kmem_cache_free(srd_cache, srdp);
13863 }
13864 
13865 /* ARGSUSED */
13866 static int
13867 sfmmu_srdcache_constructor(void *buf, void *cdrarg, int kmflags)
13868 {
13869 	sf_srd_t *srdp = (sf_srd_t *)buf;
13870 	bzero(buf, sizeof (*srdp));
13871 
13872 	mutex_init(&srdp->srd_mutex, NULL, MUTEX_DEFAULT, NULL);
13873 	mutex_init(&srdp->srd_scd_mutex, NULL, MUTEX_DEFAULT, NULL);
13874 	return (0);
13875 }
13876 
13877 /* ARGSUSED */
13878 static void
13879 sfmmu_srdcache_destructor(void *buf, void *cdrarg)
13880 {
13881 	sf_srd_t *srdp = (sf_srd_t *)buf;
13882 
13883 	mutex_destroy(&srdp->srd_mutex);
13884 	mutex_destroy(&srdp->srd_scd_mutex);
13885 }
13886 
13887 /*
13888  * The caller makes sure hat_join_region()/hat_leave_region() can't be called
13889  * at the same time for the same process and address range. This is ensured by
13890  * the fact that address space is locked as writer when a process joins the
13891  * regions. Therefore there's no need to hold an srd lock during the entire
13892  * execution of hat_join_region()/hat_leave_region().
13893  */
13894 
13895 #define	RGN_HASH_FUNCTION(obj)	(((((uintptr_t)(obj)) >> 4) ^ \
13896 				    (((uintptr_t)(obj)) >> 11)) & \
13897 					srd_rgn_hashmask)
13898 /*
13899  * This routine implements the shared context functionality required when
13900  * attaching a segment to an address space. It must be called from
13901  * hat_share() for D(ISM) segments and from segvn_create() for segments
13902  * with the MAP_PRIVATE and MAP_TEXT flags set. It returns a region_cookie
13903  * which is saved in the private segment data for hme segments and
13904  * the ism_map structure for ism segments.
13905  */
13906 hat_region_cookie_t
13907 hat_join_region(struct hat *sfmmup,
13908 	caddr_t r_saddr,
13909 	size_t r_size,
13910 	void *r_obj,
13911 	u_offset_t r_objoff,
13912 	uchar_t r_perm,
13913 	uchar_t r_pgszc,
13914 	hat_rgn_cb_func_t r_cb_function,
13915 	uint_t flags)
13916 {
13917 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13918 	uint_t rhash;
13919 	uint_t rid;
13920 	hatlock_t *hatlockp;
13921 	sf_region_t *rgnp;
13922 	sf_region_t *new_rgnp = NULL;
13923 	int i;
13924 	uint16_t *nextidp;
13925 	sf_region_t **freelistp;
13926 	int maxids;
13927 	sf_region_t **rarrp;
13928 	uint16_t *busyrgnsp;
13929 	ulong_t rttecnt;
13930 	uchar_t tteflag;
13931 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
13932 	int text = (r_type == HAT_REGION_TEXT);
13933 
13934 	if (srdp == NULL || r_size == 0) {
13935 		return (HAT_INVALID_REGION_COOKIE);
13936 	}
13937 
13938 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
13939 	ASSERT(sfmmup != ksfmmup);
13940 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
13941 	ASSERT(srdp->srd_refcnt > 0);
13942 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
13943 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
13944 	ASSERT(r_pgszc < mmu_page_sizes);
13945 	if (!IS_P2ALIGNED(r_saddr, TTEBYTES(r_pgszc)) ||
13946 	    !IS_P2ALIGNED(r_size, TTEBYTES(r_pgszc))) {
13947 		panic("hat_join_region: region addr or size is not aligned\n");
13948 	}
13949 
13950 
13951 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
13952 	    SFMMU_REGION_HME;
13953 	/*
13954 	 * Currently only support shared hmes for the read only main text
13955 	 * region.
13956 	 */
13957 	if (r_type == SFMMU_REGION_HME && ((r_obj != srdp->srd_evp) ||
13958 	    (r_perm & PROT_WRITE))) {
13959 		return (HAT_INVALID_REGION_COOKIE);
13960 	}
13961 
13962 	rhash = RGN_HASH_FUNCTION(r_obj);
13963 
13964 	if (r_type == SFMMU_REGION_ISM) {
13965 		nextidp = &srdp->srd_next_ismrid;
13966 		freelistp = &srdp->srd_ismrgnfree;
13967 		maxids = SFMMU_MAX_ISM_REGIONS;
13968 		rarrp = srdp->srd_ismrgnp;
13969 		busyrgnsp = &srdp->srd_ismbusyrgns;
13970 	} else {
13971 		nextidp = &srdp->srd_next_hmerid;
13972 		freelistp = &srdp->srd_hmergnfree;
13973 		maxids = SFMMU_MAX_HME_REGIONS;
13974 		rarrp = srdp->srd_hmergnp;
13975 		busyrgnsp = &srdp->srd_hmebusyrgns;
13976 	}
13977 
13978 	mutex_enter(&srdp->srd_mutex);
13979 
13980 	for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
13981 	    rgnp = rgnp->rgn_hash) {
13982 		if (rgnp->rgn_saddr == r_saddr && rgnp->rgn_size == r_size &&
13983 		    rgnp->rgn_obj == r_obj && rgnp->rgn_objoff == r_objoff &&
13984 		    rgnp->rgn_perm == r_perm && rgnp->rgn_pgszc == r_pgszc) {
13985 			break;
13986 		}
13987 	}
13988 
13989 rfound:
13990 	if (rgnp != NULL) {
13991 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
13992 		ASSERT(rgnp->rgn_cb_function == r_cb_function);
13993 		ASSERT(rgnp->rgn_refcnt >= 0);
13994 		rid = rgnp->rgn_id;
13995 		ASSERT(rid < maxids);
13996 		ASSERT(rarrp[rid] == rgnp);
13997 		ASSERT(rid < *nextidp);
13998 		atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
13999 		mutex_exit(&srdp->srd_mutex);
14000 		if (new_rgnp != NULL) {
14001 			kmem_cache_free(region_cache, new_rgnp);
14002 		}
14003 		if (r_type == SFMMU_REGION_HME) {
14004 			int myjoin =
14005 			    (sfmmup == astosfmmu(curthread->t_procp->p_as));
14006 
14007 			sfmmu_link_to_hmeregion(sfmmup, rgnp);
14008 			/*
14009 			 * bitmap should be updated after linking sfmmu on
14010 			 * region list so that pageunload() doesn't skip
14011 			 * TSB/TLB flush. As soon as bitmap is updated another
14012 			 * thread in this process can already start accessing
14013 			 * this region.
14014 			 */
14015 			/*
14016 			 * Normally ttecnt accounting is done as part of
14017 			 * pagefault handling. But a process may not take any
14018 			 * pagefaults on shared hmeblks created by some other
14019 			 * process. To compensate for this assume that the
14020 			 * entire region will end up faulted in using
14021 			 * the region's pagesize.
14022 			 *
14023 			 */
14024 			if (r_pgszc > TTE8K) {
14025 				tteflag = 1 << r_pgszc;
14026 				if (disable_large_pages & tteflag) {
14027 					tteflag = 0;
14028 				}
14029 			} else {
14030 				tteflag = 0;
14031 			}
14032 			if (tteflag && !(sfmmup->sfmmu_rtteflags & tteflag)) {
14033 				hatlockp = sfmmu_hat_enter(sfmmup);
14034 				sfmmup->sfmmu_rtteflags |= tteflag;
14035 				sfmmu_hat_exit(hatlockp);
14036 			}
14037 			hatlockp = sfmmu_hat_enter(sfmmup);
14038 
14039 			/*
14040 			 * Preallocate 1/4 of ttecnt's in 8K TSB for >= 4M
14041 			 * region to allow for large page allocation failure.
14042 			 */
14043 			if (r_pgszc >= TTE4M) {
14044 				sfmmup->sfmmu_tsb0_4minflcnt +=
14045 				    r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14046 			}
14047 
14048 			/* update sfmmu_ttecnt with the shme rgn ttecnt */
14049 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14050 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14051 			    rttecnt);
14052 
14053 			if (text && r_pgszc >= TTE4M &&
14054 			    (tteflag || ((disable_large_pages >> TTE4M) &
14055 			    ((1 << (r_pgszc - TTE4M + 1)) - 1))) &&
14056 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
14057 				SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
14058 			}
14059 
14060 			sfmmu_hat_exit(hatlockp);
14061 			/*
14062 			 * On Panther we need to make sure TLB is programmed
14063 			 * to accept 32M/256M pages.  Call
14064 			 * sfmmu_check_page_sizes() now to make sure TLB is
14065 			 * setup before making hmeregions visible to other
14066 			 * threads.
14067 			 */
14068 			sfmmu_check_page_sizes(sfmmup, 1);
14069 			hatlockp = sfmmu_hat_enter(sfmmup);
14070 			SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14071 
14072 			/*
14073 			 * if context is invalid tsb miss exception code will
14074 			 * call sfmmu_check_page_sizes() and update tsbmiss
14075 			 * area later.
14076 			 */
14077 			kpreempt_disable();
14078 			if (myjoin &&
14079 			    (sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
14080 			    != INVALID_CONTEXT)) {
14081 				struct tsbmiss *tsbmp;
14082 
14083 				tsbmp = &tsbmiss_area[CPU->cpu_id];
14084 				ASSERT(sfmmup == tsbmp->usfmmup);
14085 				BT_SET(tsbmp->shmermap, rid);
14086 				if (r_pgszc > TTE64K) {
14087 					tsbmp->uhat_rtteflags |= tteflag;
14088 				}
14089 
14090 			}
14091 			kpreempt_enable();
14092 
14093 			sfmmu_hat_exit(hatlockp);
14094 			ASSERT((hat_region_cookie_t)((uint64_t)rid) !=
14095 			    HAT_INVALID_REGION_COOKIE);
14096 		} else {
14097 			hatlockp = sfmmu_hat_enter(sfmmup);
14098 			SF_RGNMAP_ADD(sfmmup->sfmmu_ismregion_map, rid);
14099 			sfmmu_hat_exit(hatlockp);
14100 		}
14101 		ASSERT(rid < maxids);
14102 
14103 		if (r_type == SFMMU_REGION_ISM) {
14104 			sfmmu_find_scd(sfmmup);
14105 		}
14106 		return ((hat_region_cookie_t)((uint64_t)rid));
14107 	}
14108 
14109 	ASSERT(new_rgnp == NULL);
14110 
14111 	if (*busyrgnsp >= maxids) {
14112 		mutex_exit(&srdp->srd_mutex);
14113 		return (HAT_INVALID_REGION_COOKIE);
14114 	}
14115 
14116 	ASSERT(MUTEX_HELD(&srdp->srd_mutex));
14117 	if (*freelistp != NULL) {
14118 		rgnp = *freelistp;
14119 		*freelistp = rgnp->rgn_next;
14120 		ASSERT(rgnp->rgn_id < *nextidp);
14121 		ASSERT(rgnp->rgn_id < maxids);
14122 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
14123 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK)
14124 		    == r_type);
14125 		ASSERT(rarrp[rgnp->rgn_id] == rgnp);
14126 		ASSERT(rgnp->rgn_hmeflags == 0);
14127 	} else {
14128 		/*
14129 		 * release local locks before memory allocation.
14130 		 */
14131 		mutex_exit(&srdp->srd_mutex);
14132 
14133 		new_rgnp = kmem_cache_alloc(region_cache, KM_SLEEP);
14134 
14135 		mutex_enter(&srdp->srd_mutex);
14136 		for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
14137 		    rgnp = rgnp->rgn_hash) {
14138 			if (rgnp->rgn_saddr == r_saddr &&
14139 			    rgnp->rgn_size == r_size &&
14140 			    rgnp->rgn_obj == r_obj &&
14141 			    rgnp->rgn_objoff == r_objoff &&
14142 			    rgnp->rgn_perm == r_perm &&
14143 			    rgnp->rgn_pgszc == r_pgszc) {
14144 				break;
14145 			}
14146 		}
14147 		if (rgnp != NULL) {
14148 			goto rfound;
14149 		}
14150 
14151 		if (*nextidp >= maxids) {
14152 			mutex_exit(&srdp->srd_mutex);
14153 			goto fail;
14154 		}
14155 		rgnp = new_rgnp;
14156 		new_rgnp = NULL;
14157 		rgnp->rgn_id = (*nextidp)++;
14158 		ASSERT(rgnp->rgn_id < maxids);
14159 		ASSERT(rarrp[rgnp->rgn_id] == NULL);
14160 		rarrp[rgnp->rgn_id] = rgnp;
14161 	}
14162 
14163 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14164 	ASSERT(rgnp->rgn_hmeflags == 0);
14165 #ifdef DEBUG
14166 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14167 		ASSERT(rgnp->rgn_ttecnt[i] == 0);
14168 	}
14169 #endif
14170 	rgnp->rgn_saddr = r_saddr;
14171 	rgnp->rgn_size = r_size;
14172 	rgnp->rgn_obj = r_obj;
14173 	rgnp->rgn_objoff = r_objoff;
14174 	rgnp->rgn_perm = r_perm;
14175 	rgnp->rgn_pgszc = r_pgszc;
14176 	rgnp->rgn_flags = r_type;
14177 	rgnp->rgn_refcnt = 0;
14178 	rgnp->rgn_cb_function = r_cb_function;
14179 	rgnp->rgn_hash = srdp->srd_rgnhash[rhash];
14180 	srdp->srd_rgnhash[rhash] = rgnp;
14181 	(*busyrgnsp)++;
14182 	ASSERT(*busyrgnsp <= maxids);
14183 	goto rfound;
14184 
14185 fail:
14186 	ASSERT(new_rgnp != NULL);
14187 	kmem_cache_free(region_cache, new_rgnp);
14188 	return (HAT_INVALID_REGION_COOKIE);
14189 }
14190 
14191 /*
14192  * This function implements the shared context functionality required
14193  * when detaching a segment from an address space. It must be called
14194  * from hat_unshare() for all D(ISM) segments and from segvn_unmap(),
14195  * for segments with a valid region_cookie.
14196  * It will also be called from all seg_vn routines which change a
14197  * segment's attributes such as segvn_setprot(), segvn_setpagesize(),
14198  * segvn_clrszc() & segvn_advise(), as well as in the case of COW fault
14199  * from segvn_fault().
14200  */
14201 void
14202 hat_leave_region(struct hat *sfmmup, hat_region_cookie_t rcookie, uint_t flags)
14203 {
14204 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14205 	sf_scd_t *scdp;
14206 	uint_t rhash;
14207 	uint_t rid = (uint_t)((uint64_t)rcookie);
14208 	hatlock_t *hatlockp = NULL;
14209 	sf_region_t *rgnp;
14210 	sf_region_t **prev_rgnpp;
14211 	sf_region_t *cur_rgnp;
14212 	void *r_obj;
14213 	int i;
14214 	caddr_t	r_saddr;
14215 	caddr_t r_eaddr;
14216 	size_t	r_size;
14217 	uchar_t	r_pgszc;
14218 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
14219 
14220 	ASSERT(sfmmup != ksfmmup);
14221 	ASSERT(srdp != NULL);
14222 	ASSERT(srdp->srd_refcnt > 0);
14223 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
14224 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
14225 	ASSERT(!sfmmup->sfmmu_free || sfmmup->sfmmu_scdp == NULL);
14226 
14227 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
14228 	    SFMMU_REGION_HME;
14229 
14230 	if (r_type == SFMMU_REGION_ISM) {
14231 		ASSERT(SFMMU_IS_ISMRID_VALID(rid));
14232 		ASSERT(rid < SFMMU_MAX_ISM_REGIONS);
14233 		rgnp = srdp->srd_ismrgnp[rid];
14234 	} else {
14235 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14236 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14237 		rgnp = srdp->srd_hmergnp[rid];
14238 	}
14239 	ASSERT(rgnp != NULL);
14240 	ASSERT(rgnp->rgn_id == rid);
14241 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14242 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14243 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
14244 
14245 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
14246 	if (r_type == SFMMU_REGION_HME && sfmmup->sfmmu_as->a_xhat != NULL) {
14247 		xhat_unload_callback_all(sfmmup->sfmmu_as, rgnp->rgn_saddr,
14248 		    rgnp->rgn_size, 0, NULL);
14249 	}
14250 
14251 	if (sfmmup->sfmmu_free) {
14252 		ulong_t rttecnt;
14253 		r_pgszc = rgnp->rgn_pgszc;
14254 		r_size = rgnp->rgn_size;
14255 
14256 		ASSERT(sfmmup->sfmmu_scdp == NULL);
14257 		if (r_type == SFMMU_REGION_ISM) {
14258 			SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14259 		} else {
14260 			/* update shme rgns ttecnt in sfmmu_ttecnt */
14261 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14262 			ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14263 
14264 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14265 			    -rttecnt);
14266 
14267 			SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14268 		}
14269 	} else if (r_type == SFMMU_REGION_ISM) {
14270 		hatlockp = sfmmu_hat_enter(sfmmup);
14271 		ASSERT(rid < srdp->srd_next_ismrid);
14272 		SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14273 		scdp = sfmmup->sfmmu_scdp;
14274 		if (scdp != NULL &&
14275 		    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
14276 			sfmmu_leave_scd(sfmmup, r_type);
14277 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14278 		}
14279 		sfmmu_hat_exit(hatlockp);
14280 	} else {
14281 		ulong_t rttecnt;
14282 		r_pgszc = rgnp->rgn_pgszc;
14283 		r_saddr = rgnp->rgn_saddr;
14284 		r_size = rgnp->rgn_size;
14285 		r_eaddr = r_saddr + r_size;
14286 
14287 		ASSERT(r_type == SFMMU_REGION_HME);
14288 		hatlockp = sfmmu_hat_enter(sfmmup);
14289 		ASSERT(rid < srdp->srd_next_hmerid);
14290 		SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14291 
14292 		/*
14293 		 * If region is part of an SCD call sfmmu_leave_scd().
14294 		 * Otherwise if process is not exiting and has valid context
14295 		 * just drop the context on the floor to lose stale TLB
14296 		 * entries and force the update of tsb miss area to reflect
14297 		 * the new region map. After that clean our TSB entries.
14298 		 */
14299 		scdp = sfmmup->sfmmu_scdp;
14300 		if (scdp != NULL &&
14301 		    SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
14302 			sfmmu_leave_scd(sfmmup, r_type);
14303 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14304 		}
14305 		sfmmu_invalidate_ctx(sfmmup);
14306 
14307 		i = TTE8K;
14308 		while (i < mmu_page_sizes) {
14309 			if (rgnp->rgn_ttecnt[i] != 0) {
14310 				sfmmu_unload_tsb_range(sfmmup, r_saddr,
14311 				    r_eaddr, i);
14312 				if (i < TTE4M) {
14313 					i = TTE4M;
14314 					continue;
14315 				} else {
14316 					break;
14317 				}
14318 			}
14319 			i++;
14320 		}
14321 		/* Remove the preallocated 1/4 8k ttecnt for 4M regions. */
14322 		if (r_pgszc >= TTE4M) {
14323 			rttecnt = r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14324 			ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
14325 			    rttecnt);
14326 			sfmmup->sfmmu_tsb0_4minflcnt -= rttecnt;
14327 		}
14328 
14329 		/* update shme rgns ttecnt in sfmmu_ttecnt */
14330 		rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14331 		ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14332 		atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc], -rttecnt);
14333 
14334 		sfmmu_hat_exit(hatlockp);
14335 		if (scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
14336 			/* sfmmup left the scd, grow private tsb */
14337 			sfmmu_check_page_sizes(sfmmup, 1);
14338 		} else {
14339 			sfmmu_check_page_sizes(sfmmup, 0);
14340 		}
14341 	}
14342 
14343 	if (r_type == SFMMU_REGION_HME) {
14344 		sfmmu_unlink_from_hmeregion(sfmmup, rgnp);
14345 	}
14346 
14347 	r_obj = rgnp->rgn_obj;
14348 	if (atomic_add_32_nv((volatile uint_t *)&rgnp->rgn_refcnt, -1)) {
14349 		return;
14350 	}
14351 
14352 	/*
14353 	 * looks like nobody uses this region anymore. Free it.
14354 	 */
14355 	rhash = RGN_HASH_FUNCTION(r_obj);
14356 	mutex_enter(&srdp->srd_mutex);
14357 	for (prev_rgnpp = &srdp->srd_rgnhash[rhash];
14358 	    (cur_rgnp = *prev_rgnpp) != NULL;
14359 	    prev_rgnpp = &cur_rgnp->rgn_hash) {
14360 		if (cur_rgnp == rgnp && cur_rgnp->rgn_refcnt == 0) {
14361 			break;
14362 		}
14363 	}
14364 
14365 	if (cur_rgnp == NULL) {
14366 		mutex_exit(&srdp->srd_mutex);
14367 		return;
14368 	}
14369 
14370 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14371 	*prev_rgnpp = rgnp->rgn_hash;
14372 	if (r_type == SFMMU_REGION_ISM) {
14373 		rgnp->rgn_flags |= SFMMU_REGION_FREE;
14374 		ASSERT(rid < srdp->srd_next_ismrid);
14375 		rgnp->rgn_next = srdp->srd_ismrgnfree;
14376 		srdp->srd_ismrgnfree = rgnp;
14377 		ASSERT(srdp->srd_ismbusyrgns > 0);
14378 		srdp->srd_ismbusyrgns--;
14379 		mutex_exit(&srdp->srd_mutex);
14380 		return;
14381 	}
14382 	mutex_exit(&srdp->srd_mutex);
14383 
14384 	/*
14385 	 * Destroy region's hmeblks.
14386 	 */
14387 	sfmmu_unload_hmeregion(srdp, rgnp);
14388 
14389 	rgnp->rgn_hmeflags = 0;
14390 
14391 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14392 	ASSERT(rgnp->rgn_id == rid);
14393 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14394 		rgnp->rgn_ttecnt[i] = 0;
14395 	}
14396 	rgnp->rgn_flags |= SFMMU_REGION_FREE;
14397 	mutex_enter(&srdp->srd_mutex);
14398 	ASSERT(rid < srdp->srd_next_hmerid);
14399 	rgnp->rgn_next = srdp->srd_hmergnfree;
14400 	srdp->srd_hmergnfree = rgnp;
14401 	ASSERT(srdp->srd_hmebusyrgns > 0);
14402 	srdp->srd_hmebusyrgns--;
14403 	mutex_exit(&srdp->srd_mutex);
14404 }
14405 
14406 /*
14407  * For now only called for hmeblk regions and not for ISM regions.
14408  */
14409 void
14410 hat_dup_region(struct hat *sfmmup, hat_region_cookie_t rcookie)
14411 {
14412 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14413 	uint_t rid = (uint_t)((uint64_t)rcookie);
14414 	sf_region_t *rgnp;
14415 	sf_rgn_link_t *rlink;
14416 	sf_rgn_link_t *hrlink;
14417 	ulong_t	rttecnt;
14418 
14419 	ASSERT(sfmmup != ksfmmup);
14420 	ASSERT(srdp != NULL);
14421 	ASSERT(srdp->srd_refcnt > 0);
14422 
14423 	ASSERT(rid < srdp->srd_next_hmerid);
14424 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14425 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14426 
14427 	rgnp = srdp->srd_hmergnp[rid];
14428 	ASSERT(rgnp->rgn_refcnt > 0);
14429 	ASSERT(rgnp->rgn_id == rid);
14430 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == SFMMU_REGION_HME);
14431 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14432 
14433 	atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
14434 
14435 	/* LINTED: constant in conditional context */
14436 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 0);
14437 	ASSERT(rlink != NULL);
14438 	mutex_enter(&rgnp->rgn_mutex);
14439 	ASSERT(rgnp->rgn_sfmmu_head != NULL);
14440 	/* LINTED: constant in conditional context */
14441 	SFMMU_HMERID2RLINKP(rgnp->rgn_sfmmu_head, rid, hrlink, 0, 0);
14442 	ASSERT(hrlink != NULL);
14443 	ASSERT(hrlink->prev == NULL);
14444 	rlink->next = rgnp->rgn_sfmmu_head;
14445 	rlink->prev = NULL;
14446 	hrlink->prev = sfmmup;
14447 	/*
14448 	 * make sure rlink's next field is correct
14449 	 * before making this link visible.
14450 	 */
14451 	membar_stst();
14452 	rgnp->rgn_sfmmu_head = sfmmup;
14453 	mutex_exit(&rgnp->rgn_mutex);
14454 
14455 	/* update sfmmu_ttecnt with the shme rgn ttecnt */
14456 	rttecnt = rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
14457 	atomic_add_long(&sfmmup->sfmmu_ttecnt[rgnp->rgn_pgszc], rttecnt);
14458 	/* update tsb0 inflation count */
14459 	if (rgnp->rgn_pgszc >= TTE4M) {
14460 		sfmmup->sfmmu_tsb0_4minflcnt +=
14461 		    rgnp->rgn_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14462 	}
14463 	/*
14464 	 * Update regionid bitmask without hat lock since no other thread
14465 	 * can update this region bitmask right now.
14466 	 */
14467 	SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14468 }
14469 
14470 /* ARGSUSED */
14471 static int
14472 sfmmu_rgncache_constructor(void *buf, void *cdrarg, int kmflags)
14473 {
14474 	sf_region_t *rgnp = (sf_region_t *)buf;
14475 	bzero(buf, sizeof (*rgnp));
14476 
14477 	mutex_init(&rgnp->rgn_mutex, NULL, MUTEX_DEFAULT, NULL);
14478 
14479 	return (0);
14480 }
14481 
14482 /* ARGSUSED */
14483 static void
14484 sfmmu_rgncache_destructor(void *buf, void *cdrarg)
14485 {
14486 	sf_region_t *rgnp = (sf_region_t *)buf;
14487 	mutex_destroy(&rgnp->rgn_mutex);
14488 }
14489 
14490 static int
14491 sfrgnmap_isnull(sf_region_map_t *map)
14492 {
14493 	int i;
14494 
14495 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14496 		if (map->bitmap[i] != 0) {
14497 			return (0);
14498 		}
14499 	}
14500 	return (1);
14501 }
14502 
14503 static int
14504 sfhmergnmap_isnull(sf_hmeregion_map_t *map)
14505 {
14506 	int i;
14507 
14508 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
14509 		if (map->bitmap[i] != 0) {
14510 			return (0);
14511 		}
14512 	}
14513 	return (1);
14514 }
14515 
14516 #ifdef DEBUG
14517 static void
14518 check_scd_sfmmu_list(sfmmu_t **headp, sfmmu_t *sfmmup, int onlist)
14519 {
14520 	sfmmu_t *sp;
14521 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14522 
14523 	for (sp = *headp; sp != NULL; sp = sp->sfmmu_scd_link.next) {
14524 		ASSERT(srdp == sp->sfmmu_srdp);
14525 		if (sp == sfmmup) {
14526 			if (onlist) {
14527 				return;
14528 			} else {
14529 				panic("shctx: sfmmu 0x%p found on scd"
14530 				    "list 0x%p", (void *)sfmmup,
14531 				    (void *)*headp);
14532 			}
14533 		}
14534 	}
14535 	if (onlist) {
14536 		panic("shctx: sfmmu 0x%p not found on scd list 0x%p",
14537 		    (void *)sfmmup, (void *)*headp);
14538 	} else {
14539 		return;
14540 	}
14541 }
14542 #else /* DEBUG */
14543 #define	check_scd_sfmmu_list(headp, sfmmup, onlist)
14544 #endif /* DEBUG */
14545 
14546 /*
14547  * Removes an sfmmu from the SCD sfmmu list.
14548  */
14549 static void
14550 sfmmu_from_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14551 {
14552 	ASSERT(sfmmup->sfmmu_srdp != NULL);
14553 	check_scd_sfmmu_list(headp, sfmmup, 1);
14554 	if (sfmmup->sfmmu_scd_link.prev != NULL) {
14555 		ASSERT(*headp != sfmmup);
14556 		sfmmup->sfmmu_scd_link.prev->sfmmu_scd_link.next =
14557 		    sfmmup->sfmmu_scd_link.next;
14558 	} else {
14559 		ASSERT(*headp == sfmmup);
14560 		*headp = sfmmup->sfmmu_scd_link.next;
14561 	}
14562 	if (sfmmup->sfmmu_scd_link.next != NULL) {
14563 		sfmmup->sfmmu_scd_link.next->sfmmu_scd_link.prev =
14564 		    sfmmup->sfmmu_scd_link.prev;
14565 	}
14566 }
14567 
14568 
14569 /*
14570  * Adds an sfmmu to the start of the queue.
14571  */
14572 static void
14573 sfmmu_to_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14574 {
14575 	check_scd_sfmmu_list(headp, sfmmup, 0);
14576 	sfmmup->sfmmu_scd_link.prev = NULL;
14577 	sfmmup->sfmmu_scd_link.next = *headp;
14578 	if (*headp != NULL)
14579 		(*headp)->sfmmu_scd_link.prev = sfmmup;
14580 	*headp = sfmmup;
14581 }
14582 
14583 /*
14584  * Remove an scd from the start of the queue.
14585  */
14586 static void
14587 sfmmu_remove_scd(sf_scd_t **headp, sf_scd_t *scdp)
14588 {
14589 	if (scdp->scd_prev != NULL) {
14590 		ASSERT(*headp != scdp);
14591 		scdp->scd_prev->scd_next = scdp->scd_next;
14592 	} else {
14593 		ASSERT(*headp == scdp);
14594 		*headp = scdp->scd_next;
14595 	}
14596 
14597 	if (scdp->scd_next != NULL) {
14598 		scdp->scd_next->scd_prev = scdp->scd_prev;
14599 	}
14600 }
14601 
14602 /*
14603  * Add an scd to the start of the queue.
14604  */
14605 static void
14606 sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *scdp)
14607 {
14608 	scdp->scd_prev = NULL;
14609 	scdp->scd_next = *headp;
14610 	if (*headp != NULL) {
14611 		(*headp)->scd_prev = scdp;
14612 	}
14613 	*headp = scdp;
14614 }
14615 
14616 static int
14617 sfmmu_alloc_scd_tsbs(sf_srd_t *srdp, sf_scd_t *scdp)
14618 {
14619 	uint_t rid;
14620 	uint_t i;
14621 	uint_t j;
14622 	ulong_t w;
14623 	sf_region_t *rgnp;
14624 	ulong_t tte8k_cnt = 0;
14625 	ulong_t tte4m_cnt = 0;
14626 	uint_t tsb_szc;
14627 	sfmmu_t *scsfmmup = scdp->scd_sfmmup;
14628 	sfmmu_t	*ism_hatid;
14629 	struct tsb_info *newtsb;
14630 	int szc;
14631 
14632 	ASSERT(srdp != NULL);
14633 
14634 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14635 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14636 			continue;
14637 		}
14638 		j = 0;
14639 		while (w) {
14640 			if (!(w & 0x1)) {
14641 				j++;
14642 				w >>= 1;
14643 				continue;
14644 			}
14645 			rid = (i << BT_ULSHIFT) | j;
14646 			j++;
14647 			w >>= 1;
14648 
14649 			if (rid < SFMMU_MAX_HME_REGIONS) {
14650 				rgnp = srdp->srd_hmergnp[rid];
14651 				ASSERT(rgnp->rgn_id == rid);
14652 				ASSERT(rgnp->rgn_refcnt > 0);
14653 
14654 				if (rgnp->rgn_pgszc < TTE4M) {
14655 					tte8k_cnt += rgnp->rgn_size >>
14656 					    TTE_PAGE_SHIFT(TTE8K);
14657 				} else {
14658 					ASSERT(rgnp->rgn_pgszc >= TTE4M);
14659 					tte4m_cnt += rgnp->rgn_size >>
14660 					    TTE_PAGE_SHIFT(TTE4M);
14661 					/*
14662 					 * Inflate SCD tsb0 by preallocating
14663 					 * 1/4 8k ttecnt for 4M regions to
14664 					 * allow for lgpg alloc failure.
14665 					 */
14666 					tte8k_cnt += rgnp->rgn_size >>
14667 					    (TTE_PAGE_SHIFT(TTE8K) + 2);
14668 				}
14669 			} else {
14670 				rid -= SFMMU_MAX_HME_REGIONS;
14671 				rgnp = srdp->srd_ismrgnp[rid];
14672 				ASSERT(rgnp->rgn_id == rid);
14673 				ASSERT(rgnp->rgn_refcnt > 0);
14674 
14675 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14676 				ASSERT(ism_hatid->sfmmu_ismhat);
14677 
14678 				for (szc = 0; szc < TTE4M; szc++) {
14679 					tte8k_cnt +=
14680 					    ism_hatid->sfmmu_ttecnt[szc] <<
14681 					    TTE_BSZS_SHIFT(szc);
14682 				}
14683 
14684 				ASSERT(rgnp->rgn_pgszc >= TTE4M);
14685 				if (rgnp->rgn_pgszc >= TTE4M) {
14686 					tte4m_cnt += rgnp->rgn_size >>
14687 					    TTE_PAGE_SHIFT(TTE4M);
14688 				}
14689 			}
14690 		}
14691 	}
14692 
14693 	tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
14694 
14695 	/* Allocate both the SCD TSBs here. */
14696 	if (sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14697 	    tsb_szc, TSB8K|TSB64K|TSB512K, TSB_ALLOC, scsfmmup) &&
14698 	    (tsb_szc <= TSB_4M_SZCODE ||
14699 	    sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14700 	    TSB_4M_SZCODE, TSB8K|TSB64K|TSB512K,
14701 	    TSB_ALLOC, scsfmmup))) {
14702 
14703 		SFMMU_STAT(sf_scd_1sttsb_allocfail);
14704 		return (TSB_ALLOCFAIL);
14705 	} else {
14706 		scsfmmup->sfmmu_tsb->tsb_flags |= TSB_SHAREDCTX;
14707 
14708 		if (tte4m_cnt) {
14709 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
14710 			if (sfmmu_tsbinfo_alloc(&newtsb, tsb_szc,
14711 			    TSB4M|TSB32M|TSB256M, TSB_ALLOC, scsfmmup) &&
14712 			    (tsb_szc <= TSB_4M_SZCODE ||
14713 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
14714 			    TSB4M|TSB32M|TSB256M,
14715 			    TSB_ALLOC, scsfmmup))) {
14716 				/*
14717 				 * If we fail to allocate the 2nd shared tsb,
14718 				 * just free the 1st tsb, return failure.
14719 				 */
14720 				sfmmu_tsbinfo_free(scsfmmup->sfmmu_tsb);
14721 				SFMMU_STAT(sf_scd_2ndtsb_allocfail);
14722 				return (TSB_ALLOCFAIL);
14723 			} else {
14724 				ASSERT(scsfmmup->sfmmu_tsb->tsb_next == NULL);
14725 				newtsb->tsb_flags |= TSB_SHAREDCTX;
14726 				scsfmmup->sfmmu_tsb->tsb_next = newtsb;
14727 				SFMMU_STAT(sf_scd_2ndtsb_alloc);
14728 			}
14729 		}
14730 		SFMMU_STAT(sf_scd_1sttsb_alloc);
14731 	}
14732 	return (TSB_SUCCESS);
14733 }
14734 
14735 static void
14736 sfmmu_free_scd_tsbs(sfmmu_t *scd_sfmmu)
14737 {
14738 	while (scd_sfmmu->sfmmu_tsb != NULL) {
14739 		struct tsb_info *next = scd_sfmmu->sfmmu_tsb->tsb_next;
14740 		sfmmu_tsbinfo_free(scd_sfmmu->sfmmu_tsb);
14741 		scd_sfmmu->sfmmu_tsb = next;
14742 	}
14743 }
14744 
14745 /*
14746  * Link the sfmmu onto the hme region list.
14747  */
14748 void
14749 sfmmu_link_to_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14750 {
14751 	uint_t rid;
14752 	sf_rgn_link_t *rlink;
14753 	sfmmu_t *head;
14754 	sf_rgn_link_t *hrlink;
14755 
14756 	rid = rgnp->rgn_id;
14757 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14758 
14759 	/* LINTED: constant in conditional context */
14760 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 1);
14761 	ASSERT(rlink != NULL);
14762 	mutex_enter(&rgnp->rgn_mutex);
14763 	if ((head = rgnp->rgn_sfmmu_head) == NULL) {
14764 		rlink->next = NULL;
14765 		rlink->prev = NULL;
14766 		/*
14767 		 * make sure rlink's next field is NULL
14768 		 * before making this link visible.
14769 		 */
14770 		membar_stst();
14771 		rgnp->rgn_sfmmu_head = sfmmup;
14772 	} else {
14773 		/* LINTED: constant in conditional context */
14774 		SFMMU_HMERID2RLINKP(head, rid, hrlink, 0, 0);
14775 		ASSERT(hrlink != NULL);
14776 		ASSERT(hrlink->prev == NULL);
14777 		rlink->next = head;
14778 		rlink->prev = NULL;
14779 		hrlink->prev = sfmmup;
14780 		/*
14781 		 * make sure rlink's next field is correct
14782 		 * before making this link visible.
14783 		 */
14784 		membar_stst();
14785 		rgnp->rgn_sfmmu_head = sfmmup;
14786 	}
14787 	mutex_exit(&rgnp->rgn_mutex);
14788 }
14789 
14790 /*
14791  * Unlink the sfmmu from the hme region list.
14792  */
14793 void
14794 sfmmu_unlink_from_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14795 {
14796 	uint_t rid;
14797 	sf_rgn_link_t *rlink;
14798 
14799 	rid = rgnp->rgn_id;
14800 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14801 
14802 	/* LINTED: constant in conditional context */
14803 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
14804 	ASSERT(rlink != NULL);
14805 	mutex_enter(&rgnp->rgn_mutex);
14806 	if (rgnp->rgn_sfmmu_head == sfmmup) {
14807 		sfmmu_t *next = rlink->next;
14808 		rgnp->rgn_sfmmu_head = next;
14809 		/*
14810 		 * if we are stopped by xc_attention() after this
14811 		 * point the forward link walking in
14812 		 * sfmmu_rgntlb_demap() will work correctly since the
14813 		 * head correctly points to the next element.
14814 		 */
14815 		membar_stst();
14816 		rlink->next = NULL;
14817 		ASSERT(rlink->prev == NULL);
14818 		if (next != NULL) {
14819 			sf_rgn_link_t *nrlink;
14820 			/* LINTED: constant in conditional context */
14821 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14822 			ASSERT(nrlink != NULL);
14823 			ASSERT(nrlink->prev == sfmmup);
14824 			nrlink->prev = NULL;
14825 		}
14826 	} else {
14827 		sfmmu_t *next = rlink->next;
14828 		sfmmu_t *prev = rlink->prev;
14829 		sf_rgn_link_t *prlink;
14830 
14831 		ASSERT(prev != NULL);
14832 		/* LINTED: constant in conditional context */
14833 		SFMMU_HMERID2RLINKP(prev, rid, prlink, 0, 0);
14834 		ASSERT(prlink != NULL);
14835 		ASSERT(prlink->next == sfmmup);
14836 		prlink->next = next;
14837 		/*
14838 		 * if we are stopped by xc_attention()
14839 		 * after this point the forward link walking
14840 		 * will work correctly since the prev element
14841 		 * correctly points to the next element.
14842 		 */
14843 		membar_stst();
14844 		rlink->next = NULL;
14845 		rlink->prev = NULL;
14846 		if (next != NULL) {
14847 			sf_rgn_link_t *nrlink;
14848 			/* LINTED: constant in conditional context */
14849 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14850 			ASSERT(nrlink != NULL);
14851 			ASSERT(nrlink->prev == sfmmup);
14852 			nrlink->prev = prev;
14853 		}
14854 	}
14855 	mutex_exit(&rgnp->rgn_mutex);
14856 }
14857 
14858 /*
14859  * Link scd sfmmu onto ism or hme region list for each region in the
14860  * scd region map.
14861  */
14862 void
14863 sfmmu_link_scd_to_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14864 {
14865 	uint_t rid;
14866 	uint_t i;
14867 	uint_t j;
14868 	ulong_t w;
14869 	sf_region_t *rgnp;
14870 	sfmmu_t *scsfmmup;
14871 
14872 	scsfmmup = scdp->scd_sfmmup;
14873 	ASSERT(scsfmmup->sfmmu_scdhat);
14874 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14875 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14876 			continue;
14877 		}
14878 		j = 0;
14879 		while (w) {
14880 			if (!(w & 0x1)) {
14881 				j++;
14882 				w >>= 1;
14883 				continue;
14884 			}
14885 			rid = (i << BT_ULSHIFT) | j;
14886 			j++;
14887 			w >>= 1;
14888 
14889 			if (rid < SFMMU_MAX_HME_REGIONS) {
14890 				rgnp = srdp->srd_hmergnp[rid];
14891 				ASSERT(rgnp->rgn_id == rid);
14892 				ASSERT(rgnp->rgn_refcnt > 0);
14893 				sfmmu_link_to_hmeregion(scsfmmup, rgnp);
14894 			} else {
14895 				sfmmu_t *ism_hatid = NULL;
14896 				ism_ment_t *ism_ment;
14897 				rid -= SFMMU_MAX_HME_REGIONS;
14898 				rgnp = srdp->srd_ismrgnp[rid];
14899 				ASSERT(rgnp->rgn_id == rid);
14900 				ASSERT(rgnp->rgn_refcnt > 0);
14901 
14902 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14903 				ASSERT(ism_hatid->sfmmu_ismhat);
14904 				ism_ment = &scdp->scd_ism_links[rid];
14905 				ism_ment->iment_hat = scsfmmup;
14906 				ism_ment->iment_base_va = rgnp->rgn_saddr;
14907 				mutex_enter(&ism_mlist_lock);
14908 				iment_add(ism_ment, ism_hatid);
14909 				mutex_exit(&ism_mlist_lock);
14910 
14911 			}
14912 		}
14913 	}
14914 }
14915 /*
14916  * Unlink scd sfmmu from ism or hme region list for each region in the
14917  * scd region map.
14918  */
14919 void
14920 sfmmu_unlink_scd_from_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14921 {
14922 	uint_t rid;
14923 	uint_t i;
14924 	uint_t j;
14925 	ulong_t w;
14926 	sf_region_t *rgnp;
14927 	sfmmu_t *scsfmmup;
14928 
14929 	scsfmmup = scdp->scd_sfmmup;
14930 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14931 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14932 			continue;
14933 		}
14934 		j = 0;
14935 		while (w) {
14936 			if (!(w & 0x1)) {
14937 				j++;
14938 				w >>= 1;
14939 				continue;
14940 			}
14941 			rid = (i << BT_ULSHIFT) | j;
14942 			j++;
14943 			w >>= 1;
14944 
14945 			if (rid < SFMMU_MAX_HME_REGIONS) {
14946 				rgnp = srdp->srd_hmergnp[rid];
14947 				ASSERT(rgnp->rgn_id == rid);
14948 				ASSERT(rgnp->rgn_refcnt > 0);
14949 				sfmmu_unlink_from_hmeregion(scsfmmup,
14950 				    rgnp);
14951 
14952 			} else {
14953 				sfmmu_t *ism_hatid = NULL;
14954 				ism_ment_t *ism_ment;
14955 				rid -= SFMMU_MAX_HME_REGIONS;
14956 				rgnp = srdp->srd_ismrgnp[rid];
14957 				ASSERT(rgnp->rgn_id == rid);
14958 				ASSERT(rgnp->rgn_refcnt > 0);
14959 
14960 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14961 				ASSERT(ism_hatid->sfmmu_ismhat);
14962 				ism_ment = &scdp->scd_ism_links[rid];
14963 				ASSERT(ism_ment->iment_hat == scdp->scd_sfmmup);
14964 				ASSERT(ism_ment->iment_base_va ==
14965 				    rgnp->rgn_saddr);
14966 				ism_ment->iment_hat = NULL;
14967 				ism_ment->iment_base_va = 0;
14968 				mutex_enter(&ism_mlist_lock);
14969 				iment_sub(ism_ment, ism_hatid);
14970 				mutex_exit(&ism_mlist_lock);
14971 
14972 			}
14973 		}
14974 	}
14975 }
14976 /*
14977  * Allocates and initialises a new SCD structure, this is called with
14978  * the srd_scd_mutex held and returns with the reference count
14979  * initialised to 1.
14980  */
14981 static sf_scd_t *
14982 sfmmu_alloc_scd(sf_srd_t *srdp, sf_region_map_t *new_map)
14983 {
14984 	sf_scd_t *new_scdp;
14985 	sfmmu_t *scsfmmup;
14986 	int i;
14987 
14988 	ASSERT(MUTEX_HELD(&srdp->srd_scd_mutex));
14989 	new_scdp = kmem_cache_alloc(scd_cache, KM_SLEEP);
14990 
14991 	scsfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
14992 	new_scdp->scd_sfmmup = scsfmmup;
14993 	scsfmmup->sfmmu_srdp = srdp;
14994 	scsfmmup->sfmmu_scdp = new_scdp;
14995 	scsfmmup->sfmmu_tsb0_4minflcnt = 0;
14996 	scsfmmup->sfmmu_scdhat = 1;
14997 	CPUSET_ALL(scsfmmup->sfmmu_cpusran);
14998 	bzero(scsfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
14999 
15000 	ASSERT(max_mmu_ctxdoms > 0);
15001 	for (i = 0; i < max_mmu_ctxdoms; i++) {
15002 		scsfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
15003 		scsfmmup->sfmmu_ctxs[i].gnum = 0;
15004 	}
15005 
15006 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
15007 		new_scdp->scd_rttecnt[i] = 0;
15008 	}
15009 
15010 	new_scdp->scd_region_map = *new_map;
15011 	new_scdp->scd_refcnt = 1;
15012 	if (sfmmu_alloc_scd_tsbs(srdp, new_scdp) != TSB_SUCCESS) {
15013 		kmem_cache_free(scd_cache, new_scdp);
15014 		kmem_cache_free(sfmmuid_cache, scsfmmup);
15015 		return (NULL);
15016 	}
15017 	return (new_scdp);
15018 }
15019 
15020 /*
15021  * The first phase of a process joining an SCD. The hat structure is
15022  * linked to the SCD queue and then the HAT_JOIN_SCD sfmmu flag is set
15023  * and a cross-call with context invalidation is used to cause the
15024  * remaining work to be carried out in the sfmmu_tsbmiss_exception()
15025  * routine.
15026  */
15027 static void
15028 sfmmu_join_scd(sf_scd_t *scdp, sfmmu_t *sfmmup)
15029 {
15030 	hatlock_t *hatlockp;
15031 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15032 	int i;
15033 	sf_scd_t *old_scdp;
15034 
15035 	ASSERT(srdp != NULL);
15036 	ASSERT(scdp != NULL);
15037 	ASSERT(scdp->scd_refcnt > 0);
15038 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15039 
15040 	if ((old_scdp = sfmmup->sfmmu_scdp) != NULL) {
15041 		ASSERT(old_scdp != scdp);
15042 
15043 		mutex_enter(&old_scdp->scd_mutex);
15044 		sfmmu_from_scd_list(&old_scdp->scd_sf_list, sfmmup);
15045 		mutex_exit(&old_scdp->scd_mutex);
15046 		/*
15047 		 * sfmmup leaves the old scd. Update sfmmu_ttecnt to
15048 		 * include the shme rgn ttecnt for rgns that
15049 		 * were in the old SCD
15050 		 */
15051 		for (i = 0; i < mmu_page_sizes; i++) {
15052 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15053 			    old_scdp->scd_rttecnt[i]);
15054 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15055 			    sfmmup->sfmmu_scdrttecnt[i]);
15056 		}
15057 	}
15058 
15059 	/*
15060 	 * Move sfmmu to the scd lists.
15061 	 */
15062 	mutex_enter(&scdp->scd_mutex);
15063 	sfmmu_to_scd_list(&scdp->scd_sf_list, sfmmup);
15064 	mutex_exit(&scdp->scd_mutex);
15065 	SF_SCD_INCR_REF(scdp);
15066 
15067 	hatlockp = sfmmu_hat_enter(sfmmup);
15068 	/*
15069 	 * For a multi-thread process, we must stop
15070 	 * all the other threads before joining the scd.
15071 	 */
15072 
15073 	SFMMU_FLAGS_SET(sfmmup, HAT_JOIN_SCD);
15074 
15075 	sfmmu_invalidate_ctx(sfmmup);
15076 	sfmmup->sfmmu_scdp = scdp;
15077 
15078 	/*
15079 	 * Copy scd_rttecnt into sfmmup's sfmmu_scdrttecnt, and update
15080 	 * sfmmu_ttecnt to not include the rgn ttecnt just joined in SCD.
15081 	 */
15082 	for (i = 0; i < mmu_page_sizes; i++) {
15083 		sfmmup->sfmmu_scdrttecnt[i] = scdp->scd_rttecnt[i];
15084 		ASSERT(sfmmup->sfmmu_ttecnt[i] >= scdp->scd_rttecnt[i]);
15085 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15086 		    -sfmmup->sfmmu_scdrttecnt[i]);
15087 	}
15088 	/* update tsb0 inflation count */
15089 	if (old_scdp != NULL) {
15090 		sfmmup->sfmmu_tsb0_4minflcnt +=
15091 		    old_scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15092 	}
15093 	ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
15094 	    scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt);
15095 	sfmmup->sfmmu_tsb0_4minflcnt -= scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15096 
15097 	sfmmu_hat_exit(hatlockp);
15098 
15099 	if (old_scdp != NULL) {
15100 		SF_SCD_DECR_REF(srdp, old_scdp);
15101 	}
15102 
15103 }
15104 
15105 /*
15106  * This routine is called by a process to become part of an SCD. It is called
15107  * from sfmmu_tsbmiss_exception() once most of the initial work has been
15108  * done by sfmmu_join_scd(). This routine must not drop the hat lock.
15109  */
15110 static void
15111 sfmmu_finish_join_scd(sfmmu_t *sfmmup)
15112 {
15113 	struct tsb_info	*tsbinfop;
15114 
15115 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15116 	ASSERT(sfmmup->sfmmu_scdp != NULL);
15117 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD));
15118 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15119 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID));
15120 
15121 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
15122 	    tsbinfop = tsbinfop->tsb_next) {
15123 		if (tsbinfop->tsb_flags & TSB_SWAPPED) {
15124 			continue;
15125 		}
15126 		ASSERT(!(tsbinfop->tsb_flags & TSB_RELOC_FLAG));
15127 
15128 		sfmmu_inv_tsb(tsbinfop->tsb_va,
15129 		    TSB_BYTES(tsbinfop->tsb_szc));
15130 	}
15131 
15132 	/* Set HAT_CTX1_FLAG for all SCD ISMs */
15133 	sfmmu_ism_hatflags(sfmmup, 1);
15134 
15135 	SFMMU_STAT(sf_join_scd);
15136 }
15137 
15138 /*
15139  * This routine is called in order to check if there is an SCD which matches
15140  * the process's region map if not then a new SCD may be created.
15141  */
15142 static void
15143 sfmmu_find_scd(sfmmu_t *sfmmup)
15144 {
15145 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15146 	sf_scd_t *scdp, *new_scdp;
15147 	int ret;
15148 
15149 	ASSERT(srdp != NULL);
15150 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15151 
15152 	mutex_enter(&srdp->srd_scd_mutex);
15153 	for (scdp = srdp->srd_scdp; scdp != NULL;
15154 	    scdp = scdp->scd_next) {
15155 		SF_RGNMAP_EQUAL(&scdp->scd_region_map,
15156 		    &sfmmup->sfmmu_region_map, ret);
15157 		if (ret == 1) {
15158 			SF_SCD_INCR_REF(scdp);
15159 			mutex_exit(&srdp->srd_scd_mutex);
15160 			sfmmu_join_scd(scdp, sfmmup);
15161 			ASSERT(scdp->scd_refcnt >= 2);
15162 			atomic_add_32((volatile uint32_t *)
15163 			    &scdp->scd_refcnt, -1);
15164 			return;
15165 		} else {
15166 			/*
15167 			 * If the sfmmu region map is a subset of the scd
15168 			 * region map, then the assumption is that this process
15169 			 * will continue attaching to ISM segments until the
15170 			 * region maps are equal.
15171 			 */
15172 			SF_RGNMAP_IS_SUBSET(&scdp->scd_region_map,
15173 			    &sfmmup->sfmmu_region_map, ret);
15174 			if (ret == 1) {
15175 				mutex_exit(&srdp->srd_scd_mutex);
15176 				return;
15177 			}
15178 		}
15179 	}
15180 
15181 	ASSERT(scdp == NULL);
15182 	/*
15183 	 * No matching SCD has been found, create a new one.
15184 	 */
15185 	if ((new_scdp = sfmmu_alloc_scd(srdp, &sfmmup->sfmmu_region_map)) ==
15186 	    NULL) {
15187 		mutex_exit(&srdp->srd_scd_mutex);
15188 		return;
15189 	}
15190 
15191 	/*
15192 	 * sfmmu_alloc_scd() returns with a ref count of 1 on the scd.
15193 	 */
15194 
15195 	/* Set scd_rttecnt for shme rgns in SCD */
15196 	sfmmu_set_scd_rttecnt(srdp, new_scdp);
15197 
15198 	/*
15199 	 * Link scd onto srd_scdp list and scd sfmmu onto region/iment lists.
15200 	 */
15201 	sfmmu_link_scd_to_regions(srdp, new_scdp);
15202 	sfmmu_add_scd(&srdp->srd_scdp, new_scdp);
15203 	SFMMU_STAT_ADD(sf_create_scd, 1);
15204 
15205 	mutex_exit(&srdp->srd_scd_mutex);
15206 	sfmmu_join_scd(new_scdp, sfmmup);
15207 	ASSERT(new_scdp->scd_refcnt >= 2);
15208 	atomic_add_32((volatile uint32_t *)&new_scdp->scd_refcnt, -1);
15209 }
15210 
15211 /*
15212  * This routine is called by a process to remove itself from an SCD. It is
15213  * either called when the processes has detached from a segment or from
15214  * hat_free_start() as a result of calling exit.
15215  */
15216 static void
15217 sfmmu_leave_scd(sfmmu_t *sfmmup, uchar_t r_type)
15218 {
15219 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15220 	sf_srd_t *srdp =  sfmmup->sfmmu_srdp;
15221 	hatlock_t *hatlockp = TSB_HASH(sfmmup);
15222 	int i;
15223 
15224 	ASSERT(scdp != NULL);
15225 	ASSERT(srdp != NULL);
15226 
15227 	if (sfmmup->sfmmu_free) {
15228 		/*
15229 		 * If the process is part of an SCD the sfmmu is unlinked
15230 		 * from scd_sf_list.
15231 		 */
15232 		mutex_enter(&scdp->scd_mutex);
15233 		sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15234 		mutex_exit(&scdp->scd_mutex);
15235 		/*
15236 		 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15237 		 * are about to leave the SCD
15238 		 */
15239 		for (i = 0; i < mmu_page_sizes; i++) {
15240 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15241 			    scdp->scd_rttecnt[i]);
15242 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15243 			    sfmmup->sfmmu_scdrttecnt[i]);
15244 			sfmmup->sfmmu_scdrttecnt[i] = 0;
15245 		}
15246 		sfmmup->sfmmu_scdp = NULL;
15247 
15248 		SF_SCD_DECR_REF(srdp, scdp);
15249 		return;
15250 	}
15251 
15252 	ASSERT(r_type != SFMMU_REGION_ISM ||
15253 	    SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15254 	ASSERT(scdp->scd_refcnt);
15255 	ASSERT(!sfmmup->sfmmu_free);
15256 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15257 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15258 
15259 	/*
15260 	 * Wait for ISM maps to be updated.
15261 	 */
15262 	if (r_type != SFMMU_REGION_ISM) {
15263 		while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY) &&
15264 		    sfmmup->sfmmu_scdp != NULL) {
15265 			cv_wait(&sfmmup->sfmmu_tsb_cv,
15266 			    HATLOCK_MUTEXP(hatlockp));
15267 		}
15268 
15269 		if (sfmmup->sfmmu_scdp == NULL) {
15270 			sfmmu_hat_exit(hatlockp);
15271 			return;
15272 		}
15273 		SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
15274 	}
15275 
15276 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
15277 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
15278 		/*
15279 		 * Since HAT_JOIN_SCD was set our context
15280 		 * is still invalid.
15281 		 */
15282 	} else {
15283 		/*
15284 		 * For a multi-thread process, we must stop
15285 		 * all the other threads before leaving the scd.
15286 		 */
15287 
15288 		sfmmu_invalidate_ctx(sfmmup);
15289 	}
15290 
15291 	/* Clear all the rid's for ISM, delete flags, etc */
15292 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15293 	sfmmu_ism_hatflags(sfmmup, 0);
15294 
15295 	/*
15296 	 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15297 	 * are in SCD before this sfmmup leaves the SCD.
15298 	 */
15299 	for (i = 0; i < mmu_page_sizes; i++) {
15300 		ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15301 		    scdp->scd_rttecnt[i]);
15302 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15303 		    sfmmup->sfmmu_scdrttecnt[i]);
15304 		sfmmup->sfmmu_scdrttecnt[i] = 0;
15305 		/* update ismttecnt to include SCD ism before hat leaves SCD */
15306 		sfmmup->sfmmu_ismttecnt[i] += sfmmup->sfmmu_scdismttecnt[i];
15307 		sfmmup->sfmmu_scdismttecnt[i] = 0;
15308 	}
15309 	/* update tsb0 inflation count */
15310 	sfmmup->sfmmu_tsb0_4minflcnt += scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15311 
15312 	if (r_type != SFMMU_REGION_ISM) {
15313 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
15314 	}
15315 	sfmmup->sfmmu_scdp = NULL;
15316 
15317 	sfmmu_hat_exit(hatlockp);
15318 
15319 	/*
15320 	 * Unlink sfmmu from scd_sf_list this can be done without holding
15321 	 * the hat lock as we hold the sfmmu_as lock which prevents
15322 	 * hat_join_region from adding this thread to the scd again. Other
15323 	 * threads check if sfmmu_scdp is NULL under hat lock and if it's NULL
15324 	 * they won't get here, since sfmmu_leave_scd() clears sfmmu_scdp
15325 	 * while holding the hat lock.
15326 	 */
15327 	mutex_enter(&scdp->scd_mutex);
15328 	sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15329 	mutex_exit(&scdp->scd_mutex);
15330 	SFMMU_STAT(sf_leave_scd);
15331 
15332 	SF_SCD_DECR_REF(srdp, scdp);
15333 	hatlockp = sfmmu_hat_enter(sfmmup);
15334 
15335 }
15336 
15337 /*
15338  * Unlink and free up an SCD structure with a reference count of 0.
15339  */
15340 static void
15341 sfmmu_destroy_scd(sf_srd_t *srdp, sf_scd_t *scdp, sf_region_map_t *scd_rmap)
15342 {
15343 	sfmmu_t *scsfmmup;
15344 	sf_scd_t *sp;
15345 	hatlock_t *shatlockp;
15346 	int i, ret;
15347 
15348 	mutex_enter(&srdp->srd_scd_mutex);
15349 	for (sp = srdp->srd_scdp; sp != NULL; sp = sp->scd_next) {
15350 		if (sp == scdp)
15351 			break;
15352 	}
15353 	if (sp == NULL || sp->scd_refcnt) {
15354 		mutex_exit(&srdp->srd_scd_mutex);
15355 		return;
15356 	}
15357 
15358 	/*
15359 	 * It is possible that the scd has been freed and reallocated with a
15360 	 * different region map while we've been waiting for the srd_scd_mutex.
15361 	 */
15362 	SF_RGNMAP_EQUAL(scd_rmap, &sp->scd_region_map, ret);
15363 	if (ret != 1) {
15364 		mutex_exit(&srdp->srd_scd_mutex);
15365 		return;
15366 	}
15367 
15368 	ASSERT(scdp->scd_sf_list == NULL);
15369 	/*
15370 	 * Unlink scd from srd_scdp list.
15371 	 */
15372 	sfmmu_remove_scd(&srdp->srd_scdp, scdp);
15373 	mutex_exit(&srdp->srd_scd_mutex);
15374 
15375 	sfmmu_unlink_scd_from_regions(srdp, scdp);
15376 
15377 	/* Clear shared context tsb and release ctx */
15378 	scsfmmup = scdp->scd_sfmmup;
15379 
15380 	/*
15381 	 * create a barrier so that scd will not be destroyed
15382 	 * if other thread still holds the same shared hat lock.
15383 	 * E.g., sfmmu_tsbmiss_exception() needs to acquire the
15384 	 * shared hat lock before checking the shared tsb reloc flag.
15385 	 */
15386 	shatlockp = sfmmu_hat_enter(scsfmmup);
15387 	sfmmu_hat_exit(shatlockp);
15388 
15389 	sfmmu_free_scd_tsbs(scsfmmup);
15390 
15391 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
15392 		if (scsfmmup->sfmmu_hmeregion_links[i] != NULL) {
15393 			kmem_free(scsfmmup->sfmmu_hmeregion_links[i],
15394 			    SFMMU_L2_HMERLINKS_SIZE);
15395 			scsfmmup->sfmmu_hmeregion_links[i] = NULL;
15396 		}
15397 	}
15398 	kmem_cache_free(sfmmuid_cache, scsfmmup);
15399 	kmem_cache_free(scd_cache, scdp);
15400 	SFMMU_STAT(sf_destroy_scd);
15401 }
15402 
15403 /*
15404  * Modifies the HAT_CTX1_FLAG for each of the ISM segments which correspond to
15405  * bits which are set in the ism_region_map parameter. This flag indicates to
15406  * the tsbmiss handler that mapping for these segments should be loaded using
15407  * the shared context.
15408  */
15409 static void
15410 sfmmu_ism_hatflags(sfmmu_t *sfmmup, int addflag)
15411 {
15412 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15413 	ism_blk_t *ism_blkp;
15414 	ism_map_t *ism_map;
15415 	int i, rid;
15416 
15417 	ASSERT(sfmmup->sfmmu_iblk != NULL);
15418 	ASSERT(scdp != NULL);
15419 	/*
15420 	 * Note that the caller either set HAT_ISMBUSY flag or checked
15421 	 * under hat lock that HAT_ISMBUSY was not set by another thread.
15422 	 */
15423 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15424 
15425 	ism_blkp = sfmmup->sfmmu_iblk;
15426 	while (ism_blkp != NULL) {
15427 		ism_map = ism_blkp->iblk_maps;
15428 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
15429 			rid = ism_map[i].imap_rid;
15430 			if (rid == SFMMU_INVALID_ISMRID) {
15431 				continue;
15432 			}
15433 			ASSERT(rid >= 0 && rid < SFMMU_MAX_ISM_REGIONS);
15434 			if (SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid) &&
15435 			    addflag) {
15436 				ism_map[i].imap_hatflags |=
15437 				    HAT_CTX1_FLAG;
15438 			} else {
15439 				ism_map[i].imap_hatflags &=
15440 				    ~HAT_CTX1_FLAG;
15441 			}
15442 		}
15443 		ism_blkp = ism_blkp->iblk_next;
15444 	}
15445 }
15446 
15447 static int
15448 sfmmu_srd_lock_held(sf_srd_t *srdp)
15449 {
15450 	return (MUTEX_HELD(&srdp->srd_mutex));
15451 }
15452 
15453 /* ARGSUSED */
15454 static int
15455 sfmmu_scdcache_constructor(void *buf, void *cdrarg, int kmflags)
15456 {
15457 	sf_scd_t *scdp = (sf_scd_t *)buf;
15458 
15459 	bzero(buf, sizeof (sf_scd_t));
15460 	mutex_init(&scdp->scd_mutex, NULL, MUTEX_DEFAULT, NULL);
15461 	return (0);
15462 }
15463 
15464 /* ARGSUSED */
15465 static void
15466 sfmmu_scdcache_destructor(void *buf, void *cdrarg)
15467 {
15468 	sf_scd_t *scdp = (sf_scd_t *)buf;
15469 
15470 	mutex_destroy(&scdp->scd_mutex);
15471 }
15472