xref: /illumos-gate/usr/src/uts/sfmmu/vm/hat_sfmmu.c (revision 8aa6aadbbfba50077655c6a46a5e269c880e4ab4)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * VM - Hardware Address Translation management for Spitfire MMU.
28  *
29  * This file implements the machine specific hardware translation
30  * needed by the VM system.  The machine independent interface is
31  * described in <vm/hat.h> while the machine dependent interface
32  * and data structures are described in <vm/hat_sfmmu.h>.
33  *
34  * The hat layer manages the address translation hardware as a cache
35  * driven by calls from the higher levels in the VM system.
36  */
37 
38 #include <sys/types.h>
39 #include <sys/kstat.h>
40 #include <vm/hat.h>
41 #include <vm/hat_sfmmu.h>
42 #include <vm/page.h>
43 #include <sys/pte.h>
44 #include <sys/systm.h>
45 #include <sys/mman.h>
46 #include <sys/sysmacros.h>
47 #include <sys/machparam.h>
48 #include <sys/vtrace.h>
49 #include <sys/kmem.h>
50 #include <sys/mmu.h>
51 #include <sys/cmn_err.h>
52 #include <sys/cpu.h>
53 #include <sys/cpuvar.h>
54 #include <sys/debug.h>
55 #include <sys/lgrp.h>
56 #include <sys/archsystm.h>
57 #include <sys/machsystm.h>
58 #include <sys/vmsystm.h>
59 #include <vm/as.h>
60 #include <vm/seg.h>
61 #include <vm/seg_kp.h>
62 #include <vm/seg_kmem.h>
63 #include <vm/seg_kpm.h>
64 #include <vm/rm.h>
65 #include <sys/t_lock.h>
66 #include <sys/obpdefs.h>
67 #include <sys/vm_machparam.h>
68 #include <sys/var.h>
69 #include <sys/trap.h>
70 #include <sys/machtrap.h>
71 #include <sys/scb.h>
72 #include <sys/bitmap.h>
73 #include <sys/machlock.h>
74 #include <sys/membar.h>
75 #include <sys/atomic.h>
76 #include <sys/cpu_module.h>
77 #include <sys/prom_debug.h>
78 #include <sys/ksynch.h>
79 #include <sys/mem_config.h>
80 #include <sys/mem_cage.h>
81 #include <vm/vm_dep.h>
82 #include <vm/xhat_sfmmu.h>
83 #include <sys/fpu/fpusystm.h>
84 #include <vm/mach_kpm.h>
85 #include <sys/callb.h>
86 
87 #ifdef	DEBUG
88 #define	SFMMU_VALIDATE_HMERID(hat, rid, saddr, len)			\
89 	if (SFMMU_IS_SHMERID_VALID(rid)) {				\
90 		caddr_t _eaddr = (saddr) + (len);			\
91 		sf_srd_t *_srdp;					\
92 		sf_region_t *_rgnp;					\
93 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			\
94 		ASSERT(SF_RGNMAP_TEST(hat->sfmmu_hmeregion_map, rid));	\
95 		ASSERT((hat) != ksfmmup);				\
96 		_srdp = (hat)->sfmmu_srdp;				\
97 		ASSERT(_srdp != NULL);					\
98 		ASSERT(_srdp->srd_refcnt != 0);				\
99 		_rgnp = _srdp->srd_hmergnp[(rid)];			\
100 		ASSERT(_rgnp != NULL && _rgnp->rgn_id == rid);		\
101 		ASSERT(_rgnp->rgn_refcnt != 0);				\
102 		ASSERT(!(_rgnp->rgn_flags & SFMMU_REGION_FREE));	\
103 		ASSERT((_rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	\
104 		    SFMMU_REGION_HME);					\
105 		ASSERT((saddr) >= _rgnp->rgn_saddr);			\
106 		ASSERT((saddr) < _rgnp->rgn_saddr + _rgnp->rgn_size);	\
107 		ASSERT(_eaddr > _rgnp->rgn_saddr);			\
108 		ASSERT(_eaddr <= _rgnp->rgn_saddr + _rgnp->rgn_size);	\
109 	}
110 
111 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid) 	 	 \
112 {						 			 \
113 		caddr_t _hsva;						 \
114 		caddr_t _heva;						 \
115 		caddr_t _rsva;					 	 \
116 		caddr_t _reva;					 	 \
117 		int	_ttesz = get_hblk_ttesz(hmeblkp);		 \
118 		int	_flagtte;					 \
119 		ASSERT((srdp)->srd_refcnt != 0);			 \
120 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			 \
121 		ASSERT((rgnp)->rgn_id == rid);				 \
122 		ASSERT(!((rgnp)->rgn_flags & SFMMU_REGION_FREE));	 \
123 		ASSERT(((rgnp)->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	 \
124 		    SFMMU_REGION_HME);					 \
125 		ASSERT(_ttesz <= (rgnp)->rgn_pgszc);			 \
126 		_hsva = (caddr_t)get_hblk_base(hmeblkp);		 \
127 		_heva = get_hblk_endaddr(hmeblkp);			 \
128 		_rsva = (caddr_t)P2ALIGN(				 \
129 		    (uintptr_t)(rgnp)->rgn_saddr, HBLK_MIN_BYTES);	 \
130 		_reva = (caddr_t)P2ROUNDUP(				 \
131 		    (uintptr_t)((rgnp)->rgn_saddr + (rgnp)->rgn_size),	 \
132 		    HBLK_MIN_BYTES);					 \
133 		ASSERT(_hsva >= _rsva);				 	 \
134 		ASSERT(_hsva < _reva);				 	 \
135 		ASSERT(_heva > _rsva);				 	 \
136 		ASSERT(_heva <= _reva);				 	 \
137 		_flagtte = (_ttesz < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ :  \
138 			_ttesz;						 \
139 		ASSERT(rgnp->rgn_hmeflags & (0x1 << _flagtte));		 \
140 }
141 
142 #else /* DEBUG */
143 #define	SFMMU_VALIDATE_HMERID(hat, rid, addr, len)
144 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid)
145 #endif /* DEBUG */
146 
147 #if defined(SF_ERRATA_57)
148 extern caddr_t errata57_limit;
149 #endif
150 
151 #define	HME8BLK_SZ_RND		((roundup(HME8BLK_SZ, sizeof (int64_t))) /  \
152 				(sizeof (int64_t)))
153 #define	HBLK_RESERVE		((struct hme_blk *)hblk_reserve)
154 
155 #define	HBLK_RESERVE_CNT	128
156 #define	HBLK_RESERVE_MIN	20
157 
158 static struct hme_blk		*freehblkp;
159 static kmutex_t			freehblkp_lock;
160 static int			freehblkcnt;
161 
162 static int64_t			hblk_reserve[HME8BLK_SZ_RND];
163 static kmutex_t			hblk_reserve_lock;
164 static kthread_t		*hblk_reserve_thread;
165 
166 static nucleus_hblk8_info_t	nucleus_hblk8;
167 static nucleus_hblk1_info_t	nucleus_hblk1;
168 
169 /*
170  * Data to manage per-cpu hmeblk pending queues, hmeblks are queued here
171  * after the initial phase of removing an hmeblk from the hash chain, see
172  * the detailed comment in sfmmu_hblk_hash_rm() for further details.
173  */
174 static cpu_hme_pend_t		*cpu_hme_pend;
175 static uint_t			cpu_hme_pend_thresh;
176 /*
177  * SFMMU specific hat functions
178  */
179 void	hat_pagecachectl(struct page *, int);
180 
181 /* flags for hat_pagecachectl */
182 #define	HAT_CACHE	0x1
183 #define	HAT_UNCACHE	0x2
184 #define	HAT_TMPNC	0x4
185 
186 /*
187  * Flag to allow the creation of non-cacheable translations
188  * to system memory. It is off by default. At the moment this
189  * flag is used by the ecache error injector. The error injector
190  * will turn it on when creating such a translation then shut it
191  * off when it's finished.
192  */
193 
194 int	sfmmu_allow_nc_trans = 0;
195 
196 /*
197  * Flag to disable large page support.
198  * 	value of 1 => disable all large pages.
199  *	bits 1, 2, and 3 are to disable 64K, 512K and 4M pages respectively.
200  *
201  * For example, use the value 0x4 to disable 512K pages.
202  *
203  */
204 #define	LARGE_PAGES_OFF		0x1
205 
206 /*
207  * The disable_large_pages and disable_ism_large_pages variables control
208  * hat_memload_array and the page sizes to be used by ISM and the kernel.
209  *
210  * The disable_auto_data_large_pages and disable_auto_text_large_pages variables
211  * are only used to control which OOB pages to use at upper VM segment creation
212  * time, and are set in hat_init_pagesizes and used in the map_pgsz* routines.
213  * Their values may come from platform or CPU specific code to disable page
214  * sizes that should not be used.
215  *
216  * WARNING: 512K pages are currently not supported for ISM/DISM.
217  */
218 uint_t	disable_large_pages = 0;
219 uint_t	disable_ism_large_pages = (1 << TTE512K);
220 uint_t	disable_auto_data_large_pages = 0;
221 uint_t	disable_auto_text_large_pages = 0;
222 
223 /*
224  * Private sfmmu data structures for hat management
225  */
226 static struct kmem_cache *sfmmuid_cache;
227 static struct kmem_cache *mmuctxdom_cache;
228 
229 /*
230  * Private sfmmu data structures for tsb management
231  */
232 static struct kmem_cache *sfmmu_tsbinfo_cache;
233 static struct kmem_cache *sfmmu_tsb8k_cache;
234 static struct kmem_cache *sfmmu_tsb_cache[NLGRPS_MAX];
235 static vmem_t *kmem_bigtsb_arena;
236 static vmem_t *kmem_tsb_arena;
237 
238 /*
239  * sfmmu static variables for hmeblk resource management.
240  */
241 static vmem_t *hat_memload1_arena; /* HAT translation arena for sfmmu1_cache */
242 static struct kmem_cache *sfmmu8_cache;
243 static struct kmem_cache *sfmmu1_cache;
244 static struct kmem_cache *pa_hment_cache;
245 
246 static kmutex_t 	ism_mlist_lock;	/* mutex for ism mapping list */
247 /*
248  * private data for ism
249  */
250 static struct kmem_cache *ism_blk_cache;
251 static struct kmem_cache *ism_ment_cache;
252 #define	ISMID_STARTADDR	NULL
253 
254 /*
255  * Region management data structures and function declarations.
256  */
257 
258 static void	sfmmu_leave_srd(sfmmu_t *);
259 static int	sfmmu_srdcache_constructor(void *, void *, int);
260 static void	sfmmu_srdcache_destructor(void *, void *);
261 static int	sfmmu_rgncache_constructor(void *, void *, int);
262 static void	sfmmu_rgncache_destructor(void *, void *);
263 static int	sfrgnmap_isnull(sf_region_map_t *);
264 static int	sfhmergnmap_isnull(sf_hmeregion_map_t *);
265 static int	sfmmu_scdcache_constructor(void *, void *, int);
266 static void	sfmmu_scdcache_destructor(void *, void *);
267 static void	sfmmu_rgn_cb_noop(caddr_t, caddr_t, caddr_t,
268     size_t, void *, u_offset_t);
269 
270 static uint_t srd_hashmask = SFMMU_MAX_SRD_BUCKETS - 1;
271 static sf_srd_bucket_t *srd_buckets;
272 static struct kmem_cache *srd_cache;
273 static uint_t srd_rgn_hashmask = SFMMU_MAX_REGION_BUCKETS - 1;
274 static struct kmem_cache *region_cache;
275 static struct kmem_cache *scd_cache;
276 
277 #ifdef sun4v
278 int use_bigtsb_arena = 1;
279 #else
280 int use_bigtsb_arena = 0;
281 #endif
282 
283 /* External /etc/system tunable, for turning on&off the shctx support */
284 int disable_shctx = 0;
285 /* Internal variable, set by MD if the HW supports shctx feature */
286 int shctx_on = 0;
287 
288 #ifdef DEBUG
289 static void check_scd_sfmmu_list(sfmmu_t **, sfmmu_t *, int);
290 #endif
291 static void sfmmu_to_scd_list(sfmmu_t **, sfmmu_t *);
292 static void sfmmu_from_scd_list(sfmmu_t **, sfmmu_t *);
293 
294 static sf_scd_t *sfmmu_alloc_scd(sf_srd_t *, sf_region_map_t *);
295 static void sfmmu_find_scd(sfmmu_t *);
296 static void sfmmu_join_scd(sf_scd_t *, sfmmu_t *);
297 static void sfmmu_finish_join_scd(sfmmu_t *);
298 static void sfmmu_leave_scd(sfmmu_t *, uchar_t);
299 static void sfmmu_destroy_scd(sf_srd_t *, sf_scd_t *, sf_region_map_t *);
300 static int sfmmu_alloc_scd_tsbs(sf_srd_t *, sf_scd_t *);
301 static void sfmmu_free_scd_tsbs(sfmmu_t *);
302 static void sfmmu_tsb_inv_ctx(sfmmu_t *);
303 static int find_ism_rid(sfmmu_t *, sfmmu_t *, caddr_t, uint_t *);
304 static void sfmmu_ism_hatflags(sfmmu_t *, int);
305 static int sfmmu_srd_lock_held(sf_srd_t *);
306 static void sfmmu_remove_scd(sf_scd_t **, sf_scd_t *);
307 static void sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *);
308 static void sfmmu_link_scd_to_regions(sf_srd_t *, sf_scd_t *);
309 static void sfmmu_unlink_scd_from_regions(sf_srd_t *, sf_scd_t *);
310 static void sfmmu_link_to_hmeregion(sfmmu_t *, sf_region_t *);
311 static void sfmmu_unlink_from_hmeregion(sfmmu_t *, sf_region_t *);
312 
313 /*
314  * ``hat_lock'' is a hashed mutex lock for protecting sfmmu TSB lists,
315  * HAT flags, synchronizing TLB/TSB coherency, and context management.
316  * The lock is hashed on the sfmmup since the case where we need to lock
317  * all processes is rare but does occur (e.g. we need to unload a shared
318  * mapping from all processes using the mapping).  We have a lot of buckets,
319  * and each slab of sfmmu_t's can use about a quarter of them, giving us
320  * a fairly good distribution without wasting too much space and overhead
321  * when we have to grab them all.
322  */
323 #define	SFMMU_NUM_LOCK	128		/* must be power of two */
324 hatlock_t	hat_lock[SFMMU_NUM_LOCK];
325 
326 /*
327  * Hash algorithm optimized for a small number of slabs.
328  *  7 is (highbit((sizeof sfmmu_t)) - 1)
329  * This hash algorithm is based upon the knowledge that sfmmu_t's come from a
330  * kmem_cache, and thus they will be sequential within that cache.  In
331  * addition, each new slab will have a different "color" up to cache_maxcolor
332  * which will skew the hashing for each successive slab which is allocated.
333  * If the size of sfmmu_t changed to a larger size, this algorithm may need
334  * to be revisited.
335  */
336 #define	TSB_HASH_SHIFT_BITS (7)
337 #define	PTR_HASH(x) ((uintptr_t)x >> TSB_HASH_SHIFT_BITS)
338 
339 #ifdef DEBUG
340 int tsb_hash_debug = 0;
341 #define	TSB_HASH(sfmmup)	\
342 	(tsb_hash_debug ? &hat_lock[0] : \
343 	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)])
344 #else	/* DEBUG */
345 #define	TSB_HASH(sfmmup)	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)]
346 #endif	/* DEBUG */
347 
348 
349 /* sfmmu_replace_tsb() return codes. */
350 typedef enum tsb_replace_rc {
351 	TSB_SUCCESS,
352 	TSB_ALLOCFAIL,
353 	TSB_LOSTRACE,
354 	TSB_ALREADY_SWAPPED,
355 	TSB_CANTGROW
356 } tsb_replace_rc_t;
357 
358 /*
359  * Flags for TSB allocation routines.
360  */
361 #define	TSB_ALLOC	0x01
362 #define	TSB_FORCEALLOC	0x02
363 #define	TSB_GROW	0x04
364 #define	TSB_SHRINK	0x08
365 #define	TSB_SWAPIN	0x10
366 
367 /*
368  * Support for HAT callbacks.
369  */
370 #define	SFMMU_MAX_RELOC_CALLBACKS	10
371 int sfmmu_max_cb_id = SFMMU_MAX_RELOC_CALLBACKS;
372 static id_t sfmmu_cb_nextid = 0;
373 static id_t sfmmu_tsb_cb_id;
374 struct sfmmu_callback *sfmmu_cb_table;
375 
376 /*
377  * Kernel page relocation is enabled by default for non-caged
378  * kernel pages.  This has little effect unless segkmem_reloc is
379  * set, since by default kernel memory comes from inside the
380  * kernel cage.
381  */
382 int hat_kpr_enabled = 1;
383 
384 kmutex_t	kpr_mutex;
385 kmutex_t	kpr_suspendlock;
386 kthread_t	*kreloc_thread;
387 
388 /*
389  * Enable VA->PA translation sanity checking on DEBUG kernels.
390  * Disabled by default.  This is incompatible with some
391  * drivers (error injector, RSM) so if it breaks you get
392  * to keep both pieces.
393  */
394 int hat_check_vtop = 0;
395 
396 /*
397  * Private sfmmu routines (prototypes)
398  */
399 static struct hme_blk *sfmmu_shadow_hcreate(sfmmu_t *, caddr_t, int, uint_t);
400 static struct 	hme_blk *sfmmu_hblk_alloc(sfmmu_t *, caddr_t,
401 			struct hmehash_bucket *, uint_t, hmeblk_tag, uint_t,
402 			uint_t);
403 static caddr_t	sfmmu_hblk_unload(struct hat *, struct hme_blk *, caddr_t,
404 			caddr_t, demap_range_t *, uint_t);
405 static caddr_t	sfmmu_hblk_sync(struct hat *, struct hme_blk *, caddr_t,
406 			caddr_t, int);
407 static void	sfmmu_hblk_free(struct hme_blk **);
408 static void	sfmmu_hblks_list_purge(struct hme_blk **, int);
409 static uint_t	sfmmu_get_free_hblk(struct hme_blk **, uint_t);
410 static uint_t	sfmmu_put_free_hblk(struct hme_blk *, uint_t);
411 static struct hme_blk *sfmmu_hblk_steal(int);
412 static int	sfmmu_steal_this_hblk(struct hmehash_bucket *,
413 			struct hme_blk *, uint64_t, struct hme_blk *);
414 static caddr_t	sfmmu_hblk_unlock(struct hme_blk *, caddr_t, caddr_t);
415 
416 static void	hat_do_memload_array(struct hat *, caddr_t, size_t,
417 		    struct page **, uint_t, uint_t, uint_t);
418 static void	hat_do_memload(struct hat *, caddr_t, struct page *,
419 		    uint_t, uint_t, uint_t);
420 static void	sfmmu_memload_batchsmall(struct hat *, caddr_t, page_t **,
421 		    uint_t, uint_t, pgcnt_t, uint_t);
422 void		sfmmu_tteload(struct hat *, tte_t *, caddr_t, page_t *,
423 			uint_t);
424 static int	sfmmu_tteload_array(sfmmu_t *, tte_t *, caddr_t, page_t **,
425 			uint_t, uint_t);
426 static struct hmehash_bucket *sfmmu_tteload_acquire_hashbucket(sfmmu_t *,
427 					caddr_t, int, uint_t);
428 static struct hme_blk *sfmmu_tteload_find_hmeblk(sfmmu_t *,
429 			struct hmehash_bucket *, caddr_t, uint_t, uint_t,
430 			uint_t);
431 static int	sfmmu_tteload_addentry(sfmmu_t *, struct hme_blk *, tte_t *,
432 			caddr_t, page_t **, uint_t, uint_t);
433 static void	sfmmu_tteload_release_hashbucket(struct hmehash_bucket *);
434 
435 static int	sfmmu_pagearray_setup(caddr_t, page_t **, tte_t *, int);
436 static pfn_t	sfmmu_uvatopfn(caddr_t, sfmmu_t *, tte_t *);
437 void		sfmmu_memtte(tte_t *, pfn_t, uint_t, int);
438 #ifdef VAC
439 static void	sfmmu_vac_conflict(struct hat *, caddr_t, page_t *);
440 static int	sfmmu_vacconflict_array(caddr_t, page_t *, int *);
441 int	tst_tnc(page_t *pp, pgcnt_t);
442 void	conv_tnc(page_t *pp, int);
443 #endif
444 
445 static void	sfmmu_get_ctx(sfmmu_t *);
446 static void	sfmmu_free_sfmmu(sfmmu_t *);
447 
448 static void	sfmmu_ttesync(struct hat *, caddr_t, tte_t *, page_t *);
449 static void	sfmmu_chgattr(struct hat *, caddr_t, size_t, uint_t, int);
450 
451 cpuset_t	sfmmu_pageunload(page_t *, struct sf_hment *, int);
452 static void	hat_pagereload(struct page *, struct page *);
453 static cpuset_t	sfmmu_pagesync(page_t *, struct sf_hment *, uint_t);
454 #ifdef VAC
455 void	sfmmu_page_cache_array(page_t *, int, int, pgcnt_t);
456 static void	sfmmu_page_cache(page_t *, int, int, int);
457 #endif
458 
459 cpuset_t	sfmmu_rgntlb_demap(caddr_t, sf_region_t *,
460     struct hme_blk *, int);
461 static void	sfmmu_tlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
462 			pfn_t, int, int, int, int);
463 static void	sfmmu_ismtlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
464 			pfn_t, int);
465 static void	sfmmu_tlb_demap(caddr_t, sfmmu_t *, struct hme_blk *, int, int);
466 static void	sfmmu_tlb_range_demap(demap_range_t *);
467 static void	sfmmu_invalidate_ctx(sfmmu_t *);
468 static void	sfmmu_sync_mmustate(sfmmu_t *);
469 
470 static void 	sfmmu_tsbinfo_setup_phys(struct tsb_info *, pfn_t);
471 static int	sfmmu_tsbinfo_alloc(struct tsb_info **, int, int, uint_t,
472 			sfmmu_t *);
473 static void	sfmmu_tsb_free(struct tsb_info *);
474 static void	sfmmu_tsbinfo_free(struct tsb_info *);
475 static int	sfmmu_init_tsbinfo(struct tsb_info *, int, int, uint_t,
476 			sfmmu_t *);
477 static void	sfmmu_tsb_chk_reloc(sfmmu_t *, hatlock_t *);
478 static void	sfmmu_tsb_swapin(sfmmu_t *, hatlock_t *);
479 static int	sfmmu_select_tsb_szc(pgcnt_t);
480 static void	sfmmu_mod_tsb(sfmmu_t *, caddr_t, tte_t *, int);
481 #define		sfmmu_load_tsb(sfmmup, vaddr, tte, szc) \
482 	sfmmu_mod_tsb(sfmmup, vaddr, tte, szc)
483 #define		sfmmu_unload_tsb(sfmmup, vaddr, szc)    \
484 	sfmmu_mod_tsb(sfmmup, vaddr, NULL, szc)
485 static void	sfmmu_copy_tsb(struct tsb_info *, struct tsb_info *);
486 static tsb_replace_rc_t sfmmu_replace_tsb(sfmmu_t *, struct tsb_info *, uint_t,
487     hatlock_t *, uint_t);
488 static void	sfmmu_size_tsb(sfmmu_t *, int, uint64_t, uint64_t, int);
489 
490 #ifdef VAC
491 void	sfmmu_cache_flush(pfn_t, int);
492 void	sfmmu_cache_flushcolor(int, pfn_t);
493 #endif
494 static caddr_t	sfmmu_hblk_chgattr(sfmmu_t *, struct hme_blk *, caddr_t,
495 			caddr_t, demap_range_t *, uint_t, int);
496 
497 static uint64_t	sfmmu_vtop_attr(uint_t, int mode, tte_t *);
498 static uint_t	sfmmu_ptov_attr(tte_t *);
499 static caddr_t	sfmmu_hblk_chgprot(sfmmu_t *, struct hme_blk *, caddr_t,
500 			caddr_t, demap_range_t *, uint_t);
501 static uint_t	sfmmu_vtop_prot(uint_t, uint_t *);
502 static int	sfmmu_idcache_constructor(void *, void *, int);
503 static void	sfmmu_idcache_destructor(void *, void *);
504 static int	sfmmu_hblkcache_constructor(void *, void *, int);
505 static void	sfmmu_hblkcache_destructor(void *, void *);
506 static void	sfmmu_hblkcache_reclaim(void *);
507 static void	sfmmu_shadow_hcleanup(sfmmu_t *, struct hme_blk *,
508 			struct hmehash_bucket *);
509 static void	sfmmu_hblk_hash_rm(struct hmehash_bucket *, struct hme_blk *,
510 			struct hme_blk *, struct hme_blk **, int);
511 static void	sfmmu_hblk_hash_add(struct hmehash_bucket *, struct hme_blk *,
512 			uint64_t);
513 static struct hme_blk *sfmmu_check_pending_hblks(int);
514 static void	sfmmu_free_hblks(sfmmu_t *, caddr_t, caddr_t, int);
515 static void	sfmmu_cleanup_rhblk(sf_srd_t *, caddr_t, uint_t, int);
516 static void	sfmmu_unload_hmeregion_va(sf_srd_t *, uint_t, caddr_t, caddr_t,
517 			int, caddr_t *);
518 static void	sfmmu_unload_hmeregion(sf_srd_t *, sf_region_t *);
519 
520 static void	sfmmu_rm_large_mappings(page_t *, int);
521 
522 static void	hat_lock_init(void);
523 static void	hat_kstat_init(void);
524 static int	sfmmu_kstat_percpu_update(kstat_t *ksp, int rw);
525 static void	sfmmu_set_scd_rttecnt(sf_srd_t *, sf_scd_t *);
526 static	int	sfmmu_is_rgnva(sf_srd_t *, caddr_t, ulong_t, ulong_t);
527 static void	sfmmu_check_page_sizes(sfmmu_t *, int);
528 int	fnd_mapping_sz(page_t *);
529 static void	iment_add(struct ism_ment *,  struct hat *);
530 static void	iment_sub(struct ism_ment *, struct hat *);
531 static pgcnt_t	ism_tsb_entries(sfmmu_t *, int szc);
532 extern void	sfmmu_setup_tsbinfo(sfmmu_t *);
533 extern void	sfmmu_clear_utsbinfo(void);
534 
535 static void	sfmmu_ctx_wrap_around(mmu_ctx_t *);
536 
537 extern int vpm_enable;
538 
539 /* kpm globals */
540 #ifdef	DEBUG
541 /*
542  * Enable trap level tsbmiss handling
543  */
544 int	kpm_tsbmtl = 1;
545 
546 /*
547  * Flush the TLB on kpm mapout. Note: Xcalls are used (again) for the
548  * required TLB shootdowns in this case, so handle w/ care. Off by default.
549  */
550 int	kpm_tlb_flush;
551 #endif	/* DEBUG */
552 
553 static void	*sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *, size_t, int);
554 
555 #ifdef DEBUG
556 static void	sfmmu_check_hblk_flist();
557 #endif
558 
559 /*
560  * Semi-private sfmmu data structures.  Some of them are initialize in
561  * startup or in hat_init. Some of them are private but accessed by
562  * assembly code or mach_sfmmu.c
563  */
564 struct hmehash_bucket *uhme_hash;	/* user hmeblk hash table */
565 struct hmehash_bucket *khme_hash;	/* kernel hmeblk hash table */
566 uint64_t	uhme_hash_pa;		/* PA of uhme_hash */
567 uint64_t	khme_hash_pa;		/* PA of khme_hash */
568 int 		uhmehash_num;		/* # of buckets in user hash table */
569 int 		khmehash_num;		/* # of buckets in kernel hash table */
570 
571 uint_t		max_mmu_ctxdoms = 0;	/* max context domains in the system */
572 mmu_ctx_t	**mmu_ctxs_tbl;		/* global array of context domains */
573 uint64_t	mmu_saved_gnum = 0;	/* to init incoming MMUs' gnums */
574 
575 #define	DEFAULT_NUM_CTXS_PER_MMU 8192
576 static uint_t	nctxs = DEFAULT_NUM_CTXS_PER_MMU;
577 
578 int		cache;			/* describes system cache */
579 
580 caddr_t		ktsb_base;		/* kernel 8k-indexed tsb base address */
581 uint64_t	ktsb_pbase;		/* kernel 8k-indexed tsb phys address */
582 int		ktsb_szcode;		/* kernel 8k-indexed tsb size code */
583 int		ktsb_sz;		/* kernel 8k-indexed tsb size */
584 
585 caddr_t		ktsb4m_base;		/* kernel 4m-indexed tsb base address */
586 uint64_t	ktsb4m_pbase;		/* kernel 4m-indexed tsb phys address */
587 int		ktsb4m_szcode;		/* kernel 4m-indexed tsb size code */
588 int		ktsb4m_sz;		/* kernel 4m-indexed tsb size */
589 
590 uint64_t	kpm_tsbbase;		/* kernel seg_kpm 4M TSB base address */
591 int		kpm_tsbsz;		/* kernel seg_kpm 4M TSB size code */
592 uint64_t	kpmsm_tsbbase;		/* kernel seg_kpm 8K TSB base address */
593 int		kpmsm_tsbsz;		/* kernel seg_kpm 8K TSB size code */
594 
595 #ifndef sun4v
596 int		utsb_dtlb_ttenum = -1;	/* index in TLB for utsb locked TTE */
597 int		utsb4m_dtlb_ttenum = -1; /* index in TLB for 4M TSB TTE */
598 int		dtlb_resv_ttenum;	/* index in TLB of first reserved TTE */
599 caddr_t		utsb_vabase;		/* reserved kernel virtual memory */
600 caddr_t		utsb4m_vabase;		/* for trap handler TSB accesses */
601 #endif /* sun4v */
602 uint64_t	tsb_alloc_bytes = 0;	/* bytes allocated to TSBs */
603 vmem_t		*kmem_tsb_default_arena[NLGRPS_MAX];	/* For dynamic TSBs */
604 vmem_t		*kmem_bigtsb_default_arena[NLGRPS_MAX]; /* dynamic 256M TSBs */
605 
606 /*
607  * Size to use for TSB slabs.  Future platforms that support page sizes
608  * larger than 4M may wish to change these values, and provide their own
609  * assembly macros for building and decoding the TSB base register contents.
610  * Note disable_large_pages will override the value set here.
611  */
612 static	uint_t tsb_slab_ttesz = TTE4M;
613 size_t	tsb_slab_size = MMU_PAGESIZE4M;
614 uint_t	tsb_slab_shift = MMU_PAGESHIFT4M;
615 /* PFN mask for TTE */
616 size_t	tsb_slab_mask = MMU_PAGEOFFSET4M >> MMU_PAGESHIFT;
617 
618 /*
619  * Size to use for TSB slabs.  These are used only when 256M tsb arenas
620  * exist.
621  */
622 static uint_t	bigtsb_slab_ttesz = TTE256M;
623 static size_t	bigtsb_slab_size = MMU_PAGESIZE256M;
624 static uint_t	bigtsb_slab_shift = MMU_PAGESHIFT256M;
625 /* 256M page alignment for 8K pfn */
626 static size_t	bigtsb_slab_mask = MMU_PAGEOFFSET256M >> MMU_PAGESHIFT;
627 
628 /* largest TSB size to grow to, will be smaller on smaller memory systems */
629 static int	tsb_max_growsize = 0;
630 
631 /*
632  * Tunable parameters dealing with TSB policies.
633  */
634 
635 /*
636  * This undocumented tunable forces all 8K TSBs to be allocated from
637  * the kernel heap rather than from the kmem_tsb_default_arena arenas.
638  */
639 #ifdef	DEBUG
640 int	tsb_forceheap = 0;
641 #endif	/* DEBUG */
642 
643 /*
644  * Decide whether to use per-lgroup arenas, or one global set of
645  * TSB arenas.  The default is not to break up per-lgroup, since
646  * most platforms don't recognize any tangible benefit from it.
647  */
648 int	tsb_lgrp_affinity = 0;
649 
650 /*
651  * Used for growing the TSB based on the process RSS.
652  * tsb_rss_factor is based on the smallest TSB, and is
653  * shifted by the TSB size to determine if we need to grow.
654  * The default will grow the TSB if the number of TTEs for
655  * this page size exceeds 75% of the number of TSB entries,
656  * which should _almost_ eliminate all conflict misses
657  * (at the expense of using up lots and lots of memory).
658  */
659 #define	TSB_RSS_FACTOR		(TSB_ENTRIES(TSB_MIN_SZCODE) * 0.75)
660 #define	SFMMU_RSS_TSBSIZE(tsbszc)	(tsb_rss_factor << tsbszc)
661 #define	SELECT_TSB_SIZECODE(pgcnt) ( \
662 	(enable_tsb_rss_sizing)? sfmmu_select_tsb_szc(pgcnt) : \
663 	default_tsb_size)
664 #define	TSB_OK_SHRINK()	\
665 	(tsb_alloc_bytes > tsb_alloc_hiwater || freemem < desfree)
666 #define	TSB_OK_GROW()	\
667 	(tsb_alloc_bytes < tsb_alloc_hiwater && freemem > desfree)
668 
669 int	enable_tsb_rss_sizing = 1;
670 int	tsb_rss_factor	= (int)TSB_RSS_FACTOR;
671 
672 /* which TSB size code to use for new address spaces or if rss sizing off */
673 int default_tsb_size = TSB_8K_SZCODE;
674 
675 static uint64_t tsb_alloc_hiwater; /* limit TSB reserved memory */
676 uint64_t tsb_alloc_hiwater_factor; /* tsb_alloc_hiwater = physmem / this */
677 #define	TSB_ALLOC_HIWATER_FACTOR_DEFAULT	32
678 
679 #ifdef DEBUG
680 static int tsb_random_size = 0;	/* set to 1 to test random tsb sizes on alloc */
681 static int tsb_grow_stress = 0;	/* if set to 1, keep replacing TSB w/ random */
682 static int tsb_alloc_mtbf = 0;	/* fail allocation every n attempts */
683 static int tsb_alloc_fail_mtbf = 0;
684 static int tsb_alloc_count = 0;
685 #endif /* DEBUG */
686 
687 /* if set to 1, will remap valid TTEs when growing TSB. */
688 int tsb_remap_ttes = 1;
689 
690 /*
691  * If we have more than this many mappings, allocate a second TSB.
692  * This default is chosen because the I/D fully associative TLBs are
693  * assumed to have at least 8 available entries. Platforms with a
694  * larger fully-associative TLB could probably override the default.
695  */
696 
697 #ifdef sun4v
698 int tsb_sectsb_threshold = 0;
699 #else
700 int tsb_sectsb_threshold = 8;
701 #endif
702 
703 /*
704  * kstat data
705  */
706 struct sfmmu_global_stat sfmmu_global_stat;
707 struct sfmmu_tsbsize_stat sfmmu_tsbsize_stat;
708 
709 /*
710  * Global data
711  */
712 sfmmu_t 	*ksfmmup;		/* kernel's hat id */
713 
714 #ifdef DEBUG
715 static void	chk_tte(tte_t *, tte_t *, tte_t *, struct hme_blk *);
716 #endif
717 
718 /* sfmmu locking operations */
719 static kmutex_t *sfmmu_mlspl_enter(struct page *, int);
720 static int	sfmmu_mlspl_held(struct page *, int);
721 
722 kmutex_t *sfmmu_page_enter(page_t *);
723 void	sfmmu_page_exit(kmutex_t *);
724 int	sfmmu_page_spl_held(struct page *);
725 
726 /* sfmmu internal locking operations - accessed directly */
727 static void	sfmmu_mlist_reloc_enter(page_t *, page_t *,
728 				kmutex_t **, kmutex_t **);
729 static void	sfmmu_mlist_reloc_exit(kmutex_t *, kmutex_t *);
730 static hatlock_t *
731 		sfmmu_hat_enter(sfmmu_t *);
732 static hatlock_t *
733 		sfmmu_hat_tryenter(sfmmu_t *);
734 static void	sfmmu_hat_exit(hatlock_t *);
735 static void	sfmmu_hat_lock_all(void);
736 static void	sfmmu_hat_unlock_all(void);
737 static void	sfmmu_ismhat_enter(sfmmu_t *, int);
738 static void	sfmmu_ismhat_exit(sfmmu_t *, int);
739 
740 /*
741  * Array of mutexes protecting a page's mapping list and p_nrm field.
742  *
743  * The hash function looks complicated, but is made up so that:
744  *
745  * "pp" not shifted, so adjacent pp values will hash to different cache lines
746  *  (8 byte alignment * 8 bytes/mutes == 64 byte coherency subblock)
747  *
748  * "pp" >> mml_shift, incorporates more source bits into the hash result
749  *
750  *  "& (mml_table_size - 1), should be faster than using remainder "%"
751  *
752  * Hopefully, mml_table, mml_table_size and mml_shift are all in the same
753  * cacheline, since they get declared next to each other below. We'll trust
754  * ld not to do something random.
755  */
756 #ifdef	DEBUG
757 int mlist_hash_debug = 0;
758 #define	MLIST_HASH(pp)	(mlist_hash_debug ? &mml_table[0] : \
759 	&mml_table[((uintptr_t)(pp) + \
760 	((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)])
761 #else	/* !DEBUG */
762 #define	MLIST_HASH(pp)   &mml_table[ \
763 	((uintptr_t)(pp) + ((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)]
764 #endif	/* !DEBUG */
765 
766 kmutex_t		*mml_table;
767 uint_t			mml_table_sz;	/* must be a power of 2 */
768 uint_t			mml_shift;	/* log2(mml_table_sz) + 3 for align */
769 
770 kpm_hlk_t	*kpmp_table;
771 uint_t		kpmp_table_sz;	/* must be a power of 2 */
772 uchar_t		kpmp_shift;
773 
774 kpm_shlk_t	*kpmp_stable;
775 uint_t		kpmp_stable_sz;	/* must be a power of 2 */
776 
777 /*
778  * SPL_HASH was improved to avoid false cache line sharing
779  */
780 #define	SPL_TABLE_SIZE	128
781 #define	SPL_MASK	(SPL_TABLE_SIZE - 1)
782 #define	SPL_SHIFT	7		/* log2(SPL_TABLE_SIZE) */
783 
784 #define	SPL_INDEX(pp) \
785 	((((uintptr_t)(pp) >> SPL_SHIFT) ^ \
786 	((uintptr_t)(pp) >> (SPL_SHIFT << 1))) & \
787 	(SPL_TABLE_SIZE - 1))
788 
789 #define	SPL_HASH(pp)    \
790 	(&sfmmu_page_lock[SPL_INDEX(pp) & SPL_MASK].pad_mutex)
791 
792 static	pad_mutex_t	sfmmu_page_lock[SPL_TABLE_SIZE];
793 
794 
795 /*
796  * hat_unload_callback() will group together callbacks in order
797  * to avoid xt_sync() calls.  This is the maximum size of the group.
798  */
799 #define	MAX_CB_ADDR	32
800 
801 tte_t	hw_tte;
802 static ulong_t sfmmu_dmr_maxbit = DMR_MAXBIT;
803 
804 static char	*mmu_ctx_kstat_names[] = {
805 	"mmu_ctx_tsb_exceptions",
806 	"mmu_ctx_tsb_raise_exception",
807 	"mmu_ctx_wrap_around",
808 };
809 
810 /*
811  * Wrapper for vmem_xalloc since vmem_create only allows limited
812  * parameters for vm_source_alloc functions.  This function allows us
813  * to specify alignment consistent with the size of the object being
814  * allocated.
815  */
816 static void *
817 sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *vmp, size_t size, int vmflag)
818 {
819 	return (vmem_xalloc(vmp, size, size, 0, 0, NULL, NULL, vmflag));
820 }
821 
822 /* Common code for setting tsb_alloc_hiwater. */
823 #define	SFMMU_SET_TSB_ALLOC_HIWATER(pages)	tsb_alloc_hiwater = \
824 		ptob(pages) / tsb_alloc_hiwater_factor
825 
826 /*
827  * Set tsb_max_growsize to allow at most all of physical memory to be mapped by
828  * a single TSB.  physmem is the number of physical pages so we need physmem 8K
829  * TTEs to represent all those physical pages.  We round this up by using
830  * 1<<highbit().  To figure out which size code to use, remember that the size
831  * code is just an amount to shift the smallest TSB size to get the size of
832  * this TSB.  So we subtract that size, TSB_START_SIZE, from highbit() (or
833  * highbit() - 1) to get the size code for the smallest TSB that can represent
834  * all of physical memory, while erring on the side of too much.
835  *
836  * Restrict tsb_max_growsize to make sure that:
837  *	1) TSBs can't grow larger than the TSB slab size
838  *	2) TSBs can't grow larger than UTSB_MAX_SZCODE.
839  */
840 #define	SFMMU_SET_TSB_MAX_GROWSIZE(pages) {				\
841 	int	_i, _szc, _slabszc, _tsbszc;				\
842 									\
843 	_i = highbit(pages);						\
844 	if ((1 << (_i - 1)) == (pages))					\
845 		_i--;		/* 2^n case, round down */              \
846 	_szc = _i - TSB_START_SIZE;					\
847 	_slabszc = bigtsb_slab_shift - (TSB_START_SIZE + TSB_ENTRY_SHIFT); \
848 	_tsbszc = MIN(_szc, _slabszc);                                  \
849 	tsb_max_growsize = MIN(_tsbszc, UTSB_MAX_SZCODE);               \
850 }
851 
852 /*
853  * Given a pointer to an sfmmu and a TTE size code, return a pointer to the
854  * tsb_info which handles that TTE size.
855  */
856 #define	SFMMU_GET_TSBINFO(tsbinfop, sfmmup, tte_szc) {			\
857 	(tsbinfop) = (sfmmup)->sfmmu_tsb;				\
858 	ASSERT(((tsbinfop)->tsb_flags & TSB_SHAREDCTX) ||		\
859 	    sfmmu_hat_lock_held(sfmmup));				\
860 	if ((tte_szc) >= TTE4M)	{					\
861 		ASSERT((tsbinfop) != NULL);				\
862 		(tsbinfop) = (tsbinfop)->tsb_next;			\
863 	}								\
864 }
865 
866 /*
867  * Macro to use to unload entries from the TSB.
868  * It has knowledge of which page sizes get replicated in the TSB
869  * and will call the appropriate unload routine for the appropriate size.
870  */
871 #define	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, ismhat)		\
872 {									\
873 	int ttesz = get_hblk_ttesz(hmeblkp);				\
874 	if (ttesz == TTE8K || ttesz == TTE4M) {				\
875 		sfmmu_unload_tsb(sfmmup, addr, ttesz);			\
876 	} else {							\
877 		caddr_t sva = ismhat ? addr : 				\
878 		    (caddr_t)get_hblk_base(hmeblkp);			\
879 		caddr_t eva = sva + get_hblk_span(hmeblkp);		\
880 		ASSERT(addr >= sva && addr < eva);			\
881 		sfmmu_unload_tsb_range(sfmmup, sva, eva, ttesz);	\
882 	}								\
883 }
884 
885 
886 /* Update tsb_alloc_hiwater after memory is configured. */
887 /*ARGSUSED*/
888 static void
889 sfmmu_update_post_add(void *arg, pgcnt_t delta_pages)
890 {
891 	/* Assumes physmem has already been updated. */
892 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
893 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
894 }
895 
896 /*
897  * Update tsb_alloc_hiwater before memory is deleted.  We'll do nothing here
898  * and update tsb_alloc_hiwater and tsb_max_growsize after the memory is
899  * deleted.
900  */
901 /*ARGSUSED*/
902 static int
903 sfmmu_update_pre_del(void *arg, pgcnt_t delta_pages)
904 {
905 	return (0);
906 }
907 
908 /* Update tsb_alloc_hiwater after memory fails to be unconfigured. */
909 /*ARGSUSED*/
910 static void
911 sfmmu_update_post_del(void *arg, pgcnt_t delta_pages, int cancelled)
912 {
913 	/*
914 	 * Whether the delete was cancelled or not, just go ahead and update
915 	 * tsb_alloc_hiwater and tsb_max_growsize.
916 	 */
917 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
918 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
919 }
920 
921 static kphysm_setup_vector_t sfmmu_update_vec = {
922 	KPHYSM_SETUP_VECTOR_VERSION,	/* version */
923 	sfmmu_update_post_add,		/* post_add */
924 	sfmmu_update_pre_del,		/* pre_del */
925 	sfmmu_update_post_del		/* post_del */
926 };
927 
928 
929 /*
930  * HME_BLK HASH PRIMITIVES
931  */
932 
933 /*
934  * Enter a hme on the mapping list for page pp.
935  * When large pages are more prevalent in the system we might want to
936  * keep the mapping list in ascending order by the hment size. For now,
937  * small pages are more frequent, so don't slow it down.
938  */
939 #define	HME_ADD(hme, pp)					\
940 {								\
941 	ASSERT(sfmmu_mlist_held(pp));				\
942 								\
943 	hme->hme_prev = NULL;					\
944 	hme->hme_next = pp->p_mapping;				\
945 	hme->hme_page = pp;					\
946 	if (pp->p_mapping) {					\
947 		((struct sf_hment *)(pp->p_mapping))->hme_prev = hme;\
948 		ASSERT(pp->p_share > 0);			\
949 	} else  {						\
950 		/* EMPTY */					\
951 		ASSERT(pp->p_share == 0);			\
952 	}							\
953 	pp->p_mapping = hme;					\
954 	pp->p_share++;						\
955 }
956 
957 /*
958  * Enter a hme on the mapping list for page pp.
959  * If we are unmapping a large translation, we need to make sure that the
960  * change is reflect in the corresponding bit of the p_index field.
961  */
962 #define	HME_SUB(hme, pp)					\
963 {								\
964 	ASSERT(sfmmu_mlist_held(pp));				\
965 	ASSERT(hme->hme_page == pp || IS_PAHME(hme));		\
966 								\
967 	if (pp->p_mapping == NULL) {				\
968 		panic("hme_remove - no mappings");		\
969 	}							\
970 								\
971 	membar_stst();	/* ensure previous stores finish */	\
972 								\
973 	ASSERT(pp->p_share > 0);				\
974 	pp->p_share--;						\
975 								\
976 	if (hme->hme_prev) {					\
977 		ASSERT(pp->p_mapping != hme);			\
978 		ASSERT(hme->hme_prev->hme_page == pp ||		\
979 			IS_PAHME(hme->hme_prev));		\
980 		hme->hme_prev->hme_next = hme->hme_next;	\
981 	} else {						\
982 		ASSERT(pp->p_mapping == hme);			\
983 		pp->p_mapping = hme->hme_next;			\
984 		ASSERT((pp->p_mapping == NULL) ?		\
985 			(pp->p_share == 0) : 1);		\
986 	}							\
987 								\
988 	if (hme->hme_next) {					\
989 		ASSERT(hme->hme_next->hme_page == pp ||		\
990 			IS_PAHME(hme->hme_next));		\
991 		hme->hme_next->hme_prev = hme->hme_prev;	\
992 	}							\
993 								\
994 	/* zero out the entry */				\
995 	hme->hme_next = NULL;					\
996 	hme->hme_prev = NULL;					\
997 	hme->hme_page = NULL;					\
998 								\
999 	if (hme_size(hme) > TTE8K) {				\
1000 		/* remove mappings for remainder of large pg */	\
1001 		sfmmu_rm_large_mappings(pp, hme_size(hme));	\
1002 	}							\
1003 }
1004 
1005 /*
1006  * This function returns the hment given the hme_blk and a vaddr.
1007  * It assumes addr has already been checked to belong to hme_blk's
1008  * range.
1009  */
1010 #define	HBLKTOHME(hment, hmeblkp, addr)					\
1011 {									\
1012 	int index;							\
1013 	HBLKTOHME_IDX(hment, hmeblkp, addr, index)			\
1014 }
1015 
1016 /*
1017  * Version of HBLKTOHME that also returns the index in hmeblkp
1018  * of the hment.
1019  */
1020 #define	HBLKTOHME_IDX(hment, hmeblkp, addr, idx)			\
1021 {									\
1022 	ASSERT(in_hblk_range((hmeblkp), (addr)));			\
1023 									\
1024 	if (get_hblk_ttesz(hmeblkp) == TTE8K) {				\
1025 		idx = (((uintptr_t)(addr) >> MMU_PAGESHIFT) & (NHMENTS-1)); \
1026 	} else								\
1027 		idx = 0;						\
1028 									\
1029 	(hment) = &(hmeblkp)->hblk_hme[idx];				\
1030 }
1031 
1032 /*
1033  * Disable any page sizes not supported by the CPU
1034  */
1035 void
1036 hat_init_pagesizes()
1037 {
1038 	int 		i;
1039 
1040 	mmu_exported_page_sizes = 0;
1041 	for (i = TTE8K; i < max_mmu_page_sizes; i++) {
1042 
1043 		szc_2_userszc[i] = (uint_t)-1;
1044 		userszc_2_szc[i] = (uint_t)-1;
1045 
1046 		if ((mmu_exported_pagesize_mask & (1 << i)) == 0) {
1047 			disable_large_pages |= (1 << i);
1048 		} else {
1049 			szc_2_userszc[i] = mmu_exported_page_sizes;
1050 			userszc_2_szc[mmu_exported_page_sizes] = i;
1051 			mmu_exported_page_sizes++;
1052 		}
1053 	}
1054 
1055 	disable_ism_large_pages |= disable_large_pages;
1056 	disable_auto_data_large_pages = disable_large_pages;
1057 	disable_auto_text_large_pages = disable_large_pages;
1058 
1059 	/*
1060 	 * Initialize mmu-specific large page sizes.
1061 	 */
1062 	if (&mmu_large_pages_disabled) {
1063 		disable_large_pages |= mmu_large_pages_disabled(HAT_LOAD);
1064 		disable_ism_large_pages |=
1065 		    mmu_large_pages_disabled(HAT_LOAD_SHARE);
1066 		disable_auto_data_large_pages |=
1067 		    mmu_large_pages_disabled(HAT_AUTO_DATA);
1068 		disable_auto_text_large_pages |=
1069 		    mmu_large_pages_disabled(HAT_AUTO_TEXT);
1070 	}
1071 }
1072 
1073 /*
1074  * Initialize the hardware address translation structures.
1075  */
1076 void
1077 hat_init(void)
1078 {
1079 	int 		i;
1080 	uint_t		sz;
1081 	size_t		size;
1082 
1083 	hat_lock_init();
1084 	hat_kstat_init();
1085 
1086 	/*
1087 	 * Hardware-only bits in a TTE
1088 	 */
1089 	MAKE_TTE_MASK(&hw_tte);
1090 
1091 	hat_init_pagesizes();
1092 
1093 	/* Initialize the hash locks */
1094 	for (i = 0; i < khmehash_num; i++) {
1095 		mutex_init(&khme_hash[i].hmehash_mutex, NULL,
1096 		    MUTEX_DEFAULT, NULL);
1097 		khme_hash[i].hmeh_nextpa = HMEBLK_ENDPA;
1098 	}
1099 	for (i = 0; i < uhmehash_num; i++) {
1100 		mutex_init(&uhme_hash[i].hmehash_mutex, NULL,
1101 		    MUTEX_DEFAULT, NULL);
1102 		uhme_hash[i].hmeh_nextpa = HMEBLK_ENDPA;
1103 	}
1104 	khmehash_num--;		/* make sure counter starts from 0 */
1105 	uhmehash_num--;		/* make sure counter starts from 0 */
1106 
1107 	/*
1108 	 * Allocate context domain structures.
1109 	 *
1110 	 * A platform may choose to modify max_mmu_ctxdoms in
1111 	 * set_platform_defaults(). If a platform does not define
1112 	 * a set_platform_defaults() or does not choose to modify
1113 	 * max_mmu_ctxdoms, it gets one MMU context domain for every CPU.
1114 	 *
1115 	 * For sun4v, there will be one global context domain, this is to
1116 	 * avoid the ldom cpu substitution problem.
1117 	 *
1118 	 * For all platforms that have CPUs sharing MMUs, this
1119 	 * value must be defined.
1120 	 */
1121 	if (max_mmu_ctxdoms == 0) {
1122 #ifndef sun4v
1123 		max_mmu_ctxdoms = max_ncpus;
1124 #else /* sun4v */
1125 		max_mmu_ctxdoms = 1;
1126 #endif /* sun4v */
1127 	}
1128 
1129 	size = max_mmu_ctxdoms * sizeof (mmu_ctx_t *);
1130 	mmu_ctxs_tbl = kmem_zalloc(size, KM_SLEEP);
1131 
1132 	/* mmu_ctx_t is 64 bytes aligned */
1133 	mmuctxdom_cache = kmem_cache_create("mmuctxdom_cache",
1134 	    sizeof (mmu_ctx_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
1135 	/*
1136 	 * MMU context domain initialization for the Boot CPU.
1137 	 * This needs the context domains array allocated above.
1138 	 */
1139 	mutex_enter(&cpu_lock);
1140 	sfmmu_cpu_init(CPU);
1141 	mutex_exit(&cpu_lock);
1142 
1143 	/*
1144 	 * Intialize ism mapping list lock.
1145 	 */
1146 
1147 	mutex_init(&ism_mlist_lock, NULL, MUTEX_DEFAULT, NULL);
1148 
1149 	/*
1150 	 * Each sfmmu structure carries an array of MMU context info
1151 	 * structures, one per context domain. The size of this array depends
1152 	 * on the maximum number of context domains. So, the size of the
1153 	 * sfmmu structure varies per platform.
1154 	 *
1155 	 * sfmmu is allocated from static arena, because trap
1156 	 * handler at TL > 0 is not allowed to touch kernel relocatable
1157 	 * memory. sfmmu's alignment is changed to 64 bytes from
1158 	 * default 8 bytes, as the lower 6 bits will be used to pass
1159 	 * pgcnt to vtag_flush_pgcnt_tl1.
1160 	 */
1161 	size = sizeof (sfmmu_t) + sizeof (sfmmu_ctx_t) * (max_mmu_ctxdoms - 1);
1162 
1163 	sfmmuid_cache = kmem_cache_create("sfmmuid_cache", size,
1164 	    64, sfmmu_idcache_constructor, sfmmu_idcache_destructor,
1165 	    NULL, NULL, static_arena, 0);
1166 
1167 	sfmmu_tsbinfo_cache = kmem_cache_create("sfmmu_tsbinfo_cache",
1168 	    sizeof (struct tsb_info), 0, NULL, NULL, NULL, NULL, NULL, 0);
1169 
1170 	/*
1171 	 * Since we only use the tsb8k cache to "borrow" pages for TSBs
1172 	 * from the heap when low on memory or when TSB_FORCEALLOC is
1173 	 * specified, don't use magazines to cache them--we want to return
1174 	 * them to the system as quickly as possible.
1175 	 */
1176 	sfmmu_tsb8k_cache = kmem_cache_create("sfmmu_tsb8k_cache",
1177 	    MMU_PAGESIZE, MMU_PAGESIZE, NULL, NULL, NULL, NULL,
1178 	    static_arena, KMC_NOMAGAZINE);
1179 
1180 	/*
1181 	 * Set tsb_alloc_hiwater to 1/tsb_alloc_hiwater_factor of physical
1182 	 * memory, which corresponds to the old static reserve for TSBs.
1183 	 * tsb_alloc_hiwater_factor defaults to 32.  This caps the amount of
1184 	 * memory we'll allocate for TSB slabs; beyond this point TSB
1185 	 * allocations will be taken from the kernel heap (via
1186 	 * sfmmu_tsb8k_cache) and will be throttled as would any other kmem
1187 	 * consumer.
1188 	 */
1189 	if (tsb_alloc_hiwater_factor == 0) {
1190 		tsb_alloc_hiwater_factor = TSB_ALLOC_HIWATER_FACTOR_DEFAULT;
1191 	}
1192 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
1193 
1194 	for (sz = tsb_slab_ttesz; sz > 0; sz--) {
1195 		if (!(disable_large_pages & (1 << sz)))
1196 			break;
1197 	}
1198 
1199 	if (sz < tsb_slab_ttesz) {
1200 		tsb_slab_ttesz = sz;
1201 		tsb_slab_shift = MMU_PAGESHIFT + (sz << 1) + sz;
1202 		tsb_slab_size = 1 << tsb_slab_shift;
1203 		tsb_slab_mask = (1 << (tsb_slab_shift - MMU_PAGESHIFT)) - 1;
1204 		use_bigtsb_arena = 0;
1205 	} else if (use_bigtsb_arena &&
1206 	    (disable_large_pages & (1 << bigtsb_slab_ttesz))) {
1207 		use_bigtsb_arena = 0;
1208 	}
1209 
1210 	if (!use_bigtsb_arena) {
1211 		bigtsb_slab_shift = tsb_slab_shift;
1212 	}
1213 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
1214 
1215 	/*
1216 	 * On smaller memory systems, allocate TSB memory in smaller chunks
1217 	 * than the default 4M slab size. We also honor disable_large_pages
1218 	 * here.
1219 	 *
1220 	 * The trap handlers need to be patched with the final slab shift,
1221 	 * since they need to be able to construct the TSB pointer at runtime.
1222 	 */
1223 	if ((tsb_max_growsize <= TSB_512K_SZCODE) &&
1224 	    !(disable_large_pages & (1 << TTE512K))) {
1225 		tsb_slab_ttesz = TTE512K;
1226 		tsb_slab_shift = MMU_PAGESHIFT512K;
1227 		tsb_slab_size = MMU_PAGESIZE512K;
1228 		tsb_slab_mask = MMU_PAGEOFFSET512K >> MMU_PAGESHIFT;
1229 		use_bigtsb_arena = 0;
1230 	}
1231 
1232 	if (!use_bigtsb_arena) {
1233 		bigtsb_slab_ttesz = tsb_slab_ttesz;
1234 		bigtsb_slab_shift = tsb_slab_shift;
1235 		bigtsb_slab_size = tsb_slab_size;
1236 		bigtsb_slab_mask = tsb_slab_mask;
1237 	}
1238 
1239 
1240 	/*
1241 	 * Set up memory callback to update tsb_alloc_hiwater and
1242 	 * tsb_max_growsize.
1243 	 */
1244 	i = kphysm_setup_func_register(&sfmmu_update_vec, (void *) 0);
1245 	ASSERT(i == 0);
1246 
1247 	/*
1248 	 * kmem_tsb_arena is the source from which large TSB slabs are
1249 	 * drawn.  The quantum of this arena corresponds to the largest
1250 	 * TSB size we can dynamically allocate for user processes.
1251 	 * Currently it must also be a supported page size since we
1252 	 * use exactly one translation entry to map each slab page.
1253 	 *
1254 	 * The per-lgroup kmem_tsb_default_arena arenas are the arenas from
1255 	 * which most TSBs are allocated.  Since most TSB allocations are
1256 	 * typically 8K we have a kmem cache we stack on top of each
1257 	 * kmem_tsb_default_arena to speed up those allocations.
1258 	 *
1259 	 * Note the two-level scheme of arenas is required only
1260 	 * because vmem_create doesn't allow us to specify alignment
1261 	 * requirements.  If this ever changes the code could be
1262 	 * simplified to use only one level of arenas.
1263 	 *
1264 	 * If 256M page support exists on sun4v, 256MB kmem_bigtsb_arena
1265 	 * will be provided in addition to the 4M kmem_tsb_arena.
1266 	 */
1267 	if (use_bigtsb_arena) {
1268 		kmem_bigtsb_arena = vmem_create("kmem_bigtsb", NULL, 0,
1269 		    bigtsb_slab_size, sfmmu_vmem_xalloc_aligned_wrapper,
1270 		    vmem_xfree, heap_arena, 0, VM_SLEEP);
1271 	}
1272 
1273 	kmem_tsb_arena = vmem_create("kmem_tsb", NULL, 0, tsb_slab_size,
1274 	    sfmmu_vmem_xalloc_aligned_wrapper,
1275 	    vmem_xfree, heap_arena, 0, VM_SLEEP);
1276 
1277 	if (tsb_lgrp_affinity) {
1278 		char s[50];
1279 		for (i = 0; i < NLGRPS_MAX; i++) {
1280 			if (use_bigtsb_arena) {
1281 				(void) sprintf(s, "kmem_bigtsb_lgrp%d", i);
1282 				kmem_bigtsb_default_arena[i] = vmem_create(s,
1283 				    NULL, 0, 2 * tsb_slab_size,
1284 				    sfmmu_tsb_segkmem_alloc,
1285 				    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena,
1286 				    0, VM_SLEEP | VM_BESTFIT);
1287 			}
1288 
1289 			(void) sprintf(s, "kmem_tsb_lgrp%d", i);
1290 			kmem_tsb_default_arena[i] = vmem_create(s,
1291 			    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1292 			    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1293 			    VM_SLEEP | VM_BESTFIT);
1294 
1295 			(void) sprintf(s, "sfmmu_tsb_lgrp%d_cache", i);
1296 			sfmmu_tsb_cache[i] = kmem_cache_create(s,
1297 			    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1298 			    kmem_tsb_default_arena[i], 0);
1299 		}
1300 	} else {
1301 		if (use_bigtsb_arena) {
1302 			kmem_bigtsb_default_arena[0] =
1303 			    vmem_create("kmem_bigtsb_default", NULL, 0,
1304 			    2 * tsb_slab_size, sfmmu_tsb_segkmem_alloc,
1305 			    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena, 0,
1306 			    VM_SLEEP | VM_BESTFIT);
1307 		}
1308 
1309 		kmem_tsb_default_arena[0] = vmem_create("kmem_tsb_default",
1310 		    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1311 		    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1312 		    VM_SLEEP | VM_BESTFIT);
1313 		sfmmu_tsb_cache[0] = kmem_cache_create("sfmmu_tsb_cache",
1314 		    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1315 		    kmem_tsb_default_arena[0], 0);
1316 	}
1317 
1318 	sfmmu8_cache = kmem_cache_create("sfmmu8_cache", HME8BLK_SZ,
1319 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1320 	    sfmmu_hblkcache_destructor,
1321 	    sfmmu_hblkcache_reclaim, (void *)HME8BLK_SZ,
1322 	    hat_memload_arena, KMC_NOHASH);
1323 
1324 	hat_memload1_arena = vmem_create("hat_memload1", NULL, 0, PAGESIZE,
1325 	    segkmem_alloc_permanent, segkmem_free, heap_arena, 0, VM_SLEEP);
1326 
1327 	sfmmu1_cache = kmem_cache_create("sfmmu1_cache", HME1BLK_SZ,
1328 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1329 	    sfmmu_hblkcache_destructor,
1330 	    NULL, (void *)HME1BLK_SZ,
1331 	    hat_memload1_arena, KMC_NOHASH);
1332 
1333 	pa_hment_cache = kmem_cache_create("pa_hment_cache", PAHME_SZ,
1334 	    0, NULL, NULL, NULL, NULL, static_arena, KMC_NOHASH);
1335 
1336 	ism_blk_cache = kmem_cache_create("ism_blk_cache",
1337 	    sizeof (ism_blk_t), ecache_alignsize, NULL, NULL,
1338 	    NULL, NULL, static_arena, KMC_NOHASH);
1339 
1340 	ism_ment_cache = kmem_cache_create("ism_ment_cache",
1341 	    sizeof (ism_ment_t), 0, NULL, NULL,
1342 	    NULL, NULL, NULL, 0);
1343 
1344 	/*
1345 	 * We grab the first hat for the kernel,
1346 	 */
1347 	AS_LOCK_ENTER(&kas, &kas.a_lock, RW_WRITER);
1348 	kas.a_hat = hat_alloc(&kas);
1349 	AS_LOCK_EXIT(&kas, &kas.a_lock);
1350 
1351 	/*
1352 	 * Initialize hblk_reserve.
1353 	 */
1354 	((struct hme_blk *)hblk_reserve)->hblk_nextpa =
1355 	    va_to_pa((caddr_t)hblk_reserve);
1356 
1357 #ifndef UTSB_PHYS
1358 	/*
1359 	 * Reserve some kernel virtual address space for the locked TTEs
1360 	 * that allow us to probe the TSB from TL>0.
1361 	 */
1362 	utsb_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1363 	    0, 0, NULL, NULL, VM_SLEEP);
1364 	utsb4m_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1365 	    0, 0, NULL, NULL, VM_SLEEP);
1366 #endif
1367 
1368 #ifdef VAC
1369 	/*
1370 	 * The big page VAC handling code assumes VAC
1371 	 * will not be bigger than the smallest big
1372 	 * page- which is 64K.
1373 	 */
1374 	if (TTEPAGES(TTE64K) < CACHE_NUM_COLOR) {
1375 		cmn_err(CE_PANIC, "VAC too big!");
1376 	}
1377 #endif
1378 
1379 	(void) xhat_init();
1380 
1381 	uhme_hash_pa = va_to_pa(uhme_hash);
1382 	khme_hash_pa = va_to_pa(khme_hash);
1383 
1384 	/*
1385 	 * Initialize relocation locks. kpr_suspendlock is held
1386 	 * at PIL_MAX to prevent interrupts from pinning the holder
1387 	 * of a suspended TTE which may access it leading to a
1388 	 * deadlock condition.
1389 	 */
1390 	mutex_init(&kpr_mutex, NULL, MUTEX_DEFAULT, NULL);
1391 	mutex_init(&kpr_suspendlock, NULL, MUTEX_SPIN, (void *)PIL_MAX);
1392 
1393 	/*
1394 	 * If Shared context support is disabled via /etc/system
1395 	 * set shctx_on to 0 here if it was set to 1 earlier in boot
1396 	 * sequence by cpu module initialization code.
1397 	 */
1398 	if (shctx_on && disable_shctx) {
1399 		shctx_on = 0;
1400 	}
1401 
1402 	if (shctx_on) {
1403 		srd_buckets = kmem_zalloc(SFMMU_MAX_SRD_BUCKETS *
1404 		    sizeof (srd_buckets[0]), KM_SLEEP);
1405 		for (i = 0; i < SFMMU_MAX_SRD_BUCKETS; i++) {
1406 			mutex_init(&srd_buckets[i].srdb_lock, NULL,
1407 			    MUTEX_DEFAULT, NULL);
1408 		}
1409 
1410 		srd_cache = kmem_cache_create("srd_cache", sizeof (sf_srd_t),
1411 		    0, sfmmu_srdcache_constructor, sfmmu_srdcache_destructor,
1412 		    NULL, NULL, NULL, 0);
1413 		region_cache = kmem_cache_create("region_cache",
1414 		    sizeof (sf_region_t), 0, sfmmu_rgncache_constructor,
1415 		    sfmmu_rgncache_destructor, NULL, NULL, NULL, 0);
1416 		scd_cache = kmem_cache_create("scd_cache", sizeof (sf_scd_t),
1417 		    0, sfmmu_scdcache_constructor,  sfmmu_scdcache_destructor,
1418 		    NULL, NULL, NULL, 0);
1419 	}
1420 
1421 	/*
1422 	 * Pre-allocate hrm_hashtab before enabling the collection of
1423 	 * refmod statistics.  Allocating on the fly would mean us
1424 	 * running the risk of suffering recursive mutex enters or
1425 	 * deadlocks.
1426 	 */
1427 	hrm_hashtab = kmem_zalloc(HRM_HASHSIZE * sizeof (struct hrmstat *),
1428 	    KM_SLEEP);
1429 
1430 	/* Allocate per-cpu pending freelist of hmeblks */
1431 	cpu_hme_pend = kmem_zalloc((NCPU * sizeof (cpu_hme_pend_t)) + 64,
1432 	    KM_SLEEP);
1433 	cpu_hme_pend = (cpu_hme_pend_t *)P2ROUNDUP(
1434 	    (uintptr_t)cpu_hme_pend, 64);
1435 
1436 	for (i = 0; i < NCPU; i++) {
1437 		mutex_init(&cpu_hme_pend[i].chp_mutex, NULL, MUTEX_DEFAULT,
1438 		    NULL);
1439 	}
1440 
1441 	if (cpu_hme_pend_thresh == 0) {
1442 		cpu_hme_pend_thresh = CPU_HME_PEND_THRESH;
1443 	}
1444 }
1445 
1446 /*
1447  * Initialize locking for the hat layer, called early during boot.
1448  */
1449 static void
1450 hat_lock_init()
1451 {
1452 	int i;
1453 
1454 	/*
1455 	 * initialize the array of mutexes protecting a page's mapping
1456 	 * list and p_nrm field.
1457 	 */
1458 	for (i = 0; i < mml_table_sz; i++)
1459 		mutex_init(&mml_table[i], NULL, MUTEX_DEFAULT, NULL);
1460 
1461 	if (kpm_enable) {
1462 		for (i = 0; i < kpmp_table_sz; i++) {
1463 			mutex_init(&kpmp_table[i].khl_mutex, NULL,
1464 			    MUTEX_DEFAULT, NULL);
1465 		}
1466 	}
1467 
1468 	/*
1469 	 * Initialize array of mutex locks that protects sfmmu fields and
1470 	 * TSB lists.
1471 	 */
1472 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
1473 		mutex_init(HATLOCK_MUTEXP(&hat_lock[i]), NULL, MUTEX_DEFAULT,
1474 		    NULL);
1475 }
1476 
1477 #define	SFMMU_KERNEL_MAXVA \
1478 	(kmem64_base ? (uintptr_t)kmem64_end : (SYSLIMIT))
1479 
1480 /*
1481  * Allocate a hat structure.
1482  * Called when an address space first uses a hat.
1483  */
1484 struct hat *
1485 hat_alloc(struct as *as)
1486 {
1487 	sfmmu_t *sfmmup;
1488 	int i;
1489 	uint64_t cnum;
1490 	extern uint_t get_color_start(struct as *);
1491 
1492 	ASSERT(AS_WRITE_HELD(as, &as->a_lock));
1493 	sfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
1494 	sfmmup->sfmmu_as = as;
1495 	sfmmup->sfmmu_flags = 0;
1496 	sfmmup->sfmmu_tteflags = 0;
1497 	sfmmup->sfmmu_rtteflags = 0;
1498 	LOCK_INIT_CLEAR(&sfmmup->sfmmu_ctx_lock);
1499 
1500 	if (as == &kas) {
1501 		ksfmmup = sfmmup;
1502 		sfmmup->sfmmu_cext = 0;
1503 		cnum = KCONTEXT;
1504 
1505 		sfmmup->sfmmu_clrstart = 0;
1506 		sfmmup->sfmmu_tsb = NULL;
1507 		/*
1508 		 * hat_kern_setup() will call sfmmu_init_ktsbinfo()
1509 		 * to setup tsb_info for ksfmmup.
1510 		 */
1511 	} else {
1512 
1513 		/*
1514 		 * Just set to invalid ctx. When it faults, it will
1515 		 * get a valid ctx. This would avoid the situation
1516 		 * where we get a ctx, but it gets stolen and then
1517 		 * we fault when we try to run and so have to get
1518 		 * another ctx.
1519 		 */
1520 		sfmmup->sfmmu_cext = 0;
1521 		cnum = INVALID_CONTEXT;
1522 
1523 		/* initialize original physical page coloring bin */
1524 		sfmmup->sfmmu_clrstart = get_color_start(as);
1525 #ifdef DEBUG
1526 		if (tsb_random_size) {
1527 			uint32_t randval = (uint32_t)gettick() >> 4;
1528 			int size = randval % (tsb_max_growsize + 1);
1529 
1530 			/* chose a random tsb size for stress testing */
1531 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb, size,
1532 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1533 		} else
1534 #endif /* DEBUG */
1535 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb,
1536 			    default_tsb_size,
1537 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1538 		sfmmup->sfmmu_flags = HAT_SWAPPED | HAT_ALLCTX_INVALID;
1539 		ASSERT(sfmmup->sfmmu_tsb != NULL);
1540 	}
1541 
1542 	ASSERT(max_mmu_ctxdoms > 0);
1543 	for (i = 0; i < max_mmu_ctxdoms; i++) {
1544 		sfmmup->sfmmu_ctxs[i].cnum = cnum;
1545 		sfmmup->sfmmu_ctxs[i].gnum = 0;
1546 	}
1547 
1548 	for (i = 0; i < max_mmu_page_sizes; i++) {
1549 		sfmmup->sfmmu_ttecnt[i] = 0;
1550 		sfmmup->sfmmu_scdrttecnt[i] = 0;
1551 		sfmmup->sfmmu_ismttecnt[i] = 0;
1552 		sfmmup->sfmmu_scdismttecnt[i] = 0;
1553 		sfmmup->sfmmu_pgsz[i] = TTE8K;
1554 	}
1555 	sfmmup->sfmmu_tsb0_4minflcnt = 0;
1556 	sfmmup->sfmmu_iblk = NULL;
1557 	sfmmup->sfmmu_ismhat = 0;
1558 	sfmmup->sfmmu_scdhat = 0;
1559 	sfmmup->sfmmu_ismblkpa = (uint64_t)-1;
1560 	if (sfmmup == ksfmmup) {
1561 		CPUSET_ALL(sfmmup->sfmmu_cpusran);
1562 	} else {
1563 		CPUSET_ZERO(sfmmup->sfmmu_cpusran);
1564 	}
1565 	sfmmup->sfmmu_free = 0;
1566 	sfmmup->sfmmu_rmstat = 0;
1567 	sfmmup->sfmmu_clrbin = sfmmup->sfmmu_clrstart;
1568 	sfmmup->sfmmu_xhat_provider = NULL;
1569 	cv_init(&sfmmup->sfmmu_tsb_cv, NULL, CV_DEFAULT, NULL);
1570 	sfmmup->sfmmu_srdp = NULL;
1571 	SF_RGNMAP_ZERO(sfmmup->sfmmu_region_map);
1572 	bzero(sfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
1573 	sfmmup->sfmmu_scdp = NULL;
1574 	sfmmup->sfmmu_scd_link.next = NULL;
1575 	sfmmup->sfmmu_scd_link.prev = NULL;
1576 	return (sfmmup);
1577 }
1578 
1579 /*
1580  * Create per-MMU context domain kstats for a given MMU ctx.
1581  */
1582 static void
1583 sfmmu_mmu_kstat_create(mmu_ctx_t *mmu_ctxp)
1584 {
1585 	mmu_ctx_stat_t	stat;
1586 	kstat_t		*mmu_kstat;
1587 
1588 	ASSERT(MUTEX_HELD(&cpu_lock));
1589 	ASSERT(mmu_ctxp->mmu_kstat == NULL);
1590 
1591 	mmu_kstat = kstat_create("unix", mmu_ctxp->mmu_idx, "mmu_ctx",
1592 	    "hat", KSTAT_TYPE_NAMED, MMU_CTX_NUM_STATS, KSTAT_FLAG_VIRTUAL);
1593 
1594 	if (mmu_kstat == NULL) {
1595 		cmn_err(CE_WARN, "kstat_create for MMU %d failed",
1596 		    mmu_ctxp->mmu_idx);
1597 	} else {
1598 		mmu_kstat->ks_data = mmu_ctxp->mmu_kstat_data;
1599 		for (stat = 0; stat < MMU_CTX_NUM_STATS; stat++)
1600 			kstat_named_init(&mmu_ctxp->mmu_kstat_data[stat],
1601 			    mmu_ctx_kstat_names[stat], KSTAT_DATA_INT64);
1602 		mmu_ctxp->mmu_kstat = mmu_kstat;
1603 		kstat_install(mmu_kstat);
1604 	}
1605 }
1606 
1607 /*
1608  * plat_cpuid_to_mmu_ctx_info() is a platform interface that returns MMU
1609  * context domain information for a given CPU. If a platform does not
1610  * specify that interface, then the function below is used instead to return
1611  * default information. The defaults are as follows:
1612  *
1613  *	- For sun4u systems there's one MMU context domain per CPU.
1614  *	  This default is used by all sun4u systems except OPL. OPL systems
1615  *	  provide platform specific interface to map CPU ids to MMU ids
1616  *	  because on OPL more than 1 CPU shares a single MMU.
1617  *        Note that on sun4v, there is one global context domain for
1618  *	  the entire system. This is to avoid running into potential problem
1619  *	  with ldom physical cpu substitution feature.
1620  *	- The number of MMU context IDs supported on any CPU in the
1621  *	  system is 8K.
1622  */
1623 /*ARGSUSED*/
1624 static void
1625 sfmmu_cpuid_to_mmu_ctx_info(processorid_t cpuid, mmu_ctx_info_t *infop)
1626 {
1627 	infop->mmu_nctxs = nctxs;
1628 #ifndef sun4v
1629 	infop->mmu_idx = cpu[cpuid]->cpu_seqid;
1630 #else /* sun4v */
1631 	infop->mmu_idx = 0;
1632 #endif /* sun4v */
1633 }
1634 
1635 /*
1636  * Called during CPU initialization to set the MMU context-related information
1637  * for a CPU.
1638  *
1639  * cpu_lock serializes accesses to mmu_ctxs and mmu_saved_gnum.
1640  */
1641 void
1642 sfmmu_cpu_init(cpu_t *cp)
1643 {
1644 	mmu_ctx_info_t	info;
1645 	mmu_ctx_t	*mmu_ctxp;
1646 
1647 	ASSERT(MUTEX_HELD(&cpu_lock));
1648 
1649 	if (&plat_cpuid_to_mmu_ctx_info == NULL)
1650 		sfmmu_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1651 	else
1652 		plat_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1653 
1654 	ASSERT(info.mmu_idx < max_mmu_ctxdoms);
1655 
1656 	if ((mmu_ctxp = mmu_ctxs_tbl[info.mmu_idx]) == NULL) {
1657 		/* Each mmu_ctx is cacheline aligned. */
1658 		mmu_ctxp = kmem_cache_alloc(mmuctxdom_cache, KM_SLEEP);
1659 		bzero(mmu_ctxp, sizeof (mmu_ctx_t));
1660 
1661 		mutex_init(&mmu_ctxp->mmu_lock, NULL, MUTEX_SPIN,
1662 		    (void *)ipltospl(DISP_LEVEL));
1663 		mmu_ctxp->mmu_idx = info.mmu_idx;
1664 		mmu_ctxp->mmu_nctxs = info.mmu_nctxs;
1665 		/*
1666 		 * Globally for lifetime of a system,
1667 		 * gnum must always increase.
1668 		 * mmu_saved_gnum is protected by the cpu_lock.
1669 		 */
1670 		mmu_ctxp->mmu_gnum = mmu_saved_gnum + 1;
1671 		mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
1672 
1673 		sfmmu_mmu_kstat_create(mmu_ctxp);
1674 
1675 		mmu_ctxs_tbl[info.mmu_idx] = mmu_ctxp;
1676 	} else {
1677 		ASSERT(mmu_ctxp->mmu_idx == info.mmu_idx);
1678 	}
1679 
1680 	/*
1681 	 * The mmu_lock is acquired here to prevent races with
1682 	 * the wrap-around code.
1683 	 */
1684 	mutex_enter(&mmu_ctxp->mmu_lock);
1685 
1686 
1687 	mmu_ctxp->mmu_ncpus++;
1688 	CPUSET_ADD(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1689 	CPU_MMU_IDX(cp) = info.mmu_idx;
1690 	CPU_MMU_CTXP(cp) = mmu_ctxp;
1691 
1692 	mutex_exit(&mmu_ctxp->mmu_lock);
1693 }
1694 
1695 /*
1696  * Called to perform MMU context-related cleanup for a CPU.
1697  */
1698 void
1699 sfmmu_cpu_cleanup(cpu_t *cp)
1700 {
1701 	mmu_ctx_t	*mmu_ctxp;
1702 
1703 	ASSERT(MUTEX_HELD(&cpu_lock));
1704 
1705 	mmu_ctxp = CPU_MMU_CTXP(cp);
1706 	ASSERT(mmu_ctxp != NULL);
1707 
1708 	/*
1709 	 * The mmu_lock is acquired here to prevent races with
1710 	 * the wrap-around code.
1711 	 */
1712 	mutex_enter(&mmu_ctxp->mmu_lock);
1713 
1714 	CPU_MMU_CTXP(cp) = NULL;
1715 
1716 	CPUSET_DEL(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1717 	if (--mmu_ctxp->mmu_ncpus == 0) {
1718 		mmu_ctxs_tbl[mmu_ctxp->mmu_idx] = NULL;
1719 		mutex_exit(&mmu_ctxp->mmu_lock);
1720 		mutex_destroy(&mmu_ctxp->mmu_lock);
1721 
1722 		if (mmu_ctxp->mmu_kstat)
1723 			kstat_delete(mmu_ctxp->mmu_kstat);
1724 
1725 		/* mmu_saved_gnum is protected by the cpu_lock. */
1726 		if (mmu_saved_gnum < mmu_ctxp->mmu_gnum)
1727 			mmu_saved_gnum = mmu_ctxp->mmu_gnum;
1728 
1729 		kmem_cache_free(mmuctxdom_cache, mmu_ctxp);
1730 
1731 		return;
1732 	}
1733 
1734 	mutex_exit(&mmu_ctxp->mmu_lock);
1735 }
1736 
1737 /*
1738  * Hat_setup, makes an address space context the current active one.
1739  * In sfmmu this translates to setting the secondary context with the
1740  * corresponding context.
1741  */
1742 void
1743 hat_setup(struct hat *sfmmup, int allocflag)
1744 {
1745 	hatlock_t *hatlockp;
1746 
1747 	/* Init needs some special treatment. */
1748 	if (allocflag == HAT_INIT) {
1749 		/*
1750 		 * Make sure that we have
1751 		 * 1. a TSB
1752 		 * 2. a valid ctx that doesn't get stolen after this point.
1753 		 */
1754 		hatlockp = sfmmu_hat_enter(sfmmup);
1755 
1756 		/*
1757 		 * Swap in the TSB.  hat_init() allocates tsbinfos without
1758 		 * TSBs, but we need one for init, since the kernel does some
1759 		 * special things to set up its stack and needs the TSB to
1760 		 * resolve page faults.
1761 		 */
1762 		sfmmu_tsb_swapin(sfmmup, hatlockp);
1763 
1764 		sfmmu_get_ctx(sfmmup);
1765 
1766 		sfmmu_hat_exit(hatlockp);
1767 	} else {
1768 		ASSERT(allocflag == HAT_ALLOC);
1769 
1770 		hatlockp = sfmmu_hat_enter(sfmmup);
1771 		kpreempt_disable();
1772 
1773 		CPUSET_ADD(sfmmup->sfmmu_cpusran, CPU->cpu_id);
1774 		/*
1775 		 * sfmmu_setctx_sec takes <pgsz|cnum> as a parameter,
1776 		 * pagesize bits don't matter in this case since we are passing
1777 		 * INVALID_CONTEXT to it.
1778 		 * Compatibility Note: hw takes care of MMU_SCONTEXT1
1779 		 */
1780 		sfmmu_setctx_sec(INVALID_CONTEXT);
1781 		sfmmu_clear_utsbinfo();
1782 
1783 		kpreempt_enable();
1784 		sfmmu_hat_exit(hatlockp);
1785 	}
1786 }
1787 
1788 /*
1789  * Free all the translation resources for the specified address space.
1790  * Called from as_free when an address space is being destroyed.
1791  */
1792 void
1793 hat_free_start(struct hat *sfmmup)
1794 {
1795 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
1796 	ASSERT(sfmmup != ksfmmup);
1797 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1798 
1799 	sfmmup->sfmmu_free = 1;
1800 	if (sfmmup->sfmmu_scdp != NULL) {
1801 		sfmmu_leave_scd(sfmmup, 0);
1802 	}
1803 
1804 	ASSERT(sfmmup->sfmmu_scdp == NULL);
1805 }
1806 
1807 void
1808 hat_free_end(struct hat *sfmmup)
1809 {
1810 	int i;
1811 
1812 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1813 	ASSERT(sfmmup->sfmmu_free == 1);
1814 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
1815 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
1816 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
1817 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
1818 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
1819 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
1820 
1821 	if (sfmmup->sfmmu_rmstat) {
1822 		hat_freestat(sfmmup->sfmmu_as, NULL);
1823 	}
1824 
1825 	while (sfmmup->sfmmu_tsb != NULL) {
1826 		struct tsb_info *next = sfmmup->sfmmu_tsb->tsb_next;
1827 		sfmmu_tsbinfo_free(sfmmup->sfmmu_tsb);
1828 		sfmmup->sfmmu_tsb = next;
1829 	}
1830 
1831 	if (sfmmup->sfmmu_srdp != NULL) {
1832 		sfmmu_leave_srd(sfmmup);
1833 		ASSERT(sfmmup->sfmmu_srdp == NULL);
1834 		for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1835 			if (sfmmup->sfmmu_hmeregion_links[i] != NULL) {
1836 				kmem_free(sfmmup->sfmmu_hmeregion_links[i],
1837 				    SFMMU_L2_HMERLINKS_SIZE);
1838 				sfmmup->sfmmu_hmeregion_links[i] = NULL;
1839 			}
1840 		}
1841 	}
1842 	sfmmu_free_sfmmu(sfmmup);
1843 
1844 #ifdef DEBUG
1845 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1846 		ASSERT(sfmmup->sfmmu_hmeregion_links[i] == NULL);
1847 	}
1848 #endif
1849 
1850 	kmem_cache_free(sfmmuid_cache, sfmmup);
1851 }
1852 
1853 /*
1854  * Set up any translation structures, for the specified address space,
1855  * that are needed or preferred when the process is being swapped in.
1856  */
1857 /* ARGSUSED */
1858 void
1859 hat_swapin(struct hat *hat)
1860 {
1861 	ASSERT(hat->sfmmu_xhat_provider == NULL);
1862 }
1863 
1864 /*
1865  * Free all of the translation resources, for the specified address space,
1866  * that can be freed while the process is swapped out. Called from as_swapout.
1867  * Also, free up the ctx that this process was using.
1868  */
1869 void
1870 hat_swapout(struct hat *sfmmup)
1871 {
1872 	struct hmehash_bucket *hmebp;
1873 	struct hme_blk *hmeblkp;
1874 	struct hme_blk *pr_hblk = NULL;
1875 	struct hme_blk *nx_hblk;
1876 	int i;
1877 	struct hme_blk *list = NULL;
1878 	hatlock_t *hatlockp;
1879 	struct tsb_info *tsbinfop;
1880 	struct free_tsb {
1881 		struct free_tsb *next;
1882 		struct tsb_info *tsbinfop;
1883 	};			/* free list of TSBs */
1884 	struct free_tsb *freelist, *last, *next;
1885 
1886 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1887 	SFMMU_STAT(sf_swapout);
1888 
1889 	/*
1890 	 * There is no way to go from an as to all its translations in sfmmu.
1891 	 * Here is one of the times when we take the big hit and traverse
1892 	 * the hash looking for hme_blks to free up.  Not only do we free up
1893 	 * this as hme_blks but all those that are free.  We are obviously
1894 	 * swapping because we need memory so let's free up as much
1895 	 * as we can.
1896 	 *
1897 	 * Note that we don't flush TLB/TSB here -- it's not necessary
1898 	 * because:
1899 	 *  1) we free the ctx we're using and throw away the TSB(s);
1900 	 *  2) processes aren't runnable while being swapped out.
1901 	 */
1902 	ASSERT(sfmmup != KHATID);
1903 	for (i = 0; i <= UHMEHASH_SZ; i++) {
1904 		hmebp = &uhme_hash[i];
1905 		SFMMU_HASH_LOCK(hmebp);
1906 		hmeblkp = hmebp->hmeblkp;
1907 		pr_hblk = NULL;
1908 		while (hmeblkp) {
1909 
1910 			ASSERT(!hmeblkp->hblk_xhat_bit);
1911 
1912 			if ((hmeblkp->hblk_tag.htag_id == sfmmup) &&
1913 			    !hmeblkp->hblk_shw_bit && !hmeblkp->hblk_lckcnt) {
1914 				ASSERT(!hmeblkp->hblk_shared);
1915 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
1916 				    (caddr_t)get_hblk_base(hmeblkp),
1917 				    get_hblk_endaddr(hmeblkp),
1918 				    NULL, HAT_UNLOAD);
1919 			}
1920 			nx_hblk = hmeblkp->hblk_next;
1921 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
1922 				ASSERT(!hmeblkp->hblk_lckcnt);
1923 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
1924 				    &list, 0);
1925 			} else {
1926 				pr_hblk = hmeblkp;
1927 			}
1928 			hmeblkp = nx_hblk;
1929 		}
1930 		SFMMU_HASH_UNLOCK(hmebp);
1931 	}
1932 
1933 	sfmmu_hblks_list_purge(&list, 0);
1934 
1935 	/*
1936 	 * Now free up the ctx so that others can reuse it.
1937 	 */
1938 	hatlockp = sfmmu_hat_enter(sfmmup);
1939 
1940 	sfmmu_invalidate_ctx(sfmmup);
1941 
1942 	/*
1943 	 * Free TSBs, but not tsbinfos, and set SWAPPED flag.
1944 	 * If TSBs were never swapped in, just return.
1945 	 * This implies that we don't support partial swapping
1946 	 * of TSBs -- either all are swapped out, or none are.
1947 	 *
1948 	 * We must hold the HAT lock here to prevent racing with another
1949 	 * thread trying to unmap TTEs from the TSB or running the post-
1950 	 * relocator after relocating the TSB's memory.  Unfortunately, we
1951 	 * can't free memory while holding the HAT lock or we could
1952 	 * deadlock, so we build a list of TSBs to be freed after marking
1953 	 * the tsbinfos as swapped out and free them after dropping the
1954 	 * lock.
1955 	 */
1956 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
1957 		sfmmu_hat_exit(hatlockp);
1958 		return;
1959 	}
1960 
1961 	SFMMU_FLAGS_SET(sfmmup, HAT_SWAPPED);
1962 	last = freelist = NULL;
1963 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
1964 	    tsbinfop = tsbinfop->tsb_next) {
1965 		ASSERT((tsbinfop->tsb_flags & TSB_SWAPPED) == 0);
1966 
1967 		/*
1968 		 * Cast the TSB into a struct free_tsb and put it on the free
1969 		 * list.
1970 		 */
1971 		if (freelist == NULL) {
1972 			last = freelist = (struct free_tsb *)tsbinfop->tsb_va;
1973 		} else {
1974 			last->next = (struct free_tsb *)tsbinfop->tsb_va;
1975 			last = last->next;
1976 		}
1977 		last->next = NULL;
1978 		last->tsbinfop = tsbinfop;
1979 		tsbinfop->tsb_flags |= TSB_SWAPPED;
1980 		/*
1981 		 * Zero out the TTE to clear the valid bit.
1982 		 * Note we can't use a value like 0xbad because we want to
1983 		 * ensure diagnostic bits are NEVER set on TTEs that might
1984 		 * be loaded.  The intent is to catch any invalid access
1985 		 * to the swapped TSB, such as a thread running with a valid
1986 		 * context without first calling sfmmu_tsb_swapin() to
1987 		 * allocate TSB memory.
1988 		 */
1989 		tsbinfop->tsb_tte.ll = 0;
1990 	}
1991 
1992 	/* Now we can drop the lock and free the TSB memory. */
1993 	sfmmu_hat_exit(hatlockp);
1994 	for (; freelist != NULL; freelist = next) {
1995 		next = freelist->next;
1996 		sfmmu_tsb_free(freelist->tsbinfop);
1997 	}
1998 }
1999 
2000 /*
2001  * Duplicate the translations of an as into another newas
2002  */
2003 /* ARGSUSED */
2004 int
2005 hat_dup(struct hat *hat, struct hat *newhat, caddr_t addr, size_t len,
2006 	uint_t flag)
2007 {
2008 	sf_srd_t *srdp;
2009 	sf_scd_t *scdp;
2010 	int i;
2011 	extern uint_t get_color_start(struct as *);
2012 
2013 	ASSERT(hat->sfmmu_xhat_provider == NULL);
2014 	ASSERT((flag == 0) || (flag == HAT_DUP_ALL) || (flag == HAT_DUP_COW) ||
2015 	    (flag == HAT_DUP_SRD));
2016 	ASSERT(hat != ksfmmup);
2017 	ASSERT(newhat != ksfmmup);
2018 	ASSERT(flag != HAT_DUP_ALL || hat->sfmmu_srdp == newhat->sfmmu_srdp);
2019 
2020 	if (flag == HAT_DUP_COW) {
2021 		panic("hat_dup: HAT_DUP_COW not supported");
2022 	}
2023 
2024 	if (flag == HAT_DUP_SRD && ((srdp = hat->sfmmu_srdp) != NULL)) {
2025 		ASSERT(srdp->srd_evp != NULL);
2026 		VN_HOLD(srdp->srd_evp);
2027 		ASSERT(srdp->srd_refcnt > 0);
2028 		newhat->sfmmu_srdp = srdp;
2029 		atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
2030 	}
2031 
2032 	/*
2033 	 * HAT_DUP_ALL flag is used after as duplication is done.
2034 	 */
2035 	if (flag == HAT_DUP_ALL && ((srdp = newhat->sfmmu_srdp) != NULL)) {
2036 		ASSERT(newhat->sfmmu_srdp->srd_refcnt >= 2);
2037 		newhat->sfmmu_rtteflags = hat->sfmmu_rtteflags;
2038 		if (hat->sfmmu_flags & HAT_4MTEXT_FLAG) {
2039 			newhat->sfmmu_flags |= HAT_4MTEXT_FLAG;
2040 		}
2041 
2042 		/* check if need to join scd */
2043 		if ((scdp = hat->sfmmu_scdp) != NULL &&
2044 		    newhat->sfmmu_scdp != scdp) {
2045 			int ret;
2046 			SF_RGNMAP_IS_SUBSET(&newhat->sfmmu_region_map,
2047 			    &scdp->scd_region_map, ret);
2048 			ASSERT(ret);
2049 			sfmmu_join_scd(scdp, newhat);
2050 			ASSERT(newhat->sfmmu_scdp == scdp &&
2051 			    scdp->scd_refcnt >= 2);
2052 			for (i = 0; i < max_mmu_page_sizes; i++) {
2053 				newhat->sfmmu_ismttecnt[i] =
2054 				    hat->sfmmu_ismttecnt[i];
2055 				newhat->sfmmu_scdismttecnt[i] =
2056 				    hat->sfmmu_scdismttecnt[i];
2057 			}
2058 		}
2059 
2060 		sfmmu_check_page_sizes(newhat, 1);
2061 	}
2062 
2063 	if (flag == HAT_DUP_ALL && consistent_coloring == 0 &&
2064 	    update_proc_pgcolorbase_after_fork != 0) {
2065 		hat->sfmmu_clrbin = get_color_start(hat->sfmmu_as);
2066 	}
2067 	return (0);
2068 }
2069 
2070 void
2071 hat_memload(struct hat *hat, caddr_t addr, struct page *pp,
2072 	uint_t attr, uint_t flags)
2073 {
2074 	hat_do_memload(hat, addr, pp, attr, flags,
2075 	    SFMMU_INVALID_SHMERID);
2076 }
2077 
2078 void
2079 hat_memload_region(struct hat *hat, caddr_t addr, struct page *pp,
2080 	uint_t attr, uint_t flags, hat_region_cookie_t rcookie)
2081 {
2082 	uint_t rid;
2083 	if (rcookie == HAT_INVALID_REGION_COOKIE ||
2084 	    hat->sfmmu_xhat_provider != NULL) {
2085 		hat_do_memload(hat, addr, pp, attr, flags,
2086 		    SFMMU_INVALID_SHMERID);
2087 		return;
2088 	}
2089 	rid = (uint_t)((uint64_t)rcookie);
2090 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2091 	hat_do_memload(hat, addr, pp, attr, flags, rid);
2092 }
2093 
2094 /*
2095  * Set up addr to map to page pp with protection prot.
2096  * As an optimization we also load the TSB with the
2097  * corresponding tte but it is no big deal if  the tte gets kicked out.
2098  */
2099 static void
2100 hat_do_memload(struct hat *hat, caddr_t addr, struct page *pp,
2101 	uint_t attr, uint_t flags, uint_t rid)
2102 {
2103 	tte_t tte;
2104 
2105 
2106 	ASSERT(hat != NULL);
2107 	ASSERT(PAGE_LOCKED(pp));
2108 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2109 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2110 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2111 	SFMMU_VALIDATE_HMERID(hat, rid, addr, MMU_PAGESIZE);
2112 
2113 	if (PP_ISFREE(pp)) {
2114 		panic("hat_memload: loading a mapping to free page %p",
2115 		    (void *)pp);
2116 	}
2117 
2118 	if (hat->sfmmu_xhat_provider) {
2119 		/* no regions for xhats */
2120 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
2121 		XHAT_MEMLOAD(hat, addr, pp, attr, flags);
2122 		return;
2123 	}
2124 
2125 	ASSERT((hat == ksfmmup) ||
2126 	    AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
2127 
2128 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2129 		cmn_err(CE_NOTE, "hat_memload: unsupported flags %d",
2130 		    flags & ~SFMMU_LOAD_ALLFLAG);
2131 
2132 	if (hat->sfmmu_rmstat)
2133 		hat_resvstat(MMU_PAGESIZE, hat->sfmmu_as, addr);
2134 
2135 #if defined(SF_ERRATA_57)
2136 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2137 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2138 	    !(flags & HAT_LOAD_SHARE)) {
2139 		cmn_err(CE_WARN, "hat_memload: illegal attempt to make user "
2140 		    " page executable");
2141 		attr &= ~PROT_EXEC;
2142 	}
2143 #endif
2144 
2145 	sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2146 	(void) sfmmu_tteload_array(hat, &tte, addr, &pp, flags, rid);
2147 
2148 	/*
2149 	 * Check TSB and TLB page sizes.
2150 	 */
2151 	if ((flags & HAT_LOAD_SHARE) == 0) {
2152 		sfmmu_check_page_sizes(hat, 1);
2153 	}
2154 }
2155 
2156 /*
2157  * hat_devload can be called to map real memory (e.g.
2158  * /dev/kmem) and even though hat_devload will determine pf is
2159  * for memory, it will be unable to get a shared lock on the
2160  * page (because someone else has it exclusively) and will
2161  * pass dp = NULL.  If tteload doesn't get a non-NULL
2162  * page pointer it can't cache memory.
2163  */
2164 void
2165 hat_devload(struct hat *hat, caddr_t addr, size_t len, pfn_t pfn,
2166 	uint_t attr, int flags)
2167 {
2168 	tte_t tte;
2169 	struct page *pp = NULL;
2170 	int use_lgpg = 0;
2171 
2172 	ASSERT(hat != NULL);
2173 
2174 	if (hat->sfmmu_xhat_provider) {
2175 		XHAT_DEVLOAD(hat, addr, len, pfn, attr, flags);
2176 		return;
2177 	}
2178 
2179 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2180 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2181 	ASSERT((hat == ksfmmup) ||
2182 	    AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
2183 	if (len == 0)
2184 		panic("hat_devload: zero len");
2185 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2186 		cmn_err(CE_NOTE, "hat_devload: unsupported flags %d",
2187 		    flags & ~SFMMU_LOAD_ALLFLAG);
2188 
2189 #if defined(SF_ERRATA_57)
2190 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2191 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2192 	    !(flags & HAT_LOAD_SHARE)) {
2193 		cmn_err(CE_WARN, "hat_devload: illegal attempt to make user "
2194 		    " page executable");
2195 		attr &= ~PROT_EXEC;
2196 	}
2197 #endif
2198 
2199 	/*
2200 	 * If it's a memory page find its pp
2201 	 */
2202 	if (!(flags & HAT_LOAD_NOCONSIST) && pf_is_memory(pfn)) {
2203 		pp = page_numtopp_nolock(pfn);
2204 		if (pp == NULL) {
2205 			flags |= HAT_LOAD_NOCONSIST;
2206 		} else {
2207 			if (PP_ISFREE(pp)) {
2208 				panic("hat_memload: loading "
2209 				    "a mapping to free page %p",
2210 				    (void *)pp);
2211 			}
2212 			if (!PAGE_LOCKED(pp) && !PP_ISNORELOC(pp)) {
2213 				panic("hat_memload: loading a mapping "
2214 				    "to unlocked relocatable page %p",
2215 				    (void *)pp);
2216 			}
2217 			ASSERT(len == MMU_PAGESIZE);
2218 		}
2219 	}
2220 
2221 	if (hat->sfmmu_rmstat)
2222 		hat_resvstat(len, hat->sfmmu_as, addr);
2223 
2224 	if (flags & HAT_LOAD_NOCONSIST) {
2225 		attr |= SFMMU_UNCACHEVTTE;
2226 		use_lgpg = 1;
2227 	}
2228 	if (!pf_is_memory(pfn)) {
2229 		attr |= SFMMU_UNCACHEPTTE | HAT_NOSYNC;
2230 		use_lgpg = 1;
2231 		switch (attr & HAT_ORDER_MASK) {
2232 			case HAT_STRICTORDER:
2233 			case HAT_UNORDERED_OK:
2234 				/*
2235 				 * we set the side effect bit for all non
2236 				 * memory mappings unless merging is ok
2237 				 */
2238 				attr |= SFMMU_SIDEFFECT;
2239 				break;
2240 			case HAT_MERGING_OK:
2241 			case HAT_LOADCACHING_OK:
2242 			case HAT_STORECACHING_OK:
2243 				break;
2244 			default:
2245 				panic("hat_devload: bad attr");
2246 				break;
2247 		}
2248 	}
2249 	while (len) {
2250 		if (!use_lgpg) {
2251 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2252 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2253 			    flags, SFMMU_INVALID_SHMERID);
2254 			len -= MMU_PAGESIZE;
2255 			addr += MMU_PAGESIZE;
2256 			pfn++;
2257 			continue;
2258 		}
2259 		/*
2260 		 *  try to use large pages, check va/pa alignments
2261 		 *  Note that 32M/256M page sizes are not (yet) supported.
2262 		 */
2263 		if ((len >= MMU_PAGESIZE4M) &&
2264 		    !((uintptr_t)addr & MMU_PAGEOFFSET4M) &&
2265 		    !(disable_large_pages & (1 << TTE4M)) &&
2266 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET4M)) {
2267 			sfmmu_memtte(&tte, pfn, attr, TTE4M);
2268 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2269 			    flags, SFMMU_INVALID_SHMERID);
2270 			len -= MMU_PAGESIZE4M;
2271 			addr += MMU_PAGESIZE4M;
2272 			pfn += MMU_PAGESIZE4M / MMU_PAGESIZE;
2273 		} else if ((len >= MMU_PAGESIZE512K) &&
2274 		    !((uintptr_t)addr & MMU_PAGEOFFSET512K) &&
2275 		    !(disable_large_pages & (1 << TTE512K)) &&
2276 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET512K)) {
2277 			sfmmu_memtte(&tte, pfn, attr, TTE512K);
2278 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2279 			    flags, SFMMU_INVALID_SHMERID);
2280 			len -= MMU_PAGESIZE512K;
2281 			addr += MMU_PAGESIZE512K;
2282 			pfn += MMU_PAGESIZE512K / MMU_PAGESIZE;
2283 		} else if ((len >= MMU_PAGESIZE64K) &&
2284 		    !((uintptr_t)addr & MMU_PAGEOFFSET64K) &&
2285 		    !(disable_large_pages & (1 << TTE64K)) &&
2286 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET64K)) {
2287 			sfmmu_memtte(&tte, pfn, attr, TTE64K);
2288 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2289 			    flags, SFMMU_INVALID_SHMERID);
2290 			len -= MMU_PAGESIZE64K;
2291 			addr += MMU_PAGESIZE64K;
2292 			pfn += MMU_PAGESIZE64K / MMU_PAGESIZE;
2293 		} else {
2294 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2295 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2296 			    flags, SFMMU_INVALID_SHMERID);
2297 			len -= MMU_PAGESIZE;
2298 			addr += MMU_PAGESIZE;
2299 			pfn++;
2300 		}
2301 	}
2302 
2303 	/*
2304 	 * Check TSB and TLB page sizes.
2305 	 */
2306 	if ((flags & HAT_LOAD_SHARE) == 0) {
2307 		sfmmu_check_page_sizes(hat, 1);
2308 	}
2309 }
2310 
2311 void
2312 hat_memload_array(struct hat *hat, caddr_t addr, size_t len,
2313 	struct page **pps, uint_t attr, uint_t flags)
2314 {
2315 	hat_do_memload_array(hat, addr, len, pps, attr, flags,
2316 	    SFMMU_INVALID_SHMERID);
2317 }
2318 
2319 void
2320 hat_memload_array_region(struct hat *hat, caddr_t addr, size_t len,
2321 	struct page **pps, uint_t attr, uint_t flags,
2322 	hat_region_cookie_t rcookie)
2323 {
2324 	uint_t rid;
2325 	if (rcookie == HAT_INVALID_REGION_COOKIE ||
2326 	    hat->sfmmu_xhat_provider != NULL) {
2327 		hat_do_memload_array(hat, addr, len, pps, attr, flags,
2328 		    SFMMU_INVALID_SHMERID);
2329 		return;
2330 	}
2331 	rid = (uint_t)((uint64_t)rcookie);
2332 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2333 	hat_do_memload_array(hat, addr, len, pps, attr, flags, rid);
2334 }
2335 
2336 /*
2337  * Map the largest extend possible out of the page array. The array may NOT
2338  * be in order.  The largest possible mapping a page can have
2339  * is specified in the p_szc field.  The p_szc field
2340  * cannot change as long as there any mappings (large or small)
2341  * to any of the pages that make up the large page. (ie. any
2342  * promotion/demotion of page size is not up to the hat but up to
2343  * the page free list manager).  The array
2344  * should consist of properly aligned contigous pages that are
2345  * part of a big page for a large mapping to be created.
2346  */
2347 static void
2348 hat_do_memload_array(struct hat *hat, caddr_t addr, size_t len,
2349 	struct page **pps, uint_t attr, uint_t flags, uint_t rid)
2350 {
2351 	int  ttesz;
2352 	size_t mapsz;
2353 	pgcnt_t	numpg, npgs;
2354 	tte_t tte;
2355 	page_t *pp;
2356 	uint_t large_pages_disable;
2357 
2358 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2359 	SFMMU_VALIDATE_HMERID(hat, rid, addr, len);
2360 
2361 	if (hat->sfmmu_xhat_provider) {
2362 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
2363 		XHAT_MEMLOAD_ARRAY(hat, addr, len, pps, attr, flags);
2364 		return;
2365 	}
2366 
2367 	if (hat->sfmmu_rmstat)
2368 		hat_resvstat(len, hat->sfmmu_as, addr);
2369 
2370 #if defined(SF_ERRATA_57)
2371 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2372 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2373 	    !(flags & HAT_LOAD_SHARE)) {
2374 		cmn_err(CE_WARN, "hat_memload_array: illegal attempt to make "
2375 		    "user page executable");
2376 		attr &= ~PROT_EXEC;
2377 	}
2378 #endif
2379 
2380 	/* Get number of pages */
2381 	npgs = len >> MMU_PAGESHIFT;
2382 
2383 	if (flags & HAT_LOAD_SHARE) {
2384 		large_pages_disable = disable_ism_large_pages;
2385 	} else {
2386 		large_pages_disable = disable_large_pages;
2387 	}
2388 
2389 	if (npgs < NHMENTS || large_pages_disable == LARGE_PAGES_OFF) {
2390 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2391 		    rid);
2392 		return;
2393 	}
2394 
2395 	while (npgs >= NHMENTS) {
2396 		pp = *pps;
2397 		for (ttesz = pp->p_szc; ttesz != TTE8K; ttesz--) {
2398 			/*
2399 			 * Check if this page size is disabled.
2400 			 */
2401 			if (large_pages_disable & (1 << ttesz))
2402 				continue;
2403 
2404 			numpg = TTEPAGES(ttesz);
2405 			mapsz = numpg << MMU_PAGESHIFT;
2406 			if ((npgs >= numpg) &&
2407 			    IS_P2ALIGNED(addr, mapsz) &&
2408 			    IS_P2ALIGNED(pp->p_pagenum, numpg)) {
2409 				/*
2410 				 * At this point we have enough pages and
2411 				 * we know the virtual address and the pfn
2412 				 * are properly aligned.  We still need
2413 				 * to check for physical contiguity but since
2414 				 * it is very likely that this is the case
2415 				 * we will assume they are so and undo
2416 				 * the request if necessary.  It would
2417 				 * be great if we could get a hint flag
2418 				 * like HAT_CONTIG which would tell us
2419 				 * the pages are contigous for sure.
2420 				 */
2421 				sfmmu_memtte(&tte, (*pps)->p_pagenum,
2422 				    attr, ttesz);
2423 				if (!sfmmu_tteload_array(hat, &tte, addr,
2424 				    pps, flags, rid)) {
2425 					break;
2426 				}
2427 			}
2428 		}
2429 		if (ttesz == TTE8K) {
2430 			/*
2431 			 * We were not able to map array using a large page
2432 			 * batch a hmeblk or fraction at a time.
2433 			 */
2434 			numpg = ((uintptr_t)addr >> MMU_PAGESHIFT)
2435 			    & (NHMENTS-1);
2436 			numpg = NHMENTS - numpg;
2437 			ASSERT(numpg <= npgs);
2438 			mapsz = numpg * MMU_PAGESIZE;
2439 			sfmmu_memload_batchsmall(hat, addr, pps, attr, flags,
2440 			    numpg, rid);
2441 		}
2442 		addr += mapsz;
2443 		npgs -= numpg;
2444 		pps += numpg;
2445 	}
2446 
2447 	if (npgs) {
2448 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2449 		    rid);
2450 	}
2451 
2452 	/*
2453 	 * Check TSB and TLB page sizes.
2454 	 */
2455 	if ((flags & HAT_LOAD_SHARE) == 0) {
2456 		sfmmu_check_page_sizes(hat, 1);
2457 	}
2458 }
2459 
2460 /*
2461  * Function tries to batch 8K pages into the same hme blk.
2462  */
2463 static void
2464 sfmmu_memload_batchsmall(struct hat *hat, caddr_t vaddr, page_t **pps,
2465 		    uint_t attr, uint_t flags, pgcnt_t npgs, uint_t rid)
2466 {
2467 	tte_t	tte;
2468 	page_t *pp;
2469 	struct hmehash_bucket *hmebp;
2470 	struct hme_blk *hmeblkp;
2471 	int	index;
2472 
2473 	while (npgs) {
2474 		/*
2475 		 * Acquire the hash bucket.
2476 		 */
2477 		hmebp = sfmmu_tteload_acquire_hashbucket(hat, vaddr, TTE8K,
2478 		    rid);
2479 		ASSERT(hmebp);
2480 
2481 		/*
2482 		 * Find the hment block.
2483 		 */
2484 		hmeblkp = sfmmu_tteload_find_hmeblk(hat, hmebp, vaddr,
2485 		    TTE8K, flags, rid);
2486 		ASSERT(hmeblkp);
2487 
2488 		do {
2489 			/*
2490 			 * Make the tte.
2491 			 */
2492 			pp = *pps;
2493 			sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2494 
2495 			/*
2496 			 * Add the translation.
2497 			 */
2498 			(void) sfmmu_tteload_addentry(hat, hmeblkp, &tte,
2499 			    vaddr, pps, flags, rid);
2500 
2501 			/*
2502 			 * Goto next page.
2503 			 */
2504 			pps++;
2505 			npgs--;
2506 
2507 			/*
2508 			 * Goto next address.
2509 			 */
2510 			vaddr += MMU_PAGESIZE;
2511 
2512 			/*
2513 			 * Don't crossover into a different hmentblk.
2514 			 */
2515 			index = (int)(((uintptr_t)vaddr >> MMU_PAGESHIFT) &
2516 			    (NHMENTS-1));
2517 
2518 		} while (index != 0 && npgs != 0);
2519 
2520 		/*
2521 		 * Release the hash bucket.
2522 		 */
2523 
2524 		sfmmu_tteload_release_hashbucket(hmebp);
2525 	}
2526 }
2527 
2528 /*
2529  * Construct a tte for a page:
2530  *
2531  * tte_valid = 1
2532  * tte_size2 = size & TTE_SZ2_BITS (Panther and Olympus-C only)
2533  * tte_size = size
2534  * tte_nfo = attr & HAT_NOFAULT
2535  * tte_ie = attr & HAT_STRUCTURE_LE
2536  * tte_hmenum = hmenum
2537  * tte_pahi = pp->p_pagenum >> TTE_PASHIFT;
2538  * tte_palo = pp->p_pagenum & TTE_PALOMASK;
2539  * tte_ref = 1 (optimization)
2540  * tte_wr_perm = attr & PROT_WRITE;
2541  * tte_no_sync = attr & HAT_NOSYNC
2542  * tte_lock = attr & SFMMU_LOCKTTE
2543  * tte_cp = !(attr & SFMMU_UNCACHEPTTE)
2544  * tte_cv = !(attr & SFMMU_UNCACHEVTTE)
2545  * tte_e = attr & SFMMU_SIDEFFECT
2546  * tte_priv = !(attr & PROT_USER)
2547  * tte_hwwr = if nosync is set and it is writable we set the mod bit (opt)
2548  * tte_glb = 0
2549  */
2550 void
2551 sfmmu_memtte(tte_t *ttep, pfn_t pfn, uint_t attr, int tte_sz)
2552 {
2553 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2554 
2555 	ttep->tte_inthi = MAKE_TTE_INTHI(pfn, attr, tte_sz, 0 /* hmenum */);
2556 	ttep->tte_intlo = MAKE_TTE_INTLO(pfn, attr, tte_sz, 0 /* hmenum */);
2557 
2558 	if (TTE_IS_NOSYNC(ttep)) {
2559 		TTE_SET_REF(ttep);
2560 		if (TTE_IS_WRITABLE(ttep)) {
2561 			TTE_SET_MOD(ttep);
2562 		}
2563 	}
2564 	if (TTE_IS_NFO(ttep) && TTE_IS_EXECUTABLE(ttep)) {
2565 		panic("sfmmu_memtte: can't set both NFO and EXEC bits");
2566 	}
2567 }
2568 
2569 /*
2570  * This function will add a translation to the hme_blk and allocate the
2571  * hme_blk if one does not exist.
2572  * If a page structure is specified then it will add the
2573  * corresponding hment to the mapping list.
2574  * It will also update the hmenum field for the tte.
2575  *
2576  * Currently this function is only used for kernel mappings.
2577  * So pass invalid region to sfmmu_tteload_array().
2578  */
2579 void
2580 sfmmu_tteload(struct hat *sfmmup, tte_t *ttep, caddr_t vaddr, page_t *pp,
2581 	uint_t flags)
2582 {
2583 	ASSERT(sfmmup == ksfmmup);
2584 	(void) sfmmu_tteload_array(sfmmup, ttep, vaddr, &pp, flags,
2585 	    SFMMU_INVALID_SHMERID);
2586 }
2587 
2588 /*
2589  * Load (ttep != NULL) or unload (ttep == NULL) one entry in the TSB.
2590  * Assumes that a particular page size may only be resident in one TSB.
2591  */
2592 static void
2593 sfmmu_mod_tsb(sfmmu_t *sfmmup, caddr_t vaddr, tte_t *ttep, int ttesz)
2594 {
2595 	struct tsb_info *tsbinfop = NULL;
2596 	uint64_t tag;
2597 	struct tsbe *tsbe_addr;
2598 	uint64_t tsb_base;
2599 	uint_t tsb_size;
2600 	int vpshift = MMU_PAGESHIFT;
2601 	int phys = 0;
2602 
2603 	if (sfmmup == ksfmmup) { /* No support for 32/256M ksfmmu pages */
2604 		phys = ktsb_phys;
2605 		if (ttesz >= TTE4M) {
2606 #ifndef sun4v
2607 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2608 #endif
2609 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2610 			tsb_size = ktsb4m_szcode;
2611 		} else {
2612 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2613 			tsb_size = ktsb_szcode;
2614 		}
2615 	} else {
2616 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2617 
2618 		/*
2619 		 * If there isn't a TSB for this page size, or the TSB is
2620 		 * swapped out, there is nothing to do.  Note that the latter
2621 		 * case seems impossible but can occur if hat_pageunload()
2622 		 * is called on an ISM mapping while the process is swapped
2623 		 * out.
2624 		 */
2625 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2626 			return;
2627 
2628 		/*
2629 		 * If another thread is in the middle of relocating a TSB
2630 		 * we can't unload the entry so set a flag so that the
2631 		 * TSB will be flushed before it can be accessed by the
2632 		 * process.
2633 		 */
2634 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2635 			if (ttep == NULL)
2636 				tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2637 			return;
2638 		}
2639 #if defined(UTSB_PHYS)
2640 		phys = 1;
2641 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2642 #else
2643 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2644 #endif
2645 		tsb_size = tsbinfop->tsb_szc;
2646 	}
2647 	if (ttesz >= TTE4M)
2648 		vpshift = MMU_PAGESHIFT4M;
2649 
2650 	tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2651 	tag = sfmmu_make_tsbtag(vaddr);
2652 
2653 	if (ttep == NULL) {
2654 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2655 	} else {
2656 		if (ttesz >= TTE4M) {
2657 			SFMMU_STAT(sf_tsb_load4m);
2658 		} else {
2659 			SFMMU_STAT(sf_tsb_load8k);
2660 		}
2661 
2662 		sfmmu_load_tsbe(tsbe_addr, tag, ttep, phys);
2663 	}
2664 }
2665 
2666 /*
2667  * Unmap all entries from [start, end) matching the given page size.
2668  *
2669  * This function is used primarily to unmap replicated 64K or 512K entries
2670  * from the TSB that are inserted using the base page size TSB pointer, but
2671  * it may also be called to unmap a range of addresses from the TSB.
2672  */
2673 void
2674 sfmmu_unload_tsb_range(sfmmu_t *sfmmup, caddr_t start, caddr_t end, int ttesz)
2675 {
2676 	struct tsb_info *tsbinfop;
2677 	uint64_t tag;
2678 	struct tsbe *tsbe_addr;
2679 	caddr_t vaddr;
2680 	uint64_t tsb_base;
2681 	int vpshift, vpgsz;
2682 	uint_t tsb_size;
2683 	int phys = 0;
2684 
2685 	/*
2686 	 * Assumptions:
2687 	 *  If ttesz == 8K, 64K or 512K, we walk through the range 8K
2688 	 *  at a time shooting down any valid entries we encounter.
2689 	 *
2690 	 *  If ttesz >= 4M we walk the range 4M at a time shooting
2691 	 *  down any valid mappings we find.
2692 	 */
2693 	if (sfmmup == ksfmmup) {
2694 		phys = ktsb_phys;
2695 		if (ttesz >= TTE4M) {
2696 #ifndef sun4v
2697 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2698 #endif
2699 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2700 			tsb_size = ktsb4m_szcode;
2701 		} else {
2702 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2703 			tsb_size = ktsb_szcode;
2704 		}
2705 	} else {
2706 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2707 
2708 		/*
2709 		 * If there isn't a TSB for this page size, or the TSB is
2710 		 * swapped out, there is nothing to do.  Note that the latter
2711 		 * case seems impossible but can occur if hat_pageunload()
2712 		 * is called on an ISM mapping while the process is swapped
2713 		 * out.
2714 		 */
2715 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2716 			return;
2717 
2718 		/*
2719 		 * If another thread is in the middle of relocating a TSB
2720 		 * we can't unload the entry so set a flag so that the
2721 		 * TSB will be flushed before it can be accessed by the
2722 		 * process.
2723 		 */
2724 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2725 			tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2726 			return;
2727 		}
2728 #if defined(UTSB_PHYS)
2729 		phys = 1;
2730 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2731 #else
2732 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2733 #endif
2734 		tsb_size = tsbinfop->tsb_szc;
2735 	}
2736 	if (ttesz >= TTE4M) {
2737 		vpshift = MMU_PAGESHIFT4M;
2738 		vpgsz = MMU_PAGESIZE4M;
2739 	} else {
2740 		vpshift = MMU_PAGESHIFT;
2741 		vpgsz = MMU_PAGESIZE;
2742 	}
2743 
2744 	for (vaddr = start; vaddr < end; vaddr += vpgsz) {
2745 		tag = sfmmu_make_tsbtag(vaddr);
2746 		tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2747 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2748 	}
2749 }
2750 
2751 /*
2752  * Select the optimum TSB size given the number of mappings
2753  * that need to be cached.
2754  */
2755 static int
2756 sfmmu_select_tsb_szc(pgcnt_t pgcnt)
2757 {
2758 	int szc = 0;
2759 
2760 #ifdef DEBUG
2761 	if (tsb_grow_stress) {
2762 		uint32_t randval = (uint32_t)gettick() >> 4;
2763 		return (randval % (tsb_max_growsize + 1));
2764 	}
2765 #endif	/* DEBUG */
2766 
2767 	while ((szc < tsb_max_growsize) && (pgcnt > SFMMU_RSS_TSBSIZE(szc)))
2768 		szc++;
2769 	return (szc);
2770 }
2771 
2772 /*
2773  * This function will add a translation to the hme_blk and allocate the
2774  * hme_blk if one does not exist.
2775  * If a page structure is specified then it will add the
2776  * corresponding hment to the mapping list.
2777  * It will also update the hmenum field for the tte.
2778  * Furthermore, it attempts to create a large page translation
2779  * for <addr,hat> at page array pps.  It assumes addr and first
2780  * pp is correctly aligned.  It returns 0 if successful and 1 otherwise.
2781  */
2782 static int
2783 sfmmu_tteload_array(sfmmu_t *sfmmup, tte_t *ttep, caddr_t vaddr,
2784 	page_t **pps, uint_t flags, uint_t rid)
2785 {
2786 	struct hmehash_bucket *hmebp;
2787 	struct hme_blk *hmeblkp;
2788 	int 	ret;
2789 	uint_t	size;
2790 
2791 	/*
2792 	 * Get mapping size.
2793 	 */
2794 	size = TTE_CSZ(ttep);
2795 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
2796 
2797 	/*
2798 	 * Acquire the hash bucket.
2799 	 */
2800 	hmebp = sfmmu_tteload_acquire_hashbucket(sfmmup, vaddr, size, rid);
2801 	ASSERT(hmebp);
2802 
2803 	/*
2804 	 * Find the hment block.
2805 	 */
2806 	hmeblkp = sfmmu_tteload_find_hmeblk(sfmmup, hmebp, vaddr, size, flags,
2807 	    rid);
2808 	ASSERT(hmeblkp);
2809 
2810 	/*
2811 	 * Add the translation.
2812 	 */
2813 	ret = sfmmu_tteload_addentry(sfmmup, hmeblkp, ttep, vaddr, pps, flags,
2814 	    rid);
2815 
2816 	/*
2817 	 * Release the hash bucket.
2818 	 */
2819 	sfmmu_tteload_release_hashbucket(hmebp);
2820 
2821 	return (ret);
2822 }
2823 
2824 /*
2825  * Function locks and returns a pointer to the hash bucket for vaddr and size.
2826  */
2827 static struct hmehash_bucket *
2828 sfmmu_tteload_acquire_hashbucket(sfmmu_t *sfmmup, caddr_t vaddr, int size,
2829     uint_t rid)
2830 {
2831 	struct hmehash_bucket *hmebp;
2832 	int hmeshift;
2833 	void *htagid = sfmmutohtagid(sfmmup, rid);
2834 
2835 	ASSERT(htagid != NULL);
2836 
2837 	hmeshift = HME_HASH_SHIFT(size);
2838 
2839 	hmebp = HME_HASH_FUNCTION(htagid, vaddr, hmeshift);
2840 
2841 	SFMMU_HASH_LOCK(hmebp);
2842 
2843 	return (hmebp);
2844 }
2845 
2846 /*
2847  * Function returns a pointer to an hmeblk in the hash bucket, hmebp. If the
2848  * hmeblk doesn't exists for the [sfmmup, vaddr & size] signature, a hmeblk is
2849  * allocated.
2850  */
2851 static struct hme_blk *
2852 sfmmu_tteload_find_hmeblk(sfmmu_t *sfmmup, struct hmehash_bucket *hmebp,
2853 	caddr_t vaddr, uint_t size, uint_t flags, uint_t rid)
2854 {
2855 	hmeblk_tag hblktag;
2856 	int hmeshift;
2857 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
2858 
2859 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
2860 
2861 	hblktag.htag_id = sfmmutohtagid(sfmmup, rid);
2862 	ASSERT(hblktag.htag_id != NULL);
2863 	hmeshift = HME_HASH_SHIFT(size);
2864 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
2865 	hblktag.htag_rehash = HME_HASH_REHASH(size);
2866 	hblktag.htag_rid = rid;
2867 
2868 ttearray_realloc:
2869 
2870 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
2871 
2872 	/*
2873 	 * We block until hblk_reserve_lock is released; it's held by
2874 	 * the thread, temporarily using hblk_reserve, until hblk_reserve is
2875 	 * replaced by a hblk from sfmmu8_cache.
2876 	 */
2877 	if (hmeblkp == (struct hme_blk *)hblk_reserve &&
2878 	    hblk_reserve_thread != curthread) {
2879 		SFMMU_HASH_UNLOCK(hmebp);
2880 		mutex_enter(&hblk_reserve_lock);
2881 		mutex_exit(&hblk_reserve_lock);
2882 		SFMMU_STAT(sf_hblk_reserve_hit);
2883 		SFMMU_HASH_LOCK(hmebp);
2884 		goto ttearray_realloc;
2885 	}
2886 
2887 	if (hmeblkp == NULL) {
2888 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
2889 		    hblktag, flags, rid);
2890 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
2891 		ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
2892 	} else {
2893 		/*
2894 		 * It is possible for 8k and 64k hblks to collide since they
2895 		 * have the same rehash value. This is because we
2896 		 * lazily free hblks and 8K/64K blks could be lingering.
2897 		 * If we find size mismatch we free the block and & try again.
2898 		 */
2899 		if (get_hblk_ttesz(hmeblkp) != size) {
2900 			ASSERT(!hmeblkp->hblk_vcnt);
2901 			ASSERT(!hmeblkp->hblk_hmecnt);
2902 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
2903 			    &list, 0);
2904 			goto ttearray_realloc;
2905 		}
2906 		if (hmeblkp->hblk_shw_bit) {
2907 			/*
2908 			 * if the hblk was previously used as a shadow hblk then
2909 			 * we will change it to a normal hblk
2910 			 */
2911 			ASSERT(!hmeblkp->hblk_shared);
2912 			if (hmeblkp->hblk_shw_mask) {
2913 				sfmmu_shadow_hcleanup(sfmmup, hmeblkp, hmebp);
2914 				ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
2915 				goto ttearray_realloc;
2916 			} else {
2917 				hmeblkp->hblk_shw_bit = 0;
2918 			}
2919 		}
2920 		SFMMU_STAT(sf_hblk_hit);
2921 	}
2922 
2923 	/*
2924 	 * hat_memload() should never call kmem_cache_free() for kernel hmeblks;
2925 	 * see block comment showing the stacktrace in sfmmu_hblk_alloc();
2926 	 * set the flag parameter to 1 so that sfmmu_hblks_list_purge() will
2927 	 * just add these hmeblks to the per-cpu pending queue.
2928 	 */
2929 	sfmmu_hblks_list_purge(&list, 1);
2930 
2931 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
2932 	ASSERT(!hmeblkp->hblk_shw_bit);
2933 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
2934 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
2935 	ASSERT(hmeblkp->hblk_tag.htag_rid == rid);
2936 
2937 	return (hmeblkp);
2938 }
2939 
2940 /*
2941  * Function adds a tte entry into the hmeblk. It returns 0 if successful and 1
2942  * otherwise.
2943  */
2944 static int
2945 sfmmu_tteload_addentry(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, tte_t *ttep,
2946 	caddr_t vaddr, page_t **pps, uint_t flags, uint_t rid)
2947 {
2948 	page_t *pp = *pps;
2949 	int hmenum, size, remap;
2950 	tte_t tteold, flush_tte;
2951 #ifdef DEBUG
2952 	tte_t orig_old;
2953 #endif /* DEBUG */
2954 	struct sf_hment *sfhme;
2955 	kmutex_t *pml, *pmtx;
2956 	hatlock_t *hatlockp;
2957 	int myflt;
2958 
2959 	/*
2960 	 * remove this panic when we decide to let user virtual address
2961 	 * space be >= USERLIMIT.
2962 	 */
2963 	if (!TTE_IS_PRIVILEGED(ttep) && vaddr >= (caddr_t)USERLIMIT)
2964 		panic("user addr %p in kernel space", (void *)vaddr);
2965 #if defined(TTE_IS_GLOBAL)
2966 	if (TTE_IS_GLOBAL(ttep))
2967 		panic("sfmmu_tteload: creating global tte");
2968 #endif
2969 
2970 #ifdef DEBUG
2971 	if (pf_is_memory(sfmmu_ttetopfn(ttep, vaddr)) &&
2972 	    !TTE_IS_PCACHEABLE(ttep) && !sfmmu_allow_nc_trans)
2973 		panic("sfmmu_tteload: non cacheable memory tte");
2974 #endif /* DEBUG */
2975 
2976 	/* don't simulate dirty bit for writeable ISM/DISM mappings */
2977 	if ((flags & HAT_LOAD_SHARE) && TTE_IS_WRITABLE(ttep)) {
2978 		TTE_SET_REF(ttep);
2979 		TTE_SET_MOD(ttep);
2980 	}
2981 
2982 	if ((flags & HAT_LOAD_SHARE) || !TTE_IS_REF(ttep) ||
2983 	    !TTE_IS_MOD(ttep)) {
2984 		/*
2985 		 * Don't load TSB for dummy as in ISM.  Also don't preload
2986 		 * the TSB if the TTE isn't writable since we're likely to
2987 		 * fault on it again -- preloading can be fairly expensive.
2988 		 */
2989 		flags |= SFMMU_NO_TSBLOAD;
2990 	}
2991 
2992 	size = TTE_CSZ(ttep);
2993 	switch (size) {
2994 	case TTE8K:
2995 		SFMMU_STAT(sf_tteload8k);
2996 		break;
2997 	case TTE64K:
2998 		SFMMU_STAT(sf_tteload64k);
2999 		break;
3000 	case TTE512K:
3001 		SFMMU_STAT(sf_tteload512k);
3002 		break;
3003 	case TTE4M:
3004 		SFMMU_STAT(sf_tteload4m);
3005 		break;
3006 	case (TTE32M):
3007 		SFMMU_STAT(sf_tteload32m);
3008 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3009 		break;
3010 	case (TTE256M):
3011 		SFMMU_STAT(sf_tteload256m);
3012 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3013 		break;
3014 	}
3015 
3016 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
3017 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
3018 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3019 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3020 
3021 	HBLKTOHME_IDX(sfhme, hmeblkp, vaddr, hmenum);
3022 
3023 	/*
3024 	 * Need to grab mlist lock here so that pageunload
3025 	 * will not change tte behind us.
3026 	 */
3027 	if (pp) {
3028 		pml = sfmmu_mlist_enter(pp);
3029 	}
3030 
3031 	sfmmu_copytte(&sfhme->hme_tte, &tteold);
3032 	/*
3033 	 * Look for corresponding hment and if valid verify
3034 	 * pfns are equal.
3035 	 */
3036 	remap = TTE_IS_VALID(&tteold);
3037 	if (remap) {
3038 		pfn_t	new_pfn, old_pfn;
3039 
3040 		old_pfn = TTE_TO_PFN(vaddr, &tteold);
3041 		new_pfn = TTE_TO_PFN(vaddr, ttep);
3042 
3043 		if (flags & HAT_LOAD_REMAP) {
3044 			/* make sure we are remapping same type of pages */
3045 			if (pf_is_memory(old_pfn) != pf_is_memory(new_pfn)) {
3046 				panic("sfmmu_tteload - tte remap io<->memory");
3047 			}
3048 			if (old_pfn != new_pfn &&
3049 			    (pp != NULL || sfhme->hme_page != NULL)) {
3050 				panic("sfmmu_tteload - tte remap pp != NULL");
3051 			}
3052 		} else if (old_pfn != new_pfn) {
3053 			panic("sfmmu_tteload - tte remap, hmeblkp 0x%p",
3054 			    (void *)hmeblkp);
3055 		}
3056 		ASSERT(TTE_CSZ(&tteold) == TTE_CSZ(ttep));
3057 	}
3058 
3059 	if (pp) {
3060 		if (size == TTE8K) {
3061 #ifdef VAC
3062 			/*
3063 			 * Handle VAC consistency
3064 			 */
3065 			if (!remap && (cache & CACHE_VAC) && !PP_ISNC(pp)) {
3066 				sfmmu_vac_conflict(sfmmup, vaddr, pp);
3067 			}
3068 #endif
3069 
3070 			if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3071 				pmtx = sfmmu_page_enter(pp);
3072 				PP_CLRRO(pp);
3073 				sfmmu_page_exit(pmtx);
3074 			} else if (!PP_ISMAPPED(pp) &&
3075 			    (!TTE_IS_WRITABLE(ttep)) && !(PP_ISMOD(pp))) {
3076 				pmtx = sfmmu_page_enter(pp);
3077 				if (!(PP_ISMOD(pp))) {
3078 					PP_SETRO(pp);
3079 				}
3080 				sfmmu_page_exit(pmtx);
3081 			}
3082 
3083 		} else if (sfmmu_pagearray_setup(vaddr, pps, ttep, remap)) {
3084 			/*
3085 			 * sfmmu_pagearray_setup failed so return
3086 			 */
3087 			sfmmu_mlist_exit(pml);
3088 			return (1);
3089 		}
3090 	}
3091 
3092 	/*
3093 	 * Make sure hment is not on a mapping list.
3094 	 */
3095 	ASSERT(remap || (sfhme->hme_page == NULL));
3096 
3097 	/* if it is not a remap then hme->next better be NULL */
3098 	ASSERT((!remap) ? sfhme->hme_next == NULL : 1);
3099 
3100 	if (flags & HAT_LOAD_LOCK) {
3101 		if ((hmeblkp->hblk_lckcnt + 1) >= MAX_HBLK_LCKCNT) {
3102 			panic("too high lckcnt-hmeblk %p",
3103 			    (void *)hmeblkp);
3104 		}
3105 		atomic_add_32(&hmeblkp->hblk_lckcnt, 1);
3106 
3107 		HBLK_STACK_TRACE(hmeblkp, HBLK_LOCK);
3108 	}
3109 
3110 #ifdef VAC
3111 	if (pp && PP_ISNC(pp)) {
3112 		/*
3113 		 * If the physical page is marked to be uncacheable, like
3114 		 * by a vac conflict, make sure the new mapping is also
3115 		 * uncacheable.
3116 		 */
3117 		TTE_CLR_VCACHEABLE(ttep);
3118 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
3119 	}
3120 #endif
3121 	ttep->tte_hmenum = hmenum;
3122 
3123 #ifdef DEBUG
3124 	orig_old = tteold;
3125 #endif /* DEBUG */
3126 
3127 	while (sfmmu_modifytte_try(&tteold, ttep, &sfhme->hme_tte) < 0) {
3128 		if ((sfmmup == KHATID) &&
3129 		    (flags & (HAT_LOAD_LOCK | HAT_LOAD_REMAP))) {
3130 			sfmmu_copytte(&sfhme->hme_tte, &tteold);
3131 		}
3132 #ifdef DEBUG
3133 		chk_tte(&orig_old, &tteold, ttep, hmeblkp);
3134 #endif /* DEBUG */
3135 	}
3136 	ASSERT(TTE_IS_VALID(&sfhme->hme_tte));
3137 
3138 	if (!TTE_IS_VALID(&tteold)) {
3139 
3140 		atomic_add_16(&hmeblkp->hblk_vcnt, 1);
3141 		if (rid == SFMMU_INVALID_SHMERID) {
3142 			atomic_add_long(&sfmmup->sfmmu_ttecnt[size], 1);
3143 		} else {
3144 			sf_srd_t *srdp = sfmmup->sfmmu_srdp;
3145 			sf_region_t *rgnp = srdp->srd_hmergnp[rid];
3146 			/*
3147 			 * We already accounted for region ttecnt's in sfmmu
3148 			 * during hat_join_region() processing. Here we
3149 			 * only update ttecnt's in region struture.
3150 			 */
3151 			atomic_add_long(&rgnp->rgn_ttecnt[size], 1);
3152 		}
3153 	}
3154 
3155 	myflt = (astosfmmu(curthread->t_procp->p_as) == sfmmup);
3156 	if (size > TTE8K && (flags & HAT_LOAD_SHARE) == 0 &&
3157 	    sfmmup != ksfmmup) {
3158 		uchar_t tteflag = 1 << size;
3159 		if (rid == SFMMU_INVALID_SHMERID) {
3160 			if (!(sfmmup->sfmmu_tteflags & tteflag)) {
3161 				hatlockp = sfmmu_hat_enter(sfmmup);
3162 				sfmmup->sfmmu_tteflags |= tteflag;
3163 				sfmmu_hat_exit(hatlockp);
3164 			}
3165 		} else if (!(sfmmup->sfmmu_rtteflags & tteflag)) {
3166 			hatlockp = sfmmu_hat_enter(sfmmup);
3167 			sfmmup->sfmmu_rtteflags |= tteflag;
3168 			sfmmu_hat_exit(hatlockp);
3169 		}
3170 		/*
3171 		 * Update the current CPU tsbmiss area, so the current thread
3172 		 * won't need to take the tsbmiss for the new pagesize.
3173 		 * The other threads in the process will update their tsb
3174 		 * miss area lazily in sfmmu_tsbmiss_exception() when they
3175 		 * fail to find the translation for a newly added pagesize.
3176 		 */
3177 		if (size > TTE64K && myflt) {
3178 			struct tsbmiss *tsbmp;
3179 			kpreempt_disable();
3180 			tsbmp = &tsbmiss_area[CPU->cpu_id];
3181 			if (rid == SFMMU_INVALID_SHMERID) {
3182 				if (!(tsbmp->uhat_tteflags & tteflag)) {
3183 					tsbmp->uhat_tteflags |= tteflag;
3184 				}
3185 			} else {
3186 				if (!(tsbmp->uhat_rtteflags & tteflag)) {
3187 					tsbmp->uhat_rtteflags |= tteflag;
3188 				}
3189 			}
3190 			kpreempt_enable();
3191 		}
3192 	}
3193 
3194 	if (size >= TTE4M && (flags & HAT_LOAD_TEXT) &&
3195 	    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
3196 		hatlockp = sfmmu_hat_enter(sfmmup);
3197 		SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
3198 		sfmmu_hat_exit(hatlockp);
3199 	}
3200 
3201 	flush_tte.tte_intlo = (tteold.tte_intlo ^ ttep->tte_intlo) &
3202 	    hw_tte.tte_intlo;
3203 	flush_tte.tte_inthi = (tteold.tte_inthi ^ ttep->tte_inthi) &
3204 	    hw_tte.tte_inthi;
3205 
3206 	if (remap && (flush_tte.tte_inthi || flush_tte.tte_intlo)) {
3207 		/*
3208 		 * If remap and new tte differs from old tte we need
3209 		 * to sync the mod bit and flush TLB/TSB.  We don't
3210 		 * need to sync ref bit because we currently always set
3211 		 * ref bit in tteload.
3212 		 */
3213 		ASSERT(TTE_IS_REF(ttep));
3214 		if (TTE_IS_MOD(&tteold)) {
3215 			sfmmu_ttesync(sfmmup, vaddr, &tteold, pp);
3216 		}
3217 		/*
3218 		 * hwtte bits shouldn't change for SRD hmeblks as long as SRD
3219 		 * hmes are only used for read only text. Adding this code for
3220 		 * completeness and future use of shared hmeblks with writable
3221 		 * mappings of VMODSORT vnodes.
3222 		 */
3223 		if (hmeblkp->hblk_shared) {
3224 			cpuset_t cpuset = sfmmu_rgntlb_demap(vaddr,
3225 			    sfmmup->sfmmu_srdp->srd_hmergnp[rid], hmeblkp, 1);
3226 			xt_sync(cpuset);
3227 			SFMMU_STAT_ADD(sf_region_remap_demap, 1);
3228 		} else {
3229 			sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 0);
3230 			xt_sync(sfmmup->sfmmu_cpusran);
3231 		}
3232 	}
3233 
3234 	if ((flags & SFMMU_NO_TSBLOAD) == 0) {
3235 		/*
3236 		 * We only preload 8K and 4M mappings into the TSB, since
3237 		 * 64K and 512K mappings are replicated and hence don't
3238 		 * have a single, unique TSB entry. Ditto for 32M/256M.
3239 		 */
3240 		if (size == TTE8K || size == TTE4M) {
3241 			sf_scd_t *scdp;
3242 			hatlockp = sfmmu_hat_enter(sfmmup);
3243 			/*
3244 			 * Don't preload private TSB if the mapping is used
3245 			 * by the shctx in the SCD.
3246 			 */
3247 			scdp = sfmmup->sfmmu_scdp;
3248 			if (rid == SFMMU_INVALID_SHMERID || scdp == NULL ||
3249 			    !SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
3250 				sfmmu_load_tsb(sfmmup, vaddr, &sfhme->hme_tte,
3251 				    size);
3252 			}
3253 			sfmmu_hat_exit(hatlockp);
3254 		}
3255 	}
3256 	if (pp) {
3257 		if (!remap) {
3258 			HME_ADD(sfhme, pp);
3259 			atomic_add_16(&hmeblkp->hblk_hmecnt, 1);
3260 			ASSERT(hmeblkp->hblk_hmecnt > 0);
3261 
3262 			/*
3263 			 * Cannot ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
3264 			 * see pageunload() for comment.
3265 			 */
3266 		}
3267 		sfmmu_mlist_exit(pml);
3268 	}
3269 
3270 	return (0);
3271 }
3272 /*
3273  * Function unlocks hash bucket.
3274  */
3275 static void
3276 sfmmu_tteload_release_hashbucket(struct hmehash_bucket *hmebp)
3277 {
3278 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3279 	SFMMU_HASH_UNLOCK(hmebp);
3280 }
3281 
3282 /*
3283  * function which checks and sets up page array for a large
3284  * translation.  Will set p_vcolor, p_index, p_ro fields.
3285  * Assumes addr and pfnum of first page are properly aligned.
3286  * Will check for physical contiguity. If check fails it return
3287  * non null.
3288  */
3289 static int
3290 sfmmu_pagearray_setup(caddr_t addr, page_t **pps, tte_t *ttep, int remap)
3291 {
3292 	int 	i, index, ttesz;
3293 	pfn_t	pfnum;
3294 	pgcnt_t	npgs;
3295 	page_t *pp, *pp1;
3296 	kmutex_t *pmtx;
3297 #ifdef VAC
3298 	int osz;
3299 	int cflags = 0;
3300 	int vac_err = 0;
3301 #endif
3302 	int newidx = 0;
3303 
3304 	ttesz = TTE_CSZ(ttep);
3305 
3306 	ASSERT(ttesz > TTE8K);
3307 
3308 	npgs = TTEPAGES(ttesz);
3309 	index = PAGESZ_TO_INDEX(ttesz);
3310 
3311 	pfnum = (*pps)->p_pagenum;
3312 	ASSERT(IS_P2ALIGNED(pfnum, npgs));
3313 
3314 	/*
3315 	 * Save the first pp so we can do HAT_TMPNC at the end.
3316 	 */
3317 	pp1 = *pps;
3318 #ifdef VAC
3319 	osz = fnd_mapping_sz(pp1);
3320 #endif
3321 
3322 	for (i = 0; i < npgs; i++, pps++) {
3323 		pp = *pps;
3324 		ASSERT(PAGE_LOCKED(pp));
3325 		ASSERT(pp->p_szc >= ttesz);
3326 		ASSERT(pp->p_szc == pp1->p_szc);
3327 		ASSERT(sfmmu_mlist_held(pp));
3328 
3329 		/*
3330 		 * XXX is it possible to maintain P_RO on the root only?
3331 		 */
3332 		if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3333 			pmtx = sfmmu_page_enter(pp);
3334 			PP_CLRRO(pp);
3335 			sfmmu_page_exit(pmtx);
3336 		} else if (!PP_ISMAPPED(pp) && !TTE_IS_WRITABLE(ttep) &&
3337 		    !PP_ISMOD(pp)) {
3338 			pmtx = sfmmu_page_enter(pp);
3339 			if (!(PP_ISMOD(pp))) {
3340 				PP_SETRO(pp);
3341 			}
3342 			sfmmu_page_exit(pmtx);
3343 		}
3344 
3345 		/*
3346 		 * If this is a remap we skip vac & contiguity checks.
3347 		 */
3348 		if (remap)
3349 			continue;
3350 
3351 		/*
3352 		 * set p_vcolor and detect any vac conflicts.
3353 		 */
3354 #ifdef VAC
3355 		if (vac_err == 0) {
3356 			vac_err = sfmmu_vacconflict_array(addr, pp, &cflags);
3357 
3358 		}
3359 #endif
3360 
3361 		/*
3362 		 * Save current index in case we need to undo it.
3363 		 * Note: "PAGESZ_TO_INDEX(sz)	(1 << (sz))"
3364 		 *	"SFMMU_INDEX_SHIFT	6"
3365 		 *	 "SFMMU_INDEX_MASK	((1 << SFMMU_INDEX_SHIFT) - 1)"
3366 		 *	 "PP_MAPINDEX(p_index)	(p_index & SFMMU_INDEX_MASK)"
3367 		 *
3368 		 * So:	index = PAGESZ_TO_INDEX(ttesz);
3369 		 *	if ttesz == 1 then index = 0x2
3370 		 *		    2 then index = 0x4
3371 		 *		    3 then index = 0x8
3372 		 *		    4 then index = 0x10
3373 		 *		    5 then index = 0x20
3374 		 * The code below checks if it's a new pagesize (ie, newidx)
3375 		 * in case we need to take it back out of p_index,
3376 		 * and then or's the new index into the existing index.
3377 		 */
3378 		if ((PP_MAPINDEX(pp) & index) == 0)
3379 			newidx = 1;
3380 		pp->p_index = (PP_MAPINDEX(pp) | index);
3381 
3382 		/*
3383 		 * contiguity check
3384 		 */
3385 		if (pp->p_pagenum != pfnum) {
3386 			/*
3387 			 * If we fail the contiguity test then
3388 			 * the only thing we need to fix is the p_index field.
3389 			 * We might get a few extra flushes but since this
3390 			 * path is rare that is ok.  The p_ro field will
3391 			 * get automatically fixed on the next tteload to
3392 			 * the page.  NO TNC bit is set yet.
3393 			 */
3394 			while (i >= 0) {
3395 				pp = *pps;
3396 				if (newidx)
3397 					pp->p_index = (PP_MAPINDEX(pp) &
3398 					    ~index);
3399 				pps--;
3400 				i--;
3401 			}
3402 			return (1);
3403 		}
3404 		pfnum++;
3405 		addr += MMU_PAGESIZE;
3406 	}
3407 
3408 #ifdef VAC
3409 	if (vac_err) {
3410 		if (ttesz > osz) {
3411 			/*
3412 			 * There are some smaller mappings that causes vac
3413 			 * conflicts. Convert all existing small mappings to
3414 			 * TNC.
3415 			 */
3416 			SFMMU_STAT_ADD(sf_uncache_conflict, npgs);
3417 			sfmmu_page_cache_array(pp1, HAT_TMPNC, CACHE_FLUSH,
3418 			    npgs);
3419 		} else {
3420 			/* EMPTY */
3421 			/*
3422 			 * If there exists an big page mapping,
3423 			 * that means the whole existing big page
3424 			 * has TNC setting already. No need to covert to
3425 			 * TNC again.
3426 			 */
3427 			ASSERT(PP_ISTNC(pp1));
3428 		}
3429 	}
3430 #endif	/* VAC */
3431 
3432 	return (0);
3433 }
3434 
3435 #ifdef VAC
3436 /*
3437  * Routine that detects vac consistency for a large page. It also
3438  * sets virtual color for all pp's for this big mapping.
3439  */
3440 static int
3441 sfmmu_vacconflict_array(caddr_t addr, page_t *pp, int *cflags)
3442 {
3443 	int vcolor, ocolor;
3444 
3445 	ASSERT(sfmmu_mlist_held(pp));
3446 
3447 	if (PP_ISNC(pp)) {
3448 		return (HAT_TMPNC);
3449 	}
3450 
3451 	vcolor = addr_to_vcolor(addr);
3452 	if (PP_NEWPAGE(pp)) {
3453 		PP_SET_VCOLOR(pp, vcolor);
3454 		return (0);
3455 	}
3456 
3457 	ocolor = PP_GET_VCOLOR(pp);
3458 	if (ocolor == vcolor) {
3459 		return (0);
3460 	}
3461 
3462 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
3463 		/*
3464 		 * Previous user of page had a differnet color
3465 		 * but since there are no current users
3466 		 * we just flush the cache and change the color.
3467 		 * As an optimization for large pages we flush the
3468 		 * entire cache of that color and set a flag.
3469 		 */
3470 		SFMMU_STAT(sf_pgcolor_conflict);
3471 		if (!CacheColor_IsFlushed(*cflags, ocolor)) {
3472 			CacheColor_SetFlushed(*cflags, ocolor);
3473 			sfmmu_cache_flushcolor(ocolor, pp->p_pagenum);
3474 		}
3475 		PP_SET_VCOLOR(pp, vcolor);
3476 		return (0);
3477 	}
3478 
3479 	/*
3480 	 * We got a real conflict with a current mapping.
3481 	 * set flags to start unencaching all mappings
3482 	 * and return failure so we restart looping
3483 	 * the pp array from the beginning.
3484 	 */
3485 	return (HAT_TMPNC);
3486 }
3487 #endif	/* VAC */
3488 
3489 /*
3490  * creates a large page shadow hmeblk for a tte.
3491  * The purpose of this routine is to allow us to do quick unloads because
3492  * the vm layer can easily pass a very large but sparsely populated range.
3493  */
3494 static struct hme_blk *
3495 sfmmu_shadow_hcreate(sfmmu_t *sfmmup, caddr_t vaddr, int ttesz, uint_t flags)
3496 {
3497 	struct hmehash_bucket *hmebp;
3498 	hmeblk_tag hblktag;
3499 	int hmeshift, size, vshift;
3500 	uint_t shw_mask, newshw_mask;
3501 	struct hme_blk *hmeblkp;
3502 
3503 	ASSERT(sfmmup != KHATID);
3504 	if (mmu_page_sizes == max_mmu_page_sizes) {
3505 		ASSERT(ttesz < TTE256M);
3506 	} else {
3507 		ASSERT(ttesz < TTE4M);
3508 		ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
3509 		ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
3510 	}
3511 
3512 	if (ttesz == TTE8K) {
3513 		size = TTE512K;
3514 	} else {
3515 		size = ++ttesz;
3516 	}
3517 
3518 	hblktag.htag_id = sfmmup;
3519 	hmeshift = HME_HASH_SHIFT(size);
3520 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
3521 	hblktag.htag_rehash = HME_HASH_REHASH(size);
3522 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3523 	hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
3524 
3525 	SFMMU_HASH_LOCK(hmebp);
3526 
3527 	HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
3528 	ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
3529 	if (hmeblkp == NULL) {
3530 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
3531 		    hblktag, flags, SFMMU_INVALID_SHMERID);
3532 	}
3533 	ASSERT(hmeblkp);
3534 	if (!hmeblkp->hblk_shw_mask) {
3535 		/*
3536 		 * if this is a unused hblk it was just allocated or could
3537 		 * potentially be a previous large page hblk so we need to
3538 		 * set the shadow bit.
3539 		 */
3540 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3541 		hmeblkp->hblk_shw_bit = 1;
3542 	} else if (hmeblkp->hblk_shw_bit == 0) {
3543 		panic("sfmmu_shadow_hcreate: shw bit not set in hmeblkp 0x%p",
3544 		    (void *)hmeblkp);
3545 	}
3546 	ASSERT(hmeblkp->hblk_shw_bit == 1);
3547 	ASSERT(!hmeblkp->hblk_shared);
3548 	vshift = vaddr_to_vshift(hblktag, vaddr, size);
3549 	ASSERT(vshift < 8);
3550 	/*
3551 	 * Atomically set shw mask bit
3552 	 */
3553 	do {
3554 		shw_mask = hmeblkp->hblk_shw_mask;
3555 		newshw_mask = shw_mask | (1 << vshift);
3556 		newshw_mask = cas32(&hmeblkp->hblk_shw_mask, shw_mask,
3557 		    newshw_mask);
3558 	} while (newshw_mask != shw_mask);
3559 
3560 	SFMMU_HASH_UNLOCK(hmebp);
3561 
3562 	return (hmeblkp);
3563 }
3564 
3565 /*
3566  * This routine cleanup a previous shadow hmeblk and changes it to
3567  * a regular hblk.  This happens rarely but it is possible
3568  * when a process wants to use large pages and there are hblks still
3569  * lying around from the previous as that used these hmeblks.
3570  * The alternative was to cleanup the shadow hblks at unload time
3571  * but since so few user processes actually use large pages, it is
3572  * better to be lazy and cleanup at this time.
3573  */
3574 static void
3575 sfmmu_shadow_hcleanup(sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
3576 	struct hmehash_bucket *hmebp)
3577 {
3578 	caddr_t addr, endaddr;
3579 	int hashno, size;
3580 
3581 	ASSERT(hmeblkp->hblk_shw_bit);
3582 	ASSERT(!hmeblkp->hblk_shared);
3583 
3584 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3585 
3586 	if (!hmeblkp->hblk_shw_mask) {
3587 		hmeblkp->hblk_shw_bit = 0;
3588 		return;
3589 	}
3590 	addr = (caddr_t)get_hblk_base(hmeblkp);
3591 	endaddr = get_hblk_endaddr(hmeblkp);
3592 	size = get_hblk_ttesz(hmeblkp);
3593 	hashno = size - 1;
3594 	ASSERT(hashno > 0);
3595 	SFMMU_HASH_UNLOCK(hmebp);
3596 
3597 	sfmmu_free_hblks(sfmmup, addr, endaddr, hashno);
3598 
3599 	SFMMU_HASH_LOCK(hmebp);
3600 }
3601 
3602 static void
3603 sfmmu_free_hblks(sfmmu_t *sfmmup, caddr_t addr, caddr_t endaddr,
3604 	int hashno)
3605 {
3606 	int hmeshift, shadow = 0;
3607 	hmeblk_tag hblktag;
3608 	struct hmehash_bucket *hmebp;
3609 	struct hme_blk *hmeblkp;
3610 	struct hme_blk *nx_hblk, *pr_hblk, *list = NULL;
3611 
3612 	ASSERT(hashno > 0);
3613 	hblktag.htag_id = sfmmup;
3614 	hblktag.htag_rehash = hashno;
3615 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3616 
3617 	hmeshift = HME_HASH_SHIFT(hashno);
3618 
3619 	while (addr < endaddr) {
3620 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3621 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3622 		SFMMU_HASH_LOCK(hmebp);
3623 		/* inline HME_HASH_SEARCH */
3624 		hmeblkp = hmebp->hmeblkp;
3625 		pr_hblk = NULL;
3626 		while (hmeblkp) {
3627 			if (HTAGS_EQ(hmeblkp->hblk_tag, hblktag)) {
3628 				/* found hme_blk */
3629 				ASSERT(!hmeblkp->hblk_shared);
3630 				if (hmeblkp->hblk_shw_bit) {
3631 					if (hmeblkp->hblk_shw_mask) {
3632 						shadow = 1;
3633 						sfmmu_shadow_hcleanup(sfmmup,
3634 						    hmeblkp, hmebp);
3635 						break;
3636 					} else {
3637 						hmeblkp->hblk_shw_bit = 0;
3638 					}
3639 				}
3640 
3641 				/*
3642 				 * Hblk_hmecnt and hblk_vcnt could be non zero
3643 				 * since hblk_unload() does not gurantee that.
3644 				 *
3645 				 * XXX - this could cause tteload() to spin
3646 				 * where sfmmu_shadow_hcleanup() is called.
3647 				 */
3648 			}
3649 
3650 			nx_hblk = hmeblkp->hblk_next;
3651 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
3652 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3653 				    &list, 0);
3654 			} else {
3655 				pr_hblk = hmeblkp;
3656 			}
3657 			hmeblkp = nx_hblk;
3658 		}
3659 
3660 		SFMMU_HASH_UNLOCK(hmebp);
3661 
3662 		if (shadow) {
3663 			/*
3664 			 * We found another shadow hblk so cleaned its
3665 			 * children.  We need to go back and cleanup
3666 			 * the original hblk so we don't change the
3667 			 * addr.
3668 			 */
3669 			shadow = 0;
3670 		} else {
3671 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
3672 			    (1 << hmeshift));
3673 		}
3674 	}
3675 	sfmmu_hblks_list_purge(&list, 0);
3676 }
3677 
3678 /*
3679  * This routine's job is to delete stale invalid shared hmeregions hmeblks that
3680  * may still linger on after pageunload.
3681  */
3682 static void
3683 sfmmu_cleanup_rhblk(sf_srd_t *srdp, caddr_t addr, uint_t rid, int ttesz)
3684 {
3685 	int hmeshift;
3686 	hmeblk_tag hblktag;
3687 	struct hmehash_bucket *hmebp;
3688 	struct hme_blk *hmeblkp;
3689 	struct hme_blk *pr_hblk;
3690 	struct hme_blk *list = NULL;
3691 
3692 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3693 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3694 
3695 	hmeshift = HME_HASH_SHIFT(ttesz);
3696 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3697 	hblktag.htag_rehash = ttesz;
3698 	hblktag.htag_rid = rid;
3699 	hblktag.htag_id = srdp;
3700 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3701 
3702 	SFMMU_HASH_LOCK(hmebp);
3703 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
3704 	if (hmeblkp != NULL) {
3705 		ASSERT(hmeblkp->hblk_shared);
3706 		ASSERT(!hmeblkp->hblk_shw_bit);
3707 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3708 			panic("sfmmu_cleanup_rhblk: valid hmeblk");
3709 		}
3710 		ASSERT(!hmeblkp->hblk_lckcnt);
3711 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3712 		    &list, 0);
3713 	}
3714 	SFMMU_HASH_UNLOCK(hmebp);
3715 	sfmmu_hblks_list_purge(&list, 0);
3716 }
3717 
3718 /* ARGSUSED */
3719 static void
3720 sfmmu_rgn_cb_noop(caddr_t saddr, caddr_t eaddr, caddr_t r_saddr,
3721     size_t r_size, void *r_obj, u_offset_t r_objoff)
3722 {
3723 }
3724 
3725 /*
3726  * Searches for an hmeblk which maps addr, then unloads this mapping
3727  * and updates *eaddrp, if the hmeblk is found.
3728  */
3729 static void
3730 sfmmu_unload_hmeregion_va(sf_srd_t *srdp, uint_t rid, caddr_t addr,
3731     caddr_t eaddr, int ttesz, caddr_t *eaddrp)
3732 {
3733 	int hmeshift;
3734 	hmeblk_tag hblktag;
3735 	struct hmehash_bucket *hmebp;
3736 	struct hme_blk *hmeblkp;
3737 	struct hme_blk *pr_hblk;
3738 	struct hme_blk *list = NULL;
3739 
3740 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3741 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3742 	ASSERT(ttesz >= HBLK_MIN_TTESZ);
3743 
3744 	hmeshift = HME_HASH_SHIFT(ttesz);
3745 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3746 	hblktag.htag_rehash = ttesz;
3747 	hblktag.htag_rid = rid;
3748 	hblktag.htag_id = srdp;
3749 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3750 
3751 	SFMMU_HASH_LOCK(hmebp);
3752 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
3753 	if (hmeblkp != NULL) {
3754 		ASSERT(hmeblkp->hblk_shared);
3755 		ASSERT(!hmeblkp->hblk_lckcnt);
3756 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3757 			*eaddrp = sfmmu_hblk_unload(NULL, hmeblkp, addr,
3758 			    eaddr, NULL, HAT_UNLOAD);
3759 			ASSERT(*eaddrp > addr);
3760 		}
3761 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3762 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3763 		    &list, 0);
3764 	}
3765 	SFMMU_HASH_UNLOCK(hmebp);
3766 	sfmmu_hblks_list_purge(&list, 0);
3767 }
3768 
3769 static void
3770 sfmmu_unload_hmeregion(sf_srd_t *srdp, sf_region_t *rgnp)
3771 {
3772 	int ttesz = rgnp->rgn_pgszc;
3773 	size_t rsz = rgnp->rgn_size;
3774 	caddr_t rsaddr = rgnp->rgn_saddr;
3775 	caddr_t readdr = rsaddr + rsz;
3776 	caddr_t rhsaddr;
3777 	caddr_t va;
3778 	uint_t rid = rgnp->rgn_id;
3779 	caddr_t cbsaddr;
3780 	caddr_t cbeaddr;
3781 	hat_rgn_cb_func_t rcbfunc;
3782 	ulong_t cnt;
3783 
3784 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3785 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3786 
3787 	ASSERT(IS_P2ALIGNED(rsaddr, TTEBYTES(ttesz)));
3788 	ASSERT(IS_P2ALIGNED(rsz, TTEBYTES(ttesz)));
3789 	if (ttesz < HBLK_MIN_TTESZ) {
3790 		ttesz = HBLK_MIN_TTESZ;
3791 		rhsaddr = (caddr_t)P2ALIGN((uintptr_t)rsaddr, HBLK_MIN_BYTES);
3792 	} else {
3793 		rhsaddr = rsaddr;
3794 	}
3795 
3796 	if ((rcbfunc = rgnp->rgn_cb_function) == NULL) {
3797 		rcbfunc = sfmmu_rgn_cb_noop;
3798 	}
3799 
3800 	while (ttesz >= HBLK_MIN_TTESZ) {
3801 		cbsaddr = rsaddr;
3802 		cbeaddr = rsaddr;
3803 		if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
3804 			ttesz--;
3805 			continue;
3806 		}
3807 		cnt = 0;
3808 		va = rsaddr;
3809 		while (va < readdr) {
3810 			ASSERT(va >= rhsaddr);
3811 			if (va != cbeaddr) {
3812 				if (cbeaddr != cbsaddr) {
3813 					ASSERT(cbeaddr > cbsaddr);
3814 					(*rcbfunc)(cbsaddr, cbeaddr,
3815 					    rsaddr, rsz, rgnp->rgn_obj,
3816 					    rgnp->rgn_objoff);
3817 				}
3818 				cbsaddr = va;
3819 				cbeaddr = va;
3820 			}
3821 			sfmmu_unload_hmeregion_va(srdp, rid, va, readdr,
3822 			    ttesz, &cbeaddr);
3823 			cnt++;
3824 			va = rhsaddr + (cnt << TTE_PAGE_SHIFT(ttesz));
3825 		}
3826 		if (cbeaddr != cbsaddr) {
3827 			ASSERT(cbeaddr > cbsaddr);
3828 			(*rcbfunc)(cbsaddr, cbeaddr, rsaddr,
3829 			    rsz, rgnp->rgn_obj,
3830 			    rgnp->rgn_objoff);
3831 		}
3832 		ttesz--;
3833 	}
3834 }
3835 
3836 /*
3837  * Release one hardware address translation lock on the given address range.
3838  */
3839 void
3840 hat_unlock(struct hat *sfmmup, caddr_t addr, size_t len)
3841 {
3842 	struct hmehash_bucket *hmebp;
3843 	hmeblk_tag hblktag;
3844 	int hmeshift, hashno = 1;
3845 	struct hme_blk *hmeblkp, *list = NULL;
3846 	caddr_t endaddr;
3847 
3848 	ASSERT(sfmmup != NULL);
3849 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
3850 
3851 	ASSERT((sfmmup == ksfmmup) ||
3852 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
3853 	ASSERT((len & MMU_PAGEOFFSET) == 0);
3854 	endaddr = addr + len;
3855 	hblktag.htag_id = sfmmup;
3856 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3857 
3858 	/*
3859 	 * Spitfire supports 4 page sizes.
3860 	 * Most pages are expected to be of the smallest page size (8K) and
3861 	 * these will not need to be rehashed. 64K pages also don't need to be
3862 	 * rehashed because an hmeblk spans 64K of address space. 512K pages
3863 	 * might need 1 rehash and and 4M pages might need 2 rehashes.
3864 	 */
3865 	while (addr < endaddr) {
3866 		hmeshift = HME_HASH_SHIFT(hashno);
3867 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3868 		hblktag.htag_rehash = hashno;
3869 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3870 
3871 		SFMMU_HASH_LOCK(hmebp);
3872 
3873 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
3874 		if (hmeblkp != NULL) {
3875 			ASSERT(!hmeblkp->hblk_shared);
3876 			/*
3877 			 * If we encounter a shadow hmeblk then
3878 			 * we know there are no valid hmeblks mapping
3879 			 * this address at this size or larger.
3880 			 * Just increment address by the smallest
3881 			 * page size.
3882 			 */
3883 			if (hmeblkp->hblk_shw_bit) {
3884 				addr += MMU_PAGESIZE;
3885 			} else {
3886 				addr = sfmmu_hblk_unlock(hmeblkp, addr,
3887 				    endaddr);
3888 			}
3889 			SFMMU_HASH_UNLOCK(hmebp);
3890 			hashno = 1;
3891 			continue;
3892 		}
3893 		SFMMU_HASH_UNLOCK(hmebp);
3894 
3895 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
3896 			/*
3897 			 * We have traversed the whole list and rehashed
3898 			 * if necessary without finding the address to unlock
3899 			 * which should never happen.
3900 			 */
3901 			panic("sfmmu_unlock: addr not found. "
3902 			    "addr %p hat %p", (void *)addr, (void *)sfmmup);
3903 		} else {
3904 			hashno++;
3905 		}
3906 	}
3907 
3908 	sfmmu_hblks_list_purge(&list, 0);
3909 }
3910 
3911 void
3912 hat_unlock_region(struct hat *sfmmup, caddr_t addr, size_t len,
3913     hat_region_cookie_t rcookie)
3914 {
3915 	sf_srd_t *srdp;
3916 	sf_region_t *rgnp;
3917 	int ttesz;
3918 	uint_t rid;
3919 	caddr_t eaddr;
3920 	caddr_t va;
3921 	int hmeshift;
3922 	hmeblk_tag hblktag;
3923 	struct hmehash_bucket *hmebp;
3924 	struct hme_blk *hmeblkp;
3925 	struct hme_blk *pr_hblk;
3926 	struct hme_blk *list;
3927 
3928 	if (rcookie == HAT_INVALID_REGION_COOKIE) {
3929 		hat_unlock(sfmmup, addr, len);
3930 		return;
3931 	}
3932 
3933 	ASSERT(sfmmup != NULL);
3934 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
3935 	ASSERT(sfmmup != ksfmmup);
3936 
3937 	srdp = sfmmup->sfmmu_srdp;
3938 	rid = (uint_t)((uint64_t)rcookie);
3939 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3940 	eaddr = addr + len;
3941 	va = addr;
3942 	list = NULL;
3943 	rgnp = srdp->srd_hmergnp[rid];
3944 	SFMMU_VALIDATE_HMERID(sfmmup, rid, addr, len);
3945 
3946 	ASSERT(IS_P2ALIGNED(addr, TTEBYTES(rgnp->rgn_pgszc)));
3947 	ASSERT(IS_P2ALIGNED(len, TTEBYTES(rgnp->rgn_pgszc)));
3948 	if (rgnp->rgn_pgszc < HBLK_MIN_TTESZ) {
3949 		ttesz = HBLK_MIN_TTESZ;
3950 	} else {
3951 		ttesz = rgnp->rgn_pgszc;
3952 	}
3953 	while (va < eaddr) {
3954 		while (ttesz < rgnp->rgn_pgszc &&
3955 		    IS_P2ALIGNED(va, TTEBYTES(ttesz + 1))) {
3956 			ttesz++;
3957 		}
3958 		while (ttesz >= HBLK_MIN_TTESZ) {
3959 			if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
3960 				ttesz--;
3961 				continue;
3962 			}
3963 			hmeshift = HME_HASH_SHIFT(ttesz);
3964 			hblktag.htag_bspage = HME_HASH_BSPAGE(va, hmeshift);
3965 			hblktag.htag_rehash = ttesz;
3966 			hblktag.htag_rid = rid;
3967 			hblktag.htag_id = srdp;
3968 			hmebp = HME_HASH_FUNCTION(srdp, va, hmeshift);
3969 			SFMMU_HASH_LOCK(hmebp);
3970 			HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk,
3971 			    &list);
3972 			if (hmeblkp == NULL) {
3973 				SFMMU_HASH_UNLOCK(hmebp);
3974 				ttesz--;
3975 				continue;
3976 			}
3977 			ASSERT(hmeblkp->hblk_shared);
3978 			va = sfmmu_hblk_unlock(hmeblkp, va, eaddr);
3979 			ASSERT(va >= eaddr ||
3980 			    IS_P2ALIGNED((uintptr_t)va, TTEBYTES(ttesz)));
3981 			SFMMU_HASH_UNLOCK(hmebp);
3982 			break;
3983 		}
3984 		if (ttesz < HBLK_MIN_TTESZ) {
3985 			panic("hat_unlock_region: addr not found "
3986 			    "addr %p hat %p", (void *)va, (void *)sfmmup);
3987 		}
3988 	}
3989 	sfmmu_hblks_list_purge(&list, 0);
3990 }
3991 
3992 /*
3993  * Function to unlock a range of addresses in an hmeblk.  It returns the
3994  * next address that needs to be unlocked.
3995  * Should be called with the hash lock held.
3996  */
3997 static caddr_t
3998 sfmmu_hblk_unlock(struct hme_blk *hmeblkp, caddr_t addr, caddr_t endaddr)
3999 {
4000 	struct sf_hment *sfhme;
4001 	tte_t tteold, ttemod;
4002 	int ttesz, ret;
4003 
4004 	ASSERT(in_hblk_range(hmeblkp, addr));
4005 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4006 
4007 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4008 	ttesz = get_hblk_ttesz(hmeblkp);
4009 
4010 	HBLKTOHME(sfhme, hmeblkp, addr);
4011 	while (addr < endaddr) {
4012 readtte:
4013 		sfmmu_copytte(&sfhme->hme_tte, &tteold);
4014 		if (TTE_IS_VALID(&tteold)) {
4015 
4016 			ttemod = tteold;
4017 
4018 			ret = sfmmu_modifytte_try(&tteold, &ttemod,
4019 			    &sfhme->hme_tte);
4020 
4021 			if (ret < 0)
4022 				goto readtte;
4023 
4024 			if (hmeblkp->hblk_lckcnt == 0)
4025 				panic("zero hblk lckcnt");
4026 
4027 			if (((uintptr_t)addr + TTEBYTES(ttesz)) >
4028 			    (uintptr_t)endaddr)
4029 				panic("can't unlock large tte");
4030 
4031 			ASSERT(hmeblkp->hblk_lckcnt > 0);
4032 			atomic_add_32(&hmeblkp->hblk_lckcnt, -1);
4033 			HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
4034 		} else {
4035 			panic("sfmmu_hblk_unlock: invalid tte");
4036 		}
4037 		addr += TTEBYTES(ttesz);
4038 		sfhme++;
4039 	}
4040 	return (addr);
4041 }
4042 
4043 /*
4044  * Physical Address Mapping Framework
4045  *
4046  * General rules:
4047  *
4048  * (1) Applies only to seg_kmem memory pages. To make things easier,
4049  *     seg_kpm addresses are also accepted by the routines, but nothing
4050  *     is done with them since by definition their PA mappings are static.
4051  * (2) hat_add_callback() may only be called while holding the page lock
4052  *     SE_SHARED or SE_EXCL of the underlying page (e.g., as_pagelock()),
4053  *     or passing HAC_PAGELOCK flag.
4054  * (3) prehandler() and posthandler() may not call hat_add_callback() or
4055  *     hat_delete_callback(), nor should they allocate memory. Post quiesce
4056  *     callbacks may not sleep or acquire adaptive mutex locks.
4057  * (4) Either prehandler() or posthandler() (but not both) may be specified
4058  *     as being NULL.  Specifying an errhandler() is optional.
4059  *
4060  * Details of using the framework:
4061  *
4062  * registering a callback (hat_register_callback())
4063  *
4064  *	Pass prehandler, posthandler, errhandler addresses
4065  *	as described below. If capture_cpus argument is nonzero,
4066  *	suspend callback to the prehandler will occur with CPUs
4067  *	captured and executing xc_loop() and CPUs will remain
4068  *	captured until after the posthandler suspend callback
4069  *	occurs.
4070  *
4071  * adding a callback (hat_add_callback())
4072  *
4073  *      as_pagelock();
4074  *	hat_add_callback();
4075  *      save returned pfn in private data structures or program registers;
4076  *      as_pageunlock();
4077  *
4078  * prehandler()
4079  *
4080  *	Stop all accesses by physical address to this memory page.
4081  *	Called twice: the first, PRESUSPEND, is a context safe to acquire
4082  *	adaptive locks. The second, SUSPEND, is called at high PIL with
4083  *	CPUs captured so adaptive locks may NOT be acquired (and all spin
4084  *	locks must be XCALL_PIL or higher locks).
4085  *
4086  *	May return the following errors:
4087  *		EIO:	A fatal error has occurred. This will result in panic.
4088  *		EAGAIN:	The page cannot be suspended. This will fail the
4089  *			relocation.
4090  *		0:	Success.
4091  *
4092  * posthandler()
4093  *
4094  *      Save new pfn in private data structures or program registers;
4095  *	not allowed to fail (non-zero return values will result in panic).
4096  *
4097  * errhandler()
4098  *
4099  *	called when an error occurs related to the callback.  Currently
4100  *	the only such error is HAT_CB_ERR_LEAKED which indicates that
4101  *	a page is being freed, but there are still outstanding callback(s)
4102  *	registered on the page.
4103  *
4104  * removing a callback (hat_delete_callback(); e.g., prior to freeing memory)
4105  *
4106  *	stop using physical address
4107  *	hat_delete_callback();
4108  *
4109  */
4110 
4111 /*
4112  * Register a callback class.  Each subsystem should do this once and
4113  * cache the id_t returned for use in setting up and tearing down callbacks.
4114  *
4115  * There is no facility for removing callback IDs once they are created;
4116  * the "key" should be unique for each module, so in case a module is unloaded
4117  * and subsequently re-loaded, we can recycle the module's previous entry.
4118  */
4119 id_t
4120 hat_register_callback(int key,
4121 	int (*prehandler)(caddr_t, uint_t, uint_t, void *),
4122 	int (*posthandler)(caddr_t, uint_t, uint_t, void *, pfn_t),
4123 	int (*errhandler)(caddr_t, uint_t, uint_t, void *),
4124 	int capture_cpus)
4125 {
4126 	id_t id;
4127 
4128 	/*
4129 	 * Search the table for a pre-existing callback associated with
4130 	 * the identifier "key".  If one exists, we re-use that entry in
4131 	 * the table for this instance, otherwise we assign the next
4132 	 * available table slot.
4133 	 */
4134 	for (id = 0; id < sfmmu_max_cb_id; id++) {
4135 		if (sfmmu_cb_table[id].key == key)
4136 			break;
4137 	}
4138 
4139 	if (id == sfmmu_max_cb_id) {
4140 		id = sfmmu_cb_nextid++;
4141 		if (id >= sfmmu_max_cb_id)
4142 			panic("hat_register_callback: out of callback IDs");
4143 	}
4144 
4145 	ASSERT(prehandler != NULL || posthandler != NULL);
4146 
4147 	sfmmu_cb_table[id].key = key;
4148 	sfmmu_cb_table[id].prehandler = prehandler;
4149 	sfmmu_cb_table[id].posthandler = posthandler;
4150 	sfmmu_cb_table[id].errhandler = errhandler;
4151 	sfmmu_cb_table[id].capture_cpus = capture_cpus;
4152 
4153 	return (id);
4154 }
4155 
4156 #define	HAC_COOKIE_NONE	(void *)-1
4157 
4158 /*
4159  * Add relocation callbacks to the specified addr/len which will be called
4160  * when relocating the associated page. See the description of pre and
4161  * posthandler above for more details.
4162  *
4163  * If HAC_PAGELOCK is included in flags, the underlying memory page is
4164  * locked internally so the caller must be able to deal with the callback
4165  * running even before this function has returned.  If HAC_PAGELOCK is not
4166  * set, it is assumed that the underlying memory pages are locked.
4167  *
4168  * Since the caller must track the individual page boundaries anyway,
4169  * we only allow a callback to be added to a single page (large
4170  * or small).  Thus [addr, addr + len) MUST be contained within a single
4171  * page.
4172  *
4173  * Registering multiple callbacks on the same [addr, addr+len) is supported,
4174  * _provided_that_ a unique parameter is specified for each callback.
4175  * If multiple callbacks are registered on the same range the callback will
4176  * be invoked with each unique parameter. Registering the same callback with
4177  * the same argument more than once will result in corrupted kernel state.
4178  *
4179  * Returns the pfn of the underlying kernel page in *rpfn
4180  * on success, or PFN_INVALID on failure.
4181  *
4182  * cookiep (if passed) provides storage space for an opaque cookie
4183  * to return later to hat_delete_callback(). This cookie makes the callback
4184  * deletion significantly quicker by avoiding a potentially lengthy hash
4185  * search.
4186  *
4187  * Returns values:
4188  *    0:      success
4189  *    ENOMEM: memory allocation failure (e.g. flags was passed as HAC_NOSLEEP)
4190  *    EINVAL: callback ID is not valid
4191  *    ENXIO:  ["vaddr", "vaddr" + len) is not mapped in the kernel's address
4192  *            space
4193  *    ERANGE: ["vaddr", "vaddr" + len) crosses a page boundary
4194  */
4195 int
4196 hat_add_callback(id_t callback_id, caddr_t vaddr, uint_t len, uint_t flags,
4197 	void *pvt, pfn_t *rpfn, void **cookiep)
4198 {
4199 	struct 		hmehash_bucket *hmebp;
4200 	hmeblk_tag 	hblktag;
4201 	struct hme_blk	*hmeblkp;
4202 	int 		hmeshift, hashno;
4203 	caddr_t 	saddr, eaddr, baseaddr;
4204 	struct pa_hment *pahmep;
4205 	struct sf_hment *sfhmep, *osfhmep;
4206 	kmutex_t	*pml;
4207 	tte_t   	tte;
4208 	page_t		*pp;
4209 	vnode_t		*vp;
4210 	u_offset_t	off;
4211 	pfn_t		pfn;
4212 	int		kmflags = (flags & HAC_SLEEP)? KM_SLEEP : KM_NOSLEEP;
4213 	int		locked = 0;
4214 
4215 	/*
4216 	 * For KPM mappings, just return the physical address since we
4217 	 * don't need to register any callbacks.
4218 	 */
4219 	if (IS_KPM_ADDR(vaddr)) {
4220 		uint64_t paddr;
4221 		SFMMU_KPM_VTOP(vaddr, paddr);
4222 		*rpfn = btop(paddr);
4223 		if (cookiep != NULL)
4224 			*cookiep = HAC_COOKIE_NONE;
4225 		return (0);
4226 	}
4227 
4228 	if (callback_id < (id_t)0 || callback_id >= sfmmu_cb_nextid) {
4229 		*rpfn = PFN_INVALID;
4230 		return (EINVAL);
4231 	}
4232 
4233 	if ((pahmep = kmem_cache_alloc(pa_hment_cache, kmflags)) == NULL) {
4234 		*rpfn = PFN_INVALID;
4235 		return (ENOMEM);
4236 	}
4237 
4238 	sfhmep = &pahmep->sfment;
4239 
4240 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4241 	eaddr = saddr + len;
4242 
4243 rehash:
4244 	/* Find the mapping(s) for this page */
4245 	for (hashno = TTE64K, hmeblkp = NULL;
4246 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4247 	    hashno++) {
4248 		hmeshift = HME_HASH_SHIFT(hashno);
4249 		hblktag.htag_id = ksfmmup;
4250 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4251 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4252 		hblktag.htag_rehash = hashno;
4253 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4254 
4255 		SFMMU_HASH_LOCK(hmebp);
4256 
4257 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4258 
4259 		if (hmeblkp == NULL)
4260 			SFMMU_HASH_UNLOCK(hmebp);
4261 	}
4262 
4263 	if (hmeblkp == NULL) {
4264 		kmem_cache_free(pa_hment_cache, pahmep);
4265 		*rpfn = PFN_INVALID;
4266 		return (ENXIO);
4267 	}
4268 
4269 	ASSERT(!hmeblkp->hblk_shared);
4270 
4271 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4272 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4273 
4274 	if (!TTE_IS_VALID(&tte)) {
4275 		SFMMU_HASH_UNLOCK(hmebp);
4276 		kmem_cache_free(pa_hment_cache, pahmep);
4277 		*rpfn = PFN_INVALID;
4278 		return (ENXIO);
4279 	}
4280 
4281 	/*
4282 	 * Make sure the boundaries for the callback fall within this
4283 	 * single mapping.
4284 	 */
4285 	baseaddr = (caddr_t)get_hblk_base(hmeblkp);
4286 	ASSERT(saddr >= baseaddr);
4287 	if (eaddr > saddr + TTEBYTES(TTE_CSZ(&tte))) {
4288 		SFMMU_HASH_UNLOCK(hmebp);
4289 		kmem_cache_free(pa_hment_cache, pahmep);
4290 		*rpfn = PFN_INVALID;
4291 		return (ERANGE);
4292 	}
4293 
4294 	pfn = sfmmu_ttetopfn(&tte, vaddr);
4295 
4296 	/*
4297 	 * The pfn may not have a page_t underneath in which case we
4298 	 * just return it. This can happen if we are doing I/O to a
4299 	 * static portion of the kernel's address space, for instance.
4300 	 */
4301 	pp = osfhmep->hme_page;
4302 	if (pp == NULL) {
4303 		SFMMU_HASH_UNLOCK(hmebp);
4304 		kmem_cache_free(pa_hment_cache, pahmep);
4305 		*rpfn = pfn;
4306 		if (cookiep)
4307 			*cookiep = HAC_COOKIE_NONE;
4308 		return (0);
4309 	}
4310 	ASSERT(pp == PP_PAGEROOT(pp));
4311 
4312 	vp = pp->p_vnode;
4313 	off = pp->p_offset;
4314 
4315 	pml = sfmmu_mlist_enter(pp);
4316 
4317 	if (flags & HAC_PAGELOCK) {
4318 		if (!page_trylock(pp, SE_SHARED)) {
4319 			/*
4320 			 * Somebody is holding SE_EXCL lock. Might
4321 			 * even be hat_page_relocate(). Drop all
4322 			 * our locks, lookup the page in &kvp, and
4323 			 * retry. If it doesn't exist in &kvp and &zvp,
4324 			 * then we must be dealing with a kernel mapped
4325 			 * page which doesn't actually belong to
4326 			 * segkmem so we punt.
4327 			 */
4328 			sfmmu_mlist_exit(pml);
4329 			SFMMU_HASH_UNLOCK(hmebp);
4330 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4331 
4332 			/* check zvp before giving up */
4333 			if (pp == NULL)
4334 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4335 				    SE_SHARED);
4336 
4337 			/* Okay, we didn't find it, give up */
4338 			if (pp == NULL) {
4339 				kmem_cache_free(pa_hment_cache, pahmep);
4340 				*rpfn = pfn;
4341 				if (cookiep)
4342 					*cookiep = HAC_COOKIE_NONE;
4343 				return (0);
4344 			}
4345 			page_unlock(pp);
4346 			goto rehash;
4347 		}
4348 		locked = 1;
4349 	}
4350 
4351 	if (!PAGE_LOCKED(pp) && !panicstr)
4352 		panic("hat_add_callback: page 0x%p not locked", (void *)pp);
4353 
4354 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4355 	    pp->p_offset != off) {
4356 		/*
4357 		 * The page moved before we got our hands on it.  Drop
4358 		 * all the locks and try again.
4359 		 */
4360 		ASSERT((flags & HAC_PAGELOCK) != 0);
4361 		sfmmu_mlist_exit(pml);
4362 		SFMMU_HASH_UNLOCK(hmebp);
4363 		page_unlock(pp);
4364 		locked = 0;
4365 		goto rehash;
4366 	}
4367 
4368 	if (!VN_ISKAS(vp)) {
4369 		/*
4370 		 * This is not a segkmem page but another page which
4371 		 * has been kernel mapped. It had better have at least
4372 		 * a share lock on it. Return the pfn.
4373 		 */
4374 		sfmmu_mlist_exit(pml);
4375 		SFMMU_HASH_UNLOCK(hmebp);
4376 		if (locked)
4377 			page_unlock(pp);
4378 		kmem_cache_free(pa_hment_cache, pahmep);
4379 		ASSERT(PAGE_LOCKED(pp));
4380 		*rpfn = pfn;
4381 		if (cookiep)
4382 			*cookiep = HAC_COOKIE_NONE;
4383 		return (0);
4384 	}
4385 
4386 	/*
4387 	 * Setup this pa_hment and link its embedded dummy sf_hment into
4388 	 * the mapping list.
4389 	 */
4390 	pp->p_share++;
4391 	pahmep->cb_id = callback_id;
4392 	pahmep->addr = vaddr;
4393 	pahmep->len = len;
4394 	pahmep->refcnt = 1;
4395 	pahmep->flags = 0;
4396 	pahmep->pvt = pvt;
4397 
4398 	sfhmep->hme_tte.ll = 0;
4399 	sfhmep->hme_data = pahmep;
4400 	sfhmep->hme_prev = osfhmep;
4401 	sfhmep->hme_next = osfhmep->hme_next;
4402 
4403 	if (osfhmep->hme_next)
4404 		osfhmep->hme_next->hme_prev = sfhmep;
4405 
4406 	osfhmep->hme_next = sfhmep;
4407 
4408 	sfmmu_mlist_exit(pml);
4409 	SFMMU_HASH_UNLOCK(hmebp);
4410 
4411 	if (locked)
4412 		page_unlock(pp);
4413 
4414 	*rpfn = pfn;
4415 	if (cookiep)
4416 		*cookiep = (void *)pahmep;
4417 
4418 	return (0);
4419 }
4420 
4421 /*
4422  * Remove the relocation callbacks from the specified addr/len.
4423  */
4424 void
4425 hat_delete_callback(caddr_t vaddr, uint_t len, void *pvt, uint_t flags,
4426 	void *cookie)
4427 {
4428 	struct		hmehash_bucket *hmebp;
4429 	hmeblk_tag	hblktag;
4430 	struct hme_blk	*hmeblkp;
4431 	int		hmeshift, hashno;
4432 	caddr_t		saddr;
4433 	struct pa_hment	*pahmep;
4434 	struct sf_hment	*sfhmep, *osfhmep;
4435 	kmutex_t	*pml;
4436 	tte_t		tte;
4437 	page_t		*pp;
4438 	vnode_t		*vp;
4439 	u_offset_t	off;
4440 	int		locked = 0;
4441 
4442 	/*
4443 	 * If the cookie is HAC_COOKIE_NONE then there is no pa_hment to
4444 	 * remove so just return.
4445 	 */
4446 	if (cookie == HAC_COOKIE_NONE || IS_KPM_ADDR(vaddr))
4447 		return;
4448 
4449 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4450 
4451 rehash:
4452 	/* Find the mapping(s) for this page */
4453 	for (hashno = TTE64K, hmeblkp = NULL;
4454 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4455 	    hashno++) {
4456 		hmeshift = HME_HASH_SHIFT(hashno);
4457 		hblktag.htag_id = ksfmmup;
4458 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4459 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4460 		hblktag.htag_rehash = hashno;
4461 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4462 
4463 		SFMMU_HASH_LOCK(hmebp);
4464 
4465 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4466 
4467 		if (hmeblkp == NULL)
4468 			SFMMU_HASH_UNLOCK(hmebp);
4469 	}
4470 
4471 	if (hmeblkp == NULL)
4472 		return;
4473 
4474 	ASSERT(!hmeblkp->hblk_shared);
4475 
4476 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4477 
4478 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4479 	if (!TTE_IS_VALID(&tte)) {
4480 		SFMMU_HASH_UNLOCK(hmebp);
4481 		return;
4482 	}
4483 
4484 	pp = osfhmep->hme_page;
4485 	if (pp == NULL) {
4486 		SFMMU_HASH_UNLOCK(hmebp);
4487 		ASSERT(cookie == NULL);
4488 		return;
4489 	}
4490 
4491 	vp = pp->p_vnode;
4492 	off = pp->p_offset;
4493 
4494 	pml = sfmmu_mlist_enter(pp);
4495 
4496 	if (flags & HAC_PAGELOCK) {
4497 		if (!page_trylock(pp, SE_SHARED)) {
4498 			/*
4499 			 * Somebody is holding SE_EXCL lock. Might
4500 			 * even be hat_page_relocate(). Drop all
4501 			 * our locks, lookup the page in &kvp, and
4502 			 * retry. If it doesn't exist in &kvp and &zvp,
4503 			 * then we must be dealing with a kernel mapped
4504 			 * page which doesn't actually belong to
4505 			 * segkmem so we punt.
4506 			 */
4507 			sfmmu_mlist_exit(pml);
4508 			SFMMU_HASH_UNLOCK(hmebp);
4509 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4510 			/* check zvp before giving up */
4511 			if (pp == NULL)
4512 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4513 				    SE_SHARED);
4514 
4515 			if (pp == NULL) {
4516 				ASSERT(cookie == NULL);
4517 				return;
4518 			}
4519 			page_unlock(pp);
4520 			goto rehash;
4521 		}
4522 		locked = 1;
4523 	}
4524 
4525 	ASSERT(PAGE_LOCKED(pp));
4526 
4527 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4528 	    pp->p_offset != off) {
4529 		/*
4530 		 * The page moved before we got our hands on it.  Drop
4531 		 * all the locks and try again.
4532 		 */
4533 		ASSERT((flags & HAC_PAGELOCK) != 0);
4534 		sfmmu_mlist_exit(pml);
4535 		SFMMU_HASH_UNLOCK(hmebp);
4536 		page_unlock(pp);
4537 		locked = 0;
4538 		goto rehash;
4539 	}
4540 
4541 	if (!VN_ISKAS(vp)) {
4542 		/*
4543 		 * This is not a segkmem page but another page which
4544 		 * has been kernel mapped.
4545 		 */
4546 		sfmmu_mlist_exit(pml);
4547 		SFMMU_HASH_UNLOCK(hmebp);
4548 		if (locked)
4549 			page_unlock(pp);
4550 		ASSERT(cookie == NULL);
4551 		return;
4552 	}
4553 
4554 	if (cookie != NULL) {
4555 		pahmep = (struct pa_hment *)cookie;
4556 		sfhmep = &pahmep->sfment;
4557 	} else {
4558 		for (sfhmep = pp->p_mapping; sfhmep != NULL;
4559 		    sfhmep = sfhmep->hme_next) {
4560 
4561 			/*
4562 			 * skip va<->pa mappings
4563 			 */
4564 			if (!IS_PAHME(sfhmep))
4565 				continue;
4566 
4567 			pahmep = sfhmep->hme_data;
4568 			ASSERT(pahmep != NULL);
4569 
4570 			/*
4571 			 * if pa_hment matches, remove it
4572 			 */
4573 			if ((pahmep->pvt == pvt) &&
4574 			    (pahmep->addr == vaddr) &&
4575 			    (pahmep->len == len)) {
4576 				break;
4577 			}
4578 		}
4579 	}
4580 
4581 	if (sfhmep == NULL) {
4582 		if (!panicstr) {
4583 			panic("hat_delete_callback: pa_hment not found, pp %p",
4584 			    (void *)pp);
4585 		}
4586 		return;
4587 	}
4588 
4589 	/*
4590 	 * Note: at this point a valid kernel mapping must still be
4591 	 * present on this page.
4592 	 */
4593 	pp->p_share--;
4594 	if (pp->p_share <= 0)
4595 		panic("hat_delete_callback: zero p_share");
4596 
4597 	if (--pahmep->refcnt == 0) {
4598 		if (pahmep->flags != 0)
4599 			panic("hat_delete_callback: pa_hment is busy");
4600 
4601 		/*
4602 		 * Remove sfhmep from the mapping list for the page.
4603 		 */
4604 		if (sfhmep->hme_prev) {
4605 			sfhmep->hme_prev->hme_next = sfhmep->hme_next;
4606 		} else {
4607 			pp->p_mapping = sfhmep->hme_next;
4608 		}
4609 
4610 		if (sfhmep->hme_next)
4611 			sfhmep->hme_next->hme_prev = sfhmep->hme_prev;
4612 
4613 		sfmmu_mlist_exit(pml);
4614 		SFMMU_HASH_UNLOCK(hmebp);
4615 
4616 		if (locked)
4617 			page_unlock(pp);
4618 
4619 		kmem_cache_free(pa_hment_cache, pahmep);
4620 		return;
4621 	}
4622 
4623 	sfmmu_mlist_exit(pml);
4624 	SFMMU_HASH_UNLOCK(hmebp);
4625 	if (locked)
4626 		page_unlock(pp);
4627 }
4628 
4629 /*
4630  * hat_probe returns 1 if the translation for the address 'addr' is
4631  * loaded, zero otherwise.
4632  *
4633  * hat_probe should be used only for advisorary purposes because it may
4634  * occasionally return the wrong value. The implementation must guarantee that
4635  * returning the wrong value is a very rare event. hat_probe is used
4636  * to implement optimizations in the segment drivers.
4637  *
4638  */
4639 int
4640 hat_probe(struct hat *sfmmup, caddr_t addr)
4641 {
4642 	pfn_t pfn;
4643 	tte_t tte;
4644 
4645 	ASSERT(sfmmup != NULL);
4646 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4647 
4648 	ASSERT((sfmmup == ksfmmup) ||
4649 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4650 
4651 	if (sfmmup == ksfmmup) {
4652 		while ((pfn = sfmmu_vatopfn(addr, sfmmup, &tte))
4653 		    == PFN_SUSPENDED) {
4654 			sfmmu_vatopfn_suspended(addr, sfmmup, &tte);
4655 		}
4656 	} else {
4657 		pfn = sfmmu_uvatopfn(addr, sfmmup, NULL);
4658 	}
4659 
4660 	if (pfn != PFN_INVALID)
4661 		return (1);
4662 	else
4663 		return (0);
4664 }
4665 
4666 ssize_t
4667 hat_getpagesize(struct hat *sfmmup, caddr_t addr)
4668 {
4669 	tte_t tte;
4670 
4671 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4672 
4673 	if (sfmmup == ksfmmup) {
4674 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4675 			return (-1);
4676 		}
4677 	} else {
4678 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4679 			return (-1);
4680 		}
4681 	}
4682 
4683 	ASSERT(TTE_IS_VALID(&tte));
4684 	return (TTEBYTES(TTE_CSZ(&tte)));
4685 }
4686 
4687 uint_t
4688 hat_getattr(struct hat *sfmmup, caddr_t addr, uint_t *attr)
4689 {
4690 	tte_t tte;
4691 
4692 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4693 
4694 	if (sfmmup == ksfmmup) {
4695 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4696 			tte.ll = 0;
4697 		}
4698 	} else {
4699 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4700 			tte.ll = 0;
4701 		}
4702 	}
4703 	if (TTE_IS_VALID(&tte)) {
4704 		*attr = sfmmu_ptov_attr(&tte);
4705 		return (0);
4706 	}
4707 	*attr = 0;
4708 	return ((uint_t)0xffffffff);
4709 }
4710 
4711 /*
4712  * Enables more attributes on specified address range (ie. logical OR)
4713  */
4714 void
4715 hat_setattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4716 {
4717 	if (hat->sfmmu_xhat_provider) {
4718 		XHAT_SETATTR(hat, addr, len, attr);
4719 		return;
4720 	} else {
4721 		/*
4722 		 * This must be a CPU HAT. If the address space has
4723 		 * XHATs attached, change attributes for all of them,
4724 		 * just in case
4725 		 */
4726 		ASSERT(hat->sfmmu_as != NULL);
4727 		if (hat->sfmmu_as->a_xhat != NULL)
4728 			xhat_setattr_all(hat->sfmmu_as, addr, len, attr);
4729 	}
4730 
4731 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_SETATTR);
4732 }
4733 
4734 /*
4735  * Assigns attributes to the specified address range.  All the attributes
4736  * are specified.
4737  */
4738 void
4739 hat_chgattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4740 {
4741 	if (hat->sfmmu_xhat_provider) {
4742 		XHAT_CHGATTR(hat, addr, len, attr);
4743 		return;
4744 	} else {
4745 		/*
4746 		 * This must be a CPU HAT. If the address space has
4747 		 * XHATs attached, change attributes for all of them,
4748 		 * just in case
4749 		 */
4750 		ASSERT(hat->sfmmu_as != NULL);
4751 		if (hat->sfmmu_as->a_xhat != NULL)
4752 			xhat_chgattr_all(hat->sfmmu_as, addr, len, attr);
4753 	}
4754 
4755 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CHGATTR);
4756 }
4757 
4758 /*
4759  * Remove attributes on the specified address range (ie. loginal NAND)
4760  */
4761 void
4762 hat_clrattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4763 {
4764 	if (hat->sfmmu_xhat_provider) {
4765 		XHAT_CLRATTR(hat, addr, len, attr);
4766 		return;
4767 	} else {
4768 		/*
4769 		 * This must be a CPU HAT. If the address space has
4770 		 * XHATs attached, change attributes for all of them,
4771 		 * just in case
4772 		 */
4773 		ASSERT(hat->sfmmu_as != NULL);
4774 		if (hat->sfmmu_as->a_xhat != NULL)
4775 			xhat_clrattr_all(hat->sfmmu_as, addr, len, attr);
4776 	}
4777 
4778 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CLRATTR);
4779 }
4780 
4781 /*
4782  * Change attributes on an address range to that specified by attr and mode.
4783  */
4784 static void
4785 sfmmu_chgattr(struct hat *sfmmup, caddr_t addr, size_t len, uint_t attr,
4786 	int mode)
4787 {
4788 	struct hmehash_bucket *hmebp;
4789 	hmeblk_tag hblktag;
4790 	int hmeshift, hashno = 1;
4791 	struct hme_blk *hmeblkp, *list = NULL;
4792 	caddr_t endaddr;
4793 	cpuset_t cpuset;
4794 	demap_range_t dmr;
4795 
4796 	CPUSET_ZERO(cpuset);
4797 
4798 	ASSERT((sfmmup == ksfmmup) ||
4799 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4800 	ASSERT((len & MMU_PAGEOFFSET) == 0);
4801 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
4802 
4803 	if ((attr & PROT_USER) && (mode != SFMMU_CLRATTR) &&
4804 	    ((addr + len) > (caddr_t)USERLIMIT)) {
4805 		panic("user addr %p in kernel space",
4806 		    (void *)addr);
4807 	}
4808 
4809 	endaddr = addr + len;
4810 	hblktag.htag_id = sfmmup;
4811 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4812 	DEMAP_RANGE_INIT(sfmmup, &dmr);
4813 
4814 	while (addr < endaddr) {
4815 		hmeshift = HME_HASH_SHIFT(hashno);
4816 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
4817 		hblktag.htag_rehash = hashno;
4818 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
4819 
4820 		SFMMU_HASH_LOCK(hmebp);
4821 
4822 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
4823 		if (hmeblkp != NULL) {
4824 			ASSERT(!hmeblkp->hblk_shared);
4825 			/*
4826 			 * We've encountered a shadow hmeblk so skip the range
4827 			 * of the next smaller mapping size.
4828 			 */
4829 			if (hmeblkp->hblk_shw_bit) {
4830 				ASSERT(sfmmup != ksfmmup);
4831 				ASSERT(hashno > 1);
4832 				addr = (caddr_t)P2END((uintptr_t)addr,
4833 				    TTEBYTES(hashno - 1));
4834 			} else {
4835 				addr = sfmmu_hblk_chgattr(sfmmup,
4836 				    hmeblkp, addr, endaddr, &dmr, attr, mode);
4837 			}
4838 			SFMMU_HASH_UNLOCK(hmebp);
4839 			hashno = 1;
4840 			continue;
4841 		}
4842 		SFMMU_HASH_UNLOCK(hmebp);
4843 
4844 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
4845 			/*
4846 			 * We have traversed the whole list and rehashed
4847 			 * if necessary without finding the address to chgattr.
4848 			 * This is ok, so we increment the address by the
4849 			 * smallest hmeblk range for kernel mappings or for
4850 			 * user mappings with no large pages, and the largest
4851 			 * hmeblk range, to account for shadow hmeblks, for
4852 			 * user mappings with large pages and continue.
4853 			 */
4854 			if (sfmmup == ksfmmup)
4855 				addr = (caddr_t)P2END((uintptr_t)addr,
4856 				    TTEBYTES(1));
4857 			else
4858 				addr = (caddr_t)P2END((uintptr_t)addr,
4859 				    TTEBYTES(hashno));
4860 			hashno = 1;
4861 		} else {
4862 			hashno++;
4863 		}
4864 	}
4865 
4866 	sfmmu_hblks_list_purge(&list, 0);
4867 	DEMAP_RANGE_FLUSH(&dmr);
4868 	cpuset = sfmmup->sfmmu_cpusran;
4869 	xt_sync(cpuset);
4870 }
4871 
4872 /*
4873  * This function chgattr on a range of addresses in an hmeblk.  It returns the
4874  * next addres that needs to be chgattr.
4875  * It should be called with the hash lock held.
4876  * XXX It should be possible to optimize chgattr by not flushing every time but
4877  * on the other hand:
4878  * 1. do one flush crosscall.
4879  * 2. only flush if we are increasing permissions (make sure this will work)
4880  */
4881 static caddr_t
4882 sfmmu_hblk_chgattr(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
4883 	caddr_t endaddr, demap_range_t *dmrp, uint_t attr, int mode)
4884 {
4885 	tte_t tte, tteattr, tteflags, ttemod;
4886 	struct sf_hment *sfhmep;
4887 	int ttesz;
4888 	struct page *pp = NULL;
4889 	kmutex_t *pml, *pmtx;
4890 	int ret;
4891 	int use_demap_range;
4892 #if defined(SF_ERRATA_57)
4893 	int check_exec;
4894 #endif
4895 
4896 	ASSERT(in_hblk_range(hmeblkp, addr));
4897 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4898 	ASSERT(!hmeblkp->hblk_shared);
4899 
4900 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4901 	ttesz = get_hblk_ttesz(hmeblkp);
4902 
4903 	/*
4904 	 * Flush the current demap region if addresses have been
4905 	 * skipped or the page size doesn't match.
4906 	 */
4907 	use_demap_range = (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp));
4908 	if (use_demap_range) {
4909 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
4910 	} else {
4911 		DEMAP_RANGE_FLUSH(dmrp);
4912 	}
4913 
4914 	tteattr.ll = sfmmu_vtop_attr(attr, mode, &tteflags);
4915 #if defined(SF_ERRATA_57)
4916 	check_exec = (sfmmup != ksfmmup) &&
4917 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
4918 	    TTE_IS_EXECUTABLE(&tteattr);
4919 #endif
4920 	HBLKTOHME(sfhmep, hmeblkp, addr);
4921 	while (addr < endaddr) {
4922 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
4923 		if (TTE_IS_VALID(&tte)) {
4924 			if ((tte.ll & tteflags.ll) == tteattr.ll) {
4925 				/*
4926 				 * if the new attr is the same as old
4927 				 * continue
4928 				 */
4929 				goto next_addr;
4930 			}
4931 			if (!TTE_IS_WRITABLE(&tteattr)) {
4932 				/*
4933 				 * make sure we clear hw modify bit if we
4934 				 * removing write protections
4935 				 */
4936 				tteflags.tte_intlo |= TTE_HWWR_INT;
4937 			}
4938 
4939 			pml = NULL;
4940 			pp = sfhmep->hme_page;
4941 			if (pp) {
4942 				pml = sfmmu_mlist_enter(pp);
4943 			}
4944 
4945 			if (pp != sfhmep->hme_page) {
4946 				/*
4947 				 * tte must have been unloaded.
4948 				 */
4949 				ASSERT(pml);
4950 				sfmmu_mlist_exit(pml);
4951 				continue;
4952 			}
4953 
4954 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
4955 
4956 			ttemod = tte;
4957 			ttemod.ll = (ttemod.ll & ~tteflags.ll) | tteattr.ll;
4958 			ASSERT(TTE_TO_TTEPFN(&ttemod) == TTE_TO_TTEPFN(&tte));
4959 
4960 #if defined(SF_ERRATA_57)
4961 			if (check_exec && addr < errata57_limit)
4962 				ttemod.tte_exec_perm = 0;
4963 #endif
4964 			ret = sfmmu_modifytte_try(&tte, &ttemod,
4965 			    &sfhmep->hme_tte);
4966 
4967 			if (ret < 0) {
4968 				/* tte changed underneath us */
4969 				if (pml) {
4970 					sfmmu_mlist_exit(pml);
4971 				}
4972 				continue;
4973 			}
4974 
4975 			if (tteflags.tte_intlo & TTE_HWWR_INT) {
4976 				/*
4977 				 * need to sync if we are clearing modify bit.
4978 				 */
4979 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
4980 			}
4981 
4982 			if (pp && PP_ISRO(pp)) {
4983 				if (tteattr.tte_intlo & TTE_WRPRM_INT) {
4984 					pmtx = sfmmu_page_enter(pp);
4985 					PP_CLRRO(pp);
4986 					sfmmu_page_exit(pmtx);
4987 				}
4988 			}
4989 
4990 			if (ret > 0 && use_demap_range) {
4991 				DEMAP_RANGE_MARKPG(dmrp, addr);
4992 			} else if (ret > 0) {
4993 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
4994 			}
4995 
4996 			if (pml) {
4997 				sfmmu_mlist_exit(pml);
4998 			}
4999 		}
5000 next_addr:
5001 		addr += TTEBYTES(ttesz);
5002 		sfhmep++;
5003 		DEMAP_RANGE_NEXTPG(dmrp);
5004 	}
5005 	return (addr);
5006 }
5007 
5008 /*
5009  * This routine converts virtual attributes to physical ones.  It will
5010  * update the tteflags field with the tte mask corresponding to the attributes
5011  * affected and it returns the new attributes.  It will also clear the modify
5012  * bit if we are taking away write permission.  This is necessary since the
5013  * modify bit is the hardware permission bit and we need to clear it in order
5014  * to detect write faults.
5015  */
5016 static uint64_t
5017 sfmmu_vtop_attr(uint_t attr, int mode, tte_t *ttemaskp)
5018 {
5019 	tte_t ttevalue;
5020 
5021 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
5022 
5023 	switch (mode) {
5024 	case SFMMU_CHGATTR:
5025 		/* all attributes specified */
5026 		ttevalue.tte_inthi = MAKE_TTEATTR_INTHI(attr);
5027 		ttevalue.tte_intlo = MAKE_TTEATTR_INTLO(attr);
5028 		ttemaskp->tte_inthi = TTEINTHI_ATTR;
5029 		ttemaskp->tte_intlo = TTEINTLO_ATTR;
5030 		break;
5031 	case SFMMU_SETATTR:
5032 		ASSERT(!(attr & ~HAT_PROT_MASK));
5033 		ttemaskp->ll = 0;
5034 		ttevalue.ll = 0;
5035 		/*
5036 		 * a valid tte implies exec and read for sfmmu
5037 		 * so no need to do anything about them.
5038 		 * since priviledged access implies user access
5039 		 * PROT_USER doesn't make sense either.
5040 		 */
5041 		if (attr & PROT_WRITE) {
5042 			ttemaskp->tte_intlo |= TTE_WRPRM_INT;
5043 			ttevalue.tte_intlo |= TTE_WRPRM_INT;
5044 		}
5045 		break;
5046 	case SFMMU_CLRATTR:
5047 		/* attributes will be nand with current ones */
5048 		if (attr & ~(PROT_WRITE | PROT_USER)) {
5049 			panic("sfmmu: attr %x not supported", attr);
5050 		}
5051 		ttemaskp->ll = 0;
5052 		ttevalue.ll = 0;
5053 		if (attr & PROT_WRITE) {
5054 			/* clear both writable and modify bit */
5055 			ttemaskp->tte_intlo |= TTE_WRPRM_INT | TTE_HWWR_INT;
5056 		}
5057 		if (attr & PROT_USER) {
5058 			ttemaskp->tte_intlo |= TTE_PRIV_INT;
5059 			ttevalue.tte_intlo |= TTE_PRIV_INT;
5060 		}
5061 		break;
5062 	default:
5063 		panic("sfmmu_vtop_attr: bad mode %x", mode);
5064 	}
5065 	ASSERT(TTE_TO_TTEPFN(&ttevalue) == 0);
5066 	return (ttevalue.ll);
5067 }
5068 
5069 static uint_t
5070 sfmmu_ptov_attr(tte_t *ttep)
5071 {
5072 	uint_t attr;
5073 
5074 	ASSERT(TTE_IS_VALID(ttep));
5075 
5076 	attr = PROT_READ;
5077 
5078 	if (TTE_IS_WRITABLE(ttep)) {
5079 		attr |= PROT_WRITE;
5080 	}
5081 	if (TTE_IS_EXECUTABLE(ttep)) {
5082 		attr |= PROT_EXEC;
5083 	}
5084 	if (!TTE_IS_PRIVILEGED(ttep)) {
5085 		attr |= PROT_USER;
5086 	}
5087 	if (TTE_IS_NFO(ttep)) {
5088 		attr |= HAT_NOFAULT;
5089 	}
5090 	if (TTE_IS_NOSYNC(ttep)) {
5091 		attr |= HAT_NOSYNC;
5092 	}
5093 	if (TTE_IS_SIDEFFECT(ttep)) {
5094 		attr |= SFMMU_SIDEFFECT;
5095 	}
5096 	if (!TTE_IS_VCACHEABLE(ttep)) {
5097 		attr |= SFMMU_UNCACHEVTTE;
5098 	}
5099 	if (!TTE_IS_PCACHEABLE(ttep)) {
5100 		attr |= SFMMU_UNCACHEPTTE;
5101 	}
5102 	return (attr);
5103 }
5104 
5105 /*
5106  * hat_chgprot is a deprecated hat call.  New segment drivers
5107  * should store all attributes and use hat_*attr calls.
5108  *
5109  * Change the protections in the virtual address range
5110  * given to the specified virtual protection.  If vprot is ~PROT_WRITE,
5111  * then remove write permission, leaving the other
5112  * permissions unchanged.  If vprot is ~PROT_USER, remove user permissions.
5113  *
5114  */
5115 void
5116 hat_chgprot(struct hat *sfmmup, caddr_t addr, size_t len, uint_t vprot)
5117 {
5118 	struct hmehash_bucket *hmebp;
5119 	hmeblk_tag hblktag;
5120 	int hmeshift, hashno = 1;
5121 	struct hme_blk *hmeblkp, *list = NULL;
5122 	caddr_t endaddr;
5123 	cpuset_t cpuset;
5124 	demap_range_t dmr;
5125 
5126 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5127 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
5128 
5129 	if (sfmmup->sfmmu_xhat_provider) {
5130 		XHAT_CHGPROT(sfmmup, addr, len, vprot);
5131 		return;
5132 	} else {
5133 		/*
5134 		 * This must be a CPU HAT. If the address space has
5135 		 * XHATs attached, change attributes for all of them,
5136 		 * just in case
5137 		 */
5138 		ASSERT(sfmmup->sfmmu_as != NULL);
5139 		if (sfmmup->sfmmu_as->a_xhat != NULL)
5140 			xhat_chgprot_all(sfmmup->sfmmu_as, addr, len, vprot);
5141 	}
5142 
5143 	CPUSET_ZERO(cpuset);
5144 
5145 	if ((vprot != (uint_t)~PROT_WRITE) && (vprot & PROT_USER) &&
5146 	    ((addr + len) > (caddr_t)USERLIMIT)) {
5147 		panic("user addr %p vprot %x in kernel space",
5148 		    (void *)addr, vprot);
5149 	}
5150 	endaddr = addr + len;
5151 	hblktag.htag_id = sfmmup;
5152 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5153 	DEMAP_RANGE_INIT(sfmmup, &dmr);
5154 
5155 	while (addr < endaddr) {
5156 		hmeshift = HME_HASH_SHIFT(hashno);
5157 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5158 		hblktag.htag_rehash = hashno;
5159 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5160 
5161 		SFMMU_HASH_LOCK(hmebp);
5162 
5163 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
5164 		if (hmeblkp != NULL) {
5165 			ASSERT(!hmeblkp->hblk_shared);
5166 			/*
5167 			 * We've encountered a shadow hmeblk so skip the range
5168 			 * of the next smaller mapping size.
5169 			 */
5170 			if (hmeblkp->hblk_shw_bit) {
5171 				ASSERT(sfmmup != ksfmmup);
5172 				ASSERT(hashno > 1);
5173 				addr = (caddr_t)P2END((uintptr_t)addr,
5174 				    TTEBYTES(hashno - 1));
5175 			} else {
5176 				addr = sfmmu_hblk_chgprot(sfmmup, hmeblkp,
5177 				    addr, endaddr, &dmr, vprot);
5178 			}
5179 			SFMMU_HASH_UNLOCK(hmebp);
5180 			hashno = 1;
5181 			continue;
5182 		}
5183 		SFMMU_HASH_UNLOCK(hmebp);
5184 
5185 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
5186 			/*
5187 			 * We have traversed the whole list and rehashed
5188 			 * if necessary without finding the address to chgprot.
5189 			 * This is ok so we increment the address by the
5190 			 * smallest hmeblk range for kernel mappings and the
5191 			 * largest hmeblk range, to account for shadow hmeblks,
5192 			 * for user mappings and continue.
5193 			 */
5194 			if (sfmmup == ksfmmup)
5195 				addr = (caddr_t)P2END((uintptr_t)addr,
5196 				    TTEBYTES(1));
5197 			else
5198 				addr = (caddr_t)P2END((uintptr_t)addr,
5199 				    TTEBYTES(hashno));
5200 			hashno = 1;
5201 		} else {
5202 			hashno++;
5203 		}
5204 	}
5205 
5206 	sfmmu_hblks_list_purge(&list, 0);
5207 	DEMAP_RANGE_FLUSH(&dmr);
5208 	cpuset = sfmmup->sfmmu_cpusran;
5209 	xt_sync(cpuset);
5210 }
5211 
5212 /*
5213  * This function chgprots a range of addresses in an hmeblk.  It returns the
5214  * next addres that needs to be chgprot.
5215  * It should be called with the hash lock held.
5216  * XXX It shold be possible to optimize chgprot by not flushing every time but
5217  * on the other hand:
5218  * 1. do one flush crosscall.
5219  * 2. only flush if we are increasing permissions (make sure this will work)
5220  */
5221 static caddr_t
5222 sfmmu_hblk_chgprot(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5223 	caddr_t endaddr, demap_range_t *dmrp, uint_t vprot)
5224 {
5225 	uint_t pprot;
5226 	tte_t tte, ttemod;
5227 	struct sf_hment *sfhmep;
5228 	uint_t tteflags;
5229 	int ttesz;
5230 	struct page *pp = NULL;
5231 	kmutex_t *pml, *pmtx;
5232 	int ret;
5233 	int use_demap_range;
5234 #if defined(SF_ERRATA_57)
5235 	int check_exec;
5236 #endif
5237 
5238 	ASSERT(in_hblk_range(hmeblkp, addr));
5239 	ASSERT(hmeblkp->hblk_shw_bit == 0);
5240 	ASSERT(!hmeblkp->hblk_shared);
5241 
5242 #ifdef DEBUG
5243 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5244 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5245 		panic("sfmmu_hblk_chgprot: partial chgprot of large page");
5246 	}
5247 #endif /* DEBUG */
5248 
5249 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5250 	ttesz = get_hblk_ttesz(hmeblkp);
5251 
5252 	pprot = sfmmu_vtop_prot(vprot, &tteflags);
5253 #if defined(SF_ERRATA_57)
5254 	check_exec = (sfmmup != ksfmmup) &&
5255 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
5256 	    ((vprot & PROT_EXEC) == PROT_EXEC);
5257 #endif
5258 	HBLKTOHME(sfhmep, hmeblkp, addr);
5259 
5260 	/*
5261 	 * Flush the current demap region if addresses have been
5262 	 * skipped or the page size doesn't match.
5263 	 */
5264 	use_demap_range = (TTEBYTES(ttesz) == MMU_PAGESIZE);
5265 	if (use_demap_range) {
5266 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5267 	} else {
5268 		DEMAP_RANGE_FLUSH(dmrp);
5269 	}
5270 
5271 	while (addr < endaddr) {
5272 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5273 		if (TTE_IS_VALID(&tte)) {
5274 			if (TTE_GET_LOFLAGS(&tte, tteflags) == pprot) {
5275 				/*
5276 				 * if the new protection is the same as old
5277 				 * continue
5278 				 */
5279 				goto next_addr;
5280 			}
5281 			pml = NULL;
5282 			pp = sfhmep->hme_page;
5283 			if (pp) {
5284 				pml = sfmmu_mlist_enter(pp);
5285 			}
5286 			if (pp != sfhmep->hme_page) {
5287 				/*
5288 				 * tte most have been unloaded
5289 				 * underneath us.  Recheck
5290 				 */
5291 				ASSERT(pml);
5292 				sfmmu_mlist_exit(pml);
5293 				continue;
5294 			}
5295 
5296 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5297 
5298 			ttemod = tte;
5299 			TTE_SET_LOFLAGS(&ttemod, tteflags, pprot);
5300 #if defined(SF_ERRATA_57)
5301 			if (check_exec && addr < errata57_limit)
5302 				ttemod.tte_exec_perm = 0;
5303 #endif
5304 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5305 			    &sfhmep->hme_tte);
5306 
5307 			if (ret < 0) {
5308 				/* tte changed underneath us */
5309 				if (pml) {
5310 					sfmmu_mlist_exit(pml);
5311 				}
5312 				continue;
5313 			}
5314 
5315 			if (tteflags & TTE_HWWR_INT) {
5316 				/*
5317 				 * need to sync if we are clearing modify bit.
5318 				 */
5319 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
5320 			}
5321 
5322 			if (pp && PP_ISRO(pp)) {
5323 				if (pprot & TTE_WRPRM_INT) {
5324 					pmtx = sfmmu_page_enter(pp);
5325 					PP_CLRRO(pp);
5326 					sfmmu_page_exit(pmtx);
5327 				}
5328 			}
5329 
5330 			if (ret > 0 && use_demap_range) {
5331 				DEMAP_RANGE_MARKPG(dmrp, addr);
5332 			} else if (ret > 0) {
5333 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
5334 			}
5335 
5336 			if (pml) {
5337 				sfmmu_mlist_exit(pml);
5338 			}
5339 		}
5340 next_addr:
5341 		addr += TTEBYTES(ttesz);
5342 		sfhmep++;
5343 		DEMAP_RANGE_NEXTPG(dmrp);
5344 	}
5345 	return (addr);
5346 }
5347 
5348 /*
5349  * This routine is deprecated and should only be used by hat_chgprot.
5350  * The correct routine is sfmmu_vtop_attr.
5351  * This routine converts virtual page protections to physical ones.  It will
5352  * update the tteflags field with the tte mask corresponding to the protections
5353  * affected and it returns the new protections.  It will also clear the modify
5354  * bit if we are taking away write permission.  This is necessary since the
5355  * modify bit is the hardware permission bit and we need to clear it in order
5356  * to detect write faults.
5357  * It accepts the following special protections:
5358  * ~PROT_WRITE = remove write permissions.
5359  * ~PROT_USER = remove user permissions.
5360  */
5361 static uint_t
5362 sfmmu_vtop_prot(uint_t vprot, uint_t *tteflagsp)
5363 {
5364 	if (vprot == (uint_t)~PROT_WRITE) {
5365 		*tteflagsp = TTE_WRPRM_INT | TTE_HWWR_INT;
5366 		return (0);		/* will cause wrprm to be cleared */
5367 	}
5368 	if (vprot == (uint_t)~PROT_USER) {
5369 		*tteflagsp = TTE_PRIV_INT;
5370 		return (0);		/* will cause privprm to be cleared */
5371 	}
5372 	if ((vprot == 0) || (vprot == PROT_USER) ||
5373 	    ((vprot & PROT_ALL) != vprot)) {
5374 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5375 	}
5376 
5377 	switch (vprot) {
5378 	case (PROT_READ):
5379 	case (PROT_EXEC):
5380 	case (PROT_EXEC | PROT_READ):
5381 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5382 		return (TTE_PRIV_INT); 		/* set prv and clr wrt */
5383 	case (PROT_WRITE):
5384 	case (PROT_WRITE | PROT_READ):
5385 	case (PROT_EXEC | PROT_WRITE):
5386 	case (PROT_EXEC | PROT_WRITE | PROT_READ):
5387 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5388 		return (TTE_PRIV_INT | TTE_WRPRM_INT); 	/* set prv and wrt */
5389 	case (PROT_USER | PROT_READ):
5390 	case (PROT_USER | PROT_EXEC):
5391 	case (PROT_USER | PROT_EXEC | PROT_READ):
5392 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5393 		return (0); 			/* clr prv and wrt */
5394 	case (PROT_USER | PROT_WRITE):
5395 	case (PROT_USER | PROT_WRITE | PROT_READ):
5396 	case (PROT_USER | PROT_EXEC | PROT_WRITE):
5397 	case (PROT_USER | PROT_EXEC | PROT_WRITE | PROT_READ):
5398 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5399 		return (TTE_WRPRM_INT); 	/* clr prv and set wrt */
5400 	default:
5401 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5402 	}
5403 	return (0);
5404 }
5405 
5406 /*
5407  * Alternate unload for very large virtual ranges. With a true 64 bit VA,
5408  * the normal algorithm would take too long for a very large VA range with
5409  * few real mappings. This routine just walks thru all HMEs in the global
5410  * hash table to find and remove mappings.
5411  */
5412 static void
5413 hat_unload_large_virtual(
5414 	struct hat		*sfmmup,
5415 	caddr_t			startaddr,
5416 	size_t			len,
5417 	uint_t			flags,
5418 	hat_callback_t		*callback)
5419 {
5420 	struct hmehash_bucket *hmebp;
5421 	struct hme_blk *hmeblkp;
5422 	struct hme_blk *pr_hblk = NULL;
5423 	struct hme_blk *nx_hblk;
5424 	struct hme_blk *list = NULL;
5425 	int i;
5426 	demap_range_t dmr, *dmrp;
5427 	cpuset_t cpuset;
5428 	caddr_t	endaddr = startaddr + len;
5429 	caddr_t	sa;
5430 	caddr_t	ea;
5431 	caddr_t	cb_sa[MAX_CB_ADDR];
5432 	caddr_t	cb_ea[MAX_CB_ADDR];
5433 	int	addr_cnt = 0;
5434 	int	a = 0;
5435 
5436 	if (sfmmup->sfmmu_free) {
5437 		dmrp = NULL;
5438 	} else {
5439 		dmrp = &dmr;
5440 		DEMAP_RANGE_INIT(sfmmup, dmrp);
5441 	}
5442 
5443 	/*
5444 	 * Loop through all the hash buckets of HME blocks looking for matches.
5445 	 */
5446 	for (i = 0; i <= UHMEHASH_SZ; i++) {
5447 		hmebp = &uhme_hash[i];
5448 		SFMMU_HASH_LOCK(hmebp);
5449 		hmeblkp = hmebp->hmeblkp;
5450 		pr_hblk = NULL;
5451 		while (hmeblkp) {
5452 			nx_hblk = hmeblkp->hblk_next;
5453 
5454 			/*
5455 			 * skip if not this context, if a shadow block or
5456 			 * if the mapping is not in the requested range
5457 			 */
5458 			if (hmeblkp->hblk_tag.htag_id != sfmmup ||
5459 			    hmeblkp->hblk_shw_bit ||
5460 			    (sa = (caddr_t)get_hblk_base(hmeblkp)) >= endaddr ||
5461 			    (ea = get_hblk_endaddr(hmeblkp)) <= startaddr) {
5462 				pr_hblk = hmeblkp;
5463 				goto next_block;
5464 			}
5465 
5466 			ASSERT(!hmeblkp->hblk_shared);
5467 			/*
5468 			 * unload if there are any current valid mappings
5469 			 */
5470 			if (hmeblkp->hblk_vcnt != 0 ||
5471 			    hmeblkp->hblk_hmecnt != 0)
5472 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
5473 				    sa, ea, dmrp, flags);
5474 
5475 			/*
5476 			 * on unmap we also release the HME block itself, once
5477 			 * all mappings are gone.
5478 			 */
5479 			if ((flags & HAT_UNLOAD_UNMAP) != 0 &&
5480 			    !hmeblkp->hblk_vcnt &&
5481 			    !hmeblkp->hblk_hmecnt) {
5482 				ASSERT(!hmeblkp->hblk_lckcnt);
5483 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
5484 				    &list, 0);
5485 			} else {
5486 				pr_hblk = hmeblkp;
5487 			}
5488 
5489 			if (callback == NULL)
5490 				goto next_block;
5491 
5492 			/*
5493 			 * HME blocks may span more than one page, but we may be
5494 			 * unmapping only one page, so check for a smaller range
5495 			 * for the callback
5496 			 */
5497 			if (sa < startaddr)
5498 				sa = startaddr;
5499 			if (--ea > endaddr)
5500 				ea = endaddr - 1;
5501 
5502 			cb_sa[addr_cnt] = sa;
5503 			cb_ea[addr_cnt] = ea;
5504 			if (++addr_cnt == MAX_CB_ADDR) {
5505 				if (dmrp != NULL) {
5506 					DEMAP_RANGE_FLUSH(dmrp);
5507 					cpuset = sfmmup->sfmmu_cpusran;
5508 					xt_sync(cpuset);
5509 				}
5510 
5511 				for (a = 0; a < MAX_CB_ADDR; ++a) {
5512 					callback->hcb_start_addr = cb_sa[a];
5513 					callback->hcb_end_addr = cb_ea[a];
5514 					callback->hcb_function(callback);
5515 				}
5516 				addr_cnt = 0;
5517 			}
5518 
5519 next_block:
5520 			hmeblkp = nx_hblk;
5521 		}
5522 		SFMMU_HASH_UNLOCK(hmebp);
5523 	}
5524 
5525 	sfmmu_hblks_list_purge(&list, 0);
5526 	if (dmrp != NULL) {
5527 		DEMAP_RANGE_FLUSH(dmrp);
5528 		cpuset = sfmmup->sfmmu_cpusran;
5529 		xt_sync(cpuset);
5530 	}
5531 
5532 	for (a = 0; a < addr_cnt; ++a) {
5533 		callback->hcb_start_addr = cb_sa[a];
5534 		callback->hcb_end_addr = cb_ea[a];
5535 		callback->hcb_function(callback);
5536 	}
5537 
5538 	/*
5539 	 * Check TSB and TLB page sizes if the process isn't exiting.
5540 	 */
5541 	if (!sfmmup->sfmmu_free)
5542 		sfmmu_check_page_sizes(sfmmup, 0);
5543 }
5544 
5545 /*
5546  * Unload all the mappings in the range [addr..addr+len). addr and len must
5547  * be MMU_PAGESIZE aligned.
5548  */
5549 
5550 extern struct seg *segkmap;
5551 #define	ISSEGKMAP(sfmmup, addr) (sfmmup == ksfmmup && \
5552 segkmap->s_base <= (addr) && (addr) < (segkmap->s_base + segkmap->s_size))
5553 
5554 
5555 void
5556 hat_unload_callback(
5557 	struct hat *sfmmup,
5558 	caddr_t addr,
5559 	size_t len,
5560 	uint_t flags,
5561 	hat_callback_t *callback)
5562 {
5563 	struct hmehash_bucket *hmebp;
5564 	hmeblk_tag hblktag;
5565 	int hmeshift, hashno, iskernel;
5566 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
5567 	caddr_t endaddr;
5568 	cpuset_t cpuset;
5569 	int addr_count = 0;
5570 	int a;
5571 	caddr_t cb_start_addr[MAX_CB_ADDR];
5572 	caddr_t cb_end_addr[MAX_CB_ADDR];
5573 	int issegkmap = ISSEGKMAP(sfmmup, addr);
5574 	demap_range_t dmr, *dmrp;
5575 
5576 	if (sfmmup->sfmmu_xhat_provider) {
5577 		XHAT_UNLOAD_CALLBACK(sfmmup, addr, len, flags, callback);
5578 		return;
5579 	} else {
5580 		/*
5581 		 * This must be a CPU HAT. If the address space has
5582 		 * XHATs attached, unload the mappings for all of them,
5583 		 * just in case
5584 		 */
5585 		ASSERT(sfmmup->sfmmu_as != NULL);
5586 		if (sfmmup->sfmmu_as->a_xhat != NULL)
5587 			xhat_unload_callback_all(sfmmup->sfmmu_as, addr,
5588 			    len, flags, callback);
5589 	}
5590 
5591 	ASSERT((sfmmup == ksfmmup) || (flags & HAT_UNLOAD_OTHER) || \
5592 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
5593 
5594 	ASSERT(sfmmup != NULL);
5595 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5596 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
5597 
5598 	/*
5599 	 * Probing through a large VA range (say 63 bits) will be slow, even
5600 	 * at 4 Meg steps between the probes. So, when the virtual address range
5601 	 * is very large, search the HME entries for what to unload.
5602 	 *
5603 	 *	len >> TTE_PAGE_SHIFT(TTE4M) is the # of 4Meg probes we'd need
5604 	 *
5605 	 *	UHMEHASH_SZ is number of hash buckets to examine
5606 	 *
5607 	 */
5608 	if (sfmmup != KHATID && (len >> TTE_PAGE_SHIFT(TTE4M)) > UHMEHASH_SZ) {
5609 		hat_unload_large_virtual(sfmmup, addr, len, flags, callback);
5610 		return;
5611 	}
5612 
5613 	CPUSET_ZERO(cpuset);
5614 
5615 	/*
5616 	 * If the process is exiting, we can save a lot of fuss since
5617 	 * we'll flush the TLB when we free the ctx anyway.
5618 	 */
5619 	if (sfmmup->sfmmu_free)
5620 		dmrp = NULL;
5621 	else
5622 		dmrp = &dmr;
5623 
5624 	DEMAP_RANGE_INIT(sfmmup, dmrp);
5625 	endaddr = addr + len;
5626 	hblktag.htag_id = sfmmup;
5627 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5628 
5629 	/*
5630 	 * It is likely for the vm to call unload over a wide range of
5631 	 * addresses that are actually very sparsely populated by
5632 	 * translations.  In order to speed this up the sfmmu hat supports
5633 	 * the concept of shadow hmeblks. Dummy large page hmeblks that
5634 	 * correspond to actual small translations are allocated at tteload
5635 	 * time and are referred to as shadow hmeblks.  Now, during unload
5636 	 * time, we first check if we have a shadow hmeblk for that
5637 	 * translation.  The absence of one means the corresponding address
5638 	 * range is empty and can be skipped.
5639 	 *
5640 	 * The kernel is an exception to above statement and that is why
5641 	 * we don't use shadow hmeblks and hash starting from the smallest
5642 	 * page size.
5643 	 */
5644 	if (sfmmup == KHATID) {
5645 		iskernel = 1;
5646 		hashno = TTE64K;
5647 	} else {
5648 		iskernel = 0;
5649 		if (mmu_page_sizes == max_mmu_page_sizes) {
5650 			hashno = TTE256M;
5651 		} else {
5652 			hashno = TTE4M;
5653 		}
5654 	}
5655 	while (addr < endaddr) {
5656 		hmeshift = HME_HASH_SHIFT(hashno);
5657 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5658 		hblktag.htag_rehash = hashno;
5659 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5660 
5661 		SFMMU_HASH_LOCK(hmebp);
5662 
5663 		HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
5664 		if (hmeblkp == NULL) {
5665 			/*
5666 			 * didn't find an hmeblk. skip the appropiate
5667 			 * address range.
5668 			 */
5669 			SFMMU_HASH_UNLOCK(hmebp);
5670 			if (iskernel) {
5671 				if (hashno < mmu_hashcnt) {
5672 					hashno++;
5673 					continue;
5674 				} else {
5675 					hashno = TTE64K;
5676 					addr = (caddr_t)roundup((uintptr_t)addr
5677 					    + 1, MMU_PAGESIZE64K);
5678 					continue;
5679 				}
5680 			}
5681 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5682 			    (1 << hmeshift));
5683 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5684 				ASSERT(hashno == TTE64K);
5685 				continue;
5686 			}
5687 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5688 				hashno = TTE512K;
5689 				continue;
5690 			}
5691 			if (mmu_page_sizes == max_mmu_page_sizes) {
5692 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5693 					hashno = TTE4M;
5694 					continue;
5695 				}
5696 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5697 					hashno = TTE32M;
5698 					continue;
5699 				}
5700 				hashno = TTE256M;
5701 				continue;
5702 			} else {
5703 				hashno = TTE4M;
5704 				continue;
5705 			}
5706 		}
5707 		ASSERT(hmeblkp);
5708 		ASSERT(!hmeblkp->hblk_shared);
5709 		if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5710 			/*
5711 			 * If the valid count is zero we can skip the range
5712 			 * mapped by this hmeblk.
5713 			 * We free hblks in the case of HAT_UNMAP.  HAT_UNMAP
5714 			 * is used by segment drivers as a hint
5715 			 * that the mapping resource won't be used any longer.
5716 			 * The best example of this is during exit().
5717 			 */
5718 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5719 			    get_hblk_span(hmeblkp));
5720 			if ((flags & HAT_UNLOAD_UNMAP) ||
5721 			    (iskernel && !issegkmap)) {
5722 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
5723 				    &list, 0);
5724 			}
5725 			SFMMU_HASH_UNLOCK(hmebp);
5726 
5727 			if (iskernel) {
5728 				hashno = TTE64K;
5729 				continue;
5730 			}
5731 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5732 				ASSERT(hashno == TTE64K);
5733 				continue;
5734 			}
5735 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5736 				hashno = TTE512K;
5737 				continue;
5738 			}
5739 			if (mmu_page_sizes == max_mmu_page_sizes) {
5740 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5741 					hashno = TTE4M;
5742 					continue;
5743 				}
5744 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5745 					hashno = TTE32M;
5746 					continue;
5747 				}
5748 				hashno = TTE256M;
5749 				continue;
5750 			} else {
5751 				hashno = TTE4M;
5752 				continue;
5753 			}
5754 		}
5755 		if (hmeblkp->hblk_shw_bit) {
5756 			/*
5757 			 * If we encounter a shadow hmeblk we know there is
5758 			 * smaller sized hmeblks mapping the same address space.
5759 			 * Decrement the hash size and rehash.
5760 			 */
5761 			ASSERT(sfmmup != KHATID);
5762 			hashno--;
5763 			SFMMU_HASH_UNLOCK(hmebp);
5764 			continue;
5765 		}
5766 
5767 		/*
5768 		 * track callback address ranges.
5769 		 * only start a new range when it's not contiguous
5770 		 */
5771 		if (callback != NULL) {
5772 			if (addr_count > 0 &&
5773 			    addr == cb_end_addr[addr_count - 1])
5774 				--addr_count;
5775 			else
5776 				cb_start_addr[addr_count] = addr;
5777 		}
5778 
5779 		addr = sfmmu_hblk_unload(sfmmup, hmeblkp, addr, endaddr,
5780 		    dmrp, flags);
5781 
5782 		if (callback != NULL)
5783 			cb_end_addr[addr_count++] = addr;
5784 
5785 		if (((flags & HAT_UNLOAD_UNMAP) || (iskernel && !issegkmap)) &&
5786 		    !hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5787 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk, &list, 0);
5788 		}
5789 		SFMMU_HASH_UNLOCK(hmebp);
5790 
5791 		/*
5792 		 * Notify our caller as to exactly which pages
5793 		 * have been unloaded. We do these in clumps,
5794 		 * to minimize the number of xt_sync()s that need to occur.
5795 		 */
5796 		if (callback != NULL && addr_count == MAX_CB_ADDR) {
5797 			DEMAP_RANGE_FLUSH(dmrp);
5798 			if (dmrp != NULL) {
5799 				cpuset = sfmmup->sfmmu_cpusran;
5800 				xt_sync(cpuset);
5801 			}
5802 
5803 			for (a = 0; a < MAX_CB_ADDR; ++a) {
5804 				callback->hcb_start_addr = cb_start_addr[a];
5805 				callback->hcb_end_addr = cb_end_addr[a];
5806 				callback->hcb_function(callback);
5807 			}
5808 			addr_count = 0;
5809 		}
5810 		if (iskernel) {
5811 			hashno = TTE64K;
5812 			continue;
5813 		}
5814 		if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5815 			ASSERT(hashno == TTE64K);
5816 			continue;
5817 		}
5818 		if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5819 			hashno = TTE512K;
5820 			continue;
5821 		}
5822 		if (mmu_page_sizes == max_mmu_page_sizes) {
5823 			if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5824 				hashno = TTE4M;
5825 				continue;
5826 			}
5827 			if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5828 				hashno = TTE32M;
5829 				continue;
5830 			}
5831 			hashno = TTE256M;
5832 		} else {
5833 			hashno = TTE4M;
5834 		}
5835 	}
5836 
5837 	sfmmu_hblks_list_purge(&list, 0);
5838 	DEMAP_RANGE_FLUSH(dmrp);
5839 	if (dmrp != NULL) {
5840 		cpuset = sfmmup->sfmmu_cpusran;
5841 		xt_sync(cpuset);
5842 	}
5843 	if (callback && addr_count != 0) {
5844 		for (a = 0; a < addr_count; ++a) {
5845 			callback->hcb_start_addr = cb_start_addr[a];
5846 			callback->hcb_end_addr = cb_end_addr[a];
5847 			callback->hcb_function(callback);
5848 		}
5849 	}
5850 
5851 	/*
5852 	 * Check TSB and TLB page sizes if the process isn't exiting.
5853 	 */
5854 	if (!sfmmup->sfmmu_free)
5855 		sfmmu_check_page_sizes(sfmmup, 0);
5856 }
5857 
5858 /*
5859  * Unload all the mappings in the range [addr..addr+len). addr and len must
5860  * be MMU_PAGESIZE aligned.
5861  */
5862 void
5863 hat_unload(struct hat *sfmmup, caddr_t addr, size_t len, uint_t flags)
5864 {
5865 	if (sfmmup->sfmmu_xhat_provider) {
5866 		XHAT_UNLOAD(sfmmup, addr, len, flags);
5867 		return;
5868 	}
5869 	hat_unload_callback(sfmmup, addr, len, flags, NULL);
5870 }
5871 
5872 
5873 /*
5874  * Find the largest mapping size for this page.
5875  */
5876 int
5877 fnd_mapping_sz(page_t *pp)
5878 {
5879 	int sz;
5880 	int p_index;
5881 
5882 	p_index = PP_MAPINDEX(pp);
5883 
5884 	sz = 0;
5885 	p_index >>= 1;	/* don't care about 8K bit */
5886 	for (; p_index; p_index >>= 1) {
5887 		sz++;
5888 	}
5889 
5890 	return (sz);
5891 }
5892 
5893 /*
5894  * This function unloads a range of addresses for an hmeblk.
5895  * It returns the next address to be unloaded.
5896  * It should be called with the hash lock held.
5897  */
5898 static caddr_t
5899 sfmmu_hblk_unload(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5900 	caddr_t endaddr, demap_range_t *dmrp, uint_t flags)
5901 {
5902 	tte_t	tte, ttemod;
5903 	struct	sf_hment *sfhmep;
5904 	int	ttesz;
5905 	long	ttecnt;
5906 	page_t *pp;
5907 	kmutex_t *pml;
5908 	int ret;
5909 	int use_demap_range;
5910 
5911 	ASSERT(in_hblk_range(hmeblkp, addr));
5912 	ASSERT(!hmeblkp->hblk_shw_bit);
5913 	ASSERT(sfmmup != NULL || hmeblkp->hblk_shared);
5914 	ASSERT(sfmmup == NULL || !hmeblkp->hblk_shared);
5915 	ASSERT(dmrp == NULL || !hmeblkp->hblk_shared);
5916 
5917 #ifdef DEBUG
5918 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5919 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5920 		panic("sfmmu_hblk_unload: partial unload of large page");
5921 	}
5922 #endif /* DEBUG */
5923 
5924 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5925 	ttesz = get_hblk_ttesz(hmeblkp);
5926 
5927 	use_demap_range = ((dmrp == NULL) ||
5928 	    (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp)));
5929 
5930 	if (use_demap_range) {
5931 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5932 	} else {
5933 		DEMAP_RANGE_FLUSH(dmrp);
5934 	}
5935 	ttecnt = 0;
5936 	HBLKTOHME(sfhmep, hmeblkp, addr);
5937 
5938 	while (addr < endaddr) {
5939 		pml = NULL;
5940 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5941 		if (TTE_IS_VALID(&tte)) {
5942 			pp = sfhmep->hme_page;
5943 			if (pp != NULL) {
5944 				pml = sfmmu_mlist_enter(pp);
5945 			}
5946 
5947 			/*
5948 			 * Verify if hme still points to 'pp' now that
5949 			 * we have p_mapping lock.
5950 			 */
5951 			if (sfhmep->hme_page != pp) {
5952 				if (pp != NULL && sfhmep->hme_page != NULL) {
5953 					ASSERT(pml != NULL);
5954 					sfmmu_mlist_exit(pml);
5955 					/* Re-start this iteration. */
5956 					continue;
5957 				}
5958 				ASSERT((pp != NULL) &&
5959 				    (sfhmep->hme_page == NULL));
5960 				goto tte_unloaded;
5961 			}
5962 
5963 			/*
5964 			 * This point on we have both HASH and p_mapping
5965 			 * lock.
5966 			 */
5967 			ASSERT(pp == sfhmep->hme_page);
5968 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5969 
5970 			/*
5971 			 * We need to loop on modify tte because it is
5972 			 * possible for pagesync to come along and
5973 			 * change the software bits beneath us.
5974 			 *
5975 			 * Page_unload can also invalidate the tte after
5976 			 * we read tte outside of p_mapping lock.
5977 			 */
5978 again:
5979 			ttemod = tte;
5980 
5981 			TTE_SET_INVALID(&ttemod);
5982 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5983 			    &sfhmep->hme_tte);
5984 
5985 			if (ret <= 0) {
5986 				if (TTE_IS_VALID(&tte)) {
5987 					ASSERT(ret < 0);
5988 					goto again;
5989 				}
5990 				if (pp != NULL) {
5991 					panic("sfmmu_hblk_unload: pp = 0x%p "
5992 					    "tte became invalid under mlist"
5993 					    " lock = 0x%p", (void *)pp,
5994 					    (void *)pml);
5995 				}
5996 				continue;
5997 			}
5998 
5999 			if (!(flags & HAT_UNLOAD_NOSYNC)) {
6000 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
6001 			}
6002 
6003 			/*
6004 			 * Ok- we invalidated the tte. Do the rest of the job.
6005 			 */
6006 			ttecnt++;
6007 
6008 			if (flags & HAT_UNLOAD_UNLOCK) {
6009 				ASSERT(hmeblkp->hblk_lckcnt > 0);
6010 				atomic_add_32(&hmeblkp->hblk_lckcnt, -1);
6011 				HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
6012 			}
6013 
6014 			/*
6015 			 * Normally we would need to flush the page
6016 			 * from the virtual cache at this point in
6017 			 * order to prevent a potential cache alias
6018 			 * inconsistency.
6019 			 * The particular scenario we need to worry
6020 			 * about is:
6021 			 * Given:  va1 and va2 are two virtual address
6022 			 * that alias and map the same physical
6023 			 * address.
6024 			 * 1.   mapping exists from va1 to pa and data
6025 			 * has been read into the cache.
6026 			 * 2.   unload va1.
6027 			 * 3.   load va2 and modify data using va2.
6028 			 * 4    unload va2.
6029 			 * 5.   load va1 and reference data.  Unless we
6030 			 * flush the data cache when we unload we will
6031 			 * get stale data.
6032 			 * Fortunately, page coloring eliminates the
6033 			 * above scenario by remembering the color a
6034 			 * physical page was last or is currently
6035 			 * mapped to.  Now, we delay the flush until
6036 			 * the loading of translations.  Only when the
6037 			 * new translation is of a different color
6038 			 * are we forced to flush.
6039 			 */
6040 			if (use_demap_range) {
6041 				/*
6042 				 * Mark this page as needing a demap.
6043 				 */
6044 				DEMAP_RANGE_MARKPG(dmrp, addr);
6045 			} else {
6046 				ASSERT(sfmmup != NULL);
6047 				ASSERT(!hmeblkp->hblk_shared);
6048 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
6049 				    sfmmup->sfmmu_free, 0);
6050 			}
6051 
6052 			if (pp) {
6053 				/*
6054 				 * Remove the hment from the mapping list
6055 				 */
6056 				ASSERT(hmeblkp->hblk_hmecnt > 0);
6057 
6058 				/*
6059 				 * Again, we cannot
6060 				 * ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS);
6061 				 */
6062 				HME_SUB(sfhmep, pp);
6063 				membar_stst();
6064 				atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
6065 			}
6066 
6067 			ASSERT(hmeblkp->hblk_vcnt > 0);
6068 			atomic_add_16(&hmeblkp->hblk_vcnt, -1);
6069 
6070 			ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
6071 			    !hmeblkp->hblk_lckcnt);
6072 
6073 #ifdef VAC
6074 			if (pp && (pp->p_nrm & (P_KPMC | P_KPMS | P_TNC))) {
6075 				if (PP_ISTNC(pp)) {
6076 					/*
6077 					 * If page was temporary
6078 					 * uncached, try to recache
6079 					 * it. Note that HME_SUB() was
6080 					 * called above so p_index and
6081 					 * mlist had been updated.
6082 					 */
6083 					conv_tnc(pp, ttesz);
6084 				} else if (pp->p_mapping == NULL) {
6085 					ASSERT(kpm_enable);
6086 					/*
6087 					 * Page is marked to be in VAC conflict
6088 					 * to an existing kpm mapping and/or is
6089 					 * kpm mapped using only the regular
6090 					 * pagesize.
6091 					 */
6092 					sfmmu_kpm_hme_unload(pp);
6093 				}
6094 			}
6095 #endif	/* VAC */
6096 		} else if ((pp = sfhmep->hme_page) != NULL) {
6097 				/*
6098 				 * TTE is invalid but the hme
6099 				 * still exists. let pageunload
6100 				 * complete its job.
6101 				 */
6102 				ASSERT(pml == NULL);
6103 				pml = sfmmu_mlist_enter(pp);
6104 				if (sfhmep->hme_page != NULL) {
6105 					sfmmu_mlist_exit(pml);
6106 					continue;
6107 				}
6108 				ASSERT(sfhmep->hme_page == NULL);
6109 		} else if (hmeblkp->hblk_hmecnt != 0) {
6110 			/*
6111 			 * pageunload may have not finished decrementing
6112 			 * hblk_vcnt and hblk_hmecnt. Find page_t if any and
6113 			 * wait for pageunload to finish. Rely on pageunload
6114 			 * to decrement hblk_hmecnt after hblk_vcnt.
6115 			 */
6116 			pfn_t pfn = TTE_TO_TTEPFN(&tte);
6117 			ASSERT(pml == NULL);
6118 			if (pf_is_memory(pfn)) {
6119 				pp = page_numtopp_nolock(pfn);
6120 				if (pp != NULL) {
6121 					pml = sfmmu_mlist_enter(pp);
6122 					sfmmu_mlist_exit(pml);
6123 					pml = NULL;
6124 				}
6125 			}
6126 		}
6127 
6128 tte_unloaded:
6129 		/*
6130 		 * At this point, the tte we are looking at
6131 		 * should be unloaded, and hme has been unlinked
6132 		 * from page too. This is important because in
6133 		 * pageunload, it does ttesync() then HME_SUB.
6134 		 * We need to make sure HME_SUB has been completed
6135 		 * so we know ttesync() has been completed. Otherwise,
6136 		 * at exit time, after return from hat layer, VM will
6137 		 * release as structure which hat_setstat() (called
6138 		 * by ttesync()) needs.
6139 		 */
6140 #ifdef DEBUG
6141 		{
6142 			tte_t	dtte;
6143 
6144 			ASSERT(sfhmep->hme_page == NULL);
6145 
6146 			sfmmu_copytte(&sfhmep->hme_tte, &dtte);
6147 			ASSERT(!TTE_IS_VALID(&dtte));
6148 		}
6149 #endif
6150 
6151 		if (pml) {
6152 			sfmmu_mlist_exit(pml);
6153 		}
6154 
6155 		addr += TTEBYTES(ttesz);
6156 		sfhmep++;
6157 		DEMAP_RANGE_NEXTPG(dmrp);
6158 	}
6159 	/*
6160 	 * For shared hmeblks this routine is only called when region is freed
6161 	 * and no longer referenced.  So no need to decrement ttecnt
6162 	 * in the region structure here.
6163 	 */
6164 	if (ttecnt > 0 && sfmmup != NULL) {
6165 		atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -ttecnt);
6166 	}
6167 	return (addr);
6168 }
6169 
6170 /*
6171  * Synchronize all the mappings in the range [addr..addr+len).
6172  * Can be called with clearflag having two states:
6173  * HAT_SYNC_DONTZERO means just return the rm stats
6174  * HAT_SYNC_ZERORM means zero rm bits in the tte and return the stats
6175  */
6176 void
6177 hat_sync(struct hat *sfmmup, caddr_t addr, size_t len, uint_t clearflag)
6178 {
6179 	struct hmehash_bucket *hmebp;
6180 	hmeblk_tag hblktag;
6181 	int hmeshift, hashno = 1;
6182 	struct hme_blk *hmeblkp, *list = NULL;
6183 	caddr_t endaddr;
6184 	cpuset_t cpuset;
6185 
6186 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
6187 	ASSERT((sfmmup == ksfmmup) ||
6188 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
6189 	ASSERT((len & MMU_PAGEOFFSET) == 0);
6190 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
6191 	    (clearflag == HAT_SYNC_ZERORM));
6192 
6193 	CPUSET_ZERO(cpuset);
6194 
6195 	endaddr = addr + len;
6196 	hblktag.htag_id = sfmmup;
6197 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
6198 
6199 	/*
6200 	 * Spitfire supports 4 page sizes.
6201 	 * Most pages are expected to be of the smallest page
6202 	 * size (8K) and these will not need to be rehashed. 64K
6203 	 * pages also don't need to be rehashed because the an hmeblk
6204 	 * spans 64K of address space. 512K pages might need 1 rehash and
6205 	 * and 4M pages 2 rehashes.
6206 	 */
6207 	while (addr < endaddr) {
6208 		hmeshift = HME_HASH_SHIFT(hashno);
6209 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
6210 		hblktag.htag_rehash = hashno;
6211 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
6212 
6213 		SFMMU_HASH_LOCK(hmebp);
6214 
6215 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
6216 		if (hmeblkp != NULL) {
6217 			ASSERT(!hmeblkp->hblk_shared);
6218 			/*
6219 			 * We've encountered a shadow hmeblk so skip the range
6220 			 * of the next smaller mapping size.
6221 			 */
6222 			if (hmeblkp->hblk_shw_bit) {
6223 				ASSERT(sfmmup != ksfmmup);
6224 				ASSERT(hashno > 1);
6225 				addr = (caddr_t)P2END((uintptr_t)addr,
6226 				    TTEBYTES(hashno - 1));
6227 			} else {
6228 				addr = sfmmu_hblk_sync(sfmmup, hmeblkp,
6229 				    addr, endaddr, clearflag);
6230 			}
6231 			SFMMU_HASH_UNLOCK(hmebp);
6232 			hashno = 1;
6233 			continue;
6234 		}
6235 		SFMMU_HASH_UNLOCK(hmebp);
6236 
6237 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
6238 			/*
6239 			 * We have traversed the whole list and rehashed
6240 			 * if necessary without finding the address to sync.
6241 			 * This is ok so we increment the address by the
6242 			 * smallest hmeblk range for kernel mappings and the
6243 			 * largest hmeblk range, to account for shadow hmeblks,
6244 			 * for user mappings and continue.
6245 			 */
6246 			if (sfmmup == ksfmmup)
6247 				addr = (caddr_t)P2END((uintptr_t)addr,
6248 				    TTEBYTES(1));
6249 			else
6250 				addr = (caddr_t)P2END((uintptr_t)addr,
6251 				    TTEBYTES(hashno));
6252 			hashno = 1;
6253 		} else {
6254 			hashno++;
6255 		}
6256 	}
6257 	sfmmu_hblks_list_purge(&list, 0);
6258 	cpuset = sfmmup->sfmmu_cpusran;
6259 	xt_sync(cpuset);
6260 }
6261 
6262 static caddr_t
6263 sfmmu_hblk_sync(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
6264 	caddr_t endaddr, int clearflag)
6265 {
6266 	tte_t	tte, ttemod;
6267 	struct sf_hment *sfhmep;
6268 	int ttesz;
6269 	struct page *pp;
6270 	kmutex_t *pml;
6271 	int ret;
6272 
6273 	ASSERT(hmeblkp->hblk_shw_bit == 0);
6274 	ASSERT(!hmeblkp->hblk_shared);
6275 
6276 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
6277 
6278 	ttesz = get_hblk_ttesz(hmeblkp);
6279 	HBLKTOHME(sfhmep, hmeblkp, addr);
6280 
6281 	while (addr < endaddr) {
6282 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6283 		if (TTE_IS_VALID(&tte)) {
6284 			pml = NULL;
6285 			pp = sfhmep->hme_page;
6286 			if (pp) {
6287 				pml = sfmmu_mlist_enter(pp);
6288 			}
6289 			if (pp != sfhmep->hme_page) {
6290 				/*
6291 				 * tte most have been unloaded
6292 				 * underneath us.  Recheck
6293 				 */
6294 				ASSERT(pml);
6295 				sfmmu_mlist_exit(pml);
6296 				continue;
6297 			}
6298 
6299 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
6300 
6301 			if (clearflag == HAT_SYNC_ZERORM) {
6302 				ttemod = tte;
6303 				TTE_CLR_RM(&ttemod);
6304 				ret = sfmmu_modifytte_try(&tte, &ttemod,
6305 				    &sfhmep->hme_tte);
6306 				if (ret < 0) {
6307 					if (pml) {
6308 						sfmmu_mlist_exit(pml);
6309 					}
6310 					continue;
6311 				}
6312 
6313 				if (ret > 0) {
6314 					sfmmu_tlb_demap(addr, sfmmup,
6315 					    hmeblkp, 0, 0);
6316 				}
6317 			}
6318 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
6319 			if (pml) {
6320 				sfmmu_mlist_exit(pml);
6321 			}
6322 		}
6323 		addr += TTEBYTES(ttesz);
6324 		sfhmep++;
6325 	}
6326 	return (addr);
6327 }
6328 
6329 /*
6330  * This function will sync a tte to the page struct and it will
6331  * update the hat stats. Currently it allows us to pass a NULL pp
6332  * and we will simply update the stats.  We may want to change this
6333  * so we only keep stats for pages backed by pp's.
6334  */
6335 static void
6336 sfmmu_ttesync(struct hat *sfmmup, caddr_t addr, tte_t *ttep, page_t *pp)
6337 {
6338 	uint_t rm = 0;
6339 	int   	sz;
6340 	pgcnt_t	npgs;
6341 
6342 	ASSERT(TTE_IS_VALID(ttep));
6343 
6344 	if (TTE_IS_NOSYNC(ttep)) {
6345 		return;
6346 	}
6347 
6348 	if (TTE_IS_REF(ttep))  {
6349 		rm = P_REF;
6350 	}
6351 	if (TTE_IS_MOD(ttep))  {
6352 		rm |= P_MOD;
6353 	}
6354 
6355 	if (rm == 0) {
6356 		return;
6357 	}
6358 
6359 	sz = TTE_CSZ(ttep);
6360 	if (sfmmup != NULL && sfmmup->sfmmu_rmstat) {
6361 		int i;
6362 		caddr_t	vaddr = addr;
6363 
6364 		for (i = 0; i < TTEPAGES(sz); i++, vaddr += MMU_PAGESIZE) {
6365 			hat_setstat(sfmmup->sfmmu_as, vaddr, MMU_PAGESIZE, rm);
6366 		}
6367 
6368 	}
6369 
6370 	/*
6371 	 * XXX I want to use cas to update nrm bits but they
6372 	 * currently belong in common/vm and not in hat where
6373 	 * they should be.
6374 	 * The nrm bits are protected by the same mutex as
6375 	 * the one that protects the page's mapping list.
6376 	 */
6377 	if (!pp)
6378 		return;
6379 	ASSERT(sfmmu_mlist_held(pp));
6380 	/*
6381 	 * If the tte is for a large page, we need to sync all the
6382 	 * pages covered by the tte.
6383 	 */
6384 	if (sz != TTE8K) {
6385 		ASSERT(pp->p_szc != 0);
6386 		pp = PP_GROUPLEADER(pp, sz);
6387 		ASSERT(sfmmu_mlist_held(pp));
6388 	}
6389 
6390 	/* Get number of pages from tte size. */
6391 	npgs = TTEPAGES(sz);
6392 
6393 	do {
6394 		ASSERT(pp);
6395 		ASSERT(sfmmu_mlist_held(pp));
6396 		if (((rm & P_REF) != 0 && !PP_ISREF(pp)) ||
6397 		    ((rm & P_MOD) != 0 && !PP_ISMOD(pp)))
6398 			hat_page_setattr(pp, rm);
6399 
6400 		/*
6401 		 * Are we done? If not, we must have a large mapping.
6402 		 * For large mappings we need to sync the rest of the pages
6403 		 * covered by this tte; goto the next page.
6404 		 */
6405 	} while (--npgs > 0 && (pp = PP_PAGENEXT(pp)));
6406 }
6407 
6408 /*
6409  * Execute pre-callback handler of each pa_hment linked to pp
6410  *
6411  * Inputs:
6412  *   flag: either HAT_PRESUSPEND or HAT_SUSPEND.
6413  *   capture_cpus: pointer to return value (below)
6414  *
6415  * Returns:
6416  *   Propagates the subsystem callback return values back to the caller;
6417  *   returns 0 on success.  If capture_cpus is non-NULL, the value returned
6418  *   is zero if all of the pa_hments are of a type that do not require
6419  *   capturing CPUs prior to suspending the mapping, else it is 1.
6420  */
6421 static int
6422 hat_pageprocess_precallbacks(struct page *pp, uint_t flag, int *capture_cpus)
6423 {
6424 	struct sf_hment	*sfhmep;
6425 	struct pa_hment *pahmep;
6426 	int (*f)(caddr_t, uint_t, uint_t, void *);
6427 	int		ret;
6428 	id_t		id;
6429 	int		locked = 0;
6430 	kmutex_t	*pml;
6431 
6432 	ASSERT(PAGE_EXCL(pp));
6433 	if (!sfmmu_mlist_held(pp)) {
6434 		pml = sfmmu_mlist_enter(pp);
6435 		locked = 1;
6436 	}
6437 
6438 	if (capture_cpus)
6439 		*capture_cpus = 0;
6440 
6441 top:
6442 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6443 		/*
6444 		 * skip sf_hments corresponding to VA<->PA mappings;
6445 		 * for pa_hment's, hme_tte.ll is zero
6446 		 */
6447 		if (!IS_PAHME(sfhmep))
6448 			continue;
6449 
6450 		pahmep = sfhmep->hme_data;
6451 		ASSERT(pahmep != NULL);
6452 
6453 		/*
6454 		 * skip if pre-handler has been called earlier in this loop
6455 		 */
6456 		if (pahmep->flags & flag)
6457 			continue;
6458 
6459 		id = pahmep->cb_id;
6460 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6461 		if (capture_cpus && sfmmu_cb_table[id].capture_cpus != 0)
6462 			*capture_cpus = 1;
6463 		if ((f = sfmmu_cb_table[id].prehandler) == NULL) {
6464 			pahmep->flags |= flag;
6465 			continue;
6466 		}
6467 
6468 		/*
6469 		 * Drop the mapping list lock to avoid locking order issues.
6470 		 */
6471 		if (locked)
6472 			sfmmu_mlist_exit(pml);
6473 
6474 		ret = f(pahmep->addr, pahmep->len, flag, pahmep->pvt);
6475 		if (ret != 0)
6476 			return (ret);	/* caller must do the cleanup */
6477 
6478 		if (locked) {
6479 			pml = sfmmu_mlist_enter(pp);
6480 			pahmep->flags |= flag;
6481 			goto top;
6482 		}
6483 
6484 		pahmep->flags |= flag;
6485 	}
6486 
6487 	if (locked)
6488 		sfmmu_mlist_exit(pml);
6489 
6490 	return (0);
6491 }
6492 
6493 /*
6494  * Execute post-callback handler of each pa_hment linked to pp
6495  *
6496  * Same overall assumptions and restrictions apply as for
6497  * hat_pageprocess_precallbacks().
6498  */
6499 static void
6500 hat_pageprocess_postcallbacks(struct page *pp, uint_t flag)
6501 {
6502 	pfn_t pgpfn = pp->p_pagenum;
6503 	pfn_t pgmask = btop(page_get_pagesize(pp->p_szc)) - 1;
6504 	pfn_t newpfn;
6505 	struct sf_hment *sfhmep;
6506 	struct pa_hment *pahmep;
6507 	int (*f)(caddr_t, uint_t, uint_t, void *, pfn_t);
6508 	id_t	id;
6509 	int	locked = 0;
6510 	kmutex_t *pml;
6511 
6512 	ASSERT(PAGE_EXCL(pp));
6513 	if (!sfmmu_mlist_held(pp)) {
6514 		pml = sfmmu_mlist_enter(pp);
6515 		locked = 1;
6516 	}
6517 
6518 top:
6519 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6520 		/*
6521 		 * skip sf_hments corresponding to VA<->PA mappings;
6522 		 * for pa_hment's, hme_tte.ll is zero
6523 		 */
6524 		if (!IS_PAHME(sfhmep))
6525 			continue;
6526 
6527 		pahmep = sfhmep->hme_data;
6528 		ASSERT(pahmep != NULL);
6529 
6530 		if ((pahmep->flags & flag) == 0)
6531 			continue;
6532 
6533 		pahmep->flags &= ~flag;
6534 
6535 		id = pahmep->cb_id;
6536 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6537 		if ((f = sfmmu_cb_table[id].posthandler) == NULL)
6538 			continue;
6539 
6540 		/*
6541 		 * Convert the base page PFN into the constituent PFN
6542 		 * which is needed by the callback handler.
6543 		 */
6544 		newpfn = pgpfn | (btop((uintptr_t)pahmep->addr) & pgmask);
6545 
6546 		/*
6547 		 * Drop the mapping list lock to avoid locking order issues.
6548 		 */
6549 		if (locked)
6550 			sfmmu_mlist_exit(pml);
6551 
6552 		if (f(pahmep->addr, pahmep->len, flag, pahmep->pvt, newpfn)
6553 		    != 0)
6554 			panic("sfmmu: posthandler failed");
6555 
6556 		if (locked) {
6557 			pml = sfmmu_mlist_enter(pp);
6558 			goto top;
6559 		}
6560 	}
6561 
6562 	if (locked)
6563 		sfmmu_mlist_exit(pml);
6564 }
6565 
6566 /*
6567  * Suspend locked kernel mapping
6568  */
6569 void
6570 hat_pagesuspend(struct page *pp)
6571 {
6572 	struct sf_hment *sfhmep;
6573 	sfmmu_t *sfmmup;
6574 	tte_t tte, ttemod;
6575 	struct hme_blk *hmeblkp;
6576 	caddr_t addr;
6577 	int index, cons;
6578 	cpuset_t cpuset;
6579 
6580 	ASSERT(PAGE_EXCL(pp));
6581 	ASSERT(sfmmu_mlist_held(pp));
6582 
6583 	mutex_enter(&kpr_suspendlock);
6584 
6585 	/*
6586 	 * We're about to suspend a kernel mapping so mark this thread as
6587 	 * non-traceable by DTrace. This prevents us from running into issues
6588 	 * with probe context trying to touch a suspended page
6589 	 * in the relocation codepath itself.
6590 	 */
6591 	curthread->t_flag |= T_DONTDTRACE;
6592 
6593 	index = PP_MAPINDEX(pp);
6594 	cons = TTE8K;
6595 
6596 retry:
6597 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6598 
6599 		if (IS_PAHME(sfhmep))
6600 			continue;
6601 
6602 		if (get_hblk_ttesz(sfmmu_hmetohblk(sfhmep)) != cons)
6603 			continue;
6604 
6605 		/*
6606 		 * Loop until we successfully set the suspend bit in
6607 		 * the TTE.
6608 		 */
6609 again:
6610 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6611 		ASSERT(TTE_IS_VALID(&tte));
6612 
6613 		ttemod = tte;
6614 		TTE_SET_SUSPEND(&ttemod);
6615 		if (sfmmu_modifytte_try(&tte, &ttemod,
6616 		    &sfhmep->hme_tte) < 0)
6617 			goto again;
6618 
6619 		/*
6620 		 * Invalidate TSB entry
6621 		 */
6622 		hmeblkp = sfmmu_hmetohblk(sfhmep);
6623 
6624 		sfmmup = hblktosfmmu(hmeblkp);
6625 		ASSERT(sfmmup == ksfmmup);
6626 		ASSERT(!hmeblkp->hblk_shared);
6627 
6628 		addr = tte_to_vaddr(hmeblkp, tte);
6629 
6630 		/*
6631 		 * No need to make sure that the TSB for this sfmmu is
6632 		 * not being relocated since it is ksfmmup and thus it
6633 		 * will never be relocated.
6634 		 */
6635 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
6636 
6637 		/*
6638 		 * Update xcall stats
6639 		 */
6640 		cpuset = cpu_ready_set;
6641 		CPUSET_DEL(cpuset, CPU->cpu_id);
6642 
6643 		/* LINTED: constant in conditional context */
6644 		SFMMU_XCALL_STATS(ksfmmup);
6645 
6646 		/*
6647 		 * Flush TLB entry on remote CPU's
6648 		 */
6649 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
6650 		    (uint64_t)ksfmmup);
6651 		xt_sync(cpuset);
6652 
6653 		/*
6654 		 * Flush TLB entry on local CPU
6655 		 */
6656 		vtag_flushpage(addr, (uint64_t)ksfmmup);
6657 	}
6658 
6659 	while (index != 0) {
6660 		index = index >> 1;
6661 		if (index != 0)
6662 			cons++;
6663 		if (index & 0x1) {
6664 			pp = PP_GROUPLEADER(pp, cons);
6665 			goto retry;
6666 		}
6667 	}
6668 }
6669 
6670 #ifdef	DEBUG
6671 
6672 #define	N_PRLE	1024
6673 struct prle {
6674 	page_t *targ;
6675 	page_t *repl;
6676 	int status;
6677 	int pausecpus;
6678 	hrtime_t whence;
6679 };
6680 
6681 static struct prle page_relocate_log[N_PRLE];
6682 static int prl_entry;
6683 static kmutex_t prl_mutex;
6684 
6685 #define	PAGE_RELOCATE_LOG(t, r, s, p)					\
6686 	mutex_enter(&prl_mutex);					\
6687 	page_relocate_log[prl_entry].targ = *(t);			\
6688 	page_relocate_log[prl_entry].repl = *(r);			\
6689 	page_relocate_log[prl_entry].status = (s);			\
6690 	page_relocate_log[prl_entry].pausecpus = (p);			\
6691 	page_relocate_log[prl_entry].whence = gethrtime();		\
6692 	prl_entry = (prl_entry == (N_PRLE - 1))? 0 : prl_entry + 1;	\
6693 	mutex_exit(&prl_mutex);
6694 
6695 #else	/* !DEBUG */
6696 #define	PAGE_RELOCATE_LOG(t, r, s, p)
6697 #endif
6698 
6699 /*
6700  * Core Kernel Page Relocation Algorithm
6701  *
6702  * Input:
6703  *
6704  * target : 	constituent pages are SE_EXCL locked.
6705  * replacement:	constituent pages are SE_EXCL locked.
6706  *
6707  * Output:
6708  *
6709  * nrelocp:	number of pages relocated
6710  */
6711 int
6712 hat_page_relocate(page_t **target, page_t **replacement, spgcnt_t *nrelocp)
6713 {
6714 	page_t		*targ, *repl;
6715 	page_t		*tpp, *rpp;
6716 	kmutex_t	*low, *high;
6717 	spgcnt_t	npages, i;
6718 	page_t		*pl = NULL;
6719 	int		old_pil;
6720 	cpuset_t	cpuset;
6721 	int		cap_cpus;
6722 	int		ret;
6723 #ifdef VAC
6724 	int		cflags = 0;
6725 #endif
6726 
6727 	if (hat_kpr_enabled == 0 || !kcage_on || PP_ISNORELOC(*target)) {
6728 		PAGE_RELOCATE_LOG(target, replacement, EAGAIN, -1);
6729 		return (EAGAIN);
6730 	}
6731 
6732 	mutex_enter(&kpr_mutex);
6733 	kreloc_thread = curthread;
6734 
6735 	targ = *target;
6736 	repl = *replacement;
6737 	ASSERT(repl != NULL);
6738 	ASSERT(targ->p_szc == repl->p_szc);
6739 
6740 	npages = page_get_pagecnt(targ->p_szc);
6741 
6742 	/*
6743 	 * unload VA<->PA mappings that are not locked
6744 	 */
6745 	tpp = targ;
6746 	for (i = 0; i < npages; i++) {
6747 		(void) hat_pageunload(tpp, SFMMU_KERNEL_RELOC);
6748 		tpp++;
6749 	}
6750 
6751 	/*
6752 	 * Do "presuspend" callbacks, in a context from which we can still
6753 	 * block as needed. Note that we don't hold the mapping list lock
6754 	 * of "targ" at this point due to potential locking order issues;
6755 	 * we assume that between the hat_pageunload() above and holding
6756 	 * the SE_EXCL lock that the mapping list *cannot* change at this
6757 	 * point.
6758 	 */
6759 	ret = hat_pageprocess_precallbacks(targ, HAT_PRESUSPEND, &cap_cpus);
6760 	if (ret != 0) {
6761 		/*
6762 		 * EIO translates to fatal error, for all others cleanup
6763 		 * and return EAGAIN.
6764 		 */
6765 		ASSERT(ret != EIO);
6766 		hat_pageprocess_postcallbacks(targ, HAT_POSTUNSUSPEND);
6767 		PAGE_RELOCATE_LOG(target, replacement, ret, -1);
6768 		kreloc_thread = NULL;
6769 		mutex_exit(&kpr_mutex);
6770 		return (EAGAIN);
6771 	}
6772 
6773 	/*
6774 	 * acquire p_mapping list lock for both the target and replacement
6775 	 * root pages.
6776 	 *
6777 	 * low and high refer to the need to grab the mlist locks in a
6778 	 * specific order in order to prevent race conditions.  Thus the
6779 	 * lower lock must be grabbed before the higher lock.
6780 	 *
6781 	 * This will block hat_unload's accessing p_mapping list.  Since
6782 	 * we have SE_EXCL lock, hat_memload and hat_pageunload will be
6783 	 * blocked.  Thus, no one else will be accessing the p_mapping list
6784 	 * while we suspend and reload the locked mapping below.
6785 	 */
6786 	tpp = targ;
6787 	rpp = repl;
6788 	sfmmu_mlist_reloc_enter(tpp, rpp, &low, &high);
6789 
6790 	kpreempt_disable();
6791 
6792 	/*
6793 	 * We raise our PIL to 13 so that we don't get captured by
6794 	 * another CPU or pinned by an interrupt thread.  We can't go to
6795 	 * PIL 14 since the nexus driver(s) may need to interrupt at
6796 	 * that level in the case of IOMMU pseudo mappings.
6797 	 */
6798 	cpuset = cpu_ready_set;
6799 	CPUSET_DEL(cpuset, CPU->cpu_id);
6800 	if (!cap_cpus || CPUSET_ISNULL(cpuset)) {
6801 		old_pil = splr(XCALL_PIL);
6802 	} else {
6803 		old_pil = -1;
6804 		xc_attention(cpuset);
6805 	}
6806 	ASSERT(getpil() == XCALL_PIL);
6807 
6808 	/*
6809 	 * Now do suspend callbacks. In the case of an IOMMU mapping
6810 	 * this will suspend all DMA activity to the page while it is
6811 	 * being relocated. Since we are well above LOCK_LEVEL and CPUs
6812 	 * may be captured at this point we should have acquired any needed
6813 	 * locks in the presuspend callback.
6814 	 */
6815 	ret = hat_pageprocess_precallbacks(targ, HAT_SUSPEND, NULL);
6816 	if (ret != 0) {
6817 		repl = targ;
6818 		goto suspend_fail;
6819 	}
6820 
6821 	/*
6822 	 * Raise the PIL yet again, this time to block all high-level
6823 	 * interrupts on this CPU. This is necessary to prevent an
6824 	 * interrupt routine from pinning the thread which holds the
6825 	 * mapping suspended and then touching the suspended page.
6826 	 *
6827 	 * Once the page is suspended we also need to be careful to
6828 	 * avoid calling any functions which touch any seg_kmem memory
6829 	 * since that memory may be backed by the very page we are
6830 	 * relocating in here!
6831 	 */
6832 	hat_pagesuspend(targ);
6833 
6834 	/*
6835 	 * Now that we are confident everybody has stopped using this page,
6836 	 * copy the page contents.  Note we use a physical copy to prevent
6837 	 * locking issues and to avoid fpRAS because we can't handle it in
6838 	 * this context.
6839 	 */
6840 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6841 #ifdef VAC
6842 		/*
6843 		 * If the replacement has a different vcolor than
6844 		 * the one being replacd, we need to handle VAC
6845 		 * consistency for it just as we were setting up
6846 		 * a new mapping to it.
6847 		 */
6848 		if ((PP_GET_VCOLOR(rpp) != NO_VCOLOR) &&
6849 		    (tpp->p_vcolor != rpp->p_vcolor) &&
6850 		    !CacheColor_IsFlushed(cflags, PP_GET_VCOLOR(rpp))) {
6851 			CacheColor_SetFlushed(cflags, PP_GET_VCOLOR(rpp));
6852 			sfmmu_cache_flushcolor(PP_GET_VCOLOR(rpp),
6853 			    rpp->p_pagenum);
6854 		}
6855 #endif
6856 		/*
6857 		 * Copy the contents of the page.
6858 		 */
6859 		ppcopy_kernel(tpp, rpp);
6860 	}
6861 
6862 	tpp = targ;
6863 	rpp = repl;
6864 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6865 		/*
6866 		 * Copy attributes.  VAC consistency was handled above,
6867 		 * if required.
6868 		 */
6869 		rpp->p_nrm = tpp->p_nrm;
6870 		tpp->p_nrm = 0;
6871 		rpp->p_index = tpp->p_index;
6872 		tpp->p_index = 0;
6873 #ifdef VAC
6874 		rpp->p_vcolor = tpp->p_vcolor;
6875 #endif
6876 	}
6877 
6878 	/*
6879 	 * First, unsuspend the page, if we set the suspend bit, and transfer
6880 	 * the mapping list from the target page to the replacement page.
6881 	 * Next process postcallbacks; since pa_hment's are linked only to the
6882 	 * p_mapping list of root page, we don't iterate over the constituent
6883 	 * pages.
6884 	 */
6885 	hat_pagereload(targ, repl);
6886 
6887 suspend_fail:
6888 	hat_pageprocess_postcallbacks(repl, HAT_UNSUSPEND);
6889 
6890 	/*
6891 	 * Now lower our PIL and release any captured CPUs since we
6892 	 * are out of the "danger zone".  After this it will again be
6893 	 * safe to acquire adaptive mutex locks, or to drop them...
6894 	 */
6895 	if (old_pil != -1) {
6896 		splx(old_pil);
6897 	} else {
6898 		xc_dismissed(cpuset);
6899 	}
6900 
6901 	kpreempt_enable();
6902 
6903 	sfmmu_mlist_reloc_exit(low, high);
6904 
6905 	/*
6906 	 * Postsuspend callbacks should drop any locks held across
6907 	 * the suspend callbacks.  As before, we don't hold the mapping
6908 	 * list lock at this point.. our assumption is that the mapping
6909 	 * list still can't change due to our holding SE_EXCL lock and
6910 	 * there being no unlocked mappings left. Hence the restriction
6911 	 * on calling context to hat_delete_callback()
6912 	 */
6913 	hat_pageprocess_postcallbacks(repl, HAT_POSTUNSUSPEND);
6914 	if (ret != 0) {
6915 		/*
6916 		 * The second presuspend call failed: we got here through
6917 		 * the suspend_fail label above.
6918 		 */
6919 		ASSERT(ret != EIO);
6920 		PAGE_RELOCATE_LOG(target, replacement, ret, cap_cpus);
6921 		kreloc_thread = NULL;
6922 		mutex_exit(&kpr_mutex);
6923 		return (EAGAIN);
6924 	}
6925 
6926 	/*
6927 	 * Now that we're out of the performance critical section we can
6928 	 * take care of updating the hash table, since we still
6929 	 * hold all the pages locked SE_EXCL at this point we
6930 	 * needn't worry about things changing out from under us.
6931 	 */
6932 	tpp = targ;
6933 	rpp = repl;
6934 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6935 
6936 		/*
6937 		 * replace targ with replacement in page_hash table
6938 		 */
6939 		targ = tpp;
6940 		page_relocate_hash(rpp, targ);
6941 
6942 		/*
6943 		 * concatenate target; caller of platform_page_relocate()
6944 		 * expects target to be concatenated after returning.
6945 		 */
6946 		ASSERT(targ->p_next == targ);
6947 		ASSERT(targ->p_prev == targ);
6948 		page_list_concat(&pl, &targ);
6949 	}
6950 
6951 	ASSERT(*target == pl);
6952 	*nrelocp = npages;
6953 	PAGE_RELOCATE_LOG(target, replacement, 0, cap_cpus);
6954 	kreloc_thread = NULL;
6955 	mutex_exit(&kpr_mutex);
6956 	return (0);
6957 }
6958 
6959 /*
6960  * Called when stray pa_hments are found attached to a page which is
6961  * being freed.  Notify the subsystem which attached the pa_hment of
6962  * the error if it registered a suitable handler, else panic.
6963  */
6964 static void
6965 sfmmu_pahment_leaked(struct pa_hment *pahmep)
6966 {
6967 	id_t cb_id = pahmep->cb_id;
6968 
6969 	ASSERT(cb_id >= (id_t)0 && cb_id < sfmmu_cb_nextid);
6970 	if (sfmmu_cb_table[cb_id].errhandler != NULL) {
6971 		if (sfmmu_cb_table[cb_id].errhandler(pahmep->addr, pahmep->len,
6972 		    HAT_CB_ERR_LEAKED, pahmep->pvt) == 0)
6973 			return;		/* non-fatal */
6974 	}
6975 	panic("pa_hment leaked: 0x%p", (void *)pahmep);
6976 }
6977 
6978 /*
6979  * Remove all mappings to page 'pp'.
6980  */
6981 int
6982 hat_pageunload(struct page *pp, uint_t forceflag)
6983 {
6984 	struct page *origpp = pp;
6985 	struct sf_hment *sfhme, *tmphme;
6986 	struct hme_blk *hmeblkp;
6987 	kmutex_t *pml;
6988 #ifdef VAC
6989 	kmutex_t *pmtx;
6990 #endif
6991 	cpuset_t cpuset, tset;
6992 	int index, cons;
6993 	int xhme_blks;
6994 	int pa_hments;
6995 
6996 	ASSERT(PAGE_EXCL(pp));
6997 
6998 retry_xhat:
6999 	tmphme = NULL;
7000 	xhme_blks = 0;
7001 	pa_hments = 0;
7002 	CPUSET_ZERO(cpuset);
7003 
7004 	pml = sfmmu_mlist_enter(pp);
7005 
7006 #ifdef VAC
7007 	if (pp->p_kpmref)
7008 		sfmmu_kpm_pageunload(pp);
7009 	ASSERT(!PP_ISMAPPED_KPM(pp));
7010 #endif
7011 	/*
7012 	 * Clear vpm reference. Since the page is exclusively locked
7013 	 * vpm cannot be referencing it.
7014 	 */
7015 	if (vpm_enable) {
7016 		pp->p_vpmref = 0;
7017 	}
7018 
7019 	index = PP_MAPINDEX(pp);
7020 	cons = TTE8K;
7021 retry:
7022 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7023 		tmphme = sfhme->hme_next;
7024 
7025 		if (IS_PAHME(sfhme)) {
7026 			ASSERT(sfhme->hme_data != NULL);
7027 			pa_hments++;
7028 			continue;
7029 		}
7030 
7031 		hmeblkp = sfmmu_hmetohblk(sfhme);
7032 		if (hmeblkp->hblk_xhat_bit) {
7033 			struct xhat_hme_blk *xblk =
7034 			    (struct xhat_hme_blk *)hmeblkp;
7035 
7036 			(void) XHAT_PAGEUNLOAD(xblk->xhat_hme_blk_hat,
7037 			    pp, forceflag, XBLK2PROVBLK(xblk));
7038 
7039 			xhme_blks = 1;
7040 			continue;
7041 		}
7042 
7043 		/*
7044 		 * If there are kernel mappings don't unload them, they will
7045 		 * be suspended.
7046 		 */
7047 		if (forceflag == SFMMU_KERNEL_RELOC && hmeblkp->hblk_lckcnt &&
7048 		    hmeblkp->hblk_tag.htag_id == ksfmmup)
7049 			continue;
7050 
7051 		tset = sfmmu_pageunload(pp, sfhme, cons);
7052 		CPUSET_OR(cpuset, tset);
7053 	}
7054 
7055 	while (index != 0) {
7056 		index = index >> 1;
7057 		if (index != 0)
7058 			cons++;
7059 		if (index & 0x1) {
7060 			/* Go to leading page */
7061 			pp = PP_GROUPLEADER(pp, cons);
7062 			ASSERT(sfmmu_mlist_held(pp));
7063 			goto retry;
7064 		}
7065 	}
7066 
7067 	/*
7068 	 * cpuset may be empty if the page was only mapped by segkpm,
7069 	 * in which case we won't actually cross-trap.
7070 	 */
7071 	xt_sync(cpuset);
7072 
7073 	/*
7074 	 * The page should have no mappings at this point, unless
7075 	 * we were called from hat_page_relocate() in which case we
7076 	 * leave the locked mappings which will be suspended later.
7077 	 */
7078 	ASSERT(!PP_ISMAPPED(origpp) || xhme_blks || pa_hments ||
7079 	    (forceflag == SFMMU_KERNEL_RELOC));
7080 
7081 #ifdef VAC
7082 	if (PP_ISTNC(pp)) {
7083 		if (cons == TTE8K) {
7084 			pmtx = sfmmu_page_enter(pp);
7085 			PP_CLRTNC(pp);
7086 			sfmmu_page_exit(pmtx);
7087 		} else {
7088 			conv_tnc(pp, cons);
7089 		}
7090 	}
7091 #endif	/* VAC */
7092 
7093 	if (pa_hments && forceflag != SFMMU_KERNEL_RELOC) {
7094 		/*
7095 		 * Unlink any pa_hments and free them, calling back
7096 		 * the responsible subsystem to notify it of the error.
7097 		 * This can occur in situations such as drivers leaking
7098 		 * DMA handles: naughty, but common enough that we'd like
7099 		 * to keep the system running rather than bringing it
7100 		 * down with an obscure error like "pa_hment leaked"
7101 		 * which doesn't aid the user in debugging their driver.
7102 		 */
7103 		for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7104 			tmphme = sfhme->hme_next;
7105 			if (IS_PAHME(sfhme)) {
7106 				struct pa_hment *pahmep = sfhme->hme_data;
7107 				sfmmu_pahment_leaked(pahmep);
7108 				HME_SUB(sfhme, pp);
7109 				kmem_cache_free(pa_hment_cache, pahmep);
7110 			}
7111 		}
7112 
7113 		ASSERT(!PP_ISMAPPED(origpp) || xhme_blks);
7114 	}
7115 
7116 	sfmmu_mlist_exit(pml);
7117 
7118 	/*
7119 	 * XHAT may not have finished unloading pages
7120 	 * because some other thread was waiting for
7121 	 * mlist lock and XHAT_PAGEUNLOAD let it do
7122 	 * the job.
7123 	 */
7124 	if (xhme_blks) {
7125 		pp = origpp;
7126 		goto retry_xhat;
7127 	}
7128 
7129 	return (0);
7130 }
7131 
7132 cpuset_t
7133 sfmmu_pageunload(page_t *pp, struct sf_hment *sfhme, int cons)
7134 {
7135 	struct hme_blk *hmeblkp;
7136 	sfmmu_t *sfmmup;
7137 	tte_t tte, ttemod;
7138 #ifdef DEBUG
7139 	tte_t orig_old;
7140 #endif /* DEBUG */
7141 	caddr_t addr;
7142 	int ttesz;
7143 	int ret;
7144 	cpuset_t cpuset;
7145 
7146 	ASSERT(pp != NULL);
7147 	ASSERT(sfmmu_mlist_held(pp));
7148 	ASSERT(!PP_ISKAS(pp));
7149 
7150 	CPUSET_ZERO(cpuset);
7151 
7152 	hmeblkp = sfmmu_hmetohblk(sfhme);
7153 
7154 readtte:
7155 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7156 	if (TTE_IS_VALID(&tte)) {
7157 		sfmmup = hblktosfmmu(hmeblkp);
7158 		ttesz = get_hblk_ttesz(hmeblkp);
7159 		/*
7160 		 * Only unload mappings of 'cons' size.
7161 		 */
7162 		if (ttesz != cons)
7163 			return (cpuset);
7164 
7165 		/*
7166 		 * Note that we have p_mapping lock, but no hash lock here.
7167 		 * hblk_unload() has to have both hash lock AND p_mapping
7168 		 * lock before it tries to modify tte. So, the tte could
7169 		 * not become invalid in the sfmmu_modifytte_try() below.
7170 		 */
7171 		ttemod = tte;
7172 #ifdef DEBUG
7173 		orig_old = tte;
7174 #endif /* DEBUG */
7175 
7176 		TTE_SET_INVALID(&ttemod);
7177 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7178 		if (ret < 0) {
7179 #ifdef DEBUG
7180 			/* only R/M bits can change. */
7181 			chk_tte(&orig_old, &tte, &ttemod, hmeblkp);
7182 #endif /* DEBUG */
7183 			goto readtte;
7184 		}
7185 
7186 		if (ret == 0) {
7187 			panic("pageunload: cas failed?");
7188 		}
7189 
7190 		addr = tte_to_vaddr(hmeblkp, tte);
7191 
7192 		if (hmeblkp->hblk_shared) {
7193 			sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7194 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
7195 			sf_region_t *rgnp;
7196 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7197 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7198 			ASSERT(srdp != NULL);
7199 			rgnp = srdp->srd_hmergnp[rid];
7200 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
7201 			cpuset = sfmmu_rgntlb_demap(addr, rgnp, hmeblkp, 1);
7202 			sfmmu_ttesync(NULL, addr, &tte, pp);
7203 			ASSERT(rgnp->rgn_ttecnt[ttesz] > 0);
7204 			atomic_add_long(&rgnp->rgn_ttecnt[ttesz], -1);
7205 		} else {
7206 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
7207 			atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -1);
7208 
7209 			/*
7210 			 * We need to flush the page from the virtual cache
7211 			 * in order to prevent a virtual cache alias
7212 			 * inconsistency. The particular scenario we need
7213 			 * to worry about is:
7214 			 * Given:  va1 and va2 are two virtual address that
7215 			 * alias and will map the same physical address.
7216 			 * 1.   mapping exists from va1 to pa and data has
7217 			 *	been read into the cache.
7218 			 * 2.   unload va1.
7219 			 * 3.   load va2 and modify data using va2.
7220 			 * 4    unload va2.
7221 			 * 5.   load va1 and reference data.  Unless we flush
7222 			 *	the data cache when we unload we will get
7223 			 *	stale data.
7224 			 * This scenario is taken care of by using virtual
7225 			 * page coloring.
7226 			 */
7227 			if (sfmmup->sfmmu_ismhat) {
7228 				/*
7229 				 * Flush TSBs, TLBs and caches
7230 				 * of every process
7231 				 * sharing this ism segment.
7232 				 */
7233 				sfmmu_hat_lock_all();
7234 				mutex_enter(&ism_mlist_lock);
7235 				kpreempt_disable();
7236 				sfmmu_ismtlbcache_demap(addr, sfmmup, hmeblkp,
7237 				    pp->p_pagenum, CACHE_NO_FLUSH);
7238 				kpreempt_enable();
7239 				mutex_exit(&ism_mlist_lock);
7240 				sfmmu_hat_unlock_all();
7241 				cpuset = cpu_ready_set;
7242 			} else {
7243 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7244 				cpuset = sfmmup->sfmmu_cpusran;
7245 			}
7246 		}
7247 
7248 		/*
7249 		 * Hme_sub has to run after ttesync() and a_rss update.
7250 		 * See hblk_unload().
7251 		 */
7252 		HME_SUB(sfhme, pp);
7253 		membar_stst();
7254 
7255 		/*
7256 		 * We can not make ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
7257 		 * since pteload may have done a HME_ADD() right after
7258 		 * we did the HME_SUB() above. Hmecnt is now maintained
7259 		 * by cas only. no lock guranteed its value. The only
7260 		 * gurantee we have is the hmecnt should not be less than
7261 		 * what it should be so the hblk will not be taken away.
7262 		 * It's also important that we decremented the hmecnt after
7263 		 * we are done with hmeblkp so that this hmeblk won't be
7264 		 * stolen.
7265 		 */
7266 		ASSERT(hmeblkp->hblk_hmecnt > 0);
7267 		ASSERT(hmeblkp->hblk_vcnt > 0);
7268 		atomic_add_16(&hmeblkp->hblk_vcnt, -1);
7269 		atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
7270 		/*
7271 		 * This is bug 4063182.
7272 		 * XXX: fixme
7273 		 * ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
7274 		 *	!hmeblkp->hblk_lckcnt);
7275 		 */
7276 	} else {
7277 		panic("invalid tte? pp %p &tte %p",
7278 		    (void *)pp, (void *)&tte);
7279 	}
7280 
7281 	return (cpuset);
7282 }
7283 
7284 /*
7285  * While relocating a kernel page, this function will move the mappings
7286  * from tpp to dpp and modify any associated data with these mappings.
7287  * It also unsuspends the suspended kernel mapping.
7288  */
7289 static void
7290 hat_pagereload(struct page *tpp, struct page *dpp)
7291 {
7292 	struct sf_hment *sfhme;
7293 	tte_t tte, ttemod;
7294 	int index, cons;
7295 
7296 	ASSERT(getpil() == PIL_MAX);
7297 	ASSERT(sfmmu_mlist_held(tpp));
7298 	ASSERT(sfmmu_mlist_held(dpp));
7299 
7300 	index = PP_MAPINDEX(tpp);
7301 	cons = TTE8K;
7302 
7303 	/* Update real mappings to the page */
7304 retry:
7305 	for (sfhme = tpp->p_mapping; sfhme != NULL; sfhme = sfhme->hme_next) {
7306 		if (IS_PAHME(sfhme))
7307 			continue;
7308 		sfmmu_copytte(&sfhme->hme_tte, &tte);
7309 		ttemod = tte;
7310 
7311 		/*
7312 		 * replace old pfn with new pfn in TTE
7313 		 */
7314 		PFN_TO_TTE(ttemod, dpp->p_pagenum);
7315 
7316 		/*
7317 		 * clear suspend bit
7318 		 */
7319 		ASSERT(TTE_IS_SUSPEND(&ttemod));
7320 		TTE_CLR_SUSPEND(&ttemod);
7321 
7322 		if (sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte) < 0)
7323 			panic("hat_pagereload(): sfmmu_modifytte_try() failed");
7324 
7325 		/*
7326 		 * set hme_page point to new page
7327 		 */
7328 		sfhme->hme_page = dpp;
7329 	}
7330 
7331 	/*
7332 	 * move p_mapping list from old page to new page
7333 	 */
7334 	dpp->p_mapping = tpp->p_mapping;
7335 	tpp->p_mapping = NULL;
7336 	dpp->p_share = tpp->p_share;
7337 	tpp->p_share = 0;
7338 
7339 	while (index != 0) {
7340 		index = index >> 1;
7341 		if (index != 0)
7342 			cons++;
7343 		if (index & 0x1) {
7344 			tpp = PP_GROUPLEADER(tpp, cons);
7345 			dpp = PP_GROUPLEADER(dpp, cons);
7346 			goto retry;
7347 		}
7348 	}
7349 
7350 	curthread->t_flag &= ~T_DONTDTRACE;
7351 	mutex_exit(&kpr_suspendlock);
7352 }
7353 
7354 uint_t
7355 hat_pagesync(struct page *pp, uint_t clearflag)
7356 {
7357 	struct sf_hment *sfhme, *tmphme = NULL;
7358 	struct hme_blk *hmeblkp;
7359 	kmutex_t *pml;
7360 	cpuset_t cpuset, tset;
7361 	int	index, cons;
7362 	extern	ulong_t po_share;
7363 	page_t	*save_pp = pp;
7364 	int	stop_on_sh = 0;
7365 	uint_t	shcnt;
7366 
7367 	CPUSET_ZERO(cpuset);
7368 
7369 	if (PP_ISRO(pp) && (clearflag & HAT_SYNC_STOPON_MOD)) {
7370 		return (PP_GENERIC_ATTR(pp));
7371 	}
7372 
7373 	if ((clearflag & HAT_SYNC_ZERORM) == 0) {
7374 		if ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(pp)) {
7375 			return (PP_GENERIC_ATTR(pp));
7376 		}
7377 		if ((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(pp)) {
7378 			return (PP_GENERIC_ATTR(pp));
7379 		}
7380 		if (clearflag & HAT_SYNC_STOPON_SHARED) {
7381 			if (pp->p_share > po_share) {
7382 				hat_page_setattr(pp, P_REF);
7383 				return (PP_GENERIC_ATTR(pp));
7384 			}
7385 			stop_on_sh = 1;
7386 			shcnt = 0;
7387 		}
7388 	}
7389 
7390 	clearflag &= ~HAT_SYNC_STOPON_SHARED;
7391 	pml = sfmmu_mlist_enter(pp);
7392 	index = PP_MAPINDEX(pp);
7393 	cons = TTE8K;
7394 retry:
7395 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7396 		/*
7397 		 * We need to save the next hment on the list since
7398 		 * it is possible for pagesync to remove an invalid hment
7399 		 * from the list.
7400 		 */
7401 		tmphme = sfhme->hme_next;
7402 		if (IS_PAHME(sfhme))
7403 			continue;
7404 		/*
7405 		 * If we are looking for large mappings and this hme doesn't
7406 		 * reach the range we are seeking, just ignore it.
7407 		 */
7408 		hmeblkp = sfmmu_hmetohblk(sfhme);
7409 		if (hmeblkp->hblk_xhat_bit)
7410 			continue;
7411 
7412 		if (hme_size(sfhme) < cons)
7413 			continue;
7414 
7415 		if (stop_on_sh) {
7416 			if (hmeblkp->hblk_shared) {
7417 				sf_srd_t *srdp = hblktosrd(hmeblkp);
7418 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7419 				sf_region_t *rgnp;
7420 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7421 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7422 				ASSERT(srdp != NULL);
7423 				rgnp = srdp->srd_hmergnp[rid];
7424 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
7425 				    rgnp, rid);
7426 				shcnt += rgnp->rgn_refcnt;
7427 			} else {
7428 				shcnt++;
7429 			}
7430 			if (shcnt > po_share) {
7431 				/*
7432 				 * tell the pager to spare the page this time
7433 				 * around.
7434 				 */
7435 				hat_page_setattr(save_pp, P_REF);
7436 				index = 0;
7437 				break;
7438 			}
7439 		}
7440 		tset = sfmmu_pagesync(pp, sfhme,
7441 		    clearflag & ~HAT_SYNC_STOPON_RM);
7442 		CPUSET_OR(cpuset, tset);
7443 
7444 		/*
7445 		 * If clearflag is HAT_SYNC_DONTZERO, break out as soon
7446 		 * as the "ref" or "mod" is set or share cnt exceeds po_share.
7447 		 */
7448 		if ((clearflag & ~HAT_SYNC_STOPON_RM) == HAT_SYNC_DONTZERO &&
7449 		    (((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(save_pp)) ||
7450 		    ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(save_pp)))) {
7451 			index = 0;
7452 			break;
7453 		}
7454 	}
7455 
7456 	while (index) {
7457 		index = index >> 1;
7458 		cons++;
7459 		if (index & 0x1) {
7460 			/* Go to leading page */
7461 			pp = PP_GROUPLEADER(pp, cons);
7462 			goto retry;
7463 		}
7464 	}
7465 
7466 	xt_sync(cpuset);
7467 	sfmmu_mlist_exit(pml);
7468 	return (PP_GENERIC_ATTR(save_pp));
7469 }
7470 
7471 /*
7472  * Get all the hardware dependent attributes for a page struct
7473  */
7474 static cpuset_t
7475 sfmmu_pagesync(struct page *pp, struct sf_hment *sfhme,
7476 	uint_t clearflag)
7477 {
7478 	caddr_t addr;
7479 	tte_t tte, ttemod;
7480 	struct hme_blk *hmeblkp;
7481 	int ret;
7482 	sfmmu_t *sfmmup;
7483 	cpuset_t cpuset;
7484 
7485 	ASSERT(pp != NULL);
7486 	ASSERT(sfmmu_mlist_held(pp));
7487 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
7488 	    (clearflag == HAT_SYNC_ZERORM));
7489 
7490 	SFMMU_STAT(sf_pagesync);
7491 
7492 	CPUSET_ZERO(cpuset);
7493 
7494 sfmmu_pagesync_retry:
7495 
7496 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7497 	if (TTE_IS_VALID(&tte)) {
7498 		hmeblkp = sfmmu_hmetohblk(sfhme);
7499 		sfmmup = hblktosfmmu(hmeblkp);
7500 		addr = tte_to_vaddr(hmeblkp, tte);
7501 		if (clearflag == HAT_SYNC_ZERORM) {
7502 			ttemod = tte;
7503 			TTE_CLR_RM(&ttemod);
7504 			ret = sfmmu_modifytte_try(&tte, &ttemod,
7505 			    &sfhme->hme_tte);
7506 			if (ret < 0) {
7507 				/*
7508 				 * cas failed and the new value is not what
7509 				 * we want.
7510 				 */
7511 				goto sfmmu_pagesync_retry;
7512 			}
7513 
7514 			if (ret > 0) {
7515 				/* we win the cas */
7516 				if (hmeblkp->hblk_shared) {
7517 					sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7518 					uint_t rid =
7519 					    hmeblkp->hblk_tag.htag_rid;
7520 					sf_region_t *rgnp;
7521 					ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7522 					ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7523 					ASSERT(srdp != NULL);
7524 					rgnp = srdp->srd_hmergnp[rid];
7525 					SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7526 					    srdp, rgnp, rid);
7527 					cpuset = sfmmu_rgntlb_demap(addr,
7528 					    rgnp, hmeblkp, 1);
7529 				} else {
7530 					sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
7531 					    0, 0);
7532 					cpuset = sfmmup->sfmmu_cpusran;
7533 				}
7534 			}
7535 		}
7536 		sfmmu_ttesync(hmeblkp->hblk_shared ? NULL : sfmmup, addr,
7537 		    &tte, pp);
7538 	}
7539 	return (cpuset);
7540 }
7541 
7542 /*
7543  * Remove write permission from a mappings to a page, so that
7544  * we can detect the next modification of it. This requires modifying
7545  * the TTE then invalidating (demap) any TLB entry using that TTE.
7546  * This code is similar to sfmmu_pagesync().
7547  */
7548 static cpuset_t
7549 sfmmu_pageclrwrt(struct page *pp, struct sf_hment *sfhme)
7550 {
7551 	caddr_t addr;
7552 	tte_t tte;
7553 	tte_t ttemod;
7554 	struct hme_blk *hmeblkp;
7555 	int ret;
7556 	sfmmu_t *sfmmup;
7557 	cpuset_t cpuset;
7558 
7559 	ASSERT(pp != NULL);
7560 	ASSERT(sfmmu_mlist_held(pp));
7561 
7562 	CPUSET_ZERO(cpuset);
7563 	SFMMU_STAT(sf_clrwrt);
7564 
7565 retry:
7566 
7567 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7568 	if (TTE_IS_VALID(&tte) && TTE_IS_WRITABLE(&tte)) {
7569 		hmeblkp = sfmmu_hmetohblk(sfhme);
7570 
7571 		/*
7572 		 * xhat mappings should never be to a VMODSORT page.
7573 		 */
7574 		ASSERT(hmeblkp->hblk_xhat_bit == 0);
7575 
7576 		sfmmup = hblktosfmmu(hmeblkp);
7577 		addr = tte_to_vaddr(hmeblkp, tte);
7578 
7579 		ttemod = tte;
7580 		TTE_CLR_WRT(&ttemod);
7581 		TTE_CLR_MOD(&ttemod);
7582 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7583 
7584 		/*
7585 		 * if cas failed and the new value is not what
7586 		 * we want retry
7587 		 */
7588 		if (ret < 0)
7589 			goto retry;
7590 
7591 		/* we win the cas */
7592 		if (ret > 0) {
7593 			if (hmeblkp->hblk_shared) {
7594 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7595 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7596 				sf_region_t *rgnp;
7597 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7598 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7599 				ASSERT(srdp != NULL);
7600 				rgnp = srdp->srd_hmergnp[rid];
7601 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7602 				    srdp, rgnp, rid);
7603 				cpuset = sfmmu_rgntlb_demap(addr,
7604 				    rgnp, hmeblkp, 1);
7605 			} else {
7606 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7607 				cpuset = sfmmup->sfmmu_cpusran;
7608 			}
7609 		}
7610 	}
7611 
7612 	return (cpuset);
7613 }
7614 
7615 /*
7616  * Walk all mappings of a page, removing write permission and clearing the
7617  * ref/mod bits. This code is similar to hat_pagesync()
7618  */
7619 static void
7620 hat_page_clrwrt(page_t *pp)
7621 {
7622 	struct sf_hment *sfhme;
7623 	struct sf_hment *tmphme = NULL;
7624 	kmutex_t *pml;
7625 	cpuset_t cpuset;
7626 	cpuset_t tset;
7627 	int	index;
7628 	int	 cons;
7629 
7630 	CPUSET_ZERO(cpuset);
7631 
7632 	pml = sfmmu_mlist_enter(pp);
7633 	index = PP_MAPINDEX(pp);
7634 	cons = TTE8K;
7635 retry:
7636 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7637 		tmphme = sfhme->hme_next;
7638 
7639 		/*
7640 		 * If we are looking for large mappings and this hme doesn't
7641 		 * reach the range we are seeking, just ignore its.
7642 		 */
7643 
7644 		if (hme_size(sfhme) < cons)
7645 			continue;
7646 
7647 		tset = sfmmu_pageclrwrt(pp, sfhme);
7648 		CPUSET_OR(cpuset, tset);
7649 	}
7650 
7651 	while (index) {
7652 		index = index >> 1;
7653 		cons++;
7654 		if (index & 0x1) {
7655 			/* Go to leading page */
7656 			pp = PP_GROUPLEADER(pp, cons);
7657 			goto retry;
7658 		}
7659 	}
7660 
7661 	xt_sync(cpuset);
7662 	sfmmu_mlist_exit(pml);
7663 }
7664 
7665 /*
7666  * Set the given REF/MOD/RO bits for the given page.
7667  * For a vnode with a sorted v_pages list, we need to change
7668  * the attributes and the v_pages list together under page_vnode_mutex.
7669  */
7670 void
7671 hat_page_setattr(page_t *pp, uint_t flag)
7672 {
7673 	vnode_t		*vp = pp->p_vnode;
7674 	page_t		**listp;
7675 	kmutex_t	*pmtx;
7676 	kmutex_t	*vphm = NULL;
7677 	int		noshuffle;
7678 
7679 	noshuffle = flag & P_NSH;
7680 	flag &= ~P_NSH;
7681 
7682 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7683 
7684 	/*
7685 	 * nothing to do if attribute already set
7686 	 */
7687 	if ((pp->p_nrm & flag) == flag)
7688 		return;
7689 
7690 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp) &&
7691 	    !noshuffle) {
7692 		vphm = page_vnode_mutex(vp);
7693 		mutex_enter(vphm);
7694 	}
7695 
7696 	pmtx = sfmmu_page_enter(pp);
7697 	pp->p_nrm |= flag;
7698 	sfmmu_page_exit(pmtx);
7699 
7700 	if (vphm != NULL) {
7701 		/*
7702 		 * Some File Systems examine v_pages for NULL w/o
7703 		 * grabbing the vphm mutex. Must not let it become NULL when
7704 		 * pp is the only page on the list.
7705 		 */
7706 		if (pp->p_vpnext != pp) {
7707 			page_vpsub(&vp->v_pages, pp);
7708 			if (vp->v_pages != NULL)
7709 				listp = &vp->v_pages->p_vpprev->p_vpnext;
7710 			else
7711 				listp = &vp->v_pages;
7712 			page_vpadd(listp, pp);
7713 		}
7714 		mutex_exit(vphm);
7715 	}
7716 }
7717 
7718 void
7719 hat_page_clrattr(page_t *pp, uint_t flag)
7720 {
7721 	vnode_t		*vp = pp->p_vnode;
7722 	kmutex_t	*pmtx;
7723 
7724 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7725 
7726 	pmtx = sfmmu_page_enter(pp);
7727 
7728 	/*
7729 	 * Caller is expected to hold page's io lock for VMODSORT to work
7730 	 * correctly with pvn_vplist_dirty() and pvn_getdirty() when mod
7731 	 * bit is cleared.
7732 	 * We don't have assert to avoid tripping some existing third party
7733 	 * code. The dirty page is moved back to top of the v_page list
7734 	 * after IO is done in pvn_write_done().
7735 	 */
7736 	pp->p_nrm &= ~flag;
7737 	sfmmu_page_exit(pmtx);
7738 
7739 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
7740 
7741 		/*
7742 		 * VMODSORT works by removing write permissions and getting
7743 		 * a fault when a page is made dirty. At this point
7744 		 * we need to remove write permission from all mappings
7745 		 * to this page.
7746 		 */
7747 		hat_page_clrwrt(pp);
7748 	}
7749 }
7750 
7751 uint_t
7752 hat_page_getattr(page_t *pp, uint_t flag)
7753 {
7754 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7755 	return ((uint_t)(pp->p_nrm & flag));
7756 }
7757 
7758 /*
7759  * DEBUG kernels: verify that a kernel va<->pa translation
7760  * is safe by checking the underlying page_t is in a page
7761  * relocation-safe state.
7762  */
7763 #ifdef	DEBUG
7764 void
7765 sfmmu_check_kpfn(pfn_t pfn)
7766 {
7767 	page_t *pp;
7768 	int index, cons;
7769 
7770 	if (hat_check_vtop == 0)
7771 		return;
7772 
7773 	if (hat_kpr_enabled == 0 || kvseg.s_base == NULL || panicstr)
7774 		return;
7775 
7776 	pp = page_numtopp_nolock(pfn);
7777 	if (!pp)
7778 		return;
7779 
7780 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7781 		return;
7782 
7783 	/*
7784 	 * Handed a large kernel page, we dig up the root page since we
7785 	 * know the root page might have the lock also.
7786 	 */
7787 	if (pp->p_szc != 0) {
7788 		index = PP_MAPINDEX(pp);
7789 		cons = TTE8K;
7790 again:
7791 		while (index != 0) {
7792 			index >>= 1;
7793 			if (index != 0)
7794 				cons++;
7795 			if (index & 0x1) {
7796 				pp = PP_GROUPLEADER(pp, cons);
7797 				goto again;
7798 			}
7799 		}
7800 	}
7801 
7802 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7803 		return;
7804 
7805 	/*
7806 	 * Pages need to be locked or allocated "permanent" (either from
7807 	 * static_arena arena or explicitly setting PG_NORELOC when calling
7808 	 * page_create_va()) for VA->PA translations to be valid.
7809 	 */
7810 	if (!PP_ISNORELOC(pp))
7811 		panic("Illegal VA->PA translation, pp 0x%p not permanent",
7812 		    (void *)pp);
7813 	else
7814 		panic("Illegal VA->PA translation, pp 0x%p not locked",
7815 		    (void *)pp);
7816 }
7817 #endif	/* DEBUG */
7818 
7819 /*
7820  * Returns a page frame number for a given virtual address.
7821  * Returns PFN_INVALID to indicate an invalid mapping
7822  */
7823 pfn_t
7824 hat_getpfnum(struct hat *hat, caddr_t addr)
7825 {
7826 	pfn_t pfn;
7827 	tte_t tte;
7828 
7829 	/*
7830 	 * We would like to
7831 	 * ASSERT(AS_LOCK_HELD(as, &as->a_lock));
7832 	 * but we can't because the iommu driver will call this
7833 	 * routine at interrupt time and it can't grab the as lock
7834 	 * or it will deadlock: A thread could have the as lock
7835 	 * and be waiting for io.  The io can't complete
7836 	 * because the interrupt thread is blocked trying to grab
7837 	 * the as lock.
7838 	 */
7839 
7840 	ASSERT(hat->sfmmu_xhat_provider == NULL);
7841 
7842 	if (hat == ksfmmup) {
7843 		if (IS_KMEM_VA_LARGEPAGE(addr)) {
7844 			ASSERT(segkmem_lpszc > 0);
7845 			pfn = sfmmu_kvaszc2pfn(addr, segkmem_lpszc);
7846 			if (pfn != PFN_INVALID) {
7847 				sfmmu_check_kpfn(pfn);
7848 				return (pfn);
7849 			}
7850 		} else if (segkpm && IS_KPM_ADDR(addr)) {
7851 			return (sfmmu_kpm_vatopfn(addr));
7852 		}
7853 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7854 		    == PFN_SUSPENDED) {
7855 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7856 		}
7857 		sfmmu_check_kpfn(pfn);
7858 		return (pfn);
7859 	} else {
7860 		return (sfmmu_uvatopfn(addr, hat, NULL));
7861 	}
7862 }
7863 
7864 /*
7865  * hat_getkpfnum() is an obsolete DDI routine, and its use is discouraged.
7866  * Use hat_getpfnum(kas.a_hat, ...) instead.
7867  *
7868  * We'd like to return PFN_INVALID if the mappings have underlying page_t's
7869  * but can't right now due to the fact that some software has grown to use
7870  * this interface incorrectly. So for now when the interface is misused,
7871  * return a warning to the user that in the future it won't work in the
7872  * way they're abusing it, and carry on (after disabling page relocation).
7873  */
7874 pfn_t
7875 hat_getkpfnum(caddr_t addr)
7876 {
7877 	pfn_t pfn;
7878 	tte_t tte;
7879 	int badcaller = 0;
7880 	extern int segkmem_reloc;
7881 
7882 	if (segkpm && IS_KPM_ADDR(addr)) {
7883 		badcaller = 1;
7884 		pfn = sfmmu_kpm_vatopfn(addr);
7885 	} else {
7886 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7887 		    == PFN_SUSPENDED) {
7888 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7889 		}
7890 		badcaller = pf_is_memory(pfn);
7891 	}
7892 
7893 	if (badcaller) {
7894 		/*
7895 		 * We can't return PFN_INVALID or the caller may panic
7896 		 * or corrupt the system.  The only alternative is to
7897 		 * disable page relocation at this point for all kernel
7898 		 * memory.  This will impact any callers of page_relocate()
7899 		 * such as FMA or DR.
7900 		 *
7901 		 * RFE: Add junk here to spit out an ereport so the sysadmin
7902 		 * can be advised that he should upgrade his device driver
7903 		 * so that this doesn't happen.
7904 		 */
7905 		hat_getkpfnum_badcall(caller());
7906 		if (hat_kpr_enabled && segkmem_reloc) {
7907 			hat_kpr_enabled = 0;
7908 			segkmem_reloc = 0;
7909 			cmn_err(CE_WARN, "Kernel Page Relocation is DISABLED");
7910 		}
7911 	}
7912 	return (pfn);
7913 }
7914 
7915 /*
7916  * This routine will return both pfn and tte for the vaddr.
7917  */
7918 static pfn_t
7919 sfmmu_uvatopfn(caddr_t vaddr, struct hat *sfmmup, tte_t *ttep)
7920 {
7921 	struct hmehash_bucket *hmebp;
7922 	hmeblk_tag hblktag;
7923 	int hmeshift, hashno = 1;
7924 	struct hme_blk *hmeblkp = NULL;
7925 	tte_t tte;
7926 
7927 	struct sf_hment *sfhmep;
7928 	pfn_t pfn;
7929 
7930 	/* support for ISM */
7931 	ism_map_t	*ism_map;
7932 	ism_blk_t	*ism_blkp;
7933 	int		i;
7934 	sfmmu_t *ism_hatid = NULL;
7935 	sfmmu_t *locked_hatid = NULL;
7936 	sfmmu_t	*sv_sfmmup = sfmmup;
7937 	caddr_t	sv_vaddr = vaddr;
7938 	sf_srd_t *srdp;
7939 
7940 	if (ttep == NULL) {
7941 		ttep = &tte;
7942 	} else {
7943 		ttep->ll = 0;
7944 	}
7945 
7946 	ASSERT(sfmmup != ksfmmup);
7947 	SFMMU_STAT(sf_user_vtop);
7948 	/*
7949 	 * Set ism_hatid if vaddr falls in a ISM segment.
7950 	 */
7951 	ism_blkp = sfmmup->sfmmu_iblk;
7952 	if (ism_blkp != NULL) {
7953 		sfmmu_ismhat_enter(sfmmup, 0);
7954 		locked_hatid = sfmmup;
7955 	}
7956 	while (ism_blkp != NULL && ism_hatid == NULL) {
7957 		ism_map = ism_blkp->iblk_maps;
7958 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
7959 			if (vaddr >= ism_start(ism_map[i]) &&
7960 			    vaddr < ism_end(ism_map[i])) {
7961 				sfmmup = ism_hatid = ism_map[i].imap_ismhat;
7962 				vaddr = (caddr_t)(vaddr -
7963 				    ism_start(ism_map[i]));
7964 				break;
7965 			}
7966 		}
7967 		ism_blkp = ism_blkp->iblk_next;
7968 	}
7969 	if (locked_hatid) {
7970 		sfmmu_ismhat_exit(locked_hatid, 0);
7971 	}
7972 
7973 	hblktag.htag_id = sfmmup;
7974 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
7975 	do {
7976 		hmeshift = HME_HASH_SHIFT(hashno);
7977 		hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
7978 		hblktag.htag_rehash = hashno;
7979 		hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
7980 
7981 		SFMMU_HASH_LOCK(hmebp);
7982 
7983 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
7984 		if (hmeblkp != NULL) {
7985 			ASSERT(!hmeblkp->hblk_shared);
7986 			HBLKTOHME(sfhmep, hmeblkp, vaddr);
7987 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
7988 			SFMMU_HASH_UNLOCK(hmebp);
7989 			if (TTE_IS_VALID(ttep)) {
7990 				pfn = TTE_TO_PFN(vaddr, ttep);
7991 				return (pfn);
7992 			}
7993 			break;
7994 		}
7995 		SFMMU_HASH_UNLOCK(hmebp);
7996 		hashno++;
7997 	} while (HME_REHASH(sfmmup) && (hashno <= mmu_hashcnt));
7998 
7999 	if (SF_HMERGNMAP_ISNULL(sv_sfmmup)) {
8000 		return (PFN_INVALID);
8001 	}
8002 	srdp = sv_sfmmup->sfmmu_srdp;
8003 	ASSERT(srdp != NULL);
8004 	ASSERT(srdp->srd_refcnt != 0);
8005 	hblktag.htag_id = srdp;
8006 	hashno = 1;
8007 	do {
8008 		hmeshift = HME_HASH_SHIFT(hashno);
8009 		hblktag.htag_bspage = HME_HASH_BSPAGE(sv_vaddr, hmeshift);
8010 		hblktag.htag_rehash = hashno;
8011 		hmebp = HME_HASH_FUNCTION(srdp, sv_vaddr, hmeshift);
8012 
8013 		SFMMU_HASH_LOCK(hmebp);
8014 		for (hmeblkp = hmebp->hmeblkp; hmeblkp != NULL;
8015 		    hmeblkp = hmeblkp->hblk_next) {
8016 			uint_t rid;
8017 			sf_region_t *rgnp;
8018 			caddr_t rsaddr;
8019 			caddr_t readdr;
8020 
8021 			if (!HTAGS_EQ_SHME(hmeblkp->hblk_tag, hblktag,
8022 			    sv_sfmmup->sfmmu_hmeregion_map)) {
8023 				continue;
8024 			}
8025 			ASSERT(hmeblkp->hblk_shared);
8026 			rid = hmeblkp->hblk_tag.htag_rid;
8027 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8028 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8029 			rgnp = srdp->srd_hmergnp[rid];
8030 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
8031 			HBLKTOHME(sfhmep, hmeblkp, sv_vaddr);
8032 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
8033 			rsaddr = rgnp->rgn_saddr;
8034 			readdr = rsaddr + rgnp->rgn_size;
8035 #ifdef DEBUG
8036 			if (TTE_IS_VALID(ttep) ||
8037 			    get_hblk_ttesz(hmeblkp) > TTE8K) {
8038 				caddr_t eva = tte_to_evaddr(hmeblkp, ttep);
8039 				ASSERT(eva > sv_vaddr);
8040 				ASSERT(sv_vaddr >= rsaddr);
8041 				ASSERT(sv_vaddr < readdr);
8042 				ASSERT(eva <= readdr);
8043 			}
8044 #endif /* DEBUG */
8045 			/*
8046 			 * Continue the search if we
8047 			 * found an invalid 8K tte outside of the area
8048 			 * covered by this hmeblk's region.
8049 			 */
8050 			if (TTE_IS_VALID(ttep)) {
8051 				SFMMU_HASH_UNLOCK(hmebp);
8052 				pfn = TTE_TO_PFN(sv_vaddr, ttep);
8053 				return (pfn);
8054 			} else if (get_hblk_ttesz(hmeblkp) > TTE8K ||
8055 			    (sv_vaddr >= rsaddr && sv_vaddr < readdr)) {
8056 				SFMMU_HASH_UNLOCK(hmebp);
8057 				pfn = PFN_INVALID;
8058 				return (pfn);
8059 			}
8060 		}
8061 		SFMMU_HASH_UNLOCK(hmebp);
8062 		hashno++;
8063 	} while (hashno <= mmu_hashcnt);
8064 	return (PFN_INVALID);
8065 }
8066 
8067 
8068 /*
8069  * For compatability with AT&T and later optimizations
8070  */
8071 /* ARGSUSED */
8072 void
8073 hat_map(struct hat *hat, caddr_t addr, size_t len, uint_t flags)
8074 {
8075 	ASSERT(hat != NULL);
8076 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8077 }
8078 
8079 /*
8080  * Return the number of mappings to a particular page.  This number is an
8081  * approximation of the number of people sharing the page.
8082  *
8083  * shared hmeblks or ism hmeblks are counted as 1 mapping here.
8084  * hat_page_checkshare() can be used to compare threshold to share
8085  * count that reflects the number of region sharers albeit at higher cost.
8086  */
8087 ulong_t
8088 hat_page_getshare(page_t *pp)
8089 {
8090 	page_t *spp = pp;	/* start page */
8091 	kmutex_t *pml;
8092 	ulong_t	cnt;
8093 	int index, sz = TTE64K;
8094 
8095 	/*
8096 	 * We need to grab the mlist lock to make sure any outstanding
8097 	 * load/unloads complete.  Otherwise we could return zero
8098 	 * even though the unload(s) hasn't finished yet.
8099 	 */
8100 	pml = sfmmu_mlist_enter(spp);
8101 	cnt = spp->p_share;
8102 
8103 #ifdef VAC
8104 	if (kpm_enable)
8105 		cnt += spp->p_kpmref;
8106 #endif
8107 	if (vpm_enable && pp->p_vpmref) {
8108 		cnt += 1;
8109 	}
8110 
8111 	/*
8112 	 * If we have any large mappings, we count the number of
8113 	 * mappings that this large page is part of.
8114 	 */
8115 	index = PP_MAPINDEX(spp);
8116 	index >>= 1;
8117 	while (index) {
8118 		pp = PP_GROUPLEADER(spp, sz);
8119 		if ((index & 0x1) && pp != spp) {
8120 			cnt += pp->p_share;
8121 			spp = pp;
8122 		}
8123 		index >>= 1;
8124 		sz++;
8125 	}
8126 	sfmmu_mlist_exit(pml);
8127 	return (cnt);
8128 }
8129 
8130 /*
8131  * Return 1 if the number of mappings exceeds sh_thresh. Return 0
8132  * otherwise. Count shared hmeblks by region's refcnt.
8133  */
8134 int
8135 hat_page_checkshare(page_t *pp, ulong_t sh_thresh)
8136 {
8137 	kmutex_t *pml;
8138 	ulong_t	cnt = 0;
8139 	int index, sz = TTE8K;
8140 	struct sf_hment *sfhme, *tmphme = NULL;
8141 	struct hme_blk *hmeblkp;
8142 
8143 	pml = sfmmu_mlist_enter(pp);
8144 
8145 #ifdef VAC
8146 	if (kpm_enable)
8147 		cnt = pp->p_kpmref;
8148 #endif
8149 
8150 	if (vpm_enable && pp->p_vpmref) {
8151 		cnt += 1;
8152 	}
8153 
8154 	if (pp->p_share + cnt > sh_thresh) {
8155 		sfmmu_mlist_exit(pml);
8156 		return (1);
8157 	}
8158 
8159 	index = PP_MAPINDEX(pp);
8160 
8161 again:
8162 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
8163 		tmphme = sfhme->hme_next;
8164 		if (IS_PAHME(sfhme)) {
8165 			continue;
8166 		}
8167 
8168 		hmeblkp = sfmmu_hmetohblk(sfhme);
8169 		if (hmeblkp->hblk_xhat_bit) {
8170 			cnt++;
8171 			if (cnt > sh_thresh) {
8172 				sfmmu_mlist_exit(pml);
8173 				return (1);
8174 			}
8175 			continue;
8176 		}
8177 		if (hme_size(sfhme) != sz) {
8178 			continue;
8179 		}
8180 
8181 		if (hmeblkp->hblk_shared) {
8182 			sf_srd_t *srdp = hblktosrd(hmeblkp);
8183 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
8184 			sf_region_t *rgnp;
8185 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8186 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8187 			ASSERT(srdp != NULL);
8188 			rgnp = srdp->srd_hmergnp[rid];
8189 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
8190 			    rgnp, rid);
8191 			cnt += rgnp->rgn_refcnt;
8192 		} else {
8193 			cnt++;
8194 		}
8195 		if (cnt > sh_thresh) {
8196 			sfmmu_mlist_exit(pml);
8197 			return (1);
8198 		}
8199 	}
8200 
8201 	index >>= 1;
8202 	sz++;
8203 	while (index) {
8204 		pp = PP_GROUPLEADER(pp, sz);
8205 		ASSERT(sfmmu_mlist_held(pp));
8206 		if (index & 0x1) {
8207 			goto again;
8208 		}
8209 		index >>= 1;
8210 		sz++;
8211 	}
8212 	sfmmu_mlist_exit(pml);
8213 	return (0);
8214 }
8215 
8216 /*
8217  * Unload all large mappings to the pp and reset the p_szc field of every
8218  * constituent page according to the remaining mappings.
8219  *
8220  * pp must be locked SE_EXCL. Even though no other constituent pages are
8221  * locked it's legal to unload the large mappings to the pp because all
8222  * constituent pages of large locked mappings have to be locked SE_SHARED.
8223  * This means if we have SE_EXCL lock on one of constituent pages none of the
8224  * large mappings to pp are locked.
8225  *
8226  * Decrease p_szc field starting from the last constituent page and ending
8227  * with the root page. This method is used because other threads rely on the
8228  * root's p_szc to find the lock to syncronize on. After a root page_t's p_szc
8229  * is demoted then other threads will succeed in sfmmu_mlspl_enter(). This
8230  * ensures that p_szc changes of the constituent pages appears atomic for all
8231  * threads that use sfmmu_mlspl_enter() to examine p_szc field.
8232  *
8233  * This mechanism is only used for file system pages where it's not always
8234  * possible to get SE_EXCL locks on all constituent pages to demote the size
8235  * code (as is done for anonymous or kernel large pages).
8236  *
8237  * See more comments in front of sfmmu_mlspl_enter().
8238  */
8239 void
8240 hat_page_demote(page_t *pp)
8241 {
8242 	int index;
8243 	int sz;
8244 	cpuset_t cpuset;
8245 	int sync = 0;
8246 	page_t *rootpp;
8247 	struct sf_hment *sfhme;
8248 	struct sf_hment *tmphme = NULL;
8249 	struct hme_blk *hmeblkp;
8250 	uint_t pszc;
8251 	page_t *lastpp;
8252 	cpuset_t tset;
8253 	pgcnt_t npgs;
8254 	kmutex_t *pml;
8255 	kmutex_t *pmtx = NULL;
8256 
8257 	ASSERT(PAGE_EXCL(pp));
8258 	ASSERT(!PP_ISFREE(pp));
8259 	ASSERT(!PP_ISKAS(pp));
8260 	ASSERT(page_szc_lock_assert(pp));
8261 	pml = sfmmu_mlist_enter(pp);
8262 
8263 	pszc = pp->p_szc;
8264 	if (pszc == 0) {
8265 		goto out;
8266 	}
8267 
8268 	index = PP_MAPINDEX(pp) >> 1;
8269 
8270 	if (index) {
8271 		CPUSET_ZERO(cpuset);
8272 		sz = TTE64K;
8273 		sync = 1;
8274 	}
8275 
8276 	while (index) {
8277 		if (!(index & 0x1)) {
8278 			index >>= 1;
8279 			sz++;
8280 			continue;
8281 		}
8282 		ASSERT(sz <= pszc);
8283 		rootpp = PP_GROUPLEADER(pp, sz);
8284 		for (sfhme = rootpp->p_mapping; sfhme; sfhme = tmphme) {
8285 			tmphme = sfhme->hme_next;
8286 			ASSERT(!IS_PAHME(sfhme));
8287 			hmeblkp = sfmmu_hmetohblk(sfhme);
8288 			if (hme_size(sfhme) != sz) {
8289 				continue;
8290 			}
8291 			if (hmeblkp->hblk_xhat_bit) {
8292 				cmn_err(CE_PANIC,
8293 				    "hat_page_demote: xhat hmeblk");
8294 			}
8295 			tset = sfmmu_pageunload(rootpp, sfhme, sz);
8296 			CPUSET_OR(cpuset, tset);
8297 		}
8298 		if (index >>= 1) {
8299 			sz++;
8300 		}
8301 	}
8302 
8303 	ASSERT(!PP_ISMAPPED_LARGE(pp));
8304 
8305 	if (sync) {
8306 		xt_sync(cpuset);
8307 #ifdef VAC
8308 		if (PP_ISTNC(pp)) {
8309 			conv_tnc(rootpp, sz);
8310 		}
8311 #endif	/* VAC */
8312 	}
8313 
8314 	pmtx = sfmmu_page_enter(pp);
8315 
8316 	ASSERT(pp->p_szc == pszc);
8317 	rootpp = PP_PAGEROOT(pp);
8318 	ASSERT(rootpp->p_szc == pszc);
8319 	lastpp = PP_PAGENEXT_N(rootpp, TTEPAGES(pszc) - 1);
8320 
8321 	while (lastpp != rootpp) {
8322 		sz = PP_MAPINDEX(lastpp) ? fnd_mapping_sz(lastpp) : 0;
8323 		ASSERT(sz < pszc);
8324 		npgs = (sz == 0) ? 1 : TTEPAGES(sz);
8325 		ASSERT(P2PHASE(lastpp->p_pagenum, npgs) == npgs - 1);
8326 		while (--npgs > 0) {
8327 			lastpp->p_szc = (uchar_t)sz;
8328 			lastpp = PP_PAGEPREV(lastpp);
8329 		}
8330 		if (sz) {
8331 			/*
8332 			 * make sure before current root's pszc
8333 			 * is updated all updates to constituent pages pszc
8334 			 * fields are globally visible.
8335 			 */
8336 			membar_producer();
8337 		}
8338 		lastpp->p_szc = sz;
8339 		ASSERT(IS_P2ALIGNED(lastpp->p_pagenum, TTEPAGES(sz)));
8340 		if (lastpp != rootpp) {
8341 			lastpp = PP_PAGEPREV(lastpp);
8342 		}
8343 	}
8344 	if (sz == 0) {
8345 		/* the loop above doesn't cover this case */
8346 		rootpp->p_szc = 0;
8347 	}
8348 out:
8349 	ASSERT(pp->p_szc == 0);
8350 	if (pmtx != NULL) {
8351 		sfmmu_page_exit(pmtx);
8352 	}
8353 	sfmmu_mlist_exit(pml);
8354 }
8355 
8356 /*
8357  * Refresh the HAT ismttecnt[] element for size szc.
8358  * Caller must have set ISM busy flag to prevent mapping
8359  * lists from changing while we're traversing them.
8360  */
8361 pgcnt_t
8362 ism_tsb_entries(sfmmu_t *sfmmup, int szc)
8363 {
8364 	ism_blk_t	*ism_blkp = sfmmup->sfmmu_iblk;
8365 	ism_map_t	*ism_map;
8366 	pgcnt_t		npgs = 0;
8367 	pgcnt_t		npgs_scd = 0;
8368 	int		j;
8369 	sf_scd_t	*scdp;
8370 	uchar_t		rid;
8371 
8372 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
8373 	scdp = sfmmup->sfmmu_scdp;
8374 
8375 	for (; ism_blkp != NULL; ism_blkp = ism_blkp->iblk_next) {
8376 		ism_map = ism_blkp->iblk_maps;
8377 		for (j = 0; ism_map[j].imap_ismhat && j < ISM_MAP_SLOTS; j++) {
8378 			rid = ism_map[j].imap_rid;
8379 			ASSERT(rid == SFMMU_INVALID_ISMRID ||
8380 			    rid < sfmmup->sfmmu_srdp->srd_next_ismrid);
8381 
8382 			if (scdp != NULL && rid != SFMMU_INVALID_ISMRID &&
8383 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
8384 				/* ISM is in sfmmup's SCD */
8385 				npgs_scd +=
8386 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8387 			} else {
8388 				/* ISMs is not in SCD */
8389 				npgs +=
8390 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8391 			}
8392 		}
8393 	}
8394 	sfmmup->sfmmu_ismttecnt[szc] = npgs;
8395 	sfmmup->sfmmu_scdismttecnt[szc] = npgs_scd;
8396 	return (npgs);
8397 }
8398 
8399 /*
8400  * Yield the memory claim requirement for an address space.
8401  *
8402  * This is currently implemented as the number of bytes that have active
8403  * hardware translations that have page structures.  Therefore, it can
8404  * underestimate the traditional resident set size, eg, if the
8405  * physical page is present and the hardware translation is missing;
8406  * and it can overestimate the rss, eg, if there are active
8407  * translations to a frame buffer with page structs.
8408  * Also, it does not take sharing into account.
8409  *
8410  * Note that we don't acquire locks here since this function is most often
8411  * called from the clock thread.
8412  */
8413 size_t
8414 hat_get_mapped_size(struct hat *hat)
8415 {
8416 	size_t		assize = 0;
8417 	int 		i;
8418 
8419 	if (hat == NULL)
8420 		return (0);
8421 
8422 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8423 
8424 	for (i = 0; i < mmu_page_sizes; i++)
8425 		assize += ((pgcnt_t)hat->sfmmu_ttecnt[i] +
8426 		    (pgcnt_t)hat->sfmmu_scdrttecnt[i]) * TTEBYTES(i);
8427 
8428 	if (hat->sfmmu_iblk == NULL)
8429 		return (assize);
8430 
8431 	for (i = 0; i < mmu_page_sizes; i++)
8432 		assize += ((pgcnt_t)hat->sfmmu_ismttecnt[i] +
8433 		    (pgcnt_t)hat->sfmmu_scdismttecnt[i]) * TTEBYTES(i);
8434 
8435 	return (assize);
8436 }
8437 
8438 int
8439 hat_stats_enable(struct hat *hat)
8440 {
8441 	hatlock_t	*hatlockp;
8442 
8443 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8444 
8445 	hatlockp = sfmmu_hat_enter(hat);
8446 	hat->sfmmu_rmstat++;
8447 	sfmmu_hat_exit(hatlockp);
8448 	return (1);
8449 }
8450 
8451 void
8452 hat_stats_disable(struct hat *hat)
8453 {
8454 	hatlock_t	*hatlockp;
8455 
8456 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8457 
8458 	hatlockp = sfmmu_hat_enter(hat);
8459 	hat->sfmmu_rmstat--;
8460 	sfmmu_hat_exit(hatlockp);
8461 }
8462 
8463 /*
8464  * Routines for entering or removing  ourselves from the
8465  * ism_hat's mapping list. This is used for both private and
8466  * SCD hats.
8467  */
8468 static void
8469 iment_add(struct ism_ment *iment,  struct hat *ism_hat)
8470 {
8471 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8472 
8473 	iment->iment_prev = NULL;
8474 	iment->iment_next = ism_hat->sfmmu_iment;
8475 	if (ism_hat->sfmmu_iment) {
8476 		ism_hat->sfmmu_iment->iment_prev = iment;
8477 	}
8478 	ism_hat->sfmmu_iment = iment;
8479 }
8480 
8481 static void
8482 iment_sub(struct ism_ment *iment, struct hat *ism_hat)
8483 {
8484 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8485 
8486 	if (ism_hat->sfmmu_iment == NULL) {
8487 		panic("ism map entry remove - no entries");
8488 	}
8489 
8490 	if (iment->iment_prev) {
8491 		ASSERT(ism_hat->sfmmu_iment != iment);
8492 		iment->iment_prev->iment_next = iment->iment_next;
8493 	} else {
8494 		ASSERT(ism_hat->sfmmu_iment == iment);
8495 		ism_hat->sfmmu_iment = iment->iment_next;
8496 	}
8497 
8498 	if (iment->iment_next) {
8499 		iment->iment_next->iment_prev = iment->iment_prev;
8500 	}
8501 
8502 	/*
8503 	 * zero out the entry
8504 	 */
8505 	iment->iment_next = NULL;
8506 	iment->iment_prev = NULL;
8507 	iment->iment_hat =  NULL;
8508 }
8509 
8510 /*
8511  * Hat_share()/unshare() return an (non-zero) error
8512  * when saddr and daddr are not properly aligned.
8513  *
8514  * The top level mapping element determines the alignment
8515  * requirement for saddr and daddr, depending on different
8516  * architectures.
8517  *
8518  * When hat_share()/unshare() are not supported,
8519  * HATOP_SHARE()/UNSHARE() return 0
8520  */
8521 int
8522 hat_share(struct hat *sfmmup, caddr_t addr,
8523 	struct hat *ism_hatid, caddr_t sptaddr, size_t len, uint_t ismszc)
8524 {
8525 	ism_blk_t	*ism_blkp;
8526 	ism_blk_t	*new_iblk;
8527 	ism_map_t 	*ism_map;
8528 	ism_ment_t	*ism_ment;
8529 	int		i, added;
8530 	hatlock_t	*hatlockp;
8531 	int		reload_mmu = 0;
8532 	uint_t		ismshift = page_get_shift(ismszc);
8533 	size_t		ismpgsz = page_get_pagesize(ismszc);
8534 	uint_t		ismmask = (uint_t)ismpgsz - 1;
8535 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8536 	ushort_t	ismhatflag;
8537 	hat_region_cookie_t rcookie;
8538 	sf_scd_t	*old_scdp;
8539 
8540 #ifdef DEBUG
8541 	caddr_t		eaddr = addr + len;
8542 #endif /* DEBUG */
8543 
8544 	ASSERT(ism_hatid != NULL && sfmmup != NULL);
8545 	ASSERT(sptaddr == ISMID_STARTADDR);
8546 	/*
8547 	 * Check the alignment.
8548 	 */
8549 	if (!ISM_ALIGNED(ismshift, addr) || !ISM_ALIGNED(ismshift, sptaddr))
8550 		return (EINVAL);
8551 
8552 	/*
8553 	 * Check size alignment.
8554 	 */
8555 	if (!ISM_ALIGNED(ismshift, len))
8556 		return (EINVAL);
8557 
8558 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
8559 
8560 	/*
8561 	 * Allocate ism_ment for the ism_hat's mapping list, and an
8562 	 * ism map blk in case we need one.  We must do our
8563 	 * allocations before acquiring locks to prevent a deadlock
8564 	 * in the kmem allocator on the mapping list lock.
8565 	 */
8566 	new_iblk = kmem_cache_alloc(ism_blk_cache, KM_SLEEP);
8567 	ism_ment = kmem_cache_alloc(ism_ment_cache, KM_SLEEP);
8568 
8569 	/*
8570 	 * Serialize ISM mappings with the ISM busy flag, and also the
8571 	 * trap handlers.
8572 	 */
8573 	sfmmu_ismhat_enter(sfmmup, 0);
8574 
8575 	/*
8576 	 * Allocate an ism map blk if necessary.
8577 	 */
8578 	if (sfmmup->sfmmu_iblk == NULL) {
8579 		sfmmup->sfmmu_iblk = new_iblk;
8580 		bzero(new_iblk, sizeof (*new_iblk));
8581 		new_iblk->iblk_nextpa = (uint64_t)-1;
8582 		membar_stst();	/* make sure next ptr visible to all CPUs */
8583 		sfmmup->sfmmu_ismblkpa = va_to_pa((caddr_t)new_iblk);
8584 		reload_mmu = 1;
8585 		new_iblk = NULL;
8586 	}
8587 
8588 #ifdef DEBUG
8589 	/*
8590 	 * Make sure mapping does not already exist.
8591 	 */
8592 	ism_blkp = sfmmup->sfmmu_iblk;
8593 	while (ism_blkp != NULL) {
8594 		ism_map = ism_blkp->iblk_maps;
8595 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
8596 			if ((addr >= ism_start(ism_map[i]) &&
8597 			    addr < ism_end(ism_map[i])) ||
8598 			    eaddr > ism_start(ism_map[i]) &&
8599 			    eaddr <= ism_end(ism_map[i])) {
8600 				panic("sfmmu_share: Already mapped!");
8601 			}
8602 		}
8603 		ism_blkp = ism_blkp->iblk_next;
8604 	}
8605 #endif /* DEBUG */
8606 
8607 	ASSERT(ismszc >= TTE4M);
8608 	if (ismszc == TTE4M) {
8609 		ismhatflag = HAT_4M_FLAG;
8610 	} else if (ismszc == TTE32M) {
8611 		ismhatflag = HAT_32M_FLAG;
8612 	} else if (ismszc == TTE256M) {
8613 		ismhatflag = HAT_256M_FLAG;
8614 	}
8615 	/*
8616 	 * Add mapping to first available mapping slot.
8617 	 */
8618 	ism_blkp = sfmmup->sfmmu_iblk;
8619 	added = 0;
8620 	while (!added) {
8621 		ism_map = ism_blkp->iblk_maps;
8622 		for (i = 0; i < ISM_MAP_SLOTS; i++)  {
8623 			if (ism_map[i].imap_ismhat == NULL) {
8624 
8625 				ism_map[i].imap_ismhat = ism_hatid;
8626 				ism_map[i].imap_vb_shift = (uchar_t)ismshift;
8627 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8628 				ism_map[i].imap_hatflags = ismhatflag;
8629 				ism_map[i].imap_sz_mask = ismmask;
8630 				/*
8631 				 * imap_seg is checked in ISM_CHECK to see if
8632 				 * non-NULL, then other info assumed valid.
8633 				 */
8634 				membar_stst();
8635 				ism_map[i].imap_seg = (uintptr_t)addr | sh_size;
8636 				ism_map[i].imap_ment = ism_ment;
8637 
8638 				/*
8639 				 * Now add ourselves to the ism_hat's
8640 				 * mapping list.
8641 				 */
8642 				ism_ment->iment_hat = sfmmup;
8643 				ism_ment->iment_base_va = addr;
8644 				ism_hatid->sfmmu_ismhat = 1;
8645 				mutex_enter(&ism_mlist_lock);
8646 				iment_add(ism_ment, ism_hatid);
8647 				mutex_exit(&ism_mlist_lock);
8648 				added = 1;
8649 				break;
8650 			}
8651 		}
8652 		if (!added && ism_blkp->iblk_next == NULL) {
8653 			ism_blkp->iblk_next = new_iblk;
8654 			new_iblk = NULL;
8655 			bzero(ism_blkp->iblk_next,
8656 			    sizeof (*ism_blkp->iblk_next));
8657 			ism_blkp->iblk_next->iblk_nextpa = (uint64_t)-1;
8658 			membar_stst();
8659 			ism_blkp->iblk_nextpa =
8660 			    va_to_pa((caddr_t)ism_blkp->iblk_next);
8661 		}
8662 		ism_blkp = ism_blkp->iblk_next;
8663 	}
8664 
8665 	/*
8666 	 * After calling hat_join_region, sfmmup may join a new SCD or
8667 	 * move from the old scd to a new scd, in which case, we want to
8668 	 * shrink the sfmmup's private tsb size, i.e., pass shrink to
8669 	 * sfmmu_check_page_sizes at the end of this routine.
8670 	 */
8671 	old_scdp = sfmmup->sfmmu_scdp;
8672 
8673 	rcookie = hat_join_region(sfmmup, addr, len, (void *)ism_hatid, 0,
8674 	    PROT_ALL, ismszc, NULL, HAT_REGION_ISM);
8675 	if (rcookie != HAT_INVALID_REGION_COOKIE) {
8676 		ism_map[i].imap_rid = (uchar_t)((uint64_t)rcookie);
8677 	}
8678 	/*
8679 	 * Update our counters for this sfmmup's ism mappings.
8680 	 */
8681 	for (i = 0; i <= ismszc; i++) {
8682 		if (!(disable_ism_large_pages & (1 << i)))
8683 			(void) ism_tsb_entries(sfmmup, i);
8684 	}
8685 
8686 	/*
8687 	 * For ISM and DISM we do not support 512K pages, so we only only
8688 	 * search the 4M and 8K/64K hashes for 4 pagesize cpus, and search the
8689 	 * 256M or 32M, and 4M and 8K/64K hashes for 6 pagesize cpus.
8690 	 *
8691 	 * Need to set 32M/256M ISM flags to make sure
8692 	 * sfmmu_check_page_sizes() enables them on Panther.
8693 	 */
8694 	ASSERT((disable_ism_large_pages & (1 << TTE512K)) != 0);
8695 
8696 	switch (ismszc) {
8697 	case TTE256M:
8698 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_256M_ISM)) {
8699 			hatlockp = sfmmu_hat_enter(sfmmup);
8700 			SFMMU_FLAGS_SET(sfmmup, HAT_256M_ISM);
8701 			sfmmu_hat_exit(hatlockp);
8702 		}
8703 		break;
8704 	case TTE32M:
8705 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_32M_ISM)) {
8706 			hatlockp = sfmmu_hat_enter(sfmmup);
8707 			SFMMU_FLAGS_SET(sfmmup, HAT_32M_ISM);
8708 			sfmmu_hat_exit(hatlockp);
8709 		}
8710 		break;
8711 	default:
8712 		break;
8713 	}
8714 
8715 	/*
8716 	 * If we updated the ismblkpa for this HAT we must make
8717 	 * sure all CPUs running this process reload their tsbmiss area.
8718 	 * Otherwise they will fail to load the mappings in the tsbmiss
8719 	 * handler and will loop calling pagefault().
8720 	 */
8721 	if (reload_mmu) {
8722 		hatlockp = sfmmu_hat_enter(sfmmup);
8723 		sfmmu_sync_mmustate(sfmmup);
8724 		sfmmu_hat_exit(hatlockp);
8725 	}
8726 
8727 	sfmmu_ismhat_exit(sfmmup, 0);
8728 
8729 	/*
8730 	 * Free up ismblk if we didn't use it.
8731 	 */
8732 	if (new_iblk != NULL)
8733 		kmem_cache_free(ism_blk_cache, new_iblk);
8734 
8735 	/*
8736 	 * Check TSB and TLB page sizes.
8737 	 */
8738 	if (sfmmup->sfmmu_scdp != NULL && old_scdp != sfmmup->sfmmu_scdp) {
8739 		sfmmu_check_page_sizes(sfmmup, 0);
8740 	} else {
8741 		sfmmu_check_page_sizes(sfmmup, 1);
8742 	}
8743 	return (0);
8744 }
8745 
8746 /*
8747  * hat_unshare removes exactly one ism_map from
8748  * this process's as.  It expects multiple calls
8749  * to hat_unshare for multiple shm segments.
8750  */
8751 void
8752 hat_unshare(struct hat *sfmmup, caddr_t addr, size_t len, uint_t ismszc)
8753 {
8754 	ism_map_t 	*ism_map;
8755 	ism_ment_t	*free_ment = NULL;
8756 	ism_blk_t	*ism_blkp;
8757 	struct hat	*ism_hatid;
8758 	int 		found, i;
8759 	hatlock_t	*hatlockp;
8760 	struct tsb_info	*tsbinfo;
8761 	uint_t		ismshift = page_get_shift(ismszc);
8762 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8763 	uchar_t		ism_rid;
8764 	sf_scd_t	*old_scdp;
8765 
8766 	ASSERT(ISM_ALIGNED(ismshift, addr));
8767 	ASSERT(ISM_ALIGNED(ismshift, len));
8768 	ASSERT(sfmmup != NULL);
8769 	ASSERT(sfmmup != ksfmmup);
8770 
8771 	if (sfmmup->sfmmu_xhat_provider) {
8772 		XHAT_UNSHARE(sfmmup, addr, len);
8773 		return;
8774 	} else {
8775 		/*
8776 		 * This must be a CPU HAT. If the address space has
8777 		 * XHATs attached, inform all XHATs that ISM segment
8778 		 * is going away
8779 		 */
8780 		ASSERT(sfmmup->sfmmu_as != NULL);
8781 		if (sfmmup->sfmmu_as->a_xhat != NULL)
8782 			xhat_unshare_all(sfmmup->sfmmu_as, addr, len);
8783 	}
8784 
8785 	/*
8786 	 * Make sure that during the entire time ISM mappings are removed,
8787 	 * the trap handlers serialize behind us, and that no one else
8788 	 * can be mucking with ISM mappings.  This also lets us get away
8789 	 * with not doing expensive cross calls to flush the TLB -- we
8790 	 * just discard the context, flush the entire TSB, and call it
8791 	 * a day.
8792 	 */
8793 	sfmmu_ismhat_enter(sfmmup, 0);
8794 
8795 	/*
8796 	 * Remove the mapping.
8797 	 *
8798 	 * We can't have any holes in the ism map.
8799 	 * The tsb miss code while searching the ism map will
8800 	 * stop on an empty map slot.  So we must move
8801 	 * everyone past the hole up 1 if any.
8802 	 *
8803 	 * Also empty ism map blks are not freed until the
8804 	 * process exits. This is to prevent a MT race condition
8805 	 * between sfmmu_unshare() and sfmmu_tsbmiss_exception().
8806 	 */
8807 	found = 0;
8808 	ism_blkp = sfmmup->sfmmu_iblk;
8809 	while (!found && ism_blkp != NULL) {
8810 		ism_map = ism_blkp->iblk_maps;
8811 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
8812 			if (addr == ism_start(ism_map[i]) &&
8813 			    sh_size == (size_t)(ism_size(ism_map[i]))) {
8814 				found = 1;
8815 				break;
8816 			}
8817 		}
8818 		if (!found)
8819 			ism_blkp = ism_blkp->iblk_next;
8820 	}
8821 
8822 	if (found) {
8823 		ism_hatid = ism_map[i].imap_ismhat;
8824 		ism_rid = ism_map[i].imap_rid;
8825 		ASSERT(ism_hatid != NULL);
8826 		ASSERT(ism_hatid->sfmmu_ismhat == 1);
8827 
8828 		/*
8829 		 * After hat_leave_region, the sfmmup may leave SCD,
8830 		 * in which case, we want to grow the private tsb size when
8831 		 * calling sfmmu_check_page_sizes at the end of the routine.
8832 		 */
8833 		old_scdp = sfmmup->sfmmu_scdp;
8834 		/*
8835 		 * Then remove ourselves from the region.
8836 		 */
8837 		if (ism_rid != SFMMU_INVALID_ISMRID) {
8838 			hat_leave_region(sfmmup, (void *)((uint64_t)ism_rid),
8839 			    HAT_REGION_ISM);
8840 		}
8841 
8842 		/*
8843 		 * And now guarantee that any other cpu
8844 		 * that tries to process an ISM miss
8845 		 * will go to tl=0.
8846 		 */
8847 		hatlockp = sfmmu_hat_enter(sfmmup);
8848 		sfmmu_invalidate_ctx(sfmmup);
8849 		sfmmu_hat_exit(hatlockp);
8850 
8851 		/*
8852 		 * Remove ourselves from the ism mapping list.
8853 		 */
8854 		mutex_enter(&ism_mlist_lock);
8855 		iment_sub(ism_map[i].imap_ment, ism_hatid);
8856 		mutex_exit(&ism_mlist_lock);
8857 		free_ment = ism_map[i].imap_ment;
8858 
8859 		/*
8860 		 * We delete the ism map by copying
8861 		 * the next map over the current one.
8862 		 * We will take the next one in the maps
8863 		 * array or from the next ism_blk.
8864 		 */
8865 		while (ism_blkp != NULL) {
8866 			ism_map = ism_blkp->iblk_maps;
8867 			while (i < (ISM_MAP_SLOTS - 1)) {
8868 				ism_map[i] = ism_map[i + 1];
8869 				i++;
8870 			}
8871 			/* i == (ISM_MAP_SLOTS - 1) */
8872 			ism_blkp = ism_blkp->iblk_next;
8873 			if (ism_blkp != NULL) {
8874 				ism_map[i] = ism_blkp->iblk_maps[0];
8875 				i = 0;
8876 			} else {
8877 				ism_map[i].imap_seg = 0;
8878 				ism_map[i].imap_vb_shift = 0;
8879 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8880 				ism_map[i].imap_hatflags = 0;
8881 				ism_map[i].imap_sz_mask = 0;
8882 				ism_map[i].imap_ismhat = NULL;
8883 				ism_map[i].imap_ment = NULL;
8884 			}
8885 		}
8886 
8887 		/*
8888 		 * Now flush entire TSB for the process, since
8889 		 * demapping page by page can be too expensive.
8890 		 * We don't have to flush the TLB here anymore
8891 		 * since we switch to a new TLB ctx instead.
8892 		 * Also, there is no need to flush if the process
8893 		 * is exiting since the TSB will be freed later.
8894 		 */
8895 		if (!sfmmup->sfmmu_free) {
8896 			hatlockp = sfmmu_hat_enter(sfmmup);
8897 			for (tsbinfo = sfmmup->sfmmu_tsb; tsbinfo != NULL;
8898 			    tsbinfo = tsbinfo->tsb_next) {
8899 				if (tsbinfo->tsb_flags & TSB_SWAPPED)
8900 					continue;
8901 				if (tsbinfo->tsb_flags & TSB_RELOC_FLAG) {
8902 					tsbinfo->tsb_flags |=
8903 					    TSB_FLUSH_NEEDED;
8904 					continue;
8905 				}
8906 
8907 				sfmmu_inv_tsb(tsbinfo->tsb_va,
8908 				    TSB_BYTES(tsbinfo->tsb_szc));
8909 			}
8910 			sfmmu_hat_exit(hatlockp);
8911 		}
8912 	}
8913 
8914 	/*
8915 	 * Update our counters for this sfmmup's ism mappings.
8916 	 */
8917 	for (i = 0; i <= ismszc; i++) {
8918 		if (!(disable_ism_large_pages & (1 << i)))
8919 			(void) ism_tsb_entries(sfmmup, i);
8920 	}
8921 
8922 	sfmmu_ismhat_exit(sfmmup, 0);
8923 
8924 	/*
8925 	 * We must do our freeing here after dropping locks
8926 	 * to prevent a deadlock in the kmem allocator on the
8927 	 * mapping list lock.
8928 	 */
8929 	if (free_ment != NULL)
8930 		kmem_cache_free(ism_ment_cache, free_ment);
8931 
8932 	/*
8933 	 * Check TSB and TLB page sizes if the process isn't exiting.
8934 	 */
8935 	if (!sfmmup->sfmmu_free) {
8936 		if (found && old_scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
8937 			sfmmu_check_page_sizes(sfmmup, 1);
8938 		} else {
8939 			sfmmu_check_page_sizes(sfmmup, 0);
8940 		}
8941 	}
8942 }
8943 
8944 /* ARGSUSED */
8945 static int
8946 sfmmu_idcache_constructor(void *buf, void *cdrarg, int kmflags)
8947 {
8948 	/* void *buf is sfmmu_t pointer */
8949 	bzero(buf, sizeof (sfmmu_t));
8950 
8951 	return (0);
8952 }
8953 
8954 /* ARGSUSED */
8955 static void
8956 sfmmu_idcache_destructor(void *buf, void *cdrarg)
8957 {
8958 	/* void *buf is sfmmu_t pointer */
8959 }
8960 
8961 /*
8962  * setup kmem hmeblks by bzeroing all members and initializing the nextpa
8963  * field to be the pa of this hmeblk
8964  */
8965 /* ARGSUSED */
8966 static int
8967 sfmmu_hblkcache_constructor(void *buf, void *cdrarg, int kmflags)
8968 {
8969 	struct hme_blk *hmeblkp;
8970 
8971 	bzero(buf, (size_t)cdrarg);
8972 	hmeblkp = (struct hme_blk *)buf;
8973 	hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
8974 
8975 #ifdef	HBLK_TRACE
8976 	mutex_init(&hmeblkp->hblk_audit_lock, NULL, MUTEX_DEFAULT, NULL);
8977 #endif	/* HBLK_TRACE */
8978 
8979 	return (0);
8980 }
8981 
8982 /* ARGSUSED */
8983 static void
8984 sfmmu_hblkcache_destructor(void *buf, void *cdrarg)
8985 {
8986 
8987 #ifdef	HBLK_TRACE
8988 
8989 	struct hme_blk *hmeblkp;
8990 
8991 	hmeblkp = (struct hme_blk *)buf;
8992 	mutex_destroy(&hmeblkp->hblk_audit_lock);
8993 
8994 #endif	/* HBLK_TRACE */
8995 }
8996 
8997 #define	SFMMU_CACHE_RECLAIM_SCAN_RATIO 8
8998 static int sfmmu_cache_reclaim_scan_ratio = SFMMU_CACHE_RECLAIM_SCAN_RATIO;
8999 /*
9000  * The kmem allocator will callback into our reclaim routine when the system
9001  * is running low in memory.  We traverse the hash and free up all unused but
9002  * still cached hme_blks.  We also traverse the free list and free them up
9003  * as well.
9004  */
9005 /*ARGSUSED*/
9006 static void
9007 sfmmu_hblkcache_reclaim(void *cdrarg)
9008 {
9009 	int i;
9010 	struct hmehash_bucket *hmebp;
9011 	struct hme_blk *hmeblkp, *nx_hblk, *pr_hblk = NULL;
9012 	static struct hmehash_bucket *uhmehash_reclaim_hand;
9013 	static struct hmehash_bucket *khmehash_reclaim_hand;
9014 	struct hme_blk *list = NULL, *last_hmeblkp;
9015 	cpuset_t cpuset = cpu_ready_set;
9016 	cpu_hme_pend_t *cpuhp;
9017 
9018 	/* Free up hmeblks on the cpu pending lists */
9019 	for (i = 0; i < NCPU; i++) {
9020 		cpuhp = &cpu_hme_pend[i];
9021 		if (cpuhp->chp_listp != NULL)  {
9022 			mutex_enter(&cpuhp->chp_mutex);
9023 			if (cpuhp->chp_listp == NULL) {
9024 				mutex_exit(&cpuhp->chp_mutex);
9025 				continue;
9026 			}
9027 			for (last_hmeblkp = cpuhp->chp_listp;
9028 			    last_hmeblkp->hblk_next != NULL;
9029 			    last_hmeblkp = last_hmeblkp->hblk_next)
9030 				;
9031 			last_hmeblkp->hblk_next = list;
9032 			list = cpuhp->chp_listp;
9033 			cpuhp->chp_listp = NULL;
9034 			cpuhp->chp_count = 0;
9035 			mutex_exit(&cpuhp->chp_mutex);
9036 		}
9037 
9038 	}
9039 
9040 	if (list != NULL) {
9041 		kpreempt_disable();
9042 		CPUSET_DEL(cpuset, CPU->cpu_id);
9043 		xt_sync(cpuset);
9044 		xt_sync(cpuset);
9045 		kpreempt_enable();
9046 		sfmmu_hblk_free(&list);
9047 		list = NULL;
9048 	}
9049 
9050 	hmebp = uhmehash_reclaim_hand;
9051 	if (hmebp == NULL || hmebp > &uhme_hash[UHMEHASH_SZ])
9052 		uhmehash_reclaim_hand = hmebp = uhme_hash;
9053 	uhmehash_reclaim_hand += UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9054 
9055 	for (i = UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9056 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9057 			hmeblkp = hmebp->hmeblkp;
9058 			pr_hblk = NULL;
9059 			while (hmeblkp) {
9060 				nx_hblk = hmeblkp->hblk_next;
9061 				if (!hmeblkp->hblk_vcnt &&
9062 				    !hmeblkp->hblk_hmecnt) {
9063 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9064 					    pr_hblk, &list, 0);
9065 				} else {
9066 					pr_hblk = hmeblkp;
9067 				}
9068 				hmeblkp = nx_hblk;
9069 			}
9070 			SFMMU_HASH_UNLOCK(hmebp);
9071 		}
9072 		if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
9073 			hmebp = uhme_hash;
9074 	}
9075 
9076 	hmebp = khmehash_reclaim_hand;
9077 	if (hmebp == NULL || hmebp > &khme_hash[KHMEHASH_SZ])
9078 		khmehash_reclaim_hand = hmebp = khme_hash;
9079 	khmehash_reclaim_hand += KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9080 
9081 	for (i = KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9082 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9083 			hmeblkp = hmebp->hmeblkp;
9084 			pr_hblk = NULL;
9085 			while (hmeblkp) {
9086 				nx_hblk = hmeblkp->hblk_next;
9087 				if (!hmeblkp->hblk_vcnt &&
9088 				    !hmeblkp->hblk_hmecnt) {
9089 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9090 					    pr_hblk, &list, 0);
9091 				} else {
9092 					pr_hblk = hmeblkp;
9093 				}
9094 				hmeblkp = nx_hblk;
9095 			}
9096 			SFMMU_HASH_UNLOCK(hmebp);
9097 		}
9098 		if (hmebp++ == &khme_hash[KHMEHASH_SZ])
9099 			hmebp = khme_hash;
9100 	}
9101 	sfmmu_hblks_list_purge(&list, 0);
9102 }
9103 
9104 /*
9105  * sfmmu_get_ppvcolor should become a vm_machdep or hatop interface.
9106  * same goes for sfmmu_get_addrvcolor().
9107  *
9108  * This function will return the virtual color for the specified page. The
9109  * virtual color corresponds to this page current mapping or its last mapping.
9110  * It is used by memory allocators to choose addresses with the correct
9111  * alignment so vac consistency is automatically maintained.  If the page
9112  * has no color it returns -1.
9113  */
9114 /*ARGSUSED*/
9115 int
9116 sfmmu_get_ppvcolor(struct page *pp)
9117 {
9118 #ifdef VAC
9119 	int color;
9120 
9121 	if (!(cache & CACHE_VAC) || PP_NEWPAGE(pp)) {
9122 		return (-1);
9123 	}
9124 	color = PP_GET_VCOLOR(pp);
9125 	ASSERT(color < mmu_btop(shm_alignment));
9126 	return (color);
9127 #else
9128 	return (-1);
9129 #endif	/* VAC */
9130 }
9131 
9132 /*
9133  * This function will return the desired alignment for vac consistency
9134  * (vac color) given a virtual address.  If no vac is present it returns -1.
9135  */
9136 /*ARGSUSED*/
9137 int
9138 sfmmu_get_addrvcolor(caddr_t vaddr)
9139 {
9140 #ifdef VAC
9141 	if (cache & CACHE_VAC) {
9142 		return (addr_to_vcolor(vaddr));
9143 	} else {
9144 		return (-1);
9145 	}
9146 #else
9147 	return (-1);
9148 #endif	/* VAC */
9149 }
9150 
9151 #ifdef VAC
9152 /*
9153  * Check for conflicts.
9154  * A conflict exists if the new and existent mappings do not match in
9155  * their "shm_alignment fields. If conflicts exist, the existant mappings
9156  * are flushed unless one of them is locked. If one of them is locked, then
9157  * the mappings are flushed and converted to non-cacheable mappings.
9158  */
9159 static void
9160 sfmmu_vac_conflict(struct hat *hat, caddr_t addr, page_t *pp)
9161 {
9162 	struct hat *tmphat;
9163 	struct sf_hment *sfhmep, *tmphme = NULL;
9164 	struct hme_blk *hmeblkp;
9165 	int vcolor;
9166 	tte_t tte;
9167 
9168 	ASSERT(sfmmu_mlist_held(pp));
9169 	ASSERT(!PP_ISNC(pp));		/* page better be cacheable */
9170 
9171 	vcolor = addr_to_vcolor(addr);
9172 	if (PP_NEWPAGE(pp)) {
9173 		PP_SET_VCOLOR(pp, vcolor);
9174 		return;
9175 	}
9176 
9177 	if (PP_GET_VCOLOR(pp) == vcolor) {
9178 		return;
9179 	}
9180 
9181 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
9182 		/*
9183 		 * Previous user of page had a different color
9184 		 * but since there are no current users
9185 		 * we just flush the cache and change the color.
9186 		 */
9187 		SFMMU_STAT(sf_pgcolor_conflict);
9188 		sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9189 		PP_SET_VCOLOR(pp, vcolor);
9190 		return;
9191 	}
9192 
9193 	/*
9194 	 * If we get here we have a vac conflict with a current
9195 	 * mapping.  VAC conflict policy is as follows.
9196 	 * - The default is to unload the other mappings unless:
9197 	 * - If we have a large mapping we uncache the page.
9198 	 * We need to uncache the rest of the large page too.
9199 	 * - If any of the mappings are locked we uncache the page.
9200 	 * - If the requested mapping is inconsistent
9201 	 * with another mapping and that mapping
9202 	 * is in the same address space we have to
9203 	 * make it non-cached.  The default thing
9204 	 * to do is unload the inconsistent mapping
9205 	 * but if they are in the same address space
9206 	 * we run the risk of unmapping the pc or the
9207 	 * stack which we will use as we return to the user,
9208 	 * in which case we can then fault on the thing
9209 	 * we just unloaded and get into an infinite loop.
9210 	 */
9211 	if (PP_ISMAPPED_LARGE(pp)) {
9212 		int sz;
9213 
9214 		/*
9215 		 * Existing mapping is for big pages. We don't unload
9216 		 * existing big mappings to satisfy new mappings.
9217 		 * Always convert all mappings to TNC.
9218 		 */
9219 		sz = fnd_mapping_sz(pp);
9220 		pp = PP_GROUPLEADER(pp, sz);
9221 		SFMMU_STAT_ADD(sf_uncache_conflict, TTEPAGES(sz));
9222 		sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH,
9223 		    TTEPAGES(sz));
9224 
9225 		return;
9226 	}
9227 
9228 	/*
9229 	 * check if any mapping is in same as or if it is locked
9230 	 * since in that case we need to uncache.
9231 	 */
9232 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9233 		tmphme = sfhmep->hme_next;
9234 		if (IS_PAHME(sfhmep))
9235 			continue;
9236 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9237 		if (hmeblkp->hblk_xhat_bit)
9238 			continue;
9239 		tmphat = hblktosfmmu(hmeblkp);
9240 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
9241 		ASSERT(TTE_IS_VALID(&tte));
9242 		if (hmeblkp->hblk_shared || tmphat == hat ||
9243 		    hmeblkp->hblk_lckcnt) {
9244 			/*
9245 			 * We have an uncache conflict
9246 			 */
9247 			SFMMU_STAT(sf_uncache_conflict);
9248 			sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH, 1);
9249 			return;
9250 		}
9251 	}
9252 
9253 	/*
9254 	 * We have an unload conflict
9255 	 * We have already checked for LARGE mappings, therefore
9256 	 * the remaining mapping(s) must be TTE8K.
9257 	 */
9258 	SFMMU_STAT(sf_unload_conflict);
9259 
9260 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9261 		tmphme = sfhmep->hme_next;
9262 		if (IS_PAHME(sfhmep))
9263 			continue;
9264 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9265 		if (hmeblkp->hblk_xhat_bit)
9266 			continue;
9267 		ASSERT(!hmeblkp->hblk_shared);
9268 		(void) sfmmu_pageunload(pp, sfhmep, TTE8K);
9269 	}
9270 
9271 	if (PP_ISMAPPED_KPM(pp))
9272 		sfmmu_kpm_vac_unload(pp, addr);
9273 
9274 	/*
9275 	 * Unloads only do TLB flushes so we need to flush the
9276 	 * cache here.
9277 	 */
9278 	sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9279 	PP_SET_VCOLOR(pp, vcolor);
9280 }
9281 
9282 /*
9283  * Whenever a mapping is unloaded and the page is in TNC state,
9284  * we see if the page can be made cacheable again. 'pp' is
9285  * the page that we just unloaded a mapping from, the size
9286  * of mapping that was unloaded is 'ottesz'.
9287  * Remark:
9288  * The recache policy for mpss pages can leave a performance problem
9289  * under the following circumstances:
9290  * . A large page in uncached mode has just been unmapped.
9291  * . All constituent pages are TNC due to a conflicting small mapping.
9292  * . There are many other, non conflicting, small mappings around for
9293  *   a lot of the constituent pages.
9294  * . We're called w/ the "old" groupleader page and the old ottesz,
9295  *   but this is irrelevant, since we're no more "PP_ISMAPPED_LARGE", so
9296  *   we end up w/ TTE8K or npages == 1.
9297  * . We call tst_tnc w/ the old groupleader only, and if there is no
9298  *   conflict, we re-cache only this page.
9299  * . All other small mappings are not checked and will be left in TNC mode.
9300  * The problem is not very serious because:
9301  * . mpss is actually only defined for heap and stack, so the probability
9302  *   is not very high that a large page mapping exists in parallel to a small
9303  *   one (this is possible, but seems to be bad programming style in the
9304  *   appl).
9305  * . The problem gets a little bit more serious, when those TNC pages
9306  *   have to be mapped into kernel space, e.g. for networking.
9307  * . When VAC alias conflicts occur in applications, this is regarded
9308  *   as an application bug. So if kstat's show them, the appl should
9309  *   be changed anyway.
9310  */
9311 void
9312 conv_tnc(page_t *pp, int ottesz)
9313 {
9314 	int cursz, dosz;
9315 	pgcnt_t curnpgs, dopgs;
9316 	pgcnt_t pg64k;
9317 	page_t *pp2;
9318 
9319 	/*
9320 	 * Determine how big a range we check for TNC and find
9321 	 * leader page. cursz is the size of the biggest
9322 	 * mapping that still exist on 'pp'.
9323 	 */
9324 	if (PP_ISMAPPED_LARGE(pp)) {
9325 		cursz = fnd_mapping_sz(pp);
9326 	} else {
9327 		cursz = TTE8K;
9328 	}
9329 
9330 	if (ottesz >= cursz) {
9331 		dosz = ottesz;
9332 		pp2 = pp;
9333 	} else {
9334 		dosz = cursz;
9335 		pp2 = PP_GROUPLEADER(pp, dosz);
9336 	}
9337 
9338 	pg64k = TTEPAGES(TTE64K);
9339 	dopgs = TTEPAGES(dosz);
9340 
9341 	ASSERT(dopgs == 1 || ((dopgs & (pg64k - 1)) == 0));
9342 
9343 	while (dopgs != 0) {
9344 		curnpgs = TTEPAGES(cursz);
9345 		if (tst_tnc(pp2, curnpgs)) {
9346 			SFMMU_STAT_ADD(sf_recache, curnpgs);
9347 			sfmmu_page_cache_array(pp2, HAT_CACHE, CACHE_NO_FLUSH,
9348 			    curnpgs);
9349 		}
9350 
9351 		ASSERT(dopgs >= curnpgs);
9352 		dopgs -= curnpgs;
9353 
9354 		if (dopgs == 0) {
9355 			break;
9356 		}
9357 
9358 		pp2 = PP_PAGENEXT_N(pp2, curnpgs);
9359 		if (((dopgs & (pg64k - 1)) == 0) && PP_ISMAPPED_LARGE(pp2)) {
9360 			cursz = fnd_mapping_sz(pp2);
9361 		} else {
9362 			cursz = TTE8K;
9363 		}
9364 	}
9365 }
9366 
9367 /*
9368  * Returns 1 if page(s) can be converted from TNC to cacheable setting,
9369  * returns 0 otherwise. Note that oaddr argument is valid for only
9370  * 8k pages.
9371  */
9372 int
9373 tst_tnc(page_t *pp, pgcnt_t npages)
9374 {
9375 	struct	sf_hment *sfhme;
9376 	struct	hme_blk *hmeblkp;
9377 	tte_t	tte;
9378 	caddr_t	vaddr;
9379 	int	clr_valid = 0;
9380 	int 	color, color1, bcolor;
9381 	int	i, ncolors;
9382 
9383 	ASSERT(pp != NULL);
9384 	ASSERT(!(cache & CACHE_WRITEBACK));
9385 
9386 	if (npages > 1) {
9387 		ncolors = CACHE_NUM_COLOR;
9388 	}
9389 
9390 	for (i = 0; i < npages; i++) {
9391 		ASSERT(sfmmu_mlist_held(pp));
9392 		ASSERT(PP_ISTNC(pp));
9393 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
9394 
9395 		if (PP_ISPNC(pp)) {
9396 			return (0);
9397 		}
9398 
9399 		clr_valid = 0;
9400 		if (PP_ISMAPPED_KPM(pp)) {
9401 			caddr_t kpmvaddr;
9402 
9403 			ASSERT(kpm_enable);
9404 			kpmvaddr = hat_kpm_page2va(pp, 1);
9405 			ASSERT(!(npages > 1 && IS_KPM_ALIAS_RANGE(kpmvaddr)));
9406 			color1 = addr_to_vcolor(kpmvaddr);
9407 			clr_valid = 1;
9408 		}
9409 
9410 		for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9411 			if (IS_PAHME(sfhme))
9412 				continue;
9413 			hmeblkp = sfmmu_hmetohblk(sfhme);
9414 			if (hmeblkp->hblk_xhat_bit)
9415 				continue;
9416 
9417 			sfmmu_copytte(&sfhme->hme_tte, &tte);
9418 			ASSERT(TTE_IS_VALID(&tte));
9419 
9420 			vaddr = tte_to_vaddr(hmeblkp, tte);
9421 			color = addr_to_vcolor(vaddr);
9422 
9423 			if (npages > 1) {
9424 				/*
9425 				 * If there is a big mapping, make sure
9426 				 * 8K mapping is consistent with the big
9427 				 * mapping.
9428 				 */
9429 				bcolor = i % ncolors;
9430 				if (color != bcolor) {
9431 					return (0);
9432 				}
9433 			}
9434 			if (!clr_valid) {
9435 				clr_valid = 1;
9436 				color1 = color;
9437 			}
9438 
9439 			if (color1 != color) {
9440 				return (0);
9441 			}
9442 		}
9443 
9444 		pp = PP_PAGENEXT(pp);
9445 	}
9446 
9447 	return (1);
9448 }
9449 
9450 void
9451 sfmmu_page_cache_array(page_t *pp, int flags, int cache_flush_flag,
9452 	pgcnt_t npages)
9453 {
9454 	kmutex_t *pmtx;
9455 	int i, ncolors, bcolor;
9456 	kpm_hlk_t *kpmp;
9457 	cpuset_t cpuset;
9458 
9459 	ASSERT(pp != NULL);
9460 	ASSERT(!(cache & CACHE_WRITEBACK));
9461 
9462 	kpmp = sfmmu_kpm_kpmp_enter(pp, npages);
9463 	pmtx = sfmmu_page_enter(pp);
9464 
9465 	/*
9466 	 * Fast path caching single unmapped page
9467 	 */
9468 	if (npages == 1 && !PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp) &&
9469 	    flags == HAT_CACHE) {
9470 		PP_CLRTNC(pp);
9471 		PP_CLRPNC(pp);
9472 		sfmmu_page_exit(pmtx);
9473 		sfmmu_kpm_kpmp_exit(kpmp);
9474 		return;
9475 	}
9476 
9477 	/*
9478 	 * We need to capture all cpus in order to change cacheability
9479 	 * because we can't allow one cpu to access the same physical
9480 	 * page using a cacheable and a non-cachebale mapping at the same
9481 	 * time. Since we may end up walking the ism mapping list
9482 	 * have to grab it's lock now since we can't after all the
9483 	 * cpus have been captured.
9484 	 */
9485 	sfmmu_hat_lock_all();
9486 	mutex_enter(&ism_mlist_lock);
9487 	kpreempt_disable();
9488 	cpuset = cpu_ready_set;
9489 	xc_attention(cpuset);
9490 
9491 	if (npages > 1) {
9492 		/*
9493 		 * Make sure all colors are flushed since the
9494 		 * sfmmu_page_cache() only flushes one color-
9495 		 * it does not know big pages.
9496 		 */
9497 		ncolors = CACHE_NUM_COLOR;
9498 		if (flags & HAT_TMPNC) {
9499 			for (i = 0; i < ncolors; i++) {
9500 				sfmmu_cache_flushcolor(i, pp->p_pagenum);
9501 			}
9502 			cache_flush_flag = CACHE_NO_FLUSH;
9503 		}
9504 	}
9505 
9506 	for (i = 0; i < npages; i++) {
9507 
9508 		ASSERT(sfmmu_mlist_held(pp));
9509 
9510 		if (!(flags == HAT_TMPNC && PP_ISTNC(pp))) {
9511 
9512 			if (npages > 1) {
9513 				bcolor = i % ncolors;
9514 			} else {
9515 				bcolor = NO_VCOLOR;
9516 			}
9517 
9518 			sfmmu_page_cache(pp, flags, cache_flush_flag,
9519 			    bcolor);
9520 		}
9521 
9522 		pp = PP_PAGENEXT(pp);
9523 	}
9524 
9525 	xt_sync(cpuset);
9526 	xc_dismissed(cpuset);
9527 	mutex_exit(&ism_mlist_lock);
9528 	sfmmu_hat_unlock_all();
9529 	sfmmu_page_exit(pmtx);
9530 	sfmmu_kpm_kpmp_exit(kpmp);
9531 	kpreempt_enable();
9532 }
9533 
9534 /*
9535  * This function changes the virtual cacheability of all mappings to a
9536  * particular page.  When changing from uncache to cacheable the mappings will
9537  * only be changed if all of them have the same virtual color.
9538  * We need to flush the cache in all cpus.  It is possible that
9539  * a process referenced a page as cacheable but has sinced exited
9540  * and cleared the mapping list.  We still to flush it but have no
9541  * state so all cpus is the only alternative.
9542  */
9543 static void
9544 sfmmu_page_cache(page_t *pp, int flags, int cache_flush_flag, int bcolor)
9545 {
9546 	struct	sf_hment *sfhme;
9547 	struct	hme_blk *hmeblkp;
9548 	sfmmu_t *sfmmup;
9549 	tte_t	tte, ttemod;
9550 	caddr_t	vaddr;
9551 	int	ret, color;
9552 	pfn_t	pfn;
9553 
9554 	color = bcolor;
9555 	pfn = pp->p_pagenum;
9556 
9557 	for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9558 
9559 		if (IS_PAHME(sfhme))
9560 			continue;
9561 		hmeblkp = sfmmu_hmetohblk(sfhme);
9562 
9563 		if (hmeblkp->hblk_xhat_bit)
9564 			continue;
9565 
9566 		sfmmu_copytte(&sfhme->hme_tte, &tte);
9567 		ASSERT(TTE_IS_VALID(&tte));
9568 		vaddr = tte_to_vaddr(hmeblkp, tte);
9569 		color = addr_to_vcolor(vaddr);
9570 
9571 #ifdef DEBUG
9572 		if ((flags & HAT_CACHE) && bcolor != NO_VCOLOR) {
9573 			ASSERT(color == bcolor);
9574 		}
9575 #endif
9576 
9577 		ASSERT(flags != HAT_TMPNC || color == PP_GET_VCOLOR(pp));
9578 
9579 		ttemod = tte;
9580 		if (flags & (HAT_UNCACHE | HAT_TMPNC)) {
9581 			TTE_CLR_VCACHEABLE(&ttemod);
9582 		} else {	/* flags & HAT_CACHE */
9583 			TTE_SET_VCACHEABLE(&ttemod);
9584 		}
9585 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
9586 		if (ret < 0) {
9587 			/*
9588 			 * Since all cpus are captured modifytte should not
9589 			 * fail.
9590 			 */
9591 			panic("sfmmu_page_cache: write to tte failed");
9592 		}
9593 
9594 		sfmmup = hblktosfmmu(hmeblkp);
9595 		if (cache_flush_flag == CACHE_FLUSH) {
9596 			/*
9597 			 * Flush TSBs, TLBs and caches
9598 			 */
9599 			if (hmeblkp->hblk_shared) {
9600 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9601 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9602 				sf_region_t *rgnp;
9603 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9604 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9605 				ASSERT(srdp != NULL);
9606 				rgnp = srdp->srd_hmergnp[rid];
9607 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9608 				    srdp, rgnp, rid);
9609 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9610 				    hmeblkp, 0);
9611 				sfmmu_cache_flush(pfn, addr_to_vcolor(vaddr));
9612 			} else if (sfmmup->sfmmu_ismhat) {
9613 				if (flags & HAT_CACHE) {
9614 					SFMMU_STAT(sf_ism_recache);
9615 				} else {
9616 					SFMMU_STAT(sf_ism_uncache);
9617 				}
9618 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9619 				    pfn, CACHE_FLUSH);
9620 			} else {
9621 				sfmmu_tlbcache_demap(vaddr, sfmmup, hmeblkp,
9622 				    pfn, 0, FLUSH_ALL_CPUS, CACHE_FLUSH, 1);
9623 			}
9624 
9625 			/*
9626 			 * all cache entries belonging to this pfn are
9627 			 * now flushed.
9628 			 */
9629 			cache_flush_flag = CACHE_NO_FLUSH;
9630 		} else {
9631 			/*
9632 			 * Flush only TSBs and TLBs.
9633 			 */
9634 			if (hmeblkp->hblk_shared) {
9635 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9636 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9637 				sf_region_t *rgnp;
9638 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9639 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9640 				ASSERT(srdp != NULL);
9641 				rgnp = srdp->srd_hmergnp[rid];
9642 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9643 				    srdp, rgnp, rid);
9644 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9645 				    hmeblkp, 0);
9646 			} else if (sfmmup->sfmmu_ismhat) {
9647 				if (flags & HAT_CACHE) {
9648 					SFMMU_STAT(sf_ism_recache);
9649 				} else {
9650 					SFMMU_STAT(sf_ism_uncache);
9651 				}
9652 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9653 				    pfn, CACHE_NO_FLUSH);
9654 			} else {
9655 				sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 1);
9656 			}
9657 		}
9658 	}
9659 
9660 	if (PP_ISMAPPED_KPM(pp))
9661 		sfmmu_kpm_page_cache(pp, flags, cache_flush_flag);
9662 
9663 	switch (flags) {
9664 
9665 		default:
9666 			panic("sfmmu_pagecache: unknown flags");
9667 			break;
9668 
9669 		case HAT_CACHE:
9670 			PP_CLRTNC(pp);
9671 			PP_CLRPNC(pp);
9672 			PP_SET_VCOLOR(pp, color);
9673 			break;
9674 
9675 		case HAT_TMPNC:
9676 			PP_SETTNC(pp);
9677 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9678 			break;
9679 
9680 		case HAT_UNCACHE:
9681 			PP_SETPNC(pp);
9682 			PP_CLRTNC(pp);
9683 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9684 			break;
9685 	}
9686 }
9687 #endif	/* VAC */
9688 
9689 
9690 /*
9691  * Wrapper routine used to return a context.
9692  *
9693  * It's the responsibility of the caller to guarantee that the
9694  * process serializes on calls here by taking the HAT lock for
9695  * the hat.
9696  *
9697  */
9698 static void
9699 sfmmu_get_ctx(sfmmu_t *sfmmup)
9700 {
9701 	mmu_ctx_t *mmu_ctxp;
9702 	uint_t pstate_save;
9703 	int ret;
9704 
9705 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9706 	ASSERT(sfmmup != ksfmmup);
9707 
9708 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID)) {
9709 		sfmmu_setup_tsbinfo(sfmmup);
9710 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ALLCTX_INVALID);
9711 	}
9712 
9713 	kpreempt_disable();
9714 
9715 	mmu_ctxp = CPU_MMU_CTXP(CPU);
9716 	ASSERT(mmu_ctxp);
9717 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
9718 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
9719 
9720 	/*
9721 	 * Do a wrap-around if cnum reaches the max # cnum supported by a MMU.
9722 	 */
9723 	if (mmu_ctxp->mmu_cnum == mmu_ctxp->mmu_nctxs)
9724 		sfmmu_ctx_wrap_around(mmu_ctxp);
9725 
9726 	/*
9727 	 * Let the MMU set up the page sizes to use for
9728 	 * this context in the TLB. Don't program 2nd dtlb for ism hat.
9729 	 */
9730 	if ((&mmu_set_ctx_page_sizes) && (sfmmup->sfmmu_ismhat == 0)) {
9731 		mmu_set_ctx_page_sizes(sfmmup);
9732 	}
9733 
9734 	/*
9735 	 * sfmmu_alloc_ctx and sfmmu_load_mmustate will be performed with
9736 	 * interrupts disabled to prevent race condition with wrap-around
9737 	 * ctx invalidatation. In sun4v, ctx invalidation also involves
9738 	 * a HV call to set the number of TSBs to 0. If interrupts are not
9739 	 * disabled until after sfmmu_load_mmustate is complete TSBs may
9740 	 * become assigned to INVALID_CONTEXT. This is not allowed.
9741 	 */
9742 	pstate_save = sfmmu_disable_intrs();
9743 
9744 	if (sfmmu_alloc_ctx(sfmmup, 1, CPU, SFMMU_PRIVATE) &&
9745 	    sfmmup->sfmmu_scdp != NULL) {
9746 		sf_scd_t *scdp = sfmmup->sfmmu_scdp;
9747 		sfmmu_t *scsfmmup = scdp->scd_sfmmup;
9748 		ret = sfmmu_alloc_ctx(scsfmmup, 1, CPU, SFMMU_SHARED);
9749 		/* debug purpose only */
9750 		ASSERT(!ret || scsfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
9751 		    != INVALID_CONTEXT);
9752 	}
9753 	sfmmu_load_mmustate(sfmmup);
9754 
9755 	sfmmu_enable_intrs(pstate_save);
9756 
9757 	kpreempt_enable();
9758 }
9759 
9760 /*
9761  * When all cnums are used up in a MMU, cnum will wrap around to the
9762  * next generation and start from 2.
9763  */
9764 static void
9765 sfmmu_ctx_wrap_around(mmu_ctx_t *mmu_ctxp)
9766 {
9767 
9768 	/* caller must have disabled the preemption */
9769 	ASSERT(curthread->t_preempt >= 1);
9770 	ASSERT(mmu_ctxp != NULL);
9771 
9772 	/* acquire Per-MMU (PM) spin lock */
9773 	mutex_enter(&mmu_ctxp->mmu_lock);
9774 
9775 	/* re-check to see if wrap-around is needed */
9776 	if (mmu_ctxp->mmu_cnum < mmu_ctxp->mmu_nctxs)
9777 		goto done;
9778 
9779 	SFMMU_MMU_STAT(mmu_wrap_around);
9780 
9781 	/* update gnum */
9782 	ASSERT(mmu_ctxp->mmu_gnum != 0);
9783 	mmu_ctxp->mmu_gnum++;
9784 	if (mmu_ctxp->mmu_gnum == 0 ||
9785 	    mmu_ctxp->mmu_gnum > MAX_SFMMU_GNUM_VAL) {
9786 		cmn_err(CE_PANIC, "mmu_gnum of mmu_ctx 0x%p is out of bound.",
9787 		    (void *)mmu_ctxp);
9788 	}
9789 
9790 	if (mmu_ctxp->mmu_ncpus > 1) {
9791 		cpuset_t cpuset;
9792 
9793 		membar_enter(); /* make sure updated gnum visible */
9794 
9795 		SFMMU_XCALL_STATS(NULL);
9796 
9797 		/* xcall to others on the same MMU to invalidate ctx */
9798 		cpuset = mmu_ctxp->mmu_cpuset;
9799 		ASSERT(CPU_IN_SET(cpuset, CPU->cpu_id));
9800 		CPUSET_DEL(cpuset, CPU->cpu_id);
9801 		CPUSET_AND(cpuset, cpu_ready_set);
9802 
9803 		/*
9804 		 * Pass in INVALID_CONTEXT as the first parameter to
9805 		 * sfmmu_raise_tsb_exception, which invalidates the context
9806 		 * of any process running on the CPUs in the MMU.
9807 		 */
9808 		xt_some(cpuset, sfmmu_raise_tsb_exception,
9809 		    INVALID_CONTEXT, INVALID_CONTEXT);
9810 		xt_sync(cpuset);
9811 
9812 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
9813 	}
9814 
9815 	if (sfmmu_getctx_sec() != INVALID_CONTEXT) {
9816 		sfmmu_setctx_sec(INVALID_CONTEXT);
9817 		sfmmu_clear_utsbinfo();
9818 	}
9819 
9820 	/*
9821 	 * No xcall is needed here. For sun4u systems all CPUs in context
9822 	 * domain share a single physical MMU therefore it's enough to flush
9823 	 * TLB on local CPU. On sun4v systems we use 1 global context
9824 	 * domain and flush all remote TLBs in sfmmu_raise_tsb_exception
9825 	 * handler. Note that vtag_flushall_uctxs() is called
9826 	 * for Ultra II machine, where the equivalent flushall functionality
9827 	 * is implemented in SW, and only user ctx TLB entries are flushed.
9828 	 */
9829 	if (&vtag_flushall_uctxs != NULL) {
9830 		vtag_flushall_uctxs();
9831 	} else {
9832 		vtag_flushall();
9833 	}
9834 
9835 	/* reset mmu cnum, skips cnum 0 and 1 */
9836 	mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
9837 
9838 done:
9839 	mutex_exit(&mmu_ctxp->mmu_lock);
9840 }
9841 
9842 
9843 /*
9844  * For multi-threaded process, set the process context to INVALID_CONTEXT
9845  * so that it faults and reloads the MMU state from TL=0. For single-threaded
9846  * process, we can just load the MMU state directly without having to
9847  * set context invalid. Caller must hold the hat lock since we don't
9848  * acquire it here.
9849  */
9850 static void
9851 sfmmu_sync_mmustate(sfmmu_t *sfmmup)
9852 {
9853 	uint_t cnum;
9854 	uint_t pstate_save;
9855 
9856 	ASSERT(sfmmup != ksfmmup);
9857 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9858 
9859 	kpreempt_disable();
9860 
9861 	/*
9862 	 * We check whether the pass'ed-in sfmmup is the same as the
9863 	 * current running proc. This is to makes sure the current proc
9864 	 * stays single-threaded if it already is.
9865 	 */
9866 	if ((sfmmup == curthread->t_procp->p_as->a_hat) &&
9867 	    (curthread->t_procp->p_lwpcnt == 1)) {
9868 		/* single-thread */
9869 		cnum = sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum;
9870 		if (cnum != INVALID_CONTEXT) {
9871 			uint_t curcnum;
9872 			/*
9873 			 * Disable interrupts to prevent race condition
9874 			 * with sfmmu_ctx_wrap_around ctx invalidation.
9875 			 * In sun4v, ctx invalidation involves setting
9876 			 * TSB to NULL, hence, interrupts should be disabled
9877 			 * untill after sfmmu_load_mmustate is completed.
9878 			 */
9879 			pstate_save = sfmmu_disable_intrs();
9880 			curcnum = sfmmu_getctx_sec();
9881 			if (curcnum == cnum)
9882 				sfmmu_load_mmustate(sfmmup);
9883 			sfmmu_enable_intrs(pstate_save);
9884 			ASSERT(curcnum == cnum || curcnum == INVALID_CONTEXT);
9885 		}
9886 	} else {
9887 		/*
9888 		 * multi-thread
9889 		 * or when sfmmup is not the same as the curproc.
9890 		 */
9891 		sfmmu_invalidate_ctx(sfmmup);
9892 	}
9893 
9894 	kpreempt_enable();
9895 }
9896 
9897 
9898 /*
9899  * Replace the specified TSB with a new TSB.  This function gets called when
9900  * we grow, shrink or swapin a TSB.  When swapping in a TSB (TSB_SWAPIN), the
9901  * TSB_FORCEALLOC flag may be used to force allocation of a minimum-sized TSB
9902  * (8K).
9903  *
9904  * Caller must hold the HAT lock, but should assume any tsb_info
9905  * pointers it has are no longer valid after calling this function.
9906  *
9907  * Return values:
9908  *	TSB_ALLOCFAIL	Failed to allocate a TSB, due to memory constraints
9909  *	TSB_LOSTRACE	HAT is busy, i.e. another thread is already doing
9910  *			something to this tsbinfo/TSB
9911  *	TSB_SUCCESS	Operation succeeded
9912  */
9913 static tsb_replace_rc_t
9914 sfmmu_replace_tsb(sfmmu_t *sfmmup, struct tsb_info *old_tsbinfo, uint_t szc,
9915     hatlock_t *hatlockp, uint_t flags)
9916 {
9917 	struct tsb_info *new_tsbinfo = NULL;
9918 	struct tsb_info *curtsb, *prevtsb;
9919 	uint_t tte_sz_mask;
9920 	int i;
9921 
9922 	ASSERT(sfmmup != ksfmmup);
9923 	ASSERT(sfmmup->sfmmu_ismhat == 0);
9924 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9925 	ASSERT(szc <= tsb_max_growsize);
9926 
9927 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_BUSY))
9928 		return (TSB_LOSTRACE);
9929 
9930 	/*
9931 	 * Find the tsb_info ahead of this one in the list, and
9932 	 * also make sure that the tsb_info passed in really
9933 	 * exists!
9934 	 */
9935 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9936 	    curtsb != old_tsbinfo && curtsb != NULL;
9937 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
9938 		;
9939 	ASSERT(curtsb != NULL);
9940 
9941 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9942 		/*
9943 		 * The process is swapped out, so just set the new size
9944 		 * code.  When it swaps back in, we'll allocate a new one
9945 		 * of the new chosen size.
9946 		 */
9947 		curtsb->tsb_szc = szc;
9948 		return (TSB_SUCCESS);
9949 	}
9950 	SFMMU_FLAGS_SET(sfmmup, HAT_BUSY);
9951 
9952 	tte_sz_mask = old_tsbinfo->tsb_ttesz_mask;
9953 
9954 	/*
9955 	 * All initialization is done inside of sfmmu_tsbinfo_alloc().
9956 	 * If we fail to allocate a TSB, exit.
9957 	 *
9958 	 * If tsb grows with new tsb size > 4M and old tsb size < 4M,
9959 	 * then try 4M slab after the initial alloc fails.
9960 	 *
9961 	 * If tsb swapin with tsb size > 4M, then try 4M after the
9962 	 * initial alloc fails.
9963 	 */
9964 	sfmmu_hat_exit(hatlockp);
9965 	if (sfmmu_tsbinfo_alloc(&new_tsbinfo, szc,
9966 	    tte_sz_mask, flags, sfmmup) &&
9967 	    (!(flags & (TSB_GROW | TSB_SWAPIN)) || (szc <= TSB_4M_SZCODE) ||
9968 	    (!(flags & TSB_SWAPIN) &&
9969 	    (old_tsbinfo->tsb_szc >= TSB_4M_SZCODE)) ||
9970 	    sfmmu_tsbinfo_alloc(&new_tsbinfo, TSB_4M_SZCODE,
9971 	    tte_sz_mask, flags, sfmmup))) {
9972 		(void) sfmmu_hat_enter(sfmmup);
9973 		if (!(flags & TSB_SWAPIN))
9974 			SFMMU_STAT(sf_tsb_resize_failures);
9975 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9976 		return (TSB_ALLOCFAIL);
9977 	}
9978 	(void) sfmmu_hat_enter(sfmmup);
9979 
9980 	/*
9981 	 * Re-check to make sure somebody else didn't muck with us while we
9982 	 * didn't hold the HAT lock.  If the process swapped out, fine, just
9983 	 * exit; this can happen if we try to shrink the TSB from the context
9984 	 * of another process (such as on an ISM unmap), though it is rare.
9985 	 */
9986 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9987 		SFMMU_STAT(sf_tsb_resize_failures);
9988 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9989 		sfmmu_hat_exit(hatlockp);
9990 		sfmmu_tsbinfo_free(new_tsbinfo);
9991 		(void) sfmmu_hat_enter(sfmmup);
9992 		return (TSB_LOSTRACE);
9993 	}
9994 
9995 #ifdef	DEBUG
9996 	/* Reverify that the tsb_info still exists.. for debugging only */
9997 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9998 	    curtsb != old_tsbinfo && curtsb != NULL;
9999 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
10000 		;
10001 	ASSERT(curtsb != NULL);
10002 #endif	/* DEBUG */
10003 
10004 	/*
10005 	 * Quiesce any CPUs running this process on their next TLB miss
10006 	 * so they atomically see the new tsb_info.  We temporarily set the
10007 	 * context to invalid context so new threads that come on processor
10008 	 * after we do the xcall to cpusran will also serialize behind the
10009 	 * HAT lock on TLB miss and will see the new TSB.  Since this short
10010 	 * race with a new thread coming on processor is relatively rare,
10011 	 * this synchronization mechanism should be cheaper than always
10012 	 * pausing all CPUs for the duration of the setup, which is what
10013 	 * the old implementation did.  This is particuarly true if we are
10014 	 * copying a huge chunk of memory around during that window.
10015 	 *
10016 	 * The memory barriers are to make sure things stay consistent
10017 	 * with resume() since it does not hold the HAT lock while
10018 	 * walking the list of tsb_info structures.
10019 	 */
10020 	if ((flags & TSB_SWAPIN) != TSB_SWAPIN) {
10021 		/* The TSB is either growing or shrinking. */
10022 		sfmmu_invalidate_ctx(sfmmup);
10023 	} else {
10024 		/*
10025 		 * It is illegal to swap in TSBs from a process other
10026 		 * than a process being swapped in.  This in turn
10027 		 * implies we do not have a valid MMU context here
10028 		 * since a process needs one to resolve translation
10029 		 * misses.
10030 		 */
10031 		ASSERT(curthread->t_procp->p_as->a_hat == sfmmup);
10032 	}
10033 
10034 #ifdef DEBUG
10035 	ASSERT(max_mmu_ctxdoms > 0);
10036 
10037 	/*
10038 	 * Process should have INVALID_CONTEXT on all MMUs
10039 	 */
10040 	for (i = 0; i < max_mmu_ctxdoms; i++) {
10041 
10042 		ASSERT(sfmmup->sfmmu_ctxs[i].cnum == INVALID_CONTEXT);
10043 	}
10044 #endif
10045 
10046 	new_tsbinfo->tsb_next = old_tsbinfo->tsb_next;
10047 	membar_stst();	/* strict ordering required */
10048 	if (prevtsb)
10049 		prevtsb->tsb_next = new_tsbinfo;
10050 	else
10051 		sfmmup->sfmmu_tsb = new_tsbinfo;
10052 	membar_enter();	/* make sure new TSB globally visible */
10053 
10054 	/*
10055 	 * We need to migrate TSB entries from the old TSB to the new TSB
10056 	 * if tsb_remap_ttes is set and the TSB is growing.
10057 	 */
10058 	if (tsb_remap_ttes && ((flags & TSB_GROW) == TSB_GROW))
10059 		sfmmu_copy_tsb(old_tsbinfo, new_tsbinfo);
10060 
10061 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
10062 
10063 	/*
10064 	 * Drop the HAT lock to free our old tsb_info.
10065 	 */
10066 	sfmmu_hat_exit(hatlockp);
10067 
10068 	if ((flags & TSB_GROW) == TSB_GROW) {
10069 		SFMMU_STAT(sf_tsb_grow);
10070 	} else if ((flags & TSB_SHRINK) == TSB_SHRINK) {
10071 		SFMMU_STAT(sf_tsb_shrink);
10072 	}
10073 
10074 	sfmmu_tsbinfo_free(old_tsbinfo);
10075 
10076 	(void) sfmmu_hat_enter(sfmmup);
10077 	return (TSB_SUCCESS);
10078 }
10079 
10080 /*
10081  * This function will re-program hat pgsz array, and invalidate the
10082  * process' context, forcing the process to switch to another
10083  * context on the next TLB miss, and therefore start using the
10084  * TLB that is reprogrammed for the new page sizes.
10085  */
10086 void
10087 sfmmu_reprog_pgsz_arr(sfmmu_t *sfmmup, uint8_t *tmp_pgsz)
10088 {
10089 	int i;
10090 	hatlock_t *hatlockp = NULL;
10091 
10092 	hatlockp = sfmmu_hat_enter(sfmmup);
10093 	/* USIII+-IV+ optimization, requires hat lock */
10094 	if (tmp_pgsz) {
10095 		for (i = 0; i < mmu_page_sizes; i++)
10096 			sfmmup->sfmmu_pgsz[i] = tmp_pgsz[i];
10097 	}
10098 	SFMMU_STAT(sf_tlb_reprog_pgsz);
10099 
10100 	sfmmu_invalidate_ctx(sfmmup);
10101 
10102 	sfmmu_hat_exit(hatlockp);
10103 }
10104 
10105 /*
10106  * The scd_rttecnt field in the SCD must be updated to take account of the
10107  * regions which it contains.
10108  */
10109 static void
10110 sfmmu_set_scd_rttecnt(sf_srd_t *srdp, sf_scd_t *scdp)
10111 {
10112 	uint_t rid;
10113 	uint_t i, j;
10114 	ulong_t w;
10115 	sf_region_t *rgnp;
10116 
10117 	ASSERT(srdp != NULL);
10118 
10119 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
10120 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
10121 			continue;
10122 		}
10123 
10124 		j = 0;
10125 		while (w) {
10126 			if (!(w & 0x1)) {
10127 				j++;
10128 				w >>= 1;
10129 				continue;
10130 			}
10131 			rid = (i << BT_ULSHIFT) | j;
10132 			j++;
10133 			w >>= 1;
10134 
10135 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
10136 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
10137 			rgnp = srdp->srd_hmergnp[rid];
10138 			ASSERT(rgnp->rgn_refcnt > 0);
10139 			ASSERT(rgnp->rgn_id == rid);
10140 
10141 			scdp->scd_rttecnt[rgnp->rgn_pgszc] +=
10142 			    rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
10143 
10144 			/*
10145 			 * Maintain the tsb0 inflation cnt for the regions
10146 			 * in the SCD.
10147 			 */
10148 			if (rgnp->rgn_pgszc >= TTE4M) {
10149 				scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt +=
10150 				    rgnp->rgn_size >>
10151 				    (TTE_PAGE_SHIFT(TTE8K) + 2);
10152 			}
10153 		}
10154 	}
10155 }
10156 
10157 /*
10158  * This function assumes that there are either four or six supported page
10159  * sizes and at most two programmable TLBs, so we need to decide which
10160  * page sizes are most important and then tell the MMU layer so it
10161  * can adjust the TLB page sizes accordingly (if supported).
10162  *
10163  * If these assumptions change, this function will need to be
10164  * updated to support whatever the new limits are.
10165  *
10166  * The growing flag is nonzero if we are growing the address space,
10167  * and zero if it is shrinking.  This allows us to decide whether
10168  * to grow or shrink our TSB, depending upon available memory
10169  * conditions.
10170  */
10171 static void
10172 sfmmu_check_page_sizes(sfmmu_t *sfmmup, int growing)
10173 {
10174 	uint64_t ttecnt[MMU_PAGE_SIZES];
10175 	uint64_t tte8k_cnt, tte4m_cnt;
10176 	uint8_t i;
10177 	int sectsb_thresh;
10178 
10179 	/*
10180 	 * Kernel threads, processes with small address spaces not using
10181 	 * large pages, and dummy ISM HATs need not apply.
10182 	 */
10183 	if (sfmmup == ksfmmup || sfmmup->sfmmu_ismhat != NULL)
10184 		return;
10185 
10186 	if (!SFMMU_LGPGS_INUSE(sfmmup) &&
10187 	    sfmmup->sfmmu_ttecnt[TTE8K] <= tsb_rss_factor)
10188 		return;
10189 
10190 	for (i = 0; i < mmu_page_sizes; i++) {
10191 		ttecnt[i] = sfmmup->sfmmu_ttecnt[i] +
10192 		    sfmmup->sfmmu_ismttecnt[i];
10193 	}
10194 
10195 	/* Check pagesizes in use, and possibly reprogram DTLB. */
10196 	if (&mmu_check_page_sizes)
10197 		mmu_check_page_sizes(sfmmup, ttecnt);
10198 
10199 	/*
10200 	 * Calculate the number of 8k ttes to represent the span of these
10201 	 * pages.
10202 	 */
10203 	tte8k_cnt = ttecnt[TTE8K] +
10204 	    (ttecnt[TTE64K] << (MMU_PAGESHIFT64K - MMU_PAGESHIFT)) +
10205 	    (ttecnt[TTE512K] << (MMU_PAGESHIFT512K - MMU_PAGESHIFT));
10206 	if (mmu_page_sizes == max_mmu_page_sizes) {
10207 		tte4m_cnt = ttecnt[TTE4M] +
10208 		    (ttecnt[TTE32M] << (MMU_PAGESHIFT32M - MMU_PAGESHIFT4M)) +
10209 		    (ttecnt[TTE256M] << (MMU_PAGESHIFT256M - MMU_PAGESHIFT4M));
10210 	} else {
10211 		tte4m_cnt = ttecnt[TTE4M];
10212 	}
10213 
10214 	/*
10215 	 * Inflate tte8k_cnt to allow for region large page allocation failure.
10216 	 */
10217 	tte8k_cnt += sfmmup->sfmmu_tsb0_4minflcnt;
10218 
10219 	/*
10220 	 * Inflate TSB sizes by a factor of 2 if this process
10221 	 * uses 4M text pages to minimize extra conflict misses
10222 	 * in the first TSB since without counting text pages
10223 	 * 8K TSB may become too small.
10224 	 *
10225 	 * Also double the size of the second TSB to minimize
10226 	 * extra conflict misses due to competition between 4M text pages
10227 	 * and data pages.
10228 	 *
10229 	 * We need to adjust the second TSB allocation threshold by the
10230 	 * inflation factor, since there is no point in creating a second
10231 	 * TSB when we know all the mappings can fit in the I/D TLBs.
10232 	 */
10233 	sectsb_thresh = tsb_sectsb_threshold;
10234 	if (sfmmup->sfmmu_flags & HAT_4MTEXT_FLAG) {
10235 		tte8k_cnt <<= 1;
10236 		tte4m_cnt <<= 1;
10237 		sectsb_thresh <<= 1;
10238 	}
10239 
10240 	/*
10241 	 * Check to see if our TSB is the right size; we may need to
10242 	 * grow or shrink it.  If the process is small, our work is
10243 	 * finished at this point.
10244 	 */
10245 	if (tte8k_cnt <= tsb_rss_factor && tte4m_cnt <= sectsb_thresh) {
10246 		return;
10247 	}
10248 	sfmmu_size_tsb(sfmmup, growing, tte8k_cnt, tte4m_cnt, sectsb_thresh);
10249 }
10250 
10251 static void
10252 sfmmu_size_tsb(sfmmu_t *sfmmup, int growing, uint64_t tte8k_cnt,
10253 	uint64_t tte4m_cnt, int sectsb_thresh)
10254 {
10255 	int tsb_bits;
10256 	uint_t tsb_szc;
10257 	struct tsb_info *tsbinfop;
10258 	hatlock_t *hatlockp = NULL;
10259 
10260 	hatlockp = sfmmu_hat_enter(sfmmup);
10261 	ASSERT(hatlockp != NULL);
10262 	tsbinfop = sfmmup->sfmmu_tsb;
10263 	ASSERT(tsbinfop != NULL);
10264 
10265 	/*
10266 	 * If we're growing, select the size based on RSS.  If we're
10267 	 * shrinking, leave some room so we don't have to turn around and
10268 	 * grow again immediately.
10269 	 */
10270 	if (growing)
10271 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
10272 	else
10273 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt << 1);
10274 
10275 	if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10276 	    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10277 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10278 		    hatlockp, TSB_SHRINK);
10279 	} else if (growing && tsb_szc > tsbinfop->tsb_szc && TSB_OK_GROW()) {
10280 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10281 		    hatlockp, TSB_GROW);
10282 	}
10283 	tsbinfop = sfmmup->sfmmu_tsb;
10284 
10285 	/*
10286 	 * With the TLB and first TSB out of the way, we need to see if
10287 	 * we need a second TSB for 4M pages.  If we managed to reprogram
10288 	 * the TLB page sizes above, the process will start using this new
10289 	 * TSB right away; otherwise, it will start using it on the next
10290 	 * context switch.  Either way, it's no big deal so there's no
10291 	 * synchronization with the trap handlers here unless we grow the
10292 	 * TSB (in which case it's required to prevent using the old one
10293 	 * after it's freed). Note: second tsb is required for 32M/256M
10294 	 * page sizes.
10295 	 */
10296 	if (tte4m_cnt > sectsb_thresh) {
10297 		/*
10298 		 * If we're growing, select the size based on RSS.  If we're
10299 		 * shrinking, leave some room so we don't have to turn
10300 		 * around and grow again immediately.
10301 		 */
10302 		if (growing)
10303 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
10304 		else
10305 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt << 1);
10306 		if (tsbinfop->tsb_next == NULL) {
10307 			struct tsb_info *newtsb;
10308 			int allocflags = SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)?
10309 			    0 : TSB_ALLOC;
10310 
10311 			sfmmu_hat_exit(hatlockp);
10312 
10313 			/*
10314 			 * Try to allocate a TSB for 4[32|256]M pages.  If we
10315 			 * can't get the size we want, retry w/a minimum sized
10316 			 * TSB.  If that still didn't work, give up; we can
10317 			 * still run without one.
10318 			 */
10319 			tsb_bits = (mmu_page_sizes == max_mmu_page_sizes)?
10320 			    TSB4M|TSB32M|TSB256M:TSB4M;
10321 			if ((sfmmu_tsbinfo_alloc(&newtsb, tsb_szc, tsb_bits,
10322 			    allocflags, sfmmup)) &&
10323 			    (tsb_szc <= TSB_4M_SZCODE ||
10324 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
10325 			    tsb_bits, allocflags, sfmmup)) &&
10326 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_MIN_SZCODE,
10327 			    tsb_bits, allocflags, sfmmup)) {
10328 				return;
10329 			}
10330 
10331 			hatlockp = sfmmu_hat_enter(sfmmup);
10332 
10333 			sfmmu_invalidate_ctx(sfmmup);
10334 
10335 			if (sfmmup->sfmmu_tsb->tsb_next == NULL) {
10336 				sfmmup->sfmmu_tsb->tsb_next = newtsb;
10337 				SFMMU_STAT(sf_tsb_sectsb_create);
10338 				sfmmu_hat_exit(hatlockp);
10339 				return;
10340 			} else {
10341 				/*
10342 				 * It's annoying, but possible for us
10343 				 * to get here.. we dropped the HAT lock
10344 				 * because of locking order in the kmem
10345 				 * allocator, and while we were off getting
10346 				 * our memory, some other thread decided to
10347 				 * do us a favor and won the race to get a
10348 				 * second TSB for this process.  Sigh.
10349 				 */
10350 				sfmmu_hat_exit(hatlockp);
10351 				sfmmu_tsbinfo_free(newtsb);
10352 				return;
10353 			}
10354 		}
10355 
10356 		/*
10357 		 * We have a second TSB, see if it's big enough.
10358 		 */
10359 		tsbinfop = tsbinfop->tsb_next;
10360 
10361 		/*
10362 		 * Check to see if our second TSB is the right size;
10363 		 * we may need to grow or shrink it.
10364 		 * To prevent thrashing (e.g. growing the TSB on a
10365 		 * subsequent map operation), only try to shrink if
10366 		 * the TSB reach exceeds twice the virtual address
10367 		 * space size.
10368 		 */
10369 		if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10370 		    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10371 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10372 			    tsb_szc, hatlockp, TSB_SHRINK);
10373 		} else if (growing && tsb_szc > tsbinfop->tsb_szc &&
10374 		    TSB_OK_GROW()) {
10375 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10376 			    tsb_szc, hatlockp, TSB_GROW);
10377 		}
10378 	}
10379 
10380 	sfmmu_hat_exit(hatlockp);
10381 }
10382 
10383 /*
10384  * Free up a sfmmu
10385  * Since the sfmmu is currently embedded in the hat struct we simply zero
10386  * out our fields and free up the ism map blk list if any.
10387  */
10388 static void
10389 sfmmu_free_sfmmu(sfmmu_t *sfmmup)
10390 {
10391 	ism_blk_t	*blkp, *nx_blkp;
10392 #ifdef	DEBUG
10393 	ism_map_t	*map;
10394 	int 		i;
10395 #endif
10396 
10397 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
10398 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
10399 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
10400 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
10401 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
10402 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
10403 	ASSERT(SF_RGNMAP_ISNULL(sfmmup));
10404 
10405 	sfmmup->sfmmu_free = 0;
10406 	sfmmup->sfmmu_ismhat = 0;
10407 
10408 	blkp = sfmmup->sfmmu_iblk;
10409 	sfmmup->sfmmu_iblk = NULL;
10410 
10411 	while (blkp) {
10412 #ifdef	DEBUG
10413 		map = blkp->iblk_maps;
10414 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
10415 			ASSERT(map[i].imap_seg == 0);
10416 			ASSERT(map[i].imap_ismhat == NULL);
10417 			ASSERT(map[i].imap_ment == NULL);
10418 		}
10419 #endif
10420 		nx_blkp = blkp->iblk_next;
10421 		blkp->iblk_next = NULL;
10422 		blkp->iblk_nextpa = (uint64_t)-1;
10423 		kmem_cache_free(ism_blk_cache, blkp);
10424 		blkp = nx_blkp;
10425 	}
10426 }
10427 
10428 /*
10429  * Locking primitves accessed by HATLOCK macros
10430  */
10431 
10432 #define	SFMMU_SPL_MTX	(0x0)
10433 #define	SFMMU_ML_MTX	(0x1)
10434 
10435 #define	SFMMU_MLSPL_MTX(type, pg)	(((type) == SFMMU_SPL_MTX) ? \
10436 					    SPL_HASH(pg) : MLIST_HASH(pg))
10437 
10438 kmutex_t *
10439 sfmmu_page_enter(struct page *pp)
10440 {
10441 	return (sfmmu_mlspl_enter(pp, SFMMU_SPL_MTX));
10442 }
10443 
10444 void
10445 sfmmu_page_exit(kmutex_t *spl)
10446 {
10447 	mutex_exit(spl);
10448 }
10449 
10450 int
10451 sfmmu_page_spl_held(struct page *pp)
10452 {
10453 	return (sfmmu_mlspl_held(pp, SFMMU_SPL_MTX));
10454 }
10455 
10456 kmutex_t *
10457 sfmmu_mlist_enter(struct page *pp)
10458 {
10459 	return (sfmmu_mlspl_enter(pp, SFMMU_ML_MTX));
10460 }
10461 
10462 void
10463 sfmmu_mlist_exit(kmutex_t *mml)
10464 {
10465 	mutex_exit(mml);
10466 }
10467 
10468 int
10469 sfmmu_mlist_held(struct page *pp)
10470 {
10471 
10472 	return (sfmmu_mlspl_held(pp, SFMMU_ML_MTX));
10473 }
10474 
10475 /*
10476  * Common code for sfmmu_mlist_enter() and sfmmu_page_enter().  For
10477  * sfmmu_mlist_enter() case mml_table lock array is used and for
10478  * sfmmu_page_enter() sfmmu_page_lock lock array is used.
10479  *
10480  * The lock is taken on a root page so that it protects an operation on all
10481  * constituent pages of a large page pp belongs to.
10482  *
10483  * The routine takes a lock from the appropriate array. The lock is determined
10484  * by hashing the root page. After taking the lock this routine checks if the
10485  * root page has the same size code that was used to determine the root (i.e
10486  * that root hasn't changed).  If root page has the expected p_szc field we
10487  * have the right lock and it's returned to the caller. If root's p_szc
10488  * decreased we release the lock and retry from the beginning.  This case can
10489  * happen due to hat_page_demote() decreasing p_szc between our load of p_szc
10490  * value and taking the lock. The number of retries due to p_szc decrease is
10491  * limited by the maximum p_szc value. If p_szc is 0 we return the lock
10492  * determined by hashing pp itself.
10493  *
10494  * If our caller doesn't hold a SE_SHARED or SE_EXCL lock on pp it's also
10495  * possible that p_szc can increase. To increase p_szc a thread has to lock
10496  * all constituent pages EXCL and do hat_pageunload() on all of them. All the
10497  * callers that don't hold a page locked recheck if hmeblk through which pp
10498  * was found still maps this pp.  If it doesn't map it anymore returned lock
10499  * is immediately dropped. Therefore if sfmmu_mlspl_enter() hits the case of
10500  * p_szc increase after taking the lock it returns this lock without further
10501  * retries because in this case the caller doesn't care about which lock was
10502  * taken. The caller will drop it right away.
10503  *
10504  * After the routine returns it's guaranteed that hat_page_demote() can't
10505  * change p_szc field of any of constituent pages of a large page pp belongs
10506  * to as long as pp was either locked at least SHARED prior to this call or
10507  * the caller finds that hment that pointed to this pp still references this
10508  * pp (this also assumes that the caller holds hme hash bucket lock so that
10509  * the same pp can't be remapped into the same hmeblk after it was unmapped by
10510  * hat_pageunload()).
10511  */
10512 static kmutex_t *
10513 sfmmu_mlspl_enter(struct page *pp, int type)
10514 {
10515 	kmutex_t	*mtx;
10516 	uint_t		prev_rszc = UINT_MAX;
10517 	page_t		*rootpp;
10518 	uint_t		szc;
10519 	uint_t		rszc;
10520 	uint_t		pszc = pp->p_szc;
10521 
10522 	ASSERT(pp != NULL);
10523 
10524 again:
10525 	if (pszc == 0) {
10526 		mtx = SFMMU_MLSPL_MTX(type, pp);
10527 		mutex_enter(mtx);
10528 		return (mtx);
10529 	}
10530 
10531 	/* The lock lives in the root page */
10532 	rootpp = PP_GROUPLEADER(pp, pszc);
10533 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10534 	mutex_enter(mtx);
10535 
10536 	/*
10537 	 * Return mml in the following 3 cases:
10538 	 *
10539 	 * 1) If pp itself is root since if its p_szc decreased before we took
10540 	 * the lock pp is still the root of smaller szc page. And if its p_szc
10541 	 * increased it doesn't matter what lock we return (see comment in
10542 	 * front of this routine).
10543 	 *
10544 	 * 2) If pp's not root but rootpp is the root of a rootpp->p_szc size
10545 	 * large page we have the right lock since any previous potential
10546 	 * hat_page_demote() is done demoting from greater than current root's
10547 	 * p_szc because hat_page_demote() changes root's p_szc last. No
10548 	 * further hat_page_demote() can start or be in progress since it
10549 	 * would need the same lock we currently hold.
10550 	 *
10551 	 * 3) If rootpp's p_szc increased since previous iteration it doesn't
10552 	 * matter what lock we return (see comment in front of this routine).
10553 	 */
10554 	if (pp == rootpp || (rszc = rootpp->p_szc) == pszc ||
10555 	    rszc >= prev_rszc) {
10556 		return (mtx);
10557 	}
10558 
10559 	/*
10560 	 * hat_page_demote() could have decreased root's p_szc.
10561 	 * In this case pp's p_szc must also be smaller than pszc.
10562 	 * Retry.
10563 	 */
10564 	if (rszc < pszc) {
10565 		szc = pp->p_szc;
10566 		if (szc < pszc) {
10567 			mutex_exit(mtx);
10568 			pszc = szc;
10569 			goto again;
10570 		}
10571 		/*
10572 		 * pp's p_szc increased after it was decreased.
10573 		 * page cannot be mapped. Return current lock. The caller
10574 		 * will drop it right away.
10575 		 */
10576 		return (mtx);
10577 	}
10578 
10579 	/*
10580 	 * root's p_szc is greater than pp's p_szc.
10581 	 * hat_page_demote() is not done with all pages
10582 	 * yet. Wait for it to complete.
10583 	 */
10584 	mutex_exit(mtx);
10585 	rootpp = PP_GROUPLEADER(rootpp, rszc);
10586 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10587 	mutex_enter(mtx);
10588 	mutex_exit(mtx);
10589 	prev_rszc = rszc;
10590 	goto again;
10591 }
10592 
10593 static int
10594 sfmmu_mlspl_held(struct page *pp, int type)
10595 {
10596 	kmutex_t	*mtx;
10597 
10598 	ASSERT(pp != NULL);
10599 	/* The lock lives in the root page */
10600 	pp = PP_PAGEROOT(pp);
10601 	ASSERT(pp != NULL);
10602 
10603 	mtx = SFMMU_MLSPL_MTX(type, pp);
10604 	return (MUTEX_HELD(mtx));
10605 }
10606 
10607 static uint_t
10608 sfmmu_get_free_hblk(struct hme_blk **hmeblkpp, uint_t critical)
10609 {
10610 	struct  hme_blk *hblkp;
10611 
10612 
10613 	if (freehblkp != NULL) {
10614 		mutex_enter(&freehblkp_lock);
10615 		if (freehblkp != NULL) {
10616 			/*
10617 			 * If the current thread is owning hblk_reserve OR
10618 			 * critical request from sfmmu_hblk_steal()
10619 			 * let it succeed even if freehblkcnt is really low.
10620 			 */
10621 			if (freehblkcnt <= HBLK_RESERVE_MIN && !critical) {
10622 				SFMMU_STAT(sf_get_free_throttle);
10623 				mutex_exit(&freehblkp_lock);
10624 				return (0);
10625 			}
10626 			freehblkcnt--;
10627 			*hmeblkpp = freehblkp;
10628 			hblkp = *hmeblkpp;
10629 			freehblkp = hblkp->hblk_next;
10630 			mutex_exit(&freehblkp_lock);
10631 			hblkp->hblk_next = NULL;
10632 			SFMMU_STAT(sf_get_free_success);
10633 
10634 			ASSERT(hblkp->hblk_hmecnt == 0);
10635 			ASSERT(hblkp->hblk_vcnt == 0);
10636 			ASSERT(hblkp->hblk_nextpa == va_to_pa((caddr_t)hblkp));
10637 
10638 			return (1);
10639 		}
10640 		mutex_exit(&freehblkp_lock);
10641 	}
10642 
10643 	/* Check cpu hblk pending queues */
10644 	if ((*hmeblkpp = sfmmu_check_pending_hblks(TTE8K)) != NULL) {
10645 		hblkp = *hmeblkpp;
10646 		hblkp->hblk_next = NULL;
10647 		hblkp->hblk_nextpa = va_to_pa((caddr_t)hblkp);
10648 
10649 		ASSERT(hblkp->hblk_hmecnt == 0);
10650 		ASSERT(hblkp->hblk_vcnt == 0);
10651 
10652 		return (1);
10653 	}
10654 
10655 	SFMMU_STAT(sf_get_free_fail);
10656 	return (0);
10657 }
10658 
10659 static uint_t
10660 sfmmu_put_free_hblk(struct hme_blk *hmeblkp, uint_t critical)
10661 {
10662 	struct  hme_blk *hblkp;
10663 
10664 	ASSERT(hmeblkp->hblk_hmecnt == 0);
10665 	ASSERT(hmeblkp->hblk_vcnt == 0);
10666 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
10667 
10668 	/*
10669 	 * If the current thread is mapping into kernel space,
10670 	 * let it succede even if freehblkcnt is max
10671 	 * so that it will avoid freeing it to kmem.
10672 	 * This will prevent stack overflow due to
10673 	 * possible recursion since kmem_cache_free()
10674 	 * might require creation of a slab which
10675 	 * in turn needs an hmeblk to map that slab;
10676 	 * let's break this vicious chain at the first
10677 	 * opportunity.
10678 	 */
10679 	if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10680 		mutex_enter(&freehblkp_lock);
10681 		if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10682 			SFMMU_STAT(sf_put_free_success);
10683 			freehblkcnt++;
10684 			hmeblkp->hblk_next = freehblkp;
10685 			freehblkp = hmeblkp;
10686 			mutex_exit(&freehblkp_lock);
10687 			return (1);
10688 		}
10689 		mutex_exit(&freehblkp_lock);
10690 	}
10691 
10692 	/*
10693 	 * Bring down freehblkcnt to HBLK_RESERVE_CNT. We are here
10694 	 * only if freehblkcnt is at least HBLK_RESERVE_CNT *and*
10695 	 * we are not in the process of mapping into kernel space.
10696 	 */
10697 	ASSERT(!critical);
10698 	while (freehblkcnt > HBLK_RESERVE_CNT) {
10699 		mutex_enter(&freehblkp_lock);
10700 		if (freehblkcnt > HBLK_RESERVE_CNT) {
10701 			freehblkcnt--;
10702 			hblkp = freehblkp;
10703 			freehblkp = hblkp->hblk_next;
10704 			mutex_exit(&freehblkp_lock);
10705 			ASSERT(get_hblk_cache(hblkp) == sfmmu8_cache);
10706 			kmem_cache_free(sfmmu8_cache, hblkp);
10707 			continue;
10708 		}
10709 		mutex_exit(&freehblkp_lock);
10710 	}
10711 	SFMMU_STAT(sf_put_free_fail);
10712 	return (0);
10713 }
10714 
10715 static void
10716 sfmmu_hblk_swap(struct hme_blk *new)
10717 {
10718 	struct hme_blk *old, *hblkp, *prev;
10719 	uint64_t newpa;
10720 	caddr_t	base, vaddr, endaddr;
10721 	struct hmehash_bucket *hmebp;
10722 	struct sf_hment *osfhme, *nsfhme;
10723 	page_t *pp;
10724 	kmutex_t *pml;
10725 	tte_t tte;
10726 	struct hme_blk *list = NULL;
10727 
10728 #ifdef	DEBUG
10729 	hmeblk_tag		hblktag;
10730 	struct hme_blk		*found;
10731 #endif
10732 	old = HBLK_RESERVE;
10733 	ASSERT(!old->hblk_shared);
10734 
10735 	/*
10736 	 * save pa before bcopy clobbers it
10737 	 */
10738 	newpa = new->hblk_nextpa;
10739 
10740 	base = (caddr_t)get_hblk_base(old);
10741 	endaddr = base + get_hblk_span(old);
10742 
10743 	/*
10744 	 * acquire hash bucket lock.
10745 	 */
10746 	hmebp = sfmmu_tteload_acquire_hashbucket(ksfmmup, base, TTE8K,
10747 	    SFMMU_INVALID_SHMERID);
10748 
10749 	/*
10750 	 * copy contents from old to new
10751 	 */
10752 	bcopy((void *)old, (void *)new, HME8BLK_SZ);
10753 
10754 	/*
10755 	 * add new to hash chain
10756 	 */
10757 	sfmmu_hblk_hash_add(hmebp, new, newpa);
10758 
10759 	/*
10760 	 * search hash chain for hblk_reserve; this needs to be performed
10761 	 * after adding new, otherwise prev won't correspond to the hblk which
10762 	 * is prior to old in hash chain when we call sfmmu_hblk_hash_rm to
10763 	 * remove old later.
10764 	 */
10765 	for (prev = NULL,
10766 	    hblkp = hmebp->hmeblkp; hblkp != NULL && hblkp != old;
10767 	    prev = hblkp, hblkp = hblkp->hblk_next)
10768 		;
10769 
10770 	if (hblkp != old)
10771 		panic("sfmmu_hblk_swap: hblk_reserve not found");
10772 
10773 	/*
10774 	 * p_mapping list is still pointing to hments in hblk_reserve;
10775 	 * fix up p_mapping list so that they point to hments in new.
10776 	 *
10777 	 * Since all these mappings are created by hblk_reserve_thread
10778 	 * on the way and it's using at least one of the buffers from each of
10779 	 * the newly minted slabs, there is no danger of any of these
10780 	 * mappings getting unloaded by another thread.
10781 	 *
10782 	 * tsbmiss could only modify ref/mod bits of hments in old/new.
10783 	 * Since all of these hments hold mappings established by segkmem
10784 	 * and mappings in segkmem are setup with HAT_NOSYNC, ref/mod bits
10785 	 * have no meaning for the mappings in hblk_reserve.  hments in
10786 	 * old and new are identical except for ref/mod bits.
10787 	 */
10788 	for (vaddr = base; vaddr < endaddr; vaddr += TTEBYTES(TTE8K)) {
10789 
10790 		HBLKTOHME(osfhme, old, vaddr);
10791 		sfmmu_copytte(&osfhme->hme_tte, &tte);
10792 
10793 		if (TTE_IS_VALID(&tte)) {
10794 			if ((pp = osfhme->hme_page) == NULL)
10795 				panic("sfmmu_hblk_swap: page not mapped");
10796 
10797 			pml = sfmmu_mlist_enter(pp);
10798 
10799 			if (pp != osfhme->hme_page)
10800 				panic("sfmmu_hblk_swap: mapping changed");
10801 
10802 			HBLKTOHME(nsfhme, new, vaddr);
10803 
10804 			HME_ADD(nsfhme, pp);
10805 			HME_SUB(osfhme, pp);
10806 
10807 			sfmmu_mlist_exit(pml);
10808 		}
10809 	}
10810 
10811 	/*
10812 	 * remove old from hash chain
10813 	 */
10814 	sfmmu_hblk_hash_rm(hmebp, old, prev, &list, 1);
10815 
10816 #ifdef	DEBUG
10817 
10818 	hblktag.htag_id = ksfmmup;
10819 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
10820 	hblktag.htag_bspage = HME_HASH_BSPAGE(base, HME_HASH_SHIFT(TTE8K));
10821 	hblktag.htag_rehash = HME_HASH_REHASH(TTE8K);
10822 	HME_HASH_FAST_SEARCH(hmebp, hblktag, found);
10823 
10824 	if (found != new)
10825 		panic("sfmmu_hblk_swap: new hblk not found");
10826 #endif
10827 
10828 	SFMMU_HASH_UNLOCK(hmebp);
10829 
10830 	/*
10831 	 * Reset hblk_reserve
10832 	 */
10833 	bzero((void *)old, HME8BLK_SZ);
10834 	old->hblk_nextpa = va_to_pa((caddr_t)old);
10835 }
10836 
10837 /*
10838  * Grab the mlist mutex for both pages passed in.
10839  *
10840  * low and high will be returned as pointers to the mutexes for these pages.
10841  * low refers to the mutex residing in the lower bin of the mlist hash, while
10842  * high refers to the mutex residing in the higher bin of the mlist hash.  This
10843  * is due to the locking order restrictions on the same thread grabbing
10844  * multiple mlist mutexes.  The low lock must be acquired before the high lock.
10845  *
10846  * If both pages hash to the same mutex, only grab that single mutex, and
10847  * high will be returned as NULL
10848  * If the pages hash to different bins in the hash, grab the lower addressed
10849  * lock first and then the higher addressed lock in order to follow the locking
10850  * rules involved with the same thread grabbing multiple mlist mutexes.
10851  * low and high will both have non-NULL values.
10852  */
10853 static void
10854 sfmmu_mlist_reloc_enter(struct page *targ, struct page *repl,
10855     kmutex_t **low, kmutex_t **high)
10856 {
10857 	kmutex_t	*mml_targ, *mml_repl;
10858 
10859 	/*
10860 	 * no need to do the dance around szc as in sfmmu_mlist_enter()
10861 	 * because this routine is only called by hat_page_relocate() and all
10862 	 * targ and repl pages are already locked EXCL so szc can't change.
10863 	 */
10864 
10865 	mml_targ = MLIST_HASH(PP_PAGEROOT(targ));
10866 	mml_repl = MLIST_HASH(PP_PAGEROOT(repl));
10867 
10868 	if (mml_targ == mml_repl) {
10869 		*low = mml_targ;
10870 		*high = NULL;
10871 	} else {
10872 		if (mml_targ < mml_repl) {
10873 			*low = mml_targ;
10874 			*high = mml_repl;
10875 		} else {
10876 			*low = mml_repl;
10877 			*high = mml_targ;
10878 		}
10879 	}
10880 
10881 	mutex_enter(*low);
10882 	if (*high)
10883 		mutex_enter(*high);
10884 }
10885 
10886 static void
10887 sfmmu_mlist_reloc_exit(kmutex_t *low, kmutex_t *high)
10888 {
10889 	if (high)
10890 		mutex_exit(high);
10891 	mutex_exit(low);
10892 }
10893 
10894 static hatlock_t *
10895 sfmmu_hat_enter(sfmmu_t *sfmmup)
10896 {
10897 	hatlock_t	*hatlockp;
10898 
10899 	if (sfmmup != ksfmmup) {
10900 		hatlockp = TSB_HASH(sfmmup);
10901 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
10902 		return (hatlockp);
10903 	}
10904 	return (NULL);
10905 }
10906 
10907 static hatlock_t *
10908 sfmmu_hat_tryenter(sfmmu_t *sfmmup)
10909 {
10910 	hatlock_t	*hatlockp;
10911 
10912 	if (sfmmup != ksfmmup) {
10913 		hatlockp = TSB_HASH(sfmmup);
10914 		if (mutex_tryenter(HATLOCK_MUTEXP(hatlockp)) == 0)
10915 			return (NULL);
10916 		return (hatlockp);
10917 	}
10918 	return (NULL);
10919 }
10920 
10921 static void
10922 sfmmu_hat_exit(hatlock_t *hatlockp)
10923 {
10924 	if (hatlockp != NULL)
10925 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
10926 }
10927 
10928 static void
10929 sfmmu_hat_lock_all(void)
10930 {
10931 	int i;
10932 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
10933 		mutex_enter(HATLOCK_MUTEXP(&hat_lock[i]));
10934 }
10935 
10936 static void
10937 sfmmu_hat_unlock_all(void)
10938 {
10939 	int i;
10940 	for (i = SFMMU_NUM_LOCK - 1; i >= 0; i--)
10941 		mutex_exit(HATLOCK_MUTEXP(&hat_lock[i]));
10942 }
10943 
10944 int
10945 sfmmu_hat_lock_held(sfmmu_t *sfmmup)
10946 {
10947 	ASSERT(sfmmup != ksfmmup);
10948 	return (MUTEX_HELD(HATLOCK_MUTEXP(TSB_HASH(sfmmup))));
10949 }
10950 
10951 /*
10952  * Locking primitives to provide consistency between ISM unmap
10953  * and other operations.  Since ISM unmap can take a long time, we
10954  * use HAT_ISMBUSY flag (protected by the hatlock) to avoid creating
10955  * contention on the hatlock buckets while ISM segments are being
10956  * unmapped.  The tradeoff is that the flags don't prevent priority
10957  * inversion from occurring, so we must request kernel priority in
10958  * case we have to sleep to keep from getting buried while holding
10959  * the HAT_ISMBUSY flag set, which in turn could block other kernel
10960  * threads from running (for example, in sfmmu_uvatopfn()).
10961  */
10962 static void
10963 sfmmu_ismhat_enter(sfmmu_t *sfmmup, int hatlock_held)
10964 {
10965 	hatlock_t *hatlockp;
10966 
10967 	THREAD_KPRI_REQUEST();
10968 	if (!hatlock_held)
10969 		hatlockp = sfmmu_hat_enter(sfmmup);
10970 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY))
10971 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
10972 	SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
10973 	if (!hatlock_held)
10974 		sfmmu_hat_exit(hatlockp);
10975 }
10976 
10977 static void
10978 sfmmu_ismhat_exit(sfmmu_t *sfmmup, int hatlock_held)
10979 {
10980 	hatlock_t *hatlockp;
10981 
10982 	if (!hatlock_held)
10983 		hatlockp = sfmmu_hat_enter(sfmmup);
10984 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
10985 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
10986 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
10987 	if (!hatlock_held)
10988 		sfmmu_hat_exit(hatlockp);
10989 	THREAD_KPRI_RELEASE();
10990 }
10991 
10992 /*
10993  *
10994  * Algorithm:
10995  *
10996  * (1) if segkmem is not ready, allocate hblk from an array of pre-alloc'ed
10997  *	hblks.
10998  *
10999  * (2) if we are allocating an hblk for mapping a slab in sfmmu_cache,
11000  *
11001  * 		(a) try to return an hblk from reserve pool of free hblks;
11002  *		(b) if the reserve pool is empty, acquire hblk_reserve_lock
11003  *		    and return hblk_reserve.
11004  *
11005  * (3) call kmem_cache_alloc() to allocate hblk;
11006  *
11007  *		(a) if hblk_reserve_lock is held by the current thread,
11008  *		    atomically replace hblk_reserve by the hblk that is
11009  *		    returned by kmem_cache_alloc; release hblk_reserve_lock
11010  *		    and call kmem_cache_alloc() again.
11011  *		(b) if reserve pool is not full, add the hblk that is
11012  *		    returned by kmem_cache_alloc to reserve pool and
11013  *		    call kmem_cache_alloc again.
11014  *
11015  */
11016 static struct hme_blk *
11017 sfmmu_hblk_alloc(sfmmu_t *sfmmup, caddr_t vaddr,
11018 	struct hmehash_bucket *hmebp, uint_t size, hmeblk_tag hblktag,
11019 	uint_t flags, uint_t rid)
11020 {
11021 	struct hme_blk *hmeblkp = NULL;
11022 	struct hme_blk *newhblkp;
11023 	struct hme_blk *shw_hblkp = NULL;
11024 	struct kmem_cache *sfmmu_cache = NULL;
11025 	uint64_t hblkpa;
11026 	ulong_t index;
11027 	uint_t owner;		/* set to 1 if using hblk_reserve */
11028 	uint_t forcefree;
11029 	int sleep;
11030 	sf_srd_t *srdp;
11031 	sf_region_t *rgnp;
11032 
11033 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11034 	ASSERT(hblktag.htag_rid == rid);
11035 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
11036 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11037 	    IS_P2ALIGNED(vaddr, TTEBYTES(size)));
11038 
11039 	/*
11040 	 * If segkmem is not created yet, allocate from static hmeblks
11041 	 * created at the end of startup_modules().  See the block comment
11042 	 * in startup_modules() describing how we estimate the number of
11043 	 * static hmeblks that will be needed during re-map.
11044 	 */
11045 	if (!hblk_alloc_dynamic) {
11046 
11047 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11048 
11049 		if (size == TTE8K) {
11050 			index = nucleus_hblk8.index;
11051 			if (index >= nucleus_hblk8.len) {
11052 				/*
11053 				 * If we panic here, see startup_modules() to
11054 				 * make sure that we are calculating the
11055 				 * number of hblk8's that we need correctly.
11056 				 */
11057 				prom_panic("no nucleus hblk8 to allocate");
11058 			}
11059 			hmeblkp =
11060 			    (struct hme_blk *)&nucleus_hblk8.list[index];
11061 			nucleus_hblk8.index++;
11062 			SFMMU_STAT(sf_hblk8_nalloc);
11063 		} else {
11064 			index = nucleus_hblk1.index;
11065 			if (nucleus_hblk1.index >= nucleus_hblk1.len) {
11066 				/*
11067 				 * If we panic here, see startup_modules().
11068 				 * Most likely you need to update the
11069 				 * calculation of the number of hblk1 elements
11070 				 * that the kernel needs to boot.
11071 				 */
11072 				prom_panic("no nucleus hblk1 to allocate");
11073 			}
11074 			hmeblkp =
11075 			    (struct hme_blk *)&nucleus_hblk1.list[index];
11076 			nucleus_hblk1.index++;
11077 			SFMMU_STAT(sf_hblk1_nalloc);
11078 		}
11079 
11080 		goto hblk_init;
11081 	}
11082 
11083 	SFMMU_HASH_UNLOCK(hmebp);
11084 
11085 	if (sfmmup != KHATID && !SFMMU_IS_SHMERID_VALID(rid)) {
11086 		if (mmu_page_sizes == max_mmu_page_sizes) {
11087 			if (size < TTE256M)
11088 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11089 				    size, flags);
11090 		} else {
11091 			if (size < TTE4M)
11092 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11093 				    size, flags);
11094 		}
11095 	} else if (SFMMU_IS_SHMERID_VALID(rid)) {
11096 		/*
11097 		 * Shared hmes use per region bitmaps in rgn_hmeflag
11098 		 * rather than shadow hmeblks to keep track of the
11099 		 * mapping sizes which have been allocated for the region.
11100 		 * Here we cleanup old invalid hmeblks with this rid,
11101 		 * which may be left around by pageunload().
11102 		 */
11103 		int ttesz;
11104 		caddr_t va;
11105 		caddr_t	eva = vaddr + TTEBYTES(size);
11106 
11107 		ASSERT(sfmmup != KHATID);
11108 
11109 		srdp = sfmmup->sfmmu_srdp;
11110 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11111 		rgnp = srdp->srd_hmergnp[rid];
11112 		ASSERT(rgnp != NULL && rgnp->rgn_id == rid);
11113 		ASSERT(rgnp->rgn_refcnt != 0);
11114 		ASSERT(size <= rgnp->rgn_pgszc);
11115 
11116 		ttesz = HBLK_MIN_TTESZ;
11117 		do {
11118 			if (!(rgnp->rgn_hmeflags & (0x1 << ttesz))) {
11119 				continue;
11120 			}
11121 
11122 			if (ttesz > size && ttesz != HBLK_MIN_TTESZ) {
11123 				sfmmu_cleanup_rhblk(srdp, vaddr, rid, ttesz);
11124 			} else if (ttesz < size) {
11125 				for (va = vaddr; va < eva;
11126 				    va += TTEBYTES(ttesz)) {
11127 					sfmmu_cleanup_rhblk(srdp, va, rid,
11128 					    ttesz);
11129 				}
11130 			}
11131 		} while (++ttesz <= rgnp->rgn_pgszc);
11132 	}
11133 
11134 fill_hblk:
11135 	owner = (hblk_reserve_thread == curthread) ? 1 : 0;
11136 
11137 	if (owner && size == TTE8K) {
11138 
11139 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11140 		/*
11141 		 * We are really in a tight spot. We already own
11142 		 * hblk_reserve and we need another hblk.  In anticipation
11143 		 * of this kind of scenario, we specifically set aside
11144 		 * HBLK_RESERVE_MIN number of hblks to be used exclusively
11145 		 * by owner of hblk_reserve.
11146 		 */
11147 		SFMMU_STAT(sf_hblk_recurse_cnt);
11148 
11149 		if (!sfmmu_get_free_hblk(&hmeblkp, 1))
11150 			panic("sfmmu_hblk_alloc: reserve list is empty");
11151 
11152 		goto hblk_verify;
11153 	}
11154 
11155 	ASSERT(!owner);
11156 
11157 	if ((flags & HAT_NO_KALLOC) == 0) {
11158 
11159 		sfmmu_cache = ((size == TTE8K) ? sfmmu8_cache : sfmmu1_cache);
11160 		sleep = ((sfmmup == KHATID) ? KM_NOSLEEP : KM_SLEEP);
11161 
11162 		if ((hmeblkp = kmem_cache_alloc(sfmmu_cache, sleep)) == NULL) {
11163 			hmeblkp = sfmmu_hblk_steal(size);
11164 		} else {
11165 			/*
11166 			 * if we are the owner of hblk_reserve,
11167 			 * swap hblk_reserve with hmeblkp and
11168 			 * start a fresh life.  Hope things go
11169 			 * better this time.
11170 			 */
11171 			if (hblk_reserve_thread == curthread) {
11172 				ASSERT(sfmmu_cache == sfmmu8_cache);
11173 				sfmmu_hblk_swap(hmeblkp);
11174 				hblk_reserve_thread = NULL;
11175 				mutex_exit(&hblk_reserve_lock);
11176 				goto fill_hblk;
11177 			}
11178 			/*
11179 			 * let's donate this hblk to our reserve list if
11180 			 * we are not mapping kernel range
11181 			 */
11182 			if (size == TTE8K && sfmmup != KHATID) {
11183 				if (sfmmu_put_free_hblk(hmeblkp, 0))
11184 					goto fill_hblk;
11185 			}
11186 		}
11187 	} else {
11188 		/*
11189 		 * We are here to map the slab in sfmmu8_cache; let's
11190 		 * check if we could tap our reserve list; if successful,
11191 		 * this will avoid the pain of going thru sfmmu_hblk_swap
11192 		 */
11193 		SFMMU_STAT(sf_hblk_slab_cnt);
11194 		if (!sfmmu_get_free_hblk(&hmeblkp, 0)) {
11195 			/*
11196 			 * let's start hblk_reserve dance
11197 			 */
11198 			SFMMU_STAT(sf_hblk_reserve_cnt);
11199 			owner = 1;
11200 			mutex_enter(&hblk_reserve_lock);
11201 			hmeblkp = HBLK_RESERVE;
11202 			hblk_reserve_thread = curthread;
11203 		}
11204 	}
11205 
11206 hblk_verify:
11207 	ASSERT(hmeblkp != NULL);
11208 	set_hblk_sz(hmeblkp, size);
11209 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
11210 	SFMMU_HASH_LOCK(hmebp);
11211 	HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11212 	if (newhblkp != NULL) {
11213 		SFMMU_HASH_UNLOCK(hmebp);
11214 		if (hmeblkp != HBLK_RESERVE) {
11215 			/*
11216 			 * This is really tricky!
11217 			 *
11218 			 * vmem_alloc(vmem_seg_arena)
11219 			 *  vmem_alloc(vmem_internal_arena)
11220 			 *   segkmem_alloc(heap_arena)
11221 			 *    vmem_alloc(heap_arena)
11222 			 *    page_create()
11223 			 *    hat_memload()
11224 			 *	kmem_cache_free()
11225 			 *	 kmem_cache_alloc()
11226 			 *	  kmem_slab_create()
11227 			 *	   vmem_alloc(kmem_internal_arena)
11228 			 *	    segkmem_alloc(heap_arena)
11229 			 *		vmem_alloc(heap_arena)
11230 			 *		page_create()
11231 			 *		hat_memload()
11232 			 *		  kmem_cache_free()
11233 			 *		...
11234 			 *
11235 			 * Thus, hat_memload() could call kmem_cache_free
11236 			 * for enough number of times that we could easily
11237 			 * hit the bottom of the stack or run out of reserve
11238 			 * list of vmem_seg structs.  So, we must donate
11239 			 * this hblk to reserve list if it's allocated
11240 			 * from sfmmu8_cache *and* mapping kernel range.
11241 			 * We don't need to worry about freeing hmeblk1's
11242 			 * to kmem since they don't map any kmem slabs.
11243 			 *
11244 			 * Note: When segkmem supports largepages, we must
11245 			 * free hmeblk1's to reserve list as well.
11246 			 */
11247 			forcefree = (sfmmup == KHATID) ? 1 : 0;
11248 			if (size == TTE8K &&
11249 			    sfmmu_put_free_hblk(hmeblkp, forcefree)) {
11250 				goto re_verify;
11251 			}
11252 			ASSERT(sfmmup != KHATID);
11253 			kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
11254 		} else {
11255 			/*
11256 			 * Hey! we don't need hblk_reserve any more.
11257 			 */
11258 			ASSERT(owner);
11259 			hblk_reserve_thread = NULL;
11260 			mutex_exit(&hblk_reserve_lock);
11261 			owner = 0;
11262 		}
11263 re_verify:
11264 		/*
11265 		 * let's check if the goodies are still present
11266 		 */
11267 		SFMMU_HASH_LOCK(hmebp);
11268 		HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11269 		if (newhblkp != NULL) {
11270 			/*
11271 			 * return newhblkp if it's not hblk_reserve;
11272 			 * if newhblkp is hblk_reserve, return it
11273 			 * _only if_ we are the owner of hblk_reserve.
11274 			 */
11275 			if (newhblkp != HBLK_RESERVE || owner) {
11276 				ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11277 				    newhblkp->hblk_shared);
11278 				ASSERT(SFMMU_IS_SHMERID_VALID(rid) ||
11279 				    !newhblkp->hblk_shared);
11280 				return (newhblkp);
11281 			} else {
11282 				/*
11283 				 * we just hit hblk_reserve in the hash and
11284 				 * we are not the owner of that;
11285 				 *
11286 				 * block until hblk_reserve_thread completes
11287 				 * swapping hblk_reserve and try the dance
11288 				 * once again.
11289 				 */
11290 				SFMMU_HASH_UNLOCK(hmebp);
11291 				mutex_enter(&hblk_reserve_lock);
11292 				mutex_exit(&hblk_reserve_lock);
11293 				SFMMU_STAT(sf_hblk_reserve_hit);
11294 				goto fill_hblk;
11295 			}
11296 		} else {
11297 			/*
11298 			 * it's no more! try the dance once again.
11299 			 */
11300 			SFMMU_HASH_UNLOCK(hmebp);
11301 			goto fill_hblk;
11302 		}
11303 	}
11304 
11305 hblk_init:
11306 	if (SFMMU_IS_SHMERID_VALID(rid)) {
11307 		uint16_t tteflag = 0x1 <<
11308 		    ((size < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ : size);
11309 
11310 		if (!(rgnp->rgn_hmeflags & tteflag)) {
11311 			atomic_or_16(&rgnp->rgn_hmeflags, tteflag);
11312 		}
11313 		hmeblkp->hblk_shared = 1;
11314 	} else {
11315 		hmeblkp->hblk_shared = 0;
11316 	}
11317 	set_hblk_sz(hmeblkp, size);
11318 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11319 	hmeblkp->hblk_next = (struct hme_blk *)NULL;
11320 	hmeblkp->hblk_tag = hblktag;
11321 	hmeblkp->hblk_shadow = shw_hblkp;
11322 	hblkpa = hmeblkp->hblk_nextpa;
11323 	hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
11324 
11325 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
11326 	ASSERT(get_hblk_span(hmeblkp) == HMEBLK_SPAN(size));
11327 	ASSERT(hmeblkp->hblk_hmecnt == 0);
11328 	ASSERT(hmeblkp->hblk_vcnt == 0);
11329 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11330 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
11331 	sfmmu_hblk_hash_add(hmebp, hmeblkp, hblkpa);
11332 	return (hmeblkp);
11333 }
11334 
11335 /*
11336  * This function cleans up the hme_blk and returns it to the free list.
11337  */
11338 /* ARGSUSED */
11339 static void
11340 sfmmu_hblk_free(struct hme_blk **listp)
11341 {
11342 	struct hme_blk *hmeblkp, *next_hmeblkp;
11343 	int		size;
11344 	uint_t		critical;
11345 	uint64_t	hblkpa;
11346 
11347 	ASSERT(*listp != NULL);
11348 
11349 	hmeblkp = *listp;
11350 	while (hmeblkp != NULL) {
11351 		next_hmeblkp = hmeblkp->hblk_next;
11352 		ASSERT(!hmeblkp->hblk_hmecnt);
11353 		ASSERT(!hmeblkp->hblk_vcnt);
11354 		ASSERT(!hmeblkp->hblk_lckcnt);
11355 		ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
11356 		ASSERT(hmeblkp->hblk_shared == 0);
11357 		ASSERT(hmeblkp->hblk_shw_bit == 0);
11358 		ASSERT(hmeblkp->hblk_shadow == NULL);
11359 
11360 		hblkpa = va_to_pa((caddr_t)hmeblkp);
11361 		ASSERT(hblkpa != (uint64_t)-1);
11362 		critical = (hblktosfmmu(hmeblkp) == KHATID) ? 1 : 0;
11363 
11364 		size = get_hblk_ttesz(hmeblkp);
11365 		hmeblkp->hblk_next = NULL;
11366 		hmeblkp->hblk_nextpa = hblkpa;
11367 
11368 		if (hmeblkp->hblk_nuc_bit == 0) {
11369 
11370 			if (size != TTE8K ||
11371 			    !sfmmu_put_free_hblk(hmeblkp, critical))
11372 				kmem_cache_free(get_hblk_cache(hmeblkp),
11373 				    hmeblkp);
11374 		}
11375 		hmeblkp = next_hmeblkp;
11376 	}
11377 }
11378 
11379 #define	BUCKETS_TO_SEARCH_BEFORE_UNLOAD	30
11380 #define	SFMMU_HBLK_STEAL_THRESHOLD 5
11381 
11382 static uint_t sfmmu_hblk_steal_twice;
11383 static uint_t sfmmu_hblk_steal_count, sfmmu_hblk_steal_unload_count;
11384 
11385 /*
11386  * Steal a hmeblk from user or kernel hme hash lists.
11387  * For 8K tte grab one from reserve pool (freehblkp) before proceeding to
11388  * steal and if we fail to steal after SFMMU_HBLK_STEAL_THRESHOLD attempts
11389  * tap into critical reserve of freehblkp.
11390  * Note: We remain looping in this routine until we find one.
11391  */
11392 static struct hme_blk *
11393 sfmmu_hblk_steal(int size)
11394 {
11395 	static struct hmehash_bucket *uhmehash_steal_hand = NULL;
11396 	struct hmehash_bucket *hmebp;
11397 	struct hme_blk *hmeblkp = NULL, *pr_hblk;
11398 	uint64_t hblkpa;
11399 	int i;
11400 	uint_t loop_cnt = 0, critical;
11401 
11402 	for (;;) {
11403 		/* Check cpu hblk pending queues */
11404 		if ((hmeblkp = sfmmu_check_pending_hblks(size)) != NULL) {
11405 			hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
11406 			ASSERT(hmeblkp->hblk_hmecnt == 0);
11407 			ASSERT(hmeblkp->hblk_vcnt == 0);
11408 			return (hmeblkp);
11409 		}
11410 
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 			pr_hblk = NULL;
11428 			while (hmeblkp) {
11429 				/*
11430 				 * check if it is a hmeblk that is not locked
11431 				 * and not shared. skip shadow hmeblks with
11432 				 * shadow_mask set i.e valid count non zero.
11433 				 */
11434 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11435 				    (hmeblkp->hblk_shw_bit == 0 ||
11436 				    hmeblkp->hblk_vcnt == 0) &&
11437 				    (hmeblkp->hblk_lckcnt == 0)) {
11438 					/*
11439 					 * there is a high probability that we
11440 					 * will find a free one. search some
11441 					 * buckets for a free hmeblk initially
11442 					 * before unloading a valid hmeblk.
11443 					 */
11444 					if ((hmeblkp->hblk_vcnt == 0 &&
11445 					    hmeblkp->hblk_hmecnt == 0) || (i >=
11446 					    BUCKETS_TO_SEARCH_BEFORE_UNLOAD)) {
11447 						if (sfmmu_steal_this_hblk(hmebp,
11448 						    hmeblkp, hblkpa, pr_hblk)) {
11449 							/*
11450 							 * Hblk is unloaded
11451 							 * successfully
11452 							 */
11453 							break;
11454 						}
11455 					}
11456 				}
11457 				pr_hblk = hmeblkp;
11458 				hblkpa = hmeblkp->hblk_nextpa;
11459 				hmeblkp = hmeblkp->hblk_next;
11460 			}
11461 
11462 			SFMMU_HASH_UNLOCK(hmebp);
11463 			if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
11464 				hmebp = uhme_hash;
11465 		}
11466 		uhmehash_steal_hand = hmebp;
11467 
11468 		if (hmeblkp != NULL)
11469 			break;
11470 
11471 		/*
11472 		 * in the worst case, look for a free one in the kernel
11473 		 * hash table.
11474 		 */
11475 		for (i = 0, hmebp = khme_hash; i <= KHMEHASH_SZ; i++) {
11476 			SFMMU_HASH_LOCK(hmebp);
11477 			hmeblkp = hmebp->hmeblkp;
11478 			hblkpa = hmebp->hmeh_nextpa;
11479 			pr_hblk = NULL;
11480 			while (hmeblkp) {
11481 				/*
11482 				 * check if it is free hmeblk
11483 				 */
11484 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11485 				    (hmeblkp->hblk_lckcnt == 0) &&
11486 				    (hmeblkp->hblk_vcnt == 0) &&
11487 				    (hmeblkp->hblk_hmecnt == 0)) {
11488 					if (sfmmu_steal_this_hblk(hmebp,
11489 					    hmeblkp, hblkpa, pr_hblk)) {
11490 						break;
11491 					} else {
11492 						/*
11493 						 * Cannot fail since we have
11494 						 * hash lock.
11495 						 */
11496 						panic("fail to steal?");
11497 					}
11498 				}
11499 
11500 				pr_hblk = hmeblkp;
11501 				hblkpa = hmeblkp->hblk_nextpa;
11502 				hmeblkp = hmeblkp->hblk_next;
11503 			}
11504 
11505 			SFMMU_HASH_UNLOCK(hmebp);
11506 			if (hmebp++ == &khme_hash[KHMEHASH_SZ])
11507 				hmebp = khme_hash;
11508 		}
11509 
11510 		if (hmeblkp != NULL)
11511 			break;
11512 		sfmmu_hblk_steal_twice++;
11513 	}
11514 	return (hmeblkp);
11515 }
11516 
11517 /*
11518  * This routine does real work to prepare a hblk to be "stolen" by
11519  * unloading the mappings, updating shadow counts ....
11520  * It returns 1 if the block is ready to be reused (stolen), or 0
11521  * means the block cannot be stolen yet- pageunload is still working
11522  * on this hblk.
11523  */
11524 static int
11525 sfmmu_steal_this_hblk(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
11526 	uint64_t hblkpa, struct hme_blk *pr_hblk)
11527 {
11528 	int shw_size, vshift;
11529 	struct hme_blk *shw_hblkp;
11530 	caddr_t vaddr;
11531 	uint_t shw_mask, newshw_mask;
11532 	struct hme_blk *list = NULL;
11533 
11534 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11535 
11536 	/*
11537 	 * check if the hmeblk is free, unload if necessary
11538 	 */
11539 	if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11540 		sfmmu_t *sfmmup;
11541 		demap_range_t dmr;
11542 
11543 		sfmmup = hblktosfmmu(hmeblkp);
11544 		if (hmeblkp->hblk_shared || sfmmup->sfmmu_ismhat) {
11545 			return (0);
11546 		}
11547 		DEMAP_RANGE_INIT(sfmmup, &dmr);
11548 		(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
11549 		    (caddr_t)get_hblk_base(hmeblkp),
11550 		    get_hblk_endaddr(hmeblkp), &dmr, HAT_UNLOAD);
11551 		DEMAP_RANGE_FLUSH(&dmr);
11552 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11553 			/*
11554 			 * Pageunload is working on the same hblk.
11555 			 */
11556 			return (0);
11557 		}
11558 
11559 		sfmmu_hblk_steal_unload_count++;
11560 	}
11561 
11562 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11563 	ASSERT(hmeblkp->hblk_vcnt == 0 && hmeblkp->hblk_hmecnt == 0);
11564 
11565 	sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk, &list, 1);
11566 	hmeblkp->hblk_nextpa = hblkpa;
11567 
11568 	shw_hblkp = hmeblkp->hblk_shadow;
11569 	if (shw_hblkp) {
11570 		ASSERT(!hmeblkp->hblk_shared);
11571 		shw_size = get_hblk_ttesz(shw_hblkp);
11572 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11573 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
11574 		ASSERT(vshift < 8);
11575 		/*
11576 		 * Atomically clear shadow mask bit
11577 		 */
11578 		do {
11579 			shw_mask = shw_hblkp->hblk_shw_mask;
11580 			ASSERT(shw_mask & (1 << vshift));
11581 			newshw_mask = shw_mask & ~(1 << vshift);
11582 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
11583 			    shw_mask, newshw_mask);
11584 		} while (newshw_mask != shw_mask);
11585 		hmeblkp->hblk_shadow = NULL;
11586 	}
11587 
11588 	/*
11589 	 * remove shadow bit if we are stealing an unused shadow hmeblk.
11590 	 * sfmmu_hblk_alloc needs it that way, will set shadow bit later if
11591 	 * we are indeed allocating a shadow hmeblk.
11592 	 */
11593 	hmeblkp->hblk_shw_bit = 0;
11594 
11595 	if (hmeblkp->hblk_shared) {
11596 		sf_srd_t	*srdp;
11597 		sf_region_t	*rgnp;
11598 		uint_t		rid;
11599 
11600 		srdp = hblktosrd(hmeblkp);
11601 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11602 		rid = hmeblkp->hblk_tag.htag_rid;
11603 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11604 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11605 		rgnp = srdp->srd_hmergnp[rid];
11606 		ASSERT(rgnp != NULL);
11607 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
11608 		hmeblkp->hblk_shared = 0;
11609 	}
11610 
11611 	sfmmu_hblk_steal_count++;
11612 	SFMMU_STAT(sf_steal_count);
11613 
11614 	return (1);
11615 }
11616 
11617 struct hme_blk *
11618 sfmmu_hmetohblk(struct sf_hment *sfhme)
11619 {
11620 	struct hme_blk *hmeblkp;
11621 	struct sf_hment *sfhme0;
11622 	struct hme_blk *hblk_dummy = 0;
11623 
11624 	/*
11625 	 * No dummy sf_hments, please.
11626 	 */
11627 	ASSERT(sfhme->hme_tte.ll != 0);
11628 
11629 	sfhme0 = sfhme - sfhme->hme_tte.tte_hmenum;
11630 	hmeblkp = (struct hme_blk *)((uintptr_t)sfhme0 -
11631 	    (uintptr_t)&hblk_dummy->hblk_hme[0]);
11632 
11633 	return (hmeblkp);
11634 }
11635 
11636 /*
11637  * On swapin, get appropriately sized TSB(s) and clear the HAT_SWAPPED flag.
11638  * If we can't get appropriately sized TSB(s), try for 8K TSB(s) using
11639  * KM_SLEEP allocation.
11640  *
11641  * Return 0 on success, -1 otherwise.
11642  */
11643 static void
11644 sfmmu_tsb_swapin(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11645 {
11646 	struct tsb_info *tsbinfop, *next;
11647 	tsb_replace_rc_t rc;
11648 	boolean_t gotfirst = B_FALSE;
11649 
11650 	ASSERT(sfmmup != ksfmmup);
11651 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11652 
11653 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPIN)) {
11654 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
11655 	}
11656 
11657 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11658 		SFMMU_FLAGS_SET(sfmmup, HAT_SWAPIN);
11659 	} else {
11660 		return;
11661 	}
11662 
11663 	ASSERT(sfmmup->sfmmu_tsb != NULL);
11664 
11665 	/*
11666 	 * Loop over all tsbinfo's replacing them with ones that actually have
11667 	 * a TSB.  If any of the replacements ever fail, bail out of the loop.
11668 	 */
11669 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL; tsbinfop = next) {
11670 		ASSERT(tsbinfop->tsb_flags & TSB_SWAPPED);
11671 		next = tsbinfop->tsb_next;
11672 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, tsbinfop->tsb_szc,
11673 		    hatlockp, TSB_SWAPIN);
11674 		if (rc != TSB_SUCCESS) {
11675 			break;
11676 		}
11677 		gotfirst = B_TRUE;
11678 	}
11679 
11680 	switch (rc) {
11681 	case TSB_SUCCESS:
11682 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11683 		cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11684 		return;
11685 	case TSB_LOSTRACE:
11686 		break;
11687 	case TSB_ALLOCFAIL:
11688 		break;
11689 	default:
11690 		panic("sfmmu_replace_tsb returned unrecognized failure code "
11691 		    "%d", rc);
11692 	}
11693 
11694 	/*
11695 	 * In this case, we failed to get one of our TSBs.  If we failed to
11696 	 * get the first TSB, get one of minimum size (8KB).  Walk the list
11697 	 * and throw away the tsbinfos, starting where the allocation failed;
11698 	 * we can get by with just one TSB as long as we don't leave the
11699 	 * SWAPPED tsbinfo structures lying around.
11700 	 */
11701 	tsbinfop = sfmmup->sfmmu_tsb;
11702 	next = tsbinfop->tsb_next;
11703 	tsbinfop->tsb_next = NULL;
11704 
11705 	sfmmu_hat_exit(hatlockp);
11706 	for (tsbinfop = next; tsbinfop != NULL; tsbinfop = next) {
11707 		next = tsbinfop->tsb_next;
11708 		sfmmu_tsbinfo_free(tsbinfop);
11709 	}
11710 	hatlockp = sfmmu_hat_enter(sfmmup);
11711 
11712 	/*
11713 	 * If we don't have any TSBs, get a single 8K TSB for 8K, 64K and 512K
11714 	 * pages.
11715 	 */
11716 	if (!gotfirst) {
11717 		tsbinfop = sfmmup->sfmmu_tsb;
11718 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, TSB_MIN_SZCODE,
11719 		    hatlockp, TSB_SWAPIN | TSB_FORCEALLOC);
11720 		ASSERT(rc == TSB_SUCCESS);
11721 	}
11722 
11723 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11724 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11725 }
11726 
11727 static int
11728 sfmmu_is_rgnva(sf_srd_t *srdp, caddr_t addr, ulong_t w, ulong_t bmw)
11729 {
11730 	ulong_t bix = 0;
11731 	uint_t rid;
11732 	sf_region_t *rgnp;
11733 
11734 	ASSERT(srdp != NULL);
11735 	ASSERT(srdp->srd_refcnt != 0);
11736 
11737 	w <<= BT_ULSHIFT;
11738 	while (bmw) {
11739 		if (!(bmw & 0x1)) {
11740 			bix++;
11741 			bmw >>= 1;
11742 			continue;
11743 		}
11744 		rid = w | bix;
11745 		rgnp = srdp->srd_hmergnp[rid];
11746 		ASSERT(rgnp->rgn_refcnt > 0);
11747 		ASSERT(rgnp->rgn_id == rid);
11748 		if (addr < rgnp->rgn_saddr ||
11749 		    addr >= (rgnp->rgn_saddr + rgnp->rgn_size)) {
11750 			bix++;
11751 			bmw >>= 1;
11752 		} else {
11753 			return (1);
11754 		}
11755 	}
11756 	return (0);
11757 }
11758 
11759 /*
11760  * Handle exceptions for low level tsb_handler.
11761  *
11762  * There are many scenarios that could land us here:
11763  *
11764  * If the context is invalid we land here. The context can be invalid
11765  * for 3 reasons: 1) we couldn't allocate a new context and now need to
11766  * perform a wrap around operation in order to allocate a new context.
11767  * 2) Context was invalidated to change pagesize programming 3) ISMs or
11768  * TSBs configuration is changeing for this process and we are forced into
11769  * here to do a syncronization operation. If the context is valid we can
11770  * be here from window trap hanlder. In this case just call trap to handle
11771  * the fault.
11772  *
11773  * Note that the process will run in INVALID_CONTEXT before
11774  * faulting into here and subsequently loading the MMU registers
11775  * (including the TSB base register) associated with this process.
11776  * For this reason, the trap handlers must all test for
11777  * INVALID_CONTEXT before attempting to access any registers other
11778  * than the context registers.
11779  */
11780 void
11781 sfmmu_tsbmiss_exception(struct regs *rp, uintptr_t tagaccess, uint_t traptype)
11782 {
11783 	sfmmu_t *sfmmup, *shsfmmup;
11784 	uint_t ctxtype;
11785 	klwp_id_t lwp;
11786 	char lwp_save_state;
11787 	hatlock_t *hatlockp, *shatlockp;
11788 	struct tsb_info *tsbinfop;
11789 	struct tsbmiss *tsbmp;
11790 	sf_scd_t *scdp;
11791 
11792 	SFMMU_STAT(sf_tsb_exceptions);
11793 	SFMMU_MMU_STAT(mmu_tsb_exceptions);
11794 	sfmmup = astosfmmu(curthread->t_procp->p_as);
11795 	/*
11796 	 * note that in sun4u, tagacces register contains ctxnum
11797 	 * while sun4v passes ctxtype in the tagaccess register.
11798 	 */
11799 	ctxtype = tagaccess & TAGACC_CTX_MASK;
11800 
11801 	ASSERT(sfmmup != ksfmmup && ctxtype != KCONTEXT);
11802 	ASSERT(sfmmup->sfmmu_ismhat == 0);
11803 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED) ||
11804 	    ctxtype == INVALID_CONTEXT);
11805 
11806 	if (ctxtype != INVALID_CONTEXT && traptype != T_DATA_PROT) {
11807 		/*
11808 		 * We may land here because shme bitmap and pagesize
11809 		 * flags are updated lazily in tsbmiss area on other cpus.
11810 		 * If we detect here that tsbmiss area is out of sync with
11811 		 * sfmmu update it and retry the trapped instruction.
11812 		 * Otherwise call trap().
11813 		 */
11814 		int ret = 0;
11815 		uchar_t tteflag_mask = (1 << TTE64K) | (1 << TTE8K);
11816 		caddr_t addr = (caddr_t)(tagaccess & TAGACC_VADDR_MASK);
11817 
11818 		/*
11819 		 * Must set lwp state to LWP_SYS before
11820 		 * trying to acquire any adaptive lock
11821 		 */
11822 		lwp = ttolwp(curthread);
11823 		ASSERT(lwp);
11824 		lwp_save_state = lwp->lwp_state;
11825 		lwp->lwp_state = LWP_SYS;
11826 
11827 		hatlockp = sfmmu_hat_enter(sfmmup);
11828 		kpreempt_disable();
11829 		tsbmp = &tsbmiss_area[CPU->cpu_id];
11830 		ASSERT(sfmmup == tsbmp->usfmmup);
11831 		if (((tsbmp->uhat_tteflags ^ sfmmup->sfmmu_tteflags) &
11832 		    ~tteflag_mask) ||
11833 		    ((tsbmp->uhat_rtteflags ^  sfmmup->sfmmu_rtteflags) &
11834 		    ~tteflag_mask)) {
11835 			tsbmp->uhat_tteflags = sfmmup->sfmmu_tteflags;
11836 			tsbmp->uhat_rtteflags = sfmmup->sfmmu_rtteflags;
11837 			ret = 1;
11838 		}
11839 		if (sfmmup->sfmmu_srdp != NULL) {
11840 			ulong_t *sm = sfmmup->sfmmu_hmeregion_map.bitmap;
11841 			ulong_t *tm = tsbmp->shmermap;
11842 			ulong_t i;
11843 			for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
11844 				ulong_t d = tm[i] ^ sm[i];
11845 				if (d) {
11846 					if (d & sm[i]) {
11847 						if (!ret && sfmmu_is_rgnva(
11848 						    sfmmup->sfmmu_srdp,
11849 						    addr, i, d & sm[i])) {
11850 							ret = 1;
11851 						}
11852 					}
11853 					tm[i] = sm[i];
11854 				}
11855 			}
11856 		}
11857 		kpreempt_enable();
11858 		sfmmu_hat_exit(hatlockp);
11859 		lwp->lwp_state = lwp_save_state;
11860 		if (ret) {
11861 			return;
11862 		}
11863 	} else if (ctxtype == INVALID_CONTEXT) {
11864 		/*
11865 		 * First, make sure we come out of here with a valid ctx,
11866 		 * since if we don't get one we'll simply loop on the
11867 		 * faulting instruction.
11868 		 *
11869 		 * If the ISM mappings are changing, the TSB is relocated,
11870 		 * the process is swapped, the process is joining SCD or
11871 		 * leaving SCD or shared regions we serialize behind the
11872 		 * controlling thread with hat lock, sfmmu_flags and
11873 		 * sfmmu_tsb_cv condition variable.
11874 		 */
11875 
11876 		/*
11877 		 * Must set lwp state to LWP_SYS before
11878 		 * trying to acquire any adaptive lock
11879 		 */
11880 		lwp = ttolwp(curthread);
11881 		ASSERT(lwp);
11882 		lwp_save_state = lwp->lwp_state;
11883 		lwp->lwp_state = LWP_SYS;
11884 
11885 		hatlockp = sfmmu_hat_enter(sfmmup);
11886 retry:
11887 		if ((scdp = sfmmup->sfmmu_scdp) != NULL) {
11888 			shsfmmup = scdp->scd_sfmmup;
11889 			ASSERT(shsfmmup != NULL);
11890 
11891 			for (tsbinfop = shsfmmup->sfmmu_tsb; tsbinfop != NULL;
11892 			    tsbinfop = tsbinfop->tsb_next) {
11893 				if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11894 					/* drop the private hat lock */
11895 					sfmmu_hat_exit(hatlockp);
11896 					/* acquire the shared hat lock */
11897 					shatlockp = sfmmu_hat_enter(shsfmmup);
11898 					/*
11899 					 * recheck to see if anything changed
11900 					 * after we drop the private hat lock.
11901 					 */
11902 					if (sfmmup->sfmmu_scdp == scdp &&
11903 					    shsfmmup == scdp->scd_sfmmup) {
11904 						sfmmu_tsb_chk_reloc(shsfmmup,
11905 						    shatlockp);
11906 					}
11907 					sfmmu_hat_exit(shatlockp);
11908 					hatlockp = sfmmu_hat_enter(sfmmup);
11909 					goto retry;
11910 				}
11911 			}
11912 		}
11913 
11914 		for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
11915 		    tsbinfop = tsbinfop->tsb_next) {
11916 			if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11917 				cv_wait(&sfmmup->sfmmu_tsb_cv,
11918 				    HATLOCK_MUTEXP(hatlockp));
11919 				goto retry;
11920 			}
11921 		}
11922 
11923 		/*
11924 		 * Wait for ISM maps to be updated.
11925 		 */
11926 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
11927 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11928 			    HATLOCK_MUTEXP(hatlockp));
11929 			goto retry;
11930 		}
11931 
11932 		/* Is this process joining an SCD? */
11933 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
11934 			/*
11935 			 * Flush private TSB and setup shared TSB.
11936 			 * sfmmu_finish_join_scd() does not drop the
11937 			 * hat lock.
11938 			 */
11939 			sfmmu_finish_join_scd(sfmmup);
11940 			SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
11941 		}
11942 
11943 		/*
11944 		 * If we're swapping in, get TSB(s).  Note that we must do
11945 		 * this before we get a ctx or load the MMU state.  Once
11946 		 * we swap in we have to recheck to make sure the TSB(s) and
11947 		 * ISM mappings didn't change while we slept.
11948 		 */
11949 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11950 			sfmmu_tsb_swapin(sfmmup, hatlockp);
11951 			goto retry;
11952 		}
11953 
11954 		sfmmu_get_ctx(sfmmup);
11955 
11956 		sfmmu_hat_exit(hatlockp);
11957 		/*
11958 		 * Must restore lwp_state if not calling
11959 		 * trap() for further processing. Restore
11960 		 * it anyway.
11961 		 */
11962 		lwp->lwp_state = lwp_save_state;
11963 		return;
11964 	}
11965 	trap(rp, (caddr_t)tagaccess, traptype, 0);
11966 }
11967 
11968 static void
11969 sfmmu_tsb_chk_reloc(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11970 {
11971 	struct tsb_info *tp;
11972 
11973 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11974 
11975 	for (tp = sfmmup->sfmmu_tsb; tp != NULL; tp = tp->tsb_next) {
11976 		if (tp->tsb_flags & TSB_RELOC_FLAG) {
11977 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11978 			    HATLOCK_MUTEXP(hatlockp));
11979 			break;
11980 		}
11981 	}
11982 }
11983 
11984 /*
11985  * sfmmu_vatopfn_suspended is called from GET_TTE when TL=0 and
11986  * TTE_SUSPENDED bit set in tte we block on aquiring a page lock
11987  * rather than spinning to avoid send mondo timeouts with
11988  * interrupts enabled. When the lock is acquired it is immediately
11989  * released and we return back to sfmmu_vatopfn just after
11990  * the GET_TTE call.
11991  */
11992 void
11993 sfmmu_vatopfn_suspended(caddr_t vaddr, sfmmu_t *sfmmu, tte_t *ttep)
11994 {
11995 	struct page	**pp;
11996 
11997 	(void) as_pagelock(sfmmu->sfmmu_as, &pp, vaddr, TTE_CSZ(ttep), S_WRITE);
11998 	as_pageunlock(sfmmu->sfmmu_as, pp, vaddr, TTE_CSZ(ttep), S_WRITE);
11999 }
12000 
12001 /*
12002  * sfmmu_tsbmiss_suspended is called from GET_TTE when TL>0 and
12003  * TTE_SUSPENDED bit set in tte. We do this so that we can handle
12004  * cross traps which cannot be handled while spinning in the
12005  * trap handlers. Simply enter and exit the kpr_suspendlock spin
12006  * mutex, which is held by the holder of the suspend bit, and then
12007  * retry the trapped instruction after unwinding.
12008  */
12009 /*ARGSUSED*/
12010 void
12011 sfmmu_tsbmiss_suspended(struct regs *rp, uintptr_t tagacc, uint_t traptype)
12012 {
12013 	ASSERT(curthread != kreloc_thread);
12014 	mutex_enter(&kpr_suspendlock);
12015 	mutex_exit(&kpr_suspendlock);
12016 }
12017 
12018 /*
12019  * This routine could be optimized to reduce the number of xcalls by flushing
12020  * the entire TLBs if region reference count is above some threshold but the
12021  * tradeoff will depend on the size of the TLB. So for now flush the specific
12022  * page a context at a time.
12023  *
12024  * If uselocks is 0 then it's called after all cpus were captured and all the
12025  * hat locks were taken. In this case don't take the region lock by relying on
12026  * the order of list region update operations in hat_join_region(),
12027  * hat_leave_region() and hat_dup_region(). The ordering in those routines
12028  * guarantees that list is always forward walkable and reaches active sfmmus
12029  * regardless of where xc_attention() captures a cpu.
12030  */
12031 cpuset_t
12032 sfmmu_rgntlb_demap(caddr_t addr, sf_region_t *rgnp,
12033     struct hme_blk *hmeblkp, int uselocks)
12034 {
12035 	sfmmu_t	*sfmmup;
12036 	cpuset_t cpuset;
12037 	cpuset_t rcpuset;
12038 	hatlock_t *hatlockp;
12039 	uint_t rid = rgnp->rgn_id;
12040 	sf_rgn_link_t *rlink;
12041 	sf_scd_t *scdp;
12042 
12043 	ASSERT(hmeblkp->hblk_shared);
12044 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
12045 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
12046 
12047 	CPUSET_ZERO(rcpuset);
12048 	if (uselocks) {
12049 		mutex_enter(&rgnp->rgn_mutex);
12050 	}
12051 	sfmmup = rgnp->rgn_sfmmu_head;
12052 	while (sfmmup != NULL) {
12053 		if (uselocks) {
12054 			hatlockp = sfmmu_hat_enter(sfmmup);
12055 		}
12056 
12057 		/*
12058 		 * When an SCD is created the SCD hat is linked on the sfmmu
12059 		 * region lists for each hme region which is part of the
12060 		 * SCD. If we find an SCD hat, when walking these lists,
12061 		 * then we flush the shared TSBs, if we find a private hat,
12062 		 * which is part of an SCD, but where the region
12063 		 * is not part of the SCD then we flush the private TSBs.
12064 		 */
12065 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12066 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
12067 			scdp = sfmmup->sfmmu_scdp;
12068 			if (SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
12069 				if (uselocks) {
12070 					sfmmu_hat_exit(hatlockp);
12071 				}
12072 				goto next;
12073 			}
12074 		}
12075 
12076 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12077 
12078 		kpreempt_disable();
12079 		cpuset = sfmmup->sfmmu_cpusran;
12080 		CPUSET_AND(cpuset, cpu_ready_set);
12081 		CPUSET_DEL(cpuset, CPU->cpu_id);
12082 		SFMMU_XCALL_STATS(sfmmup);
12083 		xt_some(cpuset, vtag_flushpage_tl1,
12084 		    (uint64_t)addr, (uint64_t)sfmmup);
12085 		vtag_flushpage(addr, (uint64_t)sfmmup);
12086 		if (uselocks) {
12087 			sfmmu_hat_exit(hatlockp);
12088 		}
12089 		kpreempt_enable();
12090 		CPUSET_OR(rcpuset, cpuset);
12091 
12092 next:
12093 		/* LINTED: constant in conditional context */
12094 		SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
12095 		ASSERT(rlink != NULL);
12096 		sfmmup = rlink->next;
12097 	}
12098 	if (uselocks) {
12099 		mutex_exit(&rgnp->rgn_mutex);
12100 	}
12101 	return (rcpuset);
12102 }
12103 
12104 /*
12105  * This routine takes an sfmmu pointer and the va for an adddress in an
12106  * ISM region as input and returns the corresponding region id in ism_rid.
12107  * The return value of 1 indicates that a region has been found and ism_rid
12108  * is valid, otherwise 0 is returned.
12109  */
12110 static int
12111 find_ism_rid(sfmmu_t *sfmmup, sfmmu_t *ism_sfmmup, caddr_t va, uint_t *ism_rid)
12112 {
12113 	ism_blk_t	*ism_blkp;
12114 	int		i;
12115 	ism_map_t	*ism_map;
12116 #ifdef DEBUG
12117 	struct hat	*ism_hatid;
12118 #endif
12119 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12120 
12121 	ism_blkp = sfmmup->sfmmu_iblk;
12122 	while (ism_blkp != NULL) {
12123 		ism_map = ism_blkp->iblk_maps;
12124 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
12125 			if ((va >= ism_start(ism_map[i])) &&
12126 			    (va < ism_end(ism_map[i]))) {
12127 
12128 				*ism_rid = ism_map[i].imap_rid;
12129 #ifdef DEBUG
12130 				ism_hatid = ism_map[i].imap_ismhat;
12131 				ASSERT(ism_hatid == ism_sfmmup);
12132 				ASSERT(ism_hatid->sfmmu_ismhat);
12133 #endif
12134 				return (1);
12135 			}
12136 		}
12137 		ism_blkp = ism_blkp->iblk_next;
12138 	}
12139 	return (0);
12140 }
12141 
12142 /*
12143  * Special routine to flush out ism mappings- TSBs, TLBs and D-caches.
12144  * This routine may be called with all cpu's captured. Therefore, the
12145  * caller is responsible for holding all locks and disabling kernel
12146  * preemption.
12147  */
12148 /* ARGSUSED */
12149 static void
12150 sfmmu_ismtlbcache_demap(caddr_t addr, sfmmu_t *ism_sfmmup,
12151 	struct hme_blk *hmeblkp, pfn_t pfnum, int cache_flush_flag)
12152 {
12153 	cpuset_t 	cpuset;
12154 	caddr_t 	va;
12155 	ism_ment_t	*ment;
12156 	sfmmu_t		*sfmmup;
12157 #ifdef VAC
12158 	int 		vcolor;
12159 #endif
12160 
12161 	sf_scd_t	*scdp;
12162 	uint_t		ism_rid;
12163 
12164 	ASSERT(!hmeblkp->hblk_shared);
12165 	/*
12166 	 * Walk the ism_hat's mapping list and flush the page
12167 	 * from every hat sharing this ism_hat. This routine
12168 	 * may be called while all cpu's have been captured.
12169 	 * Therefore we can't attempt to grab any locks. For now
12170 	 * this means we will protect the ism mapping list under
12171 	 * a single lock which will be grabbed by the caller.
12172 	 * If hat_share/unshare scalibility becomes a performance
12173 	 * problem then we may need to re-think ism mapping list locking.
12174 	 */
12175 	ASSERT(ism_sfmmup->sfmmu_ismhat);
12176 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
12177 	addr = addr - ISMID_STARTADDR;
12178 
12179 	for (ment = ism_sfmmup->sfmmu_iment; ment; ment = ment->iment_next) {
12180 
12181 		sfmmup = ment->iment_hat;
12182 
12183 		va = ment->iment_base_va;
12184 		va = (caddr_t)((uintptr_t)va  + (uintptr_t)addr);
12185 
12186 		/*
12187 		 * When an SCD is created the SCD hat is linked on the ism
12188 		 * mapping lists for each ISM segment which is part of the
12189 		 * SCD. If we find an SCD hat, when walking these lists,
12190 		 * then we flush the shared TSBs, if we find a private hat,
12191 		 * which is part of an SCD, but where the region
12192 		 * corresponding to this va is not part of the SCD then we
12193 		 * flush the private TSBs.
12194 		 */
12195 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12196 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD) &&
12197 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
12198 			if (!find_ism_rid(sfmmup, ism_sfmmup, va,
12199 			    &ism_rid)) {
12200 				cmn_err(CE_PANIC,
12201 				    "can't find matching ISM rid!");
12202 			}
12203 
12204 			scdp = sfmmup->sfmmu_scdp;
12205 			if (SFMMU_IS_ISMRID_VALID(ism_rid) &&
12206 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map,
12207 			    ism_rid)) {
12208 				continue;
12209 			}
12210 		}
12211 		SFMMU_UNLOAD_TSB(va, sfmmup, hmeblkp, 1);
12212 
12213 		cpuset = sfmmup->sfmmu_cpusran;
12214 		CPUSET_AND(cpuset, cpu_ready_set);
12215 		CPUSET_DEL(cpuset, CPU->cpu_id);
12216 		SFMMU_XCALL_STATS(sfmmup);
12217 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)va,
12218 		    (uint64_t)sfmmup);
12219 		vtag_flushpage(va, (uint64_t)sfmmup);
12220 
12221 #ifdef VAC
12222 		/*
12223 		 * Flush D$
12224 		 * When flushing D$ we must flush all
12225 		 * cpu's. See sfmmu_cache_flush().
12226 		 */
12227 		if (cache_flush_flag == CACHE_FLUSH) {
12228 			cpuset = cpu_ready_set;
12229 			CPUSET_DEL(cpuset, CPU->cpu_id);
12230 
12231 			SFMMU_XCALL_STATS(sfmmup);
12232 			vcolor = addr_to_vcolor(va);
12233 			xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12234 			vac_flushpage(pfnum, vcolor);
12235 		}
12236 #endif	/* VAC */
12237 	}
12238 }
12239 
12240 /*
12241  * Demaps the TSB, CPU caches, and flushes all TLBs on all CPUs of
12242  * a particular virtual address and ctx.  If noflush is set we do not
12243  * flush the TLB/TSB.  This function may or may not be called with the
12244  * HAT lock held.
12245  */
12246 static void
12247 sfmmu_tlbcache_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12248 	pfn_t pfnum, int tlb_noflush, int cpu_flag, int cache_flush_flag,
12249 	int hat_lock_held)
12250 {
12251 #ifdef VAC
12252 	int vcolor;
12253 #endif
12254 	cpuset_t cpuset;
12255 	hatlock_t *hatlockp;
12256 
12257 	ASSERT(!hmeblkp->hblk_shared);
12258 
12259 #if defined(lint) && !defined(VAC)
12260 	pfnum = pfnum;
12261 	cpu_flag = cpu_flag;
12262 	cache_flush_flag = cache_flush_flag;
12263 #endif
12264 
12265 	/*
12266 	 * There is no longer a need to protect against ctx being
12267 	 * stolen here since we don't store the ctx in the TSB anymore.
12268 	 */
12269 #ifdef VAC
12270 	vcolor = addr_to_vcolor(addr);
12271 #endif
12272 
12273 	/*
12274 	 * We must hold the hat lock during the flush of TLB,
12275 	 * to avoid a race with sfmmu_invalidate_ctx(), where
12276 	 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12277 	 * causing TLB demap routine to skip flush on that MMU.
12278 	 * If the context on a MMU has already been set to
12279 	 * INVALID_CONTEXT, we just get an extra flush on
12280 	 * that MMU.
12281 	 */
12282 	if (!hat_lock_held && !tlb_noflush)
12283 		hatlockp = sfmmu_hat_enter(sfmmup);
12284 
12285 	kpreempt_disable();
12286 	if (!tlb_noflush) {
12287 		/*
12288 		 * Flush the TSB and TLB.
12289 		 */
12290 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12291 
12292 		cpuset = sfmmup->sfmmu_cpusran;
12293 		CPUSET_AND(cpuset, cpu_ready_set);
12294 		CPUSET_DEL(cpuset, CPU->cpu_id);
12295 
12296 		SFMMU_XCALL_STATS(sfmmup);
12297 
12298 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
12299 		    (uint64_t)sfmmup);
12300 
12301 		vtag_flushpage(addr, (uint64_t)sfmmup);
12302 	}
12303 
12304 	if (!hat_lock_held && !tlb_noflush)
12305 		sfmmu_hat_exit(hatlockp);
12306 
12307 #ifdef VAC
12308 	/*
12309 	 * Flush the D$
12310 	 *
12311 	 * Even if the ctx is stolen, we need to flush the
12312 	 * cache. Our ctx stealer only flushes the TLBs.
12313 	 */
12314 	if (cache_flush_flag == CACHE_FLUSH) {
12315 		if (cpu_flag & FLUSH_ALL_CPUS) {
12316 			cpuset = cpu_ready_set;
12317 		} else {
12318 			cpuset = sfmmup->sfmmu_cpusran;
12319 			CPUSET_AND(cpuset, cpu_ready_set);
12320 		}
12321 		CPUSET_DEL(cpuset, CPU->cpu_id);
12322 		SFMMU_XCALL_STATS(sfmmup);
12323 		xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12324 		vac_flushpage(pfnum, vcolor);
12325 	}
12326 #endif	/* VAC */
12327 	kpreempt_enable();
12328 }
12329 
12330 /*
12331  * Demaps the TSB and flushes all TLBs on all cpus for a particular virtual
12332  * address and ctx.  If noflush is set we do not currently do anything.
12333  * This function may or may not be called with the HAT lock held.
12334  */
12335 static void
12336 sfmmu_tlb_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12337 	int tlb_noflush, int hat_lock_held)
12338 {
12339 	cpuset_t cpuset;
12340 	hatlock_t *hatlockp;
12341 
12342 	ASSERT(!hmeblkp->hblk_shared);
12343 
12344 	/*
12345 	 * If the process is exiting we have nothing to do.
12346 	 */
12347 	if (tlb_noflush)
12348 		return;
12349 
12350 	/*
12351 	 * Flush TSB.
12352 	 */
12353 	if (!hat_lock_held)
12354 		hatlockp = sfmmu_hat_enter(sfmmup);
12355 	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12356 
12357 	kpreempt_disable();
12358 
12359 	cpuset = sfmmup->sfmmu_cpusran;
12360 	CPUSET_AND(cpuset, cpu_ready_set);
12361 	CPUSET_DEL(cpuset, CPU->cpu_id);
12362 
12363 	SFMMU_XCALL_STATS(sfmmup);
12364 	xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr, (uint64_t)sfmmup);
12365 
12366 	vtag_flushpage(addr, (uint64_t)sfmmup);
12367 
12368 	if (!hat_lock_held)
12369 		sfmmu_hat_exit(hatlockp);
12370 
12371 	kpreempt_enable();
12372 
12373 }
12374 
12375 /*
12376  * Special case of sfmmu_tlb_demap for MMU_PAGESIZE hblks. Use the xcall
12377  * call handler that can flush a range of pages to save on xcalls.
12378  */
12379 static int sfmmu_xcall_save;
12380 
12381 /*
12382  * this routine is never used for demaping addresses backed by SRD hmeblks.
12383  */
12384 static void
12385 sfmmu_tlb_range_demap(demap_range_t *dmrp)
12386 {
12387 	sfmmu_t *sfmmup = dmrp->dmr_sfmmup;
12388 	hatlock_t *hatlockp;
12389 	cpuset_t cpuset;
12390 	uint64_t sfmmu_pgcnt;
12391 	pgcnt_t pgcnt = 0;
12392 	int pgunload = 0;
12393 	int dirtypg = 0;
12394 	caddr_t addr = dmrp->dmr_addr;
12395 	caddr_t eaddr;
12396 	uint64_t bitvec = dmrp->dmr_bitvec;
12397 
12398 	ASSERT(bitvec & 1);
12399 
12400 	/*
12401 	 * Flush TSB and calculate number of pages to flush.
12402 	 */
12403 	while (bitvec != 0) {
12404 		dirtypg = 0;
12405 		/*
12406 		 * Find the first page to flush and then count how many
12407 		 * pages there are after it that also need to be flushed.
12408 		 * This way the number of TSB flushes is minimized.
12409 		 */
12410 		while ((bitvec & 1) == 0) {
12411 			pgcnt++;
12412 			addr += MMU_PAGESIZE;
12413 			bitvec >>= 1;
12414 		}
12415 		while (bitvec & 1) {
12416 			dirtypg++;
12417 			bitvec >>= 1;
12418 		}
12419 		eaddr = addr + ptob(dirtypg);
12420 		hatlockp = sfmmu_hat_enter(sfmmup);
12421 		sfmmu_unload_tsb_range(sfmmup, addr, eaddr, TTE8K);
12422 		sfmmu_hat_exit(hatlockp);
12423 		pgunload += dirtypg;
12424 		addr = eaddr;
12425 		pgcnt += dirtypg;
12426 	}
12427 
12428 	ASSERT((pgcnt<<MMU_PAGESHIFT) <= dmrp->dmr_endaddr - dmrp->dmr_addr);
12429 	if (sfmmup->sfmmu_free == 0) {
12430 		addr = dmrp->dmr_addr;
12431 		bitvec = dmrp->dmr_bitvec;
12432 
12433 		/*
12434 		 * make sure it has SFMMU_PGCNT_SHIFT bits only,
12435 		 * as it will be used to pack argument for xt_some
12436 		 */
12437 		ASSERT((pgcnt > 0) &&
12438 		    (pgcnt <= (1 << SFMMU_PGCNT_SHIFT)));
12439 
12440 		/*
12441 		 * Encode pgcnt as (pgcnt -1 ), and pass (pgcnt - 1) in
12442 		 * the low 6 bits of sfmmup. This is doable since pgcnt
12443 		 * always >= 1.
12444 		 */
12445 		ASSERT(!((uint64_t)sfmmup & SFMMU_PGCNT_MASK));
12446 		sfmmu_pgcnt = (uint64_t)sfmmup |
12447 		    ((pgcnt - 1) & SFMMU_PGCNT_MASK);
12448 
12449 		/*
12450 		 * We must hold the hat lock during the flush of TLB,
12451 		 * to avoid a race with sfmmu_invalidate_ctx(), where
12452 		 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12453 		 * causing TLB demap routine to skip flush on that MMU.
12454 		 * If the context on a MMU has already been set to
12455 		 * INVALID_CONTEXT, we just get an extra flush on
12456 		 * that MMU.
12457 		 */
12458 		hatlockp = sfmmu_hat_enter(sfmmup);
12459 		kpreempt_disable();
12460 
12461 		cpuset = sfmmup->sfmmu_cpusran;
12462 		CPUSET_AND(cpuset, cpu_ready_set);
12463 		CPUSET_DEL(cpuset, CPU->cpu_id);
12464 
12465 		SFMMU_XCALL_STATS(sfmmup);
12466 		xt_some(cpuset, vtag_flush_pgcnt_tl1, (uint64_t)addr,
12467 		    sfmmu_pgcnt);
12468 
12469 		for (; bitvec != 0; bitvec >>= 1) {
12470 			if (bitvec & 1)
12471 				vtag_flushpage(addr, (uint64_t)sfmmup);
12472 			addr += MMU_PAGESIZE;
12473 		}
12474 		kpreempt_enable();
12475 		sfmmu_hat_exit(hatlockp);
12476 
12477 		sfmmu_xcall_save += (pgunload-1);
12478 	}
12479 	dmrp->dmr_bitvec = 0;
12480 }
12481 
12482 /*
12483  * In cases where we need to synchronize with TLB/TSB miss trap
12484  * handlers, _and_ need to flush the TLB, it's a lot easier to
12485  * throw away the context from the process than to do a
12486  * special song and dance to keep things consistent for the
12487  * handlers.
12488  *
12489  * Since the process suddenly ends up without a context and our caller
12490  * holds the hat lock, threads that fault after this function is called
12491  * will pile up on the lock.  We can then do whatever we need to
12492  * atomically from the context of the caller.  The first blocked thread
12493  * to resume executing will get the process a new context, and the
12494  * process will resume executing.
12495  *
12496  * One added advantage of this approach is that on MMUs that
12497  * support a "flush all" operation, we will delay the flush until
12498  * cnum wrap-around, and then flush the TLB one time.  This
12499  * is rather rare, so it's a lot less expensive than making 8000
12500  * x-calls to flush the TLB 8000 times.
12501  *
12502  * A per-process (PP) lock is used to synchronize ctx allocations in
12503  * resume() and ctx invalidations here.
12504  */
12505 static void
12506 sfmmu_invalidate_ctx(sfmmu_t *sfmmup)
12507 {
12508 	cpuset_t cpuset;
12509 	int cnum, currcnum;
12510 	mmu_ctx_t *mmu_ctxp;
12511 	int i;
12512 	uint_t pstate_save;
12513 
12514 	SFMMU_STAT(sf_ctx_inv);
12515 
12516 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12517 	ASSERT(sfmmup != ksfmmup);
12518 
12519 	kpreempt_disable();
12520 
12521 	mmu_ctxp = CPU_MMU_CTXP(CPU);
12522 	ASSERT(mmu_ctxp);
12523 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
12524 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
12525 
12526 	currcnum = sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum;
12527 
12528 	pstate_save = sfmmu_disable_intrs();
12529 
12530 	lock_set(&sfmmup->sfmmu_ctx_lock);	/* acquire PP lock */
12531 	/* set HAT cnum invalid across all context domains. */
12532 	for (i = 0; i < max_mmu_ctxdoms; i++) {
12533 
12534 		cnum = 	sfmmup->sfmmu_ctxs[i].cnum;
12535 		if (cnum == INVALID_CONTEXT) {
12536 			continue;
12537 		}
12538 
12539 		sfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
12540 	}
12541 	membar_enter();	/* make sure globally visible to all CPUs */
12542 	lock_clear(&sfmmup->sfmmu_ctx_lock);	/* release PP lock */
12543 
12544 	sfmmu_enable_intrs(pstate_save);
12545 
12546 	cpuset = sfmmup->sfmmu_cpusran;
12547 	CPUSET_DEL(cpuset, CPU->cpu_id);
12548 	CPUSET_AND(cpuset, cpu_ready_set);
12549 	if (!CPUSET_ISNULL(cpuset)) {
12550 		SFMMU_XCALL_STATS(sfmmup);
12551 		xt_some(cpuset, sfmmu_raise_tsb_exception,
12552 		    (uint64_t)sfmmup, INVALID_CONTEXT);
12553 		xt_sync(cpuset);
12554 		SFMMU_STAT(sf_tsb_raise_exception);
12555 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
12556 	}
12557 
12558 	/*
12559 	 * If the hat to-be-invalidated is the same as the current
12560 	 * process on local CPU we need to invalidate
12561 	 * this CPU context as well.
12562 	 */
12563 	if ((sfmmu_getctx_sec() == currcnum) &&
12564 	    (currcnum != INVALID_CONTEXT)) {
12565 		/* sets shared context to INVALID too */
12566 		sfmmu_setctx_sec(INVALID_CONTEXT);
12567 		sfmmu_clear_utsbinfo();
12568 	}
12569 
12570 	SFMMU_FLAGS_SET(sfmmup, HAT_ALLCTX_INVALID);
12571 
12572 	kpreempt_enable();
12573 
12574 	/*
12575 	 * we hold the hat lock, so nobody should allocate a context
12576 	 * for us yet
12577 	 */
12578 	ASSERT(sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum == INVALID_CONTEXT);
12579 }
12580 
12581 #ifdef VAC
12582 /*
12583  * We need to flush the cache in all cpus.  It is possible that
12584  * a process referenced a page as cacheable but has sinced exited
12585  * and cleared the mapping list.  We still to flush it but have no
12586  * state so all cpus is the only alternative.
12587  */
12588 void
12589 sfmmu_cache_flush(pfn_t pfnum, int vcolor)
12590 {
12591 	cpuset_t cpuset;
12592 
12593 	kpreempt_disable();
12594 	cpuset = cpu_ready_set;
12595 	CPUSET_DEL(cpuset, CPU->cpu_id);
12596 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12597 	xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12598 	xt_sync(cpuset);
12599 	vac_flushpage(pfnum, vcolor);
12600 	kpreempt_enable();
12601 }
12602 
12603 void
12604 sfmmu_cache_flushcolor(int vcolor, pfn_t pfnum)
12605 {
12606 	cpuset_t cpuset;
12607 
12608 	ASSERT(vcolor >= 0);
12609 
12610 	kpreempt_disable();
12611 	cpuset = cpu_ready_set;
12612 	CPUSET_DEL(cpuset, CPU->cpu_id);
12613 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12614 	xt_some(cpuset, vac_flushcolor_tl1, vcolor, pfnum);
12615 	xt_sync(cpuset);
12616 	vac_flushcolor(vcolor, pfnum);
12617 	kpreempt_enable();
12618 }
12619 #endif	/* VAC */
12620 
12621 /*
12622  * We need to prevent processes from accessing the TSB using a cached physical
12623  * address.  It's alright if they try to access the TSB via virtual address
12624  * since they will just fault on that virtual address once the mapping has
12625  * been suspended.
12626  */
12627 #pragma weak sendmondo_in_recover
12628 
12629 /* ARGSUSED */
12630 static int
12631 sfmmu_tsb_pre_relocator(caddr_t va, uint_t tsbsz, uint_t flags, void *tsbinfo)
12632 {
12633 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12634 	sfmmu_t *sfmmup = tsbinfop->tsb_sfmmu;
12635 	hatlock_t *hatlockp;
12636 	sf_scd_t *scdp;
12637 
12638 	if (flags != HAT_PRESUSPEND)
12639 		return (0);
12640 
12641 	/*
12642 	 * If tsb is a shared TSB with TSB_SHAREDCTX set, sfmmup must
12643 	 * be a shared hat, then set SCD's tsbinfo's flag.
12644 	 * If tsb is not shared, sfmmup is a private hat, then set
12645 	 * its private tsbinfo's flag.
12646 	 */
12647 	hatlockp = sfmmu_hat_enter(sfmmup);
12648 	tsbinfop->tsb_flags |= TSB_RELOC_FLAG;
12649 
12650 	if (!(tsbinfop->tsb_flags & TSB_SHAREDCTX)) {
12651 		sfmmu_tsb_inv_ctx(sfmmup);
12652 		sfmmu_hat_exit(hatlockp);
12653 	} else {
12654 		/* release lock on the shared hat */
12655 		sfmmu_hat_exit(hatlockp);
12656 		/* sfmmup is a shared hat */
12657 		ASSERT(sfmmup->sfmmu_scdhat);
12658 		scdp = sfmmup->sfmmu_scdp;
12659 		ASSERT(scdp != NULL);
12660 		/* get private hat from the scd list */
12661 		mutex_enter(&scdp->scd_mutex);
12662 		sfmmup = scdp->scd_sf_list;
12663 		while (sfmmup != NULL) {
12664 			hatlockp = sfmmu_hat_enter(sfmmup);
12665 			/*
12666 			 * We do not call sfmmu_tsb_inv_ctx here because
12667 			 * sendmondo_in_recover check is only needed for
12668 			 * sun4u.
12669 			 */
12670 			sfmmu_invalidate_ctx(sfmmup);
12671 			sfmmu_hat_exit(hatlockp);
12672 			sfmmup = sfmmup->sfmmu_scd_link.next;
12673 
12674 		}
12675 		mutex_exit(&scdp->scd_mutex);
12676 	}
12677 	return (0);
12678 }
12679 
12680 static void
12681 sfmmu_tsb_inv_ctx(sfmmu_t *sfmmup)
12682 {
12683 	extern uint32_t sendmondo_in_recover;
12684 
12685 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12686 
12687 	/*
12688 	 * For Cheetah+ Erratum 25:
12689 	 * Wait for any active recovery to finish.  We can't risk
12690 	 * relocating the TSB of the thread running mondo_recover_proc()
12691 	 * since, if we did that, we would deadlock.  The scenario we are
12692 	 * trying to avoid is as follows:
12693 	 *
12694 	 * THIS CPU			RECOVER CPU
12695 	 * --------			-----------
12696 	 *				Begins recovery, walking through TSB
12697 	 * hat_pagesuspend() TSB TTE
12698 	 *				TLB miss on TSB TTE, spins at TL1
12699 	 * xt_sync()
12700 	 *	send_mondo_timeout()
12701 	 *	mondo_recover_proc()
12702 	 *	((deadlocked))
12703 	 *
12704 	 * The second half of the workaround is that mondo_recover_proc()
12705 	 * checks to see if the tsb_info has the RELOC flag set, and if it
12706 	 * does, it skips over that TSB without ever touching tsbinfop->tsb_va
12707 	 * and hence avoiding the TLB miss that could result in a deadlock.
12708 	 */
12709 	if (&sendmondo_in_recover) {
12710 		membar_enter();	/* make sure RELOC flag visible */
12711 		while (sendmondo_in_recover) {
12712 			drv_usecwait(1);
12713 			membar_consumer();
12714 		}
12715 	}
12716 
12717 	sfmmu_invalidate_ctx(sfmmup);
12718 }
12719 
12720 /* ARGSUSED */
12721 static int
12722 sfmmu_tsb_post_relocator(caddr_t va, uint_t tsbsz, uint_t flags,
12723 	void *tsbinfo, pfn_t newpfn)
12724 {
12725 	hatlock_t *hatlockp;
12726 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12727 	sfmmu_t	*sfmmup = tsbinfop->tsb_sfmmu;
12728 
12729 	if (flags != HAT_POSTUNSUSPEND)
12730 		return (0);
12731 
12732 	hatlockp = sfmmu_hat_enter(sfmmup);
12733 
12734 	SFMMU_STAT(sf_tsb_reloc);
12735 
12736 	/*
12737 	 * The process may have swapped out while we were relocating one
12738 	 * of its TSBs.  If so, don't bother doing the setup since the
12739 	 * process can't be using the memory anymore.
12740 	 */
12741 	if ((tsbinfop->tsb_flags & TSB_SWAPPED) == 0) {
12742 		ASSERT(va == tsbinfop->tsb_va);
12743 		sfmmu_tsbinfo_setup_phys(tsbinfop, newpfn);
12744 
12745 		if (tsbinfop->tsb_flags & TSB_FLUSH_NEEDED) {
12746 			sfmmu_inv_tsb(tsbinfop->tsb_va,
12747 			    TSB_BYTES(tsbinfop->tsb_szc));
12748 			tsbinfop->tsb_flags &= ~TSB_FLUSH_NEEDED;
12749 		}
12750 	}
12751 
12752 	membar_exit();
12753 	tsbinfop->tsb_flags &= ~TSB_RELOC_FLAG;
12754 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
12755 
12756 	sfmmu_hat_exit(hatlockp);
12757 
12758 	return (0);
12759 }
12760 
12761 /*
12762  * Allocate and initialize a tsb_info structure.  Note that we may or may not
12763  * allocate a TSB here, depending on the flags passed in.
12764  */
12765 static int
12766 sfmmu_tsbinfo_alloc(struct tsb_info **tsbinfopp, int tsb_szc, int tte_sz_mask,
12767 	uint_t flags, sfmmu_t *sfmmup)
12768 {
12769 	int err;
12770 
12771 	*tsbinfopp = (struct tsb_info *)kmem_cache_alloc(
12772 	    sfmmu_tsbinfo_cache, KM_SLEEP);
12773 
12774 	if ((err = sfmmu_init_tsbinfo(*tsbinfopp, tte_sz_mask,
12775 	    tsb_szc, flags, sfmmup)) != 0) {
12776 		kmem_cache_free(sfmmu_tsbinfo_cache, *tsbinfopp);
12777 		SFMMU_STAT(sf_tsb_allocfail);
12778 		*tsbinfopp = NULL;
12779 		return (err);
12780 	}
12781 	SFMMU_STAT(sf_tsb_alloc);
12782 
12783 	/*
12784 	 * Bump the TSB size counters for this TSB size.
12785 	 */
12786 	(*(((int *)&sfmmu_tsbsize_stat) + tsb_szc))++;
12787 	return (0);
12788 }
12789 
12790 static void
12791 sfmmu_tsb_free(struct tsb_info *tsbinfo)
12792 {
12793 	caddr_t tsbva = tsbinfo->tsb_va;
12794 	uint_t tsb_size = TSB_BYTES(tsbinfo->tsb_szc);
12795 	struct kmem_cache *kmem_cachep = tsbinfo->tsb_cache;
12796 	vmem_t	*vmp = tsbinfo->tsb_vmp;
12797 
12798 	/*
12799 	 * If we allocated this TSB from relocatable kernel memory, then we
12800 	 * need to uninstall the callback handler.
12801 	 */
12802 	if (tsbinfo->tsb_cache != sfmmu_tsb8k_cache) {
12803 		uintptr_t slab_mask;
12804 		caddr_t slab_vaddr;
12805 		page_t **ppl;
12806 		int ret;
12807 
12808 		ASSERT(tsb_size <= MMU_PAGESIZE4M || use_bigtsb_arena);
12809 		if (tsb_size > MMU_PAGESIZE4M)
12810 			slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12811 		else
12812 			slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12813 		slab_vaddr = (caddr_t)((uintptr_t)tsbva & slab_mask);
12814 
12815 		ret = as_pagelock(&kas, &ppl, slab_vaddr, PAGESIZE, S_WRITE);
12816 		ASSERT(ret == 0);
12817 		hat_delete_callback(tsbva, (uint_t)tsb_size, (void *)tsbinfo,
12818 		    0, NULL);
12819 		as_pageunlock(&kas, ppl, slab_vaddr, PAGESIZE, S_WRITE);
12820 	}
12821 
12822 	if (kmem_cachep != NULL) {
12823 		kmem_cache_free(kmem_cachep, tsbva);
12824 	} else {
12825 		vmem_xfree(vmp, (void *)tsbva, tsb_size);
12826 	}
12827 	tsbinfo->tsb_va = (caddr_t)0xbad00bad;
12828 	atomic_add_64(&tsb_alloc_bytes, -(int64_t)tsb_size);
12829 }
12830 
12831 static void
12832 sfmmu_tsbinfo_free(struct tsb_info *tsbinfo)
12833 {
12834 	if ((tsbinfo->tsb_flags & TSB_SWAPPED) == 0) {
12835 		sfmmu_tsb_free(tsbinfo);
12836 	}
12837 	kmem_cache_free(sfmmu_tsbinfo_cache, tsbinfo);
12838 
12839 }
12840 
12841 /*
12842  * Setup all the references to physical memory for this tsbinfo.
12843  * The underlying page(s) must be locked.
12844  */
12845 static void
12846 sfmmu_tsbinfo_setup_phys(struct tsb_info *tsbinfo, pfn_t pfn)
12847 {
12848 	ASSERT(pfn != PFN_INVALID);
12849 	ASSERT(pfn == va_to_pfn(tsbinfo->tsb_va));
12850 
12851 #ifndef sun4v
12852 	if (tsbinfo->tsb_szc == 0) {
12853 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn,
12854 		    PROT_WRITE|PROT_READ, TTE8K);
12855 	} else {
12856 		/*
12857 		 * Round down PA and use a large mapping; the handlers will
12858 		 * compute the TSB pointer at the correct offset into the
12859 		 * big virtual page.  NOTE: this assumes all TSBs larger
12860 		 * than 8K must come from physically contiguous slabs of
12861 		 * size tsb_slab_size.
12862 		 */
12863 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn & ~tsb_slab_mask,
12864 		    PROT_WRITE|PROT_READ, tsb_slab_ttesz);
12865 	}
12866 	tsbinfo->tsb_pa = ptob(pfn);
12867 
12868 	TTE_SET_LOCKED(&tsbinfo->tsb_tte); /* lock the tte into dtlb */
12869 	TTE_SET_MOD(&tsbinfo->tsb_tte);    /* enable writes */
12870 
12871 	ASSERT(TTE_IS_PRIVILEGED(&tsbinfo->tsb_tte));
12872 	ASSERT(TTE_IS_LOCKED(&tsbinfo->tsb_tte));
12873 #else /* sun4v */
12874 	tsbinfo->tsb_pa = ptob(pfn);
12875 #endif /* sun4v */
12876 }
12877 
12878 
12879 /*
12880  * Returns zero on success, ENOMEM if over the high water mark,
12881  * or EAGAIN if the caller needs to retry with a smaller TSB
12882  * size (or specify TSB_FORCEALLOC if the allocation can't fail).
12883  *
12884  * This call cannot fail to allocate a TSB if TSB_FORCEALLOC
12885  * is specified and the TSB requested is PAGESIZE, though it
12886  * may sleep waiting for memory if sufficient memory is not
12887  * available.
12888  */
12889 static int
12890 sfmmu_init_tsbinfo(struct tsb_info *tsbinfo, int tteszmask,
12891     int tsbcode, uint_t flags, sfmmu_t *sfmmup)
12892 {
12893 	caddr_t vaddr = NULL;
12894 	caddr_t slab_vaddr;
12895 	uintptr_t slab_mask;
12896 	int tsbbytes = TSB_BYTES(tsbcode);
12897 	int lowmem = 0;
12898 	struct kmem_cache *kmem_cachep = NULL;
12899 	vmem_t *vmp = NULL;
12900 	lgrp_id_t lgrpid = LGRP_NONE;
12901 	pfn_t pfn;
12902 	uint_t cbflags = HAC_SLEEP;
12903 	page_t **pplist;
12904 	int ret;
12905 
12906 	ASSERT(tsbbytes <= MMU_PAGESIZE4M || use_bigtsb_arena);
12907 	if (tsbbytes > MMU_PAGESIZE4M)
12908 		slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12909 	else
12910 		slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12911 
12912 	if (flags & (TSB_FORCEALLOC | TSB_SWAPIN | TSB_GROW | TSB_SHRINK))
12913 		flags |= TSB_ALLOC;
12914 
12915 	ASSERT((flags & TSB_FORCEALLOC) == 0 || tsbcode == TSB_MIN_SZCODE);
12916 
12917 	tsbinfo->tsb_sfmmu = sfmmup;
12918 
12919 	/*
12920 	 * If not allocating a TSB, set up the tsbinfo, set TSB_SWAPPED, and
12921 	 * return.
12922 	 */
12923 	if ((flags & TSB_ALLOC) == 0) {
12924 		tsbinfo->tsb_szc = tsbcode;
12925 		tsbinfo->tsb_ttesz_mask = tteszmask;
12926 		tsbinfo->tsb_va = (caddr_t)0xbadbadbeef;
12927 		tsbinfo->tsb_pa = -1;
12928 		tsbinfo->tsb_tte.ll = 0;
12929 		tsbinfo->tsb_next = NULL;
12930 		tsbinfo->tsb_flags = TSB_SWAPPED;
12931 		tsbinfo->tsb_cache = NULL;
12932 		tsbinfo->tsb_vmp = NULL;
12933 		return (0);
12934 	}
12935 
12936 #ifdef DEBUG
12937 	/*
12938 	 * For debugging:
12939 	 * Randomly force allocation failures every tsb_alloc_mtbf
12940 	 * tries if TSB_FORCEALLOC is not specified.  This will
12941 	 * return ENOMEM if tsb_alloc_mtbf is odd, or EAGAIN if
12942 	 * it is even, to allow testing of both failure paths...
12943 	 */
12944 	if (tsb_alloc_mtbf && ((flags & TSB_FORCEALLOC) == 0) &&
12945 	    (tsb_alloc_count++ == tsb_alloc_mtbf)) {
12946 		tsb_alloc_count = 0;
12947 		tsb_alloc_fail_mtbf++;
12948 		return ((tsb_alloc_mtbf & 1)? ENOMEM : EAGAIN);
12949 	}
12950 #endif	/* DEBUG */
12951 
12952 	/*
12953 	 * Enforce high water mark if we are not doing a forced allocation
12954 	 * and are not shrinking a process' TSB.
12955 	 */
12956 	if ((flags & TSB_SHRINK) == 0 &&
12957 	    (tsbbytes + tsb_alloc_bytes) > tsb_alloc_hiwater) {
12958 		if ((flags & TSB_FORCEALLOC) == 0)
12959 			return (ENOMEM);
12960 		lowmem = 1;
12961 	}
12962 
12963 	/*
12964 	 * Allocate from the correct location based upon the size of the TSB
12965 	 * compared to the base page size, and what memory conditions dictate.
12966 	 * Note we always do nonblocking allocations from the TSB arena since
12967 	 * we don't want memory fragmentation to cause processes to block
12968 	 * indefinitely waiting for memory; until the kernel algorithms that
12969 	 * coalesce large pages are improved this is our best option.
12970 	 *
12971 	 * Algorithm:
12972 	 *	If allocating a "large" TSB (>8K), allocate from the
12973 	 *		appropriate kmem_tsb_default_arena vmem arena
12974 	 *	else if low on memory or the TSB_FORCEALLOC flag is set or
12975 	 *	tsb_forceheap is set
12976 	 *		Allocate from kernel heap via sfmmu_tsb8k_cache with
12977 	 *		KM_SLEEP (never fails)
12978 	 *	else
12979 	 *		Allocate from appropriate sfmmu_tsb_cache with
12980 	 *		KM_NOSLEEP
12981 	 *	endif
12982 	 */
12983 	if (tsb_lgrp_affinity)
12984 		lgrpid = lgrp_home_id(curthread);
12985 	if (lgrpid == LGRP_NONE)
12986 		lgrpid = 0;	/* use lgrp of boot CPU */
12987 
12988 	if (tsbbytes > MMU_PAGESIZE) {
12989 		if (tsbbytes > MMU_PAGESIZE4M) {
12990 			vmp = kmem_bigtsb_default_arena[lgrpid];
12991 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
12992 			    0, 0, NULL, NULL, VM_NOSLEEP);
12993 		} else {
12994 			vmp = kmem_tsb_default_arena[lgrpid];
12995 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
12996 			    0, 0, NULL, NULL, VM_NOSLEEP);
12997 		}
12998 #ifdef	DEBUG
12999 	} else if (lowmem || (flags & TSB_FORCEALLOC) || tsb_forceheap) {
13000 #else	/* !DEBUG */
13001 	} else if (lowmem || (flags & TSB_FORCEALLOC)) {
13002 #endif	/* DEBUG */
13003 		kmem_cachep = sfmmu_tsb8k_cache;
13004 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_SLEEP);
13005 		ASSERT(vaddr != NULL);
13006 	} else {
13007 		kmem_cachep = sfmmu_tsb_cache[lgrpid];
13008 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_NOSLEEP);
13009 	}
13010 
13011 	tsbinfo->tsb_cache = kmem_cachep;
13012 	tsbinfo->tsb_vmp = vmp;
13013 
13014 	if (vaddr == NULL) {
13015 		return (EAGAIN);
13016 	}
13017 
13018 	atomic_add_64(&tsb_alloc_bytes, (int64_t)tsbbytes);
13019 	kmem_cachep = tsbinfo->tsb_cache;
13020 
13021 	/*
13022 	 * If we are allocating from outside the cage, then we need to
13023 	 * register a relocation callback handler.  Note that for now
13024 	 * since pseudo mappings always hang off of the slab's root page,
13025 	 * we need only lock the first 8K of the TSB slab.  This is a bit
13026 	 * hacky but it is good for performance.
13027 	 */
13028 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13029 		slab_vaddr = (caddr_t)((uintptr_t)vaddr & slab_mask);
13030 		ret = as_pagelock(&kas, &pplist, slab_vaddr, PAGESIZE, S_WRITE);
13031 		ASSERT(ret == 0);
13032 		ret = hat_add_callback(sfmmu_tsb_cb_id, vaddr, (uint_t)tsbbytes,
13033 		    cbflags, (void *)tsbinfo, &pfn, NULL);
13034 
13035 		/*
13036 		 * Need to free up resources if we could not successfully
13037 		 * add the callback function and return an error condition.
13038 		 */
13039 		if (ret != 0) {
13040 			if (kmem_cachep) {
13041 				kmem_cache_free(kmem_cachep, vaddr);
13042 			} else {
13043 				vmem_xfree(vmp, (void *)vaddr, tsbbytes);
13044 			}
13045 			as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE,
13046 			    S_WRITE);
13047 			return (EAGAIN);
13048 		}
13049 	} else {
13050 		/*
13051 		 * Since allocation of 8K TSBs from heap is rare and occurs
13052 		 * during memory pressure we allocate them from permanent
13053 		 * memory rather than using callbacks to get the PFN.
13054 		 */
13055 		pfn = hat_getpfnum(kas.a_hat, vaddr);
13056 	}
13057 
13058 	tsbinfo->tsb_va = vaddr;
13059 	tsbinfo->tsb_szc = tsbcode;
13060 	tsbinfo->tsb_ttesz_mask = tteszmask;
13061 	tsbinfo->tsb_next = NULL;
13062 	tsbinfo->tsb_flags = 0;
13063 
13064 	sfmmu_tsbinfo_setup_phys(tsbinfo, pfn);
13065 
13066 	sfmmu_inv_tsb(vaddr, tsbbytes);
13067 
13068 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13069 		as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE, S_WRITE);
13070 	}
13071 
13072 	return (0);
13073 }
13074 
13075 /*
13076  * Initialize per cpu tsb and per cpu tsbmiss_area
13077  */
13078 void
13079 sfmmu_init_tsbs(void)
13080 {
13081 	int i;
13082 	struct tsbmiss	*tsbmissp;
13083 	struct kpmtsbm	*kpmtsbmp;
13084 #ifndef sun4v
13085 	extern int	dcache_line_mask;
13086 #endif /* sun4v */
13087 	extern uint_t	vac_colors;
13088 
13089 	/*
13090 	 * Init. tsb miss area.
13091 	 */
13092 	tsbmissp = tsbmiss_area;
13093 
13094 	for (i = 0; i < NCPU; tsbmissp++, i++) {
13095 		/*
13096 		 * initialize the tsbmiss area.
13097 		 * Do this for all possible CPUs as some may be added
13098 		 * while the system is running. There is no cost to this.
13099 		 */
13100 		tsbmissp->ksfmmup = ksfmmup;
13101 #ifndef sun4v
13102 		tsbmissp->dcache_line_mask = (uint16_t)dcache_line_mask;
13103 #endif /* sun4v */
13104 		tsbmissp->khashstart =
13105 		    (struct hmehash_bucket *)va_to_pa((caddr_t)khme_hash);
13106 		tsbmissp->uhashstart =
13107 		    (struct hmehash_bucket *)va_to_pa((caddr_t)uhme_hash);
13108 		tsbmissp->khashsz = khmehash_num;
13109 		tsbmissp->uhashsz = uhmehash_num;
13110 	}
13111 
13112 	sfmmu_tsb_cb_id = hat_register_callback('T'<<16 | 'S' << 8 | 'B',
13113 	    sfmmu_tsb_pre_relocator, sfmmu_tsb_post_relocator, NULL, 0);
13114 
13115 	if (kpm_enable == 0)
13116 		return;
13117 
13118 	/* -- Begin KPM specific init -- */
13119 
13120 	if (kpm_smallpages) {
13121 		/*
13122 		 * If we're using base pagesize pages for seg_kpm
13123 		 * mappings, we use the kernel TSB since we can't afford
13124 		 * to allocate a second huge TSB for these mappings.
13125 		 */
13126 		kpm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13127 		kpm_tsbsz = ktsb_szcode;
13128 		kpmsm_tsbbase = kpm_tsbbase;
13129 		kpmsm_tsbsz = kpm_tsbsz;
13130 	} else {
13131 		/*
13132 		 * In VAC conflict case, just put the entries in the
13133 		 * kernel 8K indexed TSB for now so we can find them.
13134 		 * This could really be changed in the future if we feel
13135 		 * the need...
13136 		 */
13137 		kpmsm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13138 		kpmsm_tsbsz = ktsb_szcode;
13139 		kpm_tsbbase = ktsb_phys? ktsb4m_pbase : (uint64_t)ktsb4m_base;
13140 		kpm_tsbsz = ktsb4m_szcode;
13141 	}
13142 
13143 	kpmtsbmp = kpmtsbm_area;
13144 	for (i = 0; i < NCPU; kpmtsbmp++, i++) {
13145 		/*
13146 		 * Initialize the kpmtsbm area.
13147 		 * Do this for all possible CPUs as some may be added
13148 		 * while the system is running. There is no cost to this.
13149 		 */
13150 		kpmtsbmp->vbase = kpm_vbase;
13151 		kpmtsbmp->vend = kpm_vbase + kpm_size * vac_colors;
13152 		kpmtsbmp->sz_shift = kpm_size_shift;
13153 		kpmtsbmp->kpmp_shift = kpmp_shift;
13154 		kpmtsbmp->kpmp2pshft = (uchar_t)kpmp2pshft;
13155 		if (kpm_smallpages == 0) {
13156 			kpmtsbmp->kpmp_table_sz = kpmp_table_sz;
13157 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_table);
13158 		} else {
13159 			kpmtsbmp->kpmp_table_sz = kpmp_stable_sz;
13160 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_stable);
13161 		}
13162 		kpmtsbmp->msegphashpa = va_to_pa(memseg_phash);
13163 		kpmtsbmp->flags = KPMTSBM_ENABLE_FLAG;
13164 #ifdef	DEBUG
13165 		kpmtsbmp->flags |= (kpm_tsbmtl) ?  KPMTSBM_TLTSBM_FLAG : 0;
13166 #endif	/* DEBUG */
13167 		if (ktsb_phys)
13168 			kpmtsbmp->flags |= KPMTSBM_TSBPHYS_FLAG;
13169 	}
13170 
13171 	/* -- End KPM specific init -- */
13172 }
13173 
13174 /* Avoid using sfmmu_tsbinfo_alloc() to avoid kmem_alloc - no real reason */
13175 struct tsb_info ktsb_info[2];
13176 
13177 /*
13178  * Called from hat_kern_setup() to setup the tsb_info for ksfmmup.
13179  */
13180 void
13181 sfmmu_init_ktsbinfo()
13182 {
13183 	ASSERT(ksfmmup != NULL);
13184 	ASSERT(ksfmmup->sfmmu_tsb == NULL);
13185 	/*
13186 	 * Allocate tsbinfos for kernel and copy in data
13187 	 * to make debug easier and sun4v setup easier.
13188 	 */
13189 	ktsb_info[0].tsb_sfmmu = ksfmmup;
13190 	ktsb_info[0].tsb_szc = ktsb_szcode;
13191 	ktsb_info[0].tsb_ttesz_mask = TSB8K|TSB64K|TSB512K;
13192 	ktsb_info[0].tsb_va = ktsb_base;
13193 	ktsb_info[0].tsb_pa = ktsb_pbase;
13194 	ktsb_info[0].tsb_flags = 0;
13195 	ktsb_info[0].tsb_tte.ll = 0;
13196 	ktsb_info[0].tsb_cache = NULL;
13197 
13198 	ktsb_info[1].tsb_sfmmu = ksfmmup;
13199 	ktsb_info[1].tsb_szc = ktsb4m_szcode;
13200 	ktsb_info[1].tsb_ttesz_mask = TSB4M;
13201 	ktsb_info[1].tsb_va = ktsb4m_base;
13202 	ktsb_info[1].tsb_pa = ktsb4m_pbase;
13203 	ktsb_info[1].tsb_flags = 0;
13204 	ktsb_info[1].tsb_tte.ll = 0;
13205 	ktsb_info[1].tsb_cache = NULL;
13206 
13207 	/* Link them into ksfmmup. */
13208 	ktsb_info[0].tsb_next = &ktsb_info[1];
13209 	ktsb_info[1].tsb_next = NULL;
13210 	ksfmmup->sfmmu_tsb = &ktsb_info[0];
13211 
13212 	sfmmu_setup_tsbinfo(ksfmmup);
13213 }
13214 
13215 /*
13216  * Cache the last value returned from va_to_pa().  If the VA specified
13217  * in the current call to cached_va_to_pa() maps to the same Page (as the
13218  * previous call to cached_va_to_pa()), then compute the PA using
13219  * cached info, else call va_to_pa().
13220  *
13221  * Note: this function is neither MT-safe nor consistent in the presence
13222  * of multiple, interleaved threads.  This function was created to enable
13223  * an optimization used during boot (at a point when there's only one thread
13224  * executing on the "boot CPU", and before startup_vm() has been called).
13225  */
13226 static uint64_t
13227 cached_va_to_pa(void *vaddr)
13228 {
13229 	static uint64_t prev_vaddr_base = 0;
13230 	static uint64_t prev_pfn = 0;
13231 
13232 	if ((((uint64_t)vaddr) & MMU_PAGEMASK) == prev_vaddr_base) {
13233 		return (prev_pfn | ((uint64_t)vaddr & MMU_PAGEOFFSET));
13234 	} else {
13235 		uint64_t pa = va_to_pa(vaddr);
13236 
13237 		if (pa != ((uint64_t)-1)) {
13238 			/*
13239 			 * Computed physical address is valid.  Cache its
13240 			 * related info for the next cached_va_to_pa() call.
13241 			 */
13242 			prev_pfn = pa & MMU_PAGEMASK;
13243 			prev_vaddr_base = ((uint64_t)vaddr) & MMU_PAGEMASK;
13244 		}
13245 
13246 		return (pa);
13247 	}
13248 }
13249 
13250 /*
13251  * Carve up our nucleus hblk region.  We may allocate more hblks than
13252  * asked due to rounding errors but we are guaranteed to have at least
13253  * enough space to allocate the requested number of hblk8's and hblk1's.
13254  */
13255 void
13256 sfmmu_init_nucleus_hblks(caddr_t addr, size_t size, int nhblk8, int nhblk1)
13257 {
13258 	struct hme_blk *hmeblkp;
13259 	size_t hme8blk_sz, hme1blk_sz;
13260 	size_t i;
13261 	size_t hblk8_bound;
13262 	ulong_t j = 0, k = 0;
13263 
13264 	ASSERT(addr != NULL && size != 0);
13265 
13266 	/* Need to use proper structure alignment */
13267 	hme8blk_sz = roundup(HME8BLK_SZ, sizeof (int64_t));
13268 	hme1blk_sz = roundup(HME1BLK_SZ, sizeof (int64_t));
13269 
13270 	nucleus_hblk8.list = (void *)addr;
13271 	nucleus_hblk8.index = 0;
13272 
13273 	/*
13274 	 * Use as much memory as possible for hblk8's since we
13275 	 * expect all bop_alloc'ed memory to be allocated in 8k chunks.
13276 	 * We need to hold back enough space for the hblk1's which
13277 	 * we'll allocate next.
13278 	 */
13279 	hblk8_bound = size - (nhblk1 * hme1blk_sz) - hme8blk_sz;
13280 	for (i = 0; i <= hblk8_bound; i += hme8blk_sz, j++) {
13281 		hmeblkp = (struct hme_blk *)addr;
13282 		addr += hme8blk_sz;
13283 		hmeblkp->hblk_nuc_bit = 1;
13284 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13285 	}
13286 	nucleus_hblk8.len = j;
13287 	ASSERT(j >= nhblk8);
13288 	SFMMU_STAT_ADD(sf_hblk8_ncreate, j);
13289 
13290 	nucleus_hblk1.list = (void *)addr;
13291 	nucleus_hblk1.index = 0;
13292 	for (; i <= (size - hme1blk_sz); i += hme1blk_sz, k++) {
13293 		hmeblkp = (struct hme_blk *)addr;
13294 		addr += hme1blk_sz;
13295 		hmeblkp->hblk_nuc_bit = 1;
13296 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13297 	}
13298 	ASSERT(k >= nhblk1);
13299 	nucleus_hblk1.len = k;
13300 	SFMMU_STAT_ADD(sf_hblk1_ncreate, k);
13301 }
13302 
13303 /*
13304  * This function is currently not supported on this platform. For what
13305  * it's supposed to do, see hat.c and hat_srmmu.c
13306  */
13307 /* ARGSUSED */
13308 faultcode_t
13309 hat_softlock(struct hat *hat, caddr_t addr, size_t *lenp, page_t **ppp,
13310     uint_t flags)
13311 {
13312 	ASSERT(hat->sfmmu_xhat_provider == NULL);
13313 	return (FC_NOSUPPORT);
13314 }
13315 
13316 /*
13317  * Searchs the mapping list of the page for a mapping of the same size. If not
13318  * found the corresponding bit is cleared in the p_index field. When large
13319  * pages are more prevalent in the system, we can maintain the mapping list
13320  * in order and we don't have to traverse the list each time. Just check the
13321  * next and prev entries, and if both are of different size, we clear the bit.
13322  */
13323 static void
13324 sfmmu_rm_large_mappings(page_t *pp, int ttesz)
13325 {
13326 	struct sf_hment *sfhmep;
13327 	struct hme_blk *hmeblkp;
13328 	int	index;
13329 	pgcnt_t	npgs;
13330 
13331 	ASSERT(ttesz > TTE8K);
13332 
13333 	ASSERT(sfmmu_mlist_held(pp));
13334 
13335 	ASSERT(PP_ISMAPPED_LARGE(pp));
13336 
13337 	/*
13338 	 * Traverse mapping list looking for another mapping of same size.
13339 	 * since we only want to clear index field if all mappings of
13340 	 * that size are gone.
13341 	 */
13342 
13343 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
13344 		if (IS_PAHME(sfhmep))
13345 			continue;
13346 		hmeblkp = sfmmu_hmetohblk(sfhmep);
13347 		if (hmeblkp->hblk_xhat_bit)
13348 			continue;
13349 		if (hme_size(sfhmep) == ttesz) {
13350 			/*
13351 			 * another mapping of the same size. don't clear index.
13352 			 */
13353 			return;
13354 		}
13355 	}
13356 
13357 	/*
13358 	 * Clear the p_index bit for large page.
13359 	 */
13360 	index = PAGESZ_TO_INDEX(ttesz);
13361 	npgs = TTEPAGES(ttesz);
13362 	while (npgs-- > 0) {
13363 		ASSERT(pp->p_index & index);
13364 		pp->p_index &= ~index;
13365 		pp = PP_PAGENEXT(pp);
13366 	}
13367 }
13368 
13369 /*
13370  * return supported features
13371  */
13372 /* ARGSUSED */
13373 int
13374 hat_supported(enum hat_features feature, void *arg)
13375 {
13376 	switch (feature) {
13377 	case    HAT_SHARED_PT:
13378 	case	HAT_DYNAMIC_ISM_UNMAP:
13379 	case	HAT_VMODSORT:
13380 		return (1);
13381 	case	HAT_SHARED_REGIONS:
13382 		if (shctx_on)
13383 			return (1);
13384 		else
13385 			return (0);
13386 	default:
13387 		return (0);
13388 	}
13389 }
13390 
13391 void
13392 hat_enter(struct hat *hat)
13393 {
13394 	hatlock_t	*hatlockp;
13395 
13396 	if (hat != ksfmmup) {
13397 		hatlockp = TSB_HASH(hat);
13398 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
13399 	}
13400 }
13401 
13402 void
13403 hat_exit(struct hat *hat)
13404 {
13405 	hatlock_t	*hatlockp;
13406 
13407 	if (hat != ksfmmup) {
13408 		hatlockp = TSB_HASH(hat);
13409 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
13410 	}
13411 }
13412 
13413 /*ARGSUSED*/
13414 void
13415 hat_reserve(struct as *as, caddr_t addr, size_t len)
13416 {
13417 }
13418 
13419 static void
13420 hat_kstat_init(void)
13421 {
13422 	kstat_t *ksp;
13423 
13424 	ksp = kstat_create("unix", 0, "sfmmu_global_stat", "hat",
13425 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_global_stat),
13426 	    KSTAT_FLAG_VIRTUAL);
13427 	if (ksp) {
13428 		ksp->ks_data = (void *) &sfmmu_global_stat;
13429 		kstat_install(ksp);
13430 	}
13431 	ksp = kstat_create("unix", 0, "sfmmu_tsbsize_stat", "hat",
13432 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_tsbsize_stat),
13433 	    KSTAT_FLAG_VIRTUAL);
13434 	if (ksp) {
13435 		ksp->ks_data = (void *) &sfmmu_tsbsize_stat;
13436 		kstat_install(ksp);
13437 	}
13438 	ksp = kstat_create("unix", 0, "sfmmu_percpu_stat", "hat",
13439 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_percpu_stat) * NCPU,
13440 	    KSTAT_FLAG_WRITABLE);
13441 	if (ksp) {
13442 		ksp->ks_update = sfmmu_kstat_percpu_update;
13443 		kstat_install(ksp);
13444 	}
13445 }
13446 
13447 /* ARGSUSED */
13448 static int
13449 sfmmu_kstat_percpu_update(kstat_t *ksp, int rw)
13450 {
13451 	struct sfmmu_percpu_stat *cpu_kstat = ksp->ks_data;
13452 	struct tsbmiss *tsbm = tsbmiss_area;
13453 	struct kpmtsbm *kpmtsbm = kpmtsbm_area;
13454 	int i;
13455 
13456 	ASSERT(cpu_kstat);
13457 	if (rw == KSTAT_READ) {
13458 		for (i = 0; i < NCPU; cpu_kstat++, tsbm++, kpmtsbm++, i++) {
13459 			cpu_kstat->sf_itlb_misses = 0;
13460 			cpu_kstat->sf_dtlb_misses = 0;
13461 			cpu_kstat->sf_utsb_misses = tsbm->utsb_misses -
13462 			    tsbm->uprot_traps;
13463 			cpu_kstat->sf_ktsb_misses = tsbm->ktsb_misses +
13464 			    kpmtsbm->kpm_tsb_misses - tsbm->kprot_traps;
13465 			cpu_kstat->sf_tsb_hits = 0;
13466 			cpu_kstat->sf_umod_faults = tsbm->uprot_traps;
13467 			cpu_kstat->sf_kmod_faults = tsbm->kprot_traps;
13468 		}
13469 	} else {
13470 		/* KSTAT_WRITE is used to clear stats */
13471 		for (i = 0; i < NCPU; tsbm++, kpmtsbm++, i++) {
13472 			tsbm->utsb_misses = 0;
13473 			tsbm->ktsb_misses = 0;
13474 			tsbm->uprot_traps = 0;
13475 			tsbm->kprot_traps = 0;
13476 			kpmtsbm->kpm_dtlb_misses = 0;
13477 			kpmtsbm->kpm_tsb_misses = 0;
13478 		}
13479 	}
13480 	return (0);
13481 }
13482 
13483 #ifdef	DEBUG
13484 
13485 tte_t  *gorig[NCPU], *gcur[NCPU], *gnew[NCPU];
13486 
13487 /*
13488  * A tte checker. *orig_old is the value we read before cas.
13489  *	*cur is the value returned by cas.
13490  *	*new is the desired value when we do the cas.
13491  *
13492  *	*hmeblkp is currently unused.
13493  */
13494 
13495 /* ARGSUSED */
13496 void
13497 chk_tte(tte_t *orig_old, tte_t *cur, tte_t *new, struct hme_blk *hmeblkp)
13498 {
13499 	pfn_t i, j, k;
13500 	int cpuid = CPU->cpu_id;
13501 
13502 	gorig[cpuid] = orig_old;
13503 	gcur[cpuid] = cur;
13504 	gnew[cpuid] = new;
13505 
13506 #ifdef lint
13507 	hmeblkp = hmeblkp;
13508 #endif
13509 
13510 	if (TTE_IS_VALID(orig_old)) {
13511 		if (TTE_IS_VALID(cur)) {
13512 			i = TTE_TO_TTEPFN(orig_old);
13513 			j = TTE_TO_TTEPFN(cur);
13514 			k = TTE_TO_TTEPFN(new);
13515 			if (i != j) {
13516 				/* remap error? */
13517 				panic("chk_tte: bad pfn, 0x%lx, 0x%lx", i, j);
13518 			}
13519 
13520 			if (i != k) {
13521 				/* remap error? */
13522 				panic("chk_tte: bad pfn2, 0x%lx, 0x%lx", i, k);
13523 			}
13524 		} else {
13525 			if (TTE_IS_VALID(new)) {
13526 				panic("chk_tte: invalid cur? ");
13527 			}
13528 
13529 			i = TTE_TO_TTEPFN(orig_old);
13530 			k = TTE_TO_TTEPFN(new);
13531 			if (i != k) {
13532 				panic("chk_tte: bad pfn3, 0x%lx, 0x%lx", i, k);
13533 			}
13534 		}
13535 	} else {
13536 		if (TTE_IS_VALID(cur)) {
13537 			j = TTE_TO_TTEPFN(cur);
13538 			if (TTE_IS_VALID(new)) {
13539 				k = TTE_TO_TTEPFN(new);
13540 				if (j != k) {
13541 					panic("chk_tte: bad pfn4, 0x%lx, 0x%lx",
13542 					    j, k);
13543 				}
13544 			} else {
13545 				panic("chk_tte: why here?");
13546 			}
13547 		} else {
13548 			if (!TTE_IS_VALID(new)) {
13549 				panic("chk_tte: why here2 ?");
13550 			}
13551 		}
13552 	}
13553 }
13554 
13555 #endif /* DEBUG */
13556 
13557 extern void prefetch_tsbe_read(struct tsbe *);
13558 extern void prefetch_tsbe_write(struct tsbe *);
13559 
13560 
13561 /*
13562  * We want to prefetch 7 cache lines ahead for our read prefetch.  This gives
13563  * us optimal performance on Cheetah+.  You can only have 8 outstanding
13564  * prefetches at any one time, so we opted for 7 read prefetches and 1 write
13565  * prefetch to make the most utilization of the prefetch capability.
13566  */
13567 #define	TSBE_PREFETCH_STRIDE (7)
13568 
13569 void
13570 sfmmu_copy_tsb(struct tsb_info *old_tsbinfo, struct tsb_info *new_tsbinfo)
13571 {
13572 	int old_bytes = TSB_BYTES(old_tsbinfo->tsb_szc);
13573 	int new_bytes = TSB_BYTES(new_tsbinfo->tsb_szc);
13574 	int old_entries = TSB_ENTRIES(old_tsbinfo->tsb_szc);
13575 	int new_entries = TSB_ENTRIES(new_tsbinfo->tsb_szc);
13576 	struct tsbe *old;
13577 	struct tsbe *new;
13578 	struct tsbe *new_base = (struct tsbe *)new_tsbinfo->tsb_va;
13579 	uint64_t va;
13580 	int new_offset;
13581 	int i;
13582 	int vpshift;
13583 	int last_prefetch;
13584 
13585 	if (old_bytes == new_bytes) {
13586 		bcopy(old_tsbinfo->tsb_va, new_tsbinfo->tsb_va, new_bytes);
13587 	} else {
13588 
13589 		/*
13590 		 * A TSBE is 16 bytes which means there are four TSBE's per
13591 		 * P$ line (64 bytes), thus every 4 TSBE's we prefetch.
13592 		 */
13593 		old = (struct tsbe *)old_tsbinfo->tsb_va;
13594 		last_prefetch = old_entries - (4*(TSBE_PREFETCH_STRIDE+1));
13595 		for (i = 0; i < old_entries; i++, old++) {
13596 			if (((i & (4-1)) == 0) && (i < last_prefetch))
13597 				prefetch_tsbe_read(old);
13598 			if (!old->tte_tag.tag_invalid) {
13599 				/*
13600 				 * We have a valid TTE to remap.  Check the
13601 				 * size.  We won't remap 64K or 512K TTEs
13602 				 * because they span more than one TSB entry
13603 				 * and are indexed using an 8K virt. page.
13604 				 * Ditto for 32M and 256M TTEs.
13605 				 */
13606 				if (TTE_CSZ(&old->tte_data) == TTE64K ||
13607 				    TTE_CSZ(&old->tte_data) == TTE512K)
13608 					continue;
13609 				if (mmu_page_sizes == max_mmu_page_sizes) {
13610 					if (TTE_CSZ(&old->tte_data) == TTE32M ||
13611 					    TTE_CSZ(&old->tte_data) == TTE256M)
13612 						continue;
13613 				}
13614 
13615 				/* clear the lower 22 bits of the va */
13616 				va = *(uint64_t *)old << 22;
13617 				/* turn va into a virtual pfn */
13618 				va >>= 22 - TSB_START_SIZE;
13619 				/*
13620 				 * or in bits from the offset in the tsb
13621 				 * to get the real virtual pfn. These
13622 				 * correspond to bits [21:13] in the va
13623 				 */
13624 				vpshift =
13625 				    TTE_BSZS_SHIFT(TTE_CSZ(&old->tte_data)) &
13626 				    0x1ff;
13627 				va |= (i << vpshift);
13628 				va >>= vpshift;
13629 				new_offset = va & (new_entries - 1);
13630 				new = new_base + new_offset;
13631 				prefetch_tsbe_write(new);
13632 				*new = *old;
13633 			}
13634 		}
13635 	}
13636 }
13637 
13638 /*
13639  * unused in sfmmu
13640  */
13641 void
13642 hat_dump(void)
13643 {
13644 }
13645 
13646 /*
13647  * Called when a thread is exiting and we have switched to the kernel address
13648  * space.  Perform the same VM initialization resume() uses when switching
13649  * processes.
13650  *
13651  * Note that sfmmu_load_mmustate() is currently a no-op for kernel threads, but
13652  * we call it anyway in case the semantics change in the future.
13653  */
13654 /*ARGSUSED*/
13655 void
13656 hat_thread_exit(kthread_t *thd)
13657 {
13658 	uint_t pgsz_cnum;
13659 	uint_t pstate_save;
13660 
13661 	ASSERT(thd->t_procp->p_as == &kas);
13662 
13663 	pgsz_cnum = KCONTEXT;
13664 #ifdef sun4u
13665 	pgsz_cnum |= (ksfmmup->sfmmu_cext << CTXREG_EXT_SHIFT);
13666 #endif
13667 
13668 	/*
13669 	 * Note that sfmmu_load_mmustate() is currently a no-op for
13670 	 * kernel threads. We need to disable interrupts here,
13671 	 * simply because otherwise sfmmu_load_mmustate() would panic
13672 	 * if the caller does not disable interrupts.
13673 	 */
13674 	pstate_save = sfmmu_disable_intrs();
13675 
13676 	/* Compatibility Note: hw takes care of MMU_SCONTEXT1 */
13677 	sfmmu_setctx_sec(pgsz_cnum);
13678 	sfmmu_load_mmustate(ksfmmup);
13679 	sfmmu_enable_intrs(pstate_save);
13680 }
13681 
13682 
13683 /*
13684  * SRD support
13685  */
13686 #define	SRD_HASH_FUNCTION(vp)	(((((uintptr_t)(vp)) >> 4) ^ \
13687 				    (((uintptr_t)(vp)) >> 11)) & \
13688 				    srd_hashmask)
13689 
13690 /*
13691  * Attach the process to the srd struct associated with the exec vnode
13692  * from which the process is started.
13693  */
13694 void
13695 hat_join_srd(struct hat *sfmmup, vnode_t *evp)
13696 {
13697 	uint_t hash = SRD_HASH_FUNCTION(evp);
13698 	sf_srd_t *srdp;
13699 	sf_srd_t *newsrdp;
13700 
13701 	ASSERT(sfmmup != ksfmmup);
13702 	ASSERT(sfmmup->sfmmu_srdp == NULL);
13703 
13704 	if (!shctx_on) {
13705 		return;
13706 	}
13707 
13708 	VN_HOLD(evp);
13709 
13710 	if (srd_buckets[hash].srdb_srdp != NULL) {
13711 		mutex_enter(&srd_buckets[hash].srdb_lock);
13712 		for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13713 		    srdp = srdp->srd_hash) {
13714 			if (srdp->srd_evp == evp) {
13715 				ASSERT(srdp->srd_refcnt >= 0);
13716 				sfmmup->sfmmu_srdp = srdp;
13717 				atomic_add_32(
13718 				    (volatile uint_t *)&srdp->srd_refcnt, 1);
13719 				mutex_exit(&srd_buckets[hash].srdb_lock);
13720 				return;
13721 			}
13722 		}
13723 		mutex_exit(&srd_buckets[hash].srdb_lock);
13724 	}
13725 	newsrdp = kmem_cache_alloc(srd_cache, KM_SLEEP);
13726 	ASSERT(newsrdp->srd_next_ismrid == 0 && newsrdp->srd_next_hmerid == 0);
13727 
13728 	newsrdp->srd_evp = evp;
13729 	newsrdp->srd_refcnt = 1;
13730 	newsrdp->srd_hmergnfree = NULL;
13731 	newsrdp->srd_ismrgnfree = NULL;
13732 
13733 	mutex_enter(&srd_buckets[hash].srdb_lock);
13734 	for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13735 	    srdp = srdp->srd_hash) {
13736 		if (srdp->srd_evp == evp) {
13737 			ASSERT(srdp->srd_refcnt >= 0);
13738 			sfmmup->sfmmu_srdp = srdp;
13739 			atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
13740 			mutex_exit(&srd_buckets[hash].srdb_lock);
13741 			kmem_cache_free(srd_cache, newsrdp);
13742 			return;
13743 		}
13744 	}
13745 	newsrdp->srd_hash = srd_buckets[hash].srdb_srdp;
13746 	srd_buckets[hash].srdb_srdp = newsrdp;
13747 	sfmmup->sfmmu_srdp = newsrdp;
13748 
13749 	mutex_exit(&srd_buckets[hash].srdb_lock);
13750 
13751 }
13752 
13753 static void
13754 sfmmu_leave_srd(sfmmu_t *sfmmup)
13755 {
13756 	vnode_t *evp;
13757 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13758 	uint_t hash;
13759 	sf_srd_t **prev_srdpp;
13760 	sf_region_t *rgnp;
13761 	sf_region_t *nrgnp;
13762 #ifdef DEBUG
13763 	int rgns = 0;
13764 #endif
13765 	int i;
13766 
13767 	ASSERT(sfmmup != ksfmmup);
13768 	ASSERT(srdp != NULL);
13769 	ASSERT(srdp->srd_refcnt > 0);
13770 	ASSERT(sfmmup->sfmmu_scdp == NULL);
13771 	ASSERT(sfmmup->sfmmu_free == 1);
13772 
13773 	sfmmup->sfmmu_srdp = NULL;
13774 	evp = srdp->srd_evp;
13775 	ASSERT(evp != NULL);
13776 	if (atomic_add_32_nv(
13777 	    (volatile uint_t *)&srdp->srd_refcnt, -1)) {
13778 		VN_RELE(evp);
13779 		return;
13780 	}
13781 
13782 	hash = SRD_HASH_FUNCTION(evp);
13783 	mutex_enter(&srd_buckets[hash].srdb_lock);
13784 	for (prev_srdpp = &srd_buckets[hash].srdb_srdp;
13785 	    (srdp = *prev_srdpp) != NULL; prev_srdpp = &srdp->srd_hash) {
13786 		if (srdp->srd_evp == evp) {
13787 			break;
13788 		}
13789 	}
13790 	if (srdp == NULL || srdp->srd_refcnt) {
13791 		mutex_exit(&srd_buckets[hash].srdb_lock);
13792 		VN_RELE(evp);
13793 		return;
13794 	}
13795 	*prev_srdpp = srdp->srd_hash;
13796 	mutex_exit(&srd_buckets[hash].srdb_lock);
13797 
13798 	ASSERT(srdp->srd_refcnt == 0);
13799 	VN_RELE(evp);
13800 
13801 #ifdef DEBUG
13802 	for (i = 0; i < SFMMU_MAX_REGION_BUCKETS; i++) {
13803 		ASSERT(srdp->srd_rgnhash[i] == NULL);
13804 	}
13805 #endif /* DEBUG */
13806 
13807 	/* free each hme regions in the srd */
13808 	for (rgnp = srdp->srd_hmergnfree; rgnp != NULL; rgnp = nrgnp) {
13809 		nrgnp = rgnp->rgn_next;
13810 		ASSERT(rgnp->rgn_id < srdp->srd_next_hmerid);
13811 		ASSERT(rgnp->rgn_refcnt == 0);
13812 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13813 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13814 		ASSERT(rgnp->rgn_hmeflags == 0);
13815 		ASSERT(srdp->srd_hmergnp[rgnp->rgn_id] == rgnp);
13816 #ifdef DEBUG
13817 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13818 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13819 		}
13820 		rgns++;
13821 #endif /* DEBUG */
13822 		kmem_cache_free(region_cache, rgnp);
13823 	}
13824 	ASSERT(rgns == srdp->srd_next_hmerid);
13825 
13826 #ifdef DEBUG
13827 	rgns = 0;
13828 #endif
13829 	/* free each ism rgns in the srd */
13830 	for (rgnp = srdp->srd_ismrgnfree; rgnp != NULL; rgnp = nrgnp) {
13831 		nrgnp = rgnp->rgn_next;
13832 		ASSERT(rgnp->rgn_id < srdp->srd_next_ismrid);
13833 		ASSERT(rgnp->rgn_refcnt == 0);
13834 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13835 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13836 		ASSERT(srdp->srd_ismrgnp[rgnp->rgn_id] == rgnp);
13837 #ifdef DEBUG
13838 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13839 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13840 		}
13841 		rgns++;
13842 #endif /* DEBUG */
13843 		kmem_cache_free(region_cache, rgnp);
13844 	}
13845 	ASSERT(rgns == srdp->srd_next_ismrid);
13846 	ASSERT(srdp->srd_ismbusyrgns == 0);
13847 	ASSERT(srdp->srd_hmebusyrgns == 0);
13848 
13849 	srdp->srd_next_ismrid = 0;
13850 	srdp->srd_next_hmerid = 0;
13851 
13852 	bzero((void *)srdp->srd_ismrgnp,
13853 	    sizeof (sf_region_t *) * SFMMU_MAX_ISM_REGIONS);
13854 	bzero((void *)srdp->srd_hmergnp,
13855 	    sizeof (sf_region_t *) * SFMMU_MAX_HME_REGIONS);
13856 
13857 	ASSERT(srdp->srd_scdp == NULL);
13858 	kmem_cache_free(srd_cache, srdp);
13859 }
13860 
13861 /* ARGSUSED */
13862 static int
13863 sfmmu_srdcache_constructor(void *buf, void *cdrarg, int kmflags)
13864 {
13865 	sf_srd_t *srdp = (sf_srd_t *)buf;
13866 	bzero(buf, sizeof (*srdp));
13867 
13868 	mutex_init(&srdp->srd_mutex, NULL, MUTEX_DEFAULT, NULL);
13869 	mutex_init(&srdp->srd_scd_mutex, NULL, MUTEX_DEFAULT, NULL);
13870 	return (0);
13871 }
13872 
13873 /* ARGSUSED */
13874 static void
13875 sfmmu_srdcache_destructor(void *buf, void *cdrarg)
13876 {
13877 	sf_srd_t *srdp = (sf_srd_t *)buf;
13878 
13879 	mutex_destroy(&srdp->srd_mutex);
13880 	mutex_destroy(&srdp->srd_scd_mutex);
13881 }
13882 
13883 /*
13884  * The caller makes sure hat_join_region()/hat_leave_region() can't be called
13885  * at the same time for the same process and address range. This is ensured by
13886  * the fact that address space is locked as writer when a process joins the
13887  * regions. Therefore there's no need to hold an srd lock during the entire
13888  * execution of hat_join_region()/hat_leave_region().
13889  */
13890 
13891 #define	RGN_HASH_FUNCTION(obj)	(((((uintptr_t)(obj)) >> 4) ^ \
13892 				    (((uintptr_t)(obj)) >> 11)) & \
13893 					srd_rgn_hashmask)
13894 /*
13895  * This routine implements the shared context functionality required when
13896  * attaching a segment to an address space. It must be called from
13897  * hat_share() for D(ISM) segments and from segvn_create() for segments
13898  * with the MAP_PRIVATE and MAP_TEXT flags set. It returns a region_cookie
13899  * which is saved in the private segment data for hme segments and
13900  * the ism_map structure for ism segments.
13901  */
13902 hat_region_cookie_t
13903 hat_join_region(struct hat *sfmmup,
13904 	caddr_t r_saddr,
13905 	size_t r_size,
13906 	void *r_obj,
13907 	u_offset_t r_objoff,
13908 	uchar_t r_perm,
13909 	uchar_t r_pgszc,
13910 	hat_rgn_cb_func_t r_cb_function,
13911 	uint_t flags)
13912 {
13913 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13914 	uint_t rhash;
13915 	uint_t rid;
13916 	hatlock_t *hatlockp;
13917 	sf_region_t *rgnp;
13918 	sf_region_t *new_rgnp = NULL;
13919 	int i;
13920 	uint16_t *nextidp;
13921 	sf_region_t **freelistp;
13922 	int maxids;
13923 	sf_region_t **rarrp;
13924 	uint16_t *busyrgnsp;
13925 	ulong_t rttecnt;
13926 	uchar_t tteflag;
13927 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
13928 	int text = (r_type == HAT_REGION_TEXT);
13929 
13930 	if (srdp == NULL || r_size == 0) {
13931 		return (HAT_INVALID_REGION_COOKIE);
13932 	}
13933 
13934 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
13935 	ASSERT(sfmmup != ksfmmup);
13936 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
13937 	ASSERT(srdp->srd_refcnt > 0);
13938 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
13939 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
13940 	ASSERT(r_pgszc < mmu_page_sizes);
13941 	if (!IS_P2ALIGNED(r_saddr, TTEBYTES(r_pgszc)) ||
13942 	    !IS_P2ALIGNED(r_size, TTEBYTES(r_pgszc))) {
13943 		panic("hat_join_region: region addr or size is not aligned\n");
13944 	}
13945 
13946 
13947 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
13948 	    SFMMU_REGION_HME;
13949 	/*
13950 	 * Currently only support shared hmes for the read only main text
13951 	 * region.
13952 	 */
13953 	if (r_type == SFMMU_REGION_HME && ((r_obj != srdp->srd_evp) ||
13954 	    (r_perm & PROT_WRITE))) {
13955 		return (HAT_INVALID_REGION_COOKIE);
13956 	}
13957 
13958 	rhash = RGN_HASH_FUNCTION(r_obj);
13959 
13960 	if (r_type == SFMMU_REGION_ISM) {
13961 		nextidp = &srdp->srd_next_ismrid;
13962 		freelistp = &srdp->srd_ismrgnfree;
13963 		maxids = SFMMU_MAX_ISM_REGIONS;
13964 		rarrp = srdp->srd_ismrgnp;
13965 		busyrgnsp = &srdp->srd_ismbusyrgns;
13966 	} else {
13967 		nextidp = &srdp->srd_next_hmerid;
13968 		freelistp = &srdp->srd_hmergnfree;
13969 		maxids = SFMMU_MAX_HME_REGIONS;
13970 		rarrp = srdp->srd_hmergnp;
13971 		busyrgnsp = &srdp->srd_hmebusyrgns;
13972 	}
13973 
13974 	mutex_enter(&srdp->srd_mutex);
13975 
13976 	for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
13977 	    rgnp = rgnp->rgn_hash) {
13978 		if (rgnp->rgn_saddr == r_saddr && rgnp->rgn_size == r_size &&
13979 		    rgnp->rgn_obj == r_obj && rgnp->rgn_objoff == r_objoff &&
13980 		    rgnp->rgn_perm == r_perm && rgnp->rgn_pgszc == r_pgszc) {
13981 			break;
13982 		}
13983 	}
13984 
13985 rfound:
13986 	if (rgnp != NULL) {
13987 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
13988 		ASSERT(rgnp->rgn_cb_function == r_cb_function);
13989 		ASSERT(rgnp->rgn_refcnt >= 0);
13990 		rid = rgnp->rgn_id;
13991 		ASSERT(rid < maxids);
13992 		ASSERT(rarrp[rid] == rgnp);
13993 		ASSERT(rid < *nextidp);
13994 		atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
13995 		mutex_exit(&srdp->srd_mutex);
13996 		if (new_rgnp != NULL) {
13997 			kmem_cache_free(region_cache, new_rgnp);
13998 		}
13999 		if (r_type == SFMMU_REGION_HME) {
14000 			int myjoin =
14001 			    (sfmmup == astosfmmu(curthread->t_procp->p_as));
14002 
14003 			sfmmu_link_to_hmeregion(sfmmup, rgnp);
14004 			/*
14005 			 * bitmap should be updated after linking sfmmu on
14006 			 * region list so that pageunload() doesn't skip
14007 			 * TSB/TLB flush. As soon as bitmap is updated another
14008 			 * thread in this process can already start accessing
14009 			 * this region.
14010 			 */
14011 			/*
14012 			 * Normally ttecnt accounting is done as part of
14013 			 * pagefault handling. But a process may not take any
14014 			 * pagefaults on shared hmeblks created by some other
14015 			 * process. To compensate for this assume that the
14016 			 * entire region will end up faulted in using
14017 			 * the region's pagesize.
14018 			 *
14019 			 */
14020 			if (r_pgszc > TTE8K) {
14021 				tteflag = 1 << r_pgszc;
14022 				if (disable_large_pages & tteflag) {
14023 					tteflag = 0;
14024 				}
14025 			} else {
14026 				tteflag = 0;
14027 			}
14028 			if (tteflag && !(sfmmup->sfmmu_rtteflags & tteflag)) {
14029 				hatlockp = sfmmu_hat_enter(sfmmup);
14030 				sfmmup->sfmmu_rtteflags |= tteflag;
14031 				sfmmu_hat_exit(hatlockp);
14032 			}
14033 			hatlockp = sfmmu_hat_enter(sfmmup);
14034 
14035 			/*
14036 			 * Preallocate 1/4 of ttecnt's in 8K TSB for >= 4M
14037 			 * region to allow for large page allocation failure.
14038 			 */
14039 			if (r_pgszc >= TTE4M) {
14040 				sfmmup->sfmmu_tsb0_4minflcnt +=
14041 				    r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14042 			}
14043 
14044 			/* update sfmmu_ttecnt with the shme rgn ttecnt */
14045 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14046 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14047 			    rttecnt);
14048 
14049 			if (text && r_pgszc >= TTE4M &&
14050 			    (tteflag || ((disable_large_pages >> TTE4M) &
14051 			    ((1 << (r_pgszc - TTE4M + 1)) - 1))) &&
14052 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
14053 				SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
14054 			}
14055 
14056 			sfmmu_hat_exit(hatlockp);
14057 			/*
14058 			 * On Panther we need to make sure TLB is programmed
14059 			 * to accept 32M/256M pages.  Call
14060 			 * sfmmu_check_page_sizes() now to make sure TLB is
14061 			 * setup before making hmeregions visible to other
14062 			 * threads.
14063 			 */
14064 			sfmmu_check_page_sizes(sfmmup, 1);
14065 			hatlockp = sfmmu_hat_enter(sfmmup);
14066 			SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14067 
14068 			/*
14069 			 * if context is invalid tsb miss exception code will
14070 			 * call sfmmu_check_page_sizes() and update tsbmiss
14071 			 * area later.
14072 			 */
14073 			kpreempt_disable();
14074 			if (myjoin &&
14075 			    (sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
14076 			    != INVALID_CONTEXT)) {
14077 				struct tsbmiss *tsbmp;
14078 
14079 				tsbmp = &tsbmiss_area[CPU->cpu_id];
14080 				ASSERT(sfmmup == tsbmp->usfmmup);
14081 				BT_SET(tsbmp->shmermap, rid);
14082 				if (r_pgszc > TTE64K) {
14083 					tsbmp->uhat_rtteflags |= tteflag;
14084 				}
14085 
14086 			}
14087 			kpreempt_enable();
14088 
14089 			sfmmu_hat_exit(hatlockp);
14090 			ASSERT((hat_region_cookie_t)((uint64_t)rid) !=
14091 			    HAT_INVALID_REGION_COOKIE);
14092 		} else {
14093 			hatlockp = sfmmu_hat_enter(sfmmup);
14094 			SF_RGNMAP_ADD(sfmmup->sfmmu_ismregion_map, rid);
14095 			sfmmu_hat_exit(hatlockp);
14096 		}
14097 		ASSERT(rid < maxids);
14098 
14099 		if (r_type == SFMMU_REGION_ISM) {
14100 			sfmmu_find_scd(sfmmup);
14101 		}
14102 		return ((hat_region_cookie_t)((uint64_t)rid));
14103 	}
14104 
14105 	ASSERT(new_rgnp == NULL);
14106 
14107 	if (*busyrgnsp >= maxids) {
14108 		mutex_exit(&srdp->srd_mutex);
14109 		return (HAT_INVALID_REGION_COOKIE);
14110 	}
14111 
14112 	ASSERT(MUTEX_HELD(&srdp->srd_mutex));
14113 	if (*freelistp != NULL) {
14114 		rgnp = *freelistp;
14115 		*freelistp = rgnp->rgn_next;
14116 		ASSERT(rgnp->rgn_id < *nextidp);
14117 		ASSERT(rgnp->rgn_id < maxids);
14118 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
14119 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK)
14120 		    == r_type);
14121 		ASSERT(rarrp[rgnp->rgn_id] == rgnp);
14122 		ASSERT(rgnp->rgn_hmeflags == 0);
14123 	} else {
14124 		/*
14125 		 * release local locks before memory allocation.
14126 		 */
14127 		mutex_exit(&srdp->srd_mutex);
14128 
14129 		new_rgnp = kmem_cache_alloc(region_cache, KM_SLEEP);
14130 
14131 		mutex_enter(&srdp->srd_mutex);
14132 		for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
14133 		    rgnp = rgnp->rgn_hash) {
14134 			if (rgnp->rgn_saddr == r_saddr &&
14135 			    rgnp->rgn_size == r_size &&
14136 			    rgnp->rgn_obj == r_obj &&
14137 			    rgnp->rgn_objoff == r_objoff &&
14138 			    rgnp->rgn_perm == r_perm &&
14139 			    rgnp->rgn_pgszc == r_pgszc) {
14140 				break;
14141 			}
14142 		}
14143 		if (rgnp != NULL) {
14144 			goto rfound;
14145 		}
14146 
14147 		if (*nextidp >= maxids) {
14148 			mutex_exit(&srdp->srd_mutex);
14149 			goto fail;
14150 		}
14151 		rgnp = new_rgnp;
14152 		new_rgnp = NULL;
14153 		rgnp->rgn_id = (*nextidp)++;
14154 		ASSERT(rgnp->rgn_id < maxids);
14155 		ASSERT(rarrp[rgnp->rgn_id] == NULL);
14156 		rarrp[rgnp->rgn_id] = rgnp;
14157 	}
14158 
14159 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14160 	ASSERT(rgnp->rgn_hmeflags == 0);
14161 #ifdef DEBUG
14162 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14163 		ASSERT(rgnp->rgn_ttecnt[i] == 0);
14164 	}
14165 #endif
14166 	rgnp->rgn_saddr = r_saddr;
14167 	rgnp->rgn_size = r_size;
14168 	rgnp->rgn_obj = r_obj;
14169 	rgnp->rgn_objoff = r_objoff;
14170 	rgnp->rgn_perm = r_perm;
14171 	rgnp->rgn_pgszc = r_pgszc;
14172 	rgnp->rgn_flags = r_type;
14173 	rgnp->rgn_refcnt = 0;
14174 	rgnp->rgn_cb_function = r_cb_function;
14175 	rgnp->rgn_hash = srdp->srd_rgnhash[rhash];
14176 	srdp->srd_rgnhash[rhash] = rgnp;
14177 	(*busyrgnsp)++;
14178 	ASSERT(*busyrgnsp <= maxids);
14179 	goto rfound;
14180 
14181 fail:
14182 	ASSERT(new_rgnp != NULL);
14183 	kmem_cache_free(region_cache, new_rgnp);
14184 	return (HAT_INVALID_REGION_COOKIE);
14185 }
14186 
14187 /*
14188  * This function implements the shared context functionality required
14189  * when detaching a segment from an address space. It must be called
14190  * from hat_unshare() for all D(ISM) segments and from segvn_unmap(),
14191  * for segments with a valid region_cookie.
14192  * It will also be called from all seg_vn routines which change a
14193  * segment's attributes such as segvn_setprot(), segvn_setpagesize(),
14194  * segvn_clrszc() & segvn_advise(), as well as in the case of COW fault
14195  * from segvn_fault().
14196  */
14197 void
14198 hat_leave_region(struct hat *sfmmup, hat_region_cookie_t rcookie, uint_t flags)
14199 {
14200 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14201 	sf_scd_t *scdp;
14202 	uint_t rhash;
14203 	uint_t rid = (uint_t)((uint64_t)rcookie);
14204 	hatlock_t *hatlockp = NULL;
14205 	sf_region_t *rgnp;
14206 	sf_region_t **prev_rgnpp;
14207 	sf_region_t *cur_rgnp;
14208 	void *r_obj;
14209 	int i;
14210 	caddr_t	r_saddr;
14211 	caddr_t r_eaddr;
14212 	size_t	r_size;
14213 	uchar_t	r_pgszc;
14214 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
14215 
14216 	ASSERT(sfmmup != ksfmmup);
14217 	ASSERT(srdp != NULL);
14218 	ASSERT(srdp->srd_refcnt > 0);
14219 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
14220 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
14221 	ASSERT(!sfmmup->sfmmu_free || sfmmup->sfmmu_scdp == NULL);
14222 
14223 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
14224 	    SFMMU_REGION_HME;
14225 
14226 	if (r_type == SFMMU_REGION_ISM) {
14227 		ASSERT(SFMMU_IS_ISMRID_VALID(rid));
14228 		ASSERT(rid < SFMMU_MAX_ISM_REGIONS);
14229 		rgnp = srdp->srd_ismrgnp[rid];
14230 	} else {
14231 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14232 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14233 		rgnp = srdp->srd_hmergnp[rid];
14234 	}
14235 	ASSERT(rgnp != NULL);
14236 	ASSERT(rgnp->rgn_id == rid);
14237 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14238 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14239 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
14240 
14241 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
14242 	if (r_type == SFMMU_REGION_HME && sfmmup->sfmmu_as->a_xhat != NULL) {
14243 		xhat_unload_callback_all(sfmmup->sfmmu_as, rgnp->rgn_saddr,
14244 		    rgnp->rgn_size, 0, NULL);
14245 	}
14246 
14247 	if (sfmmup->sfmmu_free) {
14248 		ulong_t rttecnt;
14249 		r_pgszc = rgnp->rgn_pgszc;
14250 		r_size = rgnp->rgn_size;
14251 
14252 		ASSERT(sfmmup->sfmmu_scdp == NULL);
14253 		if (r_type == SFMMU_REGION_ISM) {
14254 			SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14255 		} else {
14256 			/* update shme rgns ttecnt in sfmmu_ttecnt */
14257 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14258 			ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14259 
14260 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14261 			    -rttecnt);
14262 
14263 			SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14264 		}
14265 	} else if (r_type == SFMMU_REGION_ISM) {
14266 		hatlockp = sfmmu_hat_enter(sfmmup);
14267 		ASSERT(rid < srdp->srd_next_ismrid);
14268 		SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14269 		scdp = sfmmup->sfmmu_scdp;
14270 		if (scdp != NULL &&
14271 		    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
14272 			sfmmu_leave_scd(sfmmup, r_type);
14273 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14274 		}
14275 		sfmmu_hat_exit(hatlockp);
14276 	} else {
14277 		ulong_t rttecnt;
14278 		r_pgszc = rgnp->rgn_pgszc;
14279 		r_saddr = rgnp->rgn_saddr;
14280 		r_size = rgnp->rgn_size;
14281 		r_eaddr = r_saddr + r_size;
14282 
14283 		ASSERT(r_type == SFMMU_REGION_HME);
14284 		hatlockp = sfmmu_hat_enter(sfmmup);
14285 		ASSERT(rid < srdp->srd_next_hmerid);
14286 		SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14287 
14288 		/*
14289 		 * If region is part of an SCD call sfmmu_leave_scd().
14290 		 * Otherwise if process is not exiting and has valid context
14291 		 * just drop the context on the floor to lose stale TLB
14292 		 * entries and force the update of tsb miss area to reflect
14293 		 * the new region map. After that clean our TSB entries.
14294 		 */
14295 		scdp = sfmmup->sfmmu_scdp;
14296 		if (scdp != NULL &&
14297 		    SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
14298 			sfmmu_leave_scd(sfmmup, r_type);
14299 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14300 		}
14301 		sfmmu_invalidate_ctx(sfmmup);
14302 
14303 		i = TTE8K;
14304 		while (i < mmu_page_sizes) {
14305 			if (rgnp->rgn_ttecnt[i] != 0) {
14306 				sfmmu_unload_tsb_range(sfmmup, r_saddr,
14307 				    r_eaddr, i);
14308 				if (i < TTE4M) {
14309 					i = TTE4M;
14310 					continue;
14311 				} else {
14312 					break;
14313 				}
14314 			}
14315 			i++;
14316 		}
14317 		/* Remove the preallocated 1/4 8k ttecnt for 4M regions. */
14318 		if (r_pgszc >= TTE4M) {
14319 			rttecnt = r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14320 			ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
14321 			    rttecnt);
14322 			sfmmup->sfmmu_tsb0_4minflcnt -= rttecnt;
14323 		}
14324 
14325 		/* update shme rgns ttecnt in sfmmu_ttecnt */
14326 		rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14327 		ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14328 		atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc], -rttecnt);
14329 
14330 		sfmmu_hat_exit(hatlockp);
14331 		if (scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
14332 			/* sfmmup left the scd, grow private tsb */
14333 			sfmmu_check_page_sizes(sfmmup, 1);
14334 		} else {
14335 			sfmmu_check_page_sizes(sfmmup, 0);
14336 		}
14337 	}
14338 
14339 	if (r_type == SFMMU_REGION_HME) {
14340 		sfmmu_unlink_from_hmeregion(sfmmup, rgnp);
14341 	}
14342 
14343 	r_obj = rgnp->rgn_obj;
14344 	if (atomic_add_32_nv((volatile uint_t *)&rgnp->rgn_refcnt, -1)) {
14345 		return;
14346 	}
14347 
14348 	/*
14349 	 * looks like nobody uses this region anymore. Free it.
14350 	 */
14351 	rhash = RGN_HASH_FUNCTION(r_obj);
14352 	mutex_enter(&srdp->srd_mutex);
14353 	for (prev_rgnpp = &srdp->srd_rgnhash[rhash];
14354 	    (cur_rgnp = *prev_rgnpp) != NULL;
14355 	    prev_rgnpp = &cur_rgnp->rgn_hash) {
14356 		if (cur_rgnp == rgnp && cur_rgnp->rgn_refcnt == 0) {
14357 			break;
14358 		}
14359 	}
14360 
14361 	if (cur_rgnp == NULL) {
14362 		mutex_exit(&srdp->srd_mutex);
14363 		return;
14364 	}
14365 
14366 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14367 	*prev_rgnpp = rgnp->rgn_hash;
14368 	if (r_type == SFMMU_REGION_ISM) {
14369 		rgnp->rgn_flags |= SFMMU_REGION_FREE;
14370 		ASSERT(rid < srdp->srd_next_ismrid);
14371 		rgnp->rgn_next = srdp->srd_ismrgnfree;
14372 		srdp->srd_ismrgnfree = rgnp;
14373 		ASSERT(srdp->srd_ismbusyrgns > 0);
14374 		srdp->srd_ismbusyrgns--;
14375 		mutex_exit(&srdp->srd_mutex);
14376 		return;
14377 	}
14378 	mutex_exit(&srdp->srd_mutex);
14379 
14380 	/*
14381 	 * Destroy region's hmeblks.
14382 	 */
14383 	sfmmu_unload_hmeregion(srdp, rgnp);
14384 
14385 	rgnp->rgn_hmeflags = 0;
14386 
14387 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14388 	ASSERT(rgnp->rgn_id == rid);
14389 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14390 		rgnp->rgn_ttecnt[i] = 0;
14391 	}
14392 	rgnp->rgn_flags |= SFMMU_REGION_FREE;
14393 	mutex_enter(&srdp->srd_mutex);
14394 	ASSERT(rid < srdp->srd_next_hmerid);
14395 	rgnp->rgn_next = srdp->srd_hmergnfree;
14396 	srdp->srd_hmergnfree = rgnp;
14397 	ASSERT(srdp->srd_hmebusyrgns > 0);
14398 	srdp->srd_hmebusyrgns--;
14399 	mutex_exit(&srdp->srd_mutex);
14400 }
14401 
14402 /*
14403  * For now only called for hmeblk regions and not for ISM regions.
14404  */
14405 void
14406 hat_dup_region(struct hat *sfmmup, hat_region_cookie_t rcookie)
14407 {
14408 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14409 	uint_t rid = (uint_t)((uint64_t)rcookie);
14410 	sf_region_t *rgnp;
14411 	sf_rgn_link_t *rlink;
14412 	sf_rgn_link_t *hrlink;
14413 	ulong_t	rttecnt;
14414 
14415 	ASSERT(sfmmup != ksfmmup);
14416 	ASSERT(srdp != NULL);
14417 	ASSERT(srdp->srd_refcnt > 0);
14418 
14419 	ASSERT(rid < srdp->srd_next_hmerid);
14420 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14421 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14422 
14423 	rgnp = srdp->srd_hmergnp[rid];
14424 	ASSERT(rgnp->rgn_refcnt > 0);
14425 	ASSERT(rgnp->rgn_id == rid);
14426 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == SFMMU_REGION_HME);
14427 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14428 
14429 	atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
14430 
14431 	/* LINTED: constant in conditional context */
14432 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 0);
14433 	ASSERT(rlink != NULL);
14434 	mutex_enter(&rgnp->rgn_mutex);
14435 	ASSERT(rgnp->rgn_sfmmu_head != NULL);
14436 	/* LINTED: constant in conditional context */
14437 	SFMMU_HMERID2RLINKP(rgnp->rgn_sfmmu_head, rid, hrlink, 0, 0);
14438 	ASSERT(hrlink != NULL);
14439 	ASSERT(hrlink->prev == NULL);
14440 	rlink->next = rgnp->rgn_sfmmu_head;
14441 	rlink->prev = NULL;
14442 	hrlink->prev = sfmmup;
14443 	/*
14444 	 * make sure rlink's next field is correct
14445 	 * before making this link visible.
14446 	 */
14447 	membar_stst();
14448 	rgnp->rgn_sfmmu_head = sfmmup;
14449 	mutex_exit(&rgnp->rgn_mutex);
14450 
14451 	/* update sfmmu_ttecnt with the shme rgn ttecnt */
14452 	rttecnt = rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
14453 	atomic_add_long(&sfmmup->sfmmu_ttecnt[rgnp->rgn_pgszc], rttecnt);
14454 	/* update tsb0 inflation count */
14455 	if (rgnp->rgn_pgszc >= TTE4M) {
14456 		sfmmup->sfmmu_tsb0_4minflcnt +=
14457 		    rgnp->rgn_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14458 	}
14459 	/*
14460 	 * Update regionid bitmask without hat lock since no other thread
14461 	 * can update this region bitmask right now.
14462 	 */
14463 	SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14464 }
14465 
14466 /* ARGSUSED */
14467 static int
14468 sfmmu_rgncache_constructor(void *buf, void *cdrarg, int kmflags)
14469 {
14470 	sf_region_t *rgnp = (sf_region_t *)buf;
14471 	bzero(buf, sizeof (*rgnp));
14472 
14473 	mutex_init(&rgnp->rgn_mutex, NULL, MUTEX_DEFAULT, NULL);
14474 
14475 	return (0);
14476 }
14477 
14478 /* ARGSUSED */
14479 static void
14480 sfmmu_rgncache_destructor(void *buf, void *cdrarg)
14481 {
14482 	sf_region_t *rgnp = (sf_region_t *)buf;
14483 	mutex_destroy(&rgnp->rgn_mutex);
14484 }
14485 
14486 static int
14487 sfrgnmap_isnull(sf_region_map_t *map)
14488 {
14489 	int i;
14490 
14491 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14492 		if (map->bitmap[i] != 0) {
14493 			return (0);
14494 		}
14495 	}
14496 	return (1);
14497 }
14498 
14499 static int
14500 sfhmergnmap_isnull(sf_hmeregion_map_t *map)
14501 {
14502 	int i;
14503 
14504 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
14505 		if (map->bitmap[i] != 0) {
14506 			return (0);
14507 		}
14508 	}
14509 	return (1);
14510 }
14511 
14512 #ifdef DEBUG
14513 static void
14514 check_scd_sfmmu_list(sfmmu_t **headp, sfmmu_t *sfmmup, int onlist)
14515 {
14516 	sfmmu_t *sp;
14517 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14518 
14519 	for (sp = *headp; sp != NULL; sp = sp->sfmmu_scd_link.next) {
14520 		ASSERT(srdp == sp->sfmmu_srdp);
14521 		if (sp == sfmmup) {
14522 			if (onlist) {
14523 				return;
14524 			} else {
14525 				panic("shctx: sfmmu 0x%p found on scd"
14526 				    "list 0x%p", (void *)sfmmup,
14527 				    (void *)*headp);
14528 			}
14529 		}
14530 	}
14531 	if (onlist) {
14532 		panic("shctx: sfmmu 0x%p not found on scd list 0x%p",
14533 		    (void *)sfmmup, (void *)*headp);
14534 	} else {
14535 		return;
14536 	}
14537 }
14538 #else /* DEBUG */
14539 #define	check_scd_sfmmu_list(headp, sfmmup, onlist)
14540 #endif /* DEBUG */
14541 
14542 /*
14543  * Removes an sfmmu from the SCD sfmmu list.
14544  */
14545 static void
14546 sfmmu_from_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14547 {
14548 	ASSERT(sfmmup->sfmmu_srdp != NULL);
14549 	check_scd_sfmmu_list(headp, sfmmup, 1);
14550 	if (sfmmup->sfmmu_scd_link.prev != NULL) {
14551 		ASSERT(*headp != sfmmup);
14552 		sfmmup->sfmmu_scd_link.prev->sfmmu_scd_link.next =
14553 		    sfmmup->sfmmu_scd_link.next;
14554 	} else {
14555 		ASSERT(*headp == sfmmup);
14556 		*headp = sfmmup->sfmmu_scd_link.next;
14557 	}
14558 	if (sfmmup->sfmmu_scd_link.next != NULL) {
14559 		sfmmup->sfmmu_scd_link.next->sfmmu_scd_link.prev =
14560 		    sfmmup->sfmmu_scd_link.prev;
14561 	}
14562 }
14563 
14564 
14565 /*
14566  * Adds an sfmmu to the start of the queue.
14567  */
14568 static void
14569 sfmmu_to_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14570 {
14571 	check_scd_sfmmu_list(headp, sfmmup, 0);
14572 	sfmmup->sfmmu_scd_link.prev = NULL;
14573 	sfmmup->sfmmu_scd_link.next = *headp;
14574 	if (*headp != NULL)
14575 		(*headp)->sfmmu_scd_link.prev = sfmmup;
14576 	*headp = sfmmup;
14577 }
14578 
14579 /*
14580  * Remove an scd from the start of the queue.
14581  */
14582 static void
14583 sfmmu_remove_scd(sf_scd_t **headp, sf_scd_t *scdp)
14584 {
14585 	if (scdp->scd_prev != NULL) {
14586 		ASSERT(*headp != scdp);
14587 		scdp->scd_prev->scd_next = scdp->scd_next;
14588 	} else {
14589 		ASSERT(*headp == scdp);
14590 		*headp = scdp->scd_next;
14591 	}
14592 
14593 	if (scdp->scd_next != NULL) {
14594 		scdp->scd_next->scd_prev = scdp->scd_prev;
14595 	}
14596 }
14597 
14598 /*
14599  * Add an scd to the start of the queue.
14600  */
14601 static void
14602 sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *scdp)
14603 {
14604 	scdp->scd_prev = NULL;
14605 	scdp->scd_next = *headp;
14606 	if (*headp != NULL) {
14607 		(*headp)->scd_prev = scdp;
14608 	}
14609 	*headp = scdp;
14610 }
14611 
14612 static int
14613 sfmmu_alloc_scd_tsbs(sf_srd_t *srdp, sf_scd_t *scdp)
14614 {
14615 	uint_t rid;
14616 	uint_t i;
14617 	uint_t j;
14618 	ulong_t w;
14619 	sf_region_t *rgnp;
14620 	ulong_t tte8k_cnt = 0;
14621 	ulong_t tte4m_cnt = 0;
14622 	uint_t tsb_szc;
14623 	sfmmu_t *scsfmmup = scdp->scd_sfmmup;
14624 	sfmmu_t	*ism_hatid;
14625 	struct tsb_info *newtsb;
14626 	int szc;
14627 
14628 	ASSERT(srdp != NULL);
14629 
14630 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14631 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14632 			continue;
14633 		}
14634 		j = 0;
14635 		while (w) {
14636 			if (!(w & 0x1)) {
14637 				j++;
14638 				w >>= 1;
14639 				continue;
14640 			}
14641 			rid = (i << BT_ULSHIFT) | j;
14642 			j++;
14643 			w >>= 1;
14644 
14645 			if (rid < SFMMU_MAX_HME_REGIONS) {
14646 				rgnp = srdp->srd_hmergnp[rid];
14647 				ASSERT(rgnp->rgn_id == rid);
14648 				ASSERT(rgnp->rgn_refcnt > 0);
14649 
14650 				if (rgnp->rgn_pgszc < TTE4M) {
14651 					tte8k_cnt += rgnp->rgn_size >>
14652 					    TTE_PAGE_SHIFT(TTE8K);
14653 				} else {
14654 					ASSERT(rgnp->rgn_pgszc >= TTE4M);
14655 					tte4m_cnt += rgnp->rgn_size >>
14656 					    TTE_PAGE_SHIFT(TTE4M);
14657 					/*
14658 					 * Inflate SCD tsb0 by preallocating
14659 					 * 1/4 8k ttecnt for 4M regions to
14660 					 * allow for lgpg alloc failure.
14661 					 */
14662 					tte8k_cnt += rgnp->rgn_size >>
14663 					    (TTE_PAGE_SHIFT(TTE8K) + 2);
14664 				}
14665 			} else {
14666 				rid -= SFMMU_MAX_HME_REGIONS;
14667 				rgnp = srdp->srd_ismrgnp[rid];
14668 				ASSERT(rgnp->rgn_id == rid);
14669 				ASSERT(rgnp->rgn_refcnt > 0);
14670 
14671 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14672 				ASSERT(ism_hatid->sfmmu_ismhat);
14673 
14674 				for (szc = 0; szc < TTE4M; szc++) {
14675 					tte8k_cnt +=
14676 					    ism_hatid->sfmmu_ttecnt[szc] <<
14677 					    TTE_BSZS_SHIFT(szc);
14678 				}
14679 
14680 				ASSERT(rgnp->rgn_pgszc >= TTE4M);
14681 				if (rgnp->rgn_pgszc >= TTE4M) {
14682 					tte4m_cnt += rgnp->rgn_size >>
14683 					    TTE_PAGE_SHIFT(TTE4M);
14684 				}
14685 			}
14686 		}
14687 	}
14688 
14689 	tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
14690 
14691 	/* Allocate both the SCD TSBs here. */
14692 	if (sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14693 	    tsb_szc, TSB8K|TSB64K|TSB512K, TSB_ALLOC, scsfmmup) &&
14694 	    (tsb_szc <= TSB_4M_SZCODE ||
14695 	    sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14696 	    TSB_4M_SZCODE, TSB8K|TSB64K|TSB512K,
14697 	    TSB_ALLOC, scsfmmup))) {
14698 
14699 		SFMMU_STAT(sf_scd_1sttsb_allocfail);
14700 		return (TSB_ALLOCFAIL);
14701 	} else {
14702 		scsfmmup->sfmmu_tsb->tsb_flags |= TSB_SHAREDCTX;
14703 
14704 		if (tte4m_cnt) {
14705 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
14706 			if (sfmmu_tsbinfo_alloc(&newtsb, tsb_szc,
14707 			    TSB4M|TSB32M|TSB256M, TSB_ALLOC, scsfmmup) &&
14708 			    (tsb_szc <= TSB_4M_SZCODE ||
14709 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
14710 			    TSB4M|TSB32M|TSB256M,
14711 			    TSB_ALLOC, scsfmmup))) {
14712 				/*
14713 				 * If we fail to allocate the 2nd shared tsb,
14714 				 * just free the 1st tsb, return failure.
14715 				 */
14716 				sfmmu_tsbinfo_free(scsfmmup->sfmmu_tsb);
14717 				SFMMU_STAT(sf_scd_2ndtsb_allocfail);
14718 				return (TSB_ALLOCFAIL);
14719 			} else {
14720 				ASSERT(scsfmmup->sfmmu_tsb->tsb_next == NULL);
14721 				newtsb->tsb_flags |= TSB_SHAREDCTX;
14722 				scsfmmup->sfmmu_tsb->tsb_next = newtsb;
14723 				SFMMU_STAT(sf_scd_2ndtsb_alloc);
14724 			}
14725 		}
14726 		SFMMU_STAT(sf_scd_1sttsb_alloc);
14727 	}
14728 	return (TSB_SUCCESS);
14729 }
14730 
14731 static void
14732 sfmmu_free_scd_tsbs(sfmmu_t *scd_sfmmu)
14733 {
14734 	while (scd_sfmmu->sfmmu_tsb != NULL) {
14735 		struct tsb_info *next = scd_sfmmu->sfmmu_tsb->tsb_next;
14736 		sfmmu_tsbinfo_free(scd_sfmmu->sfmmu_tsb);
14737 		scd_sfmmu->sfmmu_tsb = next;
14738 	}
14739 }
14740 
14741 /*
14742  * Link the sfmmu onto the hme region list.
14743  */
14744 void
14745 sfmmu_link_to_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14746 {
14747 	uint_t rid;
14748 	sf_rgn_link_t *rlink;
14749 	sfmmu_t *head;
14750 	sf_rgn_link_t *hrlink;
14751 
14752 	rid = rgnp->rgn_id;
14753 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14754 
14755 	/* LINTED: constant in conditional context */
14756 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 1);
14757 	ASSERT(rlink != NULL);
14758 	mutex_enter(&rgnp->rgn_mutex);
14759 	if ((head = rgnp->rgn_sfmmu_head) == NULL) {
14760 		rlink->next = NULL;
14761 		rlink->prev = NULL;
14762 		/*
14763 		 * make sure rlink's next field is NULL
14764 		 * before making this link visible.
14765 		 */
14766 		membar_stst();
14767 		rgnp->rgn_sfmmu_head = sfmmup;
14768 	} else {
14769 		/* LINTED: constant in conditional context */
14770 		SFMMU_HMERID2RLINKP(head, rid, hrlink, 0, 0);
14771 		ASSERT(hrlink != NULL);
14772 		ASSERT(hrlink->prev == NULL);
14773 		rlink->next = head;
14774 		rlink->prev = NULL;
14775 		hrlink->prev = sfmmup;
14776 		/*
14777 		 * make sure rlink's next field is correct
14778 		 * before making this link visible.
14779 		 */
14780 		membar_stst();
14781 		rgnp->rgn_sfmmu_head = sfmmup;
14782 	}
14783 	mutex_exit(&rgnp->rgn_mutex);
14784 }
14785 
14786 /*
14787  * Unlink the sfmmu from the hme region list.
14788  */
14789 void
14790 sfmmu_unlink_from_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14791 {
14792 	uint_t rid;
14793 	sf_rgn_link_t *rlink;
14794 
14795 	rid = rgnp->rgn_id;
14796 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14797 
14798 	/* LINTED: constant in conditional context */
14799 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
14800 	ASSERT(rlink != NULL);
14801 	mutex_enter(&rgnp->rgn_mutex);
14802 	if (rgnp->rgn_sfmmu_head == sfmmup) {
14803 		sfmmu_t *next = rlink->next;
14804 		rgnp->rgn_sfmmu_head = next;
14805 		/*
14806 		 * if we are stopped by xc_attention() after this
14807 		 * point the forward link walking in
14808 		 * sfmmu_rgntlb_demap() will work correctly since the
14809 		 * head correctly points to the next element.
14810 		 */
14811 		membar_stst();
14812 		rlink->next = NULL;
14813 		ASSERT(rlink->prev == NULL);
14814 		if (next != NULL) {
14815 			sf_rgn_link_t *nrlink;
14816 			/* LINTED: constant in conditional context */
14817 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14818 			ASSERT(nrlink != NULL);
14819 			ASSERT(nrlink->prev == sfmmup);
14820 			nrlink->prev = NULL;
14821 		}
14822 	} else {
14823 		sfmmu_t *next = rlink->next;
14824 		sfmmu_t *prev = rlink->prev;
14825 		sf_rgn_link_t *prlink;
14826 
14827 		ASSERT(prev != NULL);
14828 		/* LINTED: constant in conditional context */
14829 		SFMMU_HMERID2RLINKP(prev, rid, prlink, 0, 0);
14830 		ASSERT(prlink != NULL);
14831 		ASSERT(prlink->next == sfmmup);
14832 		prlink->next = next;
14833 		/*
14834 		 * if we are stopped by xc_attention()
14835 		 * after this point the forward link walking
14836 		 * will work correctly since the prev element
14837 		 * correctly points to the next element.
14838 		 */
14839 		membar_stst();
14840 		rlink->next = NULL;
14841 		rlink->prev = NULL;
14842 		if (next != NULL) {
14843 			sf_rgn_link_t *nrlink;
14844 			/* LINTED: constant in conditional context */
14845 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14846 			ASSERT(nrlink != NULL);
14847 			ASSERT(nrlink->prev == sfmmup);
14848 			nrlink->prev = prev;
14849 		}
14850 	}
14851 	mutex_exit(&rgnp->rgn_mutex);
14852 }
14853 
14854 /*
14855  * Link scd sfmmu onto ism or hme region list for each region in the
14856  * scd region map.
14857  */
14858 void
14859 sfmmu_link_scd_to_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14860 {
14861 	uint_t rid;
14862 	uint_t i;
14863 	uint_t j;
14864 	ulong_t w;
14865 	sf_region_t *rgnp;
14866 	sfmmu_t *scsfmmup;
14867 
14868 	scsfmmup = scdp->scd_sfmmup;
14869 	ASSERT(scsfmmup->sfmmu_scdhat);
14870 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14871 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14872 			continue;
14873 		}
14874 		j = 0;
14875 		while (w) {
14876 			if (!(w & 0x1)) {
14877 				j++;
14878 				w >>= 1;
14879 				continue;
14880 			}
14881 			rid = (i << BT_ULSHIFT) | j;
14882 			j++;
14883 			w >>= 1;
14884 
14885 			if (rid < SFMMU_MAX_HME_REGIONS) {
14886 				rgnp = srdp->srd_hmergnp[rid];
14887 				ASSERT(rgnp->rgn_id == rid);
14888 				ASSERT(rgnp->rgn_refcnt > 0);
14889 				sfmmu_link_to_hmeregion(scsfmmup, rgnp);
14890 			} else {
14891 				sfmmu_t *ism_hatid = NULL;
14892 				ism_ment_t *ism_ment;
14893 				rid -= SFMMU_MAX_HME_REGIONS;
14894 				rgnp = srdp->srd_ismrgnp[rid];
14895 				ASSERT(rgnp->rgn_id == rid);
14896 				ASSERT(rgnp->rgn_refcnt > 0);
14897 
14898 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14899 				ASSERT(ism_hatid->sfmmu_ismhat);
14900 				ism_ment = &scdp->scd_ism_links[rid];
14901 				ism_ment->iment_hat = scsfmmup;
14902 				ism_ment->iment_base_va = rgnp->rgn_saddr;
14903 				mutex_enter(&ism_mlist_lock);
14904 				iment_add(ism_ment, ism_hatid);
14905 				mutex_exit(&ism_mlist_lock);
14906 
14907 			}
14908 		}
14909 	}
14910 }
14911 /*
14912  * Unlink scd sfmmu from ism or hme region list for each region in the
14913  * scd region map.
14914  */
14915 void
14916 sfmmu_unlink_scd_from_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14917 {
14918 	uint_t rid;
14919 	uint_t i;
14920 	uint_t j;
14921 	ulong_t w;
14922 	sf_region_t *rgnp;
14923 	sfmmu_t *scsfmmup;
14924 
14925 	scsfmmup = scdp->scd_sfmmup;
14926 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14927 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14928 			continue;
14929 		}
14930 		j = 0;
14931 		while (w) {
14932 			if (!(w & 0x1)) {
14933 				j++;
14934 				w >>= 1;
14935 				continue;
14936 			}
14937 			rid = (i << BT_ULSHIFT) | j;
14938 			j++;
14939 			w >>= 1;
14940 
14941 			if (rid < SFMMU_MAX_HME_REGIONS) {
14942 				rgnp = srdp->srd_hmergnp[rid];
14943 				ASSERT(rgnp->rgn_id == rid);
14944 				ASSERT(rgnp->rgn_refcnt > 0);
14945 				sfmmu_unlink_from_hmeregion(scsfmmup,
14946 				    rgnp);
14947 
14948 			} else {
14949 				sfmmu_t *ism_hatid = NULL;
14950 				ism_ment_t *ism_ment;
14951 				rid -= SFMMU_MAX_HME_REGIONS;
14952 				rgnp = srdp->srd_ismrgnp[rid];
14953 				ASSERT(rgnp->rgn_id == rid);
14954 				ASSERT(rgnp->rgn_refcnt > 0);
14955 
14956 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14957 				ASSERT(ism_hatid->sfmmu_ismhat);
14958 				ism_ment = &scdp->scd_ism_links[rid];
14959 				ASSERT(ism_ment->iment_hat == scdp->scd_sfmmup);
14960 				ASSERT(ism_ment->iment_base_va ==
14961 				    rgnp->rgn_saddr);
14962 				ism_ment->iment_hat = NULL;
14963 				ism_ment->iment_base_va = 0;
14964 				mutex_enter(&ism_mlist_lock);
14965 				iment_sub(ism_ment, ism_hatid);
14966 				mutex_exit(&ism_mlist_lock);
14967 
14968 			}
14969 		}
14970 	}
14971 }
14972 /*
14973  * Allocates and initialises a new SCD structure, this is called with
14974  * the srd_scd_mutex held and returns with the reference count
14975  * initialised to 1.
14976  */
14977 static sf_scd_t *
14978 sfmmu_alloc_scd(sf_srd_t *srdp, sf_region_map_t *new_map)
14979 {
14980 	sf_scd_t *new_scdp;
14981 	sfmmu_t *scsfmmup;
14982 	int i;
14983 
14984 	ASSERT(MUTEX_HELD(&srdp->srd_scd_mutex));
14985 	new_scdp = kmem_cache_alloc(scd_cache, KM_SLEEP);
14986 
14987 	scsfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
14988 	new_scdp->scd_sfmmup = scsfmmup;
14989 	scsfmmup->sfmmu_srdp = srdp;
14990 	scsfmmup->sfmmu_scdp = new_scdp;
14991 	scsfmmup->sfmmu_tsb0_4minflcnt = 0;
14992 	scsfmmup->sfmmu_scdhat = 1;
14993 	CPUSET_ALL(scsfmmup->sfmmu_cpusran);
14994 	bzero(scsfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
14995 
14996 	ASSERT(max_mmu_ctxdoms > 0);
14997 	for (i = 0; i < max_mmu_ctxdoms; i++) {
14998 		scsfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
14999 		scsfmmup->sfmmu_ctxs[i].gnum = 0;
15000 	}
15001 
15002 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
15003 		new_scdp->scd_rttecnt[i] = 0;
15004 	}
15005 
15006 	new_scdp->scd_region_map = *new_map;
15007 	new_scdp->scd_refcnt = 1;
15008 	if (sfmmu_alloc_scd_tsbs(srdp, new_scdp) != TSB_SUCCESS) {
15009 		kmem_cache_free(scd_cache, new_scdp);
15010 		kmem_cache_free(sfmmuid_cache, scsfmmup);
15011 		return (NULL);
15012 	}
15013 	if (&mmu_init_scd) {
15014 		mmu_init_scd(new_scdp);
15015 	}
15016 	return (new_scdp);
15017 }
15018 
15019 /*
15020  * The first phase of a process joining an SCD. The hat structure is
15021  * linked to the SCD queue and then the HAT_JOIN_SCD sfmmu flag is set
15022  * and a cross-call with context invalidation is used to cause the
15023  * remaining work to be carried out in the sfmmu_tsbmiss_exception()
15024  * routine.
15025  */
15026 static void
15027 sfmmu_join_scd(sf_scd_t *scdp, sfmmu_t *sfmmup)
15028 {
15029 	hatlock_t *hatlockp;
15030 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15031 	int i;
15032 	sf_scd_t *old_scdp;
15033 
15034 	ASSERT(srdp != NULL);
15035 	ASSERT(scdp != NULL);
15036 	ASSERT(scdp->scd_refcnt > 0);
15037 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15038 
15039 	if ((old_scdp = sfmmup->sfmmu_scdp) != NULL) {
15040 		ASSERT(old_scdp != scdp);
15041 
15042 		mutex_enter(&old_scdp->scd_mutex);
15043 		sfmmu_from_scd_list(&old_scdp->scd_sf_list, sfmmup);
15044 		mutex_exit(&old_scdp->scd_mutex);
15045 		/*
15046 		 * sfmmup leaves the old scd. Update sfmmu_ttecnt to
15047 		 * include the shme rgn ttecnt for rgns that
15048 		 * were in the old SCD
15049 		 */
15050 		for (i = 0; i < mmu_page_sizes; i++) {
15051 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15052 			    old_scdp->scd_rttecnt[i]);
15053 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15054 			    sfmmup->sfmmu_scdrttecnt[i]);
15055 		}
15056 	}
15057 
15058 	/*
15059 	 * Move sfmmu to the scd lists.
15060 	 */
15061 	mutex_enter(&scdp->scd_mutex);
15062 	sfmmu_to_scd_list(&scdp->scd_sf_list, sfmmup);
15063 	mutex_exit(&scdp->scd_mutex);
15064 	SF_SCD_INCR_REF(scdp);
15065 
15066 	hatlockp = sfmmu_hat_enter(sfmmup);
15067 	/*
15068 	 * For a multi-thread process, we must stop
15069 	 * all the other threads before joining the scd.
15070 	 */
15071 
15072 	SFMMU_FLAGS_SET(sfmmup, HAT_JOIN_SCD);
15073 
15074 	sfmmu_invalidate_ctx(sfmmup);
15075 	sfmmup->sfmmu_scdp = scdp;
15076 
15077 	/*
15078 	 * Copy scd_rttecnt into sfmmup's sfmmu_scdrttecnt, and update
15079 	 * sfmmu_ttecnt to not include the rgn ttecnt just joined in SCD.
15080 	 */
15081 	for (i = 0; i < mmu_page_sizes; i++) {
15082 		sfmmup->sfmmu_scdrttecnt[i] = scdp->scd_rttecnt[i];
15083 		ASSERT(sfmmup->sfmmu_ttecnt[i] >= scdp->scd_rttecnt[i]);
15084 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15085 		    -sfmmup->sfmmu_scdrttecnt[i]);
15086 	}
15087 	/* update tsb0 inflation count */
15088 	if (old_scdp != NULL) {
15089 		sfmmup->sfmmu_tsb0_4minflcnt +=
15090 		    old_scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15091 	}
15092 	ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
15093 	    scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt);
15094 	sfmmup->sfmmu_tsb0_4minflcnt -= scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15095 
15096 	sfmmu_hat_exit(hatlockp);
15097 
15098 	if (old_scdp != NULL) {
15099 		SF_SCD_DECR_REF(srdp, old_scdp);
15100 	}
15101 
15102 }
15103 
15104 /*
15105  * This routine is called by a process to become part of an SCD. It is called
15106  * from sfmmu_tsbmiss_exception() once most of the initial work has been
15107  * done by sfmmu_join_scd(). This routine must not drop the hat lock.
15108  */
15109 static void
15110 sfmmu_finish_join_scd(sfmmu_t *sfmmup)
15111 {
15112 	struct tsb_info	*tsbinfop;
15113 
15114 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15115 	ASSERT(sfmmup->sfmmu_scdp != NULL);
15116 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD));
15117 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15118 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID));
15119 
15120 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
15121 	    tsbinfop = tsbinfop->tsb_next) {
15122 		if (tsbinfop->tsb_flags & TSB_SWAPPED) {
15123 			continue;
15124 		}
15125 		ASSERT(!(tsbinfop->tsb_flags & TSB_RELOC_FLAG));
15126 
15127 		sfmmu_inv_tsb(tsbinfop->tsb_va,
15128 		    TSB_BYTES(tsbinfop->tsb_szc));
15129 	}
15130 
15131 	/* Set HAT_CTX1_FLAG for all SCD ISMs */
15132 	sfmmu_ism_hatflags(sfmmup, 1);
15133 
15134 	SFMMU_STAT(sf_join_scd);
15135 }
15136 
15137 /*
15138  * This routine is called in order to check if there is an SCD which matches
15139  * the process's region map if not then a new SCD may be created.
15140  */
15141 static void
15142 sfmmu_find_scd(sfmmu_t *sfmmup)
15143 {
15144 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15145 	sf_scd_t *scdp, *new_scdp;
15146 	int ret;
15147 
15148 	ASSERT(srdp != NULL);
15149 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15150 
15151 	mutex_enter(&srdp->srd_scd_mutex);
15152 	for (scdp = srdp->srd_scdp; scdp != NULL;
15153 	    scdp = scdp->scd_next) {
15154 		SF_RGNMAP_EQUAL(&scdp->scd_region_map,
15155 		    &sfmmup->sfmmu_region_map, ret);
15156 		if (ret == 1) {
15157 			SF_SCD_INCR_REF(scdp);
15158 			mutex_exit(&srdp->srd_scd_mutex);
15159 			sfmmu_join_scd(scdp, sfmmup);
15160 			ASSERT(scdp->scd_refcnt >= 2);
15161 			atomic_add_32((volatile uint32_t *)
15162 			    &scdp->scd_refcnt, -1);
15163 			return;
15164 		} else {
15165 			/*
15166 			 * If the sfmmu region map is a subset of the scd
15167 			 * region map, then the assumption is that this process
15168 			 * will continue attaching to ISM segments until the
15169 			 * region maps are equal.
15170 			 */
15171 			SF_RGNMAP_IS_SUBSET(&scdp->scd_region_map,
15172 			    &sfmmup->sfmmu_region_map, ret);
15173 			if (ret == 1) {
15174 				mutex_exit(&srdp->srd_scd_mutex);
15175 				return;
15176 			}
15177 		}
15178 	}
15179 
15180 	ASSERT(scdp == NULL);
15181 	/*
15182 	 * No matching SCD has been found, create a new one.
15183 	 */
15184 	if ((new_scdp = sfmmu_alloc_scd(srdp, &sfmmup->sfmmu_region_map)) ==
15185 	    NULL) {
15186 		mutex_exit(&srdp->srd_scd_mutex);
15187 		return;
15188 	}
15189 
15190 	/*
15191 	 * sfmmu_alloc_scd() returns with a ref count of 1 on the scd.
15192 	 */
15193 
15194 	/* Set scd_rttecnt for shme rgns in SCD */
15195 	sfmmu_set_scd_rttecnt(srdp, new_scdp);
15196 
15197 	/*
15198 	 * Link scd onto srd_scdp list and scd sfmmu onto region/iment lists.
15199 	 */
15200 	sfmmu_link_scd_to_regions(srdp, new_scdp);
15201 	sfmmu_add_scd(&srdp->srd_scdp, new_scdp);
15202 	SFMMU_STAT_ADD(sf_create_scd, 1);
15203 
15204 	mutex_exit(&srdp->srd_scd_mutex);
15205 	sfmmu_join_scd(new_scdp, sfmmup);
15206 	ASSERT(new_scdp->scd_refcnt >= 2);
15207 	atomic_add_32((volatile uint32_t *)&new_scdp->scd_refcnt, -1);
15208 }
15209 
15210 /*
15211  * This routine is called by a process to remove itself from an SCD. It is
15212  * either called when the processes has detached from a segment or from
15213  * hat_free_start() as a result of calling exit.
15214  */
15215 static void
15216 sfmmu_leave_scd(sfmmu_t *sfmmup, uchar_t r_type)
15217 {
15218 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15219 	sf_srd_t *srdp =  sfmmup->sfmmu_srdp;
15220 	hatlock_t *hatlockp = TSB_HASH(sfmmup);
15221 	int i;
15222 
15223 	ASSERT(scdp != NULL);
15224 	ASSERT(srdp != NULL);
15225 
15226 	if (sfmmup->sfmmu_free) {
15227 		/*
15228 		 * If the process is part of an SCD the sfmmu is unlinked
15229 		 * from scd_sf_list.
15230 		 */
15231 		mutex_enter(&scdp->scd_mutex);
15232 		sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15233 		mutex_exit(&scdp->scd_mutex);
15234 		/*
15235 		 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15236 		 * are about to leave the SCD
15237 		 */
15238 		for (i = 0; i < mmu_page_sizes; i++) {
15239 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15240 			    scdp->scd_rttecnt[i]);
15241 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15242 			    sfmmup->sfmmu_scdrttecnt[i]);
15243 			sfmmup->sfmmu_scdrttecnt[i] = 0;
15244 		}
15245 		sfmmup->sfmmu_scdp = NULL;
15246 
15247 		SF_SCD_DECR_REF(srdp, scdp);
15248 		return;
15249 	}
15250 
15251 	ASSERT(r_type != SFMMU_REGION_ISM ||
15252 	    SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15253 	ASSERT(scdp->scd_refcnt);
15254 	ASSERT(!sfmmup->sfmmu_free);
15255 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15256 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15257 
15258 	/*
15259 	 * Wait for ISM maps to be updated.
15260 	 */
15261 	if (r_type != SFMMU_REGION_ISM) {
15262 		while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY) &&
15263 		    sfmmup->sfmmu_scdp != NULL) {
15264 			cv_wait(&sfmmup->sfmmu_tsb_cv,
15265 			    HATLOCK_MUTEXP(hatlockp));
15266 		}
15267 
15268 		if (sfmmup->sfmmu_scdp == NULL) {
15269 			sfmmu_hat_exit(hatlockp);
15270 			return;
15271 		}
15272 		SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
15273 	}
15274 
15275 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
15276 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
15277 		/*
15278 		 * Since HAT_JOIN_SCD was set our context
15279 		 * is still invalid.
15280 		 */
15281 	} else {
15282 		/*
15283 		 * For a multi-thread process, we must stop
15284 		 * all the other threads before leaving the scd.
15285 		 */
15286 
15287 		sfmmu_invalidate_ctx(sfmmup);
15288 	}
15289 
15290 	/* Clear all the rid's for ISM, delete flags, etc */
15291 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15292 	sfmmu_ism_hatflags(sfmmup, 0);
15293 
15294 	/*
15295 	 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15296 	 * are in SCD before this sfmmup leaves the SCD.
15297 	 */
15298 	for (i = 0; i < mmu_page_sizes; i++) {
15299 		ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15300 		    scdp->scd_rttecnt[i]);
15301 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15302 		    sfmmup->sfmmu_scdrttecnt[i]);
15303 		sfmmup->sfmmu_scdrttecnt[i] = 0;
15304 		/* update ismttecnt to include SCD ism before hat leaves SCD */
15305 		sfmmup->sfmmu_ismttecnt[i] += sfmmup->sfmmu_scdismttecnt[i];
15306 		sfmmup->sfmmu_scdismttecnt[i] = 0;
15307 	}
15308 	/* update tsb0 inflation count */
15309 	sfmmup->sfmmu_tsb0_4minflcnt += scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15310 
15311 	if (r_type != SFMMU_REGION_ISM) {
15312 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
15313 	}
15314 	sfmmup->sfmmu_scdp = NULL;
15315 
15316 	sfmmu_hat_exit(hatlockp);
15317 
15318 	/*
15319 	 * Unlink sfmmu from scd_sf_list this can be done without holding
15320 	 * the hat lock as we hold the sfmmu_as lock which prevents
15321 	 * hat_join_region from adding this thread to the scd again. Other
15322 	 * threads check if sfmmu_scdp is NULL under hat lock and if it's NULL
15323 	 * they won't get here, since sfmmu_leave_scd() clears sfmmu_scdp
15324 	 * while holding the hat lock.
15325 	 */
15326 	mutex_enter(&scdp->scd_mutex);
15327 	sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15328 	mutex_exit(&scdp->scd_mutex);
15329 	SFMMU_STAT(sf_leave_scd);
15330 
15331 	SF_SCD_DECR_REF(srdp, scdp);
15332 	hatlockp = sfmmu_hat_enter(sfmmup);
15333 
15334 }
15335 
15336 /*
15337  * Unlink and free up an SCD structure with a reference count of 0.
15338  */
15339 static void
15340 sfmmu_destroy_scd(sf_srd_t *srdp, sf_scd_t *scdp, sf_region_map_t *scd_rmap)
15341 {
15342 	sfmmu_t *scsfmmup;
15343 	sf_scd_t *sp;
15344 	hatlock_t *shatlockp;
15345 	int i, ret;
15346 
15347 	mutex_enter(&srdp->srd_scd_mutex);
15348 	for (sp = srdp->srd_scdp; sp != NULL; sp = sp->scd_next) {
15349 		if (sp == scdp)
15350 			break;
15351 	}
15352 	if (sp == NULL || sp->scd_refcnt) {
15353 		mutex_exit(&srdp->srd_scd_mutex);
15354 		return;
15355 	}
15356 
15357 	/*
15358 	 * It is possible that the scd has been freed and reallocated with a
15359 	 * different region map while we've been waiting for the srd_scd_mutex.
15360 	 */
15361 	SF_RGNMAP_EQUAL(scd_rmap, &sp->scd_region_map, ret);
15362 	if (ret != 1) {
15363 		mutex_exit(&srdp->srd_scd_mutex);
15364 		return;
15365 	}
15366 
15367 	ASSERT(scdp->scd_sf_list == NULL);
15368 	/*
15369 	 * Unlink scd from srd_scdp list.
15370 	 */
15371 	sfmmu_remove_scd(&srdp->srd_scdp, scdp);
15372 	mutex_exit(&srdp->srd_scd_mutex);
15373 
15374 	sfmmu_unlink_scd_from_regions(srdp, scdp);
15375 
15376 	/* Clear shared context tsb and release ctx */
15377 	scsfmmup = scdp->scd_sfmmup;
15378 
15379 	/*
15380 	 * create a barrier so that scd will not be destroyed
15381 	 * if other thread still holds the same shared hat lock.
15382 	 * E.g., sfmmu_tsbmiss_exception() needs to acquire the
15383 	 * shared hat lock before checking the shared tsb reloc flag.
15384 	 */
15385 	shatlockp = sfmmu_hat_enter(scsfmmup);
15386 	sfmmu_hat_exit(shatlockp);
15387 
15388 	sfmmu_free_scd_tsbs(scsfmmup);
15389 
15390 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
15391 		if (scsfmmup->sfmmu_hmeregion_links[i] != NULL) {
15392 			kmem_free(scsfmmup->sfmmu_hmeregion_links[i],
15393 			    SFMMU_L2_HMERLINKS_SIZE);
15394 			scsfmmup->sfmmu_hmeregion_links[i] = NULL;
15395 		}
15396 	}
15397 	kmem_cache_free(sfmmuid_cache, scsfmmup);
15398 	kmem_cache_free(scd_cache, scdp);
15399 	SFMMU_STAT(sf_destroy_scd);
15400 }
15401 
15402 /*
15403  * Modifies the HAT_CTX1_FLAG for each of the ISM segments which correspond to
15404  * bits which are set in the ism_region_map parameter. This flag indicates to
15405  * the tsbmiss handler that mapping for these segments should be loaded using
15406  * the shared context.
15407  */
15408 static void
15409 sfmmu_ism_hatflags(sfmmu_t *sfmmup, int addflag)
15410 {
15411 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15412 	ism_blk_t *ism_blkp;
15413 	ism_map_t *ism_map;
15414 	int i, rid;
15415 
15416 	ASSERT(sfmmup->sfmmu_iblk != NULL);
15417 	ASSERT(scdp != NULL);
15418 	/*
15419 	 * Note that the caller either set HAT_ISMBUSY flag or checked
15420 	 * under hat lock that HAT_ISMBUSY was not set by another thread.
15421 	 */
15422 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15423 
15424 	ism_blkp = sfmmup->sfmmu_iblk;
15425 	while (ism_blkp != NULL) {
15426 		ism_map = ism_blkp->iblk_maps;
15427 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
15428 			rid = ism_map[i].imap_rid;
15429 			if (rid == SFMMU_INVALID_ISMRID) {
15430 				continue;
15431 			}
15432 			ASSERT(rid >= 0 && rid < SFMMU_MAX_ISM_REGIONS);
15433 			if (SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid) &&
15434 			    addflag) {
15435 				ism_map[i].imap_hatflags |=
15436 				    HAT_CTX1_FLAG;
15437 			} else {
15438 				ism_map[i].imap_hatflags &=
15439 				    ~HAT_CTX1_FLAG;
15440 			}
15441 		}
15442 		ism_blkp = ism_blkp->iblk_next;
15443 	}
15444 }
15445 
15446 static int
15447 sfmmu_srd_lock_held(sf_srd_t *srdp)
15448 {
15449 	return (MUTEX_HELD(&srdp->srd_mutex));
15450 }
15451 
15452 /* ARGSUSED */
15453 static int
15454 sfmmu_scdcache_constructor(void *buf, void *cdrarg, int kmflags)
15455 {
15456 	sf_scd_t *scdp = (sf_scd_t *)buf;
15457 
15458 	bzero(buf, sizeof (sf_scd_t));
15459 	mutex_init(&scdp->scd_mutex, NULL, MUTEX_DEFAULT, NULL);
15460 	return (0);
15461 }
15462 
15463 /* ARGSUSED */
15464 static void
15465 sfmmu_scdcache_destructor(void *buf, void *cdrarg)
15466 {
15467 	sf_scd_t *scdp = (sf_scd_t *)buf;
15468 
15469 	mutex_destroy(&scdp->scd_mutex);
15470 }
15471 
15472 /*
15473  * The listp parameter is a pointer to a list of hmeblks which are partially
15474  * freed as result of calling sfmmu_hblk_hash_rm(), the last phase of the
15475  * freeing process is to cross-call all cpus to ensure that there are no
15476  * remaining cached references.
15477  *
15478  * If the local generation number is less than the global then we can free
15479  * hmeblks which are already on the pending queue as another cpu has completed
15480  * the cross-call.
15481  *
15482  * We cross-call to make sure that there are no threads on other cpus accessing
15483  * these hmblks and then complete the process of freeing them under the
15484  * following conditions:
15485  * 	The total number of pending hmeblks is greater than the threshold
15486  *	The reserve list has fewer than HBLK_RESERVE_CNT hmeblks
15487  *	It is at least 1 second since the last time we cross-called
15488  *
15489  * Otherwise, we add the hmeblks to the per-cpu pending queue.
15490  */
15491 static void
15492 sfmmu_hblks_list_purge(struct hme_blk **listp, int dontfree)
15493 {
15494 	struct hme_blk *hblkp, *pr_hblkp = NULL;
15495 	int		count = 0;
15496 	cpuset_t	cpuset = cpu_ready_set;
15497 	cpu_hme_pend_t	*cpuhp;
15498 	timestruc_t	now;
15499 	int		one_second_expired = 0;
15500 
15501 	gethrestime_lasttick(&now);
15502 
15503 	for (hblkp = *listp; hblkp != NULL; hblkp = hblkp->hblk_next) {
15504 		ASSERT(hblkp->hblk_shw_bit == 0);
15505 		ASSERT(hblkp->hblk_shared == 0);
15506 		count++;
15507 		pr_hblkp = hblkp;
15508 	}
15509 
15510 	cpuhp = &cpu_hme_pend[CPU->cpu_seqid];
15511 	mutex_enter(&cpuhp->chp_mutex);
15512 
15513 	if ((cpuhp->chp_count + count) == 0) {
15514 		mutex_exit(&cpuhp->chp_mutex);
15515 		return;
15516 	}
15517 
15518 	if ((now.tv_sec - cpuhp->chp_timestamp) > 1) {
15519 		one_second_expired  = 1;
15520 	}
15521 
15522 	if (!dontfree && (freehblkcnt < HBLK_RESERVE_CNT ||
15523 	    (cpuhp->chp_count + count) > cpu_hme_pend_thresh ||
15524 	    one_second_expired)) {
15525 		/* Append global list to local */
15526 		if (pr_hblkp == NULL) {
15527 			*listp = cpuhp->chp_listp;
15528 		} else {
15529 			pr_hblkp->hblk_next = cpuhp->chp_listp;
15530 		}
15531 		cpuhp->chp_listp = NULL;
15532 		cpuhp->chp_count = 0;
15533 		cpuhp->chp_timestamp = now.tv_sec;
15534 		mutex_exit(&cpuhp->chp_mutex);
15535 
15536 		kpreempt_disable();
15537 		CPUSET_DEL(cpuset, CPU->cpu_id);
15538 		xt_sync(cpuset);
15539 		xt_sync(cpuset);
15540 		kpreempt_enable();
15541 
15542 		/*
15543 		 * At this stage we know that no trap handlers on other
15544 		 * cpus can have references to hmeblks on the list.
15545 		 */
15546 		sfmmu_hblk_free(listp);
15547 	} else if (*listp != NULL) {
15548 		pr_hblkp->hblk_next = cpuhp->chp_listp;
15549 		cpuhp->chp_listp = *listp;
15550 		cpuhp->chp_count += count;
15551 		*listp = NULL;
15552 		mutex_exit(&cpuhp->chp_mutex);
15553 	} else {
15554 		mutex_exit(&cpuhp->chp_mutex);
15555 	}
15556 }
15557 
15558 /*
15559  * Add an hmeblk to the the hash list.
15560  */
15561 void
15562 sfmmu_hblk_hash_add(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15563 	uint64_t hblkpa)
15564 {
15565 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15566 #ifdef	DEBUG
15567 	if (hmebp->hmeblkp == NULL) {
15568 		ASSERT(hmebp->hmeh_nextpa == HMEBLK_ENDPA);
15569 	}
15570 #endif /* DEBUG */
15571 
15572 	hmeblkp->hblk_nextpa = hmebp->hmeh_nextpa;
15573 	/*
15574 	 * Since the TSB miss handler now does not lock the hash chain before
15575 	 * walking it, make sure that the hmeblks nextpa is globally visible
15576 	 * before we make the hmeblk globally visible by updating the chain root
15577 	 * pointer in the hash bucket.
15578 	 */
15579 	membar_producer();
15580 	hmebp->hmeh_nextpa = hblkpa;
15581 	hmeblkp->hblk_next = hmebp->hmeblkp;
15582 	hmebp->hmeblkp = hmeblkp;
15583 
15584 }
15585 
15586 /*
15587  * This function is the first part of a 2 part process to remove an hmeblk
15588  * from the hash chain. In this phase we unlink the hmeblk from the hash chain
15589  * but leave the next physical pointer unchanged. The hmeblk is then linked onto
15590  * a per-cpu pending list using the virtual address pointer.
15591  *
15592  * TSB miss trap handlers that start after this phase will no longer see
15593  * this hmeblk. TSB miss handlers that still cache this hmeblk in a register
15594  * can still use it for further chain traversal because we haven't yet modifed
15595  * the next physical pointer or freed it.
15596  *
15597  * In the second phase of hmeblk removal we'll issue a barrier xcall before
15598  * we reuse or free this hmeblk. This will make sure all lingering references to
15599  * the hmeblk after first phase disappear before we finally reclaim it.
15600  * This scheme eliminates the need for TSB miss handlers to lock hmeblk chains
15601  * during their traversal.
15602  *
15603  * The hmehash_mutex must be held when calling this function.
15604  *
15605  * Input:
15606  *	 hmebp - hme hash bucket pointer
15607  *	 hmeblkp - address of hmeblk to be removed
15608  *	 pr_hblk - virtual address of previous hmeblkp
15609  *	 listp - pointer to list of hmeblks linked by virtual address
15610  *	 free_now flag - indicates that a complete removal from the hash chains
15611  *			 is necessary.
15612  *
15613  * It is inefficient to use the free_now flag as a cross-call is required to
15614  * remove a single hmeblk from the hash chain but is necessary when hmeblks are
15615  * in short supply.
15616  */
15617 void
15618 sfmmu_hblk_hash_rm(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15619     struct hme_blk *pr_hblk, struct hme_blk **listp,
15620     int free_now)
15621 {
15622 	int shw_size, vshift;
15623 	struct hme_blk *shw_hblkp;
15624 	uint_t		shw_mask, newshw_mask;
15625 	caddr_t		vaddr;
15626 	int		size;
15627 	cpuset_t cpuset = cpu_ready_set;
15628 
15629 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15630 
15631 	if (hmebp->hmeblkp == hmeblkp) {
15632 		hmebp->hmeh_nextpa = hmeblkp->hblk_nextpa;
15633 		hmebp->hmeblkp = hmeblkp->hblk_next;
15634 	} else {
15635 		pr_hblk->hblk_nextpa = hmeblkp->hblk_nextpa;
15636 		pr_hblk->hblk_next = hmeblkp->hblk_next;
15637 	}
15638 
15639 	size = get_hblk_ttesz(hmeblkp);
15640 	shw_hblkp = hmeblkp->hblk_shadow;
15641 	if (shw_hblkp) {
15642 		ASSERT(hblktosfmmu(hmeblkp) != KHATID);
15643 		ASSERT(!hmeblkp->hblk_shared);
15644 #ifdef	DEBUG
15645 		if (mmu_page_sizes == max_mmu_page_sizes) {
15646 			ASSERT(size < TTE256M);
15647 		} else {
15648 			ASSERT(size < TTE4M);
15649 		}
15650 #endif /* DEBUG */
15651 
15652 		shw_size = get_hblk_ttesz(shw_hblkp);
15653 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
15654 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
15655 		ASSERT(vshift < 8);
15656 		/*
15657 		 * Atomically clear shadow mask bit
15658 		 */
15659 		do {
15660 			shw_mask = shw_hblkp->hblk_shw_mask;
15661 			ASSERT(shw_mask & (1 << vshift));
15662 			newshw_mask = shw_mask & ~(1 << vshift);
15663 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
15664 			    shw_mask, newshw_mask);
15665 		} while (newshw_mask != shw_mask);
15666 		hmeblkp->hblk_shadow = NULL;
15667 	}
15668 	hmeblkp->hblk_shw_bit = 0;
15669 
15670 	if (hmeblkp->hblk_shared) {
15671 #ifdef	DEBUG
15672 		sf_srd_t	*srdp;
15673 		sf_region_t	*rgnp;
15674 		uint_t		rid;
15675 
15676 		srdp = hblktosrd(hmeblkp);
15677 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
15678 		rid = hmeblkp->hblk_tag.htag_rid;
15679 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
15680 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
15681 		rgnp = srdp->srd_hmergnp[rid];
15682 		ASSERT(rgnp != NULL);
15683 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
15684 #endif /* DEBUG */
15685 		hmeblkp->hblk_shared = 0;
15686 	}
15687 	if (free_now) {
15688 		kpreempt_disable();
15689 		CPUSET_DEL(cpuset, CPU->cpu_id);
15690 		xt_sync(cpuset);
15691 		xt_sync(cpuset);
15692 		kpreempt_enable();
15693 
15694 		hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
15695 		hmeblkp->hblk_next = NULL;
15696 	} else {
15697 		/* Append hmeblkp to listp for processing later. */
15698 		hmeblkp->hblk_next = *listp;
15699 		*listp = hmeblkp;
15700 	}
15701 }
15702 
15703 /*
15704  * This routine is called when memory is in short supply and returns a free
15705  * hmeblk of the requested size from the cpu pending lists.
15706  */
15707 static struct hme_blk *
15708 sfmmu_check_pending_hblks(int size)
15709 {
15710 	int i;
15711 	struct hme_blk *hmeblkp = NULL, *last_hmeblkp;
15712 	int found_hmeblk;
15713 	cpuset_t cpuset = cpu_ready_set;
15714 	cpu_hme_pend_t *cpuhp;
15715 
15716 	/* Flush cpu hblk pending queues */
15717 	for (i = 0; i < NCPU; i++) {
15718 		cpuhp = &cpu_hme_pend[i];
15719 		if (cpuhp->chp_listp != NULL)  {
15720 			mutex_enter(&cpuhp->chp_mutex);
15721 			if (cpuhp->chp_listp == NULL)  {
15722 				mutex_exit(&cpuhp->chp_mutex);
15723 				continue;
15724 			}
15725 			found_hmeblk = 0;
15726 			last_hmeblkp = NULL;
15727 			for (hmeblkp = cpuhp->chp_listp; hmeblkp != NULL;
15728 			    hmeblkp = hmeblkp->hblk_next) {
15729 				if (get_hblk_ttesz(hmeblkp) == size) {
15730 					if (last_hmeblkp == NULL) {
15731 						cpuhp->chp_listp =
15732 						    hmeblkp->hblk_next;
15733 					} else {
15734 						last_hmeblkp->hblk_next =
15735 						    hmeblkp->hblk_next;
15736 					}
15737 					ASSERT(cpuhp->chp_count > 0);
15738 					cpuhp->chp_count--;
15739 					found_hmeblk = 1;
15740 					break;
15741 				} else {
15742 					last_hmeblkp = hmeblkp;
15743 				}
15744 			}
15745 			mutex_exit(&cpuhp->chp_mutex);
15746 
15747 			if (found_hmeblk) {
15748 				kpreempt_disable();
15749 				CPUSET_DEL(cpuset, CPU->cpu_id);
15750 				xt_sync(cpuset);
15751 				xt_sync(cpuset);
15752 				kpreempt_enable();
15753 				return (hmeblkp);
15754 			}
15755 		}
15756 	}
15757 	return (NULL);
15758 }
15759