xref: /titanic_51/usr/src/uts/sfmmu/vm/hat_sfmmu.c (revision 2bd43bc76740c0fef669e90cfcaa4e3f3cb2a2f5)
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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * VM - Hardware Address Translation management for Spitfire MMU.
30  *
31  * This file implements the machine specific hardware translation
32  * needed by the VM system.  The machine independent interface is
33  * described in <vm/hat.h> while the machine dependent interface
34  * and data structures are described in <vm/hat_sfmmu.h>.
35  *
36  * The hat layer manages the address translation hardware as a cache
37  * driven by calls from the higher levels in the VM system.
38  */
39 
40 #include <sys/types.h>
41 #include <sys/kstat.h>
42 #include <vm/hat.h>
43 #include <vm/hat_sfmmu.h>
44 #include <vm/page.h>
45 #include <sys/pte.h>
46 #include <sys/systm.h>
47 #include <sys/mman.h>
48 #include <sys/sysmacros.h>
49 #include <sys/machparam.h>
50 #include <sys/vtrace.h>
51 #include <sys/kmem.h>
52 #include <sys/mmu.h>
53 #include <sys/cmn_err.h>
54 #include <sys/cpu.h>
55 #include <sys/cpuvar.h>
56 #include <sys/debug.h>
57 #include <sys/lgrp.h>
58 #include <sys/archsystm.h>
59 #include <sys/machsystm.h>
60 #include <sys/vmsystm.h>
61 #include <vm/as.h>
62 #include <vm/seg.h>
63 #include <vm/seg_kp.h>
64 #include <vm/seg_kmem.h>
65 #include <vm/seg_kpm.h>
66 #include <vm/rm.h>
67 #include <sys/t_lock.h>
68 #include <sys/obpdefs.h>
69 #include <sys/vm_machparam.h>
70 #include <sys/var.h>
71 #include <sys/trap.h>
72 #include <sys/machtrap.h>
73 #include <sys/scb.h>
74 #include <sys/bitmap.h>
75 #include <sys/machlock.h>
76 #include <sys/membar.h>
77 #include <sys/atomic.h>
78 #include <sys/cpu_module.h>
79 #include <sys/prom_debug.h>
80 #include <sys/ksynch.h>
81 #include <sys/mem_config.h>
82 #include <sys/mem_cage.h>
83 #include <vm/vm_dep.h>
84 #include <vm/xhat_sfmmu.h>
85 #include <sys/fpu/fpusystm.h>
86 #include <vm/mach_kpm.h>
87 #include <sys/callb.h>
88 
89 #ifdef	DEBUG
90 #define	SFMMU_VALIDATE_HMERID(hat, rid, saddr, len)			\
91 	if (SFMMU_IS_SHMERID_VALID(rid)) {				\
92 		caddr_t _eaddr = (saddr) + (len);			\
93 		sf_srd_t *_srdp;					\
94 		sf_region_t *_rgnp;					\
95 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			\
96 		ASSERT(SF_RGNMAP_TEST(hat->sfmmu_hmeregion_map, rid));	\
97 		ASSERT((hat) != ksfmmup);				\
98 		_srdp = (hat)->sfmmu_srdp;				\
99 		ASSERT(_srdp != NULL);					\
100 		ASSERT(_srdp->srd_refcnt != 0);				\
101 		_rgnp = _srdp->srd_hmergnp[(rid)];			\
102 		ASSERT(_rgnp != NULL && _rgnp->rgn_id == rid);		\
103 		ASSERT(_rgnp->rgn_refcnt != 0);				\
104 		ASSERT(!(_rgnp->rgn_flags & SFMMU_REGION_FREE));	\
105 		ASSERT((_rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	\
106 		    SFMMU_REGION_HME);					\
107 		ASSERT((saddr) >= _rgnp->rgn_saddr);			\
108 		ASSERT((saddr) < _rgnp->rgn_saddr + _rgnp->rgn_size);	\
109 		ASSERT(_eaddr > _rgnp->rgn_saddr);			\
110 		ASSERT(_eaddr <= _rgnp->rgn_saddr + _rgnp->rgn_size);	\
111 	}
112 
113 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid) 	 	 \
114 {						 			 \
115 		caddr_t _hsva;						 \
116 		caddr_t _heva;						 \
117 		caddr_t _rsva;					 	 \
118 		caddr_t _reva;					 	 \
119 		int	_ttesz = get_hblk_ttesz(hmeblkp);		 \
120 		int	_flagtte;					 \
121 		ASSERT((srdp)->srd_refcnt != 0);			 \
122 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			 \
123 		ASSERT((rgnp)->rgn_id == rid);				 \
124 		ASSERT(!((rgnp)->rgn_flags & SFMMU_REGION_FREE));	 \
125 		ASSERT(((rgnp)->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	 \
126 		    SFMMU_REGION_HME);					 \
127 		ASSERT(_ttesz <= (rgnp)->rgn_pgszc);			 \
128 		_hsva = (caddr_t)get_hblk_base(hmeblkp);		 \
129 		_heva = get_hblk_endaddr(hmeblkp);			 \
130 		_rsva = (caddr_t)P2ALIGN(				 \
131 		    (uintptr_t)(rgnp)->rgn_saddr, HBLK_MIN_BYTES);	 \
132 		_reva = (caddr_t)P2ROUNDUP(				 \
133 		    (uintptr_t)((rgnp)->rgn_saddr + (rgnp)->rgn_size),	 \
134 		    HBLK_MIN_BYTES);					 \
135 		ASSERT(_hsva >= _rsva);				 	 \
136 		ASSERT(_hsva < _reva);				 	 \
137 		ASSERT(_heva > _rsva);				 	 \
138 		ASSERT(_heva <= _reva);				 	 \
139 		_flagtte = (_ttesz < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ :  \
140 			_ttesz;						 \
141 		ASSERT(rgnp->rgn_hmeflags & (0x1 << _flagtte));		 \
142 }
143 
144 #else /* DEBUG */
145 #define	SFMMU_VALIDATE_HMERID(hat, rid, addr, len)
146 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid)
147 #endif /* DEBUG */
148 
149 #if defined(SF_ERRATA_57)
150 extern caddr_t errata57_limit;
151 #endif
152 
153 #define	HME8BLK_SZ_RND		((roundup(HME8BLK_SZ, sizeof (int64_t))) /  \
154 				(sizeof (int64_t)))
155 #define	HBLK_RESERVE		((struct hme_blk *)hblk_reserve)
156 
157 #define	HBLK_RESERVE_CNT	128
158 #define	HBLK_RESERVE_MIN	20
159 
160 static struct hme_blk		*freehblkp;
161 static kmutex_t			freehblkp_lock;
162 static int			freehblkcnt;
163 
164 static int64_t			hblk_reserve[HME8BLK_SZ_RND];
165 static kmutex_t			hblk_reserve_lock;
166 static kthread_t		*hblk_reserve_thread;
167 
168 static nucleus_hblk8_info_t	nucleus_hblk8;
169 static nucleus_hblk1_info_t	nucleus_hblk1;
170 
171 /*
172  * SFMMU specific hat functions
173  */
174 void	hat_pagecachectl(struct page *, int);
175 
176 /* flags for hat_pagecachectl */
177 #define	HAT_CACHE	0x1
178 #define	HAT_UNCACHE	0x2
179 #define	HAT_TMPNC	0x4
180 
181 /*
182  * Flag to allow the creation of non-cacheable translations
183  * to system memory. It is off by default. At the moment this
184  * flag is used by the ecache error injector. The error injector
185  * will turn it on when creating such a translation then shut it
186  * off when it's finished.
187  */
188 
189 int	sfmmu_allow_nc_trans = 0;
190 
191 /*
192  * Flag to disable large page support.
193  * 	value of 1 => disable all large pages.
194  *	bits 1, 2, and 3 are to disable 64K, 512K and 4M pages respectively.
195  *
196  * For example, use the value 0x4 to disable 512K pages.
197  *
198  */
199 #define	LARGE_PAGES_OFF		0x1
200 
201 /*
202  * The disable_large_pages and disable_ism_large_pages variables control
203  * hat_memload_array and the page sizes to be used by ISM and the kernel.
204  *
205  * The disable_auto_data_large_pages and disable_auto_text_large_pages variables
206  * are only used to control which OOB pages to use at upper VM segment creation
207  * time, and are set in hat_init_pagesizes and used in the map_pgsz* routines.
208  * Their values may come from platform or CPU specific code to disable page
209  * sizes that should not be used.
210  *
211  * WARNING: 512K pages are currently not supported for ISM/DISM.
212  */
213 uint_t	disable_large_pages = 0;
214 uint_t	disable_ism_large_pages = (1 << TTE512K);
215 uint_t	disable_auto_data_large_pages = 0;
216 uint_t	disable_auto_text_large_pages = 0;
217 
218 /*
219  * Private sfmmu data structures for hat management
220  */
221 static struct kmem_cache *sfmmuid_cache;
222 static struct kmem_cache *mmuctxdom_cache;
223 
224 /*
225  * Private sfmmu data structures for tsb management
226  */
227 static struct kmem_cache *sfmmu_tsbinfo_cache;
228 static struct kmem_cache *sfmmu_tsb8k_cache;
229 static struct kmem_cache *sfmmu_tsb_cache[NLGRPS_MAX];
230 static vmem_t *kmem_bigtsb_arena;
231 static vmem_t *kmem_tsb_arena;
232 
233 /*
234  * sfmmu static variables for hmeblk resource management.
235  */
236 static vmem_t *hat_memload1_arena; /* HAT translation arena for sfmmu1_cache */
237 static struct kmem_cache *sfmmu8_cache;
238 static struct kmem_cache *sfmmu1_cache;
239 static struct kmem_cache *pa_hment_cache;
240 
241 static kmutex_t 	ism_mlist_lock;	/* mutex for ism mapping list */
242 /*
243  * private data for ism
244  */
245 static struct kmem_cache *ism_blk_cache;
246 static struct kmem_cache *ism_ment_cache;
247 #define	ISMID_STARTADDR	NULL
248 
249 /*
250  * Region management data structures and function declarations.
251  */
252 
253 static void	sfmmu_leave_srd(sfmmu_t *);
254 static int	sfmmu_srdcache_constructor(void *, void *, int);
255 static void	sfmmu_srdcache_destructor(void *, void *);
256 static int	sfmmu_rgncache_constructor(void *, void *, int);
257 static void	sfmmu_rgncache_destructor(void *, void *);
258 static int	sfrgnmap_isnull(sf_region_map_t *);
259 static int	sfhmergnmap_isnull(sf_hmeregion_map_t *);
260 static int	sfmmu_scdcache_constructor(void *, void *, int);
261 static void	sfmmu_scdcache_destructor(void *, void *);
262 static void	sfmmu_rgn_cb_noop(caddr_t, caddr_t, caddr_t,
263     size_t, void *, u_offset_t);
264 
265 static uint_t srd_hashmask = SFMMU_MAX_SRD_BUCKETS - 1;
266 static sf_srd_bucket_t *srd_buckets;
267 static struct kmem_cache *srd_cache;
268 static uint_t srd_rgn_hashmask = SFMMU_MAX_REGION_BUCKETS - 1;
269 static struct kmem_cache *region_cache;
270 static struct kmem_cache *scd_cache;
271 
272 #ifdef sun4v
273 int use_bigtsb_arena = 1;
274 #else
275 int use_bigtsb_arena = 0;
276 #endif
277 
278 /* External /etc/system tunable, for turning on&off the shctx support */
279 int disable_shctx = 0;
280 /* Internal variable, set by MD if the HW supports shctx feature */
281 int shctx_on = 0;
282 
283 #ifdef DEBUG
284 static void check_scd_sfmmu_list(sfmmu_t **, sfmmu_t *, int);
285 #endif
286 static void sfmmu_to_scd_list(sfmmu_t **, sfmmu_t *);
287 static void sfmmu_from_scd_list(sfmmu_t **, sfmmu_t *);
288 
289 static sf_scd_t *sfmmu_alloc_scd(sf_srd_t *, sf_region_map_t *);
290 static void sfmmu_find_scd(sfmmu_t *);
291 static void sfmmu_join_scd(sf_scd_t *, sfmmu_t *);
292 static void sfmmu_finish_join_scd(sfmmu_t *);
293 static void sfmmu_leave_scd(sfmmu_t *, uchar_t);
294 static void sfmmu_destroy_scd(sf_srd_t *, sf_scd_t *, sf_region_map_t *);
295 static int sfmmu_alloc_scd_tsbs(sf_srd_t *, sf_scd_t *);
296 static void sfmmu_free_scd_tsbs(sfmmu_t *);
297 static void sfmmu_tsb_inv_ctx(sfmmu_t *);
298 static int find_ism_rid(sfmmu_t *, sfmmu_t *, caddr_t, uint_t *);
299 static void sfmmu_ism_hatflags(sfmmu_t *, int);
300 static int sfmmu_srd_lock_held(sf_srd_t *);
301 static void sfmmu_remove_scd(sf_scd_t **, sf_scd_t *);
302 static void sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *);
303 static void sfmmu_link_scd_to_regions(sf_srd_t *, sf_scd_t *);
304 static void sfmmu_unlink_scd_from_regions(sf_srd_t *, sf_scd_t *);
305 static void sfmmu_link_to_hmeregion(sfmmu_t *, sf_region_t *);
306 static void sfmmu_unlink_from_hmeregion(sfmmu_t *, sf_region_t *);
307 
308 /*
309  * ``hat_lock'' is a hashed mutex lock for protecting sfmmu TSB lists,
310  * HAT flags, synchronizing TLB/TSB coherency, and context management.
311  * The lock is hashed on the sfmmup since the case where we need to lock
312  * all processes is rare but does occur (e.g. we need to unload a shared
313  * mapping from all processes using the mapping).  We have a lot of buckets,
314  * and each slab of sfmmu_t's can use about a quarter of them, giving us
315  * a fairly good distribution without wasting too much space and overhead
316  * when we have to grab them all.
317  */
318 #define	SFMMU_NUM_LOCK	128		/* must be power of two */
319 hatlock_t	hat_lock[SFMMU_NUM_LOCK];
320 
321 /*
322  * Hash algorithm optimized for a small number of slabs.
323  *  7 is (highbit((sizeof sfmmu_t)) - 1)
324  * This hash algorithm is based upon the knowledge that sfmmu_t's come from a
325  * kmem_cache, and thus they will be sequential within that cache.  In
326  * addition, each new slab will have a different "color" up to cache_maxcolor
327  * which will skew the hashing for each successive slab which is allocated.
328  * If the size of sfmmu_t changed to a larger size, this algorithm may need
329  * to be revisited.
330  */
331 #define	TSB_HASH_SHIFT_BITS (7)
332 #define	PTR_HASH(x) ((uintptr_t)x >> TSB_HASH_SHIFT_BITS)
333 
334 #ifdef DEBUG
335 int tsb_hash_debug = 0;
336 #define	TSB_HASH(sfmmup)	\
337 	(tsb_hash_debug ? &hat_lock[0] : \
338 	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)])
339 #else	/* DEBUG */
340 #define	TSB_HASH(sfmmup)	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)]
341 #endif	/* DEBUG */
342 
343 
344 /* sfmmu_replace_tsb() return codes. */
345 typedef enum tsb_replace_rc {
346 	TSB_SUCCESS,
347 	TSB_ALLOCFAIL,
348 	TSB_LOSTRACE,
349 	TSB_ALREADY_SWAPPED,
350 	TSB_CANTGROW
351 } tsb_replace_rc_t;
352 
353 /*
354  * Flags for TSB allocation routines.
355  */
356 #define	TSB_ALLOC	0x01
357 #define	TSB_FORCEALLOC	0x02
358 #define	TSB_GROW	0x04
359 #define	TSB_SHRINK	0x08
360 #define	TSB_SWAPIN	0x10
361 
362 /*
363  * Support for HAT callbacks.
364  */
365 #define	SFMMU_MAX_RELOC_CALLBACKS	10
366 int sfmmu_max_cb_id = SFMMU_MAX_RELOC_CALLBACKS;
367 static id_t sfmmu_cb_nextid = 0;
368 static id_t sfmmu_tsb_cb_id;
369 struct sfmmu_callback *sfmmu_cb_table;
370 
371 /*
372  * Kernel page relocation is enabled by default for non-caged
373  * kernel pages.  This has little effect unless segkmem_reloc is
374  * set, since by default kernel memory comes from inside the
375  * kernel cage.
376  */
377 int hat_kpr_enabled = 1;
378 
379 kmutex_t	kpr_mutex;
380 kmutex_t	kpr_suspendlock;
381 kthread_t	*kreloc_thread;
382 
383 /*
384  * Enable VA->PA translation sanity checking on DEBUG kernels.
385  * Disabled by default.  This is incompatible with some
386  * drivers (error injector, RSM) so if it breaks you get
387  * to keep both pieces.
388  */
389 int hat_check_vtop = 0;
390 
391 /*
392  * Private sfmmu routines (prototypes)
393  */
394 static struct hme_blk *sfmmu_shadow_hcreate(sfmmu_t *, caddr_t, int, uint_t);
395 static struct 	hme_blk *sfmmu_hblk_alloc(sfmmu_t *, caddr_t,
396 			struct hmehash_bucket *, uint_t, hmeblk_tag, uint_t,
397 			uint_t);
398 static caddr_t	sfmmu_hblk_unload(struct hat *, struct hme_blk *, caddr_t,
399 			caddr_t, demap_range_t *, uint_t);
400 static caddr_t	sfmmu_hblk_sync(struct hat *, struct hme_blk *, caddr_t,
401 			caddr_t, int);
402 static void	sfmmu_hblk_free(struct hmehash_bucket *, struct hme_blk *,
403 			uint64_t, struct hme_blk **);
404 static void	sfmmu_hblks_list_purge(struct hme_blk **);
405 static uint_t	sfmmu_get_free_hblk(struct hme_blk **, uint_t);
406 static uint_t	sfmmu_put_free_hblk(struct hme_blk *, uint_t);
407 static struct hme_blk *sfmmu_hblk_steal(int);
408 static int	sfmmu_steal_this_hblk(struct hmehash_bucket *,
409 			struct hme_blk *, uint64_t, uint64_t,
410 			struct hme_blk *);
411 static caddr_t	sfmmu_hblk_unlock(struct hme_blk *, caddr_t, caddr_t);
412 
413 static void	hat_do_memload_array(struct hat *, caddr_t, size_t,
414 		    struct page **, uint_t, uint_t, uint_t);
415 static void	hat_do_memload(struct hat *, caddr_t, struct page *,
416 		    uint_t, uint_t, uint_t);
417 static void	sfmmu_memload_batchsmall(struct hat *, caddr_t, page_t **,
418 		    uint_t, uint_t, pgcnt_t, uint_t);
419 void		sfmmu_tteload(struct hat *, tte_t *, caddr_t, page_t *,
420 			uint_t);
421 static int	sfmmu_tteload_array(sfmmu_t *, tte_t *, caddr_t, page_t **,
422 			uint_t, uint_t);
423 static struct hmehash_bucket *sfmmu_tteload_acquire_hashbucket(sfmmu_t *,
424 					caddr_t, int, uint_t);
425 static struct hme_blk *sfmmu_tteload_find_hmeblk(sfmmu_t *,
426 			struct hmehash_bucket *, caddr_t, uint_t, uint_t,
427 			uint_t);
428 static int	sfmmu_tteload_addentry(sfmmu_t *, struct hme_blk *, tte_t *,
429 			caddr_t, page_t **, uint_t, uint_t);
430 static void	sfmmu_tteload_release_hashbucket(struct hmehash_bucket *);
431 
432 static int	sfmmu_pagearray_setup(caddr_t, page_t **, tte_t *, int);
433 static pfn_t	sfmmu_uvatopfn(caddr_t, sfmmu_t *, tte_t *);
434 void		sfmmu_memtte(tte_t *, pfn_t, uint_t, int);
435 #ifdef VAC
436 static void	sfmmu_vac_conflict(struct hat *, caddr_t, page_t *);
437 static int	sfmmu_vacconflict_array(caddr_t, page_t *, int *);
438 int	tst_tnc(page_t *pp, pgcnt_t);
439 void	conv_tnc(page_t *pp, int);
440 #endif
441 
442 static void	sfmmu_get_ctx(sfmmu_t *);
443 static void	sfmmu_free_sfmmu(sfmmu_t *);
444 
445 static void	sfmmu_ttesync(struct hat *, caddr_t, tte_t *, page_t *);
446 static void	sfmmu_chgattr(struct hat *, caddr_t, size_t, uint_t, int);
447 
448 cpuset_t	sfmmu_pageunload(page_t *, struct sf_hment *, int);
449 static void	hat_pagereload(struct page *, struct page *);
450 static cpuset_t	sfmmu_pagesync(page_t *, struct sf_hment *, uint_t);
451 #ifdef VAC
452 void	sfmmu_page_cache_array(page_t *, int, int, pgcnt_t);
453 static void	sfmmu_page_cache(page_t *, int, int, int);
454 #endif
455 
456 cpuset_t	sfmmu_rgntlb_demap(caddr_t, sf_region_t *,
457     struct hme_blk *, int);
458 static void	sfmmu_tlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
459 			pfn_t, int, int, int, int);
460 static void	sfmmu_ismtlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
461 			pfn_t, int);
462 static void	sfmmu_tlb_demap(caddr_t, sfmmu_t *, struct hme_blk *, int, int);
463 static void	sfmmu_tlb_range_demap(demap_range_t *);
464 static void	sfmmu_invalidate_ctx(sfmmu_t *);
465 static void	sfmmu_sync_mmustate(sfmmu_t *);
466 
467 static void 	sfmmu_tsbinfo_setup_phys(struct tsb_info *, pfn_t);
468 static int	sfmmu_tsbinfo_alloc(struct tsb_info **, int, int, uint_t,
469 			sfmmu_t *);
470 static void	sfmmu_tsb_free(struct tsb_info *);
471 static void	sfmmu_tsbinfo_free(struct tsb_info *);
472 static int	sfmmu_init_tsbinfo(struct tsb_info *, int, int, uint_t,
473 			sfmmu_t *);
474 static void	sfmmu_tsb_chk_reloc(sfmmu_t *, hatlock_t *);
475 static void	sfmmu_tsb_swapin(sfmmu_t *, hatlock_t *);
476 static int	sfmmu_select_tsb_szc(pgcnt_t);
477 static void	sfmmu_mod_tsb(sfmmu_t *, caddr_t, tte_t *, int);
478 #define		sfmmu_load_tsb(sfmmup, vaddr, tte, szc) \
479 	sfmmu_mod_tsb(sfmmup, vaddr, tte, szc)
480 #define		sfmmu_unload_tsb(sfmmup, vaddr, szc)    \
481 	sfmmu_mod_tsb(sfmmup, vaddr, NULL, szc)
482 static void	sfmmu_copy_tsb(struct tsb_info *, struct tsb_info *);
483 static tsb_replace_rc_t sfmmu_replace_tsb(sfmmu_t *, struct tsb_info *, uint_t,
484     hatlock_t *, uint_t);
485 static void	sfmmu_size_tsb(sfmmu_t *, int, uint64_t, uint64_t, int);
486 
487 #ifdef VAC
488 void	sfmmu_cache_flush(pfn_t, int);
489 void	sfmmu_cache_flushcolor(int, pfn_t);
490 #endif
491 static caddr_t	sfmmu_hblk_chgattr(sfmmu_t *, struct hme_blk *, caddr_t,
492 			caddr_t, demap_range_t *, uint_t, int);
493 
494 static uint64_t	sfmmu_vtop_attr(uint_t, int mode, tte_t *);
495 static uint_t	sfmmu_ptov_attr(tte_t *);
496 static caddr_t	sfmmu_hblk_chgprot(sfmmu_t *, struct hme_blk *, caddr_t,
497 			caddr_t, demap_range_t *, uint_t);
498 static uint_t	sfmmu_vtop_prot(uint_t, uint_t *);
499 static int	sfmmu_idcache_constructor(void *, void *, int);
500 static void	sfmmu_idcache_destructor(void *, void *);
501 static int	sfmmu_hblkcache_constructor(void *, void *, int);
502 static void	sfmmu_hblkcache_destructor(void *, void *);
503 static void	sfmmu_hblkcache_reclaim(void *);
504 static void	sfmmu_shadow_hcleanup(sfmmu_t *, struct hme_blk *,
505 			struct hmehash_bucket *);
506 static void	sfmmu_free_hblks(sfmmu_t *, caddr_t, caddr_t, int);
507 static void	sfmmu_cleanup_rhblk(sf_srd_t *, caddr_t, uint_t, int);
508 static void	sfmmu_unload_hmeregion_va(sf_srd_t *, uint_t, caddr_t, caddr_t,
509 			int, caddr_t *);
510 static void	sfmmu_unload_hmeregion(sf_srd_t *, sf_region_t *);
511 
512 static void	sfmmu_rm_large_mappings(page_t *, int);
513 
514 static void	hat_lock_init(void);
515 static void	hat_kstat_init(void);
516 static int	sfmmu_kstat_percpu_update(kstat_t *ksp, int rw);
517 static void	sfmmu_set_scd_rttecnt(sf_srd_t *, sf_scd_t *);
518 static	int	sfmmu_is_rgnva(sf_srd_t *, caddr_t, ulong_t, ulong_t);
519 static void	sfmmu_check_page_sizes(sfmmu_t *, int);
520 int	fnd_mapping_sz(page_t *);
521 static void	iment_add(struct ism_ment *,  struct hat *);
522 static void	iment_sub(struct ism_ment *, struct hat *);
523 static pgcnt_t	ism_tsb_entries(sfmmu_t *, int szc);
524 extern void	sfmmu_setup_tsbinfo(sfmmu_t *);
525 extern void	sfmmu_clear_utsbinfo(void);
526 
527 static void	sfmmu_ctx_wrap_around(mmu_ctx_t *);
528 
529 /* kpm globals */
530 #ifdef	DEBUG
531 /*
532  * Enable trap level tsbmiss handling
533  */
534 int	kpm_tsbmtl = 1;
535 
536 /*
537  * Flush the TLB on kpm mapout. Note: Xcalls are used (again) for the
538  * required TLB shootdowns in this case, so handle w/ care. Off by default.
539  */
540 int	kpm_tlb_flush;
541 #endif	/* DEBUG */
542 
543 static void	*sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *, size_t, int);
544 
545 #ifdef DEBUG
546 static void	sfmmu_check_hblk_flist();
547 #endif
548 
549 /*
550  * Semi-private sfmmu data structures.  Some of them are initialize in
551  * startup or in hat_init. Some of them are private but accessed by
552  * assembly code or mach_sfmmu.c
553  */
554 struct hmehash_bucket *uhme_hash;	/* user hmeblk hash table */
555 struct hmehash_bucket *khme_hash;	/* kernel hmeblk hash table */
556 uint64_t	uhme_hash_pa;		/* PA of uhme_hash */
557 uint64_t	khme_hash_pa;		/* PA of khme_hash */
558 int 		uhmehash_num;		/* # of buckets in user hash table */
559 int 		khmehash_num;		/* # of buckets in kernel hash table */
560 
561 uint_t		max_mmu_ctxdoms = 0;	/* max context domains in the system */
562 mmu_ctx_t	**mmu_ctxs_tbl;		/* global array of context domains */
563 uint64_t	mmu_saved_gnum = 0;	/* to init incoming MMUs' gnums */
564 
565 #define	DEFAULT_NUM_CTXS_PER_MMU 8192
566 static uint_t	nctxs = DEFAULT_NUM_CTXS_PER_MMU;
567 
568 int		cache;			/* describes system cache */
569 
570 caddr_t		ktsb_base;		/* kernel 8k-indexed tsb base address */
571 uint64_t	ktsb_pbase;		/* kernel 8k-indexed tsb phys address */
572 int		ktsb_szcode;		/* kernel 8k-indexed tsb size code */
573 int		ktsb_sz;		/* kernel 8k-indexed tsb size */
574 
575 caddr_t		ktsb4m_base;		/* kernel 4m-indexed tsb base address */
576 uint64_t	ktsb4m_pbase;		/* kernel 4m-indexed tsb phys address */
577 int		ktsb4m_szcode;		/* kernel 4m-indexed tsb size code */
578 int		ktsb4m_sz;		/* kernel 4m-indexed tsb size */
579 
580 uint64_t	kpm_tsbbase;		/* kernel seg_kpm 4M TSB base address */
581 int		kpm_tsbsz;		/* kernel seg_kpm 4M TSB size code */
582 uint64_t	kpmsm_tsbbase;		/* kernel seg_kpm 8K TSB base address */
583 int		kpmsm_tsbsz;		/* kernel seg_kpm 8K TSB size code */
584 
585 #ifndef sun4v
586 int		utsb_dtlb_ttenum = -1;	/* index in TLB for utsb locked TTE */
587 int		utsb4m_dtlb_ttenum = -1; /* index in TLB for 4M TSB TTE */
588 int		dtlb_resv_ttenum;	/* index in TLB of first reserved TTE */
589 caddr_t		utsb_vabase;		/* reserved kernel virtual memory */
590 caddr_t		utsb4m_vabase;		/* for trap handler TSB accesses */
591 #endif /* sun4v */
592 uint64_t	tsb_alloc_bytes = 0;	/* bytes allocated to TSBs */
593 vmem_t		*kmem_tsb_default_arena[NLGRPS_MAX];	/* For dynamic TSBs */
594 vmem_t		*kmem_bigtsb_default_arena[NLGRPS_MAX]; /* dynamic 256M TSBs */
595 
596 /*
597  * Size to use for TSB slabs.  Future platforms that support page sizes
598  * larger than 4M may wish to change these values, and provide their own
599  * assembly macros for building and decoding the TSB base register contents.
600  * Note disable_large_pages will override the value set here.
601  */
602 static	uint_t tsb_slab_ttesz = TTE4M;
603 size_t	tsb_slab_size = MMU_PAGESIZE4M;
604 uint_t	tsb_slab_shift = MMU_PAGESHIFT4M;
605 /* PFN mask for TTE */
606 size_t	tsb_slab_mask = MMU_PAGEOFFSET4M >> MMU_PAGESHIFT;
607 
608 /*
609  * Size to use for TSB slabs.  These are used only when 256M tsb arenas
610  * exist.
611  */
612 static uint_t	bigtsb_slab_ttesz = TTE256M;
613 static size_t	bigtsb_slab_size = MMU_PAGESIZE256M;
614 static uint_t	bigtsb_slab_shift = MMU_PAGESHIFT256M;
615 /* 256M page alignment for 8K pfn */
616 static size_t	bigtsb_slab_mask = MMU_PAGEOFFSET256M >> MMU_PAGESHIFT;
617 
618 /* largest TSB size to grow to, will be smaller on smaller memory systems */
619 static int	tsb_max_growsize = 0;
620 
621 /*
622  * Tunable parameters dealing with TSB policies.
623  */
624 
625 /*
626  * This undocumented tunable forces all 8K TSBs to be allocated from
627  * the kernel heap rather than from the kmem_tsb_default_arena arenas.
628  */
629 #ifdef	DEBUG
630 int	tsb_forceheap = 0;
631 #endif	/* DEBUG */
632 
633 /*
634  * Decide whether to use per-lgroup arenas, or one global set of
635  * TSB arenas.  The default is not to break up per-lgroup, since
636  * most platforms don't recognize any tangible benefit from it.
637  */
638 int	tsb_lgrp_affinity = 0;
639 
640 /*
641  * Used for growing the TSB based on the process RSS.
642  * tsb_rss_factor is based on the smallest TSB, and is
643  * shifted by the TSB size to determine if we need to grow.
644  * The default will grow the TSB if the number of TTEs for
645  * this page size exceeds 75% of the number of TSB entries,
646  * which should _almost_ eliminate all conflict misses
647  * (at the expense of using up lots and lots of memory).
648  */
649 #define	TSB_RSS_FACTOR		(TSB_ENTRIES(TSB_MIN_SZCODE) * 0.75)
650 #define	SFMMU_RSS_TSBSIZE(tsbszc)	(tsb_rss_factor << tsbszc)
651 #define	SELECT_TSB_SIZECODE(pgcnt) ( \
652 	(enable_tsb_rss_sizing)? sfmmu_select_tsb_szc(pgcnt) : \
653 	default_tsb_size)
654 #define	TSB_OK_SHRINK()	\
655 	(tsb_alloc_bytes > tsb_alloc_hiwater || freemem < desfree)
656 #define	TSB_OK_GROW()	\
657 	(tsb_alloc_bytes < tsb_alloc_hiwater && freemem > desfree)
658 
659 int	enable_tsb_rss_sizing = 1;
660 int	tsb_rss_factor	= (int)TSB_RSS_FACTOR;
661 
662 /* which TSB size code to use for new address spaces or if rss sizing off */
663 int default_tsb_size = TSB_8K_SZCODE;
664 
665 static uint64_t tsb_alloc_hiwater; /* limit TSB reserved memory */
666 uint64_t tsb_alloc_hiwater_factor; /* tsb_alloc_hiwater = physmem / this */
667 #define	TSB_ALLOC_HIWATER_FACTOR_DEFAULT	32
668 
669 #ifdef DEBUG
670 static int tsb_random_size = 0;	/* set to 1 to test random tsb sizes on alloc */
671 static int tsb_grow_stress = 0;	/* if set to 1, keep replacing TSB w/ random */
672 static int tsb_alloc_mtbf = 0;	/* fail allocation every n attempts */
673 static int tsb_alloc_fail_mtbf = 0;
674 static int tsb_alloc_count = 0;
675 #endif /* DEBUG */
676 
677 /* if set to 1, will remap valid TTEs when growing TSB. */
678 int tsb_remap_ttes = 1;
679 
680 /*
681  * If we have more than this many mappings, allocate a second TSB.
682  * This default is chosen because the I/D fully associative TLBs are
683  * assumed to have at least 8 available entries. Platforms with a
684  * larger fully-associative TLB could probably override the default.
685  */
686 
687 #ifdef sun4v
688 int tsb_sectsb_threshold = 0;
689 #else
690 int tsb_sectsb_threshold = 8;
691 #endif
692 
693 /*
694  * kstat data
695  */
696 struct sfmmu_global_stat sfmmu_global_stat;
697 struct sfmmu_tsbsize_stat sfmmu_tsbsize_stat;
698 
699 /*
700  * Global data
701  */
702 sfmmu_t 	*ksfmmup;		/* kernel's hat id */
703 
704 #ifdef DEBUG
705 static void	chk_tte(tte_t *, tte_t *, tte_t *, struct hme_blk *);
706 #endif
707 
708 /* sfmmu locking operations */
709 static kmutex_t *sfmmu_mlspl_enter(struct page *, int);
710 static int	sfmmu_mlspl_held(struct page *, int);
711 
712 kmutex_t *sfmmu_page_enter(page_t *);
713 void	sfmmu_page_exit(kmutex_t *);
714 int	sfmmu_page_spl_held(struct page *);
715 
716 /* sfmmu internal locking operations - accessed directly */
717 static void	sfmmu_mlist_reloc_enter(page_t *, page_t *,
718 				kmutex_t **, kmutex_t **);
719 static void	sfmmu_mlist_reloc_exit(kmutex_t *, kmutex_t *);
720 static hatlock_t *
721 		sfmmu_hat_enter(sfmmu_t *);
722 static hatlock_t *
723 		sfmmu_hat_tryenter(sfmmu_t *);
724 static void	sfmmu_hat_exit(hatlock_t *);
725 static void	sfmmu_hat_lock_all(void);
726 static void	sfmmu_hat_unlock_all(void);
727 static void	sfmmu_ismhat_enter(sfmmu_t *, int);
728 static void	sfmmu_ismhat_exit(sfmmu_t *, int);
729 
730 /*
731  * Array of mutexes protecting a page's mapping list and p_nrm field.
732  *
733  * The hash function looks complicated, but is made up so that:
734  *
735  * "pp" not shifted, so adjacent pp values will hash to different cache lines
736  *  (8 byte alignment * 8 bytes/mutes == 64 byte coherency subblock)
737  *
738  * "pp" >> mml_shift, incorporates more source bits into the hash result
739  *
740  *  "& (mml_table_size - 1), should be faster than using remainder "%"
741  *
742  * Hopefully, mml_table, mml_table_size and mml_shift are all in the same
743  * cacheline, since they get declared next to each other below. We'll trust
744  * ld not to do something random.
745  */
746 #ifdef	DEBUG
747 int mlist_hash_debug = 0;
748 #define	MLIST_HASH(pp)	(mlist_hash_debug ? &mml_table[0] : \
749 	&mml_table[((uintptr_t)(pp) + \
750 	((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)])
751 #else	/* !DEBUG */
752 #define	MLIST_HASH(pp)   &mml_table[ \
753 	((uintptr_t)(pp) + ((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)]
754 #endif	/* !DEBUG */
755 
756 kmutex_t		*mml_table;
757 uint_t			mml_table_sz;	/* must be a power of 2 */
758 uint_t			mml_shift;	/* log2(mml_table_sz) + 3 for align */
759 
760 kpm_hlk_t	*kpmp_table;
761 uint_t		kpmp_table_sz;	/* must be a power of 2 */
762 uchar_t		kpmp_shift;
763 
764 kpm_shlk_t	*kpmp_stable;
765 uint_t		kpmp_stable_sz;	/* must be a power of 2 */
766 
767 /*
768  * SPL_HASH was improved to avoid false cache line sharing
769  */
770 #define	SPL_TABLE_SIZE	128
771 #define	SPL_MASK	(SPL_TABLE_SIZE - 1)
772 #define	SPL_SHIFT	7		/* log2(SPL_TABLE_SIZE) */
773 
774 #define	SPL_INDEX(pp) \
775 	((((uintptr_t)(pp) >> SPL_SHIFT) ^ \
776 	((uintptr_t)(pp) >> (SPL_SHIFT << 1))) & \
777 	(SPL_TABLE_SIZE - 1))
778 
779 #define	SPL_HASH(pp)    \
780 	(&sfmmu_page_lock[SPL_INDEX(pp) & SPL_MASK].pad_mutex)
781 
782 static	pad_mutex_t	sfmmu_page_lock[SPL_TABLE_SIZE];
783 
784 
785 /*
786  * hat_unload_callback() will group together callbacks in order
787  * to avoid xt_sync() calls.  This is the maximum size of the group.
788  */
789 #define	MAX_CB_ADDR	32
790 
791 tte_t	hw_tte;
792 static ulong_t sfmmu_dmr_maxbit = DMR_MAXBIT;
793 
794 static char	*mmu_ctx_kstat_names[] = {
795 	"mmu_ctx_tsb_exceptions",
796 	"mmu_ctx_tsb_raise_exception",
797 	"mmu_ctx_wrap_around",
798 };
799 
800 /*
801  * Wrapper for vmem_xalloc since vmem_create only allows limited
802  * parameters for vm_source_alloc functions.  This function allows us
803  * to specify alignment consistent with the size of the object being
804  * allocated.
805  */
806 static void *
807 sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *vmp, size_t size, int vmflag)
808 {
809 	return (vmem_xalloc(vmp, size, size, 0, 0, NULL, NULL, vmflag));
810 }
811 
812 /* Common code for setting tsb_alloc_hiwater. */
813 #define	SFMMU_SET_TSB_ALLOC_HIWATER(pages)	tsb_alloc_hiwater = \
814 		ptob(pages) / tsb_alloc_hiwater_factor
815 
816 /*
817  * Set tsb_max_growsize to allow at most all of physical memory to be mapped by
818  * a single TSB.  physmem is the number of physical pages so we need physmem 8K
819  * TTEs to represent all those physical pages.  We round this up by using
820  * 1<<highbit().  To figure out which size code to use, remember that the size
821  * code is just an amount to shift the smallest TSB size to get the size of
822  * this TSB.  So we subtract that size, TSB_START_SIZE, from highbit() (or
823  * highbit() - 1) to get the size code for the smallest TSB that can represent
824  * all of physical memory, while erring on the side of too much.
825  *
826  * If the computed size code is less than the current tsb_max_growsize, we set
827  * tsb_max_growsize to the computed size code.  In the case where the computed
828  * size code is greater than tsb_max_growsize, we have these restrictions that
829  * apply to increasing tsb_max_growsize:
830  *	1) TSBs can't grow larger than the TSB slab size
831  *	2) TSBs can't grow larger than UTSB_MAX_SZCODE.
832  */
833 #define	SFMMU_SET_TSB_MAX_GROWSIZE(pages) {				\
834 	int	_i, _szc, _slabszc, _tsbszc;				\
835 									\
836 	_i = highbit(pages);						\
837 	if ((1 << (_i - 1)) == (pages))					\
838 		_i--;		/* 2^n case, round down */              \
839 	_szc = _i - TSB_START_SIZE;					\
840 	_slabszc = bigtsb_slab_shift - (TSB_START_SIZE + TSB_ENTRY_SHIFT); \
841 	_tsbszc = MIN(_szc, _slabszc);                                  \
842 	tsb_max_growsize = MIN(_tsbszc, UTSB_MAX_SZCODE);               \
843 }
844 
845 /*
846  * Given a pointer to an sfmmu and a TTE size code, return a pointer to the
847  * tsb_info which handles that TTE size.
848  */
849 #define	SFMMU_GET_TSBINFO(tsbinfop, sfmmup, tte_szc) {			\
850 	(tsbinfop) = (sfmmup)->sfmmu_tsb;				\
851 	ASSERT(((tsbinfop)->tsb_flags & TSB_SHAREDCTX) ||		\
852 	    sfmmu_hat_lock_held(sfmmup));				\
853 	if ((tte_szc) >= TTE4M)	{					\
854 		ASSERT((tsbinfop) != NULL);				\
855 		(tsbinfop) = (tsbinfop)->tsb_next;			\
856 	}								\
857 }
858 
859 /*
860  * Macro to use to unload entries from the TSB.
861  * It has knowledge of which page sizes get replicated in the TSB
862  * and will call the appropriate unload routine for the appropriate size.
863  */
864 #define	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, ismhat)		\
865 {									\
866 	int ttesz = get_hblk_ttesz(hmeblkp);				\
867 	if (ttesz == TTE8K || ttesz == TTE4M) {				\
868 		sfmmu_unload_tsb(sfmmup, addr, ttesz);			\
869 	} else {							\
870 		caddr_t sva = ismhat ? addr : 				\
871 		    (caddr_t)get_hblk_base(hmeblkp);			\
872 		caddr_t eva = sva + get_hblk_span(hmeblkp);		\
873 		ASSERT(addr >= sva && addr < eva);			\
874 		sfmmu_unload_tsb_range(sfmmup, sva, eva, ttesz);	\
875 	}								\
876 }
877 
878 
879 /* Update tsb_alloc_hiwater after memory is configured. */
880 /*ARGSUSED*/
881 static void
882 sfmmu_update_post_add(void *arg, pgcnt_t delta_pages)
883 {
884 	/* Assumes physmem has already been updated. */
885 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
886 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
887 }
888 
889 /*
890  * Update tsb_alloc_hiwater before memory is deleted.  We'll do nothing here
891  * and update tsb_alloc_hiwater and tsb_max_growsize after the memory is
892  * deleted.
893  */
894 /*ARGSUSED*/
895 static int
896 sfmmu_update_pre_del(void *arg, pgcnt_t delta_pages)
897 {
898 	return (0);
899 }
900 
901 /* Update tsb_alloc_hiwater after memory fails to be unconfigured. */
902 /*ARGSUSED*/
903 static void
904 sfmmu_update_post_del(void *arg, pgcnt_t delta_pages, int cancelled)
905 {
906 	/*
907 	 * Whether the delete was cancelled or not, just go ahead and update
908 	 * tsb_alloc_hiwater and tsb_max_growsize.
909 	 */
910 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
911 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
912 }
913 
914 static kphysm_setup_vector_t sfmmu_update_vec = {
915 	KPHYSM_SETUP_VECTOR_VERSION,	/* version */
916 	sfmmu_update_post_add,		/* post_add */
917 	sfmmu_update_pre_del,		/* pre_del */
918 	sfmmu_update_post_del		/* post_del */
919 };
920 
921 
922 /*
923  * HME_BLK HASH PRIMITIVES
924  */
925 
926 /*
927  * Enter a hme on the mapping list for page pp.
928  * When large pages are more prevalent in the system we might want to
929  * keep the mapping list in ascending order by the hment size. For now,
930  * small pages are more frequent, so don't slow it down.
931  */
932 #define	HME_ADD(hme, pp)					\
933 {								\
934 	ASSERT(sfmmu_mlist_held(pp));				\
935 								\
936 	hme->hme_prev = NULL;					\
937 	hme->hme_next = pp->p_mapping;				\
938 	hme->hme_page = pp;					\
939 	if (pp->p_mapping) {					\
940 		((struct sf_hment *)(pp->p_mapping))->hme_prev = hme;\
941 		ASSERT(pp->p_share > 0);			\
942 	} else  {						\
943 		/* EMPTY */					\
944 		ASSERT(pp->p_share == 0);			\
945 	}							\
946 	pp->p_mapping = hme;					\
947 	pp->p_share++;						\
948 }
949 
950 /*
951  * Enter a hme on the mapping list for page pp.
952  * If we are unmapping a large translation, we need to make sure that the
953  * change is reflect in the corresponding bit of the p_index field.
954  */
955 #define	HME_SUB(hme, pp)					\
956 {								\
957 	ASSERT(sfmmu_mlist_held(pp));				\
958 	ASSERT(hme->hme_page == pp || IS_PAHME(hme));		\
959 								\
960 	if (pp->p_mapping == NULL) {				\
961 		panic("hme_remove - no mappings");		\
962 	}							\
963 								\
964 	membar_stst();	/* ensure previous stores finish */	\
965 								\
966 	ASSERT(pp->p_share > 0);				\
967 	pp->p_share--;						\
968 								\
969 	if (hme->hme_prev) {					\
970 		ASSERT(pp->p_mapping != hme);			\
971 		ASSERT(hme->hme_prev->hme_page == pp ||		\
972 			IS_PAHME(hme->hme_prev));		\
973 		hme->hme_prev->hme_next = hme->hme_next;	\
974 	} else {						\
975 		ASSERT(pp->p_mapping == hme);			\
976 		pp->p_mapping = hme->hme_next;			\
977 		ASSERT((pp->p_mapping == NULL) ?		\
978 			(pp->p_share == 0) : 1);		\
979 	}							\
980 								\
981 	if (hme->hme_next) {					\
982 		ASSERT(hme->hme_next->hme_page == pp ||		\
983 			IS_PAHME(hme->hme_next));		\
984 		hme->hme_next->hme_prev = hme->hme_prev;	\
985 	}							\
986 								\
987 	/* zero out the entry */				\
988 	hme->hme_next = NULL;					\
989 	hme->hme_prev = NULL;					\
990 	hme->hme_page = NULL;					\
991 								\
992 	if (hme_size(hme) > TTE8K) {				\
993 		/* remove mappings for remainder of large pg */	\
994 		sfmmu_rm_large_mappings(pp, hme_size(hme));	\
995 	}							\
996 }
997 
998 /*
999  * This function returns the hment given the hme_blk and a vaddr.
1000  * It assumes addr has already been checked to belong to hme_blk's
1001  * range.
1002  */
1003 #define	HBLKTOHME(hment, hmeblkp, addr)					\
1004 {									\
1005 	int index;							\
1006 	HBLKTOHME_IDX(hment, hmeblkp, addr, index)			\
1007 }
1008 
1009 /*
1010  * Version of HBLKTOHME that also returns the index in hmeblkp
1011  * of the hment.
1012  */
1013 #define	HBLKTOHME_IDX(hment, hmeblkp, addr, idx)			\
1014 {									\
1015 	ASSERT(in_hblk_range((hmeblkp), (addr)));			\
1016 									\
1017 	if (get_hblk_ttesz(hmeblkp) == TTE8K) {				\
1018 		idx = (((uintptr_t)(addr) >> MMU_PAGESHIFT) & (NHMENTS-1)); \
1019 	} else								\
1020 		idx = 0;						\
1021 									\
1022 	(hment) = &(hmeblkp)->hblk_hme[idx];				\
1023 }
1024 
1025 /*
1026  * Disable any page sizes not supported by the CPU
1027  */
1028 void
1029 hat_init_pagesizes()
1030 {
1031 	int 		i;
1032 
1033 	mmu_exported_page_sizes = 0;
1034 	for (i = TTE8K; i < max_mmu_page_sizes; i++) {
1035 
1036 		szc_2_userszc[i] = (uint_t)-1;
1037 		userszc_2_szc[i] = (uint_t)-1;
1038 
1039 		if ((mmu_exported_pagesize_mask & (1 << i)) == 0) {
1040 			disable_large_pages |= (1 << i);
1041 		} else {
1042 			szc_2_userszc[i] = mmu_exported_page_sizes;
1043 			userszc_2_szc[mmu_exported_page_sizes] = i;
1044 			mmu_exported_page_sizes++;
1045 		}
1046 	}
1047 
1048 	disable_ism_large_pages |= disable_large_pages;
1049 	disable_auto_data_large_pages = disable_large_pages;
1050 	disable_auto_text_large_pages = disable_large_pages;
1051 
1052 	/*
1053 	 * Initialize mmu-specific large page sizes.
1054 	 */
1055 	if (&mmu_large_pages_disabled) {
1056 		disable_large_pages |= mmu_large_pages_disabled(HAT_LOAD);
1057 		disable_ism_large_pages |=
1058 		    mmu_large_pages_disabled(HAT_LOAD_SHARE);
1059 		disable_auto_data_large_pages |=
1060 		    mmu_large_pages_disabled(HAT_AUTO_DATA);
1061 		disable_auto_text_large_pages |=
1062 		    mmu_large_pages_disabled(HAT_AUTO_TEXT);
1063 	}
1064 }
1065 
1066 /*
1067  * Initialize the hardware address translation structures.
1068  */
1069 void
1070 hat_init(void)
1071 {
1072 	int 		i;
1073 	uint_t		sz;
1074 	size_t		size;
1075 
1076 	hat_lock_init();
1077 	hat_kstat_init();
1078 
1079 	/*
1080 	 * Hardware-only bits in a TTE
1081 	 */
1082 	MAKE_TTE_MASK(&hw_tte);
1083 
1084 	hat_init_pagesizes();
1085 
1086 	/* Initialize the hash locks */
1087 	for (i = 0; i < khmehash_num; i++) {
1088 		mutex_init(&khme_hash[i].hmehash_mutex, NULL,
1089 		    MUTEX_DEFAULT, NULL);
1090 	}
1091 	for (i = 0; i < uhmehash_num; i++) {
1092 		mutex_init(&uhme_hash[i].hmehash_mutex, NULL,
1093 		    MUTEX_DEFAULT, NULL);
1094 	}
1095 	khmehash_num--;		/* make sure counter starts from 0 */
1096 	uhmehash_num--;		/* make sure counter starts from 0 */
1097 
1098 	/*
1099 	 * Allocate context domain structures.
1100 	 *
1101 	 * A platform may choose to modify max_mmu_ctxdoms in
1102 	 * set_platform_defaults(). If a platform does not define
1103 	 * a set_platform_defaults() or does not choose to modify
1104 	 * max_mmu_ctxdoms, it gets one MMU context domain for every CPU.
1105 	 *
1106 	 * For sun4v, there will be one global context domain, this is to
1107 	 * avoid the ldom cpu substitution problem.
1108 	 *
1109 	 * For all platforms that have CPUs sharing MMUs, this
1110 	 * value must be defined.
1111 	 */
1112 	if (max_mmu_ctxdoms == 0) {
1113 #ifndef sun4v
1114 		max_mmu_ctxdoms = max_ncpus;
1115 #else /* sun4v */
1116 		max_mmu_ctxdoms = 1;
1117 #endif /* sun4v */
1118 	}
1119 
1120 	size = max_mmu_ctxdoms * sizeof (mmu_ctx_t *);
1121 	mmu_ctxs_tbl = kmem_zalloc(size, KM_SLEEP);
1122 
1123 	/* mmu_ctx_t is 64 bytes aligned */
1124 	mmuctxdom_cache = kmem_cache_create("mmuctxdom_cache",
1125 	    sizeof (mmu_ctx_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
1126 	/*
1127 	 * MMU context domain initialization for the Boot CPU.
1128 	 * This needs the context domains array allocated above.
1129 	 */
1130 	mutex_enter(&cpu_lock);
1131 	sfmmu_cpu_init(CPU);
1132 	mutex_exit(&cpu_lock);
1133 
1134 	/*
1135 	 * Intialize ism mapping list lock.
1136 	 */
1137 
1138 	mutex_init(&ism_mlist_lock, NULL, MUTEX_DEFAULT, NULL);
1139 
1140 	/*
1141 	 * Each sfmmu structure carries an array of MMU context info
1142 	 * structures, one per context domain. The size of this array depends
1143 	 * on the maximum number of context domains. So, the size of the
1144 	 * sfmmu structure varies per platform.
1145 	 *
1146 	 * sfmmu is allocated from static arena, because trap
1147 	 * handler at TL > 0 is not allowed to touch kernel relocatable
1148 	 * memory. sfmmu's alignment is changed to 64 bytes from
1149 	 * default 8 bytes, as the lower 6 bits will be used to pass
1150 	 * pgcnt to vtag_flush_pgcnt_tl1.
1151 	 */
1152 	size = sizeof (sfmmu_t) + sizeof (sfmmu_ctx_t) * (max_mmu_ctxdoms - 1);
1153 
1154 	sfmmuid_cache = kmem_cache_create("sfmmuid_cache", size,
1155 	    64, sfmmu_idcache_constructor, sfmmu_idcache_destructor,
1156 	    NULL, NULL, static_arena, 0);
1157 
1158 	sfmmu_tsbinfo_cache = kmem_cache_create("sfmmu_tsbinfo_cache",
1159 	    sizeof (struct tsb_info), 0, NULL, NULL, NULL, NULL, NULL, 0);
1160 
1161 	/*
1162 	 * Since we only use the tsb8k cache to "borrow" pages for TSBs
1163 	 * from the heap when low on memory or when TSB_FORCEALLOC is
1164 	 * specified, don't use magazines to cache them--we want to return
1165 	 * them to the system as quickly as possible.
1166 	 */
1167 	sfmmu_tsb8k_cache = kmem_cache_create("sfmmu_tsb8k_cache",
1168 	    MMU_PAGESIZE, MMU_PAGESIZE, NULL, NULL, NULL, NULL,
1169 	    static_arena, KMC_NOMAGAZINE);
1170 
1171 	/*
1172 	 * Set tsb_alloc_hiwater to 1/tsb_alloc_hiwater_factor of physical
1173 	 * memory, which corresponds to the old static reserve for TSBs.
1174 	 * tsb_alloc_hiwater_factor defaults to 32.  This caps the amount of
1175 	 * memory we'll allocate for TSB slabs; beyond this point TSB
1176 	 * allocations will be taken from the kernel heap (via
1177 	 * sfmmu_tsb8k_cache) and will be throttled as would any other kmem
1178 	 * consumer.
1179 	 */
1180 	if (tsb_alloc_hiwater_factor == 0) {
1181 		tsb_alloc_hiwater_factor = TSB_ALLOC_HIWATER_FACTOR_DEFAULT;
1182 	}
1183 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
1184 
1185 	for (sz = tsb_slab_ttesz; sz > 0; sz--) {
1186 		if (!(disable_large_pages & (1 << sz)))
1187 			break;
1188 	}
1189 
1190 	if (sz < tsb_slab_ttesz) {
1191 		tsb_slab_ttesz = sz;
1192 		tsb_slab_shift = MMU_PAGESHIFT + (sz << 1) + sz;
1193 		tsb_slab_size = 1 << tsb_slab_shift;
1194 		tsb_slab_mask = (1 << (tsb_slab_shift - MMU_PAGESHIFT)) - 1;
1195 		use_bigtsb_arena = 0;
1196 	} else if (use_bigtsb_arena &&
1197 	    (disable_large_pages & (1 << bigtsb_slab_ttesz))) {
1198 		use_bigtsb_arena = 0;
1199 	}
1200 
1201 	if (!use_bigtsb_arena) {
1202 		bigtsb_slab_shift = tsb_slab_shift;
1203 	}
1204 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
1205 
1206 	/*
1207 	 * On smaller memory systems, allocate TSB memory in smaller chunks
1208 	 * than the default 4M slab size. We also honor disable_large_pages
1209 	 * here.
1210 	 *
1211 	 * The trap handlers need to be patched with the final slab shift,
1212 	 * since they need to be able to construct the TSB pointer at runtime.
1213 	 */
1214 	if ((tsb_max_growsize <= TSB_512K_SZCODE) &&
1215 	    !(disable_large_pages & (1 << TTE512K))) {
1216 		tsb_slab_ttesz = TTE512K;
1217 		tsb_slab_shift = MMU_PAGESHIFT512K;
1218 		tsb_slab_size = MMU_PAGESIZE512K;
1219 		tsb_slab_mask = MMU_PAGEOFFSET512K >> MMU_PAGESHIFT;
1220 		use_bigtsb_arena = 0;
1221 	}
1222 
1223 	if (!use_bigtsb_arena) {
1224 		bigtsb_slab_ttesz = tsb_slab_ttesz;
1225 		bigtsb_slab_shift = tsb_slab_shift;
1226 		bigtsb_slab_size = tsb_slab_size;
1227 		bigtsb_slab_mask = tsb_slab_mask;
1228 	}
1229 
1230 
1231 	/*
1232 	 * Set up memory callback to update tsb_alloc_hiwater and
1233 	 * tsb_max_growsize.
1234 	 */
1235 	i = kphysm_setup_func_register(&sfmmu_update_vec, (void *) 0);
1236 	ASSERT(i == 0);
1237 
1238 	/*
1239 	 * kmem_tsb_arena is the source from which large TSB slabs are
1240 	 * drawn.  The quantum of this arena corresponds to the largest
1241 	 * TSB size we can dynamically allocate for user processes.
1242 	 * Currently it must also be a supported page size since we
1243 	 * use exactly one translation entry to map each slab page.
1244 	 *
1245 	 * The per-lgroup kmem_tsb_default_arena arenas are the arenas from
1246 	 * which most TSBs are allocated.  Since most TSB allocations are
1247 	 * typically 8K we have a kmem cache we stack on top of each
1248 	 * kmem_tsb_default_arena to speed up those allocations.
1249 	 *
1250 	 * Note the two-level scheme of arenas is required only
1251 	 * because vmem_create doesn't allow us to specify alignment
1252 	 * requirements.  If this ever changes the code could be
1253 	 * simplified to use only one level of arenas.
1254 	 *
1255 	 * If 256M page support exists on sun4v, 256MB kmem_bigtsb_arena
1256 	 * will be provided in addition to the 4M kmem_tsb_arena.
1257 	 */
1258 	if (use_bigtsb_arena) {
1259 		kmem_bigtsb_arena = vmem_create("kmem_bigtsb", NULL, 0,
1260 		    bigtsb_slab_size, sfmmu_vmem_xalloc_aligned_wrapper,
1261 		    vmem_xfree, heap_arena, 0, VM_SLEEP);
1262 	}
1263 
1264 	kmem_tsb_arena = vmem_create("kmem_tsb", NULL, 0, tsb_slab_size,
1265 	    sfmmu_vmem_xalloc_aligned_wrapper,
1266 	    vmem_xfree, heap_arena, 0, VM_SLEEP);
1267 
1268 	if (tsb_lgrp_affinity) {
1269 		char s[50];
1270 		for (i = 0; i < NLGRPS_MAX; i++) {
1271 			if (use_bigtsb_arena) {
1272 				(void) sprintf(s, "kmem_bigtsb_lgrp%d", i);
1273 				kmem_bigtsb_default_arena[i] = vmem_create(s,
1274 				    NULL, 0, 2 * tsb_slab_size,
1275 				    sfmmu_tsb_segkmem_alloc,
1276 				    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena,
1277 				    0, VM_SLEEP | VM_BESTFIT);
1278 			}
1279 
1280 			(void) sprintf(s, "kmem_tsb_lgrp%d", i);
1281 			kmem_tsb_default_arena[i] = vmem_create(s,
1282 			    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1283 			    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1284 			    VM_SLEEP | VM_BESTFIT);
1285 
1286 			(void) sprintf(s, "sfmmu_tsb_lgrp%d_cache", i);
1287 			sfmmu_tsb_cache[i] = kmem_cache_create(s,
1288 			    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1289 			    kmem_tsb_default_arena[i], 0);
1290 		}
1291 	} else {
1292 		if (use_bigtsb_arena) {
1293 			kmem_bigtsb_default_arena[0] =
1294 			    vmem_create("kmem_bigtsb_default", NULL, 0,
1295 			    2 * tsb_slab_size, sfmmu_tsb_segkmem_alloc,
1296 			    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena, 0,
1297 			    VM_SLEEP | VM_BESTFIT);
1298 		}
1299 
1300 		kmem_tsb_default_arena[0] = vmem_create("kmem_tsb_default",
1301 		    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1302 		    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1303 		    VM_SLEEP | VM_BESTFIT);
1304 		sfmmu_tsb_cache[0] = kmem_cache_create("sfmmu_tsb_cache",
1305 		    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1306 		    kmem_tsb_default_arena[0], 0);
1307 	}
1308 
1309 	sfmmu8_cache = kmem_cache_create("sfmmu8_cache", HME8BLK_SZ,
1310 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1311 	    sfmmu_hblkcache_destructor,
1312 	    sfmmu_hblkcache_reclaim, (void *)HME8BLK_SZ,
1313 	    hat_memload_arena, KMC_NOHASH);
1314 
1315 	hat_memload1_arena = vmem_create("hat_memload1", NULL, 0, PAGESIZE,
1316 	    segkmem_alloc_permanent, segkmem_free, heap_arena, 0, VM_SLEEP);
1317 
1318 	sfmmu1_cache = kmem_cache_create("sfmmu1_cache", HME1BLK_SZ,
1319 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1320 	    sfmmu_hblkcache_destructor,
1321 	    NULL, (void *)HME1BLK_SZ,
1322 	    hat_memload1_arena, KMC_NOHASH);
1323 
1324 	pa_hment_cache = kmem_cache_create("pa_hment_cache", PAHME_SZ,
1325 	    0, NULL, NULL, NULL, NULL, static_arena, KMC_NOHASH);
1326 
1327 	ism_blk_cache = kmem_cache_create("ism_blk_cache",
1328 	    sizeof (ism_blk_t), ecache_alignsize, NULL, NULL,
1329 	    NULL, NULL, static_arena, KMC_NOHASH);
1330 
1331 	ism_ment_cache = kmem_cache_create("ism_ment_cache",
1332 	    sizeof (ism_ment_t), 0, NULL, NULL,
1333 	    NULL, NULL, NULL, 0);
1334 
1335 	/*
1336 	 * We grab the first hat for the kernel,
1337 	 */
1338 	AS_LOCK_ENTER(&kas, &kas.a_lock, RW_WRITER);
1339 	kas.a_hat = hat_alloc(&kas);
1340 	AS_LOCK_EXIT(&kas, &kas.a_lock);
1341 
1342 	/*
1343 	 * Initialize hblk_reserve.
1344 	 */
1345 	((struct hme_blk *)hblk_reserve)->hblk_nextpa =
1346 	    va_to_pa((caddr_t)hblk_reserve);
1347 
1348 #ifndef UTSB_PHYS
1349 	/*
1350 	 * Reserve some kernel virtual address space for the locked TTEs
1351 	 * that allow us to probe the TSB from TL>0.
1352 	 */
1353 	utsb_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1354 	    0, 0, NULL, NULL, VM_SLEEP);
1355 	utsb4m_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1356 	    0, 0, NULL, NULL, VM_SLEEP);
1357 #endif
1358 
1359 #ifdef VAC
1360 	/*
1361 	 * The big page VAC handling code assumes VAC
1362 	 * will not be bigger than the smallest big
1363 	 * page- which is 64K.
1364 	 */
1365 	if (TTEPAGES(TTE64K) < CACHE_NUM_COLOR) {
1366 		cmn_err(CE_PANIC, "VAC too big!");
1367 	}
1368 #endif
1369 
1370 	(void) xhat_init();
1371 
1372 	uhme_hash_pa = va_to_pa(uhme_hash);
1373 	khme_hash_pa = va_to_pa(khme_hash);
1374 
1375 	/*
1376 	 * Initialize relocation locks. kpr_suspendlock is held
1377 	 * at PIL_MAX to prevent interrupts from pinning the holder
1378 	 * of a suspended TTE which may access it leading to a
1379 	 * deadlock condition.
1380 	 */
1381 	mutex_init(&kpr_mutex, NULL, MUTEX_DEFAULT, NULL);
1382 	mutex_init(&kpr_suspendlock, NULL, MUTEX_SPIN, (void *)PIL_MAX);
1383 
1384 	srd_buckets = kmem_zalloc(SFMMU_MAX_SRD_BUCKETS *
1385 	    sizeof (srd_buckets[0]), KM_SLEEP);
1386 	for (i = 0; i < SFMMU_MAX_SRD_BUCKETS; i++) {
1387 		mutex_init(&srd_buckets[i].srdb_lock, NULL, MUTEX_DEFAULT,
1388 		    NULL);
1389 	}
1390 	/*
1391 	 * 64 byte alignment is required in order to isolate certain field
1392 	 * into its own cacheline.
1393 	 */
1394 	srd_cache = kmem_cache_create("srd_cache", sizeof (sf_srd_t), 64,
1395 	    sfmmu_srdcache_constructor, sfmmu_srdcache_destructor,
1396 	    NULL, NULL, NULL, 0);
1397 	region_cache = kmem_cache_create("region_cache",
1398 	    sizeof (sf_region_t), 0, sfmmu_rgncache_constructor,
1399 	    sfmmu_rgncache_destructor, NULL, NULL, NULL, 0);
1400 	scd_cache = kmem_cache_create("scd_cache", sizeof (sf_scd_t), 0,
1401 	    sfmmu_scdcache_constructor,  sfmmu_scdcache_destructor,
1402 	    NULL, NULL, NULL, 0);
1403 
1404 	/*
1405 	 * Pre-allocate hrm_hashtab before enabling the collection of
1406 	 * refmod statistics.  Allocating on the fly would mean us
1407 	 * running the risk of suffering recursive mutex enters or
1408 	 * deadlocks.
1409 	 */
1410 	hrm_hashtab = kmem_zalloc(HRM_HASHSIZE * sizeof (struct hrmstat *),
1411 	    KM_SLEEP);
1412 }
1413 
1414 /*
1415  * Initialize locking for the hat layer, called early during boot.
1416  */
1417 static void
1418 hat_lock_init()
1419 {
1420 	int i;
1421 
1422 	/*
1423 	 * initialize the array of mutexes protecting a page's mapping
1424 	 * list and p_nrm field.
1425 	 */
1426 	for (i = 0; i < mml_table_sz; i++)
1427 		mutex_init(&mml_table[i], NULL, MUTEX_DEFAULT, NULL);
1428 
1429 	if (kpm_enable) {
1430 		for (i = 0; i < kpmp_table_sz; i++) {
1431 			mutex_init(&kpmp_table[i].khl_mutex, NULL,
1432 			    MUTEX_DEFAULT, NULL);
1433 		}
1434 	}
1435 
1436 	/*
1437 	 * Initialize array of mutex locks that protects sfmmu fields and
1438 	 * TSB lists.
1439 	 */
1440 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
1441 		mutex_init(HATLOCK_MUTEXP(&hat_lock[i]), NULL, MUTEX_DEFAULT,
1442 		    NULL);
1443 }
1444 
1445 #define	SFMMU_KERNEL_MAXVA \
1446 	(kmem64_base ? (uintptr_t)kmem64_end : (SYSLIMIT))
1447 
1448 /*
1449  * Allocate a hat structure.
1450  * Called when an address space first uses a hat.
1451  */
1452 struct hat *
1453 hat_alloc(struct as *as)
1454 {
1455 	sfmmu_t *sfmmup;
1456 	int i;
1457 	uint64_t cnum;
1458 	extern uint_t get_color_start(struct as *);
1459 
1460 	ASSERT(AS_WRITE_HELD(as, &as->a_lock));
1461 	sfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
1462 	sfmmup->sfmmu_as = as;
1463 	sfmmup->sfmmu_flags = 0;
1464 	sfmmup->sfmmu_tteflags = 0;
1465 	sfmmup->sfmmu_rtteflags = 0;
1466 	LOCK_INIT_CLEAR(&sfmmup->sfmmu_ctx_lock);
1467 
1468 	if (as == &kas) {
1469 		ksfmmup = sfmmup;
1470 		sfmmup->sfmmu_cext = 0;
1471 		cnum = KCONTEXT;
1472 
1473 		sfmmup->sfmmu_clrstart = 0;
1474 		sfmmup->sfmmu_tsb = NULL;
1475 		/*
1476 		 * hat_kern_setup() will call sfmmu_init_ktsbinfo()
1477 		 * to setup tsb_info for ksfmmup.
1478 		 */
1479 	} else {
1480 
1481 		/*
1482 		 * Just set to invalid ctx. When it faults, it will
1483 		 * get a valid ctx. This would avoid the situation
1484 		 * where we get a ctx, but it gets stolen and then
1485 		 * we fault when we try to run and so have to get
1486 		 * another ctx.
1487 		 */
1488 		sfmmup->sfmmu_cext = 0;
1489 		cnum = INVALID_CONTEXT;
1490 
1491 		/* initialize original physical page coloring bin */
1492 		sfmmup->sfmmu_clrstart = get_color_start(as);
1493 #ifdef DEBUG
1494 		if (tsb_random_size) {
1495 			uint32_t randval = (uint32_t)gettick() >> 4;
1496 			int size = randval % (tsb_max_growsize + 1);
1497 
1498 			/* chose a random tsb size for stress testing */
1499 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb, size,
1500 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1501 		} else
1502 #endif /* DEBUG */
1503 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb,
1504 			    default_tsb_size,
1505 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1506 		sfmmup->sfmmu_flags = HAT_SWAPPED | HAT_ALLCTX_INVALID;
1507 		ASSERT(sfmmup->sfmmu_tsb != NULL);
1508 	}
1509 
1510 	ASSERT(max_mmu_ctxdoms > 0);
1511 	for (i = 0; i < max_mmu_ctxdoms; i++) {
1512 		sfmmup->sfmmu_ctxs[i].cnum = cnum;
1513 		sfmmup->sfmmu_ctxs[i].gnum = 0;
1514 	}
1515 
1516 	for (i = 0; i < max_mmu_page_sizes; i++) {
1517 		sfmmup->sfmmu_ttecnt[i] = 0;
1518 		sfmmup->sfmmu_scdrttecnt[i] = 0;
1519 		sfmmup->sfmmu_ismttecnt[i] = 0;
1520 		sfmmup->sfmmu_scdismttecnt[i] = 0;
1521 		sfmmup->sfmmu_pgsz[i] = TTE8K;
1522 	}
1523 	sfmmup->sfmmu_tsb0_4minflcnt = 0;
1524 	sfmmup->sfmmu_iblk = NULL;
1525 	sfmmup->sfmmu_ismhat = 0;
1526 	sfmmup->sfmmu_scdhat = 0;
1527 	sfmmup->sfmmu_ismblkpa = (uint64_t)-1;
1528 	if (sfmmup == ksfmmup) {
1529 		CPUSET_ALL(sfmmup->sfmmu_cpusran);
1530 	} else {
1531 		CPUSET_ZERO(sfmmup->sfmmu_cpusran);
1532 	}
1533 	sfmmup->sfmmu_free = 0;
1534 	sfmmup->sfmmu_rmstat = 0;
1535 	sfmmup->sfmmu_clrbin = sfmmup->sfmmu_clrstart;
1536 	sfmmup->sfmmu_xhat_provider = NULL;
1537 	cv_init(&sfmmup->sfmmu_tsb_cv, NULL, CV_DEFAULT, NULL);
1538 	sfmmup->sfmmu_srdp = NULL;
1539 	SF_RGNMAP_ZERO(sfmmup->sfmmu_region_map);
1540 	bzero(sfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
1541 	sfmmup->sfmmu_scdp = NULL;
1542 	sfmmup->sfmmu_scd_link.next = NULL;
1543 	sfmmup->sfmmu_scd_link.prev = NULL;
1544 	return (sfmmup);
1545 }
1546 
1547 /*
1548  * Create per-MMU context domain kstats for a given MMU ctx.
1549  */
1550 static void
1551 sfmmu_mmu_kstat_create(mmu_ctx_t *mmu_ctxp)
1552 {
1553 	mmu_ctx_stat_t	stat;
1554 	kstat_t		*mmu_kstat;
1555 
1556 	ASSERT(MUTEX_HELD(&cpu_lock));
1557 	ASSERT(mmu_ctxp->mmu_kstat == NULL);
1558 
1559 	mmu_kstat = kstat_create("unix", mmu_ctxp->mmu_idx, "mmu_ctx",
1560 	    "hat", KSTAT_TYPE_NAMED, MMU_CTX_NUM_STATS, KSTAT_FLAG_VIRTUAL);
1561 
1562 	if (mmu_kstat == NULL) {
1563 		cmn_err(CE_WARN, "kstat_create for MMU %d failed",
1564 		    mmu_ctxp->mmu_idx);
1565 	} else {
1566 		mmu_kstat->ks_data = mmu_ctxp->mmu_kstat_data;
1567 		for (stat = 0; stat < MMU_CTX_NUM_STATS; stat++)
1568 			kstat_named_init(&mmu_ctxp->mmu_kstat_data[stat],
1569 			    mmu_ctx_kstat_names[stat], KSTAT_DATA_INT64);
1570 		mmu_ctxp->mmu_kstat = mmu_kstat;
1571 		kstat_install(mmu_kstat);
1572 	}
1573 }
1574 
1575 /*
1576  * plat_cpuid_to_mmu_ctx_info() is a platform interface that returns MMU
1577  * context domain information for a given CPU. If a platform does not
1578  * specify that interface, then the function below is used instead to return
1579  * default information. The defaults are as follows:
1580  *
1581  *	- For sun4u systems there's one MMU context domain per CPU.
1582  *	  This default is used by all sun4u systems except OPL. OPL systems
1583  *	  provide platform specific interface to map CPU ids to MMU ids
1584  *	  because on OPL more than 1 CPU shares a single MMU.
1585  *        Note that on sun4v, there is one global context domain for
1586  *	  the entire system. This is to avoid running into potential problem
1587  *	  with ldom physical cpu substitution feature.
1588  *	- The number of MMU context IDs supported on any CPU in the
1589  *	  system is 8K.
1590  */
1591 /*ARGSUSED*/
1592 static void
1593 sfmmu_cpuid_to_mmu_ctx_info(processorid_t cpuid, mmu_ctx_info_t *infop)
1594 {
1595 	infop->mmu_nctxs = nctxs;
1596 #ifndef sun4v
1597 	infop->mmu_idx = cpu[cpuid]->cpu_seqid;
1598 #else /* sun4v */
1599 	infop->mmu_idx = 0;
1600 #endif /* sun4v */
1601 }
1602 
1603 /*
1604  * Called during CPU initialization to set the MMU context-related information
1605  * for a CPU.
1606  *
1607  * cpu_lock serializes accesses to mmu_ctxs and mmu_saved_gnum.
1608  */
1609 void
1610 sfmmu_cpu_init(cpu_t *cp)
1611 {
1612 	mmu_ctx_info_t	info;
1613 	mmu_ctx_t	*mmu_ctxp;
1614 
1615 	ASSERT(MUTEX_HELD(&cpu_lock));
1616 
1617 	if (&plat_cpuid_to_mmu_ctx_info == NULL)
1618 		sfmmu_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1619 	else
1620 		plat_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1621 
1622 	ASSERT(info.mmu_idx < max_mmu_ctxdoms);
1623 
1624 	if ((mmu_ctxp = mmu_ctxs_tbl[info.mmu_idx]) == NULL) {
1625 		/* Each mmu_ctx is cacheline aligned. */
1626 		mmu_ctxp = kmem_cache_alloc(mmuctxdom_cache, KM_SLEEP);
1627 		bzero(mmu_ctxp, sizeof (mmu_ctx_t));
1628 
1629 		mutex_init(&mmu_ctxp->mmu_lock, NULL, MUTEX_SPIN,
1630 		    (void *)ipltospl(DISP_LEVEL));
1631 		mmu_ctxp->mmu_idx = info.mmu_idx;
1632 		mmu_ctxp->mmu_nctxs = info.mmu_nctxs;
1633 		/*
1634 		 * Globally for lifetime of a system,
1635 		 * gnum must always increase.
1636 		 * mmu_saved_gnum is protected by the cpu_lock.
1637 		 */
1638 		mmu_ctxp->mmu_gnum = mmu_saved_gnum + 1;
1639 		mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
1640 
1641 		sfmmu_mmu_kstat_create(mmu_ctxp);
1642 
1643 		mmu_ctxs_tbl[info.mmu_idx] = mmu_ctxp;
1644 	} else {
1645 		ASSERT(mmu_ctxp->mmu_idx == info.mmu_idx);
1646 	}
1647 
1648 	/*
1649 	 * The mmu_lock is acquired here to prevent races with
1650 	 * the wrap-around code.
1651 	 */
1652 	mutex_enter(&mmu_ctxp->mmu_lock);
1653 
1654 
1655 	mmu_ctxp->mmu_ncpus++;
1656 	CPUSET_ADD(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1657 	CPU_MMU_IDX(cp) = info.mmu_idx;
1658 	CPU_MMU_CTXP(cp) = mmu_ctxp;
1659 
1660 	mutex_exit(&mmu_ctxp->mmu_lock);
1661 }
1662 
1663 /*
1664  * Called to perform MMU context-related cleanup for a CPU.
1665  */
1666 void
1667 sfmmu_cpu_cleanup(cpu_t *cp)
1668 {
1669 	mmu_ctx_t	*mmu_ctxp;
1670 
1671 	ASSERT(MUTEX_HELD(&cpu_lock));
1672 
1673 	mmu_ctxp = CPU_MMU_CTXP(cp);
1674 	ASSERT(mmu_ctxp != NULL);
1675 
1676 	/*
1677 	 * The mmu_lock is acquired here to prevent races with
1678 	 * the wrap-around code.
1679 	 */
1680 	mutex_enter(&mmu_ctxp->mmu_lock);
1681 
1682 	CPU_MMU_CTXP(cp) = NULL;
1683 
1684 	CPUSET_DEL(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1685 	if (--mmu_ctxp->mmu_ncpus == 0) {
1686 		mmu_ctxs_tbl[mmu_ctxp->mmu_idx] = NULL;
1687 		mutex_exit(&mmu_ctxp->mmu_lock);
1688 		mutex_destroy(&mmu_ctxp->mmu_lock);
1689 
1690 		if (mmu_ctxp->mmu_kstat)
1691 			kstat_delete(mmu_ctxp->mmu_kstat);
1692 
1693 		/* mmu_saved_gnum is protected by the cpu_lock. */
1694 		if (mmu_saved_gnum < mmu_ctxp->mmu_gnum)
1695 			mmu_saved_gnum = mmu_ctxp->mmu_gnum;
1696 
1697 		kmem_cache_free(mmuctxdom_cache, mmu_ctxp);
1698 
1699 		return;
1700 	}
1701 
1702 	mutex_exit(&mmu_ctxp->mmu_lock);
1703 }
1704 
1705 /*
1706  * Hat_setup, makes an address space context the current active one.
1707  * In sfmmu this translates to setting the secondary context with the
1708  * corresponding context.
1709  */
1710 void
1711 hat_setup(struct hat *sfmmup, int allocflag)
1712 {
1713 	hatlock_t *hatlockp;
1714 
1715 	/* Init needs some special treatment. */
1716 	if (allocflag == HAT_INIT) {
1717 		/*
1718 		 * Make sure that we have
1719 		 * 1. a TSB
1720 		 * 2. a valid ctx that doesn't get stolen after this point.
1721 		 */
1722 		hatlockp = sfmmu_hat_enter(sfmmup);
1723 
1724 		/*
1725 		 * Swap in the TSB.  hat_init() allocates tsbinfos without
1726 		 * TSBs, but we need one for init, since the kernel does some
1727 		 * special things to set up its stack and needs the TSB to
1728 		 * resolve page faults.
1729 		 */
1730 		sfmmu_tsb_swapin(sfmmup, hatlockp);
1731 
1732 		sfmmu_get_ctx(sfmmup);
1733 
1734 		sfmmu_hat_exit(hatlockp);
1735 	} else {
1736 		ASSERT(allocflag == HAT_ALLOC);
1737 
1738 		hatlockp = sfmmu_hat_enter(sfmmup);
1739 		kpreempt_disable();
1740 
1741 		CPUSET_ADD(sfmmup->sfmmu_cpusran, CPU->cpu_id);
1742 		/*
1743 		 * sfmmu_setctx_sec takes <pgsz|cnum> as a parameter,
1744 		 * pagesize bits don't matter in this case since we are passing
1745 		 * INVALID_CONTEXT to it.
1746 		 * Compatibility Note: hw takes care of MMU_SCONTEXT1
1747 		 */
1748 		sfmmu_setctx_sec(INVALID_CONTEXT);
1749 		sfmmu_clear_utsbinfo();
1750 
1751 		kpreempt_enable();
1752 		sfmmu_hat_exit(hatlockp);
1753 	}
1754 }
1755 
1756 /*
1757  * Free all the translation resources for the specified address space.
1758  * Called from as_free when an address space is being destroyed.
1759  */
1760 void
1761 hat_free_start(struct hat *sfmmup)
1762 {
1763 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
1764 	ASSERT(sfmmup != ksfmmup);
1765 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1766 
1767 	sfmmup->sfmmu_free = 1;
1768 	if (sfmmup->sfmmu_scdp != NULL) {
1769 		sfmmu_leave_scd(sfmmup, 0);
1770 	}
1771 
1772 	ASSERT(sfmmup->sfmmu_scdp == NULL);
1773 }
1774 
1775 void
1776 hat_free_end(struct hat *sfmmup)
1777 {
1778 	int i;
1779 
1780 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1781 	ASSERT(sfmmup->sfmmu_free == 1);
1782 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
1783 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
1784 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
1785 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
1786 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
1787 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
1788 
1789 	if (sfmmup->sfmmu_rmstat) {
1790 		hat_freestat(sfmmup->sfmmu_as, NULL);
1791 	}
1792 
1793 	while (sfmmup->sfmmu_tsb != NULL) {
1794 		struct tsb_info *next = sfmmup->sfmmu_tsb->tsb_next;
1795 		sfmmu_tsbinfo_free(sfmmup->sfmmu_tsb);
1796 		sfmmup->sfmmu_tsb = next;
1797 	}
1798 
1799 	if (sfmmup->sfmmu_srdp != NULL) {
1800 		sfmmu_leave_srd(sfmmup);
1801 		ASSERT(sfmmup->sfmmu_srdp == NULL);
1802 		for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1803 			if (sfmmup->sfmmu_hmeregion_links[i] != NULL) {
1804 				kmem_free(sfmmup->sfmmu_hmeregion_links[i],
1805 				    SFMMU_L2_HMERLINKS_SIZE);
1806 				sfmmup->sfmmu_hmeregion_links[i] = NULL;
1807 			}
1808 		}
1809 	}
1810 	sfmmu_free_sfmmu(sfmmup);
1811 
1812 #ifdef DEBUG
1813 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1814 		ASSERT(sfmmup->sfmmu_hmeregion_links[i] == NULL);
1815 	}
1816 #endif
1817 
1818 	kmem_cache_free(sfmmuid_cache, sfmmup);
1819 }
1820 
1821 /*
1822  * Set up any translation structures, for the specified address space,
1823  * that are needed or preferred when the process is being swapped in.
1824  */
1825 /* ARGSUSED */
1826 void
1827 hat_swapin(struct hat *hat)
1828 {
1829 	ASSERT(hat->sfmmu_xhat_provider == NULL);
1830 }
1831 
1832 /*
1833  * Free all of the translation resources, for the specified address space,
1834  * that can be freed while the process is swapped out. Called from as_swapout.
1835  * Also, free up the ctx that this process was using.
1836  */
1837 void
1838 hat_swapout(struct hat *sfmmup)
1839 {
1840 	struct hmehash_bucket *hmebp;
1841 	struct hme_blk *hmeblkp;
1842 	struct hme_blk *pr_hblk = NULL;
1843 	struct hme_blk *nx_hblk;
1844 	int i;
1845 	uint64_t hblkpa, prevpa, nx_pa;
1846 	struct hme_blk *list = NULL;
1847 	hatlock_t *hatlockp;
1848 	struct tsb_info *tsbinfop;
1849 	struct free_tsb {
1850 		struct free_tsb *next;
1851 		struct tsb_info *tsbinfop;
1852 	};			/* free list of TSBs */
1853 	struct free_tsb *freelist, *last, *next;
1854 
1855 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1856 	SFMMU_STAT(sf_swapout);
1857 
1858 	/*
1859 	 * There is no way to go from an as to all its translations in sfmmu.
1860 	 * Here is one of the times when we take the big hit and traverse
1861 	 * the hash looking for hme_blks to free up.  Not only do we free up
1862 	 * this as hme_blks but all those that are free.  We are obviously
1863 	 * swapping because we need memory so let's free up as much
1864 	 * as we can.
1865 	 *
1866 	 * Note that we don't flush TLB/TSB here -- it's not necessary
1867 	 * because:
1868 	 *  1) we free the ctx we're using and throw away the TSB(s);
1869 	 *  2) processes aren't runnable while being swapped out.
1870 	 */
1871 	ASSERT(sfmmup != KHATID);
1872 	for (i = 0; i <= UHMEHASH_SZ; i++) {
1873 		hmebp = &uhme_hash[i];
1874 		SFMMU_HASH_LOCK(hmebp);
1875 		hmeblkp = hmebp->hmeblkp;
1876 		hblkpa = hmebp->hmeh_nextpa;
1877 		prevpa = 0;
1878 		pr_hblk = NULL;
1879 		while (hmeblkp) {
1880 
1881 			ASSERT(!hmeblkp->hblk_xhat_bit);
1882 
1883 			if ((hmeblkp->hblk_tag.htag_id == sfmmup) &&
1884 			    !hmeblkp->hblk_shw_bit && !hmeblkp->hblk_lckcnt) {
1885 				ASSERT(!hmeblkp->hblk_shared);
1886 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
1887 				    (caddr_t)get_hblk_base(hmeblkp),
1888 				    get_hblk_endaddr(hmeblkp),
1889 				    NULL, HAT_UNLOAD);
1890 			}
1891 			nx_hblk = hmeblkp->hblk_next;
1892 			nx_pa = hmeblkp->hblk_nextpa;
1893 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
1894 				ASSERT(!hmeblkp->hblk_lckcnt);
1895 				sfmmu_hblk_hash_rm(hmebp, hmeblkp,
1896 				    prevpa, pr_hblk);
1897 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
1898 			} else {
1899 				pr_hblk = hmeblkp;
1900 				prevpa = hblkpa;
1901 			}
1902 			hmeblkp = nx_hblk;
1903 			hblkpa = nx_pa;
1904 		}
1905 		SFMMU_HASH_UNLOCK(hmebp);
1906 	}
1907 
1908 	sfmmu_hblks_list_purge(&list);
1909 
1910 	/*
1911 	 * Now free up the ctx so that others can reuse it.
1912 	 */
1913 	hatlockp = sfmmu_hat_enter(sfmmup);
1914 
1915 	sfmmu_invalidate_ctx(sfmmup);
1916 
1917 	/*
1918 	 * Free TSBs, but not tsbinfos, and set SWAPPED flag.
1919 	 * If TSBs were never swapped in, just return.
1920 	 * This implies that we don't support partial swapping
1921 	 * of TSBs -- either all are swapped out, or none are.
1922 	 *
1923 	 * We must hold the HAT lock here to prevent racing with another
1924 	 * thread trying to unmap TTEs from the TSB or running the post-
1925 	 * relocator after relocating the TSB's memory.  Unfortunately, we
1926 	 * can't free memory while holding the HAT lock or we could
1927 	 * deadlock, so we build a list of TSBs to be freed after marking
1928 	 * the tsbinfos as swapped out and free them after dropping the
1929 	 * lock.
1930 	 */
1931 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
1932 		sfmmu_hat_exit(hatlockp);
1933 		return;
1934 	}
1935 
1936 	SFMMU_FLAGS_SET(sfmmup, HAT_SWAPPED);
1937 	last = freelist = NULL;
1938 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
1939 	    tsbinfop = tsbinfop->tsb_next) {
1940 		ASSERT((tsbinfop->tsb_flags & TSB_SWAPPED) == 0);
1941 
1942 		/*
1943 		 * Cast the TSB into a struct free_tsb and put it on the free
1944 		 * list.
1945 		 */
1946 		if (freelist == NULL) {
1947 			last = freelist = (struct free_tsb *)tsbinfop->tsb_va;
1948 		} else {
1949 			last->next = (struct free_tsb *)tsbinfop->tsb_va;
1950 			last = last->next;
1951 		}
1952 		last->next = NULL;
1953 		last->tsbinfop = tsbinfop;
1954 		tsbinfop->tsb_flags |= TSB_SWAPPED;
1955 		/*
1956 		 * Zero out the TTE to clear the valid bit.
1957 		 * Note we can't use a value like 0xbad because we want to
1958 		 * ensure diagnostic bits are NEVER set on TTEs that might
1959 		 * be loaded.  The intent is to catch any invalid access
1960 		 * to the swapped TSB, such as a thread running with a valid
1961 		 * context without first calling sfmmu_tsb_swapin() to
1962 		 * allocate TSB memory.
1963 		 */
1964 		tsbinfop->tsb_tte.ll = 0;
1965 	}
1966 
1967 	/* Now we can drop the lock and free the TSB memory. */
1968 	sfmmu_hat_exit(hatlockp);
1969 	for (; freelist != NULL; freelist = next) {
1970 		next = freelist->next;
1971 		sfmmu_tsb_free(freelist->tsbinfop);
1972 	}
1973 }
1974 
1975 /*
1976  * Duplicate the translations of an as into another newas
1977  */
1978 /* ARGSUSED */
1979 int
1980 hat_dup(struct hat *hat, struct hat *newhat, caddr_t addr, size_t len,
1981 	uint_t flag)
1982 {
1983 	sf_srd_t *srdp;
1984 	sf_scd_t *scdp;
1985 	int i;
1986 	extern uint_t get_color_start(struct as *);
1987 
1988 	ASSERT(hat->sfmmu_xhat_provider == NULL);
1989 	ASSERT((flag == 0) || (flag == HAT_DUP_ALL) || (flag == HAT_DUP_COW) ||
1990 	    (flag == HAT_DUP_SRD));
1991 	ASSERT(hat != ksfmmup);
1992 	ASSERT(newhat != ksfmmup);
1993 	ASSERT(flag != HAT_DUP_ALL || hat->sfmmu_srdp == newhat->sfmmu_srdp);
1994 
1995 	if (flag == HAT_DUP_COW) {
1996 		panic("hat_dup: HAT_DUP_COW not supported");
1997 	}
1998 
1999 	if (flag == HAT_DUP_SRD && ((srdp = hat->sfmmu_srdp) != NULL)) {
2000 		ASSERT(srdp->srd_evp != NULL);
2001 		VN_HOLD(srdp->srd_evp);
2002 		ASSERT(srdp->srd_refcnt > 0);
2003 		newhat->sfmmu_srdp = srdp;
2004 		atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
2005 	}
2006 
2007 	/*
2008 	 * HAT_DUP_ALL flag is used after as duplication is done.
2009 	 */
2010 	if (flag == HAT_DUP_ALL && ((srdp = newhat->sfmmu_srdp) != NULL)) {
2011 		ASSERT(newhat->sfmmu_srdp->srd_refcnt >= 2);
2012 		newhat->sfmmu_rtteflags = hat->sfmmu_rtteflags;
2013 		if (hat->sfmmu_flags & HAT_4MTEXT_FLAG) {
2014 			newhat->sfmmu_flags |= HAT_4MTEXT_FLAG;
2015 		}
2016 
2017 		/* check if need to join scd */
2018 		if ((scdp = hat->sfmmu_scdp) != NULL &&
2019 		    newhat->sfmmu_scdp != scdp) {
2020 			int ret;
2021 			SF_RGNMAP_IS_SUBSET(&newhat->sfmmu_region_map,
2022 			    &scdp->scd_region_map, ret);
2023 			ASSERT(ret);
2024 			sfmmu_join_scd(scdp, newhat);
2025 			ASSERT(newhat->sfmmu_scdp == scdp &&
2026 			    scdp->scd_refcnt >= 2);
2027 			for (i = 0; i < max_mmu_page_sizes; i++) {
2028 				newhat->sfmmu_ismttecnt[i] =
2029 				    hat->sfmmu_ismttecnt[i];
2030 				newhat->sfmmu_scdismttecnt[i] =
2031 				    hat->sfmmu_scdismttecnt[i];
2032 			}
2033 		}
2034 
2035 		sfmmu_check_page_sizes(newhat, 1);
2036 	}
2037 
2038 	if (flag == HAT_DUP_ALL && consistent_coloring == 0 &&
2039 	    update_proc_pgcolorbase_after_fork != 0) {
2040 		hat->sfmmu_clrbin = get_color_start(hat->sfmmu_as);
2041 	}
2042 	return (0);
2043 }
2044 
2045 void
2046 hat_memload(struct hat *hat, caddr_t addr, struct page *pp,
2047 	uint_t attr, uint_t flags)
2048 {
2049 	hat_do_memload(hat, addr, pp, attr, flags,
2050 	    SFMMU_INVALID_SHMERID);
2051 }
2052 
2053 void
2054 hat_memload_region(struct hat *hat, caddr_t addr, struct page *pp,
2055 	uint_t attr, uint_t flags, hat_region_cookie_t rcookie)
2056 {
2057 	uint_t rid;
2058 	if (rcookie == HAT_INVALID_REGION_COOKIE ||
2059 	    hat->sfmmu_xhat_provider != NULL) {
2060 		hat_do_memload(hat, addr, pp, attr, flags,
2061 		    SFMMU_INVALID_SHMERID);
2062 		return;
2063 	}
2064 	rid = (uint_t)((uint64_t)rcookie);
2065 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2066 	hat_do_memload(hat, addr, pp, attr, flags, rid);
2067 }
2068 
2069 /*
2070  * Set up addr to map to page pp with protection prot.
2071  * As an optimization we also load the TSB with the
2072  * corresponding tte but it is no big deal if  the tte gets kicked out.
2073  */
2074 static void
2075 hat_do_memload(struct hat *hat, caddr_t addr, struct page *pp,
2076 	uint_t attr, uint_t flags, uint_t rid)
2077 {
2078 	tte_t tte;
2079 
2080 
2081 	ASSERT(hat != NULL);
2082 	ASSERT(PAGE_LOCKED(pp));
2083 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2084 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2085 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2086 	SFMMU_VALIDATE_HMERID(hat, rid, addr, MMU_PAGESIZE);
2087 
2088 	if (PP_ISFREE(pp)) {
2089 		panic("hat_memload: loading a mapping to free page %p",
2090 		    (void *)pp);
2091 	}
2092 
2093 	if (hat->sfmmu_xhat_provider) {
2094 		/* no regions for xhats */
2095 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
2096 		XHAT_MEMLOAD(hat, addr, pp, attr, flags);
2097 		return;
2098 	}
2099 
2100 	ASSERT((hat == ksfmmup) ||
2101 	    AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
2102 
2103 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2104 		cmn_err(CE_NOTE, "hat_memload: unsupported flags %d",
2105 		    flags & ~SFMMU_LOAD_ALLFLAG);
2106 
2107 	if (hat->sfmmu_rmstat)
2108 		hat_resvstat(MMU_PAGESIZE, hat->sfmmu_as, addr);
2109 
2110 #if defined(SF_ERRATA_57)
2111 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2112 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2113 	    !(flags & HAT_LOAD_SHARE)) {
2114 		cmn_err(CE_WARN, "hat_memload: illegal attempt to make user "
2115 		    " page executable");
2116 		attr &= ~PROT_EXEC;
2117 	}
2118 #endif
2119 
2120 	sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2121 	(void) sfmmu_tteload_array(hat, &tte, addr, &pp, flags, rid);
2122 
2123 	/*
2124 	 * Check TSB and TLB page sizes.
2125 	 */
2126 	if ((flags & HAT_LOAD_SHARE) == 0) {
2127 		sfmmu_check_page_sizes(hat, 1);
2128 	}
2129 }
2130 
2131 /*
2132  * hat_devload can be called to map real memory (e.g.
2133  * /dev/kmem) and even though hat_devload will determine pf is
2134  * for memory, it will be unable to get a shared lock on the
2135  * page (because someone else has it exclusively) and will
2136  * pass dp = NULL.  If tteload doesn't get a non-NULL
2137  * page pointer it can't cache memory.
2138  */
2139 void
2140 hat_devload(struct hat *hat, caddr_t addr, size_t len, pfn_t pfn,
2141 	uint_t attr, int flags)
2142 {
2143 	tte_t tte;
2144 	struct page *pp = NULL;
2145 	int use_lgpg = 0;
2146 
2147 	ASSERT(hat != NULL);
2148 
2149 	if (hat->sfmmu_xhat_provider) {
2150 		XHAT_DEVLOAD(hat, addr, len, pfn, attr, flags);
2151 		return;
2152 	}
2153 
2154 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2155 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2156 	ASSERT((hat == ksfmmup) ||
2157 	    AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
2158 	if (len == 0)
2159 		panic("hat_devload: zero len");
2160 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2161 		cmn_err(CE_NOTE, "hat_devload: unsupported flags %d",
2162 		    flags & ~SFMMU_LOAD_ALLFLAG);
2163 
2164 #if defined(SF_ERRATA_57)
2165 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2166 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2167 	    !(flags & HAT_LOAD_SHARE)) {
2168 		cmn_err(CE_WARN, "hat_devload: illegal attempt to make user "
2169 		    " page executable");
2170 		attr &= ~PROT_EXEC;
2171 	}
2172 #endif
2173 
2174 	/*
2175 	 * If it's a memory page find its pp
2176 	 */
2177 	if (!(flags & HAT_LOAD_NOCONSIST) && pf_is_memory(pfn)) {
2178 		pp = page_numtopp_nolock(pfn);
2179 		if (pp == NULL) {
2180 			flags |= HAT_LOAD_NOCONSIST;
2181 		} else {
2182 			if (PP_ISFREE(pp)) {
2183 				panic("hat_memload: loading "
2184 				    "a mapping to free page %p",
2185 				    (void *)pp);
2186 			}
2187 			if (!PAGE_LOCKED(pp) && !PP_ISNORELOC(pp)) {
2188 				panic("hat_memload: loading a mapping "
2189 				    "to unlocked relocatable page %p",
2190 				    (void *)pp);
2191 			}
2192 			ASSERT(len == MMU_PAGESIZE);
2193 		}
2194 	}
2195 
2196 	if (hat->sfmmu_rmstat)
2197 		hat_resvstat(len, hat->sfmmu_as, addr);
2198 
2199 	if (flags & HAT_LOAD_NOCONSIST) {
2200 		attr |= SFMMU_UNCACHEVTTE;
2201 		use_lgpg = 1;
2202 	}
2203 	if (!pf_is_memory(pfn)) {
2204 		attr |= SFMMU_UNCACHEPTTE | HAT_NOSYNC;
2205 		use_lgpg = 1;
2206 		switch (attr & HAT_ORDER_MASK) {
2207 			case HAT_STRICTORDER:
2208 			case HAT_UNORDERED_OK:
2209 				/*
2210 				 * we set the side effect bit for all non
2211 				 * memory mappings unless merging is ok
2212 				 */
2213 				attr |= SFMMU_SIDEFFECT;
2214 				break;
2215 			case HAT_MERGING_OK:
2216 			case HAT_LOADCACHING_OK:
2217 			case HAT_STORECACHING_OK:
2218 				break;
2219 			default:
2220 				panic("hat_devload: bad attr");
2221 				break;
2222 		}
2223 	}
2224 	while (len) {
2225 		if (!use_lgpg) {
2226 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2227 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2228 			    flags, SFMMU_INVALID_SHMERID);
2229 			len -= MMU_PAGESIZE;
2230 			addr += MMU_PAGESIZE;
2231 			pfn++;
2232 			continue;
2233 		}
2234 		/*
2235 		 *  try to use large pages, check va/pa alignments
2236 		 *  Note that 32M/256M page sizes are not (yet) supported.
2237 		 */
2238 		if ((len >= MMU_PAGESIZE4M) &&
2239 		    !((uintptr_t)addr & MMU_PAGEOFFSET4M) &&
2240 		    !(disable_large_pages & (1 << TTE4M)) &&
2241 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET4M)) {
2242 			sfmmu_memtte(&tte, pfn, attr, TTE4M);
2243 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2244 			    flags, SFMMU_INVALID_SHMERID);
2245 			len -= MMU_PAGESIZE4M;
2246 			addr += MMU_PAGESIZE4M;
2247 			pfn += MMU_PAGESIZE4M / MMU_PAGESIZE;
2248 		} else if ((len >= MMU_PAGESIZE512K) &&
2249 		    !((uintptr_t)addr & MMU_PAGEOFFSET512K) &&
2250 		    !(disable_large_pages & (1 << TTE512K)) &&
2251 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET512K)) {
2252 			sfmmu_memtte(&tte, pfn, attr, TTE512K);
2253 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2254 			    flags, SFMMU_INVALID_SHMERID);
2255 			len -= MMU_PAGESIZE512K;
2256 			addr += MMU_PAGESIZE512K;
2257 			pfn += MMU_PAGESIZE512K / MMU_PAGESIZE;
2258 		} else if ((len >= MMU_PAGESIZE64K) &&
2259 		    !((uintptr_t)addr & MMU_PAGEOFFSET64K) &&
2260 		    !(disable_large_pages & (1 << TTE64K)) &&
2261 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET64K)) {
2262 			sfmmu_memtte(&tte, pfn, attr, TTE64K);
2263 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2264 			    flags, SFMMU_INVALID_SHMERID);
2265 			len -= MMU_PAGESIZE64K;
2266 			addr += MMU_PAGESIZE64K;
2267 			pfn += MMU_PAGESIZE64K / MMU_PAGESIZE;
2268 		} else {
2269 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2270 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2271 			    flags, SFMMU_INVALID_SHMERID);
2272 			len -= MMU_PAGESIZE;
2273 			addr += MMU_PAGESIZE;
2274 			pfn++;
2275 		}
2276 	}
2277 
2278 	/*
2279 	 * Check TSB and TLB page sizes.
2280 	 */
2281 	if ((flags & HAT_LOAD_SHARE) == 0) {
2282 		sfmmu_check_page_sizes(hat, 1);
2283 	}
2284 }
2285 
2286 void
2287 hat_memload_array(struct hat *hat, caddr_t addr, size_t len,
2288 	struct page **pps, uint_t attr, uint_t flags)
2289 {
2290 	hat_do_memload_array(hat, addr, len, pps, attr, flags,
2291 	    SFMMU_INVALID_SHMERID);
2292 }
2293 
2294 void
2295 hat_memload_array_region(struct hat *hat, caddr_t addr, size_t len,
2296 	struct page **pps, uint_t attr, uint_t flags,
2297 	hat_region_cookie_t rcookie)
2298 {
2299 	uint_t rid;
2300 	if (rcookie == HAT_INVALID_REGION_COOKIE ||
2301 	    hat->sfmmu_xhat_provider != NULL) {
2302 		hat_do_memload_array(hat, addr, len, pps, attr, flags,
2303 		    SFMMU_INVALID_SHMERID);
2304 		return;
2305 	}
2306 	rid = (uint_t)((uint64_t)rcookie);
2307 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2308 	hat_do_memload_array(hat, addr, len, pps, attr, flags, rid);
2309 }
2310 
2311 /*
2312  * Map the largest extend possible out of the page array. The array may NOT
2313  * be in order.  The largest possible mapping a page can have
2314  * is specified in the p_szc field.  The p_szc field
2315  * cannot change as long as there any mappings (large or small)
2316  * to any of the pages that make up the large page. (ie. any
2317  * promotion/demotion of page size is not up to the hat but up to
2318  * the page free list manager).  The array
2319  * should consist of properly aligned contigous pages that are
2320  * part of a big page for a large mapping to be created.
2321  */
2322 static void
2323 hat_do_memload_array(struct hat *hat, caddr_t addr, size_t len,
2324 	struct page **pps, uint_t attr, uint_t flags, uint_t rid)
2325 {
2326 	int  ttesz;
2327 	size_t mapsz;
2328 	pgcnt_t	numpg, npgs;
2329 	tte_t tte;
2330 	page_t *pp;
2331 	uint_t large_pages_disable;
2332 
2333 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2334 	SFMMU_VALIDATE_HMERID(hat, rid, addr, len);
2335 
2336 	if (hat->sfmmu_xhat_provider) {
2337 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
2338 		XHAT_MEMLOAD_ARRAY(hat, addr, len, pps, attr, flags);
2339 		return;
2340 	}
2341 
2342 	if (hat->sfmmu_rmstat)
2343 		hat_resvstat(len, hat->sfmmu_as, addr);
2344 
2345 #if defined(SF_ERRATA_57)
2346 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2347 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2348 	    !(flags & HAT_LOAD_SHARE)) {
2349 		cmn_err(CE_WARN, "hat_memload_array: illegal attempt to make "
2350 		    "user page executable");
2351 		attr &= ~PROT_EXEC;
2352 	}
2353 #endif
2354 
2355 	/* Get number of pages */
2356 	npgs = len >> MMU_PAGESHIFT;
2357 
2358 	if (flags & HAT_LOAD_SHARE) {
2359 		large_pages_disable = disable_ism_large_pages;
2360 	} else {
2361 		large_pages_disable = disable_large_pages;
2362 	}
2363 
2364 	if (npgs < NHMENTS || large_pages_disable == LARGE_PAGES_OFF) {
2365 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2366 		    rid);
2367 		return;
2368 	}
2369 
2370 	while (npgs >= NHMENTS) {
2371 		pp = *pps;
2372 		for (ttesz = pp->p_szc; ttesz != TTE8K; ttesz--) {
2373 			/*
2374 			 * Check if this page size is disabled.
2375 			 */
2376 			if (large_pages_disable & (1 << ttesz))
2377 				continue;
2378 
2379 			numpg = TTEPAGES(ttesz);
2380 			mapsz = numpg << MMU_PAGESHIFT;
2381 			if ((npgs >= numpg) &&
2382 			    IS_P2ALIGNED(addr, mapsz) &&
2383 			    IS_P2ALIGNED(pp->p_pagenum, numpg)) {
2384 				/*
2385 				 * At this point we have enough pages and
2386 				 * we know the virtual address and the pfn
2387 				 * are properly aligned.  We still need
2388 				 * to check for physical contiguity but since
2389 				 * it is very likely that this is the case
2390 				 * we will assume they are so and undo
2391 				 * the request if necessary.  It would
2392 				 * be great if we could get a hint flag
2393 				 * like HAT_CONTIG which would tell us
2394 				 * the pages are contigous for sure.
2395 				 */
2396 				sfmmu_memtte(&tte, (*pps)->p_pagenum,
2397 				    attr, ttesz);
2398 				if (!sfmmu_tteload_array(hat, &tte, addr,
2399 				    pps, flags, rid)) {
2400 					break;
2401 				}
2402 			}
2403 		}
2404 		if (ttesz == TTE8K) {
2405 			/*
2406 			 * We were not able to map array using a large page
2407 			 * batch a hmeblk or fraction at a time.
2408 			 */
2409 			numpg = ((uintptr_t)addr >> MMU_PAGESHIFT)
2410 			    & (NHMENTS-1);
2411 			numpg = NHMENTS - numpg;
2412 			ASSERT(numpg <= npgs);
2413 			mapsz = numpg * MMU_PAGESIZE;
2414 			sfmmu_memload_batchsmall(hat, addr, pps, attr, flags,
2415 			    numpg, rid);
2416 		}
2417 		addr += mapsz;
2418 		npgs -= numpg;
2419 		pps += numpg;
2420 	}
2421 
2422 	if (npgs) {
2423 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2424 		    rid);
2425 	}
2426 
2427 	/*
2428 	 * Check TSB and TLB page sizes.
2429 	 */
2430 	if ((flags & HAT_LOAD_SHARE) == 0) {
2431 		sfmmu_check_page_sizes(hat, 1);
2432 	}
2433 }
2434 
2435 /*
2436  * Function tries to batch 8K pages into the same hme blk.
2437  */
2438 static void
2439 sfmmu_memload_batchsmall(struct hat *hat, caddr_t vaddr, page_t **pps,
2440 		    uint_t attr, uint_t flags, pgcnt_t npgs, uint_t rid)
2441 {
2442 	tte_t	tte;
2443 	page_t *pp;
2444 	struct hmehash_bucket *hmebp;
2445 	struct hme_blk *hmeblkp;
2446 	int	index;
2447 
2448 	while (npgs) {
2449 		/*
2450 		 * Acquire the hash bucket.
2451 		 */
2452 		hmebp = sfmmu_tteload_acquire_hashbucket(hat, vaddr, TTE8K,
2453 		    rid);
2454 		ASSERT(hmebp);
2455 
2456 		/*
2457 		 * Find the hment block.
2458 		 */
2459 		hmeblkp = sfmmu_tteload_find_hmeblk(hat, hmebp, vaddr,
2460 		    TTE8K, flags, rid);
2461 		ASSERT(hmeblkp);
2462 
2463 		do {
2464 			/*
2465 			 * Make the tte.
2466 			 */
2467 			pp = *pps;
2468 			sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2469 
2470 			/*
2471 			 * Add the translation.
2472 			 */
2473 			(void) sfmmu_tteload_addentry(hat, hmeblkp, &tte,
2474 			    vaddr, pps, flags, rid);
2475 
2476 			/*
2477 			 * Goto next page.
2478 			 */
2479 			pps++;
2480 			npgs--;
2481 
2482 			/*
2483 			 * Goto next address.
2484 			 */
2485 			vaddr += MMU_PAGESIZE;
2486 
2487 			/*
2488 			 * Don't crossover into a different hmentblk.
2489 			 */
2490 			index = (int)(((uintptr_t)vaddr >> MMU_PAGESHIFT) &
2491 			    (NHMENTS-1));
2492 
2493 		} while (index != 0 && npgs != 0);
2494 
2495 		/*
2496 		 * Release the hash bucket.
2497 		 */
2498 
2499 		sfmmu_tteload_release_hashbucket(hmebp);
2500 	}
2501 }
2502 
2503 /*
2504  * Construct a tte for a page:
2505  *
2506  * tte_valid = 1
2507  * tte_size2 = size & TTE_SZ2_BITS (Panther and Olympus-C only)
2508  * tte_size = size
2509  * tte_nfo = attr & HAT_NOFAULT
2510  * tte_ie = attr & HAT_STRUCTURE_LE
2511  * tte_hmenum = hmenum
2512  * tte_pahi = pp->p_pagenum >> TTE_PASHIFT;
2513  * tte_palo = pp->p_pagenum & TTE_PALOMASK;
2514  * tte_ref = 1 (optimization)
2515  * tte_wr_perm = attr & PROT_WRITE;
2516  * tte_no_sync = attr & HAT_NOSYNC
2517  * tte_lock = attr & SFMMU_LOCKTTE
2518  * tte_cp = !(attr & SFMMU_UNCACHEPTTE)
2519  * tte_cv = !(attr & SFMMU_UNCACHEVTTE)
2520  * tte_e = attr & SFMMU_SIDEFFECT
2521  * tte_priv = !(attr & PROT_USER)
2522  * tte_hwwr = if nosync is set and it is writable we set the mod bit (opt)
2523  * tte_glb = 0
2524  */
2525 void
2526 sfmmu_memtte(tte_t *ttep, pfn_t pfn, uint_t attr, int tte_sz)
2527 {
2528 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2529 
2530 	ttep->tte_inthi = MAKE_TTE_INTHI(pfn, attr, tte_sz, 0 /* hmenum */);
2531 	ttep->tte_intlo = MAKE_TTE_INTLO(pfn, attr, tte_sz, 0 /* hmenum */);
2532 
2533 	if (TTE_IS_NOSYNC(ttep)) {
2534 		TTE_SET_REF(ttep);
2535 		if (TTE_IS_WRITABLE(ttep)) {
2536 			TTE_SET_MOD(ttep);
2537 		}
2538 	}
2539 	if (TTE_IS_NFO(ttep) && TTE_IS_EXECUTABLE(ttep)) {
2540 		panic("sfmmu_memtte: can't set both NFO and EXEC bits");
2541 	}
2542 }
2543 
2544 /*
2545  * This function will add a translation to the hme_blk and allocate the
2546  * hme_blk if one does not exist.
2547  * If a page structure is specified then it will add the
2548  * corresponding hment to the mapping list.
2549  * It will also update the hmenum field for the tte.
2550  *
2551  * Currently this function is only used for kernel mappings.
2552  * So pass invalid region to sfmmu_tteload_array().
2553  */
2554 void
2555 sfmmu_tteload(struct hat *sfmmup, tte_t *ttep, caddr_t vaddr, page_t *pp,
2556 	uint_t flags)
2557 {
2558 	ASSERT(sfmmup == ksfmmup);
2559 	(void) sfmmu_tteload_array(sfmmup, ttep, vaddr, &pp, flags,
2560 	    SFMMU_INVALID_SHMERID);
2561 }
2562 
2563 /*
2564  * Load (ttep != NULL) or unload (ttep == NULL) one entry in the TSB.
2565  * Assumes that a particular page size may only be resident in one TSB.
2566  */
2567 static void
2568 sfmmu_mod_tsb(sfmmu_t *sfmmup, caddr_t vaddr, tte_t *ttep, int ttesz)
2569 {
2570 	struct tsb_info *tsbinfop = NULL;
2571 	uint64_t tag;
2572 	struct tsbe *tsbe_addr;
2573 	uint64_t tsb_base;
2574 	uint_t tsb_size;
2575 	int vpshift = MMU_PAGESHIFT;
2576 	int phys = 0;
2577 
2578 	if (sfmmup == ksfmmup) { /* No support for 32/256M ksfmmu pages */
2579 		phys = ktsb_phys;
2580 		if (ttesz >= TTE4M) {
2581 #ifndef sun4v
2582 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2583 #endif
2584 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2585 			tsb_size = ktsb4m_szcode;
2586 		} else {
2587 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2588 			tsb_size = ktsb_szcode;
2589 		}
2590 	} else {
2591 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2592 
2593 		/*
2594 		 * If there isn't a TSB for this page size, or the TSB is
2595 		 * swapped out, there is nothing to do.  Note that the latter
2596 		 * case seems impossible but can occur if hat_pageunload()
2597 		 * is called on an ISM mapping while the process is swapped
2598 		 * out.
2599 		 */
2600 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2601 			return;
2602 
2603 		/*
2604 		 * If another thread is in the middle of relocating a TSB
2605 		 * we can't unload the entry so set a flag so that the
2606 		 * TSB will be flushed before it can be accessed by the
2607 		 * process.
2608 		 */
2609 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2610 			if (ttep == NULL)
2611 				tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2612 			return;
2613 		}
2614 #if defined(UTSB_PHYS)
2615 		phys = 1;
2616 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2617 #else
2618 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2619 #endif
2620 		tsb_size = tsbinfop->tsb_szc;
2621 	}
2622 	if (ttesz >= TTE4M)
2623 		vpshift = MMU_PAGESHIFT4M;
2624 
2625 	tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2626 	tag = sfmmu_make_tsbtag(vaddr);
2627 
2628 	if (ttep == NULL) {
2629 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2630 	} else {
2631 		if (ttesz >= TTE4M) {
2632 			SFMMU_STAT(sf_tsb_load4m);
2633 		} else {
2634 			SFMMU_STAT(sf_tsb_load8k);
2635 		}
2636 
2637 		sfmmu_load_tsbe(tsbe_addr, tag, ttep, phys);
2638 	}
2639 }
2640 
2641 /*
2642  * Unmap all entries from [start, end) matching the given page size.
2643  *
2644  * This function is used primarily to unmap replicated 64K or 512K entries
2645  * from the TSB that are inserted using the base page size TSB pointer, but
2646  * it may also be called to unmap a range of addresses from the TSB.
2647  */
2648 void
2649 sfmmu_unload_tsb_range(sfmmu_t *sfmmup, caddr_t start, caddr_t end, int ttesz)
2650 {
2651 	struct tsb_info *tsbinfop;
2652 	uint64_t tag;
2653 	struct tsbe *tsbe_addr;
2654 	caddr_t vaddr;
2655 	uint64_t tsb_base;
2656 	int vpshift, vpgsz;
2657 	uint_t tsb_size;
2658 	int phys = 0;
2659 
2660 	/*
2661 	 * Assumptions:
2662 	 *  If ttesz == 8K, 64K or 512K, we walk through the range 8K
2663 	 *  at a time shooting down any valid entries we encounter.
2664 	 *
2665 	 *  If ttesz >= 4M we walk the range 4M at a time shooting
2666 	 *  down any valid mappings we find.
2667 	 */
2668 	if (sfmmup == ksfmmup) {
2669 		phys = ktsb_phys;
2670 		if (ttesz >= TTE4M) {
2671 #ifndef sun4v
2672 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2673 #endif
2674 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2675 			tsb_size = ktsb4m_szcode;
2676 		} else {
2677 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2678 			tsb_size = ktsb_szcode;
2679 		}
2680 	} else {
2681 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2682 
2683 		/*
2684 		 * If there isn't a TSB for this page size, or the TSB is
2685 		 * swapped out, there is nothing to do.  Note that the latter
2686 		 * case seems impossible but can occur if hat_pageunload()
2687 		 * is called on an ISM mapping while the process is swapped
2688 		 * out.
2689 		 */
2690 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2691 			return;
2692 
2693 		/*
2694 		 * If another thread is in the middle of relocating a TSB
2695 		 * we can't unload the entry so set a flag so that the
2696 		 * TSB will be flushed before it can be accessed by the
2697 		 * process.
2698 		 */
2699 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2700 			tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2701 			return;
2702 		}
2703 #if defined(UTSB_PHYS)
2704 		phys = 1;
2705 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2706 #else
2707 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2708 #endif
2709 		tsb_size = tsbinfop->tsb_szc;
2710 	}
2711 	if (ttesz >= TTE4M) {
2712 		vpshift = MMU_PAGESHIFT4M;
2713 		vpgsz = MMU_PAGESIZE4M;
2714 	} else {
2715 		vpshift = MMU_PAGESHIFT;
2716 		vpgsz = MMU_PAGESIZE;
2717 	}
2718 
2719 	for (vaddr = start; vaddr < end; vaddr += vpgsz) {
2720 		tag = sfmmu_make_tsbtag(vaddr);
2721 		tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2722 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2723 	}
2724 }
2725 
2726 /*
2727  * Select the optimum TSB size given the number of mappings
2728  * that need to be cached.
2729  */
2730 static int
2731 sfmmu_select_tsb_szc(pgcnt_t pgcnt)
2732 {
2733 	int szc = 0;
2734 
2735 #ifdef DEBUG
2736 	if (tsb_grow_stress) {
2737 		uint32_t randval = (uint32_t)gettick() >> 4;
2738 		return (randval % (tsb_max_growsize + 1));
2739 	}
2740 #endif	/* DEBUG */
2741 
2742 	while ((szc < tsb_max_growsize) && (pgcnt > SFMMU_RSS_TSBSIZE(szc)))
2743 		szc++;
2744 	return (szc);
2745 }
2746 
2747 /*
2748  * This function will add a translation to the hme_blk and allocate the
2749  * hme_blk if one does not exist.
2750  * If a page structure is specified then it will add the
2751  * corresponding hment to the mapping list.
2752  * It will also update the hmenum field for the tte.
2753  * Furthermore, it attempts to create a large page translation
2754  * for <addr,hat> at page array pps.  It assumes addr and first
2755  * pp is correctly aligned.  It returns 0 if successful and 1 otherwise.
2756  */
2757 static int
2758 sfmmu_tteload_array(sfmmu_t *sfmmup, tte_t *ttep, caddr_t vaddr,
2759 	page_t **pps, uint_t flags, uint_t rid)
2760 {
2761 	struct hmehash_bucket *hmebp;
2762 	struct hme_blk *hmeblkp;
2763 	int 	ret;
2764 	uint_t	size;
2765 
2766 	/*
2767 	 * Get mapping size.
2768 	 */
2769 	size = TTE_CSZ(ttep);
2770 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
2771 
2772 	/*
2773 	 * Acquire the hash bucket.
2774 	 */
2775 	hmebp = sfmmu_tteload_acquire_hashbucket(sfmmup, vaddr, size, rid);
2776 	ASSERT(hmebp);
2777 
2778 	/*
2779 	 * Find the hment block.
2780 	 */
2781 	hmeblkp = sfmmu_tteload_find_hmeblk(sfmmup, hmebp, vaddr, size, flags,
2782 	    rid);
2783 	ASSERT(hmeblkp);
2784 
2785 	/*
2786 	 * Add the translation.
2787 	 */
2788 	ret = sfmmu_tteload_addentry(sfmmup, hmeblkp, ttep, vaddr, pps, flags,
2789 	    rid);
2790 
2791 	/*
2792 	 * Release the hash bucket.
2793 	 */
2794 	sfmmu_tteload_release_hashbucket(hmebp);
2795 
2796 	return (ret);
2797 }
2798 
2799 /*
2800  * Function locks and returns a pointer to the hash bucket for vaddr and size.
2801  */
2802 static struct hmehash_bucket *
2803 sfmmu_tteload_acquire_hashbucket(sfmmu_t *sfmmup, caddr_t vaddr, int size,
2804     uint_t rid)
2805 {
2806 	struct hmehash_bucket *hmebp;
2807 	int hmeshift;
2808 	void *htagid = sfmmutohtagid(sfmmup, rid);
2809 
2810 	ASSERT(htagid != NULL);
2811 
2812 	hmeshift = HME_HASH_SHIFT(size);
2813 
2814 	hmebp = HME_HASH_FUNCTION(htagid, vaddr, hmeshift);
2815 
2816 	SFMMU_HASH_LOCK(hmebp);
2817 
2818 	return (hmebp);
2819 }
2820 
2821 /*
2822  * Function returns a pointer to an hmeblk in the hash bucket, hmebp. If the
2823  * hmeblk doesn't exists for the [sfmmup, vaddr & size] signature, a hmeblk is
2824  * allocated.
2825  */
2826 static struct hme_blk *
2827 sfmmu_tteload_find_hmeblk(sfmmu_t *sfmmup, struct hmehash_bucket *hmebp,
2828 	caddr_t vaddr, uint_t size, uint_t flags, uint_t rid)
2829 {
2830 	hmeblk_tag hblktag;
2831 	int hmeshift;
2832 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
2833 	uint64_t hblkpa, prevpa;
2834 	struct kmem_cache *sfmmu_cache;
2835 	uint_t forcefree;
2836 
2837 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
2838 
2839 	hblktag.htag_id = sfmmutohtagid(sfmmup, rid);
2840 	ASSERT(hblktag.htag_id != NULL);
2841 	hmeshift = HME_HASH_SHIFT(size);
2842 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
2843 	hblktag.htag_rehash = HME_HASH_REHASH(size);
2844 	hblktag.htag_rid = rid;
2845 
2846 ttearray_realloc:
2847 
2848 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa,
2849 	    pr_hblk, prevpa, &list);
2850 
2851 	/*
2852 	 * We block until hblk_reserve_lock is released; it's held by
2853 	 * the thread, temporarily using hblk_reserve, until hblk_reserve is
2854 	 * replaced by a hblk from sfmmu8_cache.
2855 	 */
2856 	if (hmeblkp == (struct hme_blk *)hblk_reserve &&
2857 	    hblk_reserve_thread != curthread) {
2858 		SFMMU_HASH_UNLOCK(hmebp);
2859 		mutex_enter(&hblk_reserve_lock);
2860 		mutex_exit(&hblk_reserve_lock);
2861 		SFMMU_STAT(sf_hblk_reserve_hit);
2862 		SFMMU_HASH_LOCK(hmebp);
2863 		goto ttearray_realloc;
2864 	}
2865 
2866 	if (hmeblkp == NULL) {
2867 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
2868 		    hblktag, flags, rid);
2869 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
2870 		ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
2871 	} else {
2872 		/*
2873 		 * It is possible for 8k and 64k hblks to collide since they
2874 		 * have the same rehash value. This is because we
2875 		 * lazily free hblks and 8K/64K blks could be lingering.
2876 		 * If we find size mismatch we free the block and & try again.
2877 		 */
2878 		if (get_hblk_ttesz(hmeblkp) != size) {
2879 			ASSERT(!hmeblkp->hblk_vcnt);
2880 			ASSERT(!hmeblkp->hblk_hmecnt);
2881 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
2882 			sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
2883 			goto ttearray_realloc;
2884 		}
2885 		if (hmeblkp->hblk_shw_bit) {
2886 			/*
2887 			 * if the hblk was previously used as a shadow hblk then
2888 			 * we will change it to a normal hblk
2889 			 */
2890 			ASSERT(!hmeblkp->hblk_shared);
2891 			if (hmeblkp->hblk_shw_mask) {
2892 				sfmmu_shadow_hcleanup(sfmmup, hmeblkp, hmebp);
2893 				ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
2894 				goto ttearray_realloc;
2895 			} else {
2896 				hmeblkp->hblk_shw_bit = 0;
2897 			}
2898 		}
2899 		SFMMU_STAT(sf_hblk_hit);
2900 	}
2901 
2902 	/*
2903 	 * hat_memload() should never call kmem_cache_free(); see block
2904 	 * comment showing the stacktrace in sfmmu_hblk_alloc();
2905 	 * enqueue each hblk in the list to reserve list if it's created
2906 	 * from sfmmu8_cache *and* sfmmup == KHATID.
2907 	 */
2908 	forcefree = (sfmmup == KHATID) ? 1 : 0;
2909 	while ((pr_hblk = list) != NULL) {
2910 		list = pr_hblk->hblk_next;
2911 		sfmmu_cache = get_hblk_cache(pr_hblk);
2912 		if ((sfmmu_cache == sfmmu8_cache) &&
2913 		    sfmmu_put_free_hblk(pr_hblk, forcefree))
2914 			continue;
2915 
2916 		ASSERT(sfmmup != KHATID);
2917 		kmem_cache_free(sfmmu_cache, pr_hblk);
2918 	}
2919 
2920 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
2921 	ASSERT(!hmeblkp->hblk_shw_bit);
2922 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
2923 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
2924 	ASSERT(hmeblkp->hblk_tag.htag_rid == rid);
2925 
2926 	return (hmeblkp);
2927 }
2928 
2929 /*
2930  * Function adds a tte entry into the hmeblk. It returns 0 if successful and 1
2931  * otherwise.
2932  */
2933 static int
2934 sfmmu_tteload_addentry(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, tte_t *ttep,
2935 	caddr_t vaddr, page_t **pps, uint_t flags, uint_t rid)
2936 {
2937 	page_t *pp = *pps;
2938 	int hmenum, size, remap;
2939 	tte_t tteold, flush_tte;
2940 #ifdef DEBUG
2941 	tte_t orig_old;
2942 #endif /* DEBUG */
2943 	struct sf_hment *sfhme;
2944 	kmutex_t *pml, *pmtx;
2945 	hatlock_t *hatlockp;
2946 	int myflt;
2947 
2948 	/*
2949 	 * remove this panic when we decide to let user virtual address
2950 	 * space be >= USERLIMIT.
2951 	 */
2952 	if (!TTE_IS_PRIVILEGED(ttep) && vaddr >= (caddr_t)USERLIMIT)
2953 		panic("user addr %p in kernel space", vaddr);
2954 #if defined(TTE_IS_GLOBAL)
2955 	if (TTE_IS_GLOBAL(ttep))
2956 		panic("sfmmu_tteload: creating global tte");
2957 #endif
2958 
2959 #ifdef DEBUG
2960 	if (pf_is_memory(sfmmu_ttetopfn(ttep, vaddr)) &&
2961 	    !TTE_IS_PCACHEABLE(ttep) && !sfmmu_allow_nc_trans)
2962 		panic("sfmmu_tteload: non cacheable memory tte");
2963 #endif /* DEBUG */
2964 
2965 	if ((flags & HAT_LOAD_SHARE) || !TTE_IS_REF(ttep) ||
2966 	    !TTE_IS_MOD(ttep)) {
2967 		/*
2968 		 * Don't load TSB for dummy as in ISM.  Also don't preload
2969 		 * the TSB if the TTE isn't writable since we're likely to
2970 		 * fault on it again -- preloading can be fairly expensive.
2971 		 */
2972 		flags |= SFMMU_NO_TSBLOAD;
2973 	}
2974 
2975 	size = TTE_CSZ(ttep);
2976 	switch (size) {
2977 	case TTE8K:
2978 		SFMMU_STAT(sf_tteload8k);
2979 		break;
2980 	case TTE64K:
2981 		SFMMU_STAT(sf_tteload64k);
2982 		break;
2983 	case TTE512K:
2984 		SFMMU_STAT(sf_tteload512k);
2985 		break;
2986 	case TTE4M:
2987 		SFMMU_STAT(sf_tteload4m);
2988 		break;
2989 	case (TTE32M):
2990 		SFMMU_STAT(sf_tteload32m);
2991 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
2992 		break;
2993 	case (TTE256M):
2994 		SFMMU_STAT(sf_tteload256m);
2995 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
2996 		break;
2997 	}
2998 
2999 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
3000 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
3001 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3002 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3003 
3004 	HBLKTOHME_IDX(sfhme, hmeblkp, vaddr, hmenum);
3005 
3006 	/*
3007 	 * Need to grab mlist lock here so that pageunload
3008 	 * will not change tte behind us.
3009 	 */
3010 	if (pp) {
3011 		pml = sfmmu_mlist_enter(pp);
3012 	}
3013 
3014 	sfmmu_copytte(&sfhme->hme_tte, &tteold);
3015 	/*
3016 	 * Look for corresponding hment and if valid verify
3017 	 * pfns are equal.
3018 	 */
3019 	remap = TTE_IS_VALID(&tteold);
3020 	if (remap) {
3021 		pfn_t	new_pfn, old_pfn;
3022 
3023 		old_pfn = TTE_TO_PFN(vaddr, &tteold);
3024 		new_pfn = TTE_TO_PFN(vaddr, ttep);
3025 
3026 		if (flags & HAT_LOAD_REMAP) {
3027 			/* make sure we are remapping same type of pages */
3028 			if (pf_is_memory(old_pfn) != pf_is_memory(new_pfn)) {
3029 				panic("sfmmu_tteload - tte remap io<->memory");
3030 			}
3031 			if (old_pfn != new_pfn &&
3032 			    (pp != NULL || sfhme->hme_page != NULL)) {
3033 				panic("sfmmu_tteload - tte remap pp != NULL");
3034 			}
3035 		} else if (old_pfn != new_pfn) {
3036 			panic("sfmmu_tteload - tte remap, hmeblkp 0x%p",
3037 			    (void *)hmeblkp);
3038 		}
3039 		ASSERT(TTE_CSZ(&tteold) == TTE_CSZ(ttep));
3040 	}
3041 
3042 	if (pp) {
3043 		if (size == TTE8K) {
3044 #ifdef VAC
3045 			/*
3046 			 * Handle VAC consistency
3047 			 */
3048 			if (!remap && (cache & CACHE_VAC) && !PP_ISNC(pp)) {
3049 				sfmmu_vac_conflict(sfmmup, vaddr, pp);
3050 			}
3051 #endif
3052 
3053 			if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3054 				pmtx = sfmmu_page_enter(pp);
3055 				PP_CLRRO(pp);
3056 				sfmmu_page_exit(pmtx);
3057 			} else if (!PP_ISMAPPED(pp) &&
3058 			    (!TTE_IS_WRITABLE(ttep)) && !(PP_ISMOD(pp))) {
3059 				pmtx = sfmmu_page_enter(pp);
3060 				if (!(PP_ISMOD(pp))) {
3061 					PP_SETRO(pp);
3062 				}
3063 				sfmmu_page_exit(pmtx);
3064 			}
3065 
3066 		} else if (sfmmu_pagearray_setup(vaddr, pps, ttep, remap)) {
3067 			/*
3068 			 * sfmmu_pagearray_setup failed so return
3069 			 */
3070 			sfmmu_mlist_exit(pml);
3071 			return (1);
3072 		}
3073 	}
3074 
3075 	/*
3076 	 * Make sure hment is not on a mapping list.
3077 	 */
3078 	ASSERT(remap || (sfhme->hme_page == NULL));
3079 
3080 	/* if it is not a remap then hme->next better be NULL */
3081 	ASSERT((!remap) ? sfhme->hme_next == NULL : 1);
3082 
3083 	if (flags & HAT_LOAD_LOCK) {
3084 		if ((hmeblkp->hblk_lckcnt + 1) >= MAX_HBLK_LCKCNT) {
3085 			panic("too high lckcnt-hmeblk %p",
3086 			    (void *)hmeblkp);
3087 		}
3088 		atomic_add_32(&hmeblkp->hblk_lckcnt, 1);
3089 
3090 		HBLK_STACK_TRACE(hmeblkp, HBLK_LOCK);
3091 	}
3092 
3093 #ifdef VAC
3094 	if (pp && PP_ISNC(pp)) {
3095 		/*
3096 		 * If the physical page is marked to be uncacheable, like
3097 		 * by a vac conflict, make sure the new mapping is also
3098 		 * uncacheable.
3099 		 */
3100 		TTE_CLR_VCACHEABLE(ttep);
3101 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
3102 	}
3103 #endif
3104 	ttep->tte_hmenum = hmenum;
3105 
3106 #ifdef DEBUG
3107 	orig_old = tteold;
3108 #endif /* DEBUG */
3109 
3110 	while (sfmmu_modifytte_try(&tteold, ttep, &sfhme->hme_tte) < 0) {
3111 		if ((sfmmup == KHATID) &&
3112 		    (flags & (HAT_LOAD_LOCK | HAT_LOAD_REMAP))) {
3113 			sfmmu_copytte(&sfhme->hme_tte, &tteold);
3114 		}
3115 #ifdef DEBUG
3116 		chk_tte(&orig_old, &tteold, ttep, hmeblkp);
3117 #endif /* DEBUG */
3118 	}
3119 	ASSERT(TTE_IS_VALID(&sfhme->hme_tte));
3120 
3121 	if (!TTE_IS_VALID(&tteold)) {
3122 
3123 		atomic_add_16(&hmeblkp->hblk_vcnt, 1);
3124 		if (rid == SFMMU_INVALID_SHMERID) {
3125 			atomic_add_long(&sfmmup->sfmmu_ttecnt[size], 1);
3126 		} else {
3127 			sf_srd_t *srdp = sfmmup->sfmmu_srdp;
3128 			sf_region_t *rgnp = srdp->srd_hmergnp[rid];
3129 			/*
3130 			 * We already accounted for region ttecnt's in sfmmu
3131 			 * during hat_join_region() processing. Here we
3132 			 * only update ttecnt's in region struture.
3133 			 */
3134 			atomic_add_long(&rgnp->rgn_ttecnt[size], 1);
3135 		}
3136 	}
3137 
3138 	myflt = (astosfmmu(curthread->t_procp->p_as) == sfmmup);
3139 	if (size > TTE8K && (flags & HAT_LOAD_SHARE) == 0 &&
3140 	    sfmmup != ksfmmup) {
3141 		uchar_t tteflag = 1 << size;
3142 		if (rid == SFMMU_INVALID_SHMERID) {
3143 			if (!(sfmmup->sfmmu_tteflags & tteflag)) {
3144 				hatlockp = sfmmu_hat_enter(sfmmup);
3145 				sfmmup->sfmmu_tteflags |= tteflag;
3146 				sfmmu_hat_exit(hatlockp);
3147 			}
3148 		} else if (!(sfmmup->sfmmu_rtteflags & tteflag)) {
3149 			hatlockp = sfmmu_hat_enter(sfmmup);
3150 			sfmmup->sfmmu_rtteflags |= tteflag;
3151 			sfmmu_hat_exit(hatlockp);
3152 		}
3153 		/*
3154 		 * Update the current CPU tsbmiss area, so the current thread
3155 		 * won't need to take the tsbmiss for the new pagesize.
3156 		 * The other threads in the process will update their tsb
3157 		 * miss area lazily in sfmmu_tsbmiss_exception() when they
3158 		 * fail to find the translation for a newly added pagesize.
3159 		 */
3160 		if (size > TTE64K && myflt) {
3161 			struct tsbmiss *tsbmp;
3162 			kpreempt_disable();
3163 			tsbmp = &tsbmiss_area[CPU->cpu_id];
3164 			if (rid == SFMMU_INVALID_SHMERID) {
3165 				if (!(tsbmp->uhat_tteflags & tteflag)) {
3166 					tsbmp->uhat_tteflags |= tteflag;
3167 				}
3168 			} else {
3169 				if (!(tsbmp->uhat_rtteflags & tteflag)) {
3170 					tsbmp->uhat_rtteflags |= tteflag;
3171 				}
3172 			}
3173 			kpreempt_enable();
3174 		}
3175 	}
3176 
3177 	if (size >= TTE4M && (flags & HAT_LOAD_TEXT) &&
3178 	    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
3179 		hatlockp = sfmmu_hat_enter(sfmmup);
3180 		SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
3181 		sfmmu_hat_exit(hatlockp);
3182 	}
3183 
3184 	flush_tte.tte_intlo = (tteold.tte_intlo ^ ttep->tte_intlo) &
3185 	    hw_tte.tte_intlo;
3186 	flush_tte.tte_inthi = (tteold.tte_inthi ^ ttep->tte_inthi) &
3187 	    hw_tte.tte_inthi;
3188 
3189 	if (remap && (flush_tte.tte_inthi || flush_tte.tte_intlo)) {
3190 		/*
3191 		 * If remap and new tte differs from old tte we need
3192 		 * to sync the mod bit and flush TLB/TSB.  We don't
3193 		 * need to sync ref bit because we currently always set
3194 		 * ref bit in tteload.
3195 		 */
3196 		ASSERT(TTE_IS_REF(ttep));
3197 		if (TTE_IS_MOD(&tteold)) {
3198 			sfmmu_ttesync(sfmmup, vaddr, &tteold, pp);
3199 		}
3200 		/*
3201 		 * hwtte bits shouldn't change for SRD hmeblks as long as SRD
3202 		 * hmes are only used for read only text. Adding this code for
3203 		 * completeness and future use of shared hmeblks with writable
3204 		 * mappings of VMODSORT vnodes.
3205 		 */
3206 		if (hmeblkp->hblk_shared) {
3207 			cpuset_t cpuset = sfmmu_rgntlb_demap(vaddr,
3208 			    sfmmup->sfmmu_srdp->srd_hmergnp[rid], hmeblkp, 1);
3209 			xt_sync(cpuset);
3210 			SFMMU_STAT_ADD(sf_region_remap_demap, 1);
3211 		} else {
3212 			sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 0);
3213 			xt_sync(sfmmup->sfmmu_cpusran);
3214 		}
3215 	}
3216 
3217 	if ((flags & SFMMU_NO_TSBLOAD) == 0) {
3218 		/*
3219 		 * We only preload 8K and 4M mappings into the TSB, since
3220 		 * 64K and 512K mappings are replicated and hence don't
3221 		 * have a single, unique TSB entry. Ditto for 32M/256M.
3222 		 */
3223 		if (size == TTE8K || size == TTE4M) {
3224 			sf_scd_t *scdp;
3225 			hatlockp = sfmmu_hat_enter(sfmmup);
3226 			/*
3227 			 * Don't preload private TSB if the mapping is used
3228 			 * by the shctx in the SCD.
3229 			 */
3230 			scdp = sfmmup->sfmmu_scdp;
3231 			if (rid == SFMMU_INVALID_SHMERID || scdp == NULL ||
3232 			    !SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
3233 				sfmmu_load_tsb(sfmmup, vaddr, &sfhme->hme_tte,
3234 				    size);
3235 			}
3236 			sfmmu_hat_exit(hatlockp);
3237 		}
3238 	}
3239 	if (pp) {
3240 		if (!remap) {
3241 			HME_ADD(sfhme, pp);
3242 			atomic_add_16(&hmeblkp->hblk_hmecnt, 1);
3243 			ASSERT(hmeblkp->hblk_hmecnt > 0);
3244 
3245 			/*
3246 			 * Cannot ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
3247 			 * see pageunload() for comment.
3248 			 */
3249 		}
3250 		sfmmu_mlist_exit(pml);
3251 	}
3252 
3253 	return (0);
3254 }
3255 /*
3256  * Function unlocks hash bucket.
3257  */
3258 static void
3259 sfmmu_tteload_release_hashbucket(struct hmehash_bucket *hmebp)
3260 {
3261 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3262 	SFMMU_HASH_UNLOCK(hmebp);
3263 }
3264 
3265 /*
3266  * function which checks and sets up page array for a large
3267  * translation.  Will set p_vcolor, p_index, p_ro fields.
3268  * Assumes addr and pfnum of first page are properly aligned.
3269  * Will check for physical contiguity. If check fails it return
3270  * non null.
3271  */
3272 static int
3273 sfmmu_pagearray_setup(caddr_t addr, page_t **pps, tte_t *ttep, int remap)
3274 {
3275 	int 	i, index, ttesz;
3276 	pfn_t	pfnum;
3277 	pgcnt_t	npgs;
3278 	page_t *pp, *pp1;
3279 	kmutex_t *pmtx;
3280 #ifdef VAC
3281 	int osz;
3282 	int cflags = 0;
3283 	int vac_err = 0;
3284 #endif
3285 	int newidx = 0;
3286 
3287 	ttesz = TTE_CSZ(ttep);
3288 
3289 	ASSERT(ttesz > TTE8K);
3290 
3291 	npgs = TTEPAGES(ttesz);
3292 	index = PAGESZ_TO_INDEX(ttesz);
3293 
3294 	pfnum = (*pps)->p_pagenum;
3295 	ASSERT(IS_P2ALIGNED(pfnum, npgs));
3296 
3297 	/*
3298 	 * Save the first pp so we can do HAT_TMPNC at the end.
3299 	 */
3300 	pp1 = *pps;
3301 #ifdef VAC
3302 	osz = fnd_mapping_sz(pp1);
3303 #endif
3304 
3305 	for (i = 0; i < npgs; i++, pps++) {
3306 		pp = *pps;
3307 		ASSERT(PAGE_LOCKED(pp));
3308 		ASSERT(pp->p_szc >= ttesz);
3309 		ASSERT(pp->p_szc == pp1->p_szc);
3310 		ASSERT(sfmmu_mlist_held(pp));
3311 
3312 		/*
3313 		 * XXX is it possible to maintain P_RO on the root only?
3314 		 */
3315 		if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3316 			pmtx = sfmmu_page_enter(pp);
3317 			PP_CLRRO(pp);
3318 			sfmmu_page_exit(pmtx);
3319 		} else if (!PP_ISMAPPED(pp) && !TTE_IS_WRITABLE(ttep) &&
3320 		    !PP_ISMOD(pp)) {
3321 			pmtx = sfmmu_page_enter(pp);
3322 			if (!(PP_ISMOD(pp))) {
3323 				PP_SETRO(pp);
3324 			}
3325 			sfmmu_page_exit(pmtx);
3326 		}
3327 
3328 		/*
3329 		 * If this is a remap we skip vac & contiguity checks.
3330 		 */
3331 		if (remap)
3332 			continue;
3333 
3334 		/*
3335 		 * set p_vcolor and detect any vac conflicts.
3336 		 */
3337 #ifdef VAC
3338 		if (vac_err == 0) {
3339 			vac_err = sfmmu_vacconflict_array(addr, pp, &cflags);
3340 
3341 		}
3342 #endif
3343 
3344 		/*
3345 		 * Save current index in case we need to undo it.
3346 		 * Note: "PAGESZ_TO_INDEX(sz)	(1 << (sz))"
3347 		 *	"SFMMU_INDEX_SHIFT	6"
3348 		 *	 "SFMMU_INDEX_MASK	((1 << SFMMU_INDEX_SHIFT) - 1)"
3349 		 *	 "PP_MAPINDEX(p_index)	(p_index & SFMMU_INDEX_MASK)"
3350 		 *
3351 		 * So:	index = PAGESZ_TO_INDEX(ttesz);
3352 		 *	if ttesz == 1 then index = 0x2
3353 		 *		    2 then index = 0x4
3354 		 *		    3 then index = 0x8
3355 		 *		    4 then index = 0x10
3356 		 *		    5 then index = 0x20
3357 		 * The code below checks if it's a new pagesize (ie, newidx)
3358 		 * in case we need to take it back out of p_index,
3359 		 * and then or's the new index into the existing index.
3360 		 */
3361 		if ((PP_MAPINDEX(pp) & index) == 0)
3362 			newidx = 1;
3363 		pp->p_index = (PP_MAPINDEX(pp) | index);
3364 
3365 		/*
3366 		 * contiguity check
3367 		 */
3368 		if (pp->p_pagenum != pfnum) {
3369 			/*
3370 			 * If we fail the contiguity test then
3371 			 * the only thing we need to fix is the p_index field.
3372 			 * We might get a few extra flushes but since this
3373 			 * path is rare that is ok.  The p_ro field will
3374 			 * get automatically fixed on the next tteload to
3375 			 * the page.  NO TNC bit is set yet.
3376 			 */
3377 			while (i >= 0) {
3378 				pp = *pps;
3379 				if (newidx)
3380 					pp->p_index = (PP_MAPINDEX(pp) &
3381 					    ~index);
3382 				pps--;
3383 				i--;
3384 			}
3385 			return (1);
3386 		}
3387 		pfnum++;
3388 		addr += MMU_PAGESIZE;
3389 	}
3390 
3391 #ifdef VAC
3392 	if (vac_err) {
3393 		if (ttesz > osz) {
3394 			/*
3395 			 * There are some smaller mappings that causes vac
3396 			 * conflicts. Convert all existing small mappings to
3397 			 * TNC.
3398 			 */
3399 			SFMMU_STAT_ADD(sf_uncache_conflict, npgs);
3400 			sfmmu_page_cache_array(pp1, HAT_TMPNC, CACHE_FLUSH,
3401 			    npgs);
3402 		} else {
3403 			/* EMPTY */
3404 			/*
3405 			 * If there exists an big page mapping,
3406 			 * that means the whole existing big page
3407 			 * has TNC setting already. No need to covert to
3408 			 * TNC again.
3409 			 */
3410 			ASSERT(PP_ISTNC(pp1));
3411 		}
3412 	}
3413 #endif	/* VAC */
3414 
3415 	return (0);
3416 }
3417 
3418 #ifdef VAC
3419 /*
3420  * Routine that detects vac consistency for a large page. It also
3421  * sets virtual color for all pp's for this big mapping.
3422  */
3423 static int
3424 sfmmu_vacconflict_array(caddr_t addr, page_t *pp, int *cflags)
3425 {
3426 	int vcolor, ocolor;
3427 
3428 	ASSERT(sfmmu_mlist_held(pp));
3429 
3430 	if (PP_ISNC(pp)) {
3431 		return (HAT_TMPNC);
3432 	}
3433 
3434 	vcolor = addr_to_vcolor(addr);
3435 	if (PP_NEWPAGE(pp)) {
3436 		PP_SET_VCOLOR(pp, vcolor);
3437 		return (0);
3438 	}
3439 
3440 	ocolor = PP_GET_VCOLOR(pp);
3441 	if (ocolor == vcolor) {
3442 		return (0);
3443 	}
3444 
3445 	if (!PP_ISMAPPED(pp)) {
3446 		/*
3447 		 * Previous user of page had a differnet color
3448 		 * but since there are no current users
3449 		 * we just flush the cache and change the color.
3450 		 * As an optimization for large pages we flush the
3451 		 * entire cache of that color and set a flag.
3452 		 */
3453 		SFMMU_STAT(sf_pgcolor_conflict);
3454 		if (!CacheColor_IsFlushed(*cflags, ocolor)) {
3455 			CacheColor_SetFlushed(*cflags, ocolor);
3456 			sfmmu_cache_flushcolor(ocolor, pp->p_pagenum);
3457 		}
3458 		PP_SET_VCOLOR(pp, vcolor);
3459 		return (0);
3460 	}
3461 
3462 	/*
3463 	 * We got a real conflict with a current mapping.
3464 	 * set flags to start unencaching all mappings
3465 	 * and return failure so we restart looping
3466 	 * the pp array from the beginning.
3467 	 */
3468 	return (HAT_TMPNC);
3469 }
3470 #endif	/* VAC */
3471 
3472 /*
3473  * creates a large page shadow hmeblk for a tte.
3474  * The purpose of this routine is to allow us to do quick unloads because
3475  * the vm layer can easily pass a very large but sparsely populated range.
3476  */
3477 static struct hme_blk *
3478 sfmmu_shadow_hcreate(sfmmu_t *sfmmup, caddr_t vaddr, int ttesz, uint_t flags)
3479 {
3480 	struct hmehash_bucket *hmebp;
3481 	hmeblk_tag hblktag;
3482 	int hmeshift, size, vshift;
3483 	uint_t shw_mask, newshw_mask;
3484 	struct hme_blk *hmeblkp;
3485 
3486 	ASSERT(sfmmup != KHATID);
3487 	if (mmu_page_sizes == max_mmu_page_sizes) {
3488 		ASSERT(ttesz < TTE256M);
3489 	} else {
3490 		ASSERT(ttesz < TTE4M);
3491 		ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
3492 		ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
3493 	}
3494 
3495 	if (ttesz == TTE8K) {
3496 		size = TTE512K;
3497 	} else {
3498 		size = ++ttesz;
3499 	}
3500 
3501 	hblktag.htag_id = sfmmup;
3502 	hmeshift = HME_HASH_SHIFT(size);
3503 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
3504 	hblktag.htag_rehash = HME_HASH_REHASH(size);
3505 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3506 	hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
3507 
3508 	SFMMU_HASH_LOCK(hmebp);
3509 
3510 	HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
3511 	ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
3512 	if (hmeblkp == NULL) {
3513 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
3514 		    hblktag, flags, SFMMU_INVALID_SHMERID);
3515 	}
3516 	ASSERT(hmeblkp);
3517 	if (!hmeblkp->hblk_shw_mask) {
3518 		/*
3519 		 * if this is a unused hblk it was just allocated or could
3520 		 * potentially be a previous large page hblk so we need to
3521 		 * set the shadow bit.
3522 		 */
3523 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3524 		hmeblkp->hblk_shw_bit = 1;
3525 	} else if (hmeblkp->hblk_shw_bit == 0) {
3526 		panic("sfmmu_shadow_hcreate: shw bit not set in hmeblkp 0x%p",
3527 		    (void *)hmeblkp);
3528 	}
3529 	ASSERT(hmeblkp->hblk_shw_bit == 1);
3530 	ASSERT(!hmeblkp->hblk_shared);
3531 	vshift = vaddr_to_vshift(hblktag, vaddr, size);
3532 	ASSERT(vshift < 8);
3533 	/*
3534 	 * Atomically set shw mask bit
3535 	 */
3536 	do {
3537 		shw_mask = hmeblkp->hblk_shw_mask;
3538 		newshw_mask = shw_mask | (1 << vshift);
3539 		newshw_mask = cas32(&hmeblkp->hblk_shw_mask, shw_mask,
3540 		    newshw_mask);
3541 	} while (newshw_mask != shw_mask);
3542 
3543 	SFMMU_HASH_UNLOCK(hmebp);
3544 
3545 	return (hmeblkp);
3546 }
3547 
3548 /*
3549  * This routine cleanup a previous shadow hmeblk and changes it to
3550  * a regular hblk.  This happens rarely but it is possible
3551  * when a process wants to use large pages and there are hblks still
3552  * lying around from the previous as that used these hmeblks.
3553  * The alternative was to cleanup the shadow hblks at unload time
3554  * but since so few user processes actually use large pages, it is
3555  * better to be lazy and cleanup at this time.
3556  */
3557 static void
3558 sfmmu_shadow_hcleanup(sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
3559 	struct hmehash_bucket *hmebp)
3560 {
3561 	caddr_t addr, endaddr;
3562 	int hashno, size;
3563 
3564 	ASSERT(hmeblkp->hblk_shw_bit);
3565 	ASSERT(!hmeblkp->hblk_shared);
3566 
3567 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3568 
3569 	if (!hmeblkp->hblk_shw_mask) {
3570 		hmeblkp->hblk_shw_bit = 0;
3571 		return;
3572 	}
3573 	addr = (caddr_t)get_hblk_base(hmeblkp);
3574 	endaddr = get_hblk_endaddr(hmeblkp);
3575 	size = get_hblk_ttesz(hmeblkp);
3576 	hashno = size - 1;
3577 	ASSERT(hashno > 0);
3578 	SFMMU_HASH_UNLOCK(hmebp);
3579 
3580 	sfmmu_free_hblks(sfmmup, addr, endaddr, hashno);
3581 
3582 	SFMMU_HASH_LOCK(hmebp);
3583 }
3584 
3585 static void
3586 sfmmu_free_hblks(sfmmu_t *sfmmup, caddr_t addr, caddr_t endaddr,
3587 	int hashno)
3588 {
3589 	int hmeshift, shadow = 0;
3590 	hmeblk_tag hblktag;
3591 	struct hmehash_bucket *hmebp;
3592 	struct hme_blk *hmeblkp;
3593 	struct hme_blk *nx_hblk, *pr_hblk, *list = NULL;
3594 	uint64_t hblkpa, prevpa, nx_pa;
3595 
3596 	ASSERT(hashno > 0);
3597 	hblktag.htag_id = sfmmup;
3598 	hblktag.htag_rehash = hashno;
3599 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3600 
3601 	hmeshift = HME_HASH_SHIFT(hashno);
3602 
3603 	while (addr < endaddr) {
3604 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3605 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3606 		SFMMU_HASH_LOCK(hmebp);
3607 		/* inline HME_HASH_SEARCH */
3608 		hmeblkp = hmebp->hmeblkp;
3609 		hblkpa = hmebp->hmeh_nextpa;
3610 		prevpa = 0;
3611 		pr_hblk = NULL;
3612 		while (hmeblkp) {
3613 			ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
3614 			if (HTAGS_EQ(hmeblkp->hblk_tag, hblktag)) {
3615 				/* found hme_blk */
3616 				ASSERT(!hmeblkp->hblk_shared);
3617 				if (hmeblkp->hblk_shw_bit) {
3618 					if (hmeblkp->hblk_shw_mask) {
3619 						shadow = 1;
3620 						sfmmu_shadow_hcleanup(sfmmup,
3621 						    hmeblkp, hmebp);
3622 						break;
3623 					} else {
3624 						hmeblkp->hblk_shw_bit = 0;
3625 					}
3626 				}
3627 
3628 				/*
3629 				 * Hblk_hmecnt and hblk_vcnt could be non zero
3630 				 * since hblk_unload() does not gurantee that.
3631 				 *
3632 				 * XXX - this could cause tteload() to spin
3633 				 * where sfmmu_shadow_hcleanup() is called.
3634 				 */
3635 			}
3636 
3637 			nx_hblk = hmeblkp->hblk_next;
3638 			nx_pa = hmeblkp->hblk_nextpa;
3639 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
3640 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa,
3641 				    pr_hblk);
3642 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
3643 			} else {
3644 				pr_hblk = hmeblkp;
3645 				prevpa = hblkpa;
3646 			}
3647 			hmeblkp = nx_hblk;
3648 			hblkpa = nx_pa;
3649 		}
3650 
3651 		SFMMU_HASH_UNLOCK(hmebp);
3652 
3653 		if (shadow) {
3654 			/*
3655 			 * We found another shadow hblk so cleaned its
3656 			 * children.  We need to go back and cleanup
3657 			 * the original hblk so we don't change the
3658 			 * addr.
3659 			 */
3660 			shadow = 0;
3661 		} else {
3662 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
3663 			    (1 << hmeshift));
3664 		}
3665 	}
3666 	sfmmu_hblks_list_purge(&list);
3667 }
3668 
3669 /*
3670  * This routine's job is to delete stale invalid shared hmeregions hmeblks that
3671  * may still linger on after pageunload.
3672  */
3673 static void
3674 sfmmu_cleanup_rhblk(sf_srd_t *srdp, caddr_t addr, uint_t rid, int ttesz)
3675 {
3676 	int hmeshift;
3677 	hmeblk_tag hblktag;
3678 	struct hmehash_bucket *hmebp;
3679 	struct hme_blk *hmeblkp;
3680 	struct hme_blk *pr_hblk;
3681 	struct hme_blk *list = NULL;
3682 	uint64_t hblkpa, prevpa;
3683 
3684 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3685 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3686 
3687 	hmeshift = HME_HASH_SHIFT(ttesz);
3688 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3689 	hblktag.htag_rehash = ttesz;
3690 	hblktag.htag_rid = rid;
3691 	hblktag.htag_id = srdp;
3692 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3693 
3694 	SFMMU_HASH_LOCK(hmebp);
3695 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa, pr_hblk,
3696 	    prevpa, &list);
3697 	if (hmeblkp != NULL) {
3698 		ASSERT(hmeblkp->hblk_shared);
3699 		ASSERT(!hmeblkp->hblk_shw_bit);
3700 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3701 			panic("sfmmu_cleanup_rhblk: valid hmeblk");
3702 		}
3703 		ASSERT(!hmeblkp->hblk_lckcnt);
3704 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
3705 		sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
3706 	}
3707 	SFMMU_HASH_UNLOCK(hmebp);
3708 	sfmmu_hblks_list_purge(&list);
3709 }
3710 
3711 /* ARGSUSED */
3712 static void
3713 sfmmu_rgn_cb_noop(caddr_t saddr, caddr_t eaddr, caddr_t r_saddr,
3714     size_t r_size, void *r_obj, u_offset_t r_objoff)
3715 {
3716 }
3717 
3718 /*
3719  * update *eaddrp only if hmeblk was unloaded.
3720  */
3721 static void
3722 sfmmu_unload_hmeregion_va(sf_srd_t *srdp, uint_t rid, caddr_t addr,
3723     caddr_t eaddr, int ttesz, caddr_t *eaddrp)
3724 {
3725 	int hmeshift;
3726 	hmeblk_tag hblktag;
3727 	struct hmehash_bucket *hmebp;
3728 	struct hme_blk *hmeblkp;
3729 	struct hme_blk *pr_hblk;
3730 	struct hme_blk *list = NULL;
3731 	uint64_t hblkpa, prevpa;
3732 
3733 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3734 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3735 	ASSERT(ttesz >= HBLK_MIN_TTESZ);
3736 
3737 	hmeshift = HME_HASH_SHIFT(ttesz);
3738 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3739 	hblktag.htag_rehash = ttesz;
3740 	hblktag.htag_rid = rid;
3741 	hblktag.htag_id = srdp;
3742 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3743 
3744 	SFMMU_HASH_LOCK(hmebp);
3745 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa, pr_hblk,
3746 	    prevpa, &list);
3747 	if (hmeblkp != NULL) {
3748 		ASSERT(hmeblkp->hblk_shared);
3749 		ASSERT(!hmeblkp->hblk_lckcnt);
3750 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3751 			*eaddrp = sfmmu_hblk_unload(NULL, hmeblkp, addr,
3752 			    eaddr, NULL, HAT_UNLOAD);
3753 			ASSERT(*eaddrp > addr);
3754 		}
3755 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3756 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
3757 		sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
3758 	}
3759 	SFMMU_HASH_UNLOCK(hmebp);
3760 	sfmmu_hblks_list_purge(&list);
3761 }
3762 
3763 /*
3764  * This routine can be optimized to eliminate scanning areas of smaller page
3765  * size bitmaps when a corresponding bit is set in the bitmap for a bigger
3766  * page size. For now assume the region will usually only have the primary
3767  * size mappings so we'll scan only one bitmap anyway by checking rgn_hmeflags
3768  * first.
3769  */
3770 static void
3771 sfmmu_unload_hmeregion(sf_srd_t *srdp, sf_region_t *rgnp)
3772 {
3773 	int ttesz = rgnp->rgn_pgszc;
3774 	size_t rsz = rgnp->rgn_size;
3775 	caddr_t rsaddr = rgnp->rgn_saddr;
3776 	caddr_t readdr = rsaddr + rsz;
3777 	caddr_t rhsaddr;
3778 	caddr_t va;
3779 	uint_t rid = rgnp->rgn_id;
3780 	caddr_t cbsaddr;
3781 	caddr_t cbeaddr;
3782 	hat_rgn_cb_func_t rcbfunc;
3783 	ulong_t cnt;
3784 
3785 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3786 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3787 
3788 	ASSERT(IS_P2ALIGNED(rsaddr, TTEBYTES(ttesz)));
3789 	ASSERT(IS_P2ALIGNED(rsz, TTEBYTES(ttesz)));
3790 	if (ttesz < HBLK_MIN_TTESZ) {
3791 		ttesz = HBLK_MIN_TTESZ;
3792 		rhsaddr = (caddr_t)P2ALIGN((uintptr_t)rsaddr, HBLK_MIN_BYTES);
3793 	} else {
3794 		rhsaddr = rsaddr;
3795 	}
3796 
3797 	if ((rcbfunc = rgnp->rgn_cb_function) == NULL) {
3798 		rcbfunc = sfmmu_rgn_cb_noop;
3799 	}
3800 
3801 	while (ttesz >= HBLK_MIN_TTESZ) {
3802 		cbsaddr = rsaddr;
3803 		cbeaddr = rsaddr;
3804 		if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
3805 			ttesz--;
3806 			continue;
3807 		}
3808 		cnt = 0;
3809 		va = rsaddr;
3810 		while (va < readdr) {
3811 			ASSERT(va >= rhsaddr);
3812 			if (va != cbeaddr) {
3813 				if (cbeaddr != cbsaddr) {
3814 					ASSERT(cbeaddr > cbsaddr);
3815 					(*rcbfunc)(cbsaddr, cbeaddr,
3816 					    rsaddr, rsz, rgnp->rgn_obj,
3817 					    rgnp->rgn_objoff);
3818 				}
3819 				cbsaddr = va;
3820 				cbeaddr = va;
3821 			}
3822 			sfmmu_unload_hmeregion_va(srdp, rid, va, readdr,
3823 			    ttesz, &cbeaddr);
3824 			cnt++;
3825 			va = rhsaddr + (cnt << TTE_PAGE_SHIFT(ttesz));
3826 		}
3827 		if (cbeaddr != cbsaddr) {
3828 			ASSERT(cbeaddr > cbsaddr);
3829 			(*rcbfunc)(cbsaddr, cbeaddr, rsaddr,
3830 			    rsz, rgnp->rgn_obj,
3831 			    rgnp->rgn_objoff);
3832 		}
3833 		ttesz--;
3834 	}
3835 }
3836 
3837 /*
3838  * Release one hardware address translation lock on the given address range.
3839  */
3840 void
3841 hat_unlock(struct hat *sfmmup, caddr_t addr, size_t len)
3842 {
3843 	struct hmehash_bucket *hmebp;
3844 	hmeblk_tag hblktag;
3845 	int hmeshift, hashno = 1;
3846 	struct hme_blk *hmeblkp, *list = NULL;
3847 	caddr_t endaddr;
3848 
3849 	ASSERT(sfmmup != NULL);
3850 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
3851 
3852 	ASSERT((sfmmup == ksfmmup) ||
3853 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
3854 	ASSERT((len & MMU_PAGEOFFSET) == 0);
3855 	endaddr = addr + len;
3856 	hblktag.htag_id = sfmmup;
3857 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3858 
3859 	/*
3860 	 * Spitfire supports 4 page sizes.
3861 	 * Most pages are expected to be of the smallest page size (8K) and
3862 	 * these will not need to be rehashed. 64K pages also don't need to be
3863 	 * rehashed because an hmeblk spans 64K of address space. 512K pages
3864 	 * might need 1 rehash and and 4M pages might need 2 rehashes.
3865 	 */
3866 	while (addr < endaddr) {
3867 		hmeshift = HME_HASH_SHIFT(hashno);
3868 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3869 		hblktag.htag_rehash = hashno;
3870 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3871 
3872 		SFMMU_HASH_LOCK(hmebp);
3873 
3874 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
3875 		if (hmeblkp != NULL) {
3876 			ASSERT(!hmeblkp->hblk_shared);
3877 			/*
3878 			 * If we encounter a shadow hmeblk then
3879 			 * we know there are no valid hmeblks mapping
3880 			 * this address at this size or larger.
3881 			 * Just increment address by the smallest
3882 			 * page size.
3883 			 */
3884 			if (hmeblkp->hblk_shw_bit) {
3885 				addr += MMU_PAGESIZE;
3886 			} else {
3887 				addr = sfmmu_hblk_unlock(hmeblkp, addr,
3888 				    endaddr);
3889 			}
3890 			SFMMU_HASH_UNLOCK(hmebp);
3891 			hashno = 1;
3892 			continue;
3893 		}
3894 		SFMMU_HASH_UNLOCK(hmebp);
3895 
3896 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
3897 			/*
3898 			 * We have traversed the whole list and rehashed
3899 			 * if necessary without finding the address to unlock
3900 			 * which should never happen.
3901 			 */
3902 			panic("sfmmu_unlock: addr not found. "
3903 			    "addr %p hat %p", (void *)addr, (void *)sfmmup);
3904 		} else {
3905 			hashno++;
3906 		}
3907 	}
3908 
3909 	sfmmu_hblks_list_purge(&list);
3910 }
3911 
3912 void
3913 hat_unlock_region(struct hat *sfmmup, caddr_t addr, size_t len,
3914     hat_region_cookie_t rcookie)
3915 {
3916 	sf_srd_t *srdp;
3917 	sf_region_t *rgnp;
3918 	int ttesz;
3919 	uint_t rid;
3920 	caddr_t eaddr;
3921 	caddr_t va;
3922 	int hmeshift;
3923 	hmeblk_tag hblktag;
3924 	struct hmehash_bucket *hmebp;
3925 	struct hme_blk *hmeblkp;
3926 	struct hme_blk *pr_hblk;
3927 	struct hme_blk *list;
3928 	uint64_t hblkpa, prevpa;
3929 
3930 	if (rcookie == HAT_INVALID_REGION_COOKIE) {
3931 		hat_unlock(sfmmup, addr, len);
3932 		return;
3933 	}
3934 
3935 	ASSERT(sfmmup != NULL);
3936 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
3937 	ASSERT(sfmmup != ksfmmup);
3938 
3939 	srdp = sfmmup->sfmmu_srdp;
3940 	rid = (uint_t)((uint64_t)rcookie);
3941 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3942 	eaddr = addr + len;
3943 	va = addr;
3944 	list = NULL;
3945 	rgnp = srdp->srd_hmergnp[rid];
3946 	SFMMU_VALIDATE_HMERID(sfmmup, rid, addr, len);
3947 
3948 	ASSERT(IS_P2ALIGNED(addr, TTEBYTES(rgnp->rgn_pgszc)));
3949 	ASSERT(IS_P2ALIGNED(len, TTEBYTES(rgnp->rgn_pgszc)));
3950 	if (rgnp->rgn_pgszc < HBLK_MIN_TTESZ) {
3951 		ttesz = HBLK_MIN_TTESZ;
3952 	} else {
3953 		ttesz = rgnp->rgn_pgszc;
3954 	}
3955 	while (va < eaddr) {
3956 		while (ttesz < rgnp->rgn_pgszc &&
3957 		    IS_P2ALIGNED(va, TTEBYTES(ttesz + 1))) {
3958 			ttesz++;
3959 		}
3960 		while (ttesz >= HBLK_MIN_TTESZ) {
3961 			if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
3962 				ttesz--;
3963 				continue;
3964 			}
3965 			hmeshift = HME_HASH_SHIFT(ttesz);
3966 			hblktag.htag_bspage = HME_HASH_BSPAGE(va, hmeshift);
3967 			hblktag.htag_rehash = ttesz;
3968 			hblktag.htag_rid = rid;
3969 			hblktag.htag_id = srdp;
3970 			hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3971 			SFMMU_HASH_LOCK(hmebp);
3972 			HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa,
3973 			    pr_hblk, prevpa, &list);
3974 			if (hmeblkp == NULL) {
3975 				ttesz--;
3976 				continue;
3977 			}
3978 			ASSERT(hmeblkp->hblk_shared);
3979 			va = sfmmu_hblk_unlock(hmeblkp, va, eaddr);
3980 			ASSERT(va >= eaddr ||
3981 			    IS_P2ALIGNED((uintptr_t)va, TTEBYTES(ttesz)));
3982 			SFMMU_HASH_UNLOCK(hmebp);
3983 			break;
3984 		}
3985 		if (ttesz < HBLK_MIN_TTESZ) {
3986 			panic("hat_unlock_region: addr not found "
3987 			    "addr %p hat %p", va, sfmmup);
3988 		}
3989 	}
3990 	sfmmu_hblks_list_purge(&list);
3991 }
3992 
3993 /*
3994  * Function to unlock a range of addresses in an hmeblk.  It returns the
3995  * next address that needs to be unlocked.
3996  * Should be called with the hash lock held.
3997  */
3998 static caddr_t
3999 sfmmu_hblk_unlock(struct hme_blk *hmeblkp, caddr_t addr, caddr_t endaddr)
4000 {
4001 	struct sf_hment *sfhme;
4002 	tte_t tteold, ttemod;
4003 	int ttesz, ret;
4004 
4005 	ASSERT(in_hblk_range(hmeblkp, addr));
4006 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4007 
4008 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4009 	ttesz = get_hblk_ttesz(hmeblkp);
4010 
4011 	HBLKTOHME(sfhme, hmeblkp, addr);
4012 	while (addr < endaddr) {
4013 readtte:
4014 		sfmmu_copytte(&sfhme->hme_tte, &tteold);
4015 		if (TTE_IS_VALID(&tteold)) {
4016 
4017 			ttemod = tteold;
4018 
4019 			ret = sfmmu_modifytte_try(&tteold, &ttemod,
4020 			    &sfhme->hme_tte);
4021 
4022 			if (ret < 0)
4023 				goto readtte;
4024 
4025 			if (hmeblkp->hblk_lckcnt == 0)
4026 				panic("zero hblk lckcnt");
4027 
4028 			if (((uintptr_t)addr + TTEBYTES(ttesz)) >
4029 			    (uintptr_t)endaddr)
4030 				panic("can't unlock large tte");
4031 
4032 			ASSERT(hmeblkp->hblk_lckcnt > 0);
4033 			atomic_add_32(&hmeblkp->hblk_lckcnt, -1);
4034 			HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
4035 		} else {
4036 			panic("sfmmu_hblk_unlock: invalid tte");
4037 		}
4038 		addr += TTEBYTES(ttesz);
4039 		sfhme++;
4040 	}
4041 	return (addr);
4042 }
4043 
4044 /*
4045  * Physical Address Mapping Framework
4046  *
4047  * General rules:
4048  *
4049  * (1) Applies only to seg_kmem memory pages. To make things easier,
4050  *     seg_kpm addresses are also accepted by the routines, but nothing
4051  *     is done with them since by definition their PA mappings are static.
4052  * (2) hat_add_callback() may only be called while holding the page lock
4053  *     SE_SHARED or SE_EXCL of the underlying page (e.g., as_pagelock()),
4054  *     or passing HAC_PAGELOCK flag.
4055  * (3) prehandler() and posthandler() may not call hat_add_callback() or
4056  *     hat_delete_callback(), nor should they allocate memory. Post quiesce
4057  *     callbacks may not sleep or acquire adaptive mutex locks.
4058  * (4) Either prehandler() or posthandler() (but not both) may be specified
4059  *     as being NULL.  Specifying an errhandler() is optional.
4060  *
4061  * Details of using the framework:
4062  *
4063  * registering a callback (hat_register_callback())
4064  *
4065  *	Pass prehandler, posthandler, errhandler addresses
4066  *	as described below. If capture_cpus argument is nonzero,
4067  *	suspend callback to the prehandler will occur with CPUs
4068  *	captured and executing xc_loop() and CPUs will remain
4069  *	captured until after the posthandler suspend callback
4070  *	occurs.
4071  *
4072  * adding a callback (hat_add_callback())
4073  *
4074  *      as_pagelock();
4075  *	hat_add_callback();
4076  *      save returned pfn in private data structures or program registers;
4077  *      as_pageunlock();
4078  *
4079  * prehandler()
4080  *
4081  *	Stop all accesses by physical address to this memory page.
4082  *	Called twice: the first, PRESUSPEND, is a context safe to acquire
4083  *	adaptive locks. The second, SUSPEND, is called at high PIL with
4084  *	CPUs captured so adaptive locks may NOT be acquired (and all spin
4085  *	locks must be XCALL_PIL or higher locks).
4086  *
4087  *	May return the following errors:
4088  *		EIO:	A fatal error has occurred. This will result in panic.
4089  *		EAGAIN:	The page cannot be suspended. This will fail the
4090  *			relocation.
4091  *		0:	Success.
4092  *
4093  * posthandler()
4094  *
4095  *      Save new pfn in private data structures or program registers;
4096  *	not allowed to fail (non-zero return values will result in panic).
4097  *
4098  * errhandler()
4099  *
4100  *	called when an error occurs related to the callback.  Currently
4101  *	the only such error is HAT_CB_ERR_LEAKED which indicates that
4102  *	a page is being freed, but there are still outstanding callback(s)
4103  *	registered on the page.
4104  *
4105  * removing a callback (hat_delete_callback(); e.g., prior to freeing memory)
4106  *
4107  *	stop using physical address
4108  *	hat_delete_callback();
4109  *
4110  */
4111 
4112 /*
4113  * Register a callback class.  Each subsystem should do this once and
4114  * cache the id_t returned for use in setting up and tearing down callbacks.
4115  *
4116  * There is no facility for removing callback IDs once they are created;
4117  * the "key" should be unique for each module, so in case a module is unloaded
4118  * and subsequently re-loaded, we can recycle the module's previous entry.
4119  */
4120 id_t
4121 hat_register_callback(int key,
4122 	int (*prehandler)(caddr_t, uint_t, uint_t, void *),
4123 	int (*posthandler)(caddr_t, uint_t, uint_t, void *, pfn_t),
4124 	int (*errhandler)(caddr_t, uint_t, uint_t, void *),
4125 	int capture_cpus)
4126 {
4127 	id_t id;
4128 
4129 	/*
4130 	 * Search the table for a pre-existing callback associated with
4131 	 * the identifier "key".  If one exists, we re-use that entry in
4132 	 * the table for this instance, otherwise we assign the next
4133 	 * available table slot.
4134 	 */
4135 	for (id = 0; id < sfmmu_max_cb_id; id++) {
4136 		if (sfmmu_cb_table[id].key == key)
4137 			break;
4138 	}
4139 
4140 	if (id == sfmmu_max_cb_id) {
4141 		id = sfmmu_cb_nextid++;
4142 		if (id >= sfmmu_max_cb_id)
4143 			panic("hat_register_callback: out of callback IDs");
4144 	}
4145 
4146 	ASSERT(prehandler != NULL || posthandler != NULL);
4147 
4148 	sfmmu_cb_table[id].key = key;
4149 	sfmmu_cb_table[id].prehandler = prehandler;
4150 	sfmmu_cb_table[id].posthandler = posthandler;
4151 	sfmmu_cb_table[id].errhandler = errhandler;
4152 	sfmmu_cb_table[id].capture_cpus = capture_cpus;
4153 
4154 	return (id);
4155 }
4156 
4157 #define	HAC_COOKIE_NONE	(void *)-1
4158 
4159 /*
4160  * Add relocation callbacks to the specified addr/len which will be called
4161  * when relocating the associated page. See the description of pre and
4162  * posthandler above for more details.
4163  *
4164  * If HAC_PAGELOCK is included in flags, the underlying memory page is
4165  * locked internally so the caller must be able to deal with the callback
4166  * running even before this function has returned.  If HAC_PAGELOCK is not
4167  * set, it is assumed that the underlying memory pages are locked.
4168  *
4169  * Since the caller must track the individual page boundaries anyway,
4170  * we only allow a callback to be added to a single page (large
4171  * or small).  Thus [addr, addr + len) MUST be contained within a single
4172  * page.
4173  *
4174  * Registering multiple callbacks on the same [addr, addr+len) is supported,
4175  * _provided_that_ a unique parameter is specified for each callback.
4176  * If multiple callbacks are registered on the same range the callback will
4177  * be invoked with each unique parameter. Registering the same callback with
4178  * the same argument more than once will result in corrupted kernel state.
4179  *
4180  * Returns the pfn of the underlying kernel page in *rpfn
4181  * on success, or PFN_INVALID on failure.
4182  *
4183  * cookiep (if passed) provides storage space for an opaque cookie
4184  * to return later to hat_delete_callback(). This cookie makes the callback
4185  * deletion significantly quicker by avoiding a potentially lengthy hash
4186  * search.
4187  *
4188  * Returns values:
4189  *    0:      success
4190  *    ENOMEM: memory allocation failure (e.g. flags was passed as HAC_NOSLEEP)
4191  *    EINVAL: callback ID is not valid
4192  *    ENXIO:  ["vaddr", "vaddr" + len) is not mapped in the kernel's address
4193  *            space
4194  *    ERANGE: ["vaddr", "vaddr" + len) crosses a page boundary
4195  */
4196 int
4197 hat_add_callback(id_t callback_id, caddr_t vaddr, uint_t len, uint_t flags,
4198 	void *pvt, pfn_t *rpfn, void **cookiep)
4199 {
4200 	struct 		hmehash_bucket *hmebp;
4201 	hmeblk_tag 	hblktag;
4202 	struct hme_blk	*hmeblkp;
4203 	int 		hmeshift, hashno;
4204 	caddr_t 	saddr, eaddr, baseaddr;
4205 	struct pa_hment *pahmep;
4206 	struct sf_hment *sfhmep, *osfhmep;
4207 	kmutex_t	*pml;
4208 	tte_t   	tte;
4209 	page_t		*pp;
4210 	vnode_t		*vp;
4211 	u_offset_t	off;
4212 	pfn_t		pfn;
4213 	int		kmflags = (flags & HAC_SLEEP)? KM_SLEEP : KM_NOSLEEP;
4214 	int		locked = 0;
4215 
4216 	/*
4217 	 * For KPM mappings, just return the physical address since we
4218 	 * don't need to register any callbacks.
4219 	 */
4220 	if (IS_KPM_ADDR(vaddr)) {
4221 		uint64_t paddr;
4222 		SFMMU_KPM_VTOP(vaddr, paddr);
4223 		*rpfn = btop(paddr);
4224 		if (cookiep != NULL)
4225 			*cookiep = HAC_COOKIE_NONE;
4226 		return (0);
4227 	}
4228 
4229 	if (callback_id < (id_t)0 || callback_id >= sfmmu_cb_nextid) {
4230 		*rpfn = PFN_INVALID;
4231 		return (EINVAL);
4232 	}
4233 
4234 	if ((pahmep = kmem_cache_alloc(pa_hment_cache, kmflags)) == NULL) {
4235 		*rpfn = PFN_INVALID;
4236 		return (ENOMEM);
4237 	}
4238 
4239 	sfhmep = &pahmep->sfment;
4240 
4241 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4242 	eaddr = saddr + len;
4243 
4244 rehash:
4245 	/* Find the mapping(s) for this page */
4246 	for (hashno = TTE64K, hmeblkp = NULL;
4247 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4248 	    hashno++) {
4249 		hmeshift = HME_HASH_SHIFT(hashno);
4250 		hblktag.htag_id = ksfmmup;
4251 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4252 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4253 		hblktag.htag_rehash = hashno;
4254 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4255 
4256 		SFMMU_HASH_LOCK(hmebp);
4257 
4258 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4259 
4260 		if (hmeblkp == NULL)
4261 			SFMMU_HASH_UNLOCK(hmebp);
4262 	}
4263 
4264 	if (hmeblkp == NULL) {
4265 		kmem_cache_free(pa_hment_cache, pahmep);
4266 		*rpfn = PFN_INVALID;
4267 		return (ENXIO);
4268 	}
4269 
4270 	ASSERT(!hmeblkp->hblk_shared);
4271 
4272 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4273 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4274 
4275 	if (!TTE_IS_VALID(&tte)) {
4276 		SFMMU_HASH_UNLOCK(hmebp);
4277 		kmem_cache_free(pa_hment_cache, pahmep);
4278 		*rpfn = PFN_INVALID;
4279 		return (ENXIO);
4280 	}
4281 
4282 	/*
4283 	 * Make sure the boundaries for the callback fall within this
4284 	 * single mapping.
4285 	 */
4286 	baseaddr = (caddr_t)get_hblk_base(hmeblkp);
4287 	ASSERT(saddr >= baseaddr);
4288 	if (eaddr > saddr + TTEBYTES(TTE_CSZ(&tte))) {
4289 		SFMMU_HASH_UNLOCK(hmebp);
4290 		kmem_cache_free(pa_hment_cache, pahmep);
4291 		*rpfn = PFN_INVALID;
4292 		return (ERANGE);
4293 	}
4294 
4295 	pfn = sfmmu_ttetopfn(&tte, vaddr);
4296 
4297 	/*
4298 	 * The pfn may not have a page_t underneath in which case we
4299 	 * just return it. This can happen if we are doing I/O to a
4300 	 * static portion of the kernel's address space, for instance.
4301 	 */
4302 	pp = osfhmep->hme_page;
4303 	if (pp == NULL) {
4304 		SFMMU_HASH_UNLOCK(hmebp);
4305 		kmem_cache_free(pa_hment_cache, pahmep);
4306 		*rpfn = pfn;
4307 		if (cookiep)
4308 			*cookiep = HAC_COOKIE_NONE;
4309 		return (0);
4310 	}
4311 	ASSERT(pp == PP_PAGEROOT(pp));
4312 
4313 	vp = pp->p_vnode;
4314 	off = pp->p_offset;
4315 
4316 	pml = sfmmu_mlist_enter(pp);
4317 
4318 	if (flags & HAC_PAGELOCK) {
4319 		if (!page_trylock(pp, SE_SHARED)) {
4320 			/*
4321 			 * Somebody is holding SE_EXCL lock. Might
4322 			 * even be hat_page_relocate(). Drop all
4323 			 * our locks, lookup the page in &kvp, and
4324 			 * retry. If it doesn't exist in &kvp and &zvp,
4325 			 * then we must be dealing with a kernel mapped
4326 			 * page which doesn't actually belong to
4327 			 * segkmem so we punt.
4328 			 */
4329 			sfmmu_mlist_exit(pml);
4330 			SFMMU_HASH_UNLOCK(hmebp);
4331 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4332 
4333 			/* check zvp before giving up */
4334 			if (pp == NULL)
4335 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4336 				    SE_SHARED);
4337 
4338 			/* Okay, we didn't find it, give up */
4339 			if (pp == NULL) {
4340 				kmem_cache_free(pa_hment_cache, pahmep);
4341 				*rpfn = pfn;
4342 				if (cookiep)
4343 					*cookiep = HAC_COOKIE_NONE;
4344 				return (0);
4345 			}
4346 			page_unlock(pp);
4347 			goto rehash;
4348 		}
4349 		locked = 1;
4350 	}
4351 
4352 	if (!PAGE_LOCKED(pp) && !panicstr)
4353 		panic("hat_add_callback: page 0x%p not locked", pp);
4354 
4355 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4356 	    pp->p_offset != off) {
4357 		/*
4358 		 * The page moved before we got our hands on it.  Drop
4359 		 * all the locks and try again.
4360 		 */
4361 		ASSERT((flags & HAC_PAGELOCK) != 0);
4362 		sfmmu_mlist_exit(pml);
4363 		SFMMU_HASH_UNLOCK(hmebp);
4364 		page_unlock(pp);
4365 		locked = 0;
4366 		goto rehash;
4367 	}
4368 
4369 	if (!VN_ISKAS(vp)) {
4370 		/*
4371 		 * This is not a segkmem page but another page which
4372 		 * has been kernel mapped. It had better have at least
4373 		 * a share lock on it. Return the pfn.
4374 		 */
4375 		sfmmu_mlist_exit(pml);
4376 		SFMMU_HASH_UNLOCK(hmebp);
4377 		if (locked)
4378 			page_unlock(pp);
4379 		kmem_cache_free(pa_hment_cache, pahmep);
4380 		ASSERT(PAGE_LOCKED(pp));
4381 		*rpfn = pfn;
4382 		if (cookiep)
4383 			*cookiep = HAC_COOKIE_NONE;
4384 		return (0);
4385 	}
4386 
4387 	/*
4388 	 * Setup this pa_hment and link its embedded dummy sf_hment into
4389 	 * the mapping list.
4390 	 */
4391 	pp->p_share++;
4392 	pahmep->cb_id = callback_id;
4393 	pahmep->addr = vaddr;
4394 	pahmep->len = len;
4395 	pahmep->refcnt = 1;
4396 	pahmep->flags = 0;
4397 	pahmep->pvt = pvt;
4398 
4399 	sfhmep->hme_tte.ll = 0;
4400 	sfhmep->hme_data = pahmep;
4401 	sfhmep->hme_prev = osfhmep;
4402 	sfhmep->hme_next = osfhmep->hme_next;
4403 
4404 	if (osfhmep->hme_next)
4405 		osfhmep->hme_next->hme_prev = sfhmep;
4406 
4407 	osfhmep->hme_next = sfhmep;
4408 
4409 	sfmmu_mlist_exit(pml);
4410 	SFMMU_HASH_UNLOCK(hmebp);
4411 
4412 	if (locked)
4413 		page_unlock(pp);
4414 
4415 	*rpfn = pfn;
4416 	if (cookiep)
4417 		*cookiep = (void *)pahmep;
4418 
4419 	return (0);
4420 }
4421 
4422 /*
4423  * Remove the relocation callbacks from the specified addr/len.
4424  */
4425 void
4426 hat_delete_callback(caddr_t vaddr, uint_t len, void *pvt, uint_t flags,
4427 	void *cookie)
4428 {
4429 	struct		hmehash_bucket *hmebp;
4430 	hmeblk_tag	hblktag;
4431 	struct hme_blk	*hmeblkp;
4432 	int		hmeshift, hashno;
4433 	caddr_t		saddr;
4434 	struct pa_hment	*pahmep;
4435 	struct sf_hment	*sfhmep, *osfhmep;
4436 	kmutex_t	*pml;
4437 	tte_t		tte;
4438 	page_t		*pp;
4439 	vnode_t		*vp;
4440 	u_offset_t	off;
4441 	int		locked = 0;
4442 
4443 	/*
4444 	 * If the cookie is HAC_COOKIE_NONE then there is no pa_hment to
4445 	 * remove so just return.
4446 	 */
4447 	if (cookie == HAC_COOKIE_NONE || IS_KPM_ADDR(vaddr))
4448 		return;
4449 
4450 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4451 
4452 rehash:
4453 	/* Find the mapping(s) for this page */
4454 	for (hashno = TTE64K, hmeblkp = NULL;
4455 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4456 	    hashno++) {
4457 		hmeshift = HME_HASH_SHIFT(hashno);
4458 		hblktag.htag_id = ksfmmup;
4459 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4460 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4461 		hblktag.htag_rehash = hashno;
4462 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4463 
4464 		SFMMU_HASH_LOCK(hmebp);
4465 
4466 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4467 
4468 		if (hmeblkp == NULL)
4469 			SFMMU_HASH_UNLOCK(hmebp);
4470 	}
4471 
4472 	if (hmeblkp == NULL)
4473 		return;
4474 
4475 	ASSERT(!hmeblkp->hblk_shared);
4476 
4477 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4478 
4479 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4480 	if (!TTE_IS_VALID(&tte)) {
4481 		SFMMU_HASH_UNLOCK(hmebp);
4482 		return;
4483 	}
4484 
4485 	pp = osfhmep->hme_page;
4486 	if (pp == NULL) {
4487 		SFMMU_HASH_UNLOCK(hmebp);
4488 		ASSERT(cookie == NULL);
4489 		return;
4490 	}
4491 
4492 	vp = pp->p_vnode;
4493 	off = pp->p_offset;
4494 
4495 	pml = sfmmu_mlist_enter(pp);
4496 
4497 	if (flags & HAC_PAGELOCK) {
4498 		if (!page_trylock(pp, SE_SHARED)) {
4499 			/*
4500 			 * Somebody is holding SE_EXCL lock. Might
4501 			 * even be hat_page_relocate(). Drop all
4502 			 * our locks, lookup the page in &kvp, and
4503 			 * retry. If it doesn't exist in &kvp and &zvp,
4504 			 * then we must be dealing with a kernel mapped
4505 			 * page which doesn't actually belong to
4506 			 * segkmem so we punt.
4507 			 */
4508 			sfmmu_mlist_exit(pml);
4509 			SFMMU_HASH_UNLOCK(hmebp);
4510 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4511 			/* check zvp before giving up */
4512 			if (pp == NULL)
4513 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4514 				    SE_SHARED);
4515 
4516 			if (pp == NULL) {
4517 				ASSERT(cookie == NULL);
4518 				return;
4519 			}
4520 			page_unlock(pp);
4521 			goto rehash;
4522 		}
4523 		locked = 1;
4524 	}
4525 
4526 	ASSERT(PAGE_LOCKED(pp));
4527 
4528 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4529 	    pp->p_offset != off) {
4530 		/*
4531 		 * The page moved before we got our hands on it.  Drop
4532 		 * all the locks and try again.
4533 		 */
4534 		ASSERT((flags & HAC_PAGELOCK) != 0);
4535 		sfmmu_mlist_exit(pml);
4536 		SFMMU_HASH_UNLOCK(hmebp);
4537 		page_unlock(pp);
4538 		locked = 0;
4539 		goto rehash;
4540 	}
4541 
4542 	if (!VN_ISKAS(vp)) {
4543 		/*
4544 		 * This is not a segkmem page but another page which
4545 		 * has been kernel mapped.
4546 		 */
4547 		sfmmu_mlist_exit(pml);
4548 		SFMMU_HASH_UNLOCK(hmebp);
4549 		if (locked)
4550 			page_unlock(pp);
4551 		ASSERT(cookie == NULL);
4552 		return;
4553 	}
4554 
4555 	if (cookie != NULL) {
4556 		pahmep = (struct pa_hment *)cookie;
4557 		sfhmep = &pahmep->sfment;
4558 	} else {
4559 		for (sfhmep = pp->p_mapping; sfhmep != NULL;
4560 		    sfhmep = sfhmep->hme_next) {
4561 
4562 			/*
4563 			 * skip va<->pa mappings
4564 			 */
4565 			if (!IS_PAHME(sfhmep))
4566 				continue;
4567 
4568 			pahmep = sfhmep->hme_data;
4569 			ASSERT(pahmep != NULL);
4570 
4571 			/*
4572 			 * if pa_hment matches, remove it
4573 			 */
4574 			if ((pahmep->pvt == pvt) &&
4575 			    (pahmep->addr == vaddr) &&
4576 			    (pahmep->len == len)) {
4577 				break;
4578 			}
4579 		}
4580 	}
4581 
4582 	if (sfhmep == NULL) {
4583 		if (!panicstr) {
4584 			panic("hat_delete_callback: pa_hment not found, pp %p",
4585 			    (void *)pp);
4586 		}
4587 		return;
4588 	}
4589 
4590 	/*
4591 	 * Note: at this point a valid kernel mapping must still be
4592 	 * present on this page.
4593 	 */
4594 	pp->p_share--;
4595 	if (pp->p_share <= 0)
4596 		panic("hat_delete_callback: zero p_share");
4597 
4598 	if (--pahmep->refcnt == 0) {
4599 		if (pahmep->flags != 0)
4600 			panic("hat_delete_callback: pa_hment is busy");
4601 
4602 		/*
4603 		 * Remove sfhmep from the mapping list for the page.
4604 		 */
4605 		if (sfhmep->hme_prev) {
4606 			sfhmep->hme_prev->hme_next = sfhmep->hme_next;
4607 		} else {
4608 			pp->p_mapping = sfhmep->hme_next;
4609 		}
4610 
4611 		if (sfhmep->hme_next)
4612 			sfhmep->hme_next->hme_prev = sfhmep->hme_prev;
4613 
4614 		sfmmu_mlist_exit(pml);
4615 		SFMMU_HASH_UNLOCK(hmebp);
4616 
4617 		if (locked)
4618 			page_unlock(pp);
4619 
4620 		kmem_cache_free(pa_hment_cache, pahmep);
4621 		return;
4622 	}
4623 
4624 	sfmmu_mlist_exit(pml);
4625 	SFMMU_HASH_UNLOCK(hmebp);
4626 	if (locked)
4627 		page_unlock(pp);
4628 }
4629 
4630 /*
4631  * hat_probe returns 1 if the translation for the address 'addr' is
4632  * loaded, zero otherwise.
4633  *
4634  * hat_probe should be used only for advisorary purposes because it may
4635  * occasionally return the wrong value. The implementation must guarantee that
4636  * returning the wrong value is a very rare event. hat_probe is used
4637  * to implement optimizations in the segment drivers.
4638  *
4639  */
4640 int
4641 hat_probe(struct hat *sfmmup, caddr_t addr)
4642 {
4643 	pfn_t pfn;
4644 	tte_t tte;
4645 
4646 	ASSERT(sfmmup != NULL);
4647 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4648 
4649 	ASSERT((sfmmup == ksfmmup) ||
4650 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4651 
4652 	if (sfmmup == ksfmmup) {
4653 		while ((pfn = sfmmu_vatopfn(addr, sfmmup, &tte))
4654 		    == PFN_SUSPENDED) {
4655 			sfmmu_vatopfn_suspended(addr, sfmmup, &tte);
4656 		}
4657 	} else {
4658 		pfn = sfmmu_uvatopfn(addr, sfmmup, NULL);
4659 	}
4660 
4661 	if (pfn != PFN_INVALID)
4662 		return (1);
4663 	else
4664 		return (0);
4665 }
4666 
4667 ssize_t
4668 hat_getpagesize(struct hat *sfmmup, caddr_t addr)
4669 {
4670 	tte_t tte;
4671 
4672 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4673 
4674 	if (sfmmup == ksfmmup) {
4675 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4676 			return (-1);
4677 		}
4678 	} else {
4679 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4680 			return (-1);
4681 		}
4682 	}
4683 
4684 	ASSERT(TTE_IS_VALID(&tte));
4685 	return (TTEBYTES(TTE_CSZ(&tte)));
4686 }
4687 
4688 uint_t
4689 hat_getattr(struct hat *sfmmup, caddr_t addr, uint_t *attr)
4690 {
4691 	tte_t tte;
4692 
4693 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4694 
4695 	if (sfmmup == ksfmmup) {
4696 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4697 			tte.ll = 0;
4698 		}
4699 	} else {
4700 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4701 			tte.ll = 0;
4702 		}
4703 	}
4704 	if (TTE_IS_VALID(&tte)) {
4705 		*attr = sfmmu_ptov_attr(&tte);
4706 		return (0);
4707 	}
4708 	*attr = 0;
4709 	return ((uint_t)0xffffffff);
4710 }
4711 
4712 /*
4713  * Enables more attributes on specified address range (ie. logical OR)
4714  */
4715 void
4716 hat_setattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4717 {
4718 	if (hat->sfmmu_xhat_provider) {
4719 		XHAT_SETATTR(hat, addr, len, attr);
4720 		return;
4721 	} else {
4722 		/*
4723 		 * This must be a CPU HAT. If the address space has
4724 		 * XHATs attached, change attributes for all of them,
4725 		 * just in case
4726 		 */
4727 		ASSERT(hat->sfmmu_as != NULL);
4728 		if (hat->sfmmu_as->a_xhat != NULL)
4729 			xhat_setattr_all(hat->sfmmu_as, addr, len, attr);
4730 	}
4731 
4732 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_SETATTR);
4733 }
4734 
4735 /*
4736  * Assigns attributes to the specified address range.  All the attributes
4737  * are specified.
4738  */
4739 void
4740 hat_chgattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4741 {
4742 	if (hat->sfmmu_xhat_provider) {
4743 		XHAT_CHGATTR(hat, addr, len, attr);
4744 		return;
4745 	} else {
4746 		/*
4747 		 * This must be a CPU HAT. If the address space has
4748 		 * XHATs attached, change attributes for all of them,
4749 		 * just in case
4750 		 */
4751 		ASSERT(hat->sfmmu_as != NULL);
4752 		if (hat->sfmmu_as->a_xhat != NULL)
4753 			xhat_chgattr_all(hat->sfmmu_as, addr, len, attr);
4754 	}
4755 
4756 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CHGATTR);
4757 }
4758 
4759 /*
4760  * Remove attributes on the specified address range (ie. loginal NAND)
4761  */
4762 void
4763 hat_clrattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4764 {
4765 	if (hat->sfmmu_xhat_provider) {
4766 		XHAT_CLRATTR(hat, addr, len, attr);
4767 		return;
4768 	} else {
4769 		/*
4770 		 * This must be a CPU HAT. If the address space has
4771 		 * XHATs attached, change attributes for all of them,
4772 		 * just in case
4773 		 */
4774 		ASSERT(hat->sfmmu_as != NULL);
4775 		if (hat->sfmmu_as->a_xhat != NULL)
4776 			xhat_clrattr_all(hat->sfmmu_as, addr, len, attr);
4777 	}
4778 
4779 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CLRATTR);
4780 }
4781 
4782 /*
4783  * Change attributes on an address range to that specified by attr and mode.
4784  */
4785 static void
4786 sfmmu_chgattr(struct hat *sfmmup, caddr_t addr, size_t len, uint_t attr,
4787 	int mode)
4788 {
4789 	struct hmehash_bucket *hmebp;
4790 	hmeblk_tag hblktag;
4791 	int hmeshift, hashno = 1;
4792 	struct hme_blk *hmeblkp, *list = NULL;
4793 	caddr_t endaddr;
4794 	cpuset_t cpuset;
4795 	demap_range_t dmr;
4796 
4797 	CPUSET_ZERO(cpuset);
4798 
4799 	ASSERT((sfmmup == ksfmmup) ||
4800 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4801 	ASSERT((len & MMU_PAGEOFFSET) == 0);
4802 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
4803 
4804 	if ((attr & PROT_USER) && (mode != SFMMU_CLRATTR) &&
4805 	    ((addr + len) > (caddr_t)USERLIMIT)) {
4806 		panic("user addr %p in kernel space",
4807 		    (void *)addr);
4808 	}
4809 
4810 	endaddr = addr + len;
4811 	hblktag.htag_id = sfmmup;
4812 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4813 	DEMAP_RANGE_INIT(sfmmup, &dmr);
4814 
4815 	while (addr < endaddr) {
4816 		hmeshift = HME_HASH_SHIFT(hashno);
4817 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
4818 		hblktag.htag_rehash = hashno;
4819 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
4820 
4821 		SFMMU_HASH_LOCK(hmebp);
4822 
4823 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
4824 		if (hmeblkp != NULL) {
4825 			ASSERT(!hmeblkp->hblk_shared);
4826 			/*
4827 			 * We've encountered a shadow hmeblk so skip the range
4828 			 * of the next smaller mapping size.
4829 			 */
4830 			if (hmeblkp->hblk_shw_bit) {
4831 				ASSERT(sfmmup != ksfmmup);
4832 				ASSERT(hashno > 1);
4833 				addr = (caddr_t)P2END((uintptr_t)addr,
4834 				    TTEBYTES(hashno - 1));
4835 			} else {
4836 				addr = sfmmu_hblk_chgattr(sfmmup,
4837 				    hmeblkp, addr, endaddr, &dmr, attr, mode);
4838 			}
4839 			SFMMU_HASH_UNLOCK(hmebp);
4840 			hashno = 1;
4841 			continue;
4842 		}
4843 		SFMMU_HASH_UNLOCK(hmebp);
4844 
4845 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
4846 			/*
4847 			 * We have traversed the whole list and rehashed
4848 			 * if necessary without finding the address to chgattr.
4849 			 * This is ok, so we increment the address by the
4850 			 * smallest hmeblk range for kernel mappings or for
4851 			 * user mappings with no large pages, and the largest
4852 			 * hmeblk range, to account for shadow hmeblks, for
4853 			 * user mappings with large pages and continue.
4854 			 */
4855 			if (sfmmup == ksfmmup)
4856 				addr = (caddr_t)P2END((uintptr_t)addr,
4857 				    TTEBYTES(1));
4858 			else
4859 				addr = (caddr_t)P2END((uintptr_t)addr,
4860 				    TTEBYTES(hashno));
4861 			hashno = 1;
4862 		} else {
4863 			hashno++;
4864 		}
4865 	}
4866 
4867 	sfmmu_hblks_list_purge(&list);
4868 	DEMAP_RANGE_FLUSH(&dmr);
4869 	cpuset = sfmmup->sfmmu_cpusran;
4870 	xt_sync(cpuset);
4871 }
4872 
4873 /*
4874  * This function chgattr on a range of addresses in an hmeblk.  It returns the
4875  * next addres that needs to be chgattr.
4876  * It should be called with the hash lock held.
4877  * XXX It should be possible to optimize chgattr by not flushing every time but
4878  * on the other hand:
4879  * 1. do one flush crosscall.
4880  * 2. only flush if we are increasing permissions (make sure this will work)
4881  */
4882 static caddr_t
4883 sfmmu_hblk_chgattr(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
4884 	caddr_t endaddr, demap_range_t *dmrp, uint_t attr, int mode)
4885 {
4886 	tte_t tte, tteattr, tteflags, ttemod;
4887 	struct sf_hment *sfhmep;
4888 	int ttesz;
4889 	struct page *pp = NULL;
4890 	kmutex_t *pml, *pmtx;
4891 	int ret;
4892 	int use_demap_range;
4893 #if defined(SF_ERRATA_57)
4894 	int check_exec;
4895 #endif
4896 
4897 	ASSERT(in_hblk_range(hmeblkp, addr));
4898 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4899 	ASSERT(!hmeblkp->hblk_shared);
4900 
4901 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4902 	ttesz = get_hblk_ttesz(hmeblkp);
4903 
4904 	/*
4905 	 * Flush the current demap region if addresses have been
4906 	 * skipped or the page size doesn't match.
4907 	 */
4908 	use_demap_range = (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp));
4909 	if (use_demap_range) {
4910 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
4911 	} else {
4912 		DEMAP_RANGE_FLUSH(dmrp);
4913 	}
4914 
4915 	tteattr.ll = sfmmu_vtop_attr(attr, mode, &tteflags);
4916 #if defined(SF_ERRATA_57)
4917 	check_exec = (sfmmup != ksfmmup) &&
4918 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
4919 	    TTE_IS_EXECUTABLE(&tteattr);
4920 #endif
4921 	HBLKTOHME(sfhmep, hmeblkp, addr);
4922 	while (addr < endaddr) {
4923 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
4924 		if (TTE_IS_VALID(&tte)) {
4925 			if ((tte.ll & tteflags.ll) == tteattr.ll) {
4926 				/*
4927 				 * if the new attr is the same as old
4928 				 * continue
4929 				 */
4930 				goto next_addr;
4931 			}
4932 			if (!TTE_IS_WRITABLE(&tteattr)) {
4933 				/*
4934 				 * make sure we clear hw modify bit if we
4935 				 * removing write protections
4936 				 */
4937 				tteflags.tte_intlo |= TTE_HWWR_INT;
4938 			}
4939 
4940 			pml = NULL;
4941 			pp = sfhmep->hme_page;
4942 			if (pp) {
4943 				pml = sfmmu_mlist_enter(pp);
4944 			}
4945 
4946 			if (pp != sfhmep->hme_page) {
4947 				/*
4948 				 * tte must have been unloaded.
4949 				 */
4950 				ASSERT(pml);
4951 				sfmmu_mlist_exit(pml);
4952 				continue;
4953 			}
4954 
4955 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
4956 
4957 			ttemod = tte;
4958 			ttemod.ll = (ttemod.ll & ~tteflags.ll) | tteattr.ll;
4959 			ASSERT(TTE_TO_TTEPFN(&ttemod) == TTE_TO_TTEPFN(&tte));
4960 
4961 #if defined(SF_ERRATA_57)
4962 			if (check_exec && addr < errata57_limit)
4963 				ttemod.tte_exec_perm = 0;
4964 #endif
4965 			ret = sfmmu_modifytte_try(&tte, &ttemod,
4966 			    &sfhmep->hme_tte);
4967 
4968 			if (ret < 0) {
4969 				/* tte changed underneath us */
4970 				if (pml) {
4971 					sfmmu_mlist_exit(pml);
4972 				}
4973 				continue;
4974 			}
4975 
4976 			if (tteflags.tte_intlo & TTE_HWWR_INT) {
4977 				/*
4978 				 * need to sync if we are clearing modify bit.
4979 				 */
4980 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
4981 			}
4982 
4983 			if (pp && PP_ISRO(pp)) {
4984 				if (tteattr.tte_intlo & TTE_WRPRM_INT) {
4985 					pmtx = sfmmu_page_enter(pp);
4986 					PP_CLRRO(pp);
4987 					sfmmu_page_exit(pmtx);
4988 				}
4989 			}
4990 
4991 			if (ret > 0 && use_demap_range) {
4992 				DEMAP_RANGE_MARKPG(dmrp, addr);
4993 			} else if (ret > 0) {
4994 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
4995 			}
4996 
4997 			if (pml) {
4998 				sfmmu_mlist_exit(pml);
4999 			}
5000 		}
5001 next_addr:
5002 		addr += TTEBYTES(ttesz);
5003 		sfhmep++;
5004 		DEMAP_RANGE_NEXTPG(dmrp);
5005 	}
5006 	return (addr);
5007 }
5008 
5009 /*
5010  * This routine converts virtual attributes to physical ones.  It will
5011  * update the tteflags field with the tte mask corresponding to the attributes
5012  * affected and it returns the new attributes.  It will also clear the modify
5013  * bit if we are taking away write permission.  This is necessary since the
5014  * modify bit is the hardware permission bit and we need to clear it in order
5015  * to detect write faults.
5016  */
5017 static uint64_t
5018 sfmmu_vtop_attr(uint_t attr, int mode, tte_t *ttemaskp)
5019 {
5020 	tte_t ttevalue;
5021 
5022 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
5023 
5024 	switch (mode) {
5025 	case SFMMU_CHGATTR:
5026 		/* all attributes specified */
5027 		ttevalue.tte_inthi = MAKE_TTEATTR_INTHI(attr);
5028 		ttevalue.tte_intlo = MAKE_TTEATTR_INTLO(attr);
5029 		ttemaskp->tte_inthi = TTEINTHI_ATTR;
5030 		ttemaskp->tte_intlo = TTEINTLO_ATTR;
5031 		break;
5032 	case SFMMU_SETATTR:
5033 		ASSERT(!(attr & ~HAT_PROT_MASK));
5034 		ttemaskp->ll = 0;
5035 		ttevalue.ll = 0;
5036 		/*
5037 		 * a valid tte implies exec and read for sfmmu
5038 		 * so no need to do anything about them.
5039 		 * since priviledged access implies user access
5040 		 * PROT_USER doesn't make sense either.
5041 		 */
5042 		if (attr & PROT_WRITE) {
5043 			ttemaskp->tte_intlo |= TTE_WRPRM_INT;
5044 			ttevalue.tte_intlo |= TTE_WRPRM_INT;
5045 		}
5046 		break;
5047 	case SFMMU_CLRATTR:
5048 		/* attributes will be nand with current ones */
5049 		if (attr & ~(PROT_WRITE | PROT_USER)) {
5050 			panic("sfmmu: attr %x not supported", attr);
5051 		}
5052 		ttemaskp->ll = 0;
5053 		ttevalue.ll = 0;
5054 		if (attr & PROT_WRITE) {
5055 			/* clear both writable and modify bit */
5056 			ttemaskp->tte_intlo |= TTE_WRPRM_INT | TTE_HWWR_INT;
5057 		}
5058 		if (attr & PROT_USER) {
5059 			ttemaskp->tte_intlo |= TTE_PRIV_INT;
5060 			ttevalue.tte_intlo |= TTE_PRIV_INT;
5061 		}
5062 		break;
5063 	default:
5064 		panic("sfmmu_vtop_attr: bad mode %x", mode);
5065 	}
5066 	ASSERT(TTE_TO_TTEPFN(&ttevalue) == 0);
5067 	return (ttevalue.ll);
5068 }
5069 
5070 static uint_t
5071 sfmmu_ptov_attr(tte_t *ttep)
5072 {
5073 	uint_t attr;
5074 
5075 	ASSERT(TTE_IS_VALID(ttep));
5076 
5077 	attr = PROT_READ;
5078 
5079 	if (TTE_IS_WRITABLE(ttep)) {
5080 		attr |= PROT_WRITE;
5081 	}
5082 	if (TTE_IS_EXECUTABLE(ttep)) {
5083 		attr |= PROT_EXEC;
5084 	}
5085 	if (!TTE_IS_PRIVILEGED(ttep)) {
5086 		attr |= PROT_USER;
5087 	}
5088 	if (TTE_IS_NFO(ttep)) {
5089 		attr |= HAT_NOFAULT;
5090 	}
5091 	if (TTE_IS_NOSYNC(ttep)) {
5092 		attr |= HAT_NOSYNC;
5093 	}
5094 	if (TTE_IS_SIDEFFECT(ttep)) {
5095 		attr |= SFMMU_SIDEFFECT;
5096 	}
5097 	if (!TTE_IS_VCACHEABLE(ttep)) {
5098 		attr |= SFMMU_UNCACHEVTTE;
5099 	}
5100 	if (!TTE_IS_PCACHEABLE(ttep)) {
5101 		attr |= SFMMU_UNCACHEPTTE;
5102 	}
5103 	return (attr);
5104 }
5105 
5106 /*
5107  * hat_chgprot is a deprecated hat call.  New segment drivers
5108  * should store all attributes and use hat_*attr calls.
5109  *
5110  * Change the protections in the virtual address range
5111  * given to the specified virtual protection.  If vprot is ~PROT_WRITE,
5112  * then remove write permission, leaving the other
5113  * permissions unchanged.  If vprot is ~PROT_USER, remove user permissions.
5114  *
5115  */
5116 void
5117 hat_chgprot(struct hat *sfmmup, caddr_t addr, size_t len, uint_t vprot)
5118 {
5119 	struct hmehash_bucket *hmebp;
5120 	hmeblk_tag hblktag;
5121 	int hmeshift, hashno = 1;
5122 	struct hme_blk *hmeblkp, *list = NULL;
5123 	caddr_t endaddr;
5124 	cpuset_t cpuset;
5125 	demap_range_t dmr;
5126 
5127 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5128 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
5129 
5130 	if (sfmmup->sfmmu_xhat_provider) {
5131 		XHAT_CHGPROT(sfmmup, addr, len, vprot);
5132 		return;
5133 	} else {
5134 		/*
5135 		 * This must be a CPU HAT. If the address space has
5136 		 * XHATs attached, change attributes for all of them,
5137 		 * just in case
5138 		 */
5139 		ASSERT(sfmmup->sfmmu_as != NULL);
5140 		if (sfmmup->sfmmu_as->a_xhat != NULL)
5141 			xhat_chgprot_all(sfmmup->sfmmu_as, addr, len, vprot);
5142 	}
5143 
5144 	CPUSET_ZERO(cpuset);
5145 
5146 	if ((vprot != (uint_t)~PROT_WRITE) && (vprot & PROT_USER) &&
5147 	    ((addr + len) > (caddr_t)USERLIMIT)) {
5148 		panic("user addr %p vprot %x in kernel space",
5149 		    (void *)addr, vprot);
5150 	}
5151 	endaddr = addr + len;
5152 	hblktag.htag_id = sfmmup;
5153 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5154 	DEMAP_RANGE_INIT(sfmmup, &dmr);
5155 
5156 	while (addr < endaddr) {
5157 		hmeshift = HME_HASH_SHIFT(hashno);
5158 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5159 		hblktag.htag_rehash = hashno;
5160 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5161 
5162 		SFMMU_HASH_LOCK(hmebp);
5163 
5164 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
5165 		if (hmeblkp != NULL) {
5166 			ASSERT(!hmeblkp->hblk_shared);
5167 			/*
5168 			 * We've encountered a shadow hmeblk so skip the range
5169 			 * of the next smaller mapping size.
5170 			 */
5171 			if (hmeblkp->hblk_shw_bit) {
5172 				ASSERT(sfmmup != ksfmmup);
5173 				ASSERT(hashno > 1);
5174 				addr = (caddr_t)P2END((uintptr_t)addr,
5175 				    TTEBYTES(hashno - 1));
5176 			} else {
5177 				addr = sfmmu_hblk_chgprot(sfmmup, hmeblkp,
5178 				    addr, endaddr, &dmr, vprot);
5179 			}
5180 			SFMMU_HASH_UNLOCK(hmebp);
5181 			hashno = 1;
5182 			continue;
5183 		}
5184 		SFMMU_HASH_UNLOCK(hmebp);
5185 
5186 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
5187 			/*
5188 			 * We have traversed the whole list and rehashed
5189 			 * if necessary without finding the address to chgprot.
5190 			 * This is ok so we increment the address by the
5191 			 * smallest hmeblk range for kernel mappings and the
5192 			 * largest hmeblk range, to account for shadow hmeblks,
5193 			 * for user mappings and continue.
5194 			 */
5195 			if (sfmmup == ksfmmup)
5196 				addr = (caddr_t)P2END((uintptr_t)addr,
5197 				    TTEBYTES(1));
5198 			else
5199 				addr = (caddr_t)P2END((uintptr_t)addr,
5200 				    TTEBYTES(hashno));
5201 			hashno = 1;
5202 		} else {
5203 			hashno++;
5204 		}
5205 	}
5206 
5207 	sfmmu_hblks_list_purge(&list);
5208 	DEMAP_RANGE_FLUSH(&dmr);
5209 	cpuset = sfmmup->sfmmu_cpusran;
5210 	xt_sync(cpuset);
5211 }
5212 
5213 /*
5214  * This function chgprots a range of addresses in an hmeblk.  It returns the
5215  * next addres that needs to be chgprot.
5216  * It should be called with the hash lock held.
5217  * XXX It shold be possible to optimize chgprot by not flushing every time but
5218  * on the other hand:
5219  * 1. do one flush crosscall.
5220  * 2. only flush if we are increasing permissions (make sure this will work)
5221  */
5222 static caddr_t
5223 sfmmu_hblk_chgprot(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5224 	caddr_t endaddr, demap_range_t *dmrp, uint_t vprot)
5225 {
5226 	uint_t pprot;
5227 	tte_t tte, ttemod;
5228 	struct sf_hment *sfhmep;
5229 	uint_t tteflags;
5230 	int ttesz;
5231 	struct page *pp = NULL;
5232 	kmutex_t *pml, *pmtx;
5233 	int ret;
5234 	int use_demap_range;
5235 #if defined(SF_ERRATA_57)
5236 	int check_exec;
5237 #endif
5238 
5239 	ASSERT(in_hblk_range(hmeblkp, addr));
5240 	ASSERT(hmeblkp->hblk_shw_bit == 0);
5241 	ASSERT(!hmeblkp->hblk_shared);
5242 
5243 #ifdef DEBUG
5244 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5245 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5246 		panic("sfmmu_hblk_chgprot: partial chgprot of large page");
5247 	}
5248 #endif /* DEBUG */
5249 
5250 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5251 	ttesz = get_hblk_ttesz(hmeblkp);
5252 
5253 	pprot = sfmmu_vtop_prot(vprot, &tteflags);
5254 #if defined(SF_ERRATA_57)
5255 	check_exec = (sfmmup != ksfmmup) &&
5256 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
5257 	    ((vprot & PROT_EXEC) == PROT_EXEC);
5258 #endif
5259 	HBLKTOHME(sfhmep, hmeblkp, addr);
5260 
5261 	/*
5262 	 * Flush the current demap region if addresses have been
5263 	 * skipped or the page size doesn't match.
5264 	 */
5265 	use_demap_range = (TTEBYTES(ttesz) == MMU_PAGESIZE);
5266 	if (use_demap_range) {
5267 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5268 	} else {
5269 		DEMAP_RANGE_FLUSH(dmrp);
5270 	}
5271 
5272 	while (addr < endaddr) {
5273 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5274 		if (TTE_IS_VALID(&tte)) {
5275 			if (TTE_GET_LOFLAGS(&tte, tteflags) == pprot) {
5276 				/*
5277 				 * if the new protection is the same as old
5278 				 * continue
5279 				 */
5280 				goto next_addr;
5281 			}
5282 			pml = NULL;
5283 			pp = sfhmep->hme_page;
5284 			if (pp) {
5285 				pml = sfmmu_mlist_enter(pp);
5286 			}
5287 			if (pp != sfhmep->hme_page) {
5288 				/*
5289 				 * tte most have been unloaded
5290 				 * underneath us.  Recheck
5291 				 */
5292 				ASSERT(pml);
5293 				sfmmu_mlist_exit(pml);
5294 				continue;
5295 			}
5296 
5297 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5298 
5299 			ttemod = tte;
5300 			TTE_SET_LOFLAGS(&ttemod, tteflags, pprot);
5301 #if defined(SF_ERRATA_57)
5302 			if (check_exec && addr < errata57_limit)
5303 				ttemod.tte_exec_perm = 0;
5304 #endif
5305 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5306 			    &sfhmep->hme_tte);
5307 
5308 			if (ret < 0) {
5309 				/* tte changed underneath us */
5310 				if (pml) {
5311 					sfmmu_mlist_exit(pml);
5312 				}
5313 				continue;
5314 			}
5315 
5316 			if (tteflags & TTE_HWWR_INT) {
5317 				/*
5318 				 * need to sync if we are clearing modify bit.
5319 				 */
5320 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
5321 			}
5322 
5323 			if (pp && PP_ISRO(pp)) {
5324 				if (pprot & TTE_WRPRM_INT) {
5325 					pmtx = sfmmu_page_enter(pp);
5326 					PP_CLRRO(pp);
5327 					sfmmu_page_exit(pmtx);
5328 				}
5329 			}
5330 
5331 			if (ret > 0 && use_demap_range) {
5332 				DEMAP_RANGE_MARKPG(dmrp, addr);
5333 			} else if (ret > 0) {
5334 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
5335 			}
5336 
5337 			if (pml) {
5338 				sfmmu_mlist_exit(pml);
5339 			}
5340 		}
5341 next_addr:
5342 		addr += TTEBYTES(ttesz);
5343 		sfhmep++;
5344 		DEMAP_RANGE_NEXTPG(dmrp);
5345 	}
5346 	return (addr);
5347 }
5348 
5349 /*
5350  * This routine is deprecated and should only be used by hat_chgprot.
5351  * The correct routine is sfmmu_vtop_attr.
5352  * This routine converts virtual page protections to physical ones.  It will
5353  * update the tteflags field with the tte mask corresponding to the protections
5354  * affected and it returns the new protections.  It will also clear the modify
5355  * bit if we are taking away write permission.  This is necessary since the
5356  * modify bit is the hardware permission bit and we need to clear it in order
5357  * to detect write faults.
5358  * It accepts the following special protections:
5359  * ~PROT_WRITE = remove write permissions.
5360  * ~PROT_USER = remove user permissions.
5361  */
5362 static uint_t
5363 sfmmu_vtop_prot(uint_t vprot, uint_t *tteflagsp)
5364 {
5365 	if (vprot == (uint_t)~PROT_WRITE) {
5366 		*tteflagsp = TTE_WRPRM_INT | TTE_HWWR_INT;
5367 		return (0);		/* will cause wrprm to be cleared */
5368 	}
5369 	if (vprot == (uint_t)~PROT_USER) {
5370 		*tteflagsp = TTE_PRIV_INT;
5371 		return (0);		/* will cause privprm to be cleared */
5372 	}
5373 	if ((vprot == 0) || (vprot == PROT_USER) ||
5374 	    ((vprot & PROT_ALL) != vprot)) {
5375 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5376 	}
5377 
5378 	switch (vprot) {
5379 	case (PROT_READ):
5380 	case (PROT_EXEC):
5381 	case (PROT_EXEC | PROT_READ):
5382 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5383 		return (TTE_PRIV_INT); 		/* set prv and clr wrt */
5384 	case (PROT_WRITE):
5385 	case (PROT_WRITE | PROT_READ):
5386 	case (PROT_EXEC | PROT_WRITE):
5387 	case (PROT_EXEC | PROT_WRITE | PROT_READ):
5388 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5389 		return (TTE_PRIV_INT | TTE_WRPRM_INT); 	/* set prv and wrt */
5390 	case (PROT_USER | PROT_READ):
5391 	case (PROT_USER | PROT_EXEC):
5392 	case (PROT_USER | PROT_EXEC | PROT_READ):
5393 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5394 		return (0); 			/* clr prv and wrt */
5395 	case (PROT_USER | PROT_WRITE):
5396 	case (PROT_USER | PROT_WRITE | PROT_READ):
5397 	case (PROT_USER | PROT_EXEC | PROT_WRITE):
5398 	case (PROT_USER | PROT_EXEC | PROT_WRITE | PROT_READ):
5399 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5400 		return (TTE_WRPRM_INT); 	/* clr prv and set wrt */
5401 	default:
5402 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5403 	}
5404 	return (0);
5405 }
5406 
5407 /*
5408  * Alternate unload for very large virtual ranges. With a true 64 bit VA,
5409  * the normal algorithm would take too long for a very large VA range with
5410  * few real mappings. This routine just walks thru all HMEs in the global
5411  * hash table to find and remove mappings.
5412  */
5413 static void
5414 hat_unload_large_virtual(
5415 	struct hat		*sfmmup,
5416 	caddr_t			startaddr,
5417 	size_t			len,
5418 	uint_t			flags,
5419 	hat_callback_t		*callback)
5420 {
5421 	struct hmehash_bucket *hmebp;
5422 	struct hme_blk *hmeblkp;
5423 	struct hme_blk *pr_hblk = NULL;
5424 	struct hme_blk *nx_hblk;
5425 	struct hme_blk *list = NULL;
5426 	int i;
5427 	uint64_t hblkpa, prevpa, nx_pa;
5428 	demap_range_t dmr, *dmrp;
5429 	cpuset_t cpuset;
5430 	caddr_t	endaddr = startaddr + len;
5431 	caddr_t	sa;
5432 	caddr_t	ea;
5433 	caddr_t	cb_sa[MAX_CB_ADDR];
5434 	caddr_t	cb_ea[MAX_CB_ADDR];
5435 	int	addr_cnt = 0;
5436 	int	a = 0;
5437 
5438 	if (sfmmup->sfmmu_free) {
5439 		dmrp = NULL;
5440 	} else {
5441 		dmrp = &dmr;
5442 		DEMAP_RANGE_INIT(sfmmup, dmrp);
5443 	}
5444 
5445 	/*
5446 	 * Loop through all the hash buckets of HME blocks looking for matches.
5447 	 */
5448 	for (i = 0; i <= UHMEHASH_SZ; i++) {
5449 		hmebp = &uhme_hash[i];
5450 		SFMMU_HASH_LOCK(hmebp);
5451 		hmeblkp = hmebp->hmeblkp;
5452 		hblkpa = hmebp->hmeh_nextpa;
5453 		prevpa = 0;
5454 		pr_hblk = NULL;
5455 		while (hmeblkp) {
5456 			nx_hblk = hmeblkp->hblk_next;
5457 			nx_pa = hmeblkp->hblk_nextpa;
5458 
5459 			/*
5460 			 * skip if not this context, if a shadow block or
5461 			 * if the mapping is not in the requested range
5462 			 */
5463 			if (hmeblkp->hblk_tag.htag_id != sfmmup ||
5464 			    hmeblkp->hblk_shw_bit ||
5465 			    (sa = (caddr_t)get_hblk_base(hmeblkp)) >= endaddr ||
5466 			    (ea = get_hblk_endaddr(hmeblkp)) <= startaddr) {
5467 				pr_hblk = hmeblkp;
5468 				prevpa = hblkpa;
5469 				goto next_block;
5470 			}
5471 
5472 			ASSERT(!hmeblkp->hblk_shared);
5473 			/*
5474 			 * unload if there are any current valid mappings
5475 			 */
5476 			if (hmeblkp->hblk_vcnt != 0 ||
5477 			    hmeblkp->hblk_hmecnt != 0)
5478 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
5479 				    sa, ea, dmrp, flags);
5480 
5481 			/*
5482 			 * on unmap we also release the HME block itself, once
5483 			 * all mappings are gone.
5484 			 */
5485 			if ((flags & HAT_UNLOAD_UNMAP) != 0 &&
5486 			    !hmeblkp->hblk_vcnt &&
5487 			    !hmeblkp->hblk_hmecnt) {
5488 				ASSERT(!hmeblkp->hblk_lckcnt);
5489 				sfmmu_hblk_hash_rm(hmebp, hmeblkp,
5490 				    prevpa, pr_hblk);
5491 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
5492 			} else {
5493 				pr_hblk = hmeblkp;
5494 				prevpa = hblkpa;
5495 			}
5496 
5497 			if (callback == NULL)
5498 				goto next_block;
5499 
5500 			/*
5501 			 * HME blocks may span more than one page, but we may be
5502 			 * unmapping only one page, so check for a smaller range
5503 			 * for the callback
5504 			 */
5505 			if (sa < startaddr)
5506 				sa = startaddr;
5507 			if (--ea > endaddr)
5508 				ea = endaddr - 1;
5509 
5510 			cb_sa[addr_cnt] = sa;
5511 			cb_ea[addr_cnt] = ea;
5512 			if (++addr_cnt == MAX_CB_ADDR) {
5513 				if (dmrp != NULL) {
5514 					DEMAP_RANGE_FLUSH(dmrp);
5515 					cpuset = sfmmup->sfmmu_cpusran;
5516 					xt_sync(cpuset);
5517 				}
5518 
5519 				for (a = 0; a < MAX_CB_ADDR; ++a) {
5520 					callback->hcb_start_addr = cb_sa[a];
5521 					callback->hcb_end_addr = cb_ea[a];
5522 					callback->hcb_function(callback);
5523 				}
5524 				addr_cnt = 0;
5525 			}
5526 
5527 next_block:
5528 			hmeblkp = nx_hblk;
5529 			hblkpa = nx_pa;
5530 		}
5531 		SFMMU_HASH_UNLOCK(hmebp);
5532 	}
5533 
5534 	sfmmu_hblks_list_purge(&list);
5535 	if (dmrp != NULL) {
5536 		DEMAP_RANGE_FLUSH(dmrp);
5537 		cpuset = sfmmup->sfmmu_cpusran;
5538 		xt_sync(cpuset);
5539 	}
5540 
5541 	for (a = 0; a < addr_cnt; ++a) {
5542 		callback->hcb_start_addr = cb_sa[a];
5543 		callback->hcb_end_addr = cb_ea[a];
5544 		callback->hcb_function(callback);
5545 	}
5546 
5547 	/*
5548 	 * Check TSB and TLB page sizes if the process isn't exiting.
5549 	 */
5550 	if (!sfmmup->sfmmu_free)
5551 		sfmmu_check_page_sizes(sfmmup, 0);
5552 }
5553 
5554 /*
5555  * Unload all the mappings in the range [addr..addr+len). addr and len must
5556  * be MMU_PAGESIZE aligned.
5557  */
5558 
5559 extern struct seg *segkmap;
5560 #define	ISSEGKMAP(sfmmup, addr) (sfmmup == ksfmmup && \
5561 segkmap->s_base <= (addr) && (addr) < (segkmap->s_base + segkmap->s_size))
5562 
5563 
5564 void
5565 hat_unload_callback(
5566 	struct hat *sfmmup,
5567 	caddr_t addr,
5568 	size_t len,
5569 	uint_t flags,
5570 	hat_callback_t *callback)
5571 {
5572 	struct hmehash_bucket *hmebp;
5573 	hmeblk_tag hblktag;
5574 	int hmeshift, hashno, iskernel;
5575 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
5576 	caddr_t endaddr;
5577 	cpuset_t cpuset;
5578 	uint64_t hblkpa, prevpa;
5579 	int addr_count = 0;
5580 	int a;
5581 	caddr_t cb_start_addr[MAX_CB_ADDR];
5582 	caddr_t cb_end_addr[MAX_CB_ADDR];
5583 	int issegkmap = ISSEGKMAP(sfmmup, addr);
5584 	demap_range_t dmr, *dmrp;
5585 
5586 	if (sfmmup->sfmmu_xhat_provider) {
5587 		XHAT_UNLOAD_CALLBACK(sfmmup, addr, len, flags, callback);
5588 		return;
5589 	} else {
5590 		/*
5591 		 * This must be a CPU HAT. If the address space has
5592 		 * XHATs attached, unload the mappings for all of them,
5593 		 * just in case
5594 		 */
5595 		ASSERT(sfmmup->sfmmu_as != NULL);
5596 		if (sfmmup->sfmmu_as->a_xhat != NULL)
5597 			xhat_unload_callback_all(sfmmup->sfmmu_as, addr,
5598 			    len, flags, callback);
5599 	}
5600 
5601 	ASSERT((sfmmup == ksfmmup) || (flags & HAT_UNLOAD_OTHER) || \
5602 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
5603 
5604 	ASSERT(sfmmup != NULL);
5605 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5606 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
5607 
5608 	/*
5609 	 * Probing through a large VA range (say 63 bits) will be slow, even
5610 	 * at 4 Meg steps between the probes. So, when the virtual address range
5611 	 * is very large, search the HME entries for what to unload.
5612 	 *
5613 	 *	len >> TTE_PAGE_SHIFT(TTE4M) is the # of 4Meg probes we'd need
5614 	 *
5615 	 *	UHMEHASH_SZ is number of hash buckets to examine
5616 	 *
5617 	 */
5618 	if (sfmmup != KHATID && (len >> TTE_PAGE_SHIFT(TTE4M)) > UHMEHASH_SZ) {
5619 		hat_unload_large_virtual(sfmmup, addr, len, flags, callback);
5620 		return;
5621 	}
5622 
5623 	CPUSET_ZERO(cpuset);
5624 
5625 	/*
5626 	 * If the process is exiting, we can save a lot of fuss since
5627 	 * we'll flush the TLB when we free the ctx anyway.
5628 	 */
5629 	if (sfmmup->sfmmu_free)
5630 		dmrp = NULL;
5631 	else
5632 		dmrp = &dmr;
5633 
5634 	DEMAP_RANGE_INIT(sfmmup, dmrp);
5635 	endaddr = addr + len;
5636 	hblktag.htag_id = sfmmup;
5637 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5638 
5639 	/*
5640 	 * It is likely for the vm to call unload over a wide range of
5641 	 * addresses that are actually very sparsely populated by
5642 	 * translations.  In order to speed this up the sfmmu hat supports
5643 	 * the concept of shadow hmeblks. Dummy large page hmeblks that
5644 	 * correspond to actual small translations are allocated at tteload
5645 	 * time and are referred to as shadow hmeblks.  Now, during unload
5646 	 * time, we first check if we have a shadow hmeblk for that
5647 	 * translation.  The absence of one means the corresponding address
5648 	 * range is empty and can be skipped.
5649 	 *
5650 	 * The kernel is an exception to above statement and that is why
5651 	 * we don't use shadow hmeblks and hash starting from the smallest
5652 	 * page size.
5653 	 */
5654 	if (sfmmup == KHATID) {
5655 		iskernel = 1;
5656 		hashno = TTE64K;
5657 	} else {
5658 		iskernel = 0;
5659 		if (mmu_page_sizes == max_mmu_page_sizes) {
5660 			hashno = TTE256M;
5661 		} else {
5662 			hashno = TTE4M;
5663 		}
5664 	}
5665 	while (addr < endaddr) {
5666 		hmeshift = HME_HASH_SHIFT(hashno);
5667 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5668 		hblktag.htag_rehash = hashno;
5669 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5670 
5671 		SFMMU_HASH_LOCK(hmebp);
5672 
5673 		HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa, pr_hblk,
5674 		    prevpa, &list);
5675 		if (hmeblkp == NULL) {
5676 			/*
5677 			 * didn't find an hmeblk. skip the appropiate
5678 			 * address range.
5679 			 */
5680 			SFMMU_HASH_UNLOCK(hmebp);
5681 			if (iskernel) {
5682 				if (hashno < mmu_hashcnt) {
5683 					hashno++;
5684 					continue;
5685 				} else {
5686 					hashno = TTE64K;
5687 					addr = (caddr_t)roundup((uintptr_t)addr
5688 					    + 1, MMU_PAGESIZE64K);
5689 					continue;
5690 				}
5691 			}
5692 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5693 			    (1 << hmeshift));
5694 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5695 				ASSERT(hashno == TTE64K);
5696 				continue;
5697 			}
5698 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5699 				hashno = TTE512K;
5700 				continue;
5701 			}
5702 			if (mmu_page_sizes == max_mmu_page_sizes) {
5703 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5704 					hashno = TTE4M;
5705 					continue;
5706 				}
5707 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5708 					hashno = TTE32M;
5709 					continue;
5710 				}
5711 				hashno = TTE256M;
5712 				continue;
5713 			} else {
5714 				hashno = TTE4M;
5715 				continue;
5716 			}
5717 		}
5718 		ASSERT(hmeblkp);
5719 		ASSERT(!hmeblkp->hblk_shared);
5720 		if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5721 			/*
5722 			 * If the valid count is zero we can skip the range
5723 			 * mapped by this hmeblk.
5724 			 * We free hblks in the case of HAT_UNMAP.  HAT_UNMAP
5725 			 * is used by segment drivers as a hint
5726 			 * that the mapping resource won't be used any longer.
5727 			 * The best example of this is during exit().
5728 			 */
5729 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5730 			    get_hblk_span(hmeblkp));
5731 			if ((flags & HAT_UNLOAD_UNMAP) ||
5732 			    (iskernel && !issegkmap)) {
5733 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa,
5734 				    pr_hblk);
5735 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
5736 			}
5737 			SFMMU_HASH_UNLOCK(hmebp);
5738 
5739 			if (iskernel) {
5740 				hashno = TTE64K;
5741 				continue;
5742 			}
5743 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5744 				ASSERT(hashno == TTE64K);
5745 				continue;
5746 			}
5747 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5748 				hashno = TTE512K;
5749 				continue;
5750 			}
5751 			if (mmu_page_sizes == max_mmu_page_sizes) {
5752 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5753 					hashno = TTE4M;
5754 					continue;
5755 				}
5756 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5757 					hashno = TTE32M;
5758 					continue;
5759 				}
5760 				hashno = TTE256M;
5761 				continue;
5762 			} else {
5763 				hashno = TTE4M;
5764 				continue;
5765 			}
5766 		}
5767 		if (hmeblkp->hblk_shw_bit) {
5768 			/*
5769 			 * If we encounter a shadow hmeblk we know there is
5770 			 * smaller sized hmeblks mapping the same address space.
5771 			 * Decrement the hash size and rehash.
5772 			 */
5773 			ASSERT(sfmmup != KHATID);
5774 			hashno--;
5775 			SFMMU_HASH_UNLOCK(hmebp);
5776 			continue;
5777 		}
5778 
5779 		/*
5780 		 * track callback address ranges.
5781 		 * only start a new range when it's not contiguous
5782 		 */
5783 		if (callback != NULL) {
5784 			if (addr_count > 0 &&
5785 			    addr == cb_end_addr[addr_count - 1])
5786 				--addr_count;
5787 			else
5788 				cb_start_addr[addr_count] = addr;
5789 		}
5790 
5791 		addr = sfmmu_hblk_unload(sfmmup, hmeblkp, addr, endaddr,
5792 		    dmrp, flags);
5793 
5794 		if (callback != NULL)
5795 			cb_end_addr[addr_count++] = addr;
5796 
5797 		if (((flags & HAT_UNLOAD_UNMAP) || (iskernel && !issegkmap)) &&
5798 		    !hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5799 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa,
5800 			    pr_hblk);
5801 			sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
5802 		}
5803 		SFMMU_HASH_UNLOCK(hmebp);
5804 
5805 		/*
5806 		 * Notify our caller as to exactly which pages
5807 		 * have been unloaded. We do these in clumps,
5808 		 * to minimize the number of xt_sync()s that need to occur.
5809 		 */
5810 		if (callback != NULL && addr_count == MAX_CB_ADDR) {
5811 			DEMAP_RANGE_FLUSH(dmrp);
5812 			if (dmrp != NULL) {
5813 				cpuset = sfmmup->sfmmu_cpusran;
5814 				xt_sync(cpuset);
5815 			}
5816 
5817 			for (a = 0; a < MAX_CB_ADDR; ++a) {
5818 				callback->hcb_start_addr = cb_start_addr[a];
5819 				callback->hcb_end_addr = cb_end_addr[a];
5820 				callback->hcb_function(callback);
5821 			}
5822 			addr_count = 0;
5823 		}
5824 		if (iskernel) {
5825 			hashno = TTE64K;
5826 			continue;
5827 		}
5828 		if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5829 			ASSERT(hashno == TTE64K);
5830 			continue;
5831 		}
5832 		if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5833 			hashno = TTE512K;
5834 			continue;
5835 		}
5836 		if (mmu_page_sizes == max_mmu_page_sizes) {
5837 			if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5838 				hashno = TTE4M;
5839 				continue;
5840 			}
5841 			if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5842 				hashno = TTE32M;
5843 				continue;
5844 			}
5845 			hashno = TTE256M;
5846 		} else {
5847 			hashno = TTE4M;
5848 		}
5849 	}
5850 
5851 	sfmmu_hblks_list_purge(&list);
5852 	DEMAP_RANGE_FLUSH(dmrp);
5853 	if (dmrp != NULL) {
5854 		cpuset = sfmmup->sfmmu_cpusran;
5855 		xt_sync(cpuset);
5856 	}
5857 	if (callback && addr_count != 0) {
5858 		for (a = 0; a < addr_count; ++a) {
5859 			callback->hcb_start_addr = cb_start_addr[a];
5860 			callback->hcb_end_addr = cb_end_addr[a];
5861 			callback->hcb_function(callback);
5862 		}
5863 	}
5864 
5865 	/*
5866 	 * Check TSB and TLB page sizes if the process isn't exiting.
5867 	 */
5868 	if (!sfmmup->sfmmu_free)
5869 		sfmmu_check_page_sizes(sfmmup, 0);
5870 }
5871 
5872 /*
5873  * Unload all the mappings in the range [addr..addr+len). addr and len must
5874  * be MMU_PAGESIZE aligned.
5875  */
5876 void
5877 hat_unload(struct hat *sfmmup, caddr_t addr, size_t len, uint_t flags)
5878 {
5879 	if (sfmmup->sfmmu_xhat_provider) {
5880 		XHAT_UNLOAD(sfmmup, addr, len, flags);
5881 		return;
5882 	}
5883 	hat_unload_callback(sfmmup, addr, len, flags, NULL);
5884 }
5885 
5886 
5887 /*
5888  * Find the largest mapping size for this page.
5889  */
5890 int
5891 fnd_mapping_sz(page_t *pp)
5892 {
5893 	int sz;
5894 	int p_index;
5895 
5896 	p_index = PP_MAPINDEX(pp);
5897 
5898 	sz = 0;
5899 	p_index >>= 1;	/* don't care about 8K bit */
5900 	for (; p_index; p_index >>= 1) {
5901 		sz++;
5902 	}
5903 
5904 	return (sz);
5905 }
5906 
5907 /*
5908  * This function unloads a range of addresses for an hmeblk.
5909  * It returns the next address to be unloaded.
5910  * It should be called with the hash lock held.
5911  */
5912 static caddr_t
5913 sfmmu_hblk_unload(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5914 	caddr_t endaddr, demap_range_t *dmrp, uint_t flags)
5915 {
5916 	tte_t	tte, ttemod;
5917 	struct	sf_hment *sfhmep;
5918 	int	ttesz;
5919 	long	ttecnt;
5920 	page_t *pp;
5921 	kmutex_t *pml;
5922 	int ret;
5923 	int use_demap_range;
5924 
5925 	ASSERT(in_hblk_range(hmeblkp, addr));
5926 	ASSERT(!hmeblkp->hblk_shw_bit);
5927 	ASSERT(sfmmup != NULL || hmeblkp->hblk_shared);
5928 	ASSERT(sfmmup == NULL || !hmeblkp->hblk_shared);
5929 	ASSERT(dmrp == NULL || !hmeblkp->hblk_shared);
5930 
5931 #ifdef DEBUG
5932 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5933 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5934 		panic("sfmmu_hblk_unload: partial unload of large page");
5935 	}
5936 #endif /* DEBUG */
5937 
5938 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5939 	ttesz = get_hblk_ttesz(hmeblkp);
5940 
5941 	use_demap_range = ((dmrp == NULL) ||
5942 	    (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp)));
5943 
5944 	if (use_demap_range) {
5945 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5946 	} else {
5947 		DEMAP_RANGE_FLUSH(dmrp);
5948 	}
5949 	ttecnt = 0;
5950 	HBLKTOHME(sfhmep, hmeblkp, addr);
5951 
5952 	while (addr < endaddr) {
5953 		pml = NULL;
5954 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5955 		if (TTE_IS_VALID(&tte)) {
5956 			pp = sfhmep->hme_page;
5957 			if (pp != NULL) {
5958 				pml = sfmmu_mlist_enter(pp);
5959 			}
5960 
5961 			/*
5962 			 * Verify if hme still points to 'pp' now that
5963 			 * we have p_mapping lock.
5964 			 */
5965 			if (sfhmep->hme_page != pp) {
5966 				if (pp != NULL && sfhmep->hme_page != NULL) {
5967 					ASSERT(pml != NULL);
5968 					sfmmu_mlist_exit(pml);
5969 					/* Re-start this iteration. */
5970 					continue;
5971 				}
5972 				ASSERT((pp != NULL) &&
5973 				    (sfhmep->hme_page == NULL));
5974 				goto tte_unloaded;
5975 			}
5976 
5977 			/*
5978 			 * This point on we have both HASH and p_mapping
5979 			 * lock.
5980 			 */
5981 			ASSERT(pp == sfhmep->hme_page);
5982 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5983 
5984 			/*
5985 			 * We need to loop on modify tte because it is
5986 			 * possible for pagesync to come along and
5987 			 * change the software bits beneath us.
5988 			 *
5989 			 * Page_unload can also invalidate the tte after
5990 			 * we read tte outside of p_mapping lock.
5991 			 */
5992 again:
5993 			ttemod = tte;
5994 
5995 			TTE_SET_INVALID(&ttemod);
5996 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5997 			    &sfhmep->hme_tte);
5998 
5999 			if (ret <= 0) {
6000 				if (TTE_IS_VALID(&tte)) {
6001 					ASSERT(ret < 0);
6002 					goto again;
6003 				}
6004 				if (pp != NULL) {
6005 					panic("sfmmu_hblk_unload: pp = 0x%p "
6006 					    "tte became invalid under mlist"
6007 					    " lock = 0x%p", pp, pml);
6008 				}
6009 				continue;
6010 			}
6011 
6012 			if (!(flags & HAT_UNLOAD_NOSYNC)) {
6013 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
6014 			}
6015 
6016 			/*
6017 			 * Ok- we invalidated the tte. Do the rest of the job.
6018 			 */
6019 			ttecnt++;
6020 
6021 			if (flags & HAT_UNLOAD_UNLOCK) {
6022 				ASSERT(hmeblkp->hblk_lckcnt > 0);
6023 				atomic_add_32(&hmeblkp->hblk_lckcnt, -1);
6024 				HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
6025 			}
6026 
6027 			/*
6028 			 * Normally we would need to flush the page
6029 			 * from the virtual cache at this point in
6030 			 * order to prevent a potential cache alias
6031 			 * inconsistency.
6032 			 * The particular scenario we need to worry
6033 			 * about is:
6034 			 * Given:  va1 and va2 are two virtual address
6035 			 * that alias and map the same physical
6036 			 * address.
6037 			 * 1.   mapping exists from va1 to pa and data
6038 			 * has been read into the cache.
6039 			 * 2.   unload va1.
6040 			 * 3.   load va2 and modify data using va2.
6041 			 * 4    unload va2.
6042 			 * 5.   load va1 and reference data.  Unless we
6043 			 * flush the data cache when we unload we will
6044 			 * get stale data.
6045 			 * Fortunately, page coloring eliminates the
6046 			 * above scenario by remembering the color a
6047 			 * physical page was last or is currently
6048 			 * mapped to.  Now, we delay the flush until
6049 			 * the loading of translations.  Only when the
6050 			 * new translation is of a different color
6051 			 * are we forced to flush.
6052 			 */
6053 			if (use_demap_range) {
6054 				/*
6055 				 * Mark this page as needing a demap.
6056 				 */
6057 				DEMAP_RANGE_MARKPG(dmrp, addr);
6058 			} else {
6059 				ASSERT(sfmmup != NULL);
6060 				ASSERT(!hmeblkp->hblk_shared);
6061 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
6062 				    sfmmup->sfmmu_free, 0);
6063 			}
6064 
6065 			if (pp) {
6066 				/*
6067 				 * Remove the hment from the mapping list
6068 				 */
6069 				ASSERT(hmeblkp->hblk_hmecnt > 0);
6070 
6071 				/*
6072 				 * Again, we cannot
6073 				 * ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS);
6074 				 */
6075 				HME_SUB(sfhmep, pp);
6076 				membar_stst();
6077 				atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
6078 			}
6079 
6080 			ASSERT(hmeblkp->hblk_vcnt > 0);
6081 			atomic_add_16(&hmeblkp->hblk_vcnt, -1);
6082 
6083 			ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
6084 			    !hmeblkp->hblk_lckcnt);
6085 
6086 #ifdef VAC
6087 			if (pp && (pp->p_nrm & (P_KPMC | P_KPMS | P_TNC))) {
6088 				if (PP_ISTNC(pp)) {
6089 					/*
6090 					 * If page was temporary
6091 					 * uncached, try to recache
6092 					 * it. Note that HME_SUB() was
6093 					 * called above so p_index and
6094 					 * mlist had been updated.
6095 					 */
6096 					conv_tnc(pp, ttesz);
6097 				} else if (pp->p_mapping == NULL) {
6098 					ASSERT(kpm_enable);
6099 					/*
6100 					 * Page is marked to be in VAC conflict
6101 					 * to an existing kpm mapping and/or is
6102 					 * kpm mapped using only the regular
6103 					 * pagesize.
6104 					 */
6105 					sfmmu_kpm_hme_unload(pp);
6106 				}
6107 			}
6108 #endif	/* VAC */
6109 		} else if ((pp = sfhmep->hme_page) != NULL) {
6110 				/*
6111 				 * TTE is invalid but the hme
6112 				 * still exists. let pageunload
6113 				 * complete its job.
6114 				 */
6115 				ASSERT(pml == NULL);
6116 				pml = sfmmu_mlist_enter(pp);
6117 				if (sfhmep->hme_page != NULL) {
6118 					sfmmu_mlist_exit(pml);
6119 					continue;
6120 				}
6121 				ASSERT(sfhmep->hme_page == NULL);
6122 		} else if (hmeblkp->hblk_hmecnt != 0) {
6123 			/*
6124 			 * pageunload may have not finished decrementing
6125 			 * hblk_vcnt and hblk_hmecnt. Find page_t if any and
6126 			 * wait for pageunload to finish. Rely on pageunload
6127 			 * to decrement hblk_hmecnt after hblk_vcnt.
6128 			 */
6129 			pfn_t pfn = TTE_TO_TTEPFN(&tte);
6130 			ASSERT(pml == NULL);
6131 			if (pf_is_memory(pfn)) {
6132 				pp = page_numtopp_nolock(pfn);
6133 				if (pp != NULL) {
6134 					pml = sfmmu_mlist_enter(pp);
6135 					sfmmu_mlist_exit(pml);
6136 					pml = NULL;
6137 				}
6138 			}
6139 		}
6140 
6141 tte_unloaded:
6142 		/*
6143 		 * At this point, the tte we are looking at
6144 		 * should be unloaded, and hme has been unlinked
6145 		 * from page too. This is important because in
6146 		 * pageunload, it does ttesync() then HME_SUB.
6147 		 * We need to make sure HME_SUB has been completed
6148 		 * so we know ttesync() has been completed. Otherwise,
6149 		 * at exit time, after return from hat layer, VM will
6150 		 * release as structure which hat_setstat() (called
6151 		 * by ttesync()) needs.
6152 		 */
6153 #ifdef DEBUG
6154 		{
6155 			tte_t	dtte;
6156 
6157 			ASSERT(sfhmep->hme_page == NULL);
6158 
6159 			sfmmu_copytte(&sfhmep->hme_tte, &dtte);
6160 			ASSERT(!TTE_IS_VALID(&dtte));
6161 		}
6162 #endif
6163 
6164 		if (pml) {
6165 			sfmmu_mlist_exit(pml);
6166 		}
6167 
6168 		addr += TTEBYTES(ttesz);
6169 		sfhmep++;
6170 		DEMAP_RANGE_NEXTPG(dmrp);
6171 	}
6172 	/*
6173 	 * For shared hmeblks this routine is only called when region is freed
6174 	 * and no longer referenced.  So no need to decrement ttecnt
6175 	 * in the region structure here.
6176 	 */
6177 	if (ttecnt > 0 && sfmmup != NULL) {
6178 		atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -ttecnt);
6179 	}
6180 	return (addr);
6181 }
6182 
6183 /*
6184  * Synchronize all the mappings in the range [addr..addr+len).
6185  * Can be called with clearflag having two states:
6186  * HAT_SYNC_DONTZERO means just return the rm stats
6187  * HAT_SYNC_ZERORM means zero rm bits in the tte and return the stats
6188  */
6189 void
6190 hat_sync(struct hat *sfmmup, caddr_t addr, size_t len, uint_t clearflag)
6191 {
6192 	struct hmehash_bucket *hmebp;
6193 	hmeblk_tag hblktag;
6194 	int hmeshift, hashno = 1;
6195 	struct hme_blk *hmeblkp, *list = NULL;
6196 	caddr_t endaddr;
6197 	cpuset_t cpuset;
6198 
6199 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
6200 	ASSERT((sfmmup == ksfmmup) ||
6201 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
6202 	ASSERT((len & MMU_PAGEOFFSET) == 0);
6203 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
6204 	    (clearflag == HAT_SYNC_ZERORM));
6205 
6206 	CPUSET_ZERO(cpuset);
6207 
6208 	endaddr = addr + len;
6209 	hblktag.htag_id = sfmmup;
6210 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
6211 
6212 	/*
6213 	 * Spitfire supports 4 page sizes.
6214 	 * Most pages are expected to be of the smallest page
6215 	 * size (8K) and these will not need to be rehashed. 64K
6216 	 * pages also don't need to be rehashed because the an hmeblk
6217 	 * spans 64K of address space. 512K pages might need 1 rehash and
6218 	 * and 4M pages 2 rehashes.
6219 	 */
6220 	while (addr < endaddr) {
6221 		hmeshift = HME_HASH_SHIFT(hashno);
6222 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
6223 		hblktag.htag_rehash = hashno;
6224 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
6225 
6226 		SFMMU_HASH_LOCK(hmebp);
6227 
6228 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
6229 		if (hmeblkp != NULL) {
6230 			ASSERT(!hmeblkp->hblk_shared);
6231 			/*
6232 			 * We've encountered a shadow hmeblk so skip the range
6233 			 * of the next smaller mapping size.
6234 			 */
6235 			if (hmeblkp->hblk_shw_bit) {
6236 				ASSERT(sfmmup != ksfmmup);
6237 				ASSERT(hashno > 1);
6238 				addr = (caddr_t)P2END((uintptr_t)addr,
6239 				    TTEBYTES(hashno - 1));
6240 			} else {
6241 				addr = sfmmu_hblk_sync(sfmmup, hmeblkp,
6242 				    addr, endaddr, clearflag);
6243 			}
6244 			SFMMU_HASH_UNLOCK(hmebp);
6245 			hashno = 1;
6246 			continue;
6247 		}
6248 		SFMMU_HASH_UNLOCK(hmebp);
6249 
6250 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
6251 			/*
6252 			 * We have traversed the whole list and rehashed
6253 			 * if necessary without finding the address to sync.
6254 			 * This is ok so we increment the address by the
6255 			 * smallest hmeblk range for kernel mappings and the
6256 			 * largest hmeblk range, to account for shadow hmeblks,
6257 			 * for user mappings and continue.
6258 			 */
6259 			if (sfmmup == ksfmmup)
6260 				addr = (caddr_t)P2END((uintptr_t)addr,
6261 				    TTEBYTES(1));
6262 			else
6263 				addr = (caddr_t)P2END((uintptr_t)addr,
6264 				    TTEBYTES(hashno));
6265 			hashno = 1;
6266 		} else {
6267 			hashno++;
6268 		}
6269 	}
6270 	sfmmu_hblks_list_purge(&list);
6271 	cpuset = sfmmup->sfmmu_cpusran;
6272 	xt_sync(cpuset);
6273 }
6274 
6275 static caddr_t
6276 sfmmu_hblk_sync(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
6277 	caddr_t endaddr, int clearflag)
6278 {
6279 	tte_t	tte, ttemod;
6280 	struct sf_hment *sfhmep;
6281 	int ttesz;
6282 	struct page *pp;
6283 	kmutex_t *pml;
6284 	int ret;
6285 
6286 	ASSERT(hmeblkp->hblk_shw_bit == 0);
6287 	ASSERT(!hmeblkp->hblk_shared);
6288 
6289 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
6290 
6291 	ttesz = get_hblk_ttesz(hmeblkp);
6292 	HBLKTOHME(sfhmep, hmeblkp, addr);
6293 
6294 	while (addr < endaddr) {
6295 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6296 		if (TTE_IS_VALID(&tte)) {
6297 			pml = NULL;
6298 			pp = sfhmep->hme_page;
6299 			if (pp) {
6300 				pml = sfmmu_mlist_enter(pp);
6301 			}
6302 			if (pp != sfhmep->hme_page) {
6303 				/*
6304 				 * tte most have been unloaded
6305 				 * underneath us.  Recheck
6306 				 */
6307 				ASSERT(pml);
6308 				sfmmu_mlist_exit(pml);
6309 				continue;
6310 			}
6311 
6312 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
6313 
6314 			if (clearflag == HAT_SYNC_ZERORM) {
6315 				ttemod = tte;
6316 				TTE_CLR_RM(&ttemod);
6317 				ret = sfmmu_modifytte_try(&tte, &ttemod,
6318 				    &sfhmep->hme_tte);
6319 				if (ret < 0) {
6320 					if (pml) {
6321 						sfmmu_mlist_exit(pml);
6322 					}
6323 					continue;
6324 				}
6325 
6326 				if (ret > 0) {
6327 					sfmmu_tlb_demap(addr, sfmmup,
6328 					    hmeblkp, 0, 0);
6329 				}
6330 			}
6331 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
6332 			if (pml) {
6333 				sfmmu_mlist_exit(pml);
6334 			}
6335 		}
6336 		addr += TTEBYTES(ttesz);
6337 		sfhmep++;
6338 	}
6339 	return (addr);
6340 }
6341 
6342 /*
6343  * This function will sync a tte to the page struct and it will
6344  * update the hat stats. Currently it allows us to pass a NULL pp
6345  * and we will simply update the stats.  We may want to change this
6346  * so we only keep stats for pages backed by pp's.
6347  */
6348 static void
6349 sfmmu_ttesync(struct hat *sfmmup, caddr_t addr, tte_t *ttep, page_t *pp)
6350 {
6351 	uint_t rm = 0;
6352 	int   	sz;
6353 	pgcnt_t	npgs;
6354 
6355 	ASSERT(TTE_IS_VALID(ttep));
6356 
6357 	if (TTE_IS_NOSYNC(ttep)) {
6358 		return;
6359 	}
6360 
6361 	if (TTE_IS_REF(ttep))  {
6362 		rm = P_REF;
6363 	}
6364 	if (TTE_IS_MOD(ttep))  {
6365 		rm |= P_MOD;
6366 	}
6367 
6368 	if (rm == 0) {
6369 		return;
6370 	}
6371 
6372 	sz = TTE_CSZ(ttep);
6373 	if (sfmmup != NULL && sfmmup->sfmmu_rmstat) {
6374 		int i;
6375 		caddr_t	vaddr = addr;
6376 
6377 		for (i = 0; i < TTEPAGES(sz); i++, vaddr += MMU_PAGESIZE) {
6378 			hat_setstat(sfmmup->sfmmu_as, vaddr, MMU_PAGESIZE, rm);
6379 		}
6380 
6381 	}
6382 
6383 	/*
6384 	 * XXX I want to use cas to update nrm bits but they
6385 	 * currently belong in common/vm and not in hat where
6386 	 * they should be.
6387 	 * The nrm bits are protected by the same mutex as
6388 	 * the one that protects the page's mapping list.
6389 	 */
6390 	if (!pp)
6391 		return;
6392 	ASSERT(sfmmu_mlist_held(pp));
6393 	/*
6394 	 * If the tte is for a large page, we need to sync all the
6395 	 * pages covered by the tte.
6396 	 */
6397 	if (sz != TTE8K) {
6398 		ASSERT(pp->p_szc != 0);
6399 		pp = PP_GROUPLEADER(pp, sz);
6400 		ASSERT(sfmmu_mlist_held(pp));
6401 	}
6402 
6403 	/* Get number of pages from tte size. */
6404 	npgs = TTEPAGES(sz);
6405 
6406 	do {
6407 		ASSERT(pp);
6408 		ASSERT(sfmmu_mlist_held(pp));
6409 		if (((rm & P_REF) != 0 && !PP_ISREF(pp)) ||
6410 		    ((rm & P_MOD) != 0 && !PP_ISMOD(pp)))
6411 			hat_page_setattr(pp, rm);
6412 
6413 		/*
6414 		 * Are we done? If not, we must have a large mapping.
6415 		 * For large mappings we need to sync the rest of the pages
6416 		 * covered by this tte; goto the next page.
6417 		 */
6418 	} while (--npgs > 0 && (pp = PP_PAGENEXT(pp)));
6419 }
6420 
6421 /*
6422  * Execute pre-callback handler of each pa_hment linked to pp
6423  *
6424  * Inputs:
6425  *   flag: either HAT_PRESUSPEND or HAT_SUSPEND.
6426  *   capture_cpus: pointer to return value (below)
6427  *
6428  * Returns:
6429  *   Propagates the subsystem callback return values back to the caller;
6430  *   returns 0 on success.  If capture_cpus is non-NULL, the value returned
6431  *   is zero if all of the pa_hments are of a type that do not require
6432  *   capturing CPUs prior to suspending the mapping, else it is 1.
6433  */
6434 static int
6435 hat_pageprocess_precallbacks(struct page *pp, uint_t flag, int *capture_cpus)
6436 {
6437 	struct sf_hment	*sfhmep;
6438 	struct pa_hment *pahmep;
6439 	int (*f)(caddr_t, uint_t, uint_t, void *);
6440 	int		ret;
6441 	id_t		id;
6442 	int		locked = 0;
6443 	kmutex_t	*pml;
6444 
6445 	ASSERT(PAGE_EXCL(pp));
6446 	if (!sfmmu_mlist_held(pp)) {
6447 		pml = sfmmu_mlist_enter(pp);
6448 		locked = 1;
6449 	}
6450 
6451 	if (capture_cpus)
6452 		*capture_cpus = 0;
6453 
6454 top:
6455 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6456 		/*
6457 		 * skip sf_hments corresponding to VA<->PA mappings;
6458 		 * for pa_hment's, hme_tte.ll is zero
6459 		 */
6460 		if (!IS_PAHME(sfhmep))
6461 			continue;
6462 
6463 		pahmep = sfhmep->hme_data;
6464 		ASSERT(pahmep != NULL);
6465 
6466 		/*
6467 		 * skip if pre-handler has been called earlier in this loop
6468 		 */
6469 		if (pahmep->flags & flag)
6470 			continue;
6471 
6472 		id = pahmep->cb_id;
6473 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6474 		if (capture_cpus && sfmmu_cb_table[id].capture_cpus != 0)
6475 			*capture_cpus = 1;
6476 		if ((f = sfmmu_cb_table[id].prehandler) == NULL) {
6477 			pahmep->flags |= flag;
6478 			continue;
6479 		}
6480 
6481 		/*
6482 		 * Drop the mapping list lock to avoid locking order issues.
6483 		 */
6484 		if (locked)
6485 			sfmmu_mlist_exit(pml);
6486 
6487 		ret = f(pahmep->addr, pahmep->len, flag, pahmep->pvt);
6488 		if (ret != 0)
6489 			return (ret);	/* caller must do the cleanup */
6490 
6491 		if (locked) {
6492 			pml = sfmmu_mlist_enter(pp);
6493 			pahmep->flags |= flag;
6494 			goto top;
6495 		}
6496 
6497 		pahmep->flags |= flag;
6498 	}
6499 
6500 	if (locked)
6501 		sfmmu_mlist_exit(pml);
6502 
6503 	return (0);
6504 }
6505 
6506 /*
6507  * Execute post-callback handler of each pa_hment linked to pp
6508  *
6509  * Same overall assumptions and restrictions apply as for
6510  * hat_pageprocess_precallbacks().
6511  */
6512 static void
6513 hat_pageprocess_postcallbacks(struct page *pp, uint_t flag)
6514 {
6515 	pfn_t pgpfn = pp->p_pagenum;
6516 	pfn_t pgmask = btop(page_get_pagesize(pp->p_szc)) - 1;
6517 	pfn_t newpfn;
6518 	struct sf_hment *sfhmep;
6519 	struct pa_hment *pahmep;
6520 	int (*f)(caddr_t, uint_t, uint_t, void *, pfn_t);
6521 	id_t	id;
6522 	int	locked = 0;
6523 	kmutex_t *pml;
6524 
6525 	ASSERT(PAGE_EXCL(pp));
6526 	if (!sfmmu_mlist_held(pp)) {
6527 		pml = sfmmu_mlist_enter(pp);
6528 		locked = 1;
6529 	}
6530 
6531 top:
6532 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6533 		/*
6534 		 * skip sf_hments corresponding to VA<->PA mappings;
6535 		 * for pa_hment's, hme_tte.ll is zero
6536 		 */
6537 		if (!IS_PAHME(sfhmep))
6538 			continue;
6539 
6540 		pahmep = sfhmep->hme_data;
6541 		ASSERT(pahmep != NULL);
6542 
6543 		if ((pahmep->flags & flag) == 0)
6544 			continue;
6545 
6546 		pahmep->flags &= ~flag;
6547 
6548 		id = pahmep->cb_id;
6549 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6550 		if ((f = sfmmu_cb_table[id].posthandler) == NULL)
6551 			continue;
6552 
6553 		/*
6554 		 * Convert the base page PFN into the constituent PFN
6555 		 * which is needed by the callback handler.
6556 		 */
6557 		newpfn = pgpfn | (btop((uintptr_t)pahmep->addr) & pgmask);
6558 
6559 		/*
6560 		 * Drop the mapping list lock to avoid locking order issues.
6561 		 */
6562 		if (locked)
6563 			sfmmu_mlist_exit(pml);
6564 
6565 		if (f(pahmep->addr, pahmep->len, flag, pahmep->pvt, newpfn)
6566 		    != 0)
6567 			panic("sfmmu: posthandler failed");
6568 
6569 		if (locked) {
6570 			pml = sfmmu_mlist_enter(pp);
6571 			goto top;
6572 		}
6573 	}
6574 
6575 	if (locked)
6576 		sfmmu_mlist_exit(pml);
6577 }
6578 
6579 /*
6580  * Suspend locked kernel mapping
6581  */
6582 void
6583 hat_pagesuspend(struct page *pp)
6584 {
6585 	struct sf_hment *sfhmep;
6586 	sfmmu_t *sfmmup;
6587 	tte_t tte, ttemod;
6588 	struct hme_blk *hmeblkp;
6589 	caddr_t addr;
6590 	int index, cons;
6591 	cpuset_t cpuset;
6592 
6593 	ASSERT(PAGE_EXCL(pp));
6594 	ASSERT(sfmmu_mlist_held(pp));
6595 
6596 	mutex_enter(&kpr_suspendlock);
6597 
6598 	/*
6599 	 * We're about to suspend a kernel mapping so mark this thread as
6600 	 * non-traceable by DTrace. This prevents us from running into issues
6601 	 * with probe context trying to touch a suspended page
6602 	 * in the relocation codepath itself.
6603 	 */
6604 	curthread->t_flag |= T_DONTDTRACE;
6605 
6606 	index = PP_MAPINDEX(pp);
6607 	cons = TTE8K;
6608 
6609 retry:
6610 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6611 
6612 		if (IS_PAHME(sfhmep))
6613 			continue;
6614 
6615 		if (get_hblk_ttesz(sfmmu_hmetohblk(sfhmep)) != cons)
6616 			continue;
6617 
6618 		/*
6619 		 * Loop until we successfully set the suspend bit in
6620 		 * the TTE.
6621 		 */
6622 again:
6623 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6624 		ASSERT(TTE_IS_VALID(&tte));
6625 
6626 		ttemod = tte;
6627 		TTE_SET_SUSPEND(&ttemod);
6628 		if (sfmmu_modifytte_try(&tte, &ttemod,
6629 		    &sfhmep->hme_tte) < 0)
6630 			goto again;
6631 
6632 		/*
6633 		 * Invalidate TSB entry
6634 		 */
6635 		hmeblkp = sfmmu_hmetohblk(sfhmep);
6636 
6637 		sfmmup = hblktosfmmu(hmeblkp);
6638 		ASSERT(sfmmup == ksfmmup);
6639 		ASSERT(!hmeblkp->hblk_shared);
6640 
6641 		addr = tte_to_vaddr(hmeblkp, tte);
6642 
6643 		/*
6644 		 * No need to make sure that the TSB for this sfmmu is
6645 		 * not being relocated since it is ksfmmup and thus it
6646 		 * will never be relocated.
6647 		 */
6648 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
6649 
6650 		/*
6651 		 * Update xcall stats
6652 		 */
6653 		cpuset = cpu_ready_set;
6654 		CPUSET_DEL(cpuset, CPU->cpu_id);
6655 
6656 		/* LINTED: constant in conditional context */
6657 		SFMMU_XCALL_STATS(ksfmmup);
6658 
6659 		/*
6660 		 * Flush TLB entry on remote CPU's
6661 		 */
6662 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
6663 		    (uint64_t)ksfmmup);
6664 		xt_sync(cpuset);
6665 
6666 		/*
6667 		 * Flush TLB entry on local CPU
6668 		 */
6669 		vtag_flushpage(addr, (uint64_t)ksfmmup);
6670 	}
6671 
6672 	while (index != 0) {
6673 		index = index >> 1;
6674 		if (index != 0)
6675 			cons++;
6676 		if (index & 0x1) {
6677 			pp = PP_GROUPLEADER(pp, cons);
6678 			goto retry;
6679 		}
6680 	}
6681 }
6682 
6683 #ifdef	DEBUG
6684 
6685 #define	N_PRLE	1024
6686 struct prle {
6687 	page_t *targ;
6688 	page_t *repl;
6689 	int status;
6690 	int pausecpus;
6691 	hrtime_t whence;
6692 };
6693 
6694 static struct prle page_relocate_log[N_PRLE];
6695 static int prl_entry;
6696 static kmutex_t prl_mutex;
6697 
6698 #define	PAGE_RELOCATE_LOG(t, r, s, p)					\
6699 	mutex_enter(&prl_mutex);					\
6700 	page_relocate_log[prl_entry].targ = *(t);			\
6701 	page_relocate_log[prl_entry].repl = *(r);			\
6702 	page_relocate_log[prl_entry].status = (s);			\
6703 	page_relocate_log[prl_entry].pausecpus = (p);			\
6704 	page_relocate_log[prl_entry].whence = gethrtime();		\
6705 	prl_entry = (prl_entry == (N_PRLE - 1))? 0 : prl_entry + 1;	\
6706 	mutex_exit(&prl_mutex);
6707 
6708 #else	/* !DEBUG */
6709 #define	PAGE_RELOCATE_LOG(t, r, s, p)
6710 #endif
6711 
6712 /*
6713  * Core Kernel Page Relocation Algorithm
6714  *
6715  * Input:
6716  *
6717  * target : 	constituent pages are SE_EXCL locked.
6718  * replacement:	constituent pages are SE_EXCL locked.
6719  *
6720  * Output:
6721  *
6722  * nrelocp:	number of pages relocated
6723  */
6724 int
6725 hat_page_relocate(page_t **target, page_t **replacement, spgcnt_t *nrelocp)
6726 {
6727 	page_t		*targ, *repl;
6728 	page_t		*tpp, *rpp;
6729 	kmutex_t	*low, *high;
6730 	spgcnt_t	npages, i;
6731 	page_t		*pl = NULL;
6732 	int		old_pil;
6733 	cpuset_t	cpuset;
6734 	int		cap_cpus;
6735 	int		ret;
6736 
6737 	if (hat_kpr_enabled == 0 || !kcage_on || PP_ISNORELOC(*target)) {
6738 		PAGE_RELOCATE_LOG(target, replacement, EAGAIN, -1);
6739 		return (EAGAIN);
6740 	}
6741 
6742 	mutex_enter(&kpr_mutex);
6743 	kreloc_thread = curthread;
6744 
6745 	targ = *target;
6746 	repl = *replacement;
6747 	ASSERT(repl != NULL);
6748 	ASSERT(targ->p_szc == repl->p_szc);
6749 
6750 	npages = page_get_pagecnt(targ->p_szc);
6751 
6752 	/*
6753 	 * unload VA<->PA mappings that are not locked
6754 	 */
6755 	tpp = targ;
6756 	for (i = 0; i < npages; i++) {
6757 		(void) hat_pageunload(tpp, SFMMU_KERNEL_RELOC);
6758 		tpp++;
6759 	}
6760 
6761 	/*
6762 	 * Do "presuspend" callbacks, in a context from which we can still
6763 	 * block as needed. Note that we don't hold the mapping list lock
6764 	 * of "targ" at this point due to potential locking order issues;
6765 	 * we assume that between the hat_pageunload() above and holding
6766 	 * the SE_EXCL lock that the mapping list *cannot* change at this
6767 	 * point.
6768 	 */
6769 	ret = hat_pageprocess_precallbacks(targ, HAT_PRESUSPEND, &cap_cpus);
6770 	if (ret != 0) {
6771 		/*
6772 		 * EIO translates to fatal error, for all others cleanup
6773 		 * and return EAGAIN.
6774 		 */
6775 		ASSERT(ret != EIO);
6776 		hat_pageprocess_postcallbacks(targ, HAT_POSTUNSUSPEND);
6777 		PAGE_RELOCATE_LOG(target, replacement, ret, -1);
6778 		kreloc_thread = NULL;
6779 		mutex_exit(&kpr_mutex);
6780 		return (EAGAIN);
6781 	}
6782 
6783 	/*
6784 	 * acquire p_mapping list lock for both the target and replacement
6785 	 * root pages.
6786 	 *
6787 	 * low and high refer to the need to grab the mlist locks in a
6788 	 * specific order in order to prevent race conditions.  Thus the
6789 	 * lower lock must be grabbed before the higher lock.
6790 	 *
6791 	 * This will block hat_unload's accessing p_mapping list.  Since
6792 	 * we have SE_EXCL lock, hat_memload and hat_pageunload will be
6793 	 * blocked.  Thus, no one else will be accessing the p_mapping list
6794 	 * while we suspend and reload the locked mapping below.
6795 	 */
6796 	tpp = targ;
6797 	rpp = repl;
6798 	sfmmu_mlist_reloc_enter(tpp, rpp, &low, &high);
6799 
6800 	kpreempt_disable();
6801 
6802 #ifdef VAC
6803 	/*
6804 	 * If the replacement page is of a different virtual color
6805 	 * than the page it is replacing, we need to handle the VAC
6806 	 * consistency for it just as we would if we were setting up
6807 	 * a new mapping to a page.
6808 	 */
6809 	if ((tpp->p_szc == 0) && (PP_GET_VCOLOR(rpp) != NO_VCOLOR)) {
6810 		if (tpp->p_vcolor != rpp->p_vcolor) {
6811 			sfmmu_cache_flushcolor(PP_GET_VCOLOR(rpp),
6812 			    rpp->p_pagenum);
6813 		}
6814 	}
6815 #endif
6816 
6817 	/*
6818 	 * We raise our PIL to 13 so that we don't get captured by
6819 	 * another CPU or pinned by an interrupt thread.  We can't go to
6820 	 * PIL 14 since the nexus driver(s) may need to interrupt at
6821 	 * that level in the case of IOMMU pseudo mappings.
6822 	 */
6823 	cpuset = cpu_ready_set;
6824 	CPUSET_DEL(cpuset, CPU->cpu_id);
6825 	if (!cap_cpus || CPUSET_ISNULL(cpuset)) {
6826 		old_pil = splr(XCALL_PIL);
6827 	} else {
6828 		old_pil = -1;
6829 		xc_attention(cpuset);
6830 	}
6831 	ASSERT(getpil() == XCALL_PIL);
6832 
6833 	/*
6834 	 * Now do suspend callbacks. In the case of an IOMMU mapping
6835 	 * this will suspend all DMA activity to the page while it is
6836 	 * being relocated. Since we are well above LOCK_LEVEL and CPUs
6837 	 * may be captured at this point we should have acquired any needed
6838 	 * locks in the presuspend callback.
6839 	 */
6840 	ret = hat_pageprocess_precallbacks(targ, HAT_SUSPEND, NULL);
6841 	if (ret != 0) {
6842 		repl = targ;
6843 		goto suspend_fail;
6844 	}
6845 
6846 	/*
6847 	 * Raise the PIL yet again, this time to block all high-level
6848 	 * interrupts on this CPU. This is necessary to prevent an
6849 	 * interrupt routine from pinning the thread which holds the
6850 	 * mapping suspended and then touching the suspended page.
6851 	 *
6852 	 * Once the page is suspended we also need to be careful to
6853 	 * avoid calling any functions which touch any seg_kmem memory
6854 	 * since that memory may be backed by the very page we are
6855 	 * relocating in here!
6856 	 */
6857 	hat_pagesuspend(targ);
6858 
6859 	/*
6860 	 * Now that we are confident everybody has stopped using this page,
6861 	 * copy the page contents.  Note we use a physical copy to prevent
6862 	 * locking issues and to avoid fpRAS because we can't handle it in
6863 	 * this context.
6864 	 */
6865 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6866 		/*
6867 		 * Copy the contents of the page.
6868 		 */
6869 		ppcopy_kernel(tpp, rpp);
6870 	}
6871 
6872 	tpp = targ;
6873 	rpp = repl;
6874 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6875 		/*
6876 		 * Copy attributes.  VAC consistency was handled above,
6877 		 * if required.
6878 		 */
6879 		rpp->p_nrm = tpp->p_nrm;
6880 		tpp->p_nrm = 0;
6881 		rpp->p_index = tpp->p_index;
6882 		tpp->p_index = 0;
6883 #ifdef VAC
6884 		rpp->p_vcolor = tpp->p_vcolor;
6885 #endif
6886 	}
6887 
6888 	/*
6889 	 * First, unsuspend the page, if we set the suspend bit, and transfer
6890 	 * the mapping list from the target page to the replacement page.
6891 	 * Next process postcallbacks; since pa_hment's are linked only to the
6892 	 * p_mapping list of root page, we don't iterate over the constituent
6893 	 * pages.
6894 	 */
6895 	hat_pagereload(targ, repl);
6896 
6897 suspend_fail:
6898 	hat_pageprocess_postcallbacks(repl, HAT_UNSUSPEND);
6899 
6900 	/*
6901 	 * Now lower our PIL and release any captured CPUs since we
6902 	 * are out of the "danger zone".  After this it will again be
6903 	 * safe to acquire adaptive mutex locks, or to drop them...
6904 	 */
6905 	if (old_pil != -1) {
6906 		splx(old_pil);
6907 	} else {
6908 		xc_dismissed(cpuset);
6909 	}
6910 
6911 	kpreempt_enable();
6912 
6913 	sfmmu_mlist_reloc_exit(low, high);
6914 
6915 	/*
6916 	 * Postsuspend callbacks should drop any locks held across
6917 	 * the suspend callbacks.  As before, we don't hold the mapping
6918 	 * list lock at this point.. our assumption is that the mapping
6919 	 * list still can't change due to our holding SE_EXCL lock and
6920 	 * there being no unlocked mappings left. Hence the restriction
6921 	 * on calling context to hat_delete_callback()
6922 	 */
6923 	hat_pageprocess_postcallbacks(repl, HAT_POSTUNSUSPEND);
6924 	if (ret != 0) {
6925 		/*
6926 		 * The second presuspend call failed: we got here through
6927 		 * the suspend_fail label above.
6928 		 */
6929 		ASSERT(ret != EIO);
6930 		PAGE_RELOCATE_LOG(target, replacement, ret, cap_cpus);
6931 		kreloc_thread = NULL;
6932 		mutex_exit(&kpr_mutex);
6933 		return (EAGAIN);
6934 	}
6935 
6936 	/*
6937 	 * Now that we're out of the performance critical section we can
6938 	 * take care of updating the hash table, since we still
6939 	 * hold all the pages locked SE_EXCL at this point we
6940 	 * needn't worry about things changing out from under us.
6941 	 */
6942 	tpp = targ;
6943 	rpp = repl;
6944 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6945 
6946 		/*
6947 		 * replace targ with replacement in page_hash table
6948 		 */
6949 		targ = tpp;
6950 		page_relocate_hash(rpp, targ);
6951 
6952 		/*
6953 		 * concatenate target; caller of platform_page_relocate()
6954 		 * expects target to be concatenated after returning.
6955 		 */
6956 		ASSERT(targ->p_next == targ);
6957 		ASSERT(targ->p_prev == targ);
6958 		page_list_concat(&pl, &targ);
6959 	}
6960 
6961 	ASSERT(*target == pl);
6962 	*nrelocp = npages;
6963 	PAGE_RELOCATE_LOG(target, replacement, 0, cap_cpus);
6964 	kreloc_thread = NULL;
6965 	mutex_exit(&kpr_mutex);
6966 	return (0);
6967 }
6968 
6969 /*
6970  * Called when stray pa_hments are found attached to a page which is
6971  * being freed.  Notify the subsystem which attached the pa_hment of
6972  * the error if it registered a suitable handler, else panic.
6973  */
6974 static void
6975 sfmmu_pahment_leaked(struct pa_hment *pahmep)
6976 {
6977 	id_t cb_id = pahmep->cb_id;
6978 
6979 	ASSERT(cb_id >= (id_t)0 && cb_id < sfmmu_cb_nextid);
6980 	if (sfmmu_cb_table[cb_id].errhandler != NULL) {
6981 		if (sfmmu_cb_table[cb_id].errhandler(pahmep->addr, pahmep->len,
6982 		    HAT_CB_ERR_LEAKED, pahmep->pvt) == 0)
6983 			return;		/* non-fatal */
6984 	}
6985 	panic("pa_hment leaked: 0x%p", pahmep);
6986 }
6987 
6988 /*
6989  * Remove all mappings to page 'pp'.
6990  */
6991 int
6992 hat_pageunload(struct page *pp, uint_t forceflag)
6993 {
6994 	struct page *origpp = pp;
6995 	struct sf_hment *sfhme, *tmphme;
6996 	struct hme_blk *hmeblkp;
6997 	kmutex_t *pml;
6998 #ifdef VAC
6999 	kmutex_t *pmtx;
7000 #endif
7001 	cpuset_t cpuset, tset;
7002 	int index, cons;
7003 	int xhme_blks;
7004 	int pa_hments;
7005 
7006 	ASSERT(PAGE_EXCL(pp));
7007 
7008 retry_xhat:
7009 	tmphme = NULL;
7010 	xhme_blks = 0;
7011 	pa_hments = 0;
7012 	CPUSET_ZERO(cpuset);
7013 
7014 	pml = sfmmu_mlist_enter(pp);
7015 
7016 #ifdef VAC
7017 	if (pp->p_kpmref)
7018 		sfmmu_kpm_pageunload(pp);
7019 	ASSERT(!PP_ISMAPPED_KPM(pp));
7020 #endif
7021 
7022 	index = PP_MAPINDEX(pp);
7023 	cons = TTE8K;
7024 retry:
7025 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7026 		tmphme = sfhme->hme_next;
7027 
7028 		if (IS_PAHME(sfhme)) {
7029 			ASSERT(sfhme->hme_data != NULL);
7030 			pa_hments++;
7031 			continue;
7032 		}
7033 
7034 		hmeblkp = sfmmu_hmetohblk(sfhme);
7035 		if (hmeblkp->hblk_xhat_bit) {
7036 			struct xhat_hme_blk *xblk =
7037 			    (struct xhat_hme_blk *)hmeblkp;
7038 
7039 			(void) XHAT_PAGEUNLOAD(xblk->xhat_hme_blk_hat,
7040 			    pp, forceflag, XBLK2PROVBLK(xblk));
7041 
7042 			xhme_blks = 1;
7043 			continue;
7044 		}
7045 
7046 		/*
7047 		 * If there are kernel mappings don't unload them, they will
7048 		 * be suspended.
7049 		 */
7050 		if (forceflag == SFMMU_KERNEL_RELOC && hmeblkp->hblk_lckcnt &&
7051 		    hmeblkp->hblk_tag.htag_id == ksfmmup)
7052 			continue;
7053 
7054 		tset = sfmmu_pageunload(pp, sfhme, cons);
7055 		CPUSET_OR(cpuset, tset);
7056 	}
7057 
7058 	while (index != 0) {
7059 		index = index >> 1;
7060 		if (index != 0)
7061 			cons++;
7062 		if (index & 0x1) {
7063 			/* Go to leading page */
7064 			pp = PP_GROUPLEADER(pp, cons);
7065 			ASSERT(sfmmu_mlist_held(pp));
7066 			goto retry;
7067 		}
7068 	}
7069 
7070 	/*
7071 	 * cpuset may be empty if the page was only mapped by segkpm,
7072 	 * in which case we won't actually cross-trap.
7073 	 */
7074 	xt_sync(cpuset);
7075 
7076 	/*
7077 	 * The page should have no mappings at this point, unless
7078 	 * we were called from hat_page_relocate() in which case we
7079 	 * leave the locked mappings which will be suspended later.
7080 	 */
7081 	ASSERT(!PP_ISMAPPED(origpp) || xhme_blks || pa_hments ||
7082 	    (forceflag == SFMMU_KERNEL_RELOC));
7083 
7084 #ifdef VAC
7085 	if (PP_ISTNC(pp)) {
7086 		if (cons == TTE8K) {
7087 			pmtx = sfmmu_page_enter(pp);
7088 			PP_CLRTNC(pp);
7089 			sfmmu_page_exit(pmtx);
7090 		} else {
7091 			conv_tnc(pp, cons);
7092 		}
7093 	}
7094 #endif	/* VAC */
7095 
7096 	if (pa_hments && forceflag != SFMMU_KERNEL_RELOC) {
7097 		/*
7098 		 * Unlink any pa_hments and free them, calling back
7099 		 * the responsible subsystem to notify it of the error.
7100 		 * This can occur in situations such as drivers leaking
7101 		 * DMA handles: naughty, but common enough that we'd like
7102 		 * to keep the system running rather than bringing it
7103 		 * down with an obscure error like "pa_hment leaked"
7104 		 * which doesn't aid the user in debugging their driver.
7105 		 */
7106 		for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7107 			tmphme = sfhme->hme_next;
7108 			if (IS_PAHME(sfhme)) {
7109 				struct pa_hment *pahmep = sfhme->hme_data;
7110 				sfmmu_pahment_leaked(pahmep);
7111 				HME_SUB(sfhme, pp);
7112 				kmem_cache_free(pa_hment_cache, pahmep);
7113 			}
7114 		}
7115 
7116 		ASSERT(!PP_ISMAPPED(origpp) || xhme_blks);
7117 	}
7118 
7119 	sfmmu_mlist_exit(pml);
7120 
7121 	/*
7122 	 * XHAT may not have finished unloading pages
7123 	 * because some other thread was waiting for
7124 	 * mlist lock and XHAT_PAGEUNLOAD let it do
7125 	 * the job.
7126 	 */
7127 	if (xhme_blks) {
7128 		pp = origpp;
7129 		goto retry_xhat;
7130 	}
7131 
7132 	return (0);
7133 }
7134 
7135 cpuset_t
7136 sfmmu_pageunload(page_t *pp, struct sf_hment *sfhme, int cons)
7137 {
7138 	struct hme_blk *hmeblkp;
7139 	sfmmu_t *sfmmup;
7140 	tte_t tte, ttemod;
7141 #ifdef DEBUG
7142 	tte_t orig_old;
7143 #endif /* DEBUG */
7144 	caddr_t addr;
7145 	int ttesz;
7146 	int ret;
7147 	cpuset_t cpuset;
7148 
7149 	ASSERT(pp != NULL);
7150 	ASSERT(sfmmu_mlist_held(pp));
7151 	ASSERT(!PP_ISKAS(pp));
7152 
7153 	CPUSET_ZERO(cpuset);
7154 
7155 	hmeblkp = sfmmu_hmetohblk(sfhme);
7156 
7157 readtte:
7158 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7159 	if (TTE_IS_VALID(&tte)) {
7160 		sfmmup = hblktosfmmu(hmeblkp);
7161 		ttesz = get_hblk_ttesz(hmeblkp);
7162 		/*
7163 		 * Only unload mappings of 'cons' size.
7164 		 */
7165 		if (ttesz != cons)
7166 			return (cpuset);
7167 
7168 		/*
7169 		 * Note that we have p_mapping lock, but no hash lock here.
7170 		 * hblk_unload() has to have both hash lock AND p_mapping
7171 		 * lock before it tries to modify tte. So, the tte could
7172 		 * not become invalid in the sfmmu_modifytte_try() below.
7173 		 */
7174 		ttemod = tte;
7175 #ifdef DEBUG
7176 		orig_old = tte;
7177 #endif /* DEBUG */
7178 
7179 		TTE_SET_INVALID(&ttemod);
7180 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7181 		if (ret < 0) {
7182 #ifdef DEBUG
7183 			/* only R/M bits can change. */
7184 			chk_tte(&orig_old, &tte, &ttemod, hmeblkp);
7185 #endif /* DEBUG */
7186 			goto readtte;
7187 		}
7188 
7189 		if (ret == 0) {
7190 			panic("pageunload: cas failed?");
7191 		}
7192 
7193 		addr = tte_to_vaddr(hmeblkp, tte);
7194 
7195 		if (hmeblkp->hblk_shared) {
7196 			sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7197 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
7198 			sf_region_t *rgnp;
7199 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7200 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7201 			ASSERT(srdp != NULL);
7202 			rgnp = srdp->srd_hmergnp[rid];
7203 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
7204 			cpuset = sfmmu_rgntlb_demap(addr, rgnp, hmeblkp, 1);
7205 			sfmmu_ttesync(NULL, addr, &tte, pp);
7206 			ASSERT(rgnp->rgn_ttecnt[ttesz] > 0);
7207 			atomic_add_long(&rgnp->rgn_ttecnt[ttesz], -1);
7208 		} else {
7209 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
7210 			atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -1);
7211 
7212 			/*
7213 			 * We need to flush the page from the virtual cache
7214 			 * in order to prevent a virtual cache alias
7215 			 * inconsistency. The particular scenario we need
7216 			 * to worry about is:
7217 			 * Given:  va1 and va2 are two virtual address that
7218 			 * alias and will map the same physical address.
7219 			 * 1.   mapping exists from va1 to pa and data has
7220 			 *	been read into the cache.
7221 			 * 2.   unload va1.
7222 			 * 3.   load va2 and modify data using va2.
7223 			 * 4    unload va2.
7224 			 * 5.   load va1 and reference data.  Unless we flush
7225 			 *	the data cache when we unload we will get
7226 			 *	stale data.
7227 			 * This scenario is taken care of by using virtual
7228 			 * page coloring.
7229 			 */
7230 			if (sfmmup->sfmmu_ismhat) {
7231 				/*
7232 				 * Flush TSBs, TLBs and caches
7233 				 * of every process
7234 				 * sharing this ism segment.
7235 				 */
7236 				sfmmu_hat_lock_all();
7237 				mutex_enter(&ism_mlist_lock);
7238 				kpreempt_disable();
7239 				sfmmu_ismtlbcache_demap(addr, sfmmup, hmeblkp,
7240 				    pp->p_pagenum, CACHE_NO_FLUSH);
7241 				kpreempt_enable();
7242 				mutex_exit(&ism_mlist_lock);
7243 				sfmmu_hat_unlock_all();
7244 				cpuset = cpu_ready_set;
7245 			} else {
7246 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7247 				cpuset = sfmmup->sfmmu_cpusran;
7248 			}
7249 		}
7250 
7251 		/*
7252 		 * Hme_sub has to run after ttesync() and a_rss update.
7253 		 * See hblk_unload().
7254 		 */
7255 		HME_SUB(sfhme, pp);
7256 		membar_stst();
7257 
7258 		/*
7259 		 * We can not make ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
7260 		 * since pteload may have done a HME_ADD() right after
7261 		 * we did the HME_SUB() above. Hmecnt is now maintained
7262 		 * by cas only. no lock guranteed its value. The only
7263 		 * gurantee we have is the hmecnt should not be less than
7264 		 * what it should be so the hblk will not be taken away.
7265 		 * It's also important that we decremented the hmecnt after
7266 		 * we are done with hmeblkp so that this hmeblk won't be
7267 		 * stolen.
7268 		 */
7269 		ASSERT(hmeblkp->hblk_hmecnt > 0);
7270 		ASSERT(hmeblkp->hblk_vcnt > 0);
7271 		atomic_add_16(&hmeblkp->hblk_vcnt, -1);
7272 		atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
7273 		/*
7274 		 * This is bug 4063182.
7275 		 * XXX: fixme
7276 		 * ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
7277 		 *	!hmeblkp->hblk_lckcnt);
7278 		 */
7279 	} else {
7280 		panic("invalid tte? pp %p &tte %p",
7281 		    (void *)pp, (void *)&tte);
7282 	}
7283 
7284 	return (cpuset);
7285 }
7286 
7287 /*
7288  * While relocating a kernel page, this function will move the mappings
7289  * from tpp to dpp and modify any associated data with these mappings.
7290  * It also unsuspends the suspended kernel mapping.
7291  */
7292 static void
7293 hat_pagereload(struct page *tpp, struct page *dpp)
7294 {
7295 	struct sf_hment *sfhme;
7296 	tte_t tte, ttemod;
7297 	int index, cons;
7298 
7299 	ASSERT(getpil() == PIL_MAX);
7300 	ASSERT(sfmmu_mlist_held(tpp));
7301 	ASSERT(sfmmu_mlist_held(dpp));
7302 
7303 	index = PP_MAPINDEX(tpp);
7304 	cons = TTE8K;
7305 
7306 	/* Update real mappings to the page */
7307 retry:
7308 	for (sfhme = tpp->p_mapping; sfhme != NULL; sfhme = sfhme->hme_next) {
7309 		if (IS_PAHME(sfhme))
7310 			continue;
7311 		sfmmu_copytte(&sfhme->hme_tte, &tte);
7312 		ttemod = tte;
7313 
7314 		/*
7315 		 * replace old pfn with new pfn in TTE
7316 		 */
7317 		PFN_TO_TTE(ttemod, dpp->p_pagenum);
7318 
7319 		/*
7320 		 * clear suspend bit
7321 		 */
7322 		ASSERT(TTE_IS_SUSPEND(&ttemod));
7323 		TTE_CLR_SUSPEND(&ttemod);
7324 
7325 		if (sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte) < 0)
7326 			panic("hat_pagereload(): sfmmu_modifytte_try() failed");
7327 
7328 		/*
7329 		 * set hme_page point to new page
7330 		 */
7331 		sfhme->hme_page = dpp;
7332 	}
7333 
7334 	/*
7335 	 * move p_mapping list from old page to new page
7336 	 */
7337 	dpp->p_mapping = tpp->p_mapping;
7338 	tpp->p_mapping = NULL;
7339 	dpp->p_share = tpp->p_share;
7340 	tpp->p_share = 0;
7341 
7342 	while (index != 0) {
7343 		index = index >> 1;
7344 		if (index != 0)
7345 			cons++;
7346 		if (index & 0x1) {
7347 			tpp = PP_GROUPLEADER(tpp, cons);
7348 			dpp = PP_GROUPLEADER(dpp, cons);
7349 			goto retry;
7350 		}
7351 	}
7352 
7353 	curthread->t_flag &= ~T_DONTDTRACE;
7354 	mutex_exit(&kpr_suspendlock);
7355 }
7356 
7357 uint_t
7358 hat_pagesync(struct page *pp, uint_t clearflag)
7359 {
7360 	struct sf_hment *sfhme, *tmphme = NULL;
7361 	struct hme_blk *hmeblkp;
7362 	kmutex_t *pml;
7363 	cpuset_t cpuset, tset;
7364 	int	index, cons;
7365 	extern	ulong_t po_share;
7366 	page_t	*save_pp = pp;
7367 	int	stop_on_sh = 0;
7368 	uint_t	shcnt;
7369 
7370 	CPUSET_ZERO(cpuset);
7371 
7372 	if (PP_ISRO(pp) && (clearflag & HAT_SYNC_STOPON_MOD)) {
7373 		return (PP_GENERIC_ATTR(pp));
7374 	}
7375 
7376 	if ((clearflag == (HAT_SYNC_STOPON_REF | HAT_SYNC_DONTZERO)) &&
7377 	    PP_ISREF(pp)) {
7378 		return (PP_GENERIC_ATTR(pp));
7379 	}
7380 
7381 	if ((clearflag == (HAT_SYNC_STOPON_MOD | HAT_SYNC_DONTZERO)) &&
7382 	    PP_ISMOD(pp)) {
7383 		return (PP_GENERIC_ATTR(pp));
7384 	}
7385 
7386 	if ((clearflag & HAT_SYNC_STOPON_SHARED) != 0 &&
7387 	    (pp->p_share > po_share) &&
7388 	    !(clearflag & HAT_SYNC_ZERORM)) {
7389 		hat_page_setattr(pp, P_REF);
7390 		return (PP_GENERIC_ATTR(pp));
7391 	}
7392 
7393 	if ((clearflag & HAT_SYNC_STOPON_SHARED) &&
7394 	    !(clearflag & HAT_SYNC_ZERORM)) {
7395 		stop_on_sh = 1;
7396 		shcnt = 0;
7397 	}
7398 	clearflag &= ~HAT_SYNC_STOPON_SHARED;
7399 	pml = sfmmu_mlist_enter(pp);
7400 	index = PP_MAPINDEX(pp);
7401 	cons = TTE8K;
7402 retry:
7403 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7404 		/*
7405 		 * We need to save the next hment on the list since
7406 		 * it is possible for pagesync to remove an invalid hment
7407 		 * from the list.
7408 		 */
7409 		tmphme = sfhme->hme_next;
7410 		/*
7411 		 * If we are looking for large mappings and this hme doesn't
7412 		 * reach the range we are seeking, just ignore its.
7413 		 */
7414 		hmeblkp = sfmmu_hmetohblk(sfhme);
7415 		if (hmeblkp->hblk_xhat_bit)
7416 			continue;
7417 
7418 		if (hme_size(sfhme) < cons)
7419 			continue;
7420 
7421 		if (stop_on_sh) {
7422 			if (hmeblkp->hblk_shared) {
7423 				sf_srd_t *srdp = hblktosrd(hmeblkp);
7424 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7425 				sf_region_t *rgnp;
7426 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7427 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7428 				ASSERT(srdp != NULL);
7429 				rgnp = srdp->srd_hmergnp[rid];
7430 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
7431 				    rgnp, rid);
7432 				shcnt += rgnp->rgn_refcnt;
7433 			} else {
7434 				shcnt++;
7435 			}
7436 			if (shcnt > po_share) {
7437 				/*
7438 				 * tell the pager to spare the page this time
7439 				 * around.
7440 				 */
7441 				hat_page_setattr(save_pp, P_REF);
7442 				index = 0;
7443 				break;
7444 			}
7445 		}
7446 		tset = sfmmu_pagesync(pp, sfhme,
7447 		    clearflag & ~HAT_SYNC_STOPON_RM);
7448 		CPUSET_OR(cpuset, tset);
7449 
7450 		/*
7451 		 * If clearflag is HAT_SYNC_DONTZERO, break out as soon
7452 		 * as the "ref" or "mod" is set or share cnt exceeds po_share.
7453 		 */
7454 		if ((clearflag & ~HAT_SYNC_STOPON_RM) == HAT_SYNC_DONTZERO &&
7455 		    (((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(save_pp)) ||
7456 		    ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(save_pp)))) {
7457 			index = 0;
7458 			break;
7459 		}
7460 	}
7461 
7462 	while (index) {
7463 		index = index >> 1;
7464 		cons++;
7465 		if (index & 0x1) {
7466 			/* Go to leading page */
7467 			pp = PP_GROUPLEADER(pp, cons);
7468 			goto retry;
7469 		}
7470 	}
7471 
7472 	xt_sync(cpuset);
7473 	sfmmu_mlist_exit(pml);
7474 	return (PP_GENERIC_ATTR(save_pp));
7475 }
7476 
7477 /*
7478  * Get all the hardware dependent attributes for a page struct
7479  */
7480 static cpuset_t
7481 sfmmu_pagesync(struct page *pp, struct sf_hment *sfhme,
7482 	uint_t clearflag)
7483 {
7484 	caddr_t addr;
7485 	tte_t tte, ttemod;
7486 	struct hme_blk *hmeblkp;
7487 	int ret;
7488 	sfmmu_t *sfmmup;
7489 	cpuset_t cpuset;
7490 
7491 	ASSERT(pp != NULL);
7492 	ASSERT(sfmmu_mlist_held(pp));
7493 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
7494 	    (clearflag == HAT_SYNC_ZERORM));
7495 
7496 	SFMMU_STAT(sf_pagesync);
7497 
7498 	CPUSET_ZERO(cpuset);
7499 
7500 sfmmu_pagesync_retry:
7501 
7502 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7503 	if (TTE_IS_VALID(&tte)) {
7504 		hmeblkp = sfmmu_hmetohblk(sfhme);
7505 		sfmmup = hblktosfmmu(hmeblkp);
7506 		addr = tte_to_vaddr(hmeblkp, tte);
7507 		if (clearflag == HAT_SYNC_ZERORM) {
7508 			ttemod = tte;
7509 			TTE_CLR_RM(&ttemod);
7510 			ret = sfmmu_modifytte_try(&tte, &ttemod,
7511 			    &sfhme->hme_tte);
7512 			if (ret < 0) {
7513 				/*
7514 				 * cas failed and the new value is not what
7515 				 * we want.
7516 				 */
7517 				goto sfmmu_pagesync_retry;
7518 			}
7519 
7520 			if (ret > 0) {
7521 				/* we win the cas */
7522 				if (hmeblkp->hblk_shared) {
7523 					sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7524 					uint_t rid =
7525 					    hmeblkp->hblk_tag.htag_rid;
7526 					sf_region_t *rgnp;
7527 					ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7528 					ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7529 					ASSERT(srdp != NULL);
7530 					rgnp = srdp->srd_hmergnp[rid];
7531 					SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7532 					    srdp, rgnp, rid);
7533 					cpuset = sfmmu_rgntlb_demap(addr,
7534 					    rgnp, hmeblkp, 1);
7535 				} else {
7536 					sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
7537 					    0, 0);
7538 					cpuset = sfmmup->sfmmu_cpusran;
7539 				}
7540 			}
7541 		}
7542 		sfmmu_ttesync(hmeblkp->hblk_shared ? NULL : sfmmup, addr,
7543 		    &tte, pp);
7544 	}
7545 	return (cpuset);
7546 }
7547 
7548 /*
7549  * Remove write permission from a mappings to a page, so that
7550  * we can detect the next modification of it. This requires modifying
7551  * the TTE then invalidating (demap) any TLB entry using that TTE.
7552  * This code is similar to sfmmu_pagesync().
7553  */
7554 static cpuset_t
7555 sfmmu_pageclrwrt(struct page *pp, struct sf_hment *sfhme)
7556 {
7557 	caddr_t addr;
7558 	tte_t tte;
7559 	tte_t ttemod;
7560 	struct hme_blk *hmeblkp;
7561 	int ret;
7562 	sfmmu_t *sfmmup;
7563 	cpuset_t cpuset;
7564 
7565 	ASSERT(pp != NULL);
7566 	ASSERT(sfmmu_mlist_held(pp));
7567 
7568 	CPUSET_ZERO(cpuset);
7569 	SFMMU_STAT(sf_clrwrt);
7570 
7571 retry:
7572 
7573 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7574 	if (TTE_IS_VALID(&tte) && TTE_IS_WRITABLE(&tte)) {
7575 		hmeblkp = sfmmu_hmetohblk(sfhme);
7576 
7577 		/*
7578 		 * xhat mappings should never be to a VMODSORT page.
7579 		 */
7580 		ASSERT(hmeblkp->hblk_xhat_bit == 0);
7581 
7582 		sfmmup = hblktosfmmu(hmeblkp);
7583 		addr = tte_to_vaddr(hmeblkp, tte);
7584 
7585 		ttemod = tte;
7586 		TTE_CLR_WRT(&ttemod);
7587 		TTE_CLR_MOD(&ttemod);
7588 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7589 
7590 		/*
7591 		 * if cas failed and the new value is not what
7592 		 * we want retry
7593 		 */
7594 		if (ret < 0)
7595 			goto retry;
7596 
7597 		/* we win the cas */
7598 		if (ret > 0) {
7599 			if (hmeblkp->hblk_shared) {
7600 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7601 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7602 				sf_region_t *rgnp;
7603 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7604 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7605 				ASSERT(srdp != NULL);
7606 				rgnp = srdp->srd_hmergnp[rid];
7607 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7608 				    srdp, rgnp, rid);
7609 				cpuset = sfmmu_rgntlb_demap(addr,
7610 				    rgnp, hmeblkp, 1);
7611 			} else {
7612 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7613 				cpuset = sfmmup->sfmmu_cpusran;
7614 			}
7615 		}
7616 	}
7617 
7618 	return (cpuset);
7619 }
7620 
7621 /*
7622  * Walk all mappings of a page, removing write permission and clearing the
7623  * ref/mod bits. This code is similar to hat_pagesync()
7624  */
7625 static void
7626 hat_page_clrwrt(page_t *pp)
7627 {
7628 	struct sf_hment *sfhme;
7629 	struct sf_hment *tmphme = NULL;
7630 	kmutex_t *pml;
7631 	cpuset_t cpuset;
7632 	cpuset_t tset;
7633 	int	index;
7634 	int	 cons;
7635 
7636 	CPUSET_ZERO(cpuset);
7637 
7638 	pml = sfmmu_mlist_enter(pp);
7639 	index = PP_MAPINDEX(pp);
7640 	cons = TTE8K;
7641 retry:
7642 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7643 		tmphme = sfhme->hme_next;
7644 
7645 		/*
7646 		 * If we are looking for large mappings and this hme doesn't
7647 		 * reach the range we are seeking, just ignore its.
7648 		 */
7649 
7650 		if (hme_size(sfhme) < cons)
7651 			continue;
7652 
7653 		tset = sfmmu_pageclrwrt(pp, sfhme);
7654 		CPUSET_OR(cpuset, tset);
7655 	}
7656 
7657 	while (index) {
7658 		index = index >> 1;
7659 		cons++;
7660 		if (index & 0x1) {
7661 			/* Go to leading page */
7662 			pp = PP_GROUPLEADER(pp, cons);
7663 			goto retry;
7664 		}
7665 	}
7666 
7667 	xt_sync(cpuset);
7668 	sfmmu_mlist_exit(pml);
7669 }
7670 
7671 /*
7672  * Set the given REF/MOD/RO bits for the given page.
7673  * For a vnode with a sorted v_pages list, we need to change
7674  * the attributes and the v_pages list together under page_vnode_mutex.
7675  */
7676 void
7677 hat_page_setattr(page_t *pp, uint_t flag)
7678 {
7679 	vnode_t		*vp = pp->p_vnode;
7680 	page_t		**listp;
7681 	kmutex_t	*pmtx;
7682 	kmutex_t	*vphm = NULL;
7683 	int		noshuffle;
7684 
7685 	noshuffle = flag & P_NSH;
7686 	flag &= ~P_NSH;
7687 
7688 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7689 
7690 	/*
7691 	 * nothing to do if attribute already set
7692 	 */
7693 	if ((pp->p_nrm & flag) == flag)
7694 		return;
7695 
7696 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp) &&
7697 	    !noshuffle) {
7698 		vphm = page_vnode_mutex(vp);
7699 		mutex_enter(vphm);
7700 	}
7701 
7702 	pmtx = sfmmu_page_enter(pp);
7703 	pp->p_nrm |= flag;
7704 	sfmmu_page_exit(pmtx);
7705 
7706 	if (vphm != NULL) {
7707 		/*
7708 		 * Some File Systems examine v_pages for NULL w/o
7709 		 * grabbing the vphm mutex. Must not let it become NULL when
7710 		 * pp is the only page on the list.
7711 		 */
7712 		if (pp->p_vpnext != pp) {
7713 			page_vpsub(&vp->v_pages, pp);
7714 			if (vp->v_pages != NULL)
7715 				listp = &vp->v_pages->p_vpprev->p_vpnext;
7716 			else
7717 				listp = &vp->v_pages;
7718 			page_vpadd(listp, pp);
7719 		}
7720 		mutex_exit(vphm);
7721 	}
7722 }
7723 
7724 void
7725 hat_page_clrattr(page_t *pp, uint_t flag)
7726 {
7727 	vnode_t		*vp = pp->p_vnode;
7728 	kmutex_t	*pmtx;
7729 
7730 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7731 
7732 	pmtx = sfmmu_page_enter(pp);
7733 
7734 	/*
7735 	 * Caller is expected to hold page's io lock for VMODSORT to work
7736 	 * correctly with pvn_vplist_dirty() and pvn_getdirty() when mod
7737 	 * bit is cleared.
7738 	 * We don't have assert to avoid tripping some existing third party
7739 	 * code. The dirty page is moved back to top of the v_page list
7740 	 * after IO is done in pvn_write_done().
7741 	 */
7742 	pp->p_nrm &= ~flag;
7743 	sfmmu_page_exit(pmtx);
7744 
7745 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
7746 
7747 		/*
7748 		 * VMODSORT works by removing write permissions and getting
7749 		 * a fault when a page is made dirty. At this point
7750 		 * we need to remove write permission from all mappings
7751 		 * to this page.
7752 		 */
7753 		hat_page_clrwrt(pp);
7754 	}
7755 }
7756 
7757 uint_t
7758 hat_page_getattr(page_t *pp, uint_t flag)
7759 {
7760 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7761 	return ((uint_t)(pp->p_nrm & flag));
7762 }
7763 
7764 /*
7765  * DEBUG kernels: verify that a kernel va<->pa translation
7766  * is safe by checking the underlying page_t is in a page
7767  * relocation-safe state.
7768  */
7769 #ifdef	DEBUG
7770 void
7771 sfmmu_check_kpfn(pfn_t pfn)
7772 {
7773 	page_t *pp;
7774 	int index, cons;
7775 
7776 	if (hat_check_vtop == 0)
7777 		return;
7778 
7779 	if (hat_kpr_enabled == 0 || kvseg.s_base == NULL || panicstr)
7780 		return;
7781 
7782 	pp = page_numtopp_nolock(pfn);
7783 	if (!pp)
7784 		return;
7785 
7786 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7787 		return;
7788 
7789 	/*
7790 	 * Handed a large kernel page, we dig up the root page since we
7791 	 * know the root page might have the lock also.
7792 	 */
7793 	if (pp->p_szc != 0) {
7794 		index = PP_MAPINDEX(pp);
7795 		cons = TTE8K;
7796 again:
7797 		while (index != 0) {
7798 			index >>= 1;
7799 			if (index != 0)
7800 				cons++;
7801 			if (index & 0x1) {
7802 				pp = PP_GROUPLEADER(pp, cons);
7803 				goto again;
7804 			}
7805 		}
7806 	}
7807 
7808 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7809 		return;
7810 
7811 	/*
7812 	 * Pages need to be locked or allocated "permanent" (either from
7813 	 * static_arena arena or explicitly setting PG_NORELOC when calling
7814 	 * page_create_va()) for VA->PA translations to be valid.
7815 	 */
7816 	if (!PP_ISNORELOC(pp))
7817 		panic("Illegal VA->PA translation, pp 0x%p not permanent", pp);
7818 	else
7819 		panic("Illegal VA->PA translation, pp 0x%p not locked", pp);
7820 }
7821 #endif	/* DEBUG */
7822 
7823 /*
7824  * Returns a page frame number for a given virtual address.
7825  * Returns PFN_INVALID to indicate an invalid mapping
7826  */
7827 pfn_t
7828 hat_getpfnum(struct hat *hat, caddr_t addr)
7829 {
7830 	pfn_t pfn;
7831 	tte_t tte;
7832 
7833 	/*
7834 	 * We would like to
7835 	 * ASSERT(AS_LOCK_HELD(as, &as->a_lock));
7836 	 * but we can't because the iommu driver will call this
7837 	 * routine at interrupt time and it can't grab the as lock
7838 	 * or it will deadlock: A thread could have the as lock
7839 	 * and be waiting for io.  The io can't complete
7840 	 * because the interrupt thread is blocked trying to grab
7841 	 * the as lock.
7842 	 */
7843 
7844 	ASSERT(hat->sfmmu_xhat_provider == NULL);
7845 
7846 	if (hat == ksfmmup) {
7847 		if (IS_KMEM_VA_LARGEPAGE(addr)) {
7848 			ASSERT(segkmem_lpszc > 0);
7849 			pfn = sfmmu_kvaszc2pfn(addr, segkmem_lpszc);
7850 			if (pfn != PFN_INVALID) {
7851 				sfmmu_check_kpfn(pfn);
7852 				return (pfn);
7853 			}
7854 		} else if (segkpm && IS_KPM_ADDR(addr)) {
7855 			return (sfmmu_kpm_vatopfn(addr));
7856 		}
7857 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7858 		    == PFN_SUSPENDED) {
7859 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7860 		}
7861 		sfmmu_check_kpfn(pfn);
7862 		return (pfn);
7863 	} else {
7864 		return (sfmmu_uvatopfn(addr, hat, NULL));
7865 	}
7866 }
7867 
7868 /*
7869  * hat_getkpfnum() is an obsolete DDI routine, and its use is discouraged.
7870  * Use hat_getpfnum(kas.a_hat, ...) instead.
7871  *
7872  * We'd like to return PFN_INVALID if the mappings have underlying page_t's
7873  * but can't right now due to the fact that some software has grown to use
7874  * this interface incorrectly. So for now when the interface is misused,
7875  * return a warning to the user that in the future it won't work in the
7876  * way they're abusing it, and carry on (after disabling page relocation).
7877  */
7878 pfn_t
7879 hat_getkpfnum(caddr_t addr)
7880 {
7881 	pfn_t pfn;
7882 	tte_t tte;
7883 	int badcaller = 0;
7884 	extern int segkmem_reloc;
7885 
7886 	if (segkpm && IS_KPM_ADDR(addr)) {
7887 		badcaller = 1;
7888 		pfn = sfmmu_kpm_vatopfn(addr);
7889 	} else {
7890 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7891 		    == PFN_SUSPENDED) {
7892 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7893 		}
7894 		badcaller = pf_is_memory(pfn);
7895 	}
7896 
7897 	if (badcaller) {
7898 		/*
7899 		 * We can't return PFN_INVALID or the caller may panic
7900 		 * or corrupt the system.  The only alternative is to
7901 		 * disable page relocation at this point for all kernel
7902 		 * memory.  This will impact any callers of page_relocate()
7903 		 * such as FMA or DR.
7904 		 *
7905 		 * RFE: Add junk here to spit out an ereport so the sysadmin
7906 		 * can be advised that he should upgrade his device driver
7907 		 * so that this doesn't happen.
7908 		 */
7909 		hat_getkpfnum_badcall(caller());
7910 		if (hat_kpr_enabled && segkmem_reloc) {
7911 			hat_kpr_enabled = 0;
7912 			segkmem_reloc = 0;
7913 			cmn_err(CE_WARN, "Kernel Page Relocation is DISABLED");
7914 		}
7915 	}
7916 	return (pfn);
7917 }
7918 
7919 /*
7920  * This routine will return both pfn and tte for the addr.
7921  */
7922 static pfn_t
7923 sfmmu_uvatopfn(caddr_t vaddr, struct hat *sfmmup, tte_t *ttep)
7924 {
7925 	struct hmehash_bucket *hmebp;
7926 	hmeblk_tag hblktag;
7927 	int hmeshift, hashno = 1;
7928 	struct hme_blk *hmeblkp = NULL;
7929 	tte_t tte;
7930 
7931 	struct sf_hment *sfhmep;
7932 	pfn_t pfn;
7933 
7934 	/* support for ISM */
7935 	ism_map_t	*ism_map;
7936 	ism_blk_t	*ism_blkp;
7937 	int		i;
7938 	sfmmu_t *ism_hatid = NULL;
7939 	sfmmu_t *locked_hatid = NULL;
7940 	sfmmu_t	*sv_sfmmup = sfmmup;
7941 	caddr_t	sv_vaddr = vaddr;
7942 	sf_srd_t *srdp;
7943 
7944 	if (ttep == NULL) {
7945 		ttep = &tte;
7946 	} else {
7947 		ttep->ll = 0;
7948 	}
7949 
7950 	ASSERT(sfmmup != ksfmmup);
7951 	SFMMU_STAT(sf_user_vtop);
7952 	/*
7953 	 * Set ism_hatid if vaddr falls in a ISM segment.
7954 	 */
7955 	ism_blkp = sfmmup->sfmmu_iblk;
7956 	if (ism_blkp != NULL) {
7957 		sfmmu_ismhat_enter(sfmmup, 0);
7958 		locked_hatid = sfmmup;
7959 	}
7960 	while (ism_blkp != NULL && ism_hatid == NULL) {
7961 		ism_map = ism_blkp->iblk_maps;
7962 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
7963 			if (vaddr >= ism_start(ism_map[i]) &&
7964 			    vaddr < ism_end(ism_map[i])) {
7965 				sfmmup = ism_hatid = ism_map[i].imap_ismhat;
7966 				vaddr = (caddr_t)(vaddr -
7967 				    ism_start(ism_map[i]));
7968 				break;
7969 			}
7970 		}
7971 		ism_blkp = ism_blkp->iblk_next;
7972 	}
7973 	if (locked_hatid) {
7974 		sfmmu_ismhat_exit(locked_hatid, 0);
7975 	}
7976 
7977 	hblktag.htag_id = sfmmup;
7978 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
7979 	do {
7980 		hmeshift = HME_HASH_SHIFT(hashno);
7981 		hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
7982 		hblktag.htag_rehash = hashno;
7983 		hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
7984 
7985 		SFMMU_HASH_LOCK(hmebp);
7986 
7987 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
7988 		if (hmeblkp != NULL) {
7989 			ASSERT(!hmeblkp->hblk_shared);
7990 			HBLKTOHME(sfhmep, hmeblkp, vaddr);
7991 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
7992 			SFMMU_HASH_UNLOCK(hmebp);
7993 			if (TTE_IS_VALID(ttep)) {
7994 				pfn = TTE_TO_PFN(vaddr, ttep);
7995 				return (pfn);
7996 			}
7997 			break;
7998 		}
7999 		SFMMU_HASH_UNLOCK(hmebp);
8000 		hashno++;
8001 	} while (HME_REHASH(sfmmup) && (hashno <= mmu_hashcnt));
8002 
8003 	if (SF_HMERGNMAP_ISNULL(sv_sfmmup)) {
8004 		return (PFN_INVALID);
8005 	}
8006 	srdp = sv_sfmmup->sfmmu_srdp;
8007 	ASSERT(srdp != NULL);
8008 	ASSERT(srdp->srd_refcnt != 0);
8009 	hblktag.htag_id = srdp;
8010 	hashno = 1;
8011 	do {
8012 		hmeshift = HME_HASH_SHIFT(hashno);
8013 		hblktag.htag_bspage = HME_HASH_BSPAGE(sv_vaddr, hmeshift);
8014 		hblktag.htag_rehash = hashno;
8015 		hmebp = HME_HASH_FUNCTION(srdp, sv_vaddr, hmeshift);
8016 
8017 		SFMMU_HASH_LOCK(hmebp);
8018 		for (hmeblkp = hmebp->hmeblkp; hmeblkp != NULL;
8019 		    hmeblkp = hmeblkp->hblk_next) {
8020 			uint_t rid;
8021 			sf_region_t *rgnp;
8022 			caddr_t rsaddr;
8023 			caddr_t readdr;
8024 
8025 			if (!HTAGS_EQ_SHME(hmeblkp->hblk_tag, hblktag,
8026 			    sv_sfmmup->sfmmu_hmeregion_map)) {
8027 				continue;
8028 			}
8029 			ASSERT(hmeblkp->hblk_shared);
8030 			rid = hmeblkp->hblk_tag.htag_rid;
8031 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8032 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8033 			rgnp = srdp->srd_hmergnp[rid];
8034 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
8035 			HBLKTOHME(sfhmep, hmeblkp, sv_vaddr);
8036 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
8037 			rsaddr = rgnp->rgn_saddr;
8038 			readdr = rsaddr + rgnp->rgn_size;
8039 #ifdef DEBUG
8040 			if (TTE_IS_VALID(ttep) ||
8041 			    get_hblk_ttesz(hmeblkp) > TTE8K) {
8042 				caddr_t eva = tte_to_evaddr(hmeblkp, ttep);
8043 				ASSERT(eva > sv_vaddr);
8044 				ASSERT(sv_vaddr >= rsaddr);
8045 				ASSERT(sv_vaddr < readdr);
8046 				ASSERT(eva <= readdr);
8047 			}
8048 #endif /* DEBUG */
8049 			/*
8050 			 * Continue the search if we
8051 			 * found an invalid 8K tte outside of the area
8052 			 * covered by this hmeblk's region.
8053 			 */
8054 			if (TTE_IS_VALID(ttep)) {
8055 				SFMMU_HASH_UNLOCK(hmebp);
8056 				pfn = TTE_TO_PFN(sv_vaddr, ttep);
8057 				return (pfn);
8058 			} else if (get_hblk_ttesz(hmeblkp) > TTE8K ||
8059 			    (sv_vaddr >= rsaddr && sv_vaddr < readdr)) {
8060 				SFMMU_HASH_UNLOCK(hmebp);
8061 				pfn = PFN_INVALID;
8062 				return (pfn);
8063 			}
8064 		}
8065 		SFMMU_HASH_UNLOCK(hmebp);
8066 		hashno++;
8067 	} while (hashno <= mmu_hashcnt);
8068 	return (PFN_INVALID);
8069 }
8070 
8071 
8072 /*
8073  * For compatability with AT&T and later optimizations
8074  */
8075 /* ARGSUSED */
8076 void
8077 hat_map(struct hat *hat, caddr_t addr, size_t len, uint_t flags)
8078 {
8079 	ASSERT(hat != NULL);
8080 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8081 }
8082 
8083 /*
8084  * Return the number of mappings to a particular page.  This number is an
8085  * approximation of the number of people sharing the page.
8086  *
8087  * shared hmeblks or ism hmeblks are counted as 1 mapping here.
8088  * hat_page_checkshare() can be used to compare threshold to share
8089  * count that reflects the number of region sharers albeit at higher cost.
8090  */
8091 ulong_t
8092 hat_page_getshare(page_t *pp)
8093 {
8094 	page_t *spp = pp;	/* start page */
8095 	kmutex_t *pml;
8096 	ulong_t	cnt;
8097 	int index, sz = TTE64K;
8098 
8099 	/*
8100 	 * We need to grab the mlist lock to make sure any outstanding
8101 	 * load/unloads complete.  Otherwise we could return zero
8102 	 * even though the unload(s) hasn't finished yet.
8103 	 */
8104 	pml = sfmmu_mlist_enter(spp);
8105 	cnt = spp->p_share;
8106 
8107 #ifdef VAC
8108 	if (kpm_enable)
8109 		cnt += spp->p_kpmref;
8110 #endif
8111 
8112 	/*
8113 	 * If we have any large mappings, we count the number of
8114 	 * mappings that this large page is part of.
8115 	 */
8116 	index = PP_MAPINDEX(spp);
8117 	index >>= 1;
8118 	while (index) {
8119 		pp = PP_GROUPLEADER(spp, sz);
8120 		if ((index & 0x1) && pp != spp) {
8121 			cnt += pp->p_share;
8122 			spp = pp;
8123 		}
8124 		index >>= 1;
8125 		sz++;
8126 	}
8127 	sfmmu_mlist_exit(pml);
8128 	return (cnt);
8129 }
8130 
8131 /*
8132  * Return 1 the number of mappings exceeds sh_thresh. Return 0
8133  * otherwise. Count shared hmeblks by region's refcnt.
8134  */
8135 int
8136 hat_page_checkshare(page_t *pp, ulong_t sh_thresh)
8137 {
8138 	kmutex_t *pml;
8139 	ulong_t	cnt = 0;
8140 	int index, sz = TTE8K;
8141 	struct sf_hment *sfhme, *tmphme = NULL;
8142 	struct hme_blk *hmeblkp;
8143 
8144 	pml = sfmmu_mlist_enter(pp);
8145 
8146 	if (kpm_enable)
8147 		cnt = pp->p_kpmref;
8148 
8149 	if (pp->p_share + cnt > sh_thresh) {
8150 		sfmmu_mlist_exit(pml);
8151 		return (1);
8152 	}
8153 
8154 	index = PP_MAPINDEX(pp);
8155 
8156 again:
8157 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
8158 		tmphme = sfhme->hme_next;
8159 		if (hme_size(sfhme) != sz) {
8160 			continue;
8161 		}
8162 		hmeblkp = sfmmu_hmetohblk(sfhme);
8163 		if (hmeblkp->hblk_shared) {
8164 			sf_srd_t *srdp = hblktosrd(hmeblkp);
8165 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
8166 			sf_region_t *rgnp;
8167 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8168 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8169 			ASSERT(srdp != NULL);
8170 			rgnp = srdp->srd_hmergnp[rid];
8171 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
8172 			    rgnp, rid);
8173 			cnt += rgnp->rgn_refcnt;
8174 		} else {
8175 			cnt++;
8176 		}
8177 		if (cnt > sh_thresh) {
8178 			sfmmu_mlist_exit(pml);
8179 			return (1);
8180 		}
8181 	}
8182 
8183 	index >>= 1;
8184 	sz++;
8185 	while (index) {
8186 		pp = PP_GROUPLEADER(pp, sz);
8187 		ASSERT(sfmmu_mlist_held(pp));
8188 		if (index & 0x1) {
8189 			goto again;
8190 		}
8191 		index >>= 1;
8192 		sz++;
8193 	}
8194 	sfmmu_mlist_exit(pml);
8195 	return (0);
8196 }
8197 
8198 /*
8199  * Unload all large mappings to the pp and reset the p_szc field of every
8200  * constituent page according to the remaining mappings.
8201  *
8202  * pp must be locked SE_EXCL. Even though no other constituent pages are
8203  * locked it's legal to unload the large mappings to the pp because all
8204  * constituent pages of large locked mappings have to be locked SE_SHARED.
8205  * This means if we have SE_EXCL lock on one of constituent pages none of the
8206  * large mappings to pp are locked.
8207  *
8208  * Decrease p_szc field starting from the last constituent page and ending
8209  * with the root page. This method is used because other threads rely on the
8210  * root's p_szc to find the lock to syncronize on. After a root page_t's p_szc
8211  * is demoted then other threads will succeed in sfmmu_mlspl_enter(). This
8212  * ensures that p_szc changes of the constituent pages appears atomic for all
8213  * threads that use sfmmu_mlspl_enter() to examine p_szc field.
8214  *
8215  * This mechanism is only used for file system pages where it's not always
8216  * possible to get SE_EXCL locks on all constituent pages to demote the size
8217  * code (as is done for anonymous or kernel large pages).
8218  *
8219  * See more comments in front of sfmmu_mlspl_enter().
8220  */
8221 void
8222 hat_page_demote(page_t *pp)
8223 {
8224 	int index;
8225 	int sz;
8226 	cpuset_t cpuset;
8227 	int sync = 0;
8228 	page_t *rootpp;
8229 	struct sf_hment *sfhme;
8230 	struct sf_hment *tmphme = NULL;
8231 	struct hme_blk *hmeblkp;
8232 	uint_t pszc;
8233 	page_t *lastpp;
8234 	cpuset_t tset;
8235 	pgcnt_t npgs;
8236 	kmutex_t *pml;
8237 	kmutex_t *pmtx = NULL;
8238 
8239 	ASSERT(PAGE_EXCL(pp));
8240 	ASSERT(!PP_ISFREE(pp));
8241 	ASSERT(page_szc_lock_assert(pp));
8242 	pml = sfmmu_mlist_enter(pp);
8243 
8244 	pszc = pp->p_szc;
8245 	if (pszc == 0) {
8246 		goto out;
8247 	}
8248 
8249 	index = PP_MAPINDEX(pp) >> 1;
8250 
8251 	if (index) {
8252 		CPUSET_ZERO(cpuset);
8253 		sz = TTE64K;
8254 		sync = 1;
8255 	}
8256 
8257 	while (index) {
8258 		if (!(index & 0x1)) {
8259 			index >>= 1;
8260 			sz++;
8261 			continue;
8262 		}
8263 		ASSERT(sz <= pszc);
8264 		rootpp = PP_GROUPLEADER(pp, sz);
8265 		for (sfhme = rootpp->p_mapping; sfhme; sfhme = tmphme) {
8266 			tmphme = sfhme->hme_next;
8267 			hmeblkp = sfmmu_hmetohblk(sfhme);
8268 			if (hme_size(sfhme) != sz) {
8269 				continue;
8270 			}
8271 			if (hmeblkp->hblk_xhat_bit) {
8272 				cmn_err(CE_PANIC,
8273 				    "hat_page_demote: xhat hmeblk");
8274 			}
8275 			tset = sfmmu_pageunload(rootpp, sfhme, sz);
8276 			CPUSET_OR(cpuset, tset);
8277 		}
8278 		if (index >>= 1) {
8279 			sz++;
8280 		}
8281 	}
8282 
8283 	ASSERT(!PP_ISMAPPED_LARGE(pp));
8284 
8285 	if (sync) {
8286 		xt_sync(cpuset);
8287 #ifdef VAC
8288 		if (PP_ISTNC(pp)) {
8289 			conv_tnc(rootpp, sz);
8290 		}
8291 #endif	/* VAC */
8292 	}
8293 
8294 	pmtx = sfmmu_page_enter(pp);
8295 
8296 	ASSERT(pp->p_szc == pszc);
8297 	rootpp = PP_PAGEROOT(pp);
8298 	ASSERT(rootpp->p_szc == pszc);
8299 	lastpp = PP_PAGENEXT_N(rootpp, TTEPAGES(pszc) - 1);
8300 
8301 	while (lastpp != rootpp) {
8302 		sz = PP_MAPINDEX(lastpp) ? fnd_mapping_sz(lastpp) : 0;
8303 		ASSERT(sz < pszc);
8304 		npgs = (sz == 0) ? 1 : TTEPAGES(sz);
8305 		ASSERT(P2PHASE(lastpp->p_pagenum, npgs) == npgs - 1);
8306 		while (--npgs > 0) {
8307 			lastpp->p_szc = (uchar_t)sz;
8308 			lastpp = PP_PAGEPREV(lastpp);
8309 		}
8310 		if (sz) {
8311 			/*
8312 			 * make sure before current root's pszc
8313 			 * is updated all updates to constituent pages pszc
8314 			 * fields are globally visible.
8315 			 */
8316 			membar_producer();
8317 		}
8318 		lastpp->p_szc = sz;
8319 		ASSERT(IS_P2ALIGNED(lastpp->p_pagenum, TTEPAGES(sz)));
8320 		if (lastpp != rootpp) {
8321 			lastpp = PP_PAGEPREV(lastpp);
8322 		}
8323 	}
8324 	if (sz == 0) {
8325 		/* the loop above doesn't cover this case */
8326 		rootpp->p_szc = 0;
8327 	}
8328 out:
8329 	ASSERT(pp->p_szc == 0);
8330 	if (pmtx != NULL) {
8331 		sfmmu_page_exit(pmtx);
8332 	}
8333 	sfmmu_mlist_exit(pml);
8334 }
8335 
8336 /*
8337  * Refresh the HAT ismttecnt[] element for size szc.
8338  * Caller must have set ISM busy flag to prevent mapping
8339  * lists from changing while we're traversing them.
8340  */
8341 pgcnt_t
8342 ism_tsb_entries(sfmmu_t *sfmmup, int szc)
8343 {
8344 	ism_blk_t	*ism_blkp = sfmmup->sfmmu_iblk;
8345 	ism_map_t	*ism_map;
8346 	pgcnt_t		npgs = 0;
8347 	pgcnt_t		npgs_scd = 0;
8348 	int		j;
8349 	sf_scd_t	*scdp;
8350 	uchar_t		rid;
8351 
8352 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
8353 	scdp = sfmmup->sfmmu_scdp;
8354 
8355 	for (; ism_blkp != NULL; ism_blkp = ism_blkp->iblk_next) {
8356 		ism_map = ism_blkp->iblk_maps;
8357 		for (j = 0; ism_map[j].imap_ismhat && j < ISM_MAP_SLOTS; j++) {
8358 			rid = ism_map[j].imap_rid;
8359 			ASSERT(rid == SFMMU_INVALID_ISMRID ||
8360 			    rid < sfmmup->sfmmu_srdp->srd_next_ismrid);
8361 
8362 			if (scdp != NULL && rid != SFMMU_INVALID_ISMRID &&
8363 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
8364 				/* ISM is in sfmmup's SCD */
8365 				npgs_scd +=
8366 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8367 			} else {
8368 				/* ISMs is not in SCD */
8369 				npgs +=
8370 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8371 			}
8372 		}
8373 	}
8374 	sfmmup->sfmmu_ismttecnt[szc] = npgs;
8375 	sfmmup->sfmmu_scdismttecnt[szc] = npgs_scd;
8376 	return (npgs);
8377 }
8378 
8379 /*
8380  * Yield the memory claim requirement for an address space.
8381  *
8382  * This is currently implemented as the number of bytes that have active
8383  * hardware translations that have page structures.  Therefore, it can
8384  * underestimate the traditional resident set size, eg, if the
8385  * physical page is present and the hardware translation is missing;
8386  * and it can overestimate the rss, eg, if there are active
8387  * translations to a frame buffer with page structs.
8388  * Also, it does not take sharing into account.
8389  *
8390  * Note that we don't acquire locks here since this function is most often
8391  * called from the clock thread.
8392  */
8393 size_t
8394 hat_get_mapped_size(struct hat *hat)
8395 {
8396 	size_t		assize = 0;
8397 	int 		i;
8398 
8399 	if (hat == NULL)
8400 		return (0);
8401 
8402 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8403 
8404 	for (i = 0; i < mmu_page_sizes; i++)
8405 		assize += ((pgcnt_t)hat->sfmmu_ttecnt[i] +
8406 		    (pgcnt_t)hat->sfmmu_scdrttecnt[i]) * TTEBYTES(i);
8407 
8408 	if (hat->sfmmu_iblk == NULL)
8409 		return (assize);
8410 
8411 	for (i = 0; i < mmu_page_sizes; i++)
8412 		assize += ((pgcnt_t)hat->sfmmu_ismttecnt[i] +
8413 		    (pgcnt_t)hat->sfmmu_scdismttecnt[i]) * TTEBYTES(i);
8414 
8415 	return (assize);
8416 }
8417 
8418 int
8419 hat_stats_enable(struct hat *hat)
8420 {
8421 	hatlock_t	*hatlockp;
8422 
8423 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8424 
8425 	hatlockp = sfmmu_hat_enter(hat);
8426 	hat->sfmmu_rmstat++;
8427 	sfmmu_hat_exit(hatlockp);
8428 	return (1);
8429 }
8430 
8431 void
8432 hat_stats_disable(struct hat *hat)
8433 {
8434 	hatlock_t	*hatlockp;
8435 
8436 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8437 
8438 	hatlockp = sfmmu_hat_enter(hat);
8439 	hat->sfmmu_rmstat--;
8440 	sfmmu_hat_exit(hatlockp);
8441 }
8442 
8443 /*
8444  * Routines for entering or removing  ourselves from the
8445  * ism_hat's mapping list. This is used for both private and
8446  * SCD hats.
8447  */
8448 static void
8449 iment_add(struct ism_ment *iment,  struct hat *ism_hat)
8450 {
8451 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8452 
8453 	iment->iment_prev = NULL;
8454 	iment->iment_next = ism_hat->sfmmu_iment;
8455 	if (ism_hat->sfmmu_iment) {
8456 		ism_hat->sfmmu_iment->iment_prev = iment;
8457 	}
8458 	ism_hat->sfmmu_iment = iment;
8459 }
8460 
8461 static void
8462 iment_sub(struct ism_ment *iment, struct hat *ism_hat)
8463 {
8464 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8465 
8466 	if (ism_hat->sfmmu_iment == NULL) {
8467 		panic("ism map entry remove - no entries");
8468 	}
8469 
8470 	if (iment->iment_prev) {
8471 		ASSERT(ism_hat->sfmmu_iment != iment);
8472 		iment->iment_prev->iment_next = iment->iment_next;
8473 	} else {
8474 		ASSERT(ism_hat->sfmmu_iment == iment);
8475 		ism_hat->sfmmu_iment = iment->iment_next;
8476 	}
8477 
8478 	if (iment->iment_next) {
8479 		iment->iment_next->iment_prev = iment->iment_prev;
8480 	}
8481 
8482 	/*
8483 	 * zero out the entry
8484 	 */
8485 	iment->iment_next = NULL;
8486 	iment->iment_prev = NULL;
8487 	iment->iment_hat =  NULL;
8488 }
8489 
8490 /*
8491  * Hat_share()/unshare() return an (non-zero) error
8492  * when saddr and daddr are not properly aligned.
8493  *
8494  * The top level mapping element determines the alignment
8495  * requirement for saddr and daddr, depending on different
8496  * architectures.
8497  *
8498  * When hat_share()/unshare() are not supported,
8499  * HATOP_SHARE()/UNSHARE() return 0
8500  */
8501 int
8502 hat_share(struct hat *sfmmup, caddr_t addr,
8503 	struct hat *ism_hatid, caddr_t sptaddr, size_t len, uint_t ismszc)
8504 {
8505 	ism_blk_t	*ism_blkp;
8506 	ism_blk_t	*new_iblk;
8507 	ism_map_t 	*ism_map;
8508 	ism_ment_t	*ism_ment;
8509 	int		i, added;
8510 	hatlock_t	*hatlockp;
8511 	int		reload_mmu = 0;
8512 	uint_t		ismshift = page_get_shift(ismszc);
8513 	size_t		ismpgsz = page_get_pagesize(ismszc);
8514 	uint_t		ismmask = (uint_t)ismpgsz - 1;
8515 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8516 	ushort_t	ismhatflag;
8517 	hat_region_cookie_t rcookie;
8518 	sf_scd_t	*old_scdp;
8519 
8520 #ifdef DEBUG
8521 	caddr_t		eaddr = addr + len;
8522 #endif /* DEBUG */
8523 
8524 	ASSERT(ism_hatid != NULL && sfmmup != NULL);
8525 	ASSERT(sptaddr == ISMID_STARTADDR);
8526 	/*
8527 	 * Check the alignment.
8528 	 */
8529 	if (!ISM_ALIGNED(ismshift, addr) || !ISM_ALIGNED(ismshift, sptaddr))
8530 		return (EINVAL);
8531 
8532 	/*
8533 	 * Check size alignment.
8534 	 */
8535 	if (!ISM_ALIGNED(ismshift, len))
8536 		return (EINVAL);
8537 
8538 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
8539 
8540 	/*
8541 	 * Allocate ism_ment for the ism_hat's mapping list, and an
8542 	 * ism map blk in case we need one.  We must do our
8543 	 * allocations before acquiring locks to prevent a deadlock
8544 	 * in the kmem allocator on the mapping list lock.
8545 	 */
8546 	new_iblk = kmem_cache_alloc(ism_blk_cache, KM_SLEEP);
8547 	ism_ment = kmem_cache_alloc(ism_ment_cache, KM_SLEEP);
8548 
8549 	/*
8550 	 * Serialize ISM mappings with the ISM busy flag, and also the
8551 	 * trap handlers.
8552 	 */
8553 	sfmmu_ismhat_enter(sfmmup, 0);
8554 
8555 	/*
8556 	 * Allocate an ism map blk if necessary.
8557 	 */
8558 	if (sfmmup->sfmmu_iblk == NULL) {
8559 		sfmmup->sfmmu_iblk = new_iblk;
8560 		bzero(new_iblk, sizeof (*new_iblk));
8561 		new_iblk->iblk_nextpa = (uint64_t)-1;
8562 		membar_stst();	/* make sure next ptr visible to all CPUs */
8563 		sfmmup->sfmmu_ismblkpa = va_to_pa((caddr_t)new_iblk);
8564 		reload_mmu = 1;
8565 		new_iblk = NULL;
8566 	}
8567 
8568 #ifdef DEBUG
8569 	/*
8570 	 * Make sure mapping does not already exist.
8571 	 */
8572 	ism_blkp = sfmmup->sfmmu_iblk;
8573 	while (ism_blkp != NULL) {
8574 		ism_map = ism_blkp->iblk_maps;
8575 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
8576 			if ((addr >= ism_start(ism_map[i]) &&
8577 			    addr < ism_end(ism_map[i])) ||
8578 			    eaddr > ism_start(ism_map[i]) &&
8579 			    eaddr <= ism_end(ism_map[i])) {
8580 				panic("sfmmu_share: Already mapped!");
8581 			}
8582 		}
8583 		ism_blkp = ism_blkp->iblk_next;
8584 	}
8585 #endif /* DEBUG */
8586 
8587 	ASSERT(ismszc >= TTE4M);
8588 	if (ismszc == TTE4M) {
8589 		ismhatflag = HAT_4M_FLAG;
8590 	} else if (ismszc == TTE32M) {
8591 		ismhatflag = HAT_32M_FLAG;
8592 	} else if (ismszc == TTE256M) {
8593 		ismhatflag = HAT_256M_FLAG;
8594 	}
8595 	/*
8596 	 * Add mapping to first available mapping slot.
8597 	 */
8598 	ism_blkp = sfmmup->sfmmu_iblk;
8599 	added = 0;
8600 	while (!added) {
8601 		ism_map = ism_blkp->iblk_maps;
8602 		for (i = 0; i < ISM_MAP_SLOTS; i++)  {
8603 			if (ism_map[i].imap_ismhat == NULL) {
8604 
8605 				ism_map[i].imap_ismhat = ism_hatid;
8606 				ism_map[i].imap_vb_shift = (uchar_t)ismshift;
8607 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8608 				ism_map[i].imap_hatflags = ismhatflag;
8609 				ism_map[i].imap_sz_mask = ismmask;
8610 				/*
8611 				 * imap_seg is checked in ISM_CHECK to see if
8612 				 * non-NULL, then other info assumed valid.
8613 				 */
8614 				membar_stst();
8615 				ism_map[i].imap_seg = (uintptr_t)addr | sh_size;
8616 				ism_map[i].imap_ment = ism_ment;
8617 
8618 				/*
8619 				 * Now add ourselves to the ism_hat's
8620 				 * mapping list.
8621 				 */
8622 				ism_ment->iment_hat = sfmmup;
8623 				ism_ment->iment_base_va = addr;
8624 				ism_hatid->sfmmu_ismhat = 1;
8625 				mutex_enter(&ism_mlist_lock);
8626 				iment_add(ism_ment, ism_hatid);
8627 				mutex_exit(&ism_mlist_lock);
8628 				added = 1;
8629 				break;
8630 			}
8631 		}
8632 		if (!added && ism_blkp->iblk_next == NULL) {
8633 			ism_blkp->iblk_next = new_iblk;
8634 			new_iblk = NULL;
8635 			bzero(ism_blkp->iblk_next,
8636 			    sizeof (*ism_blkp->iblk_next));
8637 			ism_blkp->iblk_next->iblk_nextpa = (uint64_t)-1;
8638 			membar_stst();
8639 			ism_blkp->iblk_nextpa =
8640 			    va_to_pa((caddr_t)ism_blkp->iblk_next);
8641 		}
8642 		ism_blkp = ism_blkp->iblk_next;
8643 	}
8644 
8645 	/*
8646 	 * After calling hat_join_region, sfmmup may join a new SCD or
8647 	 * move from the old scd to a new scd, in which case, we want to
8648 	 * shrink the sfmmup's private tsb size, i.e., pass shrink to
8649 	 * sfmmu_check_page_sizes at the end of this routine.
8650 	 */
8651 	old_scdp = sfmmup->sfmmu_scdp;
8652 	/*
8653 	 * Call hat_join_region without the hat lock, because it's
8654 	 * used in hat_join_region.
8655 	 */
8656 	rcookie = hat_join_region(sfmmup, addr, len, (void *)ism_hatid, 0,
8657 	    PROT_ALL, ismszc, NULL, HAT_REGION_ISM);
8658 	if (rcookie != HAT_INVALID_REGION_COOKIE) {
8659 		ism_map[i].imap_rid = (uchar_t)((uint64_t)rcookie);
8660 	}
8661 	/*
8662 	 * Update our counters for this sfmmup's ism mappings.
8663 	 */
8664 	for (i = 0; i <= ismszc; i++) {
8665 		if (!(disable_ism_large_pages & (1 << i)))
8666 			(void) ism_tsb_entries(sfmmup, i);
8667 	}
8668 
8669 	/*
8670 	 * For ISM and DISM we do not support 512K pages, so we only only
8671 	 * search the 4M and 8K/64K hashes for 4 pagesize cpus, and search the
8672 	 * 256M or 32M, and 4M and 8K/64K hashes for 6 pagesize cpus.
8673 	 *
8674 	 * Need to set 32M/256M ISM flags to make sure
8675 	 * sfmmu_check_page_sizes() enables them on Panther.
8676 	 */
8677 	ASSERT((disable_ism_large_pages & (1 << TTE512K)) != 0);
8678 
8679 	switch (ismszc) {
8680 	case TTE256M:
8681 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_256M_ISM)) {
8682 			hatlockp = sfmmu_hat_enter(sfmmup);
8683 			SFMMU_FLAGS_SET(sfmmup, HAT_256M_ISM);
8684 			sfmmu_hat_exit(hatlockp);
8685 		}
8686 		break;
8687 	case TTE32M:
8688 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_32M_ISM)) {
8689 			hatlockp = sfmmu_hat_enter(sfmmup);
8690 			SFMMU_FLAGS_SET(sfmmup, HAT_32M_ISM);
8691 			sfmmu_hat_exit(hatlockp);
8692 		}
8693 		break;
8694 	default:
8695 		break;
8696 	}
8697 
8698 	/*
8699 	 * If we updated the ismblkpa for this HAT we must make
8700 	 * sure all CPUs running this process reload their tsbmiss area.
8701 	 * Otherwise they will fail to load the mappings in the tsbmiss
8702 	 * handler and will loop calling pagefault().
8703 	 */
8704 	if (reload_mmu) {
8705 		hatlockp = sfmmu_hat_enter(sfmmup);
8706 		sfmmu_sync_mmustate(sfmmup);
8707 		sfmmu_hat_exit(hatlockp);
8708 	}
8709 
8710 	sfmmu_ismhat_exit(sfmmup, 0);
8711 
8712 	/*
8713 	 * Free up ismblk if we didn't use it.
8714 	 */
8715 	if (new_iblk != NULL)
8716 		kmem_cache_free(ism_blk_cache, new_iblk);
8717 
8718 	/*
8719 	 * Check TSB and TLB page sizes.
8720 	 */
8721 	if (sfmmup->sfmmu_scdp != NULL && old_scdp != sfmmup->sfmmu_scdp) {
8722 		sfmmu_check_page_sizes(sfmmup, 0);
8723 	} else {
8724 		sfmmu_check_page_sizes(sfmmup, 1);
8725 	}
8726 	return (0);
8727 }
8728 
8729 /*
8730  * hat_unshare removes exactly one ism_map from
8731  * this process's as.  It expects multiple calls
8732  * to hat_unshare for multiple shm segments.
8733  */
8734 void
8735 hat_unshare(struct hat *sfmmup, caddr_t addr, size_t len, uint_t ismszc)
8736 {
8737 	ism_map_t 	*ism_map;
8738 	ism_ment_t	*free_ment = NULL;
8739 	ism_blk_t	*ism_blkp;
8740 	struct hat	*ism_hatid;
8741 	int 		found, i;
8742 	hatlock_t	*hatlockp;
8743 	struct tsb_info	*tsbinfo;
8744 	uint_t		ismshift = page_get_shift(ismszc);
8745 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8746 	uchar_t		ism_rid;
8747 	sf_scd_t	*old_scdp;
8748 
8749 	ASSERT(ISM_ALIGNED(ismshift, addr));
8750 	ASSERT(ISM_ALIGNED(ismshift, len));
8751 	ASSERT(sfmmup != NULL);
8752 	ASSERT(sfmmup != ksfmmup);
8753 
8754 	if (sfmmup->sfmmu_xhat_provider) {
8755 		XHAT_UNSHARE(sfmmup, addr, len);
8756 		return;
8757 	} else {
8758 		/*
8759 		 * This must be a CPU HAT. If the address space has
8760 		 * XHATs attached, inform all XHATs that ISM segment
8761 		 * is going away
8762 		 */
8763 		ASSERT(sfmmup->sfmmu_as != NULL);
8764 		if (sfmmup->sfmmu_as->a_xhat != NULL)
8765 			xhat_unshare_all(sfmmup->sfmmu_as, addr, len);
8766 	}
8767 
8768 	/*
8769 	 * Make sure that during the entire time ISM mappings are removed,
8770 	 * the trap handlers serialize behind us, and that no one else
8771 	 * can be mucking with ISM mappings.  This also lets us get away
8772 	 * with not doing expensive cross calls to flush the TLB -- we
8773 	 * just discard the context, flush the entire TSB, and call it
8774 	 * a day.
8775 	 */
8776 	sfmmu_ismhat_enter(sfmmup, 0);
8777 
8778 	/*
8779 	 * Remove the mapping.
8780 	 *
8781 	 * We can't have any holes in the ism map.
8782 	 * The tsb miss code while searching the ism map will
8783 	 * stop on an empty map slot.  So we must move
8784 	 * everyone past the hole up 1 if any.
8785 	 *
8786 	 * Also empty ism map blks are not freed until the
8787 	 * process exits. This is to prevent a MT race condition
8788 	 * between sfmmu_unshare() and sfmmu_tsbmiss_exception().
8789 	 */
8790 	found = 0;
8791 	ism_blkp = sfmmup->sfmmu_iblk;
8792 	while (!found && ism_blkp != NULL) {
8793 		ism_map = ism_blkp->iblk_maps;
8794 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
8795 			if (addr == ism_start(ism_map[i]) &&
8796 			    sh_size == (size_t)(ism_size(ism_map[i]))) {
8797 				found = 1;
8798 				break;
8799 			}
8800 		}
8801 		if (!found)
8802 			ism_blkp = ism_blkp->iblk_next;
8803 	}
8804 
8805 	if (found) {
8806 		ism_hatid = ism_map[i].imap_ismhat;
8807 		ism_rid = ism_map[i].imap_rid;
8808 		ASSERT(ism_hatid != NULL);
8809 		ASSERT(ism_hatid->sfmmu_ismhat == 1);
8810 
8811 		/*
8812 		 * After hat_leave_region, the sfmmup may leave SCD,
8813 		 * in which case, we want to grow the private tsb size
8814 		 * when call sfmmu_check_page_sizes at the end of the routine.
8815 		 */
8816 		old_scdp = sfmmup->sfmmu_scdp;
8817 		/*
8818 		 * Then remove ourselves from the region.
8819 		 */
8820 		if (ism_rid != SFMMU_INVALID_ISMRID) {
8821 			hat_leave_region(sfmmup, (void *)((uint64_t)ism_rid),
8822 			    HAT_REGION_ISM);
8823 		}
8824 
8825 		/*
8826 		 * And now guarantee that any other cpu
8827 		 * that tries to process an ISM miss
8828 		 * will go to tl=0.
8829 		 */
8830 		hatlockp = sfmmu_hat_enter(sfmmup);
8831 		sfmmu_invalidate_ctx(sfmmup);
8832 		sfmmu_hat_exit(hatlockp);
8833 
8834 		/*
8835 		 * Remove ourselves from the ism mapping list.
8836 		 */
8837 		mutex_enter(&ism_mlist_lock);
8838 		iment_sub(ism_map[i].imap_ment, ism_hatid);
8839 		mutex_exit(&ism_mlist_lock);
8840 		free_ment = ism_map[i].imap_ment;
8841 
8842 		/*
8843 		 * We delete the ism map by copying
8844 		 * the next map over the current one.
8845 		 * We will take the next one in the maps
8846 		 * array or from the next ism_blk.
8847 		 */
8848 		while (ism_blkp != NULL) {
8849 			ism_map = ism_blkp->iblk_maps;
8850 			while (i < (ISM_MAP_SLOTS - 1)) {
8851 				ism_map[i] = ism_map[i + 1];
8852 				i++;
8853 			}
8854 			/* i == (ISM_MAP_SLOTS - 1) */
8855 			ism_blkp = ism_blkp->iblk_next;
8856 			if (ism_blkp != NULL) {
8857 				ism_map[i] = ism_blkp->iblk_maps[0];
8858 				i = 0;
8859 			} else {
8860 				ism_map[i].imap_seg = 0;
8861 				ism_map[i].imap_vb_shift = 0;
8862 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8863 				ism_map[i].imap_hatflags = 0;
8864 				ism_map[i].imap_sz_mask = 0;
8865 				ism_map[i].imap_ismhat = NULL;
8866 				ism_map[i].imap_ment = NULL;
8867 			}
8868 		}
8869 
8870 		/*
8871 		 * Now flush entire TSB for the process, since
8872 		 * demapping page by page can be too expensive.
8873 		 * We don't have to flush the TLB here anymore
8874 		 * since we switch to a new TLB ctx instead.
8875 		 * Also, there is no need to flush if the process
8876 		 * is exiting since the TSB will be freed later.
8877 		 */
8878 		if (!sfmmup->sfmmu_free) {
8879 			hatlockp = sfmmu_hat_enter(sfmmup);
8880 			for (tsbinfo = sfmmup->sfmmu_tsb; tsbinfo != NULL;
8881 			    tsbinfo = tsbinfo->tsb_next) {
8882 				if (tsbinfo->tsb_flags & TSB_SWAPPED)
8883 					continue;
8884 				if (tsbinfo->tsb_flags & TSB_RELOC_FLAG) {
8885 					tsbinfo->tsb_flags |=
8886 					    TSB_FLUSH_NEEDED;
8887 					continue;
8888 				}
8889 
8890 				sfmmu_inv_tsb(tsbinfo->tsb_va,
8891 				    TSB_BYTES(tsbinfo->tsb_szc));
8892 			}
8893 			sfmmu_hat_exit(hatlockp);
8894 		}
8895 	}
8896 
8897 	/*
8898 	 * Update our counters for this sfmmup's ism mappings.
8899 	 */
8900 	for (i = 0; i <= ismszc; i++) {
8901 		if (!(disable_ism_large_pages & (1 << i)))
8902 			(void) ism_tsb_entries(sfmmup, i);
8903 	}
8904 
8905 	sfmmu_ismhat_exit(sfmmup, 0);
8906 
8907 	/*
8908 	 * We must do our freeing here after dropping locks
8909 	 * to prevent a deadlock in the kmem allocator on the
8910 	 * mapping list lock.
8911 	 */
8912 	if (free_ment != NULL)
8913 		kmem_cache_free(ism_ment_cache, free_ment);
8914 
8915 	/*
8916 	 * Check TSB and TLB page sizes if the process isn't exiting.
8917 	 */
8918 	if (!sfmmup->sfmmu_free) {
8919 		if (found && old_scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
8920 			sfmmu_check_page_sizes(sfmmup, 1);
8921 		} else {
8922 			sfmmu_check_page_sizes(sfmmup, 0);
8923 		}
8924 	}
8925 }
8926 
8927 /* ARGSUSED */
8928 static int
8929 sfmmu_idcache_constructor(void *buf, void *cdrarg, int kmflags)
8930 {
8931 	/* void *buf is sfmmu_t pointer */
8932 	bzero(buf, sizeof (sfmmu_t));
8933 
8934 	return (0);
8935 }
8936 
8937 /* ARGSUSED */
8938 static void
8939 sfmmu_idcache_destructor(void *buf, void *cdrarg)
8940 {
8941 	/* void *buf is sfmmu_t pointer */
8942 }
8943 
8944 /*
8945  * setup kmem hmeblks by bzeroing all members and initializing the nextpa
8946  * field to be the pa of this hmeblk
8947  */
8948 /* ARGSUSED */
8949 static int
8950 sfmmu_hblkcache_constructor(void *buf, void *cdrarg, int kmflags)
8951 {
8952 	struct hme_blk *hmeblkp;
8953 
8954 	bzero(buf, (size_t)cdrarg);
8955 	hmeblkp = (struct hme_blk *)buf;
8956 	hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
8957 
8958 #ifdef	HBLK_TRACE
8959 	mutex_init(&hmeblkp->hblk_audit_lock, NULL, MUTEX_DEFAULT, NULL);
8960 #endif	/* HBLK_TRACE */
8961 
8962 	return (0);
8963 }
8964 
8965 /* ARGSUSED */
8966 static void
8967 sfmmu_hblkcache_destructor(void *buf, void *cdrarg)
8968 {
8969 
8970 #ifdef	HBLK_TRACE
8971 
8972 	struct hme_blk *hmeblkp;
8973 
8974 	hmeblkp = (struct hme_blk *)buf;
8975 	mutex_destroy(&hmeblkp->hblk_audit_lock);
8976 
8977 #endif	/* HBLK_TRACE */
8978 }
8979 
8980 #define	SFMMU_CACHE_RECLAIM_SCAN_RATIO 8
8981 static int sfmmu_cache_reclaim_scan_ratio = SFMMU_CACHE_RECLAIM_SCAN_RATIO;
8982 /*
8983  * The kmem allocator will callback into our reclaim routine when the system
8984  * is running low in memory.  We traverse the hash and free up all unused but
8985  * still cached hme_blks.  We also traverse the free list and free them up
8986  * as well.
8987  */
8988 /*ARGSUSED*/
8989 static void
8990 sfmmu_hblkcache_reclaim(void *cdrarg)
8991 {
8992 	int i;
8993 	uint64_t hblkpa, prevpa, nx_pa;
8994 	struct hmehash_bucket *hmebp;
8995 	struct hme_blk *hmeblkp, *nx_hblk, *pr_hblk = NULL;
8996 	static struct hmehash_bucket *uhmehash_reclaim_hand;
8997 	static struct hmehash_bucket *khmehash_reclaim_hand;
8998 	struct hme_blk *list = NULL;
8999 
9000 	hmebp = uhmehash_reclaim_hand;
9001 	if (hmebp == NULL || hmebp > &uhme_hash[UHMEHASH_SZ])
9002 		uhmehash_reclaim_hand = hmebp = uhme_hash;
9003 	uhmehash_reclaim_hand += UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9004 
9005 	for (i = UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9006 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9007 			hmeblkp = hmebp->hmeblkp;
9008 			hblkpa = hmebp->hmeh_nextpa;
9009 			prevpa = 0;
9010 			pr_hblk = NULL;
9011 			while (hmeblkp) {
9012 				nx_hblk = hmeblkp->hblk_next;
9013 				nx_pa = hmeblkp->hblk_nextpa;
9014 				if (!hmeblkp->hblk_vcnt &&
9015 				    !hmeblkp->hblk_hmecnt) {
9016 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9017 					    prevpa, pr_hblk);
9018 					sfmmu_hblk_free(hmebp, hmeblkp,
9019 					    hblkpa, &list);
9020 				} else {
9021 					pr_hblk = hmeblkp;
9022 					prevpa = hblkpa;
9023 				}
9024 				hmeblkp = nx_hblk;
9025 				hblkpa = nx_pa;
9026 			}
9027 			SFMMU_HASH_UNLOCK(hmebp);
9028 		}
9029 		if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
9030 			hmebp = uhme_hash;
9031 	}
9032 
9033 	hmebp = khmehash_reclaim_hand;
9034 	if (hmebp == NULL || hmebp > &khme_hash[KHMEHASH_SZ])
9035 		khmehash_reclaim_hand = hmebp = khme_hash;
9036 	khmehash_reclaim_hand += KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9037 
9038 	for (i = KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9039 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9040 			hmeblkp = hmebp->hmeblkp;
9041 			hblkpa = hmebp->hmeh_nextpa;
9042 			prevpa = 0;
9043 			pr_hblk = NULL;
9044 			while (hmeblkp) {
9045 				nx_hblk = hmeblkp->hblk_next;
9046 				nx_pa = hmeblkp->hblk_nextpa;
9047 				if (!hmeblkp->hblk_vcnt &&
9048 				    !hmeblkp->hblk_hmecnt) {
9049 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9050 					    prevpa, pr_hblk);
9051 					sfmmu_hblk_free(hmebp, hmeblkp,
9052 					    hblkpa, &list);
9053 				} else {
9054 					pr_hblk = hmeblkp;
9055 					prevpa = hblkpa;
9056 				}
9057 				hmeblkp = nx_hblk;
9058 				hblkpa = nx_pa;
9059 			}
9060 			SFMMU_HASH_UNLOCK(hmebp);
9061 		}
9062 		if (hmebp++ == &khme_hash[KHMEHASH_SZ])
9063 			hmebp = khme_hash;
9064 	}
9065 	sfmmu_hblks_list_purge(&list);
9066 }
9067 
9068 /*
9069  * sfmmu_get_ppvcolor should become a vm_machdep or hatop interface.
9070  * same goes for sfmmu_get_addrvcolor().
9071  *
9072  * This function will return the virtual color for the specified page. The
9073  * virtual color corresponds to this page current mapping or its last mapping.
9074  * It is used by memory allocators to choose addresses with the correct
9075  * alignment so vac consistency is automatically maintained.  If the page
9076  * has no color it returns -1.
9077  */
9078 /*ARGSUSED*/
9079 int
9080 sfmmu_get_ppvcolor(struct page *pp)
9081 {
9082 #ifdef VAC
9083 	int color;
9084 
9085 	if (!(cache & CACHE_VAC) || PP_NEWPAGE(pp)) {
9086 		return (-1);
9087 	}
9088 	color = PP_GET_VCOLOR(pp);
9089 	ASSERT(color < mmu_btop(shm_alignment));
9090 	return (color);
9091 #else
9092 	return (-1);
9093 #endif	/* VAC */
9094 }
9095 
9096 /*
9097  * This function will return the desired alignment for vac consistency
9098  * (vac color) given a virtual address.  If no vac is present it returns -1.
9099  */
9100 /*ARGSUSED*/
9101 int
9102 sfmmu_get_addrvcolor(caddr_t vaddr)
9103 {
9104 #ifdef VAC
9105 	if (cache & CACHE_VAC) {
9106 		return (addr_to_vcolor(vaddr));
9107 	} else {
9108 		return (-1);
9109 	}
9110 #else
9111 	return (-1);
9112 #endif	/* VAC */
9113 }
9114 
9115 #ifdef VAC
9116 /*
9117  * Check for conflicts.
9118  * A conflict exists if the new and existent mappings do not match in
9119  * their "shm_alignment fields. If conflicts exist, the existant mappings
9120  * are flushed unless one of them is locked. If one of them is locked, then
9121  * the mappings are flushed and converted to non-cacheable mappings.
9122  */
9123 static void
9124 sfmmu_vac_conflict(struct hat *hat, caddr_t addr, page_t *pp)
9125 {
9126 	struct hat *tmphat;
9127 	struct sf_hment *sfhmep, *tmphme = NULL;
9128 	struct hme_blk *hmeblkp;
9129 	int vcolor;
9130 	tte_t tte;
9131 
9132 	ASSERT(sfmmu_mlist_held(pp));
9133 	ASSERT(!PP_ISNC(pp));		/* page better be cacheable */
9134 
9135 	vcolor = addr_to_vcolor(addr);
9136 	if (PP_NEWPAGE(pp)) {
9137 		PP_SET_VCOLOR(pp, vcolor);
9138 		return;
9139 	}
9140 
9141 	if (PP_GET_VCOLOR(pp) == vcolor) {
9142 		return;
9143 	}
9144 
9145 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
9146 		/*
9147 		 * Previous user of page had a different color
9148 		 * but since there are no current users
9149 		 * we just flush the cache and change the color.
9150 		 */
9151 		SFMMU_STAT(sf_pgcolor_conflict);
9152 		sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9153 		PP_SET_VCOLOR(pp, vcolor);
9154 		return;
9155 	}
9156 
9157 	/*
9158 	 * If we get here we have a vac conflict with a current
9159 	 * mapping.  VAC conflict policy is as follows.
9160 	 * - The default is to unload the other mappings unless:
9161 	 * - If we have a large mapping we uncache the page.
9162 	 * We need to uncache the rest of the large page too.
9163 	 * - If any of the mappings are locked we uncache the page.
9164 	 * - If the requested mapping is inconsistent
9165 	 * with another mapping and that mapping
9166 	 * is in the same address space we have to
9167 	 * make it non-cached.  The default thing
9168 	 * to do is unload the inconsistent mapping
9169 	 * but if they are in the same address space
9170 	 * we run the risk of unmapping the pc or the
9171 	 * stack which we will use as we return to the user,
9172 	 * in which case we can then fault on the thing
9173 	 * we just unloaded and get into an infinite loop.
9174 	 */
9175 	if (PP_ISMAPPED_LARGE(pp)) {
9176 		int sz;
9177 
9178 		/*
9179 		 * Existing mapping is for big pages. We don't unload
9180 		 * existing big mappings to satisfy new mappings.
9181 		 * Always convert all mappings to TNC.
9182 		 */
9183 		sz = fnd_mapping_sz(pp);
9184 		pp = PP_GROUPLEADER(pp, sz);
9185 		SFMMU_STAT_ADD(sf_uncache_conflict, TTEPAGES(sz));
9186 		sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH,
9187 		    TTEPAGES(sz));
9188 
9189 		return;
9190 	}
9191 
9192 	/*
9193 	 * check if any mapping is in same as or if it is locked
9194 	 * since in that case we need to uncache.
9195 	 */
9196 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9197 		tmphme = sfhmep->hme_next;
9198 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9199 		if (hmeblkp->hblk_xhat_bit)
9200 			continue;
9201 		tmphat = hblktosfmmu(hmeblkp);
9202 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
9203 		ASSERT(TTE_IS_VALID(&tte));
9204 		if (hmeblkp->hblk_shared || tmphat == hat ||
9205 		    hmeblkp->hblk_lckcnt) {
9206 			/*
9207 			 * We have an uncache conflict
9208 			 */
9209 			SFMMU_STAT(sf_uncache_conflict);
9210 			sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH, 1);
9211 			return;
9212 		}
9213 	}
9214 
9215 	/*
9216 	 * We have an unload conflict
9217 	 * We have already checked for LARGE mappings, therefore
9218 	 * the remaining mapping(s) must be TTE8K.
9219 	 */
9220 	SFMMU_STAT(sf_unload_conflict);
9221 
9222 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9223 		tmphme = sfhmep->hme_next;
9224 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9225 		if (hmeblkp->hblk_xhat_bit)
9226 			continue;
9227 		ASSERT(!hmeblkp->hblk_shared);
9228 		(void) sfmmu_pageunload(pp, sfhmep, TTE8K);
9229 	}
9230 
9231 	if (PP_ISMAPPED_KPM(pp))
9232 		sfmmu_kpm_vac_unload(pp, addr);
9233 
9234 	/*
9235 	 * Unloads only do TLB flushes so we need to flush the
9236 	 * cache here.
9237 	 */
9238 	sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9239 	PP_SET_VCOLOR(pp, vcolor);
9240 }
9241 
9242 /*
9243  * Whenever a mapping is unloaded and the page is in TNC state,
9244  * we see if the page can be made cacheable again. 'pp' is
9245  * the page that we just unloaded a mapping from, the size
9246  * of mapping that was unloaded is 'ottesz'.
9247  * Remark:
9248  * The recache policy for mpss pages can leave a performance problem
9249  * under the following circumstances:
9250  * . A large page in uncached mode has just been unmapped.
9251  * . All constituent pages are TNC due to a conflicting small mapping.
9252  * . There are many other, non conflicting, small mappings around for
9253  *   a lot of the constituent pages.
9254  * . We're called w/ the "old" groupleader page and the old ottesz,
9255  *   but this is irrelevant, since we're no more "PP_ISMAPPED_LARGE", so
9256  *   we end up w/ TTE8K or npages == 1.
9257  * . We call tst_tnc w/ the old groupleader only, and if there is no
9258  *   conflict, we re-cache only this page.
9259  * . All other small mappings are not checked and will be left in TNC mode.
9260  * The problem is not very serious because:
9261  * . mpss is actually only defined for heap and stack, so the probability
9262  *   is not very high that a large page mapping exists in parallel to a small
9263  *   one (this is possible, but seems to be bad programming style in the
9264  *   appl).
9265  * . The problem gets a little bit more serious, when those TNC pages
9266  *   have to be mapped into kernel space, e.g. for networking.
9267  * . When VAC alias conflicts occur in applications, this is regarded
9268  *   as an application bug. So if kstat's show them, the appl should
9269  *   be changed anyway.
9270  */
9271 void
9272 conv_tnc(page_t *pp, int ottesz)
9273 {
9274 	int cursz, dosz;
9275 	pgcnt_t curnpgs, dopgs;
9276 	pgcnt_t pg64k;
9277 	page_t *pp2;
9278 
9279 	/*
9280 	 * Determine how big a range we check for TNC and find
9281 	 * leader page. cursz is the size of the biggest
9282 	 * mapping that still exist on 'pp'.
9283 	 */
9284 	if (PP_ISMAPPED_LARGE(pp)) {
9285 		cursz = fnd_mapping_sz(pp);
9286 	} else {
9287 		cursz = TTE8K;
9288 	}
9289 
9290 	if (ottesz >= cursz) {
9291 		dosz = ottesz;
9292 		pp2 = pp;
9293 	} else {
9294 		dosz = cursz;
9295 		pp2 = PP_GROUPLEADER(pp, dosz);
9296 	}
9297 
9298 	pg64k = TTEPAGES(TTE64K);
9299 	dopgs = TTEPAGES(dosz);
9300 
9301 	ASSERT(dopgs == 1 || ((dopgs & (pg64k - 1)) == 0));
9302 
9303 	while (dopgs != 0) {
9304 		curnpgs = TTEPAGES(cursz);
9305 		if (tst_tnc(pp2, curnpgs)) {
9306 			SFMMU_STAT_ADD(sf_recache, curnpgs);
9307 			sfmmu_page_cache_array(pp2, HAT_CACHE, CACHE_NO_FLUSH,
9308 			    curnpgs);
9309 		}
9310 
9311 		ASSERT(dopgs >= curnpgs);
9312 		dopgs -= curnpgs;
9313 
9314 		if (dopgs == 0) {
9315 			break;
9316 		}
9317 
9318 		pp2 = PP_PAGENEXT_N(pp2, curnpgs);
9319 		if (((dopgs & (pg64k - 1)) == 0) && PP_ISMAPPED_LARGE(pp2)) {
9320 			cursz = fnd_mapping_sz(pp2);
9321 		} else {
9322 			cursz = TTE8K;
9323 		}
9324 	}
9325 }
9326 
9327 /*
9328  * Returns 1 if page(s) can be converted from TNC to cacheable setting,
9329  * returns 0 otherwise. Note that oaddr argument is valid for only
9330  * 8k pages.
9331  */
9332 int
9333 tst_tnc(page_t *pp, pgcnt_t npages)
9334 {
9335 	struct	sf_hment *sfhme;
9336 	struct	hme_blk *hmeblkp;
9337 	tte_t	tte;
9338 	caddr_t	vaddr;
9339 	int	clr_valid = 0;
9340 	int 	color, color1, bcolor;
9341 	int	i, ncolors;
9342 
9343 	ASSERT(pp != NULL);
9344 	ASSERT(!(cache & CACHE_WRITEBACK));
9345 
9346 	if (npages > 1) {
9347 		ncolors = CACHE_NUM_COLOR;
9348 	}
9349 
9350 	for (i = 0; i < npages; i++) {
9351 		ASSERT(sfmmu_mlist_held(pp));
9352 		ASSERT(PP_ISTNC(pp));
9353 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
9354 
9355 		if (PP_ISPNC(pp)) {
9356 			return (0);
9357 		}
9358 
9359 		clr_valid = 0;
9360 		if (PP_ISMAPPED_KPM(pp)) {
9361 			caddr_t kpmvaddr;
9362 
9363 			ASSERT(kpm_enable);
9364 			kpmvaddr = hat_kpm_page2va(pp, 1);
9365 			ASSERT(!(npages > 1 && IS_KPM_ALIAS_RANGE(kpmvaddr)));
9366 			color1 = addr_to_vcolor(kpmvaddr);
9367 			clr_valid = 1;
9368 		}
9369 
9370 		for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9371 			hmeblkp = sfmmu_hmetohblk(sfhme);
9372 			if (hmeblkp->hblk_xhat_bit)
9373 				continue;
9374 
9375 			sfmmu_copytte(&sfhme->hme_tte, &tte);
9376 			ASSERT(TTE_IS_VALID(&tte));
9377 
9378 			vaddr = tte_to_vaddr(hmeblkp, tte);
9379 			color = addr_to_vcolor(vaddr);
9380 
9381 			if (npages > 1) {
9382 				/*
9383 				 * If there is a big mapping, make sure
9384 				 * 8K mapping is consistent with the big
9385 				 * mapping.
9386 				 */
9387 				bcolor = i % ncolors;
9388 				if (color != bcolor) {
9389 					return (0);
9390 				}
9391 			}
9392 			if (!clr_valid) {
9393 				clr_valid = 1;
9394 				color1 = color;
9395 			}
9396 
9397 			if (color1 != color) {
9398 				return (0);
9399 			}
9400 		}
9401 
9402 		pp = PP_PAGENEXT(pp);
9403 	}
9404 
9405 	return (1);
9406 }
9407 
9408 void
9409 sfmmu_page_cache_array(page_t *pp, int flags, int cache_flush_flag,
9410 	pgcnt_t npages)
9411 {
9412 	kmutex_t *pmtx;
9413 	int i, ncolors, bcolor;
9414 	kpm_hlk_t *kpmp;
9415 	cpuset_t cpuset;
9416 
9417 	ASSERT(pp != NULL);
9418 	ASSERT(!(cache & CACHE_WRITEBACK));
9419 
9420 	kpmp = sfmmu_kpm_kpmp_enter(pp, npages);
9421 	pmtx = sfmmu_page_enter(pp);
9422 
9423 	/*
9424 	 * Fast path caching single unmapped page
9425 	 */
9426 	if (npages == 1 && !PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp) &&
9427 	    flags == HAT_CACHE) {
9428 		PP_CLRTNC(pp);
9429 		PP_CLRPNC(pp);
9430 		sfmmu_page_exit(pmtx);
9431 		sfmmu_kpm_kpmp_exit(kpmp);
9432 		return;
9433 	}
9434 
9435 	/*
9436 	 * We need to capture all cpus in order to change cacheability
9437 	 * because we can't allow one cpu to access the same physical
9438 	 * page using a cacheable and a non-cachebale mapping at the same
9439 	 * time. Since we may end up walking the ism mapping list
9440 	 * have to grab it's lock now since we can't after all the
9441 	 * cpus have been captured.
9442 	 */
9443 	sfmmu_hat_lock_all();
9444 	mutex_enter(&ism_mlist_lock);
9445 	kpreempt_disable();
9446 	cpuset = cpu_ready_set;
9447 	xc_attention(cpuset);
9448 
9449 	if (npages > 1) {
9450 		/*
9451 		 * Make sure all colors are flushed since the
9452 		 * sfmmu_page_cache() only flushes one color-
9453 		 * it does not know big pages.
9454 		 */
9455 		ncolors = CACHE_NUM_COLOR;
9456 		if (flags & HAT_TMPNC) {
9457 			for (i = 0; i < ncolors; i++) {
9458 				sfmmu_cache_flushcolor(i, pp->p_pagenum);
9459 			}
9460 			cache_flush_flag = CACHE_NO_FLUSH;
9461 		}
9462 	}
9463 
9464 	for (i = 0; i < npages; i++) {
9465 
9466 		ASSERT(sfmmu_mlist_held(pp));
9467 
9468 		if (!(flags == HAT_TMPNC && PP_ISTNC(pp))) {
9469 
9470 			if (npages > 1) {
9471 				bcolor = i % ncolors;
9472 			} else {
9473 				bcolor = NO_VCOLOR;
9474 			}
9475 
9476 			sfmmu_page_cache(pp, flags, cache_flush_flag,
9477 			    bcolor);
9478 		}
9479 
9480 		pp = PP_PAGENEXT(pp);
9481 	}
9482 
9483 	xt_sync(cpuset);
9484 	xc_dismissed(cpuset);
9485 	mutex_exit(&ism_mlist_lock);
9486 	sfmmu_hat_unlock_all();
9487 	sfmmu_page_exit(pmtx);
9488 	sfmmu_kpm_kpmp_exit(kpmp);
9489 	kpreempt_enable();
9490 }
9491 
9492 /*
9493  * This function changes the virtual cacheability of all mappings to a
9494  * particular page.  When changing from uncache to cacheable the mappings will
9495  * only be changed if all of them have the same virtual color.
9496  * We need to flush the cache in all cpus.  It is possible that
9497  * a process referenced a page as cacheable but has sinced exited
9498  * and cleared the mapping list.  We still to flush it but have no
9499  * state so all cpus is the only alternative.
9500  */
9501 static void
9502 sfmmu_page_cache(page_t *pp, int flags, int cache_flush_flag, int bcolor)
9503 {
9504 	struct	sf_hment *sfhme;
9505 	struct	hme_blk *hmeblkp;
9506 	sfmmu_t *sfmmup;
9507 	tte_t	tte, ttemod;
9508 	caddr_t	vaddr;
9509 	int	ret, color;
9510 	pfn_t	pfn;
9511 
9512 	color = bcolor;
9513 	pfn = pp->p_pagenum;
9514 
9515 	for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9516 
9517 		hmeblkp = sfmmu_hmetohblk(sfhme);
9518 
9519 		if (hmeblkp->hblk_xhat_bit)
9520 			continue;
9521 
9522 		sfmmu_copytte(&sfhme->hme_tte, &tte);
9523 		ASSERT(TTE_IS_VALID(&tte));
9524 		vaddr = tte_to_vaddr(hmeblkp, tte);
9525 		color = addr_to_vcolor(vaddr);
9526 
9527 #ifdef DEBUG
9528 		if ((flags & HAT_CACHE) && bcolor != NO_VCOLOR) {
9529 			ASSERT(color == bcolor);
9530 		}
9531 #endif
9532 
9533 		ASSERT(flags != HAT_TMPNC || color == PP_GET_VCOLOR(pp));
9534 
9535 		ttemod = tte;
9536 		if (flags & (HAT_UNCACHE | HAT_TMPNC)) {
9537 			TTE_CLR_VCACHEABLE(&ttemod);
9538 		} else {	/* flags & HAT_CACHE */
9539 			TTE_SET_VCACHEABLE(&ttemod);
9540 		}
9541 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
9542 		if (ret < 0) {
9543 			/*
9544 			 * Since all cpus are captured modifytte should not
9545 			 * fail.
9546 			 */
9547 			panic("sfmmu_page_cache: write to tte failed");
9548 		}
9549 
9550 		sfmmup = hblktosfmmu(hmeblkp);
9551 		if (cache_flush_flag == CACHE_FLUSH) {
9552 			/*
9553 			 * Flush TSBs, TLBs and caches
9554 			 */
9555 			if (hmeblkp->hblk_shared) {
9556 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9557 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9558 				sf_region_t *rgnp;
9559 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9560 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9561 				ASSERT(srdp != NULL);
9562 				rgnp = srdp->srd_hmergnp[rid];
9563 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9564 				    srdp, rgnp, rid);
9565 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9566 				    hmeblkp, 0);
9567 				sfmmu_cache_flush(pfn, addr_to_vcolor(vaddr));
9568 			} else if (sfmmup->sfmmu_ismhat) {
9569 				if (flags & HAT_CACHE) {
9570 					SFMMU_STAT(sf_ism_recache);
9571 				} else {
9572 					SFMMU_STAT(sf_ism_uncache);
9573 				}
9574 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9575 				    pfn, CACHE_FLUSH);
9576 			} else {
9577 				sfmmu_tlbcache_demap(vaddr, sfmmup, hmeblkp,
9578 				    pfn, 0, FLUSH_ALL_CPUS, CACHE_FLUSH, 1);
9579 			}
9580 
9581 			/*
9582 			 * all cache entries belonging to this pfn are
9583 			 * now flushed.
9584 			 */
9585 			cache_flush_flag = CACHE_NO_FLUSH;
9586 		} else {
9587 			/*
9588 			 * Flush only TSBs and TLBs.
9589 			 */
9590 			if (hmeblkp->hblk_shared) {
9591 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9592 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9593 				sf_region_t *rgnp;
9594 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9595 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9596 				ASSERT(srdp != NULL);
9597 				rgnp = srdp->srd_hmergnp[rid];
9598 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9599 				    srdp, rgnp, rid);
9600 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9601 				    hmeblkp, 0);
9602 			} else if (sfmmup->sfmmu_ismhat) {
9603 				if (flags & HAT_CACHE) {
9604 					SFMMU_STAT(sf_ism_recache);
9605 				} else {
9606 					SFMMU_STAT(sf_ism_uncache);
9607 				}
9608 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9609 				    pfn, CACHE_NO_FLUSH);
9610 			} else {
9611 				sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 1);
9612 			}
9613 		}
9614 	}
9615 
9616 	if (PP_ISMAPPED_KPM(pp))
9617 		sfmmu_kpm_page_cache(pp, flags, cache_flush_flag);
9618 
9619 	switch (flags) {
9620 
9621 		default:
9622 			panic("sfmmu_pagecache: unknown flags");
9623 			break;
9624 
9625 		case HAT_CACHE:
9626 			PP_CLRTNC(pp);
9627 			PP_CLRPNC(pp);
9628 			PP_SET_VCOLOR(pp, color);
9629 			break;
9630 
9631 		case HAT_TMPNC:
9632 			PP_SETTNC(pp);
9633 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9634 			break;
9635 
9636 		case HAT_UNCACHE:
9637 			PP_SETPNC(pp);
9638 			PP_CLRTNC(pp);
9639 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9640 			break;
9641 	}
9642 }
9643 #endif	/* VAC */
9644 
9645 
9646 /*
9647  * Wrapper routine used to return a context.
9648  *
9649  * It's the responsibility of the caller to guarantee that the
9650  * process serializes on calls here by taking the HAT lock for
9651  * the hat.
9652  *
9653  */
9654 static void
9655 sfmmu_get_ctx(sfmmu_t *sfmmup)
9656 {
9657 	mmu_ctx_t *mmu_ctxp;
9658 	uint_t pstate_save;
9659 #ifdef sun4v
9660 	int ret;
9661 #endif
9662 
9663 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9664 	ASSERT(sfmmup != ksfmmup);
9665 
9666 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID)) {
9667 		sfmmu_setup_tsbinfo(sfmmup);
9668 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ALLCTX_INVALID);
9669 	}
9670 
9671 	kpreempt_disable();
9672 
9673 	mmu_ctxp = CPU_MMU_CTXP(CPU);
9674 	ASSERT(mmu_ctxp);
9675 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
9676 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
9677 
9678 	/*
9679 	 * Do a wrap-around if cnum reaches the max # cnum supported by a MMU.
9680 	 */
9681 	if (mmu_ctxp->mmu_cnum == mmu_ctxp->mmu_nctxs)
9682 		sfmmu_ctx_wrap_around(mmu_ctxp);
9683 
9684 	/*
9685 	 * Let the MMU set up the page sizes to use for
9686 	 * this context in the TLB. Don't program 2nd dtlb for ism hat.
9687 	 */
9688 	if ((&mmu_set_ctx_page_sizes) && (sfmmup->sfmmu_ismhat == 0)) {
9689 		mmu_set_ctx_page_sizes(sfmmup);
9690 	}
9691 
9692 	/*
9693 	 * sfmmu_alloc_ctx and sfmmu_load_mmustate will be performed with
9694 	 * interrupts disabled to prevent race condition with wrap-around
9695 	 * ctx invalidatation. In sun4v, ctx invalidation also involves
9696 	 * a HV call to set the number of TSBs to 0. If interrupts are not
9697 	 * disabled until after sfmmu_load_mmustate is complete TSBs may
9698 	 * become assigned to INVALID_CONTEXT. This is not allowed.
9699 	 */
9700 	pstate_save = sfmmu_disable_intrs();
9701 
9702 #ifdef sun4u
9703 	(void) sfmmu_alloc_ctx(sfmmup, 1, CPU, SFMMU_PRIVATE);
9704 #else
9705 	if (sfmmu_alloc_ctx(sfmmup, 1, CPU, SFMMU_PRIVATE) &&
9706 	    sfmmup->sfmmu_scdp != NULL) {
9707 		sf_scd_t *scdp = sfmmup->sfmmu_scdp;
9708 		sfmmu_t *scsfmmup = scdp->scd_sfmmup;
9709 		ret = sfmmu_alloc_ctx(scsfmmup, 1, CPU, SFMMU_SHARED);
9710 		/* debug purpose only */
9711 		ASSERT(!ret || scsfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
9712 		    != INVALID_CONTEXT);
9713 	}
9714 #endif
9715 	sfmmu_load_mmustate(sfmmup);
9716 
9717 	sfmmu_enable_intrs(pstate_save);
9718 
9719 	kpreempt_enable();
9720 }
9721 
9722 /*
9723  * When all cnums are used up in a MMU, cnum will wrap around to the
9724  * next generation and start from 2.
9725  */
9726 static void
9727 sfmmu_ctx_wrap_around(mmu_ctx_t *mmu_ctxp)
9728 {
9729 
9730 	/* caller must have disabled the preemption */
9731 	ASSERT(curthread->t_preempt >= 1);
9732 	ASSERT(mmu_ctxp != NULL);
9733 
9734 	/* acquire Per-MMU (PM) spin lock */
9735 	mutex_enter(&mmu_ctxp->mmu_lock);
9736 
9737 	/* re-check to see if wrap-around is needed */
9738 	if (mmu_ctxp->mmu_cnum < mmu_ctxp->mmu_nctxs)
9739 		goto done;
9740 
9741 	SFMMU_MMU_STAT(mmu_wrap_around);
9742 
9743 	/* update gnum */
9744 	ASSERT(mmu_ctxp->mmu_gnum != 0);
9745 	mmu_ctxp->mmu_gnum++;
9746 	if (mmu_ctxp->mmu_gnum == 0 ||
9747 	    mmu_ctxp->mmu_gnum > MAX_SFMMU_GNUM_VAL) {
9748 		cmn_err(CE_PANIC, "mmu_gnum of mmu_ctx 0x%p is out of bound.",
9749 		    (void *)mmu_ctxp);
9750 	}
9751 
9752 	if (mmu_ctxp->mmu_ncpus > 1) {
9753 		cpuset_t cpuset;
9754 
9755 		membar_enter(); /* make sure updated gnum visible */
9756 
9757 		SFMMU_XCALL_STATS(NULL);
9758 
9759 		/* xcall to others on the same MMU to invalidate ctx */
9760 		cpuset = mmu_ctxp->mmu_cpuset;
9761 		ASSERT(CPU_IN_SET(cpuset, CPU->cpu_id));
9762 		CPUSET_DEL(cpuset, CPU->cpu_id);
9763 		CPUSET_AND(cpuset, cpu_ready_set);
9764 
9765 		/*
9766 		 * Pass in INVALID_CONTEXT as the first parameter to
9767 		 * sfmmu_raise_tsb_exception, which invalidates the context
9768 		 * of any process running on the CPUs in the MMU.
9769 		 */
9770 		xt_some(cpuset, sfmmu_raise_tsb_exception,
9771 		    INVALID_CONTEXT, INVALID_CONTEXT);
9772 		xt_sync(cpuset);
9773 
9774 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
9775 	}
9776 
9777 	if (sfmmu_getctx_sec() != INVALID_CONTEXT) {
9778 		sfmmu_setctx_sec(INVALID_CONTEXT);
9779 		sfmmu_clear_utsbinfo();
9780 	}
9781 
9782 	/*
9783 	 * No xcall is needed here. For sun4u systems all CPUs in context
9784 	 * domain share a single physical MMU therefore it's enough to flush
9785 	 * TLB on local CPU. On sun4v systems we use 1 global context
9786 	 * domain and flush all remote TLBs in sfmmu_raise_tsb_exception
9787 	 * handler. Note that vtag_flushall_uctxs() is called
9788 	 * for Ultra II machine, where the equivalent flushall functionality
9789 	 * is implemented in SW, and only user ctx TLB entries are flushed.
9790 	 */
9791 	if (&vtag_flushall_uctxs != NULL) {
9792 		vtag_flushall_uctxs();
9793 	} else {
9794 		vtag_flushall();
9795 	}
9796 
9797 	/* reset mmu cnum, skips cnum 0 and 1 */
9798 	mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
9799 
9800 done:
9801 	mutex_exit(&mmu_ctxp->mmu_lock);
9802 }
9803 
9804 
9805 /*
9806  * For multi-threaded process, set the process context to INVALID_CONTEXT
9807  * so that it faults and reloads the MMU state from TL=0. For single-threaded
9808  * process, we can just load the MMU state directly without having to
9809  * set context invalid. Caller must hold the hat lock since we don't
9810  * acquire it here.
9811  */
9812 static void
9813 sfmmu_sync_mmustate(sfmmu_t *sfmmup)
9814 {
9815 	uint_t cnum;
9816 	uint_t pstate_save;
9817 
9818 	ASSERT(sfmmup != ksfmmup);
9819 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9820 
9821 	kpreempt_disable();
9822 
9823 	/*
9824 	 * We check whether the pass'ed-in sfmmup is the same as the
9825 	 * current running proc. This is to makes sure the current proc
9826 	 * stays single-threaded if it already is.
9827 	 */
9828 	if ((sfmmup == curthread->t_procp->p_as->a_hat) &&
9829 	    (curthread->t_procp->p_lwpcnt == 1)) {
9830 		/* single-thread */
9831 		cnum = sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum;
9832 		if (cnum != INVALID_CONTEXT) {
9833 			uint_t curcnum;
9834 			/*
9835 			 * Disable interrupts to prevent race condition
9836 			 * with sfmmu_ctx_wrap_around ctx invalidation.
9837 			 * In sun4v, ctx invalidation involves setting
9838 			 * TSB to NULL, hence, interrupts should be disabled
9839 			 * untill after sfmmu_load_mmustate is completed.
9840 			 */
9841 			pstate_save = sfmmu_disable_intrs();
9842 			curcnum = sfmmu_getctx_sec();
9843 			if (curcnum == cnum)
9844 				sfmmu_load_mmustate(sfmmup);
9845 			sfmmu_enable_intrs(pstate_save);
9846 			ASSERT(curcnum == cnum || curcnum == INVALID_CONTEXT);
9847 		}
9848 	} else {
9849 		/*
9850 		 * multi-thread
9851 		 * or when sfmmup is not the same as the curproc.
9852 		 */
9853 		sfmmu_invalidate_ctx(sfmmup);
9854 	}
9855 
9856 	kpreempt_enable();
9857 }
9858 
9859 
9860 /*
9861  * Replace the specified TSB with a new TSB.  This function gets called when
9862  * we grow, shrink or swapin a TSB.  When swapping in a TSB (TSB_SWAPIN), the
9863  * TSB_FORCEALLOC flag may be used to force allocation of a minimum-sized TSB
9864  * (8K).
9865  *
9866  * Caller must hold the HAT lock, but should assume any tsb_info
9867  * pointers it has are no longer valid after calling this function.
9868  *
9869  * Return values:
9870  *	TSB_ALLOCFAIL	Failed to allocate a TSB, due to memory constraints
9871  *	TSB_LOSTRACE	HAT is busy, i.e. another thread is already doing
9872  *			something to this tsbinfo/TSB
9873  *	TSB_SUCCESS	Operation succeeded
9874  */
9875 static tsb_replace_rc_t
9876 sfmmu_replace_tsb(sfmmu_t *sfmmup, struct tsb_info *old_tsbinfo, uint_t szc,
9877     hatlock_t *hatlockp, uint_t flags)
9878 {
9879 	struct tsb_info *new_tsbinfo = NULL;
9880 	struct tsb_info *curtsb, *prevtsb;
9881 	uint_t tte_sz_mask;
9882 	int i;
9883 
9884 	ASSERT(sfmmup != ksfmmup);
9885 	ASSERT(sfmmup->sfmmu_ismhat == 0);
9886 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9887 	ASSERT(szc <= tsb_max_growsize);
9888 
9889 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_BUSY))
9890 		return (TSB_LOSTRACE);
9891 
9892 	/*
9893 	 * Find the tsb_info ahead of this one in the list, and
9894 	 * also make sure that the tsb_info passed in really
9895 	 * exists!
9896 	 */
9897 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9898 	    curtsb != old_tsbinfo && curtsb != NULL;
9899 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
9900 		;
9901 	ASSERT(curtsb != NULL);
9902 
9903 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9904 		/*
9905 		 * The process is swapped out, so just set the new size
9906 		 * code.  When it swaps back in, we'll allocate a new one
9907 		 * of the new chosen size.
9908 		 */
9909 		curtsb->tsb_szc = szc;
9910 		return (TSB_SUCCESS);
9911 	}
9912 	SFMMU_FLAGS_SET(sfmmup, HAT_BUSY);
9913 
9914 	tte_sz_mask = old_tsbinfo->tsb_ttesz_mask;
9915 
9916 	/*
9917 	 * All initialization is done inside of sfmmu_tsbinfo_alloc().
9918 	 * If we fail to allocate a TSB, exit.
9919 	 *
9920 	 * If tsb grows with new tsb size > 4M and old tsb size < 4M,
9921 	 * then try 4M slab after the initial alloc fails.
9922 	 *
9923 	 * If tsb swapin with tsb size > 4M, then try 4M after the
9924 	 * initial alloc fails.
9925 	 */
9926 	sfmmu_hat_exit(hatlockp);
9927 	if (sfmmu_tsbinfo_alloc(&new_tsbinfo, szc,
9928 	    tte_sz_mask, flags, sfmmup) &&
9929 	    (!(flags & (TSB_GROW | TSB_SWAPIN)) || (szc <= TSB_4M_SZCODE) ||
9930 	    (!(flags & TSB_SWAPIN) &&
9931 	    (old_tsbinfo->tsb_szc >= TSB_4M_SZCODE)) ||
9932 	    sfmmu_tsbinfo_alloc(&new_tsbinfo, TSB_4M_SZCODE,
9933 	    tte_sz_mask, flags, sfmmup))) {
9934 		(void) sfmmu_hat_enter(sfmmup);
9935 		if (!(flags & TSB_SWAPIN))
9936 			SFMMU_STAT(sf_tsb_resize_failures);
9937 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9938 		return (TSB_ALLOCFAIL);
9939 	}
9940 	(void) sfmmu_hat_enter(sfmmup);
9941 
9942 	/*
9943 	 * Re-check to make sure somebody else didn't muck with us while we
9944 	 * didn't hold the HAT lock.  If the process swapped out, fine, just
9945 	 * exit; this can happen if we try to shrink the TSB from the context
9946 	 * of another process (such as on an ISM unmap), though it is rare.
9947 	 */
9948 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9949 		SFMMU_STAT(sf_tsb_resize_failures);
9950 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9951 		sfmmu_hat_exit(hatlockp);
9952 		sfmmu_tsbinfo_free(new_tsbinfo);
9953 		(void) sfmmu_hat_enter(sfmmup);
9954 		return (TSB_LOSTRACE);
9955 	}
9956 
9957 #ifdef	DEBUG
9958 	/* Reverify that the tsb_info still exists.. for debugging only */
9959 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9960 	    curtsb != old_tsbinfo && curtsb != NULL;
9961 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
9962 		;
9963 	ASSERT(curtsb != NULL);
9964 #endif	/* DEBUG */
9965 
9966 	/*
9967 	 * Quiesce any CPUs running this process on their next TLB miss
9968 	 * so they atomically see the new tsb_info.  We temporarily set the
9969 	 * context to invalid context so new threads that come on processor
9970 	 * after we do the xcall to cpusran will also serialize behind the
9971 	 * HAT lock on TLB miss and will see the new TSB.  Since this short
9972 	 * race with a new thread coming on processor is relatively rare,
9973 	 * this synchronization mechanism should be cheaper than always
9974 	 * pausing all CPUs for the duration of the setup, which is what
9975 	 * the old implementation did.  This is particuarly true if we are
9976 	 * copying a huge chunk of memory around during that window.
9977 	 *
9978 	 * The memory barriers are to make sure things stay consistent
9979 	 * with resume() since it does not hold the HAT lock while
9980 	 * walking the list of tsb_info structures.
9981 	 */
9982 	if ((flags & TSB_SWAPIN) != TSB_SWAPIN) {
9983 		/* The TSB is either growing or shrinking. */
9984 		sfmmu_invalidate_ctx(sfmmup);
9985 	} else {
9986 		/*
9987 		 * It is illegal to swap in TSBs from a process other
9988 		 * than a process being swapped in.  This in turn
9989 		 * implies we do not have a valid MMU context here
9990 		 * since a process needs one to resolve translation
9991 		 * misses.
9992 		 */
9993 		ASSERT(curthread->t_procp->p_as->a_hat == sfmmup);
9994 	}
9995 
9996 #ifdef DEBUG
9997 	ASSERT(max_mmu_ctxdoms > 0);
9998 
9999 	/*
10000 	 * Process should have INVALID_CONTEXT on all MMUs
10001 	 */
10002 	for (i = 0; i < max_mmu_ctxdoms; i++) {
10003 
10004 		ASSERT(sfmmup->sfmmu_ctxs[i].cnum == INVALID_CONTEXT);
10005 	}
10006 #endif
10007 
10008 	new_tsbinfo->tsb_next = old_tsbinfo->tsb_next;
10009 	membar_stst();	/* strict ordering required */
10010 	if (prevtsb)
10011 		prevtsb->tsb_next = new_tsbinfo;
10012 	else
10013 		sfmmup->sfmmu_tsb = new_tsbinfo;
10014 	membar_enter();	/* make sure new TSB globally visible */
10015 
10016 	/*
10017 	 * We need to migrate TSB entries from the old TSB to the new TSB
10018 	 * if tsb_remap_ttes is set and the TSB is growing.
10019 	 */
10020 	if (tsb_remap_ttes && ((flags & TSB_GROW) == TSB_GROW))
10021 		sfmmu_copy_tsb(old_tsbinfo, new_tsbinfo);
10022 
10023 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
10024 
10025 	/*
10026 	 * Drop the HAT lock to free our old tsb_info.
10027 	 */
10028 	sfmmu_hat_exit(hatlockp);
10029 
10030 	if ((flags & TSB_GROW) == TSB_GROW) {
10031 		SFMMU_STAT(sf_tsb_grow);
10032 	} else if ((flags & TSB_SHRINK) == TSB_SHRINK) {
10033 		SFMMU_STAT(sf_tsb_shrink);
10034 	}
10035 
10036 	sfmmu_tsbinfo_free(old_tsbinfo);
10037 
10038 	(void) sfmmu_hat_enter(sfmmup);
10039 	return (TSB_SUCCESS);
10040 }
10041 
10042 /*
10043  * This function will re-program hat pgsz array, and invalidate the
10044  * process' context, forcing the process to switch to another
10045  * context on the next TLB miss, and therefore start using the
10046  * TLB that is reprogrammed for the new page sizes.
10047  */
10048 void
10049 sfmmu_reprog_pgsz_arr(sfmmu_t *sfmmup, uint8_t *tmp_pgsz)
10050 {
10051 	int i;
10052 	hatlock_t *hatlockp = NULL;
10053 
10054 	hatlockp = sfmmu_hat_enter(sfmmup);
10055 	/* USIII+-IV+ optimization, requires hat lock */
10056 	if (tmp_pgsz) {
10057 		for (i = 0; i < mmu_page_sizes; i++)
10058 			sfmmup->sfmmu_pgsz[i] = tmp_pgsz[i];
10059 	}
10060 	SFMMU_STAT(sf_tlb_reprog_pgsz);
10061 
10062 	sfmmu_invalidate_ctx(sfmmup);
10063 
10064 	sfmmu_hat_exit(hatlockp);
10065 }
10066 
10067 /* Update scd_rttecnt for shme rgns in the SCD */
10068 static void
10069 sfmmu_set_scd_rttecnt(sf_srd_t *srdp, sf_scd_t *scdp)
10070 {
10071 	uint_t rid;
10072 	uint_t i, j;
10073 	ulong_t w;
10074 	sf_region_t *rgnp;
10075 
10076 	ASSERT(srdp != NULL);
10077 
10078 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
10079 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
10080 			continue;
10081 		}
10082 
10083 		j = 0;
10084 		while (w) {
10085 			if (!(w & 0x1)) {
10086 				j++;
10087 				w >>= 1;
10088 				continue;
10089 			}
10090 			rid = (i << BT_ULSHIFT) | j;
10091 			j++;
10092 			w >>= 1;
10093 
10094 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
10095 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
10096 			rgnp = srdp->srd_hmergnp[rid];
10097 			ASSERT(rgnp->rgn_refcnt > 0);
10098 			ASSERT(rgnp->rgn_id == rid);
10099 
10100 			scdp->scd_rttecnt[rgnp->rgn_pgszc] +=
10101 			    rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
10102 
10103 			/*
10104 			 * Maintain the tsb0 inflation cnt for the regions
10105 			 * in the SCD.
10106 			 */
10107 			if (rgnp->rgn_pgszc >= TTE4M) {
10108 				scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt +=
10109 				    rgnp->rgn_size >>
10110 				    (TTE_PAGE_SHIFT(TTE8K) + 2);
10111 			}
10112 		}
10113 	}
10114 }
10115 
10116 /*
10117  * This function assumes that there are either four or six supported page
10118  * sizes and at most two programmable TLBs, so we need to decide which
10119  * page sizes are most important and then tell the MMU layer so it
10120  * can adjust the TLB page sizes accordingly (if supported).
10121  *
10122  * If these assumptions change, this function will need to be
10123  * updated to support whatever the new limits are.
10124  *
10125  * The growing flag is nonzero if we are growing the address space,
10126  * and zero if it is shrinking.  This allows us to decide whether
10127  * to grow or shrink our TSB, depending upon available memory
10128  * conditions.
10129  */
10130 static void
10131 sfmmu_check_page_sizes(sfmmu_t *sfmmup, int growing)
10132 {
10133 	uint64_t ttecnt[MMU_PAGE_SIZES];
10134 	uint64_t tte8k_cnt, tte4m_cnt;
10135 	uint8_t i;
10136 	int sectsb_thresh;
10137 
10138 	/*
10139 	 * Kernel threads, processes with small address spaces not using
10140 	 * large pages, and dummy ISM HATs need not apply.
10141 	 */
10142 	if (sfmmup == ksfmmup || sfmmup->sfmmu_ismhat != NULL)
10143 		return;
10144 
10145 	if (!SFMMU_LGPGS_INUSE(sfmmup) &&
10146 	    sfmmup->sfmmu_ttecnt[TTE8K] <= tsb_rss_factor)
10147 		return;
10148 
10149 	for (i = 0; i < mmu_page_sizes; i++) {
10150 		ttecnt[i] = sfmmup->sfmmu_ttecnt[i] +
10151 		    sfmmup->sfmmu_ismttecnt[i];
10152 	}
10153 
10154 	/* Check pagesizes in use, and possibly reprogram DTLB. */
10155 	if (&mmu_check_page_sizes)
10156 		mmu_check_page_sizes(sfmmup, ttecnt);
10157 
10158 	/*
10159 	 * Calculate the number of 8k ttes to represent the span of these
10160 	 * pages.
10161 	 */
10162 	tte8k_cnt = ttecnt[TTE8K] +
10163 	    (ttecnt[TTE64K] << (MMU_PAGESHIFT64K - MMU_PAGESHIFT)) +
10164 	    (ttecnt[TTE512K] << (MMU_PAGESHIFT512K - MMU_PAGESHIFT));
10165 	if (mmu_page_sizes == max_mmu_page_sizes) {
10166 		tte4m_cnt = ttecnt[TTE4M] +
10167 		    (ttecnt[TTE32M] << (MMU_PAGESHIFT32M - MMU_PAGESHIFT4M)) +
10168 		    (ttecnt[TTE256M] << (MMU_PAGESHIFT256M - MMU_PAGESHIFT4M));
10169 	} else {
10170 		tte4m_cnt = ttecnt[TTE4M];
10171 	}
10172 
10173 	/*
10174 	 * Inflate tte8k_cnt to allow for region large page allocation failure.
10175 	 */
10176 	tte8k_cnt += sfmmup->sfmmu_tsb0_4minflcnt;
10177 
10178 	/*
10179 	 * Inflate TSB sizes by a factor of 2 if this process
10180 	 * uses 4M text pages to minimize extra conflict misses
10181 	 * in the first TSB since without counting text pages
10182 	 * 8K TSB may become too small.
10183 	 *
10184 	 * Also double the size of the second TSB to minimize
10185 	 * extra conflict misses due to competition between 4M text pages
10186 	 * and data pages.
10187 	 *
10188 	 * We need to adjust the second TSB allocation threshold by the
10189 	 * inflation factor, since there is no point in creating a second
10190 	 * TSB when we know all the mappings can fit in the I/D TLBs.
10191 	 */
10192 	sectsb_thresh = tsb_sectsb_threshold;
10193 	if (sfmmup->sfmmu_flags & HAT_4MTEXT_FLAG) {
10194 		tte8k_cnt <<= 1;
10195 		tte4m_cnt <<= 1;
10196 		sectsb_thresh <<= 1;
10197 	}
10198 
10199 	/*
10200 	 * Check to see if our TSB is the right size; we may need to
10201 	 * grow or shrink it.  If the process is small, our work is
10202 	 * finished at this point.
10203 	 */
10204 	if (tte8k_cnt <= tsb_rss_factor && tte4m_cnt <= sectsb_thresh) {
10205 		return;
10206 	}
10207 	sfmmu_size_tsb(sfmmup, growing, tte8k_cnt, tte4m_cnt, sectsb_thresh);
10208 }
10209 
10210 static void
10211 sfmmu_size_tsb(sfmmu_t *sfmmup, int growing, uint64_t tte8k_cnt,
10212 	uint64_t tte4m_cnt, int sectsb_thresh)
10213 {
10214 	int tsb_bits;
10215 	uint_t tsb_szc;
10216 	struct tsb_info *tsbinfop;
10217 	hatlock_t *hatlockp = NULL;
10218 
10219 	hatlockp = sfmmu_hat_enter(sfmmup);
10220 	ASSERT(hatlockp != NULL);
10221 	tsbinfop = sfmmup->sfmmu_tsb;
10222 	ASSERT(tsbinfop != NULL);
10223 
10224 	/*
10225 	 * If we're growing, select the size based on RSS.  If we're
10226 	 * shrinking, leave some room so we don't have to turn around and
10227 	 * grow again immediately.
10228 	 */
10229 	if (growing)
10230 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
10231 	else
10232 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt << 1);
10233 
10234 	if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10235 	    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10236 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10237 		    hatlockp, TSB_SHRINK);
10238 	} else if (growing && tsb_szc > tsbinfop->tsb_szc && TSB_OK_GROW()) {
10239 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10240 		    hatlockp, TSB_GROW);
10241 	}
10242 	tsbinfop = sfmmup->sfmmu_tsb;
10243 
10244 	/*
10245 	 * With the TLB and first TSB out of the way, we need to see if
10246 	 * we need a second TSB for 4M pages.  If we managed to reprogram
10247 	 * the TLB page sizes above, the process will start using this new
10248 	 * TSB right away; otherwise, it will start using it on the next
10249 	 * context switch.  Either way, it's no big deal so there's no
10250 	 * synchronization with the trap handlers here unless we grow the
10251 	 * TSB (in which case it's required to prevent using the old one
10252 	 * after it's freed). Note: second tsb is required for 32M/256M
10253 	 * page sizes.
10254 	 */
10255 	if (tte4m_cnt > sectsb_thresh) {
10256 		/*
10257 		 * If we're growing, select the size based on RSS.  If we're
10258 		 * shrinking, leave some room so we don't have to turn
10259 		 * around and grow again immediately.
10260 		 */
10261 		if (growing)
10262 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
10263 		else
10264 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt << 1);
10265 		if (tsbinfop->tsb_next == NULL) {
10266 			struct tsb_info *newtsb;
10267 			int allocflags = SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)?
10268 			    0 : TSB_ALLOC;
10269 
10270 			sfmmu_hat_exit(hatlockp);
10271 
10272 			/*
10273 			 * Try to allocate a TSB for 4[32|256]M pages.  If we
10274 			 * can't get the size we want, retry w/a minimum sized
10275 			 * TSB.  If that still didn't work, give up; we can
10276 			 * still run without one.
10277 			 */
10278 			tsb_bits = (mmu_page_sizes == max_mmu_page_sizes)?
10279 			    TSB4M|TSB32M|TSB256M:TSB4M;
10280 			if ((sfmmu_tsbinfo_alloc(&newtsb, tsb_szc, tsb_bits,
10281 			    allocflags, sfmmup)) &&
10282 			    (tsb_szc <= TSB_4M_SZCODE ||
10283 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
10284 			    tsb_bits, allocflags, sfmmup)) &&
10285 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_MIN_SZCODE,
10286 			    tsb_bits, allocflags, sfmmup)) {
10287 				return;
10288 			}
10289 
10290 			hatlockp = sfmmu_hat_enter(sfmmup);
10291 
10292 			sfmmu_invalidate_ctx(sfmmup);
10293 
10294 			if (sfmmup->sfmmu_tsb->tsb_next == NULL) {
10295 				sfmmup->sfmmu_tsb->tsb_next = newtsb;
10296 				SFMMU_STAT(sf_tsb_sectsb_create);
10297 				sfmmu_hat_exit(hatlockp);
10298 				return;
10299 			} else {
10300 				/*
10301 				 * It's annoying, but possible for us
10302 				 * to get here.. we dropped the HAT lock
10303 				 * because of locking order in the kmem
10304 				 * allocator, and while we were off getting
10305 				 * our memory, some other thread decided to
10306 				 * do us a favor and won the race to get a
10307 				 * second TSB for this process.  Sigh.
10308 				 */
10309 				sfmmu_hat_exit(hatlockp);
10310 				sfmmu_tsbinfo_free(newtsb);
10311 				return;
10312 			}
10313 		}
10314 
10315 		/*
10316 		 * We have a second TSB, see if it's big enough.
10317 		 */
10318 		tsbinfop = tsbinfop->tsb_next;
10319 
10320 		/*
10321 		 * Check to see if our second TSB is the right size;
10322 		 * we may need to grow or shrink it.
10323 		 * To prevent thrashing (e.g. growing the TSB on a
10324 		 * subsequent map operation), only try to shrink if
10325 		 * the TSB reach exceeds twice the virtual address
10326 		 * space size.
10327 		 */
10328 		if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10329 		    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10330 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10331 			    tsb_szc, hatlockp, TSB_SHRINK);
10332 		} else if (growing && tsb_szc > tsbinfop->tsb_szc &&
10333 		    TSB_OK_GROW()) {
10334 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10335 			    tsb_szc, hatlockp, TSB_GROW);
10336 		}
10337 	}
10338 
10339 	sfmmu_hat_exit(hatlockp);
10340 }
10341 
10342 /*
10343  * Free up a sfmmu
10344  * Since the sfmmu is currently embedded in the hat struct we simply zero
10345  * out our fields and free up the ism map blk list if any.
10346  */
10347 static void
10348 sfmmu_free_sfmmu(sfmmu_t *sfmmup)
10349 {
10350 	ism_blk_t	*blkp, *nx_blkp;
10351 #ifdef	DEBUG
10352 	ism_map_t	*map;
10353 	int 		i;
10354 #endif
10355 
10356 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
10357 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
10358 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
10359 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
10360 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
10361 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
10362 	ASSERT(SF_RGNMAP_ISNULL(sfmmup));
10363 
10364 	sfmmup->sfmmu_free = 0;
10365 	sfmmup->sfmmu_ismhat = 0;
10366 
10367 	blkp = sfmmup->sfmmu_iblk;
10368 	sfmmup->sfmmu_iblk = NULL;
10369 
10370 	while (blkp) {
10371 #ifdef	DEBUG
10372 		map = blkp->iblk_maps;
10373 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
10374 			ASSERT(map[i].imap_seg == 0);
10375 			ASSERT(map[i].imap_ismhat == NULL);
10376 			ASSERT(map[i].imap_ment == NULL);
10377 		}
10378 #endif
10379 		nx_blkp = blkp->iblk_next;
10380 		blkp->iblk_next = NULL;
10381 		blkp->iblk_nextpa = (uint64_t)-1;
10382 		kmem_cache_free(ism_blk_cache, blkp);
10383 		blkp = nx_blkp;
10384 	}
10385 }
10386 
10387 /*
10388  * Locking primitves accessed by HATLOCK macros
10389  */
10390 
10391 #define	SFMMU_SPL_MTX	(0x0)
10392 #define	SFMMU_ML_MTX	(0x1)
10393 
10394 #define	SFMMU_MLSPL_MTX(type, pg)	(((type) == SFMMU_SPL_MTX) ? \
10395 					    SPL_HASH(pg) : MLIST_HASH(pg))
10396 
10397 kmutex_t *
10398 sfmmu_page_enter(struct page *pp)
10399 {
10400 	return (sfmmu_mlspl_enter(pp, SFMMU_SPL_MTX));
10401 }
10402 
10403 void
10404 sfmmu_page_exit(kmutex_t *spl)
10405 {
10406 	mutex_exit(spl);
10407 }
10408 
10409 int
10410 sfmmu_page_spl_held(struct page *pp)
10411 {
10412 	return (sfmmu_mlspl_held(pp, SFMMU_SPL_MTX));
10413 }
10414 
10415 kmutex_t *
10416 sfmmu_mlist_enter(struct page *pp)
10417 {
10418 	return (sfmmu_mlspl_enter(pp, SFMMU_ML_MTX));
10419 }
10420 
10421 void
10422 sfmmu_mlist_exit(kmutex_t *mml)
10423 {
10424 	mutex_exit(mml);
10425 }
10426 
10427 int
10428 sfmmu_mlist_held(struct page *pp)
10429 {
10430 
10431 	return (sfmmu_mlspl_held(pp, SFMMU_ML_MTX));
10432 }
10433 
10434 /*
10435  * Common code for sfmmu_mlist_enter() and sfmmu_page_enter().  For
10436  * sfmmu_mlist_enter() case mml_table lock array is used and for
10437  * sfmmu_page_enter() sfmmu_page_lock lock array is used.
10438  *
10439  * The lock is taken on a root page so that it protects an operation on all
10440  * constituent pages of a large page pp belongs to.
10441  *
10442  * The routine takes a lock from the appropriate array. The lock is determined
10443  * by hashing the root page. After taking the lock this routine checks if the
10444  * root page has the same size code that was used to determine the root (i.e
10445  * that root hasn't changed).  If root page has the expected p_szc field we
10446  * have the right lock and it's returned to the caller. If root's p_szc
10447  * decreased we release the lock and retry from the beginning.  This case can
10448  * happen due to hat_page_demote() decreasing p_szc between our load of p_szc
10449  * value and taking the lock. The number of retries due to p_szc decrease is
10450  * limited by the maximum p_szc value. If p_szc is 0 we return the lock
10451  * determined by hashing pp itself.
10452  *
10453  * If our caller doesn't hold a SE_SHARED or SE_EXCL lock on pp it's also
10454  * possible that p_szc can increase. To increase p_szc a thread has to lock
10455  * all constituent pages EXCL and do hat_pageunload() on all of them. All the
10456  * callers that don't hold a page locked recheck if hmeblk through which pp
10457  * was found still maps this pp.  If it doesn't map it anymore returned lock
10458  * is immediately dropped. Therefore if sfmmu_mlspl_enter() hits the case of
10459  * p_szc increase after taking the lock it returns this lock without further
10460  * retries because in this case the caller doesn't care about which lock was
10461  * taken. The caller will drop it right away.
10462  *
10463  * After the routine returns it's guaranteed that hat_page_demote() can't
10464  * change p_szc field of any of constituent pages of a large page pp belongs
10465  * to as long as pp was either locked at least SHARED prior to this call or
10466  * the caller finds that hment that pointed to this pp still references this
10467  * pp (this also assumes that the caller holds hme hash bucket lock so that
10468  * the same pp can't be remapped into the same hmeblk after it was unmapped by
10469  * hat_pageunload()).
10470  */
10471 static kmutex_t *
10472 sfmmu_mlspl_enter(struct page *pp, int type)
10473 {
10474 	kmutex_t	*mtx;
10475 	uint_t		prev_rszc = UINT_MAX;
10476 	page_t		*rootpp;
10477 	uint_t		szc;
10478 	uint_t		rszc;
10479 	uint_t		pszc = pp->p_szc;
10480 
10481 	ASSERT(pp != NULL);
10482 
10483 again:
10484 	if (pszc == 0) {
10485 		mtx = SFMMU_MLSPL_MTX(type, pp);
10486 		mutex_enter(mtx);
10487 		return (mtx);
10488 	}
10489 
10490 	/* The lock lives in the root page */
10491 	rootpp = PP_GROUPLEADER(pp, pszc);
10492 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10493 	mutex_enter(mtx);
10494 
10495 	/*
10496 	 * Return mml in the following 3 cases:
10497 	 *
10498 	 * 1) If pp itself is root since if its p_szc decreased before we took
10499 	 * the lock pp is still the root of smaller szc page. And if its p_szc
10500 	 * increased it doesn't matter what lock we return (see comment in
10501 	 * front of this routine).
10502 	 *
10503 	 * 2) If pp's not root but rootpp is the root of a rootpp->p_szc size
10504 	 * large page we have the right lock since any previous potential
10505 	 * hat_page_demote() is done demoting from greater than current root's
10506 	 * p_szc because hat_page_demote() changes root's p_szc last. No
10507 	 * further hat_page_demote() can start or be in progress since it
10508 	 * would need the same lock we currently hold.
10509 	 *
10510 	 * 3) If rootpp's p_szc increased since previous iteration it doesn't
10511 	 * matter what lock we return (see comment in front of this routine).
10512 	 */
10513 	if (pp == rootpp || (rszc = rootpp->p_szc) == pszc ||
10514 	    rszc >= prev_rszc) {
10515 		return (mtx);
10516 	}
10517 
10518 	/*
10519 	 * hat_page_demote() could have decreased root's p_szc.
10520 	 * In this case pp's p_szc must also be smaller than pszc.
10521 	 * Retry.
10522 	 */
10523 	if (rszc < pszc) {
10524 		szc = pp->p_szc;
10525 		if (szc < pszc) {
10526 			mutex_exit(mtx);
10527 			pszc = szc;
10528 			goto again;
10529 		}
10530 		/*
10531 		 * pp's p_szc increased after it was decreased.
10532 		 * page cannot be mapped. Return current lock. The caller
10533 		 * will drop it right away.
10534 		 */
10535 		return (mtx);
10536 	}
10537 
10538 	/*
10539 	 * root's p_szc is greater than pp's p_szc.
10540 	 * hat_page_demote() is not done with all pages
10541 	 * yet. Wait for it to complete.
10542 	 */
10543 	mutex_exit(mtx);
10544 	rootpp = PP_GROUPLEADER(rootpp, rszc);
10545 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10546 	mutex_enter(mtx);
10547 	mutex_exit(mtx);
10548 	prev_rszc = rszc;
10549 	goto again;
10550 }
10551 
10552 static int
10553 sfmmu_mlspl_held(struct page *pp, int type)
10554 {
10555 	kmutex_t	*mtx;
10556 
10557 	ASSERT(pp != NULL);
10558 	/* The lock lives in the root page */
10559 	pp = PP_PAGEROOT(pp);
10560 	ASSERT(pp != NULL);
10561 
10562 	mtx = SFMMU_MLSPL_MTX(type, pp);
10563 	return (MUTEX_HELD(mtx));
10564 }
10565 
10566 static uint_t
10567 sfmmu_get_free_hblk(struct hme_blk **hmeblkpp, uint_t critical)
10568 {
10569 	struct  hme_blk *hblkp;
10570 
10571 	if (freehblkp != NULL) {
10572 		mutex_enter(&freehblkp_lock);
10573 		if (freehblkp != NULL) {
10574 			/*
10575 			 * If the current thread is owning hblk_reserve OR
10576 			 * critical request from sfmmu_hblk_steal()
10577 			 * let it succeed even if freehblkcnt is really low.
10578 			 */
10579 			if (freehblkcnt <= HBLK_RESERVE_MIN && !critical) {
10580 				SFMMU_STAT(sf_get_free_throttle);
10581 				mutex_exit(&freehblkp_lock);
10582 				return (0);
10583 			}
10584 			freehblkcnt--;
10585 			*hmeblkpp = freehblkp;
10586 			hblkp = *hmeblkpp;
10587 			freehblkp = hblkp->hblk_next;
10588 			mutex_exit(&freehblkp_lock);
10589 			hblkp->hblk_next = NULL;
10590 			SFMMU_STAT(sf_get_free_success);
10591 			return (1);
10592 		}
10593 		mutex_exit(&freehblkp_lock);
10594 	}
10595 	SFMMU_STAT(sf_get_free_fail);
10596 	return (0);
10597 }
10598 
10599 static uint_t
10600 sfmmu_put_free_hblk(struct hme_blk *hmeblkp, uint_t critical)
10601 {
10602 	struct  hme_blk *hblkp;
10603 
10604 	/*
10605 	 * If the current thread is mapping into kernel space,
10606 	 * let it succede even if freehblkcnt is max
10607 	 * so that it will avoid freeing it to kmem.
10608 	 * This will prevent stack overflow due to
10609 	 * possible recursion since kmem_cache_free()
10610 	 * might require creation of a slab which
10611 	 * in turn needs an hmeblk to map that slab;
10612 	 * let's break this vicious chain at the first
10613 	 * opportunity.
10614 	 */
10615 	if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10616 		mutex_enter(&freehblkp_lock);
10617 		if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10618 			SFMMU_STAT(sf_put_free_success);
10619 			freehblkcnt++;
10620 			hmeblkp->hblk_next = freehblkp;
10621 			freehblkp = hmeblkp;
10622 			mutex_exit(&freehblkp_lock);
10623 			return (1);
10624 		}
10625 		mutex_exit(&freehblkp_lock);
10626 	}
10627 
10628 	/*
10629 	 * Bring down freehblkcnt to HBLK_RESERVE_CNT. We are here
10630 	 * only if freehblkcnt is at least HBLK_RESERVE_CNT *and*
10631 	 * we are not in the process of mapping into kernel space.
10632 	 */
10633 	ASSERT(!critical);
10634 	while (freehblkcnt > HBLK_RESERVE_CNT) {
10635 		mutex_enter(&freehblkp_lock);
10636 		if (freehblkcnt > HBLK_RESERVE_CNT) {
10637 			freehblkcnt--;
10638 			hblkp = freehblkp;
10639 			freehblkp = hblkp->hblk_next;
10640 			mutex_exit(&freehblkp_lock);
10641 			ASSERT(get_hblk_cache(hblkp) == sfmmu8_cache);
10642 			kmem_cache_free(sfmmu8_cache, hblkp);
10643 			continue;
10644 		}
10645 		mutex_exit(&freehblkp_lock);
10646 	}
10647 	SFMMU_STAT(sf_put_free_fail);
10648 	return (0);
10649 }
10650 
10651 static void
10652 sfmmu_hblk_swap(struct hme_blk *new)
10653 {
10654 	struct hme_blk *old, *hblkp, *prev;
10655 	uint64_t hblkpa, prevpa, newpa;
10656 	caddr_t	base, vaddr, endaddr;
10657 	struct hmehash_bucket *hmebp;
10658 	struct sf_hment *osfhme, *nsfhme;
10659 	page_t *pp;
10660 	kmutex_t *pml;
10661 	tte_t tte;
10662 
10663 #ifdef	DEBUG
10664 	hmeblk_tag		hblktag;
10665 	struct hme_blk		*found;
10666 #endif
10667 	old = HBLK_RESERVE;
10668 	ASSERT(!old->hblk_shared);
10669 
10670 	/*
10671 	 * save pa before bcopy clobbers it
10672 	 */
10673 	newpa = new->hblk_nextpa;
10674 
10675 	base = (caddr_t)get_hblk_base(old);
10676 	endaddr = base + get_hblk_span(old);
10677 
10678 	/*
10679 	 * acquire hash bucket lock.
10680 	 */
10681 	hmebp = sfmmu_tteload_acquire_hashbucket(ksfmmup, base, TTE8K,
10682 	    SFMMU_INVALID_SHMERID);
10683 
10684 	/*
10685 	 * copy contents from old to new
10686 	 */
10687 	bcopy((void *)old, (void *)new, HME8BLK_SZ);
10688 
10689 	/*
10690 	 * add new to hash chain
10691 	 */
10692 	sfmmu_hblk_hash_add(hmebp, new, newpa);
10693 
10694 	/*
10695 	 * search hash chain for hblk_reserve; this needs to be performed
10696 	 * after adding new, otherwise prevpa and prev won't correspond
10697 	 * to the hblk which is prior to old in hash chain when we call
10698 	 * sfmmu_hblk_hash_rm to remove old later.
10699 	 */
10700 	for (prevpa = 0, prev = NULL,
10701 	    hblkpa = hmebp->hmeh_nextpa, hblkp = hmebp->hmeblkp;
10702 	    hblkp != NULL && hblkp != old;
10703 	    prevpa = hblkpa, prev = hblkp,
10704 	    hblkpa = hblkp->hblk_nextpa, hblkp = hblkp->hblk_next)
10705 		;
10706 
10707 	if (hblkp != old)
10708 		panic("sfmmu_hblk_swap: hblk_reserve not found");
10709 
10710 	/*
10711 	 * p_mapping list is still pointing to hments in hblk_reserve;
10712 	 * fix up p_mapping list so that they point to hments in new.
10713 	 *
10714 	 * Since all these mappings are created by hblk_reserve_thread
10715 	 * on the way and it's using at least one of the buffers from each of
10716 	 * the newly minted slabs, there is no danger of any of these
10717 	 * mappings getting unloaded by another thread.
10718 	 *
10719 	 * tsbmiss could only modify ref/mod bits of hments in old/new.
10720 	 * Since all of these hments hold mappings established by segkmem
10721 	 * and mappings in segkmem are setup with HAT_NOSYNC, ref/mod bits
10722 	 * have no meaning for the mappings in hblk_reserve.  hments in
10723 	 * old and new are identical except for ref/mod bits.
10724 	 */
10725 	for (vaddr = base; vaddr < endaddr; vaddr += TTEBYTES(TTE8K)) {
10726 
10727 		HBLKTOHME(osfhme, old, vaddr);
10728 		sfmmu_copytte(&osfhme->hme_tte, &tte);
10729 
10730 		if (TTE_IS_VALID(&tte)) {
10731 			if ((pp = osfhme->hme_page) == NULL)
10732 				panic("sfmmu_hblk_swap: page not mapped");
10733 
10734 			pml = sfmmu_mlist_enter(pp);
10735 
10736 			if (pp != osfhme->hme_page)
10737 				panic("sfmmu_hblk_swap: mapping changed");
10738 
10739 			HBLKTOHME(nsfhme, new, vaddr);
10740 
10741 			HME_ADD(nsfhme, pp);
10742 			HME_SUB(osfhme, pp);
10743 
10744 			sfmmu_mlist_exit(pml);
10745 		}
10746 	}
10747 
10748 	/*
10749 	 * remove old from hash chain
10750 	 */
10751 	sfmmu_hblk_hash_rm(hmebp, old, prevpa, prev);
10752 
10753 #ifdef	DEBUG
10754 
10755 	hblktag.htag_id = ksfmmup;
10756 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
10757 	hblktag.htag_bspage = HME_HASH_BSPAGE(base, HME_HASH_SHIFT(TTE8K));
10758 	hblktag.htag_rehash = HME_HASH_REHASH(TTE8K);
10759 	HME_HASH_FAST_SEARCH(hmebp, hblktag, found);
10760 
10761 	if (found != new)
10762 		panic("sfmmu_hblk_swap: new hblk not found");
10763 #endif
10764 
10765 	SFMMU_HASH_UNLOCK(hmebp);
10766 
10767 	/*
10768 	 * Reset hblk_reserve
10769 	 */
10770 	bzero((void *)old, HME8BLK_SZ);
10771 	old->hblk_nextpa = va_to_pa((caddr_t)old);
10772 }
10773 
10774 /*
10775  * Grab the mlist mutex for both pages passed in.
10776  *
10777  * low and high will be returned as pointers to the mutexes for these pages.
10778  * low refers to the mutex residing in the lower bin of the mlist hash, while
10779  * high refers to the mutex residing in the higher bin of the mlist hash.  This
10780  * is due to the locking order restrictions on the same thread grabbing
10781  * multiple mlist mutexes.  The low lock must be acquired before the high lock.
10782  *
10783  * If both pages hash to the same mutex, only grab that single mutex, and
10784  * high will be returned as NULL
10785  * If the pages hash to different bins in the hash, grab the lower addressed
10786  * lock first and then the higher addressed lock in order to follow the locking
10787  * rules involved with the same thread grabbing multiple mlist mutexes.
10788  * low and high will both have non-NULL values.
10789  */
10790 static void
10791 sfmmu_mlist_reloc_enter(struct page *targ, struct page *repl,
10792     kmutex_t **low, kmutex_t **high)
10793 {
10794 	kmutex_t	*mml_targ, *mml_repl;
10795 
10796 	/*
10797 	 * no need to do the dance around szc as in sfmmu_mlist_enter()
10798 	 * because this routine is only called by hat_page_relocate() and all
10799 	 * targ and repl pages are already locked EXCL so szc can't change.
10800 	 */
10801 
10802 	mml_targ = MLIST_HASH(PP_PAGEROOT(targ));
10803 	mml_repl = MLIST_HASH(PP_PAGEROOT(repl));
10804 
10805 	if (mml_targ == mml_repl) {
10806 		*low = mml_targ;
10807 		*high = NULL;
10808 	} else {
10809 		if (mml_targ < mml_repl) {
10810 			*low = mml_targ;
10811 			*high = mml_repl;
10812 		} else {
10813 			*low = mml_repl;
10814 			*high = mml_targ;
10815 		}
10816 	}
10817 
10818 	mutex_enter(*low);
10819 	if (*high)
10820 		mutex_enter(*high);
10821 }
10822 
10823 static void
10824 sfmmu_mlist_reloc_exit(kmutex_t *low, kmutex_t *high)
10825 {
10826 	if (high)
10827 		mutex_exit(high);
10828 	mutex_exit(low);
10829 }
10830 
10831 static hatlock_t *
10832 sfmmu_hat_enter(sfmmu_t *sfmmup)
10833 {
10834 	hatlock_t	*hatlockp;
10835 
10836 	if (sfmmup != ksfmmup) {
10837 		hatlockp = TSB_HASH(sfmmup);
10838 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
10839 		return (hatlockp);
10840 	}
10841 	return (NULL);
10842 }
10843 
10844 static hatlock_t *
10845 sfmmu_hat_tryenter(sfmmu_t *sfmmup)
10846 {
10847 	hatlock_t	*hatlockp;
10848 
10849 	if (sfmmup != ksfmmup) {
10850 		hatlockp = TSB_HASH(sfmmup);
10851 		if (mutex_tryenter(HATLOCK_MUTEXP(hatlockp)) == 0)
10852 			return (NULL);
10853 		return (hatlockp);
10854 	}
10855 	return (NULL);
10856 }
10857 
10858 static void
10859 sfmmu_hat_exit(hatlock_t *hatlockp)
10860 {
10861 	if (hatlockp != NULL)
10862 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
10863 }
10864 
10865 static void
10866 sfmmu_hat_lock_all(void)
10867 {
10868 	int i;
10869 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
10870 		mutex_enter(HATLOCK_MUTEXP(&hat_lock[i]));
10871 }
10872 
10873 static void
10874 sfmmu_hat_unlock_all(void)
10875 {
10876 	int i;
10877 	for (i = SFMMU_NUM_LOCK - 1; i >= 0; i--)
10878 		mutex_exit(HATLOCK_MUTEXP(&hat_lock[i]));
10879 }
10880 
10881 int
10882 sfmmu_hat_lock_held(sfmmu_t *sfmmup)
10883 {
10884 	ASSERT(sfmmup != ksfmmup);
10885 	return (MUTEX_HELD(HATLOCK_MUTEXP(TSB_HASH(sfmmup))));
10886 }
10887 
10888 /*
10889  * Locking primitives to provide consistency between ISM unmap
10890  * and other operations.  Since ISM unmap can take a long time, we
10891  * use HAT_ISMBUSY flag (protected by the hatlock) to avoid creating
10892  * contention on the hatlock buckets while ISM segments are being
10893  * unmapped.  The tradeoff is that the flags don't prevent priority
10894  * inversion from occurring, so we must request kernel priority in
10895  * case we have to sleep to keep from getting buried while holding
10896  * the HAT_ISMBUSY flag set, which in turn could block other kernel
10897  * threads from running (for example, in sfmmu_uvatopfn()).
10898  */
10899 static void
10900 sfmmu_ismhat_enter(sfmmu_t *sfmmup, int hatlock_held)
10901 {
10902 	hatlock_t *hatlockp;
10903 
10904 	THREAD_KPRI_REQUEST();
10905 	if (!hatlock_held)
10906 		hatlockp = sfmmu_hat_enter(sfmmup);
10907 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY))
10908 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
10909 	SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
10910 	if (!hatlock_held)
10911 		sfmmu_hat_exit(hatlockp);
10912 }
10913 
10914 static void
10915 sfmmu_ismhat_exit(sfmmu_t *sfmmup, int hatlock_held)
10916 {
10917 	hatlock_t *hatlockp;
10918 
10919 	if (!hatlock_held)
10920 		hatlockp = sfmmu_hat_enter(sfmmup);
10921 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
10922 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
10923 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
10924 	if (!hatlock_held)
10925 		sfmmu_hat_exit(hatlockp);
10926 	THREAD_KPRI_RELEASE();
10927 }
10928 
10929 /*
10930  *
10931  * Algorithm:
10932  *
10933  * (1) if segkmem is not ready, allocate hblk from an array of pre-alloc'ed
10934  *	hblks.
10935  *
10936  * (2) if we are allocating an hblk for mapping a slab in sfmmu_cache,
10937  *
10938  * 		(a) try to return an hblk from reserve pool of free hblks;
10939  *		(b) if the reserve pool is empty, acquire hblk_reserve_lock
10940  *		    and return hblk_reserve.
10941  *
10942  * (3) call kmem_cache_alloc() to allocate hblk;
10943  *
10944  *		(a) if hblk_reserve_lock is held by the current thread,
10945  *		    atomically replace hblk_reserve by the hblk that is
10946  *		    returned by kmem_cache_alloc; release hblk_reserve_lock
10947  *		    and call kmem_cache_alloc() again.
10948  *		(b) if reserve pool is not full, add the hblk that is
10949  *		    returned by kmem_cache_alloc to reserve pool and
10950  *		    call kmem_cache_alloc again.
10951  *
10952  */
10953 static struct hme_blk *
10954 sfmmu_hblk_alloc(sfmmu_t *sfmmup, caddr_t vaddr,
10955 	struct hmehash_bucket *hmebp, uint_t size, hmeblk_tag hblktag,
10956 	uint_t flags, uint_t rid)
10957 {
10958 	struct hme_blk *hmeblkp = NULL;
10959 	struct hme_blk *newhblkp;
10960 	struct hme_blk *shw_hblkp = NULL;
10961 	struct kmem_cache *sfmmu_cache = NULL;
10962 	uint64_t hblkpa;
10963 	ulong_t index;
10964 	uint_t owner;		/* set to 1 if using hblk_reserve */
10965 	uint_t forcefree;
10966 	int sleep;
10967 	sf_srd_t *srdp;
10968 	sf_region_t *rgnp;
10969 
10970 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
10971 	ASSERT(hblktag.htag_rid == rid);
10972 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
10973 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
10974 	    IS_P2ALIGNED(vaddr, TTEBYTES(size)));
10975 
10976 	/*
10977 	 * If segkmem is not created yet, allocate from static hmeblks
10978 	 * created at the end of startup_modules().  See the block comment
10979 	 * in startup_modules() describing how we estimate the number of
10980 	 * static hmeblks that will be needed during re-map.
10981 	 */
10982 	if (!hblk_alloc_dynamic) {
10983 
10984 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
10985 
10986 		if (size == TTE8K) {
10987 			index = nucleus_hblk8.index;
10988 			if (index >= nucleus_hblk8.len) {
10989 				/*
10990 				 * If we panic here, see startup_modules() to
10991 				 * make sure that we are calculating the
10992 				 * number of hblk8's that we need correctly.
10993 				 */
10994 				prom_panic("no nucleus hblk8 to allocate");
10995 			}
10996 			hmeblkp =
10997 			    (struct hme_blk *)&nucleus_hblk8.list[index];
10998 			nucleus_hblk8.index++;
10999 			SFMMU_STAT(sf_hblk8_nalloc);
11000 		} else {
11001 			index = nucleus_hblk1.index;
11002 			if (nucleus_hblk1.index >= nucleus_hblk1.len) {
11003 				/*
11004 				 * If we panic here, see startup_modules().
11005 				 * Most likely you need to update the
11006 				 * calculation of the number of hblk1 elements
11007 				 * that the kernel needs to boot.
11008 				 */
11009 				prom_panic("no nucleus hblk1 to allocate");
11010 			}
11011 			hmeblkp =
11012 			    (struct hme_blk *)&nucleus_hblk1.list[index];
11013 			nucleus_hblk1.index++;
11014 			SFMMU_STAT(sf_hblk1_nalloc);
11015 		}
11016 
11017 		goto hblk_init;
11018 	}
11019 
11020 	SFMMU_HASH_UNLOCK(hmebp);
11021 
11022 	if (sfmmup != KHATID && !SFMMU_IS_SHMERID_VALID(rid)) {
11023 		if (mmu_page_sizes == max_mmu_page_sizes) {
11024 			if (size < TTE256M)
11025 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11026 				    size, flags);
11027 		} else {
11028 			if (size < TTE4M)
11029 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11030 				    size, flags);
11031 		}
11032 	} else if (SFMMU_IS_SHMERID_VALID(rid)) {
11033 		int ttesz;
11034 		caddr_t va;
11035 		caddr_t	eva = vaddr + TTEBYTES(size);
11036 
11037 		ASSERT(sfmmup != KHATID);
11038 
11039 		srdp = sfmmup->sfmmu_srdp;
11040 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11041 		rgnp = srdp->srd_hmergnp[rid];
11042 		ASSERT(rgnp != NULL && rgnp->rgn_id == rid);
11043 		ASSERT(rgnp->rgn_refcnt != 0);
11044 		ASSERT(size <= rgnp->rgn_pgszc);
11045 
11046 		ttesz = HBLK_MIN_TTESZ;
11047 		do {
11048 			if (!(rgnp->rgn_hmeflags & (0x1 << ttesz))) {
11049 				continue;
11050 			}
11051 
11052 			if (ttesz > size && ttesz != HBLK_MIN_TTESZ) {
11053 				sfmmu_cleanup_rhblk(srdp, vaddr, rid, ttesz);
11054 			} else if (ttesz < size) {
11055 				for (va = vaddr; va < eva;
11056 				    va += TTEBYTES(ttesz)) {
11057 					sfmmu_cleanup_rhblk(srdp, va, rid,
11058 					    ttesz);
11059 				}
11060 			}
11061 		} while (++ttesz <= rgnp->rgn_pgszc);
11062 	}
11063 
11064 fill_hblk:
11065 	owner = (hblk_reserve_thread == curthread) ? 1 : 0;
11066 
11067 	if (owner && size == TTE8K) {
11068 
11069 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11070 		/*
11071 		 * We are really in a tight spot. We already own
11072 		 * hblk_reserve and we need another hblk.  In anticipation
11073 		 * of this kind of scenario, we specifically set aside
11074 		 * HBLK_RESERVE_MIN number of hblks to be used exclusively
11075 		 * by owner of hblk_reserve.
11076 		 */
11077 		SFMMU_STAT(sf_hblk_recurse_cnt);
11078 
11079 		if (!sfmmu_get_free_hblk(&hmeblkp, 1))
11080 			panic("sfmmu_hblk_alloc: reserve list is empty");
11081 
11082 		goto hblk_verify;
11083 	}
11084 
11085 	ASSERT(!owner);
11086 
11087 	if ((flags & HAT_NO_KALLOC) == 0) {
11088 
11089 		sfmmu_cache = ((size == TTE8K) ? sfmmu8_cache : sfmmu1_cache);
11090 		sleep = ((sfmmup == KHATID) ? KM_NOSLEEP : KM_SLEEP);
11091 
11092 		if ((hmeblkp = kmem_cache_alloc(sfmmu_cache, sleep)) == NULL) {
11093 			hmeblkp = sfmmu_hblk_steal(size);
11094 		} else {
11095 			/*
11096 			 * if we are the owner of hblk_reserve,
11097 			 * swap hblk_reserve with hmeblkp and
11098 			 * start a fresh life.  Hope things go
11099 			 * better this time.
11100 			 */
11101 			if (hblk_reserve_thread == curthread) {
11102 				ASSERT(sfmmu_cache == sfmmu8_cache);
11103 				sfmmu_hblk_swap(hmeblkp);
11104 				hblk_reserve_thread = NULL;
11105 				mutex_exit(&hblk_reserve_lock);
11106 				goto fill_hblk;
11107 			}
11108 			/*
11109 			 * let's donate this hblk to our reserve list if
11110 			 * we are not mapping kernel range
11111 			 */
11112 			if (size == TTE8K && sfmmup != KHATID)
11113 				if (sfmmu_put_free_hblk(hmeblkp, 0))
11114 					goto fill_hblk;
11115 		}
11116 	} else {
11117 		/*
11118 		 * We are here to map the slab in sfmmu8_cache; let's
11119 		 * check if we could tap our reserve list; if successful,
11120 		 * this will avoid the pain of going thru sfmmu_hblk_swap
11121 		 */
11122 		SFMMU_STAT(sf_hblk_slab_cnt);
11123 		if (!sfmmu_get_free_hblk(&hmeblkp, 0)) {
11124 			/*
11125 			 * let's start hblk_reserve dance
11126 			 */
11127 			SFMMU_STAT(sf_hblk_reserve_cnt);
11128 			owner = 1;
11129 			mutex_enter(&hblk_reserve_lock);
11130 			hmeblkp = HBLK_RESERVE;
11131 			hblk_reserve_thread = curthread;
11132 		}
11133 	}
11134 
11135 hblk_verify:
11136 	ASSERT(hmeblkp != NULL);
11137 	set_hblk_sz(hmeblkp, size);
11138 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
11139 	SFMMU_HASH_LOCK(hmebp);
11140 	HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11141 	if (newhblkp != NULL) {
11142 		SFMMU_HASH_UNLOCK(hmebp);
11143 		if (hmeblkp != HBLK_RESERVE) {
11144 			/*
11145 			 * This is really tricky!
11146 			 *
11147 			 * vmem_alloc(vmem_seg_arena)
11148 			 *  vmem_alloc(vmem_internal_arena)
11149 			 *   segkmem_alloc(heap_arena)
11150 			 *    vmem_alloc(heap_arena)
11151 			 *    page_create()
11152 			 *    hat_memload()
11153 			 *	kmem_cache_free()
11154 			 *	 kmem_cache_alloc()
11155 			 *	  kmem_slab_create()
11156 			 *	   vmem_alloc(kmem_internal_arena)
11157 			 *	    segkmem_alloc(heap_arena)
11158 			 *		vmem_alloc(heap_arena)
11159 			 *		page_create()
11160 			 *		hat_memload()
11161 			 *		  kmem_cache_free()
11162 			 *		...
11163 			 *
11164 			 * Thus, hat_memload() could call kmem_cache_free
11165 			 * for enough number of times that we could easily
11166 			 * hit the bottom of the stack or run out of reserve
11167 			 * list of vmem_seg structs.  So, we must donate
11168 			 * this hblk to reserve list if it's allocated
11169 			 * from sfmmu8_cache *and* mapping kernel range.
11170 			 * We don't need to worry about freeing hmeblk1's
11171 			 * to kmem since they don't map any kmem slabs.
11172 			 *
11173 			 * Note: When segkmem supports largepages, we must
11174 			 * free hmeblk1's to reserve list as well.
11175 			 */
11176 			forcefree = (sfmmup == KHATID) ? 1 : 0;
11177 			if (size == TTE8K &&
11178 			    sfmmu_put_free_hblk(hmeblkp, forcefree)) {
11179 				goto re_verify;
11180 			}
11181 			ASSERT(sfmmup != KHATID);
11182 			kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
11183 		} else {
11184 			/*
11185 			 * Hey! we don't need hblk_reserve any more.
11186 			 */
11187 			ASSERT(owner);
11188 			hblk_reserve_thread = NULL;
11189 			mutex_exit(&hblk_reserve_lock);
11190 			owner = 0;
11191 		}
11192 re_verify:
11193 		/*
11194 		 * let's check if the goodies are still present
11195 		 */
11196 		SFMMU_HASH_LOCK(hmebp);
11197 		HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11198 		if (newhblkp != NULL) {
11199 			/*
11200 			 * return newhblkp if it's not hblk_reserve;
11201 			 * if newhblkp is hblk_reserve, return it
11202 			 * _only if_ we are the owner of hblk_reserve.
11203 			 */
11204 			if (newhblkp != HBLK_RESERVE || owner) {
11205 				ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11206 				    newhblkp->hblk_shared);
11207 				ASSERT(SFMMU_IS_SHMERID_VALID(rid) ||
11208 				    !newhblkp->hblk_shared);
11209 				return (newhblkp);
11210 			} else {
11211 				/*
11212 				 * we just hit hblk_reserve in the hash and
11213 				 * we are not the owner of that;
11214 				 *
11215 				 * block until hblk_reserve_thread completes
11216 				 * swapping hblk_reserve and try the dance
11217 				 * once again.
11218 				 */
11219 				SFMMU_HASH_UNLOCK(hmebp);
11220 				mutex_enter(&hblk_reserve_lock);
11221 				mutex_exit(&hblk_reserve_lock);
11222 				SFMMU_STAT(sf_hblk_reserve_hit);
11223 				goto fill_hblk;
11224 			}
11225 		} else {
11226 			/*
11227 			 * it's no more! try the dance once again.
11228 			 */
11229 			SFMMU_HASH_UNLOCK(hmebp);
11230 			goto fill_hblk;
11231 		}
11232 	}
11233 
11234 hblk_init:
11235 	if (SFMMU_IS_SHMERID_VALID(rid)) {
11236 		uint16_t tteflag = 0x1 <<
11237 		    ((size < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ : size);
11238 
11239 		if (!(rgnp->rgn_hmeflags & tteflag)) {
11240 			atomic_or_16(&rgnp->rgn_hmeflags, tteflag);
11241 		}
11242 		hmeblkp->hblk_shared = 1;
11243 	} else {
11244 		hmeblkp->hblk_shared = 0;
11245 	}
11246 	set_hblk_sz(hmeblkp, size);
11247 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11248 	hmeblkp->hblk_next = (struct hme_blk *)NULL;
11249 	hmeblkp->hblk_tag = hblktag;
11250 	hmeblkp->hblk_shadow = shw_hblkp;
11251 	hblkpa = hmeblkp->hblk_nextpa;
11252 	hmeblkp->hblk_nextpa = 0;
11253 
11254 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
11255 	ASSERT(get_hblk_span(hmeblkp) == HMEBLK_SPAN(size));
11256 	ASSERT(hmeblkp->hblk_hmecnt == 0);
11257 	ASSERT(hmeblkp->hblk_vcnt == 0);
11258 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11259 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
11260 	sfmmu_hblk_hash_add(hmebp, hmeblkp, hblkpa);
11261 	return (hmeblkp);
11262 }
11263 
11264 /*
11265  * This function performs any cleanup required on the hme_blk
11266  * and returns it to the free list.
11267  */
11268 /* ARGSUSED */
11269 static void
11270 sfmmu_hblk_free(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
11271 	uint64_t hblkpa, struct hme_blk **listp)
11272 {
11273 	int shw_size, vshift;
11274 	struct hme_blk *shw_hblkp;
11275 	uint_t		shw_mask, newshw_mask;
11276 	caddr_t		vaddr;
11277 	int		size;
11278 	uint_t		critical;
11279 
11280 	ASSERT(hmeblkp);
11281 	ASSERT(!hmeblkp->hblk_hmecnt);
11282 	ASSERT(!hmeblkp->hblk_vcnt);
11283 	ASSERT(!hmeblkp->hblk_lckcnt);
11284 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
11285 	ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
11286 
11287 	critical = (hblktosfmmu(hmeblkp) == KHATID) ? 1 : 0;
11288 
11289 	size = get_hblk_ttesz(hmeblkp);
11290 	shw_hblkp = hmeblkp->hblk_shadow;
11291 	if (shw_hblkp) {
11292 		ASSERT(hblktosfmmu(hmeblkp) != KHATID);
11293 		ASSERT(!hmeblkp->hblk_shared);
11294 		if (mmu_page_sizes == max_mmu_page_sizes) {
11295 			ASSERT(size < TTE256M);
11296 		} else {
11297 			ASSERT(size < TTE4M);
11298 		}
11299 
11300 		shw_size = get_hblk_ttesz(shw_hblkp);
11301 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11302 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
11303 		ASSERT(vshift < 8);
11304 		/*
11305 		 * Atomically clear shadow mask bit
11306 		 */
11307 		do {
11308 			shw_mask = shw_hblkp->hblk_shw_mask;
11309 			ASSERT(shw_mask & (1 << vshift));
11310 			newshw_mask = shw_mask & ~(1 << vshift);
11311 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
11312 			    shw_mask, newshw_mask);
11313 		} while (newshw_mask != shw_mask);
11314 		hmeblkp->hblk_shadow = NULL;
11315 	}
11316 	hmeblkp->hblk_next = NULL;
11317 	hmeblkp->hblk_nextpa = hblkpa;
11318 	hmeblkp->hblk_shw_bit = 0;
11319 
11320 	/*
11321 	 * Clear ttebit map in the region this hmeblk belongs to. The region
11322 	 * must exist as long as any of its hmeblks exist. This invariant
11323 	 * holds because before region is freed all its hmeblks are removed.
11324 	 */
11325 	if (hmeblkp->hblk_shared) {
11326 		sf_srd_t	*srdp;
11327 		sf_region_t	*rgnp;
11328 		uint_t		rid;
11329 
11330 		srdp = hblktosrd(hmeblkp);
11331 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11332 		rid = hmeblkp->hblk_tag.htag_rid;
11333 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11334 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11335 		rgnp = srdp->srd_hmergnp[rid];
11336 		ASSERT(rgnp != NULL);
11337 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11338 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
11339 		hmeblkp->hblk_shared = 0;
11340 	}
11341 
11342 	if (hmeblkp->hblk_nuc_bit == 0) {
11343 
11344 		if (size == TTE8K && sfmmu_put_free_hblk(hmeblkp, critical))
11345 			return;
11346 
11347 		hmeblkp->hblk_next = *listp;
11348 		*listp = hmeblkp;
11349 	}
11350 }
11351 
11352 static void
11353 sfmmu_hblks_list_purge(struct hme_blk **listp)
11354 {
11355 	struct hme_blk	*hmeblkp;
11356 
11357 	while ((hmeblkp = *listp) != NULL) {
11358 		*listp = hmeblkp->hblk_next;
11359 		kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
11360 	}
11361 }
11362 
11363 #define	BUCKETS_TO_SEARCH_BEFORE_UNLOAD	30
11364 #define	SFMMU_HBLK_STEAL_THRESHOLD 5
11365 
11366 static uint_t sfmmu_hblk_steal_twice;
11367 static uint_t sfmmu_hblk_steal_count, sfmmu_hblk_steal_unload_count;
11368 
11369 /*
11370  * Steal a hmeblk from user or kernel hme hash lists.
11371  * For 8K tte grab one from reserve pool (freehblkp) before proceeding to
11372  * steal and if we fail to steal after SFMMU_HBLK_STEAL_THRESHOLD attempts
11373  * tap into critical reserve of freehblkp.
11374  * Note: We remain looping in this routine until we find one.
11375  */
11376 static struct hme_blk *
11377 sfmmu_hblk_steal(int size)
11378 {
11379 	static struct hmehash_bucket *uhmehash_steal_hand = NULL;
11380 	struct hmehash_bucket *hmebp;
11381 	struct hme_blk *hmeblkp = NULL, *pr_hblk;
11382 	uint64_t hblkpa, prevpa;
11383 	int i;
11384 	uint_t loop_cnt = 0, critical;
11385 
11386 	for (;;) {
11387 		if (size == TTE8K) {
11388 			critical =
11389 			    (++loop_cnt > SFMMU_HBLK_STEAL_THRESHOLD) ? 1 : 0;
11390 			if (sfmmu_get_free_hblk(&hmeblkp, critical))
11391 				return (hmeblkp);
11392 		}
11393 
11394 		hmebp = (uhmehash_steal_hand == NULL) ? uhme_hash :
11395 		    uhmehash_steal_hand;
11396 		ASSERT(hmebp >= uhme_hash && hmebp <= &uhme_hash[UHMEHASH_SZ]);
11397 
11398 		for (i = 0; hmeblkp == NULL && i <= UHMEHASH_SZ +
11399 		    BUCKETS_TO_SEARCH_BEFORE_UNLOAD; i++) {
11400 			SFMMU_HASH_LOCK(hmebp);
11401 			hmeblkp = hmebp->hmeblkp;
11402 			hblkpa = hmebp->hmeh_nextpa;
11403 			prevpa = 0;
11404 			pr_hblk = NULL;
11405 			while (hmeblkp) {
11406 				/*
11407 				 * check if it is a hmeblk that is not locked
11408 				 * and not shared. skip shadow hmeblks with
11409 				 * shadow_mask set i.e valid count non zero.
11410 				 */
11411 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11412 				    (hmeblkp->hblk_shw_bit == 0 ||
11413 				    hmeblkp->hblk_vcnt == 0) &&
11414 				    (hmeblkp->hblk_lckcnt == 0)) {
11415 					/*
11416 					 * there is a high probability that we
11417 					 * will find a free one. search some
11418 					 * buckets for a free hmeblk initially
11419 					 * before unloading a valid hmeblk.
11420 					 */
11421 					if ((hmeblkp->hblk_vcnt == 0 &&
11422 					    hmeblkp->hblk_hmecnt == 0) || (i >=
11423 					    BUCKETS_TO_SEARCH_BEFORE_UNLOAD)) {
11424 						if (sfmmu_steal_this_hblk(hmebp,
11425 						    hmeblkp, hblkpa, prevpa,
11426 						    pr_hblk)) {
11427 							/*
11428 							 * Hblk is unloaded
11429 							 * successfully
11430 							 */
11431 							break;
11432 						}
11433 					}
11434 				}
11435 				pr_hblk = hmeblkp;
11436 				prevpa = hblkpa;
11437 				hblkpa = hmeblkp->hblk_nextpa;
11438 				hmeblkp = hmeblkp->hblk_next;
11439 			}
11440 
11441 			SFMMU_HASH_UNLOCK(hmebp);
11442 			if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
11443 				hmebp = uhme_hash;
11444 		}
11445 		uhmehash_steal_hand = hmebp;
11446 
11447 		if (hmeblkp != NULL)
11448 			break;
11449 
11450 		/*
11451 		 * in the worst case, look for a free one in the kernel
11452 		 * hash table.
11453 		 */
11454 		for (i = 0, hmebp = khme_hash; i <= KHMEHASH_SZ; i++) {
11455 			SFMMU_HASH_LOCK(hmebp);
11456 			hmeblkp = hmebp->hmeblkp;
11457 			hblkpa = hmebp->hmeh_nextpa;
11458 			prevpa = 0;
11459 			pr_hblk = NULL;
11460 			while (hmeblkp) {
11461 				/*
11462 				 * check if it is free hmeblk
11463 				 */
11464 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11465 				    (hmeblkp->hblk_lckcnt == 0) &&
11466 				    (hmeblkp->hblk_vcnt == 0) &&
11467 				    (hmeblkp->hblk_hmecnt == 0)) {
11468 					if (sfmmu_steal_this_hblk(hmebp,
11469 					    hmeblkp, hblkpa, prevpa, pr_hblk)) {
11470 						break;
11471 					} else {
11472 						/*
11473 						 * Cannot fail since we have
11474 						 * hash lock.
11475 						 */
11476 						panic("fail to steal?");
11477 					}
11478 				}
11479 
11480 				pr_hblk = hmeblkp;
11481 				prevpa = hblkpa;
11482 				hblkpa = hmeblkp->hblk_nextpa;
11483 				hmeblkp = hmeblkp->hblk_next;
11484 			}
11485 
11486 			SFMMU_HASH_UNLOCK(hmebp);
11487 			if (hmebp++ == &khme_hash[KHMEHASH_SZ])
11488 				hmebp = khme_hash;
11489 		}
11490 
11491 		if (hmeblkp != NULL)
11492 			break;
11493 		sfmmu_hblk_steal_twice++;
11494 	}
11495 	return (hmeblkp);
11496 }
11497 
11498 /*
11499  * This routine does real work to prepare a hblk to be "stolen" by
11500  * unloading the mappings, updating shadow counts ....
11501  * It returns 1 if the block is ready to be reused (stolen), or 0
11502  * means the block cannot be stolen yet- pageunload is still working
11503  * on this hblk.
11504  */
11505 static int
11506 sfmmu_steal_this_hblk(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
11507 	uint64_t hblkpa, uint64_t prevpa, struct hme_blk *pr_hblk)
11508 {
11509 	int shw_size, vshift;
11510 	struct hme_blk *shw_hblkp;
11511 	caddr_t vaddr;
11512 	uint_t shw_mask, newshw_mask;
11513 
11514 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11515 
11516 	/*
11517 	 * check if the hmeblk is free, unload if necessary
11518 	 */
11519 	if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11520 		sfmmu_t *sfmmup;
11521 		demap_range_t dmr;
11522 
11523 		sfmmup = hblktosfmmu(hmeblkp);
11524 		if (hmeblkp->hblk_shared || sfmmup->sfmmu_ismhat) {
11525 			return (0);
11526 		}
11527 		DEMAP_RANGE_INIT(sfmmup, &dmr);
11528 		(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
11529 		    (caddr_t)get_hblk_base(hmeblkp),
11530 		    get_hblk_endaddr(hmeblkp), &dmr, HAT_UNLOAD);
11531 		DEMAP_RANGE_FLUSH(&dmr);
11532 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11533 			/*
11534 			 * Pageunload is working on the same hblk.
11535 			 */
11536 			return (0);
11537 		}
11538 
11539 		sfmmu_hblk_steal_unload_count++;
11540 	}
11541 
11542 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11543 	ASSERT(hmeblkp->hblk_vcnt == 0 && hmeblkp->hblk_hmecnt == 0);
11544 
11545 	sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
11546 	hmeblkp->hblk_nextpa = hblkpa;
11547 
11548 	shw_hblkp = hmeblkp->hblk_shadow;
11549 	if (shw_hblkp) {
11550 		ASSERT(!hmeblkp->hblk_shared);
11551 		shw_size = get_hblk_ttesz(shw_hblkp);
11552 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11553 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
11554 		ASSERT(vshift < 8);
11555 		/*
11556 		 * Atomically clear shadow mask bit
11557 		 */
11558 		do {
11559 			shw_mask = shw_hblkp->hblk_shw_mask;
11560 			ASSERT(shw_mask & (1 << vshift));
11561 			newshw_mask = shw_mask & ~(1 << vshift);
11562 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
11563 			    shw_mask, newshw_mask);
11564 		} while (newshw_mask != shw_mask);
11565 		hmeblkp->hblk_shadow = NULL;
11566 	}
11567 
11568 	/*
11569 	 * remove shadow bit if we are stealing an unused shadow hmeblk.
11570 	 * sfmmu_hblk_alloc needs it that way, will set shadow bit later if
11571 	 * we are indeed allocating a shadow hmeblk.
11572 	 */
11573 	hmeblkp->hblk_shw_bit = 0;
11574 
11575 	/*
11576 	 * Clear ttebit map in the region this hmeblk belongs to. The region
11577 	 * must exist as long as any of its hmeblks exist. This invariant
11578 	 * holds because before region is freed all its hmeblks are removed.
11579 	 */
11580 	if (hmeblkp->hblk_shared) {
11581 		sf_srd_t	*srdp;
11582 		sf_region_t	*rgnp;
11583 		uint_t		rid;
11584 
11585 		srdp = hblktosrd(hmeblkp);
11586 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11587 		rid = hmeblkp->hblk_tag.htag_rid;
11588 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11589 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11590 		rgnp = srdp->srd_hmergnp[rid];
11591 		ASSERT(rgnp != NULL);
11592 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11593 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
11594 		hmeblkp->hblk_shared = 0;
11595 	}
11596 
11597 	sfmmu_hblk_steal_count++;
11598 	SFMMU_STAT(sf_steal_count);
11599 
11600 	return (1);
11601 }
11602 
11603 struct hme_blk *
11604 sfmmu_hmetohblk(struct sf_hment *sfhme)
11605 {
11606 	struct hme_blk *hmeblkp;
11607 	struct sf_hment *sfhme0;
11608 	struct hme_blk *hblk_dummy = 0;
11609 
11610 	/*
11611 	 * No dummy sf_hments, please.
11612 	 */
11613 	ASSERT(sfhme->hme_tte.ll != 0);
11614 
11615 	sfhme0 = sfhme - sfhme->hme_tte.tte_hmenum;
11616 	hmeblkp = (struct hme_blk *)((uintptr_t)sfhme0 -
11617 	    (uintptr_t)&hblk_dummy->hblk_hme[0]);
11618 
11619 	return (hmeblkp);
11620 }
11621 
11622 /*
11623  * On swapin, get appropriately sized TSB(s) and clear the HAT_SWAPPED flag.
11624  * If we can't get appropriately sized TSB(s), try for 8K TSB(s) using
11625  * KM_SLEEP allocation.
11626  *
11627  * Return 0 on success, -1 otherwise.
11628  */
11629 static void
11630 sfmmu_tsb_swapin(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11631 {
11632 	struct tsb_info *tsbinfop, *next;
11633 	tsb_replace_rc_t rc;
11634 	boolean_t gotfirst = B_FALSE;
11635 
11636 	ASSERT(sfmmup != ksfmmup);
11637 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11638 
11639 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPIN)) {
11640 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
11641 	}
11642 
11643 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11644 		SFMMU_FLAGS_SET(sfmmup, HAT_SWAPIN);
11645 	} else {
11646 		return;
11647 	}
11648 
11649 	ASSERT(sfmmup->sfmmu_tsb != NULL);
11650 
11651 	/*
11652 	 * Loop over all tsbinfo's replacing them with ones that actually have
11653 	 * a TSB.  If any of the replacements ever fail, bail out of the loop.
11654 	 */
11655 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL; tsbinfop = next) {
11656 		ASSERT(tsbinfop->tsb_flags & TSB_SWAPPED);
11657 		next = tsbinfop->tsb_next;
11658 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, tsbinfop->tsb_szc,
11659 		    hatlockp, TSB_SWAPIN);
11660 		if (rc != TSB_SUCCESS) {
11661 			break;
11662 		}
11663 		gotfirst = B_TRUE;
11664 	}
11665 
11666 	switch (rc) {
11667 	case TSB_SUCCESS:
11668 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11669 		cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11670 		return;
11671 	case TSB_LOSTRACE:
11672 		break;
11673 	case TSB_ALLOCFAIL:
11674 		break;
11675 	default:
11676 		panic("sfmmu_replace_tsb returned unrecognized failure code "
11677 		    "%d", rc);
11678 	}
11679 
11680 	/*
11681 	 * In this case, we failed to get one of our TSBs.  If we failed to
11682 	 * get the first TSB, get one of minimum size (8KB).  Walk the list
11683 	 * and throw away the tsbinfos, starting where the allocation failed;
11684 	 * we can get by with just one TSB as long as we don't leave the
11685 	 * SWAPPED tsbinfo structures lying around.
11686 	 */
11687 	tsbinfop = sfmmup->sfmmu_tsb;
11688 	next = tsbinfop->tsb_next;
11689 	tsbinfop->tsb_next = NULL;
11690 
11691 	sfmmu_hat_exit(hatlockp);
11692 	for (tsbinfop = next; tsbinfop != NULL; tsbinfop = next) {
11693 		next = tsbinfop->tsb_next;
11694 		sfmmu_tsbinfo_free(tsbinfop);
11695 	}
11696 	hatlockp = sfmmu_hat_enter(sfmmup);
11697 
11698 	/*
11699 	 * If we don't have any TSBs, get a single 8K TSB for 8K, 64K and 512K
11700 	 * pages.
11701 	 */
11702 	if (!gotfirst) {
11703 		tsbinfop = sfmmup->sfmmu_tsb;
11704 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, TSB_MIN_SZCODE,
11705 		    hatlockp, TSB_SWAPIN | TSB_FORCEALLOC);
11706 		ASSERT(rc == TSB_SUCCESS);
11707 	}
11708 
11709 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11710 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11711 }
11712 
11713 static int
11714 sfmmu_is_rgnva(sf_srd_t *srdp, caddr_t addr, ulong_t w, ulong_t bmw)
11715 {
11716 	ulong_t bix = 0;
11717 	uint_t rid;
11718 	sf_region_t *rgnp;
11719 
11720 	ASSERT(srdp != NULL);
11721 	ASSERT(srdp->srd_refcnt != 0);
11722 
11723 	w <<= BT_ULSHIFT;
11724 	while (bmw) {
11725 		if (!(bmw & 0x1)) {
11726 			bix++;
11727 			bmw >>= 1;
11728 			continue;
11729 		}
11730 		rid = w | bix;
11731 		rgnp = srdp->srd_hmergnp[rid];
11732 		ASSERT(rgnp->rgn_refcnt > 0);
11733 		ASSERT(rgnp->rgn_id == rid);
11734 		if (addr < rgnp->rgn_saddr ||
11735 		    addr >= (rgnp->rgn_saddr + rgnp->rgn_size)) {
11736 			bix++;
11737 			bmw >>= 1;
11738 		} else {
11739 			return (1);
11740 		}
11741 	}
11742 	return (0);
11743 }
11744 
11745 /*
11746  * Handle exceptions for low level tsb_handler.
11747  *
11748  * There are many scenarios that could land us here:
11749  *
11750  * If the context is invalid we land here. The context can be invalid
11751  * for 3 reasons: 1) we couldn't allocate a new context and now need to
11752  * perform a wrap around operation in order to allocate a new context.
11753  * 2) Context was invalidated to change pagesize programming 3) ISMs or
11754  * TSBs configuration is changeing for this process and we are forced into
11755  * here to do a syncronization operation. If the context is valid we can
11756  * be here from window trap hanlder. In this case just call trap to handle
11757  * the fault.
11758  *
11759  * Note that the process will run in INVALID_CONTEXT before
11760  * faulting into here and subsequently loading the MMU registers
11761  * (including the TSB base register) associated with this process.
11762  * For this reason, the trap handlers must all test for
11763  * INVALID_CONTEXT before attempting to access any registers other
11764  * than the context registers.
11765  */
11766 void
11767 sfmmu_tsbmiss_exception(struct regs *rp, uintptr_t tagaccess, uint_t traptype)
11768 {
11769 	sfmmu_t *sfmmup, *shsfmmup;
11770 	uint_t ctxtype;
11771 	klwp_id_t lwp;
11772 	char lwp_save_state;
11773 	hatlock_t *hatlockp, *shatlockp;
11774 	struct tsb_info *tsbinfop;
11775 	struct tsbmiss *tsbmp;
11776 	sf_scd_t *scdp;
11777 
11778 	SFMMU_STAT(sf_tsb_exceptions);
11779 	SFMMU_MMU_STAT(mmu_tsb_exceptions);
11780 	sfmmup = astosfmmu(curthread->t_procp->p_as);
11781 	/*
11782 	 * note that in sun4u, tagacces register contains ctxnum
11783 	 * while sun4v passes ctxtype in the tagaccess register.
11784 	 */
11785 	ctxtype = tagaccess & TAGACC_CTX_MASK;
11786 
11787 	ASSERT(sfmmup != ksfmmup && ctxtype != KCONTEXT);
11788 	ASSERT(sfmmup->sfmmu_ismhat == 0);
11789 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED) ||
11790 	    ctxtype == INVALID_CONTEXT);
11791 
11792 	if (ctxtype != INVALID_CONTEXT && traptype != T_DATA_PROT) {
11793 		/*
11794 		 * We may land here because shme bitmap and pagesize
11795 		 * flags are updated lazily in tsbmiss area on other cpus.
11796 		 * If we detect here that tsbmiss area is out of sync with
11797 		 * sfmmu update it and retry the trapped instruction.
11798 		 * Otherwise call trap().
11799 		 */
11800 		int ret = 0;
11801 		uchar_t tteflag_mask = (1 << TTE64K) | (1 << TTE8K);
11802 		caddr_t addr = (caddr_t)(tagaccess & TAGACC_VADDR_MASK);
11803 
11804 		/*
11805 		 * Must set lwp state to LWP_SYS before
11806 		 * trying to acquire any adaptive lock
11807 		 */
11808 		lwp = ttolwp(curthread);
11809 		ASSERT(lwp);
11810 		lwp_save_state = lwp->lwp_state;
11811 		lwp->lwp_state = LWP_SYS;
11812 
11813 		hatlockp = sfmmu_hat_enter(sfmmup);
11814 		kpreempt_disable();
11815 		tsbmp = &tsbmiss_area[CPU->cpu_id];
11816 		ASSERT(sfmmup == tsbmp->usfmmup);
11817 		if (((tsbmp->uhat_tteflags ^ sfmmup->sfmmu_tteflags) &
11818 		    ~tteflag_mask) ||
11819 		    ((tsbmp->uhat_rtteflags ^  sfmmup->sfmmu_rtteflags) &
11820 		    ~tteflag_mask)) {
11821 			tsbmp->uhat_tteflags = sfmmup->sfmmu_tteflags;
11822 			tsbmp->uhat_rtteflags = sfmmup->sfmmu_rtteflags;
11823 			ret = 1;
11824 		}
11825 		if (sfmmup->sfmmu_srdp != NULL) {
11826 			ulong_t *sm = sfmmup->sfmmu_hmeregion_map.bitmap;
11827 			ulong_t *tm = tsbmp->shmermap;
11828 			ulong_t i;
11829 			for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
11830 				ulong_t d = tm[i] ^ sm[i];
11831 				if (d) {
11832 					if (d & sm[i]) {
11833 						if (!ret && sfmmu_is_rgnva(
11834 						    sfmmup->sfmmu_srdp,
11835 						    addr, i, d & sm[i])) {
11836 							ret = 1;
11837 						}
11838 					}
11839 					tm[i] = sm[i];
11840 				}
11841 			}
11842 		}
11843 		kpreempt_enable();
11844 		sfmmu_hat_exit(hatlockp);
11845 		lwp->lwp_state = lwp_save_state;
11846 		if (ret) {
11847 			return;
11848 		}
11849 	} else if (ctxtype == INVALID_CONTEXT) {
11850 		/*
11851 		 * First, make sure we come out of here with a valid ctx,
11852 		 * since if we don't get one we'll simply loop on the
11853 		 * faulting instruction.
11854 		 *
11855 		 * If the ISM mappings are changing, the TSB is relocated,
11856 		 * the process is swapped, the process is joining SCD or
11857 		 * leaving SCD or shared regions we serialize behind the
11858 		 * controlling thread with hat lock, sfmmu_flags and
11859 		 * sfmmu_tsb_cv condition variable.
11860 		 */
11861 
11862 		/*
11863 		 * Must set lwp state to LWP_SYS before
11864 		 * trying to acquire any adaptive lock
11865 		 */
11866 		lwp = ttolwp(curthread);
11867 		ASSERT(lwp);
11868 		lwp_save_state = lwp->lwp_state;
11869 		lwp->lwp_state = LWP_SYS;
11870 
11871 		hatlockp = sfmmu_hat_enter(sfmmup);
11872 retry:
11873 		if ((scdp = sfmmup->sfmmu_scdp) != NULL) {
11874 			shsfmmup = scdp->scd_sfmmup;
11875 			ASSERT(shsfmmup != NULL);
11876 
11877 			for (tsbinfop = shsfmmup->sfmmu_tsb; tsbinfop != NULL;
11878 			    tsbinfop = tsbinfop->tsb_next) {
11879 				if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11880 					/* drop the private hat lock */
11881 					sfmmu_hat_exit(hatlockp);
11882 					/* acquire the shared hat lock */
11883 					shatlockp = sfmmu_hat_enter(shsfmmup);
11884 					/*
11885 					 * recheck to see if anything changed
11886 					 * after we drop the private hat lock.
11887 					 */
11888 					if (sfmmup->sfmmu_scdp == scdp &&
11889 					    shsfmmup == scdp->scd_sfmmup) {
11890 						sfmmu_tsb_chk_reloc(shsfmmup,
11891 						    shatlockp);
11892 					}
11893 					sfmmu_hat_exit(shatlockp);
11894 					hatlockp = sfmmu_hat_enter(sfmmup);
11895 					goto retry;
11896 				}
11897 			}
11898 		}
11899 
11900 		for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
11901 		    tsbinfop = tsbinfop->tsb_next) {
11902 			if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11903 				cv_wait(&sfmmup->sfmmu_tsb_cv,
11904 				    HATLOCK_MUTEXP(hatlockp));
11905 				goto retry;
11906 			}
11907 		}
11908 
11909 		/*
11910 		 * Wait for ISM maps to be updated.
11911 		 */
11912 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
11913 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11914 			    HATLOCK_MUTEXP(hatlockp));
11915 			goto retry;
11916 		}
11917 
11918 		/* Is this process joining an SCD? */
11919 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
11920 			/*
11921 			 * Flush private TSB and setup shared TSB.
11922 			 * sfmmu_finish_join_scd() does not drop the
11923 			 * hat lock.
11924 			 */
11925 			sfmmu_finish_join_scd(sfmmup);
11926 			SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
11927 		}
11928 
11929 		/*
11930 		 * If we're swapping in, get TSB(s).  Note that we must do
11931 		 * this before we get a ctx or load the MMU state.  Once
11932 		 * we swap in we have to recheck to make sure the TSB(s) and
11933 		 * ISM mappings didn't change while we slept.
11934 		 */
11935 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11936 			sfmmu_tsb_swapin(sfmmup, hatlockp);
11937 			goto retry;
11938 		}
11939 
11940 		sfmmu_get_ctx(sfmmup);
11941 
11942 		sfmmu_hat_exit(hatlockp);
11943 		/*
11944 		 * Must restore lwp_state if not calling
11945 		 * trap() for further processing. Restore
11946 		 * it anyway.
11947 		 */
11948 		lwp->lwp_state = lwp_save_state;
11949 		return;
11950 	}
11951 	trap(rp, (caddr_t)tagaccess, traptype, 0);
11952 }
11953 
11954 static void
11955 sfmmu_tsb_chk_reloc(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11956 {
11957 	struct tsb_info *tp;
11958 
11959 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11960 
11961 	for (tp = sfmmup->sfmmu_tsb; tp != NULL; tp = tp->tsb_next) {
11962 		if (tp->tsb_flags & TSB_RELOC_FLAG) {
11963 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11964 			    HATLOCK_MUTEXP(hatlockp));
11965 			break;
11966 		}
11967 	}
11968 }
11969 
11970 /*
11971  * sfmmu_vatopfn_suspended is called from GET_TTE when TL=0 and
11972  * TTE_SUSPENDED bit set in tte we block on aquiring a page lock
11973  * rather than spinning to avoid send mondo timeouts with
11974  * interrupts enabled. When the lock is acquired it is immediately
11975  * released and we return back to sfmmu_vatopfn just after
11976  * the GET_TTE call.
11977  */
11978 void
11979 sfmmu_vatopfn_suspended(caddr_t vaddr, sfmmu_t *sfmmu, tte_t *ttep)
11980 {
11981 	struct page	**pp;
11982 
11983 	(void) as_pagelock(sfmmu->sfmmu_as, &pp, vaddr, TTE_CSZ(ttep), S_WRITE);
11984 	as_pageunlock(sfmmu->sfmmu_as, pp, vaddr, TTE_CSZ(ttep), S_WRITE);
11985 }
11986 
11987 /*
11988  * sfmmu_tsbmiss_suspended is called from GET_TTE when TL>0 and
11989  * TTE_SUSPENDED bit set in tte. We do this so that we can handle
11990  * cross traps which cannot be handled while spinning in the
11991  * trap handlers. Simply enter and exit the kpr_suspendlock spin
11992  * mutex, which is held by the holder of the suspend bit, and then
11993  * retry the trapped instruction after unwinding.
11994  */
11995 /*ARGSUSED*/
11996 void
11997 sfmmu_tsbmiss_suspended(struct regs *rp, uintptr_t tagacc, uint_t traptype)
11998 {
11999 	ASSERT(curthread != kreloc_thread);
12000 	mutex_enter(&kpr_suspendlock);
12001 	mutex_exit(&kpr_suspendlock);
12002 }
12003 
12004 /*
12005  * This routine could be optimized to reduce the number of xcalls by flushing
12006  * the entire TLBs if region reference count is above some threshold but the
12007  * tradeoff will depend on the size of the TLB. So for now flush the specific
12008  * page a context at a time.
12009  *
12010  * If uselocks is 0 then it's called after all cpus were captured and all the
12011  * hat locks were taken. In this case don't take the region lock by relying on
12012  * the order of list region update operations in hat_join_region(),
12013  * hat_leave_region() and hat_dup_region(). The ordering in those routines
12014  * guarantees that list is always forward walkable and reaches active sfmmus
12015  * regardless of where xc_attention() captures a cpu.
12016  */
12017 cpuset_t
12018 sfmmu_rgntlb_demap(caddr_t addr, sf_region_t *rgnp,
12019     struct hme_blk *hmeblkp, int uselocks)
12020 {
12021 	sfmmu_t	*sfmmup;
12022 	cpuset_t cpuset;
12023 	cpuset_t rcpuset;
12024 	hatlock_t *hatlockp;
12025 	uint_t rid = rgnp->rgn_id;
12026 	sf_rgn_link_t *rlink;
12027 	sf_scd_t *scdp;
12028 
12029 	ASSERT(hmeblkp->hblk_shared);
12030 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
12031 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
12032 
12033 	CPUSET_ZERO(rcpuset);
12034 	if (uselocks) {
12035 		mutex_enter(&rgnp->rgn_mutex);
12036 	}
12037 	sfmmup = rgnp->rgn_sfmmu_head;
12038 	while (sfmmup != NULL) {
12039 		if (uselocks) {
12040 			hatlockp = sfmmu_hat_enter(sfmmup);
12041 		}
12042 
12043 		/*
12044 		 * When an SCD is created the SCD hat is linked on the sfmmu
12045 		 * region lists for each hme region which is part of the
12046 		 * SCD. If we find an SCD hat, when walking these lists,
12047 		 * then we flush the shared TSBs, if we find a private hat,
12048 		 * which is part of an SCD, but where the region
12049 		 * is not part of the SCD then we flush the private TSBs.
12050 		 */
12051 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12052 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
12053 			scdp = sfmmup->sfmmu_scdp;
12054 			if (SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
12055 				if (uselocks) {
12056 					sfmmu_hat_exit(hatlockp);
12057 				}
12058 				goto next;
12059 			}
12060 		}
12061 
12062 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12063 
12064 		kpreempt_disable();
12065 		cpuset = sfmmup->sfmmu_cpusran;
12066 		CPUSET_AND(cpuset, cpu_ready_set);
12067 		CPUSET_DEL(cpuset, CPU->cpu_id);
12068 		SFMMU_XCALL_STATS(sfmmup);
12069 		xt_some(cpuset, vtag_flushpage_tl1,
12070 		    (uint64_t)addr, (uint64_t)sfmmup);
12071 		vtag_flushpage(addr, (uint64_t)sfmmup);
12072 		if (uselocks) {
12073 			sfmmu_hat_exit(hatlockp);
12074 		}
12075 		kpreempt_enable();
12076 		CPUSET_OR(rcpuset, cpuset);
12077 
12078 next:
12079 		/* LINTED: constant in conditional context */
12080 		SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
12081 		ASSERT(rlink != NULL);
12082 		sfmmup = rlink->next;
12083 	}
12084 	if (uselocks) {
12085 		mutex_exit(&rgnp->rgn_mutex);
12086 	}
12087 	return (rcpuset);
12088 }
12089 
12090 static int
12091 find_ism_rid(sfmmu_t *sfmmup, sfmmu_t *ism_sfmmup, caddr_t va, uint_t *ism_rid)
12092 {
12093 	ism_blk_t	*ism_blkp;
12094 	int		i;
12095 	ism_map_t	*ism_map;
12096 #ifdef DEBUG
12097 	struct hat	*ism_hatid;
12098 #endif
12099 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12100 
12101 	ism_blkp = sfmmup->sfmmu_iblk;
12102 	while (ism_blkp != NULL) {
12103 		ism_map = ism_blkp->iblk_maps;
12104 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
12105 			if ((va >= ism_start(ism_map[i])) &&
12106 			    (va < ism_end(ism_map[i]))) {
12107 
12108 				*ism_rid = ism_map[i].imap_rid;
12109 #ifdef DEBUG
12110 				ism_hatid = ism_map[i].imap_ismhat;
12111 				ASSERT(ism_hatid == ism_sfmmup);
12112 				ASSERT(ism_hatid->sfmmu_ismhat);
12113 #endif
12114 				return (1);
12115 			}
12116 		}
12117 		ism_blkp = ism_blkp->iblk_next;
12118 	}
12119 	return (0);
12120 }
12121 
12122 /*
12123  * Special routine to flush out ism mappings- TSBs, TLBs and D-caches.
12124  * This routine may be called with all cpu's captured. Therefore, the
12125  * caller is responsible for holding all locks and disabling kernel
12126  * preemption.
12127  */
12128 /* ARGSUSED */
12129 static void
12130 sfmmu_ismtlbcache_demap(caddr_t addr, sfmmu_t *ism_sfmmup,
12131 	struct hme_blk *hmeblkp, pfn_t pfnum, int cache_flush_flag)
12132 {
12133 	cpuset_t 	cpuset;
12134 	caddr_t 	va;
12135 	ism_ment_t	*ment;
12136 	sfmmu_t		*sfmmup;
12137 #ifdef VAC
12138 	int 		vcolor;
12139 #endif
12140 
12141 	sf_scd_t	*scdp;
12142 	uint_t		ism_rid;
12143 
12144 	ASSERT(!hmeblkp->hblk_shared);
12145 	/*
12146 	 * Walk the ism_hat's mapping list and flush the page
12147 	 * from every hat sharing this ism_hat. This routine
12148 	 * may be called while all cpu's have been captured.
12149 	 * Therefore we can't attempt to grab any locks. For now
12150 	 * this means we will protect the ism mapping list under
12151 	 * a single lock which will be grabbed by the caller.
12152 	 * If hat_share/unshare scalibility becomes a performance
12153 	 * problem then we may need to re-think ism mapping list locking.
12154 	 */
12155 	ASSERT(ism_sfmmup->sfmmu_ismhat);
12156 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
12157 	addr = addr - ISMID_STARTADDR;
12158 
12159 	for (ment = ism_sfmmup->sfmmu_iment; ment; ment = ment->iment_next) {
12160 
12161 		sfmmup = ment->iment_hat;
12162 
12163 		va = ment->iment_base_va;
12164 		va = (caddr_t)((uintptr_t)va  + (uintptr_t)addr);
12165 
12166 		/*
12167 		 * When an SCD is created the SCD hat is linked on the ism
12168 		 * mapping lists for each ISM segment which is part of the
12169 		 * SCD. If we find an SCD hat, when walking these lists,
12170 		 * then we flush the shared TSBs, if we find a private hat,
12171 		 * which is part of an SCD, but where the region
12172 		 * corresponding to this va is not part of the SCD then we
12173 		 * flush the private TSBs.
12174 		 */
12175 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12176 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD) &&
12177 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
12178 			if (!find_ism_rid(sfmmup, ism_sfmmup, va,
12179 			    &ism_rid)) {
12180 				cmn_err(CE_PANIC,
12181 				    "can't find matching ISM rid!");
12182 			}
12183 
12184 			scdp = sfmmup->sfmmu_scdp;
12185 			if (SFMMU_IS_ISMRID_VALID(ism_rid) &&
12186 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map,
12187 			    ism_rid)) {
12188 				continue;
12189 			}
12190 		}
12191 		SFMMU_UNLOAD_TSB(va, sfmmup, hmeblkp, 1);
12192 
12193 		cpuset = sfmmup->sfmmu_cpusran;
12194 		CPUSET_AND(cpuset, cpu_ready_set);
12195 		CPUSET_DEL(cpuset, CPU->cpu_id);
12196 		SFMMU_XCALL_STATS(sfmmup);
12197 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)va,
12198 		    (uint64_t)sfmmup);
12199 		vtag_flushpage(va, (uint64_t)sfmmup);
12200 
12201 #ifdef VAC
12202 		/*
12203 		 * Flush D$
12204 		 * When flushing D$ we must flush all
12205 		 * cpu's. See sfmmu_cache_flush().
12206 		 */
12207 		if (cache_flush_flag == CACHE_FLUSH) {
12208 			cpuset = cpu_ready_set;
12209 			CPUSET_DEL(cpuset, CPU->cpu_id);
12210 
12211 			SFMMU_XCALL_STATS(sfmmup);
12212 			vcolor = addr_to_vcolor(va);
12213 			xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12214 			vac_flushpage(pfnum, vcolor);
12215 		}
12216 #endif	/* VAC */
12217 	}
12218 }
12219 
12220 /*
12221  * Demaps the TSB, CPU caches, and flushes all TLBs on all CPUs of
12222  * a particular virtual address and ctx.  If noflush is set we do not
12223  * flush the TLB/TSB.  This function may or may not be called with the
12224  * HAT lock held.
12225  */
12226 static void
12227 sfmmu_tlbcache_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12228 	pfn_t pfnum, int tlb_noflush, int cpu_flag, int cache_flush_flag,
12229 	int hat_lock_held)
12230 {
12231 #ifdef VAC
12232 	int vcolor;
12233 #endif
12234 	cpuset_t cpuset;
12235 	hatlock_t *hatlockp;
12236 
12237 	ASSERT(!hmeblkp->hblk_shared);
12238 
12239 #if defined(lint) && !defined(VAC)
12240 	pfnum = pfnum;
12241 	cpu_flag = cpu_flag;
12242 	cache_flush_flag = cache_flush_flag;
12243 #endif
12244 
12245 	/*
12246 	 * There is no longer a need to protect against ctx being
12247 	 * stolen here since we don't store the ctx in the TSB anymore.
12248 	 */
12249 #ifdef VAC
12250 	vcolor = addr_to_vcolor(addr);
12251 #endif
12252 
12253 	/*
12254 	 * We must hold the hat lock during the flush of TLB,
12255 	 * to avoid a race with sfmmu_invalidate_ctx(), where
12256 	 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12257 	 * causing TLB demap routine to skip flush on that MMU.
12258 	 * If the context on a MMU has already been set to
12259 	 * INVALID_CONTEXT, we just get an extra flush on
12260 	 * that MMU.
12261 	 */
12262 	if (!hat_lock_held && !tlb_noflush)
12263 		hatlockp = sfmmu_hat_enter(sfmmup);
12264 
12265 	kpreempt_disable();
12266 	if (!tlb_noflush) {
12267 		/*
12268 		 * Flush the TSB and TLB.
12269 		 */
12270 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12271 
12272 		cpuset = sfmmup->sfmmu_cpusran;
12273 		CPUSET_AND(cpuset, cpu_ready_set);
12274 		CPUSET_DEL(cpuset, CPU->cpu_id);
12275 
12276 		SFMMU_XCALL_STATS(sfmmup);
12277 
12278 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
12279 		    (uint64_t)sfmmup);
12280 
12281 		vtag_flushpage(addr, (uint64_t)sfmmup);
12282 	}
12283 
12284 	if (!hat_lock_held && !tlb_noflush)
12285 		sfmmu_hat_exit(hatlockp);
12286 
12287 #ifdef VAC
12288 	/*
12289 	 * Flush the D$
12290 	 *
12291 	 * Even if the ctx is stolen, we need to flush the
12292 	 * cache. Our ctx stealer only flushes the TLBs.
12293 	 */
12294 	if (cache_flush_flag == CACHE_FLUSH) {
12295 		if (cpu_flag & FLUSH_ALL_CPUS) {
12296 			cpuset = cpu_ready_set;
12297 		} else {
12298 			cpuset = sfmmup->sfmmu_cpusran;
12299 			CPUSET_AND(cpuset, cpu_ready_set);
12300 		}
12301 		CPUSET_DEL(cpuset, CPU->cpu_id);
12302 		SFMMU_XCALL_STATS(sfmmup);
12303 		xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12304 		vac_flushpage(pfnum, vcolor);
12305 	}
12306 #endif	/* VAC */
12307 	kpreempt_enable();
12308 }
12309 
12310 /*
12311  * Demaps the TSB and flushes all TLBs on all cpus for a particular virtual
12312  * address and ctx.  If noflush is set we do not currently do anything.
12313  * This function may or may not be called with the HAT lock held.
12314  */
12315 static void
12316 sfmmu_tlb_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12317 	int tlb_noflush, int hat_lock_held)
12318 {
12319 	cpuset_t cpuset;
12320 	hatlock_t *hatlockp;
12321 
12322 	ASSERT(!hmeblkp->hblk_shared);
12323 
12324 	/*
12325 	 * If the process is exiting we have nothing to do.
12326 	 */
12327 	if (tlb_noflush)
12328 		return;
12329 
12330 	/*
12331 	 * Flush TSB.
12332 	 */
12333 	if (!hat_lock_held)
12334 		hatlockp = sfmmu_hat_enter(sfmmup);
12335 	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12336 
12337 	kpreempt_disable();
12338 
12339 	cpuset = sfmmup->sfmmu_cpusran;
12340 	CPUSET_AND(cpuset, cpu_ready_set);
12341 	CPUSET_DEL(cpuset, CPU->cpu_id);
12342 
12343 	SFMMU_XCALL_STATS(sfmmup);
12344 	xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr, (uint64_t)sfmmup);
12345 
12346 	vtag_flushpage(addr, (uint64_t)sfmmup);
12347 
12348 	if (!hat_lock_held)
12349 		sfmmu_hat_exit(hatlockp);
12350 
12351 	kpreempt_enable();
12352 
12353 }
12354 
12355 /*
12356  * Special case of sfmmu_tlb_demap for MMU_PAGESIZE hblks. Use the xcall
12357  * call handler that can flush a range of pages to save on xcalls.
12358  */
12359 static int sfmmu_xcall_save;
12360 
12361 /*
12362  * this routine is never used for demaping addresses backed by SRD hmeblks.
12363  */
12364 static void
12365 sfmmu_tlb_range_demap(demap_range_t *dmrp)
12366 {
12367 	sfmmu_t *sfmmup = dmrp->dmr_sfmmup;
12368 	hatlock_t *hatlockp;
12369 	cpuset_t cpuset;
12370 	uint64_t sfmmu_pgcnt;
12371 	pgcnt_t pgcnt = 0;
12372 	int pgunload = 0;
12373 	int dirtypg = 0;
12374 	caddr_t addr = dmrp->dmr_addr;
12375 	caddr_t eaddr;
12376 	uint64_t bitvec = dmrp->dmr_bitvec;
12377 
12378 	ASSERT(bitvec & 1);
12379 
12380 	/*
12381 	 * Flush TSB and calculate number of pages to flush.
12382 	 */
12383 	while (bitvec != 0) {
12384 		dirtypg = 0;
12385 		/*
12386 		 * Find the first page to flush and then count how many
12387 		 * pages there are after it that also need to be flushed.
12388 		 * This way the number of TSB flushes is minimized.
12389 		 */
12390 		while ((bitvec & 1) == 0) {
12391 			pgcnt++;
12392 			addr += MMU_PAGESIZE;
12393 			bitvec >>= 1;
12394 		}
12395 		while (bitvec & 1) {
12396 			dirtypg++;
12397 			bitvec >>= 1;
12398 		}
12399 		eaddr = addr + ptob(dirtypg);
12400 		hatlockp = sfmmu_hat_enter(sfmmup);
12401 		sfmmu_unload_tsb_range(sfmmup, addr, eaddr, TTE8K);
12402 		sfmmu_hat_exit(hatlockp);
12403 		pgunload += dirtypg;
12404 		addr = eaddr;
12405 		pgcnt += dirtypg;
12406 	}
12407 
12408 	ASSERT((pgcnt<<MMU_PAGESHIFT) <= dmrp->dmr_endaddr - dmrp->dmr_addr);
12409 	if (sfmmup->sfmmu_free == 0) {
12410 		addr = dmrp->dmr_addr;
12411 		bitvec = dmrp->dmr_bitvec;
12412 
12413 		/*
12414 		 * make sure it has SFMMU_PGCNT_SHIFT bits only,
12415 		 * as it will be used to pack argument for xt_some
12416 		 */
12417 		ASSERT((pgcnt > 0) &&
12418 		    (pgcnt <= (1 << SFMMU_PGCNT_SHIFT)));
12419 
12420 		/*
12421 		 * Encode pgcnt as (pgcnt -1 ), and pass (pgcnt - 1) in
12422 		 * the low 6 bits of sfmmup. This is doable since pgcnt
12423 		 * always >= 1.
12424 		 */
12425 		ASSERT(!((uint64_t)sfmmup & SFMMU_PGCNT_MASK));
12426 		sfmmu_pgcnt = (uint64_t)sfmmup |
12427 		    ((pgcnt - 1) & SFMMU_PGCNT_MASK);
12428 
12429 		/*
12430 		 * We must hold the hat lock during the flush of TLB,
12431 		 * to avoid a race with sfmmu_invalidate_ctx(), where
12432 		 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12433 		 * causing TLB demap routine to skip flush on that MMU.
12434 		 * If the context on a MMU has already been set to
12435 		 * INVALID_CONTEXT, we just get an extra flush on
12436 		 * that MMU.
12437 		 */
12438 		hatlockp = sfmmu_hat_enter(sfmmup);
12439 		kpreempt_disable();
12440 
12441 		cpuset = sfmmup->sfmmu_cpusran;
12442 		CPUSET_AND(cpuset, cpu_ready_set);
12443 		CPUSET_DEL(cpuset, CPU->cpu_id);
12444 
12445 		SFMMU_XCALL_STATS(sfmmup);
12446 		xt_some(cpuset, vtag_flush_pgcnt_tl1, (uint64_t)addr,
12447 		    sfmmu_pgcnt);
12448 
12449 		for (; bitvec != 0; bitvec >>= 1) {
12450 			if (bitvec & 1)
12451 				vtag_flushpage(addr, (uint64_t)sfmmup);
12452 			addr += MMU_PAGESIZE;
12453 		}
12454 		kpreempt_enable();
12455 		sfmmu_hat_exit(hatlockp);
12456 
12457 		sfmmu_xcall_save += (pgunload-1);
12458 	}
12459 	dmrp->dmr_bitvec = 0;
12460 }
12461 
12462 /*
12463  * In cases where we need to synchronize with TLB/TSB miss trap
12464  * handlers, _and_ need to flush the TLB, it's a lot easier to
12465  * throw away the context from the process than to do a
12466  * special song and dance to keep things consistent for the
12467  * handlers.
12468  *
12469  * Since the process suddenly ends up without a context and our caller
12470  * holds the hat lock, threads that fault after this function is called
12471  * will pile up on the lock.  We can then do whatever we need to
12472  * atomically from the context of the caller.  The first blocked thread
12473  * to resume executing will get the process a new context, and the
12474  * process will resume executing.
12475  *
12476  * One added advantage of this approach is that on MMUs that
12477  * support a "flush all" operation, we will delay the flush until
12478  * cnum wrap-around, and then flush the TLB one time.  This
12479  * is rather rare, so it's a lot less expensive than making 8000
12480  * x-calls to flush the TLB 8000 times.
12481  *
12482  * A per-process (PP) lock is used to synchronize ctx allocations in
12483  * resume() and ctx invalidations here.
12484  */
12485 static void
12486 sfmmu_invalidate_ctx(sfmmu_t *sfmmup)
12487 {
12488 	cpuset_t cpuset;
12489 	int cnum, currcnum;
12490 	mmu_ctx_t *mmu_ctxp;
12491 	int i;
12492 	uint_t pstate_save;
12493 
12494 	SFMMU_STAT(sf_ctx_inv);
12495 
12496 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12497 	ASSERT(sfmmup != ksfmmup);
12498 
12499 	kpreempt_disable();
12500 
12501 	mmu_ctxp = CPU_MMU_CTXP(CPU);
12502 	ASSERT(mmu_ctxp);
12503 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
12504 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
12505 
12506 	currcnum = sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum;
12507 
12508 	pstate_save = sfmmu_disable_intrs();
12509 
12510 	lock_set(&sfmmup->sfmmu_ctx_lock);	/* acquire PP lock */
12511 	/* set HAT cnum invalid across all context domains. */
12512 	for (i = 0; i < max_mmu_ctxdoms; i++) {
12513 
12514 		cnum = 	sfmmup->sfmmu_ctxs[i].cnum;
12515 		if (cnum == INVALID_CONTEXT) {
12516 			continue;
12517 		}
12518 
12519 		sfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
12520 	}
12521 	membar_enter();	/* make sure globally visible to all CPUs */
12522 	lock_clear(&sfmmup->sfmmu_ctx_lock);	/* release PP lock */
12523 
12524 	sfmmu_enable_intrs(pstate_save);
12525 
12526 	cpuset = sfmmup->sfmmu_cpusran;
12527 	CPUSET_DEL(cpuset, CPU->cpu_id);
12528 	CPUSET_AND(cpuset, cpu_ready_set);
12529 	if (!CPUSET_ISNULL(cpuset)) {
12530 		SFMMU_XCALL_STATS(sfmmup);
12531 		xt_some(cpuset, sfmmu_raise_tsb_exception,
12532 		    (uint64_t)sfmmup, INVALID_CONTEXT);
12533 		xt_sync(cpuset);
12534 		SFMMU_STAT(sf_tsb_raise_exception);
12535 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
12536 	}
12537 
12538 	/*
12539 	 * If the hat to-be-invalidated is the same as the current
12540 	 * process on local CPU we need to invalidate
12541 	 * this CPU context as well.
12542 	 */
12543 	if ((sfmmu_getctx_sec() == currcnum) &&
12544 	    (currcnum != INVALID_CONTEXT)) {
12545 		/* sets shared context to INVALID too */
12546 		sfmmu_setctx_sec(INVALID_CONTEXT);
12547 		sfmmu_clear_utsbinfo();
12548 	}
12549 
12550 	SFMMU_FLAGS_SET(sfmmup, HAT_ALLCTX_INVALID);
12551 
12552 	kpreempt_enable();
12553 
12554 	/*
12555 	 * we hold the hat lock, so nobody should allocate a context
12556 	 * for us yet
12557 	 */
12558 	ASSERT(sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum == INVALID_CONTEXT);
12559 }
12560 
12561 #ifdef VAC
12562 /*
12563  * We need to flush the cache in all cpus.  It is possible that
12564  * a process referenced a page as cacheable but has sinced exited
12565  * and cleared the mapping list.  We still to flush it but have no
12566  * state so all cpus is the only alternative.
12567  */
12568 void
12569 sfmmu_cache_flush(pfn_t pfnum, int vcolor)
12570 {
12571 	cpuset_t cpuset;
12572 
12573 	kpreempt_disable();
12574 	cpuset = cpu_ready_set;
12575 	CPUSET_DEL(cpuset, CPU->cpu_id);
12576 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12577 	xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12578 	xt_sync(cpuset);
12579 	vac_flushpage(pfnum, vcolor);
12580 	kpreempt_enable();
12581 }
12582 
12583 void
12584 sfmmu_cache_flushcolor(int vcolor, pfn_t pfnum)
12585 {
12586 	cpuset_t cpuset;
12587 
12588 	ASSERT(vcolor >= 0);
12589 
12590 	kpreempt_disable();
12591 	cpuset = cpu_ready_set;
12592 	CPUSET_DEL(cpuset, CPU->cpu_id);
12593 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12594 	xt_some(cpuset, vac_flushcolor_tl1, vcolor, pfnum);
12595 	xt_sync(cpuset);
12596 	vac_flushcolor(vcolor, pfnum);
12597 	kpreempt_enable();
12598 }
12599 #endif	/* VAC */
12600 
12601 /*
12602  * We need to prevent processes from accessing the TSB using a cached physical
12603  * address.  It's alright if they try to access the TSB via virtual address
12604  * since they will just fault on that virtual address once the mapping has
12605  * been suspended.
12606  */
12607 #pragma weak sendmondo_in_recover
12608 
12609 /* ARGSUSED */
12610 static int
12611 sfmmu_tsb_pre_relocator(caddr_t va, uint_t tsbsz, uint_t flags, void *tsbinfo)
12612 {
12613 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12614 	sfmmu_t *sfmmup = tsbinfop->tsb_sfmmu;
12615 	hatlock_t *hatlockp;
12616 	sf_scd_t *scdp;
12617 
12618 	if (flags != HAT_PRESUSPEND)
12619 		return (0);
12620 
12621 	/*
12622 	 * If tsb is a shared TSB with TSB_SHAREDCTX set, sfmmup must
12623 	 * be a shared hat, then set SCD's tsbinfo's flag.
12624 	 * If tsb is not shared, sfmmup is a private hat, then set
12625 	 * its private tsbinfo's flag.
12626 	 */
12627 	hatlockp = sfmmu_hat_enter(sfmmup);
12628 	tsbinfop->tsb_flags |= TSB_RELOC_FLAG;
12629 
12630 	if (!(tsbinfop->tsb_flags & TSB_SHAREDCTX)) {
12631 		sfmmu_tsb_inv_ctx(sfmmup);
12632 		sfmmu_hat_exit(hatlockp);
12633 	} else {
12634 		/* release lock on the shared hat */
12635 		sfmmu_hat_exit(hatlockp);
12636 		/* sfmmup is a shared hat */
12637 		ASSERT(sfmmup->sfmmu_scdhat);
12638 		scdp = sfmmup->sfmmu_scdp;
12639 		ASSERT(scdp != NULL);
12640 		/* get private hat from the scd list */
12641 		mutex_enter(&scdp->scd_mutex);
12642 		sfmmup = scdp->scd_sf_list;
12643 		while (sfmmup != NULL) {
12644 			hatlockp = sfmmu_hat_enter(sfmmup);
12645 			/*
12646 			 * We do not call sfmmu_tsb_inv_ctx here because
12647 			 * sendmondo_in_recover check is only needed for
12648 			 * sun4u.
12649 			 */
12650 			sfmmu_invalidate_ctx(sfmmup);
12651 			sfmmu_hat_exit(hatlockp);
12652 			sfmmup = sfmmup->sfmmu_scd_link.next;
12653 
12654 		}
12655 		mutex_exit(&scdp->scd_mutex);
12656 	}
12657 	return (0);
12658 }
12659 
12660 static void
12661 sfmmu_tsb_inv_ctx(sfmmu_t *sfmmup)
12662 {
12663 	extern uint32_t sendmondo_in_recover;
12664 
12665 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12666 
12667 	/*
12668 	 * For Cheetah+ Erratum 25:
12669 	 * Wait for any active recovery to finish.  We can't risk
12670 	 * relocating the TSB of the thread running mondo_recover_proc()
12671 	 * since, if we did that, we would deadlock.  The scenario we are
12672 	 * trying to avoid is as follows:
12673 	 *
12674 	 * THIS CPU			RECOVER CPU
12675 	 * --------			-----------
12676 	 *				Begins recovery, walking through TSB
12677 	 * hat_pagesuspend() TSB TTE
12678 	 *				TLB miss on TSB TTE, spins at TL1
12679 	 * xt_sync()
12680 	 *	send_mondo_timeout()
12681 	 *	mondo_recover_proc()
12682 	 *	((deadlocked))
12683 	 *
12684 	 * The second half of the workaround is that mondo_recover_proc()
12685 	 * checks to see if the tsb_info has the RELOC flag set, and if it
12686 	 * does, it skips over that TSB without ever touching tsbinfop->tsb_va
12687 	 * and hence avoiding the TLB miss that could result in a deadlock.
12688 	 */
12689 	if (&sendmondo_in_recover) {
12690 		membar_enter();	/* make sure RELOC flag visible */
12691 		while (sendmondo_in_recover) {
12692 			drv_usecwait(1);
12693 			membar_consumer();
12694 		}
12695 	}
12696 
12697 	sfmmu_invalidate_ctx(sfmmup);
12698 }
12699 
12700 /* ARGSUSED */
12701 static int
12702 sfmmu_tsb_post_relocator(caddr_t va, uint_t tsbsz, uint_t flags,
12703 	void *tsbinfo, pfn_t newpfn)
12704 {
12705 	hatlock_t *hatlockp;
12706 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12707 	sfmmu_t	*sfmmup = tsbinfop->tsb_sfmmu;
12708 
12709 	if (flags != HAT_POSTUNSUSPEND)
12710 		return (0);
12711 
12712 	hatlockp = sfmmu_hat_enter(sfmmup);
12713 
12714 	SFMMU_STAT(sf_tsb_reloc);
12715 
12716 	/*
12717 	 * The process may have swapped out while we were relocating one
12718 	 * of its TSBs.  If so, don't bother doing the setup since the
12719 	 * process can't be using the memory anymore.
12720 	 */
12721 	if ((tsbinfop->tsb_flags & TSB_SWAPPED) == 0) {
12722 		ASSERT(va == tsbinfop->tsb_va);
12723 		sfmmu_tsbinfo_setup_phys(tsbinfop, newpfn);
12724 
12725 		if (tsbinfop->tsb_flags & TSB_FLUSH_NEEDED) {
12726 			sfmmu_inv_tsb(tsbinfop->tsb_va,
12727 			    TSB_BYTES(tsbinfop->tsb_szc));
12728 			tsbinfop->tsb_flags &= ~TSB_FLUSH_NEEDED;
12729 		}
12730 	}
12731 
12732 	membar_exit();
12733 	tsbinfop->tsb_flags &= ~TSB_RELOC_FLAG;
12734 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
12735 
12736 	sfmmu_hat_exit(hatlockp);
12737 
12738 	return (0);
12739 }
12740 
12741 /*
12742  * Allocate and initialize a tsb_info structure.  Note that we may or may not
12743  * allocate a TSB here, depending on the flags passed in.
12744  */
12745 static int
12746 sfmmu_tsbinfo_alloc(struct tsb_info **tsbinfopp, int tsb_szc, int tte_sz_mask,
12747 	uint_t flags, sfmmu_t *sfmmup)
12748 {
12749 	int err;
12750 
12751 	*tsbinfopp = (struct tsb_info *)kmem_cache_alloc(
12752 	    sfmmu_tsbinfo_cache, KM_SLEEP);
12753 
12754 	if ((err = sfmmu_init_tsbinfo(*tsbinfopp, tte_sz_mask,
12755 	    tsb_szc, flags, sfmmup)) != 0) {
12756 		kmem_cache_free(sfmmu_tsbinfo_cache, *tsbinfopp);
12757 		SFMMU_STAT(sf_tsb_allocfail);
12758 		*tsbinfopp = NULL;
12759 		return (err);
12760 	}
12761 	SFMMU_STAT(sf_tsb_alloc);
12762 
12763 	/*
12764 	 * Bump the TSB size counters for this TSB size.
12765 	 */
12766 	(*(((int *)&sfmmu_tsbsize_stat) + tsb_szc))++;
12767 	return (0);
12768 }
12769 
12770 static void
12771 sfmmu_tsb_free(struct tsb_info *tsbinfo)
12772 {
12773 	caddr_t tsbva = tsbinfo->tsb_va;
12774 	uint_t tsb_size = TSB_BYTES(tsbinfo->tsb_szc);
12775 	struct kmem_cache *kmem_cachep = tsbinfo->tsb_cache;
12776 	vmem_t	*vmp = tsbinfo->tsb_vmp;
12777 
12778 	/*
12779 	 * If we allocated this TSB from relocatable kernel memory, then we
12780 	 * need to uninstall the callback handler.
12781 	 */
12782 	if (tsbinfo->tsb_cache != sfmmu_tsb8k_cache) {
12783 		uintptr_t slab_mask;
12784 		caddr_t slab_vaddr;
12785 		page_t **ppl;
12786 		int ret;
12787 
12788 		ASSERT(tsb_size <= MMU_PAGESIZE4M || use_bigtsb_arena);
12789 		if (tsb_size > MMU_PAGESIZE4M)
12790 			slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12791 		else
12792 			slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12793 		slab_vaddr = (caddr_t)((uintptr_t)tsbva & slab_mask);
12794 
12795 		ret = as_pagelock(&kas, &ppl, slab_vaddr, PAGESIZE, S_WRITE);
12796 		ASSERT(ret == 0);
12797 		hat_delete_callback(tsbva, (uint_t)tsb_size, (void *)tsbinfo,
12798 		    0, NULL);
12799 		as_pageunlock(&kas, ppl, slab_vaddr, PAGESIZE, S_WRITE);
12800 	}
12801 
12802 	if (kmem_cachep != NULL) {
12803 		kmem_cache_free(kmem_cachep, tsbva);
12804 	} else {
12805 		vmem_xfree(vmp, (void *)tsbva, tsb_size);
12806 	}
12807 	tsbinfo->tsb_va = (caddr_t)0xbad00bad;
12808 	atomic_add_64(&tsb_alloc_bytes, -(int64_t)tsb_size);
12809 }
12810 
12811 static void
12812 sfmmu_tsbinfo_free(struct tsb_info *tsbinfo)
12813 {
12814 	if ((tsbinfo->tsb_flags & TSB_SWAPPED) == 0) {
12815 		sfmmu_tsb_free(tsbinfo);
12816 	}
12817 	kmem_cache_free(sfmmu_tsbinfo_cache, tsbinfo);
12818 
12819 }
12820 
12821 /*
12822  * Setup all the references to physical memory for this tsbinfo.
12823  * The underlying page(s) must be locked.
12824  */
12825 static void
12826 sfmmu_tsbinfo_setup_phys(struct tsb_info *tsbinfo, pfn_t pfn)
12827 {
12828 	ASSERT(pfn != PFN_INVALID);
12829 	ASSERT(pfn == va_to_pfn(tsbinfo->tsb_va));
12830 
12831 #ifndef sun4v
12832 	if (tsbinfo->tsb_szc == 0) {
12833 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn,
12834 		    PROT_WRITE|PROT_READ, TTE8K);
12835 	} else {
12836 		/*
12837 		 * Round down PA and use a large mapping; the handlers will
12838 		 * compute the TSB pointer at the correct offset into the
12839 		 * big virtual page.  NOTE: this assumes all TSBs larger
12840 		 * than 8K must come from physically contiguous slabs of
12841 		 * size tsb_slab_size.
12842 		 */
12843 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn & ~tsb_slab_mask,
12844 		    PROT_WRITE|PROT_READ, tsb_slab_ttesz);
12845 	}
12846 	tsbinfo->tsb_pa = ptob(pfn);
12847 
12848 	TTE_SET_LOCKED(&tsbinfo->tsb_tte); /* lock the tte into dtlb */
12849 	TTE_SET_MOD(&tsbinfo->tsb_tte);    /* enable writes */
12850 
12851 	ASSERT(TTE_IS_PRIVILEGED(&tsbinfo->tsb_tte));
12852 	ASSERT(TTE_IS_LOCKED(&tsbinfo->tsb_tte));
12853 #else /* sun4v */
12854 	tsbinfo->tsb_pa = ptob(pfn);
12855 #endif /* sun4v */
12856 }
12857 
12858 
12859 /*
12860  * Returns zero on success, ENOMEM if over the high water mark,
12861  * or EAGAIN if the caller needs to retry with a smaller TSB
12862  * size (or specify TSB_FORCEALLOC if the allocation can't fail).
12863  *
12864  * This call cannot fail to allocate a TSB if TSB_FORCEALLOC
12865  * is specified and the TSB requested is PAGESIZE, though it
12866  * may sleep waiting for memory if sufficient memory is not
12867  * available.
12868  */
12869 static int
12870 sfmmu_init_tsbinfo(struct tsb_info *tsbinfo, int tteszmask,
12871     int tsbcode, uint_t flags, sfmmu_t *sfmmup)
12872 {
12873 	caddr_t vaddr = NULL;
12874 	caddr_t slab_vaddr;
12875 	uintptr_t slab_mask;
12876 	int tsbbytes = TSB_BYTES(tsbcode);
12877 	int lowmem = 0;
12878 	struct kmem_cache *kmem_cachep = NULL;
12879 	vmem_t *vmp = NULL;
12880 	lgrp_id_t lgrpid = LGRP_NONE;
12881 	pfn_t pfn;
12882 	uint_t cbflags = HAC_SLEEP;
12883 	page_t **pplist;
12884 	int ret;
12885 
12886 	ASSERT(tsbbytes <= MMU_PAGESIZE4M || use_bigtsb_arena);
12887 	if (tsbbytes > MMU_PAGESIZE4M)
12888 		slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12889 	else
12890 		slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12891 
12892 	if (flags & (TSB_FORCEALLOC | TSB_SWAPIN | TSB_GROW | TSB_SHRINK))
12893 		flags |= TSB_ALLOC;
12894 
12895 	ASSERT((flags & TSB_FORCEALLOC) == 0 || tsbcode == TSB_MIN_SZCODE);
12896 
12897 	tsbinfo->tsb_sfmmu = sfmmup;
12898 
12899 	/*
12900 	 * If not allocating a TSB, set up the tsbinfo, set TSB_SWAPPED, and
12901 	 * return.
12902 	 */
12903 	if ((flags & TSB_ALLOC) == 0) {
12904 		tsbinfo->tsb_szc = tsbcode;
12905 		tsbinfo->tsb_ttesz_mask = tteszmask;
12906 		tsbinfo->tsb_va = (caddr_t)0xbadbadbeef;
12907 		tsbinfo->tsb_pa = -1;
12908 		tsbinfo->tsb_tte.ll = 0;
12909 		tsbinfo->tsb_next = NULL;
12910 		tsbinfo->tsb_flags = TSB_SWAPPED;
12911 		tsbinfo->tsb_cache = NULL;
12912 		tsbinfo->tsb_vmp = NULL;
12913 		return (0);
12914 	}
12915 
12916 #ifdef DEBUG
12917 	/*
12918 	 * For debugging:
12919 	 * Randomly force allocation failures every tsb_alloc_mtbf
12920 	 * tries if TSB_FORCEALLOC is not specified.  This will
12921 	 * return ENOMEM if tsb_alloc_mtbf is odd, or EAGAIN if
12922 	 * it is even, to allow testing of both failure paths...
12923 	 */
12924 	if (tsb_alloc_mtbf && ((flags & TSB_FORCEALLOC) == 0) &&
12925 	    (tsb_alloc_count++ == tsb_alloc_mtbf)) {
12926 		tsb_alloc_count = 0;
12927 		tsb_alloc_fail_mtbf++;
12928 		return ((tsb_alloc_mtbf & 1)? ENOMEM : EAGAIN);
12929 	}
12930 #endif	/* DEBUG */
12931 
12932 	/*
12933 	 * Enforce high water mark if we are not doing a forced allocation
12934 	 * and are not shrinking a process' TSB.
12935 	 */
12936 	if ((flags & TSB_SHRINK) == 0 &&
12937 	    (tsbbytes + tsb_alloc_bytes) > tsb_alloc_hiwater) {
12938 		if ((flags & TSB_FORCEALLOC) == 0)
12939 			return (ENOMEM);
12940 		lowmem = 1;
12941 	}
12942 
12943 	/*
12944 	 * Allocate from the correct location based upon the size of the TSB
12945 	 * compared to the base page size, and what memory conditions dictate.
12946 	 * Note we always do nonblocking allocations from the TSB arena since
12947 	 * we don't want memory fragmentation to cause processes to block
12948 	 * indefinitely waiting for memory; until the kernel algorithms that
12949 	 * coalesce large pages are improved this is our best option.
12950 	 *
12951 	 * Algorithm:
12952 	 *	If allocating a "large" TSB (>8K), allocate from the
12953 	 *		appropriate kmem_tsb_default_arena vmem arena
12954 	 *	else if low on memory or the TSB_FORCEALLOC flag is set or
12955 	 *	tsb_forceheap is set
12956 	 *		Allocate from kernel heap via sfmmu_tsb8k_cache with
12957 	 *		KM_SLEEP (never fails)
12958 	 *	else
12959 	 *		Allocate from appropriate sfmmu_tsb_cache with
12960 	 *		KM_NOSLEEP
12961 	 *	endif
12962 	 */
12963 	if (tsb_lgrp_affinity)
12964 		lgrpid = lgrp_home_id(curthread);
12965 	if (lgrpid == LGRP_NONE)
12966 		lgrpid = 0;	/* use lgrp of boot CPU */
12967 
12968 	if (tsbbytes > MMU_PAGESIZE) {
12969 		if (tsbbytes > MMU_PAGESIZE4M) {
12970 			vmp = kmem_bigtsb_default_arena[lgrpid];
12971 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
12972 			    0, 0, NULL, NULL, VM_NOSLEEP);
12973 		} else {
12974 			vmp = kmem_tsb_default_arena[lgrpid];
12975 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
12976 			    0, 0, NULL, NULL, VM_NOSLEEP);
12977 		}
12978 #ifdef	DEBUG
12979 	} else if (lowmem || (flags & TSB_FORCEALLOC) || tsb_forceheap) {
12980 #else	/* !DEBUG */
12981 	} else if (lowmem || (flags & TSB_FORCEALLOC)) {
12982 #endif	/* DEBUG */
12983 		kmem_cachep = sfmmu_tsb8k_cache;
12984 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_SLEEP);
12985 		ASSERT(vaddr != NULL);
12986 	} else {
12987 		kmem_cachep = sfmmu_tsb_cache[lgrpid];
12988 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_NOSLEEP);
12989 	}
12990 
12991 	tsbinfo->tsb_cache = kmem_cachep;
12992 	tsbinfo->tsb_vmp = vmp;
12993 
12994 	if (vaddr == NULL) {
12995 		return (EAGAIN);
12996 	}
12997 
12998 	atomic_add_64(&tsb_alloc_bytes, (int64_t)tsbbytes);
12999 	kmem_cachep = tsbinfo->tsb_cache;
13000 
13001 	/*
13002 	 * If we are allocating from outside the cage, then we need to
13003 	 * register a relocation callback handler.  Note that for now
13004 	 * since pseudo mappings always hang off of the slab's root page,
13005 	 * we need only lock the first 8K of the TSB slab.  This is a bit
13006 	 * hacky but it is good for performance.
13007 	 */
13008 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13009 		slab_vaddr = (caddr_t)((uintptr_t)vaddr & slab_mask);
13010 		ret = as_pagelock(&kas, &pplist, slab_vaddr, PAGESIZE, S_WRITE);
13011 		ASSERT(ret == 0);
13012 		ret = hat_add_callback(sfmmu_tsb_cb_id, vaddr, (uint_t)tsbbytes,
13013 		    cbflags, (void *)tsbinfo, &pfn, NULL);
13014 
13015 		/*
13016 		 * Need to free up resources if we could not successfully
13017 		 * add the callback function and return an error condition.
13018 		 */
13019 		if (ret != 0) {
13020 			if (kmem_cachep) {
13021 				kmem_cache_free(kmem_cachep, vaddr);
13022 			} else {
13023 				vmem_xfree(vmp, (void *)vaddr, tsbbytes);
13024 			}
13025 			as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE,
13026 			    S_WRITE);
13027 			return (EAGAIN);
13028 		}
13029 	} else {
13030 		/*
13031 		 * Since allocation of 8K TSBs from heap is rare and occurs
13032 		 * during memory pressure we allocate them from permanent
13033 		 * memory rather than using callbacks to get the PFN.
13034 		 */
13035 		pfn = hat_getpfnum(kas.a_hat, vaddr);
13036 	}
13037 
13038 	tsbinfo->tsb_va = vaddr;
13039 	tsbinfo->tsb_szc = tsbcode;
13040 	tsbinfo->tsb_ttesz_mask = tteszmask;
13041 	tsbinfo->tsb_next = NULL;
13042 	tsbinfo->tsb_flags = 0;
13043 
13044 	sfmmu_tsbinfo_setup_phys(tsbinfo, pfn);
13045 
13046 	sfmmu_inv_tsb(vaddr, tsbbytes);
13047 
13048 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13049 		as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE, S_WRITE);
13050 	}
13051 
13052 	return (0);
13053 }
13054 
13055 /*
13056  * Initialize per cpu tsb and per cpu tsbmiss_area
13057  */
13058 void
13059 sfmmu_init_tsbs(void)
13060 {
13061 	int i;
13062 	struct tsbmiss	*tsbmissp;
13063 	struct kpmtsbm	*kpmtsbmp;
13064 #ifndef sun4v
13065 	extern int	dcache_line_mask;
13066 #endif /* sun4v */
13067 	extern uint_t	vac_colors;
13068 
13069 	/*
13070 	 * Init. tsb miss area.
13071 	 */
13072 	tsbmissp = tsbmiss_area;
13073 
13074 	for (i = 0; i < NCPU; tsbmissp++, i++) {
13075 		/*
13076 		 * initialize the tsbmiss area.
13077 		 * Do this for all possible CPUs as some may be added
13078 		 * while the system is running. There is no cost to this.
13079 		 */
13080 		tsbmissp->ksfmmup = ksfmmup;
13081 #ifndef sun4v
13082 		tsbmissp->dcache_line_mask = (uint16_t)dcache_line_mask;
13083 #endif /* sun4v */
13084 		tsbmissp->khashstart =
13085 		    (struct hmehash_bucket *)va_to_pa((caddr_t)khme_hash);
13086 		tsbmissp->uhashstart =
13087 		    (struct hmehash_bucket *)va_to_pa((caddr_t)uhme_hash);
13088 		tsbmissp->khashsz = khmehash_num;
13089 		tsbmissp->uhashsz = uhmehash_num;
13090 	}
13091 
13092 	sfmmu_tsb_cb_id = hat_register_callback('T'<<16 | 'S' << 8 | 'B',
13093 	    sfmmu_tsb_pre_relocator, sfmmu_tsb_post_relocator, NULL, 0);
13094 
13095 	if (kpm_enable == 0)
13096 		return;
13097 
13098 	/* -- Begin KPM specific init -- */
13099 
13100 	if (kpm_smallpages) {
13101 		/*
13102 		 * If we're using base pagesize pages for seg_kpm
13103 		 * mappings, we use the kernel TSB since we can't afford
13104 		 * to allocate a second huge TSB for these mappings.
13105 		 */
13106 		kpm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13107 		kpm_tsbsz = ktsb_szcode;
13108 		kpmsm_tsbbase = kpm_tsbbase;
13109 		kpmsm_tsbsz = kpm_tsbsz;
13110 	} else {
13111 		/*
13112 		 * In VAC conflict case, just put the entries in the
13113 		 * kernel 8K indexed TSB for now so we can find them.
13114 		 * This could really be changed in the future if we feel
13115 		 * the need...
13116 		 */
13117 		kpmsm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13118 		kpmsm_tsbsz = ktsb_szcode;
13119 		kpm_tsbbase = ktsb_phys? ktsb4m_pbase : (uint64_t)ktsb4m_base;
13120 		kpm_tsbsz = ktsb4m_szcode;
13121 	}
13122 
13123 	kpmtsbmp = kpmtsbm_area;
13124 	for (i = 0; i < NCPU; kpmtsbmp++, i++) {
13125 		/*
13126 		 * Initialize the kpmtsbm area.
13127 		 * Do this for all possible CPUs as some may be added
13128 		 * while the system is running. There is no cost to this.
13129 		 */
13130 		kpmtsbmp->vbase = kpm_vbase;
13131 		kpmtsbmp->vend = kpm_vbase + kpm_size * vac_colors;
13132 		kpmtsbmp->sz_shift = kpm_size_shift;
13133 		kpmtsbmp->kpmp_shift = kpmp_shift;
13134 		kpmtsbmp->kpmp2pshft = (uchar_t)kpmp2pshft;
13135 		if (kpm_smallpages == 0) {
13136 			kpmtsbmp->kpmp_table_sz = kpmp_table_sz;
13137 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_table);
13138 		} else {
13139 			kpmtsbmp->kpmp_table_sz = kpmp_stable_sz;
13140 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_stable);
13141 		}
13142 		kpmtsbmp->msegphashpa = va_to_pa(memseg_phash);
13143 		kpmtsbmp->flags = KPMTSBM_ENABLE_FLAG;
13144 #ifdef	DEBUG
13145 		kpmtsbmp->flags |= (kpm_tsbmtl) ?  KPMTSBM_TLTSBM_FLAG : 0;
13146 #endif	/* DEBUG */
13147 		if (ktsb_phys)
13148 			kpmtsbmp->flags |= KPMTSBM_TSBPHYS_FLAG;
13149 	}
13150 
13151 	/* -- End KPM specific init -- */
13152 }
13153 
13154 /* Avoid using sfmmu_tsbinfo_alloc() to avoid kmem_alloc - no real reason */
13155 struct tsb_info ktsb_info[2];
13156 
13157 /*
13158  * Called from hat_kern_setup() to setup the tsb_info for ksfmmup.
13159  */
13160 void
13161 sfmmu_init_ktsbinfo()
13162 {
13163 	ASSERT(ksfmmup != NULL);
13164 	ASSERT(ksfmmup->sfmmu_tsb == NULL);
13165 	/*
13166 	 * Allocate tsbinfos for kernel and copy in data
13167 	 * to make debug easier and sun4v setup easier.
13168 	 */
13169 	ktsb_info[0].tsb_sfmmu = ksfmmup;
13170 	ktsb_info[0].tsb_szc = ktsb_szcode;
13171 	ktsb_info[0].tsb_ttesz_mask = TSB8K|TSB64K|TSB512K;
13172 	ktsb_info[0].tsb_va = ktsb_base;
13173 	ktsb_info[0].tsb_pa = ktsb_pbase;
13174 	ktsb_info[0].tsb_flags = 0;
13175 	ktsb_info[0].tsb_tte.ll = 0;
13176 	ktsb_info[0].tsb_cache = NULL;
13177 
13178 	ktsb_info[1].tsb_sfmmu = ksfmmup;
13179 	ktsb_info[1].tsb_szc = ktsb4m_szcode;
13180 	ktsb_info[1].tsb_ttesz_mask = TSB4M;
13181 	ktsb_info[1].tsb_va = ktsb4m_base;
13182 	ktsb_info[1].tsb_pa = ktsb4m_pbase;
13183 	ktsb_info[1].tsb_flags = 0;
13184 	ktsb_info[1].tsb_tte.ll = 0;
13185 	ktsb_info[1].tsb_cache = NULL;
13186 
13187 	/* Link them into ksfmmup. */
13188 	ktsb_info[0].tsb_next = &ktsb_info[1];
13189 	ktsb_info[1].tsb_next = NULL;
13190 	ksfmmup->sfmmu_tsb = &ktsb_info[0];
13191 
13192 	sfmmu_setup_tsbinfo(ksfmmup);
13193 }
13194 
13195 /*
13196  * Cache the last value returned from va_to_pa().  If the VA specified
13197  * in the current call to cached_va_to_pa() maps to the same Page (as the
13198  * previous call to cached_va_to_pa()), then compute the PA using
13199  * cached info, else call va_to_pa().
13200  *
13201  * Note: this function is neither MT-safe nor consistent in the presence
13202  * of multiple, interleaved threads.  This function was created to enable
13203  * an optimization used during boot (at a point when there's only one thread
13204  * executing on the "boot CPU", and before startup_vm() has been called).
13205  */
13206 static uint64_t
13207 cached_va_to_pa(void *vaddr)
13208 {
13209 	static uint64_t prev_vaddr_base = 0;
13210 	static uint64_t prev_pfn = 0;
13211 
13212 	if ((((uint64_t)vaddr) & MMU_PAGEMASK) == prev_vaddr_base) {
13213 		return (prev_pfn | ((uint64_t)vaddr & MMU_PAGEOFFSET));
13214 	} else {
13215 		uint64_t pa = va_to_pa(vaddr);
13216 
13217 		if (pa != ((uint64_t)-1)) {
13218 			/*
13219 			 * Computed physical address is valid.  Cache its
13220 			 * related info for the next cached_va_to_pa() call.
13221 			 */
13222 			prev_pfn = pa & MMU_PAGEMASK;
13223 			prev_vaddr_base = ((uint64_t)vaddr) & MMU_PAGEMASK;
13224 		}
13225 
13226 		return (pa);
13227 	}
13228 }
13229 
13230 /*
13231  * Carve up our nucleus hblk region.  We may allocate more hblks than
13232  * asked due to rounding errors but we are guaranteed to have at least
13233  * enough space to allocate the requested number of hblk8's and hblk1's.
13234  */
13235 void
13236 sfmmu_init_nucleus_hblks(caddr_t addr, size_t size, int nhblk8, int nhblk1)
13237 {
13238 	struct hme_blk *hmeblkp;
13239 	size_t hme8blk_sz, hme1blk_sz;
13240 	size_t i;
13241 	size_t hblk8_bound;
13242 	ulong_t j = 0, k = 0;
13243 
13244 	ASSERT(addr != NULL && size != 0);
13245 
13246 	/* Need to use proper structure alignment */
13247 	hme8blk_sz = roundup(HME8BLK_SZ, sizeof (int64_t));
13248 	hme1blk_sz = roundup(HME1BLK_SZ, sizeof (int64_t));
13249 
13250 	nucleus_hblk8.list = (void *)addr;
13251 	nucleus_hblk8.index = 0;
13252 
13253 	/*
13254 	 * Use as much memory as possible for hblk8's since we
13255 	 * expect all bop_alloc'ed memory to be allocated in 8k chunks.
13256 	 * We need to hold back enough space for the hblk1's which
13257 	 * we'll allocate next.
13258 	 */
13259 	hblk8_bound = size - (nhblk1 * hme1blk_sz) - hme8blk_sz;
13260 	for (i = 0; i <= hblk8_bound; i += hme8blk_sz, j++) {
13261 		hmeblkp = (struct hme_blk *)addr;
13262 		addr += hme8blk_sz;
13263 		hmeblkp->hblk_nuc_bit = 1;
13264 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13265 	}
13266 	nucleus_hblk8.len = j;
13267 	ASSERT(j >= nhblk8);
13268 	SFMMU_STAT_ADD(sf_hblk8_ncreate, j);
13269 
13270 	nucleus_hblk1.list = (void *)addr;
13271 	nucleus_hblk1.index = 0;
13272 	for (; i <= (size - hme1blk_sz); i += hme1blk_sz, k++) {
13273 		hmeblkp = (struct hme_blk *)addr;
13274 		addr += hme1blk_sz;
13275 		hmeblkp->hblk_nuc_bit = 1;
13276 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13277 	}
13278 	ASSERT(k >= nhblk1);
13279 	nucleus_hblk1.len = k;
13280 	SFMMU_STAT_ADD(sf_hblk1_ncreate, k);
13281 }
13282 
13283 /*
13284  * This function is currently not supported on this platform. For what
13285  * it's supposed to do, see hat.c and hat_srmmu.c
13286  */
13287 /* ARGSUSED */
13288 faultcode_t
13289 hat_softlock(struct hat *hat, caddr_t addr, size_t *lenp, page_t **ppp,
13290     uint_t flags)
13291 {
13292 	ASSERT(hat->sfmmu_xhat_provider == NULL);
13293 	return (FC_NOSUPPORT);
13294 }
13295 
13296 /*
13297  * Searchs the mapping list of the page for a mapping of the same size. If not
13298  * found the corresponding bit is cleared in the p_index field. When large
13299  * pages are more prevalent in the system, we can maintain the mapping list
13300  * in order and we don't have to traverse the list each time. Just check the
13301  * next and prev entries, and if both are of different size, we clear the bit.
13302  */
13303 static void
13304 sfmmu_rm_large_mappings(page_t *pp, int ttesz)
13305 {
13306 	struct sf_hment *sfhmep;
13307 	struct hme_blk *hmeblkp;
13308 	int	index;
13309 	pgcnt_t	npgs;
13310 
13311 	ASSERT(ttesz > TTE8K);
13312 
13313 	ASSERT(sfmmu_mlist_held(pp));
13314 
13315 	ASSERT(PP_ISMAPPED_LARGE(pp));
13316 
13317 	/*
13318 	 * Traverse mapping list looking for another mapping of same size.
13319 	 * since we only want to clear index field if all mappings of
13320 	 * that size are gone.
13321 	 */
13322 
13323 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
13324 		hmeblkp = sfmmu_hmetohblk(sfhmep);
13325 		if (hmeblkp->hblk_xhat_bit)
13326 			continue;
13327 		if (hme_size(sfhmep) == ttesz) {
13328 			/*
13329 			 * another mapping of the same size. don't clear index.
13330 			 */
13331 			return;
13332 		}
13333 	}
13334 
13335 	/*
13336 	 * Clear the p_index bit for large page.
13337 	 */
13338 	index = PAGESZ_TO_INDEX(ttesz);
13339 	npgs = TTEPAGES(ttesz);
13340 	while (npgs-- > 0) {
13341 		ASSERT(pp->p_index & index);
13342 		pp->p_index &= ~index;
13343 		pp = PP_PAGENEXT(pp);
13344 	}
13345 }
13346 
13347 /*
13348  * return supported features
13349  */
13350 /* ARGSUSED */
13351 int
13352 hat_supported(enum hat_features feature, void *arg)
13353 {
13354 	switch (feature) {
13355 	case    HAT_SHARED_PT:
13356 	case	HAT_DYNAMIC_ISM_UNMAP:
13357 	case	HAT_VMODSORT:
13358 		return (1);
13359 	case	HAT_SHARED_REGIONS:
13360 		if (!disable_shctx && shctx_on)
13361 			return (1);
13362 		else
13363 			return (0);
13364 	default:
13365 		return (0);
13366 	}
13367 }
13368 
13369 void
13370 hat_enter(struct hat *hat)
13371 {
13372 	hatlock_t	*hatlockp;
13373 
13374 	if (hat != ksfmmup) {
13375 		hatlockp = TSB_HASH(hat);
13376 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
13377 	}
13378 }
13379 
13380 void
13381 hat_exit(struct hat *hat)
13382 {
13383 	hatlock_t	*hatlockp;
13384 
13385 	if (hat != ksfmmup) {
13386 		hatlockp = TSB_HASH(hat);
13387 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
13388 	}
13389 }
13390 
13391 /*ARGSUSED*/
13392 void
13393 hat_reserve(struct as *as, caddr_t addr, size_t len)
13394 {
13395 }
13396 
13397 static void
13398 hat_kstat_init(void)
13399 {
13400 	kstat_t *ksp;
13401 
13402 	ksp = kstat_create("unix", 0, "sfmmu_global_stat", "hat",
13403 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_global_stat),
13404 	    KSTAT_FLAG_VIRTUAL);
13405 	if (ksp) {
13406 		ksp->ks_data = (void *) &sfmmu_global_stat;
13407 		kstat_install(ksp);
13408 	}
13409 	ksp = kstat_create("unix", 0, "sfmmu_tsbsize_stat", "hat",
13410 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_tsbsize_stat),
13411 	    KSTAT_FLAG_VIRTUAL);
13412 	if (ksp) {
13413 		ksp->ks_data = (void *) &sfmmu_tsbsize_stat;
13414 		kstat_install(ksp);
13415 	}
13416 	ksp = kstat_create("unix", 0, "sfmmu_percpu_stat", "hat",
13417 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_percpu_stat) * NCPU,
13418 	    KSTAT_FLAG_WRITABLE);
13419 	if (ksp) {
13420 		ksp->ks_update = sfmmu_kstat_percpu_update;
13421 		kstat_install(ksp);
13422 	}
13423 }
13424 
13425 /* ARGSUSED */
13426 static int
13427 sfmmu_kstat_percpu_update(kstat_t *ksp, int rw)
13428 {
13429 	struct sfmmu_percpu_stat *cpu_kstat = ksp->ks_data;
13430 	struct tsbmiss *tsbm = tsbmiss_area;
13431 	struct kpmtsbm *kpmtsbm = kpmtsbm_area;
13432 	int i;
13433 
13434 	ASSERT(cpu_kstat);
13435 	if (rw == KSTAT_READ) {
13436 		for (i = 0; i < NCPU; cpu_kstat++, tsbm++, kpmtsbm++, i++) {
13437 			cpu_kstat->sf_itlb_misses = 0;
13438 			cpu_kstat->sf_dtlb_misses = 0;
13439 			cpu_kstat->sf_utsb_misses = tsbm->utsb_misses -
13440 			    tsbm->uprot_traps;
13441 			cpu_kstat->sf_ktsb_misses = tsbm->ktsb_misses +
13442 			    kpmtsbm->kpm_tsb_misses - tsbm->kprot_traps;
13443 			cpu_kstat->sf_tsb_hits = 0;
13444 			cpu_kstat->sf_umod_faults = tsbm->uprot_traps;
13445 			cpu_kstat->sf_kmod_faults = tsbm->kprot_traps;
13446 		}
13447 	} else {
13448 		/* KSTAT_WRITE is used to clear stats */
13449 		for (i = 0; i < NCPU; tsbm++, kpmtsbm++, i++) {
13450 			tsbm->utsb_misses = 0;
13451 			tsbm->ktsb_misses = 0;
13452 			tsbm->uprot_traps = 0;
13453 			tsbm->kprot_traps = 0;
13454 			kpmtsbm->kpm_dtlb_misses = 0;
13455 			kpmtsbm->kpm_tsb_misses = 0;
13456 		}
13457 	}
13458 	return (0);
13459 }
13460 
13461 #ifdef	DEBUG
13462 
13463 tte_t  *gorig[NCPU], *gcur[NCPU], *gnew[NCPU];
13464 
13465 /*
13466  * A tte checker. *orig_old is the value we read before cas.
13467  *	*cur is the value returned by cas.
13468  *	*new is the desired value when we do the cas.
13469  *
13470  *	*hmeblkp is currently unused.
13471  */
13472 
13473 /* ARGSUSED */
13474 void
13475 chk_tte(tte_t *orig_old, tte_t *cur, tte_t *new, struct hme_blk *hmeblkp)
13476 {
13477 	pfn_t i, j, k;
13478 	int cpuid = CPU->cpu_id;
13479 
13480 	gorig[cpuid] = orig_old;
13481 	gcur[cpuid] = cur;
13482 	gnew[cpuid] = new;
13483 
13484 #ifdef lint
13485 	hmeblkp = hmeblkp;
13486 #endif
13487 
13488 	if (TTE_IS_VALID(orig_old)) {
13489 		if (TTE_IS_VALID(cur)) {
13490 			i = TTE_TO_TTEPFN(orig_old);
13491 			j = TTE_TO_TTEPFN(cur);
13492 			k = TTE_TO_TTEPFN(new);
13493 			if (i != j) {
13494 				/* remap error? */
13495 				panic("chk_tte: bad pfn, 0x%lx, 0x%lx", i, j);
13496 			}
13497 
13498 			if (i != k) {
13499 				/* remap error? */
13500 				panic("chk_tte: bad pfn2, 0x%lx, 0x%lx", i, k);
13501 			}
13502 		} else {
13503 			if (TTE_IS_VALID(new)) {
13504 				panic("chk_tte: invalid cur? ");
13505 			}
13506 
13507 			i = TTE_TO_TTEPFN(orig_old);
13508 			k = TTE_TO_TTEPFN(new);
13509 			if (i != k) {
13510 				panic("chk_tte: bad pfn3, 0x%lx, 0x%lx", i, k);
13511 			}
13512 		}
13513 	} else {
13514 		if (TTE_IS_VALID(cur)) {
13515 			j = TTE_TO_TTEPFN(cur);
13516 			if (TTE_IS_VALID(new)) {
13517 				k = TTE_TO_TTEPFN(new);
13518 				if (j != k) {
13519 					panic("chk_tte: bad pfn4, 0x%lx, 0x%lx",
13520 					    j, k);
13521 				}
13522 			} else {
13523 				panic("chk_tte: why here?");
13524 			}
13525 		} else {
13526 			if (!TTE_IS_VALID(new)) {
13527 				panic("chk_tte: why here2 ?");
13528 			}
13529 		}
13530 	}
13531 }
13532 
13533 #endif /* DEBUG */
13534 
13535 extern void prefetch_tsbe_read(struct tsbe *);
13536 extern void prefetch_tsbe_write(struct tsbe *);
13537 
13538 
13539 /*
13540  * We want to prefetch 7 cache lines ahead for our read prefetch.  This gives
13541  * us optimal performance on Cheetah+.  You can only have 8 outstanding
13542  * prefetches at any one time, so we opted for 7 read prefetches and 1 write
13543  * prefetch to make the most utilization of the prefetch capability.
13544  */
13545 #define	TSBE_PREFETCH_STRIDE (7)
13546 
13547 void
13548 sfmmu_copy_tsb(struct tsb_info *old_tsbinfo, struct tsb_info *new_tsbinfo)
13549 {
13550 	int old_bytes = TSB_BYTES(old_tsbinfo->tsb_szc);
13551 	int new_bytes = TSB_BYTES(new_tsbinfo->tsb_szc);
13552 	int old_entries = TSB_ENTRIES(old_tsbinfo->tsb_szc);
13553 	int new_entries = TSB_ENTRIES(new_tsbinfo->tsb_szc);
13554 	struct tsbe *old;
13555 	struct tsbe *new;
13556 	struct tsbe *new_base = (struct tsbe *)new_tsbinfo->tsb_va;
13557 	uint64_t va;
13558 	int new_offset;
13559 	int i;
13560 	int vpshift;
13561 	int last_prefetch;
13562 
13563 	if (old_bytes == new_bytes) {
13564 		bcopy(old_tsbinfo->tsb_va, new_tsbinfo->tsb_va, new_bytes);
13565 	} else {
13566 
13567 		/*
13568 		 * A TSBE is 16 bytes which means there are four TSBE's per
13569 		 * P$ line (64 bytes), thus every 4 TSBE's we prefetch.
13570 		 */
13571 		old = (struct tsbe *)old_tsbinfo->tsb_va;
13572 		last_prefetch = old_entries - (4*(TSBE_PREFETCH_STRIDE+1));
13573 		for (i = 0; i < old_entries; i++, old++) {
13574 			if (((i & (4-1)) == 0) && (i < last_prefetch))
13575 				prefetch_tsbe_read(old);
13576 			if (!old->tte_tag.tag_invalid) {
13577 				/*
13578 				 * We have a valid TTE to remap.  Check the
13579 				 * size.  We won't remap 64K or 512K TTEs
13580 				 * because they span more than one TSB entry
13581 				 * and are indexed using an 8K virt. page.
13582 				 * Ditto for 32M and 256M TTEs.
13583 				 */
13584 				if (TTE_CSZ(&old->tte_data) == TTE64K ||
13585 				    TTE_CSZ(&old->tte_data) == TTE512K)
13586 					continue;
13587 				if (mmu_page_sizes == max_mmu_page_sizes) {
13588 					if (TTE_CSZ(&old->tte_data) == TTE32M ||
13589 					    TTE_CSZ(&old->tte_data) == TTE256M)
13590 						continue;
13591 				}
13592 
13593 				/* clear the lower 22 bits of the va */
13594 				va = *(uint64_t *)old << 22;
13595 				/* turn va into a virtual pfn */
13596 				va >>= 22 - TSB_START_SIZE;
13597 				/*
13598 				 * or in bits from the offset in the tsb
13599 				 * to get the real virtual pfn. These
13600 				 * correspond to bits [21:13] in the va
13601 				 */
13602 				vpshift =
13603 				    TTE_BSZS_SHIFT(TTE_CSZ(&old->tte_data)) &
13604 				    0x1ff;
13605 				va |= (i << vpshift);
13606 				va >>= vpshift;
13607 				new_offset = va & (new_entries - 1);
13608 				new = new_base + new_offset;
13609 				prefetch_tsbe_write(new);
13610 				*new = *old;
13611 			}
13612 		}
13613 	}
13614 }
13615 
13616 /*
13617  * unused in sfmmu
13618  */
13619 void
13620 hat_dump(void)
13621 {
13622 }
13623 
13624 /*
13625  * Called when a thread is exiting and we have switched to the kernel address
13626  * space.  Perform the same VM initialization resume() uses when switching
13627  * processes.
13628  *
13629  * Note that sfmmu_load_mmustate() is currently a no-op for kernel threads, but
13630  * we call it anyway in case the semantics change in the future.
13631  */
13632 /*ARGSUSED*/
13633 void
13634 hat_thread_exit(kthread_t *thd)
13635 {
13636 	uint_t pgsz_cnum;
13637 	uint_t pstate_save;
13638 
13639 	ASSERT(thd->t_procp->p_as == &kas);
13640 
13641 	pgsz_cnum = KCONTEXT;
13642 #ifdef sun4u
13643 	pgsz_cnum |= (ksfmmup->sfmmu_cext << CTXREG_EXT_SHIFT);
13644 #endif
13645 
13646 	/*
13647 	 * Note that sfmmu_load_mmustate() is currently a no-op for
13648 	 * kernel threads. We need to disable interrupts here,
13649 	 * simply because otherwise sfmmu_load_mmustate() would panic
13650 	 * if the caller does not disable interrupts.
13651 	 */
13652 	pstate_save = sfmmu_disable_intrs();
13653 
13654 	/* Compatibility Note: hw takes care of MMU_SCONTEXT1 */
13655 	sfmmu_setctx_sec(pgsz_cnum);
13656 	sfmmu_load_mmustate(ksfmmup);
13657 	sfmmu_enable_intrs(pstate_save);
13658 }
13659 
13660 
13661 /*
13662  * SRD support
13663  */
13664 #define	SRD_HASH_FUNCTION(vp)	(((((uintptr_t)(vp)) >> 4) ^ \
13665 				    (((uintptr_t)(vp)) >> 11)) & \
13666 				    srd_hashmask)
13667 
13668 /*
13669  * Attach the process to the srd struct associated with the exec vnode
13670  * from which the process is started.
13671  */
13672 void
13673 hat_join_srd(struct hat *sfmmup, vnode_t *evp)
13674 {
13675 	uint_t hash = SRD_HASH_FUNCTION(evp);
13676 	sf_srd_t *srdp;
13677 	sf_srd_t *newsrdp;
13678 
13679 	ASSERT(sfmmup != ksfmmup);
13680 	ASSERT(sfmmup->sfmmu_srdp == NULL);
13681 
13682 	if (disable_shctx || !shctx_on) {
13683 		return;
13684 	}
13685 
13686 	VN_HOLD(evp);
13687 
13688 	if (srd_buckets[hash].srdb_srdp != NULL) {
13689 		mutex_enter(&srd_buckets[hash].srdb_lock);
13690 		for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13691 		    srdp = srdp->srd_hash) {
13692 			if (srdp->srd_evp == evp) {
13693 				ASSERT(srdp->srd_refcnt >= 0);
13694 				sfmmup->sfmmu_srdp = srdp;
13695 				atomic_add_32(
13696 				    (volatile uint_t *)&srdp->srd_refcnt, 1);
13697 				mutex_exit(&srd_buckets[hash].srdb_lock);
13698 				return;
13699 			}
13700 		}
13701 		mutex_exit(&srd_buckets[hash].srdb_lock);
13702 	}
13703 	newsrdp = kmem_cache_alloc(srd_cache, KM_SLEEP);
13704 	ASSERT(newsrdp->srd_next_ismrid == 0 && newsrdp->srd_next_hmerid == 0);
13705 
13706 	newsrdp->srd_evp = evp;
13707 	newsrdp->srd_refcnt = 1;
13708 	newsrdp->srd_hmergnfree = NULL;
13709 	newsrdp->srd_ismrgnfree = NULL;
13710 
13711 	mutex_enter(&srd_buckets[hash].srdb_lock);
13712 	for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13713 	    srdp = srdp->srd_hash) {
13714 		if (srdp->srd_evp == evp) {
13715 			ASSERT(srdp->srd_refcnt >= 0);
13716 			sfmmup->sfmmu_srdp = srdp;
13717 			atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
13718 			mutex_exit(&srd_buckets[hash].srdb_lock);
13719 			kmem_cache_free(srd_cache, newsrdp);
13720 			return;
13721 		}
13722 	}
13723 	newsrdp->srd_hash = srd_buckets[hash].srdb_srdp;
13724 	srd_buckets[hash].srdb_srdp = newsrdp;
13725 	sfmmup->sfmmu_srdp = newsrdp;
13726 
13727 	mutex_exit(&srd_buckets[hash].srdb_lock);
13728 
13729 }
13730 
13731 static void
13732 sfmmu_leave_srd(sfmmu_t *sfmmup)
13733 {
13734 	vnode_t *evp;
13735 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13736 	uint_t hash;
13737 	sf_srd_t **prev_srdpp;
13738 	sf_region_t *rgnp;
13739 	sf_region_t *nrgnp;
13740 #ifdef DEBUG
13741 	int rgns = 0;
13742 #endif
13743 	int i;
13744 
13745 	ASSERT(sfmmup != ksfmmup);
13746 	ASSERT(srdp != NULL);
13747 	ASSERT(srdp->srd_refcnt > 0);
13748 	ASSERT(sfmmup->sfmmu_scdp == NULL);
13749 	ASSERT(sfmmup->sfmmu_free == 1);
13750 
13751 	sfmmup->sfmmu_srdp = NULL;
13752 	evp = srdp->srd_evp;
13753 	ASSERT(evp != NULL);
13754 	if (atomic_add_32_nv(
13755 	    (volatile uint_t *)&srdp->srd_refcnt, -1)) {
13756 		VN_RELE(evp);
13757 		return;
13758 	}
13759 
13760 	hash = SRD_HASH_FUNCTION(evp);
13761 	mutex_enter(&srd_buckets[hash].srdb_lock);
13762 	for (prev_srdpp = &srd_buckets[hash].srdb_srdp;
13763 	    (srdp = *prev_srdpp) != NULL; prev_srdpp = &srdp->srd_hash) {
13764 		if (srdp->srd_evp == evp) {
13765 			break;
13766 		}
13767 	}
13768 	if (srdp == NULL || srdp->srd_refcnt) {
13769 		mutex_exit(&srd_buckets[hash].srdb_lock);
13770 		VN_RELE(evp);
13771 		return;
13772 	}
13773 	*prev_srdpp = srdp->srd_hash;
13774 	mutex_exit(&srd_buckets[hash].srdb_lock);
13775 
13776 	ASSERT(srdp->srd_refcnt == 0);
13777 	VN_RELE(evp);
13778 
13779 #ifdef DEBUG
13780 	for (i = 0; i < SFMMU_MAX_REGION_BUCKETS; i++) {
13781 		ASSERT(srdp->srd_rgnhash[i] == NULL);
13782 	}
13783 #endif /* DEBUG */
13784 
13785 	/* free each hme regions in the srd */
13786 	for (rgnp = srdp->srd_hmergnfree; rgnp != NULL; rgnp = nrgnp) {
13787 		nrgnp = rgnp->rgn_next;
13788 		ASSERT(rgnp->rgn_id < srdp->srd_next_hmerid);
13789 		ASSERT(rgnp->rgn_refcnt == 0);
13790 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13791 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13792 		ASSERT(rgnp->rgn_hmeflags == 0);
13793 		ASSERT(srdp->srd_hmergnp[rgnp->rgn_id] == rgnp);
13794 #ifdef DEBUG
13795 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13796 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13797 		}
13798 		rgns++;
13799 #endif /* DEBUG */
13800 		kmem_cache_free(region_cache, rgnp);
13801 	}
13802 	ASSERT(rgns == srdp->srd_next_hmerid);
13803 
13804 #ifdef DEBUG
13805 	rgns = 0;
13806 #endif
13807 	/* free each ism rgns in the srd */
13808 	for (rgnp = srdp->srd_ismrgnfree; rgnp != NULL; rgnp = nrgnp) {
13809 		nrgnp = rgnp->rgn_next;
13810 		ASSERT(rgnp->rgn_id < srdp->srd_next_ismrid);
13811 		ASSERT(rgnp->rgn_refcnt == 0);
13812 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13813 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13814 		ASSERT(srdp->srd_ismrgnp[rgnp->rgn_id] == rgnp);
13815 #ifdef DEBUG
13816 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13817 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13818 		}
13819 		rgns++;
13820 #endif /* DEBUG */
13821 		kmem_cache_free(region_cache, rgnp);
13822 	}
13823 	ASSERT(rgns == srdp->srd_next_ismrid);
13824 	ASSERT(srdp->srd_ismbusyrgns == 0);
13825 	ASSERT(srdp->srd_hmebusyrgns == 0);
13826 
13827 	srdp->srd_next_ismrid = 0;
13828 	srdp->srd_next_hmerid = 0;
13829 
13830 	bzero((void *)srdp->srd_ismrgnp,
13831 	    sizeof (sf_region_t *) * SFMMU_MAX_ISM_REGIONS);
13832 	bzero((void *)srdp->srd_hmergnp,
13833 	    sizeof (sf_region_t *) * SFMMU_MAX_HME_REGIONS);
13834 
13835 	ASSERT(srdp->srd_scdp == NULL);
13836 	kmem_cache_free(srd_cache, srdp);
13837 }
13838 
13839 /* ARGSUSED */
13840 static int
13841 sfmmu_srdcache_constructor(void *buf, void *cdrarg, int kmflags)
13842 {
13843 	sf_srd_t *srdp = (sf_srd_t *)buf;
13844 	bzero(buf, sizeof (*srdp));
13845 
13846 	mutex_init(&srdp->srd_mutex, NULL, MUTEX_DEFAULT, NULL);
13847 	mutex_init(&srdp->srd_scd_mutex, NULL, MUTEX_DEFAULT, NULL);
13848 	return (0);
13849 }
13850 
13851 /* ARGSUSED */
13852 static void
13853 sfmmu_srdcache_destructor(void *buf, void *cdrarg)
13854 {
13855 	sf_srd_t *srdp = (sf_srd_t *)buf;
13856 
13857 	mutex_destroy(&srdp->srd_mutex);
13858 	mutex_destroy(&srdp->srd_scd_mutex);
13859 }
13860 
13861 /*
13862  * The caller makes sure hat_join_region()/hat_leave_region() can't be called
13863  * at the same time for the same process and address range. This is ensured by
13864  * the fact that address space is locked as writer when a process joins the
13865  * regions. Therefore there's no need to hold an srd lock during the entire
13866  * execution of hat_join_region()/hat_leave_region().
13867  */
13868 
13869 #define	RGN_HASH_FUNCTION(obj)	(((((uintptr_t)(obj)) >> 4) ^ \
13870 				    (((uintptr_t)(obj)) >> 11)) & \
13871 					srd_rgn_hashmask)
13872 /*
13873  * This routine implements the shared context functionality required when
13874  * attaching a segment to an address space. It must be called from
13875  * hat_share() for D(ISM) segments and from segvn_create() for segments
13876  * with the MAP_PRIVATE and MAP_TEXT flags set. It returns a region_cookie
13877  * which is saved in the private segment data for hme segments and
13878  * the ism_map structure for ism segments.
13879  */
13880 hat_region_cookie_t
13881 hat_join_region(struct hat *sfmmup,
13882 	caddr_t r_saddr,
13883 	size_t r_size,
13884 	void *r_obj,
13885 	u_offset_t r_objoff,
13886 	uchar_t r_perm,
13887 	uchar_t r_pgszc,
13888 	hat_rgn_cb_func_t r_cb_function,
13889 	uint_t flags)
13890 {
13891 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13892 	uint_t rhash;
13893 	uint_t rid;
13894 	hatlock_t *hatlockp;
13895 	sf_region_t *rgnp;
13896 	sf_region_t *new_rgnp = NULL;
13897 	int i;
13898 	uint16_t *nextidp;
13899 	sf_region_t **freelistp;
13900 	int maxids;
13901 	sf_region_t **rarrp;
13902 	uint16_t *busyrgnsp;
13903 	ulong_t rttecnt;
13904 	int rkmalloc = 0;
13905 	uchar_t tteflag;
13906 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
13907 	int text = (r_type == HAT_REGION_TEXT);
13908 
13909 	if (srdp == NULL || r_size == 0) {
13910 		return (HAT_INVALID_REGION_COOKIE);
13911 	}
13912 
13913 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
13914 	ASSERT(sfmmup != ksfmmup);
13915 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
13916 	ASSERT(srdp->srd_refcnt > 0);
13917 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
13918 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
13919 	ASSERT(r_pgszc < mmu_page_sizes);
13920 	if (!IS_P2ALIGNED(r_saddr, TTEBYTES(r_pgszc)) ||
13921 	    !IS_P2ALIGNED(r_size, TTEBYTES(r_pgszc))) {
13922 		panic("hat_join_region: region addr or size is not aligned\n");
13923 	}
13924 
13925 
13926 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
13927 	    SFMMU_REGION_HME;
13928 	/*
13929 	 * Currently only support shared hmes for the main text region.
13930 	 */
13931 	if (r_type == SFMMU_REGION_HME && r_obj != srdp->srd_evp) {
13932 		return (HAT_INVALID_REGION_COOKIE);
13933 	}
13934 
13935 	rhash = RGN_HASH_FUNCTION(r_obj);
13936 
13937 	if (r_type == SFMMU_REGION_ISM) {
13938 		nextidp = &srdp->srd_next_ismrid;
13939 		freelistp = &srdp->srd_ismrgnfree;
13940 		maxids = SFMMU_MAX_ISM_REGIONS;
13941 		rarrp = srdp->srd_ismrgnp;
13942 		busyrgnsp = &srdp->srd_ismbusyrgns;
13943 	} else {
13944 		nextidp = &srdp->srd_next_hmerid;
13945 		freelistp = &srdp->srd_hmergnfree;
13946 		maxids = SFMMU_MAX_HME_REGIONS;
13947 		rarrp = srdp->srd_hmergnp;
13948 		busyrgnsp = &srdp->srd_hmebusyrgns;
13949 	}
13950 
13951 	mutex_enter(&srdp->srd_mutex);
13952 
13953 	for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
13954 	    rgnp = rgnp->rgn_hash) {
13955 		if (rgnp->rgn_saddr == r_saddr && rgnp->rgn_size == r_size &&
13956 		    rgnp->rgn_obj == r_obj && rgnp->rgn_objoff == r_objoff &&
13957 		    rgnp->rgn_perm == r_perm && rgnp->rgn_pgszc == r_pgszc) {
13958 			break;
13959 		}
13960 	}
13961 
13962 rfound:
13963 	if (rgnp != NULL) {
13964 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
13965 		ASSERT(rgnp->rgn_cb_function == r_cb_function);
13966 		ASSERT(rgnp->rgn_refcnt >= 0);
13967 		rid = rgnp->rgn_id;
13968 		ASSERT(rid < maxids);
13969 		ASSERT(rarrp[rid] == rgnp);
13970 		ASSERT(rid < *nextidp);
13971 		atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
13972 		mutex_exit(&srdp->srd_mutex);
13973 		if (new_rgnp != NULL) {
13974 			kmem_cache_free(region_cache, new_rgnp);
13975 		}
13976 		if (r_type == SFMMU_REGION_HME) {
13977 			int myjoin =
13978 			    (sfmmup == astosfmmu(curthread->t_procp->p_as));
13979 
13980 			sfmmu_link_to_hmeregion(sfmmup, rgnp);
13981 			/*
13982 			 * bitmap should be updated after linking sfmmu on
13983 			 * region list so that pageunload() doesn't skip
13984 			 * TSB/TLB flush. As soon as bitmap is updated another
13985 			 * thread in this process can already start accessing
13986 			 * this region.
13987 			 */
13988 			/*
13989 			 * Normally ttecnt accounting is done as part of
13990 			 * pagefault handling. But a process may not take any
13991 			 * pagefaults on shared hmeblks created by some other
13992 			 * process. To compensate for this assume that the
13993 			 * entire region will end up faulted in using
13994 			 * the region's pagesize.
13995 			 *
13996 			 */
13997 			if (r_pgszc > TTE8K) {
13998 				tteflag = 1 << r_pgszc;
13999 				if (disable_large_pages & tteflag) {
14000 					tteflag = 0;
14001 				}
14002 			} else {
14003 				tteflag = 0;
14004 			}
14005 			if (tteflag && !(sfmmup->sfmmu_rtteflags & tteflag)) {
14006 				hatlockp = sfmmu_hat_enter(sfmmup);
14007 				sfmmup->sfmmu_rtteflags |= tteflag;
14008 				sfmmu_hat_exit(hatlockp);
14009 			}
14010 			hatlockp = sfmmu_hat_enter(sfmmup);
14011 
14012 			/*
14013 			 * Preallocate 1/4 of ttecnt's in 8K TSB for >= 4M
14014 			 * region to allow for large page allocation failure.
14015 			 */
14016 			if (r_pgszc >= TTE4M) {
14017 				sfmmup->sfmmu_tsb0_4minflcnt +=
14018 				    r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14019 			}
14020 
14021 			/* update sfmmu_ttecnt with the shme rgn ttecnt */
14022 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14023 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14024 			    rttecnt);
14025 
14026 			if (text && r_pgszc >= TTE4M &&
14027 			    (tteflag || ((disable_large_pages >> TTE4M) &
14028 			    ((1 << (r_pgszc - TTE4M + 1)) - 1))) &&
14029 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
14030 				SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
14031 			}
14032 
14033 			sfmmu_hat_exit(hatlockp);
14034 			/*
14035 			 * On Panther we need to make sure TLB is programmed
14036 			 * to accept 32M/256M pages.  Call
14037 			 * sfmmu_check_page_sizes() now to make sure TLB is
14038 			 * setup before making hmeregions visible to other
14039 			 * threads.
14040 			 */
14041 			sfmmu_check_page_sizes(sfmmup, 1);
14042 			hatlockp = sfmmu_hat_enter(sfmmup);
14043 			SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14044 
14045 			/*
14046 			 * if context is invalid tsb miss exception code will
14047 			 * call sfmmu_check_page_sizes() and update tsbmiss
14048 			 * area later.
14049 			 */
14050 			kpreempt_disable();
14051 			if (myjoin &&
14052 			    (sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
14053 			    != INVALID_CONTEXT)) {
14054 				struct tsbmiss *tsbmp;
14055 
14056 				tsbmp = &tsbmiss_area[CPU->cpu_id];
14057 				ASSERT(sfmmup == tsbmp->usfmmup);
14058 				BT_SET(tsbmp->shmermap, rid);
14059 				if (r_pgszc > TTE64K) {
14060 					tsbmp->uhat_rtteflags |= tteflag;
14061 				}
14062 
14063 			}
14064 			kpreempt_enable();
14065 
14066 			sfmmu_hat_exit(hatlockp);
14067 			ASSERT((hat_region_cookie_t)((uint64_t)rid) !=
14068 			    HAT_INVALID_REGION_COOKIE);
14069 		} else {
14070 			hatlockp = sfmmu_hat_enter(sfmmup);
14071 			SF_RGNMAP_ADD(sfmmup->sfmmu_ismregion_map, rid);
14072 			sfmmu_hat_exit(hatlockp);
14073 		}
14074 		ASSERT(rid < maxids);
14075 
14076 		if (r_type == SFMMU_REGION_ISM) {
14077 			sfmmu_find_scd(sfmmup);
14078 		}
14079 		return ((hat_region_cookie_t)((uint64_t)rid));
14080 	}
14081 
14082 	ASSERT(new_rgnp == NULL);
14083 
14084 	if (*busyrgnsp >= maxids) {
14085 		mutex_exit(&srdp->srd_mutex);
14086 		return (HAT_INVALID_REGION_COOKIE);
14087 	}
14088 
14089 	ASSERT(MUTEX_HELD(&srdp->srd_mutex));
14090 	if (*freelistp != NULL) {
14091 		new_rgnp = *freelistp;
14092 		*freelistp = new_rgnp->rgn_next;
14093 		ASSERT(new_rgnp->rgn_id < *nextidp);
14094 		ASSERT(new_rgnp->rgn_id < maxids);
14095 		ASSERT(new_rgnp->rgn_flags & SFMMU_REGION_FREE);
14096 		ASSERT((new_rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK)
14097 		    == r_type);
14098 		ASSERT(rarrp[new_rgnp->rgn_id] == new_rgnp);
14099 
14100 		ASSERT(new_rgnp->rgn_hmeflags == 0);
14101 	}
14102 
14103 	if (new_rgnp == NULL) {
14104 		/*
14105 		 * release local locks before memory allocation.
14106 		 */
14107 		mutex_exit(&srdp->srd_mutex);
14108 		if (new_rgnp == NULL) {
14109 			rkmalloc = 1;
14110 			new_rgnp = kmem_cache_alloc(region_cache, KM_SLEEP);
14111 		}
14112 
14113 		mutex_enter(&srdp->srd_mutex);
14114 		for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
14115 		    rgnp = rgnp->rgn_hash) {
14116 			if (rgnp->rgn_saddr == r_saddr &&
14117 			    rgnp->rgn_size == r_size &&
14118 			    rgnp->rgn_obj == r_obj &&
14119 			    rgnp->rgn_objoff == r_objoff &&
14120 			    rgnp->rgn_perm == r_perm &&
14121 			    rgnp->rgn_pgszc == r_pgszc) {
14122 				break;
14123 			}
14124 		}
14125 		if (rgnp != NULL) {
14126 			if (!rkmalloc) {
14127 				ASSERT(new_rgnp->rgn_flags &
14128 				    SFMMU_REGION_FREE);
14129 				new_rgnp->rgn_next = *freelistp;
14130 				*freelistp = new_rgnp;
14131 				new_rgnp = NULL;
14132 			}
14133 			goto rfound;
14134 		}
14135 
14136 		if (rkmalloc) {
14137 			if (*nextidp >= maxids) {
14138 				mutex_exit(&srdp->srd_mutex);
14139 				goto fail;
14140 			}
14141 			rgnp = new_rgnp;
14142 			new_rgnp = NULL;
14143 			rgnp->rgn_id = (*nextidp)++;
14144 			ASSERT(rgnp->rgn_id < maxids);
14145 			ASSERT(rarrp[rgnp->rgn_id] == NULL);
14146 			rarrp[rgnp->rgn_id] = rgnp;
14147 		} else {
14148 			rgnp = new_rgnp;
14149 			new_rgnp = NULL;
14150 		}
14151 	} else {
14152 		rgnp = new_rgnp;
14153 		new_rgnp = NULL;
14154 	}
14155 
14156 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14157 	ASSERT(rgnp->rgn_hmeflags == 0);
14158 #ifdef DEBUG
14159 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14160 		ASSERT(rgnp->rgn_ttecnt[i] == 0);
14161 	}
14162 #endif
14163 	rgnp->rgn_saddr = r_saddr;
14164 	rgnp->rgn_size = r_size;
14165 	rgnp->rgn_obj = r_obj;
14166 	rgnp->rgn_objoff = r_objoff;
14167 	rgnp->rgn_perm = r_perm;
14168 	rgnp->rgn_pgszc = r_pgszc;
14169 	rgnp->rgn_flags = r_type;
14170 	rgnp->rgn_refcnt = 0;
14171 	rgnp->rgn_cb_function = r_cb_function;
14172 	rgnp->rgn_hash = srdp->srd_rgnhash[rhash];
14173 	srdp->srd_rgnhash[rhash] = rgnp;
14174 	(*busyrgnsp)++;
14175 	ASSERT(*busyrgnsp <= maxids);
14176 	goto rfound;
14177 
14178 fail:
14179 	ASSERT(new_rgnp != NULL);
14180 	if (rkmalloc) {
14181 		kmem_cache_free(region_cache, new_rgnp);
14182 	} else {
14183 		/* put it back on the free list. */
14184 		ASSERT(new_rgnp->rgn_flags & SFMMU_REGION_FREE);
14185 		new_rgnp->rgn_next = *freelistp;
14186 		*freelistp = new_rgnp;
14187 	}
14188 	return (HAT_INVALID_REGION_COOKIE);
14189 }
14190 
14191 /*
14192  * This function implements the shared context functionality required
14193  * when detaching a segment from an address space. It must be called
14194  * from hat_unshare() for all D(ISM) segments and from segvn_unmap(),
14195  * for segments with a valid region_cookie.
14196  * It will also be called from all seg_vn routines which change a
14197  * segment's attributes such as segvn_setprot(), segvn_setpagesize(),
14198  * segvn_clrszc() & segvn_advise(), as well as in the case of COW fault
14199  * from segvn_fault().
14200  */
14201 void
14202 hat_leave_region(struct hat *sfmmup, hat_region_cookie_t rcookie, uint_t flags)
14203 {
14204 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14205 	sf_scd_t *scdp;
14206 	uint_t rhash;
14207 	uint_t rid = (uint_t)((uint64_t)rcookie);
14208 	hatlock_t *hatlockp = NULL;
14209 	sf_region_t *rgnp;
14210 	sf_region_t **prev_rgnpp;
14211 	sf_region_t *cur_rgnp;
14212 	void *r_obj;
14213 	int i;
14214 	caddr_t	r_saddr;
14215 	caddr_t r_eaddr;
14216 	size_t	r_size;
14217 	uchar_t	r_pgszc;
14218 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
14219 
14220 	ASSERT(sfmmup != ksfmmup);
14221 	ASSERT(srdp != NULL);
14222 	ASSERT(srdp->srd_refcnt > 0);
14223 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
14224 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
14225 	ASSERT(!sfmmup->sfmmu_free || sfmmup->sfmmu_scdp == NULL);
14226 
14227 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
14228 	    SFMMU_REGION_HME;
14229 
14230 	if (r_type == SFMMU_REGION_ISM) {
14231 		ASSERT(SFMMU_IS_ISMRID_VALID(rid));
14232 		ASSERT(rid < SFMMU_MAX_ISM_REGIONS);
14233 		rgnp = srdp->srd_ismrgnp[rid];
14234 	} else {
14235 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14236 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14237 		rgnp = srdp->srd_hmergnp[rid];
14238 	}
14239 	ASSERT(rgnp != NULL);
14240 	ASSERT(rgnp->rgn_id == rid);
14241 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14242 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14243 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
14244 
14245 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
14246 	if (r_type == SFMMU_REGION_HME && sfmmup->sfmmu_as->a_xhat != NULL) {
14247 		xhat_unload_callback_all(sfmmup->sfmmu_as, rgnp->rgn_saddr,
14248 		    rgnp->rgn_size, 0, NULL);
14249 	}
14250 
14251 	if (sfmmup->sfmmu_free) {
14252 		ulong_t rttecnt;
14253 		r_pgszc = rgnp->rgn_pgszc;
14254 		r_size = rgnp->rgn_size;
14255 
14256 		ASSERT(sfmmup->sfmmu_scdp == NULL);
14257 		if (r_type == SFMMU_REGION_ISM) {
14258 			SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14259 		} else {
14260 			/* update shme rgns ttecnt in sfmmu_ttecnt */
14261 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14262 			ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14263 
14264 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14265 			    -rttecnt);
14266 
14267 			SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14268 		}
14269 	} else if (r_type == SFMMU_REGION_ISM) {
14270 		hatlockp = sfmmu_hat_enter(sfmmup);
14271 		ASSERT(rid < srdp->srd_next_ismrid);
14272 		SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14273 		scdp = sfmmup->sfmmu_scdp;
14274 		if (scdp != NULL &&
14275 		    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
14276 			sfmmu_leave_scd(sfmmup, r_type);
14277 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14278 		}
14279 		sfmmu_hat_exit(hatlockp);
14280 	} else {
14281 		ulong_t rttecnt;
14282 		r_pgszc = rgnp->rgn_pgszc;
14283 		r_saddr = rgnp->rgn_saddr;
14284 		r_size = rgnp->rgn_size;
14285 		r_eaddr = r_saddr + r_size;
14286 
14287 		ASSERT(r_type == SFMMU_REGION_HME);
14288 		hatlockp = sfmmu_hat_enter(sfmmup);
14289 		ASSERT(rid < srdp->srd_next_hmerid);
14290 		SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14291 
14292 		/*
14293 		 * If region is part of an SCD call sfmmu_leave_scd().
14294 		 * Otherwise if process is not exiting and has valid context
14295 		 * just drop the context on the floor to lose stale TLB
14296 		 * entries and force the update of tsb miss area to reflect
14297 		 * the new region map. After that clean our TSB entries.
14298 		 */
14299 		scdp = sfmmup->sfmmu_scdp;
14300 		if (scdp != NULL &&
14301 		    SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
14302 			sfmmu_leave_scd(sfmmup, r_type);
14303 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14304 		}
14305 		sfmmu_invalidate_ctx(sfmmup);
14306 
14307 		i = TTE8K;
14308 		while (i < mmu_page_sizes) {
14309 			if (rgnp->rgn_ttecnt[i] != 0) {
14310 				sfmmu_unload_tsb_range(sfmmup, r_saddr,
14311 				    r_eaddr, i);
14312 				if (i < TTE4M) {
14313 					i = TTE4M;
14314 					continue;
14315 				} else {
14316 					break;
14317 				}
14318 			}
14319 			i++;
14320 		}
14321 		/* Remove the preallocated 1/4 8k ttecnt for 4M regions. */
14322 		if (r_pgszc >= TTE4M) {
14323 			rttecnt = r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14324 			ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
14325 			    rttecnt);
14326 			sfmmup->sfmmu_tsb0_4minflcnt -= rttecnt;
14327 		}
14328 
14329 		/* update shme rgns ttecnt in sfmmu_ttecnt */
14330 		rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14331 		ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14332 		atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc], -rttecnt);
14333 
14334 		sfmmu_hat_exit(hatlockp);
14335 		if (scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
14336 			/* sfmmup left the scd, grow private tsb */
14337 			sfmmu_check_page_sizes(sfmmup, 1);
14338 		} else {
14339 			sfmmu_check_page_sizes(sfmmup, 0);
14340 		}
14341 	}
14342 
14343 	if (r_type == SFMMU_REGION_HME) {
14344 		sfmmu_unlink_from_hmeregion(sfmmup, rgnp);
14345 	}
14346 
14347 	r_obj = rgnp->rgn_obj;
14348 	if (atomic_add_32_nv((volatile uint_t *)&rgnp->rgn_refcnt, -1)) {
14349 		return;
14350 	}
14351 
14352 	/*
14353 	 * looks like nobody uses this region anymore. Free it.
14354 	 */
14355 	rhash = RGN_HASH_FUNCTION(r_obj);
14356 	mutex_enter(&srdp->srd_mutex);
14357 	for (prev_rgnpp = &srdp->srd_rgnhash[rhash];
14358 	    (cur_rgnp = *prev_rgnpp) != NULL;
14359 	    prev_rgnpp = &cur_rgnp->rgn_hash) {
14360 		if (cur_rgnp == rgnp && cur_rgnp->rgn_refcnt == 0) {
14361 			break;
14362 		}
14363 	}
14364 
14365 	if (cur_rgnp == NULL) {
14366 		mutex_exit(&srdp->srd_mutex);
14367 		return;
14368 	}
14369 
14370 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14371 	*prev_rgnpp = rgnp->rgn_hash;
14372 	if (r_type == SFMMU_REGION_ISM) {
14373 		rgnp->rgn_flags |= SFMMU_REGION_FREE;
14374 		ASSERT(rid < srdp->srd_next_ismrid);
14375 		rgnp->rgn_next = srdp->srd_ismrgnfree;
14376 		srdp->srd_ismrgnfree = rgnp;
14377 		ASSERT(srdp->srd_ismbusyrgns > 0);
14378 		srdp->srd_ismbusyrgns--;
14379 		mutex_exit(&srdp->srd_mutex);
14380 		return;
14381 	}
14382 	mutex_exit(&srdp->srd_mutex);
14383 
14384 	/*
14385 	 * Destroy region's hmeblks.
14386 	 */
14387 	sfmmu_unload_hmeregion(srdp, rgnp);
14388 
14389 	rgnp->rgn_hmeflags = 0;
14390 
14391 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14392 	ASSERT(rgnp->rgn_id == rid);
14393 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14394 		rgnp->rgn_ttecnt[i] = 0;
14395 	}
14396 	rgnp->rgn_flags |= SFMMU_REGION_FREE;
14397 	mutex_enter(&srdp->srd_mutex);
14398 	ASSERT(rid < srdp->srd_next_hmerid);
14399 	rgnp->rgn_next = srdp->srd_hmergnfree;
14400 	srdp->srd_hmergnfree = rgnp;
14401 	ASSERT(srdp->srd_hmebusyrgns > 0);
14402 	srdp->srd_hmebusyrgns--;
14403 	mutex_exit(&srdp->srd_mutex);
14404 }
14405 
14406 /*
14407  * For now only called for hmeblk regions and not for ISM regions.
14408  */
14409 void
14410 hat_dup_region(struct hat *sfmmup, hat_region_cookie_t rcookie)
14411 {
14412 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14413 	uint_t rid = (uint_t)((uint64_t)rcookie);
14414 	sf_region_t *rgnp;
14415 	sf_rgn_link_t *rlink;
14416 	sf_rgn_link_t *hrlink;
14417 	ulong_t	rttecnt;
14418 
14419 	ASSERT(sfmmup != ksfmmup);
14420 	ASSERT(srdp != NULL);
14421 	ASSERT(srdp->srd_refcnt > 0);
14422 
14423 	ASSERT(rid < srdp->srd_next_hmerid);
14424 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14425 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14426 
14427 	rgnp = srdp->srd_hmergnp[rid];
14428 	ASSERT(rgnp->rgn_refcnt > 0);
14429 	ASSERT(rgnp->rgn_id == rid);
14430 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == SFMMU_REGION_HME);
14431 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14432 
14433 	atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
14434 
14435 	/* LINTED: constant in conditional context */
14436 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 0);
14437 	ASSERT(rlink != NULL);
14438 	mutex_enter(&rgnp->rgn_mutex);
14439 	ASSERT(rgnp->rgn_sfmmu_head != NULL);
14440 	/* LINTED: constant in conditional context */
14441 	SFMMU_HMERID2RLINKP(rgnp->rgn_sfmmu_head, rid, hrlink, 0, 0);
14442 	ASSERT(hrlink != NULL);
14443 	ASSERT(hrlink->prev == NULL);
14444 	rlink->next = rgnp->rgn_sfmmu_head;
14445 	rlink->prev = NULL;
14446 	hrlink->prev = sfmmup;
14447 	/*
14448 	 * make sure rlink's next field is correct
14449 	 * before making this link visible.
14450 	 */
14451 	membar_stst();
14452 	rgnp->rgn_sfmmu_head = sfmmup;
14453 	mutex_exit(&rgnp->rgn_mutex);
14454 
14455 	/* update sfmmu_ttecnt with the shme rgn ttecnt */
14456 	rttecnt = rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
14457 	atomic_add_long(&sfmmup->sfmmu_ttecnt[rgnp->rgn_pgszc], rttecnt);
14458 	/* update tsb0 inflation count */
14459 	if (rgnp->rgn_pgszc >= TTE4M) {
14460 		sfmmup->sfmmu_tsb0_4minflcnt +=
14461 		    rgnp->rgn_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14462 	}
14463 	/*
14464 	 * Update regionid bitmask without hat lock since no other thread
14465 	 * can update this region bitmask right now.
14466 	 */
14467 	SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14468 }
14469 
14470 /* ARGSUSED */
14471 static int
14472 sfmmu_rgncache_constructor(void *buf, void *cdrarg, int kmflags)
14473 {
14474 	sf_region_t *rgnp = (sf_region_t *)buf;
14475 	bzero(buf, sizeof (*rgnp));
14476 
14477 	mutex_init(&rgnp->rgn_mutex, NULL, MUTEX_DEFAULT, NULL);
14478 
14479 	return (0);
14480 }
14481 
14482 /* ARGSUSED */
14483 static void
14484 sfmmu_rgncache_destructor(void *buf, void *cdrarg)
14485 {
14486 	sf_region_t *rgnp = (sf_region_t *)buf;
14487 	mutex_destroy(&rgnp->rgn_mutex);
14488 }
14489 
14490 static int
14491 sfrgnmap_isnull(sf_region_map_t *map)
14492 {
14493 	int i;
14494 
14495 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14496 		if (map->bitmap[i] != 0) {
14497 			return (0);
14498 		}
14499 	}
14500 	return (1);
14501 }
14502 
14503 static int
14504 sfhmergnmap_isnull(sf_hmeregion_map_t *map)
14505 {
14506 	int i;
14507 
14508 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
14509 		if (map->bitmap[i] != 0) {
14510 			return (0);
14511 		}
14512 	}
14513 	return (1);
14514 }
14515 
14516 #ifdef DEBUG
14517 static void
14518 check_scd_sfmmu_list(sfmmu_t **headp, sfmmu_t *sfmmup, int onlist)
14519 {
14520 	sfmmu_t *sp;
14521 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14522 
14523 	for (sp = *headp; sp != NULL; sp = sp->sfmmu_scd_link.next) {
14524 		ASSERT(srdp == sp->sfmmu_srdp);
14525 		if (sp == sfmmup) {
14526 			if (onlist) {
14527 				return;
14528 			} else {
14529 				panic("shctx: sfmmu 0x%p found on scd"
14530 				    "list 0x%p", sfmmup, *headp);
14531 			}
14532 		}
14533 	}
14534 	if (onlist) {
14535 		panic("shctx: sfmmu 0x%p not found on scd list 0x%p",
14536 		    sfmmup, *headp);
14537 	} else {
14538 		return;
14539 	}
14540 }
14541 #else /* DEBUG */
14542 #define	check_scd_sfmmu_list(headp, sfmmup, onlist)
14543 #endif /* DEBUG */
14544 
14545 /*
14546  * Removes an sfmmu from the start of the queue.
14547  */
14548 static void
14549 sfmmu_from_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14550 {
14551 	ASSERT(sfmmup->sfmmu_srdp != NULL);
14552 	check_scd_sfmmu_list(headp, sfmmup, 1);
14553 	if (sfmmup->sfmmu_scd_link.prev != NULL) {
14554 		ASSERT(*headp != sfmmup);
14555 		sfmmup->sfmmu_scd_link.prev->sfmmu_scd_link.next =
14556 		    sfmmup->sfmmu_scd_link.next;
14557 	} else {
14558 		ASSERT(*headp == sfmmup);
14559 		*headp = sfmmup->sfmmu_scd_link.next;
14560 	}
14561 	if (sfmmup->sfmmu_scd_link.next != NULL) {
14562 		sfmmup->sfmmu_scd_link.next->sfmmu_scd_link.prev =
14563 		    sfmmup->sfmmu_scd_link.prev;
14564 	}
14565 }
14566 
14567 
14568 /*
14569  * Adds an sfmmu to the start of the queue.
14570  */
14571 static void
14572 sfmmu_to_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14573 {
14574 	check_scd_sfmmu_list(headp, sfmmup, 0);
14575 	sfmmup->sfmmu_scd_link.prev = NULL;
14576 	sfmmup->sfmmu_scd_link.next = *headp;
14577 	if (*headp != NULL)
14578 		(*headp)->sfmmu_scd_link.prev = sfmmup;
14579 	*headp = sfmmup;
14580 }
14581 
14582 /*
14583  * Remove an scd from the start of the queue.
14584  */
14585 static void
14586 sfmmu_remove_scd(sf_scd_t **headp, sf_scd_t *scdp)
14587 {
14588 	if (scdp->scd_prev != NULL) {
14589 		ASSERT(*headp != scdp);
14590 		scdp->scd_prev->scd_next = scdp->scd_next;
14591 	} else {
14592 		ASSERT(*headp == scdp);
14593 		*headp = scdp->scd_next;
14594 	}
14595 
14596 	if (scdp->scd_next != NULL) {
14597 		scdp->scd_next->scd_prev = scdp->scd_prev;
14598 	}
14599 }
14600 
14601 /*
14602  * Add an scd to the start of the queue.
14603  */
14604 static void
14605 sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *scdp)
14606 {
14607 	scdp->scd_prev = NULL;
14608 	scdp->scd_next = *headp;
14609 	if (*headp != NULL) {
14610 		(*headp)->scd_prev = scdp;
14611 	}
14612 	*headp = scdp;
14613 }
14614 
14615 static int
14616 sfmmu_alloc_scd_tsbs(sf_srd_t *srdp, sf_scd_t *scdp)
14617 {
14618 	uint_t rid;
14619 	uint_t i;
14620 	uint_t j;
14621 	ulong_t w;
14622 	sf_region_t *rgnp;
14623 	ulong_t tte8k_cnt = 0;
14624 	ulong_t tte4m_cnt = 0;
14625 	uint_t tsb_szc;
14626 	sfmmu_t *scsfmmup = scdp->scd_sfmmup;
14627 	sfmmu_t	*ism_hatid;
14628 	struct tsb_info *newtsb;
14629 	int szc;
14630 
14631 	ASSERT(srdp != NULL);
14632 
14633 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14634 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14635 			continue;
14636 		}
14637 		j = 0;
14638 		while (w) {
14639 			if (!(w & 0x1)) {
14640 				j++;
14641 				w >>= 1;
14642 				continue;
14643 			}
14644 			rid = (i << BT_ULSHIFT) | j;
14645 			j++;
14646 			w >>= 1;
14647 
14648 			if (rid < SFMMU_MAX_HME_REGIONS) {
14649 				rgnp = srdp->srd_hmergnp[rid];
14650 				ASSERT(rgnp->rgn_id == rid);
14651 				ASSERT(rgnp->rgn_refcnt > 0);
14652 
14653 				if (rgnp->rgn_pgszc < TTE4M) {
14654 					tte8k_cnt += rgnp->rgn_size >>
14655 					    TTE_PAGE_SHIFT(TTE8K);
14656 				} else {
14657 					ASSERT(rgnp->rgn_pgszc >= TTE4M);
14658 					tte4m_cnt += rgnp->rgn_size >>
14659 					    TTE_PAGE_SHIFT(TTE4M);
14660 					/*
14661 					 * Inflate SCD tsb0 by preallocating
14662 					 * 1/4 8k ttecnt for 4M regions to
14663 					 * allow for lgpg alloc failure.
14664 					 */
14665 					tte8k_cnt += rgnp->rgn_size >>
14666 					    (TTE_PAGE_SHIFT(TTE8K) + 2);
14667 				}
14668 			} else {
14669 				rid -= SFMMU_MAX_HME_REGIONS;
14670 				rgnp = srdp->srd_ismrgnp[rid];
14671 				ASSERT(rgnp->rgn_id == rid);
14672 				ASSERT(rgnp->rgn_refcnt > 0);
14673 
14674 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14675 				ASSERT(ism_hatid->sfmmu_ismhat);
14676 
14677 				for (szc = 0; szc < TTE4M; szc++) {
14678 					tte8k_cnt +=
14679 					    ism_hatid->sfmmu_ttecnt[szc] <<
14680 					    TTE_BSZS_SHIFT(szc);
14681 				}
14682 
14683 				ASSERT(rgnp->rgn_pgszc >= TTE4M);
14684 				if (rgnp->rgn_pgszc >= TTE4M) {
14685 					tte4m_cnt += rgnp->rgn_size >>
14686 					    TTE_PAGE_SHIFT(TTE4M);
14687 				}
14688 			}
14689 		}
14690 	}
14691 
14692 	tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
14693 
14694 	/* Allocate both the SCD TSBs here. */
14695 	if (sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14696 	    tsb_szc, TSB8K|TSB64K|TSB512K, TSB_ALLOC, scsfmmup) &&
14697 	    (tsb_szc <= TSB_4M_SZCODE ||
14698 	    sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14699 	    TSB_4M_SZCODE, TSB8K|TSB64K|TSB512K,
14700 	    TSB_ALLOC, scsfmmup))) {
14701 
14702 		SFMMU_STAT(sf_scd_1sttsb_allocfail);
14703 		return (TSB_ALLOCFAIL);
14704 	} else {
14705 		scsfmmup->sfmmu_tsb->tsb_flags |= TSB_SHAREDCTX;
14706 
14707 		if (tte4m_cnt) {
14708 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
14709 			if (sfmmu_tsbinfo_alloc(&newtsb, tsb_szc,
14710 			    TSB4M|TSB32M|TSB256M, TSB_ALLOC, scsfmmup) &&
14711 			    (tsb_szc <= TSB_4M_SZCODE ||
14712 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
14713 			    TSB4M|TSB32M|TSB256M,
14714 			    TSB_ALLOC, scsfmmup))) {
14715 				/*
14716 				 * If we fail to allocate the 2nd shared tsb,
14717 				 * just free the 1st tsb, return failure.
14718 				 */
14719 				sfmmu_tsbinfo_free(scsfmmup->sfmmu_tsb);
14720 				SFMMU_STAT(sf_scd_2ndtsb_allocfail);
14721 				return (TSB_ALLOCFAIL);
14722 			} else {
14723 				ASSERT(scsfmmup->sfmmu_tsb->tsb_next == NULL);
14724 				newtsb->tsb_flags |= TSB_SHAREDCTX;
14725 				scsfmmup->sfmmu_tsb->tsb_next = newtsb;
14726 				SFMMU_STAT(sf_scd_2ndtsb_alloc);
14727 			}
14728 		}
14729 		SFMMU_STAT(sf_scd_1sttsb_alloc);
14730 	}
14731 	return (TSB_SUCCESS);
14732 }
14733 
14734 static void
14735 sfmmu_free_scd_tsbs(sfmmu_t *scd_sfmmu)
14736 {
14737 	while (scd_sfmmu->sfmmu_tsb != NULL) {
14738 		struct tsb_info *next = scd_sfmmu->sfmmu_tsb->tsb_next;
14739 		sfmmu_tsbinfo_free(scd_sfmmu->sfmmu_tsb);
14740 		scd_sfmmu->sfmmu_tsb = next;
14741 	}
14742 }
14743 
14744 /*
14745  * Link the sfmmu onto the hme region list.
14746  */
14747 void
14748 sfmmu_link_to_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14749 {
14750 	uint_t rid;
14751 	sf_rgn_link_t *rlink;
14752 	sfmmu_t *head;
14753 	sf_rgn_link_t *hrlink;
14754 
14755 	rid = rgnp->rgn_id;
14756 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14757 
14758 	/* LINTED: constant in conditional context */
14759 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 1);
14760 	ASSERT(rlink != NULL);
14761 	mutex_enter(&rgnp->rgn_mutex);
14762 	if ((head = rgnp->rgn_sfmmu_head) == NULL) {
14763 		rlink->next = NULL;
14764 		rlink->prev = NULL;
14765 		/*
14766 		 * make sure rlink's next field is NULL
14767 		 * before making this link visible.
14768 		 */
14769 		membar_stst();
14770 		rgnp->rgn_sfmmu_head = sfmmup;
14771 	} else {
14772 		/* LINTED: constant in conditional context */
14773 		SFMMU_HMERID2RLINKP(head, rid, hrlink, 0, 0);
14774 		ASSERT(hrlink != NULL);
14775 		ASSERT(hrlink->prev == NULL);
14776 		rlink->next = head;
14777 		rlink->prev = NULL;
14778 		hrlink->prev = sfmmup;
14779 		/*
14780 		 * make sure rlink's next field is correct
14781 		 * before making this link visible.
14782 		 */
14783 		membar_stst();
14784 		rgnp->rgn_sfmmu_head = sfmmup;
14785 	}
14786 	mutex_exit(&rgnp->rgn_mutex);
14787 }
14788 
14789 /*
14790  * Unlink the sfmmu from the hme region list.
14791  */
14792 void
14793 sfmmu_unlink_from_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14794 {
14795 	uint_t rid;
14796 	sf_rgn_link_t *rlink;
14797 
14798 	rid = rgnp->rgn_id;
14799 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14800 
14801 	/* LINTED: constant in conditional context */
14802 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
14803 	ASSERT(rlink != NULL);
14804 	mutex_enter(&rgnp->rgn_mutex);
14805 	if (rgnp->rgn_sfmmu_head == sfmmup) {
14806 		sfmmu_t *next = rlink->next;
14807 		rgnp->rgn_sfmmu_head = next;
14808 		/*
14809 		 * if we are stopped by xc_attention() after this
14810 		 * point the forward link walking in
14811 		 * sfmmu_rgntlb_demap() will work correctly since the
14812 		 * head correctly points to the next element.
14813 		 */
14814 		membar_stst();
14815 		rlink->next = NULL;
14816 		ASSERT(rlink->prev == NULL);
14817 		if (next != NULL) {
14818 			sf_rgn_link_t *nrlink;
14819 			/* LINTED: constant in conditional context */
14820 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14821 			ASSERT(nrlink != NULL);
14822 			ASSERT(nrlink->prev == sfmmup);
14823 			nrlink->prev = NULL;
14824 		}
14825 	} else {
14826 		sfmmu_t *next = rlink->next;
14827 		sfmmu_t *prev = rlink->prev;
14828 		sf_rgn_link_t *prlink;
14829 
14830 		ASSERT(prev != NULL);
14831 		/* LINTED: constant in conditional context */
14832 		SFMMU_HMERID2RLINKP(prev, rid, prlink, 0, 0);
14833 		ASSERT(prlink != NULL);
14834 		ASSERT(prlink->next == sfmmup);
14835 		prlink->next = next;
14836 		/*
14837 		 * if we are stopped by xc_attention()
14838 		 * after this point the forward link walking
14839 		 * will work correctly since the prev element
14840 		 * correctly points to the next element.
14841 		 */
14842 		membar_stst();
14843 		rlink->next = NULL;
14844 		rlink->prev = NULL;
14845 		if (next != NULL) {
14846 			sf_rgn_link_t *nrlink;
14847 			/* LINTED: constant in conditional context */
14848 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14849 			ASSERT(nrlink != NULL);
14850 			ASSERT(nrlink->prev == sfmmup);
14851 			nrlink->prev = prev;
14852 		}
14853 	}
14854 	mutex_exit(&rgnp->rgn_mutex);
14855 }
14856 
14857 /*
14858  * Link scd sfmmu onto ism or hme region list for each region in the
14859  * scd region map.
14860  */
14861 void
14862 sfmmu_link_scd_to_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14863 {
14864 	uint_t rid;
14865 	uint_t i;
14866 	uint_t j;
14867 	ulong_t w;
14868 	sf_region_t *rgnp;
14869 	sfmmu_t *scsfmmup;
14870 
14871 	scsfmmup = scdp->scd_sfmmup;
14872 	ASSERT(scsfmmup->sfmmu_scdhat);
14873 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14874 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14875 			continue;
14876 		}
14877 		j = 0;
14878 		while (w) {
14879 			if (!(w & 0x1)) {
14880 				j++;
14881 				w >>= 1;
14882 				continue;
14883 			}
14884 			rid = (i << BT_ULSHIFT) | j;
14885 			j++;
14886 			w >>= 1;
14887 
14888 			if (rid < SFMMU_MAX_HME_REGIONS) {
14889 				rgnp = srdp->srd_hmergnp[rid];
14890 				ASSERT(rgnp->rgn_id == rid);
14891 				ASSERT(rgnp->rgn_refcnt > 0);
14892 				sfmmu_link_to_hmeregion(scsfmmup, rgnp);
14893 			} else {
14894 				sfmmu_t *ism_hatid = NULL;
14895 				ism_ment_t *ism_ment;
14896 				rid -= SFMMU_MAX_HME_REGIONS;
14897 				rgnp = srdp->srd_ismrgnp[rid];
14898 				ASSERT(rgnp->rgn_id == rid);
14899 				ASSERT(rgnp->rgn_refcnt > 0);
14900 
14901 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14902 				ASSERT(ism_hatid->sfmmu_ismhat);
14903 				ism_ment = &scdp->scd_ism_links[rid];
14904 				ism_ment->iment_hat = scsfmmup;
14905 				ism_ment->iment_base_va = rgnp->rgn_saddr;
14906 				mutex_enter(&ism_mlist_lock);
14907 				iment_add(ism_ment, ism_hatid);
14908 				mutex_exit(&ism_mlist_lock);
14909 
14910 			}
14911 		}
14912 	}
14913 }
14914 /*
14915  * Unlink scd sfmmu from ism or hme region list for each region in the
14916  * scd region map.
14917  */
14918 void
14919 sfmmu_unlink_scd_from_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14920 {
14921 	uint_t rid;
14922 	uint_t i;
14923 	uint_t j;
14924 	ulong_t w;
14925 	sf_region_t *rgnp;
14926 	sfmmu_t *scsfmmup;
14927 
14928 	scsfmmup = scdp->scd_sfmmup;
14929 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14930 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14931 			continue;
14932 		}
14933 		j = 0;
14934 		while (w) {
14935 			if (!(w & 0x1)) {
14936 				j++;
14937 				w >>= 1;
14938 				continue;
14939 			}
14940 			rid = (i << BT_ULSHIFT) | j;
14941 			j++;
14942 			w >>= 1;
14943 
14944 			if (rid < SFMMU_MAX_HME_REGIONS) {
14945 				rgnp = srdp->srd_hmergnp[rid];
14946 				ASSERT(rgnp->rgn_id == rid);
14947 				ASSERT(rgnp->rgn_refcnt > 0);
14948 				sfmmu_unlink_from_hmeregion(scsfmmup,
14949 				    rgnp);
14950 
14951 			} else {
14952 				sfmmu_t *ism_hatid = NULL;
14953 				ism_ment_t *ism_ment;
14954 				rid -= SFMMU_MAX_HME_REGIONS;
14955 				rgnp = srdp->srd_ismrgnp[rid];
14956 				ASSERT(rgnp->rgn_id == rid);
14957 				ASSERT(rgnp->rgn_refcnt > 0);
14958 
14959 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14960 				ASSERT(ism_hatid->sfmmu_ismhat);
14961 				ism_ment = &scdp->scd_ism_links[rid];
14962 				ASSERT(ism_ment->iment_hat == scdp->scd_sfmmup);
14963 				ASSERT(ism_ment->iment_base_va ==
14964 				    rgnp->rgn_saddr);
14965 				ism_ment->iment_hat = NULL;
14966 				ism_ment->iment_base_va = 0;
14967 				mutex_enter(&ism_mlist_lock);
14968 				iment_sub(ism_ment, ism_hatid);
14969 				mutex_exit(&ism_mlist_lock);
14970 
14971 			}
14972 		}
14973 	}
14974 }
14975 /*
14976  * Allocates and initialises a new SCD structure, this is called with
14977  * the srd_scd_mutex held and returns with the reference count
14978  * initialised to 1.
14979  */
14980 static sf_scd_t *
14981 sfmmu_alloc_scd(sf_srd_t *srdp, sf_region_map_t *new_map)
14982 {
14983 	sf_scd_t *new_scdp;
14984 	sfmmu_t *scsfmmup;
14985 	int i;
14986 
14987 	ASSERT(MUTEX_HELD(&srdp->srd_scd_mutex));
14988 	new_scdp = kmem_cache_alloc(scd_cache, KM_SLEEP);
14989 
14990 	scsfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
14991 	new_scdp->scd_sfmmup = scsfmmup;
14992 	scsfmmup->sfmmu_srdp = srdp;
14993 	scsfmmup->sfmmu_scdp = new_scdp;
14994 	scsfmmup->sfmmu_tsb0_4minflcnt = 0;
14995 	scsfmmup->sfmmu_scdhat = 1;
14996 	CPUSET_ALL(scsfmmup->sfmmu_cpusran);
14997 	bzero(scsfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
14998 
14999 	ASSERT(max_mmu_ctxdoms > 0);
15000 	for (i = 0; i < max_mmu_ctxdoms; i++) {
15001 		scsfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
15002 		scsfmmup->sfmmu_ctxs[i].gnum = 0;
15003 	}
15004 
15005 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
15006 		new_scdp->scd_rttecnt[i] = 0;
15007 	}
15008 
15009 	new_scdp->scd_region_map = *new_map;
15010 	new_scdp->scd_refcnt = 1;
15011 	if (sfmmu_alloc_scd_tsbs(srdp, new_scdp) != TSB_SUCCESS) {
15012 		kmem_cache_free(scd_cache, new_scdp);
15013 		kmem_cache_free(sfmmuid_cache, scsfmmup);
15014 		return (NULL);
15015 	}
15016 	return (new_scdp);
15017 }
15018 
15019 /*
15020  * The first phase of a process joining an SCD. The hat structure is
15021  * linked to the SCD queue and then the HAT_JOIN_SCD sfmmu flag is set
15022  * and a cross-call with context invalidation is used to cause the
15023  * remaining work to be carried out in the sfmmu_tsbmiss_exception()
15024  * routine.
15025  */
15026 static void
15027 sfmmu_join_scd(sf_scd_t *scdp, sfmmu_t *sfmmup)
15028 {
15029 	hatlock_t *hatlockp;
15030 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15031 	int i;
15032 	sf_scd_t *old_scdp;
15033 
15034 	ASSERT(srdp != NULL);
15035 	ASSERT(scdp != NULL);
15036 	ASSERT(scdp->scd_refcnt > 0);
15037 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15038 
15039 	if ((old_scdp = sfmmup->sfmmu_scdp) != NULL) {
15040 		ASSERT(old_scdp != scdp);
15041 
15042 		mutex_enter(&old_scdp->scd_mutex);
15043 		sfmmu_from_scd_list(&old_scdp->scd_sf_list, sfmmup);
15044 		mutex_exit(&old_scdp->scd_mutex);
15045 		/*
15046 		 * sfmmup leaves the old scd. Update sfmmu_ttecnt to
15047 		 * include the shme rgn ttecnt for rgns that
15048 		 * were in the old SCD
15049 		 */
15050 		for (i = 0; i < mmu_page_sizes; i++) {
15051 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15052 			    old_scdp->scd_rttecnt[i]);
15053 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15054 			    sfmmup->sfmmu_scdrttecnt[i]);
15055 		}
15056 	}
15057 
15058 	/*
15059 	 * Move sfmmu to the scd lists.
15060 	 */
15061 	mutex_enter(&scdp->scd_mutex);
15062 	sfmmu_to_scd_list(&scdp->scd_sf_list, sfmmup);
15063 	mutex_exit(&scdp->scd_mutex);
15064 	SF_SCD_INCR_REF(scdp);
15065 
15066 	hatlockp = sfmmu_hat_enter(sfmmup);
15067 	/*
15068 	 * For a multi-thread process, we must stop
15069 	 * all the other threads before joining the scd.
15070 	 */
15071 
15072 	SFMMU_FLAGS_SET(sfmmup, HAT_JOIN_SCD);
15073 
15074 	sfmmu_invalidate_ctx(sfmmup);
15075 	sfmmup->sfmmu_scdp = scdp;
15076 
15077 	/*
15078 	 * Copy scd_rttecnt into sfmmup's sfmmu_scdrttecnt, and update
15079 	 * sfmmu_ttecnt to not include the rgn ttecnt just joined in SCD.
15080 	 */
15081 	for (i = 0; i < mmu_page_sizes; i++) {
15082 		sfmmup->sfmmu_scdrttecnt[i] = scdp->scd_rttecnt[i];
15083 		ASSERT(sfmmup->sfmmu_ttecnt[i] >= scdp->scd_rttecnt[i]);
15084 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15085 		    -sfmmup->sfmmu_scdrttecnt[i]);
15086 	}
15087 	/* update tsb0 inflation count */
15088 	if (old_scdp != NULL) {
15089 		sfmmup->sfmmu_tsb0_4minflcnt +=
15090 		    old_scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15091 	}
15092 	ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
15093 	    scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt);
15094 	sfmmup->sfmmu_tsb0_4minflcnt -= scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15095 
15096 	sfmmu_hat_exit(hatlockp);
15097 
15098 	if (old_scdp != NULL) {
15099 		SF_SCD_DECR_REF(srdp, old_scdp);
15100 	}
15101 
15102 }
15103 
15104 /*
15105  * This routine is called by a process to become part of an SCD. It is called
15106  * from sfmmu_tsbmiss_exception() once most of the initial work has been
15107  * done by sfmmu_join_scd(). This routine must not drop the hat lock.
15108  */
15109 static void
15110 sfmmu_finish_join_scd(sfmmu_t *sfmmup)
15111 {
15112 	struct tsb_info	*tsbinfop;
15113 
15114 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15115 	ASSERT(sfmmup->sfmmu_scdp != NULL);
15116 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD));
15117 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15118 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID));
15119 
15120 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
15121 	    tsbinfop = tsbinfop->tsb_next) {
15122 		if (tsbinfop->tsb_flags & TSB_SWAPPED) {
15123 			continue;
15124 		}
15125 		ASSERT(!(tsbinfop->tsb_flags & TSB_RELOC_FLAG));
15126 
15127 		sfmmu_inv_tsb(tsbinfop->tsb_va,
15128 		    TSB_BYTES(tsbinfop->tsb_szc));
15129 	}
15130 
15131 	/* Set HAT_CTX1_FLAG for all SCD ISMs */
15132 	sfmmu_ism_hatflags(sfmmup, 1);
15133 
15134 	SFMMU_STAT(sf_join_scd);
15135 }
15136 
15137 /*
15138  * This routine is called in order to check if there is an SCD which matches
15139  * the process's region map if not then a new SCD may be created.
15140  */
15141 static void
15142 sfmmu_find_scd(sfmmu_t *sfmmup)
15143 {
15144 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15145 	sf_scd_t *scdp, *new_scdp;
15146 	int ret;
15147 
15148 	ASSERT(srdp != NULL);
15149 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15150 
15151 	mutex_enter(&srdp->srd_scd_mutex);
15152 	for (scdp = srdp->srd_scdp; scdp != NULL;
15153 	    scdp = scdp->scd_next) {
15154 		SF_RGNMAP_EQUAL(&scdp->scd_region_map,
15155 		    &sfmmup->sfmmu_region_map, ret);
15156 		if (ret == 1) {
15157 			SF_SCD_INCR_REF(scdp);
15158 			mutex_exit(&srdp->srd_scd_mutex);
15159 			sfmmu_join_scd(scdp, sfmmup);
15160 			ASSERT(scdp->scd_refcnt >= 2);
15161 			atomic_add_32((volatile uint32_t *)
15162 			    &scdp->scd_refcnt, -1);
15163 			return;
15164 		} else {
15165 			/*
15166 			 * If the sfmmu region map is a subset of the scd
15167 			 * region map, then the assumption is that this process
15168 			 * will continue attaching to ISM segments until the
15169 			 * region maps are equal.
15170 			 */
15171 			SF_RGNMAP_IS_SUBSET(&scdp->scd_region_map,
15172 			    &sfmmup->sfmmu_region_map, ret);
15173 			if (ret == 1) {
15174 				mutex_exit(&srdp->srd_scd_mutex);
15175 				return;
15176 			}
15177 		}
15178 	}
15179 
15180 	ASSERT(scdp == NULL);
15181 	/*
15182 	 * No matching SCD has been found, create a new one.
15183 	 */
15184 	if ((new_scdp = sfmmu_alloc_scd(srdp, &sfmmup->sfmmu_region_map)) ==
15185 	    NULL) {
15186 		mutex_exit(&srdp->srd_scd_mutex);
15187 		return;
15188 	}
15189 
15190 	/*
15191 	 * sfmmu_alloc_scd() returns with a ref count of 1 on the scd.
15192 	 */
15193 
15194 	/* Set scd_rttecnt for shme rgns in SCD */
15195 	sfmmu_set_scd_rttecnt(srdp, new_scdp);
15196 
15197 	/*
15198 	 * Link scd onto srd_scdp list and scd sfmmu onto region/iment lists.
15199 	 */
15200 	sfmmu_link_scd_to_regions(srdp, new_scdp);
15201 	sfmmu_add_scd(&srdp->srd_scdp, new_scdp);
15202 	SFMMU_STAT_ADD(sf_create_scd, 1);
15203 
15204 	mutex_exit(&srdp->srd_scd_mutex);
15205 	sfmmu_join_scd(new_scdp, sfmmup);
15206 	ASSERT(new_scdp->scd_refcnt >= 2);
15207 	atomic_add_32((volatile uint32_t *)&new_scdp->scd_refcnt, -1);
15208 }
15209 
15210 /*
15211  * This routine is called by a process to remove itself from an SCD. It is
15212  * either called when the processes has detached from a segment or from
15213  * hat_free_start() as a result of calling exit.
15214  */
15215 static void
15216 sfmmu_leave_scd(sfmmu_t *sfmmup, uchar_t r_type)
15217 {
15218 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15219 	sf_srd_t *srdp =  sfmmup->sfmmu_srdp;
15220 	hatlock_t *hatlockp = TSB_HASH(sfmmup);
15221 	int i;
15222 
15223 	ASSERT(scdp != NULL);
15224 	ASSERT(srdp != NULL);
15225 
15226 	if (sfmmup->sfmmu_free) {
15227 		/*
15228 		 * If the process is part of an SCD the sfmmu is unlinked
15229 		 * from scd_sf_list.
15230 		 */
15231 		mutex_enter(&scdp->scd_mutex);
15232 		sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15233 		mutex_exit(&scdp->scd_mutex);
15234 		/*
15235 		 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15236 		 * are about to leave the SCD
15237 		 */
15238 		for (i = 0; i < mmu_page_sizes; i++) {
15239 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15240 			    scdp->scd_rttecnt[i]);
15241 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15242 			    sfmmup->sfmmu_scdrttecnt[i]);
15243 			sfmmup->sfmmu_scdrttecnt[i] = 0;
15244 		}
15245 		sfmmup->sfmmu_scdp = NULL;
15246 
15247 		SF_SCD_DECR_REF(srdp, scdp);
15248 		return;
15249 	}
15250 
15251 	ASSERT(r_type != SFMMU_REGION_ISM ||
15252 	    SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15253 	ASSERT(scdp->scd_refcnt);
15254 	ASSERT(!sfmmup->sfmmu_free);
15255 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15256 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15257 
15258 	/*
15259 	 * Wait for ISM maps to be updated.
15260 	 */
15261 	if (r_type != SFMMU_REGION_ISM) {
15262 		while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY) &&
15263 		    sfmmup->sfmmu_scdp != NULL) {
15264 			cv_wait(&sfmmup->sfmmu_tsb_cv,
15265 			    HATLOCK_MUTEXP(hatlockp));
15266 		}
15267 
15268 		if (sfmmup->sfmmu_scdp == NULL) {
15269 			sfmmu_hat_exit(hatlockp);
15270 			return;
15271 		}
15272 		SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
15273 	}
15274 
15275 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
15276 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
15277 	} else {
15278 		/*
15279 		 * For a multi-thread process, we must stop
15280 		 * all the other threads before leaving the scd.
15281 		 */
15282 
15283 		sfmmu_invalidate_ctx(sfmmup);
15284 
15285 		/* Clear all the rid's for ISM, delete flags, etc */
15286 		ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15287 		sfmmu_ism_hatflags(sfmmup, 0);
15288 	}
15289 	/*
15290 	 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15291 	 * are in SCD before this sfmmup leaves the SCD.
15292 	 */
15293 	for (i = 0; i < mmu_page_sizes; i++) {
15294 		ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15295 		    scdp->scd_rttecnt[i]);
15296 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15297 		    sfmmup->sfmmu_scdrttecnt[i]);
15298 		sfmmup->sfmmu_scdrttecnt[i] = 0;
15299 		/* update ismttecnt to include SCD ism before hat leaves SCD */
15300 		sfmmup->sfmmu_ismttecnt[i] += sfmmup->sfmmu_scdismttecnt[i];
15301 		sfmmup->sfmmu_scdismttecnt[i] = 0;
15302 	}
15303 	/* update tsb0 inflation count */
15304 	sfmmup->sfmmu_tsb0_4minflcnt += scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15305 
15306 	if (r_type != SFMMU_REGION_ISM) {
15307 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
15308 	}
15309 	sfmmup->sfmmu_scdp = NULL;
15310 
15311 	sfmmu_hat_exit(hatlockp);
15312 
15313 	/*
15314 	 * Unlink sfmmu from scd_sf_list this can be done without holding
15315 	 * the hat lock as we hold the sfmmu_as lock which prevents
15316 	 * hat_join_region from adding this thread to the scd again. Other
15317 	 * threads check if sfmmu_scdp is NULL under hat lock and if it's NULL
15318 	 * they won't get here, since sfmmu_leave_scd() clears sfmmu_scdp
15319 	 * while holding the hat lock.
15320 	 */
15321 	mutex_enter(&scdp->scd_mutex);
15322 	sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15323 	mutex_exit(&scdp->scd_mutex);
15324 	SFMMU_STAT(sf_leave_scd);
15325 
15326 	SF_SCD_DECR_REF(srdp, scdp);
15327 	hatlockp = sfmmu_hat_enter(sfmmup);
15328 
15329 }
15330 
15331 /*
15332  * Unlink and free up an SCD structure with a reference count of 0.
15333  */
15334 static void
15335 sfmmu_destroy_scd(sf_srd_t *srdp, sf_scd_t *scdp, sf_region_map_t *scd_rmap)
15336 {
15337 	sfmmu_t *scsfmmup;
15338 	sf_scd_t *sp;
15339 	hatlock_t *shatlockp;
15340 	int i, ret;
15341 
15342 	mutex_enter(&srdp->srd_scd_mutex);
15343 	for (sp = srdp->srd_scdp; sp != NULL; sp = sp->scd_next) {
15344 		if (sp == scdp)
15345 			break;
15346 	}
15347 	if (sp == NULL || sp->scd_refcnt) {
15348 		mutex_exit(&srdp->srd_scd_mutex);
15349 		return;
15350 	}
15351 
15352 	/*
15353 	 * It is possible that the scd has been freed and reallocated with a
15354 	 * different region map while we've been waiting for the srd_scd_mutex.
15355 	 */
15356 	SF_RGNMAP_EQUAL(scd_rmap, &sp->scd_region_map, ret);
15357 	if (ret != 1) {
15358 		mutex_exit(&srdp->srd_scd_mutex);
15359 		return;
15360 	}
15361 
15362 	ASSERT(scdp->scd_sf_list == NULL);
15363 	/*
15364 	 * Unlink scd from srd_scdp list.
15365 	 */
15366 	sfmmu_remove_scd(&srdp->srd_scdp, scdp);
15367 	mutex_exit(&srdp->srd_scd_mutex);
15368 
15369 	sfmmu_unlink_scd_from_regions(srdp, scdp);
15370 
15371 	/* Clear shared context tsb and release ctx */
15372 	scsfmmup = scdp->scd_sfmmup;
15373 
15374 	/*
15375 	 * create a barrier so that scd will not be destroyed
15376 	 * if other thread still holds the same shared hat lock.
15377 	 * E.g., sfmmu_tsbmiss_exception() needs to acquire the
15378 	 * shared hat lock before checking the shared tsb reloc flag.
15379 	 */
15380 	shatlockp = sfmmu_hat_enter(scsfmmup);
15381 	sfmmu_hat_exit(shatlockp);
15382 
15383 	sfmmu_free_scd_tsbs(scsfmmup);
15384 
15385 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
15386 		if (scsfmmup->sfmmu_hmeregion_links[i] != NULL) {
15387 			kmem_free(scsfmmup->sfmmu_hmeregion_links[i],
15388 			    SFMMU_L2_HMERLINKS_SIZE);
15389 			scsfmmup->sfmmu_hmeregion_links[i] = NULL;
15390 		}
15391 	}
15392 	kmem_cache_free(sfmmuid_cache, scsfmmup);
15393 	kmem_cache_free(scd_cache, scdp);
15394 	SFMMU_STAT(sf_destroy_scd);
15395 }
15396 
15397 /*
15398  * Modifies the HAT_CTX1_FLAG for each of the ISM segments which correspond to
15399  * bits which are set in the ism_region_map parameter. This flag indicates to
15400  * the tsbmiss handler that mapping for these segments should be loaded using
15401  * the shared context.
15402  */
15403 static void
15404 sfmmu_ism_hatflags(sfmmu_t *sfmmup, int addflag)
15405 {
15406 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15407 	ism_blk_t *ism_blkp;
15408 	ism_map_t *ism_map;
15409 	int i, rid;
15410 
15411 	ASSERT(sfmmup->sfmmu_iblk != NULL);
15412 	ASSERT(scdp != NULL);
15413 	/*
15414 	 * Note that the caller either set HAT_ISMBUSY flag or checked
15415 	 * under hat lock that HAT_ISMBUSY was not set by another thread.
15416 	 */
15417 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15418 
15419 	ism_blkp = sfmmup->sfmmu_iblk;
15420 	while (ism_blkp != NULL) {
15421 		ism_map = ism_blkp->iblk_maps;
15422 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
15423 			rid = ism_map[i].imap_rid;
15424 			if (rid == SFMMU_INVALID_ISMRID) {
15425 				continue;
15426 			}
15427 			ASSERT(rid >= 0 && rid < SFMMU_MAX_ISM_REGIONS);
15428 			if (SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
15429 				if (addflag) {
15430 					ism_map[i].imap_hatflags |=
15431 					    HAT_CTX1_FLAG;
15432 				} else {
15433 					ism_map[i].imap_hatflags &=
15434 					    ~HAT_CTX1_FLAG;
15435 				}
15436 			}
15437 		}
15438 		ism_blkp = ism_blkp->iblk_next;
15439 	}
15440 }
15441 
15442 static int
15443 sfmmu_srd_lock_held(sf_srd_t *srdp)
15444 {
15445 	return (MUTEX_HELD(&srdp->srd_mutex));
15446 }
15447 
15448 /* ARGSUSED */
15449 static int
15450 sfmmu_scdcache_constructor(void *buf, void *cdrarg, int kmflags)
15451 {
15452 	sf_scd_t *scdp = (sf_scd_t *)buf;
15453 
15454 	bzero(buf, sizeof (sf_scd_t));
15455 	mutex_init(&scdp->scd_mutex, NULL, MUTEX_DEFAULT, NULL);
15456 	return (0);
15457 }
15458 
15459 /* ARGSUSED */
15460 static void
15461 sfmmu_scdcache_destructor(void *buf, void *cdrarg)
15462 {
15463 	sf_scd_t *scdp = (sf_scd_t *)buf;
15464 
15465 	mutex_destroy(&scdp->scd_mutex);
15466 }
15467