xref: /titanic_51/usr/src/uts/sfmmu/vm/hat_sfmmu.c (revision a643d9fdf6f49293abc965d6cf38a68ad0cb2534)
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 	iment->iment_base_va = 0;
8509 }
8510 
8511 /*
8512  * Hat_share()/unshare() return an (non-zero) error
8513  * when saddr and daddr are not properly aligned.
8514  *
8515  * The top level mapping element determines the alignment
8516  * requirement for saddr and daddr, depending on different
8517  * architectures.
8518  *
8519  * When hat_share()/unshare() are not supported,
8520  * HATOP_SHARE()/UNSHARE() return 0
8521  */
8522 int
8523 hat_share(struct hat *sfmmup, caddr_t addr,
8524 	struct hat *ism_hatid, caddr_t sptaddr, size_t len, uint_t ismszc)
8525 {
8526 	ism_blk_t	*ism_blkp;
8527 	ism_blk_t	*new_iblk;
8528 	ism_map_t 	*ism_map;
8529 	ism_ment_t	*ism_ment;
8530 	int		i, added;
8531 	hatlock_t	*hatlockp;
8532 	int		reload_mmu = 0;
8533 	uint_t		ismshift = page_get_shift(ismszc);
8534 	size_t		ismpgsz = page_get_pagesize(ismszc);
8535 	uint_t		ismmask = (uint_t)ismpgsz - 1;
8536 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8537 	ushort_t	ismhatflag;
8538 	hat_region_cookie_t rcookie;
8539 	sf_scd_t	*old_scdp;
8540 
8541 #ifdef DEBUG
8542 	caddr_t		eaddr = addr + len;
8543 #endif /* DEBUG */
8544 
8545 	ASSERT(ism_hatid != NULL && sfmmup != NULL);
8546 	ASSERT(sptaddr == ISMID_STARTADDR);
8547 	/*
8548 	 * Check the alignment.
8549 	 */
8550 	if (!ISM_ALIGNED(ismshift, addr) || !ISM_ALIGNED(ismshift, sptaddr))
8551 		return (EINVAL);
8552 
8553 	/*
8554 	 * Check size alignment.
8555 	 */
8556 	if (!ISM_ALIGNED(ismshift, len))
8557 		return (EINVAL);
8558 
8559 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
8560 
8561 	/*
8562 	 * Allocate ism_ment for the ism_hat's mapping list, and an
8563 	 * ism map blk in case we need one.  We must do our
8564 	 * allocations before acquiring locks to prevent a deadlock
8565 	 * in the kmem allocator on the mapping list lock.
8566 	 */
8567 	new_iblk = kmem_cache_alloc(ism_blk_cache, KM_SLEEP);
8568 	ism_ment = kmem_cache_alloc(ism_ment_cache, KM_SLEEP);
8569 
8570 	/*
8571 	 * Serialize ISM mappings with the ISM busy flag, and also the
8572 	 * trap handlers.
8573 	 */
8574 	sfmmu_ismhat_enter(sfmmup, 0);
8575 
8576 	/*
8577 	 * Allocate an ism map blk if necessary.
8578 	 */
8579 	if (sfmmup->sfmmu_iblk == NULL) {
8580 		sfmmup->sfmmu_iblk = new_iblk;
8581 		bzero(new_iblk, sizeof (*new_iblk));
8582 		new_iblk->iblk_nextpa = (uint64_t)-1;
8583 		membar_stst();	/* make sure next ptr visible to all CPUs */
8584 		sfmmup->sfmmu_ismblkpa = va_to_pa((caddr_t)new_iblk);
8585 		reload_mmu = 1;
8586 		new_iblk = NULL;
8587 	}
8588 
8589 #ifdef DEBUG
8590 	/*
8591 	 * Make sure mapping does not already exist.
8592 	 */
8593 	ism_blkp = sfmmup->sfmmu_iblk;
8594 	while (ism_blkp != NULL) {
8595 		ism_map = ism_blkp->iblk_maps;
8596 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
8597 			if ((addr >= ism_start(ism_map[i]) &&
8598 			    addr < ism_end(ism_map[i])) ||
8599 			    eaddr > ism_start(ism_map[i]) &&
8600 			    eaddr <= ism_end(ism_map[i])) {
8601 				panic("sfmmu_share: Already mapped!");
8602 			}
8603 		}
8604 		ism_blkp = ism_blkp->iblk_next;
8605 	}
8606 #endif /* DEBUG */
8607 
8608 	ASSERT(ismszc >= TTE4M);
8609 	if (ismszc == TTE4M) {
8610 		ismhatflag = HAT_4M_FLAG;
8611 	} else if (ismszc == TTE32M) {
8612 		ismhatflag = HAT_32M_FLAG;
8613 	} else if (ismszc == TTE256M) {
8614 		ismhatflag = HAT_256M_FLAG;
8615 	}
8616 	/*
8617 	 * Add mapping to first available mapping slot.
8618 	 */
8619 	ism_blkp = sfmmup->sfmmu_iblk;
8620 	added = 0;
8621 	while (!added) {
8622 		ism_map = ism_blkp->iblk_maps;
8623 		for (i = 0; i < ISM_MAP_SLOTS; i++)  {
8624 			if (ism_map[i].imap_ismhat == NULL) {
8625 
8626 				ism_map[i].imap_ismhat = ism_hatid;
8627 				ism_map[i].imap_vb_shift = (uchar_t)ismshift;
8628 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8629 				ism_map[i].imap_hatflags = ismhatflag;
8630 				ism_map[i].imap_sz_mask = ismmask;
8631 				/*
8632 				 * imap_seg is checked in ISM_CHECK to see if
8633 				 * non-NULL, then other info assumed valid.
8634 				 */
8635 				membar_stst();
8636 				ism_map[i].imap_seg = (uintptr_t)addr | sh_size;
8637 				ism_map[i].imap_ment = ism_ment;
8638 
8639 				/*
8640 				 * Now add ourselves to the ism_hat's
8641 				 * mapping list.
8642 				 */
8643 				ism_ment->iment_hat = sfmmup;
8644 				ism_ment->iment_base_va = addr;
8645 				ism_hatid->sfmmu_ismhat = 1;
8646 				mutex_enter(&ism_mlist_lock);
8647 				iment_add(ism_ment, ism_hatid);
8648 				mutex_exit(&ism_mlist_lock);
8649 				added = 1;
8650 				break;
8651 			}
8652 		}
8653 		if (!added && ism_blkp->iblk_next == NULL) {
8654 			ism_blkp->iblk_next = new_iblk;
8655 			new_iblk = NULL;
8656 			bzero(ism_blkp->iblk_next,
8657 			    sizeof (*ism_blkp->iblk_next));
8658 			ism_blkp->iblk_next->iblk_nextpa = (uint64_t)-1;
8659 			membar_stst();
8660 			ism_blkp->iblk_nextpa =
8661 			    va_to_pa((caddr_t)ism_blkp->iblk_next);
8662 		}
8663 		ism_blkp = ism_blkp->iblk_next;
8664 	}
8665 
8666 	/*
8667 	 * After calling hat_join_region, sfmmup may join a new SCD or
8668 	 * move from the old scd to a new scd, in which case, we want to
8669 	 * shrink the sfmmup's private tsb size, i.e., pass shrink to
8670 	 * sfmmu_check_page_sizes at the end of this routine.
8671 	 */
8672 	old_scdp = sfmmup->sfmmu_scdp;
8673 
8674 	rcookie = hat_join_region(sfmmup, addr, len, (void *)ism_hatid, 0,
8675 	    PROT_ALL, ismszc, NULL, HAT_REGION_ISM);
8676 	if (rcookie != HAT_INVALID_REGION_COOKIE) {
8677 		ism_map[i].imap_rid = (uchar_t)((uint64_t)rcookie);
8678 	}
8679 	/*
8680 	 * Update our counters for this sfmmup's ism mappings.
8681 	 */
8682 	for (i = 0; i <= ismszc; i++) {
8683 		if (!(disable_ism_large_pages & (1 << i)))
8684 			(void) ism_tsb_entries(sfmmup, i);
8685 	}
8686 
8687 	/*
8688 	 * For ISM and DISM we do not support 512K pages, so we only only
8689 	 * search the 4M and 8K/64K hashes for 4 pagesize cpus, and search the
8690 	 * 256M or 32M, and 4M and 8K/64K hashes for 6 pagesize cpus.
8691 	 *
8692 	 * Need to set 32M/256M ISM flags to make sure
8693 	 * sfmmu_check_page_sizes() enables them on Panther.
8694 	 */
8695 	ASSERT((disable_ism_large_pages & (1 << TTE512K)) != 0);
8696 
8697 	switch (ismszc) {
8698 	case TTE256M:
8699 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_256M_ISM)) {
8700 			hatlockp = sfmmu_hat_enter(sfmmup);
8701 			SFMMU_FLAGS_SET(sfmmup, HAT_256M_ISM);
8702 			sfmmu_hat_exit(hatlockp);
8703 		}
8704 		break;
8705 	case TTE32M:
8706 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_32M_ISM)) {
8707 			hatlockp = sfmmu_hat_enter(sfmmup);
8708 			SFMMU_FLAGS_SET(sfmmup, HAT_32M_ISM);
8709 			sfmmu_hat_exit(hatlockp);
8710 		}
8711 		break;
8712 	default:
8713 		break;
8714 	}
8715 
8716 	/*
8717 	 * If we updated the ismblkpa for this HAT we must make
8718 	 * sure all CPUs running this process reload their tsbmiss area.
8719 	 * Otherwise they will fail to load the mappings in the tsbmiss
8720 	 * handler and will loop calling pagefault().
8721 	 */
8722 	if (reload_mmu) {
8723 		hatlockp = sfmmu_hat_enter(sfmmup);
8724 		sfmmu_sync_mmustate(sfmmup);
8725 		sfmmu_hat_exit(hatlockp);
8726 	}
8727 
8728 	sfmmu_ismhat_exit(sfmmup, 0);
8729 
8730 	/*
8731 	 * Free up ismblk if we didn't use it.
8732 	 */
8733 	if (new_iblk != NULL)
8734 		kmem_cache_free(ism_blk_cache, new_iblk);
8735 
8736 	/*
8737 	 * Check TSB and TLB page sizes.
8738 	 */
8739 	if (sfmmup->sfmmu_scdp != NULL && old_scdp != sfmmup->sfmmu_scdp) {
8740 		sfmmu_check_page_sizes(sfmmup, 0);
8741 	} else {
8742 		sfmmu_check_page_sizes(sfmmup, 1);
8743 	}
8744 	return (0);
8745 }
8746 
8747 /*
8748  * hat_unshare removes exactly one ism_map from
8749  * this process's as.  It expects multiple calls
8750  * to hat_unshare for multiple shm segments.
8751  */
8752 void
8753 hat_unshare(struct hat *sfmmup, caddr_t addr, size_t len, uint_t ismszc)
8754 {
8755 	ism_map_t 	*ism_map;
8756 	ism_ment_t	*free_ment = NULL;
8757 	ism_blk_t	*ism_blkp;
8758 	struct hat	*ism_hatid;
8759 	int 		found, i;
8760 	hatlock_t	*hatlockp;
8761 	struct tsb_info	*tsbinfo;
8762 	uint_t		ismshift = page_get_shift(ismszc);
8763 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8764 	uchar_t		ism_rid;
8765 	sf_scd_t	*old_scdp;
8766 
8767 	ASSERT(ISM_ALIGNED(ismshift, addr));
8768 	ASSERT(ISM_ALIGNED(ismshift, len));
8769 	ASSERT(sfmmup != NULL);
8770 	ASSERT(sfmmup != ksfmmup);
8771 
8772 	if (sfmmup->sfmmu_xhat_provider) {
8773 		XHAT_UNSHARE(sfmmup, addr, len);
8774 		return;
8775 	} else {
8776 		/*
8777 		 * This must be a CPU HAT. If the address space has
8778 		 * XHATs attached, inform all XHATs that ISM segment
8779 		 * is going away
8780 		 */
8781 		ASSERT(sfmmup->sfmmu_as != NULL);
8782 		if (sfmmup->sfmmu_as->a_xhat != NULL)
8783 			xhat_unshare_all(sfmmup->sfmmu_as, addr, len);
8784 	}
8785 
8786 	/*
8787 	 * Make sure that during the entire time ISM mappings are removed,
8788 	 * the trap handlers serialize behind us, and that no one else
8789 	 * can be mucking with ISM mappings.  This also lets us get away
8790 	 * with not doing expensive cross calls to flush the TLB -- we
8791 	 * just discard the context, flush the entire TSB, and call it
8792 	 * a day.
8793 	 */
8794 	sfmmu_ismhat_enter(sfmmup, 0);
8795 
8796 	/*
8797 	 * Remove the mapping.
8798 	 *
8799 	 * We can't have any holes in the ism map.
8800 	 * The tsb miss code while searching the ism map will
8801 	 * stop on an empty map slot.  So we must move
8802 	 * everyone past the hole up 1 if any.
8803 	 *
8804 	 * Also empty ism map blks are not freed until the
8805 	 * process exits. This is to prevent a MT race condition
8806 	 * between sfmmu_unshare() and sfmmu_tsbmiss_exception().
8807 	 */
8808 	found = 0;
8809 	ism_blkp = sfmmup->sfmmu_iblk;
8810 	while (!found && ism_blkp != NULL) {
8811 		ism_map = ism_blkp->iblk_maps;
8812 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
8813 			if (addr == ism_start(ism_map[i]) &&
8814 			    sh_size == (size_t)(ism_size(ism_map[i]))) {
8815 				found = 1;
8816 				break;
8817 			}
8818 		}
8819 		if (!found)
8820 			ism_blkp = ism_blkp->iblk_next;
8821 	}
8822 
8823 	if (found) {
8824 		ism_hatid = ism_map[i].imap_ismhat;
8825 		ism_rid = ism_map[i].imap_rid;
8826 		ASSERT(ism_hatid != NULL);
8827 		ASSERT(ism_hatid->sfmmu_ismhat == 1);
8828 
8829 		/*
8830 		 * After hat_leave_region, the sfmmup may leave SCD,
8831 		 * in which case, we want to grow the private tsb size when
8832 		 * calling sfmmu_check_page_sizes at the end of the routine.
8833 		 */
8834 		old_scdp = sfmmup->sfmmu_scdp;
8835 		/*
8836 		 * Then remove ourselves from the region.
8837 		 */
8838 		if (ism_rid != SFMMU_INVALID_ISMRID) {
8839 			hat_leave_region(sfmmup, (void *)((uint64_t)ism_rid),
8840 			    HAT_REGION_ISM);
8841 		}
8842 
8843 		/*
8844 		 * And now guarantee that any other cpu
8845 		 * that tries to process an ISM miss
8846 		 * will go to tl=0.
8847 		 */
8848 		hatlockp = sfmmu_hat_enter(sfmmup);
8849 		sfmmu_invalidate_ctx(sfmmup);
8850 		sfmmu_hat_exit(hatlockp);
8851 
8852 		/*
8853 		 * Remove ourselves from the ism mapping list.
8854 		 */
8855 		mutex_enter(&ism_mlist_lock);
8856 		iment_sub(ism_map[i].imap_ment, ism_hatid);
8857 		mutex_exit(&ism_mlist_lock);
8858 		free_ment = ism_map[i].imap_ment;
8859 
8860 		/*
8861 		 * We delete the ism map by copying
8862 		 * the next map over the current one.
8863 		 * We will take the next one in the maps
8864 		 * array or from the next ism_blk.
8865 		 */
8866 		while (ism_blkp != NULL) {
8867 			ism_map = ism_blkp->iblk_maps;
8868 			while (i < (ISM_MAP_SLOTS - 1)) {
8869 				ism_map[i] = ism_map[i + 1];
8870 				i++;
8871 			}
8872 			/* i == (ISM_MAP_SLOTS - 1) */
8873 			ism_blkp = ism_blkp->iblk_next;
8874 			if (ism_blkp != NULL) {
8875 				ism_map[i] = ism_blkp->iblk_maps[0];
8876 				i = 0;
8877 			} else {
8878 				ism_map[i].imap_seg = 0;
8879 				ism_map[i].imap_vb_shift = 0;
8880 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8881 				ism_map[i].imap_hatflags = 0;
8882 				ism_map[i].imap_sz_mask = 0;
8883 				ism_map[i].imap_ismhat = NULL;
8884 				ism_map[i].imap_ment = NULL;
8885 			}
8886 		}
8887 
8888 		/*
8889 		 * Now flush entire TSB for the process, since
8890 		 * demapping page by page can be too expensive.
8891 		 * We don't have to flush the TLB here anymore
8892 		 * since we switch to a new TLB ctx instead.
8893 		 * Also, there is no need to flush if the process
8894 		 * is exiting since the TSB will be freed later.
8895 		 */
8896 		if (!sfmmup->sfmmu_free) {
8897 			hatlockp = sfmmu_hat_enter(sfmmup);
8898 			for (tsbinfo = sfmmup->sfmmu_tsb; tsbinfo != NULL;
8899 			    tsbinfo = tsbinfo->tsb_next) {
8900 				if (tsbinfo->tsb_flags & TSB_SWAPPED)
8901 					continue;
8902 				if (tsbinfo->tsb_flags & TSB_RELOC_FLAG) {
8903 					tsbinfo->tsb_flags |=
8904 					    TSB_FLUSH_NEEDED;
8905 					continue;
8906 				}
8907 
8908 				sfmmu_inv_tsb(tsbinfo->tsb_va,
8909 				    TSB_BYTES(tsbinfo->tsb_szc));
8910 			}
8911 			sfmmu_hat_exit(hatlockp);
8912 		}
8913 	}
8914 
8915 	/*
8916 	 * Update our counters for this sfmmup's ism mappings.
8917 	 */
8918 	for (i = 0; i <= ismszc; i++) {
8919 		if (!(disable_ism_large_pages & (1 << i)))
8920 			(void) ism_tsb_entries(sfmmup, i);
8921 	}
8922 
8923 	sfmmu_ismhat_exit(sfmmup, 0);
8924 
8925 	/*
8926 	 * We must do our freeing here after dropping locks
8927 	 * to prevent a deadlock in the kmem allocator on the
8928 	 * mapping list lock.
8929 	 */
8930 	if (free_ment != NULL)
8931 		kmem_cache_free(ism_ment_cache, free_ment);
8932 
8933 	/*
8934 	 * Check TSB and TLB page sizes if the process isn't exiting.
8935 	 */
8936 	if (!sfmmup->sfmmu_free) {
8937 		if (found && old_scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
8938 			sfmmu_check_page_sizes(sfmmup, 1);
8939 		} else {
8940 			sfmmu_check_page_sizes(sfmmup, 0);
8941 		}
8942 	}
8943 }
8944 
8945 /* ARGSUSED */
8946 static int
8947 sfmmu_idcache_constructor(void *buf, void *cdrarg, int kmflags)
8948 {
8949 	/* void *buf is sfmmu_t pointer */
8950 	bzero(buf, sizeof (sfmmu_t));
8951 
8952 	return (0);
8953 }
8954 
8955 /* ARGSUSED */
8956 static void
8957 sfmmu_idcache_destructor(void *buf, void *cdrarg)
8958 {
8959 	/* void *buf is sfmmu_t pointer */
8960 }
8961 
8962 /*
8963  * setup kmem hmeblks by bzeroing all members and initializing the nextpa
8964  * field to be the pa of this hmeblk
8965  */
8966 /* ARGSUSED */
8967 static int
8968 sfmmu_hblkcache_constructor(void *buf, void *cdrarg, int kmflags)
8969 {
8970 	struct hme_blk *hmeblkp;
8971 
8972 	bzero(buf, (size_t)cdrarg);
8973 	hmeblkp = (struct hme_blk *)buf;
8974 	hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
8975 
8976 #ifdef	HBLK_TRACE
8977 	mutex_init(&hmeblkp->hblk_audit_lock, NULL, MUTEX_DEFAULT, NULL);
8978 #endif	/* HBLK_TRACE */
8979 
8980 	return (0);
8981 }
8982 
8983 /* ARGSUSED */
8984 static void
8985 sfmmu_hblkcache_destructor(void *buf, void *cdrarg)
8986 {
8987 
8988 #ifdef	HBLK_TRACE
8989 
8990 	struct hme_blk *hmeblkp;
8991 
8992 	hmeblkp = (struct hme_blk *)buf;
8993 	mutex_destroy(&hmeblkp->hblk_audit_lock);
8994 
8995 #endif	/* HBLK_TRACE */
8996 }
8997 
8998 #define	SFMMU_CACHE_RECLAIM_SCAN_RATIO 8
8999 static int sfmmu_cache_reclaim_scan_ratio = SFMMU_CACHE_RECLAIM_SCAN_RATIO;
9000 /*
9001  * The kmem allocator will callback into our reclaim routine when the system
9002  * is running low in memory.  We traverse the hash and free up all unused but
9003  * still cached hme_blks.  We also traverse the free list and free them up
9004  * as well.
9005  */
9006 /*ARGSUSED*/
9007 static void
9008 sfmmu_hblkcache_reclaim(void *cdrarg)
9009 {
9010 	int i;
9011 	struct hmehash_bucket *hmebp;
9012 	struct hme_blk *hmeblkp, *nx_hblk, *pr_hblk = NULL;
9013 	static struct hmehash_bucket *uhmehash_reclaim_hand;
9014 	static struct hmehash_bucket *khmehash_reclaim_hand;
9015 	struct hme_blk *list = NULL, *last_hmeblkp;
9016 	cpuset_t cpuset = cpu_ready_set;
9017 	cpu_hme_pend_t *cpuhp;
9018 
9019 	/* Free up hmeblks on the cpu pending lists */
9020 	for (i = 0; i < NCPU; i++) {
9021 		cpuhp = &cpu_hme_pend[i];
9022 		if (cpuhp->chp_listp != NULL)  {
9023 			mutex_enter(&cpuhp->chp_mutex);
9024 			if (cpuhp->chp_listp == NULL) {
9025 				mutex_exit(&cpuhp->chp_mutex);
9026 				continue;
9027 			}
9028 			for (last_hmeblkp = cpuhp->chp_listp;
9029 			    last_hmeblkp->hblk_next != NULL;
9030 			    last_hmeblkp = last_hmeblkp->hblk_next)
9031 				;
9032 			last_hmeblkp->hblk_next = list;
9033 			list = cpuhp->chp_listp;
9034 			cpuhp->chp_listp = NULL;
9035 			cpuhp->chp_count = 0;
9036 			mutex_exit(&cpuhp->chp_mutex);
9037 		}
9038 
9039 	}
9040 
9041 	if (list != NULL) {
9042 		kpreempt_disable();
9043 		CPUSET_DEL(cpuset, CPU->cpu_id);
9044 		xt_sync(cpuset);
9045 		xt_sync(cpuset);
9046 		kpreempt_enable();
9047 		sfmmu_hblk_free(&list);
9048 		list = NULL;
9049 	}
9050 
9051 	hmebp = uhmehash_reclaim_hand;
9052 	if (hmebp == NULL || hmebp > &uhme_hash[UHMEHASH_SZ])
9053 		uhmehash_reclaim_hand = hmebp = uhme_hash;
9054 	uhmehash_reclaim_hand += UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9055 
9056 	for (i = UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9057 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9058 			hmeblkp = hmebp->hmeblkp;
9059 			pr_hblk = NULL;
9060 			while (hmeblkp) {
9061 				nx_hblk = hmeblkp->hblk_next;
9062 				if (!hmeblkp->hblk_vcnt &&
9063 				    !hmeblkp->hblk_hmecnt) {
9064 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9065 					    pr_hblk, &list, 0);
9066 				} else {
9067 					pr_hblk = hmeblkp;
9068 				}
9069 				hmeblkp = nx_hblk;
9070 			}
9071 			SFMMU_HASH_UNLOCK(hmebp);
9072 		}
9073 		if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
9074 			hmebp = uhme_hash;
9075 	}
9076 
9077 	hmebp = khmehash_reclaim_hand;
9078 	if (hmebp == NULL || hmebp > &khme_hash[KHMEHASH_SZ])
9079 		khmehash_reclaim_hand = hmebp = khme_hash;
9080 	khmehash_reclaim_hand += KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9081 
9082 	for (i = KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9083 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9084 			hmeblkp = hmebp->hmeblkp;
9085 			pr_hblk = NULL;
9086 			while (hmeblkp) {
9087 				nx_hblk = hmeblkp->hblk_next;
9088 				if (!hmeblkp->hblk_vcnt &&
9089 				    !hmeblkp->hblk_hmecnt) {
9090 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9091 					    pr_hblk, &list, 0);
9092 				} else {
9093 					pr_hblk = hmeblkp;
9094 				}
9095 				hmeblkp = nx_hblk;
9096 			}
9097 			SFMMU_HASH_UNLOCK(hmebp);
9098 		}
9099 		if (hmebp++ == &khme_hash[KHMEHASH_SZ])
9100 			hmebp = khme_hash;
9101 	}
9102 	sfmmu_hblks_list_purge(&list, 0);
9103 }
9104 
9105 /*
9106  * sfmmu_get_ppvcolor should become a vm_machdep or hatop interface.
9107  * same goes for sfmmu_get_addrvcolor().
9108  *
9109  * This function will return the virtual color for the specified page. The
9110  * virtual color corresponds to this page current mapping or its last mapping.
9111  * It is used by memory allocators to choose addresses with the correct
9112  * alignment so vac consistency is automatically maintained.  If the page
9113  * has no color it returns -1.
9114  */
9115 /*ARGSUSED*/
9116 int
9117 sfmmu_get_ppvcolor(struct page *pp)
9118 {
9119 #ifdef VAC
9120 	int color;
9121 
9122 	if (!(cache & CACHE_VAC) || PP_NEWPAGE(pp)) {
9123 		return (-1);
9124 	}
9125 	color = PP_GET_VCOLOR(pp);
9126 	ASSERT(color < mmu_btop(shm_alignment));
9127 	return (color);
9128 #else
9129 	return (-1);
9130 #endif	/* VAC */
9131 }
9132 
9133 /*
9134  * This function will return the desired alignment for vac consistency
9135  * (vac color) given a virtual address.  If no vac is present it returns -1.
9136  */
9137 /*ARGSUSED*/
9138 int
9139 sfmmu_get_addrvcolor(caddr_t vaddr)
9140 {
9141 #ifdef VAC
9142 	if (cache & CACHE_VAC) {
9143 		return (addr_to_vcolor(vaddr));
9144 	} else {
9145 		return (-1);
9146 	}
9147 #else
9148 	return (-1);
9149 #endif	/* VAC */
9150 }
9151 
9152 #ifdef VAC
9153 /*
9154  * Check for conflicts.
9155  * A conflict exists if the new and existent mappings do not match in
9156  * their "shm_alignment fields. If conflicts exist, the existant mappings
9157  * are flushed unless one of them is locked. If one of them is locked, then
9158  * the mappings are flushed and converted to non-cacheable mappings.
9159  */
9160 static void
9161 sfmmu_vac_conflict(struct hat *hat, caddr_t addr, page_t *pp)
9162 {
9163 	struct hat *tmphat;
9164 	struct sf_hment *sfhmep, *tmphme = NULL;
9165 	struct hme_blk *hmeblkp;
9166 	int vcolor;
9167 	tte_t tte;
9168 
9169 	ASSERT(sfmmu_mlist_held(pp));
9170 	ASSERT(!PP_ISNC(pp));		/* page better be cacheable */
9171 
9172 	vcolor = addr_to_vcolor(addr);
9173 	if (PP_NEWPAGE(pp)) {
9174 		PP_SET_VCOLOR(pp, vcolor);
9175 		return;
9176 	}
9177 
9178 	if (PP_GET_VCOLOR(pp) == vcolor) {
9179 		return;
9180 	}
9181 
9182 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
9183 		/*
9184 		 * Previous user of page had a different color
9185 		 * but since there are no current users
9186 		 * we just flush the cache and change the color.
9187 		 */
9188 		SFMMU_STAT(sf_pgcolor_conflict);
9189 		sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9190 		PP_SET_VCOLOR(pp, vcolor);
9191 		return;
9192 	}
9193 
9194 	/*
9195 	 * If we get here we have a vac conflict with a current
9196 	 * mapping.  VAC conflict policy is as follows.
9197 	 * - The default is to unload the other mappings unless:
9198 	 * - If we have a large mapping we uncache the page.
9199 	 * We need to uncache the rest of the large page too.
9200 	 * - If any of the mappings are locked we uncache the page.
9201 	 * - If the requested mapping is inconsistent
9202 	 * with another mapping and that mapping
9203 	 * is in the same address space we have to
9204 	 * make it non-cached.  The default thing
9205 	 * to do is unload the inconsistent mapping
9206 	 * but if they are in the same address space
9207 	 * we run the risk of unmapping the pc or the
9208 	 * stack which we will use as we return to the user,
9209 	 * in which case we can then fault on the thing
9210 	 * we just unloaded and get into an infinite loop.
9211 	 */
9212 	if (PP_ISMAPPED_LARGE(pp)) {
9213 		int sz;
9214 
9215 		/*
9216 		 * Existing mapping is for big pages. We don't unload
9217 		 * existing big mappings to satisfy new mappings.
9218 		 * Always convert all mappings to TNC.
9219 		 */
9220 		sz = fnd_mapping_sz(pp);
9221 		pp = PP_GROUPLEADER(pp, sz);
9222 		SFMMU_STAT_ADD(sf_uncache_conflict, TTEPAGES(sz));
9223 		sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH,
9224 		    TTEPAGES(sz));
9225 
9226 		return;
9227 	}
9228 
9229 	/*
9230 	 * check if any mapping is in same as or if it is locked
9231 	 * since in that case we need to uncache.
9232 	 */
9233 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9234 		tmphme = sfhmep->hme_next;
9235 		if (IS_PAHME(sfhmep))
9236 			continue;
9237 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9238 		if (hmeblkp->hblk_xhat_bit)
9239 			continue;
9240 		tmphat = hblktosfmmu(hmeblkp);
9241 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
9242 		ASSERT(TTE_IS_VALID(&tte));
9243 		if (hmeblkp->hblk_shared || tmphat == hat ||
9244 		    hmeblkp->hblk_lckcnt) {
9245 			/*
9246 			 * We have an uncache conflict
9247 			 */
9248 			SFMMU_STAT(sf_uncache_conflict);
9249 			sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH, 1);
9250 			return;
9251 		}
9252 	}
9253 
9254 	/*
9255 	 * We have an unload conflict
9256 	 * We have already checked for LARGE mappings, therefore
9257 	 * the remaining mapping(s) must be TTE8K.
9258 	 */
9259 	SFMMU_STAT(sf_unload_conflict);
9260 
9261 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9262 		tmphme = sfhmep->hme_next;
9263 		if (IS_PAHME(sfhmep))
9264 			continue;
9265 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9266 		if (hmeblkp->hblk_xhat_bit)
9267 			continue;
9268 		ASSERT(!hmeblkp->hblk_shared);
9269 		(void) sfmmu_pageunload(pp, sfhmep, TTE8K);
9270 	}
9271 
9272 	if (PP_ISMAPPED_KPM(pp))
9273 		sfmmu_kpm_vac_unload(pp, addr);
9274 
9275 	/*
9276 	 * Unloads only do TLB flushes so we need to flush the
9277 	 * cache here.
9278 	 */
9279 	sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9280 	PP_SET_VCOLOR(pp, vcolor);
9281 }
9282 
9283 /*
9284  * Whenever a mapping is unloaded and the page is in TNC state,
9285  * we see if the page can be made cacheable again. 'pp' is
9286  * the page that we just unloaded a mapping from, the size
9287  * of mapping that was unloaded is 'ottesz'.
9288  * Remark:
9289  * The recache policy for mpss pages can leave a performance problem
9290  * under the following circumstances:
9291  * . A large page in uncached mode has just been unmapped.
9292  * . All constituent pages are TNC due to a conflicting small mapping.
9293  * . There are many other, non conflicting, small mappings around for
9294  *   a lot of the constituent pages.
9295  * . We're called w/ the "old" groupleader page and the old ottesz,
9296  *   but this is irrelevant, since we're no more "PP_ISMAPPED_LARGE", so
9297  *   we end up w/ TTE8K or npages == 1.
9298  * . We call tst_tnc w/ the old groupleader only, and if there is no
9299  *   conflict, we re-cache only this page.
9300  * . All other small mappings are not checked and will be left in TNC mode.
9301  * The problem is not very serious because:
9302  * . mpss is actually only defined for heap and stack, so the probability
9303  *   is not very high that a large page mapping exists in parallel to a small
9304  *   one (this is possible, but seems to be bad programming style in the
9305  *   appl).
9306  * . The problem gets a little bit more serious, when those TNC pages
9307  *   have to be mapped into kernel space, e.g. for networking.
9308  * . When VAC alias conflicts occur in applications, this is regarded
9309  *   as an application bug. So if kstat's show them, the appl should
9310  *   be changed anyway.
9311  */
9312 void
9313 conv_tnc(page_t *pp, int ottesz)
9314 {
9315 	int cursz, dosz;
9316 	pgcnt_t curnpgs, dopgs;
9317 	pgcnt_t pg64k;
9318 	page_t *pp2;
9319 
9320 	/*
9321 	 * Determine how big a range we check for TNC and find
9322 	 * leader page. cursz is the size of the biggest
9323 	 * mapping that still exist on 'pp'.
9324 	 */
9325 	if (PP_ISMAPPED_LARGE(pp)) {
9326 		cursz = fnd_mapping_sz(pp);
9327 	} else {
9328 		cursz = TTE8K;
9329 	}
9330 
9331 	if (ottesz >= cursz) {
9332 		dosz = ottesz;
9333 		pp2 = pp;
9334 	} else {
9335 		dosz = cursz;
9336 		pp2 = PP_GROUPLEADER(pp, dosz);
9337 	}
9338 
9339 	pg64k = TTEPAGES(TTE64K);
9340 	dopgs = TTEPAGES(dosz);
9341 
9342 	ASSERT(dopgs == 1 || ((dopgs & (pg64k - 1)) == 0));
9343 
9344 	while (dopgs != 0) {
9345 		curnpgs = TTEPAGES(cursz);
9346 		if (tst_tnc(pp2, curnpgs)) {
9347 			SFMMU_STAT_ADD(sf_recache, curnpgs);
9348 			sfmmu_page_cache_array(pp2, HAT_CACHE, CACHE_NO_FLUSH,
9349 			    curnpgs);
9350 		}
9351 
9352 		ASSERT(dopgs >= curnpgs);
9353 		dopgs -= curnpgs;
9354 
9355 		if (dopgs == 0) {
9356 			break;
9357 		}
9358 
9359 		pp2 = PP_PAGENEXT_N(pp2, curnpgs);
9360 		if (((dopgs & (pg64k - 1)) == 0) && PP_ISMAPPED_LARGE(pp2)) {
9361 			cursz = fnd_mapping_sz(pp2);
9362 		} else {
9363 			cursz = TTE8K;
9364 		}
9365 	}
9366 }
9367 
9368 /*
9369  * Returns 1 if page(s) can be converted from TNC to cacheable setting,
9370  * returns 0 otherwise. Note that oaddr argument is valid for only
9371  * 8k pages.
9372  */
9373 int
9374 tst_tnc(page_t *pp, pgcnt_t npages)
9375 {
9376 	struct	sf_hment *sfhme;
9377 	struct	hme_blk *hmeblkp;
9378 	tte_t	tte;
9379 	caddr_t	vaddr;
9380 	int	clr_valid = 0;
9381 	int 	color, color1, bcolor;
9382 	int	i, ncolors;
9383 
9384 	ASSERT(pp != NULL);
9385 	ASSERT(!(cache & CACHE_WRITEBACK));
9386 
9387 	if (npages > 1) {
9388 		ncolors = CACHE_NUM_COLOR;
9389 	}
9390 
9391 	for (i = 0; i < npages; i++) {
9392 		ASSERT(sfmmu_mlist_held(pp));
9393 		ASSERT(PP_ISTNC(pp));
9394 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
9395 
9396 		if (PP_ISPNC(pp)) {
9397 			return (0);
9398 		}
9399 
9400 		clr_valid = 0;
9401 		if (PP_ISMAPPED_KPM(pp)) {
9402 			caddr_t kpmvaddr;
9403 
9404 			ASSERT(kpm_enable);
9405 			kpmvaddr = hat_kpm_page2va(pp, 1);
9406 			ASSERT(!(npages > 1 && IS_KPM_ALIAS_RANGE(kpmvaddr)));
9407 			color1 = addr_to_vcolor(kpmvaddr);
9408 			clr_valid = 1;
9409 		}
9410 
9411 		for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9412 			if (IS_PAHME(sfhme))
9413 				continue;
9414 			hmeblkp = sfmmu_hmetohblk(sfhme);
9415 			if (hmeblkp->hblk_xhat_bit)
9416 				continue;
9417 
9418 			sfmmu_copytte(&sfhme->hme_tte, &tte);
9419 			ASSERT(TTE_IS_VALID(&tte));
9420 
9421 			vaddr = tte_to_vaddr(hmeblkp, tte);
9422 			color = addr_to_vcolor(vaddr);
9423 
9424 			if (npages > 1) {
9425 				/*
9426 				 * If there is a big mapping, make sure
9427 				 * 8K mapping is consistent with the big
9428 				 * mapping.
9429 				 */
9430 				bcolor = i % ncolors;
9431 				if (color != bcolor) {
9432 					return (0);
9433 				}
9434 			}
9435 			if (!clr_valid) {
9436 				clr_valid = 1;
9437 				color1 = color;
9438 			}
9439 
9440 			if (color1 != color) {
9441 				return (0);
9442 			}
9443 		}
9444 
9445 		pp = PP_PAGENEXT(pp);
9446 	}
9447 
9448 	return (1);
9449 }
9450 
9451 void
9452 sfmmu_page_cache_array(page_t *pp, int flags, int cache_flush_flag,
9453 	pgcnt_t npages)
9454 {
9455 	kmutex_t *pmtx;
9456 	int i, ncolors, bcolor;
9457 	kpm_hlk_t *kpmp;
9458 	cpuset_t cpuset;
9459 
9460 	ASSERT(pp != NULL);
9461 	ASSERT(!(cache & CACHE_WRITEBACK));
9462 
9463 	kpmp = sfmmu_kpm_kpmp_enter(pp, npages);
9464 	pmtx = sfmmu_page_enter(pp);
9465 
9466 	/*
9467 	 * Fast path caching single unmapped page
9468 	 */
9469 	if (npages == 1 && !PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp) &&
9470 	    flags == HAT_CACHE) {
9471 		PP_CLRTNC(pp);
9472 		PP_CLRPNC(pp);
9473 		sfmmu_page_exit(pmtx);
9474 		sfmmu_kpm_kpmp_exit(kpmp);
9475 		return;
9476 	}
9477 
9478 	/*
9479 	 * We need to capture all cpus in order to change cacheability
9480 	 * because we can't allow one cpu to access the same physical
9481 	 * page using a cacheable and a non-cachebale mapping at the same
9482 	 * time. Since we may end up walking the ism mapping list
9483 	 * have to grab it's lock now since we can't after all the
9484 	 * cpus have been captured.
9485 	 */
9486 	sfmmu_hat_lock_all();
9487 	mutex_enter(&ism_mlist_lock);
9488 	kpreempt_disable();
9489 	cpuset = cpu_ready_set;
9490 	xc_attention(cpuset);
9491 
9492 	if (npages > 1) {
9493 		/*
9494 		 * Make sure all colors are flushed since the
9495 		 * sfmmu_page_cache() only flushes one color-
9496 		 * it does not know big pages.
9497 		 */
9498 		ncolors = CACHE_NUM_COLOR;
9499 		if (flags & HAT_TMPNC) {
9500 			for (i = 0; i < ncolors; i++) {
9501 				sfmmu_cache_flushcolor(i, pp->p_pagenum);
9502 			}
9503 			cache_flush_flag = CACHE_NO_FLUSH;
9504 		}
9505 	}
9506 
9507 	for (i = 0; i < npages; i++) {
9508 
9509 		ASSERT(sfmmu_mlist_held(pp));
9510 
9511 		if (!(flags == HAT_TMPNC && PP_ISTNC(pp))) {
9512 
9513 			if (npages > 1) {
9514 				bcolor = i % ncolors;
9515 			} else {
9516 				bcolor = NO_VCOLOR;
9517 			}
9518 
9519 			sfmmu_page_cache(pp, flags, cache_flush_flag,
9520 			    bcolor);
9521 		}
9522 
9523 		pp = PP_PAGENEXT(pp);
9524 	}
9525 
9526 	xt_sync(cpuset);
9527 	xc_dismissed(cpuset);
9528 	mutex_exit(&ism_mlist_lock);
9529 	sfmmu_hat_unlock_all();
9530 	sfmmu_page_exit(pmtx);
9531 	sfmmu_kpm_kpmp_exit(kpmp);
9532 	kpreempt_enable();
9533 }
9534 
9535 /*
9536  * This function changes the virtual cacheability of all mappings to a
9537  * particular page.  When changing from uncache to cacheable the mappings will
9538  * only be changed if all of them have the same virtual color.
9539  * We need to flush the cache in all cpus.  It is possible that
9540  * a process referenced a page as cacheable but has sinced exited
9541  * and cleared the mapping list.  We still to flush it but have no
9542  * state so all cpus is the only alternative.
9543  */
9544 static void
9545 sfmmu_page_cache(page_t *pp, int flags, int cache_flush_flag, int bcolor)
9546 {
9547 	struct	sf_hment *sfhme;
9548 	struct	hme_blk *hmeblkp;
9549 	sfmmu_t *sfmmup;
9550 	tte_t	tte, ttemod;
9551 	caddr_t	vaddr;
9552 	int	ret, color;
9553 	pfn_t	pfn;
9554 
9555 	color = bcolor;
9556 	pfn = pp->p_pagenum;
9557 
9558 	for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9559 
9560 		if (IS_PAHME(sfhme))
9561 			continue;
9562 		hmeblkp = sfmmu_hmetohblk(sfhme);
9563 
9564 		if (hmeblkp->hblk_xhat_bit)
9565 			continue;
9566 
9567 		sfmmu_copytte(&sfhme->hme_tte, &tte);
9568 		ASSERT(TTE_IS_VALID(&tte));
9569 		vaddr = tte_to_vaddr(hmeblkp, tte);
9570 		color = addr_to_vcolor(vaddr);
9571 
9572 #ifdef DEBUG
9573 		if ((flags & HAT_CACHE) && bcolor != NO_VCOLOR) {
9574 			ASSERT(color == bcolor);
9575 		}
9576 #endif
9577 
9578 		ASSERT(flags != HAT_TMPNC || color == PP_GET_VCOLOR(pp));
9579 
9580 		ttemod = tte;
9581 		if (flags & (HAT_UNCACHE | HAT_TMPNC)) {
9582 			TTE_CLR_VCACHEABLE(&ttemod);
9583 		} else {	/* flags & HAT_CACHE */
9584 			TTE_SET_VCACHEABLE(&ttemod);
9585 		}
9586 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
9587 		if (ret < 0) {
9588 			/*
9589 			 * Since all cpus are captured modifytte should not
9590 			 * fail.
9591 			 */
9592 			panic("sfmmu_page_cache: write to tte failed");
9593 		}
9594 
9595 		sfmmup = hblktosfmmu(hmeblkp);
9596 		if (cache_flush_flag == CACHE_FLUSH) {
9597 			/*
9598 			 * Flush TSBs, TLBs and caches
9599 			 */
9600 			if (hmeblkp->hblk_shared) {
9601 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9602 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9603 				sf_region_t *rgnp;
9604 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9605 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9606 				ASSERT(srdp != NULL);
9607 				rgnp = srdp->srd_hmergnp[rid];
9608 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9609 				    srdp, rgnp, rid);
9610 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9611 				    hmeblkp, 0);
9612 				sfmmu_cache_flush(pfn, addr_to_vcolor(vaddr));
9613 			} else if (sfmmup->sfmmu_ismhat) {
9614 				if (flags & HAT_CACHE) {
9615 					SFMMU_STAT(sf_ism_recache);
9616 				} else {
9617 					SFMMU_STAT(sf_ism_uncache);
9618 				}
9619 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9620 				    pfn, CACHE_FLUSH);
9621 			} else {
9622 				sfmmu_tlbcache_demap(vaddr, sfmmup, hmeblkp,
9623 				    pfn, 0, FLUSH_ALL_CPUS, CACHE_FLUSH, 1);
9624 			}
9625 
9626 			/*
9627 			 * all cache entries belonging to this pfn are
9628 			 * now flushed.
9629 			 */
9630 			cache_flush_flag = CACHE_NO_FLUSH;
9631 		} else {
9632 			/*
9633 			 * Flush only TSBs and TLBs.
9634 			 */
9635 			if (hmeblkp->hblk_shared) {
9636 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9637 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9638 				sf_region_t *rgnp;
9639 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9640 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9641 				ASSERT(srdp != NULL);
9642 				rgnp = srdp->srd_hmergnp[rid];
9643 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9644 				    srdp, rgnp, rid);
9645 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9646 				    hmeblkp, 0);
9647 			} else if (sfmmup->sfmmu_ismhat) {
9648 				if (flags & HAT_CACHE) {
9649 					SFMMU_STAT(sf_ism_recache);
9650 				} else {
9651 					SFMMU_STAT(sf_ism_uncache);
9652 				}
9653 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9654 				    pfn, CACHE_NO_FLUSH);
9655 			} else {
9656 				sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 1);
9657 			}
9658 		}
9659 	}
9660 
9661 	if (PP_ISMAPPED_KPM(pp))
9662 		sfmmu_kpm_page_cache(pp, flags, cache_flush_flag);
9663 
9664 	switch (flags) {
9665 
9666 		default:
9667 			panic("sfmmu_pagecache: unknown flags");
9668 			break;
9669 
9670 		case HAT_CACHE:
9671 			PP_CLRTNC(pp);
9672 			PP_CLRPNC(pp);
9673 			PP_SET_VCOLOR(pp, color);
9674 			break;
9675 
9676 		case HAT_TMPNC:
9677 			PP_SETTNC(pp);
9678 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9679 			break;
9680 
9681 		case HAT_UNCACHE:
9682 			PP_SETPNC(pp);
9683 			PP_CLRTNC(pp);
9684 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9685 			break;
9686 	}
9687 }
9688 #endif	/* VAC */
9689 
9690 
9691 /*
9692  * Wrapper routine used to return a context.
9693  *
9694  * It's the responsibility of the caller to guarantee that the
9695  * process serializes on calls here by taking the HAT lock for
9696  * the hat.
9697  *
9698  */
9699 static void
9700 sfmmu_get_ctx(sfmmu_t *sfmmup)
9701 {
9702 	mmu_ctx_t *mmu_ctxp;
9703 	uint_t pstate_save;
9704 	int ret;
9705 
9706 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9707 	ASSERT(sfmmup != ksfmmup);
9708 
9709 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID)) {
9710 		sfmmu_setup_tsbinfo(sfmmup);
9711 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ALLCTX_INVALID);
9712 	}
9713 
9714 	kpreempt_disable();
9715 
9716 	mmu_ctxp = CPU_MMU_CTXP(CPU);
9717 	ASSERT(mmu_ctxp);
9718 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
9719 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
9720 
9721 	/*
9722 	 * Do a wrap-around if cnum reaches the max # cnum supported by a MMU.
9723 	 */
9724 	if (mmu_ctxp->mmu_cnum == mmu_ctxp->mmu_nctxs)
9725 		sfmmu_ctx_wrap_around(mmu_ctxp);
9726 
9727 	/*
9728 	 * Let the MMU set up the page sizes to use for
9729 	 * this context in the TLB. Don't program 2nd dtlb for ism hat.
9730 	 */
9731 	if ((&mmu_set_ctx_page_sizes) && (sfmmup->sfmmu_ismhat == 0)) {
9732 		mmu_set_ctx_page_sizes(sfmmup);
9733 	}
9734 
9735 	/*
9736 	 * sfmmu_alloc_ctx and sfmmu_load_mmustate will be performed with
9737 	 * interrupts disabled to prevent race condition with wrap-around
9738 	 * ctx invalidatation. In sun4v, ctx invalidation also involves
9739 	 * a HV call to set the number of TSBs to 0. If interrupts are not
9740 	 * disabled until after sfmmu_load_mmustate is complete TSBs may
9741 	 * become assigned to INVALID_CONTEXT. This is not allowed.
9742 	 */
9743 	pstate_save = sfmmu_disable_intrs();
9744 
9745 	if (sfmmu_alloc_ctx(sfmmup, 1, CPU, SFMMU_PRIVATE) &&
9746 	    sfmmup->sfmmu_scdp != NULL) {
9747 		sf_scd_t *scdp = sfmmup->sfmmu_scdp;
9748 		sfmmu_t *scsfmmup = scdp->scd_sfmmup;
9749 		ret = sfmmu_alloc_ctx(scsfmmup, 1, CPU, SFMMU_SHARED);
9750 		/* debug purpose only */
9751 		ASSERT(!ret || scsfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
9752 		    != INVALID_CONTEXT);
9753 	}
9754 	sfmmu_load_mmustate(sfmmup);
9755 
9756 	sfmmu_enable_intrs(pstate_save);
9757 
9758 	kpreempt_enable();
9759 }
9760 
9761 /*
9762  * When all cnums are used up in a MMU, cnum will wrap around to the
9763  * next generation and start from 2.
9764  */
9765 static void
9766 sfmmu_ctx_wrap_around(mmu_ctx_t *mmu_ctxp)
9767 {
9768 
9769 	/* caller must have disabled the preemption */
9770 	ASSERT(curthread->t_preempt >= 1);
9771 	ASSERT(mmu_ctxp != NULL);
9772 
9773 	/* acquire Per-MMU (PM) spin lock */
9774 	mutex_enter(&mmu_ctxp->mmu_lock);
9775 
9776 	/* re-check to see if wrap-around is needed */
9777 	if (mmu_ctxp->mmu_cnum < mmu_ctxp->mmu_nctxs)
9778 		goto done;
9779 
9780 	SFMMU_MMU_STAT(mmu_wrap_around);
9781 
9782 	/* update gnum */
9783 	ASSERT(mmu_ctxp->mmu_gnum != 0);
9784 	mmu_ctxp->mmu_gnum++;
9785 	if (mmu_ctxp->mmu_gnum == 0 ||
9786 	    mmu_ctxp->mmu_gnum > MAX_SFMMU_GNUM_VAL) {
9787 		cmn_err(CE_PANIC, "mmu_gnum of mmu_ctx 0x%p is out of bound.",
9788 		    (void *)mmu_ctxp);
9789 	}
9790 
9791 	if (mmu_ctxp->mmu_ncpus > 1) {
9792 		cpuset_t cpuset;
9793 
9794 		membar_enter(); /* make sure updated gnum visible */
9795 
9796 		SFMMU_XCALL_STATS(NULL);
9797 
9798 		/* xcall to others on the same MMU to invalidate ctx */
9799 		cpuset = mmu_ctxp->mmu_cpuset;
9800 		ASSERT(CPU_IN_SET(cpuset, CPU->cpu_id));
9801 		CPUSET_DEL(cpuset, CPU->cpu_id);
9802 		CPUSET_AND(cpuset, cpu_ready_set);
9803 
9804 		/*
9805 		 * Pass in INVALID_CONTEXT as the first parameter to
9806 		 * sfmmu_raise_tsb_exception, which invalidates the context
9807 		 * of any process running on the CPUs in the MMU.
9808 		 */
9809 		xt_some(cpuset, sfmmu_raise_tsb_exception,
9810 		    INVALID_CONTEXT, INVALID_CONTEXT);
9811 		xt_sync(cpuset);
9812 
9813 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
9814 	}
9815 
9816 	if (sfmmu_getctx_sec() != INVALID_CONTEXT) {
9817 		sfmmu_setctx_sec(INVALID_CONTEXT);
9818 		sfmmu_clear_utsbinfo();
9819 	}
9820 
9821 	/*
9822 	 * No xcall is needed here. For sun4u systems all CPUs in context
9823 	 * domain share a single physical MMU therefore it's enough to flush
9824 	 * TLB on local CPU. On sun4v systems we use 1 global context
9825 	 * domain and flush all remote TLBs in sfmmu_raise_tsb_exception
9826 	 * handler. Note that vtag_flushall_uctxs() is called
9827 	 * for Ultra II machine, where the equivalent flushall functionality
9828 	 * is implemented in SW, and only user ctx TLB entries are flushed.
9829 	 */
9830 	if (&vtag_flushall_uctxs != NULL) {
9831 		vtag_flushall_uctxs();
9832 	} else {
9833 		vtag_flushall();
9834 	}
9835 
9836 	/* reset mmu cnum, skips cnum 0 and 1 */
9837 	mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
9838 
9839 done:
9840 	mutex_exit(&mmu_ctxp->mmu_lock);
9841 }
9842 
9843 
9844 /*
9845  * For multi-threaded process, set the process context to INVALID_CONTEXT
9846  * so that it faults and reloads the MMU state from TL=0. For single-threaded
9847  * process, we can just load the MMU state directly without having to
9848  * set context invalid. Caller must hold the hat lock since we don't
9849  * acquire it here.
9850  */
9851 static void
9852 sfmmu_sync_mmustate(sfmmu_t *sfmmup)
9853 {
9854 	uint_t cnum;
9855 	uint_t pstate_save;
9856 
9857 	ASSERT(sfmmup != ksfmmup);
9858 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9859 
9860 	kpreempt_disable();
9861 
9862 	/*
9863 	 * We check whether the pass'ed-in sfmmup is the same as the
9864 	 * current running proc. This is to makes sure the current proc
9865 	 * stays single-threaded if it already is.
9866 	 */
9867 	if ((sfmmup == curthread->t_procp->p_as->a_hat) &&
9868 	    (curthread->t_procp->p_lwpcnt == 1)) {
9869 		/* single-thread */
9870 		cnum = sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum;
9871 		if (cnum != INVALID_CONTEXT) {
9872 			uint_t curcnum;
9873 			/*
9874 			 * Disable interrupts to prevent race condition
9875 			 * with sfmmu_ctx_wrap_around ctx invalidation.
9876 			 * In sun4v, ctx invalidation involves setting
9877 			 * TSB to NULL, hence, interrupts should be disabled
9878 			 * untill after sfmmu_load_mmustate is completed.
9879 			 */
9880 			pstate_save = sfmmu_disable_intrs();
9881 			curcnum = sfmmu_getctx_sec();
9882 			if (curcnum == cnum)
9883 				sfmmu_load_mmustate(sfmmup);
9884 			sfmmu_enable_intrs(pstate_save);
9885 			ASSERT(curcnum == cnum || curcnum == INVALID_CONTEXT);
9886 		}
9887 	} else {
9888 		/*
9889 		 * multi-thread
9890 		 * or when sfmmup is not the same as the curproc.
9891 		 */
9892 		sfmmu_invalidate_ctx(sfmmup);
9893 	}
9894 
9895 	kpreempt_enable();
9896 }
9897 
9898 
9899 /*
9900  * Replace the specified TSB with a new TSB.  This function gets called when
9901  * we grow, shrink or swapin a TSB.  When swapping in a TSB (TSB_SWAPIN), the
9902  * TSB_FORCEALLOC flag may be used to force allocation of a minimum-sized TSB
9903  * (8K).
9904  *
9905  * Caller must hold the HAT lock, but should assume any tsb_info
9906  * pointers it has are no longer valid after calling this function.
9907  *
9908  * Return values:
9909  *	TSB_ALLOCFAIL	Failed to allocate a TSB, due to memory constraints
9910  *	TSB_LOSTRACE	HAT is busy, i.e. another thread is already doing
9911  *			something to this tsbinfo/TSB
9912  *	TSB_SUCCESS	Operation succeeded
9913  */
9914 static tsb_replace_rc_t
9915 sfmmu_replace_tsb(sfmmu_t *sfmmup, struct tsb_info *old_tsbinfo, uint_t szc,
9916     hatlock_t *hatlockp, uint_t flags)
9917 {
9918 	struct tsb_info *new_tsbinfo = NULL;
9919 	struct tsb_info *curtsb, *prevtsb;
9920 	uint_t tte_sz_mask;
9921 	int i;
9922 
9923 	ASSERT(sfmmup != ksfmmup);
9924 	ASSERT(sfmmup->sfmmu_ismhat == 0);
9925 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9926 	ASSERT(szc <= tsb_max_growsize);
9927 
9928 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_BUSY))
9929 		return (TSB_LOSTRACE);
9930 
9931 	/*
9932 	 * Find the tsb_info ahead of this one in the list, and
9933 	 * also make sure that the tsb_info passed in really
9934 	 * exists!
9935 	 */
9936 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9937 	    curtsb != old_tsbinfo && curtsb != NULL;
9938 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
9939 		;
9940 	ASSERT(curtsb != NULL);
9941 
9942 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9943 		/*
9944 		 * The process is swapped out, so just set the new size
9945 		 * code.  When it swaps back in, we'll allocate a new one
9946 		 * of the new chosen size.
9947 		 */
9948 		curtsb->tsb_szc = szc;
9949 		return (TSB_SUCCESS);
9950 	}
9951 	SFMMU_FLAGS_SET(sfmmup, HAT_BUSY);
9952 
9953 	tte_sz_mask = old_tsbinfo->tsb_ttesz_mask;
9954 
9955 	/*
9956 	 * All initialization is done inside of sfmmu_tsbinfo_alloc().
9957 	 * If we fail to allocate a TSB, exit.
9958 	 *
9959 	 * If tsb grows with new tsb size > 4M and old tsb size < 4M,
9960 	 * then try 4M slab after the initial alloc fails.
9961 	 *
9962 	 * If tsb swapin with tsb size > 4M, then try 4M after the
9963 	 * initial alloc fails.
9964 	 */
9965 	sfmmu_hat_exit(hatlockp);
9966 	if (sfmmu_tsbinfo_alloc(&new_tsbinfo, szc,
9967 	    tte_sz_mask, flags, sfmmup) &&
9968 	    (!(flags & (TSB_GROW | TSB_SWAPIN)) || (szc <= TSB_4M_SZCODE) ||
9969 	    (!(flags & TSB_SWAPIN) &&
9970 	    (old_tsbinfo->tsb_szc >= TSB_4M_SZCODE)) ||
9971 	    sfmmu_tsbinfo_alloc(&new_tsbinfo, TSB_4M_SZCODE,
9972 	    tte_sz_mask, flags, sfmmup))) {
9973 		(void) sfmmu_hat_enter(sfmmup);
9974 		if (!(flags & TSB_SWAPIN))
9975 			SFMMU_STAT(sf_tsb_resize_failures);
9976 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9977 		return (TSB_ALLOCFAIL);
9978 	}
9979 	(void) sfmmu_hat_enter(sfmmup);
9980 
9981 	/*
9982 	 * Re-check to make sure somebody else didn't muck with us while we
9983 	 * didn't hold the HAT lock.  If the process swapped out, fine, just
9984 	 * exit; this can happen if we try to shrink the TSB from the context
9985 	 * of another process (such as on an ISM unmap), though it is rare.
9986 	 */
9987 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9988 		SFMMU_STAT(sf_tsb_resize_failures);
9989 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9990 		sfmmu_hat_exit(hatlockp);
9991 		sfmmu_tsbinfo_free(new_tsbinfo);
9992 		(void) sfmmu_hat_enter(sfmmup);
9993 		return (TSB_LOSTRACE);
9994 	}
9995 
9996 #ifdef	DEBUG
9997 	/* Reverify that the tsb_info still exists.. for debugging only */
9998 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9999 	    curtsb != old_tsbinfo && curtsb != NULL;
10000 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
10001 		;
10002 	ASSERT(curtsb != NULL);
10003 #endif	/* DEBUG */
10004 
10005 	/*
10006 	 * Quiesce any CPUs running this process on their next TLB miss
10007 	 * so they atomically see the new tsb_info.  We temporarily set the
10008 	 * context to invalid context so new threads that come on processor
10009 	 * after we do the xcall to cpusran will also serialize behind the
10010 	 * HAT lock on TLB miss and will see the new TSB.  Since this short
10011 	 * race with a new thread coming on processor is relatively rare,
10012 	 * this synchronization mechanism should be cheaper than always
10013 	 * pausing all CPUs for the duration of the setup, which is what
10014 	 * the old implementation did.  This is particuarly true if we are
10015 	 * copying a huge chunk of memory around during that window.
10016 	 *
10017 	 * The memory barriers are to make sure things stay consistent
10018 	 * with resume() since it does not hold the HAT lock while
10019 	 * walking the list of tsb_info structures.
10020 	 */
10021 	if ((flags & TSB_SWAPIN) != TSB_SWAPIN) {
10022 		/* The TSB is either growing or shrinking. */
10023 		sfmmu_invalidate_ctx(sfmmup);
10024 	} else {
10025 		/*
10026 		 * It is illegal to swap in TSBs from a process other
10027 		 * than a process being swapped in.  This in turn
10028 		 * implies we do not have a valid MMU context here
10029 		 * since a process needs one to resolve translation
10030 		 * misses.
10031 		 */
10032 		ASSERT(curthread->t_procp->p_as->a_hat == sfmmup);
10033 	}
10034 
10035 #ifdef DEBUG
10036 	ASSERT(max_mmu_ctxdoms > 0);
10037 
10038 	/*
10039 	 * Process should have INVALID_CONTEXT on all MMUs
10040 	 */
10041 	for (i = 0; i < max_mmu_ctxdoms; i++) {
10042 
10043 		ASSERT(sfmmup->sfmmu_ctxs[i].cnum == INVALID_CONTEXT);
10044 	}
10045 #endif
10046 
10047 	new_tsbinfo->tsb_next = old_tsbinfo->tsb_next;
10048 	membar_stst();	/* strict ordering required */
10049 	if (prevtsb)
10050 		prevtsb->tsb_next = new_tsbinfo;
10051 	else
10052 		sfmmup->sfmmu_tsb = new_tsbinfo;
10053 	membar_enter();	/* make sure new TSB globally visible */
10054 
10055 	/*
10056 	 * We need to migrate TSB entries from the old TSB to the new TSB
10057 	 * if tsb_remap_ttes is set and the TSB is growing.
10058 	 */
10059 	if (tsb_remap_ttes && ((flags & TSB_GROW) == TSB_GROW))
10060 		sfmmu_copy_tsb(old_tsbinfo, new_tsbinfo);
10061 
10062 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
10063 
10064 	/*
10065 	 * Drop the HAT lock to free our old tsb_info.
10066 	 */
10067 	sfmmu_hat_exit(hatlockp);
10068 
10069 	if ((flags & TSB_GROW) == TSB_GROW) {
10070 		SFMMU_STAT(sf_tsb_grow);
10071 	} else if ((flags & TSB_SHRINK) == TSB_SHRINK) {
10072 		SFMMU_STAT(sf_tsb_shrink);
10073 	}
10074 
10075 	sfmmu_tsbinfo_free(old_tsbinfo);
10076 
10077 	(void) sfmmu_hat_enter(sfmmup);
10078 	return (TSB_SUCCESS);
10079 }
10080 
10081 /*
10082  * This function will re-program hat pgsz array, and invalidate the
10083  * process' context, forcing the process to switch to another
10084  * context on the next TLB miss, and therefore start using the
10085  * TLB that is reprogrammed for the new page sizes.
10086  */
10087 void
10088 sfmmu_reprog_pgsz_arr(sfmmu_t *sfmmup, uint8_t *tmp_pgsz)
10089 {
10090 	int i;
10091 	hatlock_t *hatlockp = NULL;
10092 
10093 	hatlockp = sfmmu_hat_enter(sfmmup);
10094 	/* USIII+-IV+ optimization, requires hat lock */
10095 	if (tmp_pgsz) {
10096 		for (i = 0; i < mmu_page_sizes; i++)
10097 			sfmmup->sfmmu_pgsz[i] = tmp_pgsz[i];
10098 	}
10099 	SFMMU_STAT(sf_tlb_reprog_pgsz);
10100 
10101 	sfmmu_invalidate_ctx(sfmmup);
10102 
10103 	sfmmu_hat_exit(hatlockp);
10104 }
10105 
10106 /*
10107  * The scd_rttecnt field in the SCD must be updated to take account of the
10108  * regions which it contains.
10109  */
10110 static void
10111 sfmmu_set_scd_rttecnt(sf_srd_t *srdp, sf_scd_t *scdp)
10112 {
10113 	uint_t rid;
10114 	uint_t i, j;
10115 	ulong_t w;
10116 	sf_region_t *rgnp;
10117 
10118 	ASSERT(srdp != NULL);
10119 
10120 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
10121 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
10122 			continue;
10123 		}
10124 
10125 		j = 0;
10126 		while (w) {
10127 			if (!(w & 0x1)) {
10128 				j++;
10129 				w >>= 1;
10130 				continue;
10131 			}
10132 			rid = (i << BT_ULSHIFT) | j;
10133 			j++;
10134 			w >>= 1;
10135 
10136 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
10137 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
10138 			rgnp = srdp->srd_hmergnp[rid];
10139 			ASSERT(rgnp->rgn_refcnt > 0);
10140 			ASSERT(rgnp->rgn_id == rid);
10141 
10142 			scdp->scd_rttecnt[rgnp->rgn_pgszc] +=
10143 			    rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
10144 
10145 			/*
10146 			 * Maintain the tsb0 inflation cnt for the regions
10147 			 * in the SCD.
10148 			 */
10149 			if (rgnp->rgn_pgszc >= TTE4M) {
10150 				scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt +=
10151 				    rgnp->rgn_size >>
10152 				    (TTE_PAGE_SHIFT(TTE8K) + 2);
10153 			}
10154 		}
10155 	}
10156 }
10157 
10158 /*
10159  * This function assumes that there are either four or six supported page
10160  * sizes and at most two programmable TLBs, so we need to decide which
10161  * page sizes are most important and then tell the MMU layer so it
10162  * can adjust the TLB page sizes accordingly (if supported).
10163  *
10164  * If these assumptions change, this function will need to be
10165  * updated to support whatever the new limits are.
10166  *
10167  * The growing flag is nonzero if we are growing the address space,
10168  * and zero if it is shrinking.  This allows us to decide whether
10169  * to grow or shrink our TSB, depending upon available memory
10170  * conditions.
10171  */
10172 static void
10173 sfmmu_check_page_sizes(sfmmu_t *sfmmup, int growing)
10174 {
10175 	uint64_t ttecnt[MMU_PAGE_SIZES];
10176 	uint64_t tte8k_cnt, tte4m_cnt;
10177 	uint8_t i;
10178 	int sectsb_thresh;
10179 
10180 	/*
10181 	 * Kernel threads, processes with small address spaces not using
10182 	 * large pages, and dummy ISM HATs need not apply.
10183 	 */
10184 	if (sfmmup == ksfmmup || sfmmup->sfmmu_ismhat != NULL)
10185 		return;
10186 
10187 	if (!SFMMU_LGPGS_INUSE(sfmmup) &&
10188 	    sfmmup->sfmmu_ttecnt[TTE8K] <= tsb_rss_factor)
10189 		return;
10190 
10191 	for (i = 0; i < mmu_page_sizes; i++) {
10192 		ttecnt[i] = sfmmup->sfmmu_ttecnt[i] +
10193 		    sfmmup->sfmmu_ismttecnt[i];
10194 	}
10195 
10196 	/* Check pagesizes in use, and possibly reprogram DTLB. */
10197 	if (&mmu_check_page_sizes)
10198 		mmu_check_page_sizes(sfmmup, ttecnt);
10199 
10200 	/*
10201 	 * Calculate the number of 8k ttes to represent the span of these
10202 	 * pages.
10203 	 */
10204 	tte8k_cnt = ttecnt[TTE8K] +
10205 	    (ttecnt[TTE64K] << (MMU_PAGESHIFT64K - MMU_PAGESHIFT)) +
10206 	    (ttecnt[TTE512K] << (MMU_PAGESHIFT512K - MMU_PAGESHIFT));
10207 	if (mmu_page_sizes == max_mmu_page_sizes) {
10208 		tte4m_cnt = ttecnt[TTE4M] +
10209 		    (ttecnt[TTE32M] << (MMU_PAGESHIFT32M - MMU_PAGESHIFT4M)) +
10210 		    (ttecnt[TTE256M] << (MMU_PAGESHIFT256M - MMU_PAGESHIFT4M));
10211 	} else {
10212 		tte4m_cnt = ttecnt[TTE4M];
10213 	}
10214 
10215 	/*
10216 	 * Inflate tte8k_cnt to allow for region large page allocation failure.
10217 	 */
10218 	tte8k_cnt += sfmmup->sfmmu_tsb0_4minflcnt;
10219 
10220 	/*
10221 	 * Inflate TSB sizes by a factor of 2 if this process
10222 	 * uses 4M text pages to minimize extra conflict misses
10223 	 * in the first TSB since without counting text pages
10224 	 * 8K TSB may become too small.
10225 	 *
10226 	 * Also double the size of the second TSB to minimize
10227 	 * extra conflict misses due to competition between 4M text pages
10228 	 * and data pages.
10229 	 *
10230 	 * We need to adjust the second TSB allocation threshold by the
10231 	 * inflation factor, since there is no point in creating a second
10232 	 * TSB when we know all the mappings can fit in the I/D TLBs.
10233 	 */
10234 	sectsb_thresh = tsb_sectsb_threshold;
10235 	if (sfmmup->sfmmu_flags & HAT_4MTEXT_FLAG) {
10236 		tte8k_cnt <<= 1;
10237 		tte4m_cnt <<= 1;
10238 		sectsb_thresh <<= 1;
10239 	}
10240 
10241 	/*
10242 	 * Check to see if our TSB is the right size; we may need to
10243 	 * grow or shrink it.  If the process is small, our work is
10244 	 * finished at this point.
10245 	 */
10246 	if (tte8k_cnt <= tsb_rss_factor && tte4m_cnt <= sectsb_thresh) {
10247 		return;
10248 	}
10249 	sfmmu_size_tsb(sfmmup, growing, tte8k_cnt, tte4m_cnt, sectsb_thresh);
10250 }
10251 
10252 static void
10253 sfmmu_size_tsb(sfmmu_t *sfmmup, int growing, uint64_t tte8k_cnt,
10254 	uint64_t tte4m_cnt, int sectsb_thresh)
10255 {
10256 	int tsb_bits;
10257 	uint_t tsb_szc;
10258 	struct tsb_info *tsbinfop;
10259 	hatlock_t *hatlockp = NULL;
10260 
10261 	hatlockp = sfmmu_hat_enter(sfmmup);
10262 	ASSERT(hatlockp != NULL);
10263 	tsbinfop = sfmmup->sfmmu_tsb;
10264 	ASSERT(tsbinfop != NULL);
10265 
10266 	/*
10267 	 * If we're growing, select the size based on RSS.  If we're
10268 	 * shrinking, leave some room so we don't have to turn around and
10269 	 * grow again immediately.
10270 	 */
10271 	if (growing)
10272 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
10273 	else
10274 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt << 1);
10275 
10276 	if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10277 	    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10278 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10279 		    hatlockp, TSB_SHRINK);
10280 	} else if (growing && tsb_szc > tsbinfop->tsb_szc && TSB_OK_GROW()) {
10281 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10282 		    hatlockp, TSB_GROW);
10283 	}
10284 	tsbinfop = sfmmup->sfmmu_tsb;
10285 
10286 	/*
10287 	 * With the TLB and first TSB out of the way, we need to see if
10288 	 * we need a second TSB for 4M pages.  If we managed to reprogram
10289 	 * the TLB page sizes above, the process will start using this new
10290 	 * TSB right away; otherwise, it will start using it on the next
10291 	 * context switch.  Either way, it's no big deal so there's no
10292 	 * synchronization with the trap handlers here unless we grow the
10293 	 * TSB (in which case it's required to prevent using the old one
10294 	 * after it's freed). Note: second tsb is required for 32M/256M
10295 	 * page sizes.
10296 	 */
10297 	if (tte4m_cnt > sectsb_thresh) {
10298 		/*
10299 		 * If we're growing, select the size based on RSS.  If we're
10300 		 * shrinking, leave some room so we don't have to turn
10301 		 * around and grow again immediately.
10302 		 */
10303 		if (growing)
10304 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
10305 		else
10306 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt << 1);
10307 		if (tsbinfop->tsb_next == NULL) {
10308 			struct tsb_info *newtsb;
10309 			int allocflags = SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)?
10310 			    0 : TSB_ALLOC;
10311 
10312 			sfmmu_hat_exit(hatlockp);
10313 
10314 			/*
10315 			 * Try to allocate a TSB for 4[32|256]M pages.  If we
10316 			 * can't get the size we want, retry w/a minimum sized
10317 			 * TSB.  If that still didn't work, give up; we can
10318 			 * still run without one.
10319 			 */
10320 			tsb_bits = (mmu_page_sizes == max_mmu_page_sizes)?
10321 			    TSB4M|TSB32M|TSB256M:TSB4M;
10322 			if ((sfmmu_tsbinfo_alloc(&newtsb, tsb_szc, tsb_bits,
10323 			    allocflags, sfmmup)) &&
10324 			    (tsb_szc <= TSB_4M_SZCODE ||
10325 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
10326 			    tsb_bits, allocflags, sfmmup)) &&
10327 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_MIN_SZCODE,
10328 			    tsb_bits, allocflags, sfmmup)) {
10329 				return;
10330 			}
10331 
10332 			hatlockp = sfmmu_hat_enter(sfmmup);
10333 
10334 			sfmmu_invalidate_ctx(sfmmup);
10335 
10336 			if (sfmmup->sfmmu_tsb->tsb_next == NULL) {
10337 				sfmmup->sfmmu_tsb->tsb_next = newtsb;
10338 				SFMMU_STAT(sf_tsb_sectsb_create);
10339 				sfmmu_hat_exit(hatlockp);
10340 				return;
10341 			} else {
10342 				/*
10343 				 * It's annoying, but possible for us
10344 				 * to get here.. we dropped the HAT lock
10345 				 * because of locking order in the kmem
10346 				 * allocator, and while we were off getting
10347 				 * our memory, some other thread decided to
10348 				 * do us a favor and won the race to get a
10349 				 * second TSB for this process.  Sigh.
10350 				 */
10351 				sfmmu_hat_exit(hatlockp);
10352 				sfmmu_tsbinfo_free(newtsb);
10353 				return;
10354 			}
10355 		}
10356 
10357 		/*
10358 		 * We have a second TSB, see if it's big enough.
10359 		 */
10360 		tsbinfop = tsbinfop->tsb_next;
10361 
10362 		/*
10363 		 * Check to see if our second TSB is the right size;
10364 		 * we may need to grow or shrink it.
10365 		 * To prevent thrashing (e.g. growing the TSB on a
10366 		 * subsequent map operation), only try to shrink if
10367 		 * the TSB reach exceeds twice the virtual address
10368 		 * space size.
10369 		 */
10370 		if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10371 		    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10372 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10373 			    tsb_szc, hatlockp, TSB_SHRINK);
10374 		} else if (growing && tsb_szc > tsbinfop->tsb_szc &&
10375 		    TSB_OK_GROW()) {
10376 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10377 			    tsb_szc, hatlockp, TSB_GROW);
10378 		}
10379 	}
10380 
10381 	sfmmu_hat_exit(hatlockp);
10382 }
10383 
10384 /*
10385  * Free up a sfmmu
10386  * Since the sfmmu is currently embedded in the hat struct we simply zero
10387  * out our fields and free up the ism map blk list if any.
10388  */
10389 static void
10390 sfmmu_free_sfmmu(sfmmu_t *sfmmup)
10391 {
10392 	ism_blk_t	*blkp, *nx_blkp;
10393 #ifdef	DEBUG
10394 	ism_map_t	*map;
10395 	int 		i;
10396 #endif
10397 
10398 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
10399 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
10400 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
10401 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
10402 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
10403 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
10404 	ASSERT(SF_RGNMAP_ISNULL(sfmmup));
10405 
10406 	sfmmup->sfmmu_free = 0;
10407 	sfmmup->sfmmu_ismhat = 0;
10408 
10409 	blkp = sfmmup->sfmmu_iblk;
10410 	sfmmup->sfmmu_iblk = NULL;
10411 
10412 	while (blkp) {
10413 #ifdef	DEBUG
10414 		map = blkp->iblk_maps;
10415 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
10416 			ASSERT(map[i].imap_seg == 0);
10417 			ASSERT(map[i].imap_ismhat == NULL);
10418 			ASSERT(map[i].imap_ment == NULL);
10419 		}
10420 #endif
10421 		nx_blkp = blkp->iblk_next;
10422 		blkp->iblk_next = NULL;
10423 		blkp->iblk_nextpa = (uint64_t)-1;
10424 		kmem_cache_free(ism_blk_cache, blkp);
10425 		blkp = nx_blkp;
10426 	}
10427 }
10428 
10429 /*
10430  * Locking primitves accessed by HATLOCK macros
10431  */
10432 
10433 #define	SFMMU_SPL_MTX	(0x0)
10434 #define	SFMMU_ML_MTX	(0x1)
10435 
10436 #define	SFMMU_MLSPL_MTX(type, pg)	(((type) == SFMMU_SPL_MTX) ? \
10437 					    SPL_HASH(pg) : MLIST_HASH(pg))
10438 
10439 kmutex_t *
10440 sfmmu_page_enter(struct page *pp)
10441 {
10442 	return (sfmmu_mlspl_enter(pp, SFMMU_SPL_MTX));
10443 }
10444 
10445 void
10446 sfmmu_page_exit(kmutex_t *spl)
10447 {
10448 	mutex_exit(spl);
10449 }
10450 
10451 int
10452 sfmmu_page_spl_held(struct page *pp)
10453 {
10454 	return (sfmmu_mlspl_held(pp, SFMMU_SPL_MTX));
10455 }
10456 
10457 kmutex_t *
10458 sfmmu_mlist_enter(struct page *pp)
10459 {
10460 	return (sfmmu_mlspl_enter(pp, SFMMU_ML_MTX));
10461 }
10462 
10463 void
10464 sfmmu_mlist_exit(kmutex_t *mml)
10465 {
10466 	mutex_exit(mml);
10467 }
10468 
10469 int
10470 sfmmu_mlist_held(struct page *pp)
10471 {
10472 
10473 	return (sfmmu_mlspl_held(pp, SFMMU_ML_MTX));
10474 }
10475 
10476 /*
10477  * Common code for sfmmu_mlist_enter() and sfmmu_page_enter().  For
10478  * sfmmu_mlist_enter() case mml_table lock array is used and for
10479  * sfmmu_page_enter() sfmmu_page_lock lock array is used.
10480  *
10481  * The lock is taken on a root page so that it protects an operation on all
10482  * constituent pages of a large page pp belongs to.
10483  *
10484  * The routine takes a lock from the appropriate array. The lock is determined
10485  * by hashing the root page. After taking the lock this routine checks if the
10486  * root page has the same size code that was used to determine the root (i.e
10487  * that root hasn't changed).  If root page has the expected p_szc field we
10488  * have the right lock and it's returned to the caller. If root's p_szc
10489  * decreased we release the lock and retry from the beginning.  This case can
10490  * happen due to hat_page_demote() decreasing p_szc between our load of p_szc
10491  * value and taking the lock. The number of retries due to p_szc decrease is
10492  * limited by the maximum p_szc value. If p_szc is 0 we return the lock
10493  * determined by hashing pp itself.
10494  *
10495  * If our caller doesn't hold a SE_SHARED or SE_EXCL lock on pp it's also
10496  * possible that p_szc can increase. To increase p_szc a thread has to lock
10497  * all constituent pages EXCL and do hat_pageunload() on all of them. All the
10498  * callers that don't hold a page locked recheck if hmeblk through which pp
10499  * was found still maps this pp.  If it doesn't map it anymore returned lock
10500  * is immediately dropped. Therefore if sfmmu_mlspl_enter() hits the case of
10501  * p_szc increase after taking the lock it returns this lock without further
10502  * retries because in this case the caller doesn't care about which lock was
10503  * taken. The caller will drop it right away.
10504  *
10505  * After the routine returns it's guaranteed that hat_page_demote() can't
10506  * change p_szc field of any of constituent pages of a large page pp belongs
10507  * to as long as pp was either locked at least SHARED prior to this call or
10508  * the caller finds that hment that pointed to this pp still references this
10509  * pp (this also assumes that the caller holds hme hash bucket lock so that
10510  * the same pp can't be remapped into the same hmeblk after it was unmapped by
10511  * hat_pageunload()).
10512  */
10513 static kmutex_t *
10514 sfmmu_mlspl_enter(struct page *pp, int type)
10515 {
10516 	kmutex_t	*mtx;
10517 	uint_t		prev_rszc = UINT_MAX;
10518 	page_t		*rootpp;
10519 	uint_t		szc;
10520 	uint_t		rszc;
10521 	uint_t		pszc = pp->p_szc;
10522 
10523 	ASSERT(pp != NULL);
10524 
10525 again:
10526 	if (pszc == 0) {
10527 		mtx = SFMMU_MLSPL_MTX(type, pp);
10528 		mutex_enter(mtx);
10529 		return (mtx);
10530 	}
10531 
10532 	/* The lock lives in the root page */
10533 	rootpp = PP_GROUPLEADER(pp, pszc);
10534 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10535 	mutex_enter(mtx);
10536 
10537 	/*
10538 	 * Return mml in the following 3 cases:
10539 	 *
10540 	 * 1) If pp itself is root since if its p_szc decreased before we took
10541 	 * the lock pp is still the root of smaller szc page. And if its p_szc
10542 	 * increased it doesn't matter what lock we return (see comment in
10543 	 * front of this routine).
10544 	 *
10545 	 * 2) If pp's not root but rootpp is the root of a rootpp->p_szc size
10546 	 * large page we have the right lock since any previous potential
10547 	 * hat_page_demote() is done demoting from greater than current root's
10548 	 * p_szc because hat_page_demote() changes root's p_szc last. No
10549 	 * further hat_page_demote() can start or be in progress since it
10550 	 * would need the same lock we currently hold.
10551 	 *
10552 	 * 3) If rootpp's p_szc increased since previous iteration it doesn't
10553 	 * matter what lock we return (see comment in front of this routine).
10554 	 */
10555 	if (pp == rootpp || (rszc = rootpp->p_szc) == pszc ||
10556 	    rszc >= prev_rszc) {
10557 		return (mtx);
10558 	}
10559 
10560 	/*
10561 	 * hat_page_demote() could have decreased root's p_szc.
10562 	 * In this case pp's p_szc must also be smaller than pszc.
10563 	 * Retry.
10564 	 */
10565 	if (rszc < pszc) {
10566 		szc = pp->p_szc;
10567 		if (szc < pszc) {
10568 			mutex_exit(mtx);
10569 			pszc = szc;
10570 			goto again;
10571 		}
10572 		/*
10573 		 * pp's p_szc increased after it was decreased.
10574 		 * page cannot be mapped. Return current lock. The caller
10575 		 * will drop it right away.
10576 		 */
10577 		return (mtx);
10578 	}
10579 
10580 	/*
10581 	 * root's p_szc is greater than pp's p_szc.
10582 	 * hat_page_demote() is not done with all pages
10583 	 * yet. Wait for it to complete.
10584 	 */
10585 	mutex_exit(mtx);
10586 	rootpp = PP_GROUPLEADER(rootpp, rszc);
10587 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10588 	mutex_enter(mtx);
10589 	mutex_exit(mtx);
10590 	prev_rszc = rszc;
10591 	goto again;
10592 }
10593 
10594 static int
10595 sfmmu_mlspl_held(struct page *pp, int type)
10596 {
10597 	kmutex_t	*mtx;
10598 
10599 	ASSERT(pp != NULL);
10600 	/* The lock lives in the root page */
10601 	pp = PP_PAGEROOT(pp);
10602 	ASSERT(pp != NULL);
10603 
10604 	mtx = SFMMU_MLSPL_MTX(type, pp);
10605 	return (MUTEX_HELD(mtx));
10606 }
10607 
10608 static uint_t
10609 sfmmu_get_free_hblk(struct hme_blk **hmeblkpp, uint_t critical)
10610 {
10611 	struct  hme_blk *hblkp;
10612 
10613 
10614 	if (freehblkp != NULL) {
10615 		mutex_enter(&freehblkp_lock);
10616 		if (freehblkp != NULL) {
10617 			/*
10618 			 * If the current thread is owning hblk_reserve OR
10619 			 * critical request from sfmmu_hblk_steal()
10620 			 * let it succeed even if freehblkcnt is really low.
10621 			 */
10622 			if (freehblkcnt <= HBLK_RESERVE_MIN && !critical) {
10623 				SFMMU_STAT(sf_get_free_throttle);
10624 				mutex_exit(&freehblkp_lock);
10625 				return (0);
10626 			}
10627 			freehblkcnt--;
10628 			*hmeblkpp = freehblkp;
10629 			hblkp = *hmeblkpp;
10630 			freehblkp = hblkp->hblk_next;
10631 			mutex_exit(&freehblkp_lock);
10632 			hblkp->hblk_next = NULL;
10633 			SFMMU_STAT(sf_get_free_success);
10634 
10635 			ASSERT(hblkp->hblk_hmecnt == 0);
10636 			ASSERT(hblkp->hblk_vcnt == 0);
10637 			ASSERT(hblkp->hblk_nextpa == va_to_pa((caddr_t)hblkp));
10638 
10639 			return (1);
10640 		}
10641 		mutex_exit(&freehblkp_lock);
10642 	}
10643 
10644 	/* Check cpu hblk pending queues */
10645 	if ((*hmeblkpp = sfmmu_check_pending_hblks(TTE8K)) != NULL) {
10646 		hblkp = *hmeblkpp;
10647 		hblkp->hblk_next = NULL;
10648 		hblkp->hblk_nextpa = va_to_pa((caddr_t)hblkp);
10649 
10650 		ASSERT(hblkp->hblk_hmecnt == 0);
10651 		ASSERT(hblkp->hblk_vcnt == 0);
10652 
10653 		return (1);
10654 	}
10655 
10656 	SFMMU_STAT(sf_get_free_fail);
10657 	return (0);
10658 }
10659 
10660 static uint_t
10661 sfmmu_put_free_hblk(struct hme_blk *hmeblkp, uint_t critical)
10662 {
10663 	struct  hme_blk *hblkp;
10664 
10665 	ASSERT(hmeblkp->hblk_hmecnt == 0);
10666 	ASSERT(hmeblkp->hblk_vcnt == 0);
10667 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
10668 
10669 	/*
10670 	 * If the current thread is mapping into kernel space,
10671 	 * let it succede even if freehblkcnt is max
10672 	 * so that it will avoid freeing it to kmem.
10673 	 * This will prevent stack overflow due to
10674 	 * possible recursion since kmem_cache_free()
10675 	 * might require creation of a slab which
10676 	 * in turn needs an hmeblk to map that slab;
10677 	 * let's break this vicious chain at the first
10678 	 * opportunity.
10679 	 */
10680 	if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10681 		mutex_enter(&freehblkp_lock);
10682 		if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10683 			SFMMU_STAT(sf_put_free_success);
10684 			freehblkcnt++;
10685 			hmeblkp->hblk_next = freehblkp;
10686 			freehblkp = hmeblkp;
10687 			mutex_exit(&freehblkp_lock);
10688 			return (1);
10689 		}
10690 		mutex_exit(&freehblkp_lock);
10691 	}
10692 
10693 	/*
10694 	 * Bring down freehblkcnt to HBLK_RESERVE_CNT. We are here
10695 	 * only if freehblkcnt is at least HBLK_RESERVE_CNT *and*
10696 	 * we are not in the process of mapping into kernel space.
10697 	 */
10698 	ASSERT(!critical);
10699 	while (freehblkcnt > HBLK_RESERVE_CNT) {
10700 		mutex_enter(&freehblkp_lock);
10701 		if (freehblkcnt > HBLK_RESERVE_CNT) {
10702 			freehblkcnt--;
10703 			hblkp = freehblkp;
10704 			freehblkp = hblkp->hblk_next;
10705 			mutex_exit(&freehblkp_lock);
10706 			ASSERT(get_hblk_cache(hblkp) == sfmmu8_cache);
10707 			kmem_cache_free(sfmmu8_cache, hblkp);
10708 			continue;
10709 		}
10710 		mutex_exit(&freehblkp_lock);
10711 	}
10712 	SFMMU_STAT(sf_put_free_fail);
10713 	return (0);
10714 }
10715 
10716 static void
10717 sfmmu_hblk_swap(struct hme_blk *new)
10718 {
10719 	struct hme_blk *old, *hblkp, *prev;
10720 	uint64_t newpa;
10721 	caddr_t	base, vaddr, endaddr;
10722 	struct hmehash_bucket *hmebp;
10723 	struct sf_hment *osfhme, *nsfhme;
10724 	page_t *pp;
10725 	kmutex_t *pml;
10726 	tte_t tte;
10727 	struct hme_blk *list = NULL;
10728 
10729 #ifdef	DEBUG
10730 	hmeblk_tag		hblktag;
10731 	struct hme_blk		*found;
10732 #endif
10733 	old = HBLK_RESERVE;
10734 	ASSERT(!old->hblk_shared);
10735 
10736 	/*
10737 	 * save pa before bcopy clobbers it
10738 	 */
10739 	newpa = new->hblk_nextpa;
10740 
10741 	base = (caddr_t)get_hblk_base(old);
10742 	endaddr = base + get_hblk_span(old);
10743 
10744 	/*
10745 	 * acquire hash bucket lock.
10746 	 */
10747 	hmebp = sfmmu_tteload_acquire_hashbucket(ksfmmup, base, TTE8K,
10748 	    SFMMU_INVALID_SHMERID);
10749 
10750 	/*
10751 	 * copy contents from old to new
10752 	 */
10753 	bcopy((void *)old, (void *)new, HME8BLK_SZ);
10754 
10755 	/*
10756 	 * add new to hash chain
10757 	 */
10758 	sfmmu_hblk_hash_add(hmebp, new, newpa);
10759 
10760 	/*
10761 	 * search hash chain for hblk_reserve; this needs to be performed
10762 	 * after adding new, otherwise prev won't correspond to the hblk which
10763 	 * is prior to old in hash chain when we call sfmmu_hblk_hash_rm to
10764 	 * remove old later.
10765 	 */
10766 	for (prev = NULL,
10767 	    hblkp = hmebp->hmeblkp; hblkp != NULL && hblkp != old;
10768 	    prev = hblkp, hblkp = hblkp->hblk_next)
10769 		;
10770 
10771 	if (hblkp != old)
10772 		panic("sfmmu_hblk_swap: hblk_reserve not found");
10773 
10774 	/*
10775 	 * p_mapping list is still pointing to hments in hblk_reserve;
10776 	 * fix up p_mapping list so that they point to hments in new.
10777 	 *
10778 	 * Since all these mappings are created by hblk_reserve_thread
10779 	 * on the way and it's using at least one of the buffers from each of
10780 	 * the newly minted slabs, there is no danger of any of these
10781 	 * mappings getting unloaded by another thread.
10782 	 *
10783 	 * tsbmiss could only modify ref/mod bits of hments in old/new.
10784 	 * Since all of these hments hold mappings established by segkmem
10785 	 * and mappings in segkmem are setup with HAT_NOSYNC, ref/mod bits
10786 	 * have no meaning for the mappings in hblk_reserve.  hments in
10787 	 * old and new are identical except for ref/mod bits.
10788 	 */
10789 	for (vaddr = base; vaddr < endaddr; vaddr += TTEBYTES(TTE8K)) {
10790 
10791 		HBLKTOHME(osfhme, old, vaddr);
10792 		sfmmu_copytte(&osfhme->hme_tte, &tte);
10793 
10794 		if (TTE_IS_VALID(&tte)) {
10795 			if ((pp = osfhme->hme_page) == NULL)
10796 				panic("sfmmu_hblk_swap: page not mapped");
10797 
10798 			pml = sfmmu_mlist_enter(pp);
10799 
10800 			if (pp != osfhme->hme_page)
10801 				panic("sfmmu_hblk_swap: mapping changed");
10802 
10803 			HBLKTOHME(nsfhme, new, vaddr);
10804 
10805 			HME_ADD(nsfhme, pp);
10806 			HME_SUB(osfhme, pp);
10807 
10808 			sfmmu_mlist_exit(pml);
10809 		}
10810 	}
10811 
10812 	/*
10813 	 * remove old from hash chain
10814 	 */
10815 	sfmmu_hblk_hash_rm(hmebp, old, prev, &list, 1);
10816 
10817 #ifdef	DEBUG
10818 
10819 	hblktag.htag_id = ksfmmup;
10820 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
10821 	hblktag.htag_bspage = HME_HASH_BSPAGE(base, HME_HASH_SHIFT(TTE8K));
10822 	hblktag.htag_rehash = HME_HASH_REHASH(TTE8K);
10823 	HME_HASH_FAST_SEARCH(hmebp, hblktag, found);
10824 
10825 	if (found != new)
10826 		panic("sfmmu_hblk_swap: new hblk not found");
10827 #endif
10828 
10829 	SFMMU_HASH_UNLOCK(hmebp);
10830 
10831 	/*
10832 	 * Reset hblk_reserve
10833 	 */
10834 	bzero((void *)old, HME8BLK_SZ);
10835 	old->hblk_nextpa = va_to_pa((caddr_t)old);
10836 }
10837 
10838 /*
10839  * Grab the mlist mutex for both pages passed in.
10840  *
10841  * low and high will be returned as pointers to the mutexes for these pages.
10842  * low refers to the mutex residing in the lower bin of the mlist hash, while
10843  * high refers to the mutex residing in the higher bin of the mlist hash.  This
10844  * is due to the locking order restrictions on the same thread grabbing
10845  * multiple mlist mutexes.  The low lock must be acquired before the high lock.
10846  *
10847  * If both pages hash to the same mutex, only grab that single mutex, and
10848  * high will be returned as NULL
10849  * If the pages hash to different bins in the hash, grab the lower addressed
10850  * lock first and then the higher addressed lock in order to follow the locking
10851  * rules involved with the same thread grabbing multiple mlist mutexes.
10852  * low and high will both have non-NULL values.
10853  */
10854 static void
10855 sfmmu_mlist_reloc_enter(struct page *targ, struct page *repl,
10856     kmutex_t **low, kmutex_t **high)
10857 {
10858 	kmutex_t	*mml_targ, *mml_repl;
10859 
10860 	/*
10861 	 * no need to do the dance around szc as in sfmmu_mlist_enter()
10862 	 * because this routine is only called by hat_page_relocate() and all
10863 	 * targ and repl pages are already locked EXCL so szc can't change.
10864 	 */
10865 
10866 	mml_targ = MLIST_HASH(PP_PAGEROOT(targ));
10867 	mml_repl = MLIST_HASH(PP_PAGEROOT(repl));
10868 
10869 	if (mml_targ == mml_repl) {
10870 		*low = mml_targ;
10871 		*high = NULL;
10872 	} else {
10873 		if (mml_targ < mml_repl) {
10874 			*low = mml_targ;
10875 			*high = mml_repl;
10876 		} else {
10877 			*low = mml_repl;
10878 			*high = mml_targ;
10879 		}
10880 	}
10881 
10882 	mutex_enter(*low);
10883 	if (*high)
10884 		mutex_enter(*high);
10885 }
10886 
10887 static void
10888 sfmmu_mlist_reloc_exit(kmutex_t *low, kmutex_t *high)
10889 {
10890 	if (high)
10891 		mutex_exit(high);
10892 	mutex_exit(low);
10893 }
10894 
10895 static hatlock_t *
10896 sfmmu_hat_enter(sfmmu_t *sfmmup)
10897 {
10898 	hatlock_t	*hatlockp;
10899 
10900 	if (sfmmup != ksfmmup) {
10901 		hatlockp = TSB_HASH(sfmmup);
10902 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
10903 		return (hatlockp);
10904 	}
10905 	return (NULL);
10906 }
10907 
10908 static hatlock_t *
10909 sfmmu_hat_tryenter(sfmmu_t *sfmmup)
10910 {
10911 	hatlock_t	*hatlockp;
10912 
10913 	if (sfmmup != ksfmmup) {
10914 		hatlockp = TSB_HASH(sfmmup);
10915 		if (mutex_tryenter(HATLOCK_MUTEXP(hatlockp)) == 0)
10916 			return (NULL);
10917 		return (hatlockp);
10918 	}
10919 	return (NULL);
10920 }
10921 
10922 static void
10923 sfmmu_hat_exit(hatlock_t *hatlockp)
10924 {
10925 	if (hatlockp != NULL)
10926 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
10927 }
10928 
10929 static void
10930 sfmmu_hat_lock_all(void)
10931 {
10932 	int i;
10933 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
10934 		mutex_enter(HATLOCK_MUTEXP(&hat_lock[i]));
10935 }
10936 
10937 static void
10938 sfmmu_hat_unlock_all(void)
10939 {
10940 	int i;
10941 	for (i = SFMMU_NUM_LOCK - 1; i >= 0; i--)
10942 		mutex_exit(HATLOCK_MUTEXP(&hat_lock[i]));
10943 }
10944 
10945 int
10946 sfmmu_hat_lock_held(sfmmu_t *sfmmup)
10947 {
10948 	ASSERT(sfmmup != ksfmmup);
10949 	return (MUTEX_HELD(HATLOCK_MUTEXP(TSB_HASH(sfmmup))));
10950 }
10951 
10952 /*
10953  * Locking primitives to provide consistency between ISM unmap
10954  * and other operations.  Since ISM unmap can take a long time, we
10955  * use HAT_ISMBUSY flag (protected by the hatlock) to avoid creating
10956  * contention on the hatlock buckets while ISM segments are being
10957  * unmapped.  The tradeoff is that the flags don't prevent priority
10958  * inversion from occurring, so we must request kernel priority in
10959  * case we have to sleep to keep from getting buried while holding
10960  * the HAT_ISMBUSY flag set, which in turn could block other kernel
10961  * threads from running (for example, in sfmmu_uvatopfn()).
10962  */
10963 static void
10964 sfmmu_ismhat_enter(sfmmu_t *sfmmup, int hatlock_held)
10965 {
10966 	hatlock_t *hatlockp;
10967 
10968 	THREAD_KPRI_REQUEST();
10969 	if (!hatlock_held)
10970 		hatlockp = sfmmu_hat_enter(sfmmup);
10971 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY))
10972 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
10973 	SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
10974 	if (!hatlock_held)
10975 		sfmmu_hat_exit(hatlockp);
10976 }
10977 
10978 static void
10979 sfmmu_ismhat_exit(sfmmu_t *sfmmup, int hatlock_held)
10980 {
10981 	hatlock_t *hatlockp;
10982 
10983 	if (!hatlock_held)
10984 		hatlockp = sfmmu_hat_enter(sfmmup);
10985 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
10986 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
10987 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
10988 	if (!hatlock_held)
10989 		sfmmu_hat_exit(hatlockp);
10990 	THREAD_KPRI_RELEASE();
10991 }
10992 
10993 /*
10994  *
10995  * Algorithm:
10996  *
10997  * (1) if segkmem is not ready, allocate hblk from an array of pre-alloc'ed
10998  *	hblks.
10999  *
11000  * (2) if we are allocating an hblk for mapping a slab in sfmmu_cache,
11001  *
11002  * 		(a) try to return an hblk from reserve pool of free hblks;
11003  *		(b) if the reserve pool is empty, acquire hblk_reserve_lock
11004  *		    and return hblk_reserve.
11005  *
11006  * (3) call kmem_cache_alloc() to allocate hblk;
11007  *
11008  *		(a) if hblk_reserve_lock is held by the current thread,
11009  *		    atomically replace hblk_reserve by the hblk that is
11010  *		    returned by kmem_cache_alloc; release hblk_reserve_lock
11011  *		    and call kmem_cache_alloc() again.
11012  *		(b) if reserve pool is not full, add the hblk that is
11013  *		    returned by kmem_cache_alloc to reserve pool and
11014  *		    call kmem_cache_alloc again.
11015  *
11016  */
11017 static struct hme_blk *
11018 sfmmu_hblk_alloc(sfmmu_t *sfmmup, caddr_t vaddr,
11019 	struct hmehash_bucket *hmebp, uint_t size, hmeblk_tag hblktag,
11020 	uint_t flags, uint_t rid)
11021 {
11022 	struct hme_blk *hmeblkp = NULL;
11023 	struct hme_blk *newhblkp;
11024 	struct hme_blk *shw_hblkp = NULL;
11025 	struct kmem_cache *sfmmu_cache = NULL;
11026 	uint64_t hblkpa;
11027 	ulong_t index;
11028 	uint_t owner;		/* set to 1 if using hblk_reserve */
11029 	uint_t forcefree;
11030 	int sleep;
11031 	sf_srd_t *srdp;
11032 	sf_region_t *rgnp;
11033 
11034 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11035 	ASSERT(hblktag.htag_rid == rid);
11036 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
11037 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11038 	    IS_P2ALIGNED(vaddr, TTEBYTES(size)));
11039 
11040 	/*
11041 	 * If segkmem is not created yet, allocate from static hmeblks
11042 	 * created at the end of startup_modules().  See the block comment
11043 	 * in startup_modules() describing how we estimate the number of
11044 	 * static hmeblks that will be needed during re-map.
11045 	 */
11046 	if (!hblk_alloc_dynamic) {
11047 
11048 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11049 
11050 		if (size == TTE8K) {
11051 			index = nucleus_hblk8.index;
11052 			if (index >= nucleus_hblk8.len) {
11053 				/*
11054 				 * If we panic here, see startup_modules() to
11055 				 * make sure that we are calculating the
11056 				 * number of hblk8's that we need correctly.
11057 				 */
11058 				prom_panic("no nucleus hblk8 to allocate");
11059 			}
11060 			hmeblkp =
11061 			    (struct hme_blk *)&nucleus_hblk8.list[index];
11062 			nucleus_hblk8.index++;
11063 			SFMMU_STAT(sf_hblk8_nalloc);
11064 		} else {
11065 			index = nucleus_hblk1.index;
11066 			if (nucleus_hblk1.index >= nucleus_hblk1.len) {
11067 				/*
11068 				 * If we panic here, see startup_modules().
11069 				 * Most likely you need to update the
11070 				 * calculation of the number of hblk1 elements
11071 				 * that the kernel needs to boot.
11072 				 */
11073 				prom_panic("no nucleus hblk1 to allocate");
11074 			}
11075 			hmeblkp =
11076 			    (struct hme_blk *)&nucleus_hblk1.list[index];
11077 			nucleus_hblk1.index++;
11078 			SFMMU_STAT(sf_hblk1_nalloc);
11079 		}
11080 
11081 		goto hblk_init;
11082 	}
11083 
11084 	SFMMU_HASH_UNLOCK(hmebp);
11085 
11086 	if (sfmmup != KHATID && !SFMMU_IS_SHMERID_VALID(rid)) {
11087 		if (mmu_page_sizes == max_mmu_page_sizes) {
11088 			if (size < TTE256M)
11089 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11090 				    size, flags);
11091 		} else {
11092 			if (size < TTE4M)
11093 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11094 				    size, flags);
11095 		}
11096 	} else if (SFMMU_IS_SHMERID_VALID(rid)) {
11097 		/*
11098 		 * Shared hmes use per region bitmaps in rgn_hmeflag
11099 		 * rather than shadow hmeblks to keep track of the
11100 		 * mapping sizes which have been allocated for the region.
11101 		 * Here we cleanup old invalid hmeblks with this rid,
11102 		 * which may be left around by pageunload().
11103 		 */
11104 		int ttesz;
11105 		caddr_t va;
11106 		caddr_t	eva = vaddr + TTEBYTES(size);
11107 
11108 		ASSERT(sfmmup != KHATID);
11109 
11110 		srdp = sfmmup->sfmmu_srdp;
11111 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11112 		rgnp = srdp->srd_hmergnp[rid];
11113 		ASSERT(rgnp != NULL && rgnp->rgn_id == rid);
11114 		ASSERT(rgnp->rgn_refcnt != 0);
11115 		ASSERT(size <= rgnp->rgn_pgszc);
11116 
11117 		ttesz = HBLK_MIN_TTESZ;
11118 		do {
11119 			if (!(rgnp->rgn_hmeflags & (0x1 << ttesz))) {
11120 				continue;
11121 			}
11122 
11123 			if (ttesz > size && ttesz != HBLK_MIN_TTESZ) {
11124 				sfmmu_cleanup_rhblk(srdp, vaddr, rid, ttesz);
11125 			} else if (ttesz < size) {
11126 				for (va = vaddr; va < eva;
11127 				    va += TTEBYTES(ttesz)) {
11128 					sfmmu_cleanup_rhblk(srdp, va, rid,
11129 					    ttesz);
11130 				}
11131 			}
11132 		} while (++ttesz <= rgnp->rgn_pgszc);
11133 	}
11134 
11135 fill_hblk:
11136 	owner = (hblk_reserve_thread == curthread) ? 1 : 0;
11137 
11138 	if (owner && size == TTE8K) {
11139 
11140 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11141 		/*
11142 		 * We are really in a tight spot. We already own
11143 		 * hblk_reserve and we need another hblk.  In anticipation
11144 		 * of this kind of scenario, we specifically set aside
11145 		 * HBLK_RESERVE_MIN number of hblks to be used exclusively
11146 		 * by owner of hblk_reserve.
11147 		 */
11148 		SFMMU_STAT(sf_hblk_recurse_cnt);
11149 
11150 		if (!sfmmu_get_free_hblk(&hmeblkp, 1))
11151 			panic("sfmmu_hblk_alloc: reserve list is empty");
11152 
11153 		goto hblk_verify;
11154 	}
11155 
11156 	ASSERT(!owner);
11157 
11158 	if ((flags & HAT_NO_KALLOC) == 0) {
11159 
11160 		sfmmu_cache = ((size == TTE8K) ? sfmmu8_cache : sfmmu1_cache);
11161 		sleep = ((sfmmup == KHATID) ? KM_NOSLEEP : KM_SLEEP);
11162 
11163 		if ((hmeblkp = kmem_cache_alloc(sfmmu_cache, sleep)) == NULL) {
11164 			hmeblkp = sfmmu_hblk_steal(size);
11165 		} else {
11166 			/*
11167 			 * if we are the owner of hblk_reserve,
11168 			 * swap hblk_reserve with hmeblkp and
11169 			 * start a fresh life.  Hope things go
11170 			 * better this time.
11171 			 */
11172 			if (hblk_reserve_thread == curthread) {
11173 				ASSERT(sfmmu_cache == sfmmu8_cache);
11174 				sfmmu_hblk_swap(hmeblkp);
11175 				hblk_reserve_thread = NULL;
11176 				mutex_exit(&hblk_reserve_lock);
11177 				goto fill_hblk;
11178 			}
11179 			/*
11180 			 * let's donate this hblk to our reserve list if
11181 			 * we are not mapping kernel range
11182 			 */
11183 			if (size == TTE8K && sfmmup != KHATID) {
11184 				if (sfmmu_put_free_hblk(hmeblkp, 0))
11185 					goto fill_hblk;
11186 			}
11187 		}
11188 	} else {
11189 		/*
11190 		 * We are here to map the slab in sfmmu8_cache; let's
11191 		 * check if we could tap our reserve list; if successful,
11192 		 * this will avoid the pain of going thru sfmmu_hblk_swap
11193 		 */
11194 		SFMMU_STAT(sf_hblk_slab_cnt);
11195 		if (!sfmmu_get_free_hblk(&hmeblkp, 0)) {
11196 			/*
11197 			 * let's start hblk_reserve dance
11198 			 */
11199 			SFMMU_STAT(sf_hblk_reserve_cnt);
11200 			owner = 1;
11201 			mutex_enter(&hblk_reserve_lock);
11202 			hmeblkp = HBLK_RESERVE;
11203 			hblk_reserve_thread = curthread;
11204 		}
11205 	}
11206 
11207 hblk_verify:
11208 	ASSERT(hmeblkp != NULL);
11209 	set_hblk_sz(hmeblkp, size);
11210 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
11211 	SFMMU_HASH_LOCK(hmebp);
11212 	HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11213 	if (newhblkp != NULL) {
11214 		SFMMU_HASH_UNLOCK(hmebp);
11215 		if (hmeblkp != HBLK_RESERVE) {
11216 			/*
11217 			 * This is really tricky!
11218 			 *
11219 			 * vmem_alloc(vmem_seg_arena)
11220 			 *  vmem_alloc(vmem_internal_arena)
11221 			 *   segkmem_alloc(heap_arena)
11222 			 *    vmem_alloc(heap_arena)
11223 			 *    page_create()
11224 			 *    hat_memload()
11225 			 *	kmem_cache_free()
11226 			 *	 kmem_cache_alloc()
11227 			 *	  kmem_slab_create()
11228 			 *	   vmem_alloc(kmem_internal_arena)
11229 			 *	    segkmem_alloc(heap_arena)
11230 			 *		vmem_alloc(heap_arena)
11231 			 *		page_create()
11232 			 *		hat_memload()
11233 			 *		  kmem_cache_free()
11234 			 *		...
11235 			 *
11236 			 * Thus, hat_memload() could call kmem_cache_free
11237 			 * for enough number of times that we could easily
11238 			 * hit the bottom of the stack or run out of reserve
11239 			 * list of vmem_seg structs.  So, we must donate
11240 			 * this hblk to reserve list if it's allocated
11241 			 * from sfmmu8_cache *and* mapping kernel range.
11242 			 * We don't need to worry about freeing hmeblk1's
11243 			 * to kmem since they don't map any kmem slabs.
11244 			 *
11245 			 * Note: When segkmem supports largepages, we must
11246 			 * free hmeblk1's to reserve list as well.
11247 			 */
11248 			forcefree = (sfmmup == KHATID) ? 1 : 0;
11249 			if (size == TTE8K &&
11250 			    sfmmu_put_free_hblk(hmeblkp, forcefree)) {
11251 				goto re_verify;
11252 			}
11253 			ASSERT(sfmmup != KHATID);
11254 			kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
11255 		} else {
11256 			/*
11257 			 * Hey! we don't need hblk_reserve any more.
11258 			 */
11259 			ASSERT(owner);
11260 			hblk_reserve_thread = NULL;
11261 			mutex_exit(&hblk_reserve_lock);
11262 			owner = 0;
11263 		}
11264 re_verify:
11265 		/*
11266 		 * let's check if the goodies are still present
11267 		 */
11268 		SFMMU_HASH_LOCK(hmebp);
11269 		HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11270 		if (newhblkp != NULL) {
11271 			/*
11272 			 * return newhblkp if it's not hblk_reserve;
11273 			 * if newhblkp is hblk_reserve, return it
11274 			 * _only if_ we are the owner of hblk_reserve.
11275 			 */
11276 			if (newhblkp != HBLK_RESERVE || owner) {
11277 				ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11278 				    newhblkp->hblk_shared);
11279 				ASSERT(SFMMU_IS_SHMERID_VALID(rid) ||
11280 				    !newhblkp->hblk_shared);
11281 				return (newhblkp);
11282 			} else {
11283 				/*
11284 				 * we just hit hblk_reserve in the hash and
11285 				 * we are not the owner of that;
11286 				 *
11287 				 * block until hblk_reserve_thread completes
11288 				 * swapping hblk_reserve and try the dance
11289 				 * once again.
11290 				 */
11291 				SFMMU_HASH_UNLOCK(hmebp);
11292 				mutex_enter(&hblk_reserve_lock);
11293 				mutex_exit(&hblk_reserve_lock);
11294 				SFMMU_STAT(sf_hblk_reserve_hit);
11295 				goto fill_hblk;
11296 			}
11297 		} else {
11298 			/*
11299 			 * it's no more! try the dance once again.
11300 			 */
11301 			SFMMU_HASH_UNLOCK(hmebp);
11302 			goto fill_hblk;
11303 		}
11304 	}
11305 
11306 hblk_init:
11307 	if (SFMMU_IS_SHMERID_VALID(rid)) {
11308 		uint16_t tteflag = 0x1 <<
11309 		    ((size < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ : size);
11310 
11311 		if (!(rgnp->rgn_hmeflags & tteflag)) {
11312 			atomic_or_16(&rgnp->rgn_hmeflags, tteflag);
11313 		}
11314 		hmeblkp->hblk_shared = 1;
11315 	} else {
11316 		hmeblkp->hblk_shared = 0;
11317 	}
11318 	set_hblk_sz(hmeblkp, size);
11319 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11320 	hmeblkp->hblk_next = (struct hme_blk *)NULL;
11321 	hmeblkp->hblk_tag = hblktag;
11322 	hmeblkp->hblk_shadow = shw_hblkp;
11323 	hblkpa = hmeblkp->hblk_nextpa;
11324 	hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
11325 
11326 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
11327 	ASSERT(get_hblk_span(hmeblkp) == HMEBLK_SPAN(size));
11328 	ASSERT(hmeblkp->hblk_hmecnt == 0);
11329 	ASSERT(hmeblkp->hblk_vcnt == 0);
11330 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11331 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
11332 	sfmmu_hblk_hash_add(hmebp, hmeblkp, hblkpa);
11333 	return (hmeblkp);
11334 }
11335 
11336 /*
11337  * This function cleans up the hme_blk and returns it to the free list.
11338  */
11339 /* ARGSUSED */
11340 static void
11341 sfmmu_hblk_free(struct hme_blk **listp)
11342 {
11343 	struct hme_blk *hmeblkp, *next_hmeblkp;
11344 	int		size;
11345 	uint_t		critical;
11346 	uint64_t	hblkpa;
11347 
11348 	ASSERT(*listp != NULL);
11349 
11350 	hmeblkp = *listp;
11351 	while (hmeblkp != NULL) {
11352 		next_hmeblkp = hmeblkp->hblk_next;
11353 		ASSERT(!hmeblkp->hblk_hmecnt);
11354 		ASSERT(!hmeblkp->hblk_vcnt);
11355 		ASSERT(!hmeblkp->hblk_lckcnt);
11356 		ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
11357 		ASSERT(hmeblkp->hblk_shared == 0);
11358 		ASSERT(hmeblkp->hblk_shw_bit == 0);
11359 		ASSERT(hmeblkp->hblk_shadow == NULL);
11360 
11361 		hblkpa = va_to_pa((caddr_t)hmeblkp);
11362 		ASSERT(hblkpa != (uint64_t)-1);
11363 		critical = (hblktosfmmu(hmeblkp) == KHATID) ? 1 : 0;
11364 
11365 		size = get_hblk_ttesz(hmeblkp);
11366 		hmeblkp->hblk_next = NULL;
11367 		hmeblkp->hblk_nextpa = hblkpa;
11368 
11369 		if (hmeblkp->hblk_nuc_bit == 0) {
11370 
11371 			if (size != TTE8K ||
11372 			    !sfmmu_put_free_hblk(hmeblkp, critical))
11373 				kmem_cache_free(get_hblk_cache(hmeblkp),
11374 				    hmeblkp);
11375 		}
11376 		hmeblkp = next_hmeblkp;
11377 	}
11378 }
11379 
11380 #define	BUCKETS_TO_SEARCH_BEFORE_UNLOAD	30
11381 #define	SFMMU_HBLK_STEAL_THRESHOLD 5
11382 
11383 static uint_t sfmmu_hblk_steal_twice;
11384 static uint_t sfmmu_hblk_steal_count, sfmmu_hblk_steal_unload_count;
11385 
11386 /*
11387  * Steal a hmeblk from user or kernel hme hash lists.
11388  * For 8K tte grab one from reserve pool (freehblkp) before proceeding to
11389  * steal and if we fail to steal after SFMMU_HBLK_STEAL_THRESHOLD attempts
11390  * tap into critical reserve of freehblkp.
11391  * Note: We remain looping in this routine until we find one.
11392  */
11393 static struct hme_blk *
11394 sfmmu_hblk_steal(int size)
11395 {
11396 	static struct hmehash_bucket *uhmehash_steal_hand = NULL;
11397 	struct hmehash_bucket *hmebp;
11398 	struct hme_blk *hmeblkp = NULL, *pr_hblk;
11399 	uint64_t hblkpa;
11400 	int i;
11401 	uint_t loop_cnt = 0, critical;
11402 
11403 	for (;;) {
11404 		/* Check cpu hblk pending queues */
11405 		if ((hmeblkp = sfmmu_check_pending_hblks(size)) != NULL) {
11406 			hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
11407 			ASSERT(hmeblkp->hblk_hmecnt == 0);
11408 			ASSERT(hmeblkp->hblk_vcnt == 0);
11409 			return (hmeblkp);
11410 		}
11411 
11412 		if (size == TTE8K) {
11413 			critical =
11414 			    (++loop_cnt > SFMMU_HBLK_STEAL_THRESHOLD) ? 1 : 0;
11415 			if (sfmmu_get_free_hblk(&hmeblkp, critical))
11416 				return (hmeblkp);
11417 		}
11418 
11419 		hmebp = (uhmehash_steal_hand == NULL) ? uhme_hash :
11420 		    uhmehash_steal_hand;
11421 		ASSERT(hmebp >= uhme_hash && hmebp <= &uhme_hash[UHMEHASH_SZ]);
11422 
11423 		for (i = 0; hmeblkp == NULL && i <= UHMEHASH_SZ +
11424 		    BUCKETS_TO_SEARCH_BEFORE_UNLOAD; i++) {
11425 			SFMMU_HASH_LOCK(hmebp);
11426 			hmeblkp = hmebp->hmeblkp;
11427 			hblkpa = hmebp->hmeh_nextpa;
11428 			pr_hblk = NULL;
11429 			while (hmeblkp) {
11430 				/*
11431 				 * check if it is a hmeblk that is not locked
11432 				 * and not shared. skip shadow hmeblks with
11433 				 * shadow_mask set i.e valid count non zero.
11434 				 */
11435 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11436 				    (hmeblkp->hblk_shw_bit == 0 ||
11437 				    hmeblkp->hblk_vcnt == 0) &&
11438 				    (hmeblkp->hblk_lckcnt == 0)) {
11439 					/*
11440 					 * there is a high probability that we
11441 					 * will find a free one. search some
11442 					 * buckets for a free hmeblk initially
11443 					 * before unloading a valid hmeblk.
11444 					 */
11445 					if ((hmeblkp->hblk_vcnt == 0 &&
11446 					    hmeblkp->hblk_hmecnt == 0) || (i >=
11447 					    BUCKETS_TO_SEARCH_BEFORE_UNLOAD)) {
11448 						if (sfmmu_steal_this_hblk(hmebp,
11449 						    hmeblkp, hblkpa, pr_hblk)) {
11450 							/*
11451 							 * Hblk is unloaded
11452 							 * successfully
11453 							 */
11454 							break;
11455 						}
11456 					}
11457 				}
11458 				pr_hblk = hmeblkp;
11459 				hblkpa = hmeblkp->hblk_nextpa;
11460 				hmeblkp = hmeblkp->hblk_next;
11461 			}
11462 
11463 			SFMMU_HASH_UNLOCK(hmebp);
11464 			if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
11465 				hmebp = uhme_hash;
11466 		}
11467 		uhmehash_steal_hand = hmebp;
11468 
11469 		if (hmeblkp != NULL)
11470 			break;
11471 
11472 		/*
11473 		 * in the worst case, look for a free one in the kernel
11474 		 * hash table.
11475 		 */
11476 		for (i = 0, hmebp = khme_hash; i <= KHMEHASH_SZ; i++) {
11477 			SFMMU_HASH_LOCK(hmebp);
11478 			hmeblkp = hmebp->hmeblkp;
11479 			hblkpa = hmebp->hmeh_nextpa;
11480 			pr_hblk = NULL;
11481 			while (hmeblkp) {
11482 				/*
11483 				 * check if it is free hmeblk
11484 				 */
11485 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11486 				    (hmeblkp->hblk_lckcnt == 0) &&
11487 				    (hmeblkp->hblk_vcnt == 0) &&
11488 				    (hmeblkp->hblk_hmecnt == 0)) {
11489 					if (sfmmu_steal_this_hblk(hmebp,
11490 					    hmeblkp, hblkpa, pr_hblk)) {
11491 						break;
11492 					} else {
11493 						/*
11494 						 * Cannot fail since we have
11495 						 * hash lock.
11496 						 */
11497 						panic("fail to steal?");
11498 					}
11499 				}
11500 
11501 				pr_hblk = hmeblkp;
11502 				hblkpa = hmeblkp->hblk_nextpa;
11503 				hmeblkp = hmeblkp->hblk_next;
11504 			}
11505 
11506 			SFMMU_HASH_UNLOCK(hmebp);
11507 			if (hmebp++ == &khme_hash[KHMEHASH_SZ])
11508 				hmebp = khme_hash;
11509 		}
11510 
11511 		if (hmeblkp != NULL)
11512 			break;
11513 		sfmmu_hblk_steal_twice++;
11514 	}
11515 	return (hmeblkp);
11516 }
11517 
11518 /*
11519  * This routine does real work to prepare a hblk to be "stolen" by
11520  * unloading the mappings, updating shadow counts ....
11521  * It returns 1 if the block is ready to be reused (stolen), or 0
11522  * means the block cannot be stolen yet- pageunload is still working
11523  * on this hblk.
11524  */
11525 static int
11526 sfmmu_steal_this_hblk(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
11527 	uint64_t hblkpa, struct hme_blk *pr_hblk)
11528 {
11529 	int shw_size, vshift;
11530 	struct hme_blk *shw_hblkp;
11531 	caddr_t vaddr;
11532 	uint_t shw_mask, newshw_mask;
11533 	struct hme_blk *list = NULL;
11534 
11535 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11536 
11537 	/*
11538 	 * check if the hmeblk is free, unload if necessary
11539 	 */
11540 	if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11541 		sfmmu_t *sfmmup;
11542 		demap_range_t dmr;
11543 
11544 		sfmmup = hblktosfmmu(hmeblkp);
11545 		if (hmeblkp->hblk_shared || sfmmup->sfmmu_ismhat) {
11546 			return (0);
11547 		}
11548 		DEMAP_RANGE_INIT(sfmmup, &dmr);
11549 		(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
11550 		    (caddr_t)get_hblk_base(hmeblkp),
11551 		    get_hblk_endaddr(hmeblkp), &dmr, HAT_UNLOAD);
11552 		DEMAP_RANGE_FLUSH(&dmr);
11553 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11554 			/*
11555 			 * Pageunload is working on the same hblk.
11556 			 */
11557 			return (0);
11558 		}
11559 
11560 		sfmmu_hblk_steal_unload_count++;
11561 	}
11562 
11563 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11564 	ASSERT(hmeblkp->hblk_vcnt == 0 && hmeblkp->hblk_hmecnt == 0);
11565 
11566 	sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk, &list, 1);
11567 	hmeblkp->hblk_nextpa = hblkpa;
11568 
11569 	shw_hblkp = hmeblkp->hblk_shadow;
11570 	if (shw_hblkp) {
11571 		ASSERT(!hmeblkp->hblk_shared);
11572 		shw_size = get_hblk_ttesz(shw_hblkp);
11573 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11574 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
11575 		ASSERT(vshift < 8);
11576 		/*
11577 		 * Atomically clear shadow mask bit
11578 		 */
11579 		do {
11580 			shw_mask = shw_hblkp->hblk_shw_mask;
11581 			ASSERT(shw_mask & (1 << vshift));
11582 			newshw_mask = shw_mask & ~(1 << vshift);
11583 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
11584 			    shw_mask, newshw_mask);
11585 		} while (newshw_mask != shw_mask);
11586 		hmeblkp->hblk_shadow = NULL;
11587 	}
11588 
11589 	/*
11590 	 * remove shadow bit if we are stealing an unused shadow hmeblk.
11591 	 * sfmmu_hblk_alloc needs it that way, will set shadow bit later if
11592 	 * we are indeed allocating a shadow hmeblk.
11593 	 */
11594 	hmeblkp->hblk_shw_bit = 0;
11595 
11596 	if (hmeblkp->hblk_shared) {
11597 		sf_srd_t	*srdp;
11598 		sf_region_t	*rgnp;
11599 		uint_t		rid;
11600 
11601 		srdp = hblktosrd(hmeblkp);
11602 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11603 		rid = hmeblkp->hblk_tag.htag_rid;
11604 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11605 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11606 		rgnp = srdp->srd_hmergnp[rid];
11607 		ASSERT(rgnp != NULL);
11608 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
11609 		hmeblkp->hblk_shared = 0;
11610 	}
11611 
11612 	sfmmu_hblk_steal_count++;
11613 	SFMMU_STAT(sf_steal_count);
11614 
11615 	return (1);
11616 }
11617 
11618 struct hme_blk *
11619 sfmmu_hmetohblk(struct sf_hment *sfhme)
11620 {
11621 	struct hme_blk *hmeblkp;
11622 	struct sf_hment *sfhme0;
11623 	struct hme_blk *hblk_dummy = 0;
11624 
11625 	/*
11626 	 * No dummy sf_hments, please.
11627 	 */
11628 	ASSERT(sfhme->hme_tte.ll != 0);
11629 
11630 	sfhme0 = sfhme - sfhme->hme_tte.tte_hmenum;
11631 	hmeblkp = (struct hme_blk *)((uintptr_t)sfhme0 -
11632 	    (uintptr_t)&hblk_dummy->hblk_hme[0]);
11633 
11634 	return (hmeblkp);
11635 }
11636 
11637 /*
11638  * On swapin, get appropriately sized TSB(s) and clear the HAT_SWAPPED flag.
11639  * If we can't get appropriately sized TSB(s), try for 8K TSB(s) using
11640  * KM_SLEEP allocation.
11641  *
11642  * Return 0 on success, -1 otherwise.
11643  */
11644 static void
11645 sfmmu_tsb_swapin(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11646 {
11647 	struct tsb_info *tsbinfop, *next;
11648 	tsb_replace_rc_t rc;
11649 	boolean_t gotfirst = B_FALSE;
11650 
11651 	ASSERT(sfmmup != ksfmmup);
11652 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11653 
11654 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPIN)) {
11655 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
11656 	}
11657 
11658 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11659 		SFMMU_FLAGS_SET(sfmmup, HAT_SWAPIN);
11660 	} else {
11661 		return;
11662 	}
11663 
11664 	ASSERT(sfmmup->sfmmu_tsb != NULL);
11665 
11666 	/*
11667 	 * Loop over all tsbinfo's replacing them with ones that actually have
11668 	 * a TSB.  If any of the replacements ever fail, bail out of the loop.
11669 	 */
11670 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL; tsbinfop = next) {
11671 		ASSERT(tsbinfop->tsb_flags & TSB_SWAPPED);
11672 		next = tsbinfop->tsb_next;
11673 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, tsbinfop->tsb_szc,
11674 		    hatlockp, TSB_SWAPIN);
11675 		if (rc != TSB_SUCCESS) {
11676 			break;
11677 		}
11678 		gotfirst = B_TRUE;
11679 	}
11680 
11681 	switch (rc) {
11682 	case TSB_SUCCESS:
11683 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11684 		cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11685 		return;
11686 	case TSB_LOSTRACE:
11687 		break;
11688 	case TSB_ALLOCFAIL:
11689 		break;
11690 	default:
11691 		panic("sfmmu_replace_tsb returned unrecognized failure code "
11692 		    "%d", rc);
11693 	}
11694 
11695 	/*
11696 	 * In this case, we failed to get one of our TSBs.  If we failed to
11697 	 * get the first TSB, get one of minimum size (8KB).  Walk the list
11698 	 * and throw away the tsbinfos, starting where the allocation failed;
11699 	 * we can get by with just one TSB as long as we don't leave the
11700 	 * SWAPPED tsbinfo structures lying around.
11701 	 */
11702 	tsbinfop = sfmmup->sfmmu_tsb;
11703 	next = tsbinfop->tsb_next;
11704 	tsbinfop->tsb_next = NULL;
11705 
11706 	sfmmu_hat_exit(hatlockp);
11707 	for (tsbinfop = next; tsbinfop != NULL; tsbinfop = next) {
11708 		next = tsbinfop->tsb_next;
11709 		sfmmu_tsbinfo_free(tsbinfop);
11710 	}
11711 	hatlockp = sfmmu_hat_enter(sfmmup);
11712 
11713 	/*
11714 	 * If we don't have any TSBs, get a single 8K TSB for 8K, 64K and 512K
11715 	 * pages.
11716 	 */
11717 	if (!gotfirst) {
11718 		tsbinfop = sfmmup->sfmmu_tsb;
11719 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, TSB_MIN_SZCODE,
11720 		    hatlockp, TSB_SWAPIN | TSB_FORCEALLOC);
11721 		ASSERT(rc == TSB_SUCCESS);
11722 	}
11723 
11724 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11725 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11726 }
11727 
11728 static int
11729 sfmmu_is_rgnva(sf_srd_t *srdp, caddr_t addr, ulong_t w, ulong_t bmw)
11730 {
11731 	ulong_t bix = 0;
11732 	uint_t rid;
11733 	sf_region_t *rgnp;
11734 
11735 	ASSERT(srdp != NULL);
11736 	ASSERT(srdp->srd_refcnt != 0);
11737 
11738 	w <<= BT_ULSHIFT;
11739 	while (bmw) {
11740 		if (!(bmw & 0x1)) {
11741 			bix++;
11742 			bmw >>= 1;
11743 			continue;
11744 		}
11745 		rid = w | bix;
11746 		rgnp = srdp->srd_hmergnp[rid];
11747 		ASSERT(rgnp->rgn_refcnt > 0);
11748 		ASSERT(rgnp->rgn_id == rid);
11749 		if (addr < rgnp->rgn_saddr ||
11750 		    addr >= (rgnp->rgn_saddr + rgnp->rgn_size)) {
11751 			bix++;
11752 			bmw >>= 1;
11753 		} else {
11754 			return (1);
11755 		}
11756 	}
11757 	return (0);
11758 }
11759 
11760 /*
11761  * Handle exceptions for low level tsb_handler.
11762  *
11763  * There are many scenarios that could land us here:
11764  *
11765  * If the context is invalid we land here. The context can be invalid
11766  * for 3 reasons: 1) we couldn't allocate a new context and now need to
11767  * perform a wrap around operation in order to allocate a new context.
11768  * 2) Context was invalidated to change pagesize programming 3) ISMs or
11769  * TSBs configuration is changeing for this process and we are forced into
11770  * here to do a syncronization operation. If the context is valid we can
11771  * be here from window trap hanlder. In this case just call trap to handle
11772  * the fault.
11773  *
11774  * Note that the process will run in INVALID_CONTEXT before
11775  * faulting into here and subsequently loading the MMU registers
11776  * (including the TSB base register) associated with this process.
11777  * For this reason, the trap handlers must all test for
11778  * INVALID_CONTEXT before attempting to access any registers other
11779  * than the context registers.
11780  */
11781 void
11782 sfmmu_tsbmiss_exception(struct regs *rp, uintptr_t tagaccess, uint_t traptype)
11783 {
11784 	sfmmu_t *sfmmup, *shsfmmup;
11785 	uint_t ctxtype;
11786 	klwp_id_t lwp;
11787 	char lwp_save_state;
11788 	hatlock_t *hatlockp, *shatlockp;
11789 	struct tsb_info *tsbinfop;
11790 	struct tsbmiss *tsbmp;
11791 	sf_scd_t *scdp;
11792 
11793 	SFMMU_STAT(sf_tsb_exceptions);
11794 	SFMMU_MMU_STAT(mmu_tsb_exceptions);
11795 	sfmmup = astosfmmu(curthread->t_procp->p_as);
11796 	/*
11797 	 * note that in sun4u, tagacces register contains ctxnum
11798 	 * while sun4v passes ctxtype in the tagaccess register.
11799 	 */
11800 	ctxtype = tagaccess & TAGACC_CTX_MASK;
11801 
11802 	ASSERT(sfmmup != ksfmmup && ctxtype != KCONTEXT);
11803 	ASSERT(sfmmup->sfmmu_ismhat == 0);
11804 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED) ||
11805 	    ctxtype == INVALID_CONTEXT);
11806 
11807 	if (ctxtype != INVALID_CONTEXT && traptype != T_DATA_PROT) {
11808 		/*
11809 		 * We may land here because shme bitmap and pagesize
11810 		 * flags are updated lazily in tsbmiss area on other cpus.
11811 		 * If we detect here that tsbmiss area is out of sync with
11812 		 * sfmmu update it and retry the trapped instruction.
11813 		 * Otherwise call trap().
11814 		 */
11815 		int ret = 0;
11816 		uchar_t tteflag_mask = (1 << TTE64K) | (1 << TTE8K);
11817 		caddr_t addr = (caddr_t)(tagaccess & TAGACC_VADDR_MASK);
11818 
11819 		/*
11820 		 * Must set lwp state to LWP_SYS before
11821 		 * trying to acquire any adaptive lock
11822 		 */
11823 		lwp = ttolwp(curthread);
11824 		ASSERT(lwp);
11825 		lwp_save_state = lwp->lwp_state;
11826 		lwp->lwp_state = LWP_SYS;
11827 
11828 		hatlockp = sfmmu_hat_enter(sfmmup);
11829 		kpreempt_disable();
11830 		tsbmp = &tsbmiss_area[CPU->cpu_id];
11831 		ASSERT(sfmmup == tsbmp->usfmmup);
11832 		if (((tsbmp->uhat_tteflags ^ sfmmup->sfmmu_tteflags) &
11833 		    ~tteflag_mask) ||
11834 		    ((tsbmp->uhat_rtteflags ^  sfmmup->sfmmu_rtteflags) &
11835 		    ~tteflag_mask)) {
11836 			tsbmp->uhat_tteflags = sfmmup->sfmmu_tteflags;
11837 			tsbmp->uhat_rtteflags = sfmmup->sfmmu_rtteflags;
11838 			ret = 1;
11839 		}
11840 		if (sfmmup->sfmmu_srdp != NULL) {
11841 			ulong_t *sm = sfmmup->sfmmu_hmeregion_map.bitmap;
11842 			ulong_t *tm = tsbmp->shmermap;
11843 			ulong_t i;
11844 			for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
11845 				ulong_t d = tm[i] ^ sm[i];
11846 				if (d) {
11847 					if (d & sm[i]) {
11848 						if (!ret && sfmmu_is_rgnva(
11849 						    sfmmup->sfmmu_srdp,
11850 						    addr, i, d & sm[i])) {
11851 							ret = 1;
11852 						}
11853 					}
11854 					tm[i] = sm[i];
11855 				}
11856 			}
11857 		}
11858 		kpreempt_enable();
11859 		sfmmu_hat_exit(hatlockp);
11860 		lwp->lwp_state = lwp_save_state;
11861 		if (ret) {
11862 			return;
11863 		}
11864 	} else if (ctxtype == INVALID_CONTEXT) {
11865 		/*
11866 		 * First, make sure we come out of here with a valid ctx,
11867 		 * since if we don't get one we'll simply loop on the
11868 		 * faulting instruction.
11869 		 *
11870 		 * If the ISM mappings are changing, the TSB is relocated,
11871 		 * the process is swapped, the process is joining SCD or
11872 		 * leaving SCD or shared regions we serialize behind the
11873 		 * controlling thread with hat lock, sfmmu_flags and
11874 		 * sfmmu_tsb_cv condition variable.
11875 		 */
11876 
11877 		/*
11878 		 * Must set lwp state to LWP_SYS before
11879 		 * trying to acquire any adaptive lock
11880 		 */
11881 		lwp = ttolwp(curthread);
11882 		ASSERT(lwp);
11883 		lwp_save_state = lwp->lwp_state;
11884 		lwp->lwp_state = LWP_SYS;
11885 
11886 		hatlockp = sfmmu_hat_enter(sfmmup);
11887 retry:
11888 		if ((scdp = sfmmup->sfmmu_scdp) != NULL) {
11889 			shsfmmup = scdp->scd_sfmmup;
11890 			ASSERT(shsfmmup != NULL);
11891 
11892 			for (tsbinfop = shsfmmup->sfmmu_tsb; tsbinfop != NULL;
11893 			    tsbinfop = tsbinfop->tsb_next) {
11894 				if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11895 					/* drop the private hat lock */
11896 					sfmmu_hat_exit(hatlockp);
11897 					/* acquire the shared hat lock */
11898 					shatlockp = sfmmu_hat_enter(shsfmmup);
11899 					/*
11900 					 * recheck to see if anything changed
11901 					 * after we drop the private hat lock.
11902 					 */
11903 					if (sfmmup->sfmmu_scdp == scdp &&
11904 					    shsfmmup == scdp->scd_sfmmup) {
11905 						sfmmu_tsb_chk_reloc(shsfmmup,
11906 						    shatlockp);
11907 					}
11908 					sfmmu_hat_exit(shatlockp);
11909 					hatlockp = sfmmu_hat_enter(sfmmup);
11910 					goto retry;
11911 				}
11912 			}
11913 		}
11914 
11915 		for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
11916 		    tsbinfop = tsbinfop->tsb_next) {
11917 			if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11918 				cv_wait(&sfmmup->sfmmu_tsb_cv,
11919 				    HATLOCK_MUTEXP(hatlockp));
11920 				goto retry;
11921 			}
11922 		}
11923 
11924 		/*
11925 		 * Wait for ISM maps to be updated.
11926 		 */
11927 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
11928 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11929 			    HATLOCK_MUTEXP(hatlockp));
11930 			goto retry;
11931 		}
11932 
11933 		/* Is this process joining an SCD? */
11934 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
11935 			/*
11936 			 * Flush private TSB and setup shared TSB.
11937 			 * sfmmu_finish_join_scd() does not drop the
11938 			 * hat lock.
11939 			 */
11940 			sfmmu_finish_join_scd(sfmmup);
11941 			SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
11942 		}
11943 
11944 		/*
11945 		 * If we're swapping in, get TSB(s).  Note that we must do
11946 		 * this before we get a ctx or load the MMU state.  Once
11947 		 * we swap in we have to recheck to make sure the TSB(s) and
11948 		 * ISM mappings didn't change while we slept.
11949 		 */
11950 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11951 			sfmmu_tsb_swapin(sfmmup, hatlockp);
11952 			goto retry;
11953 		}
11954 
11955 		sfmmu_get_ctx(sfmmup);
11956 
11957 		sfmmu_hat_exit(hatlockp);
11958 		/*
11959 		 * Must restore lwp_state if not calling
11960 		 * trap() for further processing. Restore
11961 		 * it anyway.
11962 		 */
11963 		lwp->lwp_state = lwp_save_state;
11964 		return;
11965 	}
11966 	trap(rp, (caddr_t)tagaccess, traptype, 0);
11967 }
11968 
11969 static void
11970 sfmmu_tsb_chk_reloc(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11971 {
11972 	struct tsb_info *tp;
11973 
11974 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11975 
11976 	for (tp = sfmmup->sfmmu_tsb; tp != NULL; tp = tp->tsb_next) {
11977 		if (tp->tsb_flags & TSB_RELOC_FLAG) {
11978 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11979 			    HATLOCK_MUTEXP(hatlockp));
11980 			break;
11981 		}
11982 	}
11983 }
11984 
11985 /*
11986  * sfmmu_vatopfn_suspended is called from GET_TTE when TL=0 and
11987  * TTE_SUSPENDED bit set in tte we block on aquiring a page lock
11988  * rather than spinning to avoid send mondo timeouts with
11989  * interrupts enabled. When the lock is acquired it is immediately
11990  * released and we return back to sfmmu_vatopfn just after
11991  * the GET_TTE call.
11992  */
11993 void
11994 sfmmu_vatopfn_suspended(caddr_t vaddr, sfmmu_t *sfmmu, tte_t *ttep)
11995 {
11996 	struct page	**pp;
11997 
11998 	(void) as_pagelock(sfmmu->sfmmu_as, &pp, vaddr, TTE_CSZ(ttep), S_WRITE);
11999 	as_pageunlock(sfmmu->sfmmu_as, pp, vaddr, TTE_CSZ(ttep), S_WRITE);
12000 }
12001 
12002 /*
12003  * sfmmu_tsbmiss_suspended is called from GET_TTE when TL>0 and
12004  * TTE_SUSPENDED bit set in tte. We do this so that we can handle
12005  * cross traps which cannot be handled while spinning in the
12006  * trap handlers. Simply enter and exit the kpr_suspendlock spin
12007  * mutex, which is held by the holder of the suspend bit, and then
12008  * retry the trapped instruction after unwinding.
12009  */
12010 /*ARGSUSED*/
12011 void
12012 sfmmu_tsbmiss_suspended(struct regs *rp, uintptr_t tagacc, uint_t traptype)
12013 {
12014 	ASSERT(curthread != kreloc_thread);
12015 	mutex_enter(&kpr_suspendlock);
12016 	mutex_exit(&kpr_suspendlock);
12017 }
12018 
12019 /*
12020  * This routine could be optimized to reduce the number of xcalls by flushing
12021  * the entire TLBs if region reference count is above some threshold but the
12022  * tradeoff will depend on the size of the TLB. So for now flush the specific
12023  * page a context at a time.
12024  *
12025  * If uselocks is 0 then it's called after all cpus were captured and all the
12026  * hat locks were taken. In this case don't take the region lock by relying on
12027  * the order of list region update operations in hat_join_region(),
12028  * hat_leave_region() and hat_dup_region(). The ordering in those routines
12029  * guarantees that list is always forward walkable and reaches active sfmmus
12030  * regardless of where xc_attention() captures a cpu.
12031  */
12032 cpuset_t
12033 sfmmu_rgntlb_demap(caddr_t addr, sf_region_t *rgnp,
12034     struct hme_blk *hmeblkp, int uselocks)
12035 {
12036 	sfmmu_t	*sfmmup;
12037 	cpuset_t cpuset;
12038 	cpuset_t rcpuset;
12039 	hatlock_t *hatlockp;
12040 	uint_t rid = rgnp->rgn_id;
12041 	sf_rgn_link_t *rlink;
12042 	sf_scd_t *scdp;
12043 
12044 	ASSERT(hmeblkp->hblk_shared);
12045 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
12046 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
12047 
12048 	CPUSET_ZERO(rcpuset);
12049 	if (uselocks) {
12050 		mutex_enter(&rgnp->rgn_mutex);
12051 	}
12052 	sfmmup = rgnp->rgn_sfmmu_head;
12053 	while (sfmmup != NULL) {
12054 		if (uselocks) {
12055 			hatlockp = sfmmu_hat_enter(sfmmup);
12056 		}
12057 
12058 		/*
12059 		 * When an SCD is created the SCD hat is linked on the sfmmu
12060 		 * region lists for each hme region which is part of the
12061 		 * SCD. If we find an SCD hat, when walking these lists,
12062 		 * then we flush the shared TSBs, if we find a private hat,
12063 		 * which is part of an SCD, but where the region
12064 		 * is not part of the SCD then we flush the private TSBs.
12065 		 */
12066 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12067 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
12068 			scdp = sfmmup->sfmmu_scdp;
12069 			if (SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
12070 				if (uselocks) {
12071 					sfmmu_hat_exit(hatlockp);
12072 				}
12073 				goto next;
12074 			}
12075 		}
12076 
12077 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12078 
12079 		kpreempt_disable();
12080 		cpuset = sfmmup->sfmmu_cpusran;
12081 		CPUSET_AND(cpuset, cpu_ready_set);
12082 		CPUSET_DEL(cpuset, CPU->cpu_id);
12083 		SFMMU_XCALL_STATS(sfmmup);
12084 		xt_some(cpuset, vtag_flushpage_tl1,
12085 		    (uint64_t)addr, (uint64_t)sfmmup);
12086 		vtag_flushpage(addr, (uint64_t)sfmmup);
12087 		if (uselocks) {
12088 			sfmmu_hat_exit(hatlockp);
12089 		}
12090 		kpreempt_enable();
12091 		CPUSET_OR(rcpuset, cpuset);
12092 
12093 next:
12094 		/* LINTED: constant in conditional context */
12095 		SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
12096 		ASSERT(rlink != NULL);
12097 		sfmmup = rlink->next;
12098 	}
12099 	if (uselocks) {
12100 		mutex_exit(&rgnp->rgn_mutex);
12101 	}
12102 	return (rcpuset);
12103 }
12104 
12105 /*
12106  * This routine takes an sfmmu pointer and the va for an adddress in an
12107  * ISM region as input and returns the corresponding region id in ism_rid.
12108  * The return value of 1 indicates that a region has been found and ism_rid
12109  * is valid, otherwise 0 is returned.
12110  */
12111 static int
12112 find_ism_rid(sfmmu_t *sfmmup, sfmmu_t *ism_sfmmup, caddr_t va, uint_t *ism_rid)
12113 {
12114 	ism_blk_t	*ism_blkp;
12115 	int		i;
12116 	ism_map_t	*ism_map;
12117 #ifdef DEBUG
12118 	struct hat	*ism_hatid;
12119 #endif
12120 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12121 
12122 	ism_blkp = sfmmup->sfmmu_iblk;
12123 	while (ism_blkp != NULL) {
12124 		ism_map = ism_blkp->iblk_maps;
12125 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
12126 			if ((va >= ism_start(ism_map[i])) &&
12127 			    (va < ism_end(ism_map[i]))) {
12128 
12129 				*ism_rid = ism_map[i].imap_rid;
12130 #ifdef DEBUG
12131 				ism_hatid = ism_map[i].imap_ismhat;
12132 				ASSERT(ism_hatid == ism_sfmmup);
12133 				ASSERT(ism_hatid->sfmmu_ismhat);
12134 #endif
12135 				return (1);
12136 			}
12137 		}
12138 		ism_blkp = ism_blkp->iblk_next;
12139 	}
12140 	return (0);
12141 }
12142 
12143 /*
12144  * Special routine to flush out ism mappings- TSBs, TLBs and D-caches.
12145  * This routine may be called with all cpu's captured. Therefore, the
12146  * caller is responsible for holding all locks and disabling kernel
12147  * preemption.
12148  */
12149 /* ARGSUSED */
12150 static void
12151 sfmmu_ismtlbcache_demap(caddr_t addr, sfmmu_t *ism_sfmmup,
12152 	struct hme_blk *hmeblkp, pfn_t pfnum, int cache_flush_flag)
12153 {
12154 	cpuset_t 	cpuset;
12155 	caddr_t 	va;
12156 	ism_ment_t	*ment;
12157 	sfmmu_t		*sfmmup;
12158 #ifdef VAC
12159 	int 		vcolor;
12160 #endif
12161 
12162 	sf_scd_t	*scdp;
12163 	uint_t		ism_rid;
12164 
12165 	ASSERT(!hmeblkp->hblk_shared);
12166 	/*
12167 	 * Walk the ism_hat's mapping list and flush the page
12168 	 * from every hat sharing this ism_hat. This routine
12169 	 * may be called while all cpu's have been captured.
12170 	 * Therefore we can't attempt to grab any locks. For now
12171 	 * this means we will protect the ism mapping list under
12172 	 * a single lock which will be grabbed by the caller.
12173 	 * If hat_share/unshare scalibility becomes a performance
12174 	 * problem then we may need to re-think ism mapping list locking.
12175 	 */
12176 	ASSERT(ism_sfmmup->sfmmu_ismhat);
12177 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
12178 	addr = addr - ISMID_STARTADDR;
12179 
12180 	for (ment = ism_sfmmup->sfmmu_iment; ment; ment = ment->iment_next) {
12181 
12182 		sfmmup = ment->iment_hat;
12183 
12184 		va = ment->iment_base_va;
12185 		va = (caddr_t)((uintptr_t)va  + (uintptr_t)addr);
12186 
12187 		/*
12188 		 * When an SCD is created the SCD hat is linked on the ism
12189 		 * mapping lists for each ISM segment which is part of the
12190 		 * SCD. If we find an SCD hat, when walking these lists,
12191 		 * then we flush the shared TSBs, if we find a private hat,
12192 		 * which is part of an SCD, but where the region
12193 		 * corresponding to this va is not part of the SCD then we
12194 		 * flush the private TSBs.
12195 		 */
12196 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12197 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD) &&
12198 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
12199 			if (!find_ism_rid(sfmmup, ism_sfmmup, va,
12200 			    &ism_rid)) {
12201 				cmn_err(CE_PANIC,
12202 				    "can't find matching ISM rid!");
12203 			}
12204 
12205 			scdp = sfmmup->sfmmu_scdp;
12206 			if (SFMMU_IS_ISMRID_VALID(ism_rid) &&
12207 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map,
12208 			    ism_rid)) {
12209 				continue;
12210 			}
12211 		}
12212 		SFMMU_UNLOAD_TSB(va, sfmmup, hmeblkp, 1);
12213 
12214 		cpuset = sfmmup->sfmmu_cpusran;
12215 		CPUSET_AND(cpuset, cpu_ready_set);
12216 		CPUSET_DEL(cpuset, CPU->cpu_id);
12217 		SFMMU_XCALL_STATS(sfmmup);
12218 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)va,
12219 		    (uint64_t)sfmmup);
12220 		vtag_flushpage(va, (uint64_t)sfmmup);
12221 
12222 #ifdef VAC
12223 		/*
12224 		 * Flush D$
12225 		 * When flushing D$ we must flush all
12226 		 * cpu's. See sfmmu_cache_flush().
12227 		 */
12228 		if (cache_flush_flag == CACHE_FLUSH) {
12229 			cpuset = cpu_ready_set;
12230 			CPUSET_DEL(cpuset, CPU->cpu_id);
12231 
12232 			SFMMU_XCALL_STATS(sfmmup);
12233 			vcolor = addr_to_vcolor(va);
12234 			xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12235 			vac_flushpage(pfnum, vcolor);
12236 		}
12237 #endif	/* VAC */
12238 	}
12239 }
12240 
12241 /*
12242  * Demaps the TSB, CPU caches, and flushes all TLBs on all CPUs of
12243  * a particular virtual address and ctx.  If noflush is set we do not
12244  * flush the TLB/TSB.  This function may or may not be called with the
12245  * HAT lock held.
12246  */
12247 static void
12248 sfmmu_tlbcache_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12249 	pfn_t pfnum, int tlb_noflush, int cpu_flag, int cache_flush_flag,
12250 	int hat_lock_held)
12251 {
12252 #ifdef VAC
12253 	int vcolor;
12254 #endif
12255 	cpuset_t cpuset;
12256 	hatlock_t *hatlockp;
12257 
12258 	ASSERT(!hmeblkp->hblk_shared);
12259 
12260 #if defined(lint) && !defined(VAC)
12261 	pfnum = pfnum;
12262 	cpu_flag = cpu_flag;
12263 	cache_flush_flag = cache_flush_flag;
12264 #endif
12265 
12266 	/*
12267 	 * There is no longer a need to protect against ctx being
12268 	 * stolen here since we don't store the ctx in the TSB anymore.
12269 	 */
12270 #ifdef VAC
12271 	vcolor = addr_to_vcolor(addr);
12272 #endif
12273 
12274 	/*
12275 	 * We must hold the hat lock during the flush of TLB,
12276 	 * to avoid a race with sfmmu_invalidate_ctx(), where
12277 	 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12278 	 * causing TLB demap routine to skip flush on that MMU.
12279 	 * If the context on a MMU has already been set to
12280 	 * INVALID_CONTEXT, we just get an extra flush on
12281 	 * that MMU.
12282 	 */
12283 	if (!hat_lock_held && !tlb_noflush)
12284 		hatlockp = sfmmu_hat_enter(sfmmup);
12285 
12286 	kpreempt_disable();
12287 	if (!tlb_noflush) {
12288 		/*
12289 		 * Flush the TSB and TLB.
12290 		 */
12291 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12292 
12293 		cpuset = sfmmup->sfmmu_cpusran;
12294 		CPUSET_AND(cpuset, cpu_ready_set);
12295 		CPUSET_DEL(cpuset, CPU->cpu_id);
12296 
12297 		SFMMU_XCALL_STATS(sfmmup);
12298 
12299 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
12300 		    (uint64_t)sfmmup);
12301 
12302 		vtag_flushpage(addr, (uint64_t)sfmmup);
12303 	}
12304 
12305 	if (!hat_lock_held && !tlb_noflush)
12306 		sfmmu_hat_exit(hatlockp);
12307 
12308 #ifdef VAC
12309 	/*
12310 	 * Flush the D$
12311 	 *
12312 	 * Even if the ctx is stolen, we need to flush the
12313 	 * cache. Our ctx stealer only flushes the TLBs.
12314 	 */
12315 	if (cache_flush_flag == CACHE_FLUSH) {
12316 		if (cpu_flag & FLUSH_ALL_CPUS) {
12317 			cpuset = cpu_ready_set;
12318 		} else {
12319 			cpuset = sfmmup->sfmmu_cpusran;
12320 			CPUSET_AND(cpuset, cpu_ready_set);
12321 		}
12322 		CPUSET_DEL(cpuset, CPU->cpu_id);
12323 		SFMMU_XCALL_STATS(sfmmup);
12324 		xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12325 		vac_flushpage(pfnum, vcolor);
12326 	}
12327 #endif	/* VAC */
12328 	kpreempt_enable();
12329 }
12330 
12331 /*
12332  * Demaps the TSB and flushes all TLBs on all cpus for a particular virtual
12333  * address and ctx.  If noflush is set we do not currently do anything.
12334  * This function may or may not be called with the HAT lock held.
12335  */
12336 static void
12337 sfmmu_tlb_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12338 	int tlb_noflush, int hat_lock_held)
12339 {
12340 	cpuset_t cpuset;
12341 	hatlock_t *hatlockp;
12342 
12343 	ASSERT(!hmeblkp->hblk_shared);
12344 
12345 	/*
12346 	 * If the process is exiting we have nothing to do.
12347 	 */
12348 	if (tlb_noflush)
12349 		return;
12350 
12351 	/*
12352 	 * Flush TSB.
12353 	 */
12354 	if (!hat_lock_held)
12355 		hatlockp = sfmmu_hat_enter(sfmmup);
12356 	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12357 
12358 	kpreempt_disable();
12359 
12360 	cpuset = sfmmup->sfmmu_cpusran;
12361 	CPUSET_AND(cpuset, cpu_ready_set);
12362 	CPUSET_DEL(cpuset, CPU->cpu_id);
12363 
12364 	SFMMU_XCALL_STATS(sfmmup);
12365 	xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr, (uint64_t)sfmmup);
12366 
12367 	vtag_flushpage(addr, (uint64_t)sfmmup);
12368 
12369 	if (!hat_lock_held)
12370 		sfmmu_hat_exit(hatlockp);
12371 
12372 	kpreempt_enable();
12373 
12374 }
12375 
12376 /*
12377  * Special case of sfmmu_tlb_demap for MMU_PAGESIZE hblks. Use the xcall
12378  * call handler that can flush a range of pages to save on xcalls.
12379  */
12380 static int sfmmu_xcall_save;
12381 
12382 /*
12383  * this routine is never used for demaping addresses backed by SRD hmeblks.
12384  */
12385 static void
12386 sfmmu_tlb_range_demap(demap_range_t *dmrp)
12387 {
12388 	sfmmu_t *sfmmup = dmrp->dmr_sfmmup;
12389 	hatlock_t *hatlockp;
12390 	cpuset_t cpuset;
12391 	uint64_t sfmmu_pgcnt;
12392 	pgcnt_t pgcnt = 0;
12393 	int pgunload = 0;
12394 	int dirtypg = 0;
12395 	caddr_t addr = dmrp->dmr_addr;
12396 	caddr_t eaddr;
12397 	uint64_t bitvec = dmrp->dmr_bitvec;
12398 
12399 	ASSERT(bitvec & 1);
12400 
12401 	/*
12402 	 * Flush TSB and calculate number of pages to flush.
12403 	 */
12404 	while (bitvec != 0) {
12405 		dirtypg = 0;
12406 		/*
12407 		 * Find the first page to flush and then count how many
12408 		 * pages there are after it that also need to be flushed.
12409 		 * This way the number of TSB flushes is minimized.
12410 		 */
12411 		while ((bitvec & 1) == 0) {
12412 			pgcnt++;
12413 			addr += MMU_PAGESIZE;
12414 			bitvec >>= 1;
12415 		}
12416 		while (bitvec & 1) {
12417 			dirtypg++;
12418 			bitvec >>= 1;
12419 		}
12420 		eaddr = addr + ptob(dirtypg);
12421 		hatlockp = sfmmu_hat_enter(sfmmup);
12422 		sfmmu_unload_tsb_range(sfmmup, addr, eaddr, TTE8K);
12423 		sfmmu_hat_exit(hatlockp);
12424 		pgunload += dirtypg;
12425 		addr = eaddr;
12426 		pgcnt += dirtypg;
12427 	}
12428 
12429 	ASSERT((pgcnt<<MMU_PAGESHIFT) <= dmrp->dmr_endaddr - dmrp->dmr_addr);
12430 	if (sfmmup->sfmmu_free == 0) {
12431 		addr = dmrp->dmr_addr;
12432 		bitvec = dmrp->dmr_bitvec;
12433 
12434 		/*
12435 		 * make sure it has SFMMU_PGCNT_SHIFT bits only,
12436 		 * as it will be used to pack argument for xt_some
12437 		 */
12438 		ASSERT((pgcnt > 0) &&
12439 		    (pgcnt <= (1 << SFMMU_PGCNT_SHIFT)));
12440 
12441 		/*
12442 		 * Encode pgcnt as (pgcnt -1 ), and pass (pgcnt - 1) in
12443 		 * the low 6 bits of sfmmup. This is doable since pgcnt
12444 		 * always >= 1.
12445 		 */
12446 		ASSERT(!((uint64_t)sfmmup & SFMMU_PGCNT_MASK));
12447 		sfmmu_pgcnt = (uint64_t)sfmmup |
12448 		    ((pgcnt - 1) & SFMMU_PGCNT_MASK);
12449 
12450 		/*
12451 		 * We must hold the hat lock during the flush of TLB,
12452 		 * to avoid a race with sfmmu_invalidate_ctx(), where
12453 		 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12454 		 * causing TLB demap routine to skip flush on that MMU.
12455 		 * If the context on a MMU has already been set to
12456 		 * INVALID_CONTEXT, we just get an extra flush on
12457 		 * that MMU.
12458 		 */
12459 		hatlockp = sfmmu_hat_enter(sfmmup);
12460 		kpreempt_disable();
12461 
12462 		cpuset = sfmmup->sfmmu_cpusran;
12463 		CPUSET_AND(cpuset, cpu_ready_set);
12464 		CPUSET_DEL(cpuset, CPU->cpu_id);
12465 
12466 		SFMMU_XCALL_STATS(sfmmup);
12467 		xt_some(cpuset, vtag_flush_pgcnt_tl1, (uint64_t)addr,
12468 		    sfmmu_pgcnt);
12469 
12470 		for (; bitvec != 0; bitvec >>= 1) {
12471 			if (bitvec & 1)
12472 				vtag_flushpage(addr, (uint64_t)sfmmup);
12473 			addr += MMU_PAGESIZE;
12474 		}
12475 		kpreempt_enable();
12476 		sfmmu_hat_exit(hatlockp);
12477 
12478 		sfmmu_xcall_save += (pgunload-1);
12479 	}
12480 	dmrp->dmr_bitvec = 0;
12481 }
12482 
12483 /*
12484  * In cases where we need to synchronize with TLB/TSB miss trap
12485  * handlers, _and_ need to flush the TLB, it's a lot easier to
12486  * throw away the context from the process than to do a
12487  * special song and dance to keep things consistent for the
12488  * handlers.
12489  *
12490  * Since the process suddenly ends up without a context and our caller
12491  * holds the hat lock, threads that fault after this function is called
12492  * will pile up on the lock.  We can then do whatever we need to
12493  * atomically from the context of the caller.  The first blocked thread
12494  * to resume executing will get the process a new context, and the
12495  * process will resume executing.
12496  *
12497  * One added advantage of this approach is that on MMUs that
12498  * support a "flush all" operation, we will delay the flush until
12499  * cnum wrap-around, and then flush the TLB one time.  This
12500  * is rather rare, so it's a lot less expensive than making 8000
12501  * x-calls to flush the TLB 8000 times.
12502  *
12503  * A per-process (PP) lock is used to synchronize ctx allocations in
12504  * resume() and ctx invalidations here.
12505  */
12506 static void
12507 sfmmu_invalidate_ctx(sfmmu_t *sfmmup)
12508 {
12509 	cpuset_t cpuset;
12510 	int cnum, currcnum;
12511 	mmu_ctx_t *mmu_ctxp;
12512 	int i;
12513 	uint_t pstate_save;
12514 
12515 	SFMMU_STAT(sf_ctx_inv);
12516 
12517 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12518 	ASSERT(sfmmup != ksfmmup);
12519 
12520 	kpreempt_disable();
12521 
12522 	mmu_ctxp = CPU_MMU_CTXP(CPU);
12523 	ASSERT(mmu_ctxp);
12524 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
12525 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
12526 
12527 	currcnum = sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum;
12528 
12529 	pstate_save = sfmmu_disable_intrs();
12530 
12531 	lock_set(&sfmmup->sfmmu_ctx_lock);	/* acquire PP lock */
12532 	/* set HAT cnum invalid across all context domains. */
12533 	for (i = 0; i < max_mmu_ctxdoms; i++) {
12534 
12535 		cnum = 	sfmmup->sfmmu_ctxs[i].cnum;
12536 		if (cnum == INVALID_CONTEXT) {
12537 			continue;
12538 		}
12539 
12540 		sfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
12541 	}
12542 	membar_enter();	/* make sure globally visible to all CPUs */
12543 	lock_clear(&sfmmup->sfmmu_ctx_lock);	/* release PP lock */
12544 
12545 	sfmmu_enable_intrs(pstate_save);
12546 
12547 	cpuset = sfmmup->sfmmu_cpusran;
12548 	CPUSET_DEL(cpuset, CPU->cpu_id);
12549 	CPUSET_AND(cpuset, cpu_ready_set);
12550 	if (!CPUSET_ISNULL(cpuset)) {
12551 		SFMMU_XCALL_STATS(sfmmup);
12552 		xt_some(cpuset, sfmmu_raise_tsb_exception,
12553 		    (uint64_t)sfmmup, INVALID_CONTEXT);
12554 		xt_sync(cpuset);
12555 		SFMMU_STAT(sf_tsb_raise_exception);
12556 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
12557 	}
12558 
12559 	/*
12560 	 * If the hat to-be-invalidated is the same as the current
12561 	 * process on local CPU we need to invalidate
12562 	 * this CPU context as well.
12563 	 */
12564 	if ((sfmmu_getctx_sec() == currcnum) &&
12565 	    (currcnum != INVALID_CONTEXT)) {
12566 		/* sets shared context to INVALID too */
12567 		sfmmu_setctx_sec(INVALID_CONTEXT);
12568 		sfmmu_clear_utsbinfo();
12569 	}
12570 
12571 	SFMMU_FLAGS_SET(sfmmup, HAT_ALLCTX_INVALID);
12572 
12573 	kpreempt_enable();
12574 
12575 	/*
12576 	 * we hold the hat lock, so nobody should allocate a context
12577 	 * for us yet
12578 	 */
12579 	ASSERT(sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum == INVALID_CONTEXT);
12580 }
12581 
12582 #ifdef VAC
12583 /*
12584  * We need to flush the cache in all cpus.  It is possible that
12585  * a process referenced a page as cacheable but has sinced exited
12586  * and cleared the mapping list.  We still to flush it but have no
12587  * state so all cpus is the only alternative.
12588  */
12589 void
12590 sfmmu_cache_flush(pfn_t pfnum, int vcolor)
12591 {
12592 	cpuset_t cpuset;
12593 
12594 	kpreempt_disable();
12595 	cpuset = cpu_ready_set;
12596 	CPUSET_DEL(cpuset, CPU->cpu_id);
12597 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12598 	xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12599 	xt_sync(cpuset);
12600 	vac_flushpage(pfnum, vcolor);
12601 	kpreempt_enable();
12602 }
12603 
12604 void
12605 sfmmu_cache_flushcolor(int vcolor, pfn_t pfnum)
12606 {
12607 	cpuset_t cpuset;
12608 
12609 	ASSERT(vcolor >= 0);
12610 
12611 	kpreempt_disable();
12612 	cpuset = cpu_ready_set;
12613 	CPUSET_DEL(cpuset, CPU->cpu_id);
12614 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12615 	xt_some(cpuset, vac_flushcolor_tl1, vcolor, pfnum);
12616 	xt_sync(cpuset);
12617 	vac_flushcolor(vcolor, pfnum);
12618 	kpreempt_enable();
12619 }
12620 #endif	/* VAC */
12621 
12622 /*
12623  * We need to prevent processes from accessing the TSB using a cached physical
12624  * address.  It's alright if they try to access the TSB via virtual address
12625  * since they will just fault on that virtual address once the mapping has
12626  * been suspended.
12627  */
12628 #pragma weak sendmondo_in_recover
12629 
12630 /* ARGSUSED */
12631 static int
12632 sfmmu_tsb_pre_relocator(caddr_t va, uint_t tsbsz, uint_t flags, void *tsbinfo)
12633 {
12634 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12635 	sfmmu_t *sfmmup = tsbinfop->tsb_sfmmu;
12636 	hatlock_t *hatlockp;
12637 	sf_scd_t *scdp;
12638 
12639 	if (flags != HAT_PRESUSPEND)
12640 		return (0);
12641 
12642 	/*
12643 	 * If tsb is a shared TSB with TSB_SHAREDCTX set, sfmmup must
12644 	 * be a shared hat, then set SCD's tsbinfo's flag.
12645 	 * If tsb is not shared, sfmmup is a private hat, then set
12646 	 * its private tsbinfo's flag.
12647 	 */
12648 	hatlockp = sfmmu_hat_enter(sfmmup);
12649 	tsbinfop->tsb_flags |= TSB_RELOC_FLAG;
12650 
12651 	if (!(tsbinfop->tsb_flags & TSB_SHAREDCTX)) {
12652 		sfmmu_tsb_inv_ctx(sfmmup);
12653 		sfmmu_hat_exit(hatlockp);
12654 	} else {
12655 		/* release lock on the shared hat */
12656 		sfmmu_hat_exit(hatlockp);
12657 		/* sfmmup is a shared hat */
12658 		ASSERT(sfmmup->sfmmu_scdhat);
12659 		scdp = sfmmup->sfmmu_scdp;
12660 		ASSERT(scdp != NULL);
12661 		/* get private hat from the scd list */
12662 		mutex_enter(&scdp->scd_mutex);
12663 		sfmmup = scdp->scd_sf_list;
12664 		while (sfmmup != NULL) {
12665 			hatlockp = sfmmu_hat_enter(sfmmup);
12666 			/*
12667 			 * We do not call sfmmu_tsb_inv_ctx here because
12668 			 * sendmondo_in_recover check is only needed for
12669 			 * sun4u.
12670 			 */
12671 			sfmmu_invalidate_ctx(sfmmup);
12672 			sfmmu_hat_exit(hatlockp);
12673 			sfmmup = sfmmup->sfmmu_scd_link.next;
12674 
12675 		}
12676 		mutex_exit(&scdp->scd_mutex);
12677 	}
12678 	return (0);
12679 }
12680 
12681 static void
12682 sfmmu_tsb_inv_ctx(sfmmu_t *sfmmup)
12683 {
12684 	extern uint32_t sendmondo_in_recover;
12685 
12686 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12687 
12688 	/*
12689 	 * For Cheetah+ Erratum 25:
12690 	 * Wait for any active recovery to finish.  We can't risk
12691 	 * relocating the TSB of the thread running mondo_recover_proc()
12692 	 * since, if we did that, we would deadlock.  The scenario we are
12693 	 * trying to avoid is as follows:
12694 	 *
12695 	 * THIS CPU			RECOVER CPU
12696 	 * --------			-----------
12697 	 *				Begins recovery, walking through TSB
12698 	 * hat_pagesuspend() TSB TTE
12699 	 *				TLB miss on TSB TTE, spins at TL1
12700 	 * xt_sync()
12701 	 *	send_mondo_timeout()
12702 	 *	mondo_recover_proc()
12703 	 *	((deadlocked))
12704 	 *
12705 	 * The second half of the workaround is that mondo_recover_proc()
12706 	 * checks to see if the tsb_info has the RELOC flag set, and if it
12707 	 * does, it skips over that TSB without ever touching tsbinfop->tsb_va
12708 	 * and hence avoiding the TLB miss that could result in a deadlock.
12709 	 */
12710 	if (&sendmondo_in_recover) {
12711 		membar_enter();	/* make sure RELOC flag visible */
12712 		while (sendmondo_in_recover) {
12713 			drv_usecwait(1);
12714 			membar_consumer();
12715 		}
12716 	}
12717 
12718 	sfmmu_invalidate_ctx(sfmmup);
12719 }
12720 
12721 /* ARGSUSED */
12722 static int
12723 sfmmu_tsb_post_relocator(caddr_t va, uint_t tsbsz, uint_t flags,
12724 	void *tsbinfo, pfn_t newpfn)
12725 {
12726 	hatlock_t *hatlockp;
12727 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12728 	sfmmu_t	*sfmmup = tsbinfop->tsb_sfmmu;
12729 
12730 	if (flags != HAT_POSTUNSUSPEND)
12731 		return (0);
12732 
12733 	hatlockp = sfmmu_hat_enter(sfmmup);
12734 
12735 	SFMMU_STAT(sf_tsb_reloc);
12736 
12737 	/*
12738 	 * The process may have swapped out while we were relocating one
12739 	 * of its TSBs.  If so, don't bother doing the setup since the
12740 	 * process can't be using the memory anymore.
12741 	 */
12742 	if ((tsbinfop->tsb_flags & TSB_SWAPPED) == 0) {
12743 		ASSERT(va == tsbinfop->tsb_va);
12744 		sfmmu_tsbinfo_setup_phys(tsbinfop, newpfn);
12745 
12746 		if (tsbinfop->tsb_flags & TSB_FLUSH_NEEDED) {
12747 			sfmmu_inv_tsb(tsbinfop->tsb_va,
12748 			    TSB_BYTES(tsbinfop->tsb_szc));
12749 			tsbinfop->tsb_flags &= ~TSB_FLUSH_NEEDED;
12750 		}
12751 	}
12752 
12753 	membar_exit();
12754 	tsbinfop->tsb_flags &= ~TSB_RELOC_FLAG;
12755 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
12756 
12757 	sfmmu_hat_exit(hatlockp);
12758 
12759 	return (0);
12760 }
12761 
12762 /*
12763  * Allocate and initialize a tsb_info structure.  Note that we may or may not
12764  * allocate a TSB here, depending on the flags passed in.
12765  */
12766 static int
12767 sfmmu_tsbinfo_alloc(struct tsb_info **tsbinfopp, int tsb_szc, int tte_sz_mask,
12768 	uint_t flags, sfmmu_t *sfmmup)
12769 {
12770 	int err;
12771 
12772 	*tsbinfopp = (struct tsb_info *)kmem_cache_alloc(
12773 	    sfmmu_tsbinfo_cache, KM_SLEEP);
12774 
12775 	if ((err = sfmmu_init_tsbinfo(*tsbinfopp, tte_sz_mask,
12776 	    tsb_szc, flags, sfmmup)) != 0) {
12777 		kmem_cache_free(sfmmu_tsbinfo_cache, *tsbinfopp);
12778 		SFMMU_STAT(sf_tsb_allocfail);
12779 		*tsbinfopp = NULL;
12780 		return (err);
12781 	}
12782 	SFMMU_STAT(sf_tsb_alloc);
12783 
12784 	/*
12785 	 * Bump the TSB size counters for this TSB size.
12786 	 */
12787 	(*(((int *)&sfmmu_tsbsize_stat) + tsb_szc))++;
12788 	return (0);
12789 }
12790 
12791 static void
12792 sfmmu_tsb_free(struct tsb_info *tsbinfo)
12793 {
12794 	caddr_t tsbva = tsbinfo->tsb_va;
12795 	uint_t tsb_size = TSB_BYTES(tsbinfo->tsb_szc);
12796 	struct kmem_cache *kmem_cachep = tsbinfo->tsb_cache;
12797 	vmem_t	*vmp = tsbinfo->tsb_vmp;
12798 
12799 	/*
12800 	 * If we allocated this TSB from relocatable kernel memory, then we
12801 	 * need to uninstall the callback handler.
12802 	 */
12803 	if (tsbinfo->tsb_cache != sfmmu_tsb8k_cache) {
12804 		uintptr_t slab_mask;
12805 		caddr_t slab_vaddr;
12806 		page_t **ppl;
12807 		int ret;
12808 
12809 		ASSERT(tsb_size <= MMU_PAGESIZE4M || use_bigtsb_arena);
12810 		if (tsb_size > MMU_PAGESIZE4M)
12811 			slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12812 		else
12813 			slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12814 		slab_vaddr = (caddr_t)((uintptr_t)tsbva & slab_mask);
12815 
12816 		ret = as_pagelock(&kas, &ppl, slab_vaddr, PAGESIZE, S_WRITE);
12817 		ASSERT(ret == 0);
12818 		hat_delete_callback(tsbva, (uint_t)tsb_size, (void *)tsbinfo,
12819 		    0, NULL);
12820 		as_pageunlock(&kas, ppl, slab_vaddr, PAGESIZE, S_WRITE);
12821 	}
12822 
12823 	if (kmem_cachep != NULL) {
12824 		kmem_cache_free(kmem_cachep, tsbva);
12825 	} else {
12826 		vmem_xfree(vmp, (void *)tsbva, tsb_size);
12827 	}
12828 	tsbinfo->tsb_va = (caddr_t)0xbad00bad;
12829 	atomic_add_64(&tsb_alloc_bytes, -(int64_t)tsb_size);
12830 }
12831 
12832 static void
12833 sfmmu_tsbinfo_free(struct tsb_info *tsbinfo)
12834 {
12835 	if ((tsbinfo->tsb_flags & TSB_SWAPPED) == 0) {
12836 		sfmmu_tsb_free(tsbinfo);
12837 	}
12838 	kmem_cache_free(sfmmu_tsbinfo_cache, tsbinfo);
12839 
12840 }
12841 
12842 /*
12843  * Setup all the references to physical memory for this tsbinfo.
12844  * The underlying page(s) must be locked.
12845  */
12846 static void
12847 sfmmu_tsbinfo_setup_phys(struct tsb_info *tsbinfo, pfn_t pfn)
12848 {
12849 	ASSERT(pfn != PFN_INVALID);
12850 	ASSERT(pfn == va_to_pfn(tsbinfo->tsb_va));
12851 
12852 #ifndef sun4v
12853 	if (tsbinfo->tsb_szc == 0) {
12854 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn,
12855 		    PROT_WRITE|PROT_READ, TTE8K);
12856 	} else {
12857 		/*
12858 		 * Round down PA and use a large mapping; the handlers will
12859 		 * compute the TSB pointer at the correct offset into the
12860 		 * big virtual page.  NOTE: this assumes all TSBs larger
12861 		 * than 8K must come from physically contiguous slabs of
12862 		 * size tsb_slab_size.
12863 		 */
12864 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn & ~tsb_slab_mask,
12865 		    PROT_WRITE|PROT_READ, tsb_slab_ttesz);
12866 	}
12867 	tsbinfo->tsb_pa = ptob(pfn);
12868 
12869 	TTE_SET_LOCKED(&tsbinfo->tsb_tte); /* lock the tte into dtlb */
12870 	TTE_SET_MOD(&tsbinfo->tsb_tte);    /* enable writes */
12871 
12872 	ASSERT(TTE_IS_PRIVILEGED(&tsbinfo->tsb_tte));
12873 	ASSERT(TTE_IS_LOCKED(&tsbinfo->tsb_tte));
12874 #else /* sun4v */
12875 	tsbinfo->tsb_pa = ptob(pfn);
12876 #endif /* sun4v */
12877 }
12878 
12879 
12880 /*
12881  * Returns zero on success, ENOMEM if over the high water mark,
12882  * or EAGAIN if the caller needs to retry with a smaller TSB
12883  * size (or specify TSB_FORCEALLOC if the allocation can't fail).
12884  *
12885  * This call cannot fail to allocate a TSB if TSB_FORCEALLOC
12886  * is specified and the TSB requested is PAGESIZE, though it
12887  * may sleep waiting for memory if sufficient memory is not
12888  * available.
12889  */
12890 static int
12891 sfmmu_init_tsbinfo(struct tsb_info *tsbinfo, int tteszmask,
12892     int tsbcode, uint_t flags, sfmmu_t *sfmmup)
12893 {
12894 	caddr_t vaddr = NULL;
12895 	caddr_t slab_vaddr;
12896 	uintptr_t slab_mask;
12897 	int tsbbytes = TSB_BYTES(tsbcode);
12898 	int lowmem = 0;
12899 	struct kmem_cache *kmem_cachep = NULL;
12900 	vmem_t *vmp = NULL;
12901 	lgrp_id_t lgrpid = LGRP_NONE;
12902 	pfn_t pfn;
12903 	uint_t cbflags = HAC_SLEEP;
12904 	page_t **pplist;
12905 	int ret;
12906 
12907 	ASSERT(tsbbytes <= MMU_PAGESIZE4M || use_bigtsb_arena);
12908 	if (tsbbytes > MMU_PAGESIZE4M)
12909 		slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12910 	else
12911 		slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12912 
12913 	if (flags & (TSB_FORCEALLOC | TSB_SWAPIN | TSB_GROW | TSB_SHRINK))
12914 		flags |= TSB_ALLOC;
12915 
12916 	ASSERT((flags & TSB_FORCEALLOC) == 0 || tsbcode == TSB_MIN_SZCODE);
12917 
12918 	tsbinfo->tsb_sfmmu = sfmmup;
12919 
12920 	/*
12921 	 * If not allocating a TSB, set up the tsbinfo, set TSB_SWAPPED, and
12922 	 * return.
12923 	 */
12924 	if ((flags & TSB_ALLOC) == 0) {
12925 		tsbinfo->tsb_szc = tsbcode;
12926 		tsbinfo->tsb_ttesz_mask = tteszmask;
12927 		tsbinfo->tsb_va = (caddr_t)0xbadbadbeef;
12928 		tsbinfo->tsb_pa = -1;
12929 		tsbinfo->tsb_tte.ll = 0;
12930 		tsbinfo->tsb_next = NULL;
12931 		tsbinfo->tsb_flags = TSB_SWAPPED;
12932 		tsbinfo->tsb_cache = NULL;
12933 		tsbinfo->tsb_vmp = NULL;
12934 		return (0);
12935 	}
12936 
12937 #ifdef DEBUG
12938 	/*
12939 	 * For debugging:
12940 	 * Randomly force allocation failures every tsb_alloc_mtbf
12941 	 * tries if TSB_FORCEALLOC is not specified.  This will
12942 	 * return ENOMEM if tsb_alloc_mtbf is odd, or EAGAIN if
12943 	 * it is even, to allow testing of both failure paths...
12944 	 */
12945 	if (tsb_alloc_mtbf && ((flags & TSB_FORCEALLOC) == 0) &&
12946 	    (tsb_alloc_count++ == tsb_alloc_mtbf)) {
12947 		tsb_alloc_count = 0;
12948 		tsb_alloc_fail_mtbf++;
12949 		return ((tsb_alloc_mtbf & 1)? ENOMEM : EAGAIN);
12950 	}
12951 #endif	/* DEBUG */
12952 
12953 	/*
12954 	 * Enforce high water mark if we are not doing a forced allocation
12955 	 * and are not shrinking a process' TSB.
12956 	 */
12957 	if ((flags & TSB_SHRINK) == 0 &&
12958 	    (tsbbytes + tsb_alloc_bytes) > tsb_alloc_hiwater) {
12959 		if ((flags & TSB_FORCEALLOC) == 0)
12960 			return (ENOMEM);
12961 		lowmem = 1;
12962 	}
12963 
12964 	/*
12965 	 * Allocate from the correct location based upon the size of the TSB
12966 	 * compared to the base page size, and what memory conditions dictate.
12967 	 * Note we always do nonblocking allocations from the TSB arena since
12968 	 * we don't want memory fragmentation to cause processes to block
12969 	 * indefinitely waiting for memory; until the kernel algorithms that
12970 	 * coalesce large pages are improved this is our best option.
12971 	 *
12972 	 * Algorithm:
12973 	 *	If allocating a "large" TSB (>8K), allocate from the
12974 	 *		appropriate kmem_tsb_default_arena vmem arena
12975 	 *	else if low on memory or the TSB_FORCEALLOC flag is set or
12976 	 *	tsb_forceheap is set
12977 	 *		Allocate from kernel heap via sfmmu_tsb8k_cache with
12978 	 *		KM_SLEEP (never fails)
12979 	 *	else
12980 	 *		Allocate from appropriate sfmmu_tsb_cache with
12981 	 *		KM_NOSLEEP
12982 	 *	endif
12983 	 */
12984 	if (tsb_lgrp_affinity)
12985 		lgrpid = lgrp_home_id(curthread);
12986 	if (lgrpid == LGRP_NONE)
12987 		lgrpid = 0;	/* use lgrp of boot CPU */
12988 
12989 	if (tsbbytes > MMU_PAGESIZE) {
12990 		if (tsbbytes > MMU_PAGESIZE4M) {
12991 			vmp = kmem_bigtsb_default_arena[lgrpid];
12992 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
12993 			    0, 0, NULL, NULL, VM_NOSLEEP);
12994 		} else {
12995 			vmp = kmem_tsb_default_arena[lgrpid];
12996 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
12997 			    0, 0, NULL, NULL, VM_NOSLEEP);
12998 		}
12999 #ifdef	DEBUG
13000 	} else if (lowmem || (flags & TSB_FORCEALLOC) || tsb_forceheap) {
13001 #else	/* !DEBUG */
13002 	} else if (lowmem || (flags & TSB_FORCEALLOC)) {
13003 #endif	/* DEBUG */
13004 		kmem_cachep = sfmmu_tsb8k_cache;
13005 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_SLEEP);
13006 		ASSERT(vaddr != NULL);
13007 	} else {
13008 		kmem_cachep = sfmmu_tsb_cache[lgrpid];
13009 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_NOSLEEP);
13010 	}
13011 
13012 	tsbinfo->tsb_cache = kmem_cachep;
13013 	tsbinfo->tsb_vmp = vmp;
13014 
13015 	if (vaddr == NULL) {
13016 		return (EAGAIN);
13017 	}
13018 
13019 	atomic_add_64(&tsb_alloc_bytes, (int64_t)tsbbytes);
13020 	kmem_cachep = tsbinfo->tsb_cache;
13021 
13022 	/*
13023 	 * If we are allocating from outside the cage, then we need to
13024 	 * register a relocation callback handler.  Note that for now
13025 	 * since pseudo mappings always hang off of the slab's root page,
13026 	 * we need only lock the first 8K of the TSB slab.  This is a bit
13027 	 * hacky but it is good for performance.
13028 	 */
13029 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13030 		slab_vaddr = (caddr_t)((uintptr_t)vaddr & slab_mask);
13031 		ret = as_pagelock(&kas, &pplist, slab_vaddr, PAGESIZE, S_WRITE);
13032 		ASSERT(ret == 0);
13033 		ret = hat_add_callback(sfmmu_tsb_cb_id, vaddr, (uint_t)tsbbytes,
13034 		    cbflags, (void *)tsbinfo, &pfn, NULL);
13035 
13036 		/*
13037 		 * Need to free up resources if we could not successfully
13038 		 * add the callback function and return an error condition.
13039 		 */
13040 		if (ret != 0) {
13041 			if (kmem_cachep) {
13042 				kmem_cache_free(kmem_cachep, vaddr);
13043 			} else {
13044 				vmem_xfree(vmp, (void *)vaddr, tsbbytes);
13045 			}
13046 			as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE,
13047 			    S_WRITE);
13048 			return (EAGAIN);
13049 		}
13050 	} else {
13051 		/*
13052 		 * Since allocation of 8K TSBs from heap is rare and occurs
13053 		 * during memory pressure we allocate them from permanent
13054 		 * memory rather than using callbacks to get the PFN.
13055 		 */
13056 		pfn = hat_getpfnum(kas.a_hat, vaddr);
13057 	}
13058 
13059 	tsbinfo->tsb_va = vaddr;
13060 	tsbinfo->tsb_szc = tsbcode;
13061 	tsbinfo->tsb_ttesz_mask = tteszmask;
13062 	tsbinfo->tsb_next = NULL;
13063 	tsbinfo->tsb_flags = 0;
13064 
13065 	sfmmu_tsbinfo_setup_phys(tsbinfo, pfn);
13066 
13067 	sfmmu_inv_tsb(vaddr, tsbbytes);
13068 
13069 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13070 		as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE, S_WRITE);
13071 	}
13072 
13073 	return (0);
13074 }
13075 
13076 /*
13077  * Initialize per cpu tsb and per cpu tsbmiss_area
13078  */
13079 void
13080 sfmmu_init_tsbs(void)
13081 {
13082 	int i;
13083 	struct tsbmiss	*tsbmissp;
13084 	struct kpmtsbm	*kpmtsbmp;
13085 #ifndef sun4v
13086 	extern int	dcache_line_mask;
13087 #endif /* sun4v */
13088 	extern uint_t	vac_colors;
13089 
13090 	/*
13091 	 * Init. tsb miss area.
13092 	 */
13093 	tsbmissp = tsbmiss_area;
13094 
13095 	for (i = 0; i < NCPU; tsbmissp++, i++) {
13096 		/*
13097 		 * initialize the tsbmiss area.
13098 		 * Do this for all possible CPUs as some may be added
13099 		 * while the system is running. There is no cost to this.
13100 		 */
13101 		tsbmissp->ksfmmup = ksfmmup;
13102 #ifndef sun4v
13103 		tsbmissp->dcache_line_mask = (uint16_t)dcache_line_mask;
13104 #endif /* sun4v */
13105 		tsbmissp->khashstart =
13106 		    (struct hmehash_bucket *)va_to_pa((caddr_t)khme_hash);
13107 		tsbmissp->uhashstart =
13108 		    (struct hmehash_bucket *)va_to_pa((caddr_t)uhme_hash);
13109 		tsbmissp->khashsz = khmehash_num;
13110 		tsbmissp->uhashsz = uhmehash_num;
13111 	}
13112 
13113 	sfmmu_tsb_cb_id = hat_register_callback('T'<<16 | 'S' << 8 | 'B',
13114 	    sfmmu_tsb_pre_relocator, sfmmu_tsb_post_relocator, NULL, 0);
13115 
13116 	if (kpm_enable == 0)
13117 		return;
13118 
13119 	/* -- Begin KPM specific init -- */
13120 
13121 	if (kpm_smallpages) {
13122 		/*
13123 		 * If we're using base pagesize pages for seg_kpm
13124 		 * mappings, we use the kernel TSB since we can't afford
13125 		 * to allocate a second huge TSB for these mappings.
13126 		 */
13127 		kpm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13128 		kpm_tsbsz = ktsb_szcode;
13129 		kpmsm_tsbbase = kpm_tsbbase;
13130 		kpmsm_tsbsz = kpm_tsbsz;
13131 	} else {
13132 		/*
13133 		 * In VAC conflict case, just put the entries in the
13134 		 * kernel 8K indexed TSB for now so we can find them.
13135 		 * This could really be changed in the future if we feel
13136 		 * the need...
13137 		 */
13138 		kpmsm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13139 		kpmsm_tsbsz = ktsb_szcode;
13140 		kpm_tsbbase = ktsb_phys? ktsb4m_pbase : (uint64_t)ktsb4m_base;
13141 		kpm_tsbsz = ktsb4m_szcode;
13142 	}
13143 
13144 	kpmtsbmp = kpmtsbm_area;
13145 	for (i = 0; i < NCPU; kpmtsbmp++, i++) {
13146 		/*
13147 		 * Initialize the kpmtsbm area.
13148 		 * Do this for all possible CPUs as some may be added
13149 		 * while the system is running. There is no cost to this.
13150 		 */
13151 		kpmtsbmp->vbase = kpm_vbase;
13152 		kpmtsbmp->vend = kpm_vbase + kpm_size * vac_colors;
13153 		kpmtsbmp->sz_shift = kpm_size_shift;
13154 		kpmtsbmp->kpmp_shift = kpmp_shift;
13155 		kpmtsbmp->kpmp2pshft = (uchar_t)kpmp2pshft;
13156 		if (kpm_smallpages == 0) {
13157 			kpmtsbmp->kpmp_table_sz = kpmp_table_sz;
13158 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_table);
13159 		} else {
13160 			kpmtsbmp->kpmp_table_sz = kpmp_stable_sz;
13161 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_stable);
13162 		}
13163 		kpmtsbmp->msegphashpa = va_to_pa(memseg_phash);
13164 		kpmtsbmp->flags = KPMTSBM_ENABLE_FLAG;
13165 #ifdef	DEBUG
13166 		kpmtsbmp->flags |= (kpm_tsbmtl) ?  KPMTSBM_TLTSBM_FLAG : 0;
13167 #endif	/* DEBUG */
13168 		if (ktsb_phys)
13169 			kpmtsbmp->flags |= KPMTSBM_TSBPHYS_FLAG;
13170 	}
13171 
13172 	/* -- End KPM specific init -- */
13173 }
13174 
13175 /* Avoid using sfmmu_tsbinfo_alloc() to avoid kmem_alloc - no real reason */
13176 struct tsb_info ktsb_info[2];
13177 
13178 /*
13179  * Called from hat_kern_setup() to setup the tsb_info for ksfmmup.
13180  */
13181 void
13182 sfmmu_init_ktsbinfo()
13183 {
13184 	ASSERT(ksfmmup != NULL);
13185 	ASSERT(ksfmmup->sfmmu_tsb == NULL);
13186 	/*
13187 	 * Allocate tsbinfos for kernel and copy in data
13188 	 * to make debug easier and sun4v setup easier.
13189 	 */
13190 	ktsb_info[0].tsb_sfmmu = ksfmmup;
13191 	ktsb_info[0].tsb_szc = ktsb_szcode;
13192 	ktsb_info[0].tsb_ttesz_mask = TSB8K|TSB64K|TSB512K;
13193 	ktsb_info[0].tsb_va = ktsb_base;
13194 	ktsb_info[0].tsb_pa = ktsb_pbase;
13195 	ktsb_info[0].tsb_flags = 0;
13196 	ktsb_info[0].tsb_tte.ll = 0;
13197 	ktsb_info[0].tsb_cache = NULL;
13198 
13199 	ktsb_info[1].tsb_sfmmu = ksfmmup;
13200 	ktsb_info[1].tsb_szc = ktsb4m_szcode;
13201 	ktsb_info[1].tsb_ttesz_mask = TSB4M;
13202 	ktsb_info[1].tsb_va = ktsb4m_base;
13203 	ktsb_info[1].tsb_pa = ktsb4m_pbase;
13204 	ktsb_info[1].tsb_flags = 0;
13205 	ktsb_info[1].tsb_tte.ll = 0;
13206 	ktsb_info[1].tsb_cache = NULL;
13207 
13208 	/* Link them into ksfmmup. */
13209 	ktsb_info[0].tsb_next = &ktsb_info[1];
13210 	ktsb_info[1].tsb_next = NULL;
13211 	ksfmmup->sfmmu_tsb = &ktsb_info[0];
13212 
13213 	sfmmu_setup_tsbinfo(ksfmmup);
13214 }
13215 
13216 /*
13217  * Cache the last value returned from va_to_pa().  If the VA specified
13218  * in the current call to cached_va_to_pa() maps to the same Page (as the
13219  * previous call to cached_va_to_pa()), then compute the PA using
13220  * cached info, else call va_to_pa().
13221  *
13222  * Note: this function is neither MT-safe nor consistent in the presence
13223  * of multiple, interleaved threads.  This function was created to enable
13224  * an optimization used during boot (at a point when there's only one thread
13225  * executing on the "boot CPU", and before startup_vm() has been called).
13226  */
13227 static uint64_t
13228 cached_va_to_pa(void *vaddr)
13229 {
13230 	static uint64_t prev_vaddr_base = 0;
13231 	static uint64_t prev_pfn = 0;
13232 
13233 	if ((((uint64_t)vaddr) & MMU_PAGEMASK) == prev_vaddr_base) {
13234 		return (prev_pfn | ((uint64_t)vaddr & MMU_PAGEOFFSET));
13235 	} else {
13236 		uint64_t pa = va_to_pa(vaddr);
13237 
13238 		if (pa != ((uint64_t)-1)) {
13239 			/*
13240 			 * Computed physical address is valid.  Cache its
13241 			 * related info for the next cached_va_to_pa() call.
13242 			 */
13243 			prev_pfn = pa & MMU_PAGEMASK;
13244 			prev_vaddr_base = ((uint64_t)vaddr) & MMU_PAGEMASK;
13245 		}
13246 
13247 		return (pa);
13248 	}
13249 }
13250 
13251 /*
13252  * Carve up our nucleus hblk region.  We may allocate more hblks than
13253  * asked due to rounding errors but we are guaranteed to have at least
13254  * enough space to allocate the requested number of hblk8's and hblk1's.
13255  */
13256 void
13257 sfmmu_init_nucleus_hblks(caddr_t addr, size_t size, int nhblk8, int nhblk1)
13258 {
13259 	struct hme_blk *hmeblkp;
13260 	size_t hme8blk_sz, hme1blk_sz;
13261 	size_t i;
13262 	size_t hblk8_bound;
13263 	ulong_t j = 0, k = 0;
13264 
13265 	ASSERT(addr != NULL && size != 0);
13266 
13267 	/* Need to use proper structure alignment */
13268 	hme8blk_sz = roundup(HME8BLK_SZ, sizeof (int64_t));
13269 	hme1blk_sz = roundup(HME1BLK_SZ, sizeof (int64_t));
13270 
13271 	nucleus_hblk8.list = (void *)addr;
13272 	nucleus_hblk8.index = 0;
13273 
13274 	/*
13275 	 * Use as much memory as possible for hblk8's since we
13276 	 * expect all bop_alloc'ed memory to be allocated in 8k chunks.
13277 	 * We need to hold back enough space for the hblk1's which
13278 	 * we'll allocate next.
13279 	 */
13280 	hblk8_bound = size - (nhblk1 * hme1blk_sz) - hme8blk_sz;
13281 	for (i = 0; i <= hblk8_bound; i += hme8blk_sz, j++) {
13282 		hmeblkp = (struct hme_blk *)addr;
13283 		addr += hme8blk_sz;
13284 		hmeblkp->hblk_nuc_bit = 1;
13285 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13286 	}
13287 	nucleus_hblk8.len = j;
13288 	ASSERT(j >= nhblk8);
13289 	SFMMU_STAT_ADD(sf_hblk8_ncreate, j);
13290 
13291 	nucleus_hblk1.list = (void *)addr;
13292 	nucleus_hblk1.index = 0;
13293 	for (; i <= (size - hme1blk_sz); i += hme1blk_sz, k++) {
13294 		hmeblkp = (struct hme_blk *)addr;
13295 		addr += hme1blk_sz;
13296 		hmeblkp->hblk_nuc_bit = 1;
13297 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13298 	}
13299 	ASSERT(k >= nhblk1);
13300 	nucleus_hblk1.len = k;
13301 	SFMMU_STAT_ADD(sf_hblk1_ncreate, k);
13302 }
13303 
13304 /*
13305  * This function is currently not supported on this platform. For what
13306  * it's supposed to do, see hat.c and hat_srmmu.c
13307  */
13308 /* ARGSUSED */
13309 faultcode_t
13310 hat_softlock(struct hat *hat, caddr_t addr, size_t *lenp, page_t **ppp,
13311     uint_t flags)
13312 {
13313 	ASSERT(hat->sfmmu_xhat_provider == NULL);
13314 	return (FC_NOSUPPORT);
13315 }
13316 
13317 /*
13318  * Searchs the mapping list of the page for a mapping of the same size. If not
13319  * found the corresponding bit is cleared in the p_index field. When large
13320  * pages are more prevalent in the system, we can maintain the mapping list
13321  * in order and we don't have to traverse the list each time. Just check the
13322  * next and prev entries, and if both are of different size, we clear the bit.
13323  */
13324 static void
13325 sfmmu_rm_large_mappings(page_t *pp, int ttesz)
13326 {
13327 	struct sf_hment *sfhmep;
13328 	struct hme_blk *hmeblkp;
13329 	int	index;
13330 	pgcnt_t	npgs;
13331 
13332 	ASSERT(ttesz > TTE8K);
13333 
13334 	ASSERT(sfmmu_mlist_held(pp));
13335 
13336 	ASSERT(PP_ISMAPPED_LARGE(pp));
13337 
13338 	/*
13339 	 * Traverse mapping list looking for another mapping of same size.
13340 	 * since we only want to clear index field if all mappings of
13341 	 * that size are gone.
13342 	 */
13343 
13344 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
13345 		if (IS_PAHME(sfhmep))
13346 			continue;
13347 		hmeblkp = sfmmu_hmetohblk(sfhmep);
13348 		if (hmeblkp->hblk_xhat_bit)
13349 			continue;
13350 		if (hme_size(sfhmep) == ttesz) {
13351 			/*
13352 			 * another mapping of the same size. don't clear index.
13353 			 */
13354 			return;
13355 		}
13356 	}
13357 
13358 	/*
13359 	 * Clear the p_index bit for large page.
13360 	 */
13361 	index = PAGESZ_TO_INDEX(ttesz);
13362 	npgs = TTEPAGES(ttesz);
13363 	while (npgs-- > 0) {
13364 		ASSERT(pp->p_index & index);
13365 		pp->p_index &= ~index;
13366 		pp = PP_PAGENEXT(pp);
13367 	}
13368 }
13369 
13370 /*
13371  * return supported features
13372  */
13373 /* ARGSUSED */
13374 int
13375 hat_supported(enum hat_features feature, void *arg)
13376 {
13377 	switch (feature) {
13378 	case    HAT_SHARED_PT:
13379 	case	HAT_DYNAMIC_ISM_UNMAP:
13380 	case	HAT_VMODSORT:
13381 		return (1);
13382 	case	HAT_SHARED_REGIONS:
13383 		if (shctx_on)
13384 			return (1);
13385 		else
13386 			return (0);
13387 	default:
13388 		return (0);
13389 	}
13390 }
13391 
13392 void
13393 hat_enter(struct hat *hat)
13394 {
13395 	hatlock_t	*hatlockp;
13396 
13397 	if (hat != ksfmmup) {
13398 		hatlockp = TSB_HASH(hat);
13399 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
13400 	}
13401 }
13402 
13403 void
13404 hat_exit(struct hat *hat)
13405 {
13406 	hatlock_t	*hatlockp;
13407 
13408 	if (hat != ksfmmup) {
13409 		hatlockp = TSB_HASH(hat);
13410 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
13411 	}
13412 }
13413 
13414 /*ARGSUSED*/
13415 void
13416 hat_reserve(struct as *as, caddr_t addr, size_t len)
13417 {
13418 }
13419 
13420 static void
13421 hat_kstat_init(void)
13422 {
13423 	kstat_t *ksp;
13424 
13425 	ksp = kstat_create("unix", 0, "sfmmu_global_stat", "hat",
13426 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_global_stat),
13427 	    KSTAT_FLAG_VIRTUAL);
13428 	if (ksp) {
13429 		ksp->ks_data = (void *) &sfmmu_global_stat;
13430 		kstat_install(ksp);
13431 	}
13432 	ksp = kstat_create("unix", 0, "sfmmu_tsbsize_stat", "hat",
13433 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_tsbsize_stat),
13434 	    KSTAT_FLAG_VIRTUAL);
13435 	if (ksp) {
13436 		ksp->ks_data = (void *) &sfmmu_tsbsize_stat;
13437 		kstat_install(ksp);
13438 	}
13439 	ksp = kstat_create("unix", 0, "sfmmu_percpu_stat", "hat",
13440 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_percpu_stat) * NCPU,
13441 	    KSTAT_FLAG_WRITABLE);
13442 	if (ksp) {
13443 		ksp->ks_update = sfmmu_kstat_percpu_update;
13444 		kstat_install(ksp);
13445 	}
13446 }
13447 
13448 /* ARGSUSED */
13449 static int
13450 sfmmu_kstat_percpu_update(kstat_t *ksp, int rw)
13451 {
13452 	struct sfmmu_percpu_stat *cpu_kstat = ksp->ks_data;
13453 	struct tsbmiss *tsbm = tsbmiss_area;
13454 	struct kpmtsbm *kpmtsbm = kpmtsbm_area;
13455 	int i;
13456 
13457 	ASSERT(cpu_kstat);
13458 	if (rw == KSTAT_READ) {
13459 		for (i = 0; i < NCPU; cpu_kstat++, tsbm++, kpmtsbm++, i++) {
13460 			cpu_kstat->sf_itlb_misses = 0;
13461 			cpu_kstat->sf_dtlb_misses = 0;
13462 			cpu_kstat->sf_utsb_misses = tsbm->utsb_misses -
13463 			    tsbm->uprot_traps;
13464 			cpu_kstat->sf_ktsb_misses = tsbm->ktsb_misses +
13465 			    kpmtsbm->kpm_tsb_misses - tsbm->kprot_traps;
13466 			cpu_kstat->sf_tsb_hits = 0;
13467 			cpu_kstat->sf_umod_faults = tsbm->uprot_traps;
13468 			cpu_kstat->sf_kmod_faults = tsbm->kprot_traps;
13469 		}
13470 	} else {
13471 		/* KSTAT_WRITE is used to clear stats */
13472 		for (i = 0; i < NCPU; tsbm++, kpmtsbm++, i++) {
13473 			tsbm->utsb_misses = 0;
13474 			tsbm->ktsb_misses = 0;
13475 			tsbm->uprot_traps = 0;
13476 			tsbm->kprot_traps = 0;
13477 			kpmtsbm->kpm_dtlb_misses = 0;
13478 			kpmtsbm->kpm_tsb_misses = 0;
13479 		}
13480 	}
13481 	return (0);
13482 }
13483 
13484 #ifdef	DEBUG
13485 
13486 tte_t  *gorig[NCPU], *gcur[NCPU], *gnew[NCPU];
13487 
13488 /*
13489  * A tte checker. *orig_old is the value we read before cas.
13490  *	*cur is the value returned by cas.
13491  *	*new is the desired value when we do the cas.
13492  *
13493  *	*hmeblkp is currently unused.
13494  */
13495 
13496 /* ARGSUSED */
13497 void
13498 chk_tte(tte_t *orig_old, tte_t *cur, tte_t *new, struct hme_blk *hmeblkp)
13499 {
13500 	pfn_t i, j, k;
13501 	int cpuid = CPU->cpu_id;
13502 
13503 	gorig[cpuid] = orig_old;
13504 	gcur[cpuid] = cur;
13505 	gnew[cpuid] = new;
13506 
13507 #ifdef lint
13508 	hmeblkp = hmeblkp;
13509 #endif
13510 
13511 	if (TTE_IS_VALID(orig_old)) {
13512 		if (TTE_IS_VALID(cur)) {
13513 			i = TTE_TO_TTEPFN(orig_old);
13514 			j = TTE_TO_TTEPFN(cur);
13515 			k = TTE_TO_TTEPFN(new);
13516 			if (i != j) {
13517 				/* remap error? */
13518 				panic("chk_tte: bad pfn, 0x%lx, 0x%lx", i, j);
13519 			}
13520 
13521 			if (i != k) {
13522 				/* remap error? */
13523 				panic("chk_tte: bad pfn2, 0x%lx, 0x%lx", i, k);
13524 			}
13525 		} else {
13526 			if (TTE_IS_VALID(new)) {
13527 				panic("chk_tte: invalid cur? ");
13528 			}
13529 
13530 			i = TTE_TO_TTEPFN(orig_old);
13531 			k = TTE_TO_TTEPFN(new);
13532 			if (i != k) {
13533 				panic("chk_tte: bad pfn3, 0x%lx, 0x%lx", i, k);
13534 			}
13535 		}
13536 	} else {
13537 		if (TTE_IS_VALID(cur)) {
13538 			j = TTE_TO_TTEPFN(cur);
13539 			if (TTE_IS_VALID(new)) {
13540 				k = TTE_TO_TTEPFN(new);
13541 				if (j != k) {
13542 					panic("chk_tte: bad pfn4, 0x%lx, 0x%lx",
13543 					    j, k);
13544 				}
13545 			} else {
13546 				panic("chk_tte: why here?");
13547 			}
13548 		} else {
13549 			if (!TTE_IS_VALID(new)) {
13550 				panic("chk_tte: why here2 ?");
13551 			}
13552 		}
13553 	}
13554 }
13555 
13556 #endif /* DEBUG */
13557 
13558 extern void prefetch_tsbe_read(struct tsbe *);
13559 extern void prefetch_tsbe_write(struct tsbe *);
13560 
13561 
13562 /*
13563  * We want to prefetch 7 cache lines ahead for our read prefetch.  This gives
13564  * us optimal performance on Cheetah+.  You can only have 8 outstanding
13565  * prefetches at any one time, so we opted for 7 read prefetches and 1 write
13566  * prefetch to make the most utilization of the prefetch capability.
13567  */
13568 #define	TSBE_PREFETCH_STRIDE (7)
13569 
13570 void
13571 sfmmu_copy_tsb(struct tsb_info *old_tsbinfo, struct tsb_info *new_tsbinfo)
13572 {
13573 	int old_bytes = TSB_BYTES(old_tsbinfo->tsb_szc);
13574 	int new_bytes = TSB_BYTES(new_tsbinfo->tsb_szc);
13575 	int old_entries = TSB_ENTRIES(old_tsbinfo->tsb_szc);
13576 	int new_entries = TSB_ENTRIES(new_tsbinfo->tsb_szc);
13577 	struct tsbe *old;
13578 	struct tsbe *new;
13579 	struct tsbe *new_base = (struct tsbe *)new_tsbinfo->tsb_va;
13580 	uint64_t va;
13581 	int new_offset;
13582 	int i;
13583 	int vpshift;
13584 	int last_prefetch;
13585 
13586 	if (old_bytes == new_bytes) {
13587 		bcopy(old_tsbinfo->tsb_va, new_tsbinfo->tsb_va, new_bytes);
13588 	} else {
13589 
13590 		/*
13591 		 * A TSBE is 16 bytes which means there are four TSBE's per
13592 		 * P$ line (64 bytes), thus every 4 TSBE's we prefetch.
13593 		 */
13594 		old = (struct tsbe *)old_tsbinfo->tsb_va;
13595 		last_prefetch = old_entries - (4*(TSBE_PREFETCH_STRIDE+1));
13596 		for (i = 0; i < old_entries; i++, old++) {
13597 			if (((i & (4-1)) == 0) && (i < last_prefetch))
13598 				prefetch_tsbe_read(old);
13599 			if (!old->tte_tag.tag_invalid) {
13600 				/*
13601 				 * We have a valid TTE to remap.  Check the
13602 				 * size.  We won't remap 64K or 512K TTEs
13603 				 * because they span more than one TSB entry
13604 				 * and are indexed using an 8K virt. page.
13605 				 * Ditto for 32M and 256M TTEs.
13606 				 */
13607 				if (TTE_CSZ(&old->tte_data) == TTE64K ||
13608 				    TTE_CSZ(&old->tte_data) == TTE512K)
13609 					continue;
13610 				if (mmu_page_sizes == max_mmu_page_sizes) {
13611 					if (TTE_CSZ(&old->tte_data) == TTE32M ||
13612 					    TTE_CSZ(&old->tte_data) == TTE256M)
13613 						continue;
13614 				}
13615 
13616 				/* clear the lower 22 bits of the va */
13617 				va = *(uint64_t *)old << 22;
13618 				/* turn va into a virtual pfn */
13619 				va >>= 22 - TSB_START_SIZE;
13620 				/*
13621 				 * or in bits from the offset in the tsb
13622 				 * to get the real virtual pfn. These
13623 				 * correspond to bits [21:13] in the va
13624 				 */
13625 				vpshift =
13626 				    TTE_BSZS_SHIFT(TTE_CSZ(&old->tte_data)) &
13627 				    0x1ff;
13628 				va |= (i << vpshift);
13629 				va >>= vpshift;
13630 				new_offset = va & (new_entries - 1);
13631 				new = new_base + new_offset;
13632 				prefetch_tsbe_write(new);
13633 				*new = *old;
13634 			}
13635 		}
13636 	}
13637 }
13638 
13639 /*
13640  * unused in sfmmu
13641  */
13642 void
13643 hat_dump(void)
13644 {
13645 }
13646 
13647 /*
13648  * Called when a thread is exiting and we have switched to the kernel address
13649  * space.  Perform the same VM initialization resume() uses when switching
13650  * processes.
13651  *
13652  * Note that sfmmu_load_mmustate() is currently a no-op for kernel threads, but
13653  * we call it anyway in case the semantics change in the future.
13654  */
13655 /*ARGSUSED*/
13656 void
13657 hat_thread_exit(kthread_t *thd)
13658 {
13659 	uint_t pgsz_cnum;
13660 	uint_t pstate_save;
13661 
13662 	ASSERT(thd->t_procp->p_as == &kas);
13663 
13664 	pgsz_cnum = KCONTEXT;
13665 #ifdef sun4u
13666 	pgsz_cnum |= (ksfmmup->sfmmu_cext << CTXREG_EXT_SHIFT);
13667 #endif
13668 
13669 	/*
13670 	 * Note that sfmmu_load_mmustate() is currently a no-op for
13671 	 * kernel threads. We need to disable interrupts here,
13672 	 * simply because otherwise sfmmu_load_mmustate() would panic
13673 	 * if the caller does not disable interrupts.
13674 	 */
13675 	pstate_save = sfmmu_disable_intrs();
13676 
13677 	/* Compatibility Note: hw takes care of MMU_SCONTEXT1 */
13678 	sfmmu_setctx_sec(pgsz_cnum);
13679 	sfmmu_load_mmustate(ksfmmup);
13680 	sfmmu_enable_intrs(pstate_save);
13681 }
13682 
13683 
13684 /*
13685  * SRD support
13686  */
13687 #define	SRD_HASH_FUNCTION(vp)	(((((uintptr_t)(vp)) >> 4) ^ \
13688 				    (((uintptr_t)(vp)) >> 11)) & \
13689 				    srd_hashmask)
13690 
13691 /*
13692  * Attach the process to the srd struct associated with the exec vnode
13693  * from which the process is started.
13694  */
13695 void
13696 hat_join_srd(struct hat *sfmmup, vnode_t *evp)
13697 {
13698 	uint_t hash = SRD_HASH_FUNCTION(evp);
13699 	sf_srd_t *srdp;
13700 	sf_srd_t *newsrdp;
13701 
13702 	ASSERT(sfmmup != ksfmmup);
13703 	ASSERT(sfmmup->sfmmu_srdp == NULL);
13704 
13705 	if (!shctx_on) {
13706 		return;
13707 	}
13708 
13709 	VN_HOLD(evp);
13710 
13711 	if (srd_buckets[hash].srdb_srdp != NULL) {
13712 		mutex_enter(&srd_buckets[hash].srdb_lock);
13713 		for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13714 		    srdp = srdp->srd_hash) {
13715 			if (srdp->srd_evp == evp) {
13716 				ASSERT(srdp->srd_refcnt >= 0);
13717 				sfmmup->sfmmu_srdp = srdp;
13718 				atomic_add_32(
13719 				    (volatile uint_t *)&srdp->srd_refcnt, 1);
13720 				mutex_exit(&srd_buckets[hash].srdb_lock);
13721 				return;
13722 			}
13723 		}
13724 		mutex_exit(&srd_buckets[hash].srdb_lock);
13725 	}
13726 	newsrdp = kmem_cache_alloc(srd_cache, KM_SLEEP);
13727 	ASSERT(newsrdp->srd_next_ismrid == 0 && newsrdp->srd_next_hmerid == 0);
13728 
13729 	newsrdp->srd_evp = evp;
13730 	newsrdp->srd_refcnt = 1;
13731 	newsrdp->srd_hmergnfree = NULL;
13732 	newsrdp->srd_ismrgnfree = NULL;
13733 
13734 	mutex_enter(&srd_buckets[hash].srdb_lock);
13735 	for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13736 	    srdp = srdp->srd_hash) {
13737 		if (srdp->srd_evp == evp) {
13738 			ASSERT(srdp->srd_refcnt >= 0);
13739 			sfmmup->sfmmu_srdp = srdp;
13740 			atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
13741 			mutex_exit(&srd_buckets[hash].srdb_lock);
13742 			kmem_cache_free(srd_cache, newsrdp);
13743 			return;
13744 		}
13745 	}
13746 	newsrdp->srd_hash = srd_buckets[hash].srdb_srdp;
13747 	srd_buckets[hash].srdb_srdp = newsrdp;
13748 	sfmmup->sfmmu_srdp = newsrdp;
13749 
13750 	mutex_exit(&srd_buckets[hash].srdb_lock);
13751 
13752 }
13753 
13754 static void
13755 sfmmu_leave_srd(sfmmu_t *sfmmup)
13756 {
13757 	vnode_t *evp;
13758 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13759 	uint_t hash;
13760 	sf_srd_t **prev_srdpp;
13761 	sf_region_t *rgnp;
13762 	sf_region_t *nrgnp;
13763 #ifdef DEBUG
13764 	int rgns = 0;
13765 #endif
13766 	int i;
13767 
13768 	ASSERT(sfmmup != ksfmmup);
13769 	ASSERT(srdp != NULL);
13770 	ASSERT(srdp->srd_refcnt > 0);
13771 	ASSERT(sfmmup->sfmmu_scdp == NULL);
13772 	ASSERT(sfmmup->sfmmu_free == 1);
13773 
13774 	sfmmup->sfmmu_srdp = NULL;
13775 	evp = srdp->srd_evp;
13776 	ASSERT(evp != NULL);
13777 	if (atomic_add_32_nv(
13778 	    (volatile uint_t *)&srdp->srd_refcnt, -1)) {
13779 		VN_RELE(evp);
13780 		return;
13781 	}
13782 
13783 	hash = SRD_HASH_FUNCTION(evp);
13784 	mutex_enter(&srd_buckets[hash].srdb_lock);
13785 	for (prev_srdpp = &srd_buckets[hash].srdb_srdp;
13786 	    (srdp = *prev_srdpp) != NULL; prev_srdpp = &srdp->srd_hash) {
13787 		if (srdp->srd_evp == evp) {
13788 			break;
13789 		}
13790 	}
13791 	if (srdp == NULL || srdp->srd_refcnt) {
13792 		mutex_exit(&srd_buckets[hash].srdb_lock);
13793 		VN_RELE(evp);
13794 		return;
13795 	}
13796 	*prev_srdpp = srdp->srd_hash;
13797 	mutex_exit(&srd_buckets[hash].srdb_lock);
13798 
13799 	ASSERT(srdp->srd_refcnt == 0);
13800 	VN_RELE(evp);
13801 
13802 #ifdef DEBUG
13803 	for (i = 0; i < SFMMU_MAX_REGION_BUCKETS; i++) {
13804 		ASSERT(srdp->srd_rgnhash[i] == NULL);
13805 	}
13806 #endif /* DEBUG */
13807 
13808 	/* free each hme regions in the srd */
13809 	for (rgnp = srdp->srd_hmergnfree; rgnp != NULL; rgnp = nrgnp) {
13810 		nrgnp = rgnp->rgn_next;
13811 		ASSERT(rgnp->rgn_id < srdp->srd_next_hmerid);
13812 		ASSERT(rgnp->rgn_refcnt == 0);
13813 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13814 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13815 		ASSERT(rgnp->rgn_hmeflags == 0);
13816 		ASSERT(srdp->srd_hmergnp[rgnp->rgn_id] == rgnp);
13817 #ifdef DEBUG
13818 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13819 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13820 		}
13821 		rgns++;
13822 #endif /* DEBUG */
13823 		kmem_cache_free(region_cache, rgnp);
13824 	}
13825 	ASSERT(rgns == srdp->srd_next_hmerid);
13826 
13827 #ifdef DEBUG
13828 	rgns = 0;
13829 #endif
13830 	/* free each ism rgns in the srd */
13831 	for (rgnp = srdp->srd_ismrgnfree; rgnp != NULL; rgnp = nrgnp) {
13832 		nrgnp = rgnp->rgn_next;
13833 		ASSERT(rgnp->rgn_id < srdp->srd_next_ismrid);
13834 		ASSERT(rgnp->rgn_refcnt == 0);
13835 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13836 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13837 		ASSERT(srdp->srd_ismrgnp[rgnp->rgn_id] == rgnp);
13838 #ifdef DEBUG
13839 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13840 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13841 		}
13842 		rgns++;
13843 #endif /* DEBUG */
13844 		kmem_cache_free(region_cache, rgnp);
13845 	}
13846 	ASSERT(rgns == srdp->srd_next_ismrid);
13847 	ASSERT(srdp->srd_ismbusyrgns == 0);
13848 	ASSERT(srdp->srd_hmebusyrgns == 0);
13849 
13850 	srdp->srd_next_ismrid = 0;
13851 	srdp->srd_next_hmerid = 0;
13852 
13853 	bzero((void *)srdp->srd_ismrgnp,
13854 	    sizeof (sf_region_t *) * SFMMU_MAX_ISM_REGIONS);
13855 	bzero((void *)srdp->srd_hmergnp,
13856 	    sizeof (sf_region_t *) * SFMMU_MAX_HME_REGIONS);
13857 
13858 	ASSERT(srdp->srd_scdp == NULL);
13859 	kmem_cache_free(srd_cache, srdp);
13860 }
13861 
13862 /* ARGSUSED */
13863 static int
13864 sfmmu_srdcache_constructor(void *buf, void *cdrarg, int kmflags)
13865 {
13866 	sf_srd_t *srdp = (sf_srd_t *)buf;
13867 	bzero(buf, sizeof (*srdp));
13868 
13869 	mutex_init(&srdp->srd_mutex, NULL, MUTEX_DEFAULT, NULL);
13870 	mutex_init(&srdp->srd_scd_mutex, NULL, MUTEX_DEFAULT, NULL);
13871 	return (0);
13872 }
13873 
13874 /* ARGSUSED */
13875 static void
13876 sfmmu_srdcache_destructor(void *buf, void *cdrarg)
13877 {
13878 	sf_srd_t *srdp = (sf_srd_t *)buf;
13879 
13880 	mutex_destroy(&srdp->srd_mutex);
13881 	mutex_destroy(&srdp->srd_scd_mutex);
13882 }
13883 
13884 /*
13885  * The caller makes sure hat_join_region()/hat_leave_region() can't be called
13886  * at the same time for the same process and address range. This is ensured by
13887  * the fact that address space is locked as writer when a process joins the
13888  * regions. Therefore there's no need to hold an srd lock during the entire
13889  * execution of hat_join_region()/hat_leave_region().
13890  */
13891 
13892 #define	RGN_HASH_FUNCTION(obj)	(((((uintptr_t)(obj)) >> 4) ^ \
13893 				    (((uintptr_t)(obj)) >> 11)) & \
13894 					srd_rgn_hashmask)
13895 /*
13896  * This routine implements the shared context functionality required when
13897  * attaching a segment to an address space. It must be called from
13898  * hat_share() for D(ISM) segments and from segvn_create() for segments
13899  * with the MAP_PRIVATE and MAP_TEXT flags set. It returns a region_cookie
13900  * which is saved in the private segment data for hme segments and
13901  * the ism_map structure for ism segments.
13902  */
13903 hat_region_cookie_t
13904 hat_join_region(struct hat *sfmmup,
13905 	caddr_t r_saddr,
13906 	size_t r_size,
13907 	void *r_obj,
13908 	u_offset_t r_objoff,
13909 	uchar_t r_perm,
13910 	uchar_t r_pgszc,
13911 	hat_rgn_cb_func_t r_cb_function,
13912 	uint_t flags)
13913 {
13914 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13915 	uint_t rhash;
13916 	uint_t rid;
13917 	hatlock_t *hatlockp;
13918 	sf_region_t *rgnp;
13919 	sf_region_t *new_rgnp = NULL;
13920 	int i;
13921 	uint16_t *nextidp;
13922 	sf_region_t **freelistp;
13923 	int maxids;
13924 	sf_region_t **rarrp;
13925 	uint16_t *busyrgnsp;
13926 	ulong_t rttecnt;
13927 	uchar_t tteflag;
13928 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
13929 	int text = (r_type == HAT_REGION_TEXT);
13930 
13931 	if (srdp == NULL || r_size == 0) {
13932 		return (HAT_INVALID_REGION_COOKIE);
13933 	}
13934 
13935 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
13936 	ASSERT(sfmmup != ksfmmup);
13937 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
13938 	ASSERT(srdp->srd_refcnt > 0);
13939 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
13940 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
13941 	ASSERT(r_pgszc < mmu_page_sizes);
13942 	if (!IS_P2ALIGNED(r_saddr, TTEBYTES(r_pgszc)) ||
13943 	    !IS_P2ALIGNED(r_size, TTEBYTES(r_pgszc))) {
13944 		panic("hat_join_region: region addr or size is not aligned\n");
13945 	}
13946 
13947 
13948 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
13949 	    SFMMU_REGION_HME;
13950 	/*
13951 	 * Currently only support shared hmes for the read only main text
13952 	 * region.
13953 	 */
13954 	if (r_type == SFMMU_REGION_HME && ((r_obj != srdp->srd_evp) ||
13955 	    (r_perm & PROT_WRITE))) {
13956 		return (HAT_INVALID_REGION_COOKIE);
13957 	}
13958 
13959 	rhash = RGN_HASH_FUNCTION(r_obj);
13960 
13961 	if (r_type == SFMMU_REGION_ISM) {
13962 		nextidp = &srdp->srd_next_ismrid;
13963 		freelistp = &srdp->srd_ismrgnfree;
13964 		maxids = SFMMU_MAX_ISM_REGIONS;
13965 		rarrp = srdp->srd_ismrgnp;
13966 		busyrgnsp = &srdp->srd_ismbusyrgns;
13967 	} else {
13968 		nextidp = &srdp->srd_next_hmerid;
13969 		freelistp = &srdp->srd_hmergnfree;
13970 		maxids = SFMMU_MAX_HME_REGIONS;
13971 		rarrp = srdp->srd_hmergnp;
13972 		busyrgnsp = &srdp->srd_hmebusyrgns;
13973 	}
13974 
13975 	mutex_enter(&srdp->srd_mutex);
13976 
13977 	for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
13978 	    rgnp = rgnp->rgn_hash) {
13979 		if (rgnp->rgn_saddr == r_saddr && rgnp->rgn_size == r_size &&
13980 		    rgnp->rgn_obj == r_obj && rgnp->rgn_objoff == r_objoff &&
13981 		    rgnp->rgn_perm == r_perm && rgnp->rgn_pgszc == r_pgszc) {
13982 			break;
13983 		}
13984 	}
13985 
13986 rfound:
13987 	if (rgnp != NULL) {
13988 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
13989 		ASSERT(rgnp->rgn_cb_function == r_cb_function);
13990 		ASSERT(rgnp->rgn_refcnt >= 0);
13991 		rid = rgnp->rgn_id;
13992 		ASSERT(rid < maxids);
13993 		ASSERT(rarrp[rid] == rgnp);
13994 		ASSERT(rid < *nextidp);
13995 		atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
13996 		mutex_exit(&srdp->srd_mutex);
13997 		if (new_rgnp != NULL) {
13998 			kmem_cache_free(region_cache, new_rgnp);
13999 		}
14000 		if (r_type == SFMMU_REGION_HME) {
14001 			int myjoin =
14002 			    (sfmmup == astosfmmu(curthread->t_procp->p_as));
14003 
14004 			sfmmu_link_to_hmeregion(sfmmup, rgnp);
14005 			/*
14006 			 * bitmap should be updated after linking sfmmu on
14007 			 * region list so that pageunload() doesn't skip
14008 			 * TSB/TLB flush. As soon as bitmap is updated another
14009 			 * thread in this process can already start accessing
14010 			 * this region.
14011 			 */
14012 			/*
14013 			 * Normally ttecnt accounting is done as part of
14014 			 * pagefault handling. But a process may not take any
14015 			 * pagefaults on shared hmeblks created by some other
14016 			 * process. To compensate for this assume that the
14017 			 * entire region will end up faulted in using
14018 			 * the region's pagesize.
14019 			 *
14020 			 */
14021 			if (r_pgszc > TTE8K) {
14022 				tteflag = 1 << r_pgszc;
14023 				if (disable_large_pages & tteflag) {
14024 					tteflag = 0;
14025 				}
14026 			} else {
14027 				tteflag = 0;
14028 			}
14029 			if (tteflag && !(sfmmup->sfmmu_rtteflags & tteflag)) {
14030 				hatlockp = sfmmu_hat_enter(sfmmup);
14031 				sfmmup->sfmmu_rtteflags |= tteflag;
14032 				sfmmu_hat_exit(hatlockp);
14033 			}
14034 			hatlockp = sfmmu_hat_enter(sfmmup);
14035 
14036 			/*
14037 			 * Preallocate 1/4 of ttecnt's in 8K TSB for >= 4M
14038 			 * region to allow for large page allocation failure.
14039 			 */
14040 			if (r_pgszc >= TTE4M) {
14041 				sfmmup->sfmmu_tsb0_4minflcnt +=
14042 				    r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14043 			}
14044 
14045 			/* update sfmmu_ttecnt with the shme rgn ttecnt */
14046 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14047 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14048 			    rttecnt);
14049 
14050 			if (text && r_pgszc >= TTE4M &&
14051 			    (tteflag || ((disable_large_pages >> TTE4M) &
14052 			    ((1 << (r_pgszc - TTE4M + 1)) - 1))) &&
14053 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
14054 				SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
14055 			}
14056 
14057 			sfmmu_hat_exit(hatlockp);
14058 			/*
14059 			 * On Panther we need to make sure TLB is programmed
14060 			 * to accept 32M/256M pages.  Call
14061 			 * sfmmu_check_page_sizes() now to make sure TLB is
14062 			 * setup before making hmeregions visible to other
14063 			 * threads.
14064 			 */
14065 			sfmmu_check_page_sizes(sfmmup, 1);
14066 			hatlockp = sfmmu_hat_enter(sfmmup);
14067 			SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14068 
14069 			/*
14070 			 * if context is invalid tsb miss exception code will
14071 			 * call sfmmu_check_page_sizes() and update tsbmiss
14072 			 * area later.
14073 			 */
14074 			kpreempt_disable();
14075 			if (myjoin &&
14076 			    (sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
14077 			    != INVALID_CONTEXT)) {
14078 				struct tsbmiss *tsbmp;
14079 
14080 				tsbmp = &tsbmiss_area[CPU->cpu_id];
14081 				ASSERT(sfmmup == tsbmp->usfmmup);
14082 				BT_SET(tsbmp->shmermap, rid);
14083 				if (r_pgszc > TTE64K) {
14084 					tsbmp->uhat_rtteflags |= tteflag;
14085 				}
14086 
14087 			}
14088 			kpreempt_enable();
14089 
14090 			sfmmu_hat_exit(hatlockp);
14091 			ASSERT((hat_region_cookie_t)((uint64_t)rid) !=
14092 			    HAT_INVALID_REGION_COOKIE);
14093 		} else {
14094 			hatlockp = sfmmu_hat_enter(sfmmup);
14095 			SF_RGNMAP_ADD(sfmmup->sfmmu_ismregion_map, rid);
14096 			sfmmu_hat_exit(hatlockp);
14097 		}
14098 		ASSERT(rid < maxids);
14099 
14100 		if (r_type == SFMMU_REGION_ISM) {
14101 			sfmmu_find_scd(sfmmup);
14102 		}
14103 		return ((hat_region_cookie_t)((uint64_t)rid));
14104 	}
14105 
14106 	ASSERT(new_rgnp == NULL);
14107 
14108 	if (*busyrgnsp >= maxids) {
14109 		mutex_exit(&srdp->srd_mutex);
14110 		return (HAT_INVALID_REGION_COOKIE);
14111 	}
14112 
14113 	ASSERT(MUTEX_HELD(&srdp->srd_mutex));
14114 	if (*freelistp != NULL) {
14115 		rgnp = *freelistp;
14116 		*freelistp = rgnp->rgn_next;
14117 		ASSERT(rgnp->rgn_id < *nextidp);
14118 		ASSERT(rgnp->rgn_id < maxids);
14119 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
14120 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK)
14121 		    == r_type);
14122 		ASSERT(rarrp[rgnp->rgn_id] == rgnp);
14123 		ASSERT(rgnp->rgn_hmeflags == 0);
14124 	} else {
14125 		/*
14126 		 * release local locks before memory allocation.
14127 		 */
14128 		mutex_exit(&srdp->srd_mutex);
14129 
14130 		new_rgnp = kmem_cache_alloc(region_cache, KM_SLEEP);
14131 
14132 		mutex_enter(&srdp->srd_mutex);
14133 		for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
14134 		    rgnp = rgnp->rgn_hash) {
14135 			if (rgnp->rgn_saddr == r_saddr &&
14136 			    rgnp->rgn_size == r_size &&
14137 			    rgnp->rgn_obj == r_obj &&
14138 			    rgnp->rgn_objoff == r_objoff &&
14139 			    rgnp->rgn_perm == r_perm &&
14140 			    rgnp->rgn_pgszc == r_pgszc) {
14141 				break;
14142 			}
14143 		}
14144 		if (rgnp != NULL) {
14145 			goto rfound;
14146 		}
14147 
14148 		if (*nextidp >= maxids) {
14149 			mutex_exit(&srdp->srd_mutex);
14150 			goto fail;
14151 		}
14152 		rgnp = new_rgnp;
14153 		new_rgnp = NULL;
14154 		rgnp->rgn_id = (*nextidp)++;
14155 		ASSERT(rgnp->rgn_id < maxids);
14156 		ASSERT(rarrp[rgnp->rgn_id] == NULL);
14157 		rarrp[rgnp->rgn_id] = rgnp;
14158 	}
14159 
14160 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14161 	ASSERT(rgnp->rgn_hmeflags == 0);
14162 #ifdef DEBUG
14163 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14164 		ASSERT(rgnp->rgn_ttecnt[i] == 0);
14165 	}
14166 #endif
14167 	rgnp->rgn_saddr = r_saddr;
14168 	rgnp->rgn_size = r_size;
14169 	rgnp->rgn_obj = r_obj;
14170 	rgnp->rgn_objoff = r_objoff;
14171 	rgnp->rgn_perm = r_perm;
14172 	rgnp->rgn_pgszc = r_pgszc;
14173 	rgnp->rgn_flags = r_type;
14174 	rgnp->rgn_refcnt = 0;
14175 	rgnp->rgn_cb_function = r_cb_function;
14176 	rgnp->rgn_hash = srdp->srd_rgnhash[rhash];
14177 	srdp->srd_rgnhash[rhash] = rgnp;
14178 	(*busyrgnsp)++;
14179 	ASSERT(*busyrgnsp <= maxids);
14180 	goto rfound;
14181 
14182 fail:
14183 	ASSERT(new_rgnp != NULL);
14184 	kmem_cache_free(region_cache, new_rgnp);
14185 	return (HAT_INVALID_REGION_COOKIE);
14186 }
14187 
14188 /*
14189  * This function implements the shared context functionality required
14190  * when detaching a segment from an address space. It must be called
14191  * from hat_unshare() for all D(ISM) segments and from segvn_unmap(),
14192  * for segments with a valid region_cookie.
14193  * It will also be called from all seg_vn routines which change a
14194  * segment's attributes such as segvn_setprot(), segvn_setpagesize(),
14195  * segvn_clrszc() & segvn_advise(), as well as in the case of COW fault
14196  * from segvn_fault().
14197  */
14198 void
14199 hat_leave_region(struct hat *sfmmup, hat_region_cookie_t rcookie, uint_t flags)
14200 {
14201 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14202 	sf_scd_t *scdp;
14203 	uint_t rhash;
14204 	uint_t rid = (uint_t)((uint64_t)rcookie);
14205 	hatlock_t *hatlockp = NULL;
14206 	sf_region_t *rgnp;
14207 	sf_region_t **prev_rgnpp;
14208 	sf_region_t *cur_rgnp;
14209 	void *r_obj;
14210 	int i;
14211 	caddr_t	r_saddr;
14212 	caddr_t r_eaddr;
14213 	size_t	r_size;
14214 	uchar_t	r_pgszc;
14215 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
14216 
14217 	ASSERT(sfmmup != ksfmmup);
14218 	ASSERT(srdp != NULL);
14219 	ASSERT(srdp->srd_refcnt > 0);
14220 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
14221 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
14222 	ASSERT(!sfmmup->sfmmu_free || sfmmup->sfmmu_scdp == NULL);
14223 
14224 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
14225 	    SFMMU_REGION_HME;
14226 
14227 	if (r_type == SFMMU_REGION_ISM) {
14228 		ASSERT(SFMMU_IS_ISMRID_VALID(rid));
14229 		ASSERT(rid < SFMMU_MAX_ISM_REGIONS);
14230 		rgnp = srdp->srd_ismrgnp[rid];
14231 	} else {
14232 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14233 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14234 		rgnp = srdp->srd_hmergnp[rid];
14235 	}
14236 	ASSERT(rgnp != NULL);
14237 	ASSERT(rgnp->rgn_id == rid);
14238 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14239 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14240 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
14241 
14242 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
14243 	if (r_type == SFMMU_REGION_HME && sfmmup->sfmmu_as->a_xhat != NULL) {
14244 		xhat_unload_callback_all(sfmmup->sfmmu_as, rgnp->rgn_saddr,
14245 		    rgnp->rgn_size, 0, NULL);
14246 	}
14247 
14248 	if (sfmmup->sfmmu_free) {
14249 		ulong_t rttecnt;
14250 		r_pgszc = rgnp->rgn_pgszc;
14251 		r_size = rgnp->rgn_size;
14252 
14253 		ASSERT(sfmmup->sfmmu_scdp == NULL);
14254 		if (r_type == SFMMU_REGION_ISM) {
14255 			SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14256 		} else {
14257 			/* update shme rgns ttecnt in sfmmu_ttecnt */
14258 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14259 			ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14260 
14261 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14262 			    -rttecnt);
14263 
14264 			SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14265 		}
14266 	} else if (r_type == SFMMU_REGION_ISM) {
14267 		hatlockp = sfmmu_hat_enter(sfmmup);
14268 		ASSERT(rid < srdp->srd_next_ismrid);
14269 		SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14270 		scdp = sfmmup->sfmmu_scdp;
14271 		if (scdp != NULL &&
14272 		    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
14273 			sfmmu_leave_scd(sfmmup, r_type);
14274 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14275 		}
14276 		sfmmu_hat_exit(hatlockp);
14277 	} else {
14278 		ulong_t rttecnt;
14279 		r_pgszc = rgnp->rgn_pgszc;
14280 		r_saddr = rgnp->rgn_saddr;
14281 		r_size = rgnp->rgn_size;
14282 		r_eaddr = r_saddr + r_size;
14283 
14284 		ASSERT(r_type == SFMMU_REGION_HME);
14285 		hatlockp = sfmmu_hat_enter(sfmmup);
14286 		ASSERT(rid < srdp->srd_next_hmerid);
14287 		SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14288 
14289 		/*
14290 		 * If region is part of an SCD call sfmmu_leave_scd().
14291 		 * Otherwise if process is not exiting and has valid context
14292 		 * just drop the context on the floor to lose stale TLB
14293 		 * entries and force the update of tsb miss area to reflect
14294 		 * the new region map. After that clean our TSB entries.
14295 		 */
14296 		scdp = sfmmup->sfmmu_scdp;
14297 		if (scdp != NULL &&
14298 		    SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
14299 			sfmmu_leave_scd(sfmmup, r_type);
14300 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14301 		}
14302 		sfmmu_invalidate_ctx(sfmmup);
14303 
14304 		i = TTE8K;
14305 		while (i < mmu_page_sizes) {
14306 			if (rgnp->rgn_ttecnt[i] != 0) {
14307 				sfmmu_unload_tsb_range(sfmmup, r_saddr,
14308 				    r_eaddr, i);
14309 				if (i < TTE4M) {
14310 					i = TTE4M;
14311 					continue;
14312 				} else {
14313 					break;
14314 				}
14315 			}
14316 			i++;
14317 		}
14318 		/* Remove the preallocated 1/4 8k ttecnt for 4M regions. */
14319 		if (r_pgszc >= TTE4M) {
14320 			rttecnt = r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14321 			ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
14322 			    rttecnt);
14323 			sfmmup->sfmmu_tsb0_4minflcnt -= rttecnt;
14324 		}
14325 
14326 		/* update shme rgns ttecnt in sfmmu_ttecnt */
14327 		rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14328 		ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14329 		atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc], -rttecnt);
14330 
14331 		sfmmu_hat_exit(hatlockp);
14332 		if (scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
14333 			/* sfmmup left the scd, grow private tsb */
14334 			sfmmu_check_page_sizes(sfmmup, 1);
14335 		} else {
14336 			sfmmu_check_page_sizes(sfmmup, 0);
14337 		}
14338 	}
14339 
14340 	if (r_type == SFMMU_REGION_HME) {
14341 		sfmmu_unlink_from_hmeregion(sfmmup, rgnp);
14342 	}
14343 
14344 	r_obj = rgnp->rgn_obj;
14345 	if (atomic_add_32_nv((volatile uint_t *)&rgnp->rgn_refcnt, -1)) {
14346 		return;
14347 	}
14348 
14349 	/*
14350 	 * looks like nobody uses this region anymore. Free it.
14351 	 */
14352 	rhash = RGN_HASH_FUNCTION(r_obj);
14353 	mutex_enter(&srdp->srd_mutex);
14354 	for (prev_rgnpp = &srdp->srd_rgnhash[rhash];
14355 	    (cur_rgnp = *prev_rgnpp) != NULL;
14356 	    prev_rgnpp = &cur_rgnp->rgn_hash) {
14357 		if (cur_rgnp == rgnp && cur_rgnp->rgn_refcnt == 0) {
14358 			break;
14359 		}
14360 	}
14361 
14362 	if (cur_rgnp == NULL) {
14363 		mutex_exit(&srdp->srd_mutex);
14364 		return;
14365 	}
14366 
14367 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14368 	*prev_rgnpp = rgnp->rgn_hash;
14369 	if (r_type == SFMMU_REGION_ISM) {
14370 		rgnp->rgn_flags |= SFMMU_REGION_FREE;
14371 		ASSERT(rid < srdp->srd_next_ismrid);
14372 		rgnp->rgn_next = srdp->srd_ismrgnfree;
14373 		srdp->srd_ismrgnfree = rgnp;
14374 		ASSERT(srdp->srd_ismbusyrgns > 0);
14375 		srdp->srd_ismbusyrgns--;
14376 		mutex_exit(&srdp->srd_mutex);
14377 		return;
14378 	}
14379 	mutex_exit(&srdp->srd_mutex);
14380 
14381 	/*
14382 	 * Destroy region's hmeblks.
14383 	 */
14384 	sfmmu_unload_hmeregion(srdp, rgnp);
14385 
14386 	rgnp->rgn_hmeflags = 0;
14387 
14388 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14389 	ASSERT(rgnp->rgn_id == rid);
14390 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14391 		rgnp->rgn_ttecnt[i] = 0;
14392 	}
14393 	rgnp->rgn_flags |= SFMMU_REGION_FREE;
14394 	mutex_enter(&srdp->srd_mutex);
14395 	ASSERT(rid < srdp->srd_next_hmerid);
14396 	rgnp->rgn_next = srdp->srd_hmergnfree;
14397 	srdp->srd_hmergnfree = rgnp;
14398 	ASSERT(srdp->srd_hmebusyrgns > 0);
14399 	srdp->srd_hmebusyrgns--;
14400 	mutex_exit(&srdp->srd_mutex);
14401 }
14402 
14403 /*
14404  * For now only called for hmeblk regions and not for ISM regions.
14405  */
14406 void
14407 hat_dup_region(struct hat *sfmmup, hat_region_cookie_t rcookie)
14408 {
14409 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14410 	uint_t rid = (uint_t)((uint64_t)rcookie);
14411 	sf_region_t *rgnp;
14412 	sf_rgn_link_t *rlink;
14413 	sf_rgn_link_t *hrlink;
14414 	ulong_t	rttecnt;
14415 
14416 	ASSERT(sfmmup != ksfmmup);
14417 	ASSERT(srdp != NULL);
14418 	ASSERT(srdp->srd_refcnt > 0);
14419 
14420 	ASSERT(rid < srdp->srd_next_hmerid);
14421 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14422 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14423 
14424 	rgnp = srdp->srd_hmergnp[rid];
14425 	ASSERT(rgnp->rgn_refcnt > 0);
14426 	ASSERT(rgnp->rgn_id == rid);
14427 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == SFMMU_REGION_HME);
14428 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14429 
14430 	atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
14431 
14432 	/* LINTED: constant in conditional context */
14433 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 0);
14434 	ASSERT(rlink != NULL);
14435 	mutex_enter(&rgnp->rgn_mutex);
14436 	ASSERT(rgnp->rgn_sfmmu_head != NULL);
14437 	/* LINTED: constant in conditional context */
14438 	SFMMU_HMERID2RLINKP(rgnp->rgn_sfmmu_head, rid, hrlink, 0, 0);
14439 	ASSERT(hrlink != NULL);
14440 	ASSERT(hrlink->prev == NULL);
14441 	rlink->next = rgnp->rgn_sfmmu_head;
14442 	rlink->prev = NULL;
14443 	hrlink->prev = sfmmup;
14444 	/*
14445 	 * make sure rlink's next field is correct
14446 	 * before making this link visible.
14447 	 */
14448 	membar_stst();
14449 	rgnp->rgn_sfmmu_head = sfmmup;
14450 	mutex_exit(&rgnp->rgn_mutex);
14451 
14452 	/* update sfmmu_ttecnt with the shme rgn ttecnt */
14453 	rttecnt = rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
14454 	atomic_add_long(&sfmmup->sfmmu_ttecnt[rgnp->rgn_pgszc], rttecnt);
14455 	/* update tsb0 inflation count */
14456 	if (rgnp->rgn_pgszc >= TTE4M) {
14457 		sfmmup->sfmmu_tsb0_4minflcnt +=
14458 		    rgnp->rgn_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14459 	}
14460 	/*
14461 	 * Update regionid bitmask without hat lock since no other thread
14462 	 * can update this region bitmask right now.
14463 	 */
14464 	SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14465 }
14466 
14467 /* ARGSUSED */
14468 static int
14469 sfmmu_rgncache_constructor(void *buf, void *cdrarg, int kmflags)
14470 {
14471 	sf_region_t *rgnp = (sf_region_t *)buf;
14472 	bzero(buf, sizeof (*rgnp));
14473 
14474 	mutex_init(&rgnp->rgn_mutex, NULL, MUTEX_DEFAULT, NULL);
14475 
14476 	return (0);
14477 }
14478 
14479 /* ARGSUSED */
14480 static void
14481 sfmmu_rgncache_destructor(void *buf, void *cdrarg)
14482 {
14483 	sf_region_t *rgnp = (sf_region_t *)buf;
14484 	mutex_destroy(&rgnp->rgn_mutex);
14485 }
14486 
14487 static int
14488 sfrgnmap_isnull(sf_region_map_t *map)
14489 {
14490 	int i;
14491 
14492 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14493 		if (map->bitmap[i] != 0) {
14494 			return (0);
14495 		}
14496 	}
14497 	return (1);
14498 }
14499 
14500 static int
14501 sfhmergnmap_isnull(sf_hmeregion_map_t *map)
14502 {
14503 	int i;
14504 
14505 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
14506 		if (map->bitmap[i] != 0) {
14507 			return (0);
14508 		}
14509 	}
14510 	return (1);
14511 }
14512 
14513 #ifdef DEBUG
14514 static void
14515 check_scd_sfmmu_list(sfmmu_t **headp, sfmmu_t *sfmmup, int onlist)
14516 {
14517 	sfmmu_t *sp;
14518 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14519 
14520 	for (sp = *headp; sp != NULL; sp = sp->sfmmu_scd_link.next) {
14521 		ASSERT(srdp == sp->sfmmu_srdp);
14522 		if (sp == sfmmup) {
14523 			if (onlist) {
14524 				return;
14525 			} else {
14526 				panic("shctx: sfmmu 0x%p found on scd"
14527 				    "list 0x%p", (void *)sfmmup,
14528 				    (void *)*headp);
14529 			}
14530 		}
14531 	}
14532 	if (onlist) {
14533 		panic("shctx: sfmmu 0x%p not found on scd list 0x%p",
14534 		    (void *)sfmmup, (void *)*headp);
14535 	} else {
14536 		return;
14537 	}
14538 }
14539 #else /* DEBUG */
14540 #define	check_scd_sfmmu_list(headp, sfmmup, onlist)
14541 #endif /* DEBUG */
14542 
14543 /*
14544  * Removes an sfmmu from the SCD sfmmu list.
14545  */
14546 static void
14547 sfmmu_from_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14548 {
14549 	ASSERT(sfmmup->sfmmu_srdp != NULL);
14550 	check_scd_sfmmu_list(headp, sfmmup, 1);
14551 	if (sfmmup->sfmmu_scd_link.prev != NULL) {
14552 		ASSERT(*headp != sfmmup);
14553 		sfmmup->sfmmu_scd_link.prev->sfmmu_scd_link.next =
14554 		    sfmmup->sfmmu_scd_link.next;
14555 	} else {
14556 		ASSERT(*headp == sfmmup);
14557 		*headp = sfmmup->sfmmu_scd_link.next;
14558 	}
14559 	if (sfmmup->sfmmu_scd_link.next != NULL) {
14560 		sfmmup->sfmmu_scd_link.next->sfmmu_scd_link.prev =
14561 		    sfmmup->sfmmu_scd_link.prev;
14562 	}
14563 }
14564 
14565 
14566 /*
14567  * Adds an sfmmu to the start of the queue.
14568  */
14569 static void
14570 sfmmu_to_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14571 {
14572 	check_scd_sfmmu_list(headp, sfmmup, 0);
14573 	sfmmup->sfmmu_scd_link.prev = NULL;
14574 	sfmmup->sfmmu_scd_link.next = *headp;
14575 	if (*headp != NULL)
14576 		(*headp)->sfmmu_scd_link.prev = sfmmup;
14577 	*headp = sfmmup;
14578 }
14579 
14580 /*
14581  * Remove an scd from the start of the queue.
14582  */
14583 static void
14584 sfmmu_remove_scd(sf_scd_t **headp, sf_scd_t *scdp)
14585 {
14586 	if (scdp->scd_prev != NULL) {
14587 		ASSERT(*headp != scdp);
14588 		scdp->scd_prev->scd_next = scdp->scd_next;
14589 	} else {
14590 		ASSERT(*headp == scdp);
14591 		*headp = scdp->scd_next;
14592 	}
14593 
14594 	if (scdp->scd_next != NULL) {
14595 		scdp->scd_next->scd_prev = scdp->scd_prev;
14596 	}
14597 }
14598 
14599 /*
14600  * Add an scd to the start of the queue.
14601  */
14602 static void
14603 sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *scdp)
14604 {
14605 	scdp->scd_prev = NULL;
14606 	scdp->scd_next = *headp;
14607 	if (*headp != NULL) {
14608 		(*headp)->scd_prev = scdp;
14609 	}
14610 	*headp = scdp;
14611 }
14612 
14613 static int
14614 sfmmu_alloc_scd_tsbs(sf_srd_t *srdp, sf_scd_t *scdp)
14615 {
14616 	uint_t rid;
14617 	uint_t i;
14618 	uint_t j;
14619 	ulong_t w;
14620 	sf_region_t *rgnp;
14621 	ulong_t tte8k_cnt = 0;
14622 	ulong_t tte4m_cnt = 0;
14623 	uint_t tsb_szc;
14624 	sfmmu_t *scsfmmup = scdp->scd_sfmmup;
14625 	sfmmu_t	*ism_hatid;
14626 	struct tsb_info *newtsb;
14627 	int szc;
14628 
14629 	ASSERT(srdp != NULL);
14630 
14631 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14632 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14633 			continue;
14634 		}
14635 		j = 0;
14636 		while (w) {
14637 			if (!(w & 0x1)) {
14638 				j++;
14639 				w >>= 1;
14640 				continue;
14641 			}
14642 			rid = (i << BT_ULSHIFT) | j;
14643 			j++;
14644 			w >>= 1;
14645 
14646 			if (rid < SFMMU_MAX_HME_REGIONS) {
14647 				rgnp = srdp->srd_hmergnp[rid];
14648 				ASSERT(rgnp->rgn_id == rid);
14649 				ASSERT(rgnp->rgn_refcnt > 0);
14650 
14651 				if (rgnp->rgn_pgszc < TTE4M) {
14652 					tte8k_cnt += rgnp->rgn_size >>
14653 					    TTE_PAGE_SHIFT(TTE8K);
14654 				} else {
14655 					ASSERT(rgnp->rgn_pgszc >= TTE4M);
14656 					tte4m_cnt += rgnp->rgn_size >>
14657 					    TTE_PAGE_SHIFT(TTE4M);
14658 					/*
14659 					 * Inflate SCD tsb0 by preallocating
14660 					 * 1/4 8k ttecnt for 4M regions to
14661 					 * allow for lgpg alloc failure.
14662 					 */
14663 					tte8k_cnt += rgnp->rgn_size >>
14664 					    (TTE_PAGE_SHIFT(TTE8K) + 2);
14665 				}
14666 			} else {
14667 				rid -= SFMMU_MAX_HME_REGIONS;
14668 				rgnp = srdp->srd_ismrgnp[rid];
14669 				ASSERT(rgnp->rgn_id == rid);
14670 				ASSERT(rgnp->rgn_refcnt > 0);
14671 
14672 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14673 				ASSERT(ism_hatid->sfmmu_ismhat);
14674 
14675 				for (szc = 0; szc < TTE4M; szc++) {
14676 					tte8k_cnt +=
14677 					    ism_hatid->sfmmu_ttecnt[szc] <<
14678 					    TTE_BSZS_SHIFT(szc);
14679 				}
14680 
14681 				ASSERT(rgnp->rgn_pgszc >= TTE4M);
14682 				if (rgnp->rgn_pgszc >= TTE4M) {
14683 					tte4m_cnt += rgnp->rgn_size >>
14684 					    TTE_PAGE_SHIFT(TTE4M);
14685 				}
14686 			}
14687 		}
14688 	}
14689 
14690 	tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
14691 
14692 	/* Allocate both the SCD TSBs here. */
14693 	if (sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14694 	    tsb_szc, TSB8K|TSB64K|TSB512K, TSB_ALLOC, scsfmmup) &&
14695 	    (tsb_szc <= TSB_4M_SZCODE ||
14696 	    sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14697 	    TSB_4M_SZCODE, TSB8K|TSB64K|TSB512K,
14698 	    TSB_ALLOC, scsfmmup))) {
14699 
14700 		SFMMU_STAT(sf_scd_1sttsb_allocfail);
14701 		return (TSB_ALLOCFAIL);
14702 	} else {
14703 		scsfmmup->sfmmu_tsb->tsb_flags |= TSB_SHAREDCTX;
14704 
14705 		if (tte4m_cnt) {
14706 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
14707 			if (sfmmu_tsbinfo_alloc(&newtsb, tsb_szc,
14708 			    TSB4M|TSB32M|TSB256M, TSB_ALLOC, scsfmmup) &&
14709 			    (tsb_szc <= TSB_4M_SZCODE ||
14710 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
14711 			    TSB4M|TSB32M|TSB256M,
14712 			    TSB_ALLOC, scsfmmup))) {
14713 				/*
14714 				 * If we fail to allocate the 2nd shared tsb,
14715 				 * just free the 1st tsb, return failure.
14716 				 */
14717 				sfmmu_tsbinfo_free(scsfmmup->sfmmu_tsb);
14718 				SFMMU_STAT(sf_scd_2ndtsb_allocfail);
14719 				return (TSB_ALLOCFAIL);
14720 			} else {
14721 				ASSERT(scsfmmup->sfmmu_tsb->tsb_next == NULL);
14722 				newtsb->tsb_flags |= TSB_SHAREDCTX;
14723 				scsfmmup->sfmmu_tsb->tsb_next = newtsb;
14724 				SFMMU_STAT(sf_scd_2ndtsb_alloc);
14725 			}
14726 		}
14727 		SFMMU_STAT(sf_scd_1sttsb_alloc);
14728 	}
14729 	return (TSB_SUCCESS);
14730 }
14731 
14732 static void
14733 sfmmu_free_scd_tsbs(sfmmu_t *scd_sfmmu)
14734 {
14735 	while (scd_sfmmu->sfmmu_tsb != NULL) {
14736 		struct tsb_info *next = scd_sfmmu->sfmmu_tsb->tsb_next;
14737 		sfmmu_tsbinfo_free(scd_sfmmu->sfmmu_tsb);
14738 		scd_sfmmu->sfmmu_tsb = next;
14739 	}
14740 }
14741 
14742 /*
14743  * Link the sfmmu onto the hme region list.
14744  */
14745 void
14746 sfmmu_link_to_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14747 {
14748 	uint_t rid;
14749 	sf_rgn_link_t *rlink;
14750 	sfmmu_t *head;
14751 	sf_rgn_link_t *hrlink;
14752 
14753 	rid = rgnp->rgn_id;
14754 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14755 
14756 	/* LINTED: constant in conditional context */
14757 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 1);
14758 	ASSERT(rlink != NULL);
14759 	mutex_enter(&rgnp->rgn_mutex);
14760 	if ((head = rgnp->rgn_sfmmu_head) == NULL) {
14761 		rlink->next = NULL;
14762 		rlink->prev = NULL;
14763 		/*
14764 		 * make sure rlink's next field is NULL
14765 		 * before making this link visible.
14766 		 */
14767 		membar_stst();
14768 		rgnp->rgn_sfmmu_head = sfmmup;
14769 	} else {
14770 		/* LINTED: constant in conditional context */
14771 		SFMMU_HMERID2RLINKP(head, rid, hrlink, 0, 0);
14772 		ASSERT(hrlink != NULL);
14773 		ASSERT(hrlink->prev == NULL);
14774 		rlink->next = head;
14775 		rlink->prev = NULL;
14776 		hrlink->prev = sfmmup;
14777 		/*
14778 		 * make sure rlink's next field is correct
14779 		 * before making this link visible.
14780 		 */
14781 		membar_stst();
14782 		rgnp->rgn_sfmmu_head = sfmmup;
14783 	}
14784 	mutex_exit(&rgnp->rgn_mutex);
14785 }
14786 
14787 /*
14788  * Unlink the sfmmu from the hme region list.
14789  */
14790 void
14791 sfmmu_unlink_from_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14792 {
14793 	uint_t rid;
14794 	sf_rgn_link_t *rlink;
14795 
14796 	rid = rgnp->rgn_id;
14797 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14798 
14799 	/* LINTED: constant in conditional context */
14800 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
14801 	ASSERT(rlink != NULL);
14802 	mutex_enter(&rgnp->rgn_mutex);
14803 	if (rgnp->rgn_sfmmu_head == sfmmup) {
14804 		sfmmu_t *next = rlink->next;
14805 		rgnp->rgn_sfmmu_head = next;
14806 		/*
14807 		 * if we are stopped by xc_attention() after this
14808 		 * point the forward link walking in
14809 		 * sfmmu_rgntlb_demap() will work correctly since the
14810 		 * head correctly points to the next element.
14811 		 */
14812 		membar_stst();
14813 		rlink->next = NULL;
14814 		ASSERT(rlink->prev == NULL);
14815 		if (next != NULL) {
14816 			sf_rgn_link_t *nrlink;
14817 			/* LINTED: constant in conditional context */
14818 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14819 			ASSERT(nrlink != NULL);
14820 			ASSERT(nrlink->prev == sfmmup);
14821 			nrlink->prev = NULL;
14822 		}
14823 	} else {
14824 		sfmmu_t *next = rlink->next;
14825 		sfmmu_t *prev = rlink->prev;
14826 		sf_rgn_link_t *prlink;
14827 
14828 		ASSERT(prev != NULL);
14829 		/* LINTED: constant in conditional context */
14830 		SFMMU_HMERID2RLINKP(prev, rid, prlink, 0, 0);
14831 		ASSERT(prlink != NULL);
14832 		ASSERT(prlink->next == sfmmup);
14833 		prlink->next = next;
14834 		/*
14835 		 * if we are stopped by xc_attention()
14836 		 * after this point the forward link walking
14837 		 * will work correctly since the prev element
14838 		 * correctly points to the next element.
14839 		 */
14840 		membar_stst();
14841 		rlink->next = NULL;
14842 		rlink->prev = NULL;
14843 		if (next != NULL) {
14844 			sf_rgn_link_t *nrlink;
14845 			/* LINTED: constant in conditional context */
14846 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14847 			ASSERT(nrlink != NULL);
14848 			ASSERT(nrlink->prev == sfmmup);
14849 			nrlink->prev = prev;
14850 		}
14851 	}
14852 	mutex_exit(&rgnp->rgn_mutex);
14853 }
14854 
14855 /*
14856  * Link scd sfmmu onto ism or hme region list for each region in the
14857  * scd region map.
14858  */
14859 void
14860 sfmmu_link_scd_to_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14861 {
14862 	uint_t rid;
14863 	uint_t i;
14864 	uint_t j;
14865 	ulong_t w;
14866 	sf_region_t *rgnp;
14867 	sfmmu_t *scsfmmup;
14868 
14869 	scsfmmup = scdp->scd_sfmmup;
14870 	ASSERT(scsfmmup->sfmmu_scdhat);
14871 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14872 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14873 			continue;
14874 		}
14875 		j = 0;
14876 		while (w) {
14877 			if (!(w & 0x1)) {
14878 				j++;
14879 				w >>= 1;
14880 				continue;
14881 			}
14882 			rid = (i << BT_ULSHIFT) | j;
14883 			j++;
14884 			w >>= 1;
14885 
14886 			if (rid < SFMMU_MAX_HME_REGIONS) {
14887 				rgnp = srdp->srd_hmergnp[rid];
14888 				ASSERT(rgnp->rgn_id == rid);
14889 				ASSERT(rgnp->rgn_refcnt > 0);
14890 				sfmmu_link_to_hmeregion(scsfmmup, rgnp);
14891 			} else {
14892 				sfmmu_t *ism_hatid = NULL;
14893 				ism_ment_t *ism_ment;
14894 				rid -= SFMMU_MAX_HME_REGIONS;
14895 				rgnp = srdp->srd_ismrgnp[rid];
14896 				ASSERT(rgnp->rgn_id == rid);
14897 				ASSERT(rgnp->rgn_refcnt > 0);
14898 
14899 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14900 				ASSERT(ism_hatid->sfmmu_ismhat);
14901 				ism_ment = &scdp->scd_ism_links[rid];
14902 				ism_ment->iment_hat = scsfmmup;
14903 				ism_ment->iment_base_va = rgnp->rgn_saddr;
14904 				mutex_enter(&ism_mlist_lock);
14905 				iment_add(ism_ment, ism_hatid);
14906 				mutex_exit(&ism_mlist_lock);
14907 
14908 			}
14909 		}
14910 	}
14911 }
14912 /*
14913  * Unlink scd sfmmu from ism or hme region list for each region in the
14914  * scd region map.
14915  */
14916 void
14917 sfmmu_unlink_scd_from_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14918 {
14919 	uint_t rid;
14920 	uint_t i;
14921 	uint_t j;
14922 	ulong_t w;
14923 	sf_region_t *rgnp;
14924 	sfmmu_t *scsfmmup;
14925 
14926 	scsfmmup = scdp->scd_sfmmup;
14927 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14928 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14929 			continue;
14930 		}
14931 		j = 0;
14932 		while (w) {
14933 			if (!(w & 0x1)) {
14934 				j++;
14935 				w >>= 1;
14936 				continue;
14937 			}
14938 			rid = (i << BT_ULSHIFT) | j;
14939 			j++;
14940 			w >>= 1;
14941 
14942 			if (rid < SFMMU_MAX_HME_REGIONS) {
14943 				rgnp = srdp->srd_hmergnp[rid];
14944 				ASSERT(rgnp->rgn_id == rid);
14945 				ASSERT(rgnp->rgn_refcnt > 0);
14946 				sfmmu_unlink_from_hmeregion(scsfmmup,
14947 				    rgnp);
14948 
14949 			} else {
14950 				sfmmu_t *ism_hatid = NULL;
14951 				ism_ment_t *ism_ment;
14952 				rid -= SFMMU_MAX_HME_REGIONS;
14953 				rgnp = srdp->srd_ismrgnp[rid];
14954 				ASSERT(rgnp->rgn_id == rid);
14955 				ASSERT(rgnp->rgn_refcnt > 0);
14956 
14957 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14958 				ASSERT(ism_hatid->sfmmu_ismhat);
14959 				ism_ment = &scdp->scd_ism_links[rid];
14960 				ASSERT(ism_ment->iment_hat == scdp->scd_sfmmup);
14961 				ASSERT(ism_ment->iment_base_va ==
14962 				    rgnp->rgn_saddr);
14963 				mutex_enter(&ism_mlist_lock);
14964 				iment_sub(ism_ment, ism_hatid);
14965 				mutex_exit(&ism_mlist_lock);
14966 
14967 			}
14968 		}
14969 	}
14970 }
14971 /*
14972  * Allocates and initialises a new SCD structure, this is called with
14973  * the srd_scd_mutex held and returns with the reference count
14974  * initialised to 1.
14975  */
14976 static sf_scd_t *
14977 sfmmu_alloc_scd(sf_srd_t *srdp, sf_region_map_t *new_map)
14978 {
14979 	sf_scd_t *new_scdp;
14980 	sfmmu_t *scsfmmup;
14981 	int i;
14982 
14983 	ASSERT(MUTEX_HELD(&srdp->srd_scd_mutex));
14984 	new_scdp = kmem_cache_alloc(scd_cache, KM_SLEEP);
14985 
14986 	scsfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
14987 	new_scdp->scd_sfmmup = scsfmmup;
14988 	scsfmmup->sfmmu_srdp = srdp;
14989 	scsfmmup->sfmmu_scdp = new_scdp;
14990 	scsfmmup->sfmmu_tsb0_4minflcnt = 0;
14991 	scsfmmup->sfmmu_scdhat = 1;
14992 	CPUSET_ALL(scsfmmup->sfmmu_cpusran);
14993 	bzero(scsfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
14994 
14995 	ASSERT(max_mmu_ctxdoms > 0);
14996 	for (i = 0; i < max_mmu_ctxdoms; i++) {
14997 		scsfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
14998 		scsfmmup->sfmmu_ctxs[i].gnum = 0;
14999 	}
15000 
15001 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
15002 		new_scdp->scd_rttecnt[i] = 0;
15003 	}
15004 
15005 	new_scdp->scd_region_map = *new_map;
15006 	new_scdp->scd_refcnt = 1;
15007 	if (sfmmu_alloc_scd_tsbs(srdp, new_scdp) != TSB_SUCCESS) {
15008 		kmem_cache_free(scd_cache, new_scdp);
15009 		kmem_cache_free(sfmmuid_cache, scsfmmup);
15010 		return (NULL);
15011 	}
15012 	if (&mmu_init_scd) {
15013 		mmu_init_scd(new_scdp);
15014 	}
15015 	return (new_scdp);
15016 }
15017 
15018 /*
15019  * The first phase of a process joining an SCD. The hat structure is
15020  * linked to the SCD queue and then the HAT_JOIN_SCD sfmmu flag is set
15021  * and a cross-call with context invalidation is used to cause the
15022  * remaining work to be carried out in the sfmmu_tsbmiss_exception()
15023  * routine.
15024  */
15025 static void
15026 sfmmu_join_scd(sf_scd_t *scdp, sfmmu_t *sfmmup)
15027 {
15028 	hatlock_t *hatlockp;
15029 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15030 	int i;
15031 	sf_scd_t *old_scdp;
15032 
15033 	ASSERT(srdp != NULL);
15034 	ASSERT(scdp != NULL);
15035 	ASSERT(scdp->scd_refcnt > 0);
15036 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15037 
15038 	if ((old_scdp = sfmmup->sfmmu_scdp) != NULL) {
15039 		ASSERT(old_scdp != scdp);
15040 
15041 		mutex_enter(&old_scdp->scd_mutex);
15042 		sfmmu_from_scd_list(&old_scdp->scd_sf_list, sfmmup);
15043 		mutex_exit(&old_scdp->scd_mutex);
15044 		/*
15045 		 * sfmmup leaves the old scd. Update sfmmu_ttecnt to
15046 		 * include the shme rgn ttecnt for rgns that
15047 		 * were in the old SCD
15048 		 */
15049 		for (i = 0; i < mmu_page_sizes; i++) {
15050 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15051 			    old_scdp->scd_rttecnt[i]);
15052 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15053 			    sfmmup->sfmmu_scdrttecnt[i]);
15054 		}
15055 	}
15056 
15057 	/*
15058 	 * Move sfmmu to the scd lists.
15059 	 */
15060 	mutex_enter(&scdp->scd_mutex);
15061 	sfmmu_to_scd_list(&scdp->scd_sf_list, sfmmup);
15062 	mutex_exit(&scdp->scd_mutex);
15063 	SF_SCD_INCR_REF(scdp);
15064 
15065 	hatlockp = sfmmu_hat_enter(sfmmup);
15066 	/*
15067 	 * For a multi-thread process, we must stop
15068 	 * all the other threads before joining the scd.
15069 	 */
15070 
15071 	SFMMU_FLAGS_SET(sfmmup, HAT_JOIN_SCD);
15072 
15073 	sfmmu_invalidate_ctx(sfmmup);
15074 	sfmmup->sfmmu_scdp = scdp;
15075 
15076 	/*
15077 	 * Copy scd_rttecnt into sfmmup's sfmmu_scdrttecnt, and update
15078 	 * sfmmu_ttecnt to not include the rgn ttecnt just joined in SCD.
15079 	 */
15080 	for (i = 0; i < mmu_page_sizes; i++) {
15081 		sfmmup->sfmmu_scdrttecnt[i] = scdp->scd_rttecnt[i];
15082 		ASSERT(sfmmup->sfmmu_ttecnt[i] >= scdp->scd_rttecnt[i]);
15083 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15084 		    -sfmmup->sfmmu_scdrttecnt[i]);
15085 	}
15086 	/* update tsb0 inflation count */
15087 	if (old_scdp != NULL) {
15088 		sfmmup->sfmmu_tsb0_4minflcnt +=
15089 		    old_scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15090 	}
15091 	ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
15092 	    scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt);
15093 	sfmmup->sfmmu_tsb0_4minflcnt -= scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15094 
15095 	sfmmu_hat_exit(hatlockp);
15096 
15097 	if (old_scdp != NULL) {
15098 		SF_SCD_DECR_REF(srdp, old_scdp);
15099 	}
15100 
15101 }
15102 
15103 /*
15104  * This routine is called by a process to become part of an SCD. It is called
15105  * from sfmmu_tsbmiss_exception() once most of the initial work has been
15106  * done by sfmmu_join_scd(). This routine must not drop the hat lock.
15107  */
15108 static void
15109 sfmmu_finish_join_scd(sfmmu_t *sfmmup)
15110 {
15111 	struct tsb_info	*tsbinfop;
15112 
15113 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15114 	ASSERT(sfmmup->sfmmu_scdp != NULL);
15115 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD));
15116 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15117 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID));
15118 
15119 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
15120 	    tsbinfop = tsbinfop->tsb_next) {
15121 		if (tsbinfop->tsb_flags & TSB_SWAPPED) {
15122 			continue;
15123 		}
15124 		ASSERT(!(tsbinfop->tsb_flags & TSB_RELOC_FLAG));
15125 
15126 		sfmmu_inv_tsb(tsbinfop->tsb_va,
15127 		    TSB_BYTES(tsbinfop->tsb_szc));
15128 	}
15129 
15130 	/* Set HAT_CTX1_FLAG for all SCD ISMs */
15131 	sfmmu_ism_hatflags(sfmmup, 1);
15132 
15133 	SFMMU_STAT(sf_join_scd);
15134 }
15135 
15136 /*
15137  * This routine is called in order to check if there is an SCD which matches
15138  * the process's region map if not then a new SCD may be created.
15139  */
15140 static void
15141 sfmmu_find_scd(sfmmu_t *sfmmup)
15142 {
15143 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15144 	sf_scd_t *scdp, *new_scdp;
15145 	int ret;
15146 
15147 	ASSERT(srdp != NULL);
15148 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15149 
15150 	mutex_enter(&srdp->srd_scd_mutex);
15151 	for (scdp = srdp->srd_scdp; scdp != NULL;
15152 	    scdp = scdp->scd_next) {
15153 		SF_RGNMAP_EQUAL(&scdp->scd_region_map,
15154 		    &sfmmup->sfmmu_region_map, ret);
15155 		if (ret == 1) {
15156 			SF_SCD_INCR_REF(scdp);
15157 			mutex_exit(&srdp->srd_scd_mutex);
15158 			sfmmu_join_scd(scdp, sfmmup);
15159 			ASSERT(scdp->scd_refcnt >= 2);
15160 			atomic_add_32((volatile uint32_t *)
15161 			    &scdp->scd_refcnt, -1);
15162 			return;
15163 		} else {
15164 			/*
15165 			 * If the sfmmu region map is a subset of the scd
15166 			 * region map, then the assumption is that this process
15167 			 * will continue attaching to ISM segments until the
15168 			 * region maps are equal.
15169 			 */
15170 			SF_RGNMAP_IS_SUBSET(&scdp->scd_region_map,
15171 			    &sfmmup->sfmmu_region_map, ret);
15172 			if (ret == 1) {
15173 				mutex_exit(&srdp->srd_scd_mutex);
15174 				return;
15175 			}
15176 		}
15177 	}
15178 
15179 	ASSERT(scdp == NULL);
15180 	/*
15181 	 * No matching SCD has been found, create a new one.
15182 	 */
15183 	if ((new_scdp = sfmmu_alloc_scd(srdp, &sfmmup->sfmmu_region_map)) ==
15184 	    NULL) {
15185 		mutex_exit(&srdp->srd_scd_mutex);
15186 		return;
15187 	}
15188 
15189 	/*
15190 	 * sfmmu_alloc_scd() returns with a ref count of 1 on the scd.
15191 	 */
15192 
15193 	/* Set scd_rttecnt for shme rgns in SCD */
15194 	sfmmu_set_scd_rttecnt(srdp, new_scdp);
15195 
15196 	/*
15197 	 * Link scd onto srd_scdp list and scd sfmmu onto region/iment lists.
15198 	 */
15199 	sfmmu_link_scd_to_regions(srdp, new_scdp);
15200 	sfmmu_add_scd(&srdp->srd_scdp, new_scdp);
15201 	SFMMU_STAT_ADD(sf_create_scd, 1);
15202 
15203 	mutex_exit(&srdp->srd_scd_mutex);
15204 	sfmmu_join_scd(new_scdp, sfmmup);
15205 	ASSERT(new_scdp->scd_refcnt >= 2);
15206 	atomic_add_32((volatile uint32_t *)&new_scdp->scd_refcnt, -1);
15207 }
15208 
15209 /*
15210  * This routine is called by a process to remove itself from an SCD. It is
15211  * either called when the processes has detached from a segment or from
15212  * hat_free_start() as a result of calling exit.
15213  */
15214 static void
15215 sfmmu_leave_scd(sfmmu_t *sfmmup, uchar_t r_type)
15216 {
15217 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15218 	sf_srd_t *srdp =  sfmmup->sfmmu_srdp;
15219 	hatlock_t *hatlockp = TSB_HASH(sfmmup);
15220 	int i;
15221 
15222 	ASSERT(scdp != NULL);
15223 	ASSERT(srdp != NULL);
15224 
15225 	if (sfmmup->sfmmu_free) {
15226 		/*
15227 		 * If the process is part of an SCD the sfmmu is unlinked
15228 		 * from scd_sf_list.
15229 		 */
15230 		mutex_enter(&scdp->scd_mutex);
15231 		sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15232 		mutex_exit(&scdp->scd_mutex);
15233 		/*
15234 		 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15235 		 * are about to leave the SCD
15236 		 */
15237 		for (i = 0; i < mmu_page_sizes; i++) {
15238 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15239 			    scdp->scd_rttecnt[i]);
15240 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15241 			    sfmmup->sfmmu_scdrttecnt[i]);
15242 			sfmmup->sfmmu_scdrttecnt[i] = 0;
15243 		}
15244 		sfmmup->sfmmu_scdp = NULL;
15245 
15246 		SF_SCD_DECR_REF(srdp, scdp);
15247 		return;
15248 	}
15249 
15250 	ASSERT(r_type != SFMMU_REGION_ISM ||
15251 	    SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15252 	ASSERT(scdp->scd_refcnt);
15253 	ASSERT(!sfmmup->sfmmu_free);
15254 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15255 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15256 
15257 	/*
15258 	 * Wait for ISM maps to be updated.
15259 	 */
15260 	if (r_type != SFMMU_REGION_ISM) {
15261 		while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY) &&
15262 		    sfmmup->sfmmu_scdp != NULL) {
15263 			cv_wait(&sfmmup->sfmmu_tsb_cv,
15264 			    HATLOCK_MUTEXP(hatlockp));
15265 		}
15266 
15267 		if (sfmmup->sfmmu_scdp == NULL) {
15268 			sfmmu_hat_exit(hatlockp);
15269 			return;
15270 		}
15271 		SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
15272 	}
15273 
15274 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
15275 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
15276 		/*
15277 		 * Since HAT_JOIN_SCD was set our context
15278 		 * is still invalid.
15279 		 */
15280 	} else {
15281 		/*
15282 		 * For a multi-thread process, we must stop
15283 		 * all the other threads before leaving the scd.
15284 		 */
15285 
15286 		sfmmu_invalidate_ctx(sfmmup);
15287 	}
15288 
15289 	/* Clear all the rid's for ISM, delete flags, etc */
15290 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15291 	sfmmu_ism_hatflags(sfmmup, 0);
15292 
15293 	/*
15294 	 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15295 	 * are in SCD before this sfmmup leaves the SCD.
15296 	 */
15297 	for (i = 0; i < mmu_page_sizes; i++) {
15298 		ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15299 		    scdp->scd_rttecnt[i]);
15300 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15301 		    sfmmup->sfmmu_scdrttecnt[i]);
15302 		sfmmup->sfmmu_scdrttecnt[i] = 0;
15303 		/* update ismttecnt to include SCD ism before hat leaves SCD */
15304 		sfmmup->sfmmu_ismttecnt[i] += sfmmup->sfmmu_scdismttecnt[i];
15305 		sfmmup->sfmmu_scdismttecnt[i] = 0;
15306 	}
15307 	/* update tsb0 inflation count */
15308 	sfmmup->sfmmu_tsb0_4minflcnt += scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15309 
15310 	if (r_type != SFMMU_REGION_ISM) {
15311 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
15312 	}
15313 	sfmmup->sfmmu_scdp = NULL;
15314 
15315 	sfmmu_hat_exit(hatlockp);
15316 
15317 	/*
15318 	 * Unlink sfmmu from scd_sf_list this can be done without holding
15319 	 * the hat lock as we hold the sfmmu_as lock which prevents
15320 	 * hat_join_region from adding this thread to the scd again. Other
15321 	 * threads check if sfmmu_scdp is NULL under hat lock and if it's NULL
15322 	 * they won't get here, since sfmmu_leave_scd() clears sfmmu_scdp
15323 	 * while holding the hat lock.
15324 	 */
15325 	mutex_enter(&scdp->scd_mutex);
15326 	sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15327 	mutex_exit(&scdp->scd_mutex);
15328 	SFMMU_STAT(sf_leave_scd);
15329 
15330 	SF_SCD_DECR_REF(srdp, scdp);
15331 	hatlockp = sfmmu_hat_enter(sfmmup);
15332 
15333 }
15334 
15335 /*
15336  * Unlink and free up an SCD structure with a reference count of 0.
15337  */
15338 static void
15339 sfmmu_destroy_scd(sf_srd_t *srdp, sf_scd_t *scdp, sf_region_map_t *scd_rmap)
15340 {
15341 	sfmmu_t *scsfmmup;
15342 	sf_scd_t *sp;
15343 	hatlock_t *shatlockp;
15344 	int i, ret;
15345 
15346 	mutex_enter(&srdp->srd_scd_mutex);
15347 	for (sp = srdp->srd_scdp; sp != NULL; sp = sp->scd_next) {
15348 		if (sp == scdp)
15349 			break;
15350 	}
15351 	if (sp == NULL || sp->scd_refcnt) {
15352 		mutex_exit(&srdp->srd_scd_mutex);
15353 		return;
15354 	}
15355 
15356 	/*
15357 	 * It is possible that the scd has been freed and reallocated with a
15358 	 * different region map while we've been waiting for the srd_scd_mutex.
15359 	 */
15360 	SF_RGNMAP_EQUAL(scd_rmap, &sp->scd_region_map, ret);
15361 	if (ret != 1) {
15362 		mutex_exit(&srdp->srd_scd_mutex);
15363 		return;
15364 	}
15365 
15366 	ASSERT(scdp->scd_sf_list == NULL);
15367 	/*
15368 	 * Unlink scd from srd_scdp list.
15369 	 */
15370 	sfmmu_remove_scd(&srdp->srd_scdp, scdp);
15371 	mutex_exit(&srdp->srd_scd_mutex);
15372 
15373 	sfmmu_unlink_scd_from_regions(srdp, scdp);
15374 
15375 	/* Clear shared context tsb and release ctx */
15376 	scsfmmup = scdp->scd_sfmmup;
15377 
15378 	/*
15379 	 * create a barrier so that scd will not be destroyed
15380 	 * if other thread still holds the same shared hat lock.
15381 	 * E.g., sfmmu_tsbmiss_exception() needs to acquire the
15382 	 * shared hat lock before checking the shared tsb reloc flag.
15383 	 */
15384 	shatlockp = sfmmu_hat_enter(scsfmmup);
15385 	sfmmu_hat_exit(shatlockp);
15386 
15387 	sfmmu_free_scd_tsbs(scsfmmup);
15388 
15389 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
15390 		if (scsfmmup->sfmmu_hmeregion_links[i] != NULL) {
15391 			kmem_free(scsfmmup->sfmmu_hmeregion_links[i],
15392 			    SFMMU_L2_HMERLINKS_SIZE);
15393 			scsfmmup->sfmmu_hmeregion_links[i] = NULL;
15394 		}
15395 	}
15396 	kmem_cache_free(sfmmuid_cache, scsfmmup);
15397 	kmem_cache_free(scd_cache, scdp);
15398 	SFMMU_STAT(sf_destroy_scd);
15399 }
15400 
15401 /*
15402  * Modifies the HAT_CTX1_FLAG for each of the ISM segments which correspond to
15403  * bits which are set in the ism_region_map parameter. This flag indicates to
15404  * the tsbmiss handler that mapping for these segments should be loaded using
15405  * the shared context.
15406  */
15407 static void
15408 sfmmu_ism_hatflags(sfmmu_t *sfmmup, int addflag)
15409 {
15410 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15411 	ism_blk_t *ism_blkp;
15412 	ism_map_t *ism_map;
15413 	int i, rid;
15414 
15415 	ASSERT(sfmmup->sfmmu_iblk != NULL);
15416 	ASSERT(scdp != NULL);
15417 	/*
15418 	 * Note that the caller either set HAT_ISMBUSY flag or checked
15419 	 * under hat lock that HAT_ISMBUSY was not set by another thread.
15420 	 */
15421 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15422 
15423 	ism_blkp = sfmmup->sfmmu_iblk;
15424 	while (ism_blkp != NULL) {
15425 		ism_map = ism_blkp->iblk_maps;
15426 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
15427 			rid = ism_map[i].imap_rid;
15428 			if (rid == SFMMU_INVALID_ISMRID) {
15429 				continue;
15430 			}
15431 			ASSERT(rid >= 0 && rid < SFMMU_MAX_ISM_REGIONS);
15432 			if (SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid) &&
15433 			    addflag) {
15434 				ism_map[i].imap_hatflags |=
15435 				    HAT_CTX1_FLAG;
15436 			} else {
15437 				ism_map[i].imap_hatflags &=
15438 				    ~HAT_CTX1_FLAG;
15439 			}
15440 		}
15441 		ism_blkp = ism_blkp->iblk_next;
15442 	}
15443 }
15444 
15445 static int
15446 sfmmu_srd_lock_held(sf_srd_t *srdp)
15447 {
15448 	return (MUTEX_HELD(&srdp->srd_mutex));
15449 }
15450 
15451 /* ARGSUSED */
15452 static int
15453 sfmmu_scdcache_constructor(void *buf, void *cdrarg, int kmflags)
15454 {
15455 	sf_scd_t *scdp = (sf_scd_t *)buf;
15456 
15457 	bzero(buf, sizeof (sf_scd_t));
15458 	mutex_init(&scdp->scd_mutex, NULL, MUTEX_DEFAULT, NULL);
15459 	return (0);
15460 }
15461 
15462 /* ARGSUSED */
15463 static void
15464 sfmmu_scdcache_destructor(void *buf, void *cdrarg)
15465 {
15466 	sf_scd_t *scdp = (sf_scd_t *)buf;
15467 
15468 	mutex_destroy(&scdp->scd_mutex);
15469 }
15470 
15471 /*
15472  * The listp parameter is a pointer to a list of hmeblks which are partially
15473  * freed as result of calling sfmmu_hblk_hash_rm(), the last phase of the
15474  * freeing process is to cross-call all cpus to ensure that there are no
15475  * remaining cached references.
15476  *
15477  * If the local generation number is less than the global then we can free
15478  * hmeblks which are already on the pending queue as another cpu has completed
15479  * the cross-call.
15480  *
15481  * We cross-call to make sure that there are no threads on other cpus accessing
15482  * these hmblks and then complete the process of freeing them under the
15483  * following conditions:
15484  * 	The total number of pending hmeblks is greater than the threshold
15485  *	The reserve list has fewer than HBLK_RESERVE_CNT hmeblks
15486  *	It is at least 1 second since the last time we cross-called
15487  *
15488  * Otherwise, we add the hmeblks to the per-cpu pending queue.
15489  */
15490 static void
15491 sfmmu_hblks_list_purge(struct hme_blk **listp, int dontfree)
15492 {
15493 	struct hme_blk *hblkp, *pr_hblkp = NULL;
15494 	int		count = 0;
15495 	cpuset_t	cpuset = cpu_ready_set;
15496 	cpu_hme_pend_t	*cpuhp;
15497 	timestruc_t	now;
15498 	int		one_second_expired = 0;
15499 
15500 	gethrestime_lasttick(&now);
15501 
15502 	for (hblkp = *listp; hblkp != NULL; hblkp = hblkp->hblk_next) {
15503 		ASSERT(hblkp->hblk_shw_bit == 0);
15504 		ASSERT(hblkp->hblk_shared == 0);
15505 		count++;
15506 		pr_hblkp = hblkp;
15507 	}
15508 
15509 	cpuhp = &cpu_hme_pend[CPU->cpu_seqid];
15510 	mutex_enter(&cpuhp->chp_mutex);
15511 
15512 	if ((cpuhp->chp_count + count) == 0) {
15513 		mutex_exit(&cpuhp->chp_mutex);
15514 		return;
15515 	}
15516 
15517 	if ((now.tv_sec - cpuhp->chp_timestamp) > 1) {
15518 		one_second_expired  = 1;
15519 	}
15520 
15521 	if (!dontfree && (freehblkcnt < HBLK_RESERVE_CNT ||
15522 	    (cpuhp->chp_count + count) > cpu_hme_pend_thresh ||
15523 	    one_second_expired)) {
15524 		/* Append global list to local */
15525 		if (pr_hblkp == NULL) {
15526 			*listp = cpuhp->chp_listp;
15527 		} else {
15528 			pr_hblkp->hblk_next = cpuhp->chp_listp;
15529 		}
15530 		cpuhp->chp_listp = NULL;
15531 		cpuhp->chp_count = 0;
15532 		cpuhp->chp_timestamp = now.tv_sec;
15533 		mutex_exit(&cpuhp->chp_mutex);
15534 
15535 		kpreempt_disable();
15536 		CPUSET_DEL(cpuset, CPU->cpu_id);
15537 		xt_sync(cpuset);
15538 		xt_sync(cpuset);
15539 		kpreempt_enable();
15540 
15541 		/*
15542 		 * At this stage we know that no trap handlers on other
15543 		 * cpus can have references to hmeblks on the list.
15544 		 */
15545 		sfmmu_hblk_free(listp);
15546 	} else if (*listp != NULL) {
15547 		pr_hblkp->hblk_next = cpuhp->chp_listp;
15548 		cpuhp->chp_listp = *listp;
15549 		cpuhp->chp_count += count;
15550 		*listp = NULL;
15551 		mutex_exit(&cpuhp->chp_mutex);
15552 	} else {
15553 		mutex_exit(&cpuhp->chp_mutex);
15554 	}
15555 }
15556 
15557 /*
15558  * Add an hmeblk to the the hash list.
15559  */
15560 void
15561 sfmmu_hblk_hash_add(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15562 	uint64_t hblkpa)
15563 {
15564 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15565 #ifdef	DEBUG
15566 	if (hmebp->hmeblkp == NULL) {
15567 		ASSERT(hmebp->hmeh_nextpa == HMEBLK_ENDPA);
15568 	}
15569 #endif /* DEBUG */
15570 
15571 	hmeblkp->hblk_nextpa = hmebp->hmeh_nextpa;
15572 	/*
15573 	 * Since the TSB miss handler now does not lock the hash chain before
15574 	 * walking it, make sure that the hmeblks nextpa is globally visible
15575 	 * before we make the hmeblk globally visible by updating the chain root
15576 	 * pointer in the hash bucket.
15577 	 */
15578 	membar_producer();
15579 	hmebp->hmeh_nextpa = hblkpa;
15580 	hmeblkp->hblk_next = hmebp->hmeblkp;
15581 	hmebp->hmeblkp = hmeblkp;
15582 
15583 }
15584 
15585 /*
15586  * This function is the first part of a 2 part process to remove an hmeblk
15587  * from the hash chain. In this phase we unlink the hmeblk from the hash chain
15588  * but leave the next physical pointer unchanged. The hmeblk is then linked onto
15589  * a per-cpu pending list using the virtual address pointer.
15590  *
15591  * TSB miss trap handlers that start after this phase will no longer see
15592  * this hmeblk. TSB miss handlers that still cache this hmeblk in a register
15593  * can still use it for further chain traversal because we haven't yet modifed
15594  * the next physical pointer or freed it.
15595  *
15596  * In the second phase of hmeblk removal we'll issue a barrier xcall before
15597  * we reuse or free this hmeblk. This will make sure all lingering references to
15598  * the hmeblk after first phase disappear before we finally reclaim it.
15599  * This scheme eliminates the need for TSB miss handlers to lock hmeblk chains
15600  * during their traversal.
15601  *
15602  * The hmehash_mutex must be held when calling this function.
15603  *
15604  * Input:
15605  *	 hmebp - hme hash bucket pointer
15606  *	 hmeblkp - address of hmeblk to be removed
15607  *	 pr_hblk - virtual address of previous hmeblkp
15608  *	 listp - pointer to list of hmeblks linked by virtual address
15609  *	 free_now flag - indicates that a complete removal from the hash chains
15610  *			 is necessary.
15611  *
15612  * It is inefficient to use the free_now flag as a cross-call is required to
15613  * remove a single hmeblk from the hash chain but is necessary when hmeblks are
15614  * in short supply.
15615  */
15616 void
15617 sfmmu_hblk_hash_rm(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15618     struct hme_blk *pr_hblk, struct hme_blk **listp,
15619     int free_now)
15620 {
15621 	int shw_size, vshift;
15622 	struct hme_blk *shw_hblkp;
15623 	uint_t		shw_mask, newshw_mask;
15624 	caddr_t		vaddr;
15625 	int		size;
15626 	cpuset_t cpuset = cpu_ready_set;
15627 
15628 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15629 
15630 	if (hmebp->hmeblkp == hmeblkp) {
15631 		hmebp->hmeh_nextpa = hmeblkp->hblk_nextpa;
15632 		hmebp->hmeblkp = hmeblkp->hblk_next;
15633 	} else {
15634 		pr_hblk->hblk_nextpa = hmeblkp->hblk_nextpa;
15635 		pr_hblk->hblk_next = hmeblkp->hblk_next;
15636 	}
15637 
15638 	size = get_hblk_ttesz(hmeblkp);
15639 	shw_hblkp = hmeblkp->hblk_shadow;
15640 	if (shw_hblkp) {
15641 		ASSERT(hblktosfmmu(hmeblkp) != KHATID);
15642 		ASSERT(!hmeblkp->hblk_shared);
15643 #ifdef	DEBUG
15644 		if (mmu_page_sizes == max_mmu_page_sizes) {
15645 			ASSERT(size < TTE256M);
15646 		} else {
15647 			ASSERT(size < TTE4M);
15648 		}
15649 #endif /* DEBUG */
15650 
15651 		shw_size = get_hblk_ttesz(shw_hblkp);
15652 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
15653 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
15654 		ASSERT(vshift < 8);
15655 		/*
15656 		 * Atomically clear shadow mask bit
15657 		 */
15658 		do {
15659 			shw_mask = shw_hblkp->hblk_shw_mask;
15660 			ASSERT(shw_mask & (1 << vshift));
15661 			newshw_mask = shw_mask & ~(1 << vshift);
15662 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
15663 			    shw_mask, newshw_mask);
15664 		} while (newshw_mask != shw_mask);
15665 		hmeblkp->hblk_shadow = NULL;
15666 	}
15667 	hmeblkp->hblk_shw_bit = 0;
15668 
15669 	if (hmeblkp->hblk_shared) {
15670 #ifdef	DEBUG
15671 		sf_srd_t	*srdp;
15672 		sf_region_t	*rgnp;
15673 		uint_t		rid;
15674 
15675 		srdp = hblktosrd(hmeblkp);
15676 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
15677 		rid = hmeblkp->hblk_tag.htag_rid;
15678 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
15679 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
15680 		rgnp = srdp->srd_hmergnp[rid];
15681 		ASSERT(rgnp != NULL);
15682 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
15683 #endif /* DEBUG */
15684 		hmeblkp->hblk_shared = 0;
15685 	}
15686 	if (free_now) {
15687 		kpreempt_disable();
15688 		CPUSET_DEL(cpuset, CPU->cpu_id);
15689 		xt_sync(cpuset);
15690 		xt_sync(cpuset);
15691 		kpreempt_enable();
15692 
15693 		hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
15694 		hmeblkp->hblk_next = NULL;
15695 	} else {
15696 		/* Append hmeblkp to listp for processing later. */
15697 		hmeblkp->hblk_next = *listp;
15698 		*listp = hmeblkp;
15699 	}
15700 }
15701 
15702 /*
15703  * This routine is called when memory is in short supply and returns a free
15704  * hmeblk of the requested size from the cpu pending lists.
15705  */
15706 static struct hme_blk *
15707 sfmmu_check_pending_hblks(int size)
15708 {
15709 	int i;
15710 	struct hme_blk *hmeblkp = NULL, *last_hmeblkp;
15711 	int found_hmeblk;
15712 	cpuset_t cpuset = cpu_ready_set;
15713 	cpu_hme_pend_t *cpuhp;
15714 
15715 	/* Flush cpu hblk pending queues */
15716 	for (i = 0; i < NCPU; i++) {
15717 		cpuhp = &cpu_hme_pend[i];
15718 		if (cpuhp->chp_listp != NULL)  {
15719 			mutex_enter(&cpuhp->chp_mutex);
15720 			if (cpuhp->chp_listp == NULL)  {
15721 				mutex_exit(&cpuhp->chp_mutex);
15722 				continue;
15723 			}
15724 			found_hmeblk = 0;
15725 			last_hmeblkp = NULL;
15726 			for (hmeblkp = cpuhp->chp_listp; hmeblkp != NULL;
15727 			    hmeblkp = hmeblkp->hblk_next) {
15728 				if (get_hblk_ttesz(hmeblkp) == size) {
15729 					if (last_hmeblkp == NULL) {
15730 						cpuhp->chp_listp =
15731 						    hmeblkp->hblk_next;
15732 					} else {
15733 						last_hmeblkp->hblk_next =
15734 						    hmeblkp->hblk_next;
15735 					}
15736 					ASSERT(cpuhp->chp_count > 0);
15737 					cpuhp->chp_count--;
15738 					found_hmeblk = 1;
15739 					break;
15740 				} else {
15741 					last_hmeblkp = hmeblkp;
15742 				}
15743 			}
15744 			mutex_exit(&cpuhp->chp_mutex);
15745 
15746 			if (found_hmeblk) {
15747 				kpreempt_disable();
15748 				CPUSET_DEL(cpuset, CPU->cpu_id);
15749 				xt_sync(cpuset);
15750 				xt_sync(cpuset);
15751 				kpreempt_enable();
15752 				return (hmeblkp);
15753 			}
15754 		}
15755 	}
15756 	return (NULL);
15757 }
15758