xref: /titanic_51/usr/src/uts/sfmmu/vm/hat_sfmmu.c (revision bbf6f00c25b6a2bed23c35eac6d62998ecdb338c)
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  * Invalidate a virtual address range for the local CPU.
6172  * For best performance ensure that the va range is completely
6173  * mapped, otherwise the entire TLB will be flushed.
6174  */
6175 void
6176 hat_flush_range(struct hat *sfmmup, caddr_t va, size_t size)
6177 {
6178 	ssize_t sz;
6179 	caddr_t endva = va + size;
6180 
6181 	while (va < endva) {
6182 		sz = hat_getpagesize(sfmmup, va);
6183 		if (sz < 0) {
6184 			vtag_flushall();
6185 			break;
6186 		}
6187 		vtag_flushpage(va, (uint64_t)sfmmup);
6188 		va += sz;
6189 	}
6190 }
6191 
6192 /*
6193  * Synchronize all the mappings in the range [addr..addr+len).
6194  * Can be called with clearflag having two states:
6195  * HAT_SYNC_DONTZERO means just return the rm stats
6196  * HAT_SYNC_ZERORM means zero rm bits in the tte and return the stats
6197  */
6198 void
6199 hat_sync(struct hat *sfmmup, caddr_t addr, size_t len, uint_t clearflag)
6200 {
6201 	struct hmehash_bucket *hmebp;
6202 	hmeblk_tag hblktag;
6203 	int hmeshift, hashno = 1;
6204 	struct hme_blk *hmeblkp, *list = NULL;
6205 	caddr_t endaddr;
6206 	cpuset_t cpuset;
6207 
6208 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
6209 	ASSERT((sfmmup == ksfmmup) ||
6210 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
6211 	ASSERT((len & MMU_PAGEOFFSET) == 0);
6212 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
6213 	    (clearflag == HAT_SYNC_ZERORM));
6214 
6215 	CPUSET_ZERO(cpuset);
6216 
6217 	endaddr = addr + len;
6218 	hblktag.htag_id = sfmmup;
6219 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
6220 
6221 	/*
6222 	 * Spitfire supports 4 page sizes.
6223 	 * Most pages are expected to be of the smallest page
6224 	 * size (8K) and these will not need to be rehashed. 64K
6225 	 * pages also don't need to be rehashed because the an hmeblk
6226 	 * spans 64K of address space. 512K pages might need 1 rehash and
6227 	 * and 4M pages 2 rehashes.
6228 	 */
6229 	while (addr < endaddr) {
6230 		hmeshift = HME_HASH_SHIFT(hashno);
6231 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
6232 		hblktag.htag_rehash = hashno;
6233 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
6234 
6235 		SFMMU_HASH_LOCK(hmebp);
6236 
6237 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
6238 		if (hmeblkp != NULL) {
6239 			ASSERT(!hmeblkp->hblk_shared);
6240 			/*
6241 			 * We've encountered a shadow hmeblk so skip the range
6242 			 * of the next smaller mapping size.
6243 			 */
6244 			if (hmeblkp->hblk_shw_bit) {
6245 				ASSERT(sfmmup != ksfmmup);
6246 				ASSERT(hashno > 1);
6247 				addr = (caddr_t)P2END((uintptr_t)addr,
6248 				    TTEBYTES(hashno - 1));
6249 			} else {
6250 				addr = sfmmu_hblk_sync(sfmmup, hmeblkp,
6251 				    addr, endaddr, clearflag);
6252 			}
6253 			SFMMU_HASH_UNLOCK(hmebp);
6254 			hashno = 1;
6255 			continue;
6256 		}
6257 		SFMMU_HASH_UNLOCK(hmebp);
6258 
6259 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
6260 			/*
6261 			 * We have traversed the whole list and rehashed
6262 			 * if necessary without finding the address to sync.
6263 			 * This is ok so we increment the address by the
6264 			 * smallest hmeblk range for kernel mappings and the
6265 			 * largest hmeblk range, to account for shadow hmeblks,
6266 			 * for user mappings and continue.
6267 			 */
6268 			if (sfmmup == ksfmmup)
6269 				addr = (caddr_t)P2END((uintptr_t)addr,
6270 				    TTEBYTES(1));
6271 			else
6272 				addr = (caddr_t)P2END((uintptr_t)addr,
6273 				    TTEBYTES(hashno));
6274 			hashno = 1;
6275 		} else {
6276 			hashno++;
6277 		}
6278 	}
6279 	sfmmu_hblks_list_purge(&list, 0);
6280 	cpuset = sfmmup->sfmmu_cpusran;
6281 	xt_sync(cpuset);
6282 }
6283 
6284 static caddr_t
6285 sfmmu_hblk_sync(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
6286 	caddr_t endaddr, int clearflag)
6287 {
6288 	tte_t	tte, ttemod;
6289 	struct sf_hment *sfhmep;
6290 	int ttesz;
6291 	struct page *pp;
6292 	kmutex_t *pml;
6293 	int ret;
6294 
6295 	ASSERT(hmeblkp->hblk_shw_bit == 0);
6296 	ASSERT(!hmeblkp->hblk_shared);
6297 
6298 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
6299 
6300 	ttesz = get_hblk_ttesz(hmeblkp);
6301 	HBLKTOHME(sfhmep, hmeblkp, addr);
6302 
6303 	while (addr < endaddr) {
6304 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6305 		if (TTE_IS_VALID(&tte)) {
6306 			pml = NULL;
6307 			pp = sfhmep->hme_page;
6308 			if (pp) {
6309 				pml = sfmmu_mlist_enter(pp);
6310 			}
6311 			if (pp != sfhmep->hme_page) {
6312 				/*
6313 				 * tte most have been unloaded
6314 				 * underneath us.  Recheck
6315 				 */
6316 				ASSERT(pml);
6317 				sfmmu_mlist_exit(pml);
6318 				continue;
6319 			}
6320 
6321 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
6322 
6323 			if (clearflag == HAT_SYNC_ZERORM) {
6324 				ttemod = tte;
6325 				TTE_CLR_RM(&ttemod);
6326 				ret = sfmmu_modifytte_try(&tte, &ttemod,
6327 				    &sfhmep->hme_tte);
6328 				if (ret < 0) {
6329 					if (pml) {
6330 						sfmmu_mlist_exit(pml);
6331 					}
6332 					continue;
6333 				}
6334 
6335 				if (ret > 0) {
6336 					sfmmu_tlb_demap(addr, sfmmup,
6337 					    hmeblkp, 0, 0);
6338 				}
6339 			}
6340 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
6341 			if (pml) {
6342 				sfmmu_mlist_exit(pml);
6343 			}
6344 		}
6345 		addr += TTEBYTES(ttesz);
6346 		sfhmep++;
6347 	}
6348 	return (addr);
6349 }
6350 
6351 /*
6352  * This function will sync a tte to the page struct and it will
6353  * update the hat stats. Currently it allows us to pass a NULL pp
6354  * and we will simply update the stats.  We may want to change this
6355  * so we only keep stats for pages backed by pp's.
6356  */
6357 static void
6358 sfmmu_ttesync(struct hat *sfmmup, caddr_t addr, tte_t *ttep, page_t *pp)
6359 {
6360 	uint_t rm = 0;
6361 	int   	sz;
6362 	pgcnt_t	npgs;
6363 
6364 	ASSERT(TTE_IS_VALID(ttep));
6365 
6366 	if (TTE_IS_NOSYNC(ttep)) {
6367 		return;
6368 	}
6369 
6370 	if (TTE_IS_REF(ttep))  {
6371 		rm = P_REF;
6372 	}
6373 	if (TTE_IS_MOD(ttep))  {
6374 		rm |= P_MOD;
6375 	}
6376 
6377 	if (rm == 0) {
6378 		return;
6379 	}
6380 
6381 	sz = TTE_CSZ(ttep);
6382 	if (sfmmup != NULL && sfmmup->sfmmu_rmstat) {
6383 		int i;
6384 		caddr_t	vaddr = addr;
6385 
6386 		for (i = 0; i < TTEPAGES(sz); i++, vaddr += MMU_PAGESIZE) {
6387 			hat_setstat(sfmmup->sfmmu_as, vaddr, MMU_PAGESIZE, rm);
6388 		}
6389 
6390 	}
6391 
6392 	/*
6393 	 * XXX I want to use cas to update nrm bits but they
6394 	 * currently belong in common/vm and not in hat where
6395 	 * they should be.
6396 	 * The nrm bits are protected by the same mutex as
6397 	 * the one that protects the page's mapping list.
6398 	 */
6399 	if (!pp)
6400 		return;
6401 	ASSERT(sfmmu_mlist_held(pp));
6402 	/*
6403 	 * If the tte is for a large page, we need to sync all the
6404 	 * pages covered by the tte.
6405 	 */
6406 	if (sz != TTE8K) {
6407 		ASSERT(pp->p_szc != 0);
6408 		pp = PP_GROUPLEADER(pp, sz);
6409 		ASSERT(sfmmu_mlist_held(pp));
6410 	}
6411 
6412 	/* Get number of pages from tte size. */
6413 	npgs = TTEPAGES(sz);
6414 
6415 	do {
6416 		ASSERT(pp);
6417 		ASSERT(sfmmu_mlist_held(pp));
6418 		if (((rm & P_REF) != 0 && !PP_ISREF(pp)) ||
6419 		    ((rm & P_MOD) != 0 && !PP_ISMOD(pp)))
6420 			hat_page_setattr(pp, rm);
6421 
6422 		/*
6423 		 * Are we done? If not, we must have a large mapping.
6424 		 * For large mappings we need to sync the rest of the pages
6425 		 * covered by this tte; goto the next page.
6426 		 */
6427 	} while (--npgs > 0 && (pp = PP_PAGENEXT(pp)));
6428 }
6429 
6430 /*
6431  * Execute pre-callback handler of each pa_hment linked to pp
6432  *
6433  * Inputs:
6434  *   flag: either HAT_PRESUSPEND or HAT_SUSPEND.
6435  *   capture_cpus: pointer to return value (below)
6436  *
6437  * Returns:
6438  *   Propagates the subsystem callback return values back to the caller;
6439  *   returns 0 on success.  If capture_cpus is non-NULL, the value returned
6440  *   is zero if all of the pa_hments are of a type that do not require
6441  *   capturing CPUs prior to suspending the mapping, else it is 1.
6442  */
6443 static int
6444 hat_pageprocess_precallbacks(struct page *pp, uint_t flag, int *capture_cpus)
6445 {
6446 	struct sf_hment	*sfhmep;
6447 	struct pa_hment *pahmep;
6448 	int (*f)(caddr_t, uint_t, uint_t, void *);
6449 	int		ret;
6450 	id_t		id;
6451 	int		locked = 0;
6452 	kmutex_t	*pml;
6453 
6454 	ASSERT(PAGE_EXCL(pp));
6455 	if (!sfmmu_mlist_held(pp)) {
6456 		pml = sfmmu_mlist_enter(pp);
6457 		locked = 1;
6458 	}
6459 
6460 	if (capture_cpus)
6461 		*capture_cpus = 0;
6462 
6463 top:
6464 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6465 		/*
6466 		 * skip sf_hments corresponding to VA<->PA mappings;
6467 		 * for pa_hment's, hme_tte.ll is zero
6468 		 */
6469 		if (!IS_PAHME(sfhmep))
6470 			continue;
6471 
6472 		pahmep = sfhmep->hme_data;
6473 		ASSERT(pahmep != NULL);
6474 
6475 		/*
6476 		 * skip if pre-handler has been called earlier in this loop
6477 		 */
6478 		if (pahmep->flags & flag)
6479 			continue;
6480 
6481 		id = pahmep->cb_id;
6482 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6483 		if (capture_cpus && sfmmu_cb_table[id].capture_cpus != 0)
6484 			*capture_cpus = 1;
6485 		if ((f = sfmmu_cb_table[id].prehandler) == NULL) {
6486 			pahmep->flags |= flag;
6487 			continue;
6488 		}
6489 
6490 		/*
6491 		 * Drop the mapping list lock to avoid locking order issues.
6492 		 */
6493 		if (locked)
6494 			sfmmu_mlist_exit(pml);
6495 
6496 		ret = f(pahmep->addr, pahmep->len, flag, pahmep->pvt);
6497 		if (ret != 0)
6498 			return (ret);	/* caller must do the cleanup */
6499 
6500 		if (locked) {
6501 			pml = sfmmu_mlist_enter(pp);
6502 			pahmep->flags |= flag;
6503 			goto top;
6504 		}
6505 
6506 		pahmep->flags |= flag;
6507 	}
6508 
6509 	if (locked)
6510 		sfmmu_mlist_exit(pml);
6511 
6512 	return (0);
6513 }
6514 
6515 /*
6516  * Execute post-callback handler of each pa_hment linked to pp
6517  *
6518  * Same overall assumptions and restrictions apply as for
6519  * hat_pageprocess_precallbacks().
6520  */
6521 static void
6522 hat_pageprocess_postcallbacks(struct page *pp, uint_t flag)
6523 {
6524 	pfn_t pgpfn = pp->p_pagenum;
6525 	pfn_t pgmask = btop(page_get_pagesize(pp->p_szc)) - 1;
6526 	pfn_t newpfn;
6527 	struct sf_hment *sfhmep;
6528 	struct pa_hment *pahmep;
6529 	int (*f)(caddr_t, uint_t, uint_t, void *, pfn_t);
6530 	id_t	id;
6531 	int	locked = 0;
6532 	kmutex_t *pml;
6533 
6534 	ASSERT(PAGE_EXCL(pp));
6535 	if (!sfmmu_mlist_held(pp)) {
6536 		pml = sfmmu_mlist_enter(pp);
6537 		locked = 1;
6538 	}
6539 
6540 top:
6541 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6542 		/*
6543 		 * skip sf_hments corresponding to VA<->PA mappings;
6544 		 * for pa_hment's, hme_tte.ll is zero
6545 		 */
6546 		if (!IS_PAHME(sfhmep))
6547 			continue;
6548 
6549 		pahmep = sfhmep->hme_data;
6550 		ASSERT(pahmep != NULL);
6551 
6552 		if ((pahmep->flags & flag) == 0)
6553 			continue;
6554 
6555 		pahmep->flags &= ~flag;
6556 
6557 		id = pahmep->cb_id;
6558 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6559 		if ((f = sfmmu_cb_table[id].posthandler) == NULL)
6560 			continue;
6561 
6562 		/*
6563 		 * Convert the base page PFN into the constituent PFN
6564 		 * which is needed by the callback handler.
6565 		 */
6566 		newpfn = pgpfn | (btop((uintptr_t)pahmep->addr) & pgmask);
6567 
6568 		/*
6569 		 * Drop the mapping list lock to avoid locking order issues.
6570 		 */
6571 		if (locked)
6572 			sfmmu_mlist_exit(pml);
6573 
6574 		if (f(pahmep->addr, pahmep->len, flag, pahmep->pvt, newpfn)
6575 		    != 0)
6576 			panic("sfmmu: posthandler failed");
6577 
6578 		if (locked) {
6579 			pml = sfmmu_mlist_enter(pp);
6580 			goto top;
6581 		}
6582 	}
6583 
6584 	if (locked)
6585 		sfmmu_mlist_exit(pml);
6586 }
6587 
6588 /*
6589  * Suspend locked kernel mapping
6590  */
6591 void
6592 hat_pagesuspend(struct page *pp)
6593 {
6594 	struct sf_hment *sfhmep;
6595 	sfmmu_t *sfmmup;
6596 	tte_t tte, ttemod;
6597 	struct hme_blk *hmeblkp;
6598 	caddr_t addr;
6599 	int index, cons;
6600 	cpuset_t cpuset;
6601 
6602 	ASSERT(PAGE_EXCL(pp));
6603 	ASSERT(sfmmu_mlist_held(pp));
6604 
6605 	mutex_enter(&kpr_suspendlock);
6606 
6607 	/*
6608 	 * We're about to suspend a kernel mapping so mark this thread as
6609 	 * non-traceable by DTrace. This prevents us from running into issues
6610 	 * with probe context trying to touch a suspended page
6611 	 * in the relocation codepath itself.
6612 	 */
6613 	curthread->t_flag |= T_DONTDTRACE;
6614 
6615 	index = PP_MAPINDEX(pp);
6616 	cons = TTE8K;
6617 
6618 retry:
6619 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6620 
6621 		if (IS_PAHME(sfhmep))
6622 			continue;
6623 
6624 		if (get_hblk_ttesz(sfmmu_hmetohblk(sfhmep)) != cons)
6625 			continue;
6626 
6627 		/*
6628 		 * Loop until we successfully set the suspend bit in
6629 		 * the TTE.
6630 		 */
6631 again:
6632 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6633 		ASSERT(TTE_IS_VALID(&tte));
6634 
6635 		ttemod = tte;
6636 		TTE_SET_SUSPEND(&ttemod);
6637 		if (sfmmu_modifytte_try(&tte, &ttemod,
6638 		    &sfhmep->hme_tte) < 0)
6639 			goto again;
6640 
6641 		/*
6642 		 * Invalidate TSB entry
6643 		 */
6644 		hmeblkp = sfmmu_hmetohblk(sfhmep);
6645 
6646 		sfmmup = hblktosfmmu(hmeblkp);
6647 		ASSERT(sfmmup == ksfmmup);
6648 		ASSERT(!hmeblkp->hblk_shared);
6649 
6650 		addr = tte_to_vaddr(hmeblkp, tte);
6651 
6652 		/*
6653 		 * No need to make sure that the TSB for this sfmmu is
6654 		 * not being relocated since it is ksfmmup and thus it
6655 		 * will never be relocated.
6656 		 */
6657 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
6658 
6659 		/*
6660 		 * Update xcall stats
6661 		 */
6662 		cpuset = cpu_ready_set;
6663 		CPUSET_DEL(cpuset, CPU->cpu_id);
6664 
6665 		/* LINTED: constant in conditional context */
6666 		SFMMU_XCALL_STATS(ksfmmup);
6667 
6668 		/*
6669 		 * Flush TLB entry on remote CPU's
6670 		 */
6671 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
6672 		    (uint64_t)ksfmmup);
6673 		xt_sync(cpuset);
6674 
6675 		/*
6676 		 * Flush TLB entry on local CPU
6677 		 */
6678 		vtag_flushpage(addr, (uint64_t)ksfmmup);
6679 	}
6680 
6681 	while (index != 0) {
6682 		index = index >> 1;
6683 		if (index != 0)
6684 			cons++;
6685 		if (index & 0x1) {
6686 			pp = PP_GROUPLEADER(pp, cons);
6687 			goto retry;
6688 		}
6689 	}
6690 }
6691 
6692 #ifdef	DEBUG
6693 
6694 #define	N_PRLE	1024
6695 struct prle {
6696 	page_t *targ;
6697 	page_t *repl;
6698 	int status;
6699 	int pausecpus;
6700 	hrtime_t whence;
6701 };
6702 
6703 static struct prle page_relocate_log[N_PRLE];
6704 static int prl_entry;
6705 static kmutex_t prl_mutex;
6706 
6707 #define	PAGE_RELOCATE_LOG(t, r, s, p)					\
6708 	mutex_enter(&prl_mutex);					\
6709 	page_relocate_log[prl_entry].targ = *(t);			\
6710 	page_relocate_log[prl_entry].repl = *(r);			\
6711 	page_relocate_log[prl_entry].status = (s);			\
6712 	page_relocate_log[prl_entry].pausecpus = (p);			\
6713 	page_relocate_log[prl_entry].whence = gethrtime();		\
6714 	prl_entry = (prl_entry == (N_PRLE - 1))? 0 : prl_entry + 1;	\
6715 	mutex_exit(&prl_mutex);
6716 
6717 #else	/* !DEBUG */
6718 #define	PAGE_RELOCATE_LOG(t, r, s, p)
6719 #endif
6720 
6721 /*
6722  * Core Kernel Page Relocation Algorithm
6723  *
6724  * Input:
6725  *
6726  * target : 	constituent pages are SE_EXCL locked.
6727  * replacement:	constituent pages are SE_EXCL locked.
6728  *
6729  * Output:
6730  *
6731  * nrelocp:	number of pages relocated
6732  */
6733 int
6734 hat_page_relocate(page_t **target, page_t **replacement, spgcnt_t *nrelocp)
6735 {
6736 	page_t		*targ, *repl;
6737 	page_t		*tpp, *rpp;
6738 	kmutex_t	*low, *high;
6739 	spgcnt_t	npages, i;
6740 	page_t		*pl = NULL;
6741 	int		old_pil;
6742 	cpuset_t	cpuset;
6743 	int		cap_cpus;
6744 	int		ret;
6745 #ifdef VAC
6746 	int		cflags = 0;
6747 #endif
6748 
6749 	if (hat_kpr_enabled == 0 || !kcage_on || PP_ISNORELOC(*target)) {
6750 		PAGE_RELOCATE_LOG(target, replacement, EAGAIN, -1);
6751 		return (EAGAIN);
6752 	}
6753 
6754 	mutex_enter(&kpr_mutex);
6755 	kreloc_thread = curthread;
6756 
6757 	targ = *target;
6758 	repl = *replacement;
6759 	ASSERT(repl != NULL);
6760 	ASSERT(targ->p_szc == repl->p_szc);
6761 
6762 	npages = page_get_pagecnt(targ->p_szc);
6763 
6764 	/*
6765 	 * unload VA<->PA mappings that are not locked
6766 	 */
6767 	tpp = targ;
6768 	for (i = 0; i < npages; i++) {
6769 		(void) hat_pageunload(tpp, SFMMU_KERNEL_RELOC);
6770 		tpp++;
6771 	}
6772 
6773 	/*
6774 	 * Do "presuspend" callbacks, in a context from which we can still
6775 	 * block as needed. Note that we don't hold the mapping list lock
6776 	 * of "targ" at this point due to potential locking order issues;
6777 	 * we assume that between the hat_pageunload() above and holding
6778 	 * the SE_EXCL lock that the mapping list *cannot* change at this
6779 	 * point.
6780 	 */
6781 	ret = hat_pageprocess_precallbacks(targ, HAT_PRESUSPEND, &cap_cpus);
6782 	if (ret != 0) {
6783 		/*
6784 		 * EIO translates to fatal error, for all others cleanup
6785 		 * and return EAGAIN.
6786 		 */
6787 		ASSERT(ret != EIO);
6788 		hat_pageprocess_postcallbacks(targ, HAT_POSTUNSUSPEND);
6789 		PAGE_RELOCATE_LOG(target, replacement, ret, -1);
6790 		kreloc_thread = NULL;
6791 		mutex_exit(&kpr_mutex);
6792 		return (EAGAIN);
6793 	}
6794 
6795 	/*
6796 	 * acquire p_mapping list lock for both the target and replacement
6797 	 * root pages.
6798 	 *
6799 	 * low and high refer to the need to grab the mlist locks in a
6800 	 * specific order in order to prevent race conditions.  Thus the
6801 	 * lower lock must be grabbed before the higher lock.
6802 	 *
6803 	 * This will block hat_unload's accessing p_mapping list.  Since
6804 	 * we have SE_EXCL lock, hat_memload and hat_pageunload will be
6805 	 * blocked.  Thus, no one else will be accessing the p_mapping list
6806 	 * while we suspend and reload the locked mapping below.
6807 	 */
6808 	tpp = targ;
6809 	rpp = repl;
6810 	sfmmu_mlist_reloc_enter(tpp, rpp, &low, &high);
6811 
6812 	kpreempt_disable();
6813 
6814 	/*
6815 	 * We raise our PIL to 13 so that we don't get captured by
6816 	 * another CPU or pinned by an interrupt thread.  We can't go to
6817 	 * PIL 14 since the nexus driver(s) may need to interrupt at
6818 	 * that level in the case of IOMMU pseudo mappings.
6819 	 */
6820 	cpuset = cpu_ready_set;
6821 	CPUSET_DEL(cpuset, CPU->cpu_id);
6822 	if (!cap_cpus || CPUSET_ISNULL(cpuset)) {
6823 		old_pil = splr(XCALL_PIL);
6824 	} else {
6825 		old_pil = -1;
6826 		xc_attention(cpuset);
6827 	}
6828 	ASSERT(getpil() == XCALL_PIL);
6829 
6830 	/*
6831 	 * Now do suspend callbacks. In the case of an IOMMU mapping
6832 	 * this will suspend all DMA activity to the page while it is
6833 	 * being relocated. Since we are well above LOCK_LEVEL and CPUs
6834 	 * may be captured at this point we should have acquired any needed
6835 	 * locks in the presuspend callback.
6836 	 */
6837 	ret = hat_pageprocess_precallbacks(targ, HAT_SUSPEND, NULL);
6838 	if (ret != 0) {
6839 		repl = targ;
6840 		goto suspend_fail;
6841 	}
6842 
6843 	/*
6844 	 * Raise the PIL yet again, this time to block all high-level
6845 	 * interrupts on this CPU. This is necessary to prevent an
6846 	 * interrupt routine from pinning the thread which holds the
6847 	 * mapping suspended and then touching the suspended page.
6848 	 *
6849 	 * Once the page is suspended we also need to be careful to
6850 	 * avoid calling any functions which touch any seg_kmem memory
6851 	 * since that memory may be backed by the very page we are
6852 	 * relocating in here!
6853 	 */
6854 	hat_pagesuspend(targ);
6855 
6856 	/*
6857 	 * Now that we are confident everybody has stopped using this page,
6858 	 * copy the page contents.  Note we use a physical copy to prevent
6859 	 * locking issues and to avoid fpRAS because we can't handle it in
6860 	 * this context.
6861 	 */
6862 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6863 #ifdef VAC
6864 		/*
6865 		 * If the replacement has a different vcolor than
6866 		 * the one being replacd, we need to handle VAC
6867 		 * consistency for it just as we were setting up
6868 		 * a new mapping to it.
6869 		 */
6870 		if ((PP_GET_VCOLOR(rpp) != NO_VCOLOR) &&
6871 		    (tpp->p_vcolor != rpp->p_vcolor) &&
6872 		    !CacheColor_IsFlushed(cflags, PP_GET_VCOLOR(rpp))) {
6873 			CacheColor_SetFlushed(cflags, PP_GET_VCOLOR(rpp));
6874 			sfmmu_cache_flushcolor(PP_GET_VCOLOR(rpp),
6875 			    rpp->p_pagenum);
6876 		}
6877 #endif
6878 		/*
6879 		 * Copy the contents of the page.
6880 		 */
6881 		ppcopy_kernel(tpp, rpp);
6882 	}
6883 
6884 	tpp = targ;
6885 	rpp = repl;
6886 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6887 		/*
6888 		 * Copy attributes.  VAC consistency was handled above,
6889 		 * if required.
6890 		 */
6891 		rpp->p_nrm = tpp->p_nrm;
6892 		tpp->p_nrm = 0;
6893 		rpp->p_index = tpp->p_index;
6894 		tpp->p_index = 0;
6895 #ifdef VAC
6896 		rpp->p_vcolor = tpp->p_vcolor;
6897 #endif
6898 	}
6899 
6900 	/*
6901 	 * First, unsuspend the page, if we set the suspend bit, and transfer
6902 	 * the mapping list from the target page to the replacement page.
6903 	 * Next process postcallbacks; since pa_hment's are linked only to the
6904 	 * p_mapping list of root page, we don't iterate over the constituent
6905 	 * pages.
6906 	 */
6907 	hat_pagereload(targ, repl);
6908 
6909 suspend_fail:
6910 	hat_pageprocess_postcallbacks(repl, HAT_UNSUSPEND);
6911 
6912 	/*
6913 	 * Now lower our PIL and release any captured CPUs since we
6914 	 * are out of the "danger zone".  After this it will again be
6915 	 * safe to acquire adaptive mutex locks, or to drop them...
6916 	 */
6917 	if (old_pil != -1) {
6918 		splx(old_pil);
6919 	} else {
6920 		xc_dismissed(cpuset);
6921 	}
6922 
6923 	kpreempt_enable();
6924 
6925 	sfmmu_mlist_reloc_exit(low, high);
6926 
6927 	/*
6928 	 * Postsuspend callbacks should drop any locks held across
6929 	 * the suspend callbacks.  As before, we don't hold the mapping
6930 	 * list lock at this point.. our assumption is that the mapping
6931 	 * list still can't change due to our holding SE_EXCL lock and
6932 	 * there being no unlocked mappings left. Hence the restriction
6933 	 * on calling context to hat_delete_callback()
6934 	 */
6935 	hat_pageprocess_postcallbacks(repl, HAT_POSTUNSUSPEND);
6936 	if (ret != 0) {
6937 		/*
6938 		 * The second presuspend call failed: we got here through
6939 		 * the suspend_fail label above.
6940 		 */
6941 		ASSERT(ret != EIO);
6942 		PAGE_RELOCATE_LOG(target, replacement, ret, cap_cpus);
6943 		kreloc_thread = NULL;
6944 		mutex_exit(&kpr_mutex);
6945 		return (EAGAIN);
6946 	}
6947 
6948 	/*
6949 	 * Now that we're out of the performance critical section we can
6950 	 * take care of updating the hash table, since we still
6951 	 * hold all the pages locked SE_EXCL at this point we
6952 	 * needn't worry about things changing out from under us.
6953 	 */
6954 	tpp = targ;
6955 	rpp = repl;
6956 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6957 
6958 		/*
6959 		 * replace targ with replacement in page_hash table
6960 		 */
6961 		targ = tpp;
6962 		page_relocate_hash(rpp, targ);
6963 
6964 		/*
6965 		 * concatenate target; caller of platform_page_relocate()
6966 		 * expects target to be concatenated after returning.
6967 		 */
6968 		ASSERT(targ->p_next == targ);
6969 		ASSERT(targ->p_prev == targ);
6970 		page_list_concat(&pl, &targ);
6971 	}
6972 
6973 	ASSERT(*target == pl);
6974 	*nrelocp = npages;
6975 	PAGE_RELOCATE_LOG(target, replacement, 0, cap_cpus);
6976 	kreloc_thread = NULL;
6977 	mutex_exit(&kpr_mutex);
6978 	return (0);
6979 }
6980 
6981 /*
6982  * Called when stray pa_hments are found attached to a page which is
6983  * being freed.  Notify the subsystem which attached the pa_hment of
6984  * the error if it registered a suitable handler, else panic.
6985  */
6986 static void
6987 sfmmu_pahment_leaked(struct pa_hment *pahmep)
6988 {
6989 	id_t cb_id = pahmep->cb_id;
6990 
6991 	ASSERT(cb_id >= (id_t)0 && cb_id < sfmmu_cb_nextid);
6992 	if (sfmmu_cb_table[cb_id].errhandler != NULL) {
6993 		if (sfmmu_cb_table[cb_id].errhandler(pahmep->addr, pahmep->len,
6994 		    HAT_CB_ERR_LEAKED, pahmep->pvt) == 0)
6995 			return;		/* non-fatal */
6996 	}
6997 	panic("pa_hment leaked: 0x%p", (void *)pahmep);
6998 }
6999 
7000 /*
7001  * Remove all mappings to page 'pp'.
7002  */
7003 int
7004 hat_pageunload(struct page *pp, uint_t forceflag)
7005 {
7006 	struct page *origpp = pp;
7007 	struct sf_hment *sfhme, *tmphme;
7008 	struct hme_blk *hmeblkp;
7009 	kmutex_t *pml;
7010 #ifdef VAC
7011 	kmutex_t *pmtx;
7012 #endif
7013 	cpuset_t cpuset, tset;
7014 	int index, cons;
7015 	int xhme_blks;
7016 	int pa_hments;
7017 
7018 	ASSERT(PAGE_EXCL(pp));
7019 
7020 retry_xhat:
7021 	tmphme = NULL;
7022 	xhme_blks = 0;
7023 	pa_hments = 0;
7024 	CPUSET_ZERO(cpuset);
7025 
7026 	pml = sfmmu_mlist_enter(pp);
7027 
7028 #ifdef VAC
7029 	if (pp->p_kpmref)
7030 		sfmmu_kpm_pageunload(pp);
7031 	ASSERT(!PP_ISMAPPED_KPM(pp));
7032 #endif
7033 	/*
7034 	 * Clear vpm reference. Since the page is exclusively locked
7035 	 * vpm cannot be referencing it.
7036 	 */
7037 	if (vpm_enable) {
7038 		pp->p_vpmref = 0;
7039 	}
7040 
7041 	index = PP_MAPINDEX(pp);
7042 	cons = TTE8K;
7043 retry:
7044 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7045 		tmphme = sfhme->hme_next;
7046 
7047 		if (IS_PAHME(sfhme)) {
7048 			ASSERT(sfhme->hme_data != NULL);
7049 			pa_hments++;
7050 			continue;
7051 		}
7052 
7053 		hmeblkp = sfmmu_hmetohblk(sfhme);
7054 		if (hmeblkp->hblk_xhat_bit) {
7055 			struct xhat_hme_blk *xblk =
7056 			    (struct xhat_hme_blk *)hmeblkp;
7057 
7058 			(void) XHAT_PAGEUNLOAD(xblk->xhat_hme_blk_hat,
7059 			    pp, forceflag, XBLK2PROVBLK(xblk));
7060 
7061 			xhme_blks = 1;
7062 			continue;
7063 		}
7064 
7065 		/*
7066 		 * If there are kernel mappings don't unload them, they will
7067 		 * be suspended.
7068 		 */
7069 		if (forceflag == SFMMU_KERNEL_RELOC && hmeblkp->hblk_lckcnt &&
7070 		    hmeblkp->hblk_tag.htag_id == ksfmmup)
7071 			continue;
7072 
7073 		tset = sfmmu_pageunload(pp, sfhme, cons);
7074 		CPUSET_OR(cpuset, tset);
7075 	}
7076 
7077 	while (index != 0) {
7078 		index = index >> 1;
7079 		if (index != 0)
7080 			cons++;
7081 		if (index & 0x1) {
7082 			/* Go to leading page */
7083 			pp = PP_GROUPLEADER(pp, cons);
7084 			ASSERT(sfmmu_mlist_held(pp));
7085 			goto retry;
7086 		}
7087 	}
7088 
7089 	/*
7090 	 * cpuset may be empty if the page was only mapped by segkpm,
7091 	 * in which case we won't actually cross-trap.
7092 	 */
7093 	xt_sync(cpuset);
7094 
7095 	/*
7096 	 * The page should have no mappings at this point, unless
7097 	 * we were called from hat_page_relocate() in which case we
7098 	 * leave the locked mappings which will be suspended later.
7099 	 */
7100 	ASSERT(!PP_ISMAPPED(origpp) || xhme_blks || pa_hments ||
7101 	    (forceflag == SFMMU_KERNEL_RELOC));
7102 
7103 #ifdef VAC
7104 	if (PP_ISTNC(pp)) {
7105 		if (cons == TTE8K) {
7106 			pmtx = sfmmu_page_enter(pp);
7107 			PP_CLRTNC(pp);
7108 			sfmmu_page_exit(pmtx);
7109 		} else {
7110 			conv_tnc(pp, cons);
7111 		}
7112 	}
7113 #endif	/* VAC */
7114 
7115 	if (pa_hments && forceflag != SFMMU_KERNEL_RELOC) {
7116 		/*
7117 		 * Unlink any pa_hments and free them, calling back
7118 		 * the responsible subsystem to notify it of the error.
7119 		 * This can occur in situations such as drivers leaking
7120 		 * DMA handles: naughty, but common enough that we'd like
7121 		 * to keep the system running rather than bringing it
7122 		 * down with an obscure error like "pa_hment leaked"
7123 		 * which doesn't aid the user in debugging their driver.
7124 		 */
7125 		for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7126 			tmphme = sfhme->hme_next;
7127 			if (IS_PAHME(sfhme)) {
7128 				struct pa_hment *pahmep = sfhme->hme_data;
7129 				sfmmu_pahment_leaked(pahmep);
7130 				HME_SUB(sfhme, pp);
7131 				kmem_cache_free(pa_hment_cache, pahmep);
7132 			}
7133 		}
7134 
7135 		ASSERT(!PP_ISMAPPED(origpp) || xhme_blks);
7136 	}
7137 
7138 	sfmmu_mlist_exit(pml);
7139 
7140 	/*
7141 	 * XHAT may not have finished unloading pages
7142 	 * because some other thread was waiting for
7143 	 * mlist lock and XHAT_PAGEUNLOAD let it do
7144 	 * the job.
7145 	 */
7146 	if (xhme_blks) {
7147 		pp = origpp;
7148 		goto retry_xhat;
7149 	}
7150 
7151 	return (0);
7152 }
7153 
7154 cpuset_t
7155 sfmmu_pageunload(page_t *pp, struct sf_hment *sfhme, int cons)
7156 {
7157 	struct hme_blk *hmeblkp;
7158 	sfmmu_t *sfmmup;
7159 	tte_t tte, ttemod;
7160 #ifdef DEBUG
7161 	tte_t orig_old;
7162 #endif /* DEBUG */
7163 	caddr_t addr;
7164 	int ttesz;
7165 	int ret;
7166 	cpuset_t cpuset;
7167 
7168 	ASSERT(pp != NULL);
7169 	ASSERT(sfmmu_mlist_held(pp));
7170 	ASSERT(!PP_ISKAS(pp));
7171 
7172 	CPUSET_ZERO(cpuset);
7173 
7174 	hmeblkp = sfmmu_hmetohblk(sfhme);
7175 
7176 readtte:
7177 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7178 	if (TTE_IS_VALID(&tte)) {
7179 		sfmmup = hblktosfmmu(hmeblkp);
7180 		ttesz = get_hblk_ttesz(hmeblkp);
7181 		/*
7182 		 * Only unload mappings of 'cons' size.
7183 		 */
7184 		if (ttesz != cons)
7185 			return (cpuset);
7186 
7187 		/*
7188 		 * Note that we have p_mapping lock, but no hash lock here.
7189 		 * hblk_unload() has to have both hash lock AND p_mapping
7190 		 * lock before it tries to modify tte. So, the tte could
7191 		 * not become invalid in the sfmmu_modifytte_try() below.
7192 		 */
7193 		ttemod = tte;
7194 #ifdef DEBUG
7195 		orig_old = tte;
7196 #endif /* DEBUG */
7197 
7198 		TTE_SET_INVALID(&ttemod);
7199 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7200 		if (ret < 0) {
7201 #ifdef DEBUG
7202 			/* only R/M bits can change. */
7203 			chk_tte(&orig_old, &tte, &ttemod, hmeblkp);
7204 #endif /* DEBUG */
7205 			goto readtte;
7206 		}
7207 
7208 		if (ret == 0) {
7209 			panic("pageunload: cas failed?");
7210 		}
7211 
7212 		addr = tte_to_vaddr(hmeblkp, tte);
7213 
7214 		if (hmeblkp->hblk_shared) {
7215 			sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7216 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
7217 			sf_region_t *rgnp;
7218 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7219 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7220 			ASSERT(srdp != NULL);
7221 			rgnp = srdp->srd_hmergnp[rid];
7222 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
7223 			cpuset = sfmmu_rgntlb_demap(addr, rgnp, hmeblkp, 1);
7224 			sfmmu_ttesync(NULL, addr, &tte, pp);
7225 			ASSERT(rgnp->rgn_ttecnt[ttesz] > 0);
7226 			atomic_add_long(&rgnp->rgn_ttecnt[ttesz], -1);
7227 		} else {
7228 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
7229 			atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -1);
7230 
7231 			/*
7232 			 * We need to flush the page from the virtual cache
7233 			 * in order to prevent a virtual cache alias
7234 			 * inconsistency. The particular scenario we need
7235 			 * to worry about is:
7236 			 * Given:  va1 and va2 are two virtual address that
7237 			 * alias and will map the same physical address.
7238 			 * 1.   mapping exists from va1 to pa and data has
7239 			 *	been read into the cache.
7240 			 * 2.   unload va1.
7241 			 * 3.   load va2 and modify data using va2.
7242 			 * 4    unload va2.
7243 			 * 5.   load va1 and reference data.  Unless we flush
7244 			 *	the data cache when we unload we will get
7245 			 *	stale data.
7246 			 * This scenario is taken care of by using virtual
7247 			 * page coloring.
7248 			 */
7249 			if (sfmmup->sfmmu_ismhat) {
7250 				/*
7251 				 * Flush TSBs, TLBs and caches
7252 				 * of every process
7253 				 * sharing this ism segment.
7254 				 */
7255 				sfmmu_hat_lock_all();
7256 				mutex_enter(&ism_mlist_lock);
7257 				kpreempt_disable();
7258 				sfmmu_ismtlbcache_demap(addr, sfmmup, hmeblkp,
7259 				    pp->p_pagenum, CACHE_NO_FLUSH);
7260 				kpreempt_enable();
7261 				mutex_exit(&ism_mlist_lock);
7262 				sfmmu_hat_unlock_all();
7263 				cpuset = cpu_ready_set;
7264 			} else {
7265 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7266 				cpuset = sfmmup->sfmmu_cpusran;
7267 			}
7268 		}
7269 
7270 		/*
7271 		 * Hme_sub has to run after ttesync() and a_rss update.
7272 		 * See hblk_unload().
7273 		 */
7274 		HME_SUB(sfhme, pp);
7275 		membar_stst();
7276 
7277 		/*
7278 		 * We can not make ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
7279 		 * since pteload may have done a HME_ADD() right after
7280 		 * we did the HME_SUB() above. Hmecnt is now maintained
7281 		 * by cas only. no lock guranteed its value. The only
7282 		 * gurantee we have is the hmecnt should not be less than
7283 		 * what it should be so the hblk will not be taken away.
7284 		 * It's also important that we decremented the hmecnt after
7285 		 * we are done with hmeblkp so that this hmeblk won't be
7286 		 * stolen.
7287 		 */
7288 		ASSERT(hmeblkp->hblk_hmecnt > 0);
7289 		ASSERT(hmeblkp->hblk_vcnt > 0);
7290 		atomic_add_16(&hmeblkp->hblk_vcnt, -1);
7291 		atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
7292 		/*
7293 		 * This is bug 4063182.
7294 		 * XXX: fixme
7295 		 * ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
7296 		 *	!hmeblkp->hblk_lckcnt);
7297 		 */
7298 	} else {
7299 		panic("invalid tte? pp %p &tte %p",
7300 		    (void *)pp, (void *)&tte);
7301 	}
7302 
7303 	return (cpuset);
7304 }
7305 
7306 /*
7307  * While relocating a kernel page, this function will move the mappings
7308  * from tpp to dpp and modify any associated data with these mappings.
7309  * It also unsuspends the suspended kernel mapping.
7310  */
7311 static void
7312 hat_pagereload(struct page *tpp, struct page *dpp)
7313 {
7314 	struct sf_hment *sfhme;
7315 	tte_t tte, ttemod;
7316 	int index, cons;
7317 
7318 	ASSERT(getpil() == PIL_MAX);
7319 	ASSERT(sfmmu_mlist_held(tpp));
7320 	ASSERT(sfmmu_mlist_held(dpp));
7321 
7322 	index = PP_MAPINDEX(tpp);
7323 	cons = TTE8K;
7324 
7325 	/* Update real mappings to the page */
7326 retry:
7327 	for (sfhme = tpp->p_mapping; sfhme != NULL; sfhme = sfhme->hme_next) {
7328 		if (IS_PAHME(sfhme))
7329 			continue;
7330 		sfmmu_copytte(&sfhme->hme_tte, &tte);
7331 		ttemod = tte;
7332 
7333 		/*
7334 		 * replace old pfn with new pfn in TTE
7335 		 */
7336 		PFN_TO_TTE(ttemod, dpp->p_pagenum);
7337 
7338 		/*
7339 		 * clear suspend bit
7340 		 */
7341 		ASSERT(TTE_IS_SUSPEND(&ttemod));
7342 		TTE_CLR_SUSPEND(&ttemod);
7343 
7344 		if (sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte) < 0)
7345 			panic("hat_pagereload(): sfmmu_modifytte_try() failed");
7346 
7347 		/*
7348 		 * set hme_page point to new page
7349 		 */
7350 		sfhme->hme_page = dpp;
7351 	}
7352 
7353 	/*
7354 	 * move p_mapping list from old page to new page
7355 	 */
7356 	dpp->p_mapping = tpp->p_mapping;
7357 	tpp->p_mapping = NULL;
7358 	dpp->p_share = tpp->p_share;
7359 	tpp->p_share = 0;
7360 
7361 	while (index != 0) {
7362 		index = index >> 1;
7363 		if (index != 0)
7364 			cons++;
7365 		if (index & 0x1) {
7366 			tpp = PP_GROUPLEADER(tpp, cons);
7367 			dpp = PP_GROUPLEADER(dpp, cons);
7368 			goto retry;
7369 		}
7370 	}
7371 
7372 	curthread->t_flag &= ~T_DONTDTRACE;
7373 	mutex_exit(&kpr_suspendlock);
7374 }
7375 
7376 uint_t
7377 hat_pagesync(struct page *pp, uint_t clearflag)
7378 {
7379 	struct sf_hment *sfhme, *tmphme = NULL;
7380 	struct hme_blk *hmeblkp;
7381 	kmutex_t *pml;
7382 	cpuset_t cpuset, tset;
7383 	int	index, cons;
7384 	extern	ulong_t po_share;
7385 	page_t	*save_pp = pp;
7386 	int	stop_on_sh = 0;
7387 	uint_t	shcnt;
7388 
7389 	CPUSET_ZERO(cpuset);
7390 
7391 	if (PP_ISRO(pp) && (clearflag & HAT_SYNC_STOPON_MOD)) {
7392 		return (PP_GENERIC_ATTR(pp));
7393 	}
7394 
7395 	if ((clearflag & HAT_SYNC_ZERORM) == 0) {
7396 		if ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(pp)) {
7397 			return (PP_GENERIC_ATTR(pp));
7398 		}
7399 		if ((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(pp)) {
7400 			return (PP_GENERIC_ATTR(pp));
7401 		}
7402 		if (clearflag & HAT_SYNC_STOPON_SHARED) {
7403 			if (pp->p_share > po_share) {
7404 				hat_page_setattr(pp, P_REF);
7405 				return (PP_GENERIC_ATTR(pp));
7406 			}
7407 			stop_on_sh = 1;
7408 			shcnt = 0;
7409 		}
7410 	}
7411 
7412 	clearflag &= ~HAT_SYNC_STOPON_SHARED;
7413 	pml = sfmmu_mlist_enter(pp);
7414 	index = PP_MAPINDEX(pp);
7415 	cons = TTE8K;
7416 retry:
7417 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7418 		/*
7419 		 * We need to save the next hment on the list since
7420 		 * it is possible for pagesync to remove an invalid hment
7421 		 * from the list.
7422 		 */
7423 		tmphme = sfhme->hme_next;
7424 		if (IS_PAHME(sfhme))
7425 			continue;
7426 		/*
7427 		 * If we are looking for large mappings and this hme doesn't
7428 		 * reach the range we are seeking, just ignore it.
7429 		 */
7430 		hmeblkp = sfmmu_hmetohblk(sfhme);
7431 		if (hmeblkp->hblk_xhat_bit)
7432 			continue;
7433 
7434 		if (hme_size(sfhme) < cons)
7435 			continue;
7436 
7437 		if (stop_on_sh) {
7438 			if (hmeblkp->hblk_shared) {
7439 				sf_srd_t *srdp = hblktosrd(hmeblkp);
7440 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7441 				sf_region_t *rgnp;
7442 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7443 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7444 				ASSERT(srdp != NULL);
7445 				rgnp = srdp->srd_hmergnp[rid];
7446 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
7447 				    rgnp, rid);
7448 				shcnt += rgnp->rgn_refcnt;
7449 			} else {
7450 				shcnt++;
7451 			}
7452 			if (shcnt > po_share) {
7453 				/*
7454 				 * tell the pager to spare the page this time
7455 				 * around.
7456 				 */
7457 				hat_page_setattr(save_pp, P_REF);
7458 				index = 0;
7459 				break;
7460 			}
7461 		}
7462 		tset = sfmmu_pagesync(pp, sfhme,
7463 		    clearflag & ~HAT_SYNC_STOPON_RM);
7464 		CPUSET_OR(cpuset, tset);
7465 
7466 		/*
7467 		 * If clearflag is HAT_SYNC_DONTZERO, break out as soon
7468 		 * as the "ref" or "mod" is set or share cnt exceeds po_share.
7469 		 */
7470 		if ((clearflag & ~HAT_SYNC_STOPON_RM) == HAT_SYNC_DONTZERO &&
7471 		    (((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(save_pp)) ||
7472 		    ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(save_pp)))) {
7473 			index = 0;
7474 			break;
7475 		}
7476 	}
7477 
7478 	while (index) {
7479 		index = index >> 1;
7480 		cons++;
7481 		if (index & 0x1) {
7482 			/* Go to leading page */
7483 			pp = PP_GROUPLEADER(pp, cons);
7484 			goto retry;
7485 		}
7486 	}
7487 
7488 	xt_sync(cpuset);
7489 	sfmmu_mlist_exit(pml);
7490 	return (PP_GENERIC_ATTR(save_pp));
7491 }
7492 
7493 /*
7494  * Get all the hardware dependent attributes for a page struct
7495  */
7496 static cpuset_t
7497 sfmmu_pagesync(struct page *pp, struct sf_hment *sfhme,
7498 	uint_t clearflag)
7499 {
7500 	caddr_t addr;
7501 	tte_t tte, ttemod;
7502 	struct hme_blk *hmeblkp;
7503 	int ret;
7504 	sfmmu_t *sfmmup;
7505 	cpuset_t cpuset;
7506 
7507 	ASSERT(pp != NULL);
7508 	ASSERT(sfmmu_mlist_held(pp));
7509 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
7510 	    (clearflag == HAT_SYNC_ZERORM));
7511 
7512 	SFMMU_STAT(sf_pagesync);
7513 
7514 	CPUSET_ZERO(cpuset);
7515 
7516 sfmmu_pagesync_retry:
7517 
7518 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7519 	if (TTE_IS_VALID(&tte)) {
7520 		hmeblkp = sfmmu_hmetohblk(sfhme);
7521 		sfmmup = hblktosfmmu(hmeblkp);
7522 		addr = tte_to_vaddr(hmeblkp, tte);
7523 		if (clearflag == HAT_SYNC_ZERORM) {
7524 			ttemod = tte;
7525 			TTE_CLR_RM(&ttemod);
7526 			ret = sfmmu_modifytte_try(&tte, &ttemod,
7527 			    &sfhme->hme_tte);
7528 			if (ret < 0) {
7529 				/*
7530 				 * cas failed and the new value is not what
7531 				 * we want.
7532 				 */
7533 				goto sfmmu_pagesync_retry;
7534 			}
7535 
7536 			if (ret > 0) {
7537 				/* we win the cas */
7538 				if (hmeblkp->hblk_shared) {
7539 					sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7540 					uint_t rid =
7541 					    hmeblkp->hblk_tag.htag_rid;
7542 					sf_region_t *rgnp;
7543 					ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7544 					ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7545 					ASSERT(srdp != NULL);
7546 					rgnp = srdp->srd_hmergnp[rid];
7547 					SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7548 					    srdp, rgnp, rid);
7549 					cpuset = sfmmu_rgntlb_demap(addr,
7550 					    rgnp, hmeblkp, 1);
7551 				} else {
7552 					sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
7553 					    0, 0);
7554 					cpuset = sfmmup->sfmmu_cpusran;
7555 				}
7556 			}
7557 		}
7558 		sfmmu_ttesync(hmeblkp->hblk_shared ? NULL : sfmmup, addr,
7559 		    &tte, pp);
7560 	}
7561 	return (cpuset);
7562 }
7563 
7564 /*
7565  * Remove write permission from a mappings to a page, so that
7566  * we can detect the next modification of it. This requires modifying
7567  * the TTE then invalidating (demap) any TLB entry using that TTE.
7568  * This code is similar to sfmmu_pagesync().
7569  */
7570 static cpuset_t
7571 sfmmu_pageclrwrt(struct page *pp, struct sf_hment *sfhme)
7572 {
7573 	caddr_t addr;
7574 	tte_t tte;
7575 	tte_t ttemod;
7576 	struct hme_blk *hmeblkp;
7577 	int ret;
7578 	sfmmu_t *sfmmup;
7579 	cpuset_t cpuset;
7580 
7581 	ASSERT(pp != NULL);
7582 	ASSERT(sfmmu_mlist_held(pp));
7583 
7584 	CPUSET_ZERO(cpuset);
7585 	SFMMU_STAT(sf_clrwrt);
7586 
7587 retry:
7588 
7589 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7590 	if (TTE_IS_VALID(&tte) && TTE_IS_WRITABLE(&tte)) {
7591 		hmeblkp = sfmmu_hmetohblk(sfhme);
7592 
7593 		/*
7594 		 * xhat mappings should never be to a VMODSORT page.
7595 		 */
7596 		ASSERT(hmeblkp->hblk_xhat_bit == 0);
7597 
7598 		sfmmup = hblktosfmmu(hmeblkp);
7599 		addr = tte_to_vaddr(hmeblkp, tte);
7600 
7601 		ttemod = tte;
7602 		TTE_CLR_WRT(&ttemod);
7603 		TTE_CLR_MOD(&ttemod);
7604 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7605 
7606 		/*
7607 		 * if cas failed and the new value is not what
7608 		 * we want retry
7609 		 */
7610 		if (ret < 0)
7611 			goto retry;
7612 
7613 		/* we win the cas */
7614 		if (ret > 0) {
7615 			if (hmeblkp->hblk_shared) {
7616 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7617 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7618 				sf_region_t *rgnp;
7619 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7620 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7621 				ASSERT(srdp != NULL);
7622 				rgnp = srdp->srd_hmergnp[rid];
7623 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7624 				    srdp, rgnp, rid);
7625 				cpuset = sfmmu_rgntlb_demap(addr,
7626 				    rgnp, hmeblkp, 1);
7627 			} else {
7628 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7629 				cpuset = sfmmup->sfmmu_cpusran;
7630 			}
7631 		}
7632 	}
7633 
7634 	return (cpuset);
7635 }
7636 
7637 /*
7638  * Walk all mappings of a page, removing write permission and clearing the
7639  * ref/mod bits. This code is similar to hat_pagesync()
7640  */
7641 static void
7642 hat_page_clrwrt(page_t *pp)
7643 {
7644 	struct sf_hment *sfhme;
7645 	struct sf_hment *tmphme = NULL;
7646 	kmutex_t *pml;
7647 	cpuset_t cpuset;
7648 	cpuset_t tset;
7649 	int	index;
7650 	int	 cons;
7651 
7652 	CPUSET_ZERO(cpuset);
7653 
7654 	pml = sfmmu_mlist_enter(pp);
7655 	index = PP_MAPINDEX(pp);
7656 	cons = TTE8K;
7657 retry:
7658 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7659 		tmphme = sfhme->hme_next;
7660 
7661 		/*
7662 		 * If we are looking for large mappings and this hme doesn't
7663 		 * reach the range we are seeking, just ignore its.
7664 		 */
7665 
7666 		if (hme_size(sfhme) < cons)
7667 			continue;
7668 
7669 		tset = sfmmu_pageclrwrt(pp, sfhme);
7670 		CPUSET_OR(cpuset, tset);
7671 	}
7672 
7673 	while (index) {
7674 		index = index >> 1;
7675 		cons++;
7676 		if (index & 0x1) {
7677 			/* Go to leading page */
7678 			pp = PP_GROUPLEADER(pp, cons);
7679 			goto retry;
7680 		}
7681 	}
7682 
7683 	xt_sync(cpuset);
7684 	sfmmu_mlist_exit(pml);
7685 }
7686 
7687 /*
7688  * Set the given REF/MOD/RO bits for the given page.
7689  * For a vnode with a sorted v_pages list, we need to change
7690  * the attributes and the v_pages list together under page_vnode_mutex.
7691  */
7692 void
7693 hat_page_setattr(page_t *pp, uint_t flag)
7694 {
7695 	vnode_t		*vp = pp->p_vnode;
7696 	page_t		**listp;
7697 	kmutex_t	*pmtx;
7698 	kmutex_t	*vphm = NULL;
7699 	int		noshuffle;
7700 
7701 	noshuffle = flag & P_NSH;
7702 	flag &= ~P_NSH;
7703 
7704 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7705 
7706 	/*
7707 	 * nothing to do if attribute already set
7708 	 */
7709 	if ((pp->p_nrm & flag) == flag)
7710 		return;
7711 
7712 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp) &&
7713 	    !noshuffle) {
7714 		vphm = page_vnode_mutex(vp);
7715 		mutex_enter(vphm);
7716 	}
7717 
7718 	pmtx = sfmmu_page_enter(pp);
7719 	pp->p_nrm |= flag;
7720 	sfmmu_page_exit(pmtx);
7721 
7722 	if (vphm != NULL) {
7723 		/*
7724 		 * Some File Systems examine v_pages for NULL w/o
7725 		 * grabbing the vphm mutex. Must not let it become NULL when
7726 		 * pp is the only page on the list.
7727 		 */
7728 		if (pp->p_vpnext != pp) {
7729 			page_vpsub(&vp->v_pages, pp);
7730 			if (vp->v_pages != NULL)
7731 				listp = &vp->v_pages->p_vpprev->p_vpnext;
7732 			else
7733 				listp = &vp->v_pages;
7734 			page_vpadd(listp, pp);
7735 		}
7736 		mutex_exit(vphm);
7737 	}
7738 }
7739 
7740 void
7741 hat_page_clrattr(page_t *pp, uint_t flag)
7742 {
7743 	vnode_t		*vp = pp->p_vnode;
7744 	kmutex_t	*pmtx;
7745 
7746 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7747 
7748 	pmtx = sfmmu_page_enter(pp);
7749 
7750 	/*
7751 	 * Caller is expected to hold page's io lock for VMODSORT to work
7752 	 * correctly with pvn_vplist_dirty() and pvn_getdirty() when mod
7753 	 * bit is cleared.
7754 	 * We don't have assert to avoid tripping some existing third party
7755 	 * code. The dirty page is moved back to top of the v_page list
7756 	 * after IO is done in pvn_write_done().
7757 	 */
7758 	pp->p_nrm &= ~flag;
7759 	sfmmu_page_exit(pmtx);
7760 
7761 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
7762 
7763 		/*
7764 		 * VMODSORT works by removing write permissions and getting
7765 		 * a fault when a page is made dirty. At this point
7766 		 * we need to remove write permission from all mappings
7767 		 * to this page.
7768 		 */
7769 		hat_page_clrwrt(pp);
7770 	}
7771 }
7772 
7773 uint_t
7774 hat_page_getattr(page_t *pp, uint_t flag)
7775 {
7776 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7777 	return ((uint_t)(pp->p_nrm & flag));
7778 }
7779 
7780 /*
7781  * DEBUG kernels: verify that a kernel va<->pa translation
7782  * is safe by checking the underlying page_t is in a page
7783  * relocation-safe state.
7784  */
7785 #ifdef	DEBUG
7786 void
7787 sfmmu_check_kpfn(pfn_t pfn)
7788 {
7789 	page_t *pp;
7790 	int index, cons;
7791 
7792 	if (hat_check_vtop == 0)
7793 		return;
7794 
7795 	if (hat_kpr_enabled == 0 || kvseg.s_base == NULL || panicstr)
7796 		return;
7797 
7798 	pp = page_numtopp_nolock(pfn);
7799 	if (!pp)
7800 		return;
7801 
7802 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7803 		return;
7804 
7805 	/*
7806 	 * Handed a large kernel page, we dig up the root page since we
7807 	 * know the root page might have the lock also.
7808 	 */
7809 	if (pp->p_szc != 0) {
7810 		index = PP_MAPINDEX(pp);
7811 		cons = TTE8K;
7812 again:
7813 		while (index != 0) {
7814 			index >>= 1;
7815 			if (index != 0)
7816 				cons++;
7817 			if (index & 0x1) {
7818 				pp = PP_GROUPLEADER(pp, cons);
7819 				goto again;
7820 			}
7821 		}
7822 	}
7823 
7824 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7825 		return;
7826 
7827 	/*
7828 	 * Pages need to be locked or allocated "permanent" (either from
7829 	 * static_arena arena or explicitly setting PG_NORELOC when calling
7830 	 * page_create_va()) for VA->PA translations to be valid.
7831 	 */
7832 	if (!PP_ISNORELOC(pp))
7833 		panic("Illegal VA->PA translation, pp 0x%p not permanent",
7834 		    (void *)pp);
7835 	else
7836 		panic("Illegal VA->PA translation, pp 0x%p not locked",
7837 		    (void *)pp);
7838 }
7839 #endif	/* DEBUG */
7840 
7841 /*
7842  * Returns a page frame number for a given virtual address.
7843  * Returns PFN_INVALID to indicate an invalid mapping
7844  */
7845 pfn_t
7846 hat_getpfnum(struct hat *hat, caddr_t addr)
7847 {
7848 	pfn_t pfn;
7849 	tte_t tte;
7850 
7851 	/*
7852 	 * We would like to
7853 	 * ASSERT(AS_LOCK_HELD(as, &as->a_lock));
7854 	 * but we can't because the iommu driver will call this
7855 	 * routine at interrupt time and it can't grab the as lock
7856 	 * or it will deadlock: A thread could have the as lock
7857 	 * and be waiting for io.  The io can't complete
7858 	 * because the interrupt thread is blocked trying to grab
7859 	 * the as lock.
7860 	 */
7861 
7862 	ASSERT(hat->sfmmu_xhat_provider == NULL);
7863 
7864 	if (hat == ksfmmup) {
7865 		if (IS_KMEM_VA_LARGEPAGE(addr)) {
7866 			ASSERT(segkmem_lpszc > 0);
7867 			pfn = sfmmu_kvaszc2pfn(addr, segkmem_lpszc);
7868 			if (pfn != PFN_INVALID) {
7869 				sfmmu_check_kpfn(pfn);
7870 				return (pfn);
7871 			}
7872 		} else if (segkpm && IS_KPM_ADDR(addr)) {
7873 			return (sfmmu_kpm_vatopfn(addr));
7874 		}
7875 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7876 		    == PFN_SUSPENDED) {
7877 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7878 		}
7879 		sfmmu_check_kpfn(pfn);
7880 		return (pfn);
7881 	} else {
7882 		return (sfmmu_uvatopfn(addr, hat, NULL));
7883 	}
7884 }
7885 
7886 /*
7887  * hat_getkpfnum() is an obsolete DDI routine, and its use is discouraged.
7888  * Use hat_getpfnum(kas.a_hat, ...) instead.
7889  *
7890  * We'd like to return PFN_INVALID if the mappings have underlying page_t's
7891  * but can't right now due to the fact that some software has grown to use
7892  * this interface incorrectly. So for now when the interface is misused,
7893  * return a warning to the user that in the future it won't work in the
7894  * way they're abusing it, and carry on (after disabling page relocation).
7895  */
7896 pfn_t
7897 hat_getkpfnum(caddr_t addr)
7898 {
7899 	pfn_t pfn;
7900 	tte_t tte;
7901 	int badcaller = 0;
7902 	extern int segkmem_reloc;
7903 
7904 	if (segkpm && IS_KPM_ADDR(addr)) {
7905 		badcaller = 1;
7906 		pfn = sfmmu_kpm_vatopfn(addr);
7907 	} else {
7908 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7909 		    == PFN_SUSPENDED) {
7910 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7911 		}
7912 		badcaller = pf_is_memory(pfn);
7913 	}
7914 
7915 	if (badcaller) {
7916 		/*
7917 		 * We can't return PFN_INVALID or the caller may panic
7918 		 * or corrupt the system.  The only alternative is to
7919 		 * disable page relocation at this point for all kernel
7920 		 * memory.  This will impact any callers of page_relocate()
7921 		 * such as FMA or DR.
7922 		 *
7923 		 * RFE: Add junk here to spit out an ereport so the sysadmin
7924 		 * can be advised that he should upgrade his device driver
7925 		 * so that this doesn't happen.
7926 		 */
7927 		hat_getkpfnum_badcall(caller());
7928 		if (hat_kpr_enabled && segkmem_reloc) {
7929 			hat_kpr_enabled = 0;
7930 			segkmem_reloc = 0;
7931 			cmn_err(CE_WARN, "Kernel Page Relocation is DISABLED");
7932 		}
7933 	}
7934 	return (pfn);
7935 }
7936 
7937 /*
7938  * This routine will return both pfn and tte for the vaddr.
7939  */
7940 static pfn_t
7941 sfmmu_uvatopfn(caddr_t vaddr, struct hat *sfmmup, tte_t *ttep)
7942 {
7943 	struct hmehash_bucket *hmebp;
7944 	hmeblk_tag hblktag;
7945 	int hmeshift, hashno = 1;
7946 	struct hme_blk *hmeblkp = NULL;
7947 	tte_t tte;
7948 
7949 	struct sf_hment *sfhmep;
7950 	pfn_t pfn;
7951 
7952 	/* support for ISM */
7953 	ism_map_t	*ism_map;
7954 	ism_blk_t	*ism_blkp;
7955 	int		i;
7956 	sfmmu_t *ism_hatid = NULL;
7957 	sfmmu_t *locked_hatid = NULL;
7958 	sfmmu_t	*sv_sfmmup = sfmmup;
7959 	caddr_t	sv_vaddr = vaddr;
7960 	sf_srd_t *srdp;
7961 
7962 	if (ttep == NULL) {
7963 		ttep = &tte;
7964 	} else {
7965 		ttep->ll = 0;
7966 	}
7967 
7968 	ASSERT(sfmmup != ksfmmup);
7969 	SFMMU_STAT(sf_user_vtop);
7970 	/*
7971 	 * Set ism_hatid if vaddr falls in a ISM segment.
7972 	 */
7973 	ism_blkp = sfmmup->sfmmu_iblk;
7974 	if (ism_blkp != NULL) {
7975 		sfmmu_ismhat_enter(sfmmup, 0);
7976 		locked_hatid = sfmmup;
7977 	}
7978 	while (ism_blkp != NULL && ism_hatid == NULL) {
7979 		ism_map = ism_blkp->iblk_maps;
7980 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
7981 			if (vaddr >= ism_start(ism_map[i]) &&
7982 			    vaddr < ism_end(ism_map[i])) {
7983 				sfmmup = ism_hatid = ism_map[i].imap_ismhat;
7984 				vaddr = (caddr_t)(vaddr -
7985 				    ism_start(ism_map[i]));
7986 				break;
7987 			}
7988 		}
7989 		ism_blkp = ism_blkp->iblk_next;
7990 	}
7991 	if (locked_hatid) {
7992 		sfmmu_ismhat_exit(locked_hatid, 0);
7993 	}
7994 
7995 	hblktag.htag_id = sfmmup;
7996 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
7997 	do {
7998 		hmeshift = HME_HASH_SHIFT(hashno);
7999 		hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
8000 		hblktag.htag_rehash = hashno;
8001 		hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
8002 
8003 		SFMMU_HASH_LOCK(hmebp);
8004 
8005 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
8006 		if (hmeblkp != NULL) {
8007 			ASSERT(!hmeblkp->hblk_shared);
8008 			HBLKTOHME(sfhmep, hmeblkp, vaddr);
8009 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
8010 			SFMMU_HASH_UNLOCK(hmebp);
8011 			if (TTE_IS_VALID(ttep)) {
8012 				pfn = TTE_TO_PFN(vaddr, ttep);
8013 				return (pfn);
8014 			}
8015 			break;
8016 		}
8017 		SFMMU_HASH_UNLOCK(hmebp);
8018 		hashno++;
8019 	} while (HME_REHASH(sfmmup) && (hashno <= mmu_hashcnt));
8020 
8021 	if (SF_HMERGNMAP_ISNULL(sv_sfmmup)) {
8022 		return (PFN_INVALID);
8023 	}
8024 	srdp = sv_sfmmup->sfmmu_srdp;
8025 	ASSERT(srdp != NULL);
8026 	ASSERT(srdp->srd_refcnt != 0);
8027 	hblktag.htag_id = srdp;
8028 	hashno = 1;
8029 	do {
8030 		hmeshift = HME_HASH_SHIFT(hashno);
8031 		hblktag.htag_bspage = HME_HASH_BSPAGE(sv_vaddr, hmeshift);
8032 		hblktag.htag_rehash = hashno;
8033 		hmebp = HME_HASH_FUNCTION(srdp, sv_vaddr, hmeshift);
8034 
8035 		SFMMU_HASH_LOCK(hmebp);
8036 		for (hmeblkp = hmebp->hmeblkp; hmeblkp != NULL;
8037 		    hmeblkp = hmeblkp->hblk_next) {
8038 			uint_t rid;
8039 			sf_region_t *rgnp;
8040 			caddr_t rsaddr;
8041 			caddr_t readdr;
8042 
8043 			if (!HTAGS_EQ_SHME(hmeblkp->hblk_tag, hblktag,
8044 			    sv_sfmmup->sfmmu_hmeregion_map)) {
8045 				continue;
8046 			}
8047 			ASSERT(hmeblkp->hblk_shared);
8048 			rid = hmeblkp->hblk_tag.htag_rid;
8049 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8050 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8051 			rgnp = srdp->srd_hmergnp[rid];
8052 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
8053 			HBLKTOHME(sfhmep, hmeblkp, sv_vaddr);
8054 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
8055 			rsaddr = rgnp->rgn_saddr;
8056 			readdr = rsaddr + rgnp->rgn_size;
8057 #ifdef DEBUG
8058 			if (TTE_IS_VALID(ttep) ||
8059 			    get_hblk_ttesz(hmeblkp) > TTE8K) {
8060 				caddr_t eva = tte_to_evaddr(hmeblkp, ttep);
8061 				ASSERT(eva > sv_vaddr);
8062 				ASSERT(sv_vaddr >= rsaddr);
8063 				ASSERT(sv_vaddr < readdr);
8064 				ASSERT(eva <= readdr);
8065 			}
8066 #endif /* DEBUG */
8067 			/*
8068 			 * Continue the search if we
8069 			 * found an invalid 8K tte outside of the area
8070 			 * covered by this hmeblk's region.
8071 			 */
8072 			if (TTE_IS_VALID(ttep)) {
8073 				SFMMU_HASH_UNLOCK(hmebp);
8074 				pfn = TTE_TO_PFN(sv_vaddr, ttep);
8075 				return (pfn);
8076 			} else if (get_hblk_ttesz(hmeblkp) > TTE8K ||
8077 			    (sv_vaddr >= rsaddr && sv_vaddr < readdr)) {
8078 				SFMMU_HASH_UNLOCK(hmebp);
8079 				pfn = PFN_INVALID;
8080 				return (pfn);
8081 			}
8082 		}
8083 		SFMMU_HASH_UNLOCK(hmebp);
8084 		hashno++;
8085 	} while (hashno <= mmu_hashcnt);
8086 	return (PFN_INVALID);
8087 }
8088 
8089 
8090 /*
8091  * For compatability with AT&T and later optimizations
8092  */
8093 /* ARGSUSED */
8094 void
8095 hat_map(struct hat *hat, caddr_t addr, size_t len, uint_t flags)
8096 {
8097 	ASSERT(hat != NULL);
8098 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8099 }
8100 
8101 /*
8102  * Return the number of mappings to a particular page.  This number is an
8103  * approximation of the number of people sharing the page.
8104  *
8105  * shared hmeblks or ism hmeblks are counted as 1 mapping here.
8106  * hat_page_checkshare() can be used to compare threshold to share
8107  * count that reflects the number of region sharers albeit at higher cost.
8108  */
8109 ulong_t
8110 hat_page_getshare(page_t *pp)
8111 {
8112 	page_t *spp = pp;	/* start page */
8113 	kmutex_t *pml;
8114 	ulong_t	cnt;
8115 	int index, sz = TTE64K;
8116 
8117 	/*
8118 	 * We need to grab the mlist lock to make sure any outstanding
8119 	 * load/unloads complete.  Otherwise we could return zero
8120 	 * even though the unload(s) hasn't finished yet.
8121 	 */
8122 	pml = sfmmu_mlist_enter(spp);
8123 	cnt = spp->p_share;
8124 
8125 #ifdef VAC
8126 	if (kpm_enable)
8127 		cnt += spp->p_kpmref;
8128 #endif
8129 	if (vpm_enable && pp->p_vpmref) {
8130 		cnt += 1;
8131 	}
8132 
8133 	/*
8134 	 * If we have any large mappings, we count the number of
8135 	 * mappings that this large page is part of.
8136 	 */
8137 	index = PP_MAPINDEX(spp);
8138 	index >>= 1;
8139 	while (index) {
8140 		pp = PP_GROUPLEADER(spp, sz);
8141 		if ((index & 0x1) && pp != spp) {
8142 			cnt += pp->p_share;
8143 			spp = pp;
8144 		}
8145 		index >>= 1;
8146 		sz++;
8147 	}
8148 	sfmmu_mlist_exit(pml);
8149 	return (cnt);
8150 }
8151 
8152 /*
8153  * Return 1 if the number of mappings exceeds sh_thresh. Return 0
8154  * otherwise. Count shared hmeblks by region's refcnt.
8155  */
8156 int
8157 hat_page_checkshare(page_t *pp, ulong_t sh_thresh)
8158 {
8159 	kmutex_t *pml;
8160 	ulong_t	cnt = 0;
8161 	int index, sz = TTE8K;
8162 	struct sf_hment *sfhme, *tmphme = NULL;
8163 	struct hme_blk *hmeblkp;
8164 
8165 	pml = sfmmu_mlist_enter(pp);
8166 
8167 #ifdef VAC
8168 	if (kpm_enable)
8169 		cnt = pp->p_kpmref;
8170 #endif
8171 
8172 	if (vpm_enable && pp->p_vpmref) {
8173 		cnt += 1;
8174 	}
8175 
8176 	if (pp->p_share + cnt > sh_thresh) {
8177 		sfmmu_mlist_exit(pml);
8178 		return (1);
8179 	}
8180 
8181 	index = PP_MAPINDEX(pp);
8182 
8183 again:
8184 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
8185 		tmphme = sfhme->hme_next;
8186 		if (IS_PAHME(sfhme)) {
8187 			continue;
8188 		}
8189 
8190 		hmeblkp = sfmmu_hmetohblk(sfhme);
8191 		if (hmeblkp->hblk_xhat_bit) {
8192 			cnt++;
8193 			if (cnt > sh_thresh) {
8194 				sfmmu_mlist_exit(pml);
8195 				return (1);
8196 			}
8197 			continue;
8198 		}
8199 		if (hme_size(sfhme) != sz) {
8200 			continue;
8201 		}
8202 
8203 		if (hmeblkp->hblk_shared) {
8204 			sf_srd_t *srdp = hblktosrd(hmeblkp);
8205 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
8206 			sf_region_t *rgnp;
8207 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8208 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8209 			ASSERT(srdp != NULL);
8210 			rgnp = srdp->srd_hmergnp[rid];
8211 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
8212 			    rgnp, rid);
8213 			cnt += rgnp->rgn_refcnt;
8214 		} else {
8215 			cnt++;
8216 		}
8217 		if (cnt > sh_thresh) {
8218 			sfmmu_mlist_exit(pml);
8219 			return (1);
8220 		}
8221 	}
8222 
8223 	index >>= 1;
8224 	sz++;
8225 	while (index) {
8226 		pp = PP_GROUPLEADER(pp, sz);
8227 		ASSERT(sfmmu_mlist_held(pp));
8228 		if (index & 0x1) {
8229 			goto again;
8230 		}
8231 		index >>= 1;
8232 		sz++;
8233 	}
8234 	sfmmu_mlist_exit(pml);
8235 	return (0);
8236 }
8237 
8238 /*
8239  * Unload all large mappings to the pp and reset the p_szc field of every
8240  * constituent page according to the remaining mappings.
8241  *
8242  * pp must be locked SE_EXCL. Even though no other constituent pages are
8243  * locked it's legal to unload the large mappings to the pp because all
8244  * constituent pages of large locked mappings have to be locked SE_SHARED.
8245  * This means if we have SE_EXCL lock on one of constituent pages none of the
8246  * large mappings to pp are locked.
8247  *
8248  * Decrease p_szc field starting from the last constituent page and ending
8249  * with the root page. This method is used because other threads rely on the
8250  * root's p_szc to find the lock to syncronize on. After a root page_t's p_szc
8251  * is demoted then other threads will succeed in sfmmu_mlspl_enter(). This
8252  * ensures that p_szc changes of the constituent pages appears atomic for all
8253  * threads that use sfmmu_mlspl_enter() to examine p_szc field.
8254  *
8255  * This mechanism is only used for file system pages where it's not always
8256  * possible to get SE_EXCL locks on all constituent pages to demote the size
8257  * code (as is done for anonymous or kernel large pages).
8258  *
8259  * See more comments in front of sfmmu_mlspl_enter().
8260  */
8261 void
8262 hat_page_demote(page_t *pp)
8263 {
8264 	int index;
8265 	int sz;
8266 	cpuset_t cpuset;
8267 	int sync = 0;
8268 	page_t *rootpp;
8269 	struct sf_hment *sfhme;
8270 	struct sf_hment *tmphme = NULL;
8271 	struct hme_blk *hmeblkp;
8272 	uint_t pszc;
8273 	page_t *lastpp;
8274 	cpuset_t tset;
8275 	pgcnt_t npgs;
8276 	kmutex_t *pml;
8277 	kmutex_t *pmtx = NULL;
8278 
8279 	ASSERT(PAGE_EXCL(pp));
8280 	ASSERT(!PP_ISFREE(pp));
8281 	ASSERT(!PP_ISKAS(pp));
8282 	ASSERT(page_szc_lock_assert(pp));
8283 	pml = sfmmu_mlist_enter(pp);
8284 
8285 	pszc = pp->p_szc;
8286 	if (pszc == 0) {
8287 		goto out;
8288 	}
8289 
8290 	index = PP_MAPINDEX(pp) >> 1;
8291 
8292 	if (index) {
8293 		CPUSET_ZERO(cpuset);
8294 		sz = TTE64K;
8295 		sync = 1;
8296 	}
8297 
8298 	while (index) {
8299 		if (!(index & 0x1)) {
8300 			index >>= 1;
8301 			sz++;
8302 			continue;
8303 		}
8304 		ASSERT(sz <= pszc);
8305 		rootpp = PP_GROUPLEADER(pp, sz);
8306 		for (sfhme = rootpp->p_mapping; sfhme; sfhme = tmphme) {
8307 			tmphme = sfhme->hme_next;
8308 			ASSERT(!IS_PAHME(sfhme));
8309 			hmeblkp = sfmmu_hmetohblk(sfhme);
8310 			if (hme_size(sfhme) != sz) {
8311 				continue;
8312 			}
8313 			if (hmeblkp->hblk_xhat_bit) {
8314 				cmn_err(CE_PANIC,
8315 				    "hat_page_demote: xhat hmeblk");
8316 			}
8317 			tset = sfmmu_pageunload(rootpp, sfhme, sz);
8318 			CPUSET_OR(cpuset, tset);
8319 		}
8320 		if (index >>= 1) {
8321 			sz++;
8322 		}
8323 	}
8324 
8325 	ASSERT(!PP_ISMAPPED_LARGE(pp));
8326 
8327 	if (sync) {
8328 		xt_sync(cpuset);
8329 #ifdef VAC
8330 		if (PP_ISTNC(pp)) {
8331 			conv_tnc(rootpp, sz);
8332 		}
8333 #endif	/* VAC */
8334 	}
8335 
8336 	pmtx = sfmmu_page_enter(pp);
8337 
8338 	ASSERT(pp->p_szc == pszc);
8339 	rootpp = PP_PAGEROOT(pp);
8340 	ASSERT(rootpp->p_szc == pszc);
8341 	lastpp = PP_PAGENEXT_N(rootpp, TTEPAGES(pszc) - 1);
8342 
8343 	while (lastpp != rootpp) {
8344 		sz = PP_MAPINDEX(lastpp) ? fnd_mapping_sz(lastpp) : 0;
8345 		ASSERT(sz < pszc);
8346 		npgs = (sz == 0) ? 1 : TTEPAGES(sz);
8347 		ASSERT(P2PHASE(lastpp->p_pagenum, npgs) == npgs - 1);
8348 		while (--npgs > 0) {
8349 			lastpp->p_szc = (uchar_t)sz;
8350 			lastpp = PP_PAGEPREV(lastpp);
8351 		}
8352 		if (sz) {
8353 			/*
8354 			 * make sure before current root's pszc
8355 			 * is updated all updates to constituent pages pszc
8356 			 * fields are globally visible.
8357 			 */
8358 			membar_producer();
8359 		}
8360 		lastpp->p_szc = sz;
8361 		ASSERT(IS_P2ALIGNED(lastpp->p_pagenum, TTEPAGES(sz)));
8362 		if (lastpp != rootpp) {
8363 			lastpp = PP_PAGEPREV(lastpp);
8364 		}
8365 	}
8366 	if (sz == 0) {
8367 		/* the loop above doesn't cover this case */
8368 		rootpp->p_szc = 0;
8369 	}
8370 out:
8371 	ASSERT(pp->p_szc == 0);
8372 	if (pmtx != NULL) {
8373 		sfmmu_page_exit(pmtx);
8374 	}
8375 	sfmmu_mlist_exit(pml);
8376 }
8377 
8378 /*
8379  * Refresh the HAT ismttecnt[] element for size szc.
8380  * Caller must have set ISM busy flag to prevent mapping
8381  * lists from changing while we're traversing them.
8382  */
8383 pgcnt_t
8384 ism_tsb_entries(sfmmu_t *sfmmup, int szc)
8385 {
8386 	ism_blk_t	*ism_blkp = sfmmup->sfmmu_iblk;
8387 	ism_map_t	*ism_map;
8388 	pgcnt_t		npgs = 0;
8389 	pgcnt_t		npgs_scd = 0;
8390 	int		j;
8391 	sf_scd_t	*scdp;
8392 	uchar_t		rid;
8393 
8394 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
8395 	scdp = sfmmup->sfmmu_scdp;
8396 
8397 	for (; ism_blkp != NULL; ism_blkp = ism_blkp->iblk_next) {
8398 		ism_map = ism_blkp->iblk_maps;
8399 		for (j = 0; ism_map[j].imap_ismhat && j < ISM_MAP_SLOTS; j++) {
8400 			rid = ism_map[j].imap_rid;
8401 			ASSERT(rid == SFMMU_INVALID_ISMRID ||
8402 			    rid < sfmmup->sfmmu_srdp->srd_next_ismrid);
8403 
8404 			if (scdp != NULL && rid != SFMMU_INVALID_ISMRID &&
8405 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
8406 				/* ISM is in sfmmup's SCD */
8407 				npgs_scd +=
8408 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8409 			} else {
8410 				/* ISMs is not in SCD */
8411 				npgs +=
8412 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8413 			}
8414 		}
8415 	}
8416 	sfmmup->sfmmu_ismttecnt[szc] = npgs;
8417 	sfmmup->sfmmu_scdismttecnt[szc] = npgs_scd;
8418 	return (npgs);
8419 }
8420 
8421 /*
8422  * Yield the memory claim requirement for an address space.
8423  *
8424  * This is currently implemented as the number of bytes that have active
8425  * hardware translations that have page structures.  Therefore, it can
8426  * underestimate the traditional resident set size, eg, if the
8427  * physical page is present and the hardware translation is missing;
8428  * and it can overestimate the rss, eg, if there are active
8429  * translations to a frame buffer with page structs.
8430  * Also, it does not take sharing into account.
8431  *
8432  * Note that we don't acquire locks here since this function is most often
8433  * called from the clock thread.
8434  */
8435 size_t
8436 hat_get_mapped_size(struct hat *hat)
8437 {
8438 	size_t		assize = 0;
8439 	int 		i;
8440 
8441 	if (hat == NULL)
8442 		return (0);
8443 
8444 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8445 
8446 	for (i = 0; i < mmu_page_sizes; i++)
8447 		assize += ((pgcnt_t)hat->sfmmu_ttecnt[i] +
8448 		    (pgcnt_t)hat->sfmmu_scdrttecnt[i]) * TTEBYTES(i);
8449 
8450 	if (hat->sfmmu_iblk == NULL)
8451 		return (assize);
8452 
8453 	for (i = 0; i < mmu_page_sizes; i++)
8454 		assize += ((pgcnt_t)hat->sfmmu_ismttecnt[i] +
8455 		    (pgcnt_t)hat->sfmmu_scdismttecnt[i]) * TTEBYTES(i);
8456 
8457 	return (assize);
8458 }
8459 
8460 int
8461 hat_stats_enable(struct hat *hat)
8462 {
8463 	hatlock_t	*hatlockp;
8464 
8465 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8466 
8467 	hatlockp = sfmmu_hat_enter(hat);
8468 	hat->sfmmu_rmstat++;
8469 	sfmmu_hat_exit(hatlockp);
8470 	return (1);
8471 }
8472 
8473 void
8474 hat_stats_disable(struct hat *hat)
8475 {
8476 	hatlock_t	*hatlockp;
8477 
8478 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8479 
8480 	hatlockp = sfmmu_hat_enter(hat);
8481 	hat->sfmmu_rmstat--;
8482 	sfmmu_hat_exit(hatlockp);
8483 }
8484 
8485 /*
8486  * Routines for entering or removing  ourselves from the
8487  * ism_hat's mapping list. This is used for both private and
8488  * SCD hats.
8489  */
8490 static void
8491 iment_add(struct ism_ment *iment,  struct hat *ism_hat)
8492 {
8493 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8494 
8495 	iment->iment_prev = NULL;
8496 	iment->iment_next = ism_hat->sfmmu_iment;
8497 	if (ism_hat->sfmmu_iment) {
8498 		ism_hat->sfmmu_iment->iment_prev = iment;
8499 	}
8500 	ism_hat->sfmmu_iment = iment;
8501 }
8502 
8503 static void
8504 iment_sub(struct ism_ment *iment, struct hat *ism_hat)
8505 {
8506 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8507 
8508 	if (ism_hat->sfmmu_iment == NULL) {
8509 		panic("ism map entry remove - no entries");
8510 	}
8511 
8512 	if (iment->iment_prev) {
8513 		ASSERT(ism_hat->sfmmu_iment != iment);
8514 		iment->iment_prev->iment_next = iment->iment_next;
8515 	} else {
8516 		ASSERT(ism_hat->sfmmu_iment == iment);
8517 		ism_hat->sfmmu_iment = iment->iment_next;
8518 	}
8519 
8520 	if (iment->iment_next) {
8521 		iment->iment_next->iment_prev = iment->iment_prev;
8522 	}
8523 
8524 	/*
8525 	 * zero out the entry
8526 	 */
8527 	iment->iment_next = NULL;
8528 	iment->iment_prev = NULL;
8529 	iment->iment_hat =  NULL;
8530 	iment->iment_base_va = 0;
8531 }
8532 
8533 /*
8534  * Hat_share()/unshare() return an (non-zero) error
8535  * when saddr and daddr are not properly aligned.
8536  *
8537  * The top level mapping element determines the alignment
8538  * requirement for saddr and daddr, depending on different
8539  * architectures.
8540  *
8541  * When hat_share()/unshare() are not supported,
8542  * HATOP_SHARE()/UNSHARE() return 0
8543  */
8544 int
8545 hat_share(struct hat *sfmmup, caddr_t addr,
8546 	struct hat *ism_hatid, caddr_t sptaddr, size_t len, uint_t ismszc)
8547 {
8548 	ism_blk_t	*ism_blkp;
8549 	ism_blk_t	*new_iblk;
8550 	ism_map_t 	*ism_map;
8551 	ism_ment_t	*ism_ment;
8552 	int		i, added;
8553 	hatlock_t	*hatlockp;
8554 	int		reload_mmu = 0;
8555 	uint_t		ismshift = page_get_shift(ismszc);
8556 	size_t		ismpgsz = page_get_pagesize(ismszc);
8557 	uint_t		ismmask = (uint_t)ismpgsz - 1;
8558 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8559 	ushort_t	ismhatflag;
8560 	hat_region_cookie_t rcookie;
8561 	sf_scd_t	*old_scdp;
8562 
8563 #ifdef DEBUG
8564 	caddr_t		eaddr = addr + len;
8565 #endif /* DEBUG */
8566 
8567 	ASSERT(ism_hatid != NULL && sfmmup != NULL);
8568 	ASSERT(sptaddr == ISMID_STARTADDR);
8569 	/*
8570 	 * Check the alignment.
8571 	 */
8572 	if (!ISM_ALIGNED(ismshift, addr) || !ISM_ALIGNED(ismshift, sptaddr))
8573 		return (EINVAL);
8574 
8575 	/*
8576 	 * Check size alignment.
8577 	 */
8578 	if (!ISM_ALIGNED(ismshift, len))
8579 		return (EINVAL);
8580 
8581 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
8582 
8583 	/*
8584 	 * Allocate ism_ment for the ism_hat's mapping list, and an
8585 	 * ism map blk in case we need one.  We must do our
8586 	 * allocations before acquiring locks to prevent a deadlock
8587 	 * in the kmem allocator on the mapping list lock.
8588 	 */
8589 	new_iblk = kmem_cache_alloc(ism_blk_cache, KM_SLEEP);
8590 	ism_ment = kmem_cache_alloc(ism_ment_cache, KM_SLEEP);
8591 
8592 	/*
8593 	 * Serialize ISM mappings with the ISM busy flag, and also the
8594 	 * trap handlers.
8595 	 */
8596 	sfmmu_ismhat_enter(sfmmup, 0);
8597 
8598 	/*
8599 	 * Allocate an ism map blk if necessary.
8600 	 */
8601 	if (sfmmup->sfmmu_iblk == NULL) {
8602 		sfmmup->sfmmu_iblk = new_iblk;
8603 		bzero(new_iblk, sizeof (*new_iblk));
8604 		new_iblk->iblk_nextpa = (uint64_t)-1;
8605 		membar_stst();	/* make sure next ptr visible to all CPUs */
8606 		sfmmup->sfmmu_ismblkpa = va_to_pa((caddr_t)new_iblk);
8607 		reload_mmu = 1;
8608 		new_iblk = NULL;
8609 	}
8610 
8611 #ifdef DEBUG
8612 	/*
8613 	 * Make sure mapping does not already exist.
8614 	 */
8615 	ism_blkp = sfmmup->sfmmu_iblk;
8616 	while (ism_blkp != NULL) {
8617 		ism_map = ism_blkp->iblk_maps;
8618 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
8619 			if ((addr >= ism_start(ism_map[i]) &&
8620 			    addr < ism_end(ism_map[i])) ||
8621 			    eaddr > ism_start(ism_map[i]) &&
8622 			    eaddr <= ism_end(ism_map[i])) {
8623 				panic("sfmmu_share: Already mapped!");
8624 			}
8625 		}
8626 		ism_blkp = ism_blkp->iblk_next;
8627 	}
8628 #endif /* DEBUG */
8629 
8630 	ASSERT(ismszc >= TTE4M);
8631 	if (ismszc == TTE4M) {
8632 		ismhatflag = HAT_4M_FLAG;
8633 	} else if (ismszc == TTE32M) {
8634 		ismhatflag = HAT_32M_FLAG;
8635 	} else if (ismszc == TTE256M) {
8636 		ismhatflag = HAT_256M_FLAG;
8637 	}
8638 	/*
8639 	 * Add mapping to first available mapping slot.
8640 	 */
8641 	ism_blkp = sfmmup->sfmmu_iblk;
8642 	added = 0;
8643 	while (!added) {
8644 		ism_map = ism_blkp->iblk_maps;
8645 		for (i = 0; i < ISM_MAP_SLOTS; i++)  {
8646 			if (ism_map[i].imap_ismhat == NULL) {
8647 
8648 				ism_map[i].imap_ismhat = ism_hatid;
8649 				ism_map[i].imap_vb_shift = (uchar_t)ismshift;
8650 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8651 				ism_map[i].imap_hatflags = ismhatflag;
8652 				ism_map[i].imap_sz_mask = ismmask;
8653 				/*
8654 				 * imap_seg is checked in ISM_CHECK to see if
8655 				 * non-NULL, then other info assumed valid.
8656 				 */
8657 				membar_stst();
8658 				ism_map[i].imap_seg = (uintptr_t)addr | sh_size;
8659 				ism_map[i].imap_ment = ism_ment;
8660 
8661 				/*
8662 				 * Now add ourselves to the ism_hat's
8663 				 * mapping list.
8664 				 */
8665 				ism_ment->iment_hat = sfmmup;
8666 				ism_ment->iment_base_va = addr;
8667 				ism_hatid->sfmmu_ismhat = 1;
8668 				mutex_enter(&ism_mlist_lock);
8669 				iment_add(ism_ment, ism_hatid);
8670 				mutex_exit(&ism_mlist_lock);
8671 				added = 1;
8672 				break;
8673 			}
8674 		}
8675 		if (!added && ism_blkp->iblk_next == NULL) {
8676 			ism_blkp->iblk_next = new_iblk;
8677 			new_iblk = NULL;
8678 			bzero(ism_blkp->iblk_next,
8679 			    sizeof (*ism_blkp->iblk_next));
8680 			ism_blkp->iblk_next->iblk_nextpa = (uint64_t)-1;
8681 			membar_stst();
8682 			ism_blkp->iblk_nextpa =
8683 			    va_to_pa((caddr_t)ism_blkp->iblk_next);
8684 		}
8685 		ism_blkp = ism_blkp->iblk_next;
8686 	}
8687 
8688 	/*
8689 	 * After calling hat_join_region, sfmmup may join a new SCD or
8690 	 * move from the old scd to a new scd, in which case, we want to
8691 	 * shrink the sfmmup's private tsb size, i.e., pass shrink to
8692 	 * sfmmu_check_page_sizes at the end of this routine.
8693 	 */
8694 	old_scdp = sfmmup->sfmmu_scdp;
8695 
8696 	rcookie = hat_join_region(sfmmup, addr, len, (void *)ism_hatid, 0,
8697 	    PROT_ALL, ismszc, NULL, HAT_REGION_ISM);
8698 	if (rcookie != HAT_INVALID_REGION_COOKIE) {
8699 		ism_map[i].imap_rid = (uchar_t)((uint64_t)rcookie);
8700 	}
8701 	/*
8702 	 * Update our counters for this sfmmup's ism mappings.
8703 	 */
8704 	for (i = 0; i <= ismszc; i++) {
8705 		if (!(disable_ism_large_pages & (1 << i)))
8706 			(void) ism_tsb_entries(sfmmup, i);
8707 	}
8708 
8709 	/*
8710 	 * For ISM and DISM we do not support 512K pages, so we only only
8711 	 * search the 4M and 8K/64K hashes for 4 pagesize cpus, and search the
8712 	 * 256M or 32M, and 4M and 8K/64K hashes for 6 pagesize cpus.
8713 	 *
8714 	 * Need to set 32M/256M ISM flags to make sure
8715 	 * sfmmu_check_page_sizes() enables them on Panther.
8716 	 */
8717 	ASSERT((disable_ism_large_pages & (1 << TTE512K)) != 0);
8718 
8719 	switch (ismszc) {
8720 	case TTE256M:
8721 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_256M_ISM)) {
8722 			hatlockp = sfmmu_hat_enter(sfmmup);
8723 			SFMMU_FLAGS_SET(sfmmup, HAT_256M_ISM);
8724 			sfmmu_hat_exit(hatlockp);
8725 		}
8726 		break;
8727 	case TTE32M:
8728 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_32M_ISM)) {
8729 			hatlockp = sfmmu_hat_enter(sfmmup);
8730 			SFMMU_FLAGS_SET(sfmmup, HAT_32M_ISM);
8731 			sfmmu_hat_exit(hatlockp);
8732 		}
8733 		break;
8734 	default:
8735 		break;
8736 	}
8737 
8738 	/*
8739 	 * If we updated the ismblkpa for this HAT we must make
8740 	 * sure all CPUs running this process reload their tsbmiss area.
8741 	 * Otherwise they will fail to load the mappings in the tsbmiss
8742 	 * handler and will loop calling pagefault().
8743 	 */
8744 	if (reload_mmu) {
8745 		hatlockp = sfmmu_hat_enter(sfmmup);
8746 		sfmmu_sync_mmustate(sfmmup);
8747 		sfmmu_hat_exit(hatlockp);
8748 	}
8749 
8750 	sfmmu_ismhat_exit(sfmmup, 0);
8751 
8752 	/*
8753 	 * Free up ismblk if we didn't use it.
8754 	 */
8755 	if (new_iblk != NULL)
8756 		kmem_cache_free(ism_blk_cache, new_iblk);
8757 
8758 	/*
8759 	 * Check TSB and TLB page sizes.
8760 	 */
8761 	if (sfmmup->sfmmu_scdp != NULL && old_scdp != sfmmup->sfmmu_scdp) {
8762 		sfmmu_check_page_sizes(sfmmup, 0);
8763 	} else {
8764 		sfmmu_check_page_sizes(sfmmup, 1);
8765 	}
8766 	return (0);
8767 }
8768 
8769 /*
8770  * hat_unshare removes exactly one ism_map from
8771  * this process's as.  It expects multiple calls
8772  * to hat_unshare for multiple shm segments.
8773  */
8774 void
8775 hat_unshare(struct hat *sfmmup, caddr_t addr, size_t len, uint_t ismszc)
8776 {
8777 	ism_map_t 	*ism_map;
8778 	ism_ment_t	*free_ment = NULL;
8779 	ism_blk_t	*ism_blkp;
8780 	struct hat	*ism_hatid;
8781 	int 		found, i;
8782 	hatlock_t	*hatlockp;
8783 	struct tsb_info	*tsbinfo;
8784 	uint_t		ismshift = page_get_shift(ismszc);
8785 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8786 	uchar_t		ism_rid;
8787 	sf_scd_t	*old_scdp;
8788 
8789 	ASSERT(ISM_ALIGNED(ismshift, addr));
8790 	ASSERT(ISM_ALIGNED(ismshift, len));
8791 	ASSERT(sfmmup != NULL);
8792 	ASSERT(sfmmup != ksfmmup);
8793 
8794 	if (sfmmup->sfmmu_xhat_provider) {
8795 		XHAT_UNSHARE(sfmmup, addr, len);
8796 		return;
8797 	} else {
8798 		/*
8799 		 * This must be a CPU HAT. If the address space has
8800 		 * XHATs attached, inform all XHATs that ISM segment
8801 		 * is going away
8802 		 */
8803 		ASSERT(sfmmup->sfmmu_as != NULL);
8804 		if (sfmmup->sfmmu_as->a_xhat != NULL)
8805 			xhat_unshare_all(sfmmup->sfmmu_as, addr, len);
8806 	}
8807 
8808 	/*
8809 	 * Make sure that during the entire time ISM mappings are removed,
8810 	 * the trap handlers serialize behind us, and that no one else
8811 	 * can be mucking with ISM mappings.  This also lets us get away
8812 	 * with not doing expensive cross calls to flush the TLB -- we
8813 	 * just discard the context, flush the entire TSB, and call it
8814 	 * a day.
8815 	 */
8816 	sfmmu_ismhat_enter(sfmmup, 0);
8817 
8818 	/*
8819 	 * Remove the mapping.
8820 	 *
8821 	 * We can't have any holes in the ism map.
8822 	 * The tsb miss code while searching the ism map will
8823 	 * stop on an empty map slot.  So we must move
8824 	 * everyone past the hole up 1 if any.
8825 	 *
8826 	 * Also empty ism map blks are not freed until the
8827 	 * process exits. This is to prevent a MT race condition
8828 	 * between sfmmu_unshare() and sfmmu_tsbmiss_exception().
8829 	 */
8830 	found = 0;
8831 	ism_blkp = sfmmup->sfmmu_iblk;
8832 	while (!found && ism_blkp != NULL) {
8833 		ism_map = ism_blkp->iblk_maps;
8834 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
8835 			if (addr == ism_start(ism_map[i]) &&
8836 			    sh_size == (size_t)(ism_size(ism_map[i]))) {
8837 				found = 1;
8838 				break;
8839 			}
8840 		}
8841 		if (!found)
8842 			ism_blkp = ism_blkp->iblk_next;
8843 	}
8844 
8845 	if (found) {
8846 		ism_hatid = ism_map[i].imap_ismhat;
8847 		ism_rid = ism_map[i].imap_rid;
8848 		ASSERT(ism_hatid != NULL);
8849 		ASSERT(ism_hatid->sfmmu_ismhat == 1);
8850 
8851 		/*
8852 		 * After hat_leave_region, the sfmmup may leave SCD,
8853 		 * in which case, we want to grow the private tsb size when
8854 		 * calling sfmmu_check_page_sizes at the end of the routine.
8855 		 */
8856 		old_scdp = sfmmup->sfmmu_scdp;
8857 		/*
8858 		 * Then remove ourselves from the region.
8859 		 */
8860 		if (ism_rid != SFMMU_INVALID_ISMRID) {
8861 			hat_leave_region(sfmmup, (void *)((uint64_t)ism_rid),
8862 			    HAT_REGION_ISM);
8863 		}
8864 
8865 		/*
8866 		 * And now guarantee that any other cpu
8867 		 * that tries to process an ISM miss
8868 		 * will go to tl=0.
8869 		 */
8870 		hatlockp = sfmmu_hat_enter(sfmmup);
8871 		sfmmu_invalidate_ctx(sfmmup);
8872 		sfmmu_hat_exit(hatlockp);
8873 
8874 		/*
8875 		 * Remove ourselves from the ism mapping list.
8876 		 */
8877 		mutex_enter(&ism_mlist_lock);
8878 		iment_sub(ism_map[i].imap_ment, ism_hatid);
8879 		mutex_exit(&ism_mlist_lock);
8880 		free_ment = ism_map[i].imap_ment;
8881 
8882 		/*
8883 		 * We delete the ism map by copying
8884 		 * the next map over the current one.
8885 		 * We will take the next one in the maps
8886 		 * array or from the next ism_blk.
8887 		 */
8888 		while (ism_blkp != NULL) {
8889 			ism_map = ism_blkp->iblk_maps;
8890 			while (i < (ISM_MAP_SLOTS - 1)) {
8891 				ism_map[i] = ism_map[i + 1];
8892 				i++;
8893 			}
8894 			/* i == (ISM_MAP_SLOTS - 1) */
8895 			ism_blkp = ism_blkp->iblk_next;
8896 			if (ism_blkp != NULL) {
8897 				ism_map[i] = ism_blkp->iblk_maps[0];
8898 				i = 0;
8899 			} else {
8900 				ism_map[i].imap_seg = 0;
8901 				ism_map[i].imap_vb_shift = 0;
8902 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8903 				ism_map[i].imap_hatflags = 0;
8904 				ism_map[i].imap_sz_mask = 0;
8905 				ism_map[i].imap_ismhat = NULL;
8906 				ism_map[i].imap_ment = NULL;
8907 			}
8908 		}
8909 
8910 		/*
8911 		 * Now flush entire TSB for the process, since
8912 		 * demapping page by page can be too expensive.
8913 		 * We don't have to flush the TLB here anymore
8914 		 * since we switch to a new TLB ctx instead.
8915 		 * Also, there is no need to flush if the process
8916 		 * is exiting since the TSB will be freed later.
8917 		 */
8918 		if (!sfmmup->sfmmu_free) {
8919 			hatlockp = sfmmu_hat_enter(sfmmup);
8920 			for (tsbinfo = sfmmup->sfmmu_tsb; tsbinfo != NULL;
8921 			    tsbinfo = tsbinfo->tsb_next) {
8922 				if (tsbinfo->tsb_flags & TSB_SWAPPED)
8923 					continue;
8924 				if (tsbinfo->tsb_flags & TSB_RELOC_FLAG) {
8925 					tsbinfo->tsb_flags |=
8926 					    TSB_FLUSH_NEEDED;
8927 					continue;
8928 				}
8929 
8930 				sfmmu_inv_tsb(tsbinfo->tsb_va,
8931 				    TSB_BYTES(tsbinfo->tsb_szc));
8932 			}
8933 			sfmmu_hat_exit(hatlockp);
8934 		}
8935 	}
8936 
8937 	/*
8938 	 * Update our counters for this sfmmup's ism mappings.
8939 	 */
8940 	for (i = 0; i <= ismszc; i++) {
8941 		if (!(disable_ism_large_pages & (1 << i)))
8942 			(void) ism_tsb_entries(sfmmup, i);
8943 	}
8944 
8945 	sfmmu_ismhat_exit(sfmmup, 0);
8946 
8947 	/*
8948 	 * We must do our freeing here after dropping locks
8949 	 * to prevent a deadlock in the kmem allocator on the
8950 	 * mapping list lock.
8951 	 */
8952 	if (free_ment != NULL)
8953 		kmem_cache_free(ism_ment_cache, free_ment);
8954 
8955 	/*
8956 	 * Check TSB and TLB page sizes if the process isn't exiting.
8957 	 */
8958 	if (!sfmmup->sfmmu_free) {
8959 		if (found && old_scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
8960 			sfmmu_check_page_sizes(sfmmup, 1);
8961 		} else {
8962 			sfmmu_check_page_sizes(sfmmup, 0);
8963 		}
8964 	}
8965 }
8966 
8967 /* ARGSUSED */
8968 static int
8969 sfmmu_idcache_constructor(void *buf, void *cdrarg, int kmflags)
8970 {
8971 	/* void *buf is sfmmu_t pointer */
8972 	bzero(buf, sizeof (sfmmu_t));
8973 
8974 	return (0);
8975 }
8976 
8977 /* ARGSUSED */
8978 static void
8979 sfmmu_idcache_destructor(void *buf, void *cdrarg)
8980 {
8981 	/* void *buf is sfmmu_t pointer */
8982 }
8983 
8984 /*
8985  * setup kmem hmeblks by bzeroing all members and initializing the nextpa
8986  * field to be the pa of this hmeblk
8987  */
8988 /* ARGSUSED */
8989 static int
8990 sfmmu_hblkcache_constructor(void *buf, void *cdrarg, int kmflags)
8991 {
8992 	struct hme_blk *hmeblkp;
8993 
8994 	bzero(buf, (size_t)cdrarg);
8995 	hmeblkp = (struct hme_blk *)buf;
8996 	hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
8997 
8998 #ifdef	HBLK_TRACE
8999 	mutex_init(&hmeblkp->hblk_audit_lock, NULL, MUTEX_DEFAULT, NULL);
9000 #endif	/* HBLK_TRACE */
9001 
9002 	return (0);
9003 }
9004 
9005 /* ARGSUSED */
9006 static void
9007 sfmmu_hblkcache_destructor(void *buf, void *cdrarg)
9008 {
9009 
9010 #ifdef	HBLK_TRACE
9011 
9012 	struct hme_blk *hmeblkp;
9013 
9014 	hmeblkp = (struct hme_blk *)buf;
9015 	mutex_destroy(&hmeblkp->hblk_audit_lock);
9016 
9017 #endif	/* HBLK_TRACE */
9018 }
9019 
9020 #define	SFMMU_CACHE_RECLAIM_SCAN_RATIO 8
9021 static int sfmmu_cache_reclaim_scan_ratio = SFMMU_CACHE_RECLAIM_SCAN_RATIO;
9022 /*
9023  * The kmem allocator will callback into our reclaim routine when the system
9024  * is running low in memory.  We traverse the hash and free up all unused but
9025  * still cached hme_blks.  We also traverse the free list and free them up
9026  * as well.
9027  */
9028 /*ARGSUSED*/
9029 static void
9030 sfmmu_hblkcache_reclaim(void *cdrarg)
9031 {
9032 	int i;
9033 	struct hmehash_bucket *hmebp;
9034 	struct hme_blk *hmeblkp, *nx_hblk, *pr_hblk = NULL;
9035 	static struct hmehash_bucket *uhmehash_reclaim_hand;
9036 	static struct hmehash_bucket *khmehash_reclaim_hand;
9037 	struct hme_blk *list = NULL, *last_hmeblkp;
9038 	cpuset_t cpuset = cpu_ready_set;
9039 	cpu_hme_pend_t *cpuhp;
9040 
9041 	/* Free up hmeblks on the cpu pending lists */
9042 	for (i = 0; i < NCPU; i++) {
9043 		cpuhp = &cpu_hme_pend[i];
9044 		if (cpuhp->chp_listp != NULL)  {
9045 			mutex_enter(&cpuhp->chp_mutex);
9046 			if (cpuhp->chp_listp == NULL) {
9047 				mutex_exit(&cpuhp->chp_mutex);
9048 				continue;
9049 			}
9050 			for (last_hmeblkp = cpuhp->chp_listp;
9051 			    last_hmeblkp->hblk_next != NULL;
9052 			    last_hmeblkp = last_hmeblkp->hblk_next)
9053 				;
9054 			last_hmeblkp->hblk_next = list;
9055 			list = cpuhp->chp_listp;
9056 			cpuhp->chp_listp = NULL;
9057 			cpuhp->chp_count = 0;
9058 			mutex_exit(&cpuhp->chp_mutex);
9059 		}
9060 
9061 	}
9062 
9063 	if (list != NULL) {
9064 		kpreempt_disable();
9065 		CPUSET_DEL(cpuset, CPU->cpu_id);
9066 		xt_sync(cpuset);
9067 		xt_sync(cpuset);
9068 		kpreempt_enable();
9069 		sfmmu_hblk_free(&list);
9070 		list = NULL;
9071 	}
9072 
9073 	hmebp = uhmehash_reclaim_hand;
9074 	if (hmebp == NULL || hmebp > &uhme_hash[UHMEHASH_SZ])
9075 		uhmehash_reclaim_hand = hmebp = uhme_hash;
9076 	uhmehash_reclaim_hand += UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9077 
9078 	for (i = UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9079 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9080 			hmeblkp = hmebp->hmeblkp;
9081 			pr_hblk = NULL;
9082 			while (hmeblkp) {
9083 				nx_hblk = hmeblkp->hblk_next;
9084 				if (!hmeblkp->hblk_vcnt &&
9085 				    !hmeblkp->hblk_hmecnt) {
9086 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9087 					    pr_hblk, &list, 0);
9088 				} else {
9089 					pr_hblk = hmeblkp;
9090 				}
9091 				hmeblkp = nx_hblk;
9092 			}
9093 			SFMMU_HASH_UNLOCK(hmebp);
9094 		}
9095 		if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
9096 			hmebp = uhme_hash;
9097 	}
9098 
9099 	hmebp = khmehash_reclaim_hand;
9100 	if (hmebp == NULL || hmebp > &khme_hash[KHMEHASH_SZ])
9101 		khmehash_reclaim_hand = hmebp = khme_hash;
9102 	khmehash_reclaim_hand += KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9103 
9104 	for (i = KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9105 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9106 			hmeblkp = hmebp->hmeblkp;
9107 			pr_hblk = NULL;
9108 			while (hmeblkp) {
9109 				nx_hblk = hmeblkp->hblk_next;
9110 				if (!hmeblkp->hblk_vcnt &&
9111 				    !hmeblkp->hblk_hmecnt) {
9112 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9113 					    pr_hblk, &list, 0);
9114 				} else {
9115 					pr_hblk = hmeblkp;
9116 				}
9117 				hmeblkp = nx_hblk;
9118 			}
9119 			SFMMU_HASH_UNLOCK(hmebp);
9120 		}
9121 		if (hmebp++ == &khme_hash[KHMEHASH_SZ])
9122 			hmebp = khme_hash;
9123 	}
9124 	sfmmu_hblks_list_purge(&list, 0);
9125 }
9126 
9127 /*
9128  * sfmmu_get_ppvcolor should become a vm_machdep or hatop interface.
9129  * same goes for sfmmu_get_addrvcolor().
9130  *
9131  * This function will return the virtual color for the specified page. The
9132  * virtual color corresponds to this page current mapping or its last mapping.
9133  * It is used by memory allocators to choose addresses with the correct
9134  * alignment so vac consistency is automatically maintained.  If the page
9135  * has no color it returns -1.
9136  */
9137 /*ARGSUSED*/
9138 int
9139 sfmmu_get_ppvcolor(struct page *pp)
9140 {
9141 #ifdef VAC
9142 	int color;
9143 
9144 	if (!(cache & CACHE_VAC) || PP_NEWPAGE(pp)) {
9145 		return (-1);
9146 	}
9147 	color = PP_GET_VCOLOR(pp);
9148 	ASSERT(color < mmu_btop(shm_alignment));
9149 	return (color);
9150 #else
9151 	return (-1);
9152 #endif	/* VAC */
9153 }
9154 
9155 /*
9156  * This function will return the desired alignment for vac consistency
9157  * (vac color) given a virtual address.  If no vac is present it returns -1.
9158  */
9159 /*ARGSUSED*/
9160 int
9161 sfmmu_get_addrvcolor(caddr_t vaddr)
9162 {
9163 #ifdef VAC
9164 	if (cache & CACHE_VAC) {
9165 		return (addr_to_vcolor(vaddr));
9166 	} else {
9167 		return (-1);
9168 	}
9169 #else
9170 	return (-1);
9171 #endif	/* VAC */
9172 }
9173 
9174 #ifdef VAC
9175 /*
9176  * Check for conflicts.
9177  * A conflict exists if the new and existent mappings do not match in
9178  * their "shm_alignment fields. If conflicts exist, the existant mappings
9179  * are flushed unless one of them is locked. If one of them is locked, then
9180  * the mappings are flushed and converted to non-cacheable mappings.
9181  */
9182 static void
9183 sfmmu_vac_conflict(struct hat *hat, caddr_t addr, page_t *pp)
9184 {
9185 	struct hat *tmphat;
9186 	struct sf_hment *sfhmep, *tmphme = NULL;
9187 	struct hme_blk *hmeblkp;
9188 	int vcolor;
9189 	tte_t tte;
9190 
9191 	ASSERT(sfmmu_mlist_held(pp));
9192 	ASSERT(!PP_ISNC(pp));		/* page better be cacheable */
9193 
9194 	vcolor = addr_to_vcolor(addr);
9195 	if (PP_NEWPAGE(pp)) {
9196 		PP_SET_VCOLOR(pp, vcolor);
9197 		return;
9198 	}
9199 
9200 	if (PP_GET_VCOLOR(pp) == vcolor) {
9201 		return;
9202 	}
9203 
9204 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
9205 		/*
9206 		 * Previous user of page had a different color
9207 		 * but since there are no current users
9208 		 * we just flush the cache and change the color.
9209 		 */
9210 		SFMMU_STAT(sf_pgcolor_conflict);
9211 		sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9212 		PP_SET_VCOLOR(pp, vcolor);
9213 		return;
9214 	}
9215 
9216 	/*
9217 	 * If we get here we have a vac conflict with a current
9218 	 * mapping.  VAC conflict policy is as follows.
9219 	 * - The default is to unload the other mappings unless:
9220 	 * - If we have a large mapping we uncache the page.
9221 	 * We need to uncache the rest of the large page too.
9222 	 * - If any of the mappings are locked we uncache the page.
9223 	 * - If the requested mapping is inconsistent
9224 	 * with another mapping and that mapping
9225 	 * is in the same address space we have to
9226 	 * make it non-cached.  The default thing
9227 	 * to do is unload the inconsistent mapping
9228 	 * but if they are in the same address space
9229 	 * we run the risk of unmapping the pc or the
9230 	 * stack which we will use as we return to the user,
9231 	 * in which case we can then fault on the thing
9232 	 * we just unloaded and get into an infinite loop.
9233 	 */
9234 	if (PP_ISMAPPED_LARGE(pp)) {
9235 		int sz;
9236 
9237 		/*
9238 		 * Existing mapping is for big pages. We don't unload
9239 		 * existing big mappings to satisfy new mappings.
9240 		 * Always convert all mappings to TNC.
9241 		 */
9242 		sz = fnd_mapping_sz(pp);
9243 		pp = PP_GROUPLEADER(pp, sz);
9244 		SFMMU_STAT_ADD(sf_uncache_conflict, TTEPAGES(sz));
9245 		sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH,
9246 		    TTEPAGES(sz));
9247 
9248 		return;
9249 	}
9250 
9251 	/*
9252 	 * check if any mapping is in same as or if it is locked
9253 	 * since in that case we need to uncache.
9254 	 */
9255 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9256 		tmphme = sfhmep->hme_next;
9257 		if (IS_PAHME(sfhmep))
9258 			continue;
9259 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9260 		if (hmeblkp->hblk_xhat_bit)
9261 			continue;
9262 		tmphat = hblktosfmmu(hmeblkp);
9263 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
9264 		ASSERT(TTE_IS_VALID(&tte));
9265 		if (hmeblkp->hblk_shared || tmphat == hat ||
9266 		    hmeblkp->hblk_lckcnt) {
9267 			/*
9268 			 * We have an uncache conflict
9269 			 */
9270 			SFMMU_STAT(sf_uncache_conflict);
9271 			sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH, 1);
9272 			return;
9273 		}
9274 	}
9275 
9276 	/*
9277 	 * We have an unload conflict
9278 	 * We have already checked for LARGE mappings, therefore
9279 	 * the remaining mapping(s) must be TTE8K.
9280 	 */
9281 	SFMMU_STAT(sf_unload_conflict);
9282 
9283 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9284 		tmphme = sfhmep->hme_next;
9285 		if (IS_PAHME(sfhmep))
9286 			continue;
9287 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9288 		if (hmeblkp->hblk_xhat_bit)
9289 			continue;
9290 		ASSERT(!hmeblkp->hblk_shared);
9291 		(void) sfmmu_pageunload(pp, sfhmep, TTE8K);
9292 	}
9293 
9294 	if (PP_ISMAPPED_KPM(pp))
9295 		sfmmu_kpm_vac_unload(pp, addr);
9296 
9297 	/*
9298 	 * Unloads only do TLB flushes so we need to flush the
9299 	 * cache here.
9300 	 */
9301 	sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9302 	PP_SET_VCOLOR(pp, vcolor);
9303 }
9304 
9305 /*
9306  * Whenever a mapping is unloaded and the page is in TNC state,
9307  * we see if the page can be made cacheable again. 'pp' is
9308  * the page that we just unloaded a mapping from, the size
9309  * of mapping that was unloaded is 'ottesz'.
9310  * Remark:
9311  * The recache policy for mpss pages can leave a performance problem
9312  * under the following circumstances:
9313  * . A large page in uncached mode has just been unmapped.
9314  * . All constituent pages are TNC due to a conflicting small mapping.
9315  * . There are many other, non conflicting, small mappings around for
9316  *   a lot of the constituent pages.
9317  * . We're called w/ the "old" groupleader page and the old ottesz,
9318  *   but this is irrelevant, since we're no more "PP_ISMAPPED_LARGE", so
9319  *   we end up w/ TTE8K or npages == 1.
9320  * . We call tst_tnc w/ the old groupleader only, and if there is no
9321  *   conflict, we re-cache only this page.
9322  * . All other small mappings are not checked and will be left in TNC mode.
9323  * The problem is not very serious because:
9324  * . mpss is actually only defined for heap and stack, so the probability
9325  *   is not very high that a large page mapping exists in parallel to a small
9326  *   one (this is possible, but seems to be bad programming style in the
9327  *   appl).
9328  * . The problem gets a little bit more serious, when those TNC pages
9329  *   have to be mapped into kernel space, e.g. for networking.
9330  * . When VAC alias conflicts occur in applications, this is regarded
9331  *   as an application bug. So if kstat's show them, the appl should
9332  *   be changed anyway.
9333  */
9334 void
9335 conv_tnc(page_t *pp, int ottesz)
9336 {
9337 	int cursz, dosz;
9338 	pgcnt_t curnpgs, dopgs;
9339 	pgcnt_t pg64k;
9340 	page_t *pp2;
9341 
9342 	/*
9343 	 * Determine how big a range we check for TNC and find
9344 	 * leader page. cursz is the size of the biggest
9345 	 * mapping that still exist on 'pp'.
9346 	 */
9347 	if (PP_ISMAPPED_LARGE(pp)) {
9348 		cursz = fnd_mapping_sz(pp);
9349 	} else {
9350 		cursz = TTE8K;
9351 	}
9352 
9353 	if (ottesz >= cursz) {
9354 		dosz = ottesz;
9355 		pp2 = pp;
9356 	} else {
9357 		dosz = cursz;
9358 		pp2 = PP_GROUPLEADER(pp, dosz);
9359 	}
9360 
9361 	pg64k = TTEPAGES(TTE64K);
9362 	dopgs = TTEPAGES(dosz);
9363 
9364 	ASSERT(dopgs == 1 || ((dopgs & (pg64k - 1)) == 0));
9365 
9366 	while (dopgs != 0) {
9367 		curnpgs = TTEPAGES(cursz);
9368 		if (tst_tnc(pp2, curnpgs)) {
9369 			SFMMU_STAT_ADD(sf_recache, curnpgs);
9370 			sfmmu_page_cache_array(pp2, HAT_CACHE, CACHE_NO_FLUSH,
9371 			    curnpgs);
9372 		}
9373 
9374 		ASSERT(dopgs >= curnpgs);
9375 		dopgs -= curnpgs;
9376 
9377 		if (dopgs == 0) {
9378 			break;
9379 		}
9380 
9381 		pp2 = PP_PAGENEXT_N(pp2, curnpgs);
9382 		if (((dopgs & (pg64k - 1)) == 0) && PP_ISMAPPED_LARGE(pp2)) {
9383 			cursz = fnd_mapping_sz(pp2);
9384 		} else {
9385 			cursz = TTE8K;
9386 		}
9387 	}
9388 }
9389 
9390 /*
9391  * Returns 1 if page(s) can be converted from TNC to cacheable setting,
9392  * returns 0 otherwise. Note that oaddr argument is valid for only
9393  * 8k pages.
9394  */
9395 int
9396 tst_tnc(page_t *pp, pgcnt_t npages)
9397 {
9398 	struct	sf_hment *sfhme;
9399 	struct	hme_blk *hmeblkp;
9400 	tte_t	tte;
9401 	caddr_t	vaddr;
9402 	int	clr_valid = 0;
9403 	int 	color, color1, bcolor;
9404 	int	i, ncolors;
9405 
9406 	ASSERT(pp != NULL);
9407 	ASSERT(!(cache & CACHE_WRITEBACK));
9408 
9409 	if (npages > 1) {
9410 		ncolors = CACHE_NUM_COLOR;
9411 	}
9412 
9413 	for (i = 0; i < npages; i++) {
9414 		ASSERT(sfmmu_mlist_held(pp));
9415 		ASSERT(PP_ISTNC(pp));
9416 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
9417 
9418 		if (PP_ISPNC(pp)) {
9419 			return (0);
9420 		}
9421 
9422 		clr_valid = 0;
9423 		if (PP_ISMAPPED_KPM(pp)) {
9424 			caddr_t kpmvaddr;
9425 
9426 			ASSERT(kpm_enable);
9427 			kpmvaddr = hat_kpm_page2va(pp, 1);
9428 			ASSERT(!(npages > 1 && IS_KPM_ALIAS_RANGE(kpmvaddr)));
9429 			color1 = addr_to_vcolor(kpmvaddr);
9430 			clr_valid = 1;
9431 		}
9432 
9433 		for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9434 			if (IS_PAHME(sfhme))
9435 				continue;
9436 			hmeblkp = sfmmu_hmetohblk(sfhme);
9437 			if (hmeblkp->hblk_xhat_bit)
9438 				continue;
9439 
9440 			sfmmu_copytte(&sfhme->hme_tte, &tte);
9441 			ASSERT(TTE_IS_VALID(&tte));
9442 
9443 			vaddr = tte_to_vaddr(hmeblkp, tte);
9444 			color = addr_to_vcolor(vaddr);
9445 
9446 			if (npages > 1) {
9447 				/*
9448 				 * If there is a big mapping, make sure
9449 				 * 8K mapping is consistent with the big
9450 				 * mapping.
9451 				 */
9452 				bcolor = i % ncolors;
9453 				if (color != bcolor) {
9454 					return (0);
9455 				}
9456 			}
9457 			if (!clr_valid) {
9458 				clr_valid = 1;
9459 				color1 = color;
9460 			}
9461 
9462 			if (color1 != color) {
9463 				return (0);
9464 			}
9465 		}
9466 
9467 		pp = PP_PAGENEXT(pp);
9468 	}
9469 
9470 	return (1);
9471 }
9472 
9473 void
9474 sfmmu_page_cache_array(page_t *pp, int flags, int cache_flush_flag,
9475 	pgcnt_t npages)
9476 {
9477 	kmutex_t *pmtx;
9478 	int i, ncolors, bcolor;
9479 	kpm_hlk_t *kpmp;
9480 	cpuset_t cpuset;
9481 
9482 	ASSERT(pp != NULL);
9483 	ASSERT(!(cache & CACHE_WRITEBACK));
9484 
9485 	kpmp = sfmmu_kpm_kpmp_enter(pp, npages);
9486 	pmtx = sfmmu_page_enter(pp);
9487 
9488 	/*
9489 	 * Fast path caching single unmapped page
9490 	 */
9491 	if (npages == 1 && !PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp) &&
9492 	    flags == HAT_CACHE) {
9493 		PP_CLRTNC(pp);
9494 		PP_CLRPNC(pp);
9495 		sfmmu_page_exit(pmtx);
9496 		sfmmu_kpm_kpmp_exit(kpmp);
9497 		return;
9498 	}
9499 
9500 	/*
9501 	 * We need to capture all cpus in order to change cacheability
9502 	 * because we can't allow one cpu to access the same physical
9503 	 * page using a cacheable and a non-cachebale mapping at the same
9504 	 * time. Since we may end up walking the ism mapping list
9505 	 * have to grab it's lock now since we can't after all the
9506 	 * cpus have been captured.
9507 	 */
9508 	sfmmu_hat_lock_all();
9509 	mutex_enter(&ism_mlist_lock);
9510 	kpreempt_disable();
9511 	cpuset = cpu_ready_set;
9512 	xc_attention(cpuset);
9513 
9514 	if (npages > 1) {
9515 		/*
9516 		 * Make sure all colors are flushed since the
9517 		 * sfmmu_page_cache() only flushes one color-
9518 		 * it does not know big pages.
9519 		 */
9520 		ncolors = CACHE_NUM_COLOR;
9521 		if (flags & HAT_TMPNC) {
9522 			for (i = 0; i < ncolors; i++) {
9523 				sfmmu_cache_flushcolor(i, pp->p_pagenum);
9524 			}
9525 			cache_flush_flag = CACHE_NO_FLUSH;
9526 		}
9527 	}
9528 
9529 	for (i = 0; i < npages; i++) {
9530 
9531 		ASSERT(sfmmu_mlist_held(pp));
9532 
9533 		if (!(flags == HAT_TMPNC && PP_ISTNC(pp))) {
9534 
9535 			if (npages > 1) {
9536 				bcolor = i % ncolors;
9537 			} else {
9538 				bcolor = NO_VCOLOR;
9539 			}
9540 
9541 			sfmmu_page_cache(pp, flags, cache_flush_flag,
9542 			    bcolor);
9543 		}
9544 
9545 		pp = PP_PAGENEXT(pp);
9546 	}
9547 
9548 	xt_sync(cpuset);
9549 	xc_dismissed(cpuset);
9550 	mutex_exit(&ism_mlist_lock);
9551 	sfmmu_hat_unlock_all();
9552 	sfmmu_page_exit(pmtx);
9553 	sfmmu_kpm_kpmp_exit(kpmp);
9554 	kpreempt_enable();
9555 }
9556 
9557 /*
9558  * This function changes the virtual cacheability of all mappings to a
9559  * particular page.  When changing from uncache to cacheable the mappings will
9560  * only be changed if all of them have the same virtual color.
9561  * We need to flush the cache in all cpus.  It is possible that
9562  * a process referenced a page as cacheable but has sinced exited
9563  * and cleared the mapping list.  We still to flush it but have no
9564  * state so all cpus is the only alternative.
9565  */
9566 static void
9567 sfmmu_page_cache(page_t *pp, int flags, int cache_flush_flag, int bcolor)
9568 {
9569 	struct	sf_hment *sfhme;
9570 	struct	hme_blk *hmeblkp;
9571 	sfmmu_t *sfmmup;
9572 	tte_t	tte, ttemod;
9573 	caddr_t	vaddr;
9574 	int	ret, color;
9575 	pfn_t	pfn;
9576 
9577 	color = bcolor;
9578 	pfn = pp->p_pagenum;
9579 
9580 	for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9581 
9582 		if (IS_PAHME(sfhme))
9583 			continue;
9584 		hmeblkp = sfmmu_hmetohblk(sfhme);
9585 
9586 		if (hmeblkp->hblk_xhat_bit)
9587 			continue;
9588 
9589 		sfmmu_copytte(&sfhme->hme_tte, &tte);
9590 		ASSERT(TTE_IS_VALID(&tte));
9591 		vaddr = tte_to_vaddr(hmeblkp, tte);
9592 		color = addr_to_vcolor(vaddr);
9593 
9594 #ifdef DEBUG
9595 		if ((flags & HAT_CACHE) && bcolor != NO_VCOLOR) {
9596 			ASSERT(color == bcolor);
9597 		}
9598 #endif
9599 
9600 		ASSERT(flags != HAT_TMPNC || color == PP_GET_VCOLOR(pp));
9601 
9602 		ttemod = tte;
9603 		if (flags & (HAT_UNCACHE | HAT_TMPNC)) {
9604 			TTE_CLR_VCACHEABLE(&ttemod);
9605 		} else {	/* flags & HAT_CACHE */
9606 			TTE_SET_VCACHEABLE(&ttemod);
9607 		}
9608 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
9609 		if (ret < 0) {
9610 			/*
9611 			 * Since all cpus are captured modifytte should not
9612 			 * fail.
9613 			 */
9614 			panic("sfmmu_page_cache: write to tte failed");
9615 		}
9616 
9617 		sfmmup = hblktosfmmu(hmeblkp);
9618 		if (cache_flush_flag == CACHE_FLUSH) {
9619 			/*
9620 			 * Flush TSBs, TLBs and caches
9621 			 */
9622 			if (hmeblkp->hblk_shared) {
9623 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9624 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9625 				sf_region_t *rgnp;
9626 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9627 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9628 				ASSERT(srdp != NULL);
9629 				rgnp = srdp->srd_hmergnp[rid];
9630 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9631 				    srdp, rgnp, rid);
9632 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9633 				    hmeblkp, 0);
9634 				sfmmu_cache_flush(pfn, addr_to_vcolor(vaddr));
9635 			} else if (sfmmup->sfmmu_ismhat) {
9636 				if (flags & HAT_CACHE) {
9637 					SFMMU_STAT(sf_ism_recache);
9638 				} else {
9639 					SFMMU_STAT(sf_ism_uncache);
9640 				}
9641 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9642 				    pfn, CACHE_FLUSH);
9643 			} else {
9644 				sfmmu_tlbcache_demap(vaddr, sfmmup, hmeblkp,
9645 				    pfn, 0, FLUSH_ALL_CPUS, CACHE_FLUSH, 1);
9646 			}
9647 
9648 			/*
9649 			 * all cache entries belonging to this pfn are
9650 			 * now flushed.
9651 			 */
9652 			cache_flush_flag = CACHE_NO_FLUSH;
9653 		} else {
9654 			/*
9655 			 * Flush only TSBs and TLBs.
9656 			 */
9657 			if (hmeblkp->hblk_shared) {
9658 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9659 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9660 				sf_region_t *rgnp;
9661 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9662 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9663 				ASSERT(srdp != NULL);
9664 				rgnp = srdp->srd_hmergnp[rid];
9665 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9666 				    srdp, rgnp, rid);
9667 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9668 				    hmeblkp, 0);
9669 			} else if (sfmmup->sfmmu_ismhat) {
9670 				if (flags & HAT_CACHE) {
9671 					SFMMU_STAT(sf_ism_recache);
9672 				} else {
9673 					SFMMU_STAT(sf_ism_uncache);
9674 				}
9675 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9676 				    pfn, CACHE_NO_FLUSH);
9677 			} else {
9678 				sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 1);
9679 			}
9680 		}
9681 	}
9682 
9683 	if (PP_ISMAPPED_KPM(pp))
9684 		sfmmu_kpm_page_cache(pp, flags, cache_flush_flag);
9685 
9686 	switch (flags) {
9687 
9688 		default:
9689 			panic("sfmmu_pagecache: unknown flags");
9690 			break;
9691 
9692 		case HAT_CACHE:
9693 			PP_CLRTNC(pp);
9694 			PP_CLRPNC(pp);
9695 			PP_SET_VCOLOR(pp, color);
9696 			break;
9697 
9698 		case HAT_TMPNC:
9699 			PP_SETTNC(pp);
9700 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9701 			break;
9702 
9703 		case HAT_UNCACHE:
9704 			PP_SETPNC(pp);
9705 			PP_CLRTNC(pp);
9706 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9707 			break;
9708 	}
9709 }
9710 #endif	/* VAC */
9711 
9712 
9713 /*
9714  * Wrapper routine used to return a context.
9715  *
9716  * It's the responsibility of the caller to guarantee that the
9717  * process serializes on calls here by taking the HAT lock for
9718  * the hat.
9719  *
9720  */
9721 static void
9722 sfmmu_get_ctx(sfmmu_t *sfmmup)
9723 {
9724 	mmu_ctx_t *mmu_ctxp;
9725 	uint_t pstate_save;
9726 	int ret;
9727 
9728 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9729 	ASSERT(sfmmup != ksfmmup);
9730 
9731 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID)) {
9732 		sfmmu_setup_tsbinfo(sfmmup);
9733 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ALLCTX_INVALID);
9734 	}
9735 
9736 	kpreempt_disable();
9737 
9738 	mmu_ctxp = CPU_MMU_CTXP(CPU);
9739 	ASSERT(mmu_ctxp);
9740 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
9741 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
9742 
9743 	/*
9744 	 * Do a wrap-around if cnum reaches the max # cnum supported by a MMU.
9745 	 */
9746 	if (mmu_ctxp->mmu_cnum == mmu_ctxp->mmu_nctxs)
9747 		sfmmu_ctx_wrap_around(mmu_ctxp);
9748 
9749 	/*
9750 	 * Let the MMU set up the page sizes to use for
9751 	 * this context in the TLB. Don't program 2nd dtlb for ism hat.
9752 	 */
9753 	if ((&mmu_set_ctx_page_sizes) && (sfmmup->sfmmu_ismhat == 0)) {
9754 		mmu_set_ctx_page_sizes(sfmmup);
9755 	}
9756 
9757 	/*
9758 	 * sfmmu_alloc_ctx and sfmmu_load_mmustate will be performed with
9759 	 * interrupts disabled to prevent race condition with wrap-around
9760 	 * ctx invalidatation. In sun4v, ctx invalidation also involves
9761 	 * a HV call to set the number of TSBs to 0. If interrupts are not
9762 	 * disabled until after sfmmu_load_mmustate is complete TSBs may
9763 	 * become assigned to INVALID_CONTEXT. This is not allowed.
9764 	 */
9765 	pstate_save = sfmmu_disable_intrs();
9766 
9767 	if (sfmmu_alloc_ctx(sfmmup, 1, CPU, SFMMU_PRIVATE) &&
9768 	    sfmmup->sfmmu_scdp != NULL) {
9769 		sf_scd_t *scdp = sfmmup->sfmmu_scdp;
9770 		sfmmu_t *scsfmmup = scdp->scd_sfmmup;
9771 		ret = sfmmu_alloc_ctx(scsfmmup, 1, CPU, SFMMU_SHARED);
9772 		/* debug purpose only */
9773 		ASSERT(!ret || scsfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
9774 		    != INVALID_CONTEXT);
9775 	}
9776 	sfmmu_load_mmustate(sfmmup);
9777 
9778 	sfmmu_enable_intrs(pstate_save);
9779 
9780 	kpreempt_enable();
9781 }
9782 
9783 /*
9784  * When all cnums are used up in a MMU, cnum will wrap around to the
9785  * next generation and start from 2.
9786  */
9787 static void
9788 sfmmu_ctx_wrap_around(mmu_ctx_t *mmu_ctxp)
9789 {
9790 
9791 	/* caller must have disabled the preemption */
9792 	ASSERT(curthread->t_preempt >= 1);
9793 	ASSERT(mmu_ctxp != NULL);
9794 
9795 	/* acquire Per-MMU (PM) spin lock */
9796 	mutex_enter(&mmu_ctxp->mmu_lock);
9797 
9798 	/* re-check to see if wrap-around is needed */
9799 	if (mmu_ctxp->mmu_cnum < mmu_ctxp->mmu_nctxs)
9800 		goto done;
9801 
9802 	SFMMU_MMU_STAT(mmu_wrap_around);
9803 
9804 	/* update gnum */
9805 	ASSERT(mmu_ctxp->mmu_gnum != 0);
9806 	mmu_ctxp->mmu_gnum++;
9807 	if (mmu_ctxp->mmu_gnum == 0 ||
9808 	    mmu_ctxp->mmu_gnum > MAX_SFMMU_GNUM_VAL) {
9809 		cmn_err(CE_PANIC, "mmu_gnum of mmu_ctx 0x%p is out of bound.",
9810 		    (void *)mmu_ctxp);
9811 	}
9812 
9813 	if (mmu_ctxp->mmu_ncpus > 1) {
9814 		cpuset_t cpuset;
9815 
9816 		membar_enter(); /* make sure updated gnum visible */
9817 
9818 		SFMMU_XCALL_STATS(NULL);
9819 
9820 		/* xcall to others on the same MMU to invalidate ctx */
9821 		cpuset = mmu_ctxp->mmu_cpuset;
9822 		ASSERT(CPU_IN_SET(cpuset, CPU->cpu_id));
9823 		CPUSET_DEL(cpuset, CPU->cpu_id);
9824 		CPUSET_AND(cpuset, cpu_ready_set);
9825 
9826 		/*
9827 		 * Pass in INVALID_CONTEXT as the first parameter to
9828 		 * sfmmu_raise_tsb_exception, which invalidates the context
9829 		 * of any process running on the CPUs in the MMU.
9830 		 */
9831 		xt_some(cpuset, sfmmu_raise_tsb_exception,
9832 		    INVALID_CONTEXT, INVALID_CONTEXT);
9833 		xt_sync(cpuset);
9834 
9835 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
9836 	}
9837 
9838 	if (sfmmu_getctx_sec() != INVALID_CONTEXT) {
9839 		sfmmu_setctx_sec(INVALID_CONTEXT);
9840 		sfmmu_clear_utsbinfo();
9841 	}
9842 
9843 	/*
9844 	 * No xcall is needed here. For sun4u systems all CPUs in context
9845 	 * domain share a single physical MMU therefore it's enough to flush
9846 	 * TLB on local CPU. On sun4v systems we use 1 global context
9847 	 * domain and flush all remote TLBs in sfmmu_raise_tsb_exception
9848 	 * handler. Note that vtag_flushall_uctxs() is called
9849 	 * for Ultra II machine, where the equivalent flushall functionality
9850 	 * is implemented in SW, and only user ctx TLB entries are flushed.
9851 	 */
9852 	if (&vtag_flushall_uctxs != NULL) {
9853 		vtag_flushall_uctxs();
9854 	} else {
9855 		vtag_flushall();
9856 	}
9857 
9858 	/* reset mmu cnum, skips cnum 0 and 1 */
9859 	mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
9860 
9861 done:
9862 	mutex_exit(&mmu_ctxp->mmu_lock);
9863 }
9864 
9865 
9866 /*
9867  * For multi-threaded process, set the process context to INVALID_CONTEXT
9868  * so that it faults and reloads the MMU state from TL=0. For single-threaded
9869  * process, we can just load the MMU state directly without having to
9870  * set context invalid. Caller must hold the hat lock since we don't
9871  * acquire it here.
9872  */
9873 static void
9874 sfmmu_sync_mmustate(sfmmu_t *sfmmup)
9875 {
9876 	uint_t cnum;
9877 	uint_t pstate_save;
9878 
9879 	ASSERT(sfmmup != ksfmmup);
9880 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9881 
9882 	kpreempt_disable();
9883 
9884 	/*
9885 	 * We check whether the pass'ed-in sfmmup is the same as the
9886 	 * current running proc. This is to makes sure the current proc
9887 	 * stays single-threaded if it already is.
9888 	 */
9889 	if ((sfmmup == curthread->t_procp->p_as->a_hat) &&
9890 	    (curthread->t_procp->p_lwpcnt == 1)) {
9891 		/* single-thread */
9892 		cnum = sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum;
9893 		if (cnum != INVALID_CONTEXT) {
9894 			uint_t curcnum;
9895 			/*
9896 			 * Disable interrupts to prevent race condition
9897 			 * with sfmmu_ctx_wrap_around ctx invalidation.
9898 			 * In sun4v, ctx invalidation involves setting
9899 			 * TSB to NULL, hence, interrupts should be disabled
9900 			 * untill after sfmmu_load_mmustate is completed.
9901 			 */
9902 			pstate_save = sfmmu_disable_intrs();
9903 			curcnum = sfmmu_getctx_sec();
9904 			if (curcnum == cnum)
9905 				sfmmu_load_mmustate(sfmmup);
9906 			sfmmu_enable_intrs(pstate_save);
9907 			ASSERT(curcnum == cnum || curcnum == INVALID_CONTEXT);
9908 		}
9909 	} else {
9910 		/*
9911 		 * multi-thread
9912 		 * or when sfmmup is not the same as the curproc.
9913 		 */
9914 		sfmmu_invalidate_ctx(sfmmup);
9915 	}
9916 
9917 	kpreempt_enable();
9918 }
9919 
9920 
9921 /*
9922  * Replace the specified TSB with a new TSB.  This function gets called when
9923  * we grow, shrink or swapin a TSB.  When swapping in a TSB (TSB_SWAPIN), the
9924  * TSB_FORCEALLOC flag may be used to force allocation of a minimum-sized TSB
9925  * (8K).
9926  *
9927  * Caller must hold the HAT lock, but should assume any tsb_info
9928  * pointers it has are no longer valid after calling this function.
9929  *
9930  * Return values:
9931  *	TSB_ALLOCFAIL	Failed to allocate a TSB, due to memory constraints
9932  *	TSB_LOSTRACE	HAT is busy, i.e. another thread is already doing
9933  *			something to this tsbinfo/TSB
9934  *	TSB_SUCCESS	Operation succeeded
9935  */
9936 static tsb_replace_rc_t
9937 sfmmu_replace_tsb(sfmmu_t *sfmmup, struct tsb_info *old_tsbinfo, uint_t szc,
9938     hatlock_t *hatlockp, uint_t flags)
9939 {
9940 	struct tsb_info *new_tsbinfo = NULL;
9941 	struct tsb_info *curtsb, *prevtsb;
9942 	uint_t tte_sz_mask;
9943 	int i;
9944 
9945 	ASSERT(sfmmup != ksfmmup);
9946 	ASSERT(sfmmup->sfmmu_ismhat == 0);
9947 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9948 	ASSERT(szc <= tsb_max_growsize);
9949 
9950 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_BUSY))
9951 		return (TSB_LOSTRACE);
9952 
9953 	/*
9954 	 * Find the tsb_info ahead of this one in the list, and
9955 	 * also make sure that the tsb_info passed in really
9956 	 * exists!
9957 	 */
9958 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9959 	    curtsb != old_tsbinfo && curtsb != NULL;
9960 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
9961 		;
9962 	ASSERT(curtsb != NULL);
9963 
9964 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9965 		/*
9966 		 * The process is swapped out, so just set the new size
9967 		 * code.  When it swaps back in, we'll allocate a new one
9968 		 * of the new chosen size.
9969 		 */
9970 		curtsb->tsb_szc = szc;
9971 		return (TSB_SUCCESS);
9972 	}
9973 	SFMMU_FLAGS_SET(sfmmup, HAT_BUSY);
9974 
9975 	tte_sz_mask = old_tsbinfo->tsb_ttesz_mask;
9976 
9977 	/*
9978 	 * All initialization is done inside of sfmmu_tsbinfo_alloc().
9979 	 * If we fail to allocate a TSB, exit.
9980 	 *
9981 	 * If tsb grows with new tsb size > 4M and old tsb size < 4M,
9982 	 * then try 4M slab after the initial alloc fails.
9983 	 *
9984 	 * If tsb swapin with tsb size > 4M, then try 4M after the
9985 	 * initial alloc fails.
9986 	 */
9987 	sfmmu_hat_exit(hatlockp);
9988 	if (sfmmu_tsbinfo_alloc(&new_tsbinfo, szc,
9989 	    tte_sz_mask, flags, sfmmup) &&
9990 	    (!(flags & (TSB_GROW | TSB_SWAPIN)) || (szc <= TSB_4M_SZCODE) ||
9991 	    (!(flags & TSB_SWAPIN) &&
9992 	    (old_tsbinfo->tsb_szc >= TSB_4M_SZCODE)) ||
9993 	    sfmmu_tsbinfo_alloc(&new_tsbinfo, TSB_4M_SZCODE,
9994 	    tte_sz_mask, flags, sfmmup))) {
9995 		(void) sfmmu_hat_enter(sfmmup);
9996 		if (!(flags & TSB_SWAPIN))
9997 			SFMMU_STAT(sf_tsb_resize_failures);
9998 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9999 		return (TSB_ALLOCFAIL);
10000 	}
10001 	(void) sfmmu_hat_enter(sfmmup);
10002 
10003 	/*
10004 	 * Re-check to make sure somebody else didn't muck with us while we
10005 	 * didn't hold the HAT lock.  If the process swapped out, fine, just
10006 	 * exit; this can happen if we try to shrink the TSB from the context
10007 	 * of another process (such as on an ISM unmap), though it is rare.
10008 	 */
10009 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
10010 		SFMMU_STAT(sf_tsb_resize_failures);
10011 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
10012 		sfmmu_hat_exit(hatlockp);
10013 		sfmmu_tsbinfo_free(new_tsbinfo);
10014 		(void) sfmmu_hat_enter(sfmmup);
10015 		return (TSB_LOSTRACE);
10016 	}
10017 
10018 #ifdef	DEBUG
10019 	/* Reverify that the tsb_info still exists.. for debugging only */
10020 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
10021 	    curtsb != old_tsbinfo && curtsb != NULL;
10022 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
10023 		;
10024 	ASSERT(curtsb != NULL);
10025 #endif	/* DEBUG */
10026 
10027 	/*
10028 	 * Quiesce any CPUs running this process on their next TLB miss
10029 	 * so they atomically see the new tsb_info.  We temporarily set the
10030 	 * context to invalid context so new threads that come on processor
10031 	 * after we do the xcall to cpusran will also serialize behind the
10032 	 * HAT lock on TLB miss and will see the new TSB.  Since this short
10033 	 * race with a new thread coming on processor is relatively rare,
10034 	 * this synchronization mechanism should be cheaper than always
10035 	 * pausing all CPUs for the duration of the setup, which is what
10036 	 * the old implementation did.  This is particuarly true if we are
10037 	 * copying a huge chunk of memory around during that window.
10038 	 *
10039 	 * The memory barriers are to make sure things stay consistent
10040 	 * with resume() since it does not hold the HAT lock while
10041 	 * walking the list of tsb_info structures.
10042 	 */
10043 	if ((flags & TSB_SWAPIN) != TSB_SWAPIN) {
10044 		/* The TSB is either growing or shrinking. */
10045 		sfmmu_invalidate_ctx(sfmmup);
10046 	} else {
10047 		/*
10048 		 * It is illegal to swap in TSBs from a process other
10049 		 * than a process being swapped in.  This in turn
10050 		 * implies we do not have a valid MMU context here
10051 		 * since a process needs one to resolve translation
10052 		 * misses.
10053 		 */
10054 		ASSERT(curthread->t_procp->p_as->a_hat == sfmmup);
10055 	}
10056 
10057 #ifdef DEBUG
10058 	ASSERT(max_mmu_ctxdoms > 0);
10059 
10060 	/*
10061 	 * Process should have INVALID_CONTEXT on all MMUs
10062 	 */
10063 	for (i = 0; i < max_mmu_ctxdoms; i++) {
10064 
10065 		ASSERT(sfmmup->sfmmu_ctxs[i].cnum == INVALID_CONTEXT);
10066 	}
10067 #endif
10068 
10069 	new_tsbinfo->tsb_next = old_tsbinfo->tsb_next;
10070 	membar_stst();	/* strict ordering required */
10071 	if (prevtsb)
10072 		prevtsb->tsb_next = new_tsbinfo;
10073 	else
10074 		sfmmup->sfmmu_tsb = new_tsbinfo;
10075 	membar_enter();	/* make sure new TSB globally visible */
10076 
10077 	/*
10078 	 * We need to migrate TSB entries from the old TSB to the new TSB
10079 	 * if tsb_remap_ttes is set and the TSB is growing.
10080 	 */
10081 	if (tsb_remap_ttes && ((flags & TSB_GROW) == TSB_GROW))
10082 		sfmmu_copy_tsb(old_tsbinfo, new_tsbinfo);
10083 
10084 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
10085 
10086 	/*
10087 	 * Drop the HAT lock to free our old tsb_info.
10088 	 */
10089 	sfmmu_hat_exit(hatlockp);
10090 
10091 	if ((flags & TSB_GROW) == TSB_GROW) {
10092 		SFMMU_STAT(sf_tsb_grow);
10093 	} else if ((flags & TSB_SHRINK) == TSB_SHRINK) {
10094 		SFMMU_STAT(sf_tsb_shrink);
10095 	}
10096 
10097 	sfmmu_tsbinfo_free(old_tsbinfo);
10098 
10099 	(void) sfmmu_hat_enter(sfmmup);
10100 	return (TSB_SUCCESS);
10101 }
10102 
10103 /*
10104  * This function will re-program hat pgsz array, and invalidate the
10105  * process' context, forcing the process to switch to another
10106  * context on the next TLB miss, and therefore start using the
10107  * TLB that is reprogrammed for the new page sizes.
10108  */
10109 void
10110 sfmmu_reprog_pgsz_arr(sfmmu_t *sfmmup, uint8_t *tmp_pgsz)
10111 {
10112 	int i;
10113 	hatlock_t *hatlockp = NULL;
10114 
10115 	hatlockp = sfmmu_hat_enter(sfmmup);
10116 	/* USIII+-IV+ optimization, requires hat lock */
10117 	if (tmp_pgsz) {
10118 		for (i = 0; i < mmu_page_sizes; i++)
10119 			sfmmup->sfmmu_pgsz[i] = tmp_pgsz[i];
10120 	}
10121 	SFMMU_STAT(sf_tlb_reprog_pgsz);
10122 
10123 	sfmmu_invalidate_ctx(sfmmup);
10124 
10125 	sfmmu_hat_exit(hatlockp);
10126 }
10127 
10128 /*
10129  * The scd_rttecnt field in the SCD must be updated to take account of the
10130  * regions which it contains.
10131  */
10132 static void
10133 sfmmu_set_scd_rttecnt(sf_srd_t *srdp, sf_scd_t *scdp)
10134 {
10135 	uint_t rid;
10136 	uint_t i, j;
10137 	ulong_t w;
10138 	sf_region_t *rgnp;
10139 
10140 	ASSERT(srdp != NULL);
10141 
10142 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
10143 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
10144 			continue;
10145 		}
10146 
10147 		j = 0;
10148 		while (w) {
10149 			if (!(w & 0x1)) {
10150 				j++;
10151 				w >>= 1;
10152 				continue;
10153 			}
10154 			rid = (i << BT_ULSHIFT) | j;
10155 			j++;
10156 			w >>= 1;
10157 
10158 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
10159 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
10160 			rgnp = srdp->srd_hmergnp[rid];
10161 			ASSERT(rgnp->rgn_refcnt > 0);
10162 			ASSERT(rgnp->rgn_id == rid);
10163 
10164 			scdp->scd_rttecnt[rgnp->rgn_pgszc] +=
10165 			    rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
10166 
10167 			/*
10168 			 * Maintain the tsb0 inflation cnt for the regions
10169 			 * in the SCD.
10170 			 */
10171 			if (rgnp->rgn_pgszc >= TTE4M) {
10172 				scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt +=
10173 				    rgnp->rgn_size >>
10174 				    (TTE_PAGE_SHIFT(TTE8K) + 2);
10175 			}
10176 		}
10177 	}
10178 }
10179 
10180 /*
10181  * This function assumes that there are either four or six supported page
10182  * sizes and at most two programmable TLBs, so we need to decide which
10183  * page sizes are most important and then tell the MMU layer so it
10184  * can adjust the TLB page sizes accordingly (if supported).
10185  *
10186  * If these assumptions change, this function will need to be
10187  * updated to support whatever the new limits are.
10188  *
10189  * The growing flag is nonzero if we are growing the address space,
10190  * and zero if it is shrinking.  This allows us to decide whether
10191  * to grow or shrink our TSB, depending upon available memory
10192  * conditions.
10193  */
10194 static void
10195 sfmmu_check_page_sizes(sfmmu_t *sfmmup, int growing)
10196 {
10197 	uint64_t ttecnt[MMU_PAGE_SIZES];
10198 	uint64_t tte8k_cnt, tte4m_cnt;
10199 	uint8_t i;
10200 	int sectsb_thresh;
10201 
10202 	/*
10203 	 * Kernel threads, processes with small address spaces not using
10204 	 * large pages, and dummy ISM HATs need not apply.
10205 	 */
10206 	if (sfmmup == ksfmmup || sfmmup->sfmmu_ismhat != NULL)
10207 		return;
10208 
10209 	if (!SFMMU_LGPGS_INUSE(sfmmup) &&
10210 	    sfmmup->sfmmu_ttecnt[TTE8K] <= tsb_rss_factor)
10211 		return;
10212 
10213 	for (i = 0; i < mmu_page_sizes; i++) {
10214 		ttecnt[i] = sfmmup->sfmmu_ttecnt[i] +
10215 		    sfmmup->sfmmu_ismttecnt[i];
10216 	}
10217 
10218 	/* Check pagesizes in use, and possibly reprogram DTLB. */
10219 	if (&mmu_check_page_sizes)
10220 		mmu_check_page_sizes(sfmmup, ttecnt);
10221 
10222 	/*
10223 	 * Calculate the number of 8k ttes to represent the span of these
10224 	 * pages.
10225 	 */
10226 	tte8k_cnt = ttecnt[TTE8K] +
10227 	    (ttecnt[TTE64K] << (MMU_PAGESHIFT64K - MMU_PAGESHIFT)) +
10228 	    (ttecnt[TTE512K] << (MMU_PAGESHIFT512K - MMU_PAGESHIFT));
10229 	if (mmu_page_sizes == max_mmu_page_sizes) {
10230 		tte4m_cnt = ttecnt[TTE4M] +
10231 		    (ttecnt[TTE32M] << (MMU_PAGESHIFT32M - MMU_PAGESHIFT4M)) +
10232 		    (ttecnt[TTE256M] << (MMU_PAGESHIFT256M - MMU_PAGESHIFT4M));
10233 	} else {
10234 		tte4m_cnt = ttecnt[TTE4M];
10235 	}
10236 
10237 	/*
10238 	 * Inflate tte8k_cnt to allow for region large page allocation failure.
10239 	 */
10240 	tte8k_cnt += sfmmup->sfmmu_tsb0_4minflcnt;
10241 
10242 	/*
10243 	 * Inflate TSB sizes by a factor of 2 if this process
10244 	 * uses 4M text pages to minimize extra conflict misses
10245 	 * in the first TSB since without counting text pages
10246 	 * 8K TSB may become too small.
10247 	 *
10248 	 * Also double the size of the second TSB to minimize
10249 	 * extra conflict misses due to competition between 4M text pages
10250 	 * and data pages.
10251 	 *
10252 	 * We need to adjust the second TSB allocation threshold by the
10253 	 * inflation factor, since there is no point in creating a second
10254 	 * TSB when we know all the mappings can fit in the I/D TLBs.
10255 	 */
10256 	sectsb_thresh = tsb_sectsb_threshold;
10257 	if (sfmmup->sfmmu_flags & HAT_4MTEXT_FLAG) {
10258 		tte8k_cnt <<= 1;
10259 		tte4m_cnt <<= 1;
10260 		sectsb_thresh <<= 1;
10261 	}
10262 
10263 	/*
10264 	 * Check to see if our TSB is the right size; we may need to
10265 	 * grow or shrink it.  If the process is small, our work is
10266 	 * finished at this point.
10267 	 */
10268 	if (tte8k_cnt <= tsb_rss_factor && tte4m_cnt <= sectsb_thresh) {
10269 		return;
10270 	}
10271 	sfmmu_size_tsb(sfmmup, growing, tte8k_cnt, tte4m_cnt, sectsb_thresh);
10272 }
10273 
10274 static void
10275 sfmmu_size_tsb(sfmmu_t *sfmmup, int growing, uint64_t tte8k_cnt,
10276 	uint64_t tte4m_cnt, int sectsb_thresh)
10277 {
10278 	int tsb_bits;
10279 	uint_t tsb_szc;
10280 	struct tsb_info *tsbinfop;
10281 	hatlock_t *hatlockp = NULL;
10282 
10283 	hatlockp = sfmmu_hat_enter(sfmmup);
10284 	ASSERT(hatlockp != NULL);
10285 	tsbinfop = sfmmup->sfmmu_tsb;
10286 	ASSERT(tsbinfop != NULL);
10287 
10288 	/*
10289 	 * If we're growing, select the size based on RSS.  If we're
10290 	 * shrinking, leave some room so we don't have to turn around and
10291 	 * grow again immediately.
10292 	 */
10293 	if (growing)
10294 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
10295 	else
10296 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt << 1);
10297 
10298 	if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10299 	    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10300 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10301 		    hatlockp, TSB_SHRINK);
10302 	} else if (growing && tsb_szc > tsbinfop->tsb_szc && TSB_OK_GROW()) {
10303 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10304 		    hatlockp, TSB_GROW);
10305 	}
10306 	tsbinfop = sfmmup->sfmmu_tsb;
10307 
10308 	/*
10309 	 * With the TLB and first TSB out of the way, we need to see if
10310 	 * we need a second TSB for 4M pages.  If we managed to reprogram
10311 	 * the TLB page sizes above, the process will start using this new
10312 	 * TSB right away; otherwise, it will start using it on the next
10313 	 * context switch.  Either way, it's no big deal so there's no
10314 	 * synchronization with the trap handlers here unless we grow the
10315 	 * TSB (in which case it's required to prevent using the old one
10316 	 * after it's freed). Note: second tsb is required for 32M/256M
10317 	 * page sizes.
10318 	 */
10319 	if (tte4m_cnt > sectsb_thresh) {
10320 		/*
10321 		 * If we're growing, select the size based on RSS.  If we're
10322 		 * shrinking, leave some room so we don't have to turn
10323 		 * around and grow again immediately.
10324 		 */
10325 		if (growing)
10326 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
10327 		else
10328 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt << 1);
10329 		if (tsbinfop->tsb_next == NULL) {
10330 			struct tsb_info *newtsb;
10331 			int allocflags = SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)?
10332 			    0 : TSB_ALLOC;
10333 
10334 			sfmmu_hat_exit(hatlockp);
10335 
10336 			/*
10337 			 * Try to allocate a TSB for 4[32|256]M pages.  If we
10338 			 * can't get the size we want, retry w/a minimum sized
10339 			 * TSB.  If that still didn't work, give up; we can
10340 			 * still run without one.
10341 			 */
10342 			tsb_bits = (mmu_page_sizes == max_mmu_page_sizes)?
10343 			    TSB4M|TSB32M|TSB256M:TSB4M;
10344 			if ((sfmmu_tsbinfo_alloc(&newtsb, tsb_szc, tsb_bits,
10345 			    allocflags, sfmmup)) &&
10346 			    (tsb_szc <= TSB_4M_SZCODE ||
10347 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
10348 			    tsb_bits, allocflags, sfmmup)) &&
10349 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_MIN_SZCODE,
10350 			    tsb_bits, allocflags, sfmmup)) {
10351 				return;
10352 			}
10353 
10354 			hatlockp = sfmmu_hat_enter(sfmmup);
10355 
10356 			sfmmu_invalidate_ctx(sfmmup);
10357 
10358 			if (sfmmup->sfmmu_tsb->tsb_next == NULL) {
10359 				sfmmup->sfmmu_tsb->tsb_next = newtsb;
10360 				SFMMU_STAT(sf_tsb_sectsb_create);
10361 				sfmmu_hat_exit(hatlockp);
10362 				return;
10363 			} else {
10364 				/*
10365 				 * It's annoying, but possible for us
10366 				 * to get here.. we dropped the HAT lock
10367 				 * because of locking order in the kmem
10368 				 * allocator, and while we were off getting
10369 				 * our memory, some other thread decided to
10370 				 * do us a favor and won the race to get a
10371 				 * second TSB for this process.  Sigh.
10372 				 */
10373 				sfmmu_hat_exit(hatlockp);
10374 				sfmmu_tsbinfo_free(newtsb);
10375 				return;
10376 			}
10377 		}
10378 
10379 		/*
10380 		 * We have a second TSB, see if it's big enough.
10381 		 */
10382 		tsbinfop = tsbinfop->tsb_next;
10383 
10384 		/*
10385 		 * Check to see if our second TSB is the right size;
10386 		 * we may need to grow or shrink it.
10387 		 * To prevent thrashing (e.g. growing the TSB on a
10388 		 * subsequent map operation), only try to shrink if
10389 		 * the TSB reach exceeds twice the virtual address
10390 		 * space size.
10391 		 */
10392 		if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10393 		    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10394 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10395 			    tsb_szc, hatlockp, TSB_SHRINK);
10396 		} else if (growing && tsb_szc > tsbinfop->tsb_szc &&
10397 		    TSB_OK_GROW()) {
10398 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10399 			    tsb_szc, hatlockp, TSB_GROW);
10400 		}
10401 	}
10402 
10403 	sfmmu_hat_exit(hatlockp);
10404 }
10405 
10406 /*
10407  * Free up a sfmmu
10408  * Since the sfmmu is currently embedded in the hat struct we simply zero
10409  * out our fields and free up the ism map blk list if any.
10410  */
10411 static void
10412 sfmmu_free_sfmmu(sfmmu_t *sfmmup)
10413 {
10414 	ism_blk_t	*blkp, *nx_blkp;
10415 #ifdef	DEBUG
10416 	ism_map_t	*map;
10417 	int 		i;
10418 #endif
10419 
10420 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
10421 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
10422 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
10423 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
10424 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
10425 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
10426 	ASSERT(SF_RGNMAP_ISNULL(sfmmup));
10427 
10428 	sfmmup->sfmmu_free = 0;
10429 	sfmmup->sfmmu_ismhat = 0;
10430 
10431 	blkp = sfmmup->sfmmu_iblk;
10432 	sfmmup->sfmmu_iblk = NULL;
10433 
10434 	while (blkp) {
10435 #ifdef	DEBUG
10436 		map = blkp->iblk_maps;
10437 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
10438 			ASSERT(map[i].imap_seg == 0);
10439 			ASSERT(map[i].imap_ismhat == NULL);
10440 			ASSERT(map[i].imap_ment == NULL);
10441 		}
10442 #endif
10443 		nx_blkp = blkp->iblk_next;
10444 		blkp->iblk_next = NULL;
10445 		blkp->iblk_nextpa = (uint64_t)-1;
10446 		kmem_cache_free(ism_blk_cache, blkp);
10447 		blkp = nx_blkp;
10448 	}
10449 }
10450 
10451 /*
10452  * Locking primitves accessed by HATLOCK macros
10453  */
10454 
10455 #define	SFMMU_SPL_MTX	(0x0)
10456 #define	SFMMU_ML_MTX	(0x1)
10457 
10458 #define	SFMMU_MLSPL_MTX(type, pg)	(((type) == SFMMU_SPL_MTX) ? \
10459 					    SPL_HASH(pg) : MLIST_HASH(pg))
10460 
10461 kmutex_t *
10462 sfmmu_page_enter(struct page *pp)
10463 {
10464 	return (sfmmu_mlspl_enter(pp, SFMMU_SPL_MTX));
10465 }
10466 
10467 void
10468 sfmmu_page_exit(kmutex_t *spl)
10469 {
10470 	mutex_exit(spl);
10471 }
10472 
10473 int
10474 sfmmu_page_spl_held(struct page *pp)
10475 {
10476 	return (sfmmu_mlspl_held(pp, SFMMU_SPL_MTX));
10477 }
10478 
10479 kmutex_t *
10480 sfmmu_mlist_enter(struct page *pp)
10481 {
10482 	return (sfmmu_mlspl_enter(pp, SFMMU_ML_MTX));
10483 }
10484 
10485 void
10486 sfmmu_mlist_exit(kmutex_t *mml)
10487 {
10488 	mutex_exit(mml);
10489 }
10490 
10491 int
10492 sfmmu_mlist_held(struct page *pp)
10493 {
10494 
10495 	return (sfmmu_mlspl_held(pp, SFMMU_ML_MTX));
10496 }
10497 
10498 /*
10499  * Common code for sfmmu_mlist_enter() and sfmmu_page_enter().  For
10500  * sfmmu_mlist_enter() case mml_table lock array is used and for
10501  * sfmmu_page_enter() sfmmu_page_lock lock array is used.
10502  *
10503  * The lock is taken on a root page so that it protects an operation on all
10504  * constituent pages of a large page pp belongs to.
10505  *
10506  * The routine takes a lock from the appropriate array. The lock is determined
10507  * by hashing the root page. After taking the lock this routine checks if the
10508  * root page has the same size code that was used to determine the root (i.e
10509  * that root hasn't changed).  If root page has the expected p_szc field we
10510  * have the right lock and it's returned to the caller. If root's p_szc
10511  * decreased we release the lock and retry from the beginning.  This case can
10512  * happen due to hat_page_demote() decreasing p_szc between our load of p_szc
10513  * value and taking the lock. The number of retries due to p_szc decrease is
10514  * limited by the maximum p_szc value. If p_szc is 0 we return the lock
10515  * determined by hashing pp itself.
10516  *
10517  * If our caller doesn't hold a SE_SHARED or SE_EXCL lock on pp it's also
10518  * possible that p_szc can increase. To increase p_szc a thread has to lock
10519  * all constituent pages EXCL and do hat_pageunload() on all of them. All the
10520  * callers that don't hold a page locked recheck if hmeblk through which pp
10521  * was found still maps this pp.  If it doesn't map it anymore returned lock
10522  * is immediately dropped. Therefore if sfmmu_mlspl_enter() hits the case of
10523  * p_szc increase after taking the lock it returns this lock without further
10524  * retries because in this case the caller doesn't care about which lock was
10525  * taken. The caller will drop it right away.
10526  *
10527  * After the routine returns it's guaranteed that hat_page_demote() can't
10528  * change p_szc field of any of constituent pages of a large page pp belongs
10529  * to as long as pp was either locked at least SHARED prior to this call or
10530  * the caller finds that hment that pointed to this pp still references this
10531  * pp (this also assumes that the caller holds hme hash bucket lock so that
10532  * the same pp can't be remapped into the same hmeblk after it was unmapped by
10533  * hat_pageunload()).
10534  */
10535 static kmutex_t *
10536 sfmmu_mlspl_enter(struct page *pp, int type)
10537 {
10538 	kmutex_t	*mtx;
10539 	uint_t		prev_rszc = UINT_MAX;
10540 	page_t		*rootpp;
10541 	uint_t		szc;
10542 	uint_t		rszc;
10543 	uint_t		pszc = pp->p_szc;
10544 
10545 	ASSERT(pp != NULL);
10546 
10547 again:
10548 	if (pszc == 0) {
10549 		mtx = SFMMU_MLSPL_MTX(type, pp);
10550 		mutex_enter(mtx);
10551 		return (mtx);
10552 	}
10553 
10554 	/* The lock lives in the root page */
10555 	rootpp = PP_GROUPLEADER(pp, pszc);
10556 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10557 	mutex_enter(mtx);
10558 
10559 	/*
10560 	 * Return mml in the following 3 cases:
10561 	 *
10562 	 * 1) If pp itself is root since if its p_szc decreased before we took
10563 	 * the lock pp is still the root of smaller szc page. And if its p_szc
10564 	 * increased it doesn't matter what lock we return (see comment in
10565 	 * front of this routine).
10566 	 *
10567 	 * 2) If pp's not root but rootpp is the root of a rootpp->p_szc size
10568 	 * large page we have the right lock since any previous potential
10569 	 * hat_page_demote() is done demoting from greater than current root's
10570 	 * p_szc because hat_page_demote() changes root's p_szc last. No
10571 	 * further hat_page_demote() can start or be in progress since it
10572 	 * would need the same lock we currently hold.
10573 	 *
10574 	 * 3) If rootpp's p_szc increased since previous iteration it doesn't
10575 	 * matter what lock we return (see comment in front of this routine).
10576 	 */
10577 	if (pp == rootpp || (rszc = rootpp->p_szc) == pszc ||
10578 	    rszc >= prev_rszc) {
10579 		return (mtx);
10580 	}
10581 
10582 	/*
10583 	 * hat_page_demote() could have decreased root's p_szc.
10584 	 * In this case pp's p_szc must also be smaller than pszc.
10585 	 * Retry.
10586 	 */
10587 	if (rszc < pszc) {
10588 		szc = pp->p_szc;
10589 		if (szc < pszc) {
10590 			mutex_exit(mtx);
10591 			pszc = szc;
10592 			goto again;
10593 		}
10594 		/*
10595 		 * pp's p_szc increased after it was decreased.
10596 		 * page cannot be mapped. Return current lock. The caller
10597 		 * will drop it right away.
10598 		 */
10599 		return (mtx);
10600 	}
10601 
10602 	/*
10603 	 * root's p_szc is greater than pp's p_szc.
10604 	 * hat_page_demote() is not done with all pages
10605 	 * yet. Wait for it to complete.
10606 	 */
10607 	mutex_exit(mtx);
10608 	rootpp = PP_GROUPLEADER(rootpp, rszc);
10609 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10610 	mutex_enter(mtx);
10611 	mutex_exit(mtx);
10612 	prev_rszc = rszc;
10613 	goto again;
10614 }
10615 
10616 static int
10617 sfmmu_mlspl_held(struct page *pp, int type)
10618 {
10619 	kmutex_t	*mtx;
10620 
10621 	ASSERT(pp != NULL);
10622 	/* The lock lives in the root page */
10623 	pp = PP_PAGEROOT(pp);
10624 	ASSERT(pp != NULL);
10625 
10626 	mtx = SFMMU_MLSPL_MTX(type, pp);
10627 	return (MUTEX_HELD(mtx));
10628 }
10629 
10630 static uint_t
10631 sfmmu_get_free_hblk(struct hme_blk **hmeblkpp, uint_t critical)
10632 {
10633 	struct  hme_blk *hblkp;
10634 
10635 
10636 	if (freehblkp != NULL) {
10637 		mutex_enter(&freehblkp_lock);
10638 		if (freehblkp != NULL) {
10639 			/*
10640 			 * If the current thread is owning hblk_reserve OR
10641 			 * critical request from sfmmu_hblk_steal()
10642 			 * let it succeed even if freehblkcnt is really low.
10643 			 */
10644 			if (freehblkcnt <= HBLK_RESERVE_MIN && !critical) {
10645 				SFMMU_STAT(sf_get_free_throttle);
10646 				mutex_exit(&freehblkp_lock);
10647 				return (0);
10648 			}
10649 			freehblkcnt--;
10650 			*hmeblkpp = freehblkp;
10651 			hblkp = *hmeblkpp;
10652 			freehblkp = hblkp->hblk_next;
10653 			mutex_exit(&freehblkp_lock);
10654 			hblkp->hblk_next = NULL;
10655 			SFMMU_STAT(sf_get_free_success);
10656 
10657 			ASSERT(hblkp->hblk_hmecnt == 0);
10658 			ASSERT(hblkp->hblk_vcnt == 0);
10659 			ASSERT(hblkp->hblk_nextpa == va_to_pa((caddr_t)hblkp));
10660 
10661 			return (1);
10662 		}
10663 		mutex_exit(&freehblkp_lock);
10664 	}
10665 
10666 	/* Check cpu hblk pending queues */
10667 	if ((*hmeblkpp = sfmmu_check_pending_hblks(TTE8K)) != NULL) {
10668 		hblkp = *hmeblkpp;
10669 		hblkp->hblk_next = NULL;
10670 		hblkp->hblk_nextpa = va_to_pa((caddr_t)hblkp);
10671 
10672 		ASSERT(hblkp->hblk_hmecnt == 0);
10673 		ASSERT(hblkp->hblk_vcnt == 0);
10674 
10675 		return (1);
10676 	}
10677 
10678 	SFMMU_STAT(sf_get_free_fail);
10679 	return (0);
10680 }
10681 
10682 static uint_t
10683 sfmmu_put_free_hblk(struct hme_blk *hmeblkp, uint_t critical)
10684 {
10685 	struct  hme_blk *hblkp;
10686 
10687 	ASSERT(hmeblkp->hblk_hmecnt == 0);
10688 	ASSERT(hmeblkp->hblk_vcnt == 0);
10689 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
10690 
10691 	/*
10692 	 * If the current thread is mapping into kernel space,
10693 	 * let it succede even if freehblkcnt is max
10694 	 * so that it will avoid freeing it to kmem.
10695 	 * This will prevent stack overflow due to
10696 	 * possible recursion since kmem_cache_free()
10697 	 * might require creation of a slab which
10698 	 * in turn needs an hmeblk to map that slab;
10699 	 * let's break this vicious chain at the first
10700 	 * opportunity.
10701 	 */
10702 	if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10703 		mutex_enter(&freehblkp_lock);
10704 		if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10705 			SFMMU_STAT(sf_put_free_success);
10706 			freehblkcnt++;
10707 			hmeblkp->hblk_next = freehblkp;
10708 			freehblkp = hmeblkp;
10709 			mutex_exit(&freehblkp_lock);
10710 			return (1);
10711 		}
10712 		mutex_exit(&freehblkp_lock);
10713 	}
10714 
10715 	/*
10716 	 * Bring down freehblkcnt to HBLK_RESERVE_CNT. We are here
10717 	 * only if freehblkcnt is at least HBLK_RESERVE_CNT *and*
10718 	 * we are not in the process of mapping into kernel space.
10719 	 */
10720 	ASSERT(!critical);
10721 	while (freehblkcnt > HBLK_RESERVE_CNT) {
10722 		mutex_enter(&freehblkp_lock);
10723 		if (freehblkcnt > HBLK_RESERVE_CNT) {
10724 			freehblkcnt--;
10725 			hblkp = freehblkp;
10726 			freehblkp = hblkp->hblk_next;
10727 			mutex_exit(&freehblkp_lock);
10728 			ASSERT(get_hblk_cache(hblkp) == sfmmu8_cache);
10729 			kmem_cache_free(sfmmu8_cache, hblkp);
10730 			continue;
10731 		}
10732 		mutex_exit(&freehblkp_lock);
10733 	}
10734 	SFMMU_STAT(sf_put_free_fail);
10735 	return (0);
10736 }
10737 
10738 static void
10739 sfmmu_hblk_swap(struct hme_blk *new)
10740 {
10741 	struct hme_blk *old, *hblkp, *prev;
10742 	uint64_t newpa;
10743 	caddr_t	base, vaddr, endaddr;
10744 	struct hmehash_bucket *hmebp;
10745 	struct sf_hment *osfhme, *nsfhme;
10746 	page_t *pp;
10747 	kmutex_t *pml;
10748 	tte_t tte;
10749 	struct hme_blk *list = NULL;
10750 
10751 #ifdef	DEBUG
10752 	hmeblk_tag		hblktag;
10753 	struct hme_blk		*found;
10754 #endif
10755 	old = HBLK_RESERVE;
10756 	ASSERT(!old->hblk_shared);
10757 
10758 	/*
10759 	 * save pa before bcopy clobbers it
10760 	 */
10761 	newpa = new->hblk_nextpa;
10762 
10763 	base = (caddr_t)get_hblk_base(old);
10764 	endaddr = base + get_hblk_span(old);
10765 
10766 	/*
10767 	 * acquire hash bucket lock.
10768 	 */
10769 	hmebp = sfmmu_tteload_acquire_hashbucket(ksfmmup, base, TTE8K,
10770 	    SFMMU_INVALID_SHMERID);
10771 
10772 	/*
10773 	 * copy contents from old to new
10774 	 */
10775 	bcopy((void *)old, (void *)new, HME8BLK_SZ);
10776 
10777 	/*
10778 	 * add new to hash chain
10779 	 */
10780 	sfmmu_hblk_hash_add(hmebp, new, newpa);
10781 
10782 	/*
10783 	 * search hash chain for hblk_reserve; this needs to be performed
10784 	 * after adding new, otherwise prev won't correspond to the hblk which
10785 	 * is prior to old in hash chain when we call sfmmu_hblk_hash_rm to
10786 	 * remove old later.
10787 	 */
10788 	for (prev = NULL,
10789 	    hblkp = hmebp->hmeblkp; hblkp != NULL && hblkp != old;
10790 	    prev = hblkp, hblkp = hblkp->hblk_next)
10791 		;
10792 
10793 	if (hblkp != old)
10794 		panic("sfmmu_hblk_swap: hblk_reserve not found");
10795 
10796 	/*
10797 	 * p_mapping list is still pointing to hments in hblk_reserve;
10798 	 * fix up p_mapping list so that they point to hments in new.
10799 	 *
10800 	 * Since all these mappings are created by hblk_reserve_thread
10801 	 * on the way and it's using at least one of the buffers from each of
10802 	 * the newly minted slabs, there is no danger of any of these
10803 	 * mappings getting unloaded by another thread.
10804 	 *
10805 	 * tsbmiss could only modify ref/mod bits of hments in old/new.
10806 	 * Since all of these hments hold mappings established by segkmem
10807 	 * and mappings in segkmem are setup with HAT_NOSYNC, ref/mod bits
10808 	 * have no meaning for the mappings in hblk_reserve.  hments in
10809 	 * old and new are identical except for ref/mod bits.
10810 	 */
10811 	for (vaddr = base; vaddr < endaddr; vaddr += TTEBYTES(TTE8K)) {
10812 
10813 		HBLKTOHME(osfhme, old, vaddr);
10814 		sfmmu_copytte(&osfhme->hme_tte, &tte);
10815 
10816 		if (TTE_IS_VALID(&tte)) {
10817 			if ((pp = osfhme->hme_page) == NULL)
10818 				panic("sfmmu_hblk_swap: page not mapped");
10819 
10820 			pml = sfmmu_mlist_enter(pp);
10821 
10822 			if (pp != osfhme->hme_page)
10823 				panic("sfmmu_hblk_swap: mapping changed");
10824 
10825 			HBLKTOHME(nsfhme, new, vaddr);
10826 
10827 			HME_ADD(nsfhme, pp);
10828 			HME_SUB(osfhme, pp);
10829 
10830 			sfmmu_mlist_exit(pml);
10831 		}
10832 	}
10833 
10834 	/*
10835 	 * remove old from hash chain
10836 	 */
10837 	sfmmu_hblk_hash_rm(hmebp, old, prev, &list, 1);
10838 
10839 #ifdef	DEBUG
10840 
10841 	hblktag.htag_id = ksfmmup;
10842 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
10843 	hblktag.htag_bspage = HME_HASH_BSPAGE(base, HME_HASH_SHIFT(TTE8K));
10844 	hblktag.htag_rehash = HME_HASH_REHASH(TTE8K);
10845 	HME_HASH_FAST_SEARCH(hmebp, hblktag, found);
10846 
10847 	if (found != new)
10848 		panic("sfmmu_hblk_swap: new hblk not found");
10849 #endif
10850 
10851 	SFMMU_HASH_UNLOCK(hmebp);
10852 
10853 	/*
10854 	 * Reset hblk_reserve
10855 	 */
10856 	bzero((void *)old, HME8BLK_SZ);
10857 	old->hblk_nextpa = va_to_pa((caddr_t)old);
10858 }
10859 
10860 /*
10861  * Grab the mlist mutex for both pages passed in.
10862  *
10863  * low and high will be returned as pointers to the mutexes for these pages.
10864  * low refers to the mutex residing in the lower bin of the mlist hash, while
10865  * high refers to the mutex residing in the higher bin of the mlist hash.  This
10866  * is due to the locking order restrictions on the same thread grabbing
10867  * multiple mlist mutexes.  The low lock must be acquired before the high lock.
10868  *
10869  * If both pages hash to the same mutex, only grab that single mutex, and
10870  * high will be returned as NULL
10871  * If the pages hash to different bins in the hash, grab the lower addressed
10872  * lock first and then the higher addressed lock in order to follow the locking
10873  * rules involved with the same thread grabbing multiple mlist mutexes.
10874  * low and high will both have non-NULL values.
10875  */
10876 static void
10877 sfmmu_mlist_reloc_enter(struct page *targ, struct page *repl,
10878     kmutex_t **low, kmutex_t **high)
10879 {
10880 	kmutex_t	*mml_targ, *mml_repl;
10881 
10882 	/*
10883 	 * no need to do the dance around szc as in sfmmu_mlist_enter()
10884 	 * because this routine is only called by hat_page_relocate() and all
10885 	 * targ and repl pages are already locked EXCL so szc can't change.
10886 	 */
10887 
10888 	mml_targ = MLIST_HASH(PP_PAGEROOT(targ));
10889 	mml_repl = MLIST_HASH(PP_PAGEROOT(repl));
10890 
10891 	if (mml_targ == mml_repl) {
10892 		*low = mml_targ;
10893 		*high = NULL;
10894 	} else {
10895 		if (mml_targ < mml_repl) {
10896 			*low = mml_targ;
10897 			*high = mml_repl;
10898 		} else {
10899 			*low = mml_repl;
10900 			*high = mml_targ;
10901 		}
10902 	}
10903 
10904 	mutex_enter(*low);
10905 	if (*high)
10906 		mutex_enter(*high);
10907 }
10908 
10909 static void
10910 sfmmu_mlist_reloc_exit(kmutex_t *low, kmutex_t *high)
10911 {
10912 	if (high)
10913 		mutex_exit(high);
10914 	mutex_exit(low);
10915 }
10916 
10917 static hatlock_t *
10918 sfmmu_hat_enter(sfmmu_t *sfmmup)
10919 {
10920 	hatlock_t	*hatlockp;
10921 
10922 	if (sfmmup != ksfmmup) {
10923 		hatlockp = TSB_HASH(sfmmup);
10924 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
10925 		return (hatlockp);
10926 	}
10927 	return (NULL);
10928 }
10929 
10930 static hatlock_t *
10931 sfmmu_hat_tryenter(sfmmu_t *sfmmup)
10932 {
10933 	hatlock_t	*hatlockp;
10934 
10935 	if (sfmmup != ksfmmup) {
10936 		hatlockp = TSB_HASH(sfmmup);
10937 		if (mutex_tryenter(HATLOCK_MUTEXP(hatlockp)) == 0)
10938 			return (NULL);
10939 		return (hatlockp);
10940 	}
10941 	return (NULL);
10942 }
10943 
10944 static void
10945 sfmmu_hat_exit(hatlock_t *hatlockp)
10946 {
10947 	if (hatlockp != NULL)
10948 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
10949 }
10950 
10951 static void
10952 sfmmu_hat_lock_all(void)
10953 {
10954 	int i;
10955 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
10956 		mutex_enter(HATLOCK_MUTEXP(&hat_lock[i]));
10957 }
10958 
10959 static void
10960 sfmmu_hat_unlock_all(void)
10961 {
10962 	int i;
10963 	for (i = SFMMU_NUM_LOCK - 1; i >= 0; i--)
10964 		mutex_exit(HATLOCK_MUTEXP(&hat_lock[i]));
10965 }
10966 
10967 int
10968 sfmmu_hat_lock_held(sfmmu_t *sfmmup)
10969 {
10970 	ASSERT(sfmmup != ksfmmup);
10971 	return (MUTEX_HELD(HATLOCK_MUTEXP(TSB_HASH(sfmmup))));
10972 }
10973 
10974 /*
10975  * Locking primitives to provide consistency between ISM unmap
10976  * and other operations.  Since ISM unmap can take a long time, we
10977  * use HAT_ISMBUSY flag (protected by the hatlock) to avoid creating
10978  * contention on the hatlock buckets while ISM segments are being
10979  * unmapped.  The tradeoff is that the flags don't prevent priority
10980  * inversion from occurring, so we must request kernel priority in
10981  * case we have to sleep to keep from getting buried while holding
10982  * the HAT_ISMBUSY flag set, which in turn could block other kernel
10983  * threads from running (for example, in sfmmu_uvatopfn()).
10984  */
10985 static void
10986 sfmmu_ismhat_enter(sfmmu_t *sfmmup, int hatlock_held)
10987 {
10988 	hatlock_t *hatlockp;
10989 
10990 	THREAD_KPRI_REQUEST();
10991 	if (!hatlock_held)
10992 		hatlockp = sfmmu_hat_enter(sfmmup);
10993 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY))
10994 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
10995 	SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
10996 	if (!hatlock_held)
10997 		sfmmu_hat_exit(hatlockp);
10998 }
10999 
11000 static void
11001 sfmmu_ismhat_exit(sfmmu_t *sfmmup, int hatlock_held)
11002 {
11003 	hatlock_t *hatlockp;
11004 
11005 	if (!hatlock_held)
11006 		hatlockp = sfmmu_hat_enter(sfmmup);
11007 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
11008 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
11009 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11010 	if (!hatlock_held)
11011 		sfmmu_hat_exit(hatlockp);
11012 	THREAD_KPRI_RELEASE();
11013 }
11014 
11015 /*
11016  *
11017  * Algorithm:
11018  *
11019  * (1) if segkmem is not ready, allocate hblk from an array of pre-alloc'ed
11020  *	hblks.
11021  *
11022  * (2) if we are allocating an hblk for mapping a slab in sfmmu_cache,
11023  *
11024  * 		(a) try to return an hblk from reserve pool of free hblks;
11025  *		(b) if the reserve pool is empty, acquire hblk_reserve_lock
11026  *		    and return hblk_reserve.
11027  *
11028  * (3) call kmem_cache_alloc() to allocate hblk;
11029  *
11030  *		(a) if hblk_reserve_lock is held by the current thread,
11031  *		    atomically replace hblk_reserve by the hblk that is
11032  *		    returned by kmem_cache_alloc; release hblk_reserve_lock
11033  *		    and call kmem_cache_alloc() again.
11034  *		(b) if reserve pool is not full, add the hblk that is
11035  *		    returned by kmem_cache_alloc to reserve pool and
11036  *		    call kmem_cache_alloc again.
11037  *
11038  */
11039 static struct hme_blk *
11040 sfmmu_hblk_alloc(sfmmu_t *sfmmup, caddr_t vaddr,
11041 	struct hmehash_bucket *hmebp, uint_t size, hmeblk_tag hblktag,
11042 	uint_t flags, uint_t rid)
11043 {
11044 	struct hme_blk *hmeblkp = NULL;
11045 	struct hme_blk *newhblkp;
11046 	struct hme_blk *shw_hblkp = NULL;
11047 	struct kmem_cache *sfmmu_cache = NULL;
11048 	uint64_t hblkpa;
11049 	ulong_t index;
11050 	uint_t owner;		/* set to 1 if using hblk_reserve */
11051 	uint_t forcefree;
11052 	int sleep;
11053 	sf_srd_t *srdp;
11054 	sf_region_t *rgnp;
11055 
11056 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11057 	ASSERT(hblktag.htag_rid == rid);
11058 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
11059 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11060 	    IS_P2ALIGNED(vaddr, TTEBYTES(size)));
11061 
11062 	/*
11063 	 * If segkmem is not created yet, allocate from static hmeblks
11064 	 * created at the end of startup_modules().  See the block comment
11065 	 * in startup_modules() describing how we estimate the number of
11066 	 * static hmeblks that will be needed during re-map.
11067 	 */
11068 	if (!hblk_alloc_dynamic) {
11069 
11070 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11071 
11072 		if (size == TTE8K) {
11073 			index = nucleus_hblk8.index;
11074 			if (index >= nucleus_hblk8.len) {
11075 				/*
11076 				 * If we panic here, see startup_modules() to
11077 				 * make sure that we are calculating the
11078 				 * number of hblk8's that we need correctly.
11079 				 */
11080 				prom_panic("no nucleus hblk8 to allocate");
11081 			}
11082 			hmeblkp =
11083 			    (struct hme_blk *)&nucleus_hblk8.list[index];
11084 			nucleus_hblk8.index++;
11085 			SFMMU_STAT(sf_hblk8_nalloc);
11086 		} else {
11087 			index = nucleus_hblk1.index;
11088 			if (nucleus_hblk1.index >= nucleus_hblk1.len) {
11089 				/*
11090 				 * If we panic here, see startup_modules().
11091 				 * Most likely you need to update the
11092 				 * calculation of the number of hblk1 elements
11093 				 * that the kernel needs to boot.
11094 				 */
11095 				prom_panic("no nucleus hblk1 to allocate");
11096 			}
11097 			hmeblkp =
11098 			    (struct hme_blk *)&nucleus_hblk1.list[index];
11099 			nucleus_hblk1.index++;
11100 			SFMMU_STAT(sf_hblk1_nalloc);
11101 		}
11102 
11103 		goto hblk_init;
11104 	}
11105 
11106 	SFMMU_HASH_UNLOCK(hmebp);
11107 
11108 	if (sfmmup != KHATID && !SFMMU_IS_SHMERID_VALID(rid)) {
11109 		if (mmu_page_sizes == max_mmu_page_sizes) {
11110 			if (size < TTE256M)
11111 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11112 				    size, flags);
11113 		} else {
11114 			if (size < TTE4M)
11115 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11116 				    size, flags);
11117 		}
11118 	} else if (SFMMU_IS_SHMERID_VALID(rid)) {
11119 		/*
11120 		 * Shared hmes use per region bitmaps in rgn_hmeflag
11121 		 * rather than shadow hmeblks to keep track of the
11122 		 * mapping sizes which have been allocated for the region.
11123 		 * Here we cleanup old invalid hmeblks with this rid,
11124 		 * which may be left around by pageunload().
11125 		 */
11126 		int ttesz;
11127 		caddr_t va;
11128 		caddr_t	eva = vaddr + TTEBYTES(size);
11129 
11130 		ASSERT(sfmmup != KHATID);
11131 
11132 		srdp = sfmmup->sfmmu_srdp;
11133 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11134 		rgnp = srdp->srd_hmergnp[rid];
11135 		ASSERT(rgnp != NULL && rgnp->rgn_id == rid);
11136 		ASSERT(rgnp->rgn_refcnt != 0);
11137 		ASSERT(size <= rgnp->rgn_pgszc);
11138 
11139 		ttesz = HBLK_MIN_TTESZ;
11140 		do {
11141 			if (!(rgnp->rgn_hmeflags & (0x1 << ttesz))) {
11142 				continue;
11143 			}
11144 
11145 			if (ttesz > size && ttesz != HBLK_MIN_TTESZ) {
11146 				sfmmu_cleanup_rhblk(srdp, vaddr, rid, ttesz);
11147 			} else if (ttesz < size) {
11148 				for (va = vaddr; va < eva;
11149 				    va += TTEBYTES(ttesz)) {
11150 					sfmmu_cleanup_rhblk(srdp, va, rid,
11151 					    ttesz);
11152 				}
11153 			}
11154 		} while (++ttesz <= rgnp->rgn_pgszc);
11155 	}
11156 
11157 fill_hblk:
11158 	owner = (hblk_reserve_thread == curthread) ? 1 : 0;
11159 
11160 	if (owner && size == TTE8K) {
11161 
11162 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11163 		/*
11164 		 * We are really in a tight spot. We already own
11165 		 * hblk_reserve and we need another hblk.  In anticipation
11166 		 * of this kind of scenario, we specifically set aside
11167 		 * HBLK_RESERVE_MIN number of hblks to be used exclusively
11168 		 * by owner of hblk_reserve.
11169 		 */
11170 		SFMMU_STAT(sf_hblk_recurse_cnt);
11171 
11172 		if (!sfmmu_get_free_hblk(&hmeblkp, 1))
11173 			panic("sfmmu_hblk_alloc: reserve list is empty");
11174 
11175 		goto hblk_verify;
11176 	}
11177 
11178 	ASSERT(!owner);
11179 
11180 	if ((flags & HAT_NO_KALLOC) == 0) {
11181 
11182 		sfmmu_cache = ((size == TTE8K) ? sfmmu8_cache : sfmmu1_cache);
11183 		sleep = ((sfmmup == KHATID) ? KM_NOSLEEP : KM_SLEEP);
11184 
11185 		if ((hmeblkp = kmem_cache_alloc(sfmmu_cache, sleep)) == NULL) {
11186 			hmeblkp = sfmmu_hblk_steal(size);
11187 		} else {
11188 			/*
11189 			 * if we are the owner of hblk_reserve,
11190 			 * swap hblk_reserve with hmeblkp and
11191 			 * start a fresh life.  Hope things go
11192 			 * better this time.
11193 			 */
11194 			if (hblk_reserve_thread == curthread) {
11195 				ASSERT(sfmmu_cache == sfmmu8_cache);
11196 				sfmmu_hblk_swap(hmeblkp);
11197 				hblk_reserve_thread = NULL;
11198 				mutex_exit(&hblk_reserve_lock);
11199 				goto fill_hblk;
11200 			}
11201 			/*
11202 			 * let's donate this hblk to our reserve list if
11203 			 * we are not mapping kernel range
11204 			 */
11205 			if (size == TTE8K && sfmmup != KHATID) {
11206 				if (sfmmu_put_free_hblk(hmeblkp, 0))
11207 					goto fill_hblk;
11208 			}
11209 		}
11210 	} else {
11211 		/*
11212 		 * We are here to map the slab in sfmmu8_cache; let's
11213 		 * check if we could tap our reserve list; if successful,
11214 		 * this will avoid the pain of going thru sfmmu_hblk_swap
11215 		 */
11216 		SFMMU_STAT(sf_hblk_slab_cnt);
11217 		if (!sfmmu_get_free_hblk(&hmeblkp, 0)) {
11218 			/*
11219 			 * let's start hblk_reserve dance
11220 			 */
11221 			SFMMU_STAT(sf_hblk_reserve_cnt);
11222 			owner = 1;
11223 			mutex_enter(&hblk_reserve_lock);
11224 			hmeblkp = HBLK_RESERVE;
11225 			hblk_reserve_thread = curthread;
11226 		}
11227 	}
11228 
11229 hblk_verify:
11230 	ASSERT(hmeblkp != NULL);
11231 	set_hblk_sz(hmeblkp, size);
11232 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
11233 	SFMMU_HASH_LOCK(hmebp);
11234 	HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11235 	if (newhblkp != NULL) {
11236 		SFMMU_HASH_UNLOCK(hmebp);
11237 		if (hmeblkp != HBLK_RESERVE) {
11238 			/*
11239 			 * This is really tricky!
11240 			 *
11241 			 * vmem_alloc(vmem_seg_arena)
11242 			 *  vmem_alloc(vmem_internal_arena)
11243 			 *   segkmem_alloc(heap_arena)
11244 			 *    vmem_alloc(heap_arena)
11245 			 *    page_create()
11246 			 *    hat_memload()
11247 			 *	kmem_cache_free()
11248 			 *	 kmem_cache_alloc()
11249 			 *	  kmem_slab_create()
11250 			 *	   vmem_alloc(kmem_internal_arena)
11251 			 *	    segkmem_alloc(heap_arena)
11252 			 *		vmem_alloc(heap_arena)
11253 			 *		page_create()
11254 			 *		hat_memload()
11255 			 *		  kmem_cache_free()
11256 			 *		...
11257 			 *
11258 			 * Thus, hat_memload() could call kmem_cache_free
11259 			 * for enough number of times that we could easily
11260 			 * hit the bottom of the stack or run out of reserve
11261 			 * list of vmem_seg structs.  So, we must donate
11262 			 * this hblk to reserve list if it's allocated
11263 			 * from sfmmu8_cache *and* mapping kernel range.
11264 			 * We don't need to worry about freeing hmeblk1's
11265 			 * to kmem since they don't map any kmem slabs.
11266 			 *
11267 			 * Note: When segkmem supports largepages, we must
11268 			 * free hmeblk1's to reserve list as well.
11269 			 */
11270 			forcefree = (sfmmup == KHATID) ? 1 : 0;
11271 			if (size == TTE8K &&
11272 			    sfmmu_put_free_hblk(hmeblkp, forcefree)) {
11273 				goto re_verify;
11274 			}
11275 			ASSERT(sfmmup != KHATID);
11276 			kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
11277 		} else {
11278 			/*
11279 			 * Hey! we don't need hblk_reserve any more.
11280 			 */
11281 			ASSERT(owner);
11282 			hblk_reserve_thread = NULL;
11283 			mutex_exit(&hblk_reserve_lock);
11284 			owner = 0;
11285 		}
11286 re_verify:
11287 		/*
11288 		 * let's check if the goodies are still present
11289 		 */
11290 		SFMMU_HASH_LOCK(hmebp);
11291 		HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11292 		if (newhblkp != NULL) {
11293 			/*
11294 			 * return newhblkp if it's not hblk_reserve;
11295 			 * if newhblkp is hblk_reserve, return it
11296 			 * _only if_ we are the owner of hblk_reserve.
11297 			 */
11298 			if (newhblkp != HBLK_RESERVE || owner) {
11299 				ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11300 				    newhblkp->hblk_shared);
11301 				ASSERT(SFMMU_IS_SHMERID_VALID(rid) ||
11302 				    !newhblkp->hblk_shared);
11303 				return (newhblkp);
11304 			} else {
11305 				/*
11306 				 * we just hit hblk_reserve in the hash and
11307 				 * we are not the owner of that;
11308 				 *
11309 				 * block until hblk_reserve_thread completes
11310 				 * swapping hblk_reserve and try the dance
11311 				 * once again.
11312 				 */
11313 				SFMMU_HASH_UNLOCK(hmebp);
11314 				mutex_enter(&hblk_reserve_lock);
11315 				mutex_exit(&hblk_reserve_lock);
11316 				SFMMU_STAT(sf_hblk_reserve_hit);
11317 				goto fill_hblk;
11318 			}
11319 		} else {
11320 			/*
11321 			 * it's no more! try the dance once again.
11322 			 */
11323 			SFMMU_HASH_UNLOCK(hmebp);
11324 			goto fill_hblk;
11325 		}
11326 	}
11327 
11328 hblk_init:
11329 	if (SFMMU_IS_SHMERID_VALID(rid)) {
11330 		uint16_t tteflag = 0x1 <<
11331 		    ((size < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ : size);
11332 
11333 		if (!(rgnp->rgn_hmeflags & tteflag)) {
11334 			atomic_or_16(&rgnp->rgn_hmeflags, tteflag);
11335 		}
11336 		hmeblkp->hblk_shared = 1;
11337 	} else {
11338 		hmeblkp->hblk_shared = 0;
11339 	}
11340 	set_hblk_sz(hmeblkp, size);
11341 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11342 	hmeblkp->hblk_next = (struct hme_blk *)NULL;
11343 	hmeblkp->hblk_tag = hblktag;
11344 	hmeblkp->hblk_shadow = shw_hblkp;
11345 	hblkpa = hmeblkp->hblk_nextpa;
11346 	hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
11347 
11348 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
11349 	ASSERT(get_hblk_span(hmeblkp) == HMEBLK_SPAN(size));
11350 	ASSERT(hmeblkp->hblk_hmecnt == 0);
11351 	ASSERT(hmeblkp->hblk_vcnt == 0);
11352 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11353 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
11354 	sfmmu_hblk_hash_add(hmebp, hmeblkp, hblkpa);
11355 	return (hmeblkp);
11356 }
11357 
11358 /*
11359  * This function cleans up the hme_blk and returns it to the free list.
11360  */
11361 /* ARGSUSED */
11362 static void
11363 sfmmu_hblk_free(struct hme_blk **listp)
11364 {
11365 	struct hme_blk *hmeblkp, *next_hmeblkp;
11366 	int		size;
11367 	uint_t		critical;
11368 	uint64_t	hblkpa;
11369 
11370 	ASSERT(*listp != NULL);
11371 
11372 	hmeblkp = *listp;
11373 	while (hmeblkp != NULL) {
11374 		next_hmeblkp = hmeblkp->hblk_next;
11375 		ASSERT(!hmeblkp->hblk_hmecnt);
11376 		ASSERT(!hmeblkp->hblk_vcnt);
11377 		ASSERT(!hmeblkp->hblk_lckcnt);
11378 		ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
11379 		ASSERT(hmeblkp->hblk_shared == 0);
11380 		ASSERT(hmeblkp->hblk_shw_bit == 0);
11381 		ASSERT(hmeblkp->hblk_shadow == NULL);
11382 
11383 		hblkpa = va_to_pa((caddr_t)hmeblkp);
11384 		ASSERT(hblkpa != (uint64_t)-1);
11385 		critical = (hblktosfmmu(hmeblkp) == KHATID) ? 1 : 0;
11386 
11387 		size = get_hblk_ttesz(hmeblkp);
11388 		hmeblkp->hblk_next = NULL;
11389 		hmeblkp->hblk_nextpa = hblkpa;
11390 
11391 		if (hmeblkp->hblk_nuc_bit == 0) {
11392 
11393 			if (size != TTE8K ||
11394 			    !sfmmu_put_free_hblk(hmeblkp, critical))
11395 				kmem_cache_free(get_hblk_cache(hmeblkp),
11396 				    hmeblkp);
11397 		}
11398 		hmeblkp = next_hmeblkp;
11399 	}
11400 }
11401 
11402 #define	BUCKETS_TO_SEARCH_BEFORE_UNLOAD	30
11403 #define	SFMMU_HBLK_STEAL_THRESHOLD 5
11404 
11405 static uint_t sfmmu_hblk_steal_twice;
11406 static uint_t sfmmu_hblk_steal_count, sfmmu_hblk_steal_unload_count;
11407 
11408 /*
11409  * Steal a hmeblk from user or kernel hme hash lists.
11410  * For 8K tte grab one from reserve pool (freehblkp) before proceeding to
11411  * steal and if we fail to steal after SFMMU_HBLK_STEAL_THRESHOLD attempts
11412  * tap into critical reserve of freehblkp.
11413  * Note: We remain looping in this routine until we find one.
11414  */
11415 static struct hme_blk *
11416 sfmmu_hblk_steal(int size)
11417 {
11418 	static struct hmehash_bucket *uhmehash_steal_hand = NULL;
11419 	struct hmehash_bucket *hmebp;
11420 	struct hme_blk *hmeblkp = NULL, *pr_hblk;
11421 	uint64_t hblkpa;
11422 	int i;
11423 	uint_t loop_cnt = 0, critical;
11424 
11425 	for (;;) {
11426 		/* Check cpu hblk pending queues */
11427 		if ((hmeblkp = sfmmu_check_pending_hblks(size)) != NULL) {
11428 			hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
11429 			ASSERT(hmeblkp->hblk_hmecnt == 0);
11430 			ASSERT(hmeblkp->hblk_vcnt == 0);
11431 			return (hmeblkp);
11432 		}
11433 
11434 		if (size == TTE8K) {
11435 			critical =
11436 			    (++loop_cnt > SFMMU_HBLK_STEAL_THRESHOLD) ? 1 : 0;
11437 			if (sfmmu_get_free_hblk(&hmeblkp, critical))
11438 				return (hmeblkp);
11439 		}
11440 
11441 		hmebp = (uhmehash_steal_hand == NULL) ? uhme_hash :
11442 		    uhmehash_steal_hand;
11443 		ASSERT(hmebp >= uhme_hash && hmebp <= &uhme_hash[UHMEHASH_SZ]);
11444 
11445 		for (i = 0; hmeblkp == NULL && i <= UHMEHASH_SZ +
11446 		    BUCKETS_TO_SEARCH_BEFORE_UNLOAD; i++) {
11447 			SFMMU_HASH_LOCK(hmebp);
11448 			hmeblkp = hmebp->hmeblkp;
11449 			hblkpa = hmebp->hmeh_nextpa;
11450 			pr_hblk = NULL;
11451 			while (hmeblkp) {
11452 				/*
11453 				 * check if it is a hmeblk that is not locked
11454 				 * and not shared. skip shadow hmeblks with
11455 				 * shadow_mask set i.e valid count non zero.
11456 				 */
11457 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11458 				    (hmeblkp->hblk_shw_bit == 0 ||
11459 				    hmeblkp->hblk_vcnt == 0) &&
11460 				    (hmeblkp->hblk_lckcnt == 0)) {
11461 					/*
11462 					 * there is a high probability that we
11463 					 * will find a free one. search some
11464 					 * buckets for a free hmeblk initially
11465 					 * before unloading a valid hmeblk.
11466 					 */
11467 					if ((hmeblkp->hblk_vcnt == 0 &&
11468 					    hmeblkp->hblk_hmecnt == 0) || (i >=
11469 					    BUCKETS_TO_SEARCH_BEFORE_UNLOAD)) {
11470 						if (sfmmu_steal_this_hblk(hmebp,
11471 						    hmeblkp, hblkpa, pr_hblk)) {
11472 							/*
11473 							 * Hblk is unloaded
11474 							 * successfully
11475 							 */
11476 							break;
11477 						}
11478 					}
11479 				}
11480 				pr_hblk = hmeblkp;
11481 				hblkpa = hmeblkp->hblk_nextpa;
11482 				hmeblkp = hmeblkp->hblk_next;
11483 			}
11484 
11485 			SFMMU_HASH_UNLOCK(hmebp);
11486 			if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
11487 				hmebp = uhme_hash;
11488 		}
11489 		uhmehash_steal_hand = hmebp;
11490 
11491 		if (hmeblkp != NULL)
11492 			break;
11493 
11494 		/*
11495 		 * in the worst case, look for a free one in the kernel
11496 		 * hash table.
11497 		 */
11498 		for (i = 0, hmebp = khme_hash; i <= KHMEHASH_SZ; i++) {
11499 			SFMMU_HASH_LOCK(hmebp);
11500 			hmeblkp = hmebp->hmeblkp;
11501 			hblkpa = hmebp->hmeh_nextpa;
11502 			pr_hblk = NULL;
11503 			while (hmeblkp) {
11504 				/*
11505 				 * check if it is free hmeblk
11506 				 */
11507 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11508 				    (hmeblkp->hblk_lckcnt == 0) &&
11509 				    (hmeblkp->hblk_vcnt == 0) &&
11510 				    (hmeblkp->hblk_hmecnt == 0)) {
11511 					if (sfmmu_steal_this_hblk(hmebp,
11512 					    hmeblkp, hblkpa, pr_hblk)) {
11513 						break;
11514 					} else {
11515 						/*
11516 						 * Cannot fail since we have
11517 						 * hash lock.
11518 						 */
11519 						panic("fail to steal?");
11520 					}
11521 				}
11522 
11523 				pr_hblk = hmeblkp;
11524 				hblkpa = hmeblkp->hblk_nextpa;
11525 				hmeblkp = hmeblkp->hblk_next;
11526 			}
11527 
11528 			SFMMU_HASH_UNLOCK(hmebp);
11529 			if (hmebp++ == &khme_hash[KHMEHASH_SZ])
11530 				hmebp = khme_hash;
11531 		}
11532 
11533 		if (hmeblkp != NULL)
11534 			break;
11535 		sfmmu_hblk_steal_twice++;
11536 	}
11537 	return (hmeblkp);
11538 }
11539 
11540 /*
11541  * This routine does real work to prepare a hblk to be "stolen" by
11542  * unloading the mappings, updating shadow counts ....
11543  * It returns 1 if the block is ready to be reused (stolen), or 0
11544  * means the block cannot be stolen yet- pageunload is still working
11545  * on this hblk.
11546  */
11547 static int
11548 sfmmu_steal_this_hblk(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
11549 	uint64_t hblkpa, struct hme_blk *pr_hblk)
11550 {
11551 	int shw_size, vshift;
11552 	struct hme_blk *shw_hblkp;
11553 	caddr_t vaddr;
11554 	uint_t shw_mask, newshw_mask;
11555 	struct hme_blk *list = NULL;
11556 
11557 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11558 
11559 	/*
11560 	 * check if the hmeblk is free, unload if necessary
11561 	 */
11562 	if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11563 		sfmmu_t *sfmmup;
11564 		demap_range_t dmr;
11565 
11566 		sfmmup = hblktosfmmu(hmeblkp);
11567 		if (hmeblkp->hblk_shared || sfmmup->sfmmu_ismhat) {
11568 			return (0);
11569 		}
11570 		DEMAP_RANGE_INIT(sfmmup, &dmr);
11571 		(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
11572 		    (caddr_t)get_hblk_base(hmeblkp),
11573 		    get_hblk_endaddr(hmeblkp), &dmr, HAT_UNLOAD);
11574 		DEMAP_RANGE_FLUSH(&dmr);
11575 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11576 			/*
11577 			 * Pageunload is working on the same hblk.
11578 			 */
11579 			return (0);
11580 		}
11581 
11582 		sfmmu_hblk_steal_unload_count++;
11583 	}
11584 
11585 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11586 	ASSERT(hmeblkp->hblk_vcnt == 0 && hmeblkp->hblk_hmecnt == 0);
11587 
11588 	sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk, &list, 1);
11589 	hmeblkp->hblk_nextpa = hblkpa;
11590 
11591 	shw_hblkp = hmeblkp->hblk_shadow;
11592 	if (shw_hblkp) {
11593 		ASSERT(!hmeblkp->hblk_shared);
11594 		shw_size = get_hblk_ttesz(shw_hblkp);
11595 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11596 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
11597 		ASSERT(vshift < 8);
11598 		/*
11599 		 * Atomically clear shadow mask bit
11600 		 */
11601 		do {
11602 			shw_mask = shw_hblkp->hblk_shw_mask;
11603 			ASSERT(shw_mask & (1 << vshift));
11604 			newshw_mask = shw_mask & ~(1 << vshift);
11605 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
11606 			    shw_mask, newshw_mask);
11607 		} while (newshw_mask != shw_mask);
11608 		hmeblkp->hblk_shadow = NULL;
11609 	}
11610 
11611 	/*
11612 	 * remove shadow bit if we are stealing an unused shadow hmeblk.
11613 	 * sfmmu_hblk_alloc needs it that way, will set shadow bit later if
11614 	 * we are indeed allocating a shadow hmeblk.
11615 	 */
11616 	hmeblkp->hblk_shw_bit = 0;
11617 
11618 	if (hmeblkp->hblk_shared) {
11619 		sf_srd_t	*srdp;
11620 		sf_region_t	*rgnp;
11621 		uint_t		rid;
11622 
11623 		srdp = hblktosrd(hmeblkp);
11624 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11625 		rid = hmeblkp->hblk_tag.htag_rid;
11626 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11627 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11628 		rgnp = srdp->srd_hmergnp[rid];
11629 		ASSERT(rgnp != NULL);
11630 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
11631 		hmeblkp->hblk_shared = 0;
11632 	}
11633 
11634 	sfmmu_hblk_steal_count++;
11635 	SFMMU_STAT(sf_steal_count);
11636 
11637 	return (1);
11638 }
11639 
11640 struct hme_blk *
11641 sfmmu_hmetohblk(struct sf_hment *sfhme)
11642 {
11643 	struct hme_blk *hmeblkp;
11644 	struct sf_hment *sfhme0;
11645 	struct hme_blk *hblk_dummy = 0;
11646 
11647 	/*
11648 	 * No dummy sf_hments, please.
11649 	 */
11650 	ASSERT(sfhme->hme_tte.ll != 0);
11651 
11652 	sfhme0 = sfhme - sfhme->hme_tte.tte_hmenum;
11653 	hmeblkp = (struct hme_blk *)((uintptr_t)sfhme0 -
11654 	    (uintptr_t)&hblk_dummy->hblk_hme[0]);
11655 
11656 	return (hmeblkp);
11657 }
11658 
11659 /*
11660  * On swapin, get appropriately sized TSB(s) and clear the HAT_SWAPPED flag.
11661  * If we can't get appropriately sized TSB(s), try for 8K TSB(s) using
11662  * KM_SLEEP allocation.
11663  *
11664  * Return 0 on success, -1 otherwise.
11665  */
11666 static void
11667 sfmmu_tsb_swapin(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11668 {
11669 	struct tsb_info *tsbinfop, *next;
11670 	tsb_replace_rc_t rc;
11671 	boolean_t gotfirst = B_FALSE;
11672 
11673 	ASSERT(sfmmup != ksfmmup);
11674 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11675 
11676 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPIN)) {
11677 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
11678 	}
11679 
11680 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11681 		SFMMU_FLAGS_SET(sfmmup, HAT_SWAPIN);
11682 	} else {
11683 		return;
11684 	}
11685 
11686 	ASSERT(sfmmup->sfmmu_tsb != NULL);
11687 
11688 	/*
11689 	 * Loop over all tsbinfo's replacing them with ones that actually have
11690 	 * a TSB.  If any of the replacements ever fail, bail out of the loop.
11691 	 */
11692 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL; tsbinfop = next) {
11693 		ASSERT(tsbinfop->tsb_flags & TSB_SWAPPED);
11694 		next = tsbinfop->tsb_next;
11695 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, tsbinfop->tsb_szc,
11696 		    hatlockp, TSB_SWAPIN);
11697 		if (rc != TSB_SUCCESS) {
11698 			break;
11699 		}
11700 		gotfirst = B_TRUE;
11701 	}
11702 
11703 	switch (rc) {
11704 	case TSB_SUCCESS:
11705 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11706 		cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11707 		return;
11708 	case TSB_LOSTRACE:
11709 		break;
11710 	case TSB_ALLOCFAIL:
11711 		break;
11712 	default:
11713 		panic("sfmmu_replace_tsb returned unrecognized failure code "
11714 		    "%d", rc);
11715 	}
11716 
11717 	/*
11718 	 * In this case, we failed to get one of our TSBs.  If we failed to
11719 	 * get the first TSB, get one of minimum size (8KB).  Walk the list
11720 	 * and throw away the tsbinfos, starting where the allocation failed;
11721 	 * we can get by with just one TSB as long as we don't leave the
11722 	 * SWAPPED tsbinfo structures lying around.
11723 	 */
11724 	tsbinfop = sfmmup->sfmmu_tsb;
11725 	next = tsbinfop->tsb_next;
11726 	tsbinfop->tsb_next = NULL;
11727 
11728 	sfmmu_hat_exit(hatlockp);
11729 	for (tsbinfop = next; tsbinfop != NULL; tsbinfop = next) {
11730 		next = tsbinfop->tsb_next;
11731 		sfmmu_tsbinfo_free(tsbinfop);
11732 	}
11733 	hatlockp = sfmmu_hat_enter(sfmmup);
11734 
11735 	/*
11736 	 * If we don't have any TSBs, get a single 8K TSB for 8K, 64K and 512K
11737 	 * pages.
11738 	 */
11739 	if (!gotfirst) {
11740 		tsbinfop = sfmmup->sfmmu_tsb;
11741 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, TSB_MIN_SZCODE,
11742 		    hatlockp, TSB_SWAPIN | TSB_FORCEALLOC);
11743 		ASSERT(rc == TSB_SUCCESS);
11744 	}
11745 
11746 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11747 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11748 }
11749 
11750 static int
11751 sfmmu_is_rgnva(sf_srd_t *srdp, caddr_t addr, ulong_t w, ulong_t bmw)
11752 {
11753 	ulong_t bix = 0;
11754 	uint_t rid;
11755 	sf_region_t *rgnp;
11756 
11757 	ASSERT(srdp != NULL);
11758 	ASSERT(srdp->srd_refcnt != 0);
11759 
11760 	w <<= BT_ULSHIFT;
11761 	while (bmw) {
11762 		if (!(bmw & 0x1)) {
11763 			bix++;
11764 			bmw >>= 1;
11765 			continue;
11766 		}
11767 		rid = w | bix;
11768 		rgnp = srdp->srd_hmergnp[rid];
11769 		ASSERT(rgnp->rgn_refcnt > 0);
11770 		ASSERT(rgnp->rgn_id == rid);
11771 		if (addr < rgnp->rgn_saddr ||
11772 		    addr >= (rgnp->rgn_saddr + rgnp->rgn_size)) {
11773 			bix++;
11774 			bmw >>= 1;
11775 		} else {
11776 			return (1);
11777 		}
11778 	}
11779 	return (0);
11780 }
11781 
11782 /*
11783  * Handle exceptions for low level tsb_handler.
11784  *
11785  * There are many scenarios that could land us here:
11786  *
11787  * If the context is invalid we land here. The context can be invalid
11788  * for 3 reasons: 1) we couldn't allocate a new context and now need to
11789  * perform a wrap around operation in order to allocate a new context.
11790  * 2) Context was invalidated to change pagesize programming 3) ISMs or
11791  * TSBs configuration is changeing for this process and we are forced into
11792  * here to do a syncronization operation. If the context is valid we can
11793  * be here from window trap hanlder. In this case just call trap to handle
11794  * the fault.
11795  *
11796  * Note that the process will run in INVALID_CONTEXT before
11797  * faulting into here and subsequently loading the MMU registers
11798  * (including the TSB base register) associated with this process.
11799  * For this reason, the trap handlers must all test for
11800  * INVALID_CONTEXT before attempting to access any registers other
11801  * than the context registers.
11802  */
11803 void
11804 sfmmu_tsbmiss_exception(struct regs *rp, uintptr_t tagaccess, uint_t traptype)
11805 {
11806 	sfmmu_t *sfmmup, *shsfmmup;
11807 	uint_t ctxtype;
11808 	klwp_id_t lwp;
11809 	char lwp_save_state;
11810 	hatlock_t *hatlockp, *shatlockp;
11811 	struct tsb_info *tsbinfop;
11812 	struct tsbmiss *tsbmp;
11813 	sf_scd_t *scdp;
11814 
11815 	SFMMU_STAT(sf_tsb_exceptions);
11816 	SFMMU_MMU_STAT(mmu_tsb_exceptions);
11817 	sfmmup = astosfmmu(curthread->t_procp->p_as);
11818 	/*
11819 	 * note that in sun4u, tagacces register contains ctxnum
11820 	 * while sun4v passes ctxtype in the tagaccess register.
11821 	 */
11822 	ctxtype = tagaccess & TAGACC_CTX_MASK;
11823 
11824 	ASSERT(sfmmup != ksfmmup && ctxtype != KCONTEXT);
11825 	ASSERT(sfmmup->sfmmu_ismhat == 0);
11826 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED) ||
11827 	    ctxtype == INVALID_CONTEXT);
11828 
11829 	if (ctxtype != INVALID_CONTEXT && traptype != T_DATA_PROT) {
11830 		/*
11831 		 * We may land here because shme bitmap and pagesize
11832 		 * flags are updated lazily in tsbmiss area on other cpus.
11833 		 * If we detect here that tsbmiss area is out of sync with
11834 		 * sfmmu update it and retry the trapped instruction.
11835 		 * Otherwise call trap().
11836 		 */
11837 		int ret = 0;
11838 		uchar_t tteflag_mask = (1 << TTE64K) | (1 << TTE8K);
11839 		caddr_t addr = (caddr_t)(tagaccess & TAGACC_VADDR_MASK);
11840 
11841 		/*
11842 		 * Must set lwp state to LWP_SYS before
11843 		 * trying to acquire any adaptive lock
11844 		 */
11845 		lwp = ttolwp(curthread);
11846 		ASSERT(lwp);
11847 		lwp_save_state = lwp->lwp_state;
11848 		lwp->lwp_state = LWP_SYS;
11849 
11850 		hatlockp = sfmmu_hat_enter(sfmmup);
11851 		kpreempt_disable();
11852 		tsbmp = &tsbmiss_area[CPU->cpu_id];
11853 		ASSERT(sfmmup == tsbmp->usfmmup);
11854 		if (((tsbmp->uhat_tteflags ^ sfmmup->sfmmu_tteflags) &
11855 		    ~tteflag_mask) ||
11856 		    ((tsbmp->uhat_rtteflags ^  sfmmup->sfmmu_rtteflags) &
11857 		    ~tteflag_mask)) {
11858 			tsbmp->uhat_tteflags = sfmmup->sfmmu_tteflags;
11859 			tsbmp->uhat_rtteflags = sfmmup->sfmmu_rtteflags;
11860 			ret = 1;
11861 		}
11862 		if (sfmmup->sfmmu_srdp != NULL) {
11863 			ulong_t *sm = sfmmup->sfmmu_hmeregion_map.bitmap;
11864 			ulong_t *tm = tsbmp->shmermap;
11865 			ulong_t i;
11866 			for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
11867 				ulong_t d = tm[i] ^ sm[i];
11868 				if (d) {
11869 					if (d & sm[i]) {
11870 						if (!ret && sfmmu_is_rgnva(
11871 						    sfmmup->sfmmu_srdp,
11872 						    addr, i, d & sm[i])) {
11873 							ret = 1;
11874 						}
11875 					}
11876 					tm[i] = sm[i];
11877 				}
11878 			}
11879 		}
11880 		kpreempt_enable();
11881 		sfmmu_hat_exit(hatlockp);
11882 		lwp->lwp_state = lwp_save_state;
11883 		if (ret) {
11884 			return;
11885 		}
11886 	} else if (ctxtype == INVALID_CONTEXT) {
11887 		/*
11888 		 * First, make sure we come out of here with a valid ctx,
11889 		 * since if we don't get one we'll simply loop on the
11890 		 * faulting instruction.
11891 		 *
11892 		 * If the ISM mappings are changing, the TSB is relocated,
11893 		 * the process is swapped, the process is joining SCD or
11894 		 * leaving SCD or shared regions we serialize behind the
11895 		 * controlling thread with hat lock, sfmmu_flags and
11896 		 * sfmmu_tsb_cv condition variable.
11897 		 */
11898 
11899 		/*
11900 		 * Must set lwp state to LWP_SYS before
11901 		 * trying to acquire any adaptive lock
11902 		 */
11903 		lwp = ttolwp(curthread);
11904 		ASSERT(lwp);
11905 		lwp_save_state = lwp->lwp_state;
11906 		lwp->lwp_state = LWP_SYS;
11907 
11908 		hatlockp = sfmmu_hat_enter(sfmmup);
11909 retry:
11910 		if ((scdp = sfmmup->sfmmu_scdp) != NULL) {
11911 			shsfmmup = scdp->scd_sfmmup;
11912 			ASSERT(shsfmmup != NULL);
11913 
11914 			for (tsbinfop = shsfmmup->sfmmu_tsb; tsbinfop != NULL;
11915 			    tsbinfop = tsbinfop->tsb_next) {
11916 				if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11917 					/* drop the private hat lock */
11918 					sfmmu_hat_exit(hatlockp);
11919 					/* acquire the shared hat lock */
11920 					shatlockp = sfmmu_hat_enter(shsfmmup);
11921 					/*
11922 					 * recheck to see if anything changed
11923 					 * after we drop the private hat lock.
11924 					 */
11925 					if (sfmmup->sfmmu_scdp == scdp &&
11926 					    shsfmmup == scdp->scd_sfmmup) {
11927 						sfmmu_tsb_chk_reloc(shsfmmup,
11928 						    shatlockp);
11929 					}
11930 					sfmmu_hat_exit(shatlockp);
11931 					hatlockp = sfmmu_hat_enter(sfmmup);
11932 					goto retry;
11933 				}
11934 			}
11935 		}
11936 
11937 		for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
11938 		    tsbinfop = tsbinfop->tsb_next) {
11939 			if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11940 				cv_wait(&sfmmup->sfmmu_tsb_cv,
11941 				    HATLOCK_MUTEXP(hatlockp));
11942 				goto retry;
11943 			}
11944 		}
11945 
11946 		/*
11947 		 * Wait for ISM maps to be updated.
11948 		 */
11949 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
11950 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11951 			    HATLOCK_MUTEXP(hatlockp));
11952 			goto retry;
11953 		}
11954 
11955 		/* Is this process joining an SCD? */
11956 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
11957 			/*
11958 			 * Flush private TSB and setup shared TSB.
11959 			 * sfmmu_finish_join_scd() does not drop the
11960 			 * hat lock.
11961 			 */
11962 			sfmmu_finish_join_scd(sfmmup);
11963 			SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
11964 		}
11965 
11966 		/*
11967 		 * If we're swapping in, get TSB(s).  Note that we must do
11968 		 * this before we get a ctx or load the MMU state.  Once
11969 		 * we swap in we have to recheck to make sure the TSB(s) and
11970 		 * ISM mappings didn't change while we slept.
11971 		 */
11972 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11973 			sfmmu_tsb_swapin(sfmmup, hatlockp);
11974 			goto retry;
11975 		}
11976 
11977 		sfmmu_get_ctx(sfmmup);
11978 
11979 		sfmmu_hat_exit(hatlockp);
11980 		/*
11981 		 * Must restore lwp_state if not calling
11982 		 * trap() for further processing. Restore
11983 		 * it anyway.
11984 		 */
11985 		lwp->lwp_state = lwp_save_state;
11986 		return;
11987 	}
11988 	trap(rp, (caddr_t)tagaccess, traptype, 0);
11989 }
11990 
11991 static void
11992 sfmmu_tsb_chk_reloc(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11993 {
11994 	struct tsb_info *tp;
11995 
11996 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11997 
11998 	for (tp = sfmmup->sfmmu_tsb; tp != NULL; tp = tp->tsb_next) {
11999 		if (tp->tsb_flags & TSB_RELOC_FLAG) {
12000 			cv_wait(&sfmmup->sfmmu_tsb_cv,
12001 			    HATLOCK_MUTEXP(hatlockp));
12002 			break;
12003 		}
12004 	}
12005 }
12006 
12007 /*
12008  * sfmmu_vatopfn_suspended is called from GET_TTE when TL=0 and
12009  * TTE_SUSPENDED bit set in tte we block on aquiring a page lock
12010  * rather than spinning to avoid send mondo timeouts with
12011  * interrupts enabled. When the lock is acquired it is immediately
12012  * released and we return back to sfmmu_vatopfn just after
12013  * the GET_TTE call.
12014  */
12015 void
12016 sfmmu_vatopfn_suspended(caddr_t vaddr, sfmmu_t *sfmmu, tte_t *ttep)
12017 {
12018 	struct page	**pp;
12019 
12020 	(void) as_pagelock(sfmmu->sfmmu_as, &pp, vaddr, TTE_CSZ(ttep), S_WRITE);
12021 	as_pageunlock(sfmmu->sfmmu_as, pp, vaddr, TTE_CSZ(ttep), S_WRITE);
12022 }
12023 
12024 /*
12025  * sfmmu_tsbmiss_suspended is called from GET_TTE when TL>0 and
12026  * TTE_SUSPENDED bit set in tte. We do this so that we can handle
12027  * cross traps which cannot be handled while spinning in the
12028  * trap handlers. Simply enter and exit the kpr_suspendlock spin
12029  * mutex, which is held by the holder of the suspend bit, and then
12030  * retry the trapped instruction after unwinding.
12031  */
12032 /*ARGSUSED*/
12033 void
12034 sfmmu_tsbmiss_suspended(struct regs *rp, uintptr_t tagacc, uint_t traptype)
12035 {
12036 	ASSERT(curthread != kreloc_thread);
12037 	mutex_enter(&kpr_suspendlock);
12038 	mutex_exit(&kpr_suspendlock);
12039 }
12040 
12041 /*
12042  * This routine could be optimized to reduce the number of xcalls by flushing
12043  * the entire TLBs if region reference count is above some threshold but the
12044  * tradeoff will depend on the size of the TLB. So for now flush the specific
12045  * page a context at a time.
12046  *
12047  * If uselocks is 0 then it's called after all cpus were captured and all the
12048  * hat locks were taken. In this case don't take the region lock by relying on
12049  * the order of list region update operations in hat_join_region(),
12050  * hat_leave_region() and hat_dup_region(). The ordering in those routines
12051  * guarantees that list is always forward walkable and reaches active sfmmus
12052  * regardless of where xc_attention() captures a cpu.
12053  */
12054 cpuset_t
12055 sfmmu_rgntlb_demap(caddr_t addr, sf_region_t *rgnp,
12056     struct hme_blk *hmeblkp, int uselocks)
12057 {
12058 	sfmmu_t	*sfmmup;
12059 	cpuset_t cpuset;
12060 	cpuset_t rcpuset;
12061 	hatlock_t *hatlockp;
12062 	uint_t rid = rgnp->rgn_id;
12063 	sf_rgn_link_t *rlink;
12064 	sf_scd_t *scdp;
12065 
12066 	ASSERT(hmeblkp->hblk_shared);
12067 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
12068 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
12069 
12070 	CPUSET_ZERO(rcpuset);
12071 	if (uselocks) {
12072 		mutex_enter(&rgnp->rgn_mutex);
12073 	}
12074 	sfmmup = rgnp->rgn_sfmmu_head;
12075 	while (sfmmup != NULL) {
12076 		if (uselocks) {
12077 			hatlockp = sfmmu_hat_enter(sfmmup);
12078 		}
12079 
12080 		/*
12081 		 * When an SCD is created the SCD hat is linked on the sfmmu
12082 		 * region lists for each hme region which is part of the
12083 		 * SCD. If we find an SCD hat, when walking these lists,
12084 		 * then we flush the shared TSBs, if we find a private hat,
12085 		 * which is part of an SCD, but where the region
12086 		 * is not part of the SCD then we flush the private TSBs.
12087 		 */
12088 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12089 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
12090 			scdp = sfmmup->sfmmu_scdp;
12091 			if (SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
12092 				if (uselocks) {
12093 					sfmmu_hat_exit(hatlockp);
12094 				}
12095 				goto next;
12096 			}
12097 		}
12098 
12099 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12100 
12101 		kpreempt_disable();
12102 		cpuset = sfmmup->sfmmu_cpusran;
12103 		CPUSET_AND(cpuset, cpu_ready_set);
12104 		CPUSET_DEL(cpuset, CPU->cpu_id);
12105 		SFMMU_XCALL_STATS(sfmmup);
12106 		xt_some(cpuset, vtag_flushpage_tl1,
12107 		    (uint64_t)addr, (uint64_t)sfmmup);
12108 		vtag_flushpage(addr, (uint64_t)sfmmup);
12109 		if (uselocks) {
12110 			sfmmu_hat_exit(hatlockp);
12111 		}
12112 		kpreempt_enable();
12113 		CPUSET_OR(rcpuset, cpuset);
12114 
12115 next:
12116 		/* LINTED: constant in conditional context */
12117 		SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
12118 		ASSERT(rlink != NULL);
12119 		sfmmup = rlink->next;
12120 	}
12121 	if (uselocks) {
12122 		mutex_exit(&rgnp->rgn_mutex);
12123 	}
12124 	return (rcpuset);
12125 }
12126 
12127 /*
12128  * This routine takes an sfmmu pointer and the va for an adddress in an
12129  * ISM region as input and returns the corresponding region id in ism_rid.
12130  * The return value of 1 indicates that a region has been found and ism_rid
12131  * is valid, otherwise 0 is returned.
12132  */
12133 static int
12134 find_ism_rid(sfmmu_t *sfmmup, sfmmu_t *ism_sfmmup, caddr_t va, uint_t *ism_rid)
12135 {
12136 	ism_blk_t	*ism_blkp;
12137 	int		i;
12138 	ism_map_t	*ism_map;
12139 #ifdef DEBUG
12140 	struct hat	*ism_hatid;
12141 #endif
12142 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12143 
12144 	ism_blkp = sfmmup->sfmmu_iblk;
12145 	while (ism_blkp != NULL) {
12146 		ism_map = ism_blkp->iblk_maps;
12147 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
12148 			if ((va >= ism_start(ism_map[i])) &&
12149 			    (va < ism_end(ism_map[i]))) {
12150 
12151 				*ism_rid = ism_map[i].imap_rid;
12152 #ifdef DEBUG
12153 				ism_hatid = ism_map[i].imap_ismhat;
12154 				ASSERT(ism_hatid == ism_sfmmup);
12155 				ASSERT(ism_hatid->sfmmu_ismhat);
12156 #endif
12157 				return (1);
12158 			}
12159 		}
12160 		ism_blkp = ism_blkp->iblk_next;
12161 	}
12162 	return (0);
12163 }
12164 
12165 /*
12166  * Special routine to flush out ism mappings- TSBs, TLBs and D-caches.
12167  * This routine may be called with all cpu's captured. Therefore, the
12168  * caller is responsible for holding all locks and disabling kernel
12169  * preemption.
12170  */
12171 /* ARGSUSED */
12172 static void
12173 sfmmu_ismtlbcache_demap(caddr_t addr, sfmmu_t *ism_sfmmup,
12174 	struct hme_blk *hmeblkp, pfn_t pfnum, int cache_flush_flag)
12175 {
12176 	cpuset_t 	cpuset;
12177 	caddr_t 	va;
12178 	ism_ment_t	*ment;
12179 	sfmmu_t		*sfmmup;
12180 #ifdef VAC
12181 	int 		vcolor;
12182 #endif
12183 
12184 	sf_scd_t	*scdp;
12185 	uint_t		ism_rid;
12186 
12187 	ASSERT(!hmeblkp->hblk_shared);
12188 	/*
12189 	 * Walk the ism_hat's mapping list and flush the page
12190 	 * from every hat sharing this ism_hat. This routine
12191 	 * may be called while all cpu's have been captured.
12192 	 * Therefore we can't attempt to grab any locks. For now
12193 	 * this means we will protect the ism mapping list under
12194 	 * a single lock which will be grabbed by the caller.
12195 	 * If hat_share/unshare scalibility becomes a performance
12196 	 * problem then we may need to re-think ism mapping list locking.
12197 	 */
12198 	ASSERT(ism_sfmmup->sfmmu_ismhat);
12199 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
12200 	addr = addr - ISMID_STARTADDR;
12201 
12202 	for (ment = ism_sfmmup->sfmmu_iment; ment; ment = ment->iment_next) {
12203 
12204 		sfmmup = ment->iment_hat;
12205 
12206 		va = ment->iment_base_va;
12207 		va = (caddr_t)((uintptr_t)va  + (uintptr_t)addr);
12208 
12209 		/*
12210 		 * When an SCD is created the SCD hat is linked on the ism
12211 		 * mapping lists for each ISM segment which is part of the
12212 		 * SCD. If we find an SCD hat, when walking these lists,
12213 		 * then we flush the shared TSBs, if we find a private hat,
12214 		 * which is part of an SCD, but where the region
12215 		 * corresponding to this va is not part of the SCD then we
12216 		 * flush the private TSBs.
12217 		 */
12218 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12219 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD) &&
12220 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
12221 			if (!find_ism_rid(sfmmup, ism_sfmmup, va,
12222 			    &ism_rid)) {
12223 				cmn_err(CE_PANIC,
12224 				    "can't find matching ISM rid!");
12225 			}
12226 
12227 			scdp = sfmmup->sfmmu_scdp;
12228 			if (SFMMU_IS_ISMRID_VALID(ism_rid) &&
12229 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map,
12230 			    ism_rid)) {
12231 				continue;
12232 			}
12233 		}
12234 		SFMMU_UNLOAD_TSB(va, sfmmup, hmeblkp, 1);
12235 
12236 		cpuset = sfmmup->sfmmu_cpusran;
12237 		CPUSET_AND(cpuset, cpu_ready_set);
12238 		CPUSET_DEL(cpuset, CPU->cpu_id);
12239 		SFMMU_XCALL_STATS(sfmmup);
12240 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)va,
12241 		    (uint64_t)sfmmup);
12242 		vtag_flushpage(va, (uint64_t)sfmmup);
12243 
12244 #ifdef VAC
12245 		/*
12246 		 * Flush D$
12247 		 * When flushing D$ we must flush all
12248 		 * cpu's. See sfmmu_cache_flush().
12249 		 */
12250 		if (cache_flush_flag == CACHE_FLUSH) {
12251 			cpuset = cpu_ready_set;
12252 			CPUSET_DEL(cpuset, CPU->cpu_id);
12253 
12254 			SFMMU_XCALL_STATS(sfmmup);
12255 			vcolor = addr_to_vcolor(va);
12256 			xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12257 			vac_flushpage(pfnum, vcolor);
12258 		}
12259 #endif	/* VAC */
12260 	}
12261 }
12262 
12263 /*
12264  * Demaps the TSB, CPU caches, and flushes all TLBs on all CPUs of
12265  * a particular virtual address and ctx.  If noflush is set we do not
12266  * flush the TLB/TSB.  This function may or may not be called with the
12267  * HAT lock held.
12268  */
12269 static void
12270 sfmmu_tlbcache_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12271 	pfn_t pfnum, int tlb_noflush, int cpu_flag, int cache_flush_flag,
12272 	int hat_lock_held)
12273 {
12274 #ifdef VAC
12275 	int vcolor;
12276 #endif
12277 	cpuset_t cpuset;
12278 	hatlock_t *hatlockp;
12279 
12280 	ASSERT(!hmeblkp->hblk_shared);
12281 
12282 #if defined(lint) && !defined(VAC)
12283 	pfnum = pfnum;
12284 	cpu_flag = cpu_flag;
12285 	cache_flush_flag = cache_flush_flag;
12286 #endif
12287 
12288 	/*
12289 	 * There is no longer a need to protect against ctx being
12290 	 * stolen here since we don't store the ctx in the TSB anymore.
12291 	 */
12292 #ifdef VAC
12293 	vcolor = addr_to_vcolor(addr);
12294 #endif
12295 
12296 	/*
12297 	 * We must hold the hat lock during the flush of TLB,
12298 	 * to avoid a race with sfmmu_invalidate_ctx(), where
12299 	 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12300 	 * causing TLB demap routine to skip flush on that MMU.
12301 	 * If the context on a MMU has already been set to
12302 	 * INVALID_CONTEXT, we just get an extra flush on
12303 	 * that MMU.
12304 	 */
12305 	if (!hat_lock_held && !tlb_noflush)
12306 		hatlockp = sfmmu_hat_enter(sfmmup);
12307 
12308 	kpreempt_disable();
12309 	if (!tlb_noflush) {
12310 		/*
12311 		 * Flush the TSB and TLB.
12312 		 */
12313 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12314 
12315 		cpuset = sfmmup->sfmmu_cpusran;
12316 		CPUSET_AND(cpuset, cpu_ready_set);
12317 		CPUSET_DEL(cpuset, CPU->cpu_id);
12318 
12319 		SFMMU_XCALL_STATS(sfmmup);
12320 
12321 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
12322 		    (uint64_t)sfmmup);
12323 
12324 		vtag_flushpage(addr, (uint64_t)sfmmup);
12325 	}
12326 
12327 	if (!hat_lock_held && !tlb_noflush)
12328 		sfmmu_hat_exit(hatlockp);
12329 
12330 #ifdef VAC
12331 	/*
12332 	 * Flush the D$
12333 	 *
12334 	 * Even if the ctx is stolen, we need to flush the
12335 	 * cache. Our ctx stealer only flushes the TLBs.
12336 	 */
12337 	if (cache_flush_flag == CACHE_FLUSH) {
12338 		if (cpu_flag & FLUSH_ALL_CPUS) {
12339 			cpuset = cpu_ready_set;
12340 		} else {
12341 			cpuset = sfmmup->sfmmu_cpusran;
12342 			CPUSET_AND(cpuset, cpu_ready_set);
12343 		}
12344 		CPUSET_DEL(cpuset, CPU->cpu_id);
12345 		SFMMU_XCALL_STATS(sfmmup);
12346 		xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12347 		vac_flushpage(pfnum, vcolor);
12348 	}
12349 #endif	/* VAC */
12350 	kpreempt_enable();
12351 }
12352 
12353 /*
12354  * Demaps the TSB and flushes all TLBs on all cpus for a particular virtual
12355  * address and ctx.  If noflush is set we do not currently do anything.
12356  * This function may or may not be called with the HAT lock held.
12357  */
12358 static void
12359 sfmmu_tlb_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12360 	int tlb_noflush, int hat_lock_held)
12361 {
12362 	cpuset_t cpuset;
12363 	hatlock_t *hatlockp;
12364 
12365 	ASSERT(!hmeblkp->hblk_shared);
12366 
12367 	/*
12368 	 * If the process is exiting we have nothing to do.
12369 	 */
12370 	if (tlb_noflush)
12371 		return;
12372 
12373 	/*
12374 	 * Flush TSB.
12375 	 */
12376 	if (!hat_lock_held)
12377 		hatlockp = sfmmu_hat_enter(sfmmup);
12378 	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12379 
12380 	kpreempt_disable();
12381 
12382 	cpuset = sfmmup->sfmmu_cpusran;
12383 	CPUSET_AND(cpuset, cpu_ready_set);
12384 	CPUSET_DEL(cpuset, CPU->cpu_id);
12385 
12386 	SFMMU_XCALL_STATS(sfmmup);
12387 	xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr, (uint64_t)sfmmup);
12388 
12389 	vtag_flushpage(addr, (uint64_t)sfmmup);
12390 
12391 	if (!hat_lock_held)
12392 		sfmmu_hat_exit(hatlockp);
12393 
12394 	kpreempt_enable();
12395 
12396 }
12397 
12398 /*
12399  * Special case of sfmmu_tlb_demap for MMU_PAGESIZE hblks. Use the xcall
12400  * call handler that can flush a range of pages to save on xcalls.
12401  */
12402 static int sfmmu_xcall_save;
12403 
12404 /*
12405  * this routine is never used for demaping addresses backed by SRD hmeblks.
12406  */
12407 static void
12408 sfmmu_tlb_range_demap(demap_range_t *dmrp)
12409 {
12410 	sfmmu_t *sfmmup = dmrp->dmr_sfmmup;
12411 	hatlock_t *hatlockp;
12412 	cpuset_t cpuset;
12413 	uint64_t sfmmu_pgcnt;
12414 	pgcnt_t pgcnt = 0;
12415 	int pgunload = 0;
12416 	int dirtypg = 0;
12417 	caddr_t addr = dmrp->dmr_addr;
12418 	caddr_t eaddr;
12419 	uint64_t bitvec = dmrp->dmr_bitvec;
12420 
12421 	ASSERT(bitvec & 1);
12422 
12423 	/*
12424 	 * Flush TSB and calculate number of pages to flush.
12425 	 */
12426 	while (bitvec != 0) {
12427 		dirtypg = 0;
12428 		/*
12429 		 * Find the first page to flush and then count how many
12430 		 * pages there are after it that also need to be flushed.
12431 		 * This way the number of TSB flushes is minimized.
12432 		 */
12433 		while ((bitvec & 1) == 0) {
12434 			pgcnt++;
12435 			addr += MMU_PAGESIZE;
12436 			bitvec >>= 1;
12437 		}
12438 		while (bitvec & 1) {
12439 			dirtypg++;
12440 			bitvec >>= 1;
12441 		}
12442 		eaddr = addr + ptob(dirtypg);
12443 		hatlockp = sfmmu_hat_enter(sfmmup);
12444 		sfmmu_unload_tsb_range(sfmmup, addr, eaddr, TTE8K);
12445 		sfmmu_hat_exit(hatlockp);
12446 		pgunload += dirtypg;
12447 		addr = eaddr;
12448 		pgcnt += dirtypg;
12449 	}
12450 
12451 	ASSERT((pgcnt<<MMU_PAGESHIFT) <= dmrp->dmr_endaddr - dmrp->dmr_addr);
12452 	if (sfmmup->sfmmu_free == 0) {
12453 		addr = dmrp->dmr_addr;
12454 		bitvec = dmrp->dmr_bitvec;
12455 
12456 		/*
12457 		 * make sure it has SFMMU_PGCNT_SHIFT bits only,
12458 		 * as it will be used to pack argument for xt_some
12459 		 */
12460 		ASSERT((pgcnt > 0) &&
12461 		    (pgcnt <= (1 << SFMMU_PGCNT_SHIFT)));
12462 
12463 		/*
12464 		 * Encode pgcnt as (pgcnt -1 ), and pass (pgcnt - 1) in
12465 		 * the low 6 bits of sfmmup. This is doable since pgcnt
12466 		 * always >= 1.
12467 		 */
12468 		ASSERT(!((uint64_t)sfmmup & SFMMU_PGCNT_MASK));
12469 		sfmmu_pgcnt = (uint64_t)sfmmup |
12470 		    ((pgcnt - 1) & SFMMU_PGCNT_MASK);
12471 
12472 		/*
12473 		 * We must hold the hat lock during the flush of TLB,
12474 		 * to avoid a race with sfmmu_invalidate_ctx(), where
12475 		 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12476 		 * causing TLB demap routine to skip flush on that MMU.
12477 		 * If the context on a MMU has already been set to
12478 		 * INVALID_CONTEXT, we just get an extra flush on
12479 		 * that MMU.
12480 		 */
12481 		hatlockp = sfmmu_hat_enter(sfmmup);
12482 		kpreempt_disable();
12483 
12484 		cpuset = sfmmup->sfmmu_cpusran;
12485 		CPUSET_AND(cpuset, cpu_ready_set);
12486 		CPUSET_DEL(cpuset, CPU->cpu_id);
12487 
12488 		SFMMU_XCALL_STATS(sfmmup);
12489 		xt_some(cpuset, vtag_flush_pgcnt_tl1, (uint64_t)addr,
12490 		    sfmmu_pgcnt);
12491 
12492 		for (; bitvec != 0; bitvec >>= 1) {
12493 			if (bitvec & 1)
12494 				vtag_flushpage(addr, (uint64_t)sfmmup);
12495 			addr += MMU_PAGESIZE;
12496 		}
12497 		kpreempt_enable();
12498 		sfmmu_hat_exit(hatlockp);
12499 
12500 		sfmmu_xcall_save += (pgunload-1);
12501 	}
12502 	dmrp->dmr_bitvec = 0;
12503 }
12504 
12505 /*
12506  * In cases where we need to synchronize with TLB/TSB miss trap
12507  * handlers, _and_ need to flush the TLB, it's a lot easier to
12508  * throw away the context from the process than to do a
12509  * special song and dance to keep things consistent for the
12510  * handlers.
12511  *
12512  * Since the process suddenly ends up without a context and our caller
12513  * holds the hat lock, threads that fault after this function is called
12514  * will pile up on the lock.  We can then do whatever we need to
12515  * atomically from the context of the caller.  The first blocked thread
12516  * to resume executing will get the process a new context, and the
12517  * process will resume executing.
12518  *
12519  * One added advantage of this approach is that on MMUs that
12520  * support a "flush all" operation, we will delay the flush until
12521  * cnum wrap-around, and then flush the TLB one time.  This
12522  * is rather rare, so it's a lot less expensive than making 8000
12523  * x-calls to flush the TLB 8000 times.
12524  *
12525  * A per-process (PP) lock is used to synchronize ctx allocations in
12526  * resume() and ctx invalidations here.
12527  */
12528 static void
12529 sfmmu_invalidate_ctx(sfmmu_t *sfmmup)
12530 {
12531 	cpuset_t cpuset;
12532 	int cnum, currcnum;
12533 	mmu_ctx_t *mmu_ctxp;
12534 	int i;
12535 	uint_t pstate_save;
12536 
12537 	SFMMU_STAT(sf_ctx_inv);
12538 
12539 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12540 	ASSERT(sfmmup != ksfmmup);
12541 
12542 	kpreempt_disable();
12543 
12544 	mmu_ctxp = CPU_MMU_CTXP(CPU);
12545 	ASSERT(mmu_ctxp);
12546 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
12547 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
12548 
12549 	currcnum = sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum;
12550 
12551 	pstate_save = sfmmu_disable_intrs();
12552 
12553 	lock_set(&sfmmup->sfmmu_ctx_lock);	/* acquire PP lock */
12554 	/* set HAT cnum invalid across all context domains. */
12555 	for (i = 0; i < max_mmu_ctxdoms; i++) {
12556 
12557 		cnum = 	sfmmup->sfmmu_ctxs[i].cnum;
12558 		if (cnum == INVALID_CONTEXT) {
12559 			continue;
12560 		}
12561 
12562 		sfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
12563 	}
12564 	membar_enter();	/* make sure globally visible to all CPUs */
12565 	lock_clear(&sfmmup->sfmmu_ctx_lock);	/* release PP lock */
12566 
12567 	sfmmu_enable_intrs(pstate_save);
12568 
12569 	cpuset = sfmmup->sfmmu_cpusran;
12570 	CPUSET_DEL(cpuset, CPU->cpu_id);
12571 	CPUSET_AND(cpuset, cpu_ready_set);
12572 	if (!CPUSET_ISNULL(cpuset)) {
12573 		SFMMU_XCALL_STATS(sfmmup);
12574 		xt_some(cpuset, sfmmu_raise_tsb_exception,
12575 		    (uint64_t)sfmmup, INVALID_CONTEXT);
12576 		xt_sync(cpuset);
12577 		SFMMU_STAT(sf_tsb_raise_exception);
12578 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
12579 	}
12580 
12581 	/*
12582 	 * If the hat to-be-invalidated is the same as the current
12583 	 * process on local CPU we need to invalidate
12584 	 * this CPU context as well.
12585 	 */
12586 	if ((sfmmu_getctx_sec() == currcnum) &&
12587 	    (currcnum != INVALID_CONTEXT)) {
12588 		/* sets shared context to INVALID too */
12589 		sfmmu_setctx_sec(INVALID_CONTEXT);
12590 		sfmmu_clear_utsbinfo();
12591 	}
12592 
12593 	SFMMU_FLAGS_SET(sfmmup, HAT_ALLCTX_INVALID);
12594 
12595 	kpreempt_enable();
12596 
12597 	/*
12598 	 * we hold the hat lock, so nobody should allocate a context
12599 	 * for us yet
12600 	 */
12601 	ASSERT(sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum == INVALID_CONTEXT);
12602 }
12603 
12604 #ifdef VAC
12605 /*
12606  * We need to flush the cache in all cpus.  It is possible that
12607  * a process referenced a page as cacheable but has sinced exited
12608  * and cleared the mapping list.  We still to flush it but have no
12609  * state so all cpus is the only alternative.
12610  */
12611 void
12612 sfmmu_cache_flush(pfn_t pfnum, int vcolor)
12613 {
12614 	cpuset_t cpuset;
12615 
12616 	kpreempt_disable();
12617 	cpuset = cpu_ready_set;
12618 	CPUSET_DEL(cpuset, CPU->cpu_id);
12619 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12620 	xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12621 	xt_sync(cpuset);
12622 	vac_flushpage(pfnum, vcolor);
12623 	kpreempt_enable();
12624 }
12625 
12626 void
12627 sfmmu_cache_flushcolor(int vcolor, pfn_t pfnum)
12628 {
12629 	cpuset_t cpuset;
12630 
12631 	ASSERT(vcolor >= 0);
12632 
12633 	kpreempt_disable();
12634 	cpuset = cpu_ready_set;
12635 	CPUSET_DEL(cpuset, CPU->cpu_id);
12636 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12637 	xt_some(cpuset, vac_flushcolor_tl1, vcolor, pfnum);
12638 	xt_sync(cpuset);
12639 	vac_flushcolor(vcolor, pfnum);
12640 	kpreempt_enable();
12641 }
12642 #endif	/* VAC */
12643 
12644 /*
12645  * We need to prevent processes from accessing the TSB using a cached physical
12646  * address.  It's alright if they try to access the TSB via virtual address
12647  * since they will just fault on that virtual address once the mapping has
12648  * been suspended.
12649  */
12650 #pragma weak sendmondo_in_recover
12651 
12652 /* ARGSUSED */
12653 static int
12654 sfmmu_tsb_pre_relocator(caddr_t va, uint_t tsbsz, uint_t flags, void *tsbinfo)
12655 {
12656 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12657 	sfmmu_t *sfmmup = tsbinfop->tsb_sfmmu;
12658 	hatlock_t *hatlockp;
12659 	sf_scd_t *scdp;
12660 
12661 	if (flags != HAT_PRESUSPEND)
12662 		return (0);
12663 
12664 	/*
12665 	 * If tsb is a shared TSB with TSB_SHAREDCTX set, sfmmup must
12666 	 * be a shared hat, then set SCD's tsbinfo's flag.
12667 	 * If tsb is not shared, sfmmup is a private hat, then set
12668 	 * its private tsbinfo's flag.
12669 	 */
12670 	hatlockp = sfmmu_hat_enter(sfmmup);
12671 	tsbinfop->tsb_flags |= TSB_RELOC_FLAG;
12672 
12673 	if (!(tsbinfop->tsb_flags & TSB_SHAREDCTX)) {
12674 		sfmmu_tsb_inv_ctx(sfmmup);
12675 		sfmmu_hat_exit(hatlockp);
12676 	} else {
12677 		/* release lock on the shared hat */
12678 		sfmmu_hat_exit(hatlockp);
12679 		/* sfmmup is a shared hat */
12680 		ASSERT(sfmmup->sfmmu_scdhat);
12681 		scdp = sfmmup->sfmmu_scdp;
12682 		ASSERT(scdp != NULL);
12683 		/* get private hat from the scd list */
12684 		mutex_enter(&scdp->scd_mutex);
12685 		sfmmup = scdp->scd_sf_list;
12686 		while (sfmmup != NULL) {
12687 			hatlockp = sfmmu_hat_enter(sfmmup);
12688 			/*
12689 			 * We do not call sfmmu_tsb_inv_ctx here because
12690 			 * sendmondo_in_recover check is only needed for
12691 			 * sun4u.
12692 			 */
12693 			sfmmu_invalidate_ctx(sfmmup);
12694 			sfmmu_hat_exit(hatlockp);
12695 			sfmmup = sfmmup->sfmmu_scd_link.next;
12696 
12697 		}
12698 		mutex_exit(&scdp->scd_mutex);
12699 	}
12700 	return (0);
12701 }
12702 
12703 static void
12704 sfmmu_tsb_inv_ctx(sfmmu_t *sfmmup)
12705 {
12706 	extern uint32_t sendmondo_in_recover;
12707 
12708 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12709 
12710 	/*
12711 	 * For Cheetah+ Erratum 25:
12712 	 * Wait for any active recovery to finish.  We can't risk
12713 	 * relocating the TSB of the thread running mondo_recover_proc()
12714 	 * since, if we did that, we would deadlock.  The scenario we are
12715 	 * trying to avoid is as follows:
12716 	 *
12717 	 * THIS CPU			RECOVER CPU
12718 	 * --------			-----------
12719 	 *				Begins recovery, walking through TSB
12720 	 * hat_pagesuspend() TSB TTE
12721 	 *				TLB miss on TSB TTE, spins at TL1
12722 	 * xt_sync()
12723 	 *	send_mondo_timeout()
12724 	 *	mondo_recover_proc()
12725 	 *	((deadlocked))
12726 	 *
12727 	 * The second half of the workaround is that mondo_recover_proc()
12728 	 * checks to see if the tsb_info has the RELOC flag set, and if it
12729 	 * does, it skips over that TSB without ever touching tsbinfop->tsb_va
12730 	 * and hence avoiding the TLB miss that could result in a deadlock.
12731 	 */
12732 	if (&sendmondo_in_recover) {
12733 		membar_enter();	/* make sure RELOC flag visible */
12734 		while (sendmondo_in_recover) {
12735 			drv_usecwait(1);
12736 			membar_consumer();
12737 		}
12738 	}
12739 
12740 	sfmmu_invalidate_ctx(sfmmup);
12741 }
12742 
12743 /* ARGSUSED */
12744 static int
12745 sfmmu_tsb_post_relocator(caddr_t va, uint_t tsbsz, uint_t flags,
12746 	void *tsbinfo, pfn_t newpfn)
12747 {
12748 	hatlock_t *hatlockp;
12749 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12750 	sfmmu_t	*sfmmup = tsbinfop->tsb_sfmmu;
12751 
12752 	if (flags != HAT_POSTUNSUSPEND)
12753 		return (0);
12754 
12755 	hatlockp = sfmmu_hat_enter(sfmmup);
12756 
12757 	SFMMU_STAT(sf_tsb_reloc);
12758 
12759 	/*
12760 	 * The process may have swapped out while we were relocating one
12761 	 * of its TSBs.  If so, don't bother doing the setup since the
12762 	 * process can't be using the memory anymore.
12763 	 */
12764 	if ((tsbinfop->tsb_flags & TSB_SWAPPED) == 0) {
12765 		ASSERT(va == tsbinfop->tsb_va);
12766 		sfmmu_tsbinfo_setup_phys(tsbinfop, newpfn);
12767 
12768 		if (tsbinfop->tsb_flags & TSB_FLUSH_NEEDED) {
12769 			sfmmu_inv_tsb(tsbinfop->tsb_va,
12770 			    TSB_BYTES(tsbinfop->tsb_szc));
12771 			tsbinfop->tsb_flags &= ~TSB_FLUSH_NEEDED;
12772 		}
12773 	}
12774 
12775 	membar_exit();
12776 	tsbinfop->tsb_flags &= ~TSB_RELOC_FLAG;
12777 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
12778 
12779 	sfmmu_hat_exit(hatlockp);
12780 
12781 	return (0);
12782 }
12783 
12784 /*
12785  * Allocate and initialize a tsb_info structure.  Note that we may or may not
12786  * allocate a TSB here, depending on the flags passed in.
12787  */
12788 static int
12789 sfmmu_tsbinfo_alloc(struct tsb_info **tsbinfopp, int tsb_szc, int tte_sz_mask,
12790 	uint_t flags, sfmmu_t *sfmmup)
12791 {
12792 	int err;
12793 
12794 	*tsbinfopp = (struct tsb_info *)kmem_cache_alloc(
12795 	    sfmmu_tsbinfo_cache, KM_SLEEP);
12796 
12797 	if ((err = sfmmu_init_tsbinfo(*tsbinfopp, tte_sz_mask,
12798 	    tsb_szc, flags, sfmmup)) != 0) {
12799 		kmem_cache_free(sfmmu_tsbinfo_cache, *tsbinfopp);
12800 		SFMMU_STAT(sf_tsb_allocfail);
12801 		*tsbinfopp = NULL;
12802 		return (err);
12803 	}
12804 	SFMMU_STAT(sf_tsb_alloc);
12805 
12806 	/*
12807 	 * Bump the TSB size counters for this TSB size.
12808 	 */
12809 	(*(((int *)&sfmmu_tsbsize_stat) + tsb_szc))++;
12810 	return (0);
12811 }
12812 
12813 static void
12814 sfmmu_tsb_free(struct tsb_info *tsbinfo)
12815 {
12816 	caddr_t tsbva = tsbinfo->tsb_va;
12817 	uint_t tsb_size = TSB_BYTES(tsbinfo->tsb_szc);
12818 	struct kmem_cache *kmem_cachep = tsbinfo->tsb_cache;
12819 	vmem_t	*vmp = tsbinfo->tsb_vmp;
12820 
12821 	/*
12822 	 * If we allocated this TSB from relocatable kernel memory, then we
12823 	 * need to uninstall the callback handler.
12824 	 */
12825 	if (tsbinfo->tsb_cache != sfmmu_tsb8k_cache) {
12826 		uintptr_t slab_mask;
12827 		caddr_t slab_vaddr;
12828 		page_t **ppl;
12829 		int ret;
12830 
12831 		ASSERT(tsb_size <= MMU_PAGESIZE4M || use_bigtsb_arena);
12832 		if (tsb_size > MMU_PAGESIZE4M)
12833 			slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12834 		else
12835 			slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12836 		slab_vaddr = (caddr_t)((uintptr_t)tsbva & slab_mask);
12837 
12838 		ret = as_pagelock(&kas, &ppl, slab_vaddr, PAGESIZE, S_WRITE);
12839 		ASSERT(ret == 0);
12840 		hat_delete_callback(tsbva, (uint_t)tsb_size, (void *)tsbinfo,
12841 		    0, NULL);
12842 		as_pageunlock(&kas, ppl, slab_vaddr, PAGESIZE, S_WRITE);
12843 	}
12844 
12845 	if (kmem_cachep != NULL) {
12846 		kmem_cache_free(kmem_cachep, tsbva);
12847 	} else {
12848 		vmem_xfree(vmp, (void *)tsbva, tsb_size);
12849 	}
12850 	tsbinfo->tsb_va = (caddr_t)0xbad00bad;
12851 	atomic_add_64(&tsb_alloc_bytes, -(int64_t)tsb_size);
12852 }
12853 
12854 static void
12855 sfmmu_tsbinfo_free(struct tsb_info *tsbinfo)
12856 {
12857 	if ((tsbinfo->tsb_flags & TSB_SWAPPED) == 0) {
12858 		sfmmu_tsb_free(tsbinfo);
12859 	}
12860 	kmem_cache_free(sfmmu_tsbinfo_cache, tsbinfo);
12861 
12862 }
12863 
12864 /*
12865  * Setup all the references to physical memory for this tsbinfo.
12866  * The underlying page(s) must be locked.
12867  */
12868 static void
12869 sfmmu_tsbinfo_setup_phys(struct tsb_info *tsbinfo, pfn_t pfn)
12870 {
12871 	ASSERT(pfn != PFN_INVALID);
12872 	ASSERT(pfn == va_to_pfn(tsbinfo->tsb_va));
12873 
12874 #ifndef sun4v
12875 	if (tsbinfo->tsb_szc == 0) {
12876 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn,
12877 		    PROT_WRITE|PROT_READ, TTE8K);
12878 	} else {
12879 		/*
12880 		 * Round down PA and use a large mapping; the handlers will
12881 		 * compute the TSB pointer at the correct offset into the
12882 		 * big virtual page.  NOTE: this assumes all TSBs larger
12883 		 * than 8K must come from physically contiguous slabs of
12884 		 * size tsb_slab_size.
12885 		 */
12886 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn & ~tsb_slab_mask,
12887 		    PROT_WRITE|PROT_READ, tsb_slab_ttesz);
12888 	}
12889 	tsbinfo->tsb_pa = ptob(pfn);
12890 
12891 	TTE_SET_LOCKED(&tsbinfo->tsb_tte); /* lock the tte into dtlb */
12892 	TTE_SET_MOD(&tsbinfo->tsb_tte);    /* enable writes */
12893 
12894 	ASSERT(TTE_IS_PRIVILEGED(&tsbinfo->tsb_tte));
12895 	ASSERT(TTE_IS_LOCKED(&tsbinfo->tsb_tte));
12896 #else /* sun4v */
12897 	tsbinfo->tsb_pa = ptob(pfn);
12898 #endif /* sun4v */
12899 }
12900 
12901 
12902 /*
12903  * Returns zero on success, ENOMEM if over the high water mark,
12904  * or EAGAIN if the caller needs to retry with a smaller TSB
12905  * size (or specify TSB_FORCEALLOC if the allocation can't fail).
12906  *
12907  * This call cannot fail to allocate a TSB if TSB_FORCEALLOC
12908  * is specified and the TSB requested is PAGESIZE, though it
12909  * may sleep waiting for memory if sufficient memory is not
12910  * available.
12911  */
12912 static int
12913 sfmmu_init_tsbinfo(struct tsb_info *tsbinfo, int tteszmask,
12914     int tsbcode, uint_t flags, sfmmu_t *sfmmup)
12915 {
12916 	caddr_t vaddr = NULL;
12917 	caddr_t slab_vaddr;
12918 	uintptr_t slab_mask;
12919 	int tsbbytes = TSB_BYTES(tsbcode);
12920 	int lowmem = 0;
12921 	struct kmem_cache *kmem_cachep = NULL;
12922 	vmem_t *vmp = NULL;
12923 	lgrp_id_t lgrpid = LGRP_NONE;
12924 	pfn_t pfn;
12925 	uint_t cbflags = HAC_SLEEP;
12926 	page_t **pplist;
12927 	int ret;
12928 
12929 	ASSERT(tsbbytes <= MMU_PAGESIZE4M || use_bigtsb_arena);
12930 	if (tsbbytes > MMU_PAGESIZE4M)
12931 		slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12932 	else
12933 		slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12934 
12935 	if (flags & (TSB_FORCEALLOC | TSB_SWAPIN | TSB_GROW | TSB_SHRINK))
12936 		flags |= TSB_ALLOC;
12937 
12938 	ASSERT((flags & TSB_FORCEALLOC) == 0 || tsbcode == TSB_MIN_SZCODE);
12939 
12940 	tsbinfo->tsb_sfmmu = sfmmup;
12941 
12942 	/*
12943 	 * If not allocating a TSB, set up the tsbinfo, set TSB_SWAPPED, and
12944 	 * return.
12945 	 */
12946 	if ((flags & TSB_ALLOC) == 0) {
12947 		tsbinfo->tsb_szc = tsbcode;
12948 		tsbinfo->tsb_ttesz_mask = tteszmask;
12949 		tsbinfo->tsb_va = (caddr_t)0xbadbadbeef;
12950 		tsbinfo->tsb_pa = -1;
12951 		tsbinfo->tsb_tte.ll = 0;
12952 		tsbinfo->tsb_next = NULL;
12953 		tsbinfo->tsb_flags = TSB_SWAPPED;
12954 		tsbinfo->tsb_cache = NULL;
12955 		tsbinfo->tsb_vmp = NULL;
12956 		return (0);
12957 	}
12958 
12959 #ifdef DEBUG
12960 	/*
12961 	 * For debugging:
12962 	 * Randomly force allocation failures every tsb_alloc_mtbf
12963 	 * tries if TSB_FORCEALLOC is not specified.  This will
12964 	 * return ENOMEM if tsb_alloc_mtbf is odd, or EAGAIN if
12965 	 * it is even, to allow testing of both failure paths...
12966 	 */
12967 	if (tsb_alloc_mtbf && ((flags & TSB_FORCEALLOC) == 0) &&
12968 	    (tsb_alloc_count++ == tsb_alloc_mtbf)) {
12969 		tsb_alloc_count = 0;
12970 		tsb_alloc_fail_mtbf++;
12971 		return ((tsb_alloc_mtbf & 1)? ENOMEM : EAGAIN);
12972 	}
12973 #endif	/* DEBUG */
12974 
12975 	/*
12976 	 * Enforce high water mark if we are not doing a forced allocation
12977 	 * and are not shrinking a process' TSB.
12978 	 */
12979 	if ((flags & TSB_SHRINK) == 0 &&
12980 	    (tsbbytes + tsb_alloc_bytes) > tsb_alloc_hiwater) {
12981 		if ((flags & TSB_FORCEALLOC) == 0)
12982 			return (ENOMEM);
12983 		lowmem = 1;
12984 	}
12985 
12986 	/*
12987 	 * Allocate from the correct location based upon the size of the TSB
12988 	 * compared to the base page size, and what memory conditions dictate.
12989 	 * Note we always do nonblocking allocations from the TSB arena since
12990 	 * we don't want memory fragmentation to cause processes to block
12991 	 * indefinitely waiting for memory; until the kernel algorithms that
12992 	 * coalesce large pages are improved this is our best option.
12993 	 *
12994 	 * Algorithm:
12995 	 *	If allocating a "large" TSB (>8K), allocate from the
12996 	 *		appropriate kmem_tsb_default_arena vmem arena
12997 	 *	else if low on memory or the TSB_FORCEALLOC flag is set or
12998 	 *	tsb_forceheap is set
12999 	 *		Allocate from kernel heap via sfmmu_tsb8k_cache with
13000 	 *		KM_SLEEP (never fails)
13001 	 *	else
13002 	 *		Allocate from appropriate sfmmu_tsb_cache with
13003 	 *		KM_NOSLEEP
13004 	 *	endif
13005 	 */
13006 	if (tsb_lgrp_affinity)
13007 		lgrpid = lgrp_home_id(curthread);
13008 	if (lgrpid == LGRP_NONE)
13009 		lgrpid = 0;	/* use lgrp of boot CPU */
13010 
13011 	if (tsbbytes > MMU_PAGESIZE) {
13012 		if (tsbbytes > MMU_PAGESIZE4M) {
13013 			vmp = kmem_bigtsb_default_arena[lgrpid];
13014 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
13015 			    0, 0, NULL, NULL, VM_NOSLEEP);
13016 		} else {
13017 			vmp = kmem_tsb_default_arena[lgrpid];
13018 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
13019 			    0, 0, NULL, NULL, VM_NOSLEEP);
13020 		}
13021 #ifdef	DEBUG
13022 	} else if (lowmem || (flags & TSB_FORCEALLOC) || tsb_forceheap) {
13023 #else	/* !DEBUG */
13024 	} else if (lowmem || (flags & TSB_FORCEALLOC)) {
13025 #endif	/* DEBUG */
13026 		kmem_cachep = sfmmu_tsb8k_cache;
13027 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_SLEEP);
13028 		ASSERT(vaddr != NULL);
13029 	} else {
13030 		kmem_cachep = sfmmu_tsb_cache[lgrpid];
13031 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_NOSLEEP);
13032 	}
13033 
13034 	tsbinfo->tsb_cache = kmem_cachep;
13035 	tsbinfo->tsb_vmp = vmp;
13036 
13037 	if (vaddr == NULL) {
13038 		return (EAGAIN);
13039 	}
13040 
13041 	atomic_add_64(&tsb_alloc_bytes, (int64_t)tsbbytes);
13042 	kmem_cachep = tsbinfo->tsb_cache;
13043 
13044 	/*
13045 	 * If we are allocating from outside the cage, then we need to
13046 	 * register a relocation callback handler.  Note that for now
13047 	 * since pseudo mappings always hang off of the slab's root page,
13048 	 * we need only lock the first 8K of the TSB slab.  This is a bit
13049 	 * hacky but it is good for performance.
13050 	 */
13051 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13052 		slab_vaddr = (caddr_t)((uintptr_t)vaddr & slab_mask);
13053 		ret = as_pagelock(&kas, &pplist, slab_vaddr, PAGESIZE, S_WRITE);
13054 		ASSERT(ret == 0);
13055 		ret = hat_add_callback(sfmmu_tsb_cb_id, vaddr, (uint_t)tsbbytes,
13056 		    cbflags, (void *)tsbinfo, &pfn, NULL);
13057 
13058 		/*
13059 		 * Need to free up resources if we could not successfully
13060 		 * add the callback function and return an error condition.
13061 		 */
13062 		if (ret != 0) {
13063 			if (kmem_cachep) {
13064 				kmem_cache_free(kmem_cachep, vaddr);
13065 			} else {
13066 				vmem_xfree(vmp, (void *)vaddr, tsbbytes);
13067 			}
13068 			as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE,
13069 			    S_WRITE);
13070 			return (EAGAIN);
13071 		}
13072 	} else {
13073 		/*
13074 		 * Since allocation of 8K TSBs from heap is rare and occurs
13075 		 * during memory pressure we allocate them from permanent
13076 		 * memory rather than using callbacks to get the PFN.
13077 		 */
13078 		pfn = hat_getpfnum(kas.a_hat, vaddr);
13079 	}
13080 
13081 	tsbinfo->tsb_va = vaddr;
13082 	tsbinfo->tsb_szc = tsbcode;
13083 	tsbinfo->tsb_ttesz_mask = tteszmask;
13084 	tsbinfo->tsb_next = NULL;
13085 	tsbinfo->tsb_flags = 0;
13086 
13087 	sfmmu_tsbinfo_setup_phys(tsbinfo, pfn);
13088 
13089 	sfmmu_inv_tsb(vaddr, tsbbytes);
13090 
13091 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13092 		as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE, S_WRITE);
13093 	}
13094 
13095 	return (0);
13096 }
13097 
13098 /*
13099  * Initialize per cpu tsb and per cpu tsbmiss_area
13100  */
13101 void
13102 sfmmu_init_tsbs(void)
13103 {
13104 	int i;
13105 	struct tsbmiss	*tsbmissp;
13106 	struct kpmtsbm	*kpmtsbmp;
13107 #ifndef sun4v
13108 	extern int	dcache_line_mask;
13109 #endif /* sun4v */
13110 	extern uint_t	vac_colors;
13111 
13112 	/*
13113 	 * Init. tsb miss area.
13114 	 */
13115 	tsbmissp = tsbmiss_area;
13116 
13117 	for (i = 0; i < NCPU; tsbmissp++, i++) {
13118 		/*
13119 		 * initialize the tsbmiss area.
13120 		 * Do this for all possible CPUs as some may be added
13121 		 * while the system is running. There is no cost to this.
13122 		 */
13123 		tsbmissp->ksfmmup = ksfmmup;
13124 #ifndef sun4v
13125 		tsbmissp->dcache_line_mask = (uint16_t)dcache_line_mask;
13126 #endif /* sun4v */
13127 		tsbmissp->khashstart =
13128 		    (struct hmehash_bucket *)va_to_pa((caddr_t)khme_hash);
13129 		tsbmissp->uhashstart =
13130 		    (struct hmehash_bucket *)va_to_pa((caddr_t)uhme_hash);
13131 		tsbmissp->khashsz = khmehash_num;
13132 		tsbmissp->uhashsz = uhmehash_num;
13133 	}
13134 
13135 	sfmmu_tsb_cb_id = hat_register_callback('T'<<16 | 'S' << 8 | 'B',
13136 	    sfmmu_tsb_pre_relocator, sfmmu_tsb_post_relocator, NULL, 0);
13137 
13138 	if (kpm_enable == 0)
13139 		return;
13140 
13141 	/* -- Begin KPM specific init -- */
13142 
13143 	if (kpm_smallpages) {
13144 		/*
13145 		 * If we're using base pagesize pages for seg_kpm
13146 		 * mappings, we use the kernel TSB since we can't afford
13147 		 * to allocate a second huge TSB for these mappings.
13148 		 */
13149 		kpm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13150 		kpm_tsbsz = ktsb_szcode;
13151 		kpmsm_tsbbase = kpm_tsbbase;
13152 		kpmsm_tsbsz = kpm_tsbsz;
13153 	} else {
13154 		/*
13155 		 * In VAC conflict case, just put the entries in the
13156 		 * kernel 8K indexed TSB for now so we can find them.
13157 		 * This could really be changed in the future if we feel
13158 		 * the need...
13159 		 */
13160 		kpmsm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13161 		kpmsm_tsbsz = ktsb_szcode;
13162 		kpm_tsbbase = ktsb_phys? ktsb4m_pbase : (uint64_t)ktsb4m_base;
13163 		kpm_tsbsz = ktsb4m_szcode;
13164 	}
13165 
13166 	kpmtsbmp = kpmtsbm_area;
13167 	for (i = 0; i < NCPU; kpmtsbmp++, i++) {
13168 		/*
13169 		 * Initialize the kpmtsbm area.
13170 		 * Do this for all possible CPUs as some may be added
13171 		 * while the system is running. There is no cost to this.
13172 		 */
13173 		kpmtsbmp->vbase = kpm_vbase;
13174 		kpmtsbmp->vend = kpm_vbase + kpm_size * vac_colors;
13175 		kpmtsbmp->sz_shift = kpm_size_shift;
13176 		kpmtsbmp->kpmp_shift = kpmp_shift;
13177 		kpmtsbmp->kpmp2pshft = (uchar_t)kpmp2pshft;
13178 		if (kpm_smallpages == 0) {
13179 			kpmtsbmp->kpmp_table_sz = kpmp_table_sz;
13180 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_table);
13181 		} else {
13182 			kpmtsbmp->kpmp_table_sz = kpmp_stable_sz;
13183 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_stable);
13184 		}
13185 		kpmtsbmp->msegphashpa = va_to_pa(memseg_phash);
13186 		kpmtsbmp->flags = KPMTSBM_ENABLE_FLAG;
13187 #ifdef	DEBUG
13188 		kpmtsbmp->flags |= (kpm_tsbmtl) ?  KPMTSBM_TLTSBM_FLAG : 0;
13189 #endif	/* DEBUG */
13190 		if (ktsb_phys)
13191 			kpmtsbmp->flags |= KPMTSBM_TSBPHYS_FLAG;
13192 	}
13193 
13194 	/* -- End KPM specific init -- */
13195 }
13196 
13197 /* Avoid using sfmmu_tsbinfo_alloc() to avoid kmem_alloc - no real reason */
13198 struct tsb_info ktsb_info[2];
13199 
13200 /*
13201  * Called from hat_kern_setup() to setup the tsb_info for ksfmmup.
13202  */
13203 void
13204 sfmmu_init_ktsbinfo()
13205 {
13206 	ASSERT(ksfmmup != NULL);
13207 	ASSERT(ksfmmup->sfmmu_tsb == NULL);
13208 	/*
13209 	 * Allocate tsbinfos for kernel and copy in data
13210 	 * to make debug easier and sun4v setup easier.
13211 	 */
13212 	ktsb_info[0].tsb_sfmmu = ksfmmup;
13213 	ktsb_info[0].tsb_szc = ktsb_szcode;
13214 	ktsb_info[0].tsb_ttesz_mask = TSB8K|TSB64K|TSB512K;
13215 	ktsb_info[0].tsb_va = ktsb_base;
13216 	ktsb_info[0].tsb_pa = ktsb_pbase;
13217 	ktsb_info[0].tsb_flags = 0;
13218 	ktsb_info[0].tsb_tte.ll = 0;
13219 	ktsb_info[0].tsb_cache = NULL;
13220 
13221 	ktsb_info[1].tsb_sfmmu = ksfmmup;
13222 	ktsb_info[1].tsb_szc = ktsb4m_szcode;
13223 	ktsb_info[1].tsb_ttesz_mask = TSB4M;
13224 	ktsb_info[1].tsb_va = ktsb4m_base;
13225 	ktsb_info[1].tsb_pa = ktsb4m_pbase;
13226 	ktsb_info[1].tsb_flags = 0;
13227 	ktsb_info[1].tsb_tte.ll = 0;
13228 	ktsb_info[1].tsb_cache = NULL;
13229 
13230 	/* Link them into ksfmmup. */
13231 	ktsb_info[0].tsb_next = &ktsb_info[1];
13232 	ktsb_info[1].tsb_next = NULL;
13233 	ksfmmup->sfmmu_tsb = &ktsb_info[0];
13234 
13235 	sfmmu_setup_tsbinfo(ksfmmup);
13236 }
13237 
13238 /*
13239  * Cache the last value returned from va_to_pa().  If the VA specified
13240  * in the current call to cached_va_to_pa() maps to the same Page (as the
13241  * previous call to cached_va_to_pa()), then compute the PA using
13242  * cached info, else call va_to_pa().
13243  *
13244  * Note: this function is neither MT-safe nor consistent in the presence
13245  * of multiple, interleaved threads.  This function was created to enable
13246  * an optimization used during boot (at a point when there's only one thread
13247  * executing on the "boot CPU", and before startup_vm() has been called).
13248  */
13249 static uint64_t
13250 cached_va_to_pa(void *vaddr)
13251 {
13252 	static uint64_t prev_vaddr_base = 0;
13253 	static uint64_t prev_pfn = 0;
13254 
13255 	if ((((uint64_t)vaddr) & MMU_PAGEMASK) == prev_vaddr_base) {
13256 		return (prev_pfn | ((uint64_t)vaddr & MMU_PAGEOFFSET));
13257 	} else {
13258 		uint64_t pa = va_to_pa(vaddr);
13259 
13260 		if (pa != ((uint64_t)-1)) {
13261 			/*
13262 			 * Computed physical address is valid.  Cache its
13263 			 * related info for the next cached_va_to_pa() call.
13264 			 */
13265 			prev_pfn = pa & MMU_PAGEMASK;
13266 			prev_vaddr_base = ((uint64_t)vaddr) & MMU_PAGEMASK;
13267 		}
13268 
13269 		return (pa);
13270 	}
13271 }
13272 
13273 /*
13274  * Carve up our nucleus hblk region.  We may allocate more hblks than
13275  * asked due to rounding errors but we are guaranteed to have at least
13276  * enough space to allocate the requested number of hblk8's and hblk1's.
13277  */
13278 void
13279 sfmmu_init_nucleus_hblks(caddr_t addr, size_t size, int nhblk8, int nhblk1)
13280 {
13281 	struct hme_blk *hmeblkp;
13282 	size_t hme8blk_sz, hme1blk_sz;
13283 	size_t i;
13284 	size_t hblk8_bound;
13285 	ulong_t j = 0, k = 0;
13286 
13287 	ASSERT(addr != NULL && size != 0);
13288 
13289 	/* Need to use proper structure alignment */
13290 	hme8blk_sz = roundup(HME8BLK_SZ, sizeof (int64_t));
13291 	hme1blk_sz = roundup(HME1BLK_SZ, sizeof (int64_t));
13292 
13293 	nucleus_hblk8.list = (void *)addr;
13294 	nucleus_hblk8.index = 0;
13295 
13296 	/*
13297 	 * Use as much memory as possible for hblk8's since we
13298 	 * expect all bop_alloc'ed memory to be allocated in 8k chunks.
13299 	 * We need to hold back enough space for the hblk1's which
13300 	 * we'll allocate next.
13301 	 */
13302 	hblk8_bound = size - (nhblk1 * hme1blk_sz) - hme8blk_sz;
13303 	for (i = 0; i <= hblk8_bound; i += hme8blk_sz, j++) {
13304 		hmeblkp = (struct hme_blk *)addr;
13305 		addr += hme8blk_sz;
13306 		hmeblkp->hblk_nuc_bit = 1;
13307 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13308 	}
13309 	nucleus_hblk8.len = j;
13310 	ASSERT(j >= nhblk8);
13311 	SFMMU_STAT_ADD(sf_hblk8_ncreate, j);
13312 
13313 	nucleus_hblk1.list = (void *)addr;
13314 	nucleus_hblk1.index = 0;
13315 	for (; i <= (size - hme1blk_sz); i += hme1blk_sz, k++) {
13316 		hmeblkp = (struct hme_blk *)addr;
13317 		addr += hme1blk_sz;
13318 		hmeblkp->hblk_nuc_bit = 1;
13319 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13320 	}
13321 	ASSERT(k >= nhblk1);
13322 	nucleus_hblk1.len = k;
13323 	SFMMU_STAT_ADD(sf_hblk1_ncreate, k);
13324 }
13325 
13326 /*
13327  * This function is currently not supported on this platform. For what
13328  * it's supposed to do, see hat.c and hat_srmmu.c
13329  */
13330 /* ARGSUSED */
13331 faultcode_t
13332 hat_softlock(struct hat *hat, caddr_t addr, size_t *lenp, page_t **ppp,
13333     uint_t flags)
13334 {
13335 	ASSERT(hat->sfmmu_xhat_provider == NULL);
13336 	return (FC_NOSUPPORT);
13337 }
13338 
13339 /*
13340  * Searchs the mapping list of the page for a mapping of the same size. If not
13341  * found the corresponding bit is cleared in the p_index field. When large
13342  * pages are more prevalent in the system, we can maintain the mapping list
13343  * in order and we don't have to traverse the list each time. Just check the
13344  * next and prev entries, and if both are of different size, we clear the bit.
13345  */
13346 static void
13347 sfmmu_rm_large_mappings(page_t *pp, int ttesz)
13348 {
13349 	struct sf_hment *sfhmep;
13350 	struct hme_blk *hmeblkp;
13351 	int	index;
13352 	pgcnt_t	npgs;
13353 
13354 	ASSERT(ttesz > TTE8K);
13355 
13356 	ASSERT(sfmmu_mlist_held(pp));
13357 
13358 	ASSERT(PP_ISMAPPED_LARGE(pp));
13359 
13360 	/*
13361 	 * Traverse mapping list looking for another mapping of same size.
13362 	 * since we only want to clear index field if all mappings of
13363 	 * that size are gone.
13364 	 */
13365 
13366 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
13367 		if (IS_PAHME(sfhmep))
13368 			continue;
13369 		hmeblkp = sfmmu_hmetohblk(sfhmep);
13370 		if (hmeblkp->hblk_xhat_bit)
13371 			continue;
13372 		if (hme_size(sfhmep) == ttesz) {
13373 			/*
13374 			 * another mapping of the same size. don't clear index.
13375 			 */
13376 			return;
13377 		}
13378 	}
13379 
13380 	/*
13381 	 * Clear the p_index bit for large page.
13382 	 */
13383 	index = PAGESZ_TO_INDEX(ttesz);
13384 	npgs = TTEPAGES(ttesz);
13385 	while (npgs-- > 0) {
13386 		ASSERT(pp->p_index & index);
13387 		pp->p_index &= ~index;
13388 		pp = PP_PAGENEXT(pp);
13389 	}
13390 }
13391 
13392 /*
13393  * return supported features
13394  */
13395 /* ARGSUSED */
13396 int
13397 hat_supported(enum hat_features feature, void *arg)
13398 {
13399 	switch (feature) {
13400 	case    HAT_SHARED_PT:
13401 	case	HAT_DYNAMIC_ISM_UNMAP:
13402 	case	HAT_VMODSORT:
13403 		return (1);
13404 	case	HAT_SHARED_REGIONS:
13405 		if (shctx_on)
13406 			return (1);
13407 		else
13408 			return (0);
13409 	default:
13410 		return (0);
13411 	}
13412 }
13413 
13414 void
13415 hat_enter(struct hat *hat)
13416 {
13417 	hatlock_t	*hatlockp;
13418 
13419 	if (hat != ksfmmup) {
13420 		hatlockp = TSB_HASH(hat);
13421 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
13422 	}
13423 }
13424 
13425 void
13426 hat_exit(struct hat *hat)
13427 {
13428 	hatlock_t	*hatlockp;
13429 
13430 	if (hat != ksfmmup) {
13431 		hatlockp = TSB_HASH(hat);
13432 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
13433 	}
13434 }
13435 
13436 /*ARGSUSED*/
13437 void
13438 hat_reserve(struct as *as, caddr_t addr, size_t len)
13439 {
13440 }
13441 
13442 static void
13443 hat_kstat_init(void)
13444 {
13445 	kstat_t *ksp;
13446 
13447 	ksp = kstat_create("unix", 0, "sfmmu_global_stat", "hat",
13448 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_global_stat),
13449 	    KSTAT_FLAG_VIRTUAL);
13450 	if (ksp) {
13451 		ksp->ks_data = (void *) &sfmmu_global_stat;
13452 		kstat_install(ksp);
13453 	}
13454 	ksp = kstat_create("unix", 0, "sfmmu_tsbsize_stat", "hat",
13455 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_tsbsize_stat),
13456 	    KSTAT_FLAG_VIRTUAL);
13457 	if (ksp) {
13458 		ksp->ks_data = (void *) &sfmmu_tsbsize_stat;
13459 		kstat_install(ksp);
13460 	}
13461 	ksp = kstat_create("unix", 0, "sfmmu_percpu_stat", "hat",
13462 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_percpu_stat) * NCPU,
13463 	    KSTAT_FLAG_WRITABLE);
13464 	if (ksp) {
13465 		ksp->ks_update = sfmmu_kstat_percpu_update;
13466 		kstat_install(ksp);
13467 	}
13468 }
13469 
13470 /* ARGSUSED */
13471 static int
13472 sfmmu_kstat_percpu_update(kstat_t *ksp, int rw)
13473 {
13474 	struct sfmmu_percpu_stat *cpu_kstat = ksp->ks_data;
13475 	struct tsbmiss *tsbm = tsbmiss_area;
13476 	struct kpmtsbm *kpmtsbm = kpmtsbm_area;
13477 	int i;
13478 
13479 	ASSERT(cpu_kstat);
13480 	if (rw == KSTAT_READ) {
13481 		for (i = 0; i < NCPU; cpu_kstat++, tsbm++, kpmtsbm++, i++) {
13482 			cpu_kstat->sf_itlb_misses = 0;
13483 			cpu_kstat->sf_dtlb_misses = 0;
13484 			cpu_kstat->sf_utsb_misses = tsbm->utsb_misses -
13485 			    tsbm->uprot_traps;
13486 			cpu_kstat->sf_ktsb_misses = tsbm->ktsb_misses +
13487 			    kpmtsbm->kpm_tsb_misses - tsbm->kprot_traps;
13488 			cpu_kstat->sf_tsb_hits = 0;
13489 			cpu_kstat->sf_umod_faults = tsbm->uprot_traps;
13490 			cpu_kstat->sf_kmod_faults = tsbm->kprot_traps;
13491 		}
13492 	} else {
13493 		/* KSTAT_WRITE is used to clear stats */
13494 		for (i = 0; i < NCPU; tsbm++, kpmtsbm++, i++) {
13495 			tsbm->utsb_misses = 0;
13496 			tsbm->ktsb_misses = 0;
13497 			tsbm->uprot_traps = 0;
13498 			tsbm->kprot_traps = 0;
13499 			kpmtsbm->kpm_dtlb_misses = 0;
13500 			kpmtsbm->kpm_tsb_misses = 0;
13501 		}
13502 	}
13503 	return (0);
13504 }
13505 
13506 #ifdef	DEBUG
13507 
13508 tte_t  *gorig[NCPU], *gcur[NCPU], *gnew[NCPU];
13509 
13510 /*
13511  * A tte checker. *orig_old is the value we read before cas.
13512  *	*cur is the value returned by cas.
13513  *	*new is the desired value when we do the cas.
13514  *
13515  *	*hmeblkp is currently unused.
13516  */
13517 
13518 /* ARGSUSED */
13519 void
13520 chk_tte(tte_t *orig_old, tte_t *cur, tte_t *new, struct hme_blk *hmeblkp)
13521 {
13522 	pfn_t i, j, k;
13523 	int cpuid = CPU->cpu_id;
13524 
13525 	gorig[cpuid] = orig_old;
13526 	gcur[cpuid] = cur;
13527 	gnew[cpuid] = new;
13528 
13529 #ifdef lint
13530 	hmeblkp = hmeblkp;
13531 #endif
13532 
13533 	if (TTE_IS_VALID(orig_old)) {
13534 		if (TTE_IS_VALID(cur)) {
13535 			i = TTE_TO_TTEPFN(orig_old);
13536 			j = TTE_TO_TTEPFN(cur);
13537 			k = TTE_TO_TTEPFN(new);
13538 			if (i != j) {
13539 				/* remap error? */
13540 				panic("chk_tte: bad pfn, 0x%lx, 0x%lx", i, j);
13541 			}
13542 
13543 			if (i != k) {
13544 				/* remap error? */
13545 				panic("chk_tte: bad pfn2, 0x%lx, 0x%lx", i, k);
13546 			}
13547 		} else {
13548 			if (TTE_IS_VALID(new)) {
13549 				panic("chk_tte: invalid cur? ");
13550 			}
13551 
13552 			i = TTE_TO_TTEPFN(orig_old);
13553 			k = TTE_TO_TTEPFN(new);
13554 			if (i != k) {
13555 				panic("chk_tte: bad pfn3, 0x%lx, 0x%lx", i, k);
13556 			}
13557 		}
13558 	} else {
13559 		if (TTE_IS_VALID(cur)) {
13560 			j = TTE_TO_TTEPFN(cur);
13561 			if (TTE_IS_VALID(new)) {
13562 				k = TTE_TO_TTEPFN(new);
13563 				if (j != k) {
13564 					panic("chk_tte: bad pfn4, 0x%lx, 0x%lx",
13565 					    j, k);
13566 				}
13567 			} else {
13568 				panic("chk_tte: why here?");
13569 			}
13570 		} else {
13571 			if (!TTE_IS_VALID(new)) {
13572 				panic("chk_tte: why here2 ?");
13573 			}
13574 		}
13575 	}
13576 }
13577 
13578 #endif /* DEBUG */
13579 
13580 extern void prefetch_tsbe_read(struct tsbe *);
13581 extern void prefetch_tsbe_write(struct tsbe *);
13582 
13583 
13584 /*
13585  * We want to prefetch 7 cache lines ahead for our read prefetch.  This gives
13586  * us optimal performance on Cheetah+.  You can only have 8 outstanding
13587  * prefetches at any one time, so we opted for 7 read prefetches and 1 write
13588  * prefetch to make the most utilization of the prefetch capability.
13589  */
13590 #define	TSBE_PREFETCH_STRIDE (7)
13591 
13592 void
13593 sfmmu_copy_tsb(struct tsb_info *old_tsbinfo, struct tsb_info *new_tsbinfo)
13594 {
13595 	int old_bytes = TSB_BYTES(old_tsbinfo->tsb_szc);
13596 	int new_bytes = TSB_BYTES(new_tsbinfo->tsb_szc);
13597 	int old_entries = TSB_ENTRIES(old_tsbinfo->tsb_szc);
13598 	int new_entries = TSB_ENTRIES(new_tsbinfo->tsb_szc);
13599 	struct tsbe *old;
13600 	struct tsbe *new;
13601 	struct tsbe *new_base = (struct tsbe *)new_tsbinfo->tsb_va;
13602 	uint64_t va;
13603 	int new_offset;
13604 	int i;
13605 	int vpshift;
13606 	int last_prefetch;
13607 
13608 	if (old_bytes == new_bytes) {
13609 		bcopy(old_tsbinfo->tsb_va, new_tsbinfo->tsb_va, new_bytes);
13610 	} else {
13611 
13612 		/*
13613 		 * A TSBE is 16 bytes which means there are four TSBE's per
13614 		 * P$ line (64 bytes), thus every 4 TSBE's we prefetch.
13615 		 */
13616 		old = (struct tsbe *)old_tsbinfo->tsb_va;
13617 		last_prefetch = old_entries - (4*(TSBE_PREFETCH_STRIDE+1));
13618 		for (i = 0; i < old_entries; i++, old++) {
13619 			if (((i & (4-1)) == 0) && (i < last_prefetch))
13620 				prefetch_tsbe_read(old);
13621 			if (!old->tte_tag.tag_invalid) {
13622 				/*
13623 				 * We have a valid TTE to remap.  Check the
13624 				 * size.  We won't remap 64K or 512K TTEs
13625 				 * because they span more than one TSB entry
13626 				 * and are indexed using an 8K virt. page.
13627 				 * Ditto for 32M and 256M TTEs.
13628 				 */
13629 				if (TTE_CSZ(&old->tte_data) == TTE64K ||
13630 				    TTE_CSZ(&old->tte_data) == TTE512K)
13631 					continue;
13632 				if (mmu_page_sizes == max_mmu_page_sizes) {
13633 					if (TTE_CSZ(&old->tte_data) == TTE32M ||
13634 					    TTE_CSZ(&old->tte_data) == TTE256M)
13635 						continue;
13636 				}
13637 
13638 				/* clear the lower 22 bits of the va */
13639 				va = *(uint64_t *)old << 22;
13640 				/* turn va into a virtual pfn */
13641 				va >>= 22 - TSB_START_SIZE;
13642 				/*
13643 				 * or in bits from the offset in the tsb
13644 				 * to get the real virtual pfn. These
13645 				 * correspond to bits [21:13] in the va
13646 				 */
13647 				vpshift =
13648 				    TTE_BSZS_SHIFT(TTE_CSZ(&old->tte_data)) &
13649 				    0x1ff;
13650 				va |= (i << vpshift);
13651 				va >>= vpshift;
13652 				new_offset = va & (new_entries - 1);
13653 				new = new_base + new_offset;
13654 				prefetch_tsbe_write(new);
13655 				*new = *old;
13656 			}
13657 		}
13658 	}
13659 }
13660 
13661 /*
13662  * unused in sfmmu
13663  */
13664 void
13665 hat_dump(void)
13666 {
13667 }
13668 
13669 /*
13670  * Called when a thread is exiting and we have switched to the kernel address
13671  * space.  Perform the same VM initialization resume() uses when switching
13672  * processes.
13673  *
13674  * Note that sfmmu_load_mmustate() is currently a no-op for kernel threads, but
13675  * we call it anyway in case the semantics change in the future.
13676  */
13677 /*ARGSUSED*/
13678 void
13679 hat_thread_exit(kthread_t *thd)
13680 {
13681 	uint_t pgsz_cnum;
13682 	uint_t pstate_save;
13683 
13684 	ASSERT(thd->t_procp->p_as == &kas);
13685 
13686 	pgsz_cnum = KCONTEXT;
13687 #ifdef sun4u
13688 	pgsz_cnum |= (ksfmmup->sfmmu_cext << CTXREG_EXT_SHIFT);
13689 #endif
13690 
13691 	/*
13692 	 * Note that sfmmu_load_mmustate() is currently a no-op for
13693 	 * kernel threads. We need to disable interrupts here,
13694 	 * simply because otherwise sfmmu_load_mmustate() would panic
13695 	 * if the caller does not disable interrupts.
13696 	 */
13697 	pstate_save = sfmmu_disable_intrs();
13698 
13699 	/* Compatibility Note: hw takes care of MMU_SCONTEXT1 */
13700 	sfmmu_setctx_sec(pgsz_cnum);
13701 	sfmmu_load_mmustate(ksfmmup);
13702 	sfmmu_enable_intrs(pstate_save);
13703 }
13704 
13705 
13706 /*
13707  * SRD support
13708  */
13709 #define	SRD_HASH_FUNCTION(vp)	(((((uintptr_t)(vp)) >> 4) ^ \
13710 				    (((uintptr_t)(vp)) >> 11)) & \
13711 				    srd_hashmask)
13712 
13713 /*
13714  * Attach the process to the srd struct associated with the exec vnode
13715  * from which the process is started.
13716  */
13717 void
13718 hat_join_srd(struct hat *sfmmup, vnode_t *evp)
13719 {
13720 	uint_t hash = SRD_HASH_FUNCTION(evp);
13721 	sf_srd_t *srdp;
13722 	sf_srd_t *newsrdp;
13723 
13724 	ASSERT(sfmmup != ksfmmup);
13725 	ASSERT(sfmmup->sfmmu_srdp == NULL);
13726 
13727 	if (!shctx_on) {
13728 		return;
13729 	}
13730 
13731 	VN_HOLD(evp);
13732 
13733 	if (srd_buckets[hash].srdb_srdp != NULL) {
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(
13741 				    (volatile uint_t *)&srdp->srd_refcnt, 1);
13742 				mutex_exit(&srd_buckets[hash].srdb_lock);
13743 				return;
13744 			}
13745 		}
13746 		mutex_exit(&srd_buckets[hash].srdb_lock);
13747 	}
13748 	newsrdp = kmem_cache_alloc(srd_cache, KM_SLEEP);
13749 	ASSERT(newsrdp->srd_next_ismrid == 0 && newsrdp->srd_next_hmerid == 0);
13750 
13751 	newsrdp->srd_evp = evp;
13752 	newsrdp->srd_refcnt = 1;
13753 	newsrdp->srd_hmergnfree = NULL;
13754 	newsrdp->srd_ismrgnfree = NULL;
13755 
13756 	mutex_enter(&srd_buckets[hash].srdb_lock);
13757 	for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13758 	    srdp = srdp->srd_hash) {
13759 		if (srdp->srd_evp == evp) {
13760 			ASSERT(srdp->srd_refcnt >= 0);
13761 			sfmmup->sfmmu_srdp = srdp;
13762 			atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
13763 			mutex_exit(&srd_buckets[hash].srdb_lock);
13764 			kmem_cache_free(srd_cache, newsrdp);
13765 			return;
13766 		}
13767 	}
13768 	newsrdp->srd_hash = srd_buckets[hash].srdb_srdp;
13769 	srd_buckets[hash].srdb_srdp = newsrdp;
13770 	sfmmup->sfmmu_srdp = newsrdp;
13771 
13772 	mutex_exit(&srd_buckets[hash].srdb_lock);
13773 
13774 }
13775 
13776 static void
13777 sfmmu_leave_srd(sfmmu_t *sfmmup)
13778 {
13779 	vnode_t *evp;
13780 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13781 	uint_t hash;
13782 	sf_srd_t **prev_srdpp;
13783 	sf_region_t *rgnp;
13784 	sf_region_t *nrgnp;
13785 #ifdef DEBUG
13786 	int rgns = 0;
13787 #endif
13788 	int i;
13789 
13790 	ASSERT(sfmmup != ksfmmup);
13791 	ASSERT(srdp != NULL);
13792 	ASSERT(srdp->srd_refcnt > 0);
13793 	ASSERT(sfmmup->sfmmu_scdp == NULL);
13794 	ASSERT(sfmmup->sfmmu_free == 1);
13795 
13796 	sfmmup->sfmmu_srdp = NULL;
13797 	evp = srdp->srd_evp;
13798 	ASSERT(evp != NULL);
13799 	if (atomic_add_32_nv(
13800 	    (volatile uint_t *)&srdp->srd_refcnt, -1)) {
13801 		VN_RELE(evp);
13802 		return;
13803 	}
13804 
13805 	hash = SRD_HASH_FUNCTION(evp);
13806 	mutex_enter(&srd_buckets[hash].srdb_lock);
13807 	for (prev_srdpp = &srd_buckets[hash].srdb_srdp;
13808 	    (srdp = *prev_srdpp) != NULL; prev_srdpp = &srdp->srd_hash) {
13809 		if (srdp->srd_evp == evp) {
13810 			break;
13811 		}
13812 	}
13813 	if (srdp == NULL || srdp->srd_refcnt) {
13814 		mutex_exit(&srd_buckets[hash].srdb_lock);
13815 		VN_RELE(evp);
13816 		return;
13817 	}
13818 	*prev_srdpp = srdp->srd_hash;
13819 	mutex_exit(&srd_buckets[hash].srdb_lock);
13820 
13821 	ASSERT(srdp->srd_refcnt == 0);
13822 	VN_RELE(evp);
13823 
13824 #ifdef DEBUG
13825 	for (i = 0; i < SFMMU_MAX_REGION_BUCKETS; i++) {
13826 		ASSERT(srdp->srd_rgnhash[i] == NULL);
13827 	}
13828 #endif /* DEBUG */
13829 
13830 	/* free each hme regions in the srd */
13831 	for (rgnp = srdp->srd_hmergnfree; rgnp != NULL; rgnp = nrgnp) {
13832 		nrgnp = rgnp->rgn_next;
13833 		ASSERT(rgnp->rgn_id < srdp->srd_next_hmerid);
13834 		ASSERT(rgnp->rgn_refcnt == 0);
13835 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13836 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13837 		ASSERT(rgnp->rgn_hmeflags == 0);
13838 		ASSERT(srdp->srd_hmergnp[rgnp->rgn_id] == rgnp);
13839 #ifdef DEBUG
13840 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13841 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13842 		}
13843 		rgns++;
13844 #endif /* DEBUG */
13845 		kmem_cache_free(region_cache, rgnp);
13846 	}
13847 	ASSERT(rgns == srdp->srd_next_hmerid);
13848 
13849 #ifdef DEBUG
13850 	rgns = 0;
13851 #endif
13852 	/* free each ism rgns in the srd */
13853 	for (rgnp = srdp->srd_ismrgnfree; rgnp != NULL; rgnp = nrgnp) {
13854 		nrgnp = rgnp->rgn_next;
13855 		ASSERT(rgnp->rgn_id < srdp->srd_next_ismrid);
13856 		ASSERT(rgnp->rgn_refcnt == 0);
13857 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13858 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13859 		ASSERT(srdp->srd_ismrgnp[rgnp->rgn_id] == rgnp);
13860 #ifdef DEBUG
13861 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13862 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13863 		}
13864 		rgns++;
13865 #endif /* DEBUG */
13866 		kmem_cache_free(region_cache, rgnp);
13867 	}
13868 	ASSERT(rgns == srdp->srd_next_ismrid);
13869 	ASSERT(srdp->srd_ismbusyrgns == 0);
13870 	ASSERT(srdp->srd_hmebusyrgns == 0);
13871 
13872 	srdp->srd_next_ismrid = 0;
13873 	srdp->srd_next_hmerid = 0;
13874 
13875 	bzero((void *)srdp->srd_ismrgnp,
13876 	    sizeof (sf_region_t *) * SFMMU_MAX_ISM_REGIONS);
13877 	bzero((void *)srdp->srd_hmergnp,
13878 	    sizeof (sf_region_t *) * SFMMU_MAX_HME_REGIONS);
13879 
13880 	ASSERT(srdp->srd_scdp == NULL);
13881 	kmem_cache_free(srd_cache, srdp);
13882 }
13883 
13884 /* ARGSUSED */
13885 static int
13886 sfmmu_srdcache_constructor(void *buf, void *cdrarg, int kmflags)
13887 {
13888 	sf_srd_t *srdp = (sf_srd_t *)buf;
13889 	bzero(buf, sizeof (*srdp));
13890 
13891 	mutex_init(&srdp->srd_mutex, NULL, MUTEX_DEFAULT, NULL);
13892 	mutex_init(&srdp->srd_scd_mutex, NULL, MUTEX_DEFAULT, NULL);
13893 	return (0);
13894 }
13895 
13896 /* ARGSUSED */
13897 static void
13898 sfmmu_srdcache_destructor(void *buf, void *cdrarg)
13899 {
13900 	sf_srd_t *srdp = (sf_srd_t *)buf;
13901 
13902 	mutex_destroy(&srdp->srd_mutex);
13903 	mutex_destroy(&srdp->srd_scd_mutex);
13904 }
13905 
13906 /*
13907  * The caller makes sure hat_join_region()/hat_leave_region() can't be called
13908  * at the same time for the same process and address range. This is ensured by
13909  * the fact that address space is locked as writer when a process joins the
13910  * regions. Therefore there's no need to hold an srd lock during the entire
13911  * execution of hat_join_region()/hat_leave_region().
13912  */
13913 
13914 #define	RGN_HASH_FUNCTION(obj)	(((((uintptr_t)(obj)) >> 4) ^ \
13915 				    (((uintptr_t)(obj)) >> 11)) & \
13916 					srd_rgn_hashmask)
13917 /*
13918  * This routine implements the shared context functionality required when
13919  * attaching a segment to an address space. It must be called from
13920  * hat_share() for D(ISM) segments and from segvn_create() for segments
13921  * with the MAP_PRIVATE and MAP_TEXT flags set. It returns a region_cookie
13922  * which is saved in the private segment data for hme segments and
13923  * the ism_map structure for ism segments.
13924  */
13925 hat_region_cookie_t
13926 hat_join_region(struct hat *sfmmup,
13927 	caddr_t r_saddr,
13928 	size_t r_size,
13929 	void *r_obj,
13930 	u_offset_t r_objoff,
13931 	uchar_t r_perm,
13932 	uchar_t r_pgszc,
13933 	hat_rgn_cb_func_t r_cb_function,
13934 	uint_t flags)
13935 {
13936 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13937 	uint_t rhash;
13938 	uint_t rid;
13939 	hatlock_t *hatlockp;
13940 	sf_region_t *rgnp;
13941 	sf_region_t *new_rgnp = NULL;
13942 	int i;
13943 	uint16_t *nextidp;
13944 	sf_region_t **freelistp;
13945 	int maxids;
13946 	sf_region_t **rarrp;
13947 	uint16_t *busyrgnsp;
13948 	ulong_t rttecnt;
13949 	uchar_t tteflag;
13950 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
13951 	int text = (r_type == HAT_REGION_TEXT);
13952 
13953 	if (srdp == NULL || r_size == 0) {
13954 		return (HAT_INVALID_REGION_COOKIE);
13955 	}
13956 
13957 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
13958 	ASSERT(sfmmup != ksfmmup);
13959 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
13960 	ASSERT(srdp->srd_refcnt > 0);
13961 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
13962 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
13963 	ASSERT(r_pgszc < mmu_page_sizes);
13964 	if (!IS_P2ALIGNED(r_saddr, TTEBYTES(r_pgszc)) ||
13965 	    !IS_P2ALIGNED(r_size, TTEBYTES(r_pgszc))) {
13966 		panic("hat_join_region: region addr or size is not aligned\n");
13967 	}
13968 
13969 
13970 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
13971 	    SFMMU_REGION_HME;
13972 	/*
13973 	 * Currently only support shared hmes for the read only main text
13974 	 * region.
13975 	 */
13976 	if (r_type == SFMMU_REGION_HME && ((r_obj != srdp->srd_evp) ||
13977 	    (r_perm & PROT_WRITE))) {
13978 		return (HAT_INVALID_REGION_COOKIE);
13979 	}
13980 
13981 	rhash = RGN_HASH_FUNCTION(r_obj);
13982 
13983 	if (r_type == SFMMU_REGION_ISM) {
13984 		nextidp = &srdp->srd_next_ismrid;
13985 		freelistp = &srdp->srd_ismrgnfree;
13986 		maxids = SFMMU_MAX_ISM_REGIONS;
13987 		rarrp = srdp->srd_ismrgnp;
13988 		busyrgnsp = &srdp->srd_ismbusyrgns;
13989 	} else {
13990 		nextidp = &srdp->srd_next_hmerid;
13991 		freelistp = &srdp->srd_hmergnfree;
13992 		maxids = SFMMU_MAX_HME_REGIONS;
13993 		rarrp = srdp->srd_hmergnp;
13994 		busyrgnsp = &srdp->srd_hmebusyrgns;
13995 	}
13996 
13997 	mutex_enter(&srdp->srd_mutex);
13998 
13999 	for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
14000 	    rgnp = rgnp->rgn_hash) {
14001 		if (rgnp->rgn_saddr == r_saddr && rgnp->rgn_size == r_size &&
14002 		    rgnp->rgn_obj == r_obj && rgnp->rgn_objoff == r_objoff &&
14003 		    rgnp->rgn_perm == r_perm && rgnp->rgn_pgszc == r_pgszc) {
14004 			break;
14005 		}
14006 	}
14007 
14008 rfound:
14009 	if (rgnp != NULL) {
14010 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14011 		ASSERT(rgnp->rgn_cb_function == r_cb_function);
14012 		ASSERT(rgnp->rgn_refcnt >= 0);
14013 		rid = rgnp->rgn_id;
14014 		ASSERT(rid < maxids);
14015 		ASSERT(rarrp[rid] == rgnp);
14016 		ASSERT(rid < *nextidp);
14017 		atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
14018 		mutex_exit(&srdp->srd_mutex);
14019 		if (new_rgnp != NULL) {
14020 			kmem_cache_free(region_cache, new_rgnp);
14021 		}
14022 		if (r_type == SFMMU_REGION_HME) {
14023 			int myjoin =
14024 			    (sfmmup == astosfmmu(curthread->t_procp->p_as));
14025 
14026 			sfmmu_link_to_hmeregion(sfmmup, rgnp);
14027 			/*
14028 			 * bitmap should be updated after linking sfmmu on
14029 			 * region list so that pageunload() doesn't skip
14030 			 * TSB/TLB flush. As soon as bitmap is updated another
14031 			 * thread in this process can already start accessing
14032 			 * this region.
14033 			 */
14034 			/*
14035 			 * Normally ttecnt accounting is done as part of
14036 			 * pagefault handling. But a process may not take any
14037 			 * pagefaults on shared hmeblks created by some other
14038 			 * process. To compensate for this assume that the
14039 			 * entire region will end up faulted in using
14040 			 * the region's pagesize.
14041 			 *
14042 			 */
14043 			if (r_pgszc > TTE8K) {
14044 				tteflag = 1 << r_pgszc;
14045 				if (disable_large_pages & tteflag) {
14046 					tteflag = 0;
14047 				}
14048 			} else {
14049 				tteflag = 0;
14050 			}
14051 			if (tteflag && !(sfmmup->sfmmu_rtteflags & tteflag)) {
14052 				hatlockp = sfmmu_hat_enter(sfmmup);
14053 				sfmmup->sfmmu_rtteflags |= tteflag;
14054 				sfmmu_hat_exit(hatlockp);
14055 			}
14056 			hatlockp = sfmmu_hat_enter(sfmmup);
14057 
14058 			/*
14059 			 * Preallocate 1/4 of ttecnt's in 8K TSB for >= 4M
14060 			 * region to allow for large page allocation failure.
14061 			 */
14062 			if (r_pgszc >= TTE4M) {
14063 				sfmmup->sfmmu_tsb0_4minflcnt +=
14064 				    r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14065 			}
14066 
14067 			/* update sfmmu_ttecnt with the shme rgn ttecnt */
14068 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14069 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14070 			    rttecnt);
14071 
14072 			if (text && r_pgszc >= TTE4M &&
14073 			    (tteflag || ((disable_large_pages >> TTE4M) &
14074 			    ((1 << (r_pgszc - TTE4M + 1)) - 1))) &&
14075 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
14076 				SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
14077 			}
14078 
14079 			sfmmu_hat_exit(hatlockp);
14080 			/*
14081 			 * On Panther we need to make sure TLB is programmed
14082 			 * to accept 32M/256M pages.  Call
14083 			 * sfmmu_check_page_sizes() now to make sure TLB is
14084 			 * setup before making hmeregions visible to other
14085 			 * threads.
14086 			 */
14087 			sfmmu_check_page_sizes(sfmmup, 1);
14088 			hatlockp = sfmmu_hat_enter(sfmmup);
14089 			SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14090 
14091 			/*
14092 			 * if context is invalid tsb miss exception code will
14093 			 * call sfmmu_check_page_sizes() and update tsbmiss
14094 			 * area later.
14095 			 */
14096 			kpreempt_disable();
14097 			if (myjoin &&
14098 			    (sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
14099 			    != INVALID_CONTEXT)) {
14100 				struct tsbmiss *tsbmp;
14101 
14102 				tsbmp = &tsbmiss_area[CPU->cpu_id];
14103 				ASSERT(sfmmup == tsbmp->usfmmup);
14104 				BT_SET(tsbmp->shmermap, rid);
14105 				if (r_pgszc > TTE64K) {
14106 					tsbmp->uhat_rtteflags |= tteflag;
14107 				}
14108 
14109 			}
14110 			kpreempt_enable();
14111 
14112 			sfmmu_hat_exit(hatlockp);
14113 			ASSERT((hat_region_cookie_t)((uint64_t)rid) !=
14114 			    HAT_INVALID_REGION_COOKIE);
14115 		} else {
14116 			hatlockp = sfmmu_hat_enter(sfmmup);
14117 			SF_RGNMAP_ADD(sfmmup->sfmmu_ismregion_map, rid);
14118 			sfmmu_hat_exit(hatlockp);
14119 		}
14120 		ASSERT(rid < maxids);
14121 
14122 		if (r_type == SFMMU_REGION_ISM) {
14123 			sfmmu_find_scd(sfmmup);
14124 		}
14125 		return ((hat_region_cookie_t)((uint64_t)rid));
14126 	}
14127 
14128 	ASSERT(new_rgnp == NULL);
14129 
14130 	if (*busyrgnsp >= maxids) {
14131 		mutex_exit(&srdp->srd_mutex);
14132 		return (HAT_INVALID_REGION_COOKIE);
14133 	}
14134 
14135 	ASSERT(MUTEX_HELD(&srdp->srd_mutex));
14136 	if (*freelistp != NULL) {
14137 		rgnp = *freelistp;
14138 		*freelistp = rgnp->rgn_next;
14139 		ASSERT(rgnp->rgn_id < *nextidp);
14140 		ASSERT(rgnp->rgn_id < maxids);
14141 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
14142 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK)
14143 		    == r_type);
14144 		ASSERT(rarrp[rgnp->rgn_id] == rgnp);
14145 		ASSERT(rgnp->rgn_hmeflags == 0);
14146 	} else {
14147 		/*
14148 		 * release local locks before memory allocation.
14149 		 */
14150 		mutex_exit(&srdp->srd_mutex);
14151 
14152 		new_rgnp = kmem_cache_alloc(region_cache, KM_SLEEP);
14153 
14154 		mutex_enter(&srdp->srd_mutex);
14155 		for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
14156 		    rgnp = rgnp->rgn_hash) {
14157 			if (rgnp->rgn_saddr == r_saddr &&
14158 			    rgnp->rgn_size == r_size &&
14159 			    rgnp->rgn_obj == r_obj &&
14160 			    rgnp->rgn_objoff == r_objoff &&
14161 			    rgnp->rgn_perm == r_perm &&
14162 			    rgnp->rgn_pgszc == r_pgszc) {
14163 				break;
14164 			}
14165 		}
14166 		if (rgnp != NULL) {
14167 			goto rfound;
14168 		}
14169 
14170 		if (*nextidp >= maxids) {
14171 			mutex_exit(&srdp->srd_mutex);
14172 			goto fail;
14173 		}
14174 		rgnp = new_rgnp;
14175 		new_rgnp = NULL;
14176 		rgnp->rgn_id = (*nextidp)++;
14177 		ASSERT(rgnp->rgn_id < maxids);
14178 		ASSERT(rarrp[rgnp->rgn_id] == NULL);
14179 		rarrp[rgnp->rgn_id] = rgnp;
14180 	}
14181 
14182 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14183 	ASSERT(rgnp->rgn_hmeflags == 0);
14184 #ifdef DEBUG
14185 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14186 		ASSERT(rgnp->rgn_ttecnt[i] == 0);
14187 	}
14188 #endif
14189 	rgnp->rgn_saddr = r_saddr;
14190 	rgnp->rgn_size = r_size;
14191 	rgnp->rgn_obj = r_obj;
14192 	rgnp->rgn_objoff = r_objoff;
14193 	rgnp->rgn_perm = r_perm;
14194 	rgnp->rgn_pgszc = r_pgszc;
14195 	rgnp->rgn_flags = r_type;
14196 	rgnp->rgn_refcnt = 0;
14197 	rgnp->rgn_cb_function = r_cb_function;
14198 	rgnp->rgn_hash = srdp->srd_rgnhash[rhash];
14199 	srdp->srd_rgnhash[rhash] = rgnp;
14200 	(*busyrgnsp)++;
14201 	ASSERT(*busyrgnsp <= maxids);
14202 	goto rfound;
14203 
14204 fail:
14205 	ASSERT(new_rgnp != NULL);
14206 	kmem_cache_free(region_cache, new_rgnp);
14207 	return (HAT_INVALID_REGION_COOKIE);
14208 }
14209 
14210 /*
14211  * This function implements the shared context functionality required
14212  * when detaching a segment from an address space. It must be called
14213  * from hat_unshare() for all D(ISM) segments and from segvn_unmap(),
14214  * for segments with a valid region_cookie.
14215  * It will also be called from all seg_vn routines which change a
14216  * segment's attributes such as segvn_setprot(), segvn_setpagesize(),
14217  * segvn_clrszc() & segvn_advise(), as well as in the case of COW fault
14218  * from segvn_fault().
14219  */
14220 void
14221 hat_leave_region(struct hat *sfmmup, hat_region_cookie_t rcookie, uint_t flags)
14222 {
14223 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14224 	sf_scd_t *scdp;
14225 	uint_t rhash;
14226 	uint_t rid = (uint_t)((uint64_t)rcookie);
14227 	hatlock_t *hatlockp = NULL;
14228 	sf_region_t *rgnp;
14229 	sf_region_t **prev_rgnpp;
14230 	sf_region_t *cur_rgnp;
14231 	void *r_obj;
14232 	int i;
14233 	caddr_t	r_saddr;
14234 	caddr_t r_eaddr;
14235 	size_t	r_size;
14236 	uchar_t	r_pgszc;
14237 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
14238 
14239 	ASSERT(sfmmup != ksfmmup);
14240 	ASSERT(srdp != NULL);
14241 	ASSERT(srdp->srd_refcnt > 0);
14242 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
14243 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
14244 	ASSERT(!sfmmup->sfmmu_free || sfmmup->sfmmu_scdp == NULL);
14245 
14246 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
14247 	    SFMMU_REGION_HME;
14248 
14249 	if (r_type == SFMMU_REGION_ISM) {
14250 		ASSERT(SFMMU_IS_ISMRID_VALID(rid));
14251 		ASSERT(rid < SFMMU_MAX_ISM_REGIONS);
14252 		rgnp = srdp->srd_ismrgnp[rid];
14253 	} else {
14254 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14255 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14256 		rgnp = srdp->srd_hmergnp[rid];
14257 	}
14258 	ASSERT(rgnp != NULL);
14259 	ASSERT(rgnp->rgn_id == rid);
14260 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14261 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14262 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
14263 
14264 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
14265 	if (r_type == SFMMU_REGION_HME && sfmmup->sfmmu_as->a_xhat != NULL) {
14266 		xhat_unload_callback_all(sfmmup->sfmmu_as, rgnp->rgn_saddr,
14267 		    rgnp->rgn_size, 0, NULL);
14268 	}
14269 
14270 	if (sfmmup->sfmmu_free) {
14271 		ulong_t rttecnt;
14272 		r_pgszc = rgnp->rgn_pgszc;
14273 		r_size = rgnp->rgn_size;
14274 
14275 		ASSERT(sfmmup->sfmmu_scdp == NULL);
14276 		if (r_type == SFMMU_REGION_ISM) {
14277 			SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14278 		} else {
14279 			/* update shme rgns ttecnt in sfmmu_ttecnt */
14280 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14281 			ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14282 
14283 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14284 			    -rttecnt);
14285 
14286 			SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14287 		}
14288 	} else if (r_type == SFMMU_REGION_ISM) {
14289 		hatlockp = sfmmu_hat_enter(sfmmup);
14290 		ASSERT(rid < srdp->srd_next_ismrid);
14291 		SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14292 		scdp = sfmmup->sfmmu_scdp;
14293 		if (scdp != NULL &&
14294 		    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
14295 			sfmmu_leave_scd(sfmmup, r_type);
14296 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14297 		}
14298 		sfmmu_hat_exit(hatlockp);
14299 	} else {
14300 		ulong_t rttecnt;
14301 		r_pgszc = rgnp->rgn_pgszc;
14302 		r_saddr = rgnp->rgn_saddr;
14303 		r_size = rgnp->rgn_size;
14304 		r_eaddr = r_saddr + r_size;
14305 
14306 		ASSERT(r_type == SFMMU_REGION_HME);
14307 		hatlockp = sfmmu_hat_enter(sfmmup);
14308 		ASSERT(rid < srdp->srd_next_hmerid);
14309 		SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14310 
14311 		/*
14312 		 * If region is part of an SCD call sfmmu_leave_scd().
14313 		 * Otherwise if process is not exiting and has valid context
14314 		 * just drop the context on the floor to lose stale TLB
14315 		 * entries and force the update of tsb miss area to reflect
14316 		 * the new region map. After that clean our TSB entries.
14317 		 */
14318 		scdp = sfmmup->sfmmu_scdp;
14319 		if (scdp != NULL &&
14320 		    SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
14321 			sfmmu_leave_scd(sfmmup, r_type);
14322 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14323 		}
14324 		sfmmu_invalidate_ctx(sfmmup);
14325 
14326 		i = TTE8K;
14327 		while (i < mmu_page_sizes) {
14328 			if (rgnp->rgn_ttecnt[i] != 0) {
14329 				sfmmu_unload_tsb_range(sfmmup, r_saddr,
14330 				    r_eaddr, i);
14331 				if (i < TTE4M) {
14332 					i = TTE4M;
14333 					continue;
14334 				} else {
14335 					break;
14336 				}
14337 			}
14338 			i++;
14339 		}
14340 		/* Remove the preallocated 1/4 8k ttecnt for 4M regions. */
14341 		if (r_pgszc >= TTE4M) {
14342 			rttecnt = r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14343 			ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
14344 			    rttecnt);
14345 			sfmmup->sfmmu_tsb0_4minflcnt -= rttecnt;
14346 		}
14347 
14348 		/* update shme rgns ttecnt in sfmmu_ttecnt */
14349 		rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14350 		ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14351 		atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc], -rttecnt);
14352 
14353 		sfmmu_hat_exit(hatlockp);
14354 		if (scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
14355 			/* sfmmup left the scd, grow private tsb */
14356 			sfmmu_check_page_sizes(sfmmup, 1);
14357 		} else {
14358 			sfmmu_check_page_sizes(sfmmup, 0);
14359 		}
14360 	}
14361 
14362 	if (r_type == SFMMU_REGION_HME) {
14363 		sfmmu_unlink_from_hmeregion(sfmmup, rgnp);
14364 	}
14365 
14366 	r_obj = rgnp->rgn_obj;
14367 	if (atomic_add_32_nv((volatile uint_t *)&rgnp->rgn_refcnt, -1)) {
14368 		return;
14369 	}
14370 
14371 	/*
14372 	 * looks like nobody uses this region anymore. Free it.
14373 	 */
14374 	rhash = RGN_HASH_FUNCTION(r_obj);
14375 	mutex_enter(&srdp->srd_mutex);
14376 	for (prev_rgnpp = &srdp->srd_rgnhash[rhash];
14377 	    (cur_rgnp = *prev_rgnpp) != NULL;
14378 	    prev_rgnpp = &cur_rgnp->rgn_hash) {
14379 		if (cur_rgnp == rgnp && cur_rgnp->rgn_refcnt == 0) {
14380 			break;
14381 		}
14382 	}
14383 
14384 	if (cur_rgnp == NULL) {
14385 		mutex_exit(&srdp->srd_mutex);
14386 		return;
14387 	}
14388 
14389 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14390 	*prev_rgnpp = rgnp->rgn_hash;
14391 	if (r_type == SFMMU_REGION_ISM) {
14392 		rgnp->rgn_flags |= SFMMU_REGION_FREE;
14393 		ASSERT(rid < srdp->srd_next_ismrid);
14394 		rgnp->rgn_next = srdp->srd_ismrgnfree;
14395 		srdp->srd_ismrgnfree = rgnp;
14396 		ASSERT(srdp->srd_ismbusyrgns > 0);
14397 		srdp->srd_ismbusyrgns--;
14398 		mutex_exit(&srdp->srd_mutex);
14399 		return;
14400 	}
14401 	mutex_exit(&srdp->srd_mutex);
14402 
14403 	/*
14404 	 * Destroy region's hmeblks.
14405 	 */
14406 	sfmmu_unload_hmeregion(srdp, rgnp);
14407 
14408 	rgnp->rgn_hmeflags = 0;
14409 
14410 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14411 	ASSERT(rgnp->rgn_id == rid);
14412 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14413 		rgnp->rgn_ttecnt[i] = 0;
14414 	}
14415 	rgnp->rgn_flags |= SFMMU_REGION_FREE;
14416 	mutex_enter(&srdp->srd_mutex);
14417 	ASSERT(rid < srdp->srd_next_hmerid);
14418 	rgnp->rgn_next = srdp->srd_hmergnfree;
14419 	srdp->srd_hmergnfree = rgnp;
14420 	ASSERT(srdp->srd_hmebusyrgns > 0);
14421 	srdp->srd_hmebusyrgns--;
14422 	mutex_exit(&srdp->srd_mutex);
14423 }
14424 
14425 /*
14426  * For now only called for hmeblk regions and not for ISM regions.
14427  */
14428 void
14429 hat_dup_region(struct hat *sfmmup, hat_region_cookie_t rcookie)
14430 {
14431 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14432 	uint_t rid = (uint_t)((uint64_t)rcookie);
14433 	sf_region_t *rgnp;
14434 	sf_rgn_link_t *rlink;
14435 	sf_rgn_link_t *hrlink;
14436 	ulong_t	rttecnt;
14437 
14438 	ASSERT(sfmmup != ksfmmup);
14439 	ASSERT(srdp != NULL);
14440 	ASSERT(srdp->srd_refcnt > 0);
14441 
14442 	ASSERT(rid < srdp->srd_next_hmerid);
14443 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14444 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14445 
14446 	rgnp = srdp->srd_hmergnp[rid];
14447 	ASSERT(rgnp->rgn_refcnt > 0);
14448 	ASSERT(rgnp->rgn_id == rid);
14449 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == SFMMU_REGION_HME);
14450 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14451 
14452 	atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
14453 
14454 	/* LINTED: constant in conditional context */
14455 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 0);
14456 	ASSERT(rlink != NULL);
14457 	mutex_enter(&rgnp->rgn_mutex);
14458 	ASSERT(rgnp->rgn_sfmmu_head != NULL);
14459 	/* LINTED: constant in conditional context */
14460 	SFMMU_HMERID2RLINKP(rgnp->rgn_sfmmu_head, rid, hrlink, 0, 0);
14461 	ASSERT(hrlink != NULL);
14462 	ASSERT(hrlink->prev == NULL);
14463 	rlink->next = rgnp->rgn_sfmmu_head;
14464 	rlink->prev = NULL;
14465 	hrlink->prev = sfmmup;
14466 	/*
14467 	 * make sure rlink's next field is correct
14468 	 * before making this link visible.
14469 	 */
14470 	membar_stst();
14471 	rgnp->rgn_sfmmu_head = sfmmup;
14472 	mutex_exit(&rgnp->rgn_mutex);
14473 
14474 	/* update sfmmu_ttecnt with the shme rgn ttecnt */
14475 	rttecnt = rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
14476 	atomic_add_long(&sfmmup->sfmmu_ttecnt[rgnp->rgn_pgszc], rttecnt);
14477 	/* update tsb0 inflation count */
14478 	if (rgnp->rgn_pgszc >= TTE4M) {
14479 		sfmmup->sfmmu_tsb0_4minflcnt +=
14480 		    rgnp->rgn_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14481 	}
14482 	/*
14483 	 * Update regionid bitmask without hat lock since no other thread
14484 	 * can update this region bitmask right now.
14485 	 */
14486 	SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14487 }
14488 
14489 /* ARGSUSED */
14490 static int
14491 sfmmu_rgncache_constructor(void *buf, void *cdrarg, int kmflags)
14492 {
14493 	sf_region_t *rgnp = (sf_region_t *)buf;
14494 	bzero(buf, sizeof (*rgnp));
14495 
14496 	mutex_init(&rgnp->rgn_mutex, NULL, MUTEX_DEFAULT, NULL);
14497 
14498 	return (0);
14499 }
14500 
14501 /* ARGSUSED */
14502 static void
14503 sfmmu_rgncache_destructor(void *buf, void *cdrarg)
14504 {
14505 	sf_region_t *rgnp = (sf_region_t *)buf;
14506 	mutex_destroy(&rgnp->rgn_mutex);
14507 }
14508 
14509 static int
14510 sfrgnmap_isnull(sf_region_map_t *map)
14511 {
14512 	int i;
14513 
14514 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14515 		if (map->bitmap[i] != 0) {
14516 			return (0);
14517 		}
14518 	}
14519 	return (1);
14520 }
14521 
14522 static int
14523 sfhmergnmap_isnull(sf_hmeregion_map_t *map)
14524 {
14525 	int i;
14526 
14527 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
14528 		if (map->bitmap[i] != 0) {
14529 			return (0);
14530 		}
14531 	}
14532 	return (1);
14533 }
14534 
14535 #ifdef DEBUG
14536 static void
14537 check_scd_sfmmu_list(sfmmu_t **headp, sfmmu_t *sfmmup, int onlist)
14538 {
14539 	sfmmu_t *sp;
14540 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14541 
14542 	for (sp = *headp; sp != NULL; sp = sp->sfmmu_scd_link.next) {
14543 		ASSERT(srdp == sp->sfmmu_srdp);
14544 		if (sp == sfmmup) {
14545 			if (onlist) {
14546 				return;
14547 			} else {
14548 				panic("shctx: sfmmu 0x%p found on scd"
14549 				    "list 0x%p", (void *)sfmmup,
14550 				    (void *)*headp);
14551 			}
14552 		}
14553 	}
14554 	if (onlist) {
14555 		panic("shctx: sfmmu 0x%p not found on scd list 0x%p",
14556 		    (void *)sfmmup, (void *)*headp);
14557 	} else {
14558 		return;
14559 	}
14560 }
14561 #else /* DEBUG */
14562 #define	check_scd_sfmmu_list(headp, sfmmup, onlist)
14563 #endif /* DEBUG */
14564 
14565 /*
14566  * Removes an sfmmu from the SCD sfmmu list.
14567  */
14568 static void
14569 sfmmu_from_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14570 {
14571 	ASSERT(sfmmup->sfmmu_srdp != NULL);
14572 	check_scd_sfmmu_list(headp, sfmmup, 1);
14573 	if (sfmmup->sfmmu_scd_link.prev != NULL) {
14574 		ASSERT(*headp != sfmmup);
14575 		sfmmup->sfmmu_scd_link.prev->sfmmu_scd_link.next =
14576 		    sfmmup->sfmmu_scd_link.next;
14577 	} else {
14578 		ASSERT(*headp == sfmmup);
14579 		*headp = sfmmup->sfmmu_scd_link.next;
14580 	}
14581 	if (sfmmup->sfmmu_scd_link.next != NULL) {
14582 		sfmmup->sfmmu_scd_link.next->sfmmu_scd_link.prev =
14583 		    sfmmup->sfmmu_scd_link.prev;
14584 	}
14585 }
14586 
14587 
14588 /*
14589  * Adds an sfmmu to the start of the queue.
14590  */
14591 static void
14592 sfmmu_to_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14593 {
14594 	check_scd_sfmmu_list(headp, sfmmup, 0);
14595 	sfmmup->sfmmu_scd_link.prev = NULL;
14596 	sfmmup->sfmmu_scd_link.next = *headp;
14597 	if (*headp != NULL)
14598 		(*headp)->sfmmu_scd_link.prev = sfmmup;
14599 	*headp = sfmmup;
14600 }
14601 
14602 /*
14603  * Remove an scd from the start of the queue.
14604  */
14605 static void
14606 sfmmu_remove_scd(sf_scd_t **headp, sf_scd_t *scdp)
14607 {
14608 	if (scdp->scd_prev != NULL) {
14609 		ASSERT(*headp != scdp);
14610 		scdp->scd_prev->scd_next = scdp->scd_next;
14611 	} else {
14612 		ASSERT(*headp == scdp);
14613 		*headp = scdp->scd_next;
14614 	}
14615 
14616 	if (scdp->scd_next != NULL) {
14617 		scdp->scd_next->scd_prev = scdp->scd_prev;
14618 	}
14619 }
14620 
14621 /*
14622  * Add an scd to the start of the queue.
14623  */
14624 static void
14625 sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *scdp)
14626 {
14627 	scdp->scd_prev = NULL;
14628 	scdp->scd_next = *headp;
14629 	if (*headp != NULL) {
14630 		(*headp)->scd_prev = scdp;
14631 	}
14632 	*headp = scdp;
14633 }
14634 
14635 static int
14636 sfmmu_alloc_scd_tsbs(sf_srd_t *srdp, sf_scd_t *scdp)
14637 {
14638 	uint_t rid;
14639 	uint_t i;
14640 	uint_t j;
14641 	ulong_t w;
14642 	sf_region_t *rgnp;
14643 	ulong_t tte8k_cnt = 0;
14644 	ulong_t tte4m_cnt = 0;
14645 	uint_t tsb_szc;
14646 	sfmmu_t *scsfmmup = scdp->scd_sfmmup;
14647 	sfmmu_t	*ism_hatid;
14648 	struct tsb_info *newtsb;
14649 	int szc;
14650 
14651 	ASSERT(srdp != NULL);
14652 
14653 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14654 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14655 			continue;
14656 		}
14657 		j = 0;
14658 		while (w) {
14659 			if (!(w & 0x1)) {
14660 				j++;
14661 				w >>= 1;
14662 				continue;
14663 			}
14664 			rid = (i << BT_ULSHIFT) | j;
14665 			j++;
14666 			w >>= 1;
14667 
14668 			if (rid < SFMMU_MAX_HME_REGIONS) {
14669 				rgnp = srdp->srd_hmergnp[rid];
14670 				ASSERT(rgnp->rgn_id == rid);
14671 				ASSERT(rgnp->rgn_refcnt > 0);
14672 
14673 				if (rgnp->rgn_pgszc < TTE4M) {
14674 					tte8k_cnt += rgnp->rgn_size >>
14675 					    TTE_PAGE_SHIFT(TTE8K);
14676 				} else {
14677 					ASSERT(rgnp->rgn_pgszc >= TTE4M);
14678 					tte4m_cnt += rgnp->rgn_size >>
14679 					    TTE_PAGE_SHIFT(TTE4M);
14680 					/*
14681 					 * Inflate SCD tsb0 by preallocating
14682 					 * 1/4 8k ttecnt for 4M regions to
14683 					 * allow for lgpg alloc failure.
14684 					 */
14685 					tte8k_cnt += rgnp->rgn_size >>
14686 					    (TTE_PAGE_SHIFT(TTE8K) + 2);
14687 				}
14688 			} else {
14689 				rid -= SFMMU_MAX_HME_REGIONS;
14690 				rgnp = srdp->srd_ismrgnp[rid];
14691 				ASSERT(rgnp->rgn_id == rid);
14692 				ASSERT(rgnp->rgn_refcnt > 0);
14693 
14694 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14695 				ASSERT(ism_hatid->sfmmu_ismhat);
14696 
14697 				for (szc = 0; szc < TTE4M; szc++) {
14698 					tte8k_cnt +=
14699 					    ism_hatid->sfmmu_ttecnt[szc] <<
14700 					    TTE_BSZS_SHIFT(szc);
14701 				}
14702 
14703 				ASSERT(rgnp->rgn_pgszc >= TTE4M);
14704 				if (rgnp->rgn_pgszc >= TTE4M) {
14705 					tte4m_cnt += rgnp->rgn_size >>
14706 					    TTE_PAGE_SHIFT(TTE4M);
14707 				}
14708 			}
14709 		}
14710 	}
14711 
14712 	tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
14713 
14714 	/* Allocate both the SCD TSBs here. */
14715 	if (sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14716 	    tsb_szc, TSB8K|TSB64K|TSB512K, TSB_ALLOC, scsfmmup) &&
14717 	    (tsb_szc <= TSB_4M_SZCODE ||
14718 	    sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14719 	    TSB_4M_SZCODE, TSB8K|TSB64K|TSB512K,
14720 	    TSB_ALLOC, scsfmmup))) {
14721 
14722 		SFMMU_STAT(sf_scd_1sttsb_allocfail);
14723 		return (TSB_ALLOCFAIL);
14724 	} else {
14725 		scsfmmup->sfmmu_tsb->tsb_flags |= TSB_SHAREDCTX;
14726 
14727 		if (tte4m_cnt) {
14728 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
14729 			if (sfmmu_tsbinfo_alloc(&newtsb, tsb_szc,
14730 			    TSB4M|TSB32M|TSB256M, TSB_ALLOC, scsfmmup) &&
14731 			    (tsb_szc <= TSB_4M_SZCODE ||
14732 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
14733 			    TSB4M|TSB32M|TSB256M,
14734 			    TSB_ALLOC, scsfmmup))) {
14735 				/*
14736 				 * If we fail to allocate the 2nd shared tsb,
14737 				 * just free the 1st tsb, return failure.
14738 				 */
14739 				sfmmu_tsbinfo_free(scsfmmup->sfmmu_tsb);
14740 				SFMMU_STAT(sf_scd_2ndtsb_allocfail);
14741 				return (TSB_ALLOCFAIL);
14742 			} else {
14743 				ASSERT(scsfmmup->sfmmu_tsb->tsb_next == NULL);
14744 				newtsb->tsb_flags |= TSB_SHAREDCTX;
14745 				scsfmmup->sfmmu_tsb->tsb_next = newtsb;
14746 				SFMMU_STAT(sf_scd_2ndtsb_alloc);
14747 			}
14748 		}
14749 		SFMMU_STAT(sf_scd_1sttsb_alloc);
14750 	}
14751 	return (TSB_SUCCESS);
14752 }
14753 
14754 static void
14755 sfmmu_free_scd_tsbs(sfmmu_t *scd_sfmmu)
14756 {
14757 	while (scd_sfmmu->sfmmu_tsb != NULL) {
14758 		struct tsb_info *next = scd_sfmmu->sfmmu_tsb->tsb_next;
14759 		sfmmu_tsbinfo_free(scd_sfmmu->sfmmu_tsb);
14760 		scd_sfmmu->sfmmu_tsb = next;
14761 	}
14762 }
14763 
14764 /*
14765  * Link the sfmmu onto the hme region list.
14766  */
14767 void
14768 sfmmu_link_to_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14769 {
14770 	uint_t rid;
14771 	sf_rgn_link_t *rlink;
14772 	sfmmu_t *head;
14773 	sf_rgn_link_t *hrlink;
14774 
14775 	rid = rgnp->rgn_id;
14776 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14777 
14778 	/* LINTED: constant in conditional context */
14779 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 1);
14780 	ASSERT(rlink != NULL);
14781 	mutex_enter(&rgnp->rgn_mutex);
14782 	if ((head = rgnp->rgn_sfmmu_head) == NULL) {
14783 		rlink->next = NULL;
14784 		rlink->prev = NULL;
14785 		/*
14786 		 * make sure rlink's next field is NULL
14787 		 * before making this link visible.
14788 		 */
14789 		membar_stst();
14790 		rgnp->rgn_sfmmu_head = sfmmup;
14791 	} else {
14792 		/* LINTED: constant in conditional context */
14793 		SFMMU_HMERID2RLINKP(head, rid, hrlink, 0, 0);
14794 		ASSERT(hrlink != NULL);
14795 		ASSERT(hrlink->prev == NULL);
14796 		rlink->next = head;
14797 		rlink->prev = NULL;
14798 		hrlink->prev = sfmmup;
14799 		/*
14800 		 * make sure rlink's next field is correct
14801 		 * before making this link visible.
14802 		 */
14803 		membar_stst();
14804 		rgnp->rgn_sfmmu_head = sfmmup;
14805 	}
14806 	mutex_exit(&rgnp->rgn_mutex);
14807 }
14808 
14809 /*
14810  * Unlink the sfmmu from the hme region list.
14811  */
14812 void
14813 sfmmu_unlink_from_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14814 {
14815 	uint_t rid;
14816 	sf_rgn_link_t *rlink;
14817 
14818 	rid = rgnp->rgn_id;
14819 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14820 
14821 	/* LINTED: constant in conditional context */
14822 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
14823 	ASSERT(rlink != NULL);
14824 	mutex_enter(&rgnp->rgn_mutex);
14825 	if (rgnp->rgn_sfmmu_head == sfmmup) {
14826 		sfmmu_t *next = rlink->next;
14827 		rgnp->rgn_sfmmu_head = next;
14828 		/*
14829 		 * if we are stopped by xc_attention() after this
14830 		 * point the forward link walking in
14831 		 * sfmmu_rgntlb_demap() will work correctly since the
14832 		 * head correctly points to the next element.
14833 		 */
14834 		membar_stst();
14835 		rlink->next = NULL;
14836 		ASSERT(rlink->prev == NULL);
14837 		if (next != NULL) {
14838 			sf_rgn_link_t *nrlink;
14839 			/* LINTED: constant in conditional context */
14840 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14841 			ASSERT(nrlink != NULL);
14842 			ASSERT(nrlink->prev == sfmmup);
14843 			nrlink->prev = NULL;
14844 		}
14845 	} else {
14846 		sfmmu_t *next = rlink->next;
14847 		sfmmu_t *prev = rlink->prev;
14848 		sf_rgn_link_t *prlink;
14849 
14850 		ASSERT(prev != NULL);
14851 		/* LINTED: constant in conditional context */
14852 		SFMMU_HMERID2RLINKP(prev, rid, prlink, 0, 0);
14853 		ASSERT(prlink != NULL);
14854 		ASSERT(prlink->next == sfmmup);
14855 		prlink->next = next;
14856 		/*
14857 		 * if we are stopped by xc_attention()
14858 		 * after this point the forward link walking
14859 		 * will work correctly since the prev element
14860 		 * correctly points to the next element.
14861 		 */
14862 		membar_stst();
14863 		rlink->next = NULL;
14864 		rlink->prev = NULL;
14865 		if (next != NULL) {
14866 			sf_rgn_link_t *nrlink;
14867 			/* LINTED: constant in conditional context */
14868 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14869 			ASSERT(nrlink != NULL);
14870 			ASSERT(nrlink->prev == sfmmup);
14871 			nrlink->prev = prev;
14872 		}
14873 	}
14874 	mutex_exit(&rgnp->rgn_mutex);
14875 }
14876 
14877 /*
14878  * Link scd sfmmu onto ism or hme region list for each region in the
14879  * scd region map.
14880  */
14881 void
14882 sfmmu_link_scd_to_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14883 {
14884 	uint_t rid;
14885 	uint_t i;
14886 	uint_t j;
14887 	ulong_t w;
14888 	sf_region_t *rgnp;
14889 	sfmmu_t *scsfmmup;
14890 
14891 	scsfmmup = scdp->scd_sfmmup;
14892 	ASSERT(scsfmmup->sfmmu_scdhat);
14893 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14894 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14895 			continue;
14896 		}
14897 		j = 0;
14898 		while (w) {
14899 			if (!(w & 0x1)) {
14900 				j++;
14901 				w >>= 1;
14902 				continue;
14903 			}
14904 			rid = (i << BT_ULSHIFT) | j;
14905 			j++;
14906 			w >>= 1;
14907 
14908 			if (rid < SFMMU_MAX_HME_REGIONS) {
14909 				rgnp = srdp->srd_hmergnp[rid];
14910 				ASSERT(rgnp->rgn_id == rid);
14911 				ASSERT(rgnp->rgn_refcnt > 0);
14912 				sfmmu_link_to_hmeregion(scsfmmup, rgnp);
14913 			} else {
14914 				sfmmu_t *ism_hatid = NULL;
14915 				ism_ment_t *ism_ment;
14916 				rid -= SFMMU_MAX_HME_REGIONS;
14917 				rgnp = srdp->srd_ismrgnp[rid];
14918 				ASSERT(rgnp->rgn_id == rid);
14919 				ASSERT(rgnp->rgn_refcnt > 0);
14920 
14921 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14922 				ASSERT(ism_hatid->sfmmu_ismhat);
14923 				ism_ment = &scdp->scd_ism_links[rid];
14924 				ism_ment->iment_hat = scsfmmup;
14925 				ism_ment->iment_base_va = rgnp->rgn_saddr;
14926 				mutex_enter(&ism_mlist_lock);
14927 				iment_add(ism_ment, ism_hatid);
14928 				mutex_exit(&ism_mlist_lock);
14929 
14930 			}
14931 		}
14932 	}
14933 }
14934 /*
14935  * Unlink scd sfmmu from ism or hme region list for each region in the
14936  * scd region map.
14937  */
14938 void
14939 sfmmu_unlink_scd_from_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14940 {
14941 	uint_t rid;
14942 	uint_t i;
14943 	uint_t j;
14944 	ulong_t w;
14945 	sf_region_t *rgnp;
14946 	sfmmu_t *scsfmmup;
14947 
14948 	scsfmmup = scdp->scd_sfmmup;
14949 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14950 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14951 			continue;
14952 		}
14953 		j = 0;
14954 		while (w) {
14955 			if (!(w & 0x1)) {
14956 				j++;
14957 				w >>= 1;
14958 				continue;
14959 			}
14960 			rid = (i << BT_ULSHIFT) | j;
14961 			j++;
14962 			w >>= 1;
14963 
14964 			if (rid < SFMMU_MAX_HME_REGIONS) {
14965 				rgnp = srdp->srd_hmergnp[rid];
14966 				ASSERT(rgnp->rgn_id == rid);
14967 				ASSERT(rgnp->rgn_refcnt > 0);
14968 				sfmmu_unlink_from_hmeregion(scsfmmup,
14969 				    rgnp);
14970 
14971 			} else {
14972 				sfmmu_t *ism_hatid = NULL;
14973 				ism_ment_t *ism_ment;
14974 				rid -= SFMMU_MAX_HME_REGIONS;
14975 				rgnp = srdp->srd_ismrgnp[rid];
14976 				ASSERT(rgnp->rgn_id == rid);
14977 				ASSERT(rgnp->rgn_refcnt > 0);
14978 
14979 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14980 				ASSERT(ism_hatid->sfmmu_ismhat);
14981 				ism_ment = &scdp->scd_ism_links[rid];
14982 				ASSERT(ism_ment->iment_hat == scdp->scd_sfmmup);
14983 				ASSERT(ism_ment->iment_base_va ==
14984 				    rgnp->rgn_saddr);
14985 				mutex_enter(&ism_mlist_lock);
14986 				iment_sub(ism_ment, ism_hatid);
14987 				mutex_exit(&ism_mlist_lock);
14988 
14989 			}
14990 		}
14991 	}
14992 }
14993 /*
14994  * Allocates and initialises a new SCD structure, this is called with
14995  * the srd_scd_mutex held and returns with the reference count
14996  * initialised to 1.
14997  */
14998 static sf_scd_t *
14999 sfmmu_alloc_scd(sf_srd_t *srdp, sf_region_map_t *new_map)
15000 {
15001 	sf_scd_t *new_scdp;
15002 	sfmmu_t *scsfmmup;
15003 	int i;
15004 
15005 	ASSERT(MUTEX_HELD(&srdp->srd_scd_mutex));
15006 	new_scdp = kmem_cache_alloc(scd_cache, KM_SLEEP);
15007 
15008 	scsfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
15009 	new_scdp->scd_sfmmup = scsfmmup;
15010 	scsfmmup->sfmmu_srdp = srdp;
15011 	scsfmmup->sfmmu_scdp = new_scdp;
15012 	scsfmmup->sfmmu_tsb0_4minflcnt = 0;
15013 	scsfmmup->sfmmu_scdhat = 1;
15014 	CPUSET_ALL(scsfmmup->sfmmu_cpusran);
15015 	bzero(scsfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
15016 
15017 	ASSERT(max_mmu_ctxdoms > 0);
15018 	for (i = 0; i < max_mmu_ctxdoms; i++) {
15019 		scsfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
15020 		scsfmmup->sfmmu_ctxs[i].gnum = 0;
15021 	}
15022 
15023 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
15024 		new_scdp->scd_rttecnt[i] = 0;
15025 	}
15026 
15027 	new_scdp->scd_region_map = *new_map;
15028 	new_scdp->scd_refcnt = 1;
15029 	if (sfmmu_alloc_scd_tsbs(srdp, new_scdp) != TSB_SUCCESS) {
15030 		kmem_cache_free(scd_cache, new_scdp);
15031 		kmem_cache_free(sfmmuid_cache, scsfmmup);
15032 		return (NULL);
15033 	}
15034 	if (&mmu_init_scd) {
15035 		mmu_init_scd(new_scdp);
15036 	}
15037 	return (new_scdp);
15038 }
15039 
15040 /*
15041  * The first phase of a process joining an SCD. The hat structure is
15042  * linked to the SCD queue and then the HAT_JOIN_SCD sfmmu flag is set
15043  * and a cross-call with context invalidation is used to cause the
15044  * remaining work to be carried out in the sfmmu_tsbmiss_exception()
15045  * routine.
15046  */
15047 static void
15048 sfmmu_join_scd(sf_scd_t *scdp, sfmmu_t *sfmmup)
15049 {
15050 	hatlock_t *hatlockp;
15051 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15052 	int i;
15053 	sf_scd_t *old_scdp;
15054 
15055 	ASSERT(srdp != NULL);
15056 	ASSERT(scdp != NULL);
15057 	ASSERT(scdp->scd_refcnt > 0);
15058 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15059 
15060 	if ((old_scdp = sfmmup->sfmmu_scdp) != NULL) {
15061 		ASSERT(old_scdp != scdp);
15062 
15063 		mutex_enter(&old_scdp->scd_mutex);
15064 		sfmmu_from_scd_list(&old_scdp->scd_sf_list, sfmmup);
15065 		mutex_exit(&old_scdp->scd_mutex);
15066 		/*
15067 		 * sfmmup leaves the old scd. Update sfmmu_ttecnt to
15068 		 * include the shme rgn ttecnt for rgns that
15069 		 * were in the old SCD
15070 		 */
15071 		for (i = 0; i < mmu_page_sizes; i++) {
15072 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15073 			    old_scdp->scd_rttecnt[i]);
15074 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15075 			    sfmmup->sfmmu_scdrttecnt[i]);
15076 		}
15077 	}
15078 
15079 	/*
15080 	 * Move sfmmu to the scd lists.
15081 	 */
15082 	mutex_enter(&scdp->scd_mutex);
15083 	sfmmu_to_scd_list(&scdp->scd_sf_list, sfmmup);
15084 	mutex_exit(&scdp->scd_mutex);
15085 	SF_SCD_INCR_REF(scdp);
15086 
15087 	hatlockp = sfmmu_hat_enter(sfmmup);
15088 	/*
15089 	 * For a multi-thread process, we must stop
15090 	 * all the other threads before joining the scd.
15091 	 */
15092 
15093 	SFMMU_FLAGS_SET(sfmmup, HAT_JOIN_SCD);
15094 
15095 	sfmmu_invalidate_ctx(sfmmup);
15096 	sfmmup->sfmmu_scdp = scdp;
15097 
15098 	/*
15099 	 * Copy scd_rttecnt into sfmmup's sfmmu_scdrttecnt, and update
15100 	 * sfmmu_ttecnt to not include the rgn ttecnt just joined in SCD.
15101 	 */
15102 	for (i = 0; i < mmu_page_sizes; i++) {
15103 		sfmmup->sfmmu_scdrttecnt[i] = scdp->scd_rttecnt[i];
15104 		ASSERT(sfmmup->sfmmu_ttecnt[i] >= scdp->scd_rttecnt[i]);
15105 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15106 		    -sfmmup->sfmmu_scdrttecnt[i]);
15107 	}
15108 	/* update tsb0 inflation count */
15109 	if (old_scdp != NULL) {
15110 		sfmmup->sfmmu_tsb0_4minflcnt +=
15111 		    old_scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15112 	}
15113 	ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
15114 	    scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt);
15115 	sfmmup->sfmmu_tsb0_4minflcnt -= scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15116 
15117 	sfmmu_hat_exit(hatlockp);
15118 
15119 	if (old_scdp != NULL) {
15120 		SF_SCD_DECR_REF(srdp, old_scdp);
15121 	}
15122 
15123 }
15124 
15125 /*
15126  * This routine is called by a process to become part of an SCD. It is called
15127  * from sfmmu_tsbmiss_exception() once most of the initial work has been
15128  * done by sfmmu_join_scd(). This routine must not drop the hat lock.
15129  */
15130 static void
15131 sfmmu_finish_join_scd(sfmmu_t *sfmmup)
15132 {
15133 	struct tsb_info	*tsbinfop;
15134 
15135 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15136 	ASSERT(sfmmup->sfmmu_scdp != NULL);
15137 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD));
15138 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15139 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID));
15140 
15141 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
15142 	    tsbinfop = tsbinfop->tsb_next) {
15143 		if (tsbinfop->tsb_flags & TSB_SWAPPED) {
15144 			continue;
15145 		}
15146 		ASSERT(!(tsbinfop->tsb_flags & TSB_RELOC_FLAG));
15147 
15148 		sfmmu_inv_tsb(tsbinfop->tsb_va,
15149 		    TSB_BYTES(tsbinfop->tsb_szc));
15150 	}
15151 
15152 	/* Set HAT_CTX1_FLAG for all SCD ISMs */
15153 	sfmmu_ism_hatflags(sfmmup, 1);
15154 
15155 	SFMMU_STAT(sf_join_scd);
15156 }
15157 
15158 /*
15159  * This routine is called in order to check if there is an SCD which matches
15160  * the process's region map if not then a new SCD may be created.
15161  */
15162 static void
15163 sfmmu_find_scd(sfmmu_t *sfmmup)
15164 {
15165 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15166 	sf_scd_t *scdp, *new_scdp;
15167 	int ret;
15168 
15169 	ASSERT(srdp != NULL);
15170 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15171 
15172 	mutex_enter(&srdp->srd_scd_mutex);
15173 	for (scdp = srdp->srd_scdp; scdp != NULL;
15174 	    scdp = scdp->scd_next) {
15175 		SF_RGNMAP_EQUAL(&scdp->scd_region_map,
15176 		    &sfmmup->sfmmu_region_map, ret);
15177 		if (ret == 1) {
15178 			SF_SCD_INCR_REF(scdp);
15179 			mutex_exit(&srdp->srd_scd_mutex);
15180 			sfmmu_join_scd(scdp, sfmmup);
15181 			ASSERT(scdp->scd_refcnt >= 2);
15182 			atomic_add_32((volatile uint32_t *)
15183 			    &scdp->scd_refcnt, -1);
15184 			return;
15185 		} else {
15186 			/*
15187 			 * If the sfmmu region map is a subset of the scd
15188 			 * region map, then the assumption is that this process
15189 			 * will continue attaching to ISM segments until the
15190 			 * region maps are equal.
15191 			 */
15192 			SF_RGNMAP_IS_SUBSET(&scdp->scd_region_map,
15193 			    &sfmmup->sfmmu_region_map, ret);
15194 			if (ret == 1) {
15195 				mutex_exit(&srdp->srd_scd_mutex);
15196 				return;
15197 			}
15198 		}
15199 	}
15200 
15201 	ASSERT(scdp == NULL);
15202 	/*
15203 	 * No matching SCD has been found, create a new one.
15204 	 */
15205 	if ((new_scdp = sfmmu_alloc_scd(srdp, &sfmmup->sfmmu_region_map)) ==
15206 	    NULL) {
15207 		mutex_exit(&srdp->srd_scd_mutex);
15208 		return;
15209 	}
15210 
15211 	/*
15212 	 * sfmmu_alloc_scd() returns with a ref count of 1 on the scd.
15213 	 */
15214 
15215 	/* Set scd_rttecnt for shme rgns in SCD */
15216 	sfmmu_set_scd_rttecnt(srdp, new_scdp);
15217 
15218 	/*
15219 	 * Link scd onto srd_scdp list and scd sfmmu onto region/iment lists.
15220 	 */
15221 	sfmmu_link_scd_to_regions(srdp, new_scdp);
15222 	sfmmu_add_scd(&srdp->srd_scdp, new_scdp);
15223 	SFMMU_STAT_ADD(sf_create_scd, 1);
15224 
15225 	mutex_exit(&srdp->srd_scd_mutex);
15226 	sfmmu_join_scd(new_scdp, sfmmup);
15227 	ASSERT(new_scdp->scd_refcnt >= 2);
15228 	atomic_add_32((volatile uint32_t *)&new_scdp->scd_refcnt, -1);
15229 }
15230 
15231 /*
15232  * This routine is called by a process to remove itself from an SCD. It is
15233  * either called when the processes has detached from a segment or from
15234  * hat_free_start() as a result of calling exit.
15235  */
15236 static void
15237 sfmmu_leave_scd(sfmmu_t *sfmmup, uchar_t r_type)
15238 {
15239 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15240 	sf_srd_t *srdp =  sfmmup->sfmmu_srdp;
15241 	hatlock_t *hatlockp = TSB_HASH(sfmmup);
15242 	int i;
15243 
15244 	ASSERT(scdp != NULL);
15245 	ASSERT(srdp != NULL);
15246 
15247 	if (sfmmup->sfmmu_free) {
15248 		/*
15249 		 * If the process is part of an SCD the sfmmu is unlinked
15250 		 * from scd_sf_list.
15251 		 */
15252 		mutex_enter(&scdp->scd_mutex);
15253 		sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15254 		mutex_exit(&scdp->scd_mutex);
15255 		/*
15256 		 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15257 		 * are about to leave the SCD
15258 		 */
15259 		for (i = 0; i < mmu_page_sizes; i++) {
15260 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15261 			    scdp->scd_rttecnt[i]);
15262 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15263 			    sfmmup->sfmmu_scdrttecnt[i]);
15264 			sfmmup->sfmmu_scdrttecnt[i] = 0;
15265 		}
15266 		sfmmup->sfmmu_scdp = NULL;
15267 
15268 		SF_SCD_DECR_REF(srdp, scdp);
15269 		return;
15270 	}
15271 
15272 	ASSERT(r_type != SFMMU_REGION_ISM ||
15273 	    SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15274 	ASSERT(scdp->scd_refcnt);
15275 	ASSERT(!sfmmup->sfmmu_free);
15276 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15277 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15278 
15279 	/*
15280 	 * Wait for ISM maps to be updated.
15281 	 */
15282 	if (r_type != SFMMU_REGION_ISM) {
15283 		while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY) &&
15284 		    sfmmup->sfmmu_scdp != NULL) {
15285 			cv_wait(&sfmmup->sfmmu_tsb_cv,
15286 			    HATLOCK_MUTEXP(hatlockp));
15287 		}
15288 
15289 		if (sfmmup->sfmmu_scdp == NULL) {
15290 			sfmmu_hat_exit(hatlockp);
15291 			return;
15292 		}
15293 		SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
15294 	}
15295 
15296 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
15297 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
15298 		/*
15299 		 * Since HAT_JOIN_SCD was set our context
15300 		 * is still invalid.
15301 		 */
15302 	} else {
15303 		/*
15304 		 * For a multi-thread process, we must stop
15305 		 * all the other threads before leaving the scd.
15306 		 */
15307 
15308 		sfmmu_invalidate_ctx(sfmmup);
15309 	}
15310 
15311 	/* Clear all the rid's for ISM, delete flags, etc */
15312 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15313 	sfmmu_ism_hatflags(sfmmup, 0);
15314 
15315 	/*
15316 	 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15317 	 * are in SCD before this sfmmup leaves the SCD.
15318 	 */
15319 	for (i = 0; i < mmu_page_sizes; i++) {
15320 		ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15321 		    scdp->scd_rttecnt[i]);
15322 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15323 		    sfmmup->sfmmu_scdrttecnt[i]);
15324 		sfmmup->sfmmu_scdrttecnt[i] = 0;
15325 		/* update ismttecnt to include SCD ism before hat leaves SCD */
15326 		sfmmup->sfmmu_ismttecnt[i] += sfmmup->sfmmu_scdismttecnt[i];
15327 		sfmmup->sfmmu_scdismttecnt[i] = 0;
15328 	}
15329 	/* update tsb0 inflation count */
15330 	sfmmup->sfmmu_tsb0_4minflcnt += scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15331 
15332 	if (r_type != SFMMU_REGION_ISM) {
15333 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
15334 	}
15335 	sfmmup->sfmmu_scdp = NULL;
15336 
15337 	sfmmu_hat_exit(hatlockp);
15338 
15339 	/*
15340 	 * Unlink sfmmu from scd_sf_list this can be done without holding
15341 	 * the hat lock as we hold the sfmmu_as lock which prevents
15342 	 * hat_join_region from adding this thread to the scd again. Other
15343 	 * threads check if sfmmu_scdp is NULL under hat lock and if it's NULL
15344 	 * they won't get here, since sfmmu_leave_scd() clears sfmmu_scdp
15345 	 * while holding the hat lock.
15346 	 */
15347 	mutex_enter(&scdp->scd_mutex);
15348 	sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15349 	mutex_exit(&scdp->scd_mutex);
15350 	SFMMU_STAT(sf_leave_scd);
15351 
15352 	SF_SCD_DECR_REF(srdp, scdp);
15353 	hatlockp = sfmmu_hat_enter(sfmmup);
15354 
15355 }
15356 
15357 /*
15358  * Unlink and free up an SCD structure with a reference count of 0.
15359  */
15360 static void
15361 sfmmu_destroy_scd(sf_srd_t *srdp, sf_scd_t *scdp, sf_region_map_t *scd_rmap)
15362 {
15363 	sfmmu_t *scsfmmup;
15364 	sf_scd_t *sp;
15365 	hatlock_t *shatlockp;
15366 	int i, ret;
15367 
15368 	mutex_enter(&srdp->srd_scd_mutex);
15369 	for (sp = srdp->srd_scdp; sp != NULL; sp = sp->scd_next) {
15370 		if (sp == scdp)
15371 			break;
15372 	}
15373 	if (sp == NULL || sp->scd_refcnt) {
15374 		mutex_exit(&srdp->srd_scd_mutex);
15375 		return;
15376 	}
15377 
15378 	/*
15379 	 * It is possible that the scd has been freed and reallocated with a
15380 	 * different region map while we've been waiting for the srd_scd_mutex.
15381 	 */
15382 	SF_RGNMAP_EQUAL(scd_rmap, &sp->scd_region_map, ret);
15383 	if (ret != 1) {
15384 		mutex_exit(&srdp->srd_scd_mutex);
15385 		return;
15386 	}
15387 
15388 	ASSERT(scdp->scd_sf_list == NULL);
15389 	/*
15390 	 * Unlink scd from srd_scdp list.
15391 	 */
15392 	sfmmu_remove_scd(&srdp->srd_scdp, scdp);
15393 	mutex_exit(&srdp->srd_scd_mutex);
15394 
15395 	sfmmu_unlink_scd_from_regions(srdp, scdp);
15396 
15397 	/* Clear shared context tsb and release ctx */
15398 	scsfmmup = scdp->scd_sfmmup;
15399 
15400 	/*
15401 	 * create a barrier so that scd will not be destroyed
15402 	 * if other thread still holds the same shared hat lock.
15403 	 * E.g., sfmmu_tsbmiss_exception() needs to acquire the
15404 	 * shared hat lock before checking the shared tsb reloc flag.
15405 	 */
15406 	shatlockp = sfmmu_hat_enter(scsfmmup);
15407 	sfmmu_hat_exit(shatlockp);
15408 
15409 	sfmmu_free_scd_tsbs(scsfmmup);
15410 
15411 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
15412 		if (scsfmmup->sfmmu_hmeregion_links[i] != NULL) {
15413 			kmem_free(scsfmmup->sfmmu_hmeregion_links[i],
15414 			    SFMMU_L2_HMERLINKS_SIZE);
15415 			scsfmmup->sfmmu_hmeregion_links[i] = NULL;
15416 		}
15417 	}
15418 	kmem_cache_free(sfmmuid_cache, scsfmmup);
15419 	kmem_cache_free(scd_cache, scdp);
15420 	SFMMU_STAT(sf_destroy_scd);
15421 }
15422 
15423 /*
15424  * Modifies the HAT_CTX1_FLAG for each of the ISM segments which correspond to
15425  * bits which are set in the ism_region_map parameter. This flag indicates to
15426  * the tsbmiss handler that mapping for these segments should be loaded using
15427  * the shared context.
15428  */
15429 static void
15430 sfmmu_ism_hatflags(sfmmu_t *sfmmup, int addflag)
15431 {
15432 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15433 	ism_blk_t *ism_blkp;
15434 	ism_map_t *ism_map;
15435 	int i, rid;
15436 
15437 	ASSERT(sfmmup->sfmmu_iblk != NULL);
15438 	ASSERT(scdp != NULL);
15439 	/*
15440 	 * Note that the caller either set HAT_ISMBUSY flag or checked
15441 	 * under hat lock that HAT_ISMBUSY was not set by another thread.
15442 	 */
15443 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15444 
15445 	ism_blkp = sfmmup->sfmmu_iblk;
15446 	while (ism_blkp != NULL) {
15447 		ism_map = ism_blkp->iblk_maps;
15448 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
15449 			rid = ism_map[i].imap_rid;
15450 			if (rid == SFMMU_INVALID_ISMRID) {
15451 				continue;
15452 			}
15453 			ASSERT(rid >= 0 && rid < SFMMU_MAX_ISM_REGIONS);
15454 			if (SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid) &&
15455 			    addflag) {
15456 				ism_map[i].imap_hatflags |=
15457 				    HAT_CTX1_FLAG;
15458 			} else {
15459 				ism_map[i].imap_hatflags &=
15460 				    ~HAT_CTX1_FLAG;
15461 			}
15462 		}
15463 		ism_blkp = ism_blkp->iblk_next;
15464 	}
15465 }
15466 
15467 static int
15468 sfmmu_srd_lock_held(sf_srd_t *srdp)
15469 {
15470 	return (MUTEX_HELD(&srdp->srd_mutex));
15471 }
15472 
15473 /* ARGSUSED */
15474 static int
15475 sfmmu_scdcache_constructor(void *buf, void *cdrarg, int kmflags)
15476 {
15477 	sf_scd_t *scdp = (sf_scd_t *)buf;
15478 
15479 	bzero(buf, sizeof (sf_scd_t));
15480 	mutex_init(&scdp->scd_mutex, NULL, MUTEX_DEFAULT, NULL);
15481 	return (0);
15482 }
15483 
15484 /* ARGSUSED */
15485 static void
15486 sfmmu_scdcache_destructor(void *buf, void *cdrarg)
15487 {
15488 	sf_scd_t *scdp = (sf_scd_t *)buf;
15489 
15490 	mutex_destroy(&scdp->scd_mutex);
15491 }
15492 
15493 /*
15494  * The listp parameter is a pointer to a list of hmeblks which are partially
15495  * freed as result of calling sfmmu_hblk_hash_rm(), the last phase of the
15496  * freeing process is to cross-call all cpus to ensure that there are no
15497  * remaining cached references.
15498  *
15499  * If the local generation number is less than the global then we can free
15500  * hmeblks which are already on the pending queue as another cpu has completed
15501  * the cross-call.
15502  *
15503  * We cross-call to make sure that there are no threads on other cpus accessing
15504  * these hmblks and then complete the process of freeing them under the
15505  * following conditions:
15506  * 	The total number of pending hmeblks is greater than the threshold
15507  *	The reserve list has fewer than HBLK_RESERVE_CNT hmeblks
15508  *	It is at least 1 second since the last time we cross-called
15509  *
15510  * Otherwise, we add the hmeblks to the per-cpu pending queue.
15511  */
15512 static void
15513 sfmmu_hblks_list_purge(struct hme_blk **listp, int dontfree)
15514 {
15515 	struct hme_blk *hblkp, *pr_hblkp = NULL;
15516 	int		count = 0;
15517 	cpuset_t	cpuset = cpu_ready_set;
15518 	cpu_hme_pend_t	*cpuhp;
15519 	timestruc_t	now;
15520 	int		one_second_expired = 0;
15521 
15522 	gethrestime_lasttick(&now);
15523 
15524 	for (hblkp = *listp; hblkp != NULL; hblkp = hblkp->hblk_next) {
15525 		ASSERT(hblkp->hblk_shw_bit == 0);
15526 		ASSERT(hblkp->hblk_shared == 0);
15527 		count++;
15528 		pr_hblkp = hblkp;
15529 	}
15530 
15531 	cpuhp = &cpu_hme_pend[CPU->cpu_seqid];
15532 	mutex_enter(&cpuhp->chp_mutex);
15533 
15534 	if ((cpuhp->chp_count + count) == 0) {
15535 		mutex_exit(&cpuhp->chp_mutex);
15536 		return;
15537 	}
15538 
15539 	if ((now.tv_sec - cpuhp->chp_timestamp) > 1) {
15540 		one_second_expired  = 1;
15541 	}
15542 
15543 	if (!dontfree && (freehblkcnt < HBLK_RESERVE_CNT ||
15544 	    (cpuhp->chp_count + count) > cpu_hme_pend_thresh ||
15545 	    one_second_expired)) {
15546 		/* Append global list to local */
15547 		if (pr_hblkp == NULL) {
15548 			*listp = cpuhp->chp_listp;
15549 		} else {
15550 			pr_hblkp->hblk_next = cpuhp->chp_listp;
15551 		}
15552 		cpuhp->chp_listp = NULL;
15553 		cpuhp->chp_count = 0;
15554 		cpuhp->chp_timestamp = now.tv_sec;
15555 		mutex_exit(&cpuhp->chp_mutex);
15556 
15557 		kpreempt_disable();
15558 		CPUSET_DEL(cpuset, CPU->cpu_id);
15559 		xt_sync(cpuset);
15560 		xt_sync(cpuset);
15561 		kpreempt_enable();
15562 
15563 		/*
15564 		 * At this stage we know that no trap handlers on other
15565 		 * cpus can have references to hmeblks on the list.
15566 		 */
15567 		sfmmu_hblk_free(listp);
15568 	} else if (*listp != NULL) {
15569 		pr_hblkp->hblk_next = cpuhp->chp_listp;
15570 		cpuhp->chp_listp = *listp;
15571 		cpuhp->chp_count += count;
15572 		*listp = NULL;
15573 		mutex_exit(&cpuhp->chp_mutex);
15574 	} else {
15575 		mutex_exit(&cpuhp->chp_mutex);
15576 	}
15577 }
15578 
15579 /*
15580  * Add an hmeblk to the the hash list.
15581  */
15582 void
15583 sfmmu_hblk_hash_add(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15584 	uint64_t hblkpa)
15585 {
15586 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15587 #ifdef	DEBUG
15588 	if (hmebp->hmeblkp == NULL) {
15589 		ASSERT(hmebp->hmeh_nextpa == HMEBLK_ENDPA);
15590 	}
15591 #endif /* DEBUG */
15592 
15593 	hmeblkp->hblk_nextpa = hmebp->hmeh_nextpa;
15594 	/*
15595 	 * Since the TSB miss handler now does not lock the hash chain before
15596 	 * walking it, make sure that the hmeblks nextpa is globally visible
15597 	 * before we make the hmeblk globally visible by updating the chain root
15598 	 * pointer in the hash bucket.
15599 	 */
15600 	membar_producer();
15601 	hmebp->hmeh_nextpa = hblkpa;
15602 	hmeblkp->hblk_next = hmebp->hmeblkp;
15603 	hmebp->hmeblkp = hmeblkp;
15604 
15605 }
15606 
15607 /*
15608  * This function is the first part of a 2 part process to remove an hmeblk
15609  * from the hash chain. In this phase we unlink the hmeblk from the hash chain
15610  * but leave the next physical pointer unchanged. The hmeblk is then linked onto
15611  * a per-cpu pending list using the virtual address pointer.
15612  *
15613  * TSB miss trap handlers that start after this phase will no longer see
15614  * this hmeblk. TSB miss handlers that still cache this hmeblk in a register
15615  * can still use it for further chain traversal because we haven't yet modifed
15616  * the next physical pointer or freed it.
15617  *
15618  * In the second phase of hmeblk removal we'll issue a barrier xcall before
15619  * we reuse or free this hmeblk. This will make sure all lingering references to
15620  * the hmeblk after first phase disappear before we finally reclaim it.
15621  * This scheme eliminates the need for TSB miss handlers to lock hmeblk chains
15622  * during their traversal.
15623  *
15624  * The hmehash_mutex must be held when calling this function.
15625  *
15626  * Input:
15627  *	 hmebp - hme hash bucket pointer
15628  *	 hmeblkp - address of hmeblk to be removed
15629  *	 pr_hblk - virtual address of previous hmeblkp
15630  *	 listp - pointer to list of hmeblks linked by virtual address
15631  *	 free_now flag - indicates that a complete removal from the hash chains
15632  *			 is necessary.
15633  *
15634  * It is inefficient to use the free_now flag as a cross-call is required to
15635  * remove a single hmeblk from the hash chain but is necessary when hmeblks are
15636  * in short supply.
15637  */
15638 void
15639 sfmmu_hblk_hash_rm(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15640     struct hme_blk *pr_hblk, struct hme_blk **listp,
15641     int free_now)
15642 {
15643 	int shw_size, vshift;
15644 	struct hme_blk *shw_hblkp;
15645 	uint_t		shw_mask, newshw_mask;
15646 	caddr_t		vaddr;
15647 	int		size;
15648 	cpuset_t cpuset = cpu_ready_set;
15649 
15650 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15651 
15652 	if (hmebp->hmeblkp == hmeblkp) {
15653 		hmebp->hmeh_nextpa = hmeblkp->hblk_nextpa;
15654 		hmebp->hmeblkp = hmeblkp->hblk_next;
15655 	} else {
15656 		pr_hblk->hblk_nextpa = hmeblkp->hblk_nextpa;
15657 		pr_hblk->hblk_next = hmeblkp->hblk_next;
15658 	}
15659 
15660 	size = get_hblk_ttesz(hmeblkp);
15661 	shw_hblkp = hmeblkp->hblk_shadow;
15662 	if (shw_hblkp) {
15663 		ASSERT(hblktosfmmu(hmeblkp) != KHATID);
15664 		ASSERT(!hmeblkp->hblk_shared);
15665 #ifdef	DEBUG
15666 		if (mmu_page_sizes == max_mmu_page_sizes) {
15667 			ASSERT(size < TTE256M);
15668 		} else {
15669 			ASSERT(size < TTE4M);
15670 		}
15671 #endif /* DEBUG */
15672 
15673 		shw_size = get_hblk_ttesz(shw_hblkp);
15674 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
15675 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
15676 		ASSERT(vshift < 8);
15677 		/*
15678 		 * Atomically clear shadow mask bit
15679 		 */
15680 		do {
15681 			shw_mask = shw_hblkp->hblk_shw_mask;
15682 			ASSERT(shw_mask & (1 << vshift));
15683 			newshw_mask = shw_mask & ~(1 << vshift);
15684 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
15685 			    shw_mask, newshw_mask);
15686 		} while (newshw_mask != shw_mask);
15687 		hmeblkp->hblk_shadow = NULL;
15688 	}
15689 	hmeblkp->hblk_shw_bit = 0;
15690 
15691 	if (hmeblkp->hblk_shared) {
15692 #ifdef	DEBUG
15693 		sf_srd_t	*srdp;
15694 		sf_region_t	*rgnp;
15695 		uint_t		rid;
15696 
15697 		srdp = hblktosrd(hmeblkp);
15698 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
15699 		rid = hmeblkp->hblk_tag.htag_rid;
15700 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
15701 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
15702 		rgnp = srdp->srd_hmergnp[rid];
15703 		ASSERT(rgnp != NULL);
15704 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
15705 #endif /* DEBUG */
15706 		hmeblkp->hblk_shared = 0;
15707 	}
15708 	if (free_now) {
15709 		kpreempt_disable();
15710 		CPUSET_DEL(cpuset, CPU->cpu_id);
15711 		xt_sync(cpuset);
15712 		xt_sync(cpuset);
15713 		kpreempt_enable();
15714 
15715 		hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
15716 		hmeblkp->hblk_next = NULL;
15717 	} else {
15718 		/* Append hmeblkp to listp for processing later. */
15719 		hmeblkp->hblk_next = *listp;
15720 		*listp = hmeblkp;
15721 	}
15722 }
15723 
15724 /*
15725  * This routine is called when memory is in short supply and returns a free
15726  * hmeblk of the requested size from the cpu pending lists.
15727  */
15728 static struct hme_blk *
15729 sfmmu_check_pending_hblks(int size)
15730 {
15731 	int i;
15732 	struct hme_blk *hmeblkp = NULL, *last_hmeblkp;
15733 	int found_hmeblk;
15734 	cpuset_t cpuset = cpu_ready_set;
15735 	cpu_hme_pend_t *cpuhp;
15736 
15737 	/* Flush cpu hblk pending queues */
15738 	for (i = 0; i < NCPU; i++) {
15739 		cpuhp = &cpu_hme_pend[i];
15740 		if (cpuhp->chp_listp != NULL)  {
15741 			mutex_enter(&cpuhp->chp_mutex);
15742 			if (cpuhp->chp_listp == NULL)  {
15743 				mutex_exit(&cpuhp->chp_mutex);
15744 				continue;
15745 			}
15746 			found_hmeblk = 0;
15747 			last_hmeblkp = NULL;
15748 			for (hmeblkp = cpuhp->chp_listp; hmeblkp != NULL;
15749 			    hmeblkp = hmeblkp->hblk_next) {
15750 				if (get_hblk_ttesz(hmeblkp) == size) {
15751 					if (last_hmeblkp == NULL) {
15752 						cpuhp->chp_listp =
15753 						    hmeblkp->hblk_next;
15754 					} else {
15755 						last_hmeblkp->hblk_next =
15756 						    hmeblkp->hblk_next;
15757 					}
15758 					ASSERT(cpuhp->chp_count > 0);
15759 					cpuhp->chp_count--;
15760 					found_hmeblk = 1;
15761 					break;
15762 				} else {
15763 					last_hmeblkp = hmeblkp;
15764 				}
15765 			}
15766 			mutex_exit(&cpuhp->chp_mutex);
15767 
15768 			if (found_hmeblk) {
15769 				kpreempt_disable();
15770 				CPUSET_DEL(cpuset, CPU->cpu_id);
15771 				xt_sync(cpuset);
15772 				xt_sync(cpuset);
15773 				kpreempt_enable();
15774 				return (hmeblkp);
15775 			}
15776 		}
15777 	}
15778 	return (NULL);
15779 }
15780