xref: /illumos-gate/usr/src/uts/sfmmu/vm/hat_sfmmu.c (revision 6c70e1f8)
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 (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 /*
26  * VM - Hardware Address Translation management for Spitfire MMU.
27  *
28  * This file implements the machine specific hardware translation
29  * needed by the VM system.  The machine independent interface is
30  * described in <vm/hat.h> while the machine dependent interface
31  * and data structures are described in <vm/hat_sfmmu.h>.
32  *
33  * The hat layer manages the address translation hardware as a cache
34  * driven by calls from the higher levels in the VM system.
35  */
36 
37 #include <sys/types.h>
38 #include <sys/kstat.h>
39 #include <vm/hat.h>
40 #include <vm/hat_sfmmu.h>
41 #include <vm/page.h>
42 #include <sys/pte.h>
43 #include <sys/systm.h>
44 #include <sys/mman.h>
45 #include <sys/sysmacros.h>
46 #include <sys/machparam.h>
47 #include <sys/vtrace.h>
48 #include <sys/kmem.h>
49 #include <sys/mmu.h>
50 #include <sys/cmn_err.h>
51 #include <sys/cpu.h>
52 #include <sys/cpuvar.h>
53 #include <sys/debug.h>
54 #include <sys/lgrp.h>
55 #include <sys/archsystm.h>
56 #include <sys/machsystm.h>
57 #include <sys/vmsystm.h>
58 #include <vm/as.h>
59 #include <vm/seg.h>
60 #include <vm/seg_kp.h>
61 #include <vm/seg_kmem.h>
62 #include <vm/seg_kpm.h>
63 #include <vm/rm.h>
64 #include <sys/t_lock.h>
65 #include <sys/obpdefs.h>
66 #include <sys/vm_machparam.h>
67 #include <sys/var.h>
68 #include <sys/trap.h>
69 #include <sys/machtrap.h>
70 #include <sys/scb.h>
71 #include <sys/bitmap.h>
72 #include <sys/machlock.h>
73 #include <sys/membar.h>
74 #include <sys/atomic.h>
75 #include <sys/cpu_module.h>
76 #include <sys/prom_debug.h>
77 #include <sys/ksynch.h>
78 #include <sys/mem_config.h>
79 #include <sys/mem_cage.h>
80 #include <vm/vm_dep.h>
81 #include <vm/xhat_sfmmu.h>
82 #include <sys/fpu/fpusystm.h>
83 #include <vm/mach_kpm.h>
84 #include <sys/callb.h>
85 
86 #ifdef	DEBUG
87 #define	SFMMU_VALIDATE_HMERID(hat, rid, saddr, len)			\
88 	if (SFMMU_IS_SHMERID_VALID(rid)) {				\
89 		caddr_t _eaddr = (saddr) + (len);			\
90 		sf_srd_t *_srdp;					\
91 		sf_region_t *_rgnp;					\
92 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			\
93 		ASSERT(SF_RGNMAP_TEST(hat->sfmmu_hmeregion_map, rid));	\
94 		ASSERT((hat) != ksfmmup);				\
95 		_srdp = (hat)->sfmmu_srdp;				\
96 		ASSERT(_srdp != NULL);					\
97 		ASSERT(_srdp->srd_refcnt != 0);				\
98 		_rgnp = _srdp->srd_hmergnp[(rid)];			\
99 		ASSERT(_rgnp != NULL && _rgnp->rgn_id == rid);		\
100 		ASSERT(_rgnp->rgn_refcnt != 0);				\
101 		ASSERT(!(_rgnp->rgn_flags & SFMMU_REGION_FREE));	\
102 		ASSERT((_rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	\
103 		    SFMMU_REGION_HME);					\
104 		ASSERT((saddr) >= _rgnp->rgn_saddr);			\
105 		ASSERT((saddr) < _rgnp->rgn_saddr + _rgnp->rgn_size);	\
106 		ASSERT(_eaddr > _rgnp->rgn_saddr);			\
107 		ASSERT(_eaddr <= _rgnp->rgn_saddr + _rgnp->rgn_size);	\
108 	}
109 
110 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid) 	 	 \
111 {						 			 \
112 		caddr_t _hsva;						 \
113 		caddr_t _heva;						 \
114 		caddr_t _rsva;					 	 \
115 		caddr_t _reva;					 	 \
116 		int	_ttesz = get_hblk_ttesz(hmeblkp);		 \
117 		int	_flagtte;					 \
118 		ASSERT((srdp)->srd_refcnt != 0);			 \
119 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			 \
120 		ASSERT((rgnp)->rgn_id == rid);				 \
121 		ASSERT(!((rgnp)->rgn_flags & SFMMU_REGION_FREE));	 \
122 		ASSERT(((rgnp)->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	 \
123 		    SFMMU_REGION_HME);					 \
124 		ASSERT(_ttesz <= (rgnp)->rgn_pgszc);			 \
125 		_hsva = (caddr_t)get_hblk_base(hmeblkp);		 \
126 		_heva = get_hblk_endaddr(hmeblkp);			 \
127 		_rsva = (caddr_t)P2ALIGN(				 \
128 		    (uintptr_t)(rgnp)->rgn_saddr, HBLK_MIN_BYTES);	 \
129 		_reva = (caddr_t)P2ROUNDUP(				 \
130 		    (uintptr_t)((rgnp)->rgn_saddr + (rgnp)->rgn_size),	 \
131 		    HBLK_MIN_BYTES);					 \
132 		ASSERT(_hsva >= _rsva);				 	 \
133 		ASSERT(_hsva < _reva);				 	 \
134 		ASSERT(_heva > _rsva);				 	 \
135 		ASSERT(_heva <= _reva);				 	 \
136 		_flagtte = (_ttesz < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ :  \
137 			_ttesz;						 \
138 		ASSERT(rgnp->rgn_hmeflags & (0x1 << _flagtte));		 \
139 }
140 
141 #else /* DEBUG */
142 #define	SFMMU_VALIDATE_HMERID(hat, rid, addr, len)
143 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid)
144 #endif /* DEBUG */
145 
146 #if defined(SF_ERRATA_57)
147 extern caddr_t errata57_limit;
148 #endif
149 
150 #define	HME8BLK_SZ_RND		((roundup(HME8BLK_SZ, sizeof (int64_t))) /  \
151 				(sizeof (int64_t)))
152 #define	HBLK_RESERVE		((struct hme_blk *)hblk_reserve)
153 
154 #define	HBLK_RESERVE_CNT	128
155 #define	HBLK_RESERVE_MIN	20
156 
157 static struct hme_blk		*freehblkp;
158 static kmutex_t			freehblkp_lock;
159 static int			freehblkcnt;
160 
161 static int64_t			hblk_reserve[HME8BLK_SZ_RND];
162 static kmutex_t			hblk_reserve_lock;
163 static kthread_t		*hblk_reserve_thread;
164 
165 static nucleus_hblk8_info_t	nucleus_hblk8;
166 static nucleus_hblk1_info_t	nucleus_hblk1;
167 
168 /*
169  * Data to manage per-cpu hmeblk pending queues, hmeblks are queued here
170  * after the initial phase of removing an hmeblk from the hash chain, see
171  * the detailed comment in sfmmu_hblk_hash_rm() for further details.
172  */
173 static cpu_hme_pend_t		*cpu_hme_pend;
174 static uint_t			cpu_hme_pend_thresh;
175 /*
176  * SFMMU specific hat functions
177  */
178 void	hat_pagecachectl(struct page *, int);
179 
180 /* flags for hat_pagecachectl */
181 #define	HAT_CACHE	0x1
182 #define	HAT_UNCACHE	0x2
183 #define	HAT_TMPNC	0x4
184 
185 /*
186  * Flag to allow the creation of non-cacheable translations
187  * to system memory. It is off by default. At the moment this
188  * flag is used by the ecache error injector. The error injector
189  * will turn it on when creating such a translation then shut it
190  * off when it's finished.
191  */
192 
193 int	sfmmu_allow_nc_trans = 0;
194 
195 /*
196  * Flag to disable large page support.
197  * 	value of 1 => disable all large pages.
198  *	bits 1, 2, and 3 are to disable 64K, 512K and 4M pages respectively.
199  *
200  * For example, use the value 0x4 to disable 512K pages.
201  *
202  */
203 #define	LARGE_PAGES_OFF		0x1
204 
205 /*
206  * The disable_large_pages and disable_ism_large_pages variables control
207  * hat_memload_array and the page sizes to be used by ISM and the kernel.
208  *
209  * The disable_auto_data_large_pages and disable_auto_text_large_pages variables
210  * are only used to control which OOB pages to use at upper VM segment creation
211  * time, and are set in hat_init_pagesizes and used in the map_pgsz* routines.
212  * Their values may come from platform or CPU specific code to disable page
213  * sizes that should not be used.
214  *
215  * WARNING: 512K pages are currently not supported for ISM/DISM.
216  */
217 uint_t	disable_large_pages = 0;
218 uint_t	disable_ism_large_pages = (1 << TTE512K);
219 uint_t	disable_auto_data_large_pages = 0;
220 uint_t	disable_auto_text_large_pages = 0;
221 
222 /*
223  * Private sfmmu data structures for hat management
224  */
225 static struct kmem_cache *sfmmuid_cache;
226 static struct kmem_cache *mmuctxdom_cache;
227 
228 /*
229  * Private sfmmu data structures for tsb management
230  */
231 static struct kmem_cache *sfmmu_tsbinfo_cache;
232 static struct kmem_cache *sfmmu_tsb8k_cache;
233 static struct kmem_cache *sfmmu_tsb_cache[NLGRPS_MAX];
234 static vmem_t *kmem_bigtsb_arena;
235 static vmem_t *kmem_tsb_arena;
236 
237 /*
238  * sfmmu static variables for hmeblk resource management.
239  */
240 static vmem_t *hat_memload1_arena; /* HAT translation arena for sfmmu1_cache */
241 static struct kmem_cache *sfmmu8_cache;
242 static struct kmem_cache *sfmmu1_cache;
243 static struct kmem_cache *pa_hment_cache;
244 
245 static kmutex_t 	ism_mlist_lock;	/* mutex for ism mapping list */
246 /*
247  * private data for ism
248  */
249 static struct kmem_cache *ism_blk_cache;
250 static struct kmem_cache *ism_ment_cache;
251 #define	ISMID_STARTADDR	NULL
252 
253 /*
254  * Region management data structures and function declarations.
255  */
256 
257 static void	sfmmu_leave_srd(sfmmu_t *);
258 static int	sfmmu_srdcache_constructor(void *, void *, int);
259 static void	sfmmu_srdcache_destructor(void *, void *);
260 static int	sfmmu_rgncache_constructor(void *, void *, int);
261 static void	sfmmu_rgncache_destructor(void *, void *);
262 static int	sfrgnmap_isnull(sf_region_map_t *);
263 static int	sfhmergnmap_isnull(sf_hmeregion_map_t *);
264 static int	sfmmu_scdcache_constructor(void *, void *, int);
265 static void	sfmmu_scdcache_destructor(void *, void *);
266 static void	sfmmu_rgn_cb_noop(caddr_t, caddr_t, caddr_t,
267     size_t, void *, u_offset_t);
268 
269 static uint_t srd_hashmask = SFMMU_MAX_SRD_BUCKETS - 1;
270 static sf_srd_bucket_t *srd_buckets;
271 static struct kmem_cache *srd_cache;
272 static uint_t srd_rgn_hashmask = SFMMU_MAX_REGION_BUCKETS - 1;
273 static struct kmem_cache *region_cache;
274 static struct kmem_cache *scd_cache;
275 
276 #ifdef sun4v
277 int use_bigtsb_arena = 1;
278 #else
279 int use_bigtsb_arena = 0;
280 #endif
281 
282 /* External /etc/system tunable, for turning on&off the shctx support */
283 int disable_shctx = 0;
284 /* Internal variable, set by MD if the HW supports shctx feature */
285 int shctx_on = 0;
286 
287 #ifdef DEBUG
288 static void check_scd_sfmmu_list(sfmmu_t **, sfmmu_t *, int);
289 #endif
290 static void sfmmu_to_scd_list(sfmmu_t **, sfmmu_t *);
291 static void sfmmu_from_scd_list(sfmmu_t **, sfmmu_t *);
292 
293 static sf_scd_t *sfmmu_alloc_scd(sf_srd_t *, sf_region_map_t *);
294 static void sfmmu_find_scd(sfmmu_t *);
295 static void sfmmu_join_scd(sf_scd_t *, sfmmu_t *);
296 static void sfmmu_finish_join_scd(sfmmu_t *);
297 static void sfmmu_leave_scd(sfmmu_t *, uchar_t);
298 static void sfmmu_destroy_scd(sf_srd_t *, sf_scd_t *, sf_region_map_t *);
299 static int sfmmu_alloc_scd_tsbs(sf_srd_t *, sf_scd_t *);
300 static void sfmmu_free_scd_tsbs(sfmmu_t *);
301 static void sfmmu_tsb_inv_ctx(sfmmu_t *);
302 static int find_ism_rid(sfmmu_t *, sfmmu_t *, caddr_t, uint_t *);
303 static void sfmmu_ism_hatflags(sfmmu_t *, int);
304 static int sfmmu_srd_lock_held(sf_srd_t *);
305 static void sfmmu_remove_scd(sf_scd_t **, sf_scd_t *);
306 static void sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *);
307 static void sfmmu_link_scd_to_regions(sf_srd_t *, sf_scd_t *);
308 static void sfmmu_unlink_scd_from_regions(sf_srd_t *, sf_scd_t *);
309 static void sfmmu_link_to_hmeregion(sfmmu_t *, sf_region_t *);
310 static void sfmmu_unlink_from_hmeregion(sfmmu_t *, sf_region_t *);
311 
312 /*
313  * ``hat_lock'' is a hashed mutex lock for protecting sfmmu TSB lists,
314  * HAT flags, synchronizing TLB/TSB coherency, and context management.
315  * The lock is hashed on the sfmmup since the case where we need to lock
316  * all processes is rare but does occur (e.g. we need to unload a shared
317  * mapping from all processes using the mapping).  We have a lot of buckets,
318  * and each slab of sfmmu_t's can use about a quarter of them, giving us
319  * a fairly good distribution without wasting too much space and overhead
320  * when we have to grab them all.
321  */
322 #define	SFMMU_NUM_LOCK	128		/* must be power of two */
323 hatlock_t	hat_lock[SFMMU_NUM_LOCK];
324 
325 /*
326  * Hash algorithm optimized for a small number of slabs.
327  *  7 is (highbit((sizeof sfmmu_t)) - 1)
328  * This hash algorithm is based upon the knowledge that sfmmu_t's come from a
329  * kmem_cache, and thus they will be sequential within that cache.  In
330  * addition, each new slab will have a different "color" up to cache_maxcolor
331  * which will skew the hashing for each successive slab which is allocated.
332  * If the size of sfmmu_t changed to a larger size, this algorithm may need
333  * to be revisited.
334  */
335 #define	TSB_HASH_SHIFT_BITS (7)
336 #define	PTR_HASH(x) ((uintptr_t)x >> TSB_HASH_SHIFT_BITS)
337 
338 #ifdef DEBUG
339 int tsb_hash_debug = 0;
340 #define	TSB_HASH(sfmmup)	\
341 	(tsb_hash_debug ? &hat_lock[0] : \
342 	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)])
343 #else	/* DEBUG */
344 #define	TSB_HASH(sfmmup)	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)]
345 #endif	/* DEBUG */
346 
347 
348 /* sfmmu_replace_tsb() return codes. */
349 typedef enum tsb_replace_rc {
350 	TSB_SUCCESS,
351 	TSB_ALLOCFAIL,
352 	TSB_LOSTRACE,
353 	TSB_ALREADY_SWAPPED,
354 	TSB_CANTGROW
355 } tsb_replace_rc_t;
356 
357 /*
358  * Flags for TSB allocation routines.
359  */
360 #define	TSB_ALLOC	0x01
361 #define	TSB_FORCEALLOC	0x02
362 #define	TSB_GROW	0x04
363 #define	TSB_SHRINK	0x08
364 #define	TSB_SWAPIN	0x10
365 
366 /*
367  * Support for HAT callbacks.
368  */
369 #define	SFMMU_MAX_RELOC_CALLBACKS	10
370 int sfmmu_max_cb_id = SFMMU_MAX_RELOC_CALLBACKS;
371 static id_t sfmmu_cb_nextid = 0;
372 static id_t sfmmu_tsb_cb_id;
373 struct sfmmu_callback *sfmmu_cb_table;
374 
375 /*
376  * Kernel page relocation is enabled by default for non-caged
377  * kernel pages.  This has little effect unless segkmem_reloc is
378  * set, since by default kernel memory comes from inside the
379  * kernel cage.
380  */
381 int hat_kpr_enabled = 1;
382 
383 kmutex_t	kpr_mutex;
384 kmutex_t	kpr_suspendlock;
385 kthread_t	*kreloc_thread;
386 
387 /*
388  * Enable VA->PA translation sanity checking on DEBUG kernels.
389  * Disabled by default.  This is incompatible with some
390  * drivers (error injector, RSM) so if it breaks you get
391  * to keep both pieces.
392  */
393 int hat_check_vtop = 0;
394 
395 /*
396  * Private sfmmu routines (prototypes)
397  */
398 static struct hme_blk *sfmmu_shadow_hcreate(sfmmu_t *, caddr_t, int, uint_t);
399 static struct 	hme_blk *sfmmu_hblk_alloc(sfmmu_t *, caddr_t,
400 			struct hmehash_bucket *, uint_t, hmeblk_tag, uint_t,
401 			uint_t);
402 static caddr_t	sfmmu_hblk_unload(struct hat *, struct hme_blk *, caddr_t,
403 			caddr_t, demap_range_t *, uint_t);
404 static caddr_t	sfmmu_hblk_sync(struct hat *, struct hme_blk *, caddr_t,
405 			caddr_t, int);
406 static void	sfmmu_hblk_free(struct hme_blk **);
407 static void	sfmmu_hblks_list_purge(struct hme_blk **, int);
408 static uint_t	sfmmu_get_free_hblk(struct hme_blk **, uint_t);
409 static uint_t	sfmmu_put_free_hblk(struct hme_blk *, uint_t);
410 static struct hme_blk *sfmmu_hblk_steal(int);
411 static int	sfmmu_steal_this_hblk(struct hmehash_bucket *,
412 			struct hme_blk *, uint64_t, struct hme_blk *);
413 static caddr_t	sfmmu_hblk_unlock(struct hme_blk *, caddr_t, caddr_t);
414 
415 static void	hat_do_memload_array(struct hat *, caddr_t, size_t,
416 		    struct page **, uint_t, uint_t, uint_t);
417 static void	hat_do_memload(struct hat *, caddr_t, struct page *,
418 		    uint_t, uint_t, uint_t);
419 static void	sfmmu_memload_batchsmall(struct hat *, caddr_t, page_t **,
420 		    uint_t, uint_t, pgcnt_t, uint_t);
421 void		sfmmu_tteload(struct hat *, tte_t *, caddr_t, page_t *,
422 			uint_t);
423 static int	sfmmu_tteload_array(sfmmu_t *, tte_t *, caddr_t, page_t **,
424 			uint_t, uint_t);
425 static struct hmehash_bucket *sfmmu_tteload_acquire_hashbucket(sfmmu_t *,
426 					caddr_t, int, uint_t);
427 static struct hme_blk *sfmmu_tteload_find_hmeblk(sfmmu_t *,
428 			struct hmehash_bucket *, caddr_t, uint_t, uint_t,
429 			uint_t);
430 static int	sfmmu_tteload_addentry(sfmmu_t *, struct hme_blk *, tte_t *,
431 			caddr_t, page_t **, uint_t, uint_t);
432 static void	sfmmu_tteload_release_hashbucket(struct hmehash_bucket *);
433 
434 static int	sfmmu_pagearray_setup(caddr_t, page_t **, tte_t *, int);
435 static pfn_t	sfmmu_uvatopfn(caddr_t, sfmmu_t *, tte_t *);
436 void		sfmmu_memtte(tte_t *, pfn_t, uint_t, int);
437 #ifdef VAC
438 static void	sfmmu_vac_conflict(struct hat *, caddr_t, page_t *);
439 static int	sfmmu_vacconflict_array(caddr_t, page_t *, int *);
440 int	tst_tnc(page_t *pp, pgcnt_t);
441 void	conv_tnc(page_t *pp, int);
442 #endif
443 
444 static void	sfmmu_get_ctx(sfmmu_t *);
445 static void	sfmmu_free_sfmmu(sfmmu_t *);
446 
447 static void	sfmmu_ttesync(struct hat *, caddr_t, tte_t *, page_t *);
448 static void	sfmmu_chgattr(struct hat *, caddr_t, size_t, uint_t, int);
449 
450 cpuset_t	sfmmu_pageunload(page_t *, struct sf_hment *, int);
451 static void	hat_pagereload(struct page *, struct page *);
452 static cpuset_t	sfmmu_pagesync(page_t *, struct sf_hment *, uint_t);
453 #ifdef VAC
454 void	sfmmu_page_cache_array(page_t *, int, int, pgcnt_t);
455 static void	sfmmu_page_cache(page_t *, int, int, int);
456 #endif
457 
458 cpuset_t	sfmmu_rgntlb_demap(caddr_t, sf_region_t *,
459     struct hme_blk *, int);
460 static void	sfmmu_tlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
461 			pfn_t, int, int, int, int);
462 static void	sfmmu_ismtlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
463 			pfn_t, int);
464 static void	sfmmu_tlb_demap(caddr_t, sfmmu_t *, struct hme_blk *, int, int);
465 static void	sfmmu_tlb_range_demap(demap_range_t *);
466 static void	sfmmu_invalidate_ctx(sfmmu_t *);
467 static void	sfmmu_sync_mmustate(sfmmu_t *);
468 
469 static void 	sfmmu_tsbinfo_setup_phys(struct tsb_info *, pfn_t);
470 static int	sfmmu_tsbinfo_alloc(struct tsb_info **, int, int, uint_t,
471 			sfmmu_t *);
472 static void	sfmmu_tsb_free(struct tsb_info *);
473 static void	sfmmu_tsbinfo_free(struct tsb_info *);
474 static int	sfmmu_init_tsbinfo(struct tsb_info *, int, int, uint_t,
475 			sfmmu_t *);
476 static void	sfmmu_tsb_chk_reloc(sfmmu_t *, hatlock_t *);
477 static void	sfmmu_tsb_swapin(sfmmu_t *, hatlock_t *);
478 static int	sfmmu_select_tsb_szc(pgcnt_t);
479 static void	sfmmu_mod_tsb(sfmmu_t *, caddr_t, tte_t *, int);
480 #define		sfmmu_load_tsb(sfmmup, vaddr, tte, szc) \
481 	sfmmu_mod_tsb(sfmmup, vaddr, tte, szc)
482 #define		sfmmu_unload_tsb(sfmmup, vaddr, szc)    \
483 	sfmmu_mod_tsb(sfmmup, vaddr, NULL, szc)
484 static void	sfmmu_copy_tsb(struct tsb_info *, struct tsb_info *);
485 static tsb_replace_rc_t sfmmu_replace_tsb(sfmmu_t *, struct tsb_info *, uint_t,
486     hatlock_t *, uint_t);
487 static void	sfmmu_size_tsb(sfmmu_t *, int, uint64_t, uint64_t, int);
488 
489 #ifdef VAC
490 void	sfmmu_cache_flush(pfn_t, int);
491 void	sfmmu_cache_flushcolor(int, pfn_t);
492 #endif
493 static caddr_t	sfmmu_hblk_chgattr(sfmmu_t *, struct hme_blk *, caddr_t,
494 			caddr_t, demap_range_t *, uint_t, int);
495 
496 static uint64_t	sfmmu_vtop_attr(uint_t, int mode, tte_t *);
497 static uint_t	sfmmu_ptov_attr(tte_t *);
498 static caddr_t	sfmmu_hblk_chgprot(sfmmu_t *, struct hme_blk *, caddr_t,
499 			caddr_t, demap_range_t *, uint_t);
500 static uint_t	sfmmu_vtop_prot(uint_t, uint_t *);
501 static int	sfmmu_idcache_constructor(void *, void *, int);
502 static void	sfmmu_idcache_destructor(void *, void *);
503 static int	sfmmu_hblkcache_constructor(void *, void *, int);
504 static void	sfmmu_hblkcache_destructor(void *, void *);
505 static void	sfmmu_hblkcache_reclaim(void *);
506 static void	sfmmu_shadow_hcleanup(sfmmu_t *, struct hme_blk *,
507 			struct hmehash_bucket *);
508 static void	sfmmu_hblk_hash_rm(struct hmehash_bucket *, struct hme_blk *,
509 			struct hme_blk *, struct hme_blk **, int);
510 static void	sfmmu_hblk_hash_add(struct hmehash_bucket *, struct hme_blk *,
511 			uint64_t);
512 static struct hme_blk *sfmmu_check_pending_hblks(int);
513 static void	sfmmu_free_hblks(sfmmu_t *, caddr_t, caddr_t, int);
514 static void	sfmmu_cleanup_rhblk(sf_srd_t *, caddr_t, uint_t, int);
515 static void	sfmmu_unload_hmeregion_va(sf_srd_t *, uint_t, caddr_t, caddr_t,
516 			int, caddr_t *);
517 static void	sfmmu_unload_hmeregion(sf_srd_t *, sf_region_t *);
518 
519 static void	sfmmu_rm_large_mappings(page_t *, int);
520 
521 static void	hat_lock_init(void);
522 static void	hat_kstat_init(void);
523 static int	sfmmu_kstat_percpu_update(kstat_t *ksp, int rw);
524 static void	sfmmu_set_scd_rttecnt(sf_srd_t *, sf_scd_t *);
525 static	int	sfmmu_is_rgnva(sf_srd_t *, caddr_t, ulong_t, ulong_t);
526 static void	sfmmu_check_page_sizes(sfmmu_t *, int);
527 int	fnd_mapping_sz(page_t *);
528 static void	iment_add(struct ism_ment *,  struct hat *);
529 static void	iment_sub(struct ism_ment *, struct hat *);
530 static pgcnt_t	ism_tsb_entries(sfmmu_t *, int szc);
531 extern void	sfmmu_setup_tsbinfo(sfmmu_t *);
532 extern void	sfmmu_clear_utsbinfo(void);
533 
534 static void		sfmmu_ctx_wrap_around(mmu_ctx_t *, boolean_t);
535 
536 extern int vpm_enable;
537 
538 /* kpm globals */
539 #ifdef	DEBUG
540 /*
541  * Enable trap level tsbmiss handling
542  */
543 int	kpm_tsbmtl = 1;
544 
545 /*
546  * Flush the TLB on kpm mapout. Note: Xcalls are used (again) for the
547  * required TLB shootdowns in this case, so handle w/ care. Off by default.
548  */
549 int	kpm_tlb_flush;
550 #endif	/* DEBUG */
551 
552 static void	*sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *, size_t, int);
553 
554 #ifdef DEBUG
555 static void	sfmmu_check_hblk_flist();
556 #endif
557 
558 /*
559  * Semi-private sfmmu data structures.  Some of them are initialize in
560  * startup or in hat_init. Some of them are private but accessed by
561  * assembly code or mach_sfmmu.c
562  */
563 struct hmehash_bucket *uhme_hash;	/* user hmeblk hash table */
564 struct hmehash_bucket *khme_hash;	/* kernel hmeblk hash table */
565 uint64_t	uhme_hash_pa;		/* PA of uhme_hash */
566 uint64_t	khme_hash_pa;		/* PA of khme_hash */
567 int 		uhmehash_num;		/* # of buckets in user hash table */
568 int 		khmehash_num;		/* # of buckets in kernel hash table */
569 
570 uint_t		max_mmu_ctxdoms = 0;	/* max context domains in the system */
571 mmu_ctx_t	**mmu_ctxs_tbl;		/* global array of context domains */
572 uint64_t	mmu_saved_gnum = 0;	/* to init incoming MMUs' gnums */
573 
574 #define	DEFAULT_NUM_CTXS_PER_MMU 8192
575 static uint_t	nctxs = DEFAULT_NUM_CTXS_PER_MMU;
576 
577 int		cache;			/* describes system cache */
578 
579 caddr_t		ktsb_base;		/* kernel 8k-indexed tsb base address */
580 uint64_t	ktsb_pbase;		/* kernel 8k-indexed tsb phys address */
581 int		ktsb_szcode;		/* kernel 8k-indexed tsb size code */
582 int		ktsb_sz;		/* kernel 8k-indexed tsb size */
583 
584 caddr_t		ktsb4m_base;		/* kernel 4m-indexed tsb base address */
585 uint64_t	ktsb4m_pbase;		/* kernel 4m-indexed tsb phys address */
586 int		ktsb4m_szcode;		/* kernel 4m-indexed tsb size code */
587 int		ktsb4m_sz;		/* kernel 4m-indexed tsb size */
588 
589 uint64_t	kpm_tsbbase;		/* kernel seg_kpm 4M TSB base address */
590 int		kpm_tsbsz;		/* kernel seg_kpm 4M TSB size code */
591 uint64_t	kpmsm_tsbbase;		/* kernel seg_kpm 8K TSB base address */
592 int		kpmsm_tsbsz;		/* kernel seg_kpm 8K TSB size code */
593 
594 #ifndef sun4v
595 int		utsb_dtlb_ttenum = -1;	/* index in TLB for utsb locked TTE */
596 int		utsb4m_dtlb_ttenum = -1; /* index in TLB for 4M TSB TTE */
597 int		dtlb_resv_ttenum;	/* index in TLB of first reserved TTE */
598 caddr_t		utsb_vabase;		/* reserved kernel virtual memory */
599 caddr_t		utsb4m_vabase;		/* for trap handler TSB accesses */
600 #endif /* sun4v */
601 uint64_t	tsb_alloc_bytes = 0;	/* bytes allocated to TSBs */
602 vmem_t		*kmem_tsb_default_arena[NLGRPS_MAX];	/* For dynamic TSBs */
603 vmem_t		*kmem_bigtsb_default_arena[NLGRPS_MAX]; /* dynamic 256M TSBs */
604 
605 /*
606  * Size to use for TSB slabs.  Future platforms that support page sizes
607  * larger than 4M may wish to change these values, and provide their own
608  * assembly macros for building and decoding the TSB base register contents.
609  * Note disable_large_pages will override the value set here.
610  */
611 static	uint_t tsb_slab_ttesz = TTE4M;
612 size_t	tsb_slab_size = MMU_PAGESIZE4M;
613 uint_t	tsb_slab_shift = MMU_PAGESHIFT4M;
614 /* PFN mask for TTE */
615 size_t	tsb_slab_mask = MMU_PAGEOFFSET4M >> MMU_PAGESHIFT;
616 
617 /*
618  * Size to use for TSB slabs.  These are used only when 256M tsb arenas
619  * exist.
620  */
621 static uint_t	bigtsb_slab_ttesz = TTE256M;
622 static size_t	bigtsb_slab_size = MMU_PAGESIZE256M;
623 static uint_t	bigtsb_slab_shift = MMU_PAGESHIFT256M;
624 /* 256M page alignment for 8K pfn */
625 static size_t	bigtsb_slab_mask = MMU_PAGEOFFSET256M >> MMU_PAGESHIFT;
626 
627 /* largest TSB size to grow to, will be smaller on smaller memory systems */
628 static int	tsb_max_growsize = 0;
629 
630 /*
631  * Tunable parameters dealing with TSB policies.
632  */
633 
634 /*
635  * This undocumented tunable forces all 8K TSBs to be allocated from
636  * the kernel heap rather than from the kmem_tsb_default_arena arenas.
637  */
638 #ifdef	DEBUG
639 int	tsb_forceheap = 0;
640 #endif	/* DEBUG */
641 
642 /*
643  * Decide whether to use per-lgroup arenas, or one global set of
644  * TSB arenas.  The default is not to break up per-lgroup, since
645  * most platforms don't recognize any tangible benefit from it.
646  */
647 int	tsb_lgrp_affinity = 0;
648 
649 /*
650  * Used for growing the TSB based on the process RSS.
651  * tsb_rss_factor is based on the smallest TSB, and is
652  * shifted by the TSB size to determine if we need to grow.
653  * The default will grow the TSB if the number of TTEs for
654  * this page size exceeds 75% of the number of TSB entries,
655  * which should _almost_ eliminate all conflict misses
656  * (at the expense of using up lots and lots of memory).
657  */
658 #define	TSB_RSS_FACTOR		(TSB_ENTRIES(TSB_MIN_SZCODE) * 0.75)
659 #define	SFMMU_RSS_TSBSIZE(tsbszc)	(tsb_rss_factor << tsbszc)
660 #define	SELECT_TSB_SIZECODE(pgcnt) ( \
661 	(enable_tsb_rss_sizing)? sfmmu_select_tsb_szc(pgcnt) : \
662 	default_tsb_size)
663 #define	TSB_OK_SHRINK()	\
664 	(tsb_alloc_bytes > tsb_alloc_hiwater || freemem < desfree)
665 #define	TSB_OK_GROW()	\
666 	(tsb_alloc_bytes < tsb_alloc_hiwater && freemem > desfree)
667 
668 int	enable_tsb_rss_sizing = 1;
669 int	tsb_rss_factor	= (int)TSB_RSS_FACTOR;
670 
671 /* which TSB size code to use for new address spaces or if rss sizing off */
672 int default_tsb_size = TSB_8K_SZCODE;
673 
674 static uint64_t tsb_alloc_hiwater; /* limit TSB reserved memory */
675 uint64_t tsb_alloc_hiwater_factor; /* tsb_alloc_hiwater = physmem / this */
676 #define	TSB_ALLOC_HIWATER_FACTOR_DEFAULT	32
677 
678 #ifdef DEBUG
679 static int tsb_random_size = 0;	/* set to 1 to test random tsb sizes on alloc */
680 static int tsb_grow_stress = 0;	/* if set to 1, keep replacing TSB w/ random */
681 static int tsb_alloc_mtbf = 0;	/* fail allocation every n attempts */
682 static int tsb_alloc_fail_mtbf = 0;
683 static int tsb_alloc_count = 0;
684 #endif /* DEBUG */
685 
686 /* if set to 1, will remap valid TTEs when growing TSB. */
687 int tsb_remap_ttes = 1;
688 
689 /*
690  * If we have more than this many mappings, allocate a second TSB.
691  * This default is chosen because the I/D fully associative TLBs are
692  * assumed to have at least 8 available entries. Platforms with a
693  * larger fully-associative TLB could probably override the default.
694  */
695 
696 #ifdef sun4v
697 int tsb_sectsb_threshold = 0;
698 #else
699 int tsb_sectsb_threshold = 8;
700 #endif
701 
702 /*
703  * kstat data
704  */
705 struct sfmmu_global_stat sfmmu_global_stat;
706 struct sfmmu_tsbsize_stat sfmmu_tsbsize_stat;
707 
708 /*
709  * Global data
710  */
711 sfmmu_t 	*ksfmmup;		/* kernel's hat id */
712 
713 #ifdef DEBUG
714 static void	chk_tte(tte_t *, tte_t *, tte_t *, struct hme_blk *);
715 #endif
716 
717 /* sfmmu locking operations */
718 static kmutex_t *sfmmu_mlspl_enter(struct page *, int);
719 static int	sfmmu_mlspl_held(struct page *, int);
720 
721 kmutex_t *sfmmu_page_enter(page_t *);
722 void	sfmmu_page_exit(kmutex_t *);
723 int	sfmmu_page_spl_held(struct page *);
724 
725 /* sfmmu internal locking operations - accessed directly */
726 static void	sfmmu_mlist_reloc_enter(page_t *, page_t *,
727 				kmutex_t **, kmutex_t **);
728 static void	sfmmu_mlist_reloc_exit(kmutex_t *, kmutex_t *);
729 static hatlock_t *
730 		sfmmu_hat_enter(sfmmu_t *);
731 static hatlock_t *
732 		sfmmu_hat_tryenter(sfmmu_t *);
733 static void	sfmmu_hat_exit(hatlock_t *);
734 static void	sfmmu_hat_lock_all(void);
735 static void	sfmmu_hat_unlock_all(void);
736 static void	sfmmu_ismhat_enter(sfmmu_t *, int);
737 static void	sfmmu_ismhat_exit(sfmmu_t *, int);
738 
739 /*
740  * Array of mutexes protecting a page's mapping list and p_nrm field.
741  *
742  * The hash function looks complicated, but is made up so that:
743  *
744  * "pp" not shifted, so adjacent pp values will hash to different cache lines
745  *  (8 byte alignment * 8 bytes/mutes == 64 byte coherency subblock)
746  *
747  * "pp" >> mml_shift, incorporates more source bits into the hash result
748  *
749  *  "& (mml_table_size - 1), should be faster than using remainder "%"
750  *
751  * Hopefully, mml_table, mml_table_size and mml_shift are all in the same
752  * cacheline, since they get declared next to each other below. We'll trust
753  * ld not to do something random.
754  */
755 #ifdef	DEBUG
756 int mlist_hash_debug = 0;
757 #define	MLIST_HASH(pp)	(mlist_hash_debug ? &mml_table[0] : \
758 	&mml_table[((uintptr_t)(pp) + \
759 	((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)])
760 #else	/* !DEBUG */
761 #define	MLIST_HASH(pp)   &mml_table[ \
762 	((uintptr_t)(pp) + ((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)]
763 #endif	/* !DEBUG */
764 
765 kmutex_t		*mml_table;
766 uint_t			mml_table_sz;	/* must be a power of 2 */
767 uint_t			mml_shift;	/* log2(mml_table_sz) + 3 for align */
768 
769 kpm_hlk_t	*kpmp_table;
770 uint_t		kpmp_table_sz;	/* must be a power of 2 */
771 uchar_t		kpmp_shift;
772 
773 kpm_shlk_t	*kpmp_stable;
774 uint_t		kpmp_stable_sz;	/* must be a power of 2 */
775 
776 /*
777  * SPL_TABLE_SIZE is 2 * NCPU, but no smaller than 128.
778  * SPL_SHIFT is log2(SPL_TABLE_SIZE).
779  */
780 #if ((2*NCPU_P2) > 128)
781 #define	SPL_SHIFT	((unsigned)(NCPU_LOG2 + 1))
782 #else
783 #define	SPL_SHIFT	7U
784 #endif
785 #define	SPL_TABLE_SIZE	(1U << SPL_SHIFT)
786 #define	SPL_MASK	(SPL_TABLE_SIZE - 1)
787 
788 /*
789  * We shift by PP_SHIFT to take care of the low-order 0 bits of a page_t
790  * and by multiples of SPL_SHIFT to get as many varied bits as we can.
791  */
792 #define	SPL_INDEX(pp) \
793 	((((uintptr_t)(pp) >> PP_SHIFT) ^ \
794 	((uintptr_t)(pp) >> (PP_SHIFT + SPL_SHIFT)) ^ \
795 	((uintptr_t)(pp) >> (PP_SHIFT + SPL_SHIFT * 2)) ^ \
796 	((uintptr_t)(pp) >> (PP_SHIFT + SPL_SHIFT * 3))) & \
797 	(SPL_TABLE_SIZE - 1))
798 
799 #define	SPL_HASH(pp)    \
800 	(&sfmmu_page_lock[SPL_INDEX(pp) & SPL_MASK].pad_mutex)
801 
802 static	pad_mutex_t	sfmmu_page_lock[SPL_TABLE_SIZE];
803 
804 
805 /*
806  * hat_unload_callback() will group together callbacks in order
807  * to avoid xt_sync() calls.  This is the maximum size of the group.
808  */
809 #define	MAX_CB_ADDR	32
810 
811 tte_t	hw_tte;
812 static ulong_t sfmmu_dmr_maxbit = DMR_MAXBIT;
813 
814 static char	*mmu_ctx_kstat_names[] = {
815 	"mmu_ctx_tsb_exceptions",
816 	"mmu_ctx_tsb_raise_exception",
817 	"mmu_ctx_wrap_around",
818 };
819 
820 /*
821  * Wrapper for vmem_xalloc since vmem_create only allows limited
822  * parameters for vm_source_alloc functions.  This function allows us
823  * to specify alignment consistent with the size of the object being
824  * allocated.
825  */
826 static void *
827 sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *vmp, size_t size, int vmflag)
828 {
829 	return (vmem_xalloc(vmp, size, size, 0, 0, NULL, NULL, vmflag));
830 }
831 
832 /* Common code for setting tsb_alloc_hiwater. */
833 #define	SFMMU_SET_TSB_ALLOC_HIWATER(pages)	tsb_alloc_hiwater = \
834 		ptob(pages) / tsb_alloc_hiwater_factor
835 
836 /*
837  * Set tsb_max_growsize to allow at most all of physical memory to be mapped by
838  * a single TSB.  physmem is the number of physical pages so we need physmem 8K
839  * TTEs to represent all those physical pages.  We round this up by using
840  * 1<<highbit().  To figure out which size code to use, remember that the size
841  * code is just an amount to shift the smallest TSB size to get the size of
842  * this TSB.  So we subtract that size, TSB_START_SIZE, from highbit() (or
843  * highbit() - 1) to get the size code for the smallest TSB that can represent
844  * all of physical memory, while erring on the side of too much.
845  *
846  * Restrict tsb_max_growsize to make sure that:
847  *	1) TSBs can't grow larger than the TSB slab size
848  *	2) TSBs can't grow larger than UTSB_MAX_SZCODE.
849  */
850 #define	SFMMU_SET_TSB_MAX_GROWSIZE(pages) {				\
851 	int	_i, _szc, _slabszc, _tsbszc;				\
852 									\
853 	_i = highbit(pages);						\
854 	if ((1 << (_i - 1)) == (pages))					\
855 		_i--;		/* 2^n case, round down */              \
856 	_szc = _i - TSB_START_SIZE;					\
857 	_slabszc = bigtsb_slab_shift - (TSB_START_SIZE + TSB_ENTRY_SHIFT); \
858 	_tsbszc = MIN(_szc, _slabszc);                                  \
859 	tsb_max_growsize = MIN(_tsbszc, UTSB_MAX_SZCODE);               \
860 }
861 
862 /*
863  * Given a pointer to an sfmmu and a TTE size code, return a pointer to the
864  * tsb_info which handles that TTE size.
865  */
866 #define	SFMMU_GET_TSBINFO(tsbinfop, sfmmup, tte_szc) {			\
867 	(tsbinfop) = (sfmmup)->sfmmu_tsb;				\
868 	ASSERT(((tsbinfop)->tsb_flags & TSB_SHAREDCTX) ||		\
869 	    sfmmu_hat_lock_held(sfmmup));				\
870 	if ((tte_szc) >= TTE4M)	{					\
871 		ASSERT((tsbinfop) != NULL);				\
872 		(tsbinfop) = (tsbinfop)->tsb_next;			\
873 	}								\
874 }
875 
876 /*
877  * Macro to use to unload entries from the TSB.
878  * It has knowledge of which page sizes get replicated in the TSB
879  * and will call the appropriate unload routine for the appropriate size.
880  */
881 #define	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, ismhat)		\
882 {									\
883 	int ttesz = get_hblk_ttesz(hmeblkp);				\
884 	if (ttesz == TTE8K || ttesz == TTE4M) {				\
885 		sfmmu_unload_tsb(sfmmup, addr, ttesz);			\
886 	} else {							\
887 		caddr_t sva = ismhat ? addr : 				\
888 		    (caddr_t)get_hblk_base(hmeblkp);			\
889 		caddr_t eva = sva + get_hblk_span(hmeblkp);		\
890 		ASSERT(addr >= sva && addr < eva);			\
891 		sfmmu_unload_tsb_range(sfmmup, sva, eva, ttesz);	\
892 	}								\
893 }
894 
895 
896 /* Update tsb_alloc_hiwater after memory is configured. */
897 /*ARGSUSED*/
898 static void
899 sfmmu_update_post_add(void *arg, pgcnt_t delta_pages)
900 {
901 	/* Assumes physmem has already been updated. */
902 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
903 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
904 }
905 
906 /*
907  * Update tsb_alloc_hiwater before memory is deleted.  We'll do nothing here
908  * and update tsb_alloc_hiwater and tsb_max_growsize after the memory is
909  * deleted.
910  */
911 /*ARGSUSED*/
912 static int
913 sfmmu_update_pre_del(void *arg, pgcnt_t delta_pages)
914 {
915 	return (0);
916 }
917 
918 /* Update tsb_alloc_hiwater after memory fails to be unconfigured. */
919 /*ARGSUSED*/
920 static void
921 sfmmu_update_post_del(void *arg, pgcnt_t delta_pages, int cancelled)
922 {
923 	/*
924 	 * Whether the delete was cancelled or not, just go ahead and update
925 	 * tsb_alloc_hiwater and tsb_max_growsize.
926 	 */
927 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
928 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
929 }
930 
931 static kphysm_setup_vector_t sfmmu_update_vec = {
932 	KPHYSM_SETUP_VECTOR_VERSION,	/* version */
933 	sfmmu_update_post_add,		/* post_add */
934 	sfmmu_update_pre_del,		/* pre_del */
935 	sfmmu_update_post_del		/* post_del */
936 };
937 
938 
939 /*
940  * HME_BLK HASH PRIMITIVES
941  */
942 
943 /*
944  * Enter a hme on the mapping list for page pp.
945  * When large pages are more prevalent in the system we might want to
946  * keep the mapping list in ascending order by the hment size. For now,
947  * small pages are more frequent, so don't slow it down.
948  */
949 #define	HME_ADD(hme, pp)					\
950 {								\
951 	ASSERT(sfmmu_mlist_held(pp));				\
952 								\
953 	hme->hme_prev = NULL;					\
954 	hme->hme_next = pp->p_mapping;				\
955 	hme->hme_page = pp;					\
956 	if (pp->p_mapping) {					\
957 		((struct sf_hment *)(pp->p_mapping))->hme_prev = hme;\
958 		ASSERT(pp->p_share > 0);			\
959 	} else  {						\
960 		/* EMPTY */					\
961 		ASSERT(pp->p_share == 0);			\
962 	}							\
963 	pp->p_mapping = hme;					\
964 	pp->p_share++;						\
965 }
966 
967 /*
968  * Enter a hme on the mapping list for page pp.
969  * If we are unmapping a large translation, we need to make sure that the
970  * change is reflect in the corresponding bit of the p_index field.
971  */
972 #define	HME_SUB(hme, pp)					\
973 {								\
974 	ASSERT(sfmmu_mlist_held(pp));				\
975 	ASSERT(hme->hme_page == pp || IS_PAHME(hme));		\
976 								\
977 	if (pp->p_mapping == NULL) {				\
978 		panic("hme_remove - no mappings");		\
979 	}							\
980 								\
981 	membar_stst();	/* ensure previous stores finish */	\
982 								\
983 	ASSERT(pp->p_share > 0);				\
984 	pp->p_share--;						\
985 								\
986 	if (hme->hme_prev) {					\
987 		ASSERT(pp->p_mapping != hme);			\
988 		ASSERT(hme->hme_prev->hme_page == pp ||		\
989 			IS_PAHME(hme->hme_prev));		\
990 		hme->hme_prev->hme_next = hme->hme_next;	\
991 	} else {						\
992 		ASSERT(pp->p_mapping == hme);			\
993 		pp->p_mapping = hme->hme_next;			\
994 		ASSERT((pp->p_mapping == NULL) ?		\
995 			(pp->p_share == 0) : 1);		\
996 	}							\
997 								\
998 	if (hme->hme_next) {					\
999 		ASSERT(hme->hme_next->hme_page == pp ||		\
1000 			IS_PAHME(hme->hme_next));		\
1001 		hme->hme_next->hme_prev = hme->hme_prev;	\
1002 	}							\
1003 								\
1004 	/* zero out the entry */				\
1005 	hme->hme_next = NULL;					\
1006 	hme->hme_prev = NULL;					\
1007 	hme->hme_page = NULL;					\
1008 								\
1009 	if (hme_size(hme) > TTE8K) {				\
1010 		/* remove mappings for remainder of large pg */	\
1011 		sfmmu_rm_large_mappings(pp, hme_size(hme));	\
1012 	}							\
1013 }
1014 
1015 /*
1016  * This function returns the hment given the hme_blk and a vaddr.
1017  * It assumes addr has already been checked to belong to hme_blk's
1018  * range.
1019  */
1020 #define	HBLKTOHME(hment, hmeblkp, addr)					\
1021 {									\
1022 	int index;							\
1023 	HBLKTOHME_IDX(hment, hmeblkp, addr, index)			\
1024 }
1025 
1026 /*
1027  * Version of HBLKTOHME that also returns the index in hmeblkp
1028  * of the hment.
1029  */
1030 #define	HBLKTOHME_IDX(hment, hmeblkp, addr, idx)			\
1031 {									\
1032 	ASSERT(in_hblk_range((hmeblkp), (addr)));			\
1033 									\
1034 	if (get_hblk_ttesz(hmeblkp) == TTE8K) {				\
1035 		idx = (((uintptr_t)(addr) >> MMU_PAGESHIFT) & (NHMENTS-1)); \
1036 	} else								\
1037 		idx = 0;						\
1038 									\
1039 	(hment) = &(hmeblkp)->hblk_hme[idx];				\
1040 }
1041 
1042 /*
1043  * Disable any page sizes not supported by the CPU
1044  */
1045 void
1046 hat_init_pagesizes()
1047 {
1048 	int 		i;
1049 
1050 	mmu_exported_page_sizes = 0;
1051 	for (i = TTE8K; i < max_mmu_page_sizes; i++) {
1052 
1053 		szc_2_userszc[i] = (uint_t)-1;
1054 		userszc_2_szc[i] = (uint_t)-1;
1055 
1056 		if ((mmu_exported_pagesize_mask & (1 << i)) == 0) {
1057 			disable_large_pages |= (1 << i);
1058 		} else {
1059 			szc_2_userszc[i] = mmu_exported_page_sizes;
1060 			userszc_2_szc[mmu_exported_page_sizes] = i;
1061 			mmu_exported_page_sizes++;
1062 		}
1063 	}
1064 
1065 	disable_ism_large_pages |= disable_large_pages;
1066 	disable_auto_data_large_pages = disable_large_pages;
1067 	disable_auto_text_large_pages = disable_large_pages;
1068 
1069 	/*
1070 	 * Initialize mmu-specific large page sizes.
1071 	 */
1072 	if (&mmu_large_pages_disabled) {
1073 		disable_large_pages |= mmu_large_pages_disabled(HAT_LOAD);
1074 		disable_ism_large_pages |=
1075 		    mmu_large_pages_disabled(HAT_LOAD_SHARE);
1076 		disable_auto_data_large_pages |=
1077 		    mmu_large_pages_disabled(HAT_AUTO_DATA);
1078 		disable_auto_text_large_pages |=
1079 		    mmu_large_pages_disabled(HAT_AUTO_TEXT);
1080 	}
1081 }
1082 
1083 /*
1084  * Initialize the hardware address translation structures.
1085  */
1086 void
1087 hat_init(void)
1088 {
1089 	int 		i;
1090 	uint_t		sz;
1091 	size_t		size;
1092 
1093 	hat_lock_init();
1094 	hat_kstat_init();
1095 
1096 	/*
1097 	 * Hardware-only bits in a TTE
1098 	 */
1099 	MAKE_TTE_MASK(&hw_tte);
1100 
1101 	hat_init_pagesizes();
1102 
1103 	/* Initialize the hash locks */
1104 	for (i = 0; i < khmehash_num; i++) {
1105 		mutex_init(&khme_hash[i].hmehash_mutex, NULL,
1106 		    MUTEX_DEFAULT, NULL);
1107 		khme_hash[i].hmeh_nextpa = HMEBLK_ENDPA;
1108 	}
1109 	for (i = 0; i < uhmehash_num; i++) {
1110 		mutex_init(&uhme_hash[i].hmehash_mutex, NULL,
1111 		    MUTEX_DEFAULT, NULL);
1112 		uhme_hash[i].hmeh_nextpa = HMEBLK_ENDPA;
1113 	}
1114 	khmehash_num--;		/* make sure counter starts from 0 */
1115 	uhmehash_num--;		/* make sure counter starts from 0 */
1116 
1117 	/*
1118 	 * Allocate context domain structures.
1119 	 *
1120 	 * A platform may choose to modify max_mmu_ctxdoms in
1121 	 * set_platform_defaults(). If a platform does not define
1122 	 * a set_platform_defaults() or does not choose to modify
1123 	 * max_mmu_ctxdoms, it gets one MMU context domain for every CPU.
1124 	 *
1125 	 * For all platforms that have CPUs sharing MMUs, this
1126 	 * value must be defined.
1127 	 */
1128 	if (max_mmu_ctxdoms == 0)
1129 		max_mmu_ctxdoms = max_ncpus;
1130 
1131 	size = max_mmu_ctxdoms * sizeof (mmu_ctx_t *);
1132 	mmu_ctxs_tbl = kmem_zalloc(size, KM_SLEEP);
1133 
1134 	/* mmu_ctx_t is 64 bytes aligned */
1135 	mmuctxdom_cache = kmem_cache_create("mmuctxdom_cache",
1136 	    sizeof (mmu_ctx_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
1137 	/*
1138 	 * MMU context domain initialization for the Boot CPU.
1139 	 * This needs the context domains array allocated above.
1140 	 */
1141 	mutex_enter(&cpu_lock);
1142 	sfmmu_cpu_init(CPU);
1143 	mutex_exit(&cpu_lock);
1144 
1145 	/*
1146 	 * Intialize ism mapping list lock.
1147 	 */
1148 
1149 	mutex_init(&ism_mlist_lock, NULL, MUTEX_DEFAULT, NULL);
1150 
1151 	/*
1152 	 * Each sfmmu structure carries an array of MMU context info
1153 	 * structures, one per context domain. The size of this array depends
1154 	 * on the maximum number of context domains. So, the size of the
1155 	 * sfmmu structure varies per platform.
1156 	 *
1157 	 * sfmmu is allocated from static arena, because trap
1158 	 * handler at TL > 0 is not allowed to touch kernel relocatable
1159 	 * memory. sfmmu's alignment is changed to 64 bytes from
1160 	 * default 8 bytes, as the lower 6 bits will be used to pass
1161 	 * pgcnt to vtag_flush_pgcnt_tl1.
1162 	 */
1163 	size = sizeof (sfmmu_t) + sizeof (sfmmu_ctx_t) * (max_mmu_ctxdoms - 1);
1164 
1165 	sfmmuid_cache = kmem_cache_create("sfmmuid_cache", size,
1166 	    64, sfmmu_idcache_constructor, sfmmu_idcache_destructor,
1167 	    NULL, NULL, static_arena, 0);
1168 
1169 	sfmmu_tsbinfo_cache = kmem_cache_create("sfmmu_tsbinfo_cache",
1170 	    sizeof (struct tsb_info), 0, NULL, NULL, NULL, NULL, NULL, 0);
1171 
1172 	/*
1173 	 * Since we only use the tsb8k cache to "borrow" pages for TSBs
1174 	 * from the heap when low on memory or when TSB_FORCEALLOC is
1175 	 * specified, don't use magazines to cache them--we want to return
1176 	 * them to the system as quickly as possible.
1177 	 */
1178 	sfmmu_tsb8k_cache = kmem_cache_create("sfmmu_tsb8k_cache",
1179 	    MMU_PAGESIZE, MMU_PAGESIZE, NULL, NULL, NULL, NULL,
1180 	    static_arena, KMC_NOMAGAZINE);
1181 
1182 	/*
1183 	 * Set tsb_alloc_hiwater to 1/tsb_alloc_hiwater_factor of physical
1184 	 * memory, which corresponds to the old static reserve for TSBs.
1185 	 * tsb_alloc_hiwater_factor defaults to 32.  This caps the amount of
1186 	 * memory we'll allocate for TSB slabs; beyond this point TSB
1187 	 * allocations will be taken from the kernel heap (via
1188 	 * sfmmu_tsb8k_cache) and will be throttled as would any other kmem
1189 	 * consumer.
1190 	 */
1191 	if (tsb_alloc_hiwater_factor == 0) {
1192 		tsb_alloc_hiwater_factor = TSB_ALLOC_HIWATER_FACTOR_DEFAULT;
1193 	}
1194 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
1195 
1196 	for (sz = tsb_slab_ttesz; sz > 0; sz--) {
1197 		if (!(disable_large_pages & (1 << sz)))
1198 			break;
1199 	}
1200 
1201 	if (sz < tsb_slab_ttesz) {
1202 		tsb_slab_ttesz = sz;
1203 		tsb_slab_shift = MMU_PAGESHIFT + (sz << 1) + sz;
1204 		tsb_slab_size = 1 << tsb_slab_shift;
1205 		tsb_slab_mask = (1 << (tsb_slab_shift - MMU_PAGESHIFT)) - 1;
1206 		use_bigtsb_arena = 0;
1207 	} else if (use_bigtsb_arena &&
1208 	    (disable_large_pages & (1 << bigtsb_slab_ttesz))) {
1209 		use_bigtsb_arena = 0;
1210 	}
1211 
1212 	if (!use_bigtsb_arena) {
1213 		bigtsb_slab_shift = tsb_slab_shift;
1214 	}
1215 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
1216 
1217 	/*
1218 	 * On smaller memory systems, allocate TSB memory in smaller chunks
1219 	 * than the default 4M slab size. We also honor disable_large_pages
1220 	 * here.
1221 	 *
1222 	 * The trap handlers need to be patched with the final slab shift,
1223 	 * since they need to be able to construct the TSB pointer at runtime.
1224 	 */
1225 	if ((tsb_max_growsize <= TSB_512K_SZCODE) &&
1226 	    !(disable_large_pages & (1 << TTE512K))) {
1227 		tsb_slab_ttesz = TTE512K;
1228 		tsb_slab_shift = MMU_PAGESHIFT512K;
1229 		tsb_slab_size = MMU_PAGESIZE512K;
1230 		tsb_slab_mask = MMU_PAGEOFFSET512K >> MMU_PAGESHIFT;
1231 		use_bigtsb_arena = 0;
1232 	}
1233 
1234 	if (!use_bigtsb_arena) {
1235 		bigtsb_slab_ttesz = tsb_slab_ttesz;
1236 		bigtsb_slab_shift = tsb_slab_shift;
1237 		bigtsb_slab_size = tsb_slab_size;
1238 		bigtsb_slab_mask = tsb_slab_mask;
1239 	}
1240 
1241 
1242 	/*
1243 	 * Set up memory callback to update tsb_alloc_hiwater and
1244 	 * tsb_max_growsize.
1245 	 */
1246 	i = kphysm_setup_func_register(&sfmmu_update_vec, (void *) 0);
1247 	ASSERT(i == 0);
1248 
1249 	/*
1250 	 * kmem_tsb_arena is the source from which large TSB slabs are
1251 	 * drawn.  The quantum of this arena corresponds to the largest
1252 	 * TSB size we can dynamically allocate for user processes.
1253 	 * Currently it must also be a supported page size since we
1254 	 * use exactly one translation entry to map each slab page.
1255 	 *
1256 	 * The per-lgroup kmem_tsb_default_arena arenas are the arenas from
1257 	 * which most TSBs are allocated.  Since most TSB allocations are
1258 	 * typically 8K we have a kmem cache we stack on top of each
1259 	 * kmem_tsb_default_arena to speed up those allocations.
1260 	 *
1261 	 * Note the two-level scheme of arenas is required only
1262 	 * because vmem_create doesn't allow us to specify alignment
1263 	 * requirements.  If this ever changes the code could be
1264 	 * simplified to use only one level of arenas.
1265 	 *
1266 	 * If 256M page support exists on sun4v, 256MB kmem_bigtsb_arena
1267 	 * will be provided in addition to the 4M kmem_tsb_arena.
1268 	 */
1269 	if (use_bigtsb_arena) {
1270 		kmem_bigtsb_arena = vmem_create("kmem_bigtsb", NULL, 0,
1271 		    bigtsb_slab_size, sfmmu_vmem_xalloc_aligned_wrapper,
1272 		    vmem_xfree, heap_arena, 0, VM_SLEEP);
1273 	}
1274 
1275 	kmem_tsb_arena = vmem_create("kmem_tsb", NULL, 0, tsb_slab_size,
1276 	    sfmmu_vmem_xalloc_aligned_wrapper,
1277 	    vmem_xfree, heap_arena, 0, VM_SLEEP);
1278 
1279 	if (tsb_lgrp_affinity) {
1280 		char s[50];
1281 		for (i = 0; i < NLGRPS_MAX; i++) {
1282 			if (use_bigtsb_arena) {
1283 				(void) sprintf(s, "kmem_bigtsb_lgrp%d", i);
1284 				kmem_bigtsb_default_arena[i] = vmem_create(s,
1285 				    NULL, 0, 2 * tsb_slab_size,
1286 				    sfmmu_tsb_segkmem_alloc,
1287 				    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena,
1288 				    0, VM_SLEEP | VM_BESTFIT);
1289 			}
1290 
1291 			(void) sprintf(s, "kmem_tsb_lgrp%d", i);
1292 			kmem_tsb_default_arena[i] = vmem_create(s,
1293 			    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1294 			    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1295 			    VM_SLEEP | VM_BESTFIT);
1296 
1297 			(void) sprintf(s, "sfmmu_tsb_lgrp%d_cache", i);
1298 			sfmmu_tsb_cache[i] = kmem_cache_create(s,
1299 			    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1300 			    kmem_tsb_default_arena[i], 0);
1301 		}
1302 	} else {
1303 		if (use_bigtsb_arena) {
1304 			kmem_bigtsb_default_arena[0] =
1305 			    vmem_create("kmem_bigtsb_default", NULL, 0,
1306 			    2 * tsb_slab_size, sfmmu_tsb_segkmem_alloc,
1307 			    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena, 0,
1308 			    VM_SLEEP | VM_BESTFIT);
1309 		}
1310 
1311 		kmem_tsb_default_arena[0] = vmem_create("kmem_tsb_default",
1312 		    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1313 		    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1314 		    VM_SLEEP | VM_BESTFIT);
1315 		sfmmu_tsb_cache[0] = kmem_cache_create("sfmmu_tsb_cache",
1316 		    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1317 		    kmem_tsb_default_arena[0], 0);
1318 	}
1319 
1320 	sfmmu8_cache = kmem_cache_create("sfmmu8_cache", HME8BLK_SZ,
1321 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1322 	    sfmmu_hblkcache_destructor,
1323 	    sfmmu_hblkcache_reclaim, (void *)HME8BLK_SZ,
1324 	    hat_memload_arena, KMC_NOHASH);
1325 
1326 	hat_memload1_arena = vmem_create("hat_memload1", NULL, 0, PAGESIZE,
1327 	    segkmem_alloc_permanent, segkmem_free, heap_arena, 0,
1328 	    VMC_DUMPSAFE | VM_SLEEP);
1329 
1330 	sfmmu1_cache = kmem_cache_create("sfmmu1_cache", HME1BLK_SZ,
1331 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1332 	    sfmmu_hblkcache_destructor,
1333 	    NULL, (void *)HME1BLK_SZ,
1334 	    hat_memload1_arena, KMC_NOHASH);
1335 
1336 	pa_hment_cache = kmem_cache_create("pa_hment_cache", PAHME_SZ,
1337 	    0, NULL, NULL, NULL, NULL, static_arena, KMC_NOHASH);
1338 
1339 	ism_blk_cache = kmem_cache_create("ism_blk_cache",
1340 	    sizeof (ism_blk_t), ecache_alignsize, NULL, NULL,
1341 	    NULL, NULL, static_arena, KMC_NOHASH);
1342 
1343 	ism_ment_cache = kmem_cache_create("ism_ment_cache",
1344 	    sizeof (ism_ment_t), 0, NULL, NULL,
1345 	    NULL, NULL, NULL, 0);
1346 
1347 	/*
1348 	 * We grab the first hat for the kernel,
1349 	 */
1350 	AS_LOCK_ENTER(&kas, &kas.a_lock, RW_WRITER);
1351 	kas.a_hat = hat_alloc(&kas);
1352 	AS_LOCK_EXIT(&kas, &kas.a_lock);
1353 
1354 	/*
1355 	 * Initialize hblk_reserve.
1356 	 */
1357 	((struct hme_blk *)hblk_reserve)->hblk_nextpa =
1358 	    va_to_pa((caddr_t)hblk_reserve);
1359 
1360 #ifndef UTSB_PHYS
1361 	/*
1362 	 * Reserve some kernel virtual address space for the locked TTEs
1363 	 * that allow us to probe the TSB from TL>0.
1364 	 */
1365 	utsb_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1366 	    0, 0, NULL, NULL, VM_SLEEP);
1367 	utsb4m_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1368 	    0, 0, NULL, NULL, VM_SLEEP);
1369 #endif
1370 
1371 #ifdef VAC
1372 	/*
1373 	 * The big page VAC handling code assumes VAC
1374 	 * will not be bigger than the smallest big
1375 	 * page- which is 64K.
1376 	 */
1377 	if (TTEPAGES(TTE64K) < CACHE_NUM_COLOR) {
1378 		cmn_err(CE_PANIC, "VAC too big!");
1379 	}
1380 #endif
1381 
1382 	(void) xhat_init();
1383 
1384 	uhme_hash_pa = va_to_pa(uhme_hash);
1385 	khme_hash_pa = va_to_pa(khme_hash);
1386 
1387 	/*
1388 	 * Initialize relocation locks. kpr_suspendlock is held
1389 	 * at PIL_MAX to prevent interrupts from pinning the holder
1390 	 * of a suspended TTE which may access it leading to a
1391 	 * deadlock condition.
1392 	 */
1393 	mutex_init(&kpr_mutex, NULL, MUTEX_DEFAULT, NULL);
1394 	mutex_init(&kpr_suspendlock, NULL, MUTEX_SPIN, (void *)PIL_MAX);
1395 
1396 	/*
1397 	 * If Shared context support is disabled via /etc/system
1398 	 * set shctx_on to 0 here if it was set to 1 earlier in boot
1399 	 * sequence by cpu module initialization code.
1400 	 */
1401 	if (shctx_on && disable_shctx) {
1402 		shctx_on = 0;
1403 	}
1404 
1405 	if (shctx_on) {
1406 		srd_buckets = kmem_zalloc(SFMMU_MAX_SRD_BUCKETS *
1407 		    sizeof (srd_buckets[0]), KM_SLEEP);
1408 		for (i = 0; i < SFMMU_MAX_SRD_BUCKETS; i++) {
1409 			mutex_init(&srd_buckets[i].srdb_lock, NULL,
1410 			    MUTEX_DEFAULT, NULL);
1411 		}
1412 
1413 		srd_cache = kmem_cache_create("srd_cache", sizeof (sf_srd_t),
1414 		    0, sfmmu_srdcache_constructor, sfmmu_srdcache_destructor,
1415 		    NULL, NULL, NULL, 0);
1416 		region_cache = kmem_cache_create("region_cache",
1417 		    sizeof (sf_region_t), 0, sfmmu_rgncache_constructor,
1418 		    sfmmu_rgncache_destructor, NULL, NULL, NULL, 0);
1419 		scd_cache = kmem_cache_create("scd_cache", sizeof (sf_scd_t),
1420 		    0, sfmmu_scdcache_constructor,  sfmmu_scdcache_destructor,
1421 		    NULL, NULL, NULL, 0);
1422 	}
1423 
1424 	/*
1425 	 * Pre-allocate hrm_hashtab before enabling the collection of
1426 	 * refmod statistics.  Allocating on the fly would mean us
1427 	 * running the risk of suffering recursive mutex enters or
1428 	 * deadlocks.
1429 	 */
1430 	hrm_hashtab = kmem_zalloc(HRM_HASHSIZE * sizeof (struct hrmstat *),
1431 	    KM_SLEEP);
1432 
1433 	/* Allocate per-cpu pending freelist of hmeblks */
1434 	cpu_hme_pend = kmem_zalloc((NCPU * sizeof (cpu_hme_pend_t)) + 64,
1435 	    KM_SLEEP);
1436 	cpu_hme_pend = (cpu_hme_pend_t *)P2ROUNDUP(
1437 	    (uintptr_t)cpu_hme_pend, 64);
1438 
1439 	for (i = 0; i < NCPU; i++) {
1440 		mutex_init(&cpu_hme_pend[i].chp_mutex, NULL, MUTEX_DEFAULT,
1441 		    NULL);
1442 	}
1443 
1444 	if (cpu_hme_pend_thresh == 0) {
1445 		cpu_hme_pend_thresh = CPU_HME_PEND_THRESH;
1446 	}
1447 }
1448 
1449 /*
1450  * Initialize locking for the hat layer, called early during boot.
1451  */
1452 static void
1453 hat_lock_init()
1454 {
1455 	int i;
1456 
1457 	/*
1458 	 * initialize the array of mutexes protecting a page's mapping
1459 	 * list and p_nrm field.
1460 	 */
1461 	for (i = 0; i < mml_table_sz; i++)
1462 		mutex_init(&mml_table[i], NULL, MUTEX_DEFAULT, NULL);
1463 
1464 	if (kpm_enable) {
1465 		for (i = 0; i < kpmp_table_sz; i++) {
1466 			mutex_init(&kpmp_table[i].khl_mutex, NULL,
1467 			    MUTEX_DEFAULT, NULL);
1468 		}
1469 	}
1470 
1471 	/*
1472 	 * Initialize array of mutex locks that protects sfmmu fields and
1473 	 * TSB lists.
1474 	 */
1475 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
1476 		mutex_init(HATLOCK_MUTEXP(&hat_lock[i]), NULL, MUTEX_DEFAULT,
1477 		    NULL);
1478 }
1479 
1480 #define	SFMMU_KERNEL_MAXVA \
1481 	(kmem64_base ? (uintptr_t)kmem64_end : (SYSLIMIT))
1482 
1483 /*
1484  * Allocate a hat structure.
1485  * Called when an address space first uses a hat.
1486  */
1487 struct hat *
1488 hat_alloc(struct as *as)
1489 {
1490 	sfmmu_t *sfmmup;
1491 	int i;
1492 	uint64_t cnum;
1493 	extern uint_t get_color_start(struct as *);
1494 
1495 	ASSERT(AS_WRITE_HELD(as, &as->a_lock));
1496 	sfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
1497 	sfmmup->sfmmu_as = as;
1498 	sfmmup->sfmmu_flags = 0;
1499 	sfmmup->sfmmu_tteflags = 0;
1500 	sfmmup->sfmmu_rtteflags = 0;
1501 	LOCK_INIT_CLEAR(&sfmmup->sfmmu_ctx_lock);
1502 
1503 	if (as == &kas) {
1504 		ksfmmup = sfmmup;
1505 		sfmmup->sfmmu_cext = 0;
1506 		cnum = KCONTEXT;
1507 
1508 		sfmmup->sfmmu_clrstart = 0;
1509 		sfmmup->sfmmu_tsb = NULL;
1510 		/*
1511 		 * hat_kern_setup() will call sfmmu_init_ktsbinfo()
1512 		 * to setup tsb_info for ksfmmup.
1513 		 */
1514 	} else {
1515 
1516 		/*
1517 		 * Just set to invalid ctx. When it faults, it will
1518 		 * get a valid ctx. This would avoid the situation
1519 		 * where we get a ctx, but it gets stolen and then
1520 		 * we fault when we try to run and so have to get
1521 		 * another ctx.
1522 		 */
1523 		sfmmup->sfmmu_cext = 0;
1524 		cnum = INVALID_CONTEXT;
1525 
1526 		/* initialize original physical page coloring bin */
1527 		sfmmup->sfmmu_clrstart = get_color_start(as);
1528 #ifdef DEBUG
1529 		if (tsb_random_size) {
1530 			uint32_t randval = (uint32_t)gettick() >> 4;
1531 			int size = randval % (tsb_max_growsize + 1);
1532 
1533 			/* chose a random tsb size for stress testing */
1534 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb, size,
1535 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1536 		} else
1537 #endif /* DEBUG */
1538 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb,
1539 			    default_tsb_size,
1540 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1541 		sfmmup->sfmmu_flags = HAT_SWAPPED | HAT_ALLCTX_INVALID;
1542 		ASSERT(sfmmup->sfmmu_tsb != NULL);
1543 	}
1544 
1545 	ASSERT(max_mmu_ctxdoms > 0);
1546 	for (i = 0; i < max_mmu_ctxdoms; i++) {
1547 		sfmmup->sfmmu_ctxs[i].cnum = cnum;
1548 		sfmmup->sfmmu_ctxs[i].gnum = 0;
1549 	}
1550 
1551 	for (i = 0; i < max_mmu_page_sizes; i++) {
1552 		sfmmup->sfmmu_ttecnt[i] = 0;
1553 		sfmmup->sfmmu_scdrttecnt[i] = 0;
1554 		sfmmup->sfmmu_ismttecnt[i] = 0;
1555 		sfmmup->sfmmu_scdismttecnt[i] = 0;
1556 		sfmmup->sfmmu_pgsz[i] = TTE8K;
1557 	}
1558 	sfmmup->sfmmu_tsb0_4minflcnt = 0;
1559 	sfmmup->sfmmu_iblk = NULL;
1560 	sfmmup->sfmmu_ismhat = 0;
1561 	sfmmup->sfmmu_scdhat = 0;
1562 	sfmmup->sfmmu_ismblkpa = (uint64_t)-1;
1563 	if (sfmmup == ksfmmup) {
1564 		CPUSET_ALL(sfmmup->sfmmu_cpusran);
1565 	} else {
1566 		CPUSET_ZERO(sfmmup->sfmmu_cpusran);
1567 	}
1568 	sfmmup->sfmmu_free = 0;
1569 	sfmmup->sfmmu_rmstat = 0;
1570 	sfmmup->sfmmu_clrbin = sfmmup->sfmmu_clrstart;
1571 	sfmmup->sfmmu_xhat_provider = NULL;
1572 	cv_init(&sfmmup->sfmmu_tsb_cv, NULL, CV_DEFAULT, NULL);
1573 	sfmmup->sfmmu_srdp = NULL;
1574 	SF_RGNMAP_ZERO(sfmmup->sfmmu_region_map);
1575 	bzero(sfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
1576 	sfmmup->sfmmu_scdp = NULL;
1577 	sfmmup->sfmmu_scd_link.next = NULL;
1578 	sfmmup->sfmmu_scd_link.prev = NULL;
1579 	return (sfmmup);
1580 }
1581 
1582 /*
1583  * Create per-MMU context domain kstats for a given MMU ctx.
1584  */
1585 static void
1586 sfmmu_mmu_kstat_create(mmu_ctx_t *mmu_ctxp)
1587 {
1588 	mmu_ctx_stat_t	stat;
1589 	kstat_t		*mmu_kstat;
1590 
1591 	ASSERT(MUTEX_HELD(&cpu_lock));
1592 	ASSERT(mmu_ctxp->mmu_kstat == NULL);
1593 
1594 	mmu_kstat = kstat_create("unix", mmu_ctxp->mmu_idx, "mmu_ctx",
1595 	    "hat", KSTAT_TYPE_NAMED, MMU_CTX_NUM_STATS, KSTAT_FLAG_VIRTUAL);
1596 
1597 	if (mmu_kstat == NULL) {
1598 		cmn_err(CE_WARN, "kstat_create for MMU %d failed",
1599 		    mmu_ctxp->mmu_idx);
1600 	} else {
1601 		mmu_kstat->ks_data = mmu_ctxp->mmu_kstat_data;
1602 		for (stat = 0; stat < MMU_CTX_NUM_STATS; stat++)
1603 			kstat_named_init(&mmu_ctxp->mmu_kstat_data[stat],
1604 			    mmu_ctx_kstat_names[stat], KSTAT_DATA_INT64);
1605 		mmu_ctxp->mmu_kstat = mmu_kstat;
1606 		kstat_install(mmu_kstat);
1607 	}
1608 }
1609 
1610 /*
1611  * plat_cpuid_to_mmu_ctx_info() is a platform interface that returns MMU
1612  * context domain information for a given CPU. If a platform does not
1613  * specify that interface, then the function below is used instead to return
1614  * default information. The defaults are as follows:
1615  *
1616  *	- The number of MMU context IDs supported on any CPU in the
1617  *	  system is 8K.
1618  *	- There is one MMU context domain per CPU.
1619  */
1620 /*ARGSUSED*/
1621 static void
1622 sfmmu_cpuid_to_mmu_ctx_info(processorid_t cpuid, mmu_ctx_info_t *infop)
1623 {
1624 	infop->mmu_nctxs = nctxs;
1625 	infop->mmu_idx = cpu[cpuid]->cpu_seqid;
1626 }
1627 
1628 /*
1629  * Called during CPU initialization to set the MMU context-related information
1630  * for a CPU.
1631  *
1632  * cpu_lock serializes accesses to mmu_ctxs and mmu_saved_gnum.
1633  */
1634 void
1635 sfmmu_cpu_init(cpu_t *cp)
1636 {
1637 	mmu_ctx_info_t	info;
1638 	mmu_ctx_t	*mmu_ctxp;
1639 
1640 	ASSERT(MUTEX_HELD(&cpu_lock));
1641 
1642 	if (&plat_cpuid_to_mmu_ctx_info == NULL)
1643 		sfmmu_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1644 	else
1645 		plat_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1646 
1647 	ASSERT(info.mmu_idx < max_mmu_ctxdoms);
1648 
1649 	if ((mmu_ctxp = mmu_ctxs_tbl[info.mmu_idx]) == NULL) {
1650 		/* Each mmu_ctx is cacheline aligned. */
1651 		mmu_ctxp = kmem_cache_alloc(mmuctxdom_cache, KM_SLEEP);
1652 		bzero(mmu_ctxp, sizeof (mmu_ctx_t));
1653 
1654 		mutex_init(&mmu_ctxp->mmu_lock, NULL, MUTEX_SPIN,
1655 		    (void *)ipltospl(DISP_LEVEL));
1656 		mmu_ctxp->mmu_idx = info.mmu_idx;
1657 		mmu_ctxp->mmu_nctxs = info.mmu_nctxs;
1658 		/*
1659 		 * Globally for lifetime of a system,
1660 		 * gnum must always increase.
1661 		 * mmu_saved_gnum is protected by the cpu_lock.
1662 		 */
1663 		mmu_ctxp->mmu_gnum = mmu_saved_gnum + 1;
1664 		mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
1665 
1666 		sfmmu_mmu_kstat_create(mmu_ctxp);
1667 
1668 		mmu_ctxs_tbl[info.mmu_idx] = mmu_ctxp;
1669 	} else {
1670 		ASSERT(mmu_ctxp->mmu_idx == info.mmu_idx);
1671 		ASSERT(mmu_ctxp->mmu_nctxs <= info.mmu_nctxs);
1672 	}
1673 
1674 	/*
1675 	 * The mmu_lock is acquired here to prevent races with
1676 	 * the wrap-around code.
1677 	 */
1678 	mutex_enter(&mmu_ctxp->mmu_lock);
1679 
1680 
1681 	mmu_ctxp->mmu_ncpus++;
1682 	CPUSET_ADD(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1683 	CPU_MMU_IDX(cp) = info.mmu_idx;
1684 	CPU_MMU_CTXP(cp) = mmu_ctxp;
1685 
1686 	mutex_exit(&mmu_ctxp->mmu_lock);
1687 }
1688 
1689 static void
1690 sfmmu_ctxdom_free(mmu_ctx_t *mmu_ctxp)
1691 {
1692 	ASSERT(MUTEX_HELD(&cpu_lock));
1693 	ASSERT(!MUTEX_HELD(&mmu_ctxp->mmu_lock));
1694 
1695 	mutex_destroy(&mmu_ctxp->mmu_lock);
1696 
1697 	if (mmu_ctxp->mmu_kstat)
1698 		kstat_delete(mmu_ctxp->mmu_kstat);
1699 
1700 	/* mmu_saved_gnum is protected by the cpu_lock. */
1701 	if (mmu_saved_gnum < mmu_ctxp->mmu_gnum)
1702 		mmu_saved_gnum = mmu_ctxp->mmu_gnum;
1703 
1704 	kmem_cache_free(mmuctxdom_cache, mmu_ctxp);
1705 }
1706 
1707 /*
1708  * Called to perform MMU context-related cleanup for a CPU.
1709  */
1710 void
1711 sfmmu_cpu_cleanup(cpu_t *cp)
1712 {
1713 	mmu_ctx_t	*mmu_ctxp;
1714 
1715 	ASSERT(MUTEX_HELD(&cpu_lock));
1716 
1717 	mmu_ctxp = CPU_MMU_CTXP(cp);
1718 	ASSERT(mmu_ctxp != NULL);
1719 
1720 	/*
1721 	 * The mmu_lock is acquired here to prevent races with
1722 	 * the wrap-around code.
1723 	 */
1724 	mutex_enter(&mmu_ctxp->mmu_lock);
1725 
1726 	CPU_MMU_CTXP(cp) = NULL;
1727 
1728 	CPUSET_DEL(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1729 	if (--mmu_ctxp->mmu_ncpus == 0) {
1730 		mmu_ctxs_tbl[mmu_ctxp->mmu_idx] = NULL;
1731 		mutex_exit(&mmu_ctxp->mmu_lock);
1732 		sfmmu_ctxdom_free(mmu_ctxp);
1733 		return;
1734 	}
1735 
1736 	mutex_exit(&mmu_ctxp->mmu_lock);
1737 }
1738 
1739 uint_t
1740 sfmmu_ctxdom_nctxs(int idx)
1741 {
1742 	return (mmu_ctxs_tbl[idx]->mmu_nctxs);
1743 }
1744 
1745 #ifdef sun4v
1746 /*
1747  * sfmmu_ctxdoms_* is an interface provided to help keep context domains
1748  * consistant after suspend/resume on system that can resume on a different
1749  * hardware than it was suspended.
1750  *
1751  * sfmmu_ctxdom_lock(void) locks all context domains and prevents new contexts
1752  * from being allocated.  It acquires all hat_locks, which blocks most access to
1753  * context data, except for a few cases that are handled separately or are
1754  * harmless.  It wraps each domain to increment gnum and invalidate on-CPU
1755  * contexts, and forces cnum to its max.  As a result of this call all user
1756  * threads that are running on CPUs trap and try to perform wrap around but
1757  * can't because hat_locks are taken.  Threads that were not on CPUs but started
1758  * by scheduler go to sfmmu_alloc_ctx() to aquire context without checking
1759  * hat_lock, but fail, because cnum == nctxs, and therefore also trap and block
1760  * on hat_lock trying to wrap.  sfmmu_ctxdom_lock() must be called before CPUs
1761  * are paused, else it could deadlock acquiring locks held by paused CPUs.
1762  *
1763  * sfmmu_ctxdoms_remove() removes context domains from every CPUs and records
1764  * the CPUs that had them.  It must be called after CPUs have been paused. This
1765  * ensures that no threads are in sfmmu_alloc_ctx() accessing domain data,
1766  * because pause_cpus sends a mondo interrupt to every CPU, and sfmmu_alloc_ctx
1767  * runs with interrupts disabled.  When CPUs are later resumed, they may enter
1768  * sfmmu_alloc_ctx, but it will check for CPU_MMU_CTXP = NULL and immediately
1769  * return failure.  Or, they will be blocked trying to acquire hat_lock. Thus
1770  * after sfmmu_ctxdoms_remove returns, we are guaranteed that no one is
1771  * accessing the old context domains.
1772  *
1773  * sfmmu_ctxdoms_update(void) frees space used by old context domains and
1774  * allocates new context domains based on hardware layout.  It initializes
1775  * every CPU that had context domain before migration to have one again.
1776  * sfmmu_ctxdoms_update must be called after CPUs are resumed, else it
1777  * could deadlock acquiring locks held by paused CPUs.
1778  *
1779  * sfmmu_ctxdoms_unlock(void) releases all hat_locks after which user threads
1780  * acquire new context ids and continue execution.
1781  *
1782  * Therefore functions should be called in the following order:
1783  *       suspend_routine()
1784  *		sfmmu_ctxdom_lock()
1785  *		pause_cpus()
1786  *		suspend()
1787  *			if (suspend failed)
1788  *				sfmmu_ctxdom_unlock()
1789  *		...
1790  *		sfmmu_ctxdom_remove()
1791  *		resume_cpus()
1792  *		sfmmu_ctxdom_update()
1793  *		sfmmu_ctxdom_unlock()
1794  */
1795 static cpuset_t sfmmu_ctxdoms_pset;
1796 
1797 void
1798 sfmmu_ctxdoms_remove()
1799 {
1800 	processorid_t	id;
1801 	cpu_t		*cp;
1802 
1803 	/*
1804 	 * Record the CPUs that have domains in sfmmu_ctxdoms_pset, so they can
1805 	 * be restored post-migration. A CPU may be powered off and not have a
1806 	 * domain, for example.
1807 	 */
1808 	CPUSET_ZERO(sfmmu_ctxdoms_pset);
1809 
1810 	for (id = 0; id < NCPU; id++) {
1811 		if ((cp = cpu[id]) != NULL && CPU_MMU_CTXP(cp) != NULL) {
1812 			CPUSET_ADD(sfmmu_ctxdoms_pset, id);
1813 			CPU_MMU_CTXP(cp) = NULL;
1814 		}
1815 	}
1816 }
1817 
1818 void
1819 sfmmu_ctxdoms_lock(void)
1820 {
1821 	int		idx;
1822 	mmu_ctx_t	*mmu_ctxp;
1823 
1824 	sfmmu_hat_lock_all();
1825 
1826 	/*
1827 	 * At this point, no thread can be in sfmmu_ctx_wrap_around, because
1828 	 * hat_lock is always taken before calling it.
1829 	 *
1830 	 * For each domain, set mmu_cnum to max so no more contexts can be
1831 	 * allocated, and wrap to flush on-CPU contexts and force threads to
1832 	 * acquire a new context when we later drop hat_lock after migration.
1833 	 * Setting mmu_cnum may race with sfmmu_alloc_ctx which also sets cnum,
1834 	 * but the latter uses CAS and will miscompare and not overwrite it.
1835 	 */
1836 	kpreempt_disable(); /* required by sfmmu_ctx_wrap_around */
1837 	for (idx = 0; idx < max_mmu_ctxdoms; idx++) {
1838 		if ((mmu_ctxp = mmu_ctxs_tbl[idx]) != NULL) {
1839 			mutex_enter(&mmu_ctxp->mmu_lock);
1840 			mmu_ctxp->mmu_cnum = mmu_ctxp->mmu_nctxs;
1841 			/* make sure updated cnum visible */
1842 			membar_enter();
1843 			mutex_exit(&mmu_ctxp->mmu_lock);
1844 			sfmmu_ctx_wrap_around(mmu_ctxp, B_FALSE);
1845 		}
1846 	}
1847 	kpreempt_enable();
1848 }
1849 
1850 void
1851 sfmmu_ctxdoms_unlock(void)
1852 {
1853 	sfmmu_hat_unlock_all();
1854 }
1855 
1856 void
1857 sfmmu_ctxdoms_update(void)
1858 {
1859 	processorid_t	id;
1860 	cpu_t		*cp;
1861 	uint_t		idx;
1862 	mmu_ctx_t	*mmu_ctxp;
1863 
1864 	/*
1865 	 * Free all context domains.  As side effect, this increases
1866 	 * mmu_saved_gnum to the maximum gnum over all domains, which is used to
1867 	 * init gnum in the new domains, which therefore will be larger than the
1868 	 * sfmmu gnum for any process, guaranteeing that every process will see
1869 	 * a new generation and allocate a new context regardless of what new
1870 	 * domain it runs in.
1871 	 */
1872 	mutex_enter(&cpu_lock);
1873 
1874 	for (idx = 0; idx < max_mmu_ctxdoms; idx++) {
1875 		if (mmu_ctxs_tbl[idx] != NULL) {
1876 			mmu_ctxp = mmu_ctxs_tbl[idx];
1877 			mmu_ctxs_tbl[idx] = NULL;
1878 			sfmmu_ctxdom_free(mmu_ctxp);
1879 		}
1880 	}
1881 
1882 	for (id = 0; id < NCPU; id++) {
1883 		if (CPU_IN_SET(sfmmu_ctxdoms_pset, id) &&
1884 		    (cp = cpu[id]) != NULL)
1885 			sfmmu_cpu_init(cp);
1886 	}
1887 	mutex_exit(&cpu_lock);
1888 }
1889 #endif
1890 
1891 /*
1892  * Hat_setup, makes an address space context the current active one.
1893  * In sfmmu this translates to setting the secondary context with the
1894  * corresponding context.
1895  */
1896 void
1897 hat_setup(struct hat *sfmmup, int allocflag)
1898 {
1899 	hatlock_t *hatlockp;
1900 
1901 	/* Init needs some special treatment. */
1902 	if (allocflag == HAT_INIT) {
1903 		/*
1904 		 * Make sure that we have
1905 		 * 1. a TSB
1906 		 * 2. a valid ctx that doesn't get stolen after this point.
1907 		 */
1908 		hatlockp = sfmmu_hat_enter(sfmmup);
1909 
1910 		/*
1911 		 * Swap in the TSB.  hat_init() allocates tsbinfos without
1912 		 * TSBs, but we need one for init, since the kernel does some
1913 		 * special things to set up its stack and needs the TSB to
1914 		 * resolve page faults.
1915 		 */
1916 		sfmmu_tsb_swapin(sfmmup, hatlockp);
1917 
1918 		sfmmu_get_ctx(sfmmup);
1919 
1920 		sfmmu_hat_exit(hatlockp);
1921 	} else {
1922 		ASSERT(allocflag == HAT_ALLOC);
1923 
1924 		hatlockp = sfmmu_hat_enter(sfmmup);
1925 		kpreempt_disable();
1926 
1927 		CPUSET_ADD(sfmmup->sfmmu_cpusran, CPU->cpu_id);
1928 		/*
1929 		 * sfmmu_setctx_sec takes <pgsz|cnum> as a parameter,
1930 		 * pagesize bits don't matter in this case since we are passing
1931 		 * INVALID_CONTEXT to it.
1932 		 * Compatibility Note: hw takes care of MMU_SCONTEXT1
1933 		 */
1934 		sfmmu_setctx_sec(INVALID_CONTEXT);
1935 		sfmmu_clear_utsbinfo();
1936 
1937 		kpreempt_enable();
1938 		sfmmu_hat_exit(hatlockp);
1939 	}
1940 }
1941 
1942 /*
1943  * Free all the translation resources for the specified address space.
1944  * Called from as_free when an address space is being destroyed.
1945  */
1946 void
1947 hat_free_start(struct hat *sfmmup)
1948 {
1949 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
1950 	ASSERT(sfmmup != ksfmmup);
1951 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1952 
1953 	sfmmup->sfmmu_free = 1;
1954 	if (sfmmup->sfmmu_scdp != NULL) {
1955 		sfmmu_leave_scd(sfmmup, 0);
1956 	}
1957 
1958 	ASSERT(sfmmup->sfmmu_scdp == NULL);
1959 }
1960 
1961 void
1962 hat_free_end(struct hat *sfmmup)
1963 {
1964 	int i;
1965 
1966 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1967 	ASSERT(sfmmup->sfmmu_free == 1);
1968 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
1969 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
1970 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
1971 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
1972 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
1973 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
1974 
1975 	if (sfmmup->sfmmu_rmstat) {
1976 		hat_freestat(sfmmup->sfmmu_as, NULL);
1977 	}
1978 
1979 	while (sfmmup->sfmmu_tsb != NULL) {
1980 		struct tsb_info *next = sfmmup->sfmmu_tsb->tsb_next;
1981 		sfmmu_tsbinfo_free(sfmmup->sfmmu_tsb);
1982 		sfmmup->sfmmu_tsb = next;
1983 	}
1984 
1985 	if (sfmmup->sfmmu_srdp != NULL) {
1986 		sfmmu_leave_srd(sfmmup);
1987 		ASSERT(sfmmup->sfmmu_srdp == NULL);
1988 		for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1989 			if (sfmmup->sfmmu_hmeregion_links[i] != NULL) {
1990 				kmem_free(sfmmup->sfmmu_hmeregion_links[i],
1991 				    SFMMU_L2_HMERLINKS_SIZE);
1992 				sfmmup->sfmmu_hmeregion_links[i] = NULL;
1993 			}
1994 		}
1995 	}
1996 	sfmmu_free_sfmmu(sfmmup);
1997 
1998 #ifdef DEBUG
1999 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
2000 		ASSERT(sfmmup->sfmmu_hmeregion_links[i] == NULL);
2001 	}
2002 #endif
2003 
2004 	kmem_cache_free(sfmmuid_cache, sfmmup);
2005 }
2006 
2007 /*
2008  * Set up any translation structures, for the specified address space,
2009  * that are needed or preferred when the process is being swapped in.
2010  */
2011 /* ARGSUSED */
2012 void
2013 hat_swapin(struct hat *hat)
2014 {
2015 	ASSERT(hat->sfmmu_xhat_provider == NULL);
2016 }
2017 
2018 /*
2019  * Free all of the translation resources, for the specified address space,
2020  * that can be freed while the process is swapped out. Called from as_swapout.
2021  * Also, free up the ctx that this process was using.
2022  */
2023 void
2024 hat_swapout(struct hat *sfmmup)
2025 {
2026 	struct hmehash_bucket *hmebp;
2027 	struct hme_blk *hmeblkp;
2028 	struct hme_blk *pr_hblk = NULL;
2029 	struct hme_blk *nx_hblk;
2030 	int i;
2031 	struct hme_blk *list = NULL;
2032 	hatlock_t *hatlockp;
2033 	struct tsb_info *tsbinfop;
2034 	struct free_tsb {
2035 		struct free_tsb *next;
2036 		struct tsb_info *tsbinfop;
2037 	};			/* free list of TSBs */
2038 	struct free_tsb *freelist, *last, *next;
2039 
2040 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
2041 	SFMMU_STAT(sf_swapout);
2042 
2043 	/*
2044 	 * There is no way to go from an as to all its translations in sfmmu.
2045 	 * Here is one of the times when we take the big hit and traverse
2046 	 * the hash looking for hme_blks to free up.  Not only do we free up
2047 	 * this as hme_blks but all those that are free.  We are obviously
2048 	 * swapping because we need memory so let's free up as much
2049 	 * as we can.
2050 	 *
2051 	 * Note that we don't flush TLB/TSB here -- it's not necessary
2052 	 * because:
2053 	 *  1) we free the ctx we're using and throw away the TSB(s);
2054 	 *  2) processes aren't runnable while being swapped out.
2055 	 */
2056 	ASSERT(sfmmup != KHATID);
2057 	for (i = 0; i <= UHMEHASH_SZ; i++) {
2058 		hmebp = &uhme_hash[i];
2059 		SFMMU_HASH_LOCK(hmebp);
2060 		hmeblkp = hmebp->hmeblkp;
2061 		pr_hblk = NULL;
2062 		while (hmeblkp) {
2063 
2064 			ASSERT(!hmeblkp->hblk_xhat_bit);
2065 
2066 			if ((hmeblkp->hblk_tag.htag_id == sfmmup) &&
2067 			    !hmeblkp->hblk_shw_bit && !hmeblkp->hblk_lckcnt) {
2068 				ASSERT(!hmeblkp->hblk_shared);
2069 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
2070 				    (caddr_t)get_hblk_base(hmeblkp),
2071 				    get_hblk_endaddr(hmeblkp),
2072 				    NULL, HAT_UNLOAD);
2073 			}
2074 			nx_hblk = hmeblkp->hblk_next;
2075 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
2076 				ASSERT(!hmeblkp->hblk_lckcnt);
2077 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
2078 				    &list, 0);
2079 			} else {
2080 				pr_hblk = hmeblkp;
2081 			}
2082 			hmeblkp = nx_hblk;
2083 		}
2084 		SFMMU_HASH_UNLOCK(hmebp);
2085 	}
2086 
2087 	sfmmu_hblks_list_purge(&list, 0);
2088 
2089 	/*
2090 	 * Now free up the ctx so that others can reuse it.
2091 	 */
2092 	hatlockp = sfmmu_hat_enter(sfmmup);
2093 
2094 	sfmmu_invalidate_ctx(sfmmup);
2095 
2096 	/*
2097 	 * Free TSBs, but not tsbinfos, and set SWAPPED flag.
2098 	 * If TSBs were never swapped in, just return.
2099 	 * This implies that we don't support partial swapping
2100 	 * of TSBs -- either all are swapped out, or none are.
2101 	 *
2102 	 * We must hold the HAT lock here to prevent racing with another
2103 	 * thread trying to unmap TTEs from the TSB or running the post-
2104 	 * relocator after relocating the TSB's memory.  Unfortunately, we
2105 	 * can't free memory while holding the HAT lock or we could
2106 	 * deadlock, so we build a list of TSBs to be freed after marking
2107 	 * the tsbinfos as swapped out and free them after dropping the
2108 	 * lock.
2109 	 */
2110 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
2111 		sfmmu_hat_exit(hatlockp);
2112 		return;
2113 	}
2114 
2115 	SFMMU_FLAGS_SET(sfmmup, HAT_SWAPPED);
2116 	last = freelist = NULL;
2117 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
2118 	    tsbinfop = tsbinfop->tsb_next) {
2119 		ASSERT((tsbinfop->tsb_flags & TSB_SWAPPED) == 0);
2120 
2121 		/*
2122 		 * Cast the TSB into a struct free_tsb and put it on the free
2123 		 * list.
2124 		 */
2125 		if (freelist == NULL) {
2126 			last = freelist = (struct free_tsb *)tsbinfop->tsb_va;
2127 		} else {
2128 			last->next = (struct free_tsb *)tsbinfop->tsb_va;
2129 			last = last->next;
2130 		}
2131 		last->next = NULL;
2132 		last->tsbinfop = tsbinfop;
2133 		tsbinfop->tsb_flags |= TSB_SWAPPED;
2134 		/*
2135 		 * Zero out the TTE to clear the valid bit.
2136 		 * Note we can't use a value like 0xbad because we want to
2137 		 * ensure diagnostic bits are NEVER set on TTEs that might
2138 		 * be loaded.  The intent is to catch any invalid access
2139 		 * to the swapped TSB, such as a thread running with a valid
2140 		 * context without first calling sfmmu_tsb_swapin() to
2141 		 * allocate TSB memory.
2142 		 */
2143 		tsbinfop->tsb_tte.ll = 0;
2144 	}
2145 
2146 	/* Now we can drop the lock and free the TSB memory. */
2147 	sfmmu_hat_exit(hatlockp);
2148 	for (; freelist != NULL; freelist = next) {
2149 		next = freelist->next;
2150 		sfmmu_tsb_free(freelist->tsbinfop);
2151 	}
2152 }
2153 
2154 /*
2155  * Duplicate the translations of an as into another newas
2156  */
2157 /* ARGSUSED */
2158 int
2159 hat_dup(struct hat *hat, struct hat *newhat, caddr_t addr, size_t len,
2160 	uint_t flag)
2161 {
2162 	sf_srd_t *srdp;
2163 	sf_scd_t *scdp;
2164 	int i;
2165 	extern uint_t get_color_start(struct as *);
2166 
2167 	ASSERT(hat->sfmmu_xhat_provider == NULL);
2168 	ASSERT((flag == 0) || (flag == HAT_DUP_ALL) || (flag == HAT_DUP_COW) ||
2169 	    (flag == HAT_DUP_SRD));
2170 	ASSERT(hat != ksfmmup);
2171 	ASSERT(newhat != ksfmmup);
2172 	ASSERT(flag != HAT_DUP_ALL || hat->sfmmu_srdp == newhat->sfmmu_srdp);
2173 
2174 	if (flag == HAT_DUP_COW) {
2175 		panic("hat_dup: HAT_DUP_COW not supported");
2176 	}
2177 
2178 	if (flag == HAT_DUP_SRD && ((srdp = hat->sfmmu_srdp) != NULL)) {
2179 		ASSERT(srdp->srd_evp != NULL);
2180 		VN_HOLD(srdp->srd_evp);
2181 		ASSERT(srdp->srd_refcnt > 0);
2182 		newhat->sfmmu_srdp = srdp;
2183 		atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
2184 	}
2185 
2186 	/*
2187 	 * HAT_DUP_ALL flag is used after as duplication is done.
2188 	 */
2189 	if (flag == HAT_DUP_ALL && ((srdp = newhat->sfmmu_srdp) != NULL)) {
2190 		ASSERT(newhat->sfmmu_srdp->srd_refcnt >= 2);
2191 		newhat->sfmmu_rtteflags = hat->sfmmu_rtteflags;
2192 		if (hat->sfmmu_flags & HAT_4MTEXT_FLAG) {
2193 			newhat->sfmmu_flags |= HAT_4MTEXT_FLAG;
2194 		}
2195 
2196 		/* check if need to join scd */
2197 		if ((scdp = hat->sfmmu_scdp) != NULL &&
2198 		    newhat->sfmmu_scdp != scdp) {
2199 			int ret;
2200 			SF_RGNMAP_IS_SUBSET(&newhat->sfmmu_region_map,
2201 			    &scdp->scd_region_map, ret);
2202 			ASSERT(ret);
2203 			sfmmu_join_scd(scdp, newhat);
2204 			ASSERT(newhat->sfmmu_scdp == scdp &&
2205 			    scdp->scd_refcnt >= 2);
2206 			for (i = 0; i < max_mmu_page_sizes; i++) {
2207 				newhat->sfmmu_ismttecnt[i] =
2208 				    hat->sfmmu_ismttecnt[i];
2209 				newhat->sfmmu_scdismttecnt[i] =
2210 				    hat->sfmmu_scdismttecnt[i];
2211 			}
2212 		}
2213 
2214 		sfmmu_check_page_sizes(newhat, 1);
2215 	}
2216 
2217 	if (flag == HAT_DUP_ALL && consistent_coloring == 0 &&
2218 	    update_proc_pgcolorbase_after_fork != 0) {
2219 		hat->sfmmu_clrbin = get_color_start(hat->sfmmu_as);
2220 	}
2221 	return (0);
2222 }
2223 
2224 void
2225 hat_memload(struct hat *hat, caddr_t addr, struct page *pp,
2226 	uint_t attr, uint_t flags)
2227 {
2228 	hat_do_memload(hat, addr, pp, attr, flags,
2229 	    SFMMU_INVALID_SHMERID);
2230 }
2231 
2232 void
2233 hat_memload_region(struct hat *hat, caddr_t addr, struct page *pp,
2234 	uint_t attr, uint_t flags, hat_region_cookie_t rcookie)
2235 {
2236 	uint_t rid;
2237 	if (rcookie == HAT_INVALID_REGION_COOKIE ||
2238 	    hat->sfmmu_xhat_provider != NULL) {
2239 		hat_do_memload(hat, addr, pp, attr, flags,
2240 		    SFMMU_INVALID_SHMERID);
2241 		return;
2242 	}
2243 	rid = (uint_t)((uint64_t)rcookie);
2244 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2245 	hat_do_memload(hat, addr, pp, attr, flags, rid);
2246 }
2247 
2248 /*
2249  * Set up addr to map to page pp with protection prot.
2250  * As an optimization we also load the TSB with the
2251  * corresponding tte but it is no big deal if  the tte gets kicked out.
2252  */
2253 static void
2254 hat_do_memload(struct hat *hat, caddr_t addr, struct page *pp,
2255 	uint_t attr, uint_t flags, uint_t rid)
2256 {
2257 	tte_t tte;
2258 
2259 
2260 	ASSERT(hat != NULL);
2261 	ASSERT(PAGE_LOCKED(pp));
2262 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2263 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2264 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2265 	SFMMU_VALIDATE_HMERID(hat, rid, addr, MMU_PAGESIZE);
2266 
2267 	if (PP_ISFREE(pp)) {
2268 		panic("hat_memload: loading a mapping to free page %p",
2269 		    (void *)pp);
2270 	}
2271 
2272 	if (hat->sfmmu_xhat_provider) {
2273 		/* no regions for xhats */
2274 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
2275 		XHAT_MEMLOAD(hat, addr, pp, attr, flags);
2276 		return;
2277 	}
2278 
2279 	ASSERT((hat == ksfmmup) ||
2280 	    AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
2281 
2282 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2283 		cmn_err(CE_NOTE, "hat_memload: unsupported flags %d",
2284 		    flags & ~SFMMU_LOAD_ALLFLAG);
2285 
2286 	if (hat->sfmmu_rmstat)
2287 		hat_resvstat(MMU_PAGESIZE, hat->sfmmu_as, addr);
2288 
2289 #if defined(SF_ERRATA_57)
2290 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2291 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2292 	    !(flags & HAT_LOAD_SHARE)) {
2293 		cmn_err(CE_WARN, "hat_memload: illegal attempt to make user "
2294 		    " page executable");
2295 		attr &= ~PROT_EXEC;
2296 	}
2297 #endif
2298 
2299 	sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2300 	(void) sfmmu_tteload_array(hat, &tte, addr, &pp, flags, rid);
2301 
2302 	/*
2303 	 * Check TSB and TLB page sizes.
2304 	 */
2305 	if ((flags & HAT_LOAD_SHARE) == 0) {
2306 		sfmmu_check_page_sizes(hat, 1);
2307 	}
2308 }
2309 
2310 /*
2311  * hat_devload can be called to map real memory (e.g.
2312  * /dev/kmem) and even though hat_devload will determine pf is
2313  * for memory, it will be unable to get a shared lock on the
2314  * page (because someone else has it exclusively) and will
2315  * pass dp = NULL.  If tteload doesn't get a non-NULL
2316  * page pointer it can't cache memory.
2317  */
2318 void
2319 hat_devload(struct hat *hat, caddr_t addr, size_t len, pfn_t pfn,
2320 	uint_t attr, int flags)
2321 {
2322 	tte_t tte;
2323 	struct page *pp = NULL;
2324 	int use_lgpg = 0;
2325 
2326 	ASSERT(hat != NULL);
2327 
2328 	if (hat->sfmmu_xhat_provider) {
2329 		XHAT_DEVLOAD(hat, addr, len, pfn, attr, flags);
2330 		return;
2331 	}
2332 
2333 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2334 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2335 	ASSERT((hat == ksfmmup) ||
2336 	    AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
2337 	if (len == 0)
2338 		panic("hat_devload: zero len");
2339 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2340 		cmn_err(CE_NOTE, "hat_devload: unsupported flags %d",
2341 		    flags & ~SFMMU_LOAD_ALLFLAG);
2342 
2343 #if defined(SF_ERRATA_57)
2344 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2345 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2346 	    !(flags & HAT_LOAD_SHARE)) {
2347 		cmn_err(CE_WARN, "hat_devload: illegal attempt to make user "
2348 		    " page executable");
2349 		attr &= ~PROT_EXEC;
2350 	}
2351 #endif
2352 
2353 	/*
2354 	 * If it's a memory page find its pp
2355 	 */
2356 	if (!(flags & HAT_LOAD_NOCONSIST) && pf_is_memory(pfn)) {
2357 		pp = page_numtopp_nolock(pfn);
2358 		if (pp == NULL) {
2359 			flags |= HAT_LOAD_NOCONSIST;
2360 		} else {
2361 			if (PP_ISFREE(pp)) {
2362 				panic("hat_memload: loading "
2363 				    "a mapping to free page %p",
2364 				    (void *)pp);
2365 			}
2366 			if (!PAGE_LOCKED(pp) && !PP_ISNORELOC(pp)) {
2367 				panic("hat_memload: loading a mapping "
2368 				    "to unlocked relocatable page %p",
2369 				    (void *)pp);
2370 			}
2371 			ASSERT(len == MMU_PAGESIZE);
2372 		}
2373 	}
2374 
2375 	if (hat->sfmmu_rmstat)
2376 		hat_resvstat(len, hat->sfmmu_as, addr);
2377 
2378 	if (flags & HAT_LOAD_NOCONSIST) {
2379 		attr |= SFMMU_UNCACHEVTTE;
2380 		use_lgpg = 1;
2381 	}
2382 	if (!pf_is_memory(pfn)) {
2383 		attr |= SFMMU_UNCACHEPTTE | HAT_NOSYNC;
2384 		use_lgpg = 1;
2385 		switch (attr & HAT_ORDER_MASK) {
2386 			case HAT_STRICTORDER:
2387 			case HAT_UNORDERED_OK:
2388 				/*
2389 				 * we set the side effect bit for all non
2390 				 * memory mappings unless merging is ok
2391 				 */
2392 				attr |= SFMMU_SIDEFFECT;
2393 				break;
2394 			case HAT_MERGING_OK:
2395 			case HAT_LOADCACHING_OK:
2396 			case HAT_STORECACHING_OK:
2397 				break;
2398 			default:
2399 				panic("hat_devload: bad attr");
2400 				break;
2401 		}
2402 	}
2403 	while (len) {
2404 		if (!use_lgpg) {
2405 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2406 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2407 			    flags, SFMMU_INVALID_SHMERID);
2408 			len -= MMU_PAGESIZE;
2409 			addr += MMU_PAGESIZE;
2410 			pfn++;
2411 			continue;
2412 		}
2413 		/*
2414 		 *  try to use large pages, check va/pa alignments
2415 		 *  Note that 32M/256M page sizes are not (yet) supported.
2416 		 */
2417 		if ((len >= MMU_PAGESIZE4M) &&
2418 		    !((uintptr_t)addr & MMU_PAGEOFFSET4M) &&
2419 		    !(disable_large_pages & (1 << TTE4M)) &&
2420 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET4M)) {
2421 			sfmmu_memtte(&tte, pfn, attr, TTE4M);
2422 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2423 			    flags, SFMMU_INVALID_SHMERID);
2424 			len -= MMU_PAGESIZE4M;
2425 			addr += MMU_PAGESIZE4M;
2426 			pfn += MMU_PAGESIZE4M / MMU_PAGESIZE;
2427 		} else if ((len >= MMU_PAGESIZE512K) &&
2428 		    !((uintptr_t)addr & MMU_PAGEOFFSET512K) &&
2429 		    !(disable_large_pages & (1 << TTE512K)) &&
2430 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET512K)) {
2431 			sfmmu_memtte(&tte, pfn, attr, TTE512K);
2432 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2433 			    flags, SFMMU_INVALID_SHMERID);
2434 			len -= MMU_PAGESIZE512K;
2435 			addr += MMU_PAGESIZE512K;
2436 			pfn += MMU_PAGESIZE512K / MMU_PAGESIZE;
2437 		} else if ((len >= MMU_PAGESIZE64K) &&
2438 		    !((uintptr_t)addr & MMU_PAGEOFFSET64K) &&
2439 		    !(disable_large_pages & (1 << TTE64K)) &&
2440 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET64K)) {
2441 			sfmmu_memtte(&tte, pfn, attr, TTE64K);
2442 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2443 			    flags, SFMMU_INVALID_SHMERID);
2444 			len -= MMU_PAGESIZE64K;
2445 			addr += MMU_PAGESIZE64K;
2446 			pfn += MMU_PAGESIZE64K / MMU_PAGESIZE;
2447 		} else {
2448 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2449 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2450 			    flags, SFMMU_INVALID_SHMERID);
2451 			len -= MMU_PAGESIZE;
2452 			addr += MMU_PAGESIZE;
2453 			pfn++;
2454 		}
2455 	}
2456 
2457 	/*
2458 	 * Check TSB and TLB page sizes.
2459 	 */
2460 	if ((flags & HAT_LOAD_SHARE) == 0) {
2461 		sfmmu_check_page_sizes(hat, 1);
2462 	}
2463 }
2464 
2465 void
2466 hat_memload_array(struct hat *hat, caddr_t addr, size_t len,
2467 	struct page **pps, uint_t attr, uint_t flags)
2468 {
2469 	hat_do_memload_array(hat, addr, len, pps, attr, flags,
2470 	    SFMMU_INVALID_SHMERID);
2471 }
2472 
2473 void
2474 hat_memload_array_region(struct hat *hat, caddr_t addr, size_t len,
2475 	struct page **pps, uint_t attr, uint_t flags,
2476 	hat_region_cookie_t rcookie)
2477 {
2478 	uint_t rid;
2479 	if (rcookie == HAT_INVALID_REGION_COOKIE ||
2480 	    hat->sfmmu_xhat_provider != NULL) {
2481 		hat_do_memload_array(hat, addr, len, pps, attr, flags,
2482 		    SFMMU_INVALID_SHMERID);
2483 		return;
2484 	}
2485 	rid = (uint_t)((uint64_t)rcookie);
2486 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2487 	hat_do_memload_array(hat, addr, len, pps, attr, flags, rid);
2488 }
2489 
2490 /*
2491  * Map the largest extend possible out of the page array. The array may NOT
2492  * be in order.  The largest possible mapping a page can have
2493  * is specified in the p_szc field.  The p_szc field
2494  * cannot change as long as there any mappings (large or small)
2495  * to any of the pages that make up the large page. (ie. any
2496  * promotion/demotion of page size is not up to the hat but up to
2497  * the page free list manager).  The array
2498  * should consist of properly aligned contigous pages that are
2499  * part of a big page for a large mapping to be created.
2500  */
2501 static void
2502 hat_do_memload_array(struct hat *hat, caddr_t addr, size_t len,
2503 	struct page **pps, uint_t attr, uint_t flags, uint_t rid)
2504 {
2505 	int  ttesz;
2506 	size_t mapsz;
2507 	pgcnt_t	numpg, npgs;
2508 	tte_t tte;
2509 	page_t *pp;
2510 	uint_t large_pages_disable;
2511 
2512 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2513 	SFMMU_VALIDATE_HMERID(hat, rid, addr, len);
2514 
2515 	if (hat->sfmmu_xhat_provider) {
2516 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
2517 		XHAT_MEMLOAD_ARRAY(hat, addr, len, pps, attr, flags);
2518 		return;
2519 	}
2520 
2521 	if (hat->sfmmu_rmstat)
2522 		hat_resvstat(len, hat->sfmmu_as, addr);
2523 
2524 #if defined(SF_ERRATA_57)
2525 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2526 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2527 	    !(flags & HAT_LOAD_SHARE)) {
2528 		cmn_err(CE_WARN, "hat_memload_array: illegal attempt to make "
2529 		    "user page executable");
2530 		attr &= ~PROT_EXEC;
2531 	}
2532 #endif
2533 
2534 	/* Get number of pages */
2535 	npgs = len >> MMU_PAGESHIFT;
2536 
2537 	if (flags & HAT_LOAD_SHARE) {
2538 		large_pages_disable = disable_ism_large_pages;
2539 	} else {
2540 		large_pages_disable = disable_large_pages;
2541 	}
2542 
2543 	if (npgs < NHMENTS || large_pages_disable == LARGE_PAGES_OFF) {
2544 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2545 		    rid);
2546 		return;
2547 	}
2548 
2549 	while (npgs >= NHMENTS) {
2550 		pp = *pps;
2551 		for (ttesz = pp->p_szc; ttesz != TTE8K; ttesz--) {
2552 			/*
2553 			 * Check if this page size is disabled.
2554 			 */
2555 			if (large_pages_disable & (1 << ttesz))
2556 				continue;
2557 
2558 			numpg = TTEPAGES(ttesz);
2559 			mapsz = numpg << MMU_PAGESHIFT;
2560 			if ((npgs >= numpg) &&
2561 			    IS_P2ALIGNED(addr, mapsz) &&
2562 			    IS_P2ALIGNED(pp->p_pagenum, numpg)) {
2563 				/*
2564 				 * At this point we have enough pages and
2565 				 * we know the virtual address and the pfn
2566 				 * are properly aligned.  We still need
2567 				 * to check for physical contiguity but since
2568 				 * it is very likely that this is the case
2569 				 * we will assume they are so and undo
2570 				 * the request if necessary.  It would
2571 				 * be great if we could get a hint flag
2572 				 * like HAT_CONTIG which would tell us
2573 				 * the pages are contigous for sure.
2574 				 */
2575 				sfmmu_memtte(&tte, (*pps)->p_pagenum,
2576 				    attr, ttesz);
2577 				if (!sfmmu_tteload_array(hat, &tte, addr,
2578 				    pps, flags, rid)) {
2579 					break;
2580 				}
2581 			}
2582 		}
2583 		if (ttesz == TTE8K) {
2584 			/*
2585 			 * We were not able to map array using a large page
2586 			 * batch a hmeblk or fraction at a time.
2587 			 */
2588 			numpg = ((uintptr_t)addr >> MMU_PAGESHIFT)
2589 			    & (NHMENTS-1);
2590 			numpg = NHMENTS - numpg;
2591 			ASSERT(numpg <= npgs);
2592 			mapsz = numpg * MMU_PAGESIZE;
2593 			sfmmu_memload_batchsmall(hat, addr, pps, attr, flags,
2594 			    numpg, rid);
2595 		}
2596 		addr += mapsz;
2597 		npgs -= numpg;
2598 		pps += numpg;
2599 	}
2600 
2601 	if (npgs) {
2602 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2603 		    rid);
2604 	}
2605 
2606 	/*
2607 	 * Check TSB and TLB page sizes.
2608 	 */
2609 	if ((flags & HAT_LOAD_SHARE) == 0) {
2610 		sfmmu_check_page_sizes(hat, 1);
2611 	}
2612 }
2613 
2614 /*
2615  * Function tries to batch 8K pages into the same hme blk.
2616  */
2617 static void
2618 sfmmu_memload_batchsmall(struct hat *hat, caddr_t vaddr, page_t **pps,
2619 		    uint_t attr, uint_t flags, pgcnt_t npgs, uint_t rid)
2620 {
2621 	tte_t	tte;
2622 	page_t *pp;
2623 	struct hmehash_bucket *hmebp;
2624 	struct hme_blk *hmeblkp;
2625 	int	index;
2626 
2627 	while (npgs) {
2628 		/*
2629 		 * Acquire the hash bucket.
2630 		 */
2631 		hmebp = sfmmu_tteload_acquire_hashbucket(hat, vaddr, TTE8K,
2632 		    rid);
2633 		ASSERT(hmebp);
2634 
2635 		/*
2636 		 * Find the hment block.
2637 		 */
2638 		hmeblkp = sfmmu_tteload_find_hmeblk(hat, hmebp, vaddr,
2639 		    TTE8K, flags, rid);
2640 		ASSERT(hmeblkp);
2641 
2642 		do {
2643 			/*
2644 			 * Make the tte.
2645 			 */
2646 			pp = *pps;
2647 			sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2648 
2649 			/*
2650 			 * Add the translation.
2651 			 */
2652 			(void) sfmmu_tteload_addentry(hat, hmeblkp, &tte,
2653 			    vaddr, pps, flags, rid);
2654 
2655 			/*
2656 			 * Goto next page.
2657 			 */
2658 			pps++;
2659 			npgs--;
2660 
2661 			/*
2662 			 * Goto next address.
2663 			 */
2664 			vaddr += MMU_PAGESIZE;
2665 
2666 			/*
2667 			 * Don't crossover into a different hmentblk.
2668 			 */
2669 			index = (int)(((uintptr_t)vaddr >> MMU_PAGESHIFT) &
2670 			    (NHMENTS-1));
2671 
2672 		} while (index != 0 && npgs != 0);
2673 
2674 		/*
2675 		 * Release the hash bucket.
2676 		 */
2677 
2678 		sfmmu_tteload_release_hashbucket(hmebp);
2679 	}
2680 }
2681 
2682 /*
2683  * Construct a tte for a page:
2684  *
2685  * tte_valid = 1
2686  * tte_size2 = size & TTE_SZ2_BITS (Panther and Olympus-C only)
2687  * tte_size = size
2688  * tte_nfo = attr & HAT_NOFAULT
2689  * tte_ie = attr & HAT_STRUCTURE_LE
2690  * tte_hmenum = hmenum
2691  * tte_pahi = pp->p_pagenum >> TTE_PASHIFT;
2692  * tte_palo = pp->p_pagenum & TTE_PALOMASK;
2693  * tte_ref = 1 (optimization)
2694  * tte_wr_perm = attr & PROT_WRITE;
2695  * tte_no_sync = attr & HAT_NOSYNC
2696  * tte_lock = attr & SFMMU_LOCKTTE
2697  * tte_cp = !(attr & SFMMU_UNCACHEPTTE)
2698  * tte_cv = !(attr & SFMMU_UNCACHEVTTE)
2699  * tte_e = attr & SFMMU_SIDEFFECT
2700  * tte_priv = !(attr & PROT_USER)
2701  * tte_hwwr = if nosync is set and it is writable we set the mod bit (opt)
2702  * tte_glb = 0
2703  */
2704 void
2705 sfmmu_memtte(tte_t *ttep, pfn_t pfn, uint_t attr, int tte_sz)
2706 {
2707 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2708 
2709 	ttep->tte_inthi = MAKE_TTE_INTHI(pfn, attr, tte_sz, 0 /* hmenum */);
2710 	ttep->tte_intlo = MAKE_TTE_INTLO(pfn, attr, tte_sz, 0 /* hmenum */);
2711 
2712 	if (TTE_IS_NOSYNC(ttep)) {
2713 		TTE_SET_REF(ttep);
2714 		if (TTE_IS_WRITABLE(ttep)) {
2715 			TTE_SET_MOD(ttep);
2716 		}
2717 	}
2718 	if (TTE_IS_NFO(ttep) && TTE_IS_EXECUTABLE(ttep)) {
2719 		panic("sfmmu_memtte: can't set both NFO and EXEC bits");
2720 	}
2721 }
2722 
2723 /*
2724  * This function will add a translation to the hme_blk and allocate the
2725  * hme_blk if one does not exist.
2726  * If a page structure is specified then it will add the
2727  * corresponding hment to the mapping list.
2728  * It will also update the hmenum field for the tte.
2729  *
2730  * Currently this function is only used for kernel mappings.
2731  * So pass invalid region to sfmmu_tteload_array().
2732  */
2733 void
2734 sfmmu_tteload(struct hat *sfmmup, tte_t *ttep, caddr_t vaddr, page_t *pp,
2735 	uint_t flags)
2736 {
2737 	ASSERT(sfmmup == ksfmmup);
2738 	(void) sfmmu_tteload_array(sfmmup, ttep, vaddr, &pp, flags,
2739 	    SFMMU_INVALID_SHMERID);
2740 }
2741 
2742 /*
2743  * Load (ttep != NULL) or unload (ttep == NULL) one entry in the TSB.
2744  * Assumes that a particular page size may only be resident in one TSB.
2745  */
2746 static void
2747 sfmmu_mod_tsb(sfmmu_t *sfmmup, caddr_t vaddr, tte_t *ttep, int ttesz)
2748 {
2749 	struct tsb_info *tsbinfop = NULL;
2750 	uint64_t tag;
2751 	struct tsbe *tsbe_addr;
2752 	uint64_t tsb_base;
2753 	uint_t tsb_size;
2754 	int vpshift = MMU_PAGESHIFT;
2755 	int phys = 0;
2756 
2757 	if (sfmmup == ksfmmup) { /* No support for 32/256M ksfmmu pages */
2758 		phys = ktsb_phys;
2759 		if (ttesz >= TTE4M) {
2760 #ifndef sun4v
2761 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2762 #endif
2763 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2764 			tsb_size = ktsb4m_szcode;
2765 		} else {
2766 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2767 			tsb_size = ktsb_szcode;
2768 		}
2769 	} else {
2770 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2771 
2772 		/*
2773 		 * If there isn't a TSB for this page size, or the TSB is
2774 		 * swapped out, there is nothing to do.  Note that the latter
2775 		 * case seems impossible but can occur if hat_pageunload()
2776 		 * is called on an ISM mapping while the process is swapped
2777 		 * out.
2778 		 */
2779 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2780 			return;
2781 
2782 		/*
2783 		 * If another thread is in the middle of relocating a TSB
2784 		 * we can't unload the entry so set a flag so that the
2785 		 * TSB will be flushed before it can be accessed by the
2786 		 * process.
2787 		 */
2788 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2789 			if (ttep == NULL)
2790 				tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2791 			return;
2792 		}
2793 #if defined(UTSB_PHYS)
2794 		phys = 1;
2795 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2796 #else
2797 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2798 #endif
2799 		tsb_size = tsbinfop->tsb_szc;
2800 	}
2801 	if (ttesz >= TTE4M)
2802 		vpshift = MMU_PAGESHIFT4M;
2803 
2804 	tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2805 	tag = sfmmu_make_tsbtag(vaddr);
2806 
2807 	if (ttep == NULL) {
2808 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2809 	} else {
2810 		if (ttesz >= TTE4M) {
2811 			SFMMU_STAT(sf_tsb_load4m);
2812 		} else {
2813 			SFMMU_STAT(sf_tsb_load8k);
2814 		}
2815 
2816 		sfmmu_load_tsbe(tsbe_addr, tag, ttep, phys);
2817 	}
2818 }
2819 
2820 /*
2821  * Unmap all entries from [start, end) matching the given page size.
2822  *
2823  * This function is used primarily to unmap replicated 64K or 512K entries
2824  * from the TSB that are inserted using the base page size TSB pointer, but
2825  * it may also be called to unmap a range of addresses from the TSB.
2826  */
2827 void
2828 sfmmu_unload_tsb_range(sfmmu_t *sfmmup, caddr_t start, caddr_t end, int ttesz)
2829 {
2830 	struct tsb_info *tsbinfop;
2831 	uint64_t tag;
2832 	struct tsbe *tsbe_addr;
2833 	caddr_t vaddr;
2834 	uint64_t tsb_base;
2835 	int vpshift, vpgsz;
2836 	uint_t tsb_size;
2837 	int phys = 0;
2838 
2839 	/*
2840 	 * Assumptions:
2841 	 *  If ttesz == 8K, 64K or 512K, we walk through the range 8K
2842 	 *  at a time shooting down any valid entries we encounter.
2843 	 *
2844 	 *  If ttesz >= 4M we walk the range 4M at a time shooting
2845 	 *  down any valid mappings we find.
2846 	 */
2847 	if (sfmmup == ksfmmup) {
2848 		phys = ktsb_phys;
2849 		if (ttesz >= TTE4M) {
2850 #ifndef sun4v
2851 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2852 #endif
2853 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2854 			tsb_size = ktsb4m_szcode;
2855 		} else {
2856 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2857 			tsb_size = ktsb_szcode;
2858 		}
2859 	} else {
2860 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2861 
2862 		/*
2863 		 * If there isn't a TSB for this page size, or the TSB is
2864 		 * swapped out, there is nothing to do.  Note that the latter
2865 		 * case seems impossible but can occur if hat_pageunload()
2866 		 * is called on an ISM mapping while the process is swapped
2867 		 * out.
2868 		 */
2869 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2870 			return;
2871 
2872 		/*
2873 		 * If another thread is in the middle of relocating a TSB
2874 		 * we can't unload the entry so set a flag so that the
2875 		 * TSB will be flushed before it can be accessed by the
2876 		 * process.
2877 		 */
2878 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2879 			tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2880 			return;
2881 		}
2882 #if defined(UTSB_PHYS)
2883 		phys = 1;
2884 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2885 #else
2886 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2887 #endif
2888 		tsb_size = tsbinfop->tsb_szc;
2889 	}
2890 	if (ttesz >= TTE4M) {
2891 		vpshift = MMU_PAGESHIFT4M;
2892 		vpgsz = MMU_PAGESIZE4M;
2893 	} else {
2894 		vpshift = MMU_PAGESHIFT;
2895 		vpgsz = MMU_PAGESIZE;
2896 	}
2897 
2898 	for (vaddr = start; vaddr < end; vaddr += vpgsz) {
2899 		tag = sfmmu_make_tsbtag(vaddr);
2900 		tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2901 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2902 	}
2903 }
2904 
2905 /*
2906  * Select the optimum TSB size given the number of mappings
2907  * that need to be cached.
2908  */
2909 static int
2910 sfmmu_select_tsb_szc(pgcnt_t pgcnt)
2911 {
2912 	int szc = 0;
2913 
2914 #ifdef DEBUG
2915 	if (tsb_grow_stress) {
2916 		uint32_t randval = (uint32_t)gettick() >> 4;
2917 		return (randval % (tsb_max_growsize + 1));
2918 	}
2919 #endif	/* DEBUG */
2920 
2921 	while ((szc < tsb_max_growsize) && (pgcnt > SFMMU_RSS_TSBSIZE(szc)))
2922 		szc++;
2923 	return (szc);
2924 }
2925 
2926 /*
2927  * This function will add a translation to the hme_blk and allocate the
2928  * hme_blk if one does not exist.
2929  * If a page structure is specified then it will add the
2930  * corresponding hment to the mapping list.
2931  * It will also update the hmenum field for the tte.
2932  * Furthermore, it attempts to create a large page translation
2933  * for <addr,hat> at page array pps.  It assumes addr and first
2934  * pp is correctly aligned.  It returns 0 if successful and 1 otherwise.
2935  */
2936 static int
2937 sfmmu_tteload_array(sfmmu_t *sfmmup, tte_t *ttep, caddr_t vaddr,
2938 	page_t **pps, uint_t flags, uint_t rid)
2939 {
2940 	struct hmehash_bucket *hmebp;
2941 	struct hme_blk *hmeblkp;
2942 	int 	ret;
2943 	uint_t	size;
2944 
2945 	/*
2946 	 * Get mapping size.
2947 	 */
2948 	size = TTE_CSZ(ttep);
2949 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
2950 
2951 	/*
2952 	 * Acquire the hash bucket.
2953 	 */
2954 	hmebp = sfmmu_tteload_acquire_hashbucket(sfmmup, vaddr, size, rid);
2955 	ASSERT(hmebp);
2956 
2957 	/*
2958 	 * Find the hment block.
2959 	 */
2960 	hmeblkp = sfmmu_tteload_find_hmeblk(sfmmup, hmebp, vaddr, size, flags,
2961 	    rid);
2962 	ASSERT(hmeblkp);
2963 
2964 	/*
2965 	 * Add the translation.
2966 	 */
2967 	ret = sfmmu_tteload_addentry(sfmmup, hmeblkp, ttep, vaddr, pps, flags,
2968 	    rid);
2969 
2970 	/*
2971 	 * Release the hash bucket.
2972 	 */
2973 	sfmmu_tteload_release_hashbucket(hmebp);
2974 
2975 	return (ret);
2976 }
2977 
2978 /*
2979  * Function locks and returns a pointer to the hash bucket for vaddr and size.
2980  */
2981 static struct hmehash_bucket *
2982 sfmmu_tteload_acquire_hashbucket(sfmmu_t *sfmmup, caddr_t vaddr, int size,
2983     uint_t rid)
2984 {
2985 	struct hmehash_bucket *hmebp;
2986 	int hmeshift;
2987 	void *htagid = sfmmutohtagid(sfmmup, rid);
2988 
2989 	ASSERT(htagid != NULL);
2990 
2991 	hmeshift = HME_HASH_SHIFT(size);
2992 
2993 	hmebp = HME_HASH_FUNCTION(htagid, vaddr, hmeshift);
2994 
2995 	SFMMU_HASH_LOCK(hmebp);
2996 
2997 	return (hmebp);
2998 }
2999 
3000 /*
3001  * Function returns a pointer to an hmeblk in the hash bucket, hmebp. If the
3002  * hmeblk doesn't exists for the [sfmmup, vaddr & size] signature, a hmeblk is
3003  * allocated.
3004  */
3005 static struct hme_blk *
3006 sfmmu_tteload_find_hmeblk(sfmmu_t *sfmmup, struct hmehash_bucket *hmebp,
3007 	caddr_t vaddr, uint_t size, uint_t flags, uint_t rid)
3008 {
3009 	hmeblk_tag hblktag;
3010 	int hmeshift;
3011 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
3012 
3013 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
3014 
3015 	hblktag.htag_id = sfmmutohtagid(sfmmup, rid);
3016 	ASSERT(hblktag.htag_id != NULL);
3017 	hmeshift = HME_HASH_SHIFT(size);
3018 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
3019 	hblktag.htag_rehash = HME_HASH_REHASH(size);
3020 	hblktag.htag_rid = rid;
3021 
3022 ttearray_realloc:
3023 
3024 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
3025 
3026 	/*
3027 	 * We block until hblk_reserve_lock is released; it's held by
3028 	 * the thread, temporarily using hblk_reserve, until hblk_reserve is
3029 	 * replaced by a hblk from sfmmu8_cache.
3030 	 */
3031 	if (hmeblkp == (struct hme_blk *)hblk_reserve &&
3032 	    hblk_reserve_thread != curthread) {
3033 		SFMMU_HASH_UNLOCK(hmebp);
3034 		mutex_enter(&hblk_reserve_lock);
3035 		mutex_exit(&hblk_reserve_lock);
3036 		SFMMU_STAT(sf_hblk_reserve_hit);
3037 		SFMMU_HASH_LOCK(hmebp);
3038 		goto ttearray_realloc;
3039 	}
3040 
3041 	if (hmeblkp == NULL) {
3042 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
3043 		    hblktag, flags, rid);
3044 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3045 		ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3046 	} else {
3047 		/*
3048 		 * It is possible for 8k and 64k hblks to collide since they
3049 		 * have the same rehash value. This is because we
3050 		 * lazily free hblks and 8K/64K blks could be lingering.
3051 		 * If we find size mismatch we free the block and & try again.
3052 		 */
3053 		if (get_hblk_ttesz(hmeblkp) != size) {
3054 			ASSERT(!hmeblkp->hblk_vcnt);
3055 			ASSERT(!hmeblkp->hblk_hmecnt);
3056 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3057 			    &list, 0);
3058 			goto ttearray_realloc;
3059 		}
3060 		if (hmeblkp->hblk_shw_bit) {
3061 			/*
3062 			 * if the hblk was previously used as a shadow hblk then
3063 			 * we will change it to a normal hblk
3064 			 */
3065 			ASSERT(!hmeblkp->hblk_shared);
3066 			if (hmeblkp->hblk_shw_mask) {
3067 				sfmmu_shadow_hcleanup(sfmmup, hmeblkp, hmebp);
3068 				ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3069 				goto ttearray_realloc;
3070 			} else {
3071 				hmeblkp->hblk_shw_bit = 0;
3072 			}
3073 		}
3074 		SFMMU_STAT(sf_hblk_hit);
3075 	}
3076 
3077 	/*
3078 	 * hat_memload() should never call kmem_cache_free() for kernel hmeblks;
3079 	 * see block comment showing the stacktrace in sfmmu_hblk_alloc();
3080 	 * set the flag parameter to 1 so that sfmmu_hblks_list_purge() will
3081 	 * just add these hmeblks to the per-cpu pending queue.
3082 	 */
3083 	sfmmu_hblks_list_purge(&list, 1);
3084 
3085 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
3086 	ASSERT(!hmeblkp->hblk_shw_bit);
3087 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3088 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3089 	ASSERT(hmeblkp->hblk_tag.htag_rid == rid);
3090 
3091 	return (hmeblkp);
3092 }
3093 
3094 /*
3095  * Function adds a tte entry into the hmeblk. It returns 0 if successful and 1
3096  * otherwise.
3097  */
3098 static int
3099 sfmmu_tteload_addentry(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, tte_t *ttep,
3100 	caddr_t vaddr, page_t **pps, uint_t flags, uint_t rid)
3101 {
3102 	page_t *pp = *pps;
3103 	int hmenum, size, remap;
3104 	tte_t tteold, flush_tte;
3105 #ifdef DEBUG
3106 	tte_t orig_old;
3107 #endif /* DEBUG */
3108 	struct sf_hment *sfhme;
3109 	kmutex_t *pml, *pmtx;
3110 	hatlock_t *hatlockp;
3111 	int myflt;
3112 
3113 	/*
3114 	 * remove this panic when we decide to let user virtual address
3115 	 * space be >= USERLIMIT.
3116 	 */
3117 	if (!TTE_IS_PRIVILEGED(ttep) && vaddr >= (caddr_t)USERLIMIT)
3118 		panic("user addr %p in kernel space", (void *)vaddr);
3119 #if defined(TTE_IS_GLOBAL)
3120 	if (TTE_IS_GLOBAL(ttep))
3121 		panic("sfmmu_tteload: creating global tte");
3122 #endif
3123 
3124 #ifdef DEBUG
3125 	if (pf_is_memory(sfmmu_ttetopfn(ttep, vaddr)) &&
3126 	    !TTE_IS_PCACHEABLE(ttep) && !sfmmu_allow_nc_trans)
3127 		panic("sfmmu_tteload: non cacheable memory tte");
3128 #endif /* DEBUG */
3129 
3130 	/* don't simulate dirty bit for writeable ISM/DISM mappings */
3131 	if ((flags & HAT_LOAD_SHARE) && TTE_IS_WRITABLE(ttep)) {
3132 		TTE_SET_REF(ttep);
3133 		TTE_SET_MOD(ttep);
3134 	}
3135 
3136 	if ((flags & HAT_LOAD_SHARE) || !TTE_IS_REF(ttep) ||
3137 	    !TTE_IS_MOD(ttep)) {
3138 		/*
3139 		 * Don't load TSB for dummy as in ISM.  Also don't preload
3140 		 * the TSB if the TTE isn't writable since we're likely to
3141 		 * fault on it again -- preloading can be fairly expensive.
3142 		 */
3143 		flags |= SFMMU_NO_TSBLOAD;
3144 	}
3145 
3146 	size = TTE_CSZ(ttep);
3147 	switch (size) {
3148 	case TTE8K:
3149 		SFMMU_STAT(sf_tteload8k);
3150 		break;
3151 	case TTE64K:
3152 		SFMMU_STAT(sf_tteload64k);
3153 		break;
3154 	case TTE512K:
3155 		SFMMU_STAT(sf_tteload512k);
3156 		break;
3157 	case TTE4M:
3158 		SFMMU_STAT(sf_tteload4m);
3159 		break;
3160 	case (TTE32M):
3161 		SFMMU_STAT(sf_tteload32m);
3162 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3163 		break;
3164 	case (TTE256M):
3165 		SFMMU_STAT(sf_tteload256m);
3166 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3167 		break;
3168 	}
3169 
3170 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
3171 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
3172 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3173 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3174 
3175 	HBLKTOHME_IDX(sfhme, hmeblkp, vaddr, hmenum);
3176 
3177 	/*
3178 	 * Need to grab mlist lock here so that pageunload
3179 	 * will not change tte behind us.
3180 	 */
3181 	if (pp) {
3182 		pml = sfmmu_mlist_enter(pp);
3183 	}
3184 
3185 	sfmmu_copytte(&sfhme->hme_tte, &tteold);
3186 	/*
3187 	 * Look for corresponding hment and if valid verify
3188 	 * pfns are equal.
3189 	 */
3190 	remap = TTE_IS_VALID(&tteold);
3191 	if (remap) {
3192 		pfn_t	new_pfn, old_pfn;
3193 
3194 		old_pfn = TTE_TO_PFN(vaddr, &tteold);
3195 		new_pfn = TTE_TO_PFN(vaddr, ttep);
3196 
3197 		if (flags & HAT_LOAD_REMAP) {
3198 			/* make sure we are remapping same type of pages */
3199 			if (pf_is_memory(old_pfn) != pf_is_memory(new_pfn)) {
3200 				panic("sfmmu_tteload - tte remap io<->memory");
3201 			}
3202 			if (old_pfn != new_pfn &&
3203 			    (pp != NULL || sfhme->hme_page != NULL)) {
3204 				panic("sfmmu_tteload - tte remap pp != NULL");
3205 			}
3206 		} else if (old_pfn != new_pfn) {
3207 			panic("sfmmu_tteload - tte remap, hmeblkp 0x%p",
3208 			    (void *)hmeblkp);
3209 		}
3210 		ASSERT(TTE_CSZ(&tteold) == TTE_CSZ(ttep));
3211 	}
3212 
3213 	if (pp) {
3214 		if (size == TTE8K) {
3215 #ifdef VAC
3216 			/*
3217 			 * Handle VAC consistency
3218 			 */
3219 			if (!remap && (cache & CACHE_VAC) && !PP_ISNC(pp)) {
3220 				sfmmu_vac_conflict(sfmmup, vaddr, pp);
3221 			}
3222 #endif
3223 
3224 			if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3225 				pmtx = sfmmu_page_enter(pp);
3226 				PP_CLRRO(pp);
3227 				sfmmu_page_exit(pmtx);
3228 			} else if (!PP_ISMAPPED(pp) &&
3229 			    (!TTE_IS_WRITABLE(ttep)) && !(PP_ISMOD(pp))) {
3230 				pmtx = sfmmu_page_enter(pp);
3231 				if (!(PP_ISMOD(pp))) {
3232 					PP_SETRO(pp);
3233 				}
3234 				sfmmu_page_exit(pmtx);
3235 			}
3236 
3237 		} else if (sfmmu_pagearray_setup(vaddr, pps, ttep, remap)) {
3238 			/*
3239 			 * sfmmu_pagearray_setup failed so return
3240 			 */
3241 			sfmmu_mlist_exit(pml);
3242 			return (1);
3243 		}
3244 	}
3245 
3246 	/*
3247 	 * Make sure hment is not on a mapping list.
3248 	 */
3249 	ASSERT(remap || (sfhme->hme_page == NULL));
3250 
3251 	/* if it is not a remap then hme->next better be NULL */
3252 	ASSERT((!remap) ? sfhme->hme_next == NULL : 1);
3253 
3254 	if (flags & HAT_LOAD_LOCK) {
3255 		if ((hmeblkp->hblk_lckcnt + 1) >= MAX_HBLK_LCKCNT) {
3256 			panic("too high lckcnt-hmeblk %p",
3257 			    (void *)hmeblkp);
3258 		}
3259 		atomic_add_32(&hmeblkp->hblk_lckcnt, 1);
3260 
3261 		HBLK_STACK_TRACE(hmeblkp, HBLK_LOCK);
3262 	}
3263 
3264 #ifdef VAC
3265 	if (pp && PP_ISNC(pp)) {
3266 		/*
3267 		 * If the physical page is marked to be uncacheable, like
3268 		 * by a vac conflict, make sure the new mapping is also
3269 		 * uncacheable.
3270 		 */
3271 		TTE_CLR_VCACHEABLE(ttep);
3272 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
3273 	}
3274 #endif
3275 	ttep->tte_hmenum = hmenum;
3276 
3277 #ifdef DEBUG
3278 	orig_old = tteold;
3279 #endif /* DEBUG */
3280 
3281 	while (sfmmu_modifytte_try(&tteold, ttep, &sfhme->hme_tte) < 0) {
3282 		if ((sfmmup == KHATID) &&
3283 		    (flags & (HAT_LOAD_LOCK | HAT_LOAD_REMAP))) {
3284 			sfmmu_copytte(&sfhme->hme_tte, &tteold);
3285 		}
3286 #ifdef DEBUG
3287 		chk_tte(&orig_old, &tteold, ttep, hmeblkp);
3288 #endif /* DEBUG */
3289 	}
3290 	ASSERT(TTE_IS_VALID(&sfhme->hme_tte));
3291 
3292 	if (!TTE_IS_VALID(&tteold)) {
3293 
3294 		atomic_add_16(&hmeblkp->hblk_vcnt, 1);
3295 		if (rid == SFMMU_INVALID_SHMERID) {
3296 			atomic_add_long(&sfmmup->sfmmu_ttecnt[size], 1);
3297 		} else {
3298 			sf_srd_t *srdp = sfmmup->sfmmu_srdp;
3299 			sf_region_t *rgnp = srdp->srd_hmergnp[rid];
3300 			/*
3301 			 * We already accounted for region ttecnt's in sfmmu
3302 			 * during hat_join_region() processing. Here we
3303 			 * only update ttecnt's in region struture.
3304 			 */
3305 			atomic_add_long(&rgnp->rgn_ttecnt[size], 1);
3306 		}
3307 	}
3308 
3309 	myflt = (astosfmmu(curthread->t_procp->p_as) == sfmmup);
3310 	if (size > TTE8K && (flags & HAT_LOAD_SHARE) == 0 &&
3311 	    sfmmup != ksfmmup) {
3312 		uchar_t tteflag = 1 << size;
3313 		if (rid == SFMMU_INVALID_SHMERID) {
3314 			if (!(sfmmup->sfmmu_tteflags & tteflag)) {
3315 				hatlockp = sfmmu_hat_enter(sfmmup);
3316 				sfmmup->sfmmu_tteflags |= tteflag;
3317 				sfmmu_hat_exit(hatlockp);
3318 			}
3319 		} else if (!(sfmmup->sfmmu_rtteflags & tteflag)) {
3320 			hatlockp = sfmmu_hat_enter(sfmmup);
3321 			sfmmup->sfmmu_rtteflags |= tteflag;
3322 			sfmmu_hat_exit(hatlockp);
3323 		}
3324 		/*
3325 		 * Update the current CPU tsbmiss area, so the current thread
3326 		 * won't need to take the tsbmiss for the new pagesize.
3327 		 * The other threads in the process will update their tsb
3328 		 * miss area lazily in sfmmu_tsbmiss_exception() when they
3329 		 * fail to find the translation for a newly added pagesize.
3330 		 */
3331 		if (size > TTE64K && myflt) {
3332 			struct tsbmiss *tsbmp;
3333 			kpreempt_disable();
3334 			tsbmp = &tsbmiss_area[CPU->cpu_id];
3335 			if (rid == SFMMU_INVALID_SHMERID) {
3336 				if (!(tsbmp->uhat_tteflags & tteflag)) {
3337 					tsbmp->uhat_tteflags |= tteflag;
3338 				}
3339 			} else {
3340 				if (!(tsbmp->uhat_rtteflags & tteflag)) {
3341 					tsbmp->uhat_rtteflags |= tteflag;
3342 				}
3343 			}
3344 			kpreempt_enable();
3345 		}
3346 	}
3347 
3348 	if (size >= TTE4M && (flags & HAT_LOAD_TEXT) &&
3349 	    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
3350 		hatlockp = sfmmu_hat_enter(sfmmup);
3351 		SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
3352 		sfmmu_hat_exit(hatlockp);
3353 	}
3354 
3355 	flush_tte.tte_intlo = (tteold.tte_intlo ^ ttep->tte_intlo) &
3356 	    hw_tte.tte_intlo;
3357 	flush_tte.tte_inthi = (tteold.tte_inthi ^ ttep->tte_inthi) &
3358 	    hw_tte.tte_inthi;
3359 
3360 	if (remap && (flush_tte.tte_inthi || flush_tte.tte_intlo)) {
3361 		/*
3362 		 * If remap and new tte differs from old tte we need
3363 		 * to sync the mod bit and flush TLB/TSB.  We don't
3364 		 * need to sync ref bit because we currently always set
3365 		 * ref bit in tteload.
3366 		 */
3367 		ASSERT(TTE_IS_REF(ttep));
3368 		if (TTE_IS_MOD(&tteold)) {
3369 			sfmmu_ttesync(sfmmup, vaddr, &tteold, pp);
3370 		}
3371 		/*
3372 		 * hwtte bits shouldn't change for SRD hmeblks as long as SRD
3373 		 * hmes are only used for read only text. Adding this code for
3374 		 * completeness and future use of shared hmeblks with writable
3375 		 * mappings of VMODSORT vnodes.
3376 		 */
3377 		if (hmeblkp->hblk_shared) {
3378 			cpuset_t cpuset = sfmmu_rgntlb_demap(vaddr,
3379 			    sfmmup->sfmmu_srdp->srd_hmergnp[rid], hmeblkp, 1);
3380 			xt_sync(cpuset);
3381 			SFMMU_STAT_ADD(sf_region_remap_demap, 1);
3382 		} else {
3383 			sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 0);
3384 			xt_sync(sfmmup->sfmmu_cpusran);
3385 		}
3386 	}
3387 
3388 	if ((flags & SFMMU_NO_TSBLOAD) == 0) {
3389 		/*
3390 		 * We only preload 8K and 4M mappings into the TSB, since
3391 		 * 64K and 512K mappings are replicated and hence don't
3392 		 * have a single, unique TSB entry. Ditto for 32M/256M.
3393 		 */
3394 		if (size == TTE8K || size == TTE4M) {
3395 			sf_scd_t *scdp;
3396 			hatlockp = sfmmu_hat_enter(sfmmup);
3397 			/*
3398 			 * Don't preload private TSB if the mapping is used
3399 			 * by the shctx in the SCD.
3400 			 */
3401 			scdp = sfmmup->sfmmu_scdp;
3402 			if (rid == SFMMU_INVALID_SHMERID || scdp == NULL ||
3403 			    !SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
3404 				sfmmu_load_tsb(sfmmup, vaddr, &sfhme->hme_tte,
3405 				    size);
3406 			}
3407 			sfmmu_hat_exit(hatlockp);
3408 		}
3409 	}
3410 	if (pp) {
3411 		if (!remap) {
3412 			HME_ADD(sfhme, pp);
3413 			atomic_add_16(&hmeblkp->hblk_hmecnt, 1);
3414 			ASSERT(hmeblkp->hblk_hmecnt > 0);
3415 
3416 			/*
3417 			 * Cannot ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
3418 			 * see pageunload() for comment.
3419 			 */
3420 		}
3421 		sfmmu_mlist_exit(pml);
3422 	}
3423 
3424 	return (0);
3425 }
3426 /*
3427  * Function unlocks hash bucket.
3428  */
3429 static void
3430 sfmmu_tteload_release_hashbucket(struct hmehash_bucket *hmebp)
3431 {
3432 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3433 	SFMMU_HASH_UNLOCK(hmebp);
3434 }
3435 
3436 /*
3437  * function which checks and sets up page array for a large
3438  * translation.  Will set p_vcolor, p_index, p_ro fields.
3439  * Assumes addr and pfnum of first page are properly aligned.
3440  * Will check for physical contiguity. If check fails it return
3441  * non null.
3442  */
3443 static int
3444 sfmmu_pagearray_setup(caddr_t addr, page_t **pps, tte_t *ttep, int remap)
3445 {
3446 	int 	i, index, ttesz;
3447 	pfn_t	pfnum;
3448 	pgcnt_t	npgs;
3449 	page_t *pp, *pp1;
3450 	kmutex_t *pmtx;
3451 #ifdef VAC
3452 	int osz;
3453 	int cflags = 0;
3454 	int vac_err = 0;
3455 #endif
3456 	int newidx = 0;
3457 
3458 	ttesz = TTE_CSZ(ttep);
3459 
3460 	ASSERT(ttesz > TTE8K);
3461 
3462 	npgs = TTEPAGES(ttesz);
3463 	index = PAGESZ_TO_INDEX(ttesz);
3464 
3465 	pfnum = (*pps)->p_pagenum;
3466 	ASSERT(IS_P2ALIGNED(pfnum, npgs));
3467 
3468 	/*
3469 	 * Save the first pp so we can do HAT_TMPNC at the end.
3470 	 */
3471 	pp1 = *pps;
3472 #ifdef VAC
3473 	osz = fnd_mapping_sz(pp1);
3474 #endif
3475 
3476 	for (i = 0; i < npgs; i++, pps++) {
3477 		pp = *pps;
3478 		ASSERT(PAGE_LOCKED(pp));
3479 		ASSERT(pp->p_szc >= ttesz);
3480 		ASSERT(pp->p_szc == pp1->p_szc);
3481 		ASSERT(sfmmu_mlist_held(pp));
3482 
3483 		/*
3484 		 * XXX is it possible to maintain P_RO on the root only?
3485 		 */
3486 		if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3487 			pmtx = sfmmu_page_enter(pp);
3488 			PP_CLRRO(pp);
3489 			sfmmu_page_exit(pmtx);
3490 		} else if (!PP_ISMAPPED(pp) && !TTE_IS_WRITABLE(ttep) &&
3491 		    !PP_ISMOD(pp)) {
3492 			pmtx = sfmmu_page_enter(pp);
3493 			if (!(PP_ISMOD(pp))) {
3494 				PP_SETRO(pp);
3495 			}
3496 			sfmmu_page_exit(pmtx);
3497 		}
3498 
3499 		/*
3500 		 * If this is a remap we skip vac & contiguity checks.
3501 		 */
3502 		if (remap)
3503 			continue;
3504 
3505 		/*
3506 		 * set p_vcolor and detect any vac conflicts.
3507 		 */
3508 #ifdef VAC
3509 		if (vac_err == 0) {
3510 			vac_err = sfmmu_vacconflict_array(addr, pp, &cflags);
3511 
3512 		}
3513 #endif
3514 
3515 		/*
3516 		 * Save current index in case we need to undo it.
3517 		 * Note: "PAGESZ_TO_INDEX(sz)	(1 << (sz))"
3518 		 *	"SFMMU_INDEX_SHIFT	6"
3519 		 *	 "SFMMU_INDEX_MASK	((1 << SFMMU_INDEX_SHIFT) - 1)"
3520 		 *	 "PP_MAPINDEX(p_index)	(p_index & SFMMU_INDEX_MASK)"
3521 		 *
3522 		 * So:	index = PAGESZ_TO_INDEX(ttesz);
3523 		 *	if ttesz == 1 then index = 0x2
3524 		 *		    2 then index = 0x4
3525 		 *		    3 then index = 0x8
3526 		 *		    4 then index = 0x10
3527 		 *		    5 then index = 0x20
3528 		 * The code below checks if it's a new pagesize (ie, newidx)
3529 		 * in case we need to take it back out of p_index,
3530 		 * and then or's the new index into the existing index.
3531 		 */
3532 		if ((PP_MAPINDEX(pp) & index) == 0)
3533 			newidx = 1;
3534 		pp->p_index = (PP_MAPINDEX(pp) | index);
3535 
3536 		/*
3537 		 * contiguity check
3538 		 */
3539 		if (pp->p_pagenum != pfnum) {
3540 			/*
3541 			 * If we fail the contiguity test then
3542 			 * the only thing we need to fix is the p_index field.
3543 			 * We might get a few extra flushes but since this
3544 			 * path is rare that is ok.  The p_ro field will
3545 			 * get automatically fixed on the next tteload to
3546 			 * the page.  NO TNC bit is set yet.
3547 			 */
3548 			while (i >= 0) {
3549 				pp = *pps;
3550 				if (newidx)
3551 					pp->p_index = (PP_MAPINDEX(pp) &
3552 					    ~index);
3553 				pps--;
3554 				i--;
3555 			}
3556 			return (1);
3557 		}
3558 		pfnum++;
3559 		addr += MMU_PAGESIZE;
3560 	}
3561 
3562 #ifdef VAC
3563 	if (vac_err) {
3564 		if (ttesz > osz) {
3565 			/*
3566 			 * There are some smaller mappings that causes vac
3567 			 * conflicts. Convert all existing small mappings to
3568 			 * TNC.
3569 			 */
3570 			SFMMU_STAT_ADD(sf_uncache_conflict, npgs);
3571 			sfmmu_page_cache_array(pp1, HAT_TMPNC, CACHE_FLUSH,
3572 			    npgs);
3573 		} else {
3574 			/* EMPTY */
3575 			/*
3576 			 * If there exists an big page mapping,
3577 			 * that means the whole existing big page
3578 			 * has TNC setting already. No need to covert to
3579 			 * TNC again.
3580 			 */
3581 			ASSERT(PP_ISTNC(pp1));
3582 		}
3583 	}
3584 #endif	/* VAC */
3585 
3586 	return (0);
3587 }
3588 
3589 #ifdef VAC
3590 /*
3591  * Routine that detects vac consistency for a large page. It also
3592  * sets virtual color for all pp's for this big mapping.
3593  */
3594 static int
3595 sfmmu_vacconflict_array(caddr_t addr, page_t *pp, int *cflags)
3596 {
3597 	int vcolor, ocolor;
3598 
3599 	ASSERT(sfmmu_mlist_held(pp));
3600 
3601 	if (PP_ISNC(pp)) {
3602 		return (HAT_TMPNC);
3603 	}
3604 
3605 	vcolor = addr_to_vcolor(addr);
3606 	if (PP_NEWPAGE(pp)) {
3607 		PP_SET_VCOLOR(pp, vcolor);
3608 		return (0);
3609 	}
3610 
3611 	ocolor = PP_GET_VCOLOR(pp);
3612 	if (ocolor == vcolor) {
3613 		return (0);
3614 	}
3615 
3616 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
3617 		/*
3618 		 * Previous user of page had a differnet color
3619 		 * but since there are no current users
3620 		 * we just flush the cache and change the color.
3621 		 * As an optimization for large pages we flush the
3622 		 * entire cache of that color and set a flag.
3623 		 */
3624 		SFMMU_STAT(sf_pgcolor_conflict);
3625 		if (!CacheColor_IsFlushed(*cflags, ocolor)) {
3626 			CacheColor_SetFlushed(*cflags, ocolor);
3627 			sfmmu_cache_flushcolor(ocolor, pp->p_pagenum);
3628 		}
3629 		PP_SET_VCOLOR(pp, vcolor);
3630 		return (0);
3631 	}
3632 
3633 	/*
3634 	 * We got a real conflict with a current mapping.
3635 	 * set flags to start unencaching all mappings
3636 	 * and return failure so we restart looping
3637 	 * the pp array from the beginning.
3638 	 */
3639 	return (HAT_TMPNC);
3640 }
3641 #endif	/* VAC */
3642 
3643 /*
3644  * creates a large page shadow hmeblk for a tte.
3645  * The purpose of this routine is to allow us to do quick unloads because
3646  * the vm layer can easily pass a very large but sparsely populated range.
3647  */
3648 static struct hme_blk *
3649 sfmmu_shadow_hcreate(sfmmu_t *sfmmup, caddr_t vaddr, int ttesz, uint_t flags)
3650 {
3651 	struct hmehash_bucket *hmebp;
3652 	hmeblk_tag hblktag;
3653 	int hmeshift, size, vshift;
3654 	uint_t shw_mask, newshw_mask;
3655 	struct hme_blk *hmeblkp;
3656 
3657 	ASSERT(sfmmup != KHATID);
3658 	if (mmu_page_sizes == max_mmu_page_sizes) {
3659 		ASSERT(ttesz < TTE256M);
3660 	} else {
3661 		ASSERT(ttesz < TTE4M);
3662 		ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
3663 		ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
3664 	}
3665 
3666 	if (ttesz == TTE8K) {
3667 		size = TTE512K;
3668 	} else {
3669 		size = ++ttesz;
3670 	}
3671 
3672 	hblktag.htag_id = sfmmup;
3673 	hmeshift = HME_HASH_SHIFT(size);
3674 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
3675 	hblktag.htag_rehash = HME_HASH_REHASH(size);
3676 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3677 	hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
3678 
3679 	SFMMU_HASH_LOCK(hmebp);
3680 
3681 	HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
3682 	ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
3683 	if (hmeblkp == NULL) {
3684 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
3685 		    hblktag, flags, SFMMU_INVALID_SHMERID);
3686 	}
3687 	ASSERT(hmeblkp);
3688 	if (!hmeblkp->hblk_shw_mask) {
3689 		/*
3690 		 * if this is a unused hblk it was just allocated or could
3691 		 * potentially be a previous large page hblk so we need to
3692 		 * set the shadow bit.
3693 		 */
3694 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3695 		hmeblkp->hblk_shw_bit = 1;
3696 	} else if (hmeblkp->hblk_shw_bit == 0) {
3697 		panic("sfmmu_shadow_hcreate: shw bit not set in hmeblkp 0x%p",
3698 		    (void *)hmeblkp);
3699 	}
3700 	ASSERT(hmeblkp->hblk_shw_bit == 1);
3701 	ASSERT(!hmeblkp->hblk_shared);
3702 	vshift = vaddr_to_vshift(hblktag, vaddr, size);
3703 	ASSERT(vshift < 8);
3704 	/*
3705 	 * Atomically set shw mask bit
3706 	 */
3707 	do {
3708 		shw_mask = hmeblkp->hblk_shw_mask;
3709 		newshw_mask = shw_mask | (1 << vshift);
3710 		newshw_mask = cas32(&hmeblkp->hblk_shw_mask, shw_mask,
3711 		    newshw_mask);
3712 	} while (newshw_mask != shw_mask);
3713 
3714 	SFMMU_HASH_UNLOCK(hmebp);
3715 
3716 	return (hmeblkp);
3717 }
3718 
3719 /*
3720  * This routine cleanup a previous shadow hmeblk and changes it to
3721  * a regular hblk.  This happens rarely but it is possible
3722  * when a process wants to use large pages and there are hblks still
3723  * lying around from the previous as that used these hmeblks.
3724  * The alternative was to cleanup the shadow hblks at unload time
3725  * but since so few user processes actually use large pages, it is
3726  * better to be lazy and cleanup at this time.
3727  */
3728 static void
3729 sfmmu_shadow_hcleanup(sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
3730 	struct hmehash_bucket *hmebp)
3731 {
3732 	caddr_t addr, endaddr;
3733 	int hashno, size;
3734 
3735 	ASSERT(hmeblkp->hblk_shw_bit);
3736 	ASSERT(!hmeblkp->hblk_shared);
3737 
3738 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3739 
3740 	if (!hmeblkp->hblk_shw_mask) {
3741 		hmeblkp->hblk_shw_bit = 0;
3742 		return;
3743 	}
3744 	addr = (caddr_t)get_hblk_base(hmeblkp);
3745 	endaddr = get_hblk_endaddr(hmeblkp);
3746 	size = get_hblk_ttesz(hmeblkp);
3747 	hashno = size - 1;
3748 	ASSERT(hashno > 0);
3749 	SFMMU_HASH_UNLOCK(hmebp);
3750 
3751 	sfmmu_free_hblks(sfmmup, addr, endaddr, hashno);
3752 
3753 	SFMMU_HASH_LOCK(hmebp);
3754 }
3755 
3756 static void
3757 sfmmu_free_hblks(sfmmu_t *sfmmup, caddr_t addr, caddr_t endaddr,
3758 	int hashno)
3759 {
3760 	int hmeshift, shadow = 0;
3761 	hmeblk_tag hblktag;
3762 	struct hmehash_bucket *hmebp;
3763 	struct hme_blk *hmeblkp;
3764 	struct hme_blk *nx_hblk, *pr_hblk, *list = NULL;
3765 
3766 	ASSERT(hashno > 0);
3767 	hblktag.htag_id = sfmmup;
3768 	hblktag.htag_rehash = hashno;
3769 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3770 
3771 	hmeshift = HME_HASH_SHIFT(hashno);
3772 
3773 	while (addr < endaddr) {
3774 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3775 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3776 		SFMMU_HASH_LOCK(hmebp);
3777 		/* inline HME_HASH_SEARCH */
3778 		hmeblkp = hmebp->hmeblkp;
3779 		pr_hblk = NULL;
3780 		while (hmeblkp) {
3781 			if (HTAGS_EQ(hmeblkp->hblk_tag, hblktag)) {
3782 				/* found hme_blk */
3783 				ASSERT(!hmeblkp->hblk_shared);
3784 				if (hmeblkp->hblk_shw_bit) {
3785 					if (hmeblkp->hblk_shw_mask) {
3786 						shadow = 1;
3787 						sfmmu_shadow_hcleanup(sfmmup,
3788 						    hmeblkp, hmebp);
3789 						break;
3790 					} else {
3791 						hmeblkp->hblk_shw_bit = 0;
3792 					}
3793 				}
3794 
3795 				/*
3796 				 * Hblk_hmecnt and hblk_vcnt could be non zero
3797 				 * since hblk_unload() does not gurantee that.
3798 				 *
3799 				 * XXX - this could cause tteload() to spin
3800 				 * where sfmmu_shadow_hcleanup() is called.
3801 				 */
3802 			}
3803 
3804 			nx_hblk = hmeblkp->hblk_next;
3805 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
3806 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3807 				    &list, 0);
3808 			} else {
3809 				pr_hblk = hmeblkp;
3810 			}
3811 			hmeblkp = nx_hblk;
3812 		}
3813 
3814 		SFMMU_HASH_UNLOCK(hmebp);
3815 
3816 		if (shadow) {
3817 			/*
3818 			 * We found another shadow hblk so cleaned its
3819 			 * children.  We need to go back and cleanup
3820 			 * the original hblk so we don't change the
3821 			 * addr.
3822 			 */
3823 			shadow = 0;
3824 		} else {
3825 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
3826 			    (1 << hmeshift));
3827 		}
3828 	}
3829 	sfmmu_hblks_list_purge(&list, 0);
3830 }
3831 
3832 /*
3833  * This routine's job is to delete stale invalid shared hmeregions hmeblks that
3834  * may still linger on after pageunload.
3835  */
3836 static void
3837 sfmmu_cleanup_rhblk(sf_srd_t *srdp, caddr_t addr, uint_t rid, int ttesz)
3838 {
3839 	int hmeshift;
3840 	hmeblk_tag hblktag;
3841 	struct hmehash_bucket *hmebp;
3842 	struct hme_blk *hmeblkp;
3843 	struct hme_blk *pr_hblk;
3844 	struct hme_blk *list = NULL;
3845 
3846 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3847 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3848 
3849 	hmeshift = HME_HASH_SHIFT(ttesz);
3850 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3851 	hblktag.htag_rehash = ttesz;
3852 	hblktag.htag_rid = rid;
3853 	hblktag.htag_id = srdp;
3854 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3855 
3856 	SFMMU_HASH_LOCK(hmebp);
3857 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
3858 	if (hmeblkp != NULL) {
3859 		ASSERT(hmeblkp->hblk_shared);
3860 		ASSERT(!hmeblkp->hblk_shw_bit);
3861 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3862 			panic("sfmmu_cleanup_rhblk: valid hmeblk");
3863 		}
3864 		ASSERT(!hmeblkp->hblk_lckcnt);
3865 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3866 		    &list, 0);
3867 	}
3868 	SFMMU_HASH_UNLOCK(hmebp);
3869 	sfmmu_hblks_list_purge(&list, 0);
3870 }
3871 
3872 /* ARGSUSED */
3873 static void
3874 sfmmu_rgn_cb_noop(caddr_t saddr, caddr_t eaddr, caddr_t r_saddr,
3875     size_t r_size, void *r_obj, u_offset_t r_objoff)
3876 {
3877 }
3878 
3879 /*
3880  * Searches for an hmeblk which maps addr, then unloads this mapping
3881  * and updates *eaddrp, if the hmeblk is found.
3882  */
3883 static void
3884 sfmmu_unload_hmeregion_va(sf_srd_t *srdp, uint_t rid, caddr_t addr,
3885     caddr_t eaddr, int ttesz, caddr_t *eaddrp)
3886 {
3887 	int hmeshift;
3888 	hmeblk_tag hblktag;
3889 	struct hmehash_bucket *hmebp;
3890 	struct hme_blk *hmeblkp;
3891 	struct hme_blk *pr_hblk;
3892 	struct hme_blk *list = NULL;
3893 
3894 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3895 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3896 	ASSERT(ttesz >= HBLK_MIN_TTESZ);
3897 
3898 	hmeshift = HME_HASH_SHIFT(ttesz);
3899 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3900 	hblktag.htag_rehash = ttesz;
3901 	hblktag.htag_rid = rid;
3902 	hblktag.htag_id = srdp;
3903 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3904 
3905 	SFMMU_HASH_LOCK(hmebp);
3906 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
3907 	if (hmeblkp != NULL) {
3908 		ASSERT(hmeblkp->hblk_shared);
3909 		ASSERT(!hmeblkp->hblk_lckcnt);
3910 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3911 			*eaddrp = sfmmu_hblk_unload(NULL, hmeblkp, addr,
3912 			    eaddr, NULL, HAT_UNLOAD);
3913 			ASSERT(*eaddrp > addr);
3914 		}
3915 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3916 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3917 		    &list, 0);
3918 	}
3919 	SFMMU_HASH_UNLOCK(hmebp);
3920 	sfmmu_hblks_list_purge(&list, 0);
3921 }
3922 
3923 static void
3924 sfmmu_unload_hmeregion(sf_srd_t *srdp, sf_region_t *rgnp)
3925 {
3926 	int ttesz = rgnp->rgn_pgszc;
3927 	size_t rsz = rgnp->rgn_size;
3928 	caddr_t rsaddr = rgnp->rgn_saddr;
3929 	caddr_t readdr = rsaddr + rsz;
3930 	caddr_t rhsaddr;
3931 	caddr_t va;
3932 	uint_t rid = rgnp->rgn_id;
3933 	caddr_t cbsaddr;
3934 	caddr_t cbeaddr;
3935 	hat_rgn_cb_func_t rcbfunc;
3936 	ulong_t cnt;
3937 
3938 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3939 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3940 
3941 	ASSERT(IS_P2ALIGNED(rsaddr, TTEBYTES(ttesz)));
3942 	ASSERT(IS_P2ALIGNED(rsz, TTEBYTES(ttesz)));
3943 	if (ttesz < HBLK_MIN_TTESZ) {
3944 		ttesz = HBLK_MIN_TTESZ;
3945 		rhsaddr = (caddr_t)P2ALIGN((uintptr_t)rsaddr, HBLK_MIN_BYTES);
3946 	} else {
3947 		rhsaddr = rsaddr;
3948 	}
3949 
3950 	if ((rcbfunc = rgnp->rgn_cb_function) == NULL) {
3951 		rcbfunc = sfmmu_rgn_cb_noop;
3952 	}
3953 
3954 	while (ttesz >= HBLK_MIN_TTESZ) {
3955 		cbsaddr = rsaddr;
3956 		cbeaddr = rsaddr;
3957 		if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
3958 			ttesz--;
3959 			continue;
3960 		}
3961 		cnt = 0;
3962 		va = rsaddr;
3963 		while (va < readdr) {
3964 			ASSERT(va >= rhsaddr);
3965 			if (va != cbeaddr) {
3966 				if (cbeaddr != cbsaddr) {
3967 					ASSERT(cbeaddr > cbsaddr);
3968 					(*rcbfunc)(cbsaddr, cbeaddr,
3969 					    rsaddr, rsz, rgnp->rgn_obj,
3970 					    rgnp->rgn_objoff);
3971 				}
3972 				cbsaddr = va;
3973 				cbeaddr = va;
3974 			}
3975 			sfmmu_unload_hmeregion_va(srdp, rid, va, readdr,
3976 			    ttesz, &cbeaddr);
3977 			cnt++;
3978 			va = rhsaddr + (cnt << TTE_PAGE_SHIFT(ttesz));
3979 		}
3980 		if (cbeaddr != cbsaddr) {
3981 			ASSERT(cbeaddr > cbsaddr);
3982 			(*rcbfunc)(cbsaddr, cbeaddr, rsaddr,
3983 			    rsz, rgnp->rgn_obj,
3984 			    rgnp->rgn_objoff);
3985 		}
3986 		ttesz--;
3987 	}
3988 }
3989 
3990 /*
3991  * Release one hardware address translation lock on the given address range.
3992  */
3993 void
3994 hat_unlock(struct hat *sfmmup, caddr_t addr, size_t len)
3995 {
3996 	struct hmehash_bucket *hmebp;
3997 	hmeblk_tag hblktag;
3998 	int hmeshift, hashno = 1;
3999 	struct hme_blk *hmeblkp, *list = NULL;
4000 	caddr_t endaddr;
4001 
4002 	ASSERT(sfmmup != NULL);
4003 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4004 
4005 	ASSERT((sfmmup == ksfmmup) ||
4006 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4007 	ASSERT((len & MMU_PAGEOFFSET) == 0);
4008 	endaddr = addr + len;
4009 	hblktag.htag_id = sfmmup;
4010 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4011 
4012 	/*
4013 	 * Spitfire supports 4 page sizes.
4014 	 * Most pages are expected to be of the smallest page size (8K) and
4015 	 * these will not need to be rehashed. 64K pages also don't need to be
4016 	 * rehashed because an hmeblk spans 64K of address space. 512K pages
4017 	 * might need 1 rehash and and 4M pages might need 2 rehashes.
4018 	 */
4019 	while (addr < endaddr) {
4020 		hmeshift = HME_HASH_SHIFT(hashno);
4021 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
4022 		hblktag.htag_rehash = hashno;
4023 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
4024 
4025 		SFMMU_HASH_LOCK(hmebp);
4026 
4027 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
4028 		if (hmeblkp != NULL) {
4029 			ASSERT(!hmeblkp->hblk_shared);
4030 			/*
4031 			 * If we encounter a shadow hmeblk then
4032 			 * we know there are no valid hmeblks mapping
4033 			 * this address at this size or larger.
4034 			 * Just increment address by the smallest
4035 			 * page size.
4036 			 */
4037 			if (hmeblkp->hblk_shw_bit) {
4038 				addr += MMU_PAGESIZE;
4039 			} else {
4040 				addr = sfmmu_hblk_unlock(hmeblkp, addr,
4041 				    endaddr);
4042 			}
4043 			SFMMU_HASH_UNLOCK(hmebp);
4044 			hashno = 1;
4045 			continue;
4046 		}
4047 		SFMMU_HASH_UNLOCK(hmebp);
4048 
4049 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
4050 			/*
4051 			 * We have traversed the whole list and rehashed
4052 			 * if necessary without finding the address to unlock
4053 			 * which should never happen.
4054 			 */
4055 			panic("sfmmu_unlock: addr not found. "
4056 			    "addr %p hat %p", (void *)addr, (void *)sfmmup);
4057 		} else {
4058 			hashno++;
4059 		}
4060 	}
4061 
4062 	sfmmu_hblks_list_purge(&list, 0);
4063 }
4064 
4065 void
4066 hat_unlock_region(struct hat *sfmmup, caddr_t addr, size_t len,
4067     hat_region_cookie_t rcookie)
4068 {
4069 	sf_srd_t *srdp;
4070 	sf_region_t *rgnp;
4071 	int ttesz;
4072 	uint_t rid;
4073 	caddr_t eaddr;
4074 	caddr_t va;
4075 	int hmeshift;
4076 	hmeblk_tag hblktag;
4077 	struct hmehash_bucket *hmebp;
4078 	struct hme_blk *hmeblkp;
4079 	struct hme_blk *pr_hblk;
4080 	struct hme_blk *list;
4081 
4082 	if (rcookie == HAT_INVALID_REGION_COOKIE) {
4083 		hat_unlock(sfmmup, addr, len);
4084 		return;
4085 	}
4086 
4087 	ASSERT(sfmmup != NULL);
4088 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4089 	ASSERT(sfmmup != ksfmmup);
4090 
4091 	srdp = sfmmup->sfmmu_srdp;
4092 	rid = (uint_t)((uint64_t)rcookie);
4093 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
4094 	eaddr = addr + len;
4095 	va = addr;
4096 	list = NULL;
4097 	rgnp = srdp->srd_hmergnp[rid];
4098 	SFMMU_VALIDATE_HMERID(sfmmup, rid, addr, len);
4099 
4100 	ASSERT(IS_P2ALIGNED(addr, TTEBYTES(rgnp->rgn_pgszc)));
4101 	ASSERT(IS_P2ALIGNED(len, TTEBYTES(rgnp->rgn_pgszc)));
4102 	if (rgnp->rgn_pgszc < HBLK_MIN_TTESZ) {
4103 		ttesz = HBLK_MIN_TTESZ;
4104 	} else {
4105 		ttesz = rgnp->rgn_pgszc;
4106 	}
4107 	while (va < eaddr) {
4108 		while (ttesz < rgnp->rgn_pgszc &&
4109 		    IS_P2ALIGNED(va, TTEBYTES(ttesz + 1))) {
4110 			ttesz++;
4111 		}
4112 		while (ttesz >= HBLK_MIN_TTESZ) {
4113 			if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
4114 				ttesz--;
4115 				continue;
4116 			}
4117 			hmeshift = HME_HASH_SHIFT(ttesz);
4118 			hblktag.htag_bspage = HME_HASH_BSPAGE(va, hmeshift);
4119 			hblktag.htag_rehash = ttesz;
4120 			hblktag.htag_rid = rid;
4121 			hblktag.htag_id = srdp;
4122 			hmebp = HME_HASH_FUNCTION(srdp, va, hmeshift);
4123 			SFMMU_HASH_LOCK(hmebp);
4124 			HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk,
4125 			    &list);
4126 			if (hmeblkp == NULL) {
4127 				SFMMU_HASH_UNLOCK(hmebp);
4128 				ttesz--;
4129 				continue;
4130 			}
4131 			ASSERT(hmeblkp->hblk_shared);
4132 			va = sfmmu_hblk_unlock(hmeblkp, va, eaddr);
4133 			ASSERT(va >= eaddr ||
4134 			    IS_P2ALIGNED((uintptr_t)va, TTEBYTES(ttesz)));
4135 			SFMMU_HASH_UNLOCK(hmebp);
4136 			break;
4137 		}
4138 		if (ttesz < HBLK_MIN_TTESZ) {
4139 			panic("hat_unlock_region: addr not found "
4140 			    "addr %p hat %p", (void *)va, (void *)sfmmup);
4141 		}
4142 	}
4143 	sfmmu_hblks_list_purge(&list, 0);
4144 }
4145 
4146 /*
4147  * Function to unlock a range of addresses in an hmeblk.  It returns the
4148  * next address that needs to be unlocked.
4149  * Should be called with the hash lock held.
4150  */
4151 static caddr_t
4152 sfmmu_hblk_unlock(struct hme_blk *hmeblkp, caddr_t addr, caddr_t endaddr)
4153 {
4154 	struct sf_hment *sfhme;
4155 	tte_t tteold, ttemod;
4156 	int ttesz, ret;
4157 
4158 	ASSERT(in_hblk_range(hmeblkp, addr));
4159 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4160 
4161 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4162 	ttesz = get_hblk_ttesz(hmeblkp);
4163 
4164 	HBLKTOHME(sfhme, hmeblkp, addr);
4165 	while (addr < endaddr) {
4166 readtte:
4167 		sfmmu_copytte(&sfhme->hme_tte, &tteold);
4168 		if (TTE_IS_VALID(&tteold)) {
4169 
4170 			ttemod = tteold;
4171 
4172 			ret = sfmmu_modifytte_try(&tteold, &ttemod,
4173 			    &sfhme->hme_tte);
4174 
4175 			if (ret < 0)
4176 				goto readtte;
4177 
4178 			if (hmeblkp->hblk_lckcnt == 0)
4179 				panic("zero hblk lckcnt");
4180 
4181 			if (((uintptr_t)addr + TTEBYTES(ttesz)) >
4182 			    (uintptr_t)endaddr)
4183 				panic("can't unlock large tte");
4184 
4185 			ASSERT(hmeblkp->hblk_lckcnt > 0);
4186 			atomic_add_32(&hmeblkp->hblk_lckcnt, -1);
4187 			HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
4188 		} else {
4189 			panic("sfmmu_hblk_unlock: invalid tte");
4190 		}
4191 		addr += TTEBYTES(ttesz);
4192 		sfhme++;
4193 	}
4194 	return (addr);
4195 }
4196 
4197 /*
4198  * Physical Address Mapping Framework
4199  *
4200  * General rules:
4201  *
4202  * (1) Applies only to seg_kmem memory pages. To make things easier,
4203  *     seg_kpm addresses are also accepted by the routines, but nothing
4204  *     is done with them since by definition their PA mappings are static.
4205  * (2) hat_add_callback() may only be called while holding the page lock
4206  *     SE_SHARED or SE_EXCL of the underlying page (e.g., as_pagelock()),
4207  *     or passing HAC_PAGELOCK flag.
4208  * (3) prehandler() and posthandler() may not call hat_add_callback() or
4209  *     hat_delete_callback(), nor should they allocate memory. Post quiesce
4210  *     callbacks may not sleep or acquire adaptive mutex locks.
4211  * (4) Either prehandler() or posthandler() (but not both) may be specified
4212  *     as being NULL.  Specifying an errhandler() is optional.
4213  *
4214  * Details of using the framework:
4215  *
4216  * registering a callback (hat_register_callback())
4217  *
4218  *	Pass prehandler, posthandler, errhandler addresses
4219  *	as described below. If capture_cpus argument is nonzero,
4220  *	suspend callback to the prehandler will occur with CPUs
4221  *	captured and executing xc_loop() and CPUs will remain
4222  *	captured until after the posthandler suspend callback
4223  *	occurs.
4224  *
4225  * adding a callback (hat_add_callback())
4226  *
4227  *      as_pagelock();
4228  *	hat_add_callback();
4229  *      save returned pfn in private data structures or program registers;
4230  *      as_pageunlock();
4231  *
4232  * prehandler()
4233  *
4234  *	Stop all accesses by physical address to this memory page.
4235  *	Called twice: the first, PRESUSPEND, is a context safe to acquire
4236  *	adaptive locks. The second, SUSPEND, is called at high PIL with
4237  *	CPUs captured so adaptive locks may NOT be acquired (and all spin
4238  *	locks must be XCALL_PIL or higher locks).
4239  *
4240  *	May return the following errors:
4241  *		EIO:	A fatal error has occurred. This will result in panic.
4242  *		EAGAIN:	The page cannot be suspended. This will fail the
4243  *			relocation.
4244  *		0:	Success.
4245  *
4246  * posthandler()
4247  *
4248  *      Save new pfn in private data structures or program registers;
4249  *	not allowed to fail (non-zero return values will result in panic).
4250  *
4251  * errhandler()
4252  *
4253  *	called when an error occurs related to the callback.  Currently
4254  *	the only such error is HAT_CB_ERR_LEAKED which indicates that
4255  *	a page is being freed, but there are still outstanding callback(s)
4256  *	registered on the page.
4257  *
4258  * removing a callback (hat_delete_callback(); e.g., prior to freeing memory)
4259  *
4260  *	stop using physical address
4261  *	hat_delete_callback();
4262  *
4263  */
4264 
4265 /*
4266  * Register a callback class.  Each subsystem should do this once and
4267  * cache the id_t returned for use in setting up and tearing down callbacks.
4268  *
4269  * There is no facility for removing callback IDs once they are created;
4270  * the "key" should be unique for each module, so in case a module is unloaded
4271  * and subsequently re-loaded, we can recycle the module's previous entry.
4272  */
4273 id_t
4274 hat_register_callback(int key,
4275 	int (*prehandler)(caddr_t, uint_t, uint_t, void *),
4276 	int (*posthandler)(caddr_t, uint_t, uint_t, void *, pfn_t),
4277 	int (*errhandler)(caddr_t, uint_t, uint_t, void *),
4278 	int capture_cpus)
4279 {
4280 	id_t id;
4281 
4282 	/*
4283 	 * Search the table for a pre-existing callback associated with
4284 	 * the identifier "key".  If one exists, we re-use that entry in
4285 	 * the table for this instance, otherwise we assign the next
4286 	 * available table slot.
4287 	 */
4288 	for (id = 0; id < sfmmu_max_cb_id; id++) {
4289 		if (sfmmu_cb_table[id].key == key)
4290 			break;
4291 	}
4292 
4293 	if (id == sfmmu_max_cb_id) {
4294 		id = sfmmu_cb_nextid++;
4295 		if (id >= sfmmu_max_cb_id)
4296 			panic("hat_register_callback: out of callback IDs");
4297 	}
4298 
4299 	ASSERT(prehandler != NULL || posthandler != NULL);
4300 
4301 	sfmmu_cb_table[id].key = key;
4302 	sfmmu_cb_table[id].prehandler = prehandler;
4303 	sfmmu_cb_table[id].posthandler = posthandler;
4304 	sfmmu_cb_table[id].errhandler = errhandler;
4305 	sfmmu_cb_table[id].capture_cpus = capture_cpus;
4306 
4307 	return (id);
4308 }
4309 
4310 #define	HAC_COOKIE_NONE	(void *)-1
4311 
4312 /*
4313  * Add relocation callbacks to the specified addr/len which will be called
4314  * when relocating the associated page. See the description of pre and
4315  * posthandler above for more details.
4316  *
4317  * If HAC_PAGELOCK is included in flags, the underlying memory page is
4318  * locked internally so the caller must be able to deal with the callback
4319  * running even before this function has returned.  If HAC_PAGELOCK is not
4320  * set, it is assumed that the underlying memory pages are locked.
4321  *
4322  * Since the caller must track the individual page boundaries anyway,
4323  * we only allow a callback to be added to a single page (large
4324  * or small).  Thus [addr, addr + len) MUST be contained within a single
4325  * page.
4326  *
4327  * Registering multiple callbacks on the same [addr, addr+len) is supported,
4328  * _provided_that_ a unique parameter is specified for each callback.
4329  * If multiple callbacks are registered on the same range the callback will
4330  * be invoked with each unique parameter. Registering the same callback with
4331  * the same argument more than once will result in corrupted kernel state.
4332  *
4333  * Returns the pfn of the underlying kernel page in *rpfn
4334  * on success, or PFN_INVALID on failure.
4335  *
4336  * cookiep (if passed) provides storage space for an opaque cookie
4337  * to return later to hat_delete_callback(). This cookie makes the callback
4338  * deletion significantly quicker by avoiding a potentially lengthy hash
4339  * search.
4340  *
4341  * Returns values:
4342  *    0:      success
4343  *    ENOMEM: memory allocation failure (e.g. flags was passed as HAC_NOSLEEP)
4344  *    EINVAL: callback ID is not valid
4345  *    ENXIO:  ["vaddr", "vaddr" + len) is not mapped in the kernel's address
4346  *            space
4347  *    ERANGE: ["vaddr", "vaddr" + len) crosses a page boundary
4348  */
4349 int
4350 hat_add_callback(id_t callback_id, caddr_t vaddr, uint_t len, uint_t flags,
4351 	void *pvt, pfn_t *rpfn, void **cookiep)
4352 {
4353 	struct 		hmehash_bucket *hmebp;
4354 	hmeblk_tag 	hblktag;
4355 	struct hme_blk	*hmeblkp;
4356 	int 		hmeshift, hashno;
4357 	caddr_t 	saddr, eaddr, baseaddr;
4358 	struct pa_hment *pahmep;
4359 	struct sf_hment *sfhmep, *osfhmep;
4360 	kmutex_t	*pml;
4361 	tte_t   	tte;
4362 	page_t		*pp;
4363 	vnode_t		*vp;
4364 	u_offset_t	off;
4365 	pfn_t		pfn;
4366 	int		kmflags = (flags & HAC_SLEEP)? KM_SLEEP : KM_NOSLEEP;
4367 	int		locked = 0;
4368 
4369 	/*
4370 	 * For KPM mappings, just return the physical address since we
4371 	 * don't need to register any callbacks.
4372 	 */
4373 	if (IS_KPM_ADDR(vaddr)) {
4374 		uint64_t paddr;
4375 		SFMMU_KPM_VTOP(vaddr, paddr);
4376 		*rpfn = btop(paddr);
4377 		if (cookiep != NULL)
4378 			*cookiep = HAC_COOKIE_NONE;
4379 		return (0);
4380 	}
4381 
4382 	if (callback_id < (id_t)0 || callback_id >= sfmmu_cb_nextid) {
4383 		*rpfn = PFN_INVALID;
4384 		return (EINVAL);
4385 	}
4386 
4387 	if ((pahmep = kmem_cache_alloc(pa_hment_cache, kmflags)) == NULL) {
4388 		*rpfn = PFN_INVALID;
4389 		return (ENOMEM);
4390 	}
4391 
4392 	sfhmep = &pahmep->sfment;
4393 
4394 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4395 	eaddr = saddr + len;
4396 
4397 rehash:
4398 	/* Find the mapping(s) for this page */
4399 	for (hashno = TTE64K, hmeblkp = NULL;
4400 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4401 	    hashno++) {
4402 		hmeshift = HME_HASH_SHIFT(hashno);
4403 		hblktag.htag_id = ksfmmup;
4404 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4405 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4406 		hblktag.htag_rehash = hashno;
4407 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4408 
4409 		SFMMU_HASH_LOCK(hmebp);
4410 
4411 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4412 
4413 		if (hmeblkp == NULL)
4414 			SFMMU_HASH_UNLOCK(hmebp);
4415 	}
4416 
4417 	if (hmeblkp == NULL) {
4418 		kmem_cache_free(pa_hment_cache, pahmep);
4419 		*rpfn = PFN_INVALID;
4420 		return (ENXIO);
4421 	}
4422 
4423 	ASSERT(!hmeblkp->hblk_shared);
4424 
4425 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4426 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4427 
4428 	if (!TTE_IS_VALID(&tte)) {
4429 		SFMMU_HASH_UNLOCK(hmebp);
4430 		kmem_cache_free(pa_hment_cache, pahmep);
4431 		*rpfn = PFN_INVALID;
4432 		return (ENXIO);
4433 	}
4434 
4435 	/*
4436 	 * Make sure the boundaries for the callback fall within this
4437 	 * single mapping.
4438 	 */
4439 	baseaddr = (caddr_t)get_hblk_base(hmeblkp);
4440 	ASSERT(saddr >= baseaddr);
4441 	if (eaddr > saddr + TTEBYTES(TTE_CSZ(&tte))) {
4442 		SFMMU_HASH_UNLOCK(hmebp);
4443 		kmem_cache_free(pa_hment_cache, pahmep);
4444 		*rpfn = PFN_INVALID;
4445 		return (ERANGE);
4446 	}
4447 
4448 	pfn = sfmmu_ttetopfn(&tte, vaddr);
4449 
4450 	/*
4451 	 * The pfn may not have a page_t underneath in which case we
4452 	 * just return it. This can happen if we are doing I/O to a
4453 	 * static portion of the kernel's address space, for instance.
4454 	 */
4455 	pp = osfhmep->hme_page;
4456 	if (pp == NULL) {
4457 		SFMMU_HASH_UNLOCK(hmebp);
4458 		kmem_cache_free(pa_hment_cache, pahmep);
4459 		*rpfn = pfn;
4460 		if (cookiep)
4461 			*cookiep = HAC_COOKIE_NONE;
4462 		return (0);
4463 	}
4464 	ASSERT(pp == PP_PAGEROOT(pp));
4465 
4466 	vp = pp->p_vnode;
4467 	off = pp->p_offset;
4468 
4469 	pml = sfmmu_mlist_enter(pp);
4470 
4471 	if (flags & HAC_PAGELOCK) {
4472 		if (!page_trylock(pp, SE_SHARED)) {
4473 			/*
4474 			 * Somebody is holding SE_EXCL lock. Might
4475 			 * even be hat_page_relocate(). Drop all
4476 			 * our locks, lookup the page in &kvp, and
4477 			 * retry. If it doesn't exist in &kvp and &zvp,
4478 			 * then we must be dealing with a kernel mapped
4479 			 * page which doesn't actually belong to
4480 			 * segkmem so we punt.
4481 			 */
4482 			sfmmu_mlist_exit(pml);
4483 			SFMMU_HASH_UNLOCK(hmebp);
4484 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4485 
4486 			/* check zvp before giving up */
4487 			if (pp == NULL)
4488 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4489 				    SE_SHARED);
4490 
4491 			/* Okay, we didn't find it, give up */
4492 			if (pp == NULL) {
4493 				kmem_cache_free(pa_hment_cache, pahmep);
4494 				*rpfn = pfn;
4495 				if (cookiep)
4496 					*cookiep = HAC_COOKIE_NONE;
4497 				return (0);
4498 			}
4499 			page_unlock(pp);
4500 			goto rehash;
4501 		}
4502 		locked = 1;
4503 	}
4504 
4505 	if (!PAGE_LOCKED(pp) && !panicstr)
4506 		panic("hat_add_callback: page 0x%p not locked", (void *)pp);
4507 
4508 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4509 	    pp->p_offset != off) {
4510 		/*
4511 		 * The page moved before we got our hands on it.  Drop
4512 		 * all the locks and try again.
4513 		 */
4514 		ASSERT((flags & HAC_PAGELOCK) != 0);
4515 		sfmmu_mlist_exit(pml);
4516 		SFMMU_HASH_UNLOCK(hmebp);
4517 		page_unlock(pp);
4518 		locked = 0;
4519 		goto rehash;
4520 	}
4521 
4522 	if (!VN_ISKAS(vp)) {
4523 		/*
4524 		 * This is not a segkmem page but another page which
4525 		 * has been kernel mapped. It had better have at least
4526 		 * a share lock on it. Return the pfn.
4527 		 */
4528 		sfmmu_mlist_exit(pml);
4529 		SFMMU_HASH_UNLOCK(hmebp);
4530 		if (locked)
4531 			page_unlock(pp);
4532 		kmem_cache_free(pa_hment_cache, pahmep);
4533 		ASSERT(PAGE_LOCKED(pp));
4534 		*rpfn = pfn;
4535 		if (cookiep)
4536 			*cookiep = HAC_COOKIE_NONE;
4537 		return (0);
4538 	}
4539 
4540 	/*
4541 	 * Setup this pa_hment and link its embedded dummy sf_hment into
4542 	 * the mapping list.
4543 	 */
4544 	pp->p_share++;
4545 	pahmep->cb_id = callback_id;
4546 	pahmep->addr = vaddr;
4547 	pahmep->len = len;
4548 	pahmep->refcnt = 1;
4549 	pahmep->flags = 0;
4550 	pahmep->pvt = pvt;
4551 
4552 	sfhmep->hme_tte.ll = 0;
4553 	sfhmep->hme_data = pahmep;
4554 	sfhmep->hme_prev = osfhmep;
4555 	sfhmep->hme_next = osfhmep->hme_next;
4556 
4557 	if (osfhmep->hme_next)
4558 		osfhmep->hme_next->hme_prev = sfhmep;
4559 
4560 	osfhmep->hme_next = sfhmep;
4561 
4562 	sfmmu_mlist_exit(pml);
4563 	SFMMU_HASH_UNLOCK(hmebp);
4564 
4565 	if (locked)
4566 		page_unlock(pp);
4567 
4568 	*rpfn = pfn;
4569 	if (cookiep)
4570 		*cookiep = (void *)pahmep;
4571 
4572 	return (0);
4573 }
4574 
4575 /*
4576  * Remove the relocation callbacks from the specified addr/len.
4577  */
4578 void
4579 hat_delete_callback(caddr_t vaddr, uint_t len, void *pvt, uint_t flags,
4580 	void *cookie)
4581 {
4582 	struct		hmehash_bucket *hmebp;
4583 	hmeblk_tag	hblktag;
4584 	struct hme_blk	*hmeblkp;
4585 	int		hmeshift, hashno;
4586 	caddr_t		saddr;
4587 	struct pa_hment	*pahmep;
4588 	struct sf_hment	*sfhmep, *osfhmep;
4589 	kmutex_t	*pml;
4590 	tte_t		tte;
4591 	page_t		*pp;
4592 	vnode_t		*vp;
4593 	u_offset_t	off;
4594 	int		locked = 0;
4595 
4596 	/*
4597 	 * If the cookie is HAC_COOKIE_NONE then there is no pa_hment to
4598 	 * remove so just return.
4599 	 */
4600 	if (cookie == HAC_COOKIE_NONE || IS_KPM_ADDR(vaddr))
4601 		return;
4602 
4603 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4604 
4605 rehash:
4606 	/* Find the mapping(s) for this page */
4607 	for (hashno = TTE64K, hmeblkp = NULL;
4608 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4609 	    hashno++) {
4610 		hmeshift = HME_HASH_SHIFT(hashno);
4611 		hblktag.htag_id = ksfmmup;
4612 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4613 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4614 		hblktag.htag_rehash = hashno;
4615 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4616 
4617 		SFMMU_HASH_LOCK(hmebp);
4618 
4619 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4620 
4621 		if (hmeblkp == NULL)
4622 			SFMMU_HASH_UNLOCK(hmebp);
4623 	}
4624 
4625 	if (hmeblkp == NULL)
4626 		return;
4627 
4628 	ASSERT(!hmeblkp->hblk_shared);
4629 
4630 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4631 
4632 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4633 	if (!TTE_IS_VALID(&tte)) {
4634 		SFMMU_HASH_UNLOCK(hmebp);
4635 		return;
4636 	}
4637 
4638 	pp = osfhmep->hme_page;
4639 	if (pp == NULL) {
4640 		SFMMU_HASH_UNLOCK(hmebp);
4641 		ASSERT(cookie == NULL);
4642 		return;
4643 	}
4644 
4645 	vp = pp->p_vnode;
4646 	off = pp->p_offset;
4647 
4648 	pml = sfmmu_mlist_enter(pp);
4649 
4650 	if (flags & HAC_PAGELOCK) {
4651 		if (!page_trylock(pp, SE_SHARED)) {
4652 			/*
4653 			 * Somebody is holding SE_EXCL lock. Might
4654 			 * even be hat_page_relocate(). Drop all
4655 			 * our locks, lookup the page in &kvp, and
4656 			 * retry. If it doesn't exist in &kvp and &zvp,
4657 			 * then we must be dealing with a kernel mapped
4658 			 * page which doesn't actually belong to
4659 			 * segkmem so we punt.
4660 			 */
4661 			sfmmu_mlist_exit(pml);
4662 			SFMMU_HASH_UNLOCK(hmebp);
4663 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4664 			/* check zvp before giving up */
4665 			if (pp == NULL)
4666 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4667 				    SE_SHARED);
4668 
4669 			if (pp == NULL) {
4670 				ASSERT(cookie == NULL);
4671 				return;
4672 			}
4673 			page_unlock(pp);
4674 			goto rehash;
4675 		}
4676 		locked = 1;
4677 	}
4678 
4679 	ASSERT(PAGE_LOCKED(pp));
4680 
4681 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4682 	    pp->p_offset != off) {
4683 		/*
4684 		 * The page moved before we got our hands on it.  Drop
4685 		 * all the locks and try again.
4686 		 */
4687 		ASSERT((flags & HAC_PAGELOCK) != 0);
4688 		sfmmu_mlist_exit(pml);
4689 		SFMMU_HASH_UNLOCK(hmebp);
4690 		page_unlock(pp);
4691 		locked = 0;
4692 		goto rehash;
4693 	}
4694 
4695 	if (!VN_ISKAS(vp)) {
4696 		/*
4697 		 * This is not a segkmem page but another page which
4698 		 * has been kernel mapped.
4699 		 */
4700 		sfmmu_mlist_exit(pml);
4701 		SFMMU_HASH_UNLOCK(hmebp);
4702 		if (locked)
4703 			page_unlock(pp);
4704 		ASSERT(cookie == NULL);
4705 		return;
4706 	}
4707 
4708 	if (cookie != NULL) {
4709 		pahmep = (struct pa_hment *)cookie;
4710 		sfhmep = &pahmep->sfment;
4711 	} else {
4712 		for (sfhmep = pp->p_mapping; sfhmep != NULL;
4713 		    sfhmep = sfhmep->hme_next) {
4714 
4715 			/*
4716 			 * skip va<->pa mappings
4717 			 */
4718 			if (!IS_PAHME(sfhmep))
4719 				continue;
4720 
4721 			pahmep = sfhmep->hme_data;
4722 			ASSERT(pahmep != NULL);
4723 
4724 			/*
4725 			 * if pa_hment matches, remove it
4726 			 */
4727 			if ((pahmep->pvt == pvt) &&
4728 			    (pahmep->addr == vaddr) &&
4729 			    (pahmep->len == len)) {
4730 				break;
4731 			}
4732 		}
4733 	}
4734 
4735 	if (sfhmep == NULL) {
4736 		if (!panicstr) {
4737 			panic("hat_delete_callback: pa_hment not found, pp %p",
4738 			    (void *)pp);
4739 		}
4740 		return;
4741 	}
4742 
4743 	/*
4744 	 * Note: at this point a valid kernel mapping must still be
4745 	 * present on this page.
4746 	 */
4747 	pp->p_share--;
4748 	if (pp->p_share <= 0)
4749 		panic("hat_delete_callback: zero p_share");
4750 
4751 	if (--pahmep->refcnt == 0) {
4752 		if (pahmep->flags != 0)
4753 			panic("hat_delete_callback: pa_hment is busy");
4754 
4755 		/*
4756 		 * Remove sfhmep from the mapping list for the page.
4757 		 */
4758 		if (sfhmep->hme_prev) {
4759 			sfhmep->hme_prev->hme_next = sfhmep->hme_next;
4760 		} else {
4761 			pp->p_mapping = sfhmep->hme_next;
4762 		}
4763 
4764 		if (sfhmep->hme_next)
4765 			sfhmep->hme_next->hme_prev = sfhmep->hme_prev;
4766 
4767 		sfmmu_mlist_exit(pml);
4768 		SFMMU_HASH_UNLOCK(hmebp);
4769 
4770 		if (locked)
4771 			page_unlock(pp);
4772 
4773 		kmem_cache_free(pa_hment_cache, pahmep);
4774 		return;
4775 	}
4776 
4777 	sfmmu_mlist_exit(pml);
4778 	SFMMU_HASH_UNLOCK(hmebp);
4779 	if (locked)
4780 		page_unlock(pp);
4781 }
4782 
4783 /*
4784  * hat_probe returns 1 if the translation for the address 'addr' is
4785  * loaded, zero otherwise.
4786  *
4787  * hat_probe should be used only for advisorary purposes because it may
4788  * occasionally return the wrong value. The implementation must guarantee that
4789  * returning the wrong value is a very rare event. hat_probe is used
4790  * to implement optimizations in the segment drivers.
4791  *
4792  */
4793 int
4794 hat_probe(struct hat *sfmmup, caddr_t addr)
4795 {
4796 	pfn_t pfn;
4797 	tte_t tte;
4798 
4799 	ASSERT(sfmmup != NULL);
4800 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4801 
4802 	ASSERT((sfmmup == ksfmmup) ||
4803 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4804 
4805 	if (sfmmup == ksfmmup) {
4806 		while ((pfn = sfmmu_vatopfn(addr, sfmmup, &tte))
4807 		    == PFN_SUSPENDED) {
4808 			sfmmu_vatopfn_suspended(addr, sfmmup, &tte);
4809 		}
4810 	} else {
4811 		pfn = sfmmu_uvatopfn(addr, sfmmup, NULL);
4812 	}
4813 
4814 	if (pfn != PFN_INVALID)
4815 		return (1);
4816 	else
4817 		return (0);
4818 }
4819 
4820 ssize_t
4821 hat_getpagesize(struct hat *sfmmup, caddr_t addr)
4822 {
4823 	tte_t tte;
4824 
4825 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4826 
4827 	if (sfmmup == ksfmmup) {
4828 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4829 			return (-1);
4830 		}
4831 	} else {
4832 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4833 			return (-1);
4834 		}
4835 	}
4836 
4837 	ASSERT(TTE_IS_VALID(&tte));
4838 	return (TTEBYTES(TTE_CSZ(&tte)));
4839 }
4840 
4841 uint_t
4842 hat_getattr(struct hat *sfmmup, caddr_t addr, uint_t *attr)
4843 {
4844 	tte_t tte;
4845 
4846 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4847 
4848 	if (sfmmup == ksfmmup) {
4849 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4850 			tte.ll = 0;
4851 		}
4852 	} else {
4853 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4854 			tte.ll = 0;
4855 		}
4856 	}
4857 	if (TTE_IS_VALID(&tte)) {
4858 		*attr = sfmmu_ptov_attr(&tte);
4859 		return (0);
4860 	}
4861 	*attr = 0;
4862 	return ((uint_t)0xffffffff);
4863 }
4864 
4865 /*
4866  * Enables more attributes on specified address range (ie. logical OR)
4867  */
4868 void
4869 hat_setattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4870 {
4871 	if (hat->sfmmu_xhat_provider) {
4872 		XHAT_SETATTR(hat, addr, len, attr);
4873 		return;
4874 	} else {
4875 		/*
4876 		 * This must be a CPU HAT. If the address space has
4877 		 * XHATs attached, change attributes for all of them,
4878 		 * just in case
4879 		 */
4880 		ASSERT(hat->sfmmu_as != NULL);
4881 		if (hat->sfmmu_as->a_xhat != NULL)
4882 			xhat_setattr_all(hat->sfmmu_as, addr, len, attr);
4883 	}
4884 
4885 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_SETATTR);
4886 }
4887 
4888 /*
4889  * Assigns attributes to the specified address range.  All the attributes
4890  * are specified.
4891  */
4892 void
4893 hat_chgattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4894 {
4895 	if (hat->sfmmu_xhat_provider) {
4896 		XHAT_CHGATTR(hat, addr, len, attr);
4897 		return;
4898 	} else {
4899 		/*
4900 		 * This must be a CPU HAT. If the address space has
4901 		 * XHATs attached, change attributes for all of them,
4902 		 * just in case
4903 		 */
4904 		ASSERT(hat->sfmmu_as != NULL);
4905 		if (hat->sfmmu_as->a_xhat != NULL)
4906 			xhat_chgattr_all(hat->sfmmu_as, addr, len, attr);
4907 	}
4908 
4909 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CHGATTR);
4910 }
4911 
4912 /*
4913  * Remove attributes on the specified address range (ie. loginal NAND)
4914  */
4915 void
4916 hat_clrattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4917 {
4918 	if (hat->sfmmu_xhat_provider) {
4919 		XHAT_CLRATTR(hat, addr, len, attr);
4920 		return;
4921 	} else {
4922 		/*
4923 		 * This must be a CPU HAT. If the address space has
4924 		 * XHATs attached, change attributes for all of them,
4925 		 * just in case
4926 		 */
4927 		ASSERT(hat->sfmmu_as != NULL);
4928 		if (hat->sfmmu_as->a_xhat != NULL)
4929 			xhat_clrattr_all(hat->sfmmu_as, addr, len, attr);
4930 	}
4931 
4932 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CLRATTR);
4933 }
4934 
4935 /*
4936  * Change attributes on an address range to that specified by attr and mode.
4937  */
4938 static void
4939 sfmmu_chgattr(struct hat *sfmmup, caddr_t addr, size_t len, uint_t attr,
4940 	int mode)
4941 {
4942 	struct hmehash_bucket *hmebp;
4943 	hmeblk_tag hblktag;
4944 	int hmeshift, hashno = 1;
4945 	struct hme_blk *hmeblkp, *list = NULL;
4946 	caddr_t endaddr;
4947 	cpuset_t cpuset;
4948 	demap_range_t dmr;
4949 
4950 	CPUSET_ZERO(cpuset);
4951 
4952 	ASSERT((sfmmup == ksfmmup) ||
4953 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4954 	ASSERT((len & MMU_PAGEOFFSET) == 0);
4955 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
4956 
4957 	if ((attr & PROT_USER) && (mode != SFMMU_CLRATTR) &&
4958 	    ((addr + len) > (caddr_t)USERLIMIT)) {
4959 		panic("user addr %p in kernel space",
4960 		    (void *)addr);
4961 	}
4962 
4963 	endaddr = addr + len;
4964 	hblktag.htag_id = sfmmup;
4965 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4966 	DEMAP_RANGE_INIT(sfmmup, &dmr);
4967 
4968 	while (addr < endaddr) {
4969 		hmeshift = HME_HASH_SHIFT(hashno);
4970 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
4971 		hblktag.htag_rehash = hashno;
4972 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
4973 
4974 		SFMMU_HASH_LOCK(hmebp);
4975 
4976 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
4977 		if (hmeblkp != NULL) {
4978 			ASSERT(!hmeblkp->hblk_shared);
4979 			/*
4980 			 * We've encountered a shadow hmeblk so skip the range
4981 			 * of the next smaller mapping size.
4982 			 */
4983 			if (hmeblkp->hblk_shw_bit) {
4984 				ASSERT(sfmmup != ksfmmup);
4985 				ASSERT(hashno > 1);
4986 				addr = (caddr_t)P2END((uintptr_t)addr,
4987 				    TTEBYTES(hashno - 1));
4988 			} else {
4989 				addr = sfmmu_hblk_chgattr(sfmmup,
4990 				    hmeblkp, addr, endaddr, &dmr, attr, mode);
4991 			}
4992 			SFMMU_HASH_UNLOCK(hmebp);
4993 			hashno = 1;
4994 			continue;
4995 		}
4996 		SFMMU_HASH_UNLOCK(hmebp);
4997 
4998 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
4999 			/*
5000 			 * We have traversed the whole list and rehashed
5001 			 * if necessary without finding the address to chgattr.
5002 			 * This is ok, so we increment the address by the
5003 			 * smallest hmeblk range for kernel mappings or for
5004 			 * user mappings with no large pages, and the largest
5005 			 * hmeblk range, to account for shadow hmeblks, for
5006 			 * user mappings with large pages and continue.
5007 			 */
5008 			if (sfmmup == ksfmmup)
5009 				addr = (caddr_t)P2END((uintptr_t)addr,
5010 				    TTEBYTES(1));
5011 			else
5012 				addr = (caddr_t)P2END((uintptr_t)addr,
5013 				    TTEBYTES(hashno));
5014 			hashno = 1;
5015 		} else {
5016 			hashno++;
5017 		}
5018 	}
5019 
5020 	sfmmu_hblks_list_purge(&list, 0);
5021 	DEMAP_RANGE_FLUSH(&dmr);
5022 	cpuset = sfmmup->sfmmu_cpusran;
5023 	xt_sync(cpuset);
5024 }
5025 
5026 /*
5027  * This function chgattr on a range of addresses in an hmeblk.  It returns the
5028  * next addres that needs to be chgattr.
5029  * It should be called with the hash lock held.
5030  * XXX It should be possible to optimize chgattr by not flushing every time but
5031  * on the other hand:
5032  * 1. do one flush crosscall.
5033  * 2. only flush if we are increasing permissions (make sure this will work)
5034  */
5035 static caddr_t
5036 sfmmu_hblk_chgattr(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5037 	caddr_t endaddr, demap_range_t *dmrp, uint_t attr, int mode)
5038 {
5039 	tte_t tte, tteattr, tteflags, ttemod;
5040 	struct sf_hment *sfhmep;
5041 	int ttesz;
5042 	struct page *pp = NULL;
5043 	kmutex_t *pml, *pmtx;
5044 	int ret;
5045 	int use_demap_range;
5046 #if defined(SF_ERRATA_57)
5047 	int check_exec;
5048 #endif
5049 
5050 	ASSERT(in_hblk_range(hmeblkp, addr));
5051 	ASSERT(hmeblkp->hblk_shw_bit == 0);
5052 	ASSERT(!hmeblkp->hblk_shared);
5053 
5054 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5055 	ttesz = get_hblk_ttesz(hmeblkp);
5056 
5057 	/*
5058 	 * Flush the current demap region if addresses have been
5059 	 * skipped or the page size doesn't match.
5060 	 */
5061 	use_demap_range = (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp));
5062 	if (use_demap_range) {
5063 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5064 	} else {
5065 		DEMAP_RANGE_FLUSH(dmrp);
5066 	}
5067 
5068 	tteattr.ll = sfmmu_vtop_attr(attr, mode, &tteflags);
5069 #if defined(SF_ERRATA_57)
5070 	check_exec = (sfmmup != ksfmmup) &&
5071 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
5072 	    TTE_IS_EXECUTABLE(&tteattr);
5073 #endif
5074 	HBLKTOHME(sfhmep, hmeblkp, addr);
5075 	while (addr < endaddr) {
5076 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5077 		if (TTE_IS_VALID(&tte)) {
5078 			if ((tte.ll & tteflags.ll) == tteattr.ll) {
5079 				/*
5080 				 * if the new attr is the same as old
5081 				 * continue
5082 				 */
5083 				goto next_addr;
5084 			}
5085 			if (!TTE_IS_WRITABLE(&tteattr)) {
5086 				/*
5087 				 * make sure we clear hw modify bit if we
5088 				 * removing write protections
5089 				 */
5090 				tteflags.tte_intlo |= TTE_HWWR_INT;
5091 			}
5092 
5093 			pml = NULL;
5094 			pp = sfhmep->hme_page;
5095 			if (pp) {
5096 				pml = sfmmu_mlist_enter(pp);
5097 			}
5098 
5099 			if (pp != sfhmep->hme_page) {
5100 				/*
5101 				 * tte must have been unloaded.
5102 				 */
5103 				ASSERT(pml);
5104 				sfmmu_mlist_exit(pml);
5105 				continue;
5106 			}
5107 
5108 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5109 
5110 			ttemod = tte;
5111 			ttemod.ll = (ttemod.ll & ~tteflags.ll) | tteattr.ll;
5112 			ASSERT(TTE_TO_TTEPFN(&ttemod) == TTE_TO_TTEPFN(&tte));
5113 
5114 #if defined(SF_ERRATA_57)
5115 			if (check_exec && addr < errata57_limit)
5116 				ttemod.tte_exec_perm = 0;
5117 #endif
5118 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5119 			    &sfhmep->hme_tte);
5120 
5121 			if (ret < 0) {
5122 				/* tte changed underneath us */
5123 				if (pml) {
5124 					sfmmu_mlist_exit(pml);
5125 				}
5126 				continue;
5127 			}
5128 
5129 			if (tteflags.tte_intlo & TTE_HWWR_INT) {
5130 				/*
5131 				 * need to sync if we are clearing modify bit.
5132 				 */
5133 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
5134 			}
5135 
5136 			if (pp && PP_ISRO(pp)) {
5137 				if (tteattr.tte_intlo & TTE_WRPRM_INT) {
5138 					pmtx = sfmmu_page_enter(pp);
5139 					PP_CLRRO(pp);
5140 					sfmmu_page_exit(pmtx);
5141 				}
5142 			}
5143 
5144 			if (ret > 0 && use_demap_range) {
5145 				DEMAP_RANGE_MARKPG(dmrp, addr);
5146 			} else if (ret > 0) {
5147 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
5148 			}
5149 
5150 			if (pml) {
5151 				sfmmu_mlist_exit(pml);
5152 			}
5153 		}
5154 next_addr:
5155 		addr += TTEBYTES(ttesz);
5156 		sfhmep++;
5157 		DEMAP_RANGE_NEXTPG(dmrp);
5158 	}
5159 	return (addr);
5160 }
5161 
5162 /*
5163  * This routine converts virtual attributes to physical ones.  It will
5164  * update the tteflags field with the tte mask corresponding to the attributes
5165  * affected and it returns the new attributes.  It will also clear the modify
5166  * bit if we are taking away write permission.  This is necessary since the
5167  * modify bit is the hardware permission bit and we need to clear it in order
5168  * to detect write faults.
5169  */
5170 static uint64_t
5171 sfmmu_vtop_attr(uint_t attr, int mode, tte_t *ttemaskp)
5172 {
5173 	tte_t ttevalue;
5174 
5175 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
5176 
5177 	switch (mode) {
5178 	case SFMMU_CHGATTR:
5179 		/* all attributes specified */
5180 		ttevalue.tte_inthi = MAKE_TTEATTR_INTHI(attr);
5181 		ttevalue.tte_intlo = MAKE_TTEATTR_INTLO(attr);
5182 		ttemaskp->tte_inthi = TTEINTHI_ATTR;
5183 		ttemaskp->tte_intlo = TTEINTLO_ATTR;
5184 		break;
5185 	case SFMMU_SETATTR:
5186 		ASSERT(!(attr & ~HAT_PROT_MASK));
5187 		ttemaskp->ll = 0;
5188 		ttevalue.ll = 0;
5189 		/*
5190 		 * a valid tte implies exec and read for sfmmu
5191 		 * so no need to do anything about them.
5192 		 * since priviledged access implies user access
5193 		 * PROT_USER doesn't make sense either.
5194 		 */
5195 		if (attr & PROT_WRITE) {
5196 			ttemaskp->tte_intlo |= TTE_WRPRM_INT;
5197 			ttevalue.tte_intlo |= TTE_WRPRM_INT;
5198 		}
5199 		break;
5200 	case SFMMU_CLRATTR:
5201 		/* attributes will be nand with current ones */
5202 		if (attr & ~(PROT_WRITE | PROT_USER)) {
5203 			panic("sfmmu: attr %x not supported", attr);
5204 		}
5205 		ttemaskp->ll = 0;
5206 		ttevalue.ll = 0;
5207 		if (attr & PROT_WRITE) {
5208 			/* clear both writable and modify bit */
5209 			ttemaskp->tte_intlo |= TTE_WRPRM_INT | TTE_HWWR_INT;
5210 		}
5211 		if (attr & PROT_USER) {
5212 			ttemaskp->tte_intlo |= TTE_PRIV_INT;
5213 			ttevalue.tte_intlo |= TTE_PRIV_INT;
5214 		}
5215 		break;
5216 	default:
5217 		panic("sfmmu_vtop_attr: bad mode %x", mode);
5218 	}
5219 	ASSERT(TTE_TO_TTEPFN(&ttevalue) == 0);
5220 	return (ttevalue.ll);
5221 }
5222 
5223 static uint_t
5224 sfmmu_ptov_attr(tte_t *ttep)
5225 {
5226 	uint_t attr;
5227 
5228 	ASSERT(TTE_IS_VALID(ttep));
5229 
5230 	attr = PROT_READ;
5231 
5232 	if (TTE_IS_WRITABLE(ttep)) {
5233 		attr |= PROT_WRITE;
5234 	}
5235 	if (TTE_IS_EXECUTABLE(ttep)) {
5236 		attr |= PROT_EXEC;
5237 	}
5238 	if (!TTE_IS_PRIVILEGED(ttep)) {
5239 		attr |= PROT_USER;
5240 	}
5241 	if (TTE_IS_NFO(ttep)) {
5242 		attr |= HAT_NOFAULT;
5243 	}
5244 	if (TTE_IS_NOSYNC(ttep)) {
5245 		attr |= HAT_NOSYNC;
5246 	}
5247 	if (TTE_IS_SIDEFFECT(ttep)) {
5248 		attr |= SFMMU_SIDEFFECT;
5249 	}
5250 	if (!TTE_IS_VCACHEABLE(ttep)) {
5251 		attr |= SFMMU_UNCACHEVTTE;
5252 	}
5253 	if (!TTE_IS_PCACHEABLE(ttep)) {
5254 		attr |= SFMMU_UNCACHEPTTE;
5255 	}
5256 	return (attr);
5257 }
5258 
5259 /*
5260  * hat_chgprot is a deprecated hat call.  New segment drivers
5261  * should store all attributes and use hat_*attr calls.
5262  *
5263  * Change the protections in the virtual address range
5264  * given to the specified virtual protection.  If vprot is ~PROT_WRITE,
5265  * then remove write permission, leaving the other
5266  * permissions unchanged.  If vprot is ~PROT_USER, remove user permissions.
5267  *
5268  */
5269 void
5270 hat_chgprot(struct hat *sfmmup, caddr_t addr, size_t len, uint_t vprot)
5271 {
5272 	struct hmehash_bucket *hmebp;
5273 	hmeblk_tag hblktag;
5274 	int hmeshift, hashno = 1;
5275 	struct hme_blk *hmeblkp, *list = NULL;
5276 	caddr_t endaddr;
5277 	cpuset_t cpuset;
5278 	demap_range_t dmr;
5279 
5280 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5281 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
5282 
5283 	if (sfmmup->sfmmu_xhat_provider) {
5284 		XHAT_CHGPROT(sfmmup, addr, len, vprot);
5285 		return;
5286 	} else {
5287 		/*
5288 		 * This must be a CPU HAT. If the address space has
5289 		 * XHATs attached, change attributes for all of them,
5290 		 * just in case
5291 		 */
5292 		ASSERT(sfmmup->sfmmu_as != NULL);
5293 		if (sfmmup->sfmmu_as->a_xhat != NULL)
5294 			xhat_chgprot_all(sfmmup->sfmmu_as, addr, len, vprot);
5295 	}
5296 
5297 	CPUSET_ZERO(cpuset);
5298 
5299 	if ((vprot != (uint_t)~PROT_WRITE) && (vprot & PROT_USER) &&
5300 	    ((addr + len) > (caddr_t)USERLIMIT)) {
5301 		panic("user addr %p vprot %x in kernel space",
5302 		    (void *)addr, vprot);
5303 	}
5304 	endaddr = addr + len;
5305 	hblktag.htag_id = sfmmup;
5306 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5307 	DEMAP_RANGE_INIT(sfmmup, &dmr);
5308 
5309 	while (addr < endaddr) {
5310 		hmeshift = HME_HASH_SHIFT(hashno);
5311 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5312 		hblktag.htag_rehash = hashno;
5313 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5314 
5315 		SFMMU_HASH_LOCK(hmebp);
5316 
5317 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
5318 		if (hmeblkp != NULL) {
5319 			ASSERT(!hmeblkp->hblk_shared);
5320 			/*
5321 			 * We've encountered a shadow hmeblk so skip the range
5322 			 * of the next smaller mapping size.
5323 			 */
5324 			if (hmeblkp->hblk_shw_bit) {
5325 				ASSERT(sfmmup != ksfmmup);
5326 				ASSERT(hashno > 1);
5327 				addr = (caddr_t)P2END((uintptr_t)addr,
5328 				    TTEBYTES(hashno - 1));
5329 			} else {
5330 				addr = sfmmu_hblk_chgprot(sfmmup, hmeblkp,
5331 				    addr, endaddr, &dmr, vprot);
5332 			}
5333 			SFMMU_HASH_UNLOCK(hmebp);
5334 			hashno = 1;
5335 			continue;
5336 		}
5337 		SFMMU_HASH_UNLOCK(hmebp);
5338 
5339 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
5340 			/*
5341 			 * We have traversed the whole list and rehashed
5342 			 * if necessary without finding the address to chgprot.
5343 			 * This is ok so we increment the address by the
5344 			 * smallest hmeblk range for kernel mappings and the
5345 			 * largest hmeblk range, to account for shadow hmeblks,
5346 			 * for user mappings and continue.
5347 			 */
5348 			if (sfmmup == ksfmmup)
5349 				addr = (caddr_t)P2END((uintptr_t)addr,
5350 				    TTEBYTES(1));
5351 			else
5352 				addr = (caddr_t)P2END((uintptr_t)addr,
5353 				    TTEBYTES(hashno));
5354 			hashno = 1;
5355 		} else {
5356 			hashno++;
5357 		}
5358 	}
5359 
5360 	sfmmu_hblks_list_purge(&list, 0);
5361 	DEMAP_RANGE_FLUSH(&dmr);
5362 	cpuset = sfmmup->sfmmu_cpusran;
5363 	xt_sync(cpuset);
5364 }
5365 
5366 /*
5367  * This function chgprots a range of addresses in an hmeblk.  It returns the
5368  * next addres that needs to be chgprot.
5369  * It should be called with the hash lock held.
5370  * XXX It shold be possible to optimize chgprot by not flushing every time but
5371  * on the other hand:
5372  * 1. do one flush crosscall.
5373  * 2. only flush if we are increasing permissions (make sure this will work)
5374  */
5375 static caddr_t
5376 sfmmu_hblk_chgprot(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5377 	caddr_t endaddr, demap_range_t *dmrp, uint_t vprot)
5378 {
5379 	uint_t pprot;
5380 	tte_t tte, ttemod;
5381 	struct sf_hment *sfhmep;
5382 	uint_t tteflags;
5383 	int ttesz;
5384 	struct page *pp = NULL;
5385 	kmutex_t *pml, *pmtx;
5386 	int ret;
5387 	int use_demap_range;
5388 #if defined(SF_ERRATA_57)
5389 	int check_exec;
5390 #endif
5391 
5392 	ASSERT(in_hblk_range(hmeblkp, addr));
5393 	ASSERT(hmeblkp->hblk_shw_bit == 0);
5394 	ASSERT(!hmeblkp->hblk_shared);
5395 
5396 #ifdef DEBUG
5397 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5398 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5399 		panic("sfmmu_hblk_chgprot: partial chgprot of large page");
5400 	}
5401 #endif /* DEBUG */
5402 
5403 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5404 	ttesz = get_hblk_ttesz(hmeblkp);
5405 
5406 	pprot = sfmmu_vtop_prot(vprot, &tteflags);
5407 #if defined(SF_ERRATA_57)
5408 	check_exec = (sfmmup != ksfmmup) &&
5409 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
5410 	    ((vprot & PROT_EXEC) == PROT_EXEC);
5411 #endif
5412 	HBLKTOHME(sfhmep, hmeblkp, addr);
5413 
5414 	/*
5415 	 * Flush the current demap region if addresses have been
5416 	 * skipped or the page size doesn't match.
5417 	 */
5418 	use_demap_range = (TTEBYTES(ttesz) == MMU_PAGESIZE);
5419 	if (use_demap_range) {
5420 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5421 	} else {
5422 		DEMAP_RANGE_FLUSH(dmrp);
5423 	}
5424 
5425 	while (addr < endaddr) {
5426 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5427 		if (TTE_IS_VALID(&tte)) {
5428 			if (TTE_GET_LOFLAGS(&tte, tteflags) == pprot) {
5429 				/*
5430 				 * if the new protection is the same as old
5431 				 * continue
5432 				 */
5433 				goto next_addr;
5434 			}
5435 			pml = NULL;
5436 			pp = sfhmep->hme_page;
5437 			if (pp) {
5438 				pml = sfmmu_mlist_enter(pp);
5439 			}
5440 			if (pp != sfhmep->hme_page) {
5441 				/*
5442 				 * tte most have been unloaded
5443 				 * underneath us.  Recheck
5444 				 */
5445 				ASSERT(pml);
5446 				sfmmu_mlist_exit(pml);
5447 				continue;
5448 			}
5449 
5450 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5451 
5452 			ttemod = tte;
5453 			TTE_SET_LOFLAGS(&ttemod, tteflags, pprot);
5454 #if defined(SF_ERRATA_57)
5455 			if (check_exec && addr < errata57_limit)
5456 				ttemod.tte_exec_perm = 0;
5457 #endif
5458 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5459 			    &sfhmep->hme_tte);
5460 
5461 			if (ret < 0) {
5462 				/* tte changed underneath us */
5463 				if (pml) {
5464 					sfmmu_mlist_exit(pml);
5465 				}
5466 				continue;
5467 			}
5468 
5469 			if (tteflags & TTE_HWWR_INT) {
5470 				/*
5471 				 * need to sync if we are clearing modify bit.
5472 				 */
5473 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
5474 			}
5475 
5476 			if (pp && PP_ISRO(pp)) {
5477 				if (pprot & TTE_WRPRM_INT) {
5478 					pmtx = sfmmu_page_enter(pp);
5479 					PP_CLRRO(pp);
5480 					sfmmu_page_exit(pmtx);
5481 				}
5482 			}
5483 
5484 			if (ret > 0 && use_demap_range) {
5485 				DEMAP_RANGE_MARKPG(dmrp, addr);
5486 			} else if (ret > 0) {
5487 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
5488 			}
5489 
5490 			if (pml) {
5491 				sfmmu_mlist_exit(pml);
5492 			}
5493 		}
5494 next_addr:
5495 		addr += TTEBYTES(ttesz);
5496 		sfhmep++;
5497 		DEMAP_RANGE_NEXTPG(dmrp);
5498 	}
5499 	return (addr);
5500 }
5501 
5502 /*
5503  * This routine is deprecated and should only be used by hat_chgprot.
5504  * The correct routine is sfmmu_vtop_attr.
5505  * This routine converts virtual page protections to physical ones.  It will
5506  * update the tteflags field with the tte mask corresponding to the protections
5507  * affected and it returns the new protections.  It will also clear the modify
5508  * bit if we are taking away write permission.  This is necessary since the
5509  * modify bit is the hardware permission bit and we need to clear it in order
5510  * to detect write faults.
5511  * It accepts the following special protections:
5512  * ~PROT_WRITE = remove write permissions.
5513  * ~PROT_USER = remove user permissions.
5514  */
5515 static uint_t
5516 sfmmu_vtop_prot(uint_t vprot, uint_t *tteflagsp)
5517 {
5518 	if (vprot == (uint_t)~PROT_WRITE) {
5519 		*tteflagsp = TTE_WRPRM_INT | TTE_HWWR_INT;
5520 		return (0);		/* will cause wrprm to be cleared */
5521 	}
5522 	if (vprot == (uint_t)~PROT_USER) {
5523 		*tteflagsp = TTE_PRIV_INT;
5524 		return (0);		/* will cause privprm to be cleared */
5525 	}
5526 	if ((vprot == 0) || (vprot == PROT_USER) ||
5527 	    ((vprot & PROT_ALL) != vprot)) {
5528 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5529 	}
5530 
5531 	switch (vprot) {
5532 	case (PROT_READ):
5533 	case (PROT_EXEC):
5534 	case (PROT_EXEC | PROT_READ):
5535 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5536 		return (TTE_PRIV_INT); 		/* set prv and clr wrt */
5537 	case (PROT_WRITE):
5538 	case (PROT_WRITE | PROT_READ):
5539 	case (PROT_EXEC | PROT_WRITE):
5540 	case (PROT_EXEC | PROT_WRITE | PROT_READ):
5541 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5542 		return (TTE_PRIV_INT | TTE_WRPRM_INT); 	/* set prv and wrt */
5543 	case (PROT_USER | PROT_READ):
5544 	case (PROT_USER | PROT_EXEC):
5545 	case (PROT_USER | PROT_EXEC | PROT_READ):
5546 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5547 		return (0); 			/* clr prv and wrt */
5548 	case (PROT_USER | PROT_WRITE):
5549 	case (PROT_USER | PROT_WRITE | PROT_READ):
5550 	case (PROT_USER | PROT_EXEC | PROT_WRITE):
5551 	case (PROT_USER | PROT_EXEC | PROT_WRITE | PROT_READ):
5552 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5553 		return (TTE_WRPRM_INT); 	/* clr prv and set wrt */
5554 	default:
5555 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5556 	}
5557 	return (0);
5558 }
5559 
5560 /*
5561  * Alternate unload for very large virtual ranges. With a true 64 bit VA,
5562  * the normal algorithm would take too long for a very large VA range with
5563  * few real mappings. This routine just walks thru all HMEs in the global
5564  * hash table to find and remove mappings.
5565  */
5566 static void
5567 hat_unload_large_virtual(
5568 	struct hat		*sfmmup,
5569 	caddr_t			startaddr,
5570 	size_t			len,
5571 	uint_t			flags,
5572 	hat_callback_t		*callback)
5573 {
5574 	struct hmehash_bucket *hmebp;
5575 	struct hme_blk *hmeblkp;
5576 	struct hme_blk *pr_hblk = NULL;
5577 	struct hme_blk *nx_hblk;
5578 	struct hme_blk *list = NULL;
5579 	int i;
5580 	demap_range_t dmr, *dmrp;
5581 	cpuset_t cpuset;
5582 	caddr_t	endaddr = startaddr + len;
5583 	caddr_t	sa;
5584 	caddr_t	ea;
5585 	caddr_t	cb_sa[MAX_CB_ADDR];
5586 	caddr_t	cb_ea[MAX_CB_ADDR];
5587 	int	addr_cnt = 0;
5588 	int	a = 0;
5589 
5590 	if (sfmmup->sfmmu_free) {
5591 		dmrp = NULL;
5592 	} else {
5593 		dmrp = &dmr;
5594 		DEMAP_RANGE_INIT(sfmmup, dmrp);
5595 	}
5596 
5597 	/*
5598 	 * Loop through all the hash buckets of HME blocks looking for matches.
5599 	 */
5600 	for (i = 0; i <= UHMEHASH_SZ; i++) {
5601 		hmebp = &uhme_hash[i];
5602 		SFMMU_HASH_LOCK(hmebp);
5603 		hmeblkp = hmebp->hmeblkp;
5604 		pr_hblk = NULL;
5605 		while (hmeblkp) {
5606 			nx_hblk = hmeblkp->hblk_next;
5607 
5608 			/*
5609 			 * skip if not this context, if a shadow block or
5610 			 * if the mapping is not in the requested range
5611 			 */
5612 			if (hmeblkp->hblk_tag.htag_id != sfmmup ||
5613 			    hmeblkp->hblk_shw_bit ||
5614 			    (sa = (caddr_t)get_hblk_base(hmeblkp)) >= endaddr ||
5615 			    (ea = get_hblk_endaddr(hmeblkp)) <= startaddr) {
5616 				pr_hblk = hmeblkp;
5617 				goto next_block;
5618 			}
5619 
5620 			ASSERT(!hmeblkp->hblk_shared);
5621 			/*
5622 			 * unload if there are any current valid mappings
5623 			 */
5624 			if (hmeblkp->hblk_vcnt != 0 ||
5625 			    hmeblkp->hblk_hmecnt != 0)
5626 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
5627 				    sa, ea, dmrp, flags);
5628 
5629 			/*
5630 			 * on unmap we also release the HME block itself, once
5631 			 * all mappings are gone.
5632 			 */
5633 			if ((flags & HAT_UNLOAD_UNMAP) != 0 &&
5634 			    !hmeblkp->hblk_vcnt &&
5635 			    !hmeblkp->hblk_hmecnt) {
5636 				ASSERT(!hmeblkp->hblk_lckcnt);
5637 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
5638 				    &list, 0);
5639 			} else {
5640 				pr_hblk = hmeblkp;
5641 			}
5642 
5643 			if (callback == NULL)
5644 				goto next_block;
5645 
5646 			/*
5647 			 * HME blocks may span more than one page, but we may be
5648 			 * unmapping only one page, so check for a smaller range
5649 			 * for the callback
5650 			 */
5651 			if (sa < startaddr)
5652 				sa = startaddr;
5653 			if (--ea > endaddr)
5654 				ea = endaddr - 1;
5655 
5656 			cb_sa[addr_cnt] = sa;
5657 			cb_ea[addr_cnt] = ea;
5658 			if (++addr_cnt == MAX_CB_ADDR) {
5659 				if (dmrp != NULL) {
5660 					DEMAP_RANGE_FLUSH(dmrp);
5661 					cpuset = sfmmup->sfmmu_cpusran;
5662 					xt_sync(cpuset);
5663 				}
5664 
5665 				for (a = 0; a < MAX_CB_ADDR; ++a) {
5666 					callback->hcb_start_addr = cb_sa[a];
5667 					callback->hcb_end_addr = cb_ea[a];
5668 					callback->hcb_function(callback);
5669 				}
5670 				addr_cnt = 0;
5671 			}
5672 
5673 next_block:
5674 			hmeblkp = nx_hblk;
5675 		}
5676 		SFMMU_HASH_UNLOCK(hmebp);
5677 	}
5678 
5679 	sfmmu_hblks_list_purge(&list, 0);
5680 	if (dmrp != NULL) {
5681 		DEMAP_RANGE_FLUSH(dmrp);
5682 		cpuset = sfmmup->sfmmu_cpusran;
5683 		xt_sync(cpuset);
5684 	}
5685 
5686 	for (a = 0; a < addr_cnt; ++a) {
5687 		callback->hcb_start_addr = cb_sa[a];
5688 		callback->hcb_end_addr = cb_ea[a];
5689 		callback->hcb_function(callback);
5690 	}
5691 
5692 	/*
5693 	 * Check TSB and TLB page sizes if the process isn't exiting.
5694 	 */
5695 	if (!sfmmup->sfmmu_free)
5696 		sfmmu_check_page_sizes(sfmmup, 0);
5697 }
5698 
5699 /*
5700  * Unload all the mappings in the range [addr..addr+len). addr and len must
5701  * be MMU_PAGESIZE aligned.
5702  */
5703 
5704 extern struct seg *segkmap;
5705 #define	ISSEGKMAP(sfmmup, addr) (sfmmup == ksfmmup && \
5706 segkmap->s_base <= (addr) && (addr) < (segkmap->s_base + segkmap->s_size))
5707 
5708 
5709 void
5710 hat_unload_callback(
5711 	struct hat *sfmmup,
5712 	caddr_t addr,
5713 	size_t len,
5714 	uint_t flags,
5715 	hat_callback_t *callback)
5716 {
5717 	struct hmehash_bucket *hmebp;
5718 	hmeblk_tag hblktag;
5719 	int hmeshift, hashno, iskernel;
5720 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
5721 	caddr_t endaddr;
5722 	cpuset_t cpuset;
5723 	int addr_count = 0;
5724 	int a;
5725 	caddr_t cb_start_addr[MAX_CB_ADDR];
5726 	caddr_t cb_end_addr[MAX_CB_ADDR];
5727 	int issegkmap = ISSEGKMAP(sfmmup, addr);
5728 	demap_range_t dmr, *dmrp;
5729 
5730 	if (sfmmup->sfmmu_xhat_provider) {
5731 		XHAT_UNLOAD_CALLBACK(sfmmup, addr, len, flags, callback);
5732 		return;
5733 	} else {
5734 		/*
5735 		 * This must be a CPU HAT. If the address space has
5736 		 * XHATs attached, unload the mappings for all of them,
5737 		 * just in case
5738 		 */
5739 		ASSERT(sfmmup->sfmmu_as != NULL);
5740 		if (sfmmup->sfmmu_as->a_xhat != NULL)
5741 			xhat_unload_callback_all(sfmmup->sfmmu_as, addr,
5742 			    len, flags, callback);
5743 	}
5744 
5745 	ASSERT((sfmmup == ksfmmup) || (flags & HAT_UNLOAD_OTHER) || \
5746 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
5747 
5748 	ASSERT(sfmmup != NULL);
5749 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5750 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
5751 
5752 	/*
5753 	 * Probing through a large VA range (say 63 bits) will be slow, even
5754 	 * at 4 Meg steps between the probes. So, when the virtual address range
5755 	 * is very large, search the HME entries for what to unload.
5756 	 *
5757 	 *	len >> TTE_PAGE_SHIFT(TTE4M) is the # of 4Meg probes we'd need
5758 	 *
5759 	 *	UHMEHASH_SZ is number of hash buckets to examine
5760 	 *
5761 	 */
5762 	if (sfmmup != KHATID && (len >> TTE_PAGE_SHIFT(TTE4M)) > UHMEHASH_SZ) {
5763 		hat_unload_large_virtual(sfmmup, addr, len, flags, callback);
5764 		return;
5765 	}
5766 
5767 	CPUSET_ZERO(cpuset);
5768 
5769 	/*
5770 	 * If the process is exiting, we can save a lot of fuss since
5771 	 * we'll flush the TLB when we free the ctx anyway.
5772 	 */
5773 	if (sfmmup->sfmmu_free)
5774 		dmrp = NULL;
5775 	else
5776 		dmrp = &dmr;
5777 
5778 	DEMAP_RANGE_INIT(sfmmup, dmrp);
5779 	endaddr = addr + len;
5780 	hblktag.htag_id = sfmmup;
5781 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5782 
5783 	/*
5784 	 * It is likely for the vm to call unload over a wide range of
5785 	 * addresses that are actually very sparsely populated by
5786 	 * translations.  In order to speed this up the sfmmu hat supports
5787 	 * the concept of shadow hmeblks. Dummy large page hmeblks that
5788 	 * correspond to actual small translations are allocated at tteload
5789 	 * time and are referred to as shadow hmeblks.  Now, during unload
5790 	 * time, we first check if we have a shadow hmeblk for that
5791 	 * translation.  The absence of one means the corresponding address
5792 	 * range is empty and can be skipped.
5793 	 *
5794 	 * The kernel is an exception to above statement and that is why
5795 	 * we don't use shadow hmeblks and hash starting from the smallest
5796 	 * page size.
5797 	 */
5798 	if (sfmmup == KHATID) {
5799 		iskernel = 1;
5800 		hashno = TTE64K;
5801 	} else {
5802 		iskernel = 0;
5803 		if (mmu_page_sizes == max_mmu_page_sizes) {
5804 			hashno = TTE256M;
5805 		} else {
5806 			hashno = TTE4M;
5807 		}
5808 	}
5809 	while (addr < endaddr) {
5810 		hmeshift = HME_HASH_SHIFT(hashno);
5811 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5812 		hblktag.htag_rehash = hashno;
5813 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5814 
5815 		SFMMU_HASH_LOCK(hmebp);
5816 
5817 		HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
5818 		if (hmeblkp == NULL) {
5819 			/*
5820 			 * didn't find an hmeblk. skip the appropiate
5821 			 * address range.
5822 			 */
5823 			SFMMU_HASH_UNLOCK(hmebp);
5824 			if (iskernel) {
5825 				if (hashno < mmu_hashcnt) {
5826 					hashno++;
5827 					continue;
5828 				} else {
5829 					hashno = TTE64K;
5830 					addr = (caddr_t)roundup((uintptr_t)addr
5831 					    + 1, MMU_PAGESIZE64K);
5832 					continue;
5833 				}
5834 			}
5835 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5836 			    (1 << hmeshift));
5837 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5838 				ASSERT(hashno == TTE64K);
5839 				continue;
5840 			}
5841 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5842 				hashno = TTE512K;
5843 				continue;
5844 			}
5845 			if (mmu_page_sizes == max_mmu_page_sizes) {
5846 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5847 					hashno = TTE4M;
5848 					continue;
5849 				}
5850 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5851 					hashno = TTE32M;
5852 					continue;
5853 				}
5854 				hashno = TTE256M;
5855 				continue;
5856 			} else {
5857 				hashno = TTE4M;
5858 				continue;
5859 			}
5860 		}
5861 		ASSERT(hmeblkp);
5862 		ASSERT(!hmeblkp->hblk_shared);
5863 		if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5864 			/*
5865 			 * If the valid count is zero we can skip the range
5866 			 * mapped by this hmeblk.
5867 			 * We free hblks in the case of HAT_UNMAP.  HAT_UNMAP
5868 			 * is used by segment drivers as a hint
5869 			 * that the mapping resource won't be used any longer.
5870 			 * The best example of this is during exit().
5871 			 */
5872 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5873 			    get_hblk_span(hmeblkp));
5874 			if ((flags & HAT_UNLOAD_UNMAP) ||
5875 			    (iskernel && !issegkmap)) {
5876 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
5877 				    &list, 0);
5878 			}
5879 			SFMMU_HASH_UNLOCK(hmebp);
5880 
5881 			if (iskernel) {
5882 				hashno = TTE64K;
5883 				continue;
5884 			}
5885 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5886 				ASSERT(hashno == TTE64K);
5887 				continue;
5888 			}
5889 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5890 				hashno = TTE512K;
5891 				continue;
5892 			}
5893 			if (mmu_page_sizes == max_mmu_page_sizes) {
5894 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5895 					hashno = TTE4M;
5896 					continue;
5897 				}
5898 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5899 					hashno = TTE32M;
5900 					continue;
5901 				}
5902 				hashno = TTE256M;
5903 				continue;
5904 			} else {
5905 				hashno = TTE4M;
5906 				continue;
5907 			}
5908 		}
5909 		if (hmeblkp->hblk_shw_bit) {
5910 			/*
5911 			 * If we encounter a shadow hmeblk we know there is
5912 			 * smaller sized hmeblks mapping the same address space.
5913 			 * Decrement the hash size and rehash.
5914 			 */
5915 			ASSERT(sfmmup != KHATID);
5916 			hashno--;
5917 			SFMMU_HASH_UNLOCK(hmebp);
5918 			continue;
5919 		}
5920 
5921 		/*
5922 		 * track callback address ranges.
5923 		 * only start a new range when it's not contiguous
5924 		 */
5925 		if (callback != NULL) {
5926 			if (addr_count > 0 &&
5927 			    addr == cb_end_addr[addr_count - 1])
5928 				--addr_count;
5929 			else
5930 				cb_start_addr[addr_count] = addr;
5931 		}
5932 
5933 		addr = sfmmu_hblk_unload(sfmmup, hmeblkp, addr, endaddr,
5934 		    dmrp, flags);
5935 
5936 		if (callback != NULL)
5937 			cb_end_addr[addr_count++] = addr;
5938 
5939 		if (((flags & HAT_UNLOAD_UNMAP) || (iskernel && !issegkmap)) &&
5940 		    !hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5941 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk, &list, 0);
5942 		}
5943 		SFMMU_HASH_UNLOCK(hmebp);
5944 
5945 		/*
5946 		 * Notify our caller as to exactly which pages
5947 		 * have been unloaded. We do these in clumps,
5948 		 * to minimize the number of xt_sync()s that need to occur.
5949 		 */
5950 		if (callback != NULL && addr_count == MAX_CB_ADDR) {
5951 			DEMAP_RANGE_FLUSH(dmrp);
5952 			if (dmrp != NULL) {
5953 				cpuset = sfmmup->sfmmu_cpusran;
5954 				xt_sync(cpuset);
5955 			}
5956 
5957 			for (a = 0; a < MAX_CB_ADDR; ++a) {
5958 				callback->hcb_start_addr = cb_start_addr[a];
5959 				callback->hcb_end_addr = cb_end_addr[a];
5960 				callback->hcb_function(callback);
5961 			}
5962 			addr_count = 0;
5963 		}
5964 		if (iskernel) {
5965 			hashno = TTE64K;
5966 			continue;
5967 		}
5968 		if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5969 			ASSERT(hashno == TTE64K);
5970 			continue;
5971 		}
5972 		if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5973 			hashno = TTE512K;
5974 			continue;
5975 		}
5976 		if (mmu_page_sizes == max_mmu_page_sizes) {
5977 			if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5978 				hashno = TTE4M;
5979 				continue;
5980 			}
5981 			if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5982 				hashno = TTE32M;
5983 				continue;
5984 			}
5985 			hashno = TTE256M;
5986 		} else {
5987 			hashno = TTE4M;
5988 		}
5989 	}
5990 
5991 	sfmmu_hblks_list_purge(&list, 0);
5992 	DEMAP_RANGE_FLUSH(dmrp);
5993 	if (dmrp != NULL) {
5994 		cpuset = sfmmup->sfmmu_cpusran;
5995 		xt_sync(cpuset);
5996 	}
5997 	if (callback && addr_count != 0) {
5998 		for (a = 0; a < addr_count; ++a) {
5999 			callback->hcb_start_addr = cb_start_addr[a];
6000 			callback->hcb_end_addr = cb_end_addr[a];
6001 			callback->hcb_function(callback);
6002 		}
6003 	}
6004 
6005 	/*
6006 	 * Check TSB and TLB page sizes if the process isn't exiting.
6007 	 */
6008 	if (!sfmmup->sfmmu_free)
6009 		sfmmu_check_page_sizes(sfmmup, 0);
6010 }
6011 
6012 /*
6013  * Unload all the mappings in the range [addr..addr+len). addr and len must
6014  * be MMU_PAGESIZE aligned.
6015  */
6016 void
6017 hat_unload(struct hat *sfmmup, caddr_t addr, size_t len, uint_t flags)
6018 {
6019 	if (sfmmup->sfmmu_xhat_provider) {
6020 		XHAT_UNLOAD(sfmmup, addr, len, flags);
6021 		return;
6022 	}
6023 	hat_unload_callback(sfmmup, addr, len, flags, NULL);
6024 }
6025 
6026 
6027 /*
6028  * Find the largest mapping size for this page.
6029  */
6030 int
6031 fnd_mapping_sz(page_t *pp)
6032 {
6033 	int sz;
6034 	int p_index;
6035 
6036 	p_index = PP_MAPINDEX(pp);
6037 
6038 	sz = 0;
6039 	p_index >>= 1;	/* don't care about 8K bit */
6040 	for (; p_index; p_index >>= 1) {
6041 		sz++;
6042 	}
6043 
6044 	return (sz);
6045 }
6046 
6047 /*
6048  * This function unloads a range of addresses for an hmeblk.
6049  * It returns the next address to be unloaded.
6050  * It should be called with the hash lock held.
6051  */
6052 static caddr_t
6053 sfmmu_hblk_unload(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
6054 	caddr_t endaddr, demap_range_t *dmrp, uint_t flags)
6055 {
6056 	tte_t	tte, ttemod;
6057 	struct	sf_hment *sfhmep;
6058 	int	ttesz;
6059 	long	ttecnt;
6060 	page_t *pp;
6061 	kmutex_t *pml;
6062 	int ret;
6063 	int use_demap_range;
6064 
6065 	ASSERT(in_hblk_range(hmeblkp, addr));
6066 	ASSERT(!hmeblkp->hblk_shw_bit);
6067 	ASSERT(sfmmup != NULL || hmeblkp->hblk_shared);
6068 	ASSERT(sfmmup == NULL || !hmeblkp->hblk_shared);
6069 	ASSERT(dmrp == NULL || !hmeblkp->hblk_shared);
6070 
6071 #ifdef DEBUG
6072 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
6073 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
6074 		panic("sfmmu_hblk_unload: partial unload of large page");
6075 	}
6076 #endif /* DEBUG */
6077 
6078 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
6079 	ttesz = get_hblk_ttesz(hmeblkp);
6080 
6081 	use_demap_range = ((dmrp == NULL) ||
6082 	    (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp)));
6083 
6084 	if (use_demap_range) {
6085 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
6086 	} else {
6087 		DEMAP_RANGE_FLUSH(dmrp);
6088 	}
6089 	ttecnt = 0;
6090 	HBLKTOHME(sfhmep, hmeblkp, addr);
6091 
6092 	while (addr < endaddr) {
6093 		pml = NULL;
6094 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6095 		if (TTE_IS_VALID(&tte)) {
6096 			pp = sfhmep->hme_page;
6097 			if (pp != NULL) {
6098 				pml = sfmmu_mlist_enter(pp);
6099 			}
6100 
6101 			/*
6102 			 * Verify if hme still points to 'pp' now that
6103 			 * we have p_mapping lock.
6104 			 */
6105 			if (sfhmep->hme_page != pp) {
6106 				if (pp != NULL && sfhmep->hme_page != NULL) {
6107 					ASSERT(pml != NULL);
6108 					sfmmu_mlist_exit(pml);
6109 					/* Re-start this iteration. */
6110 					continue;
6111 				}
6112 				ASSERT((pp != NULL) &&
6113 				    (sfhmep->hme_page == NULL));
6114 				goto tte_unloaded;
6115 			}
6116 
6117 			/*
6118 			 * This point on we have both HASH and p_mapping
6119 			 * lock.
6120 			 */
6121 			ASSERT(pp == sfhmep->hme_page);
6122 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
6123 
6124 			/*
6125 			 * We need to loop on modify tte because it is
6126 			 * possible for pagesync to come along and
6127 			 * change the software bits beneath us.
6128 			 *
6129 			 * Page_unload can also invalidate the tte after
6130 			 * we read tte outside of p_mapping lock.
6131 			 */
6132 again:
6133 			ttemod = tte;
6134 
6135 			TTE_SET_INVALID(&ttemod);
6136 			ret = sfmmu_modifytte_try(&tte, &ttemod,
6137 			    &sfhmep->hme_tte);
6138 
6139 			if (ret <= 0) {
6140 				if (TTE_IS_VALID(&tte)) {
6141 					ASSERT(ret < 0);
6142 					goto again;
6143 				}
6144 				if (pp != NULL) {
6145 					panic("sfmmu_hblk_unload: pp = 0x%p "
6146 					    "tte became invalid under mlist"
6147 					    " lock = 0x%p", (void *)pp,
6148 					    (void *)pml);
6149 				}
6150 				continue;
6151 			}
6152 
6153 			if (!(flags & HAT_UNLOAD_NOSYNC)) {
6154 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
6155 			}
6156 
6157 			/*
6158 			 * Ok- we invalidated the tte. Do the rest of the job.
6159 			 */
6160 			ttecnt++;
6161 
6162 			if (flags & HAT_UNLOAD_UNLOCK) {
6163 				ASSERT(hmeblkp->hblk_lckcnt > 0);
6164 				atomic_add_32(&hmeblkp->hblk_lckcnt, -1);
6165 				HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
6166 			}
6167 
6168 			/*
6169 			 * Normally we would need to flush the page
6170 			 * from the virtual cache at this point in
6171 			 * order to prevent a potential cache alias
6172 			 * inconsistency.
6173 			 * The particular scenario we need to worry
6174 			 * about is:
6175 			 * Given:  va1 and va2 are two virtual address
6176 			 * that alias and map the same physical
6177 			 * address.
6178 			 * 1.   mapping exists from va1 to pa and data
6179 			 * has been read into the cache.
6180 			 * 2.   unload va1.
6181 			 * 3.   load va2 and modify data using va2.
6182 			 * 4    unload va2.
6183 			 * 5.   load va1 and reference data.  Unless we
6184 			 * flush the data cache when we unload we will
6185 			 * get stale data.
6186 			 * Fortunately, page coloring eliminates the
6187 			 * above scenario by remembering the color a
6188 			 * physical page was last or is currently
6189 			 * mapped to.  Now, we delay the flush until
6190 			 * the loading of translations.  Only when the
6191 			 * new translation is of a different color
6192 			 * are we forced to flush.
6193 			 */
6194 			if (use_demap_range) {
6195 				/*
6196 				 * Mark this page as needing a demap.
6197 				 */
6198 				DEMAP_RANGE_MARKPG(dmrp, addr);
6199 			} else {
6200 				ASSERT(sfmmup != NULL);
6201 				ASSERT(!hmeblkp->hblk_shared);
6202 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
6203 				    sfmmup->sfmmu_free, 0);
6204 			}
6205 
6206 			if (pp) {
6207 				/*
6208 				 * Remove the hment from the mapping list
6209 				 */
6210 				ASSERT(hmeblkp->hblk_hmecnt > 0);
6211 
6212 				/*
6213 				 * Again, we cannot
6214 				 * ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS);
6215 				 */
6216 				HME_SUB(sfhmep, pp);
6217 				membar_stst();
6218 				atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
6219 			}
6220 
6221 			ASSERT(hmeblkp->hblk_vcnt > 0);
6222 			atomic_add_16(&hmeblkp->hblk_vcnt, -1);
6223 
6224 			ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
6225 			    !hmeblkp->hblk_lckcnt);
6226 
6227 #ifdef VAC
6228 			if (pp && (pp->p_nrm & (P_KPMC | P_KPMS | P_TNC))) {
6229 				if (PP_ISTNC(pp)) {
6230 					/*
6231 					 * If page was temporary
6232 					 * uncached, try to recache
6233 					 * it. Note that HME_SUB() was
6234 					 * called above so p_index and
6235 					 * mlist had been updated.
6236 					 */
6237 					conv_tnc(pp, ttesz);
6238 				} else if (pp->p_mapping == NULL) {
6239 					ASSERT(kpm_enable);
6240 					/*
6241 					 * Page is marked to be in VAC conflict
6242 					 * to an existing kpm mapping and/or is
6243 					 * kpm mapped using only the regular
6244 					 * pagesize.
6245 					 */
6246 					sfmmu_kpm_hme_unload(pp);
6247 				}
6248 			}
6249 #endif	/* VAC */
6250 		} else if ((pp = sfhmep->hme_page) != NULL) {
6251 				/*
6252 				 * TTE is invalid but the hme
6253 				 * still exists. let pageunload
6254 				 * complete its job.
6255 				 */
6256 				ASSERT(pml == NULL);
6257 				pml = sfmmu_mlist_enter(pp);
6258 				if (sfhmep->hme_page != NULL) {
6259 					sfmmu_mlist_exit(pml);
6260 					continue;
6261 				}
6262 				ASSERT(sfhmep->hme_page == NULL);
6263 		} else if (hmeblkp->hblk_hmecnt != 0) {
6264 			/*
6265 			 * pageunload may have not finished decrementing
6266 			 * hblk_vcnt and hblk_hmecnt. Find page_t if any and
6267 			 * wait for pageunload to finish. Rely on pageunload
6268 			 * to decrement hblk_hmecnt after hblk_vcnt.
6269 			 */
6270 			pfn_t pfn = TTE_TO_TTEPFN(&tte);
6271 			ASSERT(pml == NULL);
6272 			if (pf_is_memory(pfn)) {
6273 				pp = page_numtopp_nolock(pfn);
6274 				if (pp != NULL) {
6275 					pml = sfmmu_mlist_enter(pp);
6276 					sfmmu_mlist_exit(pml);
6277 					pml = NULL;
6278 				}
6279 			}
6280 		}
6281 
6282 tte_unloaded:
6283 		/*
6284 		 * At this point, the tte we are looking at
6285 		 * should be unloaded, and hme has been unlinked
6286 		 * from page too. This is important because in
6287 		 * pageunload, it does ttesync() then HME_SUB.
6288 		 * We need to make sure HME_SUB has been completed
6289 		 * so we know ttesync() has been completed. Otherwise,
6290 		 * at exit time, after return from hat layer, VM will
6291 		 * release as structure which hat_setstat() (called
6292 		 * by ttesync()) needs.
6293 		 */
6294 #ifdef DEBUG
6295 		{
6296 			tte_t	dtte;
6297 
6298 			ASSERT(sfhmep->hme_page == NULL);
6299 
6300 			sfmmu_copytte(&sfhmep->hme_tte, &dtte);
6301 			ASSERT(!TTE_IS_VALID(&dtte));
6302 		}
6303 #endif
6304 
6305 		if (pml) {
6306 			sfmmu_mlist_exit(pml);
6307 		}
6308 
6309 		addr += TTEBYTES(ttesz);
6310 		sfhmep++;
6311 		DEMAP_RANGE_NEXTPG(dmrp);
6312 	}
6313 	/*
6314 	 * For shared hmeblks this routine is only called when region is freed
6315 	 * and no longer referenced.  So no need to decrement ttecnt
6316 	 * in the region structure here.
6317 	 */
6318 	if (ttecnt > 0 && sfmmup != NULL) {
6319 		atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -ttecnt);
6320 	}
6321 	return (addr);
6322 }
6323 
6324 /*
6325  * Invalidate a virtual address range for the local CPU.
6326  * For best performance ensure that the va range is completely
6327  * mapped, otherwise the entire TLB will be flushed.
6328  */
6329 void
6330 hat_flush_range(struct hat *sfmmup, caddr_t va, size_t size)
6331 {
6332 	ssize_t sz;
6333 	caddr_t endva = va + size;
6334 
6335 	while (va < endva) {
6336 		sz = hat_getpagesize(sfmmup, va);
6337 		if (sz < 0) {
6338 			vtag_flushall();
6339 			break;
6340 		}
6341 		vtag_flushpage(va, (uint64_t)sfmmup);
6342 		va += sz;
6343 	}
6344 }
6345 
6346 /*
6347  * Synchronize all the mappings in the range [addr..addr+len).
6348  * Can be called with clearflag having two states:
6349  * HAT_SYNC_DONTZERO means just return the rm stats
6350  * HAT_SYNC_ZERORM means zero rm bits in the tte and return the stats
6351  */
6352 void
6353 hat_sync(struct hat *sfmmup, caddr_t addr, size_t len, uint_t clearflag)
6354 {
6355 	struct hmehash_bucket *hmebp;
6356 	hmeblk_tag hblktag;
6357 	int hmeshift, hashno = 1;
6358 	struct hme_blk *hmeblkp, *list = NULL;
6359 	caddr_t endaddr;
6360 	cpuset_t cpuset;
6361 
6362 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
6363 	ASSERT((sfmmup == ksfmmup) ||
6364 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
6365 	ASSERT((len & MMU_PAGEOFFSET) == 0);
6366 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
6367 	    (clearflag == HAT_SYNC_ZERORM));
6368 
6369 	CPUSET_ZERO(cpuset);
6370 
6371 	endaddr = addr + len;
6372 	hblktag.htag_id = sfmmup;
6373 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
6374 
6375 	/*
6376 	 * Spitfire supports 4 page sizes.
6377 	 * Most pages are expected to be of the smallest page
6378 	 * size (8K) and these will not need to be rehashed. 64K
6379 	 * pages also don't need to be rehashed because the an hmeblk
6380 	 * spans 64K of address space. 512K pages might need 1 rehash and
6381 	 * and 4M pages 2 rehashes.
6382 	 */
6383 	while (addr < endaddr) {
6384 		hmeshift = HME_HASH_SHIFT(hashno);
6385 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
6386 		hblktag.htag_rehash = hashno;
6387 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
6388 
6389 		SFMMU_HASH_LOCK(hmebp);
6390 
6391 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
6392 		if (hmeblkp != NULL) {
6393 			ASSERT(!hmeblkp->hblk_shared);
6394 			/*
6395 			 * We've encountered a shadow hmeblk so skip the range
6396 			 * of the next smaller mapping size.
6397 			 */
6398 			if (hmeblkp->hblk_shw_bit) {
6399 				ASSERT(sfmmup != ksfmmup);
6400 				ASSERT(hashno > 1);
6401 				addr = (caddr_t)P2END((uintptr_t)addr,
6402 				    TTEBYTES(hashno - 1));
6403 			} else {
6404 				addr = sfmmu_hblk_sync(sfmmup, hmeblkp,
6405 				    addr, endaddr, clearflag);
6406 			}
6407 			SFMMU_HASH_UNLOCK(hmebp);
6408 			hashno = 1;
6409 			continue;
6410 		}
6411 		SFMMU_HASH_UNLOCK(hmebp);
6412 
6413 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
6414 			/*
6415 			 * We have traversed the whole list and rehashed
6416 			 * if necessary without finding the address to sync.
6417 			 * This is ok so we increment the address by the
6418 			 * smallest hmeblk range for kernel mappings and the
6419 			 * largest hmeblk range, to account for shadow hmeblks,
6420 			 * for user mappings and continue.
6421 			 */
6422 			if (sfmmup == ksfmmup)
6423 				addr = (caddr_t)P2END((uintptr_t)addr,
6424 				    TTEBYTES(1));
6425 			else
6426 				addr = (caddr_t)P2END((uintptr_t)addr,
6427 				    TTEBYTES(hashno));
6428 			hashno = 1;
6429 		} else {
6430 			hashno++;
6431 		}
6432 	}
6433 	sfmmu_hblks_list_purge(&list, 0);
6434 	cpuset = sfmmup->sfmmu_cpusran;
6435 	xt_sync(cpuset);
6436 }
6437 
6438 static caddr_t
6439 sfmmu_hblk_sync(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
6440 	caddr_t endaddr, int clearflag)
6441 {
6442 	tte_t	tte, ttemod;
6443 	struct sf_hment *sfhmep;
6444 	int ttesz;
6445 	struct page *pp;
6446 	kmutex_t *pml;
6447 	int ret;
6448 
6449 	ASSERT(hmeblkp->hblk_shw_bit == 0);
6450 	ASSERT(!hmeblkp->hblk_shared);
6451 
6452 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
6453 
6454 	ttesz = get_hblk_ttesz(hmeblkp);
6455 	HBLKTOHME(sfhmep, hmeblkp, addr);
6456 
6457 	while (addr < endaddr) {
6458 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6459 		if (TTE_IS_VALID(&tte)) {
6460 			pml = NULL;
6461 			pp = sfhmep->hme_page;
6462 			if (pp) {
6463 				pml = sfmmu_mlist_enter(pp);
6464 			}
6465 			if (pp != sfhmep->hme_page) {
6466 				/*
6467 				 * tte most have been unloaded
6468 				 * underneath us.  Recheck
6469 				 */
6470 				ASSERT(pml);
6471 				sfmmu_mlist_exit(pml);
6472 				continue;
6473 			}
6474 
6475 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
6476 
6477 			if (clearflag == HAT_SYNC_ZERORM) {
6478 				ttemod = tte;
6479 				TTE_CLR_RM(&ttemod);
6480 				ret = sfmmu_modifytte_try(&tte, &ttemod,
6481 				    &sfhmep->hme_tte);
6482 				if (ret < 0) {
6483 					if (pml) {
6484 						sfmmu_mlist_exit(pml);
6485 					}
6486 					continue;
6487 				}
6488 
6489 				if (ret > 0) {
6490 					sfmmu_tlb_demap(addr, sfmmup,
6491 					    hmeblkp, 0, 0);
6492 				}
6493 			}
6494 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
6495 			if (pml) {
6496 				sfmmu_mlist_exit(pml);
6497 			}
6498 		}
6499 		addr += TTEBYTES(ttesz);
6500 		sfhmep++;
6501 	}
6502 	return (addr);
6503 }
6504 
6505 /*
6506  * This function will sync a tte to the page struct and it will
6507  * update the hat stats. Currently it allows us to pass a NULL pp
6508  * and we will simply update the stats.  We may want to change this
6509  * so we only keep stats for pages backed by pp's.
6510  */
6511 static void
6512 sfmmu_ttesync(struct hat *sfmmup, caddr_t addr, tte_t *ttep, page_t *pp)
6513 {
6514 	uint_t rm = 0;
6515 	int   	sz;
6516 	pgcnt_t	npgs;
6517 
6518 	ASSERT(TTE_IS_VALID(ttep));
6519 
6520 	if (TTE_IS_NOSYNC(ttep)) {
6521 		return;
6522 	}
6523 
6524 	if (TTE_IS_REF(ttep))  {
6525 		rm = P_REF;
6526 	}
6527 	if (TTE_IS_MOD(ttep))  {
6528 		rm |= P_MOD;
6529 	}
6530 
6531 	if (rm == 0) {
6532 		return;
6533 	}
6534 
6535 	sz = TTE_CSZ(ttep);
6536 	if (sfmmup != NULL && sfmmup->sfmmu_rmstat) {
6537 		int i;
6538 		caddr_t	vaddr = addr;
6539 
6540 		for (i = 0; i < TTEPAGES(sz); i++, vaddr += MMU_PAGESIZE) {
6541 			hat_setstat(sfmmup->sfmmu_as, vaddr, MMU_PAGESIZE, rm);
6542 		}
6543 
6544 	}
6545 
6546 	/*
6547 	 * XXX I want to use cas to update nrm bits but they
6548 	 * currently belong in common/vm and not in hat where
6549 	 * they should be.
6550 	 * The nrm bits are protected by the same mutex as
6551 	 * the one that protects the page's mapping list.
6552 	 */
6553 	if (!pp)
6554 		return;
6555 	ASSERT(sfmmu_mlist_held(pp));
6556 	/*
6557 	 * If the tte is for a large page, we need to sync all the
6558 	 * pages covered by the tte.
6559 	 */
6560 	if (sz != TTE8K) {
6561 		ASSERT(pp->p_szc != 0);
6562 		pp = PP_GROUPLEADER(pp, sz);
6563 		ASSERT(sfmmu_mlist_held(pp));
6564 	}
6565 
6566 	/* Get number of pages from tte size. */
6567 	npgs = TTEPAGES(sz);
6568 
6569 	do {
6570 		ASSERT(pp);
6571 		ASSERT(sfmmu_mlist_held(pp));
6572 		if (((rm & P_REF) != 0 && !PP_ISREF(pp)) ||
6573 		    ((rm & P_MOD) != 0 && !PP_ISMOD(pp)))
6574 			hat_page_setattr(pp, rm);
6575 
6576 		/*
6577 		 * Are we done? If not, we must have a large mapping.
6578 		 * For large mappings we need to sync the rest of the pages
6579 		 * covered by this tte; goto the next page.
6580 		 */
6581 	} while (--npgs > 0 && (pp = PP_PAGENEXT(pp)));
6582 }
6583 
6584 /*
6585  * Execute pre-callback handler of each pa_hment linked to pp
6586  *
6587  * Inputs:
6588  *   flag: either HAT_PRESUSPEND or HAT_SUSPEND.
6589  *   capture_cpus: pointer to return value (below)
6590  *
6591  * Returns:
6592  *   Propagates the subsystem callback return values back to the caller;
6593  *   returns 0 on success.  If capture_cpus is non-NULL, the value returned
6594  *   is zero if all of the pa_hments are of a type that do not require
6595  *   capturing CPUs prior to suspending the mapping, else it is 1.
6596  */
6597 static int
6598 hat_pageprocess_precallbacks(struct page *pp, uint_t flag, int *capture_cpus)
6599 {
6600 	struct sf_hment	*sfhmep;
6601 	struct pa_hment *pahmep;
6602 	int (*f)(caddr_t, uint_t, uint_t, void *);
6603 	int		ret;
6604 	id_t		id;
6605 	int		locked = 0;
6606 	kmutex_t	*pml;
6607 
6608 	ASSERT(PAGE_EXCL(pp));
6609 	if (!sfmmu_mlist_held(pp)) {
6610 		pml = sfmmu_mlist_enter(pp);
6611 		locked = 1;
6612 	}
6613 
6614 	if (capture_cpus)
6615 		*capture_cpus = 0;
6616 
6617 top:
6618 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6619 		/*
6620 		 * skip sf_hments corresponding to VA<->PA mappings;
6621 		 * for pa_hment's, hme_tte.ll is zero
6622 		 */
6623 		if (!IS_PAHME(sfhmep))
6624 			continue;
6625 
6626 		pahmep = sfhmep->hme_data;
6627 		ASSERT(pahmep != NULL);
6628 
6629 		/*
6630 		 * skip if pre-handler has been called earlier in this loop
6631 		 */
6632 		if (pahmep->flags & flag)
6633 			continue;
6634 
6635 		id = pahmep->cb_id;
6636 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6637 		if (capture_cpus && sfmmu_cb_table[id].capture_cpus != 0)
6638 			*capture_cpus = 1;
6639 		if ((f = sfmmu_cb_table[id].prehandler) == NULL) {
6640 			pahmep->flags |= flag;
6641 			continue;
6642 		}
6643 
6644 		/*
6645 		 * Drop the mapping list lock to avoid locking order issues.
6646 		 */
6647 		if (locked)
6648 			sfmmu_mlist_exit(pml);
6649 
6650 		ret = f(pahmep->addr, pahmep->len, flag, pahmep->pvt);
6651 		if (ret != 0)
6652 			return (ret);	/* caller must do the cleanup */
6653 
6654 		if (locked) {
6655 			pml = sfmmu_mlist_enter(pp);
6656 			pahmep->flags |= flag;
6657 			goto top;
6658 		}
6659 
6660 		pahmep->flags |= flag;
6661 	}
6662 
6663 	if (locked)
6664 		sfmmu_mlist_exit(pml);
6665 
6666 	return (0);
6667 }
6668 
6669 /*
6670  * Execute post-callback handler of each pa_hment linked to pp
6671  *
6672  * Same overall assumptions and restrictions apply as for
6673  * hat_pageprocess_precallbacks().
6674  */
6675 static void
6676 hat_pageprocess_postcallbacks(struct page *pp, uint_t flag)
6677 {
6678 	pfn_t pgpfn = pp->p_pagenum;
6679 	pfn_t pgmask = btop(page_get_pagesize(pp->p_szc)) - 1;
6680 	pfn_t newpfn;
6681 	struct sf_hment *sfhmep;
6682 	struct pa_hment *pahmep;
6683 	int (*f)(caddr_t, uint_t, uint_t, void *, pfn_t);
6684 	id_t	id;
6685 	int	locked = 0;
6686 	kmutex_t *pml;
6687 
6688 	ASSERT(PAGE_EXCL(pp));
6689 	if (!sfmmu_mlist_held(pp)) {
6690 		pml = sfmmu_mlist_enter(pp);
6691 		locked = 1;
6692 	}
6693 
6694 top:
6695 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6696 		/*
6697 		 * skip sf_hments corresponding to VA<->PA mappings;
6698 		 * for pa_hment's, hme_tte.ll is zero
6699 		 */
6700 		if (!IS_PAHME(sfhmep))
6701 			continue;
6702 
6703 		pahmep = sfhmep->hme_data;
6704 		ASSERT(pahmep != NULL);
6705 
6706 		if ((pahmep->flags & flag) == 0)
6707 			continue;
6708 
6709 		pahmep->flags &= ~flag;
6710 
6711 		id = pahmep->cb_id;
6712 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6713 		if ((f = sfmmu_cb_table[id].posthandler) == NULL)
6714 			continue;
6715 
6716 		/*
6717 		 * Convert the base page PFN into the constituent PFN
6718 		 * which is needed by the callback handler.
6719 		 */
6720 		newpfn = pgpfn | (btop((uintptr_t)pahmep->addr) & pgmask);
6721 
6722 		/*
6723 		 * Drop the mapping list lock to avoid locking order issues.
6724 		 */
6725 		if (locked)
6726 			sfmmu_mlist_exit(pml);
6727 
6728 		if (f(pahmep->addr, pahmep->len, flag, pahmep->pvt, newpfn)
6729 		    != 0)
6730 			panic("sfmmu: posthandler failed");
6731 
6732 		if (locked) {
6733 			pml = sfmmu_mlist_enter(pp);
6734 			goto top;
6735 		}
6736 	}
6737 
6738 	if (locked)
6739 		sfmmu_mlist_exit(pml);
6740 }
6741 
6742 /*
6743  * Suspend locked kernel mapping
6744  */
6745 void
6746 hat_pagesuspend(struct page *pp)
6747 {
6748 	struct sf_hment *sfhmep;
6749 	sfmmu_t *sfmmup;
6750 	tte_t tte, ttemod;
6751 	struct hme_blk *hmeblkp;
6752 	caddr_t addr;
6753 	int index, cons;
6754 	cpuset_t cpuset;
6755 
6756 	ASSERT(PAGE_EXCL(pp));
6757 	ASSERT(sfmmu_mlist_held(pp));
6758 
6759 	mutex_enter(&kpr_suspendlock);
6760 
6761 	/*
6762 	 * We're about to suspend a kernel mapping so mark this thread as
6763 	 * non-traceable by DTrace. This prevents us from running into issues
6764 	 * with probe context trying to touch a suspended page
6765 	 * in the relocation codepath itself.
6766 	 */
6767 	curthread->t_flag |= T_DONTDTRACE;
6768 
6769 	index = PP_MAPINDEX(pp);
6770 	cons = TTE8K;
6771 
6772 retry:
6773 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6774 
6775 		if (IS_PAHME(sfhmep))
6776 			continue;
6777 
6778 		if (get_hblk_ttesz(sfmmu_hmetohblk(sfhmep)) != cons)
6779 			continue;
6780 
6781 		/*
6782 		 * Loop until we successfully set the suspend bit in
6783 		 * the TTE.
6784 		 */
6785 again:
6786 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6787 		ASSERT(TTE_IS_VALID(&tte));
6788 
6789 		ttemod = tte;
6790 		TTE_SET_SUSPEND(&ttemod);
6791 		if (sfmmu_modifytte_try(&tte, &ttemod,
6792 		    &sfhmep->hme_tte) < 0)
6793 			goto again;
6794 
6795 		/*
6796 		 * Invalidate TSB entry
6797 		 */
6798 		hmeblkp = sfmmu_hmetohblk(sfhmep);
6799 
6800 		sfmmup = hblktosfmmu(hmeblkp);
6801 		ASSERT(sfmmup == ksfmmup);
6802 		ASSERT(!hmeblkp->hblk_shared);
6803 
6804 		addr = tte_to_vaddr(hmeblkp, tte);
6805 
6806 		/*
6807 		 * No need to make sure that the TSB for this sfmmu is
6808 		 * not being relocated since it is ksfmmup and thus it
6809 		 * will never be relocated.
6810 		 */
6811 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
6812 
6813 		/*
6814 		 * Update xcall stats
6815 		 */
6816 		cpuset = cpu_ready_set;
6817 		CPUSET_DEL(cpuset, CPU->cpu_id);
6818 
6819 		/* LINTED: constant in conditional context */
6820 		SFMMU_XCALL_STATS(ksfmmup);
6821 
6822 		/*
6823 		 * Flush TLB entry on remote CPU's
6824 		 */
6825 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
6826 		    (uint64_t)ksfmmup);
6827 		xt_sync(cpuset);
6828 
6829 		/*
6830 		 * Flush TLB entry on local CPU
6831 		 */
6832 		vtag_flushpage(addr, (uint64_t)ksfmmup);
6833 	}
6834 
6835 	while (index != 0) {
6836 		index = index >> 1;
6837 		if (index != 0)
6838 			cons++;
6839 		if (index & 0x1) {
6840 			pp = PP_GROUPLEADER(pp, cons);
6841 			goto retry;
6842 		}
6843 	}
6844 }
6845 
6846 #ifdef	DEBUG
6847 
6848 #define	N_PRLE	1024
6849 struct prle {
6850 	page_t *targ;
6851 	page_t *repl;
6852 	int status;
6853 	int pausecpus;
6854 	hrtime_t whence;
6855 };
6856 
6857 static struct prle page_relocate_log[N_PRLE];
6858 static int prl_entry;
6859 static kmutex_t prl_mutex;
6860 
6861 #define	PAGE_RELOCATE_LOG(t, r, s, p)					\
6862 	mutex_enter(&prl_mutex);					\
6863 	page_relocate_log[prl_entry].targ = *(t);			\
6864 	page_relocate_log[prl_entry].repl = *(r);			\
6865 	page_relocate_log[prl_entry].status = (s);			\
6866 	page_relocate_log[prl_entry].pausecpus = (p);			\
6867 	page_relocate_log[prl_entry].whence = gethrtime();		\
6868 	prl_entry = (prl_entry == (N_PRLE - 1))? 0 : prl_entry + 1;	\
6869 	mutex_exit(&prl_mutex);
6870 
6871 #else	/* !DEBUG */
6872 #define	PAGE_RELOCATE_LOG(t, r, s, p)
6873 #endif
6874 
6875 /*
6876  * Core Kernel Page Relocation Algorithm
6877  *
6878  * Input:
6879  *
6880  * target : 	constituent pages are SE_EXCL locked.
6881  * replacement:	constituent pages are SE_EXCL locked.
6882  *
6883  * Output:
6884  *
6885  * nrelocp:	number of pages relocated
6886  */
6887 int
6888 hat_page_relocate(page_t **target, page_t **replacement, spgcnt_t *nrelocp)
6889 {
6890 	page_t		*targ, *repl;
6891 	page_t		*tpp, *rpp;
6892 	kmutex_t	*low, *high;
6893 	spgcnt_t	npages, i;
6894 	page_t		*pl = NULL;
6895 	int		old_pil;
6896 	cpuset_t	cpuset;
6897 	int		cap_cpus;
6898 	int		ret;
6899 #ifdef VAC
6900 	int		cflags = 0;
6901 #endif
6902 
6903 	if (hat_kpr_enabled == 0 || !kcage_on || PP_ISNORELOC(*target)) {
6904 		PAGE_RELOCATE_LOG(target, replacement, EAGAIN, -1);
6905 		return (EAGAIN);
6906 	}
6907 
6908 	mutex_enter(&kpr_mutex);
6909 	kreloc_thread = curthread;
6910 
6911 	targ = *target;
6912 	repl = *replacement;
6913 	ASSERT(repl != NULL);
6914 	ASSERT(targ->p_szc == repl->p_szc);
6915 
6916 	npages = page_get_pagecnt(targ->p_szc);
6917 
6918 	/*
6919 	 * unload VA<->PA mappings that are not locked
6920 	 */
6921 	tpp = targ;
6922 	for (i = 0; i < npages; i++) {
6923 		(void) hat_pageunload(tpp, SFMMU_KERNEL_RELOC);
6924 		tpp++;
6925 	}
6926 
6927 	/*
6928 	 * Do "presuspend" callbacks, in a context from which we can still
6929 	 * block as needed. Note that we don't hold the mapping list lock
6930 	 * of "targ" at this point due to potential locking order issues;
6931 	 * we assume that between the hat_pageunload() above and holding
6932 	 * the SE_EXCL lock that the mapping list *cannot* change at this
6933 	 * point.
6934 	 */
6935 	ret = hat_pageprocess_precallbacks(targ, HAT_PRESUSPEND, &cap_cpus);
6936 	if (ret != 0) {
6937 		/*
6938 		 * EIO translates to fatal error, for all others cleanup
6939 		 * and return EAGAIN.
6940 		 */
6941 		ASSERT(ret != EIO);
6942 		hat_pageprocess_postcallbacks(targ, HAT_POSTUNSUSPEND);
6943 		PAGE_RELOCATE_LOG(target, replacement, ret, -1);
6944 		kreloc_thread = NULL;
6945 		mutex_exit(&kpr_mutex);
6946 		return (EAGAIN);
6947 	}
6948 
6949 	/*
6950 	 * acquire p_mapping list lock for both the target and replacement
6951 	 * root pages.
6952 	 *
6953 	 * low and high refer to the need to grab the mlist locks in a
6954 	 * specific order in order to prevent race conditions.  Thus the
6955 	 * lower lock must be grabbed before the higher lock.
6956 	 *
6957 	 * This will block hat_unload's accessing p_mapping list.  Since
6958 	 * we have SE_EXCL lock, hat_memload and hat_pageunload will be
6959 	 * blocked.  Thus, no one else will be accessing the p_mapping list
6960 	 * while we suspend and reload the locked mapping below.
6961 	 */
6962 	tpp = targ;
6963 	rpp = repl;
6964 	sfmmu_mlist_reloc_enter(tpp, rpp, &low, &high);
6965 
6966 	kpreempt_disable();
6967 
6968 	/*
6969 	 * We raise our PIL to 13 so that we don't get captured by
6970 	 * another CPU or pinned by an interrupt thread.  We can't go to
6971 	 * PIL 14 since the nexus driver(s) may need to interrupt at
6972 	 * that level in the case of IOMMU pseudo mappings.
6973 	 */
6974 	cpuset = cpu_ready_set;
6975 	CPUSET_DEL(cpuset, CPU->cpu_id);
6976 	if (!cap_cpus || CPUSET_ISNULL(cpuset)) {
6977 		old_pil = splr(XCALL_PIL);
6978 	} else {
6979 		old_pil = -1;
6980 		xc_attention(cpuset);
6981 	}
6982 	ASSERT(getpil() == XCALL_PIL);
6983 
6984 	/*
6985 	 * Now do suspend callbacks. In the case of an IOMMU mapping
6986 	 * this will suspend all DMA activity to the page while it is
6987 	 * being relocated. Since we are well above LOCK_LEVEL and CPUs
6988 	 * may be captured at this point we should have acquired any needed
6989 	 * locks in the presuspend callback.
6990 	 */
6991 	ret = hat_pageprocess_precallbacks(targ, HAT_SUSPEND, NULL);
6992 	if (ret != 0) {
6993 		repl = targ;
6994 		goto suspend_fail;
6995 	}
6996 
6997 	/*
6998 	 * Raise the PIL yet again, this time to block all high-level
6999 	 * interrupts on this CPU. This is necessary to prevent an
7000 	 * interrupt routine from pinning the thread which holds the
7001 	 * mapping suspended and then touching the suspended page.
7002 	 *
7003 	 * Once the page is suspended we also need to be careful to
7004 	 * avoid calling any functions which touch any seg_kmem memory
7005 	 * since that memory may be backed by the very page we are
7006 	 * relocating in here!
7007 	 */
7008 	hat_pagesuspend(targ);
7009 
7010 	/*
7011 	 * Now that we are confident everybody has stopped using this page,
7012 	 * copy the page contents.  Note we use a physical copy to prevent
7013 	 * locking issues and to avoid fpRAS because we can't handle it in
7014 	 * this context.
7015 	 */
7016 	for (i = 0; i < npages; i++, tpp++, rpp++) {
7017 #ifdef VAC
7018 		/*
7019 		 * If the replacement has a different vcolor than
7020 		 * the one being replacd, we need to handle VAC
7021 		 * consistency for it just as we were setting up
7022 		 * a new mapping to it.
7023 		 */
7024 		if ((PP_GET_VCOLOR(rpp) != NO_VCOLOR) &&
7025 		    (tpp->p_vcolor != rpp->p_vcolor) &&
7026 		    !CacheColor_IsFlushed(cflags, PP_GET_VCOLOR(rpp))) {
7027 			CacheColor_SetFlushed(cflags, PP_GET_VCOLOR(rpp));
7028 			sfmmu_cache_flushcolor(PP_GET_VCOLOR(rpp),
7029 			    rpp->p_pagenum);
7030 		}
7031 #endif
7032 		/*
7033 		 * Copy the contents of the page.
7034 		 */
7035 		ppcopy_kernel(tpp, rpp);
7036 	}
7037 
7038 	tpp = targ;
7039 	rpp = repl;
7040 	for (i = 0; i < npages; i++, tpp++, rpp++) {
7041 		/*
7042 		 * Copy attributes.  VAC consistency was handled above,
7043 		 * if required.
7044 		 */
7045 		rpp->p_nrm = tpp->p_nrm;
7046 		tpp->p_nrm = 0;
7047 		rpp->p_index = tpp->p_index;
7048 		tpp->p_index = 0;
7049 #ifdef VAC
7050 		rpp->p_vcolor = tpp->p_vcolor;
7051 #endif
7052 	}
7053 
7054 	/*
7055 	 * First, unsuspend the page, if we set the suspend bit, and transfer
7056 	 * the mapping list from the target page to the replacement page.
7057 	 * Next process postcallbacks; since pa_hment's are linked only to the
7058 	 * p_mapping list of root page, we don't iterate over the constituent
7059 	 * pages.
7060 	 */
7061 	hat_pagereload(targ, repl);
7062 
7063 suspend_fail:
7064 	hat_pageprocess_postcallbacks(repl, HAT_UNSUSPEND);
7065 
7066 	/*
7067 	 * Now lower our PIL and release any captured CPUs since we
7068 	 * are out of the "danger zone".  After this it will again be
7069 	 * safe to acquire adaptive mutex locks, or to drop them...
7070 	 */
7071 	if (old_pil != -1) {
7072 		splx(old_pil);
7073 	} else {
7074 		xc_dismissed(cpuset);
7075 	}
7076 
7077 	kpreempt_enable();
7078 
7079 	sfmmu_mlist_reloc_exit(low, high);
7080 
7081 	/*
7082 	 * Postsuspend callbacks should drop any locks held across
7083 	 * the suspend callbacks.  As before, we don't hold the mapping
7084 	 * list lock at this point.. our assumption is that the mapping
7085 	 * list still can't change due to our holding SE_EXCL lock and
7086 	 * there being no unlocked mappings left. Hence the restriction
7087 	 * on calling context to hat_delete_callback()
7088 	 */
7089 	hat_pageprocess_postcallbacks(repl, HAT_POSTUNSUSPEND);
7090 	if (ret != 0) {
7091 		/*
7092 		 * The second presuspend call failed: we got here through
7093 		 * the suspend_fail label above.
7094 		 */
7095 		ASSERT(ret != EIO);
7096 		PAGE_RELOCATE_LOG(target, replacement, ret, cap_cpus);
7097 		kreloc_thread = NULL;
7098 		mutex_exit(&kpr_mutex);
7099 		return (EAGAIN);
7100 	}
7101 
7102 	/*
7103 	 * Now that we're out of the performance critical section we can
7104 	 * take care of updating the hash table, since we still
7105 	 * hold all the pages locked SE_EXCL at this point we
7106 	 * needn't worry about things changing out from under us.
7107 	 */
7108 	tpp = targ;
7109 	rpp = repl;
7110 	for (i = 0; i < npages; i++, tpp++, rpp++) {
7111 
7112 		/*
7113 		 * replace targ with replacement in page_hash table
7114 		 */
7115 		targ = tpp;
7116 		page_relocate_hash(rpp, targ);
7117 
7118 		/*
7119 		 * concatenate target; caller of platform_page_relocate()
7120 		 * expects target to be concatenated after returning.
7121 		 */
7122 		ASSERT(targ->p_next == targ);
7123 		ASSERT(targ->p_prev == targ);
7124 		page_list_concat(&pl, &targ);
7125 	}
7126 
7127 	ASSERT(*target == pl);
7128 	*nrelocp = npages;
7129 	PAGE_RELOCATE_LOG(target, replacement, 0, cap_cpus);
7130 	kreloc_thread = NULL;
7131 	mutex_exit(&kpr_mutex);
7132 	return (0);
7133 }
7134 
7135 /*
7136  * Called when stray pa_hments are found attached to a page which is
7137  * being freed.  Notify the subsystem which attached the pa_hment of
7138  * the error if it registered a suitable handler, else panic.
7139  */
7140 static void
7141 sfmmu_pahment_leaked(struct pa_hment *pahmep)
7142 {
7143 	id_t cb_id = pahmep->cb_id;
7144 
7145 	ASSERT(cb_id >= (id_t)0 && cb_id < sfmmu_cb_nextid);
7146 	if (sfmmu_cb_table[cb_id].errhandler != NULL) {
7147 		if (sfmmu_cb_table[cb_id].errhandler(pahmep->addr, pahmep->len,
7148 		    HAT_CB_ERR_LEAKED, pahmep->pvt) == 0)
7149 			return;		/* non-fatal */
7150 	}
7151 	panic("pa_hment leaked: 0x%p", (void *)pahmep);
7152 }
7153 
7154 /*
7155  * Remove all mappings to page 'pp'.
7156  */
7157 int
7158 hat_pageunload(struct page *pp, uint_t forceflag)
7159 {
7160 	struct page *origpp = pp;
7161 	struct sf_hment *sfhme, *tmphme;
7162 	struct hme_blk *hmeblkp;
7163 	kmutex_t *pml;
7164 #ifdef VAC
7165 	kmutex_t *pmtx;
7166 #endif
7167 	cpuset_t cpuset, tset;
7168 	int index, cons;
7169 	int xhme_blks;
7170 	int pa_hments;
7171 
7172 	ASSERT(PAGE_EXCL(pp));
7173 
7174 retry_xhat:
7175 	tmphme = NULL;
7176 	xhme_blks = 0;
7177 	pa_hments = 0;
7178 	CPUSET_ZERO(cpuset);
7179 
7180 	pml = sfmmu_mlist_enter(pp);
7181 
7182 #ifdef VAC
7183 	if (pp->p_kpmref)
7184 		sfmmu_kpm_pageunload(pp);
7185 	ASSERT(!PP_ISMAPPED_KPM(pp));
7186 #endif
7187 	/*
7188 	 * Clear vpm reference. Since the page is exclusively locked
7189 	 * vpm cannot be referencing it.
7190 	 */
7191 	if (vpm_enable) {
7192 		pp->p_vpmref = 0;
7193 	}
7194 
7195 	index = PP_MAPINDEX(pp);
7196 	cons = TTE8K;
7197 retry:
7198 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7199 		tmphme = sfhme->hme_next;
7200 
7201 		if (IS_PAHME(sfhme)) {
7202 			ASSERT(sfhme->hme_data != NULL);
7203 			pa_hments++;
7204 			continue;
7205 		}
7206 
7207 		hmeblkp = sfmmu_hmetohblk(sfhme);
7208 		if (hmeblkp->hblk_xhat_bit) {
7209 			struct xhat_hme_blk *xblk =
7210 			    (struct xhat_hme_blk *)hmeblkp;
7211 
7212 			(void) XHAT_PAGEUNLOAD(xblk->xhat_hme_blk_hat,
7213 			    pp, forceflag, XBLK2PROVBLK(xblk));
7214 
7215 			xhme_blks = 1;
7216 			continue;
7217 		}
7218 
7219 		/*
7220 		 * If there are kernel mappings don't unload them, they will
7221 		 * be suspended.
7222 		 */
7223 		if (forceflag == SFMMU_KERNEL_RELOC && hmeblkp->hblk_lckcnt &&
7224 		    hmeblkp->hblk_tag.htag_id == ksfmmup)
7225 			continue;
7226 
7227 		tset = sfmmu_pageunload(pp, sfhme, cons);
7228 		CPUSET_OR(cpuset, tset);
7229 	}
7230 
7231 	while (index != 0) {
7232 		index = index >> 1;
7233 		if (index != 0)
7234 			cons++;
7235 		if (index & 0x1) {
7236 			/* Go to leading page */
7237 			pp = PP_GROUPLEADER(pp, cons);
7238 			ASSERT(sfmmu_mlist_held(pp));
7239 			goto retry;
7240 		}
7241 	}
7242 
7243 	/*
7244 	 * cpuset may be empty if the page was only mapped by segkpm,
7245 	 * in which case we won't actually cross-trap.
7246 	 */
7247 	xt_sync(cpuset);
7248 
7249 	/*
7250 	 * The page should have no mappings at this point, unless
7251 	 * we were called from hat_page_relocate() in which case we
7252 	 * leave the locked mappings which will be suspended later.
7253 	 */
7254 	ASSERT(!PP_ISMAPPED(origpp) || xhme_blks || pa_hments ||
7255 	    (forceflag == SFMMU_KERNEL_RELOC));
7256 
7257 #ifdef VAC
7258 	if (PP_ISTNC(pp)) {
7259 		if (cons == TTE8K) {
7260 			pmtx = sfmmu_page_enter(pp);
7261 			PP_CLRTNC(pp);
7262 			sfmmu_page_exit(pmtx);
7263 		} else {
7264 			conv_tnc(pp, cons);
7265 		}
7266 	}
7267 #endif	/* VAC */
7268 
7269 	if (pa_hments && forceflag != SFMMU_KERNEL_RELOC) {
7270 		/*
7271 		 * Unlink any pa_hments and free them, calling back
7272 		 * the responsible subsystem to notify it of the error.
7273 		 * This can occur in situations such as drivers leaking
7274 		 * DMA handles: naughty, but common enough that we'd like
7275 		 * to keep the system running rather than bringing it
7276 		 * down with an obscure error like "pa_hment leaked"
7277 		 * which doesn't aid the user in debugging their driver.
7278 		 */
7279 		for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7280 			tmphme = sfhme->hme_next;
7281 			if (IS_PAHME(sfhme)) {
7282 				struct pa_hment *pahmep = sfhme->hme_data;
7283 				sfmmu_pahment_leaked(pahmep);
7284 				HME_SUB(sfhme, pp);
7285 				kmem_cache_free(pa_hment_cache, pahmep);
7286 			}
7287 		}
7288 
7289 		ASSERT(!PP_ISMAPPED(origpp) || xhme_blks);
7290 	}
7291 
7292 	sfmmu_mlist_exit(pml);
7293 
7294 	/*
7295 	 * XHAT may not have finished unloading pages
7296 	 * because some other thread was waiting for
7297 	 * mlist lock and XHAT_PAGEUNLOAD let it do
7298 	 * the job.
7299 	 */
7300 	if (xhme_blks) {
7301 		pp = origpp;
7302 		goto retry_xhat;
7303 	}
7304 
7305 	return (0);
7306 }
7307 
7308 cpuset_t
7309 sfmmu_pageunload(page_t *pp, struct sf_hment *sfhme, int cons)
7310 {
7311 	struct hme_blk *hmeblkp;
7312 	sfmmu_t *sfmmup;
7313 	tte_t tte, ttemod;
7314 #ifdef DEBUG
7315 	tte_t orig_old;
7316 #endif /* DEBUG */
7317 	caddr_t addr;
7318 	int ttesz;
7319 	int ret;
7320 	cpuset_t cpuset;
7321 
7322 	ASSERT(pp != NULL);
7323 	ASSERT(sfmmu_mlist_held(pp));
7324 	ASSERT(!PP_ISKAS(pp));
7325 
7326 	CPUSET_ZERO(cpuset);
7327 
7328 	hmeblkp = sfmmu_hmetohblk(sfhme);
7329 
7330 readtte:
7331 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7332 	if (TTE_IS_VALID(&tte)) {
7333 		sfmmup = hblktosfmmu(hmeblkp);
7334 		ttesz = get_hblk_ttesz(hmeblkp);
7335 		/*
7336 		 * Only unload mappings of 'cons' size.
7337 		 */
7338 		if (ttesz != cons)
7339 			return (cpuset);
7340 
7341 		/*
7342 		 * Note that we have p_mapping lock, but no hash lock here.
7343 		 * hblk_unload() has to have both hash lock AND p_mapping
7344 		 * lock before it tries to modify tte. So, the tte could
7345 		 * not become invalid in the sfmmu_modifytte_try() below.
7346 		 */
7347 		ttemod = tte;
7348 #ifdef DEBUG
7349 		orig_old = tte;
7350 #endif /* DEBUG */
7351 
7352 		TTE_SET_INVALID(&ttemod);
7353 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7354 		if (ret < 0) {
7355 #ifdef DEBUG
7356 			/* only R/M bits can change. */
7357 			chk_tte(&orig_old, &tte, &ttemod, hmeblkp);
7358 #endif /* DEBUG */
7359 			goto readtte;
7360 		}
7361 
7362 		if (ret == 0) {
7363 			panic("pageunload: cas failed?");
7364 		}
7365 
7366 		addr = tte_to_vaddr(hmeblkp, tte);
7367 
7368 		if (hmeblkp->hblk_shared) {
7369 			sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7370 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
7371 			sf_region_t *rgnp;
7372 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7373 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7374 			ASSERT(srdp != NULL);
7375 			rgnp = srdp->srd_hmergnp[rid];
7376 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
7377 			cpuset = sfmmu_rgntlb_demap(addr, rgnp, hmeblkp, 1);
7378 			sfmmu_ttesync(NULL, addr, &tte, pp);
7379 			ASSERT(rgnp->rgn_ttecnt[ttesz] > 0);
7380 			atomic_add_long(&rgnp->rgn_ttecnt[ttesz], -1);
7381 		} else {
7382 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
7383 			atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -1);
7384 
7385 			/*
7386 			 * We need to flush the page from the virtual cache
7387 			 * in order to prevent a virtual cache alias
7388 			 * inconsistency. The particular scenario we need
7389 			 * to worry about is:
7390 			 * Given:  va1 and va2 are two virtual address that
7391 			 * alias and will map the same physical address.
7392 			 * 1.   mapping exists from va1 to pa and data has
7393 			 *	been read into the cache.
7394 			 * 2.   unload va1.
7395 			 * 3.   load va2 and modify data using va2.
7396 			 * 4    unload va2.
7397 			 * 5.   load va1 and reference data.  Unless we flush
7398 			 *	the data cache when we unload we will get
7399 			 *	stale data.
7400 			 * This scenario is taken care of by using virtual
7401 			 * page coloring.
7402 			 */
7403 			if (sfmmup->sfmmu_ismhat) {
7404 				/*
7405 				 * Flush TSBs, TLBs and caches
7406 				 * of every process
7407 				 * sharing this ism segment.
7408 				 */
7409 				sfmmu_hat_lock_all();
7410 				mutex_enter(&ism_mlist_lock);
7411 				kpreempt_disable();
7412 				sfmmu_ismtlbcache_demap(addr, sfmmup, hmeblkp,
7413 				    pp->p_pagenum, CACHE_NO_FLUSH);
7414 				kpreempt_enable();
7415 				mutex_exit(&ism_mlist_lock);
7416 				sfmmu_hat_unlock_all();
7417 				cpuset = cpu_ready_set;
7418 			} else {
7419 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7420 				cpuset = sfmmup->sfmmu_cpusran;
7421 			}
7422 		}
7423 
7424 		/*
7425 		 * Hme_sub has to run after ttesync() and a_rss update.
7426 		 * See hblk_unload().
7427 		 */
7428 		HME_SUB(sfhme, pp);
7429 		membar_stst();
7430 
7431 		/*
7432 		 * We can not make ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
7433 		 * since pteload may have done a HME_ADD() right after
7434 		 * we did the HME_SUB() above. Hmecnt is now maintained
7435 		 * by cas only. no lock guranteed its value. The only
7436 		 * gurantee we have is the hmecnt should not be less than
7437 		 * what it should be so the hblk will not be taken away.
7438 		 * It's also important that we decremented the hmecnt after
7439 		 * we are done with hmeblkp so that this hmeblk won't be
7440 		 * stolen.
7441 		 */
7442 		ASSERT(hmeblkp->hblk_hmecnt > 0);
7443 		ASSERT(hmeblkp->hblk_vcnt > 0);
7444 		atomic_add_16(&hmeblkp->hblk_vcnt, -1);
7445 		atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
7446 		/*
7447 		 * This is bug 4063182.
7448 		 * XXX: fixme
7449 		 * ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
7450 		 *	!hmeblkp->hblk_lckcnt);
7451 		 */
7452 	} else {
7453 		panic("invalid tte? pp %p &tte %p",
7454 		    (void *)pp, (void *)&tte);
7455 	}
7456 
7457 	return (cpuset);
7458 }
7459 
7460 /*
7461  * While relocating a kernel page, this function will move the mappings
7462  * from tpp to dpp and modify any associated data with these mappings.
7463  * It also unsuspends the suspended kernel mapping.
7464  */
7465 static void
7466 hat_pagereload(struct page *tpp, struct page *dpp)
7467 {
7468 	struct sf_hment *sfhme;
7469 	tte_t tte, ttemod;
7470 	int index, cons;
7471 
7472 	ASSERT(getpil() == PIL_MAX);
7473 	ASSERT(sfmmu_mlist_held(tpp));
7474 	ASSERT(sfmmu_mlist_held(dpp));
7475 
7476 	index = PP_MAPINDEX(tpp);
7477 	cons = TTE8K;
7478 
7479 	/* Update real mappings to the page */
7480 retry:
7481 	for (sfhme = tpp->p_mapping; sfhme != NULL; sfhme = sfhme->hme_next) {
7482 		if (IS_PAHME(sfhme))
7483 			continue;
7484 		sfmmu_copytte(&sfhme->hme_tte, &tte);
7485 		ttemod = tte;
7486 
7487 		/*
7488 		 * replace old pfn with new pfn in TTE
7489 		 */
7490 		PFN_TO_TTE(ttemod, dpp->p_pagenum);
7491 
7492 		/*
7493 		 * clear suspend bit
7494 		 */
7495 		ASSERT(TTE_IS_SUSPEND(&ttemod));
7496 		TTE_CLR_SUSPEND(&ttemod);
7497 
7498 		if (sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte) < 0)
7499 			panic("hat_pagereload(): sfmmu_modifytte_try() failed");
7500 
7501 		/*
7502 		 * set hme_page point to new page
7503 		 */
7504 		sfhme->hme_page = dpp;
7505 	}
7506 
7507 	/*
7508 	 * move p_mapping list from old page to new page
7509 	 */
7510 	dpp->p_mapping = tpp->p_mapping;
7511 	tpp->p_mapping = NULL;
7512 	dpp->p_share = tpp->p_share;
7513 	tpp->p_share = 0;
7514 
7515 	while (index != 0) {
7516 		index = index >> 1;
7517 		if (index != 0)
7518 			cons++;
7519 		if (index & 0x1) {
7520 			tpp = PP_GROUPLEADER(tpp, cons);
7521 			dpp = PP_GROUPLEADER(dpp, cons);
7522 			goto retry;
7523 		}
7524 	}
7525 
7526 	curthread->t_flag &= ~T_DONTDTRACE;
7527 	mutex_exit(&kpr_suspendlock);
7528 }
7529 
7530 uint_t
7531 hat_pagesync(struct page *pp, uint_t clearflag)
7532 {
7533 	struct sf_hment *sfhme, *tmphme = NULL;
7534 	struct hme_blk *hmeblkp;
7535 	kmutex_t *pml;
7536 	cpuset_t cpuset, tset;
7537 	int	index, cons;
7538 	extern	ulong_t po_share;
7539 	page_t	*save_pp = pp;
7540 	int	stop_on_sh = 0;
7541 	uint_t	shcnt;
7542 
7543 	CPUSET_ZERO(cpuset);
7544 
7545 	if (PP_ISRO(pp) && (clearflag & HAT_SYNC_STOPON_MOD)) {
7546 		return (PP_GENERIC_ATTR(pp));
7547 	}
7548 
7549 	if ((clearflag & HAT_SYNC_ZERORM) == 0) {
7550 		if ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(pp)) {
7551 			return (PP_GENERIC_ATTR(pp));
7552 		}
7553 		if ((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(pp)) {
7554 			return (PP_GENERIC_ATTR(pp));
7555 		}
7556 		if (clearflag & HAT_SYNC_STOPON_SHARED) {
7557 			if (pp->p_share > po_share) {
7558 				hat_page_setattr(pp, P_REF);
7559 				return (PP_GENERIC_ATTR(pp));
7560 			}
7561 			stop_on_sh = 1;
7562 			shcnt = 0;
7563 		}
7564 	}
7565 
7566 	clearflag &= ~HAT_SYNC_STOPON_SHARED;
7567 	pml = sfmmu_mlist_enter(pp);
7568 	index = PP_MAPINDEX(pp);
7569 	cons = TTE8K;
7570 retry:
7571 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7572 		/*
7573 		 * We need to save the next hment on the list since
7574 		 * it is possible for pagesync to remove an invalid hment
7575 		 * from the list.
7576 		 */
7577 		tmphme = sfhme->hme_next;
7578 		if (IS_PAHME(sfhme))
7579 			continue;
7580 		/*
7581 		 * If we are looking for large mappings and this hme doesn't
7582 		 * reach the range we are seeking, just ignore it.
7583 		 */
7584 		hmeblkp = sfmmu_hmetohblk(sfhme);
7585 		if (hmeblkp->hblk_xhat_bit)
7586 			continue;
7587 
7588 		if (hme_size(sfhme) < cons)
7589 			continue;
7590 
7591 		if (stop_on_sh) {
7592 			if (hmeblkp->hblk_shared) {
7593 				sf_srd_t *srdp = hblktosrd(hmeblkp);
7594 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7595 				sf_region_t *rgnp;
7596 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7597 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7598 				ASSERT(srdp != NULL);
7599 				rgnp = srdp->srd_hmergnp[rid];
7600 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
7601 				    rgnp, rid);
7602 				shcnt += rgnp->rgn_refcnt;
7603 			} else {
7604 				shcnt++;
7605 			}
7606 			if (shcnt > po_share) {
7607 				/*
7608 				 * tell the pager to spare the page this time
7609 				 * around.
7610 				 */
7611 				hat_page_setattr(save_pp, P_REF);
7612 				index = 0;
7613 				break;
7614 			}
7615 		}
7616 		tset = sfmmu_pagesync(pp, sfhme,
7617 		    clearflag & ~HAT_SYNC_STOPON_RM);
7618 		CPUSET_OR(cpuset, tset);
7619 
7620 		/*
7621 		 * If clearflag is HAT_SYNC_DONTZERO, break out as soon
7622 		 * as the "ref" or "mod" is set or share cnt exceeds po_share.
7623 		 */
7624 		if ((clearflag & ~HAT_SYNC_STOPON_RM) == HAT_SYNC_DONTZERO &&
7625 		    (((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(save_pp)) ||
7626 		    ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(save_pp)))) {
7627 			index = 0;
7628 			break;
7629 		}
7630 	}
7631 
7632 	while (index) {
7633 		index = index >> 1;
7634 		cons++;
7635 		if (index & 0x1) {
7636 			/* Go to leading page */
7637 			pp = PP_GROUPLEADER(pp, cons);
7638 			goto retry;
7639 		}
7640 	}
7641 
7642 	xt_sync(cpuset);
7643 	sfmmu_mlist_exit(pml);
7644 	return (PP_GENERIC_ATTR(save_pp));
7645 }
7646 
7647 /*
7648  * Get all the hardware dependent attributes for a page struct
7649  */
7650 static cpuset_t
7651 sfmmu_pagesync(struct page *pp, struct sf_hment *sfhme,
7652 	uint_t clearflag)
7653 {
7654 	caddr_t addr;
7655 	tte_t tte, ttemod;
7656 	struct hme_blk *hmeblkp;
7657 	int ret;
7658 	sfmmu_t *sfmmup;
7659 	cpuset_t cpuset;
7660 
7661 	ASSERT(pp != NULL);
7662 	ASSERT(sfmmu_mlist_held(pp));
7663 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
7664 	    (clearflag == HAT_SYNC_ZERORM));
7665 
7666 	SFMMU_STAT(sf_pagesync);
7667 
7668 	CPUSET_ZERO(cpuset);
7669 
7670 sfmmu_pagesync_retry:
7671 
7672 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7673 	if (TTE_IS_VALID(&tte)) {
7674 		hmeblkp = sfmmu_hmetohblk(sfhme);
7675 		sfmmup = hblktosfmmu(hmeblkp);
7676 		addr = tte_to_vaddr(hmeblkp, tte);
7677 		if (clearflag == HAT_SYNC_ZERORM) {
7678 			ttemod = tte;
7679 			TTE_CLR_RM(&ttemod);
7680 			ret = sfmmu_modifytte_try(&tte, &ttemod,
7681 			    &sfhme->hme_tte);
7682 			if (ret < 0) {
7683 				/*
7684 				 * cas failed and the new value is not what
7685 				 * we want.
7686 				 */
7687 				goto sfmmu_pagesync_retry;
7688 			}
7689 
7690 			if (ret > 0) {
7691 				/* we win the cas */
7692 				if (hmeblkp->hblk_shared) {
7693 					sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7694 					uint_t rid =
7695 					    hmeblkp->hblk_tag.htag_rid;
7696 					sf_region_t *rgnp;
7697 					ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7698 					ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7699 					ASSERT(srdp != NULL);
7700 					rgnp = srdp->srd_hmergnp[rid];
7701 					SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7702 					    srdp, rgnp, rid);
7703 					cpuset = sfmmu_rgntlb_demap(addr,
7704 					    rgnp, hmeblkp, 1);
7705 				} else {
7706 					sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
7707 					    0, 0);
7708 					cpuset = sfmmup->sfmmu_cpusran;
7709 				}
7710 			}
7711 		}
7712 		sfmmu_ttesync(hmeblkp->hblk_shared ? NULL : sfmmup, addr,
7713 		    &tte, pp);
7714 	}
7715 	return (cpuset);
7716 }
7717 
7718 /*
7719  * Remove write permission from a mappings to a page, so that
7720  * we can detect the next modification of it. This requires modifying
7721  * the TTE then invalidating (demap) any TLB entry using that TTE.
7722  * This code is similar to sfmmu_pagesync().
7723  */
7724 static cpuset_t
7725 sfmmu_pageclrwrt(struct page *pp, struct sf_hment *sfhme)
7726 {
7727 	caddr_t addr;
7728 	tte_t tte;
7729 	tte_t ttemod;
7730 	struct hme_blk *hmeblkp;
7731 	int ret;
7732 	sfmmu_t *sfmmup;
7733 	cpuset_t cpuset;
7734 
7735 	ASSERT(pp != NULL);
7736 	ASSERT(sfmmu_mlist_held(pp));
7737 
7738 	CPUSET_ZERO(cpuset);
7739 	SFMMU_STAT(sf_clrwrt);
7740 
7741 retry:
7742 
7743 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7744 	if (TTE_IS_VALID(&tte) && TTE_IS_WRITABLE(&tte)) {
7745 		hmeblkp = sfmmu_hmetohblk(sfhme);
7746 
7747 		/*
7748 		 * xhat mappings should never be to a VMODSORT page.
7749 		 */
7750 		ASSERT(hmeblkp->hblk_xhat_bit == 0);
7751 
7752 		sfmmup = hblktosfmmu(hmeblkp);
7753 		addr = tte_to_vaddr(hmeblkp, tte);
7754 
7755 		ttemod = tte;
7756 		TTE_CLR_WRT(&ttemod);
7757 		TTE_CLR_MOD(&ttemod);
7758 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7759 
7760 		/*
7761 		 * if cas failed and the new value is not what
7762 		 * we want retry
7763 		 */
7764 		if (ret < 0)
7765 			goto retry;
7766 
7767 		/* we win the cas */
7768 		if (ret > 0) {
7769 			if (hmeblkp->hblk_shared) {
7770 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7771 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7772 				sf_region_t *rgnp;
7773 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7774 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7775 				ASSERT(srdp != NULL);
7776 				rgnp = srdp->srd_hmergnp[rid];
7777 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7778 				    srdp, rgnp, rid);
7779 				cpuset = sfmmu_rgntlb_demap(addr,
7780 				    rgnp, hmeblkp, 1);
7781 			} else {
7782 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7783 				cpuset = sfmmup->sfmmu_cpusran;
7784 			}
7785 		}
7786 	}
7787 
7788 	return (cpuset);
7789 }
7790 
7791 /*
7792  * Walk all mappings of a page, removing write permission and clearing the
7793  * ref/mod bits. This code is similar to hat_pagesync()
7794  */
7795 static void
7796 hat_page_clrwrt(page_t *pp)
7797 {
7798 	struct sf_hment *sfhme;
7799 	struct sf_hment *tmphme = NULL;
7800 	kmutex_t *pml;
7801 	cpuset_t cpuset;
7802 	cpuset_t tset;
7803 	int	index;
7804 	int	 cons;
7805 
7806 	CPUSET_ZERO(cpuset);
7807 
7808 	pml = sfmmu_mlist_enter(pp);
7809 	index = PP_MAPINDEX(pp);
7810 	cons = TTE8K;
7811 retry:
7812 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7813 		tmphme = sfhme->hme_next;
7814 
7815 		/*
7816 		 * If we are looking for large mappings and this hme doesn't
7817 		 * reach the range we are seeking, just ignore its.
7818 		 */
7819 
7820 		if (hme_size(sfhme) < cons)
7821 			continue;
7822 
7823 		tset = sfmmu_pageclrwrt(pp, sfhme);
7824 		CPUSET_OR(cpuset, tset);
7825 	}
7826 
7827 	while (index) {
7828 		index = index >> 1;
7829 		cons++;
7830 		if (index & 0x1) {
7831 			/* Go to leading page */
7832 			pp = PP_GROUPLEADER(pp, cons);
7833 			goto retry;
7834 		}
7835 	}
7836 
7837 	xt_sync(cpuset);
7838 	sfmmu_mlist_exit(pml);
7839 }
7840 
7841 /*
7842  * Set the given REF/MOD/RO bits for the given page.
7843  * For a vnode with a sorted v_pages list, we need to change
7844  * the attributes and the v_pages list together under page_vnode_mutex.
7845  */
7846 void
7847 hat_page_setattr(page_t *pp, uint_t flag)
7848 {
7849 	vnode_t		*vp = pp->p_vnode;
7850 	page_t		**listp;
7851 	kmutex_t	*pmtx;
7852 	kmutex_t	*vphm = NULL;
7853 	int		noshuffle;
7854 
7855 	noshuffle = flag & P_NSH;
7856 	flag &= ~P_NSH;
7857 
7858 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7859 
7860 	/*
7861 	 * nothing to do if attribute already set
7862 	 */
7863 	if ((pp->p_nrm & flag) == flag)
7864 		return;
7865 
7866 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp) &&
7867 	    !noshuffle) {
7868 		vphm = page_vnode_mutex(vp);
7869 		mutex_enter(vphm);
7870 	}
7871 
7872 	pmtx = sfmmu_page_enter(pp);
7873 	pp->p_nrm |= flag;
7874 	sfmmu_page_exit(pmtx);
7875 
7876 	if (vphm != NULL) {
7877 		/*
7878 		 * Some File Systems examine v_pages for NULL w/o
7879 		 * grabbing the vphm mutex. Must not let it become NULL when
7880 		 * pp is the only page on the list.
7881 		 */
7882 		if (pp->p_vpnext != pp) {
7883 			page_vpsub(&vp->v_pages, pp);
7884 			if (vp->v_pages != NULL)
7885 				listp = &vp->v_pages->p_vpprev->p_vpnext;
7886 			else
7887 				listp = &vp->v_pages;
7888 			page_vpadd(listp, pp);
7889 		}
7890 		mutex_exit(vphm);
7891 	}
7892 }
7893 
7894 void
7895 hat_page_clrattr(page_t *pp, uint_t flag)
7896 {
7897 	vnode_t		*vp = pp->p_vnode;
7898 	kmutex_t	*pmtx;
7899 
7900 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7901 
7902 	pmtx = sfmmu_page_enter(pp);
7903 
7904 	/*
7905 	 * Caller is expected to hold page's io lock for VMODSORT to work
7906 	 * correctly with pvn_vplist_dirty() and pvn_getdirty() when mod
7907 	 * bit is cleared.
7908 	 * We don't have assert to avoid tripping some existing third party
7909 	 * code. The dirty page is moved back to top of the v_page list
7910 	 * after IO is done in pvn_write_done().
7911 	 */
7912 	pp->p_nrm &= ~flag;
7913 	sfmmu_page_exit(pmtx);
7914 
7915 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
7916 
7917 		/*
7918 		 * VMODSORT works by removing write permissions and getting
7919 		 * a fault when a page is made dirty. At this point
7920 		 * we need to remove write permission from all mappings
7921 		 * to this page.
7922 		 */
7923 		hat_page_clrwrt(pp);
7924 	}
7925 }
7926 
7927 uint_t
7928 hat_page_getattr(page_t *pp, uint_t flag)
7929 {
7930 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7931 	return ((uint_t)(pp->p_nrm & flag));
7932 }
7933 
7934 /*
7935  * DEBUG kernels: verify that a kernel va<->pa translation
7936  * is safe by checking the underlying page_t is in a page
7937  * relocation-safe state.
7938  */
7939 #ifdef	DEBUG
7940 void
7941 sfmmu_check_kpfn(pfn_t pfn)
7942 {
7943 	page_t *pp;
7944 	int index, cons;
7945 
7946 	if (hat_check_vtop == 0)
7947 		return;
7948 
7949 	if (hat_kpr_enabled == 0 || kvseg.s_base == NULL || panicstr)
7950 		return;
7951 
7952 	pp = page_numtopp_nolock(pfn);
7953 	if (!pp)
7954 		return;
7955 
7956 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7957 		return;
7958 
7959 	/*
7960 	 * Handed a large kernel page, we dig up the root page since we
7961 	 * know the root page might have the lock also.
7962 	 */
7963 	if (pp->p_szc != 0) {
7964 		index = PP_MAPINDEX(pp);
7965 		cons = TTE8K;
7966 again:
7967 		while (index != 0) {
7968 			index >>= 1;
7969 			if (index != 0)
7970 				cons++;
7971 			if (index & 0x1) {
7972 				pp = PP_GROUPLEADER(pp, cons);
7973 				goto again;
7974 			}
7975 		}
7976 	}
7977 
7978 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7979 		return;
7980 
7981 	/*
7982 	 * Pages need to be locked or allocated "permanent" (either from
7983 	 * static_arena arena or explicitly setting PG_NORELOC when calling
7984 	 * page_create_va()) for VA->PA translations to be valid.
7985 	 */
7986 	if (!PP_ISNORELOC(pp))
7987 		panic("Illegal VA->PA translation, pp 0x%p not permanent",
7988 		    (void *)pp);
7989 	else
7990 		panic("Illegal VA->PA translation, pp 0x%p not locked",
7991 		    (void *)pp);
7992 }
7993 #endif	/* DEBUG */
7994 
7995 /*
7996  * Returns a page frame number for a given virtual address.
7997  * Returns PFN_INVALID to indicate an invalid mapping
7998  */
7999 pfn_t
8000 hat_getpfnum(struct hat *hat, caddr_t addr)
8001 {
8002 	pfn_t pfn;
8003 	tte_t tte;
8004 
8005 	/*
8006 	 * We would like to
8007 	 * ASSERT(AS_LOCK_HELD(as, &as->a_lock));
8008 	 * but we can't because the iommu driver will call this
8009 	 * routine at interrupt time and it can't grab the as lock
8010 	 * or it will deadlock: A thread could have the as lock
8011 	 * and be waiting for io.  The io can't complete
8012 	 * because the interrupt thread is blocked trying to grab
8013 	 * the as lock.
8014 	 */
8015 
8016 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8017 
8018 	if (hat == ksfmmup) {
8019 		if (IS_KMEM_VA_LARGEPAGE(addr)) {
8020 			ASSERT(segkmem_lpszc > 0);
8021 			pfn = sfmmu_kvaszc2pfn(addr, segkmem_lpszc);
8022 			if (pfn != PFN_INVALID) {
8023 				sfmmu_check_kpfn(pfn);
8024 				return (pfn);
8025 			}
8026 		} else if (segkpm && IS_KPM_ADDR(addr)) {
8027 			return (sfmmu_kpm_vatopfn(addr));
8028 		}
8029 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
8030 		    == PFN_SUSPENDED) {
8031 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
8032 		}
8033 		sfmmu_check_kpfn(pfn);
8034 		return (pfn);
8035 	} else {
8036 		return (sfmmu_uvatopfn(addr, hat, NULL));
8037 	}
8038 }
8039 
8040 /*
8041  * hat_getkpfnum() is an obsolete DDI routine, and its use is discouraged.
8042  * Use hat_getpfnum(kas.a_hat, ...) instead.
8043  *
8044  * We'd like to return PFN_INVALID if the mappings have underlying page_t's
8045  * but can't right now due to the fact that some software has grown to use
8046  * this interface incorrectly. So for now when the interface is misused,
8047  * return a warning to the user that in the future it won't work in the
8048  * way they're abusing it, and carry on (after disabling page relocation).
8049  */
8050 pfn_t
8051 hat_getkpfnum(caddr_t addr)
8052 {
8053 	pfn_t pfn;
8054 	tte_t tte;
8055 	int badcaller = 0;
8056 	extern int segkmem_reloc;
8057 
8058 	if (segkpm && IS_KPM_ADDR(addr)) {
8059 		badcaller = 1;
8060 		pfn = sfmmu_kpm_vatopfn(addr);
8061 	} else {
8062 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
8063 		    == PFN_SUSPENDED) {
8064 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
8065 		}
8066 		badcaller = pf_is_memory(pfn);
8067 	}
8068 
8069 	if (badcaller) {
8070 		/*
8071 		 * We can't return PFN_INVALID or the caller may panic
8072 		 * or corrupt the system.  The only alternative is to
8073 		 * disable page relocation at this point for all kernel
8074 		 * memory.  This will impact any callers of page_relocate()
8075 		 * such as FMA or DR.
8076 		 *
8077 		 * RFE: Add junk here to spit out an ereport so the sysadmin
8078 		 * can be advised that he should upgrade his device driver
8079 		 * so that this doesn't happen.
8080 		 */
8081 		hat_getkpfnum_badcall(caller());
8082 		if (hat_kpr_enabled && segkmem_reloc) {
8083 			hat_kpr_enabled = 0;
8084 			segkmem_reloc = 0;
8085 			cmn_err(CE_WARN, "Kernel Page Relocation is DISABLED");
8086 		}
8087 	}
8088 	return (pfn);
8089 }
8090 
8091 /*
8092  * This routine will return both pfn and tte for the vaddr.
8093  */
8094 static pfn_t
8095 sfmmu_uvatopfn(caddr_t vaddr, struct hat *sfmmup, tte_t *ttep)
8096 {
8097 	struct hmehash_bucket *hmebp;
8098 	hmeblk_tag hblktag;
8099 	int hmeshift, hashno = 1;
8100 	struct hme_blk *hmeblkp = NULL;
8101 	tte_t tte;
8102 
8103 	struct sf_hment *sfhmep;
8104 	pfn_t pfn;
8105 
8106 	/* support for ISM */
8107 	ism_map_t	*ism_map;
8108 	ism_blk_t	*ism_blkp;
8109 	int		i;
8110 	sfmmu_t *ism_hatid = NULL;
8111 	sfmmu_t *locked_hatid = NULL;
8112 	sfmmu_t	*sv_sfmmup = sfmmup;
8113 	caddr_t	sv_vaddr = vaddr;
8114 	sf_srd_t *srdp;
8115 
8116 	if (ttep == NULL) {
8117 		ttep = &tte;
8118 	} else {
8119 		ttep->ll = 0;
8120 	}
8121 
8122 	ASSERT(sfmmup != ksfmmup);
8123 	SFMMU_STAT(sf_user_vtop);
8124 	/*
8125 	 * Set ism_hatid if vaddr falls in a ISM segment.
8126 	 */
8127 	ism_blkp = sfmmup->sfmmu_iblk;
8128 	if (ism_blkp != NULL) {
8129 		sfmmu_ismhat_enter(sfmmup, 0);
8130 		locked_hatid = sfmmup;
8131 	}
8132 	while (ism_blkp != NULL && ism_hatid == NULL) {
8133 		ism_map = ism_blkp->iblk_maps;
8134 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
8135 			if (vaddr >= ism_start(ism_map[i]) &&
8136 			    vaddr < ism_end(ism_map[i])) {
8137 				sfmmup = ism_hatid = ism_map[i].imap_ismhat;
8138 				vaddr = (caddr_t)(vaddr -
8139 				    ism_start(ism_map[i]));
8140 				break;
8141 			}
8142 		}
8143 		ism_blkp = ism_blkp->iblk_next;
8144 	}
8145 	if (locked_hatid) {
8146 		sfmmu_ismhat_exit(locked_hatid, 0);
8147 	}
8148 
8149 	hblktag.htag_id = sfmmup;
8150 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
8151 	do {
8152 		hmeshift = HME_HASH_SHIFT(hashno);
8153 		hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
8154 		hblktag.htag_rehash = hashno;
8155 		hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
8156 
8157 		SFMMU_HASH_LOCK(hmebp);
8158 
8159 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
8160 		if (hmeblkp != NULL) {
8161 			ASSERT(!hmeblkp->hblk_shared);
8162 			HBLKTOHME(sfhmep, hmeblkp, vaddr);
8163 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
8164 			SFMMU_HASH_UNLOCK(hmebp);
8165 			if (TTE_IS_VALID(ttep)) {
8166 				pfn = TTE_TO_PFN(vaddr, ttep);
8167 				return (pfn);
8168 			}
8169 			break;
8170 		}
8171 		SFMMU_HASH_UNLOCK(hmebp);
8172 		hashno++;
8173 	} while (HME_REHASH(sfmmup) && (hashno <= mmu_hashcnt));
8174 
8175 	if (SF_HMERGNMAP_ISNULL(sv_sfmmup)) {
8176 		return (PFN_INVALID);
8177 	}
8178 	srdp = sv_sfmmup->sfmmu_srdp;
8179 	ASSERT(srdp != NULL);
8180 	ASSERT(srdp->srd_refcnt != 0);
8181 	hblktag.htag_id = srdp;
8182 	hashno = 1;
8183 	do {
8184 		hmeshift = HME_HASH_SHIFT(hashno);
8185 		hblktag.htag_bspage = HME_HASH_BSPAGE(sv_vaddr, hmeshift);
8186 		hblktag.htag_rehash = hashno;
8187 		hmebp = HME_HASH_FUNCTION(srdp, sv_vaddr, hmeshift);
8188 
8189 		SFMMU_HASH_LOCK(hmebp);
8190 		for (hmeblkp = hmebp->hmeblkp; hmeblkp != NULL;
8191 		    hmeblkp = hmeblkp->hblk_next) {
8192 			uint_t rid;
8193 			sf_region_t *rgnp;
8194 			caddr_t rsaddr;
8195 			caddr_t readdr;
8196 
8197 			if (!HTAGS_EQ_SHME(hmeblkp->hblk_tag, hblktag,
8198 			    sv_sfmmup->sfmmu_hmeregion_map)) {
8199 				continue;
8200 			}
8201 			ASSERT(hmeblkp->hblk_shared);
8202 			rid = hmeblkp->hblk_tag.htag_rid;
8203 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8204 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8205 			rgnp = srdp->srd_hmergnp[rid];
8206 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
8207 			HBLKTOHME(sfhmep, hmeblkp, sv_vaddr);
8208 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
8209 			rsaddr = rgnp->rgn_saddr;
8210 			readdr = rsaddr + rgnp->rgn_size;
8211 #ifdef DEBUG
8212 			if (TTE_IS_VALID(ttep) ||
8213 			    get_hblk_ttesz(hmeblkp) > TTE8K) {
8214 				caddr_t eva = tte_to_evaddr(hmeblkp, ttep);
8215 				ASSERT(eva > sv_vaddr);
8216 				ASSERT(sv_vaddr >= rsaddr);
8217 				ASSERT(sv_vaddr < readdr);
8218 				ASSERT(eva <= readdr);
8219 			}
8220 #endif /* DEBUG */
8221 			/*
8222 			 * Continue the search if we
8223 			 * found an invalid 8K tte outside of the area
8224 			 * covered by this hmeblk's region.
8225 			 */
8226 			if (TTE_IS_VALID(ttep)) {
8227 				SFMMU_HASH_UNLOCK(hmebp);
8228 				pfn = TTE_TO_PFN(sv_vaddr, ttep);
8229 				return (pfn);
8230 			} else if (get_hblk_ttesz(hmeblkp) > TTE8K ||
8231 			    (sv_vaddr >= rsaddr && sv_vaddr < readdr)) {
8232 				SFMMU_HASH_UNLOCK(hmebp);
8233 				pfn = PFN_INVALID;
8234 				return (pfn);
8235 			}
8236 		}
8237 		SFMMU_HASH_UNLOCK(hmebp);
8238 		hashno++;
8239 	} while (hashno <= mmu_hashcnt);
8240 	return (PFN_INVALID);
8241 }
8242 
8243 
8244 /*
8245  * For compatability with AT&T and later optimizations
8246  */
8247 /* ARGSUSED */
8248 void
8249 hat_map(struct hat *hat, caddr_t addr, size_t len, uint_t flags)
8250 {
8251 	ASSERT(hat != NULL);
8252 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8253 }
8254 
8255 /*
8256  * Return the number of mappings to a particular page.  This number is an
8257  * approximation of the number of people sharing the page.
8258  *
8259  * shared hmeblks or ism hmeblks are counted as 1 mapping here.
8260  * hat_page_checkshare() can be used to compare threshold to share
8261  * count that reflects the number of region sharers albeit at higher cost.
8262  */
8263 ulong_t
8264 hat_page_getshare(page_t *pp)
8265 {
8266 	page_t *spp = pp;	/* start page */
8267 	kmutex_t *pml;
8268 	ulong_t	cnt;
8269 	int index, sz = TTE64K;
8270 
8271 	/*
8272 	 * We need to grab the mlist lock to make sure any outstanding
8273 	 * load/unloads complete.  Otherwise we could return zero
8274 	 * even though the unload(s) hasn't finished yet.
8275 	 */
8276 	pml = sfmmu_mlist_enter(spp);
8277 	cnt = spp->p_share;
8278 
8279 #ifdef VAC
8280 	if (kpm_enable)
8281 		cnt += spp->p_kpmref;
8282 #endif
8283 	if (vpm_enable && pp->p_vpmref) {
8284 		cnt += 1;
8285 	}
8286 
8287 	/*
8288 	 * If we have any large mappings, we count the number of
8289 	 * mappings that this large page is part of.
8290 	 */
8291 	index = PP_MAPINDEX(spp);
8292 	index >>= 1;
8293 	while (index) {
8294 		pp = PP_GROUPLEADER(spp, sz);
8295 		if ((index & 0x1) && pp != spp) {
8296 			cnt += pp->p_share;
8297 			spp = pp;
8298 		}
8299 		index >>= 1;
8300 		sz++;
8301 	}
8302 	sfmmu_mlist_exit(pml);
8303 	return (cnt);
8304 }
8305 
8306 /*
8307  * Return 1 if the number of mappings exceeds sh_thresh. Return 0
8308  * otherwise. Count shared hmeblks by region's refcnt.
8309  */
8310 int
8311 hat_page_checkshare(page_t *pp, ulong_t sh_thresh)
8312 {
8313 	kmutex_t *pml;
8314 	ulong_t	cnt = 0;
8315 	int index, sz = TTE8K;
8316 	struct sf_hment *sfhme, *tmphme = NULL;
8317 	struct hme_blk *hmeblkp;
8318 
8319 	pml = sfmmu_mlist_enter(pp);
8320 
8321 #ifdef VAC
8322 	if (kpm_enable)
8323 		cnt = pp->p_kpmref;
8324 #endif
8325 
8326 	if (vpm_enable && pp->p_vpmref) {
8327 		cnt += 1;
8328 	}
8329 
8330 	if (pp->p_share + cnt > sh_thresh) {
8331 		sfmmu_mlist_exit(pml);
8332 		return (1);
8333 	}
8334 
8335 	index = PP_MAPINDEX(pp);
8336 
8337 again:
8338 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
8339 		tmphme = sfhme->hme_next;
8340 		if (IS_PAHME(sfhme)) {
8341 			continue;
8342 		}
8343 
8344 		hmeblkp = sfmmu_hmetohblk(sfhme);
8345 		if (hmeblkp->hblk_xhat_bit) {
8346 			cnt++;
8347 			if (cnt > sh_thresh) {
8348 				sfmmu_mlist_exit(pml);
8349 				return (1);
8350 			}
8351 			continue;
8352 		}
8353 		if (hme_size(sfhme) != sz) {
8354 			continue;
8355 		}
8356 
8357 		if (hmeblkp->hblk_shared) {
8358 			sf_srd_t *srdp = hblktosrd(hmeblkp);
8359 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
8360 			sf_region_t *rgnp;
8361 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8362 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8363 			ASSERT(srdp != NULL);
8364 			rgnp = srdp->srd_hmergnp[rid];
8365 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
8366 			    rgnp, rid);
8367 			cnt += rgnp->rgn_refcnt;
8368 		} else {
8369 			cnt++;
8370 		}
8371 		if (cnt > sh_thresh) {
8372 			sfmmu_mlist_exit(pml);
8373 			return (1);
8374 		}
8375 	}
8376 
8377 	index >>= 1;
8378 	sz++;
8379 	while (index) {
8380 		pp = PP_GROUPLEADER(pp, sz);
8381 		ASSERT(sfmmu_mlist_held(pp));
8382 		if (index & 0x1) {
8383 			goto again;
8384 		}
8385 		index >>= 1;
8386 		sz++;
8387 	}
8388 	sfmmu_mlist_exit(pml);
8389 	return (0);
8390 }
8391 
8392 /*
8393  * Unload all large mappings to the pp and reset the p_szc field of every
8394  * constituent page according to the remaining mappings.
8395  *
8396  * pp must be locked SE_EXCL. Even though no other constituent pages are
8397  * locked it's legal to unload the large mappings to the pp because all
8398  * constituent pages of large locked mappings have to be locked SE_SHARED.
8399  * This means if we have SE_EXCL lock on one of constituent pages none of the
8400  * large mappings to pp are locked.
8401  *
8402  * Decrease p_szc field starting from the last constituent page and ending
8403  * with the root page. This method is used because other threads rely on the
8404  * root's p_szc to find the lock to syncronize on. After a root page_t's p_szc
8405  * is demoted then other threads will succeed in sfmmu_mlspl_enter(). This
8406  * ensures that p_szc changes of the constituent pages appears atomic for all
8407  * threads that use sfmmu_mlspl_enter() to examine p_szc field.
8408  *
8409  * This mechanism is only used for file system pages where it's not always
8410  * possible to get SE_EXCL locks on all constituent pages to demote the size
8411  * code (as is done for anonymous or kernel large pages).
8412  *
8413  * See more comments in front of sfmmu_mlspl_enter().
8414  */
8415 void
8416 hat_page_demote(page_t *pp)
8417 {
8418 	int index;
8419 	int sz;
8420 	cpuset_t cpuset;
8421 	int sync = 0;
8422 	page_t *rootpp;
8423 	struct sf_hment *sfhme;
8424 	struct sf_hment *tmphme = NULL;
8425 	struct hme_blk *hmeblkp;
8426 	uint_t pszc;
8427 	page_t *lastpp;
8428 	cpuset_t tset;
8429 	pgcnt_t npgs;
8430 	kmutex_t *pml;
8431 	kmutex_t *pmtx = NULL;
8432 
8433 	ASSERT(PAGE_EXCL(pp));
8434 	ASSERT(!PP_ISFREE(pp));
8435 	ASSERT(!PP_ISKAS(pp));
8436 	ASSERT(page_szc_lock_assert(pp));
8437 	pml = sfmmu_mlist_enter(pp);
8438 
8439 	pszc = pp->p_szc;
8440 	if (pszc == 0) {
8441 		goto out;
8442 	}
8443 
8444 	index = PP_MAPINDEX(pp) >> 1;
8445 
8446 	if (index) {
8447 		CPUSET_ZERO(cpuset);
8448 		sz = TTE64K;
8449 		sync = 1;
8450 	}
8451 
8452 	while (index) {
8453 		if (!(index & 0x1)) {
8454 			index >>= 1;
8455 			sz++;
8456 			continue;
8457 		}
8458 		ASSERT(sz <= pszc);
8459 		rootpp = PP_GROUPLEADER(pp, sz);
8460 		for (sfhme = rootpp->p_mapping; sfhme; sfhme = tmphme) {
8461 			tmphme = sfhme->hme_next;
8462 			ASSERT(!IS_PAHME(sfhme));
8463 			hmeblkp = sfmmu_hmetohblk(sfhme);
8464 			if (hme_size(sfhme) != sz) {
8465 				continue;
8466 			}
8467 			if (hmeblkp->hblk_xhat_bit) {
8468 				cmn_err(CE_PANIC,
8469 				    "hat_page_demote: xhat hmeblk");
8470 			}
8471 			tset = sfmmu_pageunload(rootpp, sfhme, sz);
8472 			CPUSET_OR(cpuset, tset);
8473 		}
8474 		if (index >>= 1) {
8475 			sz++;
8476 		}
8477 	}
8478 
8479 	ASSERT(!PP_ISMAPPED_LARGE(pp));
8480 
8481 	if (sync) {
8482 		xt_sync(cpuset);
8483 #ifdef VAC
8484 		if (PP_ISTNC(pp)) {
8485 			conv_tnc(rootpp, sz);
8486 		}
8487 #endif	/* VAC */
8488 	}
8489 
8490 	pmtx = sfmmu_page_enter(pp);
8491 
8492 	ASSERT(pp->p_szc == pszc);
8493 	rootpp = PP_PAGEROOT(pp);
8494 	ASSERT(rootpp->p_szc == pszc);
8495 	lastpp = PP_PAGENEXT_N(rootpp, TTEPAGES(pszc) - 1);
8496 
8497 	while (lastpp != rootpp) {
8498 		sz = PP_MAPINDEX(lastpp) ? fnd_mapping_sz(lastpp) : 0;
8499 		ASSERT(sz < pszc);
8500 		npgs = (sz == 0) ? 1 : TTEPAGES(sz);
8501 		ASSERT(P2PHASE(lastpp->p_pagenum, npgs) == npgs - 1);
8502 		while (--npgs > 0) {
8503 			lastpp->p_szc = (uchar_t)sz;
8504 			lastpp = PP_PAGEPREV(lastpp);
8505 		}
8506 		if (sz) {
8507 			/*
8508 			 * make sure before current root's pszc
8509 			 * is updated all updates to constituent pages pszc
8510 			 * fields are globally visible.
8511 			 */
8512 			membar_producer();
8513 		}
8514 		lastpp->p_szc = sz;
8515 		ASSERT(IS_P2ALIGNED(lastpp->p_pagenum, TTEPAGES(sz)));
8516 		if (lastpp != rootpp) {
8517 			lastpp = PP_PAGEPREV(lastpp);
8518 		}
8519 	}
8520 	if (sz == 0) {
8521 		/* the loop above doesn't cover this case */
8522 		rootpp->p_szc = 0;
8523 	}
8524 out:
8525 	ASSERT(pp->p_szc == 0);
8526 	if (pmtx != NULL) {
8527 		sfmmu_page_exit(pmtx);
8528 	}
8529 	sfmmu_mlist_exit(pml);
8530 }
8531 
8532 /*
8533  * Refresh the HAT ismttecnt[] element for size szc.
8534  * Caller must have set ISM busy flag to prevent mapping
8535  * lists from changing while we're traversing them.
8536  */
8537 pgcnt_t
8538 ism_tsb_entries(sfmmu_t *sfmmup, int szc)
8539 {
8540 	ism_blk_t	*ism_blkp = sfmmup->sfmmu_iblk;
8541 	ism_map_t	*ism_map;
8542 	pgcnt_t		npgs = 0;
8543 	pgcnt_t		npgs_scd = 0;
8544 	int		j;
8545 	sf_scd_t	*scdp;
8546 	uchar_t		rid;
8547 
8548 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
8549 	scdp = sfmmup->sfmmu_scdp;
8550 
8551 	for (; ism_blkp != NULL; ism_blkp = ism_blkp->iblk_next) {
8552 		ism_map = ism_blkp->iblk_maps;
8553 		for (j = 0; ism_map[j].imap_ismhat && j < ISM_MAP_SLOTS; j++) {
8554 			rid = ism_map[j].imap_rid;
8555 			ASSERT(rid == SFMMU_INVALID_ISMRID ||
8556 			    rid < sfmmup->sfmmu_srdp->srd_next_ismrid);
8557 
8558 			if (scdp != NULL && rid != SFMMU_INVALID_ISMRID &&
8559 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
8560 				/* ISM is in sfmmup's SCD */
8561 				npgs_scd +=
8562 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8563 			} else {
8564 				/* ISMs is not in SCD */
8565 				npgs +=
8566 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8567 			}
8568 		}
8569 	}
8570 	sfmmup->sfmmu_ismttecnt[szc] = npgs;
8571 	sfmmup->sfmmu_scdismttecnt[szc] = npgs_scd;
8572 	return (npgs);
8573 }
8574 
8575 /*
8576  * Yield the memory claim requirement for an address space.
8577  *
8578  * This is currently implemented as the number of bytes that have active
8579  * hardware translations that have page structures.  Therefore, it can
8580  * underestimate the traditional resident set size, eg, if the
8581  * physical page is present and the hardware translation is missing;
8582  * and it can overestimate the rss, eg, if there are active
8583  * translations to a frame buffer with page structs.
8584  * Also, it does not take sharing into account.
8585  *
8586  * Note that we don't acquire locks here since this function is most often
8587  * called from the clock thread.
8588  */
8589 size_t
8590 hat_get_mapped_size(struct hat *hat)
8591 {
8592 	size_t		assize = 0;
8593 	int 		i;
8594 
8595 	if (hat == NULL)
8596 		return (0);
8597 
8598 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8599 
8600 	for (i = 0; i < mmu_page_sizes; i++)
8601 		assize += ((pgcnt_t)hat->sfmmu_ttecnt[i] +
8602 		    (pgcnt_t)hat->sfmmu_scdrttecnt[i]) * TTEBYTES(i);
8603 
8604 	if (hat->sfmmu_iblk == NULL)
8605 		return (assize);
8606 
8607 	for (i = 0; i < mmu_page_sizes; i++)
8608 		assize += ((pgcnt_t)hat->sfmmu_ismttecnt[i] +
8609 		    (pgcnt_t)hat->sfmmu_scdismttecnt[i]) * TTEBYTES(i);
8610 
8611 	return (assize);
8612 }
8613 
8614 int
8615 hat_stats_enable(struct hat *hat)
8616 {
8617 	hatlock_t	*hatlockp;
8618 
8619 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8620 
8621 	hatlockp = sfmmu_hat_enter(hat);
8622 	hat->sfmmu_rmstat++;
8623 	sfmmu_hat_exit(hatlockp);
8624 	return (1);
8625 }
8626 
8627 void
8628 hat_stats_disable(struct hat *hat)
8629 {
8630 	hatlock_t	*hatlockp;
8631 
8632 	ASSERT(hat->sfmmu_xhat_provider == NULL);
8633 
8634 	hatlockp = sfmmu_hat_enter(hat);
8635 	hat->sfmmu_rmstat--;
8636 	sfmmu_hat_exit(hatlockp);
8637 }
8638 
8639 /*
8640  * Routines for entering or removing  ourselves from the
8641  * ism_hat's mapping list. This is used for both private and
8642  * SCD hats.
8643  */
8644 static void
8645 iment_add(struct ism_ment *iment,  struct hat *ism_hat)
8646 {
8647 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8648 
8649 	iment->iment_prev = NULL;
8650 	iment->iment_next = ism_hat->sfmmu_iment;
8651 	if (ism_hat->sfmmu_iment) {
8652 		ism_hat->sfmmu_iment->iment_prev = iment;
8653 	}
8654 	ism_hat->sfmmu_iment = iment;
8655 }
8656 
8657 static void
8658 iment_sub(struct ism_ment *iment, struct hat *ism_hat)
8659 {
8660 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8661 
8662 	if (ism_hat->sfmmu_iment == NULL) {
8663 		panic("ism map entry remove - no entries");
8664 	}
8665 
8666 	if (iment->iment_prev) {
8667 		ASSERT(ism_hat->sfmmu_iment != iment);
8668 		iment->iment_prev->iment_next = iment->iment_next;
8669 	} else {
8670 		ASSERT(ism_hat->sfmmu_iment == iment);
8671 		ism_hat->sfmmu_iment = iment->iment_next;
8672 	}
8673 
8674 	if (iment->iment_next) {
8675 		iment->iment_next->iment_prev = iment->iment_prev;
8676 	}
8677 
8678 	/*
8679 	 * zero out the entry
8680 	 */
8681 	iment->iment_next = NULL;
8682 	iment->iment_prev = NULL;
8683 	iment->iment_hat =  NULL;
8684 	iment->iment_base_va = 0;
8685 }
8686 
8687 /*
8688  * Hat_share()/unshare() return an (non-zero) error
8689  * when saddr and daddr are not properly aligned.
8690  *
8691  * The top level mapping element determines the alignment
8692  * requirement for saddr and daddr, depending on different
8693  * architectures.
8694  *
8695  * When hat_share()/unshare() are not supported,
8696  * HATOP_SHARE()/UNSHARE() return 0
8697  */
8698 int
8699 hat_share(struct hat *sfmmup, caddr_t addr,
8700 	struct hat *ism_hatid, caddr_t sptaddr, size_t len, uint_t ismszc)
8701 {
8702 	ism_blk_t	*ism_blkp;
8703 	ism_blk_t	*new_iblk;
8704 	ism_map_t 	*ism_map;
8705 	ism_ment_t	*ism_ment;
8706 	int		i, added;
8707 	hatlock_t	*hatlockp;
8708 	int		reload_mmu = 0;
8709 	uint_t		ismshift = page_get_shift(ismszc);
8710 	size_t		ismpgsz = page_get_pagesize(ismszc);
8711 	uint_t		ismmask = (uint_t)ismpgsz - 1;
8712 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8713 	ushort_t	ismhatflag;
8714 	hat_region_cookie_t rcookie;
8715 	sf_scd_t	*old_scdp;
8716 
8717 #ifdef DEBUG
8718 	caddr_t		eaddr = addr + len;
8719 #endif /* DEBUG */
8720 
8721 	ASSERT(ism_hatid != NULL && sfmmup != NULL);
8722 	ASSERT(sptaddr == ISMID_STARTADDR);
8723 	/*
8724 	 * Check the alignment.
8725 	 */
8726 	if (!ISM_ALIGNED(ismshift, addr) || !ISM_ALIGNED(ismshift, sptaddr))
8727 		return (EINVAL);
8728 
8729 	/*
8730 	 * Check size alignment.
8731 	 */
8732 	if (!ISM_ALIGNED(ismshift, len))
8733 		return (EINVAL);
8734 
8735 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
8736 
8737 	/*
8738 	 * Allocate ism_ment for the ism_hat's mapping list, and an
8739 	 * ism map blk in case we need one.  We must do our
8740 	 * allocations before acquiring locks to prevent a deadlock
8741 	 * in the kmem allocator on the mapping list lock.
8742 	 */
8743 	new_iblk = kmem_cache_alloc(ism_blk_cache, KM_SLEEP);
8744 	ism_ment = kmem_cache_alloc(ism_ment_cache, KM_SLEEP);
8745 
8746 	/*
8747 	 * Serialize ISM mappings with the ISM busy flag, and also the
8748 	 * trap handlers.
8749 	 */
8750 	sfmmu_ismhat_enter(sfmmup, 0);
8751 
8752 	/*
8753 	 * Allocate an ism map blk if necessary.
8754 	 */
8755 	if (sfmmup->sfmmu_iblk == NULL) {
8756 		sfmmup->sfmmu_iblk = new_iblk;
8757 		bzero(new_iblk, sizeof (*new_iblk));
8758 		new_iblk->iblk_nextpa = (uint64_t)-1;
8759 		membar_stst();	/* make sure next ptr visible to all CPUs */
8760 		sfmmup->sfmmu_ismblkpa = va_to_pa((caddr_t)new_iblk);
8761 		reload_mmu = 1;
8762 		new_iblk = NULL;
8763 	}
8764 
8765 #ifdef DEBUG
8766 	/*
8767 	 * Make sure mapping does not already exist.
8768 	 */
8769 	ism_blkp = sfmmup->sfmmu_iblk;
8770 	while (ism_blkp != NULL) {
8771 		ism_map = ism_blkp->iblk_maps;
8772 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
8773 			if ((addr >= ism_start(ism_map[i]) &&
8774 			    addr < ism_end(ism_map[i])) ||
8775 			    eaddr > ism_start(ism_map[i]) &&
8776 			    eaddr <= ism_end(ism_map[i])) {
8777 				panic("sfmmu_share: Already mapped!");
8778 			}
8779 		}
8780 		ism_blkp = ism_blkp->iblk_next;
8781 	}
8782 #endif /* DEBUG */
8783 
8784 	ASSERT(ismszc >= TTE4M);
8785 	if (ismszc == TTE4M) {
8786 		ismhatflag = HAT_4M_FLAG;
8787 	} else if (ismszc == TTE32M) {
8788 		ismhatflag = HAT_32M_FLAG;
8789 	} else if (ismszc == TTE256M) {
8790 		ismhatflag = HAT_256M_FLAG;
8791 	}
8792 	/*
8793 	 * Add mapping to first available mapping slot.
8794 	 */
8795 	ism_blkp = sfmmup->sfmmu_iblk;
8796 	added = 0;
8797 	while (!added) {
8798 		ism_map = ism_blkp->iblk_maps;
8799 		for (i = 0; i < ISM_MAP_SLOTS; i++)  {
8800 			if (ism_map[i].imap_ismhat == NULL) {
8801 
8802 				ism_map[i].imap_ismhat = ism_hatid;
8803 				ism_map[i].imap_vb_shift = (uchar_t)ismshift;
8804 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8805 				ism_map[i].imap_hatflags = ismhatflag;
8806 				ism_map[i].imap_sz_mask = ismmask;
8807 				/*
8808 				 * imap_seg is checked in ISM_CHECK to see if
8809 				 * non-NULL, then other info assumed valid.
8810 				 */
8811 				membar_stst();
8812 				ism_map[i].imap_seg = (uintptr_t)addr | sh_size;
8813 				ism_map[i].imap_ment = ism_ment;
8814 
8815 				/*
8816 				 * Now add ourselves to the ism_hat's
8817 				 * mapping list.
8818 				 */
8819 				ism_ment->iment_hat = sfmmup;
8820 				ism_ment->iment_base_va = addr;
8821 				ism_hatid->sfmmu_ismhat = 1;
8822 				mutex_enter(&ism_mlist_lock);
8823 				iment_add(ism_ment, ism_hatid);
8824 				mutex_exit(&ism_mlist_lock);
8825 				added = 1;
8826 				break;
8827 			}
8828 		}
8829 		if (!added && ism_blkp->iblk_next == NULL) {
8830 			ism_blkp->iblk_next = new_iblk;
8831 			new_iblk = NULL;
8832 			bzero(ism_blkp->iblk_next,
8833 			    sizeof (*ism_blkp->iblk_next));
8834 			ism_blkp->iblk_next->iblk_nextpa = (uint64_t)-1;
8835 			membar_stst();
8836 			ism_blkp->iblk_nextpa =
8837 			    va_to_pa((caddr_t)ism_blkp->iblk_next);
8838 		}
8839 		ism_blkp = ism_blkp->iblk_next;
8840 	}
8841 
8842 	/*
8843 	 * After calling hat_join_region, sfmmup may join a new SCD or
8844 	 * move from the old scd to a new scd, in which case, we want to
8845 	 * shrink the sfmmup's private tsb size, i.e., pass shrink to
8846 	 * sfmmu_check_page_sizes at the end of this routine.
8847 	 */
8848 	old_scdp = sfmmup->sfmmu_scdp;
8849 
8850 	rcookie = hat_join_region(sfmmup, addr, len, (void *)ism_hatid, 0,
8851 	    PROT_ALL, ismszc, NULL, HAT_REGION_ISM);
8852 	if (rcookie != HAT_INVALID_REGION_COOKIE) {
8853 		ism_map[i].imap_rid = (uchar_t)((uint64_t)rcookie);
8854 	}
8855 	/*
8856 	 * Update our counters for this sfmmup's ism mappings.
8857 	 */
8858 	for (i = 0; i <= ismszc; i++) {
8859 		if (!(disable_ism_large_pages & (1 << i)))
8860 			(void) ism_tsb_entries(sfmmup, i);
8861 	}
8862 
8863 	/*
8864 	 * For ISM and DISM we do not support 512K pages, so we only only
8865 	 * search the 4M and 8K/64K hashes for 4 pagesize cpus, and search the
8866 	 * 256M or 32M, and 4M and 8K/64K hashes for 6 pagesize cpus.
8867 	 *
8868 	 * Need to set 32M/256M ISM flags to make sure
8869 	 * sfmmu_check_page_sizes() enables them on Panther.
8870 	 */
8871 	ASSERT((disable_ism_large_pages & (1 << TTE512K)) != 0);
8872 
8873 	switch (ismszc) {
8874 	case TTE256M:
8875 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_256M_ISM)) {
8876 			hatlockp = sfmmu_hat_enter(sfmmup);
8877 			SFMMU_FLAGS_SET(sfmmup, HAT_256M_ISM);
8878 			sfmmu_hat_exit(hatlockp);
8879 		}
8880 		break;
8881 	case TTE32M:
8882 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_32M_ISM)) {
8883 			hatlockp = sfmmu_hat_enter(sfmmup);
8884 			SFMMU_FLAGS_SET(sfmmup, HAT_32M_ISM);
8885 			sfmmu_hat_exit(hatlockp);
8886 		}
8887 		break;
8888 	default:
8889 		break;
8890 	}
8891 
8892 	/*
8893 	 * If we updated the ismblkpa for this HAT we must make
8894 	 * sure all CPUs running this process reload their tsbmiss area.
8895 	 * Otherwise they will fail to load the mappings in the tsbmiss
8896 	 * handler and will loop calling pagefault().
8897 	 */
8898 	if (reload_mmu) {
8899 		hatlockp = sfmmu_hat_enter(sfmmup);
8900 		sfmmu_sync_mmustate(sfmmup);
8901 		sfmmu_hat_exit(hatlockp);
8902 	}
8903 
8904 	sfmmu_ismhat_exit(sfmmup, 0);
8905 
8906 	/*
8907 	 * Free up ismblk if we didn't use it.
8908 	 */
8909 	if (new_iblk != NULL)
8910 		kmem_cache_free(ism_blk_cache, new_iblk);
8911 
8912 	/*
8913 	 * Check TSB and TLB page sizes.
8914 	 */
8915 	if (sfmmup->sfmmu_scdp != NULL && old_scdp != sfmmup->sfmmu_scdp) {
8916 		sfmmu_check_page_sizes(sfmmup, 0);
8917 	} else {
8918 		sfmmu_check_page_sizes(sfmmup, 1);
8919 	}
8920 	return (0);
8921 }
8922 
8923 /*
8924  * hat_unshare removes exactly one ism_map from
8925  * this process's as.  It expects multiple calls
8926  * to hat_unshare for multiple shm segments.
8927  */
8928 void
8929 hat_unshare(struct hat *sfmmup, caddr_t addr, size_t len, uint_t ismszc)
8930 {
8931 	ism_map_t 	*ism_map;
8932 	ism_ment_t	*free_ment = NULL;
8933 	ism_blk_t	*ism_blkp;
8934 	struct hat	*ism_hatid;
8935 	int 		found, i;
8936 	hatlock_t	*hatlockp;
8937 	struct tsb_info	*tsbinfo;
8938 	uint_t		ismshift = page_get_shift(ismszc);
8939 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8940 	uchar_t		ism_rid;
8941 	sf_scd_t	*old_scdp;
8942 
8943 	ASSERT(ISM_ALIGNED(ismshift, addr));
8944 	ASSERT(ISM_ALIGNED(ismshift, len));
8945 	ASSERT(sfmmup != NULL);
8946 	ASSERT(sfmmup != ksfmmup);
8947 
8948 	if (sfmmup->sfmmu_xhat_provider) {
8949 		XHAT_UNSHARE(sfmmup, addr, len);
8950 		return;
8951 	} else {
8952 		/*
8953 		 * This must be a CPU HAT. If the address space has
8954 		 * XHATs attached, inform all XHATs that ISM segment
8955 		 * is going away
8956 		 */
8957 		ASSERT(sfmmup->sfmmu_as != NULL);
8958 		if (sfmmup->sfmmu_as->a_xhat != NULL)
8959 			xhat_unshare_all(sfmmup->sfmmu_as, addr, len);
8960 	}
8961 
8962 	/*
8963 	 * Make sure that during the entire time ISM mappings are removed,
8964 	 * the trap handlers serialize behind us, and that no one else
8965 	 * can be mucking with ISM mappings.  This also lets us get away
8966 	 * with not doing expensive cross calls to flush the TLB -- we
8967 	 * just discard the context, flush the entire TSB, and call it
8968 	 * a day.
8969 	 */
8970 	sfmmu_ismhat_enter(sfmmup, 0);
8971 
8972 	/*
8973 	 * Remove the mapping.
8974 	 *
8975 	 * We can't have any holes in the ism map.
8976 	 * The tsb miss code while searching the ism map will
8977 	 * stop on an empty map slot.  So we must move
8978 	 * everyone past the hole up 1 if any.
8979 	 *
8980 	 * Also empty ism map blks are not freed until the
8981 	 * process exits. This is to prevent a MT race condition
8982 	 * between sfmmu_unshare() and sfmmu_tsbmiss_exception().
8983 	 */
8984 	found = 0;
8985 	ism_blkp = sfmmup->sfmmu_iblk;
8986 	while (!found && ism_blkp != NULL) {
8987 		ism_map = ism_blkp->iblk_maps;
8988 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
8989 			if (addr == ism_start(ism_map[i]) &&
8990 			    sh_size == (size_t)(ism_size(ism_map[i]))) {
8991 				found = 1;
8992 				break;
8993 			}
8994 		}
8995 		if (!found)
8996 			ism_blkp = ism_blkp->iblk_next;
8997 	}
8998 
8999 	if (found) {
9000 		ism_hatid = ism_map[i].imap_ismhat;
9001 		ism_rid = ism_map[i].imap_rid;
9002 		ASSERT(ism_hatid != NULL);
9003 		ASSERT(ism_hatid->sfmmu_ismhat == 1);
9004 
9005 		/*
9006 		 * After hat_leave_region, the sfmmup may leave SCD,
9007 		 * in which case, we want to grow the private tsb size when
9008 		 * calling sfmmu_check_page_sizes at the end of the routine.
9009 		 */
9010 		old_scdp = sfmmup->sfmmu_scdp;
9011 		/*
9012 		 * Then remove ourselves from the region.
9013 		 */
9014 		if (ism_rid != SFMMU_INVALID_ISMRID) {
9015 			hat_leave_region(sfmmup, (void *)((uint64_t)ism_rid),
9016 			    HAT_REGION_ISM);
9017 		}
9018 
9019 		/*
9020 		 * And now guarantee that any other cpu
9021 		 * that tries to process an ISM miss
9022 		 * will go to tl=0.
9023 		 */
9024 		hatlockp = sfmmu_hat_enter(sfmmup);
9025 		sfmmu_invalidate_ctx(sfmmup);
9026 		sfmmu_hat_exit(hatlockp);
9027 
9028 		/*
9029 		 * Remove ourselves from the ism mapping list.
9030 		 */
9031 		mutex_enter(&ism_mlist_lock);
9032 		iment_sub(ism_map[i].imap_ment, ism_hatid);
9033 		mutex_exit(&ism_mlist_lock);
9034 		free_ment = ism_map[i].imap_ment;
9035 
9036 		/*
9037 		 * We delete the ism map by copying
9038 		 * the next map over the current one.
9039 		 * We will take the next one in the maps
9040 		 * array or from the next ism_blk.
9041 		 */
9042 		while (ism_blkp != NULL) {
9043 			ism_map = ism_blkp->iblk_maps;
9044 			while (i < (ISM_MAP_SLOTS - 1)) {
9045 				ism_map[i] = ism_map[i + 1];
9046 				i++;
9047 			}
9048 			/* i == (ISM_MAP_SLOTS - 1) */
9049 			ism_blkp = ism_blkp->iblk_next;
9050 			if (ism_blkp != NULL) {
9051 				ism_map[i] = ism_blkp->iblk_maps[0];
9052 				i = 0;
9053 			} else {
9054 				ism_map[i].imap_seg = 0;
9055 				ism_map[i].imap_vb_shift = 0;
9056 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
9057 				ism_map[i].imap_hatflags = 0;
9058 				ism_map[i].imap_sz_mask = 0;
9059 				ism_map[i].imap_ismhat = NULL;
9060 				ism_map[i].imap_ment = NULL;
9061 			}
9062 		}
9063 
9064 		/*
9065 		 * Now flush entire TSB for the process, since
9066 		 * demapping page by page can be too expensive.
9067 		 * We don't have to flush the TLB here anymore
9068 		 * since we switch to a new TLB ctx instead.
9069 		 * Also, there is no need to flush if the process
9070 		 * is exiting since the TSB will be freed later.
9071 		 */
9072 		if (!sfmmup->sfmmu_free) {
9073 			hatlockp = sfmmu_hat_enter(sfmmup);
9074 			for (tsbinfo = sfmmup->sfmmu_tsb; tsbinfo != NULL;
9075 			    tsbinfo = tsbinfo->tsb_next) {
9076 				if (tsbinfo->tsb_flags & TSB_SWAPPED)
9077 					continue;
9078 				if (tsbinfo->tsb_flags & TSB_RELOC_FLAG) {
9079 					tsbinfo->tsb_flags |=
9080 					    TSB_FLUSH_NEEDED;
9081 					continue;
9082 				}
9083 
9084 				sfmmu_inv_tsb(tsbinfo->tsb_va,
9085 				    TSB_BYTES(tsbinfo->tsb_szc));
9086 			}
9087 			sfmmu_hat_exit(hatlockp);
9088 		}
9089 	}
9090 
9091 	/*
9092 	 * Update our counters for this sfmmup's ism mappings.
9093 	 */
9094 	for (i = 0; i <= ismszc; i++) {
9095 		if (!(disable_ism_large_pages & (1 << i)))
9096 			(void) ism_tsb_entries(sfmmup, i);
9097 	}
9098 
9099 	sfmmu_ismhat_exit(sfmmup, 0);
9100 
9101 	/*
9102 	 * We must do our freeing here after dropping locks
9103 	 * to prevent a deadlock in the kmem allocator on the
9104 	 * mapping list lock.
9105 	 */
9106 	if (free_ment != NULL)
9107 		kmem_cache_free(ism_ment_cache, free_ment);
9108 
9109 	/*
9110 	 * Check TSB and TLB page sizes if the process isn't exiting.
9111 	 */
9112 	if (!sfmmup->sfmmu_free) {
9113 		if (found && old_scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
9114 			sfmmu_check_page_sizes(sfmmup, 1);
9115 		} else {
9116 			sfmmu_check_page_sizes(sfmmup, 0);
9117 		}
9118 	}
9119 }
9120 
9121 /* ARGSUSED */
9122 static int
9123 sfmmu_idcache_constructor(void *buf, void *cdrarg, int kmflags)
9124 {
9125 	/* void *buf is sfmmu_t pointer */
9126 	bzero(buf, sizeof (sfmmu_t));
9127 
9128 	return (0);
9129 }
9130 
9131 /* ARGSUSED */
9132 static void
9133 sfmmu_idcache_destructor(void *buf, void *cdrarg)
9134 {
9135 	/* void *buf is sfmmu_t pointer */
9136 }
9137 
9138 /*
9139  * setup kmem hmeblks by bzeroing all members and initializing the nextpa
9140  * field to be the pa of this hmeblk
9141  */
9142 /* ARGSUSED */
9143 static int
9144 sfmmu_hblkcache_constructor(void *buf, void *cdrarg, int kmflags)
9145 {
9146 	struct hme_blk *hmeblkp;
9147 
9148 	bzero(buf, (size_t)cdrarg);
9149 	hmeblkp = (struct hme_blk *)buf;
9150 	hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
9151 
9152 #ifdef	HBLK_TRACE
9153 	mutex_init(&hmeblkp->hblk_audit_lock, NULL, MUTEX_DEFAULT, NULL);
9154 #endif	/* HBLK_TRACE */
9155 
9156 	return (0);
9157 }
9158 
9159 /* ARGSUSED */
9160 static void
9161 sfmmu_hblkcache_destructor(void *buf, void *cdrarg)
9162 {
9163 
9164 #ifdef	HBLK_TRACE
9165 
9166 	struct hme_blk *hmeblkp;
9167 
9168 	hmeblkp = (struct hme_blk *)buf;
9169 	mutex_destroy(&hmeblkp->hblk_audit_lock);
9170 
9171 #endif	/* HBLK_TRACE */
9172 }
9173 
9174 #define	SFMMU_CACHE_RECLAIM_SCAN_RATIO 8
9175 static int sfmmu_cache_reclaim_scan_ratio = SFMMU_CACHE_RECLAIM_SCAN_RATIO;
9176 /*
9177  * The kmem allocator will callback into our reclaim routine when the system
9178  * is running low in memory.  We traverse the hash and free up all unused but
9179  * still cached hme_blks.  We also traverse the free list and free them up
9180  * as well.
9181  */
9182 /*ARGSUSED*/
9183 static void
9184 sfmmu_hblkcache_reclaim(void *cdrarg)
9185 {
9186 	int i;
9187 	struct hmehash_bucket *hmebp;
9188 	struct hme_blk *hmeblkp, *nx_hblk, *pr_hblk = NULL;
9189 	static struct hmehash_bucket *uhmehash_reclaim_hand;
9190 	static struct hmehash_bucket *khmehash_reclaim_hand;
9191 	struct hme_blk *list = NULL, *last_hmeblkp;
9192 	cpuset_t cpuset = cpu_ready_set;
9193 	cpu_hme_pend_t *cpuhp;
9194 
9195 	/* Free up hmeblks on the cpu pending lists */
9196 	for (i = 0; i < NCPU; i++) {
9197 		cpuhp = &cpu_hme_pend[i];
9198 		if (cpuhp->chp_listp != NULL)  {
9199 			mutex_enter(&cpuhp->chp_mutex);
9200 			if (cpuhp->chp_listp == NULL) {
9201 				mutex_exit(&cpuhp->chp_mutex);
9202 				continue;
9203 			}
9204 			for (last_hmeblkp = cpuhp->chp_listp;
9205 			    last_hmeblkp->hblk_next != NULL;
9206 			    last_hmeblkp = last_hmeblkp->hblk_next)
9207 				;
9208 			last_hmeblkp->hblk_next = list;
9209 			list = cpuhp->chp_listp;
9210 			cpuhp->chp_listp = NULL;
9211 			cpuhp->chp_count = 0;
9212 			mutex_exit(&cpuhp->chp_mutex);
9213 		}
9214 
9215 	}
9216 
9217 	if (list != NULL) {
9218 		kpreempt_disable();
9219 		CPUSET_DEL(cpuset, CPU->cpu_id);
9220 		xt_sync(cpuset);
9221 		xt_sync(cpuset);
9222 		kpreempt_enable();
9223 		sfmmu_hblk_free(&list);
9224 		list = NULL;
9225 	}
9226 
9227 	hmebp = uhmehash_reclaim_hand;
9228 	if (hmebp == NULL || hmebp > &uhme_hash[UHMEHASH_SZ])
9229 		uhmehash_reclaim_hand = hmebp = uhme_hash;
9230 	uhmehash_reclaim_hand += UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9231 
9232 	for (i = UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9233 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9234 			hmeblkp = hmebp->hmeblkp;
9235 			pr_hblk = NULL;
9236 			while (hmeblkp) {
9237 				nx_hblk = hmeblkp->hblk_next;
9238 				if (!hmeblkp->hblk_vcnt &&
9239 				    !hmeblkp->hblk_hmecnt) {
9240 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9241 					    pr_hblk, &list, 0);
9242 				} else {
9243 					pr_hblk = hmeblkp;
9244 				}
9245 				hmeblkp = nx_hblk;
9246 			}
9247 			SFMMU_HASH_UNLOCK(hmebp);
9248 		}
9249 		if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
9250 			hmebp = uhme_hash;
9251 	}
9252 
9253 	hmebp = khmehash_reclaim_hand;
9254 	if (hmebp == NULL || hmebp > &khme_hash[KHMEHASH_SZ])
9255 		khmehash_reclaim_hand = hmebp = khme_hash;
9256 	khmehash_reclaim_hand += KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
9257 
9258 	for (i = KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
9259 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
9260 			hmeblkp = hmebp->hmeblkp;
9261 			pr_hblk = NULL;
9262 			while (hmeblkp) {
9263 				nx_hblk = hmeblkp->hblk_next;
9264 				if (!hmeblkp->hblk_vcnt &&
9265 				    !hmeblkp->hblk_hmecnt) {
9266 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9267 					    pr_hblk, &list, 0);
9268 				} else {
9269 					pr_hblk = hmeblkp;
9270 				}
9271 				hmeblkp = nx_hblk;
9272 			}
9273 			SFMMU_HASH_UNLOCK(hmebp);
9274 		}
9275 		if (hmebp++ == &khme_hash[KHMEHASH_SZ])
9276 			hmebp = khme_hash;
9277 	}
9278 	sfmmu_hblks_list_purge(&list, 0);
9279 }
9280 
9281 /*
9282  * sfmmu_get_ppvcolor should become a vm_machdep or hatop interface.
9283  * same goes for sfmmu_get_addrvcolor().
9284  *
9285  * This function will return the virtual color for the specified page. The
9286  * virtual color corresponds to this page current mapping or its last mapping.
9287  * It is used by memory allocators to choose addresses with the correct
9288  * alignment so vac consistency is automatically maintained.  If the page
9289  * has no color it returns -1.
9290  */
9291 /*ARGSUSED*/
9292 int
9293 sfmmu_get_ppvcolor(struct page *pp)
9294 {
9295 #ifdef VAC
9296 	int color;
9297 
9298 	if (!(cache & CACHE_VAC) || PP_NEWPAGE(pp)) {
9299 		return (-1);
9300 	}
9301 	color = PP_GET_VCOLOR(pp);
9302 	ASSERT(color < mmu_btop(shm_alignment));
9303 	return (color);
9304 #else
9305 	return (-1);
9306 #endif	/* VAC */
9307 }
9308 
9309 /*
9310  * This function will return the desired alignment for vac consistency
9311  * (vac color) given a virtual address.  If no vac is present it returns -1.
9312  */
9313 /*ARGSUSED*/
9314 int
9315 sfmmu_get_addrvcolor(caddr_t vaddr)
9316 {
9317 #ifdef VAC
9318 	if (cache & CACHE_VAC) {
9319 		return (addr_to_vcolor(vaddr));
9320 	} else {
9321 		return (-1);
9322 	}
9323 #else
9324 	return (-1);
9325 #endif	/* VAC */
9326 }
9327 
9328 #ifdef VAC
9329 /*
9330  * Check for conflicts.
9331  * A conflict exists if the new and existent mappings do not match in
9332  * their "shm_alignment fields. If conflicts exist, the existant mappings
9333  * are flushed unless one of them is locked. If one of them is locked, then
9334  * the mappings are flushed and converted to non-cacheable mappings.
9335  */
9336 static void
9337 sfmmu_vac_conflict(struct hat *hat, caddr_t addr, page_t *pp)
9338 {
9339 	struct hat *tmphat;
9340 	struct sf_hment *sfhmep, *tmphme = NULL;
9341 	struct hme_blk *hmeblkp;
9342 	int vcolor;
9343 	tte_t tte;
9344 
9345 	ASSERT(sfmmu_mlist_held(pp));
9346 	ASSERT(!PP_ISNC(pp));		/* page better be cacheable */
9347 
9348 	vcolor = addr_to_vcolor(addr);
9349 	if (PP_NEWPAGE(pp)) {
9350 		PP_SET_VCOLOR(pp, vcolor);
9351 		return;
9352 	}
9353 
9354 	if (PP_GET_VCOLOR(pp) == vcolor) {
9355 		return;
9356 	}
9357 
9358 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
9359 		/*
9360 		 * Previous user of page had a different color
9361 		 * but since there are no current users
9362 		 * we just flush the cache and change the color.
9363 		 */
9364 		SFMMU_STAT(sf_pgcolor_conflict);
9365 		sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9366 		PP_SET_VCOLOR(pp, vcolor);
9367 		return;
9368 	}
9369 
9370 	/*
9371 	 * If we get here we have a vac conflict with a current
9372 	 * mapping.  VAC conflict policy is as follows.
9373 	 * - The default is to unload the other mappings unless:
9374 	 * - If we have a large mapping we uncache the page.
9375 	 * We need to uncache the rest of the large page too.
9376 	 * - If any of the mappings are locked we uncache the page.
9377 	 * - If the requested mapping is inconsistent
9378 	 * with another mapping and that mapping
9379 	 * is in the same address space we have to
9380 	 * make it non-cached.  The default thing
9381 	 * to do is unload the inconsistent mapping
9382 	 * but if they are in the same address space
9383 	 * we run the risk of unmapping the pc or the
9384 	 * stack which we will use as we return to the user,
9385 	 * in which case we can then fault on the thing
9386 	 * we just unloaded and get into an infinite loop.
9387 	 */
9388 	if (PP_ISMAPPED_LARGE(pp)) {
9389 		int sz;
9390 
9391 		/*
9392 		 * Existing mapping is for big pages. We don't unload
9393 		 * existing big mappings to satisfy new mappings.
9394 		 * Always convert all mappings to TNC.
9395 		 */
9396 		sz = fnd_mapping_sz(pp);
9397 		pp = PP_GROUPLEADER(pp, sz);
9398 		SFMMU_STAT_ADD(sf_uncache_conflict, TTEPAGES(sz));
9399 		sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH,
9400 		    TTEPAGES(sz));
9401 
9402 		return;
9403 	}
9404 
9405 	/*
9406 	 * check if any mapping is in same as or if it is locked
9407 	 * since in that case we need to uncache.
9408 	 */
9409 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9410 		tmphme = sfhmep->hme_next;
9411 		if (IS_PAHME(sfhmep))
9412 			continue;
9413 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9414 		if (hmeblkp->hblk_xhat_bit)
9415 			continue;
9416 		tmphat = hblktosfmmu(hmeblkp);
9417 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
9418 		ASSERT(TTE_IS_VALID(&tte));
9419 		if (hmeblkp->hblk_shared || tmphat == hat ||
9420 		    hmeblkp->hblk_lckcnt) {
9421 			/*
9422 			 * We have an uncache conflict
9423 			 */
9424 			SFMMU_STAT(sf_uncache_conflict);
9425 			sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH, 1);
9426 			return;
9427 		}
9428 	}
9429 
9430 	/*
9431 	 * We have an unload conflict
9432 	 * We have already checked for LARGE mappings, therefore
9433 	 * the remaining mapping(s) must be TTE8K.
9434 	 */
9435 	SFMMU_STAT(sf_unload_conflict);
9436 
9437 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9438 		tmphme = sfhmep->hme_next;
9439 		if (IS_PAHME(sfhmep))
9440 			continue;
9441 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9442 		if (hmeblkp->hblk_xhat_bit)
9443 			continue;
9444 		ASSERT(!hmeblkp->hblk_shared);
9445 		(void) sfmmu_pageunload(pp, sfhmep, TTE8K);
9446 	}
9447 
9448 	if (PP_ISMAPPED_KPM(pp))
9449 		sfmmu_kpm_vac_unload(pp, addr);
9450 
9451 	/*
9452 	 * Unloads only do TLB flushes so we need to flush the
9453 	 * cache here.
9454 	 */
9455 	sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9456 	PP_SET_VCOLOR(pp, vcolor);
9457 }
9458 
9459 /*
9460  * Whenever a mapping is unloaded and the page is in TNC state,
9461  * we see if the page can be made cacheable again. 'pp' is
9462  * the page that we just unloaded a mapping from, the size
9463  * of mapping that was unloaded is 'ottesz'.
9464  * Remark:
9465  * The recache policy for mpss pages can leave a performance problem
9466  * under the following circumstances:
9467  * . A large page in uncached mode has just been unmapped.
9468  * . All constituent pages are TNC due to a conflicting small mapping.
9469  * . There are many other, non conflicting, small mappings around for
9470  *   a lot of the constituent pages.
9471  * . We're called w/ the "old" groupleader page and the old ottesz,
9472  *   but this is irrelevant, since we're no more "PP_ISMAPPED_LARGE", so
9473  *   we end up w/ TTE8K or npages == 1.
9474  * . We call tst_tnc w/ the old groupleader only, and if there is no
9475  *   conflict, we re-cache only this page.
9476  * . All other small mappings are not checked and will be left in TNC mode.
9477  * The problem is not very serious because:
9478  * . mpss is actually only defined for heap and stack, so the probability
9479  *   is not very high that a large page mapping exists in parallel to a small
9480  *   one (this is possible, but seems to be bad programming style in the
9481  *   appl).
9482  * . The problem gets a little bit more serious, when those TNC pages
9483  *   have to be mapped into kernel space, e.g. for networking.
9484  * . When VAC alias conflicts occur in applications, this is regarded
9485  *   as an application bug. So if kstat's show them, the appl should
9486  *   be changed anyway.
9487  */
9488 void
9489 conv_tnc(page_t *pp, int ottesz)
9490 {
9491 	int cursz, dosz;
9492 	pgcnt_t curnpgs, dopgs;
9493 	pgcnt_t pg64k;
9494 	page_t *pp2;
9495 
9496 	/*
9497 	 * Determine how big a range we check for TNC and find
9498 	 * leader page. cursz is the size of the biggest
9499 	 * mapping that still exist on 'pp'.
9500 	 */
9501 	if (PP_ISMAPPED_LARGE(pp)) {
9502 		cursz = fnd_mapping_sz(pp);
9503 	} else {
9504 		cursz = TTE8K;
9505 	}
9506 
9507 	if (ottesz >= cursz) {
9508 		dosz = ottesz;
9509 		pp2 = pp;
9510 	} else {
9511 		dosz = cursz;
9512 		pp2 = PP_GROUPLEADER(pp, dosz);
9513 	}
9514 
9515 	pg64k = TTEPAGES(TTE64K);
9516 	dopgs = TTEPAGES(dosz);
9517 
9518 	ASSERT(dopgs == 1 || ((dopgs & (pg64k - 1)) == 0));
9519 
9520 	while (dopgs != 0) {
9521 		curnpgs = TTEPAGES(cursz);
9522 		if (tst_tnc(pp2, curnpgs)) {
9523 			SFMMU_STAT_ADD(sf_recache, curnpgs);
9524 			sfmmu_page_cache_array(pp2, HAT_CACHE, CACHE_NO_FLUSH,
9525 			    curnpgs);
9526 		}
9527 
9528 		ASSERT(dopgs >= curnpgs);
9529 		dopgs -= curnpgs;
9530 
9531 		if (dopgs == 0) {
9532 			break;
9533 		}
9534 
9535 		pp2 = PP_PAGENEXT_N(pp2, curnpgs);
9536 		if (((dopgs & (pg64k - 1)) == 0) && PP_ISMAPPED_LARGE(pp2)) {
9537 			cursz = fnd_mapping_sz(pp2);
9538 		} else {
9539 			cursz = TTE8K;
9540 		}
9541 	}
9542 }
9543 
9544 /*
9545  * Returns 1 if page(s) can be converted from TNC to cacheable setting,
9546  * returns 0 otherwise. Note that oaddr argument is valid for only
9547  * 8k pages.
9548  */
9549 int
9550 tst_tnc(page_t *pp, pgcnt_t npages)
9551 {
9552 	struct	sf_hment *sfhme;
9553 	struct	hme_blk *hmeblkp;
9554 	tte_t	tte;
9555 	caddr_t	vaddr;
9556 	int	clr_valid = 0;
9557 	int 	color, color1, bcolor;
9558 	int	i, ncolors;
9559 
9560 	ASSERT(pp != NULL);
9561 	ASSERT(!(cache & CACHE_WRITEBACK));
9562 
9563 	if (npages > 1) {
9564 		ncolors = CACHE_NUM_COLOR;
9565 	}
9566 
9567 	for (i = 0; i < npages; i++) {
9568 		ASSERT(sfmmu_mlist_held(pp));
9569 		ASSERT(PP_ISTNC(pp));
9570 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
9571 
9572 		if (PP_ISPNC(pp)) {
9573 			return (0);
9574 		}
9575 
9576 		clr_valid = 0;
9577 		if (PP_ISMAPPED_KPM(pp)) {
9578 			caddr_t kpmvaddr;
9579 
9580 			ASSERT(kpm_enable);
9581 			kpmvaddr = hat_kpm_page2va(pp, 1);
9582 			ASSERT(!(npages > 1 && IS_KPM_ALIAS_RANGE(kpmvaddr)));
9583 			color1 = addr_to_vcolor(kpmvaddr);
9584 			clr_valid = 1;
9585 		}
9586 
9587 		for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9588 			if (IS_PAHME(sfhme))
9589 				continue;
9590 			hmeblkp = sfmmu_hmetohblk(sfhme);
9591 			if (hmeblkp->hblk_xhat_bit)
9592 				continue;
9593 
9594 			sfmmu_copytte(&sfhme->hme_tte, &tte);
9595 			ASSERT(TTE_IS_VALID(&tte));
9596 
9597 			vaddr = tte_to_vaddr(hmeblkp, tte);
9598 			color = addr_to_vcolor(vaddr);
9599 
9600 			if (npages > 1) {
9601 				/*
9602 				 * If there is a big mapping, make sure
9603 				 * 8K mapping is consistent with the big
9604 				 * mapping.
9605 				 */
9606 				bcolor = i % ncolors;
9607 				if (color != bcolor) {
9608 					return (0);
9609 				}
9610 			}
9611 			if (!clr_valid) {
9612 				clr_valid = 1;
9613 				color1 = color;
9614 			}
9615 
9616 			if (color1 != color) {
9617 				return (0);
9618 			}
9619 		}
9620 
9621 		pp = PP_PAGENEXT(pp);
9622 	}
9623 
9624 	return (1);
9625 }
9626 
9627 void
9628 sfmmu_page_cache_array(page_t *pp, int flags, int cache_flush_flag,
9629 	pgcnt_t npages)
9630 {
9631 	kmutex_t *pmtx;
9632 	int i, ncolors, bcolor;
9633 	kpm_hlk_t *kpmp;
9634 	cpuset_t cpuset;
9635 
9636 	ASSERT(pp != NULL);
9637 	ASSERT(!(cache & CACHE_WRITEBACK));
9638 
9639 	kpmp = sfmmu_kpm_kpmp_enter(pp, npages);
9640 	pmtx = sfmmu_page_enter(pp);
9641 
9642 	/*
9643 	 * Fast path caching single unmapped page
9644 	 */
9645 	if (npages == 1 && !PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp) &&
9646 	    flags == HAT_CACHE) {
9647 		PP_CLRTNC(pp);
9648 		PP_CLRPNC(pp);
9649 		sfmmu_page_exit(pmtx);
9650 		sfmmu_kpm_kpmp_exit(kpmp);
9651 		return;
9652 	}
9653 
9654 	/*
9655 	 * We need to capture all cpus in order to change cacheability
9656 	 * because we can't allow one cpu to access the same physical
9657 	 * page using a cacheable and a non-cachebale mapping at the same
9658 	 * time. Since we may end up walking the ism mapping list
9659 	 * have to grab it's lock now since we can't after all the
9660 	 * cpus have been captured.
9661 	 */
9662 	sfmmu_hat_lock_all();
9663 	mutex_enter(&ism_mlist_lock);
9664 	kpreempt_disable();
9665 	cpuset = cpu_ready_set;
9666 	xc_attention(cpuset);
9667 
9668 	if (npages > 1) {
9669 		/*
9670 		 * Make sure all colors are flushed since the
9671 		 * sfmmu_page_cache() only flushes one color-
9672 		 * it does not know big pages.
9673 		 */
9674 		ncolors = CACHE_NUM_COLOR;
9675 		if (flags & HAT_TMPNC) {
9676 			for (i = 0; i < ncolors; i++) {
9677 				sfmmu_cache_flushcolor(i, pp->p_pagenum);
9678 			}
9679 			cache_flush_flag = CACHE_NO_FLUSH;
9680 		}
9681 	}
9682 
9683 	for (i = 0; i < npages; i++) {
9684 
9685 		ASSERT(sfmmu_mlist_held(pp));
9686 
9687 		if (!(flags == HAT_TMPNC && PP_ISTNC(pp))) {
9688 
9689 			if (npages > 1) {
9690 				bcolor = i % ncolors;
9691 			} else {
9692 				bcolor = NO_VCOLOR;
9693 			}
9694 
9695 			sfmmu_page_cache(pp, flags, cache_flush_flag,
9696 			    bcolor);
9697 		}
9698 
9699 		pp = PP_PAGENEXT(pp);
9700 	}
9701 
9702 	xt_sync(cpuset);
9703 	xc_dismissed(cpuset);
9704 	mutex_exit(&ism_mlist_lock);
9705 	sfmmu_hat_unlock_all();
9706 	sfmmu_page_exit(pmtx);
9707 	sfmmu_kpm_kpmp_exit(kpmp);
9708 	kpreempt_enable();
9709 }
9710 
9711 /*
9712  * This function changes the virtual cacheability of all mappings to a
9713  * particular page.  When changing from uncache to cacheable the mappings will
9714  * only be changed if all of them have the same virtual color.
9715  * We need to flush the cache in all cpus.  It is possible that
9716  * a process referenced a page as cacheable but has sinced exited
9717  * and cleared the mapping list.  We still to flush it but have no
9718  * state so all cpus is the only alternative.
9719  */
9720 static void
9721 sfmmu_page_cache(page_t *pp, int flags, int cache_flush_flag, int bcolor)
9722 {
9723 	struct	sf_hment *sfhme;
9724 	struct	hme_blk *hmeblkp;
9725 	sfmmu_t *sfmmup;
9726 	tte_t	tte, ttemod;
9727 	caddr_t	vaddr;
9728 	int	ret, color;
9729 	pfn_t	pfn;
9730 
9731 	color = bcolor;
9732 	pfn = pp->p_pagenum;
9733 
9734 	for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9735 
9736 		if (IS_PAHME(sfhme))
9737 			continue;
9738 		hmeblkp = sfmmu_hmetohblk(sfhme);
9739 
9740 		if (hmeblkp->hblk_xhat_bit)
9741 			continue;
9742 
9743 		sfmmu_copytte(&sfhme->hme_tte, &tte);
9744 		ASSERT(TTE_IS_VALID(&tte));
9745 		vaddr = tte_to_vaddr(hmeblkp, tte);
9746 		color = addr_to_vcolor(vaddr);
9747 
9748 #ifdef DEBUG
9749 		if ((flags & HAT_CACHE) && bcolor != NO_VCOLOR) {
9750 			ASSERT(color == bcolor);
9751 		}
9752 #endif
9753 
9754 		ASSERT(flags != HAT_TMPNC || color == PP_GET_VCOLOR(pp));
9755 
9756 		ttemod = tte;
9757 		if (flags & (HAT_UNCACHE | HAT_TMPNC)) {
9758 			TTE_CLR_VCACHEABLE(&ttemod);
9759 		} else {	/* flags & HAT_CACHE */
9760 			TTE_SET_VCACHEABLE(&ttemod);
9761 		}
9762 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
9763 		if (ret < 0) {
9764 			/*
9765 			 * Since all cpus are captured modifytte should not
9766 			 * fail.
9767 			 */
9768 			panic("sfmmu_page_cache: write to tte failed");
9769 		}
9770 
9771 		sfmmup = hblktosfmmu(hmeblkp);
9772 		if (cache_flush_flag == CACHE_FLUSH) {
9773 			/*
9774 			 * Flush TSBs, TLBs and caches
9775 			 */
9776 			if (hmeblkp->hblk_shared) {
9777 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9778 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9779 				sf_region_t *rgnp;
9780 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9781 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9782 				ASSERT(srdp != NULL);
9783 				rgnp = srdp->srd_hmergnp[rid];
9784 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9785 				    srdp, rgnp, rid);
9786 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9787 				    hmeblkp, 0);
9788 				sfmmu_cache_flush(pfn, addr_to_vcolor(vaddr));
9789 			} else if (sfmmup->sfmmu_ismhat) {
9790 				if (flags & HAT_CACHE) {
9791 					SFMMU_STAT(sf_ism_recache);
9792 				} else {
9793 					SFMMU_STAT(sf_ism_uncache);
9794 				}
9795 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9796 				    pfn, CACHE_FLUSH);
9797 			} else {
9798 				sfmmu_tlbcache_demap(vaddr, sfmmup, hmeblkp,
9799 				    pfn, 0, FLUSH_ALL_CPUS, CACHE_FLUSH, 1);
9800 			}
9801 
9802 			/*
9803 			 * all cache entries belonging to this pfn are
9804 			 * now flushed.
9805 			 */
9806 			cache_flush_flag = CACHE_NO_FLUSH;
9807 		} else {
9808 			/*
9809 			 * Flush only TSBs and TLBs.
9810 			 */
9811 			if (hmeblkp->hblk_shared) {
9812 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9813 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9814 				sf_region_t *rgnp;
9815 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9816 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9817 				ASSERT(srdp != NULL);
9818 				rgnp = srdp->srd_hmergnp[rid];
9819 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9820 				    srdp, rgnp, rid);
9821 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9822 				    hmeblkp, 0);
9823 			} else if (sfmmup->sfmmu_ismhat) {
9824 				if (flags & HAT_CACHE) {
9825 					SFMMU_STAT(sf_ism_recache);
9826 				} else {
9827 					SFMMU_STAT(sf_ism_uncache);
9828 				}
9829 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9830 				    pfn, CACHE_NO_FLUSH);
9831 			} else {
9832 				sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 1);
9833 			}
9834 		}
9835 	}
9836 
9837 	if (PP_ISMAPPED_KPM(pp))
9838 		sfmmu_kpm_page_cache(pp, flags, cache_flush_flag);
9839 
9840 	switch (flags) {
9841 
9842 		default:
9843 			panic("sfmmu_pagecache: unknown flags");
9844 			break;
9845 
9846 		case HAT_CACHE:
9847 			PP_CLRTNC(pp);
9848 			PP_CLRPNC(pp);
9849 			PP_SET_VCOLOR(pp, color);
9850 			break;
9851 
9852 		case HAT_TMPNC:
9853 			PP_SETTNC(pp);
9854 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9855 			break;
9856 
9857 		case HAT_UNCACHE:
9858 			PP_SETPNC(pp);
9859 			PP_CLRTNC(pp);
9860 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9861 			break;
9862 	}
9863 }
9864 #endif	/* VAC */
9865 
9866 
9867 /*
9868  * Wrapper routine used to return a context.
9869  *
9870  * It's the responsibility of the caller to guarantee that the
9871  * process serializes on calls here by taking the HAT lock for
9872  * the hat.
9873  *
9874  */
9875 static void
9876 sfmmu_get_ctx(sfmmu_t *sfmmup)
9877 {
9878 	mmu_ctx_t *mmu_ctxp;
9879 	uint_t pstate_save;
9880 	int ret;
9881 
9882 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9883 	ASSERT(sfmmup != ksfmmup);
9884 
9885 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID)) {
9886 		sfmmu_setup_tsbinfo(sfmmup);
9887 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ALLCTX_INVALID);
9888 	}
9889 
9890 	kpreempt_disable();
9891 
9892 	mmu_ctxp = CPU_MMU_CTXP(CPU);
9893 	ASSERT(mmu_ctxp);
9894 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
9895 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
9896 
9897 	/*
9898 	 * Do a wrap-around if cnum reaches the max # cnum supported by a MMU.
9899 	 */
9900 	if (mmu_ctxp->mmu_cnum == mmu_ctxp->mmu_nctxs)
9901 		sfmmu_ctx_wrap_around(mmu_ctxp, B_TRUE);
9902 
9903 	/*
9904 	 * Let the MMU set up the page sizes to use for
9905 	 * this context in the TLB. Don't program 2nd dtlb for ism hat.
9906 	 */
9907 	if ((&mmu_set_ctx_page_sizes) && (sfmmup->sfmmu_ismhat == 0)) {
9908 		mmu_set_ctx_page_sizes(sfmmup);
9909 	}
9910 
9911 	/*
9912 	 * sfmmu_alloc_ctx and sfmmu_load_mmustate will be performed with
9913 	 * interrupts disabled to prevent race condition with wrap-around
9914 	 * ctx invalidatation. In sun4v, ctx invalidation also involves
9915 	 * a HV call to set the number of TSBs to 0. If interrupts are not
9916 	 * disabled until after sfmmu_load_mmustate is complete TSBs may
9917 	 * become assigned to INVALID_CONTEXT. This is not allowed.
9918 	 */
9919 	pstate_save = sfmmu_disable_intrs();
9920 
9921 	if (sfmmu_alloc_ctx(sfmmup, 1, CPU, SFMMU_PRIVATE) &&
9922 	    sfmmup->sfmmu_scdp != NULL) {
9923 		sf_scd_t *scdp = sfmmup->sfmmu_scdp;
9924 		sfmmu_t *scsfmmup = scdp->scd_sfmmup;
9925 		ret = sfmmu_alloc_ctx(scsfmmup, 1, CPU, SFMMU_SHARED);
9926 		/* debug purpose only */
9927 		ASSERT(!ret || scsfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
9928 		    != INVALID_CONTEXT);
9929 	}
9930 	sfmmu_load_mmustate(sfmmup);
9931 
9932 	sfmmu_enable_intrs(pstate_save);
9933 
9934 	kpreempt_enable();
9935 }
9936 
9937 /*
9938  * When all cnums are used up in a MMU, cnum will wrap around to the
9939  * next generation and start from 2.
9940  */
9941 static void
9942 sfmmu_ctx_wrap_around(mmu_ctx_t *mmu_ctxp, boolean_t reset_cnum)
9943 {
9944 
9945 	/* caller must have disabled the preemption */
9946 	ASSERT(curthread->t_preempt >= 1);
9947 	ASSERT(mmu_ctxp != NULL);
9948 
9949 	/* acquire Per-MMU (PM) spin lock */
9950 	mutex_enter(&mmu_ctxp->mmu_lock);
9951 
9952 	/* re-check to see if wrap-around is needed */
9953 	if (mmu_ctxp->mmu_cnum < mmu_ctxp->mmu_nctxs)
9954 		goto done;
9955 
9956 	SFMMU_MMU_STAT(mmu_wrap_around);
9957 
9958 	/* update gnum */
9959 	ASSERT(mmu_ctxp->mmu_gnum != 0);
9960 	mmu_ctxp->mmu_gnum++;
9961 	if (mmu_ctxp->mmu_gnum == 0 ||
9962 	    mmu_ctxp->mmu_gnum > MAX_SFMMU_GNUM_VAL) {
9963 		cmn_err(CE_PANIC, "mmu_gnum of mmu_ctx 0x%p is out of bound.",
9964 		    (void *)mmu_ctxp);
9965 	}
9966 
9967 	if (mmu_ctxp->mmu_ncpus > 1) {
9968 		cpuset_t cpuset;
9969 
9970 		membar_enter(); /* make sure updated gnum visible */
9971 
9972 		SFMMU_XCALL_STATS(NULL);
9973 
9974 		/* xcall to others on the same MMU to invalidate ctx */
9975 		cpuset = mmu_ctxp->mmu_cpuset;
9976 		ASSERT(CPU_IN_SET(cpuset, CPU->cpu_id) || !reset_cnum);
9977 		CPUSET_DEL(cpuset, CPU->cpu_id);
9978 		CPUSET_AND(cpuset, cpu_ready_set);
9979 
9980 		/*
9981 		 * Pass in INVALID_CONTEXT as the first parameter to
9982 		 * sfmmu_raise_tsb_exception, which invalidates the context
9983 		 * of any process running on the CPUs in the MMU.
9984 		 */
9985 		xt_some(cpuset, sfmmu_raise_tsb_exception,
9986 		    INVALID_CONTEXT, INVALID_CONTEXT);
9987 		xt_sync(cpuset);
9988 
9989 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
9990 	}
9991 
9992 	if (sfmmu_getctx_sec() != INVALID_CONTEXT) {
9993 		sfmmu_setctx_sec(INVALID_CONTEXT);
9994 		sfmmu_clear_utsbinfo();
9995 	}
9996 
9997 	/*
9998 	 * No xcall is needed here. For sun4u systems all CPUs in context
9999 	 * domain share a single physical MMU therefore it's enough to flush
10000 	 * TLB on local CPU. On sun4v systems we use 1 global context
10001 	 * domain and flush all remote TLBs in sfmmu_raise_tsb_exception
10002 	 * handler. Note that vtag_flushall_uctxs() is called
10003 	 * for Ultra II machine, where the equivalent flushall functionality
10004 	 * is implemented in SW, and only user ctx TLB entries are flushed.
10005 	 */
10006 	if (&vtag_flushall_uctxs != NULL) {
10007 		vtag_flushall_uctxs();
10008 	} else {
10009 		vtag_flushall();
10010 	}
10011 
10012 	/* reset mmu cnum, skips cnum 0 and 1 */
10013 	if (reset_cnum == B_TRUE)
10014 		mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
10015 
10016 done:
10017 	mutex_exit(&mmu_ctxp->mmu_lock);
10018 }
10019 
10020 
10021 /*
10022  * For multi-threaded process, set the process context to INVALID_CONTEXT
10023  * so that it faults and reloads the MMU state from TL=0. For single-threaded
10024  * process, we can just load the MMU state directly without having to
10025  * set context invalid. Caller must hold the hat lock since we don't
10026  * acquire it here.
10027  */
10028 static void
10029 sfmmu_sync_mmustate(sfmmu_t *sfmmup)
10030 {
10031 	uint_t cnum;
10032 	uint_t pstate_save;
10033 
10034 	ASSERT(sfmmup != ksfmmup);
10035 	ASSERT(sfmmu_hat_lock_held(sfmmup));
10036 
10037 	kpreempt_disable();
10038 
10039 	/*
10040 	 * We check whether the pass'ed-in sfmmup is the same as the
10041 	 * current running proc. This is to makes sure the current proc
10042 	 * stays single-threaded if it already is.
10043 	 */
10044 	if ((sfmmup == curthread->t_procp->p_as->a_hat) &&
10045 	    (curthread->t_procp->p_lwpcnt == 1)) {
10046 		/* single-thread */
10047 		cnum = sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum;
10048 		if (cnum != INVALID_CONTEXT) {
10049 			uint_t curcnum;
10050 			/*
10051 			 * Disable interrupts to prevent race condition
10052 			 * with sfmmu_ctx_wrap_around ctx invalidation.
10053 			 * In sun4v, ctx invalidation involves setting
10054 			 * TSB to NULL, hence, interrupts should be disabled
10055 			 * untill after sfmmu_load_mmustate is completed.
10056 			 */
10057 			pstate_save = sfmmu_disable_intrs();
10058 			curcnum = sfmmu_getctx_sec();
10059 			if (curcnum == cnum)
10060 				sfmmu_load_mmustate(sfmmup);
10061 			sfmmu_enable_intrs(pstate_save);
10062 			ASSERT(curcnum == cnum || curcnum == INVALID_CONTEXT);
10063 		}
10064 	} else {
10065 		/*
10066 		 * multi-thread
10067 		 * or when sfmmup is not the same as the curproc.
10068 		 */
10069 		sfmmu_invalidate_ctx(sfmmup);
10070 	}
10071 
10072 	kpreempt_enable();
10073 }
10074 
10075 
10076 /*
10077  * Replace the specified TSB with a new TSB.  This function gets called when
10078  * we grow, shrink or swapin a TSB.  When swapping in a TSB (TSB_SWAPIN), the
10079  * TSB_FORCEALLOC flag may be used to force allocation of a minimum-sized TSB
10080  * (8K).
10081  *
10082  * Caller must hold the HAT lock, but should assume any tsb_info
10083  * pointers it has are no longer valid after calling this function.
10084  *
10085  * Return values:
10086  *	TSB_ALLOCFAIL	Failed to allocate a TSB, due to memory constraints
10087  *	TSB_LOSTRACE	HAT is busy, i.e. another thread is already doing
10088  *			something to this tsbinfo/TSB
10089  *	TSB_SUCCESS	Operation succeeded
10090  */
10091 static tsb_replace_rc_t
10092 sfmmu_replace_tsb(sfmmu_t *sfmmup, struct tsb_info *old_tsbinfo, uint_t szc,
10093     hatlock_t *hatlockp, uint_t flags)
10094 {
10095 	struct tsb_info *new_tsbinfo = NULL;
10096 	struct tsb_info *curtsb, *prevtsb;
10097 	uint_t tte_sz_mask;
10098 	int i;
10099 
10100 	ASSERT(sfmmup != ksfmmup);
10101 	ASSERT(sfmmup->sfmmu_ismhat == 0);
10102 	ASSERT(sfmmu_hat_lock_held(sfmmup));
10103 	ASSERT(szc <= tsb_max_growsize);
10104 
10105 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_BUSY))
10106 		return (TSB_LOSTRACE);
10107 
10108 	/*
10109 	 * Find the tsb_info ahead of this one in the list, and
10110 	 * also make sure that the tsb_info passed in really
10111 	 * exists!
10112 	 */
10113 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
10114 	    curtsb != old_tsbinfo && curtsb != NULL;
10115 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
10116 		;
10117 	ASSERT(curtsb != NULL);
10118 
10119 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
10120 		/*
10121 		 * The process is swapped out, so just set the new size
10122 		 * code.  When it swaps back in, we'll allocate a new one
10123 		 * of the new chosen size.
10124 		 */
10125 		curtsb->tsb_szc = szc;
10126 		return (TSB_SUCCESS);
10127 	}
10128 	SFMMU_FLAGS_SET(sfmmup, HAT_BUSY);
10129 
10130 	tte_sz_mask = old_tsbinfo->tsb_ttesz_mask;
10131 
10132 	/*
10133 	 * All initialization is done inside of sfmmu_tsbinfo_alloc().
10134 	 * If we fail to allocate a TSB, exit.
10135 	 *
10136 	 * If tsb grows with new tsb size > 4M and old tsb size < 4M,
10137 	 * then try 4M slab after the initial alloc fails.
10138 	 *
10139 	 * If tsb swapin with tsb size > 4M, then try 4M after the
10140 	 * initial alloc fails.
10141 	 */
10142 	sfmmu_hat_exit(hatlockp);
10143 	if (sfmmu_tsbinfo_alloc(&new_tsbinfo, szc,
10144 	    tte_sz_mask, flags, sfmmup) &&
10145 	    (!(flags & (TSB_GROW | TSB_SWAPIN)) || (szc <= TSB_4M_SZCODE) ||
10146 	    (!(flags & TSB_SWAPIN) &&
10147 	    (old_tsbinfo->tsb_szc >= TSB_4M_SZCODE)) ||
10148 	    sfmmu_tsbinfo_alloc(&new_tsbinfo, TSB_4M_SZCODE,
10149 	    tte_sz_mask, flags, sfmmup))) {
10150 		(void) sfmmu_hat_enter(sfmmup);
10151 		if (!(flags & TSB_SWAPIN))
10152 			SFMMU_STAT(sf_tsb_resize_failures);
10153 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
10154 		return (TSB_ALLOCFAIL);
10155 	}
10156 	(void) sfmmu_hat_enter(sfmmup);
10157 
10158 	/*
10159 	 * Re-check to make sure somebody else didn't muck with us while we
10160 	 * didn't hold the HAT lock.  If the process swapped out, fine, just
10161 	 * exit; this can happen if we try to shrink the TSB from the context
10162 	 * of another process (such as on an ISM unmap), though it is rare.
10163 	 */
10164 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
10165 		SFMMU_STAT(sf_tsb_resize_failures);
10166 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
10167 		sfmmu_hat_exit(hatlockp);
10168 		sfmmu_tsbinfo_free(new_tsbinfo);
10169 		(void) sfmmu_hat_enter(sfmmup);
10170 		return (TSB_LOSTRACE);
10171 	}
10172 
10173 #ifdef	DEBUG
10174 	/* Reverify that the tsb_info still exists.. for debugging only */
10175 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
10176 	    curtsb != old_tsbinfo && curtsb != NULL;
10177 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
10178 		;
10179 	ASSERT(curtsb != NULL);
10180 #endif	/* DEBUG */
10181 
10182 	/*
10183 	 * Quiesce any CPUs running this process on their next TLB miss
10184 	 * so they atomically see the new tsb_info.  We temporarily set the
10185 	 * context to invalid context so new threads that come on processor
10186 	 * after we do the xcall to cpusran will also serialize behind the
10187 	 * HAT lock on TLB miss and will see the new TSB.  Since this short
10188 	 * race with a new thread coming on processor is relatively rare,
10189 	 * this synchronization mechanism should be cheaper than always
10190 	 * pausing all CPUs for the duration of the setup, which is what
10191 	 * the old implementation did.  This is particuarly true if we are
10192 	 * copying a huge chunk of memory around during that window.
10193 	 *
10194 	 * The memory barriers are to make sure things stay consistent
10195 	 * with resume() since it does not hold the HAT lock while
10196 	 * walking the list of tsb_info structures.
10197 	 */
10198 	if ((flags & TSB_SWAPIN) != TSB_SWAPIN) {
10199 		/* The TSB is either growing or shrinking. */
10200 		sfmmu_invalidate_ctx(sfmmup);
10201 	} else {
10202 		/*
10203 		 * It is illegal to swap in TSBs from a process other
10204 		 * than a process being swapped in.  This in turn
10205 		 * implies we do not have a valid MMU context here
10206 		 * since a process needs one to resolve translation
10207 		 * misses.
10208 		 */
10209 		ASSERT(curthread->t_procp->p_as->a_hat == sfmmup);
10210 	}
10211 
10212 #ifdef DEBUG
10213 	ASSERT(max_mmu_ctxdoms > 0);
10214 
10215 	/*
10216 	 * Process should have INVALID_CONTEXT on all MMUs
10217 	 */
10218 	for (i = 0; i < max_mmu_ctxdoms; i++) {
10219 
10220 		ASSERT(sfmmup->sfmmu_ctxs[i].cnum == INVALID_CONTEXT);
10221 	}
10222 #endif
10223 
10224 	new_tsbinfo->tsb_next = old_tsbinfo->tsb_next;
10225 	membar_stst();	/* strict ordering required */
10226 	if (prevtsb)
10227 		prevtsb->tsb_next = new_tsbinfo;
10228 	else
10229 		sfmmup->sfmmu_tsb = new_tsbinfo;
10230 	membar_enter();	/* make sure new TSB globally visible */
10231 
10232 	/*
10233 	 * We need to migrate TSB entries from the old TSB to the new TSB
10234 	 * if tsb_remap_ttes is set and the TSB is growing.
10235 	 */
10236 	if (tsb_remap_ttes && ((flags & TSB_GROW) == TSB_GROW))
10237 		sfmmu_copy_tsb(old_tsbinfo, new_tsbinfo);
10238 
10239 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
10240 
10241 	/*
10242 	 * Drop the HAT lock to free our old tsb_info.
10243 	 */
10244 	sfmmu_hat_exit(hatlockp);
10245 
10246 	if ((flags & TSB_GROW) == TSB_GROW) {
10247 		SFMMU_STAT(sf_tsb_grow);
10248 	} else if ((flags & TSB_SHRINK) == TSB_SHRINK) {
10249 		SFMMU_STAT(sf_tsb_shrink);
10250 	}
10251 
10252 	sfmmu_tsbinfo_free(old_tsbinfo);
10253 
10254 	(void) sfmmu_hat_enter(sfmmup);
10255 	return (TSB_SUCCESS);
10256 }
10257 
10258 /*
10259  * This function will re-program hat pgsz array, and invalidate the
10260  * process' context, forcing the process to switch to another
10261  * context on the next TLB miss, and therefore start using the
10262  * TLB that is reprogrammed for the new page sizes.
10263  */
10264 void
10265 sfmmu_reprog_pgsz_arr(sfmmu_t *sfmmup, uint8_t *tmp_pgsz)
10266 {
10267 	int i;
10268 	hatlock_t *hatlockp = NULL;
10269 
10270 	hatlockp = sfmmu_hat_enter(sfmmup);
10271 	/* USIII+-IV+ optimization, requires hat lock */
10272 	if (tmp_pgsz) {
10273 		for (i = 0; i < mmu_page_sizes; i++)
10274 			sfmmup->sfmmu_pgsz[i] = tmp_pgsz[i];
10275 	}
10276 	SFMMU_STAT(sf_tlb_reprog_pgsz);
10277 
10278 	sfmmu_invalidate_ctx(sfmmup);
10279 
10280 	sfmmu_hat_exit(hatlockp);
10281 }
10282 
10283 /*
10284  * The scd_rttecnt field in the SCD must be updated to take account of the
10285  * regions which it contains.
10286  */
10287 static void
10288 sfmmu_set_scd_rttecnt(sf_srd_t *srdp, sf_scd_t *scdp)
10289 {
10290 	uint_t rid;
10291 	uint_t i, j;
10292 	ulong_t w;
10293 	sf_region_t *rgnp;
10294 
10295 	ASSERT(srdp != NULL);
10296 
10297 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
10298 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
10299 			continue;
10300 		}
10301 
10302 		j = 0;
10303 		while (w) {
10304 			if (!(w & 0x1)) {
10305 				j++;
10306 				w >>= 1;
10307 				continue;
10308 			}
10309 			rid = (i << BT_ULSHIFT) | j;
10310 			j++;
10311 			w >>= 1;
10312 
10313 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
10314 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
10315 			rgnp = srdp->srd_hmergnp[rid];
10316 			ASSERT(rgnp->rgn_refcnt > 0);
10317 			ASSERT(rgnp->rgn_id == rid);
10318 
10319 			scdp->scd_rttecnt[rgnp->rgn_pgszc] +=
10320 			    rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
10321 
10322 			/*
10323 			 * Maintain the tsb0 inflation cnt for the regions
10324 			 * in the SCD.
10325 			 */
10326 			if (rgnp->rgn_pgszc >= TTE4M) {
10327 				scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt +=
10328 				    rgnp->rgn_size >>
10329 				    (TTE_PAGE_SHIFT(TTE8K) + 2);
10330 			}
10331 		}
10332 	}
10333 }
10334 
10335 /*
10336  * This function assumes that there are either four or six supported page
10337  * sizes and at most two programmable TLBs, so we need to decide which
10338  * page sizes are most important and then tell the MMU layer so it
10339  * can adjust the TLB page sizes accordingly (if supported).
10340  *
10341  * If these assumptions change, this function will need to be
10342  * updated to support whatever the new limits are.
10343  *
10344  * The growing flag is nonzero if we are growing the address space,
10345  * and zero if it is shrinking.  This allows us to decide whether
10346  * to grow or shrink our TSB, depending upon available memory
10347  * conditions.
10348  */
10349 static void
10350 sfmmu_check_page_sizes(sfmmu_t *sfmmup, int growing)
10351 {
10352 	uint64_t ttecnt[MMU_PAGE_SIZES];
10353 	uint64_t tte8k_cnt, tte4m_cnt;
10354 	uint8_t i;
10355 	int sectsb_thresh;
10356 
10357 	/*
10358 	 * Kernel threads, processes with small address spaces not using
10359 	 * large pages, and dummy ISM HATs need not apply.
10360 	 */
10361 	if (sfmmup == ksfmmup || sfmmup->sfmmu_ismhat != NULL)
10362 		return;
10363 
10364 	if (!SFMMU_LGPGS_INUSE(sfmmup) &&
10365 	    sfmmup->sfmmu_ttecnt[TTE8K] <= tsb_rss_factor)
10366 		return;
10367 
10368 	for (i = 0; i < mmu_page_sizes; i++) {
10369 		ttecnt[i] = sfmmup->sfmmu_ttecnt[i] +
10370 		    sfmmup->sfmmu_ismttecnt[i];
10371 	}
10372 
10373 	/* Check pagesizes in use, and possibly reprogram DTLB. */
10374 	if (&mmu_check_page_sizes)
10375 		mmu_check_page_sizes(sfmmup, ttecnt);
10376 
10377 	/*
10378 	 * Calculate the number of 8k ttes to represent the span of these
10379 	 * pages.
10380 	 */
10381 	tte8k_cnt = ttecnt[TTE8K] +
10382 	    (ttecnt[TTE64K] << (MMU_PAGESHIFT64K - MMU_PAGESHIFT)) +
10383 	    (ttecnt[TTE512K] << (MMU_PAGESHIFT512K - MMU_PAGESHIFT));
10384 	if (mmu_page_sizes == max_mmu_page_sizes) {
10385 		tte4m_cnt = ttecnt[TTE4M] +
10386 		    (ttecnt[TTE32M] << (MMU_PAGESHIFT32M - MMU_PAGESHIFT4M)) +
10387 		    (ttecnt[TTE256M] << (MMU_PAGESHIFT256M - MMU_PAGESHIFT4M));
10388 	} else {
10389 		tte4m_cnt = ttecnt[TTE4M];
10390 	}
10391 
10392 	/*
10393 	 * Inflate tte8k_cnt to allow for region large page allocation failure.
10394 	 */
10395 	tte8k_cnt += sfmmup->sfmmu_tsb0_4minflcnt;
10396 
10397 	/*
10398 	 * Inflate TSB sizes by a factor of 2 if this process
10399 	 * uses 4M text pages to minimize extra conflict misses
10400 	 * in the first TSB since without counting text pages
10401 	 * 8K TSB may become too small.
10402 	 *
10403 	 * Also double the size of the second TSB to minimize
10404 	 * extra conflict misses due to competition between 4M text pages
10405 	 * and data pages.
10406 	 *
10407 	 * We need to adjust the second TSB allocation threshold by the
10408 	 * inflation factor, since there is no point in creating a second
10409 	 * TSB when we know all the mappings can fit in the I/D TLBs.
10410 	 */
10411 	sectsb_thresh = tsb_sectsb_threshold;
10412 	if (sfmmup->sfmmu_flags & HAT_4MTEXT_FLAG) {
10413 		tte8k_cnt <<= 1;
10414 		tte4m_cnt <<= 1;
10415 		sectsb_thresh <<= 1;
10416 	}
10417 
10418 	/*
10419 	 * Check to see if our TSB is the right size; we may need to
10420 	 * grow or shrink it.  If the process is small, our work is
10421 	 * finished at this point.
10422 	 */
10423 	if (tte8k_cnt <= tsb_rss_factor && tte4m_cnt <= sectsb_thresh) {
10424 		return;
10425 	}
10426 	sfmmu_size_tsb(sfmmup, growing, tte8k_cnt, tte4m_cnt, sectsb_thresh);
10427 }
10428 
10429 static void
10430 sfmmu_size_tsb(sfmmu_t *sfmmup, int growing, uint64_t tte8k_cnt,
10431 	uint64_t tte4m_cnt, int sectsb_thresh)
10432 {
10433 	int tsb_bits;
10434 	uint_t tsb_szc;
10435 	struct tsb_info *tsbinfop;
10436 	hatlock_t *hatlockp = NULL;
10437 
10438 	hatlockp = sfmmu_hat_enter(sfmmup);
10439 	ASSERT(hatlockp != NULL);
10440 	tsbinfop = sfmmup->sfmmu_tsb;
10441 	ASSERT(tsbinfop != NULL);
10442 
10443 	/*
10444 	 * If we're growing, select the size based on RSS.  If we're
10445 	 * shrinking, leave some room so we don't have to turn around and
10446 	 * grow again immediately.
10447 	 */
10448 	if (growing)
10449 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
10450 	else
10451 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt << 1);
10452 
10453 	if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10454 	    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10455 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10456 		    hatlockp, TSB_SHRINK);
10457 	} else if (growing && tsb_szc > tsbinfop->tsb_szc && TSB_OK_GROW()) {
10458 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10459 		    hatlockp, TSB_GROW);
10460 	}
10461 	tsbinfop = sfmmup->sfmmu_tsb;
10462 
10463 	/*
10464 	 * With the TLB and first TSB out of the way, we need to see if
10465 	 * we need a second TSB for 4M pages.  If we managed to reprogram
10466 	 * the TLB page sizes above, the process will start using this new
10467 	 * TSB right away; otherwise, it will start using it on the next
10468 	 * context switch.  Either way, it's no big deal so there's no
10469 	 * synchronization with the trap handlers here unless we grow the
10470 	 * TSB (in which case it's required to prevent using the old one
10471 	 * after it's freed). Note: second tsb is required for 32M/256M
10472 	 * page sizes.
10473 	 */
10474 	if (tte4m_cnt > sectsb_thresh) {
10475 		/*
10476 		 * If we're growing, select the size based on RSS.  If we're
10477 		 * shrinking, leave some room so we don't have to turn
10478 		 * around and grow again immediately.
10479 		 */
10480 		if (growing)
10481 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
10482 		else
10483 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt << 1);
10484 		if (tsbinfop->tsb_next == NULL) {
10485 			struct tsb_info *newtsb;
10486 			int allocflags = SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)?
10487 			    0 : TSB_ALLOC;
10488 
10489 			sfmmu_hat_exit(hatlockp);
10490 
10491 			/*
10492 			 * Try to allocate a TSB for 4[32|256]M pages.  If we
10493 			 * can't get the size we want, retry w/a minimum sized
10494 			 * TSB.  If that still didn't work, give up; we can
10495 			 * still run without one.
10496 			 */
10497 			tsb_bits = (mmu_page_sizes == max_mmu_page_sizes)?
10498 			    TSB4M|TSB32M|TSB256M:TSB4M;
10499 			if ((sfmmu_tsbinfo_alloc(&newtsb, tsb_szc, tsb_bits,
10500 			    allocflags, sfmmup)) &&
10501 			    (tsb_szc <= TSB_4M_SZCODE ||
10502 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
10503 			    tsb_bits, allocflags, sfmmup)) &&
10504 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_MIN_SZCODE,
10505 			    tsb_bits, allocflags, sfmmup)) {
10506 				return;
10507 			}
10508 
10509 			hatlockp = sfmmu_hat_enter(sfmmup);
10510 
10511 			sfmmu_invalidate_ctx(sfmmup);
10512 
10513 			if (sfmmup->sfmmu_tsb->tsb_next == NULL) {
10514 				sfmmup->sfmmu_tsb->tsb_next = newtsb;
10515 				SFMMU_STAT(sf_tsb_sectsb_create);
10516 				sfmmu_hat_exit(hatlockp);
10517 				return;
10518 			} else {
10519 				/*
10520 				 * It's annoying, but possible for us
10521 				 * to get here.. we dropped the HAT lock
10522 				 * because of locking order in the kmem
10523 				 * allocator, and while we were off getting
10524 				 * our memory, some other thread decided to
10525 				 * do us a favor and won the race to get a
10526 				 * second TSB for this process.  Sigh.
10527 				 */
10528 				sfmmu_hat_exit(hatlockp);
10529 				sfmmu_tsbinfo_free(newtsb);
10530 				return;
10531 			}
10532 		}
10533 
10534 		/*
10535 		 * We have a second TSB, see if it's big enough.
10536 		 */
10537 		tsbinfop = tsbinfop->tsb_next;
10538 
10539 		/*
10540 		 * Check to see if our second TSB is the right size;
10541 		 * we may need to grow or shrink it.
10542 		 * To prevent thrashing (e.g. growing the TSB on a
10543 		 * subsequent map operation), only try to shrink if
10544 		 * the TSB reach exceeds twice the virtual address
10545 		 * space size.
10546 		 */
10547 		if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10548 		    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10549 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10550 			    tsb_szc, hatlockp, TSB_SHRINK);
10551 		} else if (growing && tsb_szc > tsbinfop->tsb_szc &&
10552 		    TSB_OK_GROW()) {
10553 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10554 			    tsb_szc, hatlockp, TSB_GROW);
10555 		}
10556 	}
10557 
10558 	sfmmu_hat_exit(hatlockp);
10559 }
10560 
10561 /*
10562  * Free up a sfmmu
10563  * Since the sfmmu is currently embedded in the hat struct we simply zero
10564  * out our fields and free up the ism map blk list if any.
10565  */
10566 static void
10567 sfmmu_free_sfmmu(sfmmu_t *sfmmup)
10568 {
10569 	ism_blk_t	*blkp, *nx_blkp;
10570 #ifdef	DEBUG
10571 	ism_map_t	*map;
10572 	int 		i;
10573 #endif
10574 
10575 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
10576 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
10577 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
10578 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
10579 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
10580 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
10581 	ASSERT(SF_RGNMAP_ISNULL(sfmmup));
10582 
10583 	sfmmup->sfmmu_free = 0;
10584 	sfmmup->sfmmu_ismhat = 0;
10585 
10586 	blkp = sfmmup->sfmmu_iblk;
10587 	sfmmup->sfmmu_iblk = NULL;
10588 
10589 	while (blkp) {
10590 #ifdef	DEBUG
10591 		map = blkp->iblk_maps;
10592 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
10593 			ASSERT(map[i].imap_seg == 0);
10594 			ASSERT(map[i].imap_ismhat == NULL);
10595 			ASSERT(map[i].imap_ment == NULL);
10596 		}
10597 #endif
10598 		nx_blkp = blkp->iblk_next;
10599 		blkp->iblk_next = NULL;
10600 		blkp->iblk_nextpa = (uint64_t)-1;
10601 		kmem_cache_free(ism_blk_cache, blkp);
10602 		blkp = nx_blkp;
10603 	}
10604 }
10605 
10606 /*
10607  * Locking primitves accessed by HATLOCK macros
10608  */
10609 
10610 #define	SFMMU_SPL_MTX	(0x0)
10611 #define	SFMMU_ML_MTX	(0x1)
10612 
10613 #define	SFMMU_MLSPL_MTX(type, pg)	(((type) == SFMMU_SPL_MTX) ? \
10614 					    SPL_HASH(pg) : MLIST_HASH(pg))
10615 
10616 kmutex_t *
10617 sfmmu_page_enter(struct page *pp)
10618 {
10619 	return (sfmmu_mlspl_enter(pp, SFMMU_SPL_MTX));
10620 }
10621 
10622 void
10623 sfmmu_page_exit(kmutex_t *spl)
10624 {
10625 	mutex_exit(spl);
10626 }
10627 
10628 int
10629 sfmmu_page_spl_held(struct page *pp)
10630 {
10631 	return (sfmmu_mlspl_held(pp, SFMMU_SPL_MTX));
10632 }
10633 
10634 kmutex_t *
10635 sfmmu_mlist_enter(struct page *pp)
10636 {
10637 	return (sfmmu_mlspl_enter(pp, SFMMU_ML_MTX));
10638 }
10639 
10640 void
10641 sfmmu_mlist_exit(kmutex_t *mml)
10642 {
10643 	mutex_exit(mml);
10644 }
10645 
10646 int
10647 sfmmu_mlist_held(struct page *pp)
10648 {
10649 
10650 	return (sfmmu_mlspl_held(pp, SFMMU_ML_MTX));
10651 }
10652 
10653 /*
10654  * Common code for sfmmu_mlist_enter() and sfmmu_page_enter().  For
10655  * sfmmu_mlist_enter() case mml_table lock array is used and for
10656  * sfmmu_page_enter() sfmmu_page_lock lock array is used.
10657  *
10658  * The lock is taken on a root page so that it protects an operation on all
10659  * constituent pages of a large page pp belongs to.
10660  *
10661  * The routine takes a lock from the appropriate array. The lock is determined
10662  * by hashing the root page. After taking the lock this routine checks if the
10663  * root page has the same size code that was used to determine the root (i.e
10664  * that root hasn't changed).  If root page has the expected p_szc field we
10665  * have the right lock and it's returned to the caller. If root's p_szc
10666  * decreased we release the lock and retry from the beginning.  This case can
10667  * happen due to hat_page_demote() decreasing p_szc between our load of p_szc
10668  * value and taking the lock. The number of retries due to p_szc decrease is
10669  * limited by the maximum p_szc value. If p_szc is 0 we return the lock
10670  * determined by hashing pp itself.
10671  *
10672  * If our caller doesn't hold a SE_SHARED or SE_EXCL lock on pp it's also
10673  * possible that p_szc can increase. To increase p_szc a thread has to lock
10674  * all constituent pages EXCL and do hat_pageunload() on all of them. All the
10675  * callers that don't hold a page locked recheck if hmeblk through which pp
10676  * was found still maps this pp.  If it doesn't map it anymore returned lock
10677  * is immediately dropped. Therefore if sfmmu_mlspl_enter() hits the case of
10678  * p_szc increase after taking the lock it returns this lock without further
10679  * retries because in this case the caller doesn't care about which lock was
10680  * taken. The caller will drop it right away.
10681  *
10682  * After the routine returns it's guaranteed that hat_page_demote() can't
10683  * change p_szc field of any of constituent pages of a large page pp belongs
10684  * to as long as pp was either locked at least SHARED prior to this call or
10685  * the caller finds that hment that pointed to this pp still references this
10686  * pp (this also assumes that the caller holds hme hash bucket lock so that
10687  * the same pp can't be remapped into the same hmeblk after it was unmapped by
10688  * hat_pageunload()).
10689  */
10690 static kmutex_t *
10691 sfmmu_mlspl_enter(struct page *pp, int type)
10692 {
10693 	kmutex_t	*mtx;
10694 	uint_t		prev_rszc = UINT_MAX;
10695 	page_t		*rootpp;
10696 	uint_t		szc;
10697 	uint_t		rszc;
10698 	uint_t		pszc = pp->p_szc;
10699 
10700 	ASSERT(pp != NULL);
10701 
10702 again:
10703 	if (pszc == 0) {
10704 		mtx = SFMMU_MLSPL_MTX(type, pp);
10705 		mutex_enter(mtx);
10706 		return (mtx);
10707 	}
10708 
10709 	/* The lock lives in the root page */
10710 	rootpp = PP_GROUPLEADER(pp, pszc);
10711 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10712 	mutex_enter(mtx);
10713 
10714 	/*
10715 	 * Return mml in the following 3 cases:
10716 	 *
10717 	 * 1) If pp itself is root since if its p_szc decreased before we took
10718 	 * the lock pp is still the root of smaller szc page. And if its p_szc
10719 	 * increased it doesn't matter what lock we return (see comment in
10720 	 * front of this routine).
10721 	 *
10722 	 * 2) If pp's not root but rootpp is the root of a rootpp->p_szc size
10723 	 * large page we have the right lock since any previous potential
10724 	 * hat_page_demote() is done demoting from greater than current root's
10725 	 * p_szc because hat_page_demote() changes root's p_szc last. No
10726 	 * further hat_page_demote() can start or be in progress since it
10727 	 * would need the same lock we currently hold.
10728 	 *
10729 	 * 3) If rootpp's p_szc increased since previous iteration it doesn't
10730 	 * matter what lock we return (see comment in front of this routine).
10731 	 */
10732 	if (pp == rootpp || (rszc = rootpp->p_szc) == pszc ||
10733 	    rszc >= prev_rszc) {
10734 		return (mtx);
10735 	}
10736 
10737 	/*
10738 	 * hat_page_demote() could have decreased root's p_szc.
10739 	 * In this case pp's p_szc must also be smaller than pszc.
10740 	 * Retry.
10741 	 */
10742 	if (rszc < pszc) {
10743 		szc = pp->p_szc;
10744 		if (szc < pszc) {
10745 			mutex_exit(mtx);
10746 			pszc = szc;
10747 			goto again;
10748 		}
10749 		/*
10750 		 * pp's p_szc increased after it was decreased.
10751 		 * page cannot be mapped. Return current lock. The caller
10752 		 * will drop it right away.
10753 		 */
10754 		return (mtx);
10755 	}
10756 
10757 	/*
10758 	 * root's p_szc is greater than pp's p_szc.
10759 	 * hat_page_demote() is not done with all pages
10760 	 * yet. Wait for it to complete.
10761 	 */
10762 	mutex_exit(mtx);
10763 	rootpp = PP_GROUPLEADER(rootpp, rszc);
10764 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10765 	mutex_enter(mtx);
10766 	mutex_exit(mtx);
10767 	prev_rszc = rszc;
10768 	goto again;
10769 }
10770 
10771 static int
10772 sfmmu_mlspl_held(struct page *pp, int type)
10773 {
10774 	kmutex_t	*mtx;
10775 
10776 	ASSERT(pp != NULL);
10777 	/* The lock lives in the root page */
10778 	pp = PP_PAGEROOT(pp);
10779 	ASSERT(pp != NULL);
10780 
10781 	mtx = SFMMU_MLSPL_MTX(type, pp);
10782 	return (MUTEX_HELD(mtx));
10783 }
10784 
10785 static uint_t
10786 sfmmu_get_free_hblk(struct hme_blk **hmeblkpp, uint_t critical)
10787 {
10788 	struct  hme_blk *hblkp;
10789 
10790 
10791 	if (freehblkp != NULL) {
10792 		mutex_enter(&freehblkp_lock);
10793 		if (freehblkp != NULL) {
10794 			/*
10795 			 * If the current thread is owning hblk_reserve OR
10796 			 * critical request from sfmmu_hblk_steal()
10797 			 * let it succeed even if freehblkcnt is really low.
10798 			 */
10799 			if (freehblkcnt <= HBLK_RESERVE_MIN && !critical) {
10800 				SFMMU_STAT(sf_get_free_throttle);
10801 				mutex_exit(&freehblkp_lock);
10802 				return (0);
10803 			}
10804 			freehblkcnt--;
10805 			*hmeblkpp = freehblkp;
10806 			hblkp = *hmeblkpp;
10807 			freehblkp = hblkp->hblk_next;
10808 			mutex_exit(&freehblkp_lock);
10809 			hblkp->hblk_next = NULL;
10810 			SFMMU_STAT(sf_get_free_success);
10811 
10812 			ASSERT(hblkp->hblk_hmecnt == 0);
10813 			ASSERT(hblkp->hblk_vcnt == 0);
10814 			ASSERT(hblkp->hblk_nextpa == va_to_pa((caddr_t)hblkp));
10815 
10816 			return (1);
10817 		}
10818 		mutex_exit(&freehblkp_lock);
10819 	}
10820 
10821 	/* Check cpu hblk pending queues */
10822 	if ((*hmeblkpp = sfmmu_check_pending_hblks(TTE8K)) != NULL) {
10823 		hblkp = *hmeblkpp;
10824 		hblkp->hblk_next = NULL;
10825 		hblkp->hblk_nextpa = va_to_pa((caddr_t)hblkp);
10826 
10827 		ASSERT(hblkp->hblk_hmecnt == 0);
10828 		ASSERT(hblkp->hblk_vcnt == 0);
10829 
10830 		return (1);
10831 	}
10832 
10833 	SFMMU_STAT(sf_get_free_fail);
10834 	return (0);
10835 }
10836 
10837 static uint_t
10838 sfmmu_put_free_hblk(struct hme_blk *hmeblkp, uint_t critical)
10839 {
10840 	struct  hme_blk *hblkp;
10841 
10842 	ASSERT(hmeblkp->hblk_hmecnt == 0);
10843 	ASSERT(hmeblkp->hblk_vcnt == 0);
10844 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
10845 
10846 	/*
10847 	 * If the current thread is mapping into kernel space,
10848 	 * let it succede even if freehblkcnt is max
10849 	 * so that it will avoid freeing it to kmem.
10850 	 * This will prevent stack overflow due to
10851 	 * possible recursion since kmem_cache_free()
10852 	 * might require creation of a slab which
10853 	 * in turn needs an hmeblk to map that slab;
10854 	 * let's break this vicious chain at the first
10855 	 * opportunity.
10856 	 */
10857 	if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10858 		mutex_enter(&freehblkp_lock);
10859 		if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10860 			SFMMU_STAT(sf_put_free_success);
10861 			freehblkcnt++;
10862 			hmeblkp->hblk_next = freehblkp;
10863 			freehblkp = hmeblkp;
10864 			mutex_exit(&freehblkp_lock);
10865 			return (1);
10866 		}
10867 		mutex_exit(&freehblkp_lock);
10868 	}
10869 
10870 	/*
10871 	 * Bring down freehblkcnt to HBLK_RESERVE_CNT. We are here
10872 	 * only if freehblkcnt is at least HBLK_RESERVE_CNT *and*
10873 	 * we are not in the process of mapping into kernel space.
10874 	 */
10875 	ASSERT(!critical);
10876 	while (freehblkcnt > HBLK_RESERVE_CNT) {
10877 		mutex_enter(&freehblkp_lock);
10878 		if (freehblkcnt > HBLK_RESERVE_CNT) {
10879 			freehblkcnt--;
10880 			hblkp = freehblkp;
10881 			freehblkp = hblkp->hblk_next;
10882 			mutex_exit(&freehblkp_lock);
10883 			ASSERT(get_hblk_cache(hblkp) == sfmmu8_cache);
10884 			kmem_cache_free(sfmmu8_cache, hblkp);
10885 			continue;
10886 		}
10887 		mutex_exit(&freehblkp_lock);
10888 	}
10889 	SFMMU_STAT(sf_put_free_fail);
10890 	return (0);
10891 }
10892 
10893 static void
10894 sfmmu_hblk_swap(struct hme_blk *new)
10895 {
10896 	struct hme_blk *old, *hblkp, *prev;
10897 	uint64_t newpa;
10898 	caddr_t	base, vaddr, endaddr;
10899 	struct hmehash_bucket *hmebp;
10900 	struct sf_hment *osfhme, *nsfhme;
10901 	page_t *pp;
10902 	kmutex_t *pml;
10903 	tte_t tte;
10904 	struct hme_blk *list = NULL;
10905 
10906 #ifdef	DEBUG
10907 	hmeblk_tag		hblktag;
10908 	struct hme_blk		*found;
10909 #endif
10910 	old = HBLK_RESERVE;
10911 	ASSERT(!old->hblk_shared);
10912 
10913 	/*
10914 	 * save pa before bcopy clobbers it
10915 	 */
10916 	newpa = new->hblk_nextpa;
10917 
10918 	base = (caddr_t)get_hblk_base(old);
10919 	endaddr = base + get_hblk_span(old);
10920 
10921 	/*
10922 	 * acquire hash bucket lock.
10923 	 */
10924 	hmebp = sfmmu_tteload_acquire_hashbucket(ksfmmup, base, TTE8K,
10925 	    SFMMU_INVALID_SHMERID);
10926 
10927 	/*
10928 	 * copy contents from old to new
10929 	 */
10930 	bcopy((void *)old, (void *)new, HME8BLK_SZ);
10931 
10932 	/*
10933 	 * add new to hash chain
10934 	 */
10935 	sfmmu_hblk_hash_add(hmebp, new, newpa);
10936 
10937 	/*
10938 	 * search hash chain for hblk_reserve; this needs to be performed
10939 	 * after adding new, otherwise prev won't correspond to the hblk which
10940 	 * is prior to old in hash chain when we call sfmmu_hblk_hash_rm to
10941 	 * remove old later.
10942 	 */
10943 	for (prev = NULL,
10944 	    hblkp = hmebp->hmeblkp; hblkp != NULL && hblkp != old;
10945 	    prev = hblkp, hblkp = hblkp->hblk_next)
10946 		;
10947 
10948 	if (hblkp != old)
10949 		panic("sfmmu_hblk_swap: hblk_reserve not found");
10950 
10951 	/*
10952 	 * p_mapping list is still pointing to hments in hblk_reserve;
10953 	 * fix up p_mapping list so that they point to hments in new.
10954 	 *
10955 	 * Since all these mappings are created by hblk_reserve_thread
10956 	 * on the way and it's using at least one of the buffers from each of
10957 	 * the newly minted slabs, there is no danger of any of these
10958 	 * mappings getting unloaded by another thread.
10959 	 *
10960 	 * tsbmiss could only modify ref/mod bits of hments in old/new.
10961 	 * Since all of these hments hold mappings established by segkmem
10962 	 * and mappings in segkmem are setup with HAT_NOSYNC, ref/mod bits
10963 	 * have no meaning for the mappings in hblk_reserve.  hments in
10964 	 * old and new are identical except for ref/mod bits.
10965 	 */
10966 	for (vaddr = base; vaddr < endaddr; vaddr += TTEBYTES(TTE8K)) {
10967 
10968 		HBLKTOHME(osfhme, old, vaddr);
10969 		sfmmu_copytte(&osfhme->hme_tte, &tte);
10970 
10971 		if (TTE_IS_VALID(&tte)) {
10972 			if ((pp = osfhme->hme_page) == NULL)
10973 				panic("sfmmu_hblk_swap: page not mapped");
10974 
10975 			pml = sfmmu_mlist_enter(pp);
10976 
10977 			if (pp != osfhme->hme_page)
10978 				panic("sfmmu_hblk_swap: mapping changed");
10979 
10980 			HBLKTOHME(nsfhme, new, vaddr);
10981 
10982 			HME_ADD(nsfhme, pp);
10983 			HME_SUB(osfhme, pp);
10984 
10985 			sfmmu_mlist_exit(pml);
10986 		}
10987 	}
10988 
10989 	/*
10990 	 * remove old from hash chain
10991 	 */
10992 	sfmmu_hblk_hash_rm(hmebp, old, prev, &list, 1);
10993 
10994 #ifdef	DEBUG
10995 
10996 	hblktag.htag_id = ksfmmup;
10997 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
10998 	hblktag.htag_bspage = HME_HASH_BSPAGE(base, HME_HASH_SHIFT(TTE8K));
10999 	hblktag.htag_rehash = HME_HASH_REHASH(TTE8K);
11000 	HME_HASH_FAST_SEARCH(hmebp, hblktag, found);
11001 
11002 	if (found != new)
11003 		panic("sfmmu_hblk_swap: new hblk not found");
11004 #endif
11005 
11006 	SFMMU_HASH_UNLOCK(hmebp);
11007 
11008 	/*
11009 	 * Reset hblk_reserve
11010 	 */
11011 	bzero((void *)old, HME8BLK_SZ);
11012 	old->hblk_nextpa = va_to_pa((caddr_t)old);
11013 }
11014 
11015 /*
11016  * Grab the mlist mutex for both pages passed in.
11017  *
11018  * low and high will be returned as pointers to the mutexes for these pages.
11019  * low refers to the mutex residing in the lower bin of the mlist hash, while
11020  * high refers to the mutex residing in the higher bin of the mlist hash.  This
11021  * is due to the locking order restrictions on the same thread grabbing
11022  * multiple mlist mutexes.  The low lock must be acquired before the high lock.
11023  *
11024  * If both pages hash to the same mutex, only grab that single mutex, and
11025  * high will be returned as NULL
11026  * If the pages hash to different bins in the hash, grab the lower addressed
11027  * lock first and then the higher addressed lock in order to follow the locking
11028  * rules involved with the same thread grabbing multiple mlist mutexes.
11029  * low and high will both have non-NULL values.
11030  */
11031 static void
11032 sfmmu_mlist_reloc_enter(struct page *targ, struct page *repl,
11033     kmutex_t **low, kmutex_t **high)
11034 {
11035 	kmutex_t	*mml_targ, *mml_repl;
11036 
11037 	/*
11038 	 * no need to do the dance around szc as in sfmmu_mlist_enter()
11039 	 * because this routine is only called by hat_page_relocate() and all
11040 	 * targ and repl pages are already locked EXCL so szc can't change.
11041 	 */
11042 
11043 	mml_targ = MLIST_HASH(PP_PAGEROOT(targ));
11044 	mml_repl = MLIST_HASH(PP_PAGEROOT(repl));
11045 
11046 	if (mml_targ == mml_repl) {
11047 		*low = mml_targ;
11048 		*high = NULL;
11049 	} else {
11050 		if (mml_targ < mml_repl) {
11051 			*low = mml_targ;
11052 			*high = mml_repl;
11053 		} else {
11054 			*low = mml_repl;
11055 			*high = mml_targ;
11056 		}
11057 	}
11058 
11059 	mutex_enter(*low);
11060 	if (*high)
11061 		mutex_enter(*high);
11062 }
11063 
11064 static void
11065 sfmmu_mlist_reloc_exit(kmutex_t *low, kmutex_t *high)
11066 {
11067 	if (high)
11068 		mutex_exit(high);
11069 	mutex_exit(low);
11070 }
11071 
11072 static hatlock_t *
11073 sfmmu_hat_enter(sfmmu_t *sfmmup)
11074 {
11075 	hatlock_t	*hatlockp;
11076 
11077 	if (sfmmup != ksfmmup) {
11078 		hatlockp = TSB_HASH(sfmmup);
11079 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
11080 		return (hatlockp);
11081 	}
11082 	return (NULL);
11083 }
11084 
11085 static hatlock_t *
11086 sfmmu_hat_tryenter(sfmmu_t *sfmmup)
11087 {
11088 	hatlock_t	*hatlockp;
11089 
11090 	if (sfmmup != ksfmmup) {
11091 		hatlockp = TSB_HASH(sfmmup);
11092 		if (mutex_tryenter(HATLOCK_MUTEXP(hatlockp)) == 0)
11093 			return (NULL);
11094 		return (hatlockp);
11095 	}
11096 	return (NULL);
11097 }
11098 
11099 static void
11100 sfmmu_hat_exit(hatlock_t *hatlockp)
11101 {
11102 	if (hatlockp != NULL)
11103 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
11104 }
11105 
11106 static void
11107 sfmmu_hat_lock_all(void)
11108 {
11109 	int i;
11110 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
11111 		mutex_enter(HATLOCK_MUTEXP(&hat_lock[i]));
11112 }
11113 
11114 static void
11115 sfmmu_hat_unlock_all(void)
11116 {
11117 	int i;
11118 	for (i = SFMMU_NUM_LOCK - 1; i >= 0; i--)
11119 		mutex_exit(HATLOCK_MUTEXP(&hat_lock[i]));
11120 }
11121 
11122 int
11123 sfmmu_hat_lock_held(sfmmu_t *sfmmup)
11124 {
11125 	ASSERT(sfmmup != ksfmmup);
11126 	return (MUTEX_HELD(HATLOCK_MUTEXP(TSB_HASH(sfmmup))));
11127 }
11128 
11129 /*
11130  * Locking primitives to provide consistency between ISM unmap
11131  * and other operations.  Since ISM unmap can take a long time, we
11132  * use HAT_ISMBUSY flag (protected by the hatlock) to avoid creating
11133  * contention on the hatlock buckets while ISM segments are being
11134  * unmapped.  The tradeoff is that the flags don't prevent priority
11135  * inversion from occurring, so we must request kernel priority in
11136  * case we have to sleep to keep from getting buried while holding
11137  * the HAT_ISMBUSY flag set, which in turn could block other kernel
11138  * threads from running (for example, in sfmmu_uvatopfn()).
11139  */
11140 static void
11141 sfmmu_ismhat_enter(sfmmu_t *sfmmup, int hatlock_held)
11142 {
11143 	hatlock_t *hatlockp;
11144 
11145 	THREAD_KPRI_REQUEST();
11146 	if (!hatlock_held)
11147 		hatlockp = sfmmu_hat_enter(sfmmup);
11148 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY))
11149 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
11150 	SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
11151 	if (!hatlock_held)
11152 		sfmmu_hat_exit(hatlockp);
11153 }
11154 
11155 static void
11156 sfmmu_ismhat_exit(sfmmu_t *sfmmup, int hatlock_held)
11157 {
11158 	hatlock_t *hatlockp;
11159 
11160 	if (!hatlock_held)
11161 		hatlockp = sfmmu_hat_enter(sfmmup);
11162 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
11163 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
11164 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11165 	if (!hatlock_held)
11166 		sfmmu_hat_exit(hatlockp);
11167 	THREAD_KPRI_RELEASE();
11168 }
11169 
11170 /*
11171  *
11172  * Algorithm:
11173  *
11174  * (1) if segkmem is not ready, allocate hblk from an array of pre-alloc'ed
11175  *	hblks.
11176  *
11177  * (2) if we are allocating an hblk for mapping a slab in sfmmu_cache,
11178  *
11179  * 		(a) try to return an hblk from reserve pool of free hblks;
11180  *		(b) if the reserve pool is empty, acquire hblk_reserve_lock
11181  *		    and return hblk_reserve.
11182  *
11183  * (3) call kmem_cache_alloc() to allocate hblk;
11184  *
11185  *		(a) if hblk_reserve_lock is held by the current thread,
11186  *		    atomically replace hblk_reserve by the hblk that is
11187  *		    returned by kmem_cache_alloc; release hblk_reserve_lock
11188  *		    and call kmem_cache_alloc() again.
11189  *		(b) if reserve pool is not full, add the hblk that is
11190  *		    returned by kmem_cache_alloc to reserve pool and
11191  *		    call kmem_cache_alloc again.
11192  *
11193  */
11194 static struct hme_blk *
11195 sfmmu_hblk_alloc(sfmmu_t *sfmmup, caddr_t vaddr,
11196 	struct hmehash_bucket *hmebp, uint_t size, hmeblk_tag hblktag,
11197 	uint_t flags, uint_t rid)
11198 {
11199 	struct hme_blk *hmeblkp = NULL;
11200 	struct hme_blk *newhblkp;
11201 	struct hme_blk *shw_hblkp = NULL;
11202 	struct kmem_cache *sfmmu_cache = NULL;
11203 	uint64_t hblkpa;
11204 	ulong_t index;
11205 	uint_t owner;		/* set to 1 if using hblk_reserve */
11206 	uint_t forcefree;
11207 	int sleep;
11208 	sf_srd_t *srdp;
11209 	sf_region_t *rgnp;
11210 
11211 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11212 	ASSERT(hblktag.htag_rid == rid);
11213 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
11214 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11215 	    IS_P2ALIGNED(vaddr, TTEBYTES(size)));
11216 
11217 	/*
11218 	 * If segkmem is not created yet, allocate from static hmeblks
11219 	 * created at the end of startup_modules().  See the block comment
11220 	 * in startup_modules() describing how we estimate the number of
11221 	 * static hmeblks that will be needed during re-map.
11222 	 */
11223 	if (!hblk_alloc_dynamic) {
11224 
11225 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11226 
11227 		if (size == TTE8K) {
11228 			index = nucleus_hblk8.index;
11229 			if (index >= nucleus_hblk8.len) {
11230 				/*
11231 				 * If we panic here, see startup_modules() to
11232 				 * make sure that we are calculating the
11233 				 * number of hblk8's that we need correctly.
11234 				 */
11235 				prom_panic("no nucleus hblk8 to allocate");
11236 			}
11237 			hmeblkp =
11238 			    (struct hme_blk *)&nucleus_hblk8.list[index];
11239 			nucleus_hblk8.index++;
11240 			SFMMU_STAT(sf_hblk8_nalloc);
11241 		} else {
11242 			index = nucleus_hblk1.index;
11243 			if (nucleus_hblk1.index >= nucleus_hblk1.len) {
11244 				/*
11245 				 * If we panic here, see startup_modules().
11246 				 * Most likely you need to update the
11247 				 * calculation of the number of hblk1 elements
11248 				 * that the kernel needs to boot.
11249 				 */
11250 				prom_panic("no nucleus hblk1 to allocate");
11251 			}
11252 			hmeblkp =
11253 			    (struct hme_blk *)&nucleus_hblk1.list[index];
11254 			nucleus_hblk1.index++;
11255 			SFMMU_STAT(sf_hblk1_nalloc);
11256 		}
11257 
11258 		goto hblk_init;
11259 	}
11260 
11261 	SFMMU_HASH_UNLOCK(hmebp);
11262 
11263 	if (sfmmup != KHATID && !SFMMU_IS_SHMERID_VALID(rid)) {
11264 		if (mmu_page_sizes == max_mmu_page_sizes) {
11265 			if (size < TTE256M)
11266 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11267 				    size, flags);
11268 		} else {
11269 			if (size < TTE4M)
11270 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
11271 				    size, flags);
11272 		}
11273 	} else if (SFMMU_IS_SHMERID_VALID(rid)) {
11274 		/*
11275 		 * Shared hmes use per region bitmaps in rgn_hmeflag
11276 		 * rather than shadow hmeblks to keep track of the
11277 		 * mapping sizes which have been allocated for the region.
11278 		 * Here we cleanup old invalid hmeblks with this rid,
11279 		 * which may be left around by pageunload().
11280 		 */
11281 		int ttesz;
11282 		caddr_t va;
11283 		caddr_t	eva = vaddr + TTEBYTES(size);
11284 
11285 		ASSERT(sfmmup != KHATID);
11286 
11287 		srdp = sfmmup->sfmmu_srdp;
11288 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11289 		rgnp = srdp->srd_hmergnp[rid];
11290 		ASSERT(rgnp != NULL && rgnp->rgn_id == rid);
11291 		ASSERT(rgnp->rgn_refcnt != 0);
11292 		ASSERT(size <= rgnp->rgn_pgszc);
11293 
11294 		ttesz = HBLK_MIN_TTESZ;
11295 		do {
11296 			if (!(rgnp->rgn_hmeflags & (0x1 << ttesz))) {
11297 				continue;
11298 			}
11299 
11300 			if (ttesz > size && ttesz != HBLK_MIN_TTESZ) {
11301 				sfmmu_cleanup_rhblk(srdp, vaddr, rid, ttesz);
11302 			} else if (ttesz < size) {
11303 				for (va = vaddr; va < eva;
11304 				    va += TTEBYTES(ttesz)) {
11305 					sfmmu_cleanup_rhblk(srdp, va, rid,
11306 					    ttesz);
11307 				}
11308 			}
11309 		} while (++ttesz <= rgnp->rgn_pgszc);
11310 	}
11311 
11312 fill_hblk:
11313 	owner = (hblk_reserve_thread == curthread) ? 1 : 0;
11314 
11315 	if (owner && size == TTE8K) {
11316 
11317 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11318 		/*
11319 		 * We are really in a tight spot. We already own
11320 		 * hblk_reserve and we need another hblk.  In anticipation
11321 		 * of this kind of scenario, we specifically set aside
11322 		 * HBLK_RESERVE_MIN number of hblks to be used exclusively
11323 		 * by owner of hblk_reserve.
11324 		 */
11325 		SFMMU_STAT(sf_hblk_recurse_cnt);
11326 
11327 		if (!sfmmu_get_free_hblk(&hmeblkp, 1))
11328 			panic("sfmmu_hblk_alloc: reserve list is empty");
11329 
11330 		goto hblk_verify;
11331 	}
11332 
11333 	ASSERT(!owner);
11334 
11335 	if ((flags & HAT_NO_KALLOC) == 0) {
11336 
11337 		sfmmu_cache = ((size == TTE8K) ? sfmmu8_cache : sfmmu1_cache);
11338 		sleep = ((sfmmup == KHATID) ? KM_NOSLEEP : KM_SLEEP);
11339 
11340 		if ((hmeblkp = kmem_cache_alloc(sfmmu_cache, sleep)) == NULL) {
11341 			hmeblkp = sfmmu_hblk_steal(size);
11342 		} else {
11343 			/*
11344 			 * if we are the owner of hblk_reserve,
11345 			 * swap hblk_reserve with hmeblkp and
11346 			 * start a fresh life.  Hope things go
11347 			 * better this time.
11348 			 */
11349 			if (hblk_reserve_thread == curthread) {
11350 				ASSERT(sfmmu_cache == sfmmu8_cache);
11351 				sfmmu_hblk_swap(hmeblkp);
11352 				hblk_reserve_thread = NULL;
11353 				mutex_exit(&hblk_reserve_lock);
11354 				goto fill_hblk;
11355 			}
11356 			/*
11357 			 * let's donate this hblk to our reserve list if
11358 			 * we are not mapping kernel range
11359 			 */
11360 			if (size == TTE8K && sfmmup != KHATID) {
11361 				if (sfmmu_put_free_hblk(hmeblkp, 0))
11362 					goto fill_hblk;
11363 			}
11364 		}
11365 	} else {
11366 		/*
11367 		 * We are here to map the slab in sfmmu8_cache; let's
11368 		 * check if we could tap our reserve list; if successful,
11369 		 * this will avoid the pain of going thru sfmmu_hblk_swap
11370 		 */
11371 		SFMMU_STAT(sf_hblk_slab_cnt);
11372 		if (!sfmmu_get_free_hblk(&hmeblkp, 0)) {
11373 			/*
11374 			 * let's start hblk_reserve dance
11375 			 */
11376 			SFMMU_STAT(sf_hblk_reserve_cnt);
11377 			owner = 1;
11378 			mutex_enter(&hblk_reserve_lock);
11379 			hmeblkp = HBLK_RESERVE;
11380 			hblk_reserve_thread = curthread;
11381 		}
11382 	}
11383 
11384 hblk_verify:
11385 	ASSERT(hmeblkp != NULL);
11386 	set_hblk_sz(hmeblkp, size);
11387 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
11388 	SFMMU_HASH_LOCK(hmebp);
11389 	HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11390 	if (newhblkp != NULL) {
11391 		SFMMU_HASH_UNLOCK(hmebp);
11392 		if (hmeblkp != HBLK_RESERVE) {
11393 			/*
11394 			 * This is really tricky!
11395 			 *
11396 			 * vmem_alloc(vmem_seg_arena)
11397 			 *  vmem_alloc(vmem_internal_arena)
11398 			 *   segkmem_alloc(heap_arena)
11399 			 *    vmem_alloc(heap_arena)
11400 			 *    page_create()
11401 			 *    hat_memload()
11402 			 *	kmem_cache_free()
11403 			 *	 kmem_cache_alloc()
11404 			 *	  kmem_slab_create()
11405 			 *	   vmem_alloc(kmem_internal_arena)
11406 			 *	    segkmem_alloc(heap_arena)
11407 			 *		vmem_alloc(heap_arena)
11408 			 *		page_create()
11409 			 *		hat_memload()
11410 			 *		  kmem_cache_free()
11411 			 *		...
11412 			 *
11413 			 * Thus, hat_memload() could call kmem_cache_free
11414 			 * for enough number of times that we could easily
11415 			 * hit the bottom of the stack or run out of reserve
11416 			 * list of vmem_seg structs.  So, we must donate
11417 			 * this hblk to reserve list if it's allocated
11418 			 * from sfmmu8_cache *and* mapping kernel range.
11419 			 * We don't need to worry about freeing hmeblk1's
11420 			 * to kmem since they don't map any kmem slabs.
11421 			 *
11422 			 * Note: When segkmem supports largepages, we must
11423 			 * free hmeblk1's to reserve list as well.
11424 			 */
11425 			forcefree = (sfmmup == KHATID) ? 1 : 0;
11426 			if (size == TTE8K &&
11427 			    sfmmu_put_free_hblk(hmeblkp, forcefree)) {
11428 				goto re_verify;
11429 			}
11430 			ASSERT(sfmmup != KHATID);
11431 			kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
11432 		} else {
11433 			/*
11434 			 * Hey! we don't need hblk_reserve any more.
11435 			 */
11436 			ASSERT(owner);
11437 			hblk_reserve_thread = NULL;
11438 			mutex_exit(&hblk_reserve_lock);
11439 			owner = 0;
11440 		}
11441 re_verify:
11442 		/*
11443 		 * let's check if the goodies are still present
11444 		 */
11445 		SFMMU_HASH_LOCK(hmebp);
11446 		HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11447 		if (newhblkp != NULL) {
11448 			/*
11449 			 * return newhblkp if it's not hblk_reserve;
11450 			 * if newhblkp is hblk_reserve, return it
11451 			 * _only if_ we are the owner of hblk_reserve.
11452 			 */
11453 			if (newhblkp != HBLK_RESERVE || owner) {
11454 				ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11455 				    newhblkp->hblk_shared);
11456 				ASSERT(SFMMU_IS_SHMERID_VALID(rid) ||
11457 				    !newhblkp->hblk_shared);
11458 				return (newhblkp);
11459 			} else {
11460 				/*
11461 				 * we just hit hblk_reserve in the hash and
11462 				 * we are not the owner of that;
11463 				 *
11464 				 * block until hblk_reserve_thread completes
11465 				 * swapping hblk_reserve and try the dance
11466 				 * once again.
11467 				 */
11468 				SFMMU_HASH_UNLOCK(hmebp);
11469 				mutex_enter(&hblk_reserve_lock);
11470 				mutex_exit(&hblk_reserve_lock);
11471 				SFMMU_STAT(sf_hblk_reserve_hit);
11472 				goto fill_hblk;
11473 			}
11474 		} else {
11475 			/*
11476 			 * it's no more! try the dance once again.
11477 			 */
11478 			SFMMU_HASH_UNLOCK(hmebp);
11479 			goto fill_hblk;
11480 		}
11481 	}
11482 
11483 hblk_init:
11484 	if (SFMMU_IS_SHMERID_VALID(rid)) {
11485 		uint16_t tteflag = 0x1 <<
11486 		    ((size < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ : size);
11487 
11488 		if (!(rgnp->rgn_hmeflags & tteflag)) {
11489 			atomic_or_16(&rgnp->rgn_hmeflags, tteflag);
11490 		}
11491 		hmeblkp->hblk_shared = 1;
11492 	} else {
11493 		hmeblkp->hblk_shared = 0;
11494 	}
11495 	set_hblk_sz(hmeblkp, size);
11496 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11497 	hmeblkp->hblk_next = (struct hme_blk *)NULL;
11498 	hmeblkp->hblk_tag = hblktag;
11499 	hmeblkp->hblk_shadow = shw_hblkp;
11500 	hblkpa = hmeblkp->hblk_nextpa;
11501 	hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
11502 
11503 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
11504 	ASSERT(get_hblk_span(hmeblkp) == HMEBLK_SPAN(size));
11505 	ASSERT(hmeblkp->hblk_hmecnt == 0);
11506 	ASSERT(hmeblkp->hblk_vcnt == 0);
11507 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11508 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
11509 	sfmmu_hblk_hash_add(hmebp, hmeblkp, hblkpa);
11510 	return (hmeblkp);
11511 }
11512 
11513 /*
11514  * This function cleans up the hme_blk and returns it to the free list.
11515  */
11516 /* ARGSUSED */
11517 static void
11518 sfmmu_hblk_free(struct hme_blk **listp)
11519 {
11520 	struct hme_blk *hmeblkp, *next_hmeblkp;
11521 	int		size;
11522 	uint_t		critical;
11523 	uint64_t	hblkpa;
11524 
11525 	ASSERT(*listp != NULL);
11526 
11527 	hmeblkp = *listp;
11528 	while (hmeblkp != NULL) {
11529 		next_hmeblkp = hmeblkp->hblk_next;
11530 		ASSERT(!hmeblkp->hblk_hmecnt);
11531 		ASSERT(!hmeblkp->hblk_vcnt);
11532 		ASSERT(!hmeblkp->hblk_lckcnt);
11533 		ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
11534 		ASSERT(hmeblkp->hblk_shared == 0);
11535 		ASSERT(hmeblkp->hblk_shw_bit == 0);
11536 		ASSERT(hmeblkp->hblk_shadow == NULL);
11537 
11538 		hblkpa = va_to_pa((caddr_t)hmeblkp);
11539 		ASSERT(hblkpa != (uint64_t)-1);
11540 		critical = (hblktosfmmu(hmeblkp) == KHATID) ? 1 : 0;
11541 
11542 		size = get_hblk_ttesz(hmeblkp);
11543 		hmeblkp->hblk_next = NULL;
11544 		hmeblkp->hblk_nextpa = hblkpa;
11545 
11546 		if (hmeblkp->hblk_nuc_bit == 0) {
11547 
11548 			if (size != TTE8K ||
11549 			    !sfmmu_put_free_hblk(hmeblkp, critical))
11550 				kmem_cache_free(get_hblk_cache(hmeblkp),
11551 				    hmeblkp);
11552 		}
11553 		hmeblkp = next_hmeblkp;
11554 	}
11555 }
11556 
11557 #define	BUCKETS_TO_SEARCH_BEFORE_UNLOAD	30
11558 #define	SFMMU_HBLK_STEAL_THRESHOLD 5
11559 
11560 static uint_t sfmmu_hblk_steal_twice;
11561 static uint_t sfmmu_hblk_steal_count, sfmmu_hblk_steal_unload_count;
11562 
11563 /*
11564  * Steal a hmeblk from user or kernel hme hash lists.
11565  * For 8K tte grab one from reserve pool (freehblkp) before proceeding to
11566  * steal and if we fail to steal after SFMMU_HBLK_STEAL_THRESHOLD attempts
11567  * tap into critical reserve of freehblkp.
11568  * Note: We remain looping in this routine until we find one.
11569  */
11570 static struct hme_blk *
11571 sfmmu_hblk_steal(int size)
11572 {
11573 	static struct hmehash_bucket *uhmehash_steal_hand = NULL;
11574 	struct hmehash_bucket *hmebp;
11575 	struct hme_blk *hmeblkp = NULL, *pr_hblk;
11576 	uint64_t hblkpa;
11577 	int i;
11578 	uint_t loop_cnt = 0, critical;
11579 
11580 	for (;;) {
11581 		/* Check cpu hblk pending queues */
11582 		if ((hmeblkp = sfmmu_check_pending_hblks(size)) != NULL) {
11583 			hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
11584 			ASSERT(hmeblkp->hblk_hmecnt == 0);
11585 			ASSERT(hmeblkp->hblk_vcnt == 0);
11586 			return (hmeblkp);
11587 		}
11588 
11589 		if (size == TTE8K) {
11590 			critical =
11591 			    (++loop_cnt > SFMMU_HBLK_STEAL_THRESHOLD) ? 1 : 0;
11592 			if (sfmmu_get_free_hblk(&hmeblkp, critical))
11593 				return (hmeblkp);
11594 		}
11595 
11596 		hmebp = (uhmehash_steal_hand == NULL) ? uhme_hash :
11597 		    uhmehash_steal_hand;
11598 		ASSERT(hmebp >= uhme_hash && hmebp <= &uhme_hash[UHMEHASH_SZ]);
11599 
11600 		for (i = 0; hmeblkp == NULL && i <= UHMEHASH_SZ +
11601 		    BUCKETS_TO_SEARCH_BEFORE_UNLOAD; i++) {
11602 			SFMMU_HASH_LOCK(hmebp);
11603 			hmeblkp = hmebp->hmeblkp;
11604 			hblkpa = hmebp->hmeh_nextpa;
11605 			pr_hblk = NULL;
11606 			while (hmeblkp) {
11607 				/*
11608 				 * check if it is a hmeblk that is not locked
11609 				 * and not shared. skip shadow hmeblks with
11610 				 * shadow_mask set i.e valid count non zero.
11611 				 */
11612 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11613 				    (hmeblkp->hblk_shw_bit == 0 ||
11614 				    hmeblkp->hblk_vcnt == 0) &&
11615 				    (hmeblkp->hblk_lckcnt == 0)) {
11616 					/*
11617 					 * there is a high probability that we
11618 					 * will find a free one. search some
11619 					 * buckets for a free hmeblk initially
11620 					 * before unloading a valid hmeblk.
11621 					 */
11622 					if ((hmeblkp->hblk_vcnt == 0 &&
11623 					    hmeblkp->hblk_hmecnt == 0) || (i >=
11624 					    BUCKETS_TO_SEARCH_BEFORE_UNLOAD)) {
11625 						if (sfmmu_steal_this_hblk(hmebp,
11626 						    hmeblkp, hblkpa, pr_hblk)) {
11627 							/*
11628 							 * Hblk is unloaded
11629 							 * successfully
11630 							 */
11631 							break;
11632 						}
11633 					}
11634 				}
11635 				pr_hblk = hmeblkp;
11636 				hblkpa = hmeblkp->hblk_nextpa;
11637 				hmeblkp = hmeblkp->hblk_next;
11638 			}
11639 
11640 			SFMMU_HASH_UNLOCK(hmebp);
11641 			if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
11642 				hmebp = uhme_hash;
11643 		}
11644 		uhmehash_steal_hand = hmebp;
11645 
11646 		if (hmeblkp != NULL)
11647 			break;
11648 
11649 		/*
11650 		 * in the worst case, look for a free one in the kernel
11651 		 * hash table.
11652 		 */
11653 		for (i = 0, hmebp = khme_hash; i <= KHMEHASH_SZ; i++) {
11654 			SFMMU_HASH_LOCK(hmebp);
11655 			hmeblkp = hmebp->hmeblkp;
11656 			hblkpa = hmebp->hmeh_nextpa;
11657 			pr_hblk = NULL;
11658 			while (hmeblkp) {
11659 				/*
11660 				 * check if it is free hmeblk
11661 				 */
11662 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11663 				    (hmeblkp->hblk_lckcnt == 0) &&
11664 				    (hmeblkp->hblk_vcnt == 0) &&
11665 				    (hmeblkp->hblk_hmecnt == 0)) {
11666 					if (sfmmu_steal_this_hblk(hmebp,
11667 					    hmeblkp, hblkpa, pr_hblk)) {
11668 						break;
11669 					} else {
11670 						/*
11671 						 * Cannot fail since we have
11672 						 * hash lock.
11673 						 */
11674 						panic("fail to steal?");
11675 					}
11676 				}
11677 
11678 				pr_hblk = hmeblkp;
11679 				hblkpa = hmeblkp->hblk_nextpa;
11680 				hmeblkp = hmeblkp->hblk_next;
11681 			}
11682 
11683 			SFMMU_HASH_UNLOCK(hmebp);
11684 			if (hmebp++ == &khme_hash[KHMEHASH_SZ])
11685 				hmebp = khme_hash;
11686 		}
11687 
11688 		if (hmeblkp != NULL)
11689 			break;
11690 		sfmmu_hblk_steal_twice++;
11691 	}
11692 	return (hmeblkp);
11693 }
11694 
11695 /*
11696  * This routine does real work to prepare a hblk to be "stolen" by
11697  * unloading the mappings, updating shadow counts ....
11698  * It returns 1 if the block is ready to be reused (stolen), or 0
11699  * means the block cannot be stolen yet- pageunload is still working
11700  * on this hblk.
11701  */
11702 static int
11703 sfmmu_steal_this_hblk(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
11704 	uint64_t hblkpa, struct hme_blk *pr_hblk)
11705 {
11706 	int shw_size, vshift;
11707 	struct hme_blk *shw_hblkp;
11708 	caddr_t vaddr;
11709 	uint_t shw_mask, newshw_mask;
11710 	struct hme_blk *list = NULL;
11711 
11712 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11713 
11714 	/*
11715 	 * check if the hmeblk is free, unload if necessary
11716 	 */
11717 	if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11718 		sfmmu_t *sfmmup;
11719 		demap_range_t dmr;
11720 
11721 		sfmmup = hblktosfmmu(hmeblkp);
11722 		if (hmeblkp->hblk_shared || sfmmup->sfmmu_ismhat) {
11723 			return (0);
11724 		}
11725 		DEMAP_RANGE_INIT(sfmmup, &dmr);
11726 		(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
11727 		    (caddr_t)get_hblk_base(hmeblkp),
11728 		    get_hblk_endaddr(hmeblkp), &dmr, HAT_UNLOAD);
11729 		DEMAP_RANGE_FLUSH(&dmr);
11730 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11731 			/*
11732 			 * Pageunload is working on the same hblk.
11733 			 */
11734 			return (0);
11735 		}
11736 
11737 		sfmmu_hblk_steal_unload_count++;
11738 	}
11739 
11740 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11741 	ASSERT(hmeblkp->hblk_vcnt == 0 && hmeblkp->hblk_hmecnt == 0);
11742 
11743 	sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk, &list, 1);
11744 	hmeblkp->hblk_nextpa = hblkpa;
11745 
11746 	shw_hblkp = hmeblkp->hblk_shadow;
11747 	if (shw_hblkp) {
11748 		ASSERT(!hmeblkp->hblk_shared);
11749 		shw_size = get_hblk_ttesz(shw_hblkp);
11750 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11751 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
11752 		ASSERT(vshift < 8);
11753 		/*
11754 		 * Atomically clear shadow mask bit
11755 		 */
11756 		do {
11757 			shw_mask = shw_hblkp->hblk_shw_mask;
11758 			ASSERT(shw_mask & (1 << vshift));
11759 			newshw_mask = shw_mask & ~(1 << vshift);
11760 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
11761 			    shw_mask, newshw_mask);
11762 		} while (newshw_mask != shw_mask);
11763 		hmeblkp->hblk_shadow = NULL;
11764 	}
11765 
11766 	/*
11767 	 * remove shadow bit if we are stealing an unused shadow hmeblk.
11768 	 * sfmmu_hblk_alloc needs it that way, will set shadow bit later if
11769 	 * we are indeed allocating a shadow hmeblk.
11770 	 */
11771 	hmeblkp->hblk_shw_bit = 0;
11772 
11773 	if (hmeblkp->hblk_shared) {
11774 		sf_srd_t	*srdp;
11775 		sf_region_t	*rgnp;
11776 		uint_t		rid;
11777 
11778 		srdp = hblktosrd(hmeblkp);
11779 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11780 		rid = hmeblkp->hblk_tag.htag_rid;
11781 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11782 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11783 		rgnp = srdp->srd_hmergnp[rid];
11784 		ASSERT(rgnp != NULL);
11785 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
11786 		hmeblkp->hblk_shared = 0;
11787 	}
11788 
11789 	sfmmu_hblk_steal_count++;
11790 	SFMMU_STAT(sf_steal_count);
11791 
11792 	return (1);
11793 }
11794 
11795 struct hme_blk *
11796 sfmmu_hmetohblk(struct sf_hment *sfhme)
11797 {
11798 	struct hme_blk *hmeblkp;
11799 	struct sf_hment *sfhme0;
11800 	struct hme_blk *hblk_dummy = 0;
11801 
11802 	/*
11803 	 * No dummy sf_hments, please.
11804 	 */
11805 	ASSERT(sfhme->hme_tte.ll != 0);
11806 
11807 	sfhme0 = sfhme - sfhme->hme_tte.tte_hmenum;
11808 	hmeblkp = (struct hme_blk *)((uintptr_t)sfhme0 -
11809 	    (uintptr_t)&hblk_dummy->hblk_hme[0]);
11810 
11811 	return (hmeblkp);
11812 }
11813 
11814 /*
11815  * On swapin, get appropriately sized TSB(s) and clear the HAT_SWAPPED flag.
11816  * If we can't get appropriately sized TSB(s), try for 8K TSB(s) using
11817  * KM_SLEEP allocation.
11818  *
11819  * Return 0 on success, -1 otherwise.
11820  */
11821 static void
11822 sfmmu_tsb_swapin(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11823 {
11824 	struct tsb_info *tsbinfop, *next;
11825 	tsb_replace_rc_t rc;
11826 	boolean_t gotfirst = B_FALSE;
11827 
11828 	ASSERT(sfmmup != ksfmmup);
11829 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11830 
11831 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPIN)) {
11832 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
11833 	}
11834 
11835 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11836 		SFMMU_FLAGS_SET(sfmmup, HAT_SWAPIN);
11837 	} else {
11838 		return;
11839 	}
11840 
11841 	ASSERT(sfmmup->sfmmu_tsb != NULL);
11842 
11843 	/*
11844 	 * Loop over all tsbinfo's replacing them with ones that actually have
11845 	 * a TSB.  If any of the replacements ever fail, bail out of the loop.
11846 	 */
11847 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL; tsbinfop = next) {
11848 		ASSERT(tsbinfop->tsb_flags & TSB_SWAPPED);
11849 		next = tsbinfop->tsb_next;
11850 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, tsbinfop->tsb_szc,
11851 		    hatlockp, TSB_SWAPIN);
11852 		if (rc != TSB_SUCCESS) {
11853 			break;
11854 		}
11855 		gotfirst = B_TRUE;
11856 	}
11857 
11858 	switch (rc) {
11859 	case TSB_SUCCESS:
11860 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11861 		cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11862 		return;
11863 	case TSB_LOSTRACE:
11864 		break;
11865 	case TSB_ALLOCFAIL:
11866 		break;
11867 	default:
11868 		panic("sfmmu_replace_tsb returned unrecognized failure code "
11869 		    "%d", rc);
11870 	}
11871 
11872 	/*
11873 	 * In this case, we failed to get one of our TSBs.  If we failed to
11874 	 * get the first TSB, get one of minimum size (8KB).  Walk the list
11875 	 * and throw away the tsbinfos, starting where the allocation failed;
11876 	 * we can get by with just one TSB as long as we don't leave the
11877 	 * SWAPPED tsbinfo structures lying around.
11878 	 */
11879 	tsbinfop = sfmmup->sfmmu_tsb;
11880 	next = tsbinfop->tsb_next;
11881 	tsbinfop->tsb_next = NULL;
11882 
11883 	sfmmu_hat_exit(hatlockp);
11884 	for (tsbinfop = next; tsbinfop != NULL; tsbinfop = next) {
11885 		next = tsbinfop->tsb_next;
11886 		sfmmu_tsbinfo_free(tsbinfop);
11887 	}
11888 	hatlockp = sfmmu_hat_enter(sfmmup);
11889 
11890 	/*
11891 	 * If we don't have any TSBs, get a single 8K TSB for 8K, 64K and 512K
11892 	 * pages.
11893 	 */
11894 	if (!gotfirst) {
11895 		tsbinfop = sfmmup->sfmmu_tsb;
11896 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, TSB_MIN_SZCODE,
11897 		    hatlockp, TSB_SWAPIN | TSB_FORCEALLOC);
11898 		ASSERT(rc == TSB_SUCCESS);
11899 	}
11900 
11901 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11902 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11903 }
11904 
11905 static int
11906 sfmmu_is_rgnva(sf_srd_t *srdp, caddr_t addr, ulong_t w, ulong_t bmw)
11907 {
11908 	ulong_t bix = 0;
11909 	uint_t rid;
11910 	sf_region_t *rgnp;
11911 
11912 	ASSERT(srdp != NULL);
11913 	ASSERT(srdp->srd_refcnt != 0);
11914 
11915 	w <<= BT_ULSHIFT;
11916 	while (bmw) {
11917 		if (!(bmw & 0x1)) {
11918 			bix++;
11919 			bmw >>= 1;
11920 			continue;
11921 		}
11922 		rid = w | bix;
11923 		rgnp = srdp->srd_hmergnp[rid];
11924 		ASSERT(rgnp->rgn_refcnt > 0);
11925 		ASSERT(rgnp->rgn_id == rid);
11926 		if (addr < rgnp->rgn_saddr ||
11927 		    addr >= (rgnp->rgn_saddr + rgnp->rgn_size)) {
11928 			bix++;
11929 			bmw >>= 1;
11930 		} else {
11931 			return (1);
11932 		}
11933 	}
11934 	return (0);
11935 }
11936 
11937 /*
11938  * Handle exceptions for low level tsb_handler.
11939  *
11940  * There are many scenarios that could land us here:
11941  *
11942  * If the context is invalid we land here. The context can be invalid
11943  * for 3 reasons: 1) we couldn't allocate a new context and now need to
11944  * perform a wrap around operation in order to allocate a new context.
11945  * 2) Context was invalidated to change pagesize programming 3) ISMs or
11946  * TSBs configuration is changeing for this process and we are forced into
11947  * here to do a syncronization operation. If the context is valid we can
11948  * be here from window trap hanlder. In this case just call trap to handle
11949  * the fault.
11950  *
11951  * Note that the process will run in INVALID_CONTEXT before
11952  * faulting into here and subsequently loading the MMU registers
11953  * (including the TSB base register) associated with this process.
11954  * For this reason, the trap handlers must all test for
11955  * INVALID_CONTEXT before attempting to access any registers other
11956  * than the context registers.
11957  */
11958 void
11959 sfmmu_tsbmiss_exception(struct regs *rp, uintptr_t tagaccess, uint_t traptype)
11960 {
11961 	sfmmu_t *sfmmup, *shsfmmup;
11962 	uint_t ctxtype;
11963 	klwp_id_t lwp;
11964 	char lwp_save_state;
11965 	hatlock_t *hatlockp, *shatlockp;
11966 	struct tsb_info *tsbinfop;
11967 	struct tsbmiss *tsbmp;
11968 	sf_scd_t *scdp;
11969 
11970 	SFMMU_STAT(sf_tsb_exceptions);
11971 	SFMMU_MMU_STAT(mmu_tsb_exceptions);
11972 	sfmmup = astosfmmu(curthread->t_procp->p_as);
11973 	/*
11974 	 * note that in sun4u, tagacces register contains ctxnum
11975 	 * while sun4v passes ctxtype in the tagaccess register.
11976 	 */
11977 	ctxtype = tagaccess & TAGACC_CTX_MASK;
11978 
11979 	ASSERT(sfmmup != ksfmmup && ctxtype != KCONTEXT);
11980 	ASSERT(sfmmup->sfmmu_ismhat == 0);
11981 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED) ||
11982 	    ctxtype == INVALID_CONTEXT);
11983 
11984 	if (ctxtype != INVALID_CONTEXT && traptype != T_DATA_PROT) {
11985 		/*
11986 		 * We may land here because shme bitmap and pagesize
11987 		 * flags are updated lazily in tsbmiss area on other cpus.
11988 		 * If we detect here that tsbmiss area is out of sync with
11989 		 * sfmmu update it and retry the trapped instruction.
11990 		 * Otherwise call trap().
11991 		 */
11992 		int ret = 0;
11993 		uchar_t tteflag_mask = (1 << TTE64K) | (1 << TTE8K);
11994 		caddr_t addr = (caddr_t)(tagaccess & TAGACC_VADDR_MASK);
11995 
11996 		/*
11997 		 * Must set lwp state to LWP_SYS before
11998 		 * trying to acquire any adaptive lock
11999 		 */
12000 		lwp = ttolwp(curthread);
12001 		ASSERT(lwp);
12002 		lwp_save_state = lwp->lwp_state;
12003 		lwp->lwp_state = LWP_SYS;
12004 
12005 		hatlockp = sfmmu_hat_enter(sfmmup);
12006 		kpreempt_disable();
12007 		tsbmp = &tsbmiss_area[CPU->cpu_id];
12008 		ASSERT(sfmmup == tsbmp->usfmmup);
12009 		if (((tsbmp->uhat_tteflags ^ sfmmup->sfmmu_tteflags) &
12010 		    ~tteflag_mask) ||
12011 		    ((tsbmp->uhat_rtteflags ^  sfmmup->sfmmu_rtteflags) &
12012 		    ~tteflag_mask)) {
12013 			tsbmp->uhat_tteflags = sfmmup->sfmmu_tteflags;
12014 			tsbmp->uhat_rtteflags = sfmmup->sfmmu_rtteflags;
12015 			ret = 1;
12016 		}
12017 		if (sfmmup->sfmmu_srdp != NULL) {
12018 			ulong_t *sm = sfmmup->sfmmu_hmeregion_map.bitmap;
12019 			ulong_t *tm = tsbmp->shmermap;
12020 			ulong_t i;
12021 			for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
12022 				ulong_t d = tm[i] ^ sm[i];
12023 				if (d) {
12024 					if (d & sm[i]) {
12025 						if (!ret && sfmmu_is_rgnva(
12026 						    sfmmup->sfmmu_srdp,
12027 						    addr, i, d & sm[i])) {
12028 							ret = 1;
12029 						}
12030 					}
12031 					tm[i] = sm[i];
12032 				}
12033 			}
12034 		}
12035 		kpreempt_enable();
12036 		sfmmu_hat_exit(hatlockp);
12037 		lwp->lwp_state = lwp_save_state;
12038 		if (ret) {
12039 			return;
12040 		}
12041 	} else if (ctxtype == INVALID_CONTEXT) {
12042 		/*
12043 		 * First, make sure we come out of here with a valid ctx,
12044 		 * since if we don't get one we'll simply loop on the
12045 		 * faulting instruction.
12046 		 *
12047 		 * If the ISM mappings are changing, the TSB is relocated,
12048 		 * the process is swapped, the process is joining SCD or
12049 		 * leaving SCD or shared regions we serialize behind the
12050 		 * controlling thread with hat lock, sfmmu_flags and
12051 		 * sfmmu_tsb_cv condition variable.
12052 		 */
12053 
12054 		/*
12055 		 * Must set lwp state to LWP_SYS before
12056 		 * trying to acquire any adaptive lock
12057 		 */
12058 		lwp = ttolwp(curthread);
12059 		ASSERT(lwp);
12060 		lwp_save_state = lwp->lwp_state;
12061 		lwp->lwp_state = LWP_SYS;
12062 
12063 		hatlockp = sfmmu_hat_enter(sfmmup);
12064 retry:
12065 		if ((scdp = sfmmup->sfmmu_scdp) != NULL) {
12066 			shsfmmup = scdp->scd_sfmmup;
12067 			ASSERT(shsfmmup != NULL);
12068 
12069 			for (tsbinfop = shsfmmup->sfmmu_tsb; tsbinfop != NULL;
12070 			    tsbinfop = tsbinfop->tsb_next) {
12071 				if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
12072 					/* drop the private hat lock */
12073 					sfmmu_hat_exit(hatlockp);
12074 					/* acquire the shared hat lock */
12075 					shatlockp = sfmmu_hat_enter(shsfmmup);
12076 					/*
12077 					 * recheck to see if anything changed
12078 					 * after we drop the private hat lock.
12079 					 */
12080 					if (sfmmup->sfmmu_scdp == scdp &&
12081 					    shsfmmup == scdp->scd_sfmmup) {
12082 						sfmmu_tsb_chk_reloc(shsfmmup,
12083 						    shatlockp);
12084 					}
12085 					sfmmu_hat_exit(shatlockp);
12086 					hatlockp = sfmmu_hat_enter(sfmmup);
12087 					goto retry;
12088 				}
12089 			}
12090 		}
12091 
12092 		for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
12093 		    tsbinfop = tsbinfop->tsb_next) {
12094 			if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
12095 				cv_wait(&sfmmup->sfmmu_tsb_cv,
12096 				    HATLOCK_MUTEXP(hatlockp));
12097 				goto retry;
12098 			}
12099 		}
12100 
12101 		/*
12102 		 * Wait for ISM maps to be updated.
12103 		 */
12104 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
12105 			cv_wait(&sfmmup->sfmmu_tsb_cv,
12106 			    HATLOCK_MUTEXP(hatlockp));
12107 			goto retry;
12108 		}
12109 
12110 		/* Is this process joining an SCD? */
12111 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
12112 			/*
12113 			 * Flush private TSB and setup shared TSB.
12114 			 * sfmmu_finish_join_scd() does not drop the
12115 			 * hat lock.
12116 			 */
12117 			sfmmu_finish_join_scd(sfmmup);
12118 			SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
12119 		}
12120 
12121 		/*
12122 		 * If we're swapping in, get TSB(s).  Note that we must do
12123 		 * this before we get a ctx or load the MMU state.  Once
12124 		 * we swap in we have to recheck to make sure the TSB(s) and
12125 		 * ISM mappings didn't change while we slept.
12126 		 */
12127 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
12128 			sfmmu_tsb_swapin(sfmmup, hatlockp);
12129 			goto retry;
12130 		}
12131 
12132 		sfmmu_get_ctx(sfmmup);
12133 
12134 		sfmmu_hat_exit(hatlockp);
12135 		/*
12136 		 * Must restore lwp_state if not calling
12137 		 * trap() for further processing. Restore
12138 		 * it anyway.
12139 		 */
12140 		lwp->lwp_state = lwp_save_state;
12141 		return;
12142 	}
12143 	trap(rp, (caddr_t)tagaccess, traptype, 0);
12144 }
12145 
12146 static void
12147 sfmmu_tsb_chk_reloc(sfmmu_t *sfmmup, hatlock_t *hatlockp)
12148 {
12149 	struct tsb_info *tp;
12150 
12151 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12152 
12153 	for (tp = sfmmup->sfmmu_tsb; tp != NULL; tp = tp->tsb_next) {
12154 		if (tp->tsb_flags & TSB_RELOC_FLAG) {
12155 			cv_wait(&sfmmup->sfmmu_tsb_cv,
12156 			    HATLOCK_MUTEXP(hatlockp));
12157 			break;
12158 		}
12159 	}
12160 }
12161 
12162 /*
12163  * sfmmu_vatopfn_suspended is called from GET_TTE when TL=0 and
12164  * TTE_SUSPENDED bit set in tte we block on aquiring a page lock
12165  * rather than spinning to avoid send mondo timeouts with
12166  * interrupts enabled. When the lock is acquired it is immediately
12167  * released and we return back to sfmmu_vatopfn just after
12168  * the GET_TTE call.
12169  */
12170 void
12171 sfmmu_vatopfn_suspended(caddr_t vaddr, sfmmu_t *sfmmu, tte_t *ttep)
12172 {
12173 	struct page	**pp;
12174 
12175 	(void) as_pagelock(sfmmu->sfmmu_as, &pp, vaddr, TTE_CSZ(ttep), S_WRITE);
12176 	as_pageunlock(sfmmu->sfmmu_as, pp, vaddr, TTE_CSZ(ttep), S_WRITE);
12177 }
12178 
12179 /*
12180  * sfmmu_tsbmiss_suspended is called from GET_TTE when TL>0 and
12181  * TTE_SUSPENDED bit set in tte. We do this so that we can handle
12182  * cross traps which cannot be handled while spinning in the
12183  * trap handlers. Simply enter and exit the kpr_suspendlock spin
12184  * mutex, which is held by the holder of the suspend bit, and then
12185  * retry the trapped instruction after unwinding.
12186  */
12187 /*ARGSUSED*/
12188 void
12189 sfmmu_tsbmiss_suspended(struct regs *rp, uintptr_t tagacc, uint_t traptype)
12190 {
12191 	ASSERT(curthread != kreloc_thread);
12192 	mutex_enter(&kpr_suspendlock);
12193 	mutex_exit(&kpr_suspendlock);
12194 }
12195 
12196 /*
12197  * This routine could be optimized to reduce the number of xcalls by flushing
12198  * the entire TLBs if region reference count is above some threshold but the
12199  * tradeoff will depend on the size of the TLB. So for now flush the specific
12200  * page a context at a time.
12201  *
12202  * If uselocks is 0 then it's called after all cpus were captured and all the
12203  * hat locks were taken. In this case don't take the region lock by relying on
12204  * the order of list region update operations in hat_join_region(),
12205  * hat_leave_region() and hat_dup_region(). The ordering in those routines
12206  * guarantees that list is always forward walkable and reaches active sfmmus
12207  * regardless of where xc_attention() captures a cpu.
12208  */
12209 cpuset_t
12210 sfmmu_rgntlb_demap(caddr_t addr, sf_region_t *rgnp,
12211     struct hme_blk *hmeblkp, int uselocks)
12212 {
12213 	sfmmu_t	*sfmmup;
12214 	cpuset_t cpuset;
12215 	cpuset_t rcpuset;
12216 	hatlock_t *hatlockp;
12217 	uint_t rid = rgnp->rgn_id;
12218 	sf_rgn_link_t *rlink;
12219 	sf_scd_t *scdp;
12220 
12221 	ASSERT(hmeblkp->hblk_shared);
12222 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
12223 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
12224 
12225 	CPUSET_ZERO(rcpuset);
12226 	if (uselocks) {
12227 		mutex_enter(&rgnp->rgn_mutex);
12228 	}
12229 	sfmmup = rgnp->rgn_sfmmu_head;
12230 	while (sfmmup != NULL) {
12231 		if (uselocks) {
12232 			hatlockp = sfmmu_hat_enter(sfmmup);
12233 		}
12234 
12235 		/*
12236 		 * When an SCD is created the SCD hat is linked on the sfmmu
12237 		 * region lists for each hme region which is part of the
12238 		 * SCD. If we find an SCD hat, when walking these lists,
12239 		 * then we flush the shared TSBs, if we find a private hat,
12240 		 * which is part of an SCD, but where the region
12241 		 * is not part of the SCD then we flush the private TSBs.
12242 		 */
12243 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12244 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
12245 			scdp = sfmmup->sfmmu_scdp;
12246 			if (SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
12247 				if (uselocks) {
12248 					sfmmu_hat_exit(hatlockp);
12249 				}
12250 				goto next;
12251 			}
12252 		}
12253 
12254 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12255 
12256 		kpreempt_disable();
12257 		cpuset = sfmmup->sfmmu_cpusran;
12258 		CPUSET_AND(cpuset, cpu_ready_set);
12259 		CPUSET_DEL(cpuset, CPU->cpu_id);
12260 		SFMMU_XCALL_STATS(sfmmup);
12261 		xt_some(cpuset, vtag_flushpage_tl1,
12262 		    (uint64_t)addr, (uint64_t)sfmmup);
12263 		vtag_flushpage(addr, (uint64_t)sfmmup);
12264 		if (uselocks) {
12265 			sfmmu_hat_exit(hatlockp);
12266 		}
12267 		kpreempt_enable();
12268 		CPUSET_OR(rcpuset, cpuset);
12269 
12270 next:
12271 		/* LINTED: constant in conditional context */
12272 		SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
12273 		ASSERT(rlink != NULL);
12274 		sfmmup = rlink->next;
12275 	}
12276 	if (uselocks) {
12277 		mutex_exit(&rgnp->rgn_mutex);
12278 	}
12279 	return (rcpuset);
12280 }
12281 
12282 /*
12283  * This routine takes an sfmmu pointer and the va for an adddress in an
12284  * ISM region as input and returns the corresponding region id in ism_rid.
12285  * The return value of 1 indicates that a region has been found and ism_rid
12286  * is valid, otherwise 0 is returned.
12287  */
12288 static int
12289 find_ism_rid(sfmmu_t *sfmmup, sfmmu_t *ism_sfmmup, caddr_t va, uint_t *ism_rid)
12290 {
12291 	ism_blk_t	*ism_blkp;
12292 	int		i;
12293 	ism_map_t	*ism_map;
12294 #ifdef DEBUG
12295 	struct hat	*ism_hatid;
12296 #endif
12297 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12298 
12299 	ism_blkp = sfmmup->sfmmu_iblk;
12300 	while (ism_blkp != NULL) {
12301 		ism_map = ism_blkp->iblk_maps;
12302 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
12303 			if ((va >= ism_start(ism_map[i])) &&
12304 			    (va < ism_end(ism_map[i]))) {
12305 
12306 				*ism_rid = ism_map[i].imap_rid;
12307 #ifdef DEBUG
12308 				ism_hatid = ism_map[i].imap_ismhat;
12309 				ASSERT(ism_hatid == ism_sfmmup);
12310 				ASSERT(ism_hatid->sfmmu_ismhat);
12311 #endif
12312 				return (1);
12313 			}
12314 		}
12315 		ism_blkp = ism_blkp->iblk_next;
12316 	}
12317 	return (0);
12318 }
12319 
12320 /*
12321  * Special routine to flush out ism mappings- TSBs, TLBs and D-caches.
12322  * This routine may be called with all cpu's captured. Therefore, the
12323  * caller is responsible for holding all locks and disabling kernel
12324  * preemption.
12325  */
12326 /* ARGSUSED */
12327 static void
12328 sfmmu_ismtlbcache_demap(caddr_t addr, sfmmu_t *ism_sfmmup,
12329 	struct hme_blk *hmeblkp, pfn_t pfnum, int cache_flush_flag)
12330 {
12331 	cpuset_t 	cpuset;
12332 	caddr_t 	va;
12333 	ism_ment_t	*ment;
12334 	sfmmu_t		*sfmmup;
12335 #ifdef VAC
12336 	int 		vcolor;
12337 #endif
12338 
12339 	sf_scd_t	*scdp;
12340 	uint_t		ism_rid;
12341 
12342 	ASSERT(!hmeblkp->hblk_shared);
12343 	/*
12344 	 * Walk the ism_hat's mapping list and flush the page
12345 	 * from every hat sharing this ism_hat. This routine
12346 	 * may be called while all cpu's have been captured.
12347 	 * Therefore we can't attempt to grab any locks. For now
12348 	 * this means we will protect the ism mapping list under
12349 	 * a single lock which will be grabbed by the caller.
12350 	 * If hat_share/unshare scalibility becomes a performance
12351 	 * problem then we may need to re-think ism mapping list locking.
12352 	 */
12353 	ASSERT(ism_sfmmup->sfmmu_ismhat);
12354 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
12355 	addr = addr - ISMID_STARTADDR;
12356 
12357 	for (ment = ism_sfmmup->sfmmu_iment; ment; ment = ment->iment_next) {
12358 
12359 		sfmmup = ment->iment_hat;
12360 
12361 		va = ment->iment_base_va;
12362 		va = (caddr_t)((uintptr_t)va  + (uintptr_t)addr);
12363 
12364 		/*
12365 		 * When an SCD is created the SCD hat is linked on the ism
12366 		 * mapping lists for each ISM segment which is part of the
12367 		 * SCD. If we find an SCD hat, when walking these lists,
12368 		 * then we flush the shared TSBs, if we find a private hat,
12369 		 * which is part of an SCD, but where the region
12370 		 * corresponding to this va is not part of the SCD then we
12371 		 * flush the private TSBs.
12372 		 */
12373 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12374 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD) &&
12375 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
12376 			if (!find_ism_rid(sfmmup, ism_sfmmup, va,
12377 			    &ism_rid)) {
12378 				cmn_err(CE_PANIC,
12379 				    "can't find matching ISM rid!");
12380 			}
12381 
12382 			scdp = sfmmup->sfmmu_scdp;
12383 			if (SFMMU_IS_ISMRID_VALID(ism_rid) &&
12384 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map,
12385 			    ism_rid)) {
12386 				continue;
12387 			}
12388 		}
12389 		SFMMU_UNLOAD_TSB(va, sfmmup, hmeblkp, 1);
12390 
12391 		cpuset = sfmmup->sfmmu_cpusran;
12392 		CPUSET_AND(cpuset, cpu_ready_set);
12393 		CPUSET_DEL(cpuset, CPU->cpu_id);
12394 		SFMMU_XCALL_STATS(sfmmup);
12395 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)va,
12396 		    (uint64_t)sfmmup);
12397 		vtag_flushpage(va, (uint64_t)sfmmup);
12398 
12399 #ifdef VAC
12400 		/*
12401 		 * Flush D$
12402 		 * When flushing D$ we must flush all
12403 		 * cpu's. See sfmmu_cache_flush().
12404 		 */
12405 		if (cache_flush_flag == CACHE_FLUSH) {
12406 			cpuset = cpu_ready_set;
12407 			CPUSET_DEL(cpuset, CPU->cpu_id);
12408 
12409 			SFMMU_XCALL_STATS(sfmmup);
12410 			vcolor = addr_to_vcolor(va);
12411 			xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12412 			vac_flushpage(pfnum, vcolor);
12413 		}
12414 #endif	/* VAC */
12415 	}
12416 }
12417 
12418 /*
12419  * Demaps the TSB, CPU caches, and flushes all TLBs on all CPUs of
12420  * a particular virtual address and ctx.  If noflush is set we do not
12421  * flush the TLB/TSB.  This function may or may not be called with the
12422  * HAT lock held.
12423  */
12424 static void
12425 sfmmu_tlbcache_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12426 	pfn_t pfnum, int tlb_noflush, int cpu_flag, int cache_flush_flag,
12427 	int hat_lock_held)
12428 {
12429 #ifdef VAC
12430 	int vcolor;
12431 #endif
12432 	cpuset_t cpuset;
12433 	hatlock_t *hatlockp;
12434 
12435 	ASSERT(!hmeblkp->hblk_shared);
12436 
12437 #if defined(lint) && !defined(VAC)
12438 	pfnum = pfnum;
12439 	cpu_flag = cpu_flag;
12440 	cache_flush_flag = cache_flush_flag;
12441 #endif
12442 
12443 	/*
12444 	 * There is no longer a need to protect against ctx being
12445 	 * stolen here since we don't store the ctx in the TSB anymore.
12446 	 */
12447 #ifdef VAC
12448 	vcolor = addr_to_vcolor(addr);
12449 #endif
12450 
12451 	/*
12452 	 * We must hold the hat lock during the flush of TLB,
12453 	 * to avoid a race with sfmmu_invalidate_ctx(), where
12454 	 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12455 	 * causing TLB demap routine to skip flush on that MMU.
12456 	 * If the context on a MMU has already been set to
12457 	 * INVALID_CONTEXT, we just get an extra flush on
12458 	 * that MMU.
12459 	 */
12460 	if (!hat_lock_held && !tlb_noflush)
12461 		hatlockp = sfmmu_hat_enter(sfmmup);
12462 
12463 	kpreempt_disable();
12464 	if (!tlb_noflush) {
12465 		/*
12466 		 * Flush the TSB and TLB.
12467 		 */
12468 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12469 
12470 		cpuset = sfmmup->sfmmu_cpusran;
12471 		CPUSET_AND(cpuset, cpu_ready_set);
12472 		CPUSET_DEL(cpuset, CPU->cpu_id);
12473 
12474 		SFMMU_XCALL_STATS(sfmmup);
12475 
12476 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
12477 		    (uint64_t)sfmmup);
12478 
12479 		vtag_flushpage(addr, (uint64_t)sfmmup);
12480 	}
12481 
12482 	if (!hat_lock_held && !tlb_noflush)
12483 		sfmmu_hat_exit(hatlockp);
12484 
12485 #ifdef VAC
12486 	/*
12487 	 * Flush the D$
12488 	 *
12489 	 * Even if the ctx is stolen, we need to flush the
12490 	 * cache. Our ctx stealer only flushes the TLBs.
12491 	 */
12492 	if (cache_flush_flag == CACHE_FLUSH) {
12493 		if (cpu_flag & FLUSH_ALL_CPUS) {
12494 			cpuset = cpu_ready_set;
12495 		} else {
12496 			cpuset = sfmmup->sfmmu_cpusran;
12497 			CPUSET_AND(cpuset, cpu_ready_set);
12498 		}
12499 		CPUSET_DEL(cpuset, CPU->cpu_id);
12500 		SFMMU_XCALL_STATS(sfmmup);
12501 		xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12502 		vac_flushpage(pfnum, vcolor);
12503 	}
12504 #endif	/* VAC */
12505 	kpreempt_enable();
12506 }
12507 
12508 /*
12509  * Demaps the TSB and flushes all TLBs on all cpus for a particular virtual
12510  * address and ctx.  If noflush is set we do not currently do anything.
12511  * This function may or may not be called with the HAT lock held.
12512  */
12513 static void
12514 sfmmu_tlb_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12515 	int tlb_noflush, int hat_lock_held)
12516 {
12517 	cpuset_t cpuset;
12518 	hatlock_t *hatlockp;
12519 
12520 	ASSERT(!hmeblkp->hblk_shared);
12521 
12522 	/*
12523 	 * If the process is exiting we have nothing to do.
12524 	 */
12525 	if (tlb_noflush)
12526 		return;
12527 
12528 	/*
12529 	 * Flush TSB.
12530 	 */
12531 	if (!hat_lock_held)
12532 		hatlockp = sfmmu_hat_enter(sfmmup);
12533 	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12534 
12535 	kpreempt_disable();
12536 
12537 	cpuset = sfmmup->sfmmu_cpusran;
12538 	CPUSET_AND(cpuset, cpu_ready_set);
12539 	CPUSET_DEL(cpuset, CPU->cpu_id);
12540 
12541 	SFMMU_XCALL_STATS(sfmmup);
12542 	xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr, (uint64_t)sfmmup);
12543 
12544 	vtag_flushpage(addr, (uint64_t)sfmmup);
12545 
12546 	if (!hat_lock_held)
12547 		sfmmu_hat_exit(hatlockp);
12548 
12549 	kpreempt_enable();
12550 
12551 }
12552 
12553 /*
12554  * Special case of sfmmu_tlb_demap for MMU_PAGESIZE hblks. Use the xcall
12555  * call handler that can flush a range of pages to save on xcalls.
12556  */
12557 static int sfmmu_xcall_save;
12558 
12559 /*
12560  * this routine is never used for demaping addresses backed by SRD hmeblks.
12561  */
12562 static void
12563 sfmmu_tlb_range_demap(demap_range_t *dmrp)
12564 {
12565 	sfmmu_t *sfmmup = dmrp->dmr_sfmmup;
12566 	hatlock_t *hatlockp;
12567 	cpuset_t cpuset;
12568 	uint64_t sfmmu_pgcnt;
12569 	pgcnt_t pgcnt = 0;
12570 	int pgunload = 0;
12571 	int dirtypg = 0;
12572 	caddr_t addr = dmrp->dmr_addr;
12573 	caddr_t eaddr;
12574 	uint64_t bitvec = dmrp->dmr_bitvec;
12575 
12576 	ASSERT(bitvec & 1);
12577 
12578 	/*
12579 	 * Flush TSB and calculate number of pages to flush.
12580 	 */
12581 	while (bitvec != 0) {
12582 		dirtypg = 0;
12583 		/*
12584 		 * Find the first page to flush and then count how many
12585 		 * pages there are after it that also need to be flushed.
12586 		 * This way the number of TSB flushes is minimized.
12587 		 */
12588 		while ((bitvec & 1) == 0) {
12589 			pgcnt++;
12590 			addr += MMU_PAGESIZE;
12591 			bitvec >>= 1;
12592 		}
12593 		while (bitvec & 1) {
12594 			dirtypg++;
12595 			bitvec >>= 1;
12596 		}
12597 		eaddr = addr + ptob(dirtypg);
12598 		hatlockp = sfmmu_hat_enter(sfmmup);
12599 		sfmmu_unload_tsb_range(sfmmup, addr, eaddr, TTE8K);
12600 		sfmmu_hat_exit(hatlockp);
12601 		pgunload += dirtypg;
12602 		addr = eaddr;
12603 		pgcnt += dirtypg;
12604 	}
12605 
12606 	ASSERT((pgcnt<<MMU_PAGESHIFT) <= dmrp->dmr_endaddr - dmrp->dmr_addr);
12607 	if (sfmmup->sfmmu_free == 0) {
12608 		addr = dmrp->dmr_addr;
12609 		bitvec = dmrp->dmr_bitvec;
12610 
12611 		/*
12612 		 * make sure it has SFMMU_PGCNT_SHIFT bits only,
12613 		 * as it will be used to pack argument for xt_some
12614 		 */
12615 		ASSERT((pgcnt > 0) &&
12616 		    (pgcnt <= (1 << SFMMU_PGCNT_SHIFT)));
12617 
12618 		/*
12619 		 * Encode pgcnt as (pgcnt -1 ), and pass (pgcnt - 1) in
12620 		 * the low 6 bits of sfmmup. This is doable since pgcnt
12621 		 * always >= 1.
12622 		 */
12623 		ASSERT(!((uint64_t)sfmmup & SFMMU_PGCNT_MASK));
12624 		sfmmu_pgcnt = (uint64_t)sfmmup |
12625 		    ((pgcnt - 1) & SFMMU_PGCNT_MASK);
12626 
12627 		/*
12628 		 * We must hold the hat lock during the flush of TLB,
12629 		 * to avoid a race with sfmmu_invalidate_ctx(), where
12630 		 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12631 		 * causing TLB demap routine to skip flush on that MMU.
12632 		 * If the context on a MMU has already been set to
12633 		 * INVALID_CONTEXT, we just get an extra flush on
12634 		 * that MMU.
12635 		 */
12636 		hatlockp = sfmmu_hat_enter(sfmmup);
12637 		kpreempt_disable();
12638 
12639 		cpuset = sfmmup->sfmmu_cpusran;
12640 		CPUSET_AND(cpuset, cpu_ready_set);
12641 		CPUSET_DEL(cpuset, CPU->cpu_id);
12642 
12643 		SFMMU_XCALL_STATS(sfmmup);
12644 		xt_some(cpuset, vtag_flush_pgcnt_tl1, (uint64_t)addr,
12645 		    sfmmu_pgcnt);
12646 
12647 		for (; bitvec != 0; bitvec >>= 1) {
12648 			if (bitvec & 1)
12649 				vtag_flushpage(addr, (uint64_t)sfmmup);
12650 			addr += MMU_PAGESIZE;
12651 		}
12652 		kpreempt_enable();
12653 		sfmmu_hat_exit(hatlockp);
12654 
12655 		sfmmu_xcall_save += (pgunload-1);
12656 	}
12657 	dmrp->dmr_bitvec = 0;
12658 }
12659 
12660 /*
12661  * In cases where we need to synchronize with TLB/TSB miss trap
12662  * handlers, _and_ need to flush the TLB, it's a lot easier to
12663  * throw away the context from the process than to do a
12664  * special song and dance to keep things consistent for the
12665  * handlers.
12666  *
12667  * Since the process suddenly ends up without a context and our caller
12668  * holds the hat lock, threads that fault after this function is called
12669  * will pile up on the lock.  We can then do whatever we need to
12670  * atomically from the context of the caller.  The first blocked thread
12671  * to resume executing will get the process a new context, and the
12672  * process will resume executing.
12673  *
12674  * One added advantage of this approach is that on MMUs that
12675  * support a "flush all" operation, we will delay the flush until
12676  * cnum wrap-around, and then flush the TLB one time.  This
12677  * is rather rare, so it's a lot less expensive than making 8000
12678  * x-calls to flush the TLB 8000 times.
12679  *
12680  * A per-process (PP) lock is used to synchronize ctx allocations in
12681  * resume() and ctx invalidations here.
12682  */
12683 static void
12684 sfmmu_invalidate_ctx(sfmmu_t *sfmmup)
12685 {
12686 	cpuset_t cpuset;
12687 	int cnum, currcnum;
12688 	mmu_ctx_t *mmu_ctxp;
12689 	int i;
12690 	uint_t pstate_save;
12691 
12692 	SFMMU_STAT(sf_ctx_inv);
12693 
12694 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12695 	ASSERT(sfmmup != ksfmmup);
12696 
12697 	kpreempt_disable();
12698 
12699 	mmu_ctxp = CPU_MMU_CTXP(CPU);
12700 	ASSERT(mmu_ctxp);
12701 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
12702 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
12703 
12704 	currcnum = sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum;
12705 
12706 	pstate_save = sfmmu_disable_intrs();
12707 
12708 	lock_set(&sfmmup->sfmmu_ctx_lock);	/* acquire PP lock */
12709 	/* set HAT cnum invalid across all context domains. */
12710 	for (i = 0; i < max_mmu_ctxdoms; i++) {
12711 
12712 		cnum = 	sfmmup->sfmmu_ctxs[i].cnum;
12713 		if (cnum == INVALID_CONTEXT) {
12714 			continue;
12715 		}
12716 
12717 		sfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
12718 	}
12719 	membar_enter();	/* make sure globally visible to all CPUs */
12720 	lock_clear(&sfmmup->sfmmu_ctx_lock);	/* release PP lock */
12721 
12722 	sfmmu_enable_intrs(pstate_save);
12723 
12724 	cpuset = sfmmup->sfmmu_cpusran;
12725 	CPUSET_DEL(cpuset, CPU->cpu_id);
12726 	CPUSET_AND(cpuset, cpu_ready_set);
12727 	if (!CPUSET_ISNULL(cpuset)) {
12728 		SFMMU_XCALL_STATS(sfmmup);
12729 		xt_some(cpuset, sfmmu_raise_tsb_exception,
12730 		    (uint64_t)sfmmup, INVALID_CONTEXT);
12731 		xt_sync(cpuset);
12732 		SFMMU_STAT(sf_tsb_raise_exception);
12733 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
12734 	}
12735 
12736 	/*
12737 	 * If the hat to-be-invalidated is the same as the current
12738 	 * process on local CPU we need to invalidate
12739 	 * this CPU context as well.
12740 	 */
12741 	if ((sfmmu_getctx_sec() == currcnum) &&
12742 	    (currcnum != INVALID_CONTEXT)) {
12743 		/* sets shared context to INVALID too */
12744 		sfmmu_setctx_sec(INVALID_CONTEXT);
12745 		sfmmu_clear_utsbinfo();
12746 	}
12747 
12748 	SFMMU_FLAGS_SET(sfmmup, HAT_ALLCTX_INVALID);
12749 
12750 	kpreempt_enable();
12751 
12752 	/*
12753 	 * we hold the hat lock, so nobody should allocate a context
12754 	 * for us yet
12755 	 */
12756 	ASSERT(sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum == INVALID_CONTEXT);
12757 }
12758 
12759 #ifdef VAC
12760 /*
12761  * We need to flush the cache in all cpus.  It is possible that
12762  * a process referenced a page as cacheable but has sinced exited
12763  * and cleared the mapping list.  We still to flush it but have no
12764  * state so all cpus is the only alternative.
12765  */
12766 void
12767 sfmmu_cache_flush(pfn_t pfnum, int vcolor)
12768 {
12769 	cpuset_t cpuset;
12770 
12771 	kpreempt_disable();
12772 	cpuset = cpu_ready_set;
12773 	CPUSET_DEL(cpuset, CPU->cpu_id);
12774 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12775 	xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12776 	xt_sync(cpuset);
12777 	vac_flushpage(pfnum, vcolor);
12778 	kpreempt_enable();
12779 }
12780 
12781 void
12782 sfmmu_cache_flushcolor(int vcolor, pfn_t pfnum)
12783 {
12784 	cpuset_t cpuset;
12785 
12786 	ASSERT(vcolor >= 0);
12787 
12788 	kpreempt_disable();
12789 	cpuset = cpu_ready_set;
12790 	CPUSET_DEL(cpuset, CPU->cpu_id);
12791 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12792 	xt_some(cpuset, vac_flushcolor_tl1, vcolor, pfnum);
12793 	xt_sync(cpuset);
12794 	vac_flushcolor(vcolor, pfnum);
12795 	kpreempt_enable();
12796 }
12797 #endif	/* VAC */
12798 
12799 /*
12800  * We need to prevent processes from accessing the TSB using a cached physical
12801  * address.  It's alright if they try to access the TSB via virtual address
12802  * since they will just fault on that virtual address once the mapping has
12803  * been suspended.
12804  */
12805 #pragma weak sendmondo_in_recover
12806 
12807 /* ARGSUSED */
12808 static int
12809 sfmmu_tsb_pre_relocator(caddr_t va, uint_t tsbsz, uint_t flags, void *tsbinfo)
12810 {
12811 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12812 	sfmmu_t *sfmmup = tsbinfop->tsb_sfmmu;
12813 	hatlock_t *hatlockp;
12814 	sf_scd_t *scdp;
12815 
12816 	if (flags != HAT_PRESUSPEND)
12817 		return (0);
12818 
12819 	/*
12820 	 * If tsb is a shared TSB with TSB_SHAREDCTX set, sfmmup must
12821 	 * be a shared hat, then set SCD's tsbinfo's flag.
12822 	 * If tsb is not shared, sfmmup is a private hat, then set
12823 	 * its private tsbinfo's flag.
12824 	 */
12825 	hatlockp = sfmmu_hat_enter(sfmmup);
12826 	tsbinfop->tsb_flags |= TSB_RELOC_FLAG;
12827 
12828 	if (!(tsbinfop->tsb_flags & TSB_SHAREDCTX)) {
12829 		sfmmu_tsb_inv_ctx(sfmmup);
12830 		sfmmu_hat_exit(hatlockp);
12831 	} else {
12832 		/* release lock on the shared hat */
12833 		sfmmu_hat_exit(hatlockp);
12834 		/* sfmmup is a shared hat */
12835 		ASSERT(sfmmup->sfmmu_scdhat);
12836 		scdp = sfmmup->sfmmu_scdp;
12837 		ASSERT(scdp != NULL);
12838 		/* get private hat from the scd list */
12839 		mutex_enter(&scdp->scd_mutex);
12840 		sfmmup = scdp->scd_sf_list;
12841 		while (sfmmup != NULL) {
12842 			hatlockp = sfmmu_hat_enter(sfmmup);
12843 			/*
12844 			 * We do not call sfmmu_tsb_inv_ctx here because
12845 			 * sendmondo_in_recover check is only needed for
12846 			 * sun4u.
12847 			 */
12848 			sfmmu_invalidate_ctx(sfmmup);
12849 			sfmmu_hat_exit(hatlockp);
12850 			sfmmup = sfmmup->sfmmu_scd_link.next;
12851 
12852 		}
12853 		mutex_exit(&scdp->scd_mutex);
12854 	}
12855 	return (0);
12856 }
12857 
12858 static void
12859 sfmmu_tsb_inv_ctx(sfmmu_t *sfmmup)
12860 {
12861 	extern uint32_t sendmondo_in_recover;
12862 
12863 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12864 
12865 	/*
12866 	 * For Cheetah+ Erratum 25:
12867 	 * Wait for any active recovery to finish.  We can't risk
12868 	 * relocating the TSB of the thread running mondo_recover_proc()
12869 	 * since, if we did that, we would deadlock.  The scenario we are
12870 	 * trying to avoid is as follows:
12871 	 *
12872 	 * THIS CPU			RECOVER CPU
12873 	 * --------			-----------
12874 	 *				Begins recovery, walking through TSB
12875 	 * hat_pagesuspend() TSB TTE
12876 	 *				TLB miss on TSB TTE, spins at TL1
12877 	 * xt_sync()
12878 	 *	send_mondo_timeout()
12879 	 *	mondo_recover_proc()
12880 	 *	((deadlocked))
12881 	 *
12882 	 * The second half of the workaround is that mondo_recover_proc()
12883 	 * checks to see if the tsb_info has the RELOC flag set, and if it
12884 	 * does, it skips over that TSB without ever touching tsbinfop->tsb_va
12885 	 * and hence avoiding the TLB miss that could result in a deadlock.
12886 	 */
12887 	if (&sendmondo_in_recover) {
12888 		membar_enter();	/* make sure RELOC flag visible */
12889 		while (sendmondo_in_recover) {
12890 			drv_usecwait(1);
12891 			membar_consumer();
12892 		}
12893 	}
12894 
12895 	sfmmu_invalidate_ctx(sfmmup);
12896 }
12897 
12898 /* ARGSUSED */
12899 static int
12900 sfmmu_tsb_post_relocator(caddr_t va, uint_t tsbsz, uint_t flags,
12901 	void *tsbinfo, pfn_t newpfn)
12902 {
12903 	hatlock_t *hatlockp;
12904 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12905 	sfmmu_t	*sfmmup = tsbinfop->tsb_sfmmu;
12906 
12907 	if (flags != HAT_POSTUNSUSPEND)
12908 		return (0);
12909 
12910 	hatlockp = sfmmu_hat_enter(sfmmup);
12911 
12912 	SFMMU_STAT(sf_tsb_reloc);
12913 
12914 	/*
12915 	 * The process may have swapped out while we were relocating one
12916 	 * of its TSBs.  If so, don't bother doing the setup since the
12917 	 * process can't be using the memory anymore.
12918 	 */
12919 	if ((tsbinfop->tsb_flags & TSB_SWAPPED) == 0) {
12920 		ASSERT(va == tsbinfop->tsb_va);
12921 		sfmmu_tsbinfo_setup_phys(tsbinfop, newpfn);
12922 
12923 		if (tsbinfop->tsb_flags & TSB_FLUSH_NEEDED) {
12924 			sfmmu_inv_tsb(tsbinfop->tsb_va,
12925 			    TSB_BYTES(tsbinfop->tsb_szc));
12926 			tsbinfop->tsb_flags &= ~TSB_FLUSH_NEEDED;
12927 		}
12928 	}
12929 
12930 	membar_exit();
12931 	tsbinfop->tsb_flags &= ~TSB_RELOC_FLAG;
12932 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
12933 
12934 	sfmmu_hat_exit(hatlockp);
12935 
12936 	return (0);
12937 }
12938 
12939 /*
12940  * Allocate and initialize a tsb_info structure.  Note that we may or may not
12941  * allocate a TSB here, depending on the flags passed in.
12942  */
12943 static int
12944 sfmmu_tsbinfo_alloc(struct tsb_info **tsbinfopp, int tsb_szc, int tte_sz_mask,
12945 	uint_t flags, sfmmu_t *sfmmup)
12946 {
12947 	int err;
12948 
12949 	*tsbinfopp = (struct tsb_info *)kmem_cache_alloc(
12950 	    sfmmu_tsbinfo_cache, KM_SLEEP);
12951 
12952 	if ((err = sfmmu_init_tsbinfo(*tsbinfopp, tte_sz_mask,
12953 	    tsb_szc, flags, sfmmup)) != 0) {
12954 		kmem_cache_free(sfmmu_tsbinfo_cache, *tsbinfopp);
12955 		SFMMU_STAT(sf_tsb_allocfail);
12956 		*tsbinfopp = NULL;
12957 		return (err);
12958 	}
12959 	SFMMU_STAT(sf_tsb_alloc);
12960 
12961 	/*
12962 	 * Bump the TSB size counters for this TSB size.
12963 	 */
12964 	(*(((int *)&sfmmu_tsbsize_stat) + tsb_szc))++;
12965 	return (0);
12966 }
12967 
12968 static void
12969 sfmmu_tsb_free(struct tsb_info *tsbinfo)
12970 {
12971 	caddr_t tsbva = tsbinfo->tsb_va;
12972 	uint_t tsb_size = TSB_BYTES(tsbinfo->tsb_szc);
12973 	struct kmem_cache *kmem_cachep = tsbinfo->tsb_cache;
12974 	vmem_t	*vmp = tsbinfo->tsb_vmp;
12975 
12976 	/*
12977 	 * If we allocated this TSB from relocatable kernel memory, then we
12978 	 * need to uninstall the callback handler.
12979 	 */
12980 	if (tsbinfo->tsb_cache != sfmmu_tsb8k_cache) {
12981 		uintptr_t slab_mask;
12982 		caddr_t slab_vaddr;
12983 		page_t **ppl;
12984 		int ret;
12985 
12986 		ASSERT(tsb_size <= MMU_PAGESIZE4M || use_bigtsb_arena);
12987 		if (tsb_size > MMU_PAGESIZE4M)
12988 			slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12989 		else
12990 			slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12991 		slab_vaddr = (caddr_t)((uintptr_t)tsbva & slab_mask);
12992 
12993 		ret = as_pagelock(&kas, &ppl, slab_vaddr, PAGESIZE, S_WRITE);
12994 		ASSERT(ret == 0);
12995 		hat_delete_callback(tsbva, (uint_t)tsb_size, (void *)tsbinfo,
12996 		    0, NULL);
12997 		as_pageunlock(&kas, ppl, slab_vaddr, PAGESIZE, S_WRITE);
12998 	}
12999 
13000 	if (kmem_cachep != NULL) {
13001 		kmem_cache_free(kmem_cachep, tsbva);
13002 	} else {
13003 		vmem_xfree(vmp, (void *)tsbva, tsb_size);
13004 	}
13005 	tsbinfo->tsb_va = (caddr_t)0xbad00bad;
13006 	atomic_add_64(&tsb_alloc_bytes, -(int64_t)tsb_size);
13007 }
13008 
13009 static void
13010 sfmmu_tsbinfo_free(struct tsb_info *tsbinfo)
13011 {
13012 	if ((tsbinfo->tsb_flags & TSB_SWAPPED) == 0) {
13013 		sfmmu_tsb_free(tsbinfo);
13014 	}
13015 	kmem_cache_free(sfmmu_tsbinfo_cache, tsbinfo);
13016 
13017 }
13018 
13019 /*
13020  * Setup all the references to physical memory for this tsbinfo.
13021  * The underlying page(s) must be locked.
13022  */
13023 static void
13024 sfmmu_tsbinfo_setup_phys(struct tsb_info *tsbinfo, pfn_t pfn)
13025 {
13026 	ASSERT(pfn != PFN_INVALID);
13027 	ASSERT(pfn == va_to_pfn(tsbinfo->tsb_va));
13028 
13029 #ifndef sun4v
13030 	if (tsbinfo->tsb_szc == 0) {
13031 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn,
13032 		    PROT_WRITE|PROT_READ, TTE8K);
13033 	} else {
13034 		/*
13035 		 * Round down PA and use a large mapping; the handlers will
13036 		 * compute the TSB pointer at the correct offset into the
13037 		 * big virtual page.  NOTE: this assumes all TSBs larger
13038 		 * than 8K must come from physically contiguous slabs of
13039 		 * size tsb_slab_size.
13040 		 */
13041 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn & ~tsb_slab_mask,
13042 		    PROT_WRITE|PROT_READ, tsb_slab_ttesz);
13043 	}
13044 	tsbinfo->tsb_pa = ptob(pfn);
13045 
13046 	TTE_SET_LOCKED(&tsbinfo->tsb_tte); /* lock the tte into dtlb */
13047 	TTE_SET_MOD(&tsbinfo->tsb_tte);    /* enable writes */
13048 
13049 	ASSERT(TTE_IS_PRIVILEGED(&tsbinfo->tsb_tte));
13050 	ASSERT(TTE_IS_LOCKED(&tsbinfo->tsb_tte));
13051 #else /* sun4v */
13052 	tsbinfo->tsb_pa = ptob(pfn);
13053 #endif /* sun4v */
13054 }
13055 
13056 
13057 /*
13058  * Returns zero on success, ENOMEM if over the high water mark,
13059  * or EAGAIN if the caller needs to retry with a smaller TSB
13060  * size (or specify TSB_FORCEALLOC if the allocation can't fail).
13061  *
13062  * This call cannot fail to allocate a TSB if TSB_FORCEALLOC
13063  * is specified and the TSB requested is PAGESIZE, though it
13064  * may sleep waiting for memory if sufficient memory is not
13065  * available.
13066  */
13067 static int
13068 sfmmu_init_tsbinfo(struct tsb_info *tsbinfo, int tteszmask,
13069     int tsbcode, uint_t flags, sfmmu_t *sfmmup)
13070 {
13071 	caddr_t vaddr = NULL;
13072 	caddr_t slab_vaddr;
13073 	uintptr_t slab_mask;
13074 	int tsbbytes = TSB_BYTES(tsbcode);
13075 	int lowmem = 0;
13076 	struct kmem_cache *kmem_cachep = NULL;
13077 	vmem_t *vmp = NULL;
13078 	lgrp_id_t lgrpid = LGRP_NONE;
13079 	pfn_t pfn;
13080 	uint_t cbflags = HAC_SLEEP;
13081 	page_t **pplist;
13082 	int ret;
13083 
13084 	ASSERT(tsbbytes <= MMU_PAGESIZE4M || use_bigtsb_arena);
13085 	if (tsbbytes > MMU_PAGESIZE4M)
13086 		slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
13087 	else
13088 		slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
13089 
13090 	if (flags & (TSB_FORCEALLOC | TSB_SWAPIN | TSB_GROW | TSB_SHRINK))
13091 		flags |= TSB_ALLOC;
13092 
13093 	ASSERT((flags & TSB_FORCEALLOC) == 0 || tsbcode == TSB_MIN_SZCODE);
13094 
13095 	tsbinfo->tsb_sfmmu = sfmmup;
13096 
13097 	/*
13098 	 * If not allocating a TSB, set up the tsbinfo, set TSB_SWAPPED, and
13099 	 * return.
13100 	 */
13101 	if ((flags & TSB_ALLOC) == 0) {
13102 		tsbinfo->tsb_szc = tsbcode;
13103 		tsbinfo->tsb_ttesz_mask = tteszmask;
13104 		tsbinfo->tsb_va = (caddr_t)0xbadbadbeef;
13105 		tsbinfo->tsb_pa = -1;
13106 		tsbinfo->tsb_tte.ll = 0;
13107 		tsbinfo->tsb_next = NULL;
13108 		tsbinfo->tsb_flags = TSB_SWAPPED;
13109 		tsbinfo->tsb_cache = NULL;
13110 		tsbinfo->tsb_vmp = NULL;
13111 		return (0);
13112 	}
13113 
13114 #ifdef DEBUG
13115 	/*
13116 	 * For debugging:
13117 	 * Randomly force allocation failures every tsb_alloc_mtbf
13118 	 * tries if TSB_FORCEALLOC is not specified.  This will
13119 	 * return ENOMEM if tsb_alloc_mtbf is odd, or EAGAIN if
13120 	 * it is even, to allow testing of both failure paths...
13121 	 */
13122 	if (tsb_alloc_mtbf && ((flags & TSB_FORCEALLOC) == 0) &&
13123 	    (tsb_alloc_count++ == tsb_alloc_mtbf)) {
13124 		tsb_alloc_count = 0;
13125 		tsb_alloc_fail_mtbf++;
13126 		return ((tsb_alloc_mtbf & 1)? ENOMEM : EAGAIN);
13127 	}
13128 #endif	/* DEBUG */
13129 
13130 	/*
13131 	 * Enforce high water mark if we are not doing a forced allocation
13132 	 * and are not shrinking a process' TSB.
13133 	 */
13134 	if ((flags & TSB_SHRINK) == 0 &&
13135 	    (tsbbytes + tsb_alloc_bytes) > tsb_alloc_hiwater) {
13136 		if ((flags & TSB_FORCEALLOC) == 0)
13137 			return (ENOMEM);
13138 		lowmem = 1;
13139 	}
13140 
13141 	/*
13142 	 * Allocate from the correct location based upon the size of the TSB
13143 	 * compared to the base page size, and what memory conditions dictate.
13144 	 * Note we always do nonblocking allocations from the TSB arena since
13145 	 * we don't want memory fragmentation to cause processes to block
13146 	 * indefinitely waiting for memory; until the kernel algorithms that
13147 	 * coalesce large pages are improved this is our best option.
13148 	 *
13149 	 * Algorithm:
13150 	 *	If allocating a "large" TSB (>8K), allocate from the
13151 	 *		appropriate kmem_tsb_default_arena vmem arena
13152 	 *	else if low on memory or the TSB_FORCEALLOC flag is set or
13153 	 *	tsb_forceheap is set
13154 	 *		Allocate from kernel heap via sfmmu_tsb8k_cache with
13155 	 *		KM_SLEEP (never fails)
13156 	 *	else
13157 	 *		Allocate from appropriate sfmmu_tsb_cache with
13158 	 *		KM_NOSLEEP
13159 	 *	endif
13160 	 */
13161 	if (tsb_lgrp_affinity)
13162 		lgrpid = lgrp_home_id(curthread);
13163 	if (lgrpid == LGRP_NONE)
13164 		lgrpid = 0;	/* use lgrp of boot CPU */
13165 
13166 	if (tsbbytes > MMU_PAGESIZE) {
13167 		if (tsbbytes > MMU_PAGESIZE4M) {
13168 			vmp = kmem_bigtsb_default_arena[lgrpid];
13169 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
13170 			    0, 0, NULL, NULL, VM_NOSLEEP);
13171 		} else {
13172 			vmp = kmem_tsb_default_arena[lgrpid];
13173 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
13174 			    0, 0, NULL, NULL, VM_NOSLEEP);
13175 		}
13176 #ifdef	DEBUG
13177 	} else if (lowmem || (flags & TSB_FORCEALLOC) || tsb_forceheap) {
13178 #else	/* !DEBUG */
13179 	} else if (lowmem || (flags & TSB_FORCEALLOC)) {
13180 #endif	/* DEBUG */
13181 		kmem_cachep = sfmmu_tsb8k_cache;
13182 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_SLEEP);
13183 		ASSERT(vaddr != NULL);
13184 	} else {
13185 		kmem_cachep = sfmmu_tsb_cache[lgrpid];
13186 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_NOSLEEP);
13187 	}
13188 
13189 	tsbinfo->tsb_cache = kmem_cachep;
13190 	tsbinfo->tsb_vmp = vmp;
13191 
13192 	if (vaddr == NULL) {
13193 		return (EAGAIN);
13194 	}
13195 
13196 	atomic_add_64(&tsb_alloc_bytes, (int64_t)tsbbytes);
13197 	kmem_cachep = tsbinfo->tsb_cache;
13198 
13199 	/*
13200 	 * If we are allocating from outside the cage, then we need to
13201 	 * register a relocation callback handler.  Note that for now
13202 	 * since pseudo mappings always hang off of the slab's root page,
13203 	 * we need only lock the first 8K of the TSB slab.  This is a bit
13204 	 * hacky but it is good for performance.
13205 	 */
13206 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13207 		slab_vaddr = (caddr_t)((uintptr_t)vaddr & slab_mask);
13208 		ret = as_pagelock(&kas, &pplist, slab_vaddr, PAGESIZE, S_WRITE);
13209 		ASSERT(ret == 0);
13210 		ret = hat_add_callback(sfmmu_tsb_cb_id, vaddr, (uint_t)tsbbytes,
13211 		    cbflags, (void *)tsbinfo, &pfn, NULL);
13212 
13213 		/*
13214 		 * Need to free up resources if we could not successfully
13215 		 * add the callback function and return an error condition.
13216 		 */
13217 		if (ret != 0) {
13218 			if (kmem_cachep) {
13219 				kmem_cache_free(kmem_cachep, vaddr);
13220 			} else {
13221 				vmem_xfree(vmp, (void *)vaddr, tsbbytes);
13222 			}
13223 			as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE,
13224 			    S_WRITE);
13225 			return (EAGAIN);
13226 		}
13227 	} else {
13228 		/*
13229 		 * Since allocation of 8K TSBs from heap is rare and occurs
13230 		 * during memory pressure we allocate them from permanent
13231 		 * memory rather than using callbacks to get the PFN.
13232 		 */
13233 		pfn = hat_getpfnum(kas.a_hat, vaddr);
13234 	}
13235 
13236 	tsbinfo->tsb_va = vaddr;
13237 	tsbinfo->tsb_szc = tsbcode;
13238 	tsbinfo->tsb_ttesz_mask = tteszmask;
13239 	tsbinfo->tsb_next = NULL;
13240 	tsbinfo->tsb_flags = 0;
13241 
13242 	sfmmu_tsbinfo_setup_phys(tsbinfo, pfn);
13243 
13244 	sfmmu_inv_tsb(vaddr, tsbbytes);
13245 
13246 	if (kmem_cachep != sfmmu_tsb8k_cache) {
13247 		as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE, S_WRITE);
13248 	}
13249 
13250 	return (0);
13251 }
13252 
13253 /*
13254  * Initialize per cpu tsb and per cpu tsbmiss_area
13255  */
13256 void
13257 sfmmu_init_tsbs(void)
13258 {
13259 	int i;
13260 	struct tsbmiss	*tsbmissp;
13261 	struct kpmtsbm	*kpmtsbmp;
13262 #ifndef sun4v
13263 	extern int	dcache_line_mask;
13264 #endif /* sun4v */
13265 	extern uint_t	vac_colors;
13266 
13267 	/*
13268 	 * Init. tsb miss area.
13269 	 */
13270 	tsbmissp = tsbmiss_area;
13271 
13272 	for (i = 0; i < NCPU; tsbmissp++, i++) {
13273 		/*
13274 		 * initialize the tsbmiss area.
13275 		 * Do this for all possible CPUs as some may be added
13276 		 * while the system is running. There is no cost to this.
13277 		 */
13278 		tsbmissp->ksfmmup = ksfmmup;
13279 #ifndef sun4v
13280 		tsbmissp->dcache_line_mask = (uint16_t)dcache_line_mask;
13281 #endif /* sun4v */
13282 		tsbmissp->khashstart =
13283 		    (struct hmehash_bucket *)va_to_pa((caddr_t)khme_hash);
13284 		tsbmissp->uhashstart =
13285 		    (struct hmehash_bucket *)va_to_pa((caddr_t)uhme_hash);
13286 		tsbmissp->khashsz = khmehash_num;
13287 		tsbmissp->uhashsz = uhmehash_num;
13288 	}
13289 
13290 	sfmmu_tsb_cb_id = hat_register_callback('T'<<16 | 'S' << 8 | 'B',
13291 	    sfmmu_tsb_pre_relocator, sfmmu_tsb_post_relocator, NULL, 0);
13292 
13293 	if (kpm_enable == 0)
13294 		return;
13295 
13296 	/* -- Begin KPM specific init -- */
13297 
13298 	if (kpm_smallpages) {
13299 		/*
13300 		 * If we're using base pagesize pages for seg_kpm
13301 		 * mappings, we use the kernel TSB since we can't afford
13302 		 * to allocate a second huge TSB for these mappings.
13303 		 */
13304 		kpm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13305 		kpm_tsbsz = ktsb_szcode;
13306 		kpmsm_tsbbase = kpm_tsbbase;
13307 		kpmsm_tsbsz = kpm_tsbsz;
13308 	} else {
13309 		/*
13310 		 * In VAC conflict case, just put the entries in the
13311 		 * kernel 8K indexed TSB for now so we can find them.
13312 		 * This could really be changed in the future if we feel
13313 		 * the need...
13314 		 */
13315 		kpmsm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13316 		kpmsm_tsbsz = ktsb_szcode;
13317 		kpm_tsbbase = ktsb_phys? ktsb4m_pbase : (uint64_t)ktsb4m_base;
13318 		kpm_tsbsz = ktsb4m_szcode;
13319 	}
13320 
13321 	kpmtsbmp = kpmtsbm_area;
13322 	for (i = 0; i < NCPU; kpmtsbmp++, i++) {
13323 		/*
13324 		 * Initialize the kpmtsbm area.
13325 		 * Do this for all possible CPUs as some may be added
13326 		 * while the system is running. There is no cost to this.
13327 		 */
13328 		kpmtsbmp->vbase = kpm_vbase;
13329 		kpmtsbmp->vend = kpm_vbase + kpm_size * vac_colors;
13330 		kpmtsbmp->sz_shift = kpm_size_shift;
13331 		kpmtsbmp->kpmp_shift = kpmp_shift;
13332 		kpmtsbmp->kpmp2pshft = (uchar_t)kpmp2pshft;
13333 		if (kpm_smallpages == 0) {
13334 			kpmtsbmp->kpmp_table_sz = kpmp_table_sz;
13335 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_table);
13336 		} else {
13337 			kpmtsbmp->kpmp_table_sz = kpmp_stable_sz;
13338 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_stable);
13339 		}
13340 		kpmtsbmp->msegphashpa = va_to_pa(memseg_phash);
13341 		kpmtsbmp->flags = KPMTSBM_ENABLE_FLAG;
13342 #ifdef	DEBUG
13343 		kpmtsbmp->flags |= (kpm_tsbmtl) ?  KPMTSBM_TLTSBM_FLAG : 0;
13344 #endif	/* DEBUG */
13345 		if (ktsb_phys)
13346 			kpmtsbmp->flags |= KPMTSBM_TSBPHYS_FLAG;
13347 	}
13348 
13349 	/* -- End KPM specific init -- */
13350 }
13351 
13352 /* Avoid using sfmmu_tsbinfo_alloc() to avoid kmem_alloc - no real reason */
13353 struct tsb_info ktsb_info[2];
13354 
13355 /*
13356  * Called from hat_kern_setup() to setup the tsb_info for ksfmmup.
13357  */
13358 void
13359 sfmmu_init_ktsbinfo()
13360 {
13361 	ASSERT(ksfmmup != NULL);
13362 	ASSERT(ksfmmup->sfmmu_tsb == NULL);
13363 	/*
13364 	 * Allocate tsbinfos for kernel and copy in data
13365 	 * to make debug easier and sun4v setup easier.
13366 	 */
13367 	ktsb_info[0].tsb_sfmmu = ksfmmup;
13368 	ktsb_info[0].tsb_szc = ktsb_szcode;
13369 	ktsb_info[0].tsb_ttesz_mask = TSB8K|TSB64K|TSB512K;
13370 	ktsb_info[0].tsb_va = ktsb_base;
13371 	ktsb_info[0].tsb_pa = ktsb_pbase;
13372 	ktsb_info[0].tsb_flags = 0;
13373 	ktsb_info[0].tsb_tte.ll = 0;
13374 	ktsb_info[0].tsb_cache = NULL;
13375 
13376 	ktsb_info[1].tsb_sfmmu = ksfmmup;
13377 	ktsb_info[1].tsb_szc = ktsb4m_szcode;
13378 	ktsb_info[1].tsb_ttesz_mask = TSB4M;
13379 	ktsb_info[1].tsb_va = ktsb4m_base;
13380 	ktsb_info[1].tsb_pa = ktsb4m_pbase;
13381 	ktsb_info[1].tsb_flags = 0;
13382 	ktsb_info[1].tsb_tte.ll = 0;
13383 	ktsb_info[1].tsb_cache = NULL;
13384 
13385 	/* Link them into ksfmmup. */
13386 	ktsb_info[0].tsb_next = &ktsb_info[1];
13387 	ktsb_info[1].tsb_next = NULL;
13388 	ksfmmup->sfmmu_tsb = &ktsb_info[0];
13389 
13390 	sfmmu_setup_tsbinfo(ksfmmup);
13391 }
13392 
13393 /*
13394  * Cache the last value returned from va_to_pa().  If the VA specified
13395  * in the current call to cached_va_to_pa() maps to the same Page (as the
13396  * previous call to cached_va_to_pa()), then compute the PA using
13397  * cached info, else call va_to_pa().
13398  *
13399  * Note: this function is neither MT-safe nor consistent in the presence
13400  * of multiple, interleaved threads.  This function was created to enable
13401  * an optimization used during boot (at a point when there's only one thread
13402  * executing on the "boot CPU", and before startup_vm() has been called).
13403  */
13404 static uint64_t
13405 cached_va_to_pa(void *vaddr)
13406 {
13407 	static uint64_t prev_vaddr_base = 0;
13408 	static uint64_t prev_pfn = 0;
13409 
13410 	if ((((uint64_t)vaddr) & MMU_PAGEMASK) == prev_vaddr_base) {
13411 		return (prev_pfn | ((uint64_t)vaddr & MMU_PAGEOFFSET));
13412 	} else {
13413 		uint64_t pa = va_to_pa(vaddr);
13414 
13415 		if (pa != ((uint64_t)-1)) {
13416 			/*
13417 			 * Computed physical address is valid.  Cache its
13418 			 * related info for the next cached_va_to_pa() call.
13419 			 */
13420 			prev_pfn = pa & MMU_PAGEMASK;
13421 			prev_vaddr_base = ((uint64_t)vaddr) & MMU_PAGEMASK;
13422 		}
13423 
13424 		return (pa);
13425 	}
13426 }
13427 
13428 /*
13429  * Carve up our nucleus hblk region.  We may allocate more hblks than
13430  * asked due to rounding errors but we are guaranteed to have at least
13431  * enough space to allocate the requested number of hblk8's and hblk1's.
13432  */
13433 void
13434 sfmmu_init_nucleus_hblks(caddr_t addr, size_t size, int nhblk8, int nhblk1)
13435 {
13436 	struct hme_blk *hmeblkp;
13437 	size_t hme8blk_sz, hme1blk_sz;
13438 	size_t i;
13439 	size_t hblk8_bound;
13440 	ulong_t j = 0, k = 0;
13441 
13442 	ASSERT(addr != NULL && size != 0);
13443 
13444 	/* Need to use proper structure alignment */
13445 	hme8blk_sz = roundup(HME8BLK_SZ, sizeof (int64_t));
13446 	hme1blk_sz = roundup(HME1BLK_SZ, sizeof (int64_t));
13447 
13448 	nucleus_hblk8.list = (void *)addr;
13449 	nucleus_hblk8.index = 0;
13450 
13451 	/*
13452 	 * Use as much memory as possible for hblk8's since we
13453 	 * expect all bop_alloc'ed memory to be allocated in 8k chunks.
13454 	 * We need to hold back enough space for the hblk1's which
13455 	 * we'll allocate next.
13456 	 */
13457 	hblk8_bound = size - (nhblk1 * hme1blk_sz) - hme8blk_sz;
13458 	for (i = 0; i <= hblk8_bound; i += hme8blk_sz, j++) {
13459 		hmeblkp = (struct hme_blk *)addr;
13460 		addr += hme8blk_sz;
13461 		hmeblkp->hblk_nuc_bit = 1;
13462 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13463 	}
13464 	nucleus_hblk8.len = j;
13465 	ASSERT(j >= nhblk8);
13466 	SFMMU_STAT_ADD(sf_hblk8_ncreate, j);
13467 
13468 	nucleus_hblk1.list = (void *)addr;
13469 	nucleus_hblk1.index = 0;
13470 	for (; i <= (size - hme1blk_sz); i += hme1blk_sz, k++) {
13471 		hmeblkp = (struct hme_blk *)addr;
13472 		addr += hme1blk_sz;
13473 		hmeblkp->hblk_nuc_bit = 1;
13474 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13475 	}
13476 	ASSERT(k >= nhblk1);
13477 	nucleus_hblk1.len = k;
13478 	SFMMU_STAT_ADD(sf_hblk1_ncreate, k);
13479 }
13480 
13481 /*
13482  * This function is currently not supported on this platform. For what
13483  * it's supposed to do, see hat.c and hat_srmmu.c
13484  */
13485 /* ARGSUSED */
13486 faultcode_t
13487 hat_softlock(struct hat *hat, caddr_t addr, size_t *lenp, page_t **ppp,
13488     uint_t flags)
13489 {
13490 	ASSERT(hat->sfmmu_xhat_provider == NULL);
13491 	return (FC_NOSUPPORT);
13492 }
13493 
13494 /*
13495  * Searchs the mapping list of the page for a mapping of the same size. If not
13496  * found the corresponding bit is cleared in the p_index field. When large
13497  * pages are more prevalent in the system, we can maintain the mapping list
13498  * in order and we don't have to traverse the list each time. Just check the
13499  * next and prev entries, and if both are of different size, we clear the bit.
13500  */
13501 static void
13502 sfmmu_rm_large_mappings(page_t *pp, int ttesz)
13503 {
13504 	struct sf_hment *sfhmep;
13505 	struct hme_blk *hmeblkp;
13506 	int	index;
13507 	pgcnt_t	npgs;
13508 
13509 	ASSERT(ttesz > TTE8K);
13510 
13511 	ASSERT(sfmmu_mlist_held(pp));
13512 
13513 	ASSERT(PP_ISMAPPED_LARGE(pp));
13514 
13515 	/*
13516 	 * Traverse mapping list looking for another mapping of same size.
13517 	 * since we only want to clear index field if all mappings of
13518 	 * that size are gone.
13519 	 */
13520 
13521 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
13522 		if (IS_PAHME(sfhmep))
13523 			continue;
13524 		hmeblkp = sfmmu_hmetohblk(sfhmep);
13525 		if (hmeblkp->hblk_xhat_bit)
13526 			continue;
13527 		if (hme_size(sfhmep) == ttesz) {
13528 			/*
13529 			 * another mapping of the same size. don't clear index.
13530 			 */
13531 			return;
13532 		}
13533 	}
13534 
13535 	/*
13536 	 * Clear the p_index bit for large page.
13537 	 */
13538 	index = PAGESZ_TO_INDEX(ttesz);
13539 	npgs = TTEPAGES(ttesz);
13540 	while (npgs-- > 0) {
13541 		ASSERT(pp->p_index & index);
13542 		pp->p_index &= ~index;
13543 		pp = PP_PAGENEXT(pp);
13544 	}
13545 }
13546 
13547 /*
13548  * return supported features
13549  */
13550 /* ARGSUSED */
13551 int
13552 hat_supported(enum hat_features feature, void *arg)
13553 {
13554 	switch (feature) {
13555 	case    HAT_SHARED_PT:
13556 	case	HAT_DYNAMIC_ISM_UNMAP:
13557 	case	HAT_VMODSORT:
13558 		return (1);
13559 	case	HAT_SHARED_REGIONS:
13560 		if (shctx_on)
13561 			return (1);
13562 		else
13563 			return (0);
13564 	default:
13565 		return (0);
13566 	}
13567 }
13568 
13569 void
13570 hat_enter(struct hat *hat)
13571 {
13572 	hatlock_t	*hatlockp;
13573 
13574 	if (hat != ksfmmup) {
13575 		hatlockp = TSB_HASH(hat);
13576 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
13577 	}
13578 }
13579 
13580 void
13581 hat_exit(struct hat *hat)
13582 {
13583 	hatlock_t	*hatlockp;
13584 
13585 	if (hat != ksfmmup) {
13586 		hatlockp = TSB_HASH(hat);
13587 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
13588 	}
13589 }
13590 
13591 /*ARGSUSED*/
13592 void
13593 hat_reserve(struct as *as, caddr_t addr, size_t len)
13594 {
13595 }
13596 
13597 static void
13598 hat_kstat_init(void)
13599 {
13600 	kstat_t *ksp;
13601 
13602 	ksp = kstat_create("unix", 0, "sfmmu_global_stat", "hat",
13603 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_global_stat),
13604 	    KSTAT_FLAG_VIRTUAL);
13605 	if (ksp) {
13606 		ksp->ks_data = (void *) &sfmmu_global_stat;
13607 		kstat_install(ksp);
13608 	}
13609 	ksp = kstat_create("unix", 0, "sfmmu_tsbsize_stat", "hat",
13610 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_tsbsize_stat),
13611 	    KSTAT_FLAG_VIRTUAL);
13612 	if (ksp) {
13613 		ksp->ks_data = (void *) &sfmmu_tsbsize_stat;
13614 		kstat_install(ksp);
13615 	}
13616 	ksp = kstat_create("unix", 0, "sfmmu_percpu_stat", "hat",
13617 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_percpu_stat) * NCPU,
13618 	    KSTAT_FLAG_WRITABLE);
13619 	if (ksp) {
13620 		ksp->ks_update = sfmmu_kstat_percpu_update;
13621 		kstat_install(ksp);
13622 	}
13623 }
13624 
13625 /* ARGSUSED */
13626 static int
13627 sfmmu_kstat_percpu_update(kstat_t *ksp, int rw)
13628 {
13629 	struct sfmmu_percpu_stat *cpu_kstat = ksp->ks_data;
13630 	struct tsbmiss *tsbm = tsbmiss_area;
13631 	struct kpmtsbm *kpmtsbm = kpmtsbm_area;
13632 	int i;
13633 
13634 	ASSERT(cpu_kstat);
13635 	if (rw == KSTAT_READ) {
13636 		for (i = 0; i < NCPU; cpu_kstat++, tsbm++, kpmtsbm++, i++) {
13637 			cpu_kstat->sf_itlb_misses = 0;
13638 			cpu_kstat->sf_dtlb_misses = 0;
13639 			cpu_kstat->sf_utsb_misses = tsbm->utsb_misses -
13640 			    tsbm->uprot_traps;
13641 			cpu_kstat->sf_ktsb_misses = tsbm->ktsb_misses +
13642 			    kpmtsbm->kpm_tsb_misses - tsbm->kprot_traps;
13643 			cpu_kstat->sf_tsb_hits = 0;
13644 			cpu_kstat->sf_umod_faults = tsbm->uprot_traps;
13645 			cpu_kstat->sf_kmod_faults = tsbm->kprot_traps;
13646 		}
13647 	} else {
13648 		/* KSTAT_WRITE is used to clear stats */
13649 		for (i = 0; i < NCPU; tsbm++, kpmtsbm++, i++) {
13650 			tsbm->utsb_misses = 0;
13651 			tsbm->ktsb_misses = 0;
13652 			tsbm->uprot_traps = 0;
13653 			tsbm->kprot_traps = 0;
13654 			kpmtsbm->kpm_dtlb_misses = 0;
13655 			kpmtsbm->kpm_tsb_misses = 0;
13656 		}
13657 	}
13658 	return (0);
13659 }
13660 
13661 #ifdef	DEBUG
13662 
13663 tte_t  *gorig[NCPU], *gcur[NCPU], *gnew[NCPU];
13664 
13665 /*
13666  * A tte checker. *orig_old is the value we read before cas.
13667  *	*cur is the value returned by cas.
13668  *	*new is the desired value when we do the cas.
13669  *
13670  *	*hmeblkp is currently unused.
13671  */
13672 
13673 /* ARGSUSED */
13674 void
13675 chk_tte(tte_t *orig_old, tte_t *cur, tte_t *new, struct hme_blk *hmeblkp)
13676 {
13677 	pfn_t i, j, k;
13678 	int cpuid = CPU->cpu_id;
13679 
13680 	gorig[cpuid] = orig_old;
13681 	gcur[cpuid] = cur;
13682 	gnew[cpuid] = new;
13683 
13684 #ifdef lint
13685 	hmeblkp = hmeblkp;
13686 #endif
13687 
13688 	if (TTE_IS_VALID(orig_old)) {
13689 		if (TTE_IS_VALID(cur)) {
13690 			i = TTE_TO_TTEPFN(orig_old);
13691 			j = TTE_TO_TTEPFN(cur);
13692 			k = TTE_TO_TTEPFN(new);
13693 			if (i != j) {
13694 				/* remap error? */
13695 				panic("chk_tte: bad pfn, 0x%lx, 0x%lx", i, j);
13696 			}
13697 
13698 			if (i != k) {
13699 				/* remap error? */
13700 				panic("chk_tte: bad pfn2, 0x%lx, 0x%lx", i, k);
13701 			}
13702 		} else {
13703 			if (TTE_IS_VALID(new)) {
13704 				panic("chk_tte: invalid cur? ");
13705 			}
13706 
13707 			i = TTE_TO_TTEPFN(orig_old);
13708 			k = TTE_TO_TTEPFN(new);
13709 			if (i != k) {
13710 				panic("chk_tte: bad pfn3, 0x%lx, 0x%lx", i, k);
13711 			}
13712 		}
13713 	} else {
13714 		if (TTE_IS_VALID(cur)) {
13715 			j = TTE_TO_TTEPFN(cur);
13716 			if (TTE_IS_VALID(new)) {
13717 				k = TTE_TO_TTEPFN(new);
13718 				if (j != k) {
13719 					panic("chk_tte: bad pfn4, 0x%lx, 0x%lx",
13720 					    j, k);
13721 				}
13722 			} else {
13723 				panic("chk_tte: why here?");
13724 			}
13725 		} else {
13726 			if (!TTE_IS_VALID(new)) {
13727 				panic("chk_tte: why here2 ?");
13728 			}
13729 		}
13730 	}
13731 }
13732 
13733 #endif /* DEBUG */
13734 
13735 extern void prefetch_tsbe_read(struct tsbe *);
13736 extern void prefetch_tsbe_write(struct tsbe *);
13737 
13738 
13739 /*
13740  * We want to prefetch 7 cache lines ahead for our read prefetch.  This gives
13741  * us optimal performance on Cheetah+.  You can only have 8 outstanding
13742  * prefetches at any one time, so we opted for 7 read prefetches and 1 write
13743  * prefetch to make the most utilization of the prefetch capability.
13744  */
13745 #define	TSBE_PREFETCH_STRIDE (7)
13746 
13747 void
13748 sfmmu_copy_tsb(struct tsb_info *old_tsbinfo, struct tsb_info *new_tsbinfo)
13749 {
13750 	int old_bytes = TSB_BYTES(old_tsbinfo->tsb_szc);
13751 	int new_bytes = TSB_BYTES(new_tsbinfo->tsb_szc);
13752 	int old_entries = TSB_ENTRIES(old_tsbinfo->tsb_szc);
13753 	int new_entries = TSB_ENTRIES(new_tsbinfo->tsb_szc);
13754 	struct tsbe *old;
13755 	struct tsbe *new;
13756 	struct tsbe *new_base = (struct tsbe *)new_tsbinfo->tsb_va;
13757 	uint64_t va;
13758 	int new_offset;
13759 	int i;
13760 	int vpshift;
13761 	int last_prefetch;
13762 
13763 	if (old_bytes == new_bytes) {
13764 		bcopy(old_tsbinfo->tsb_va, new_tsbinfo->tsb_va, new_bytes);
13765 	} else {
13766 
13767 		/*
13768 		 * A TSBE is 16 bytes which means there are four TSBE's per
13769 		 * P$ line (64 bytes), thus every 4 TSBE's we prefetch.
13770 		 */
13771 		old = (struct tsbe *)old_tsbinfo->tsb_va;
13772 		last_prefetch = old_entries - (4*(TSBE_PREFETCH_STRIDE+1));
13773 		for (i = 0; i < old_entries; i++, old++) {
13774 			if (((i & (4-1)) == 0) && (i < last_prefetch))
13775 				prefetch_tsbe_read(old);
13776 			if (!old->tte_tag.tag_invalid) {
13777 				/*
13778 				 * We have a valid TTE to remap.  Check the
13779 				 * size.  We won't remap 64K or 512K TTEs
13780 				 * because they span more than one TSB entry
13781 				 * and are indexed using an 8K virt. page.
13782 				 * Ditto for 32M and 256M TTEs.
13783 				 */
13784 				if (TTE_CSZ(&old->tte_data) == TTE64K ||
13785 				    TTE_CSZ(&old->tte_data) == TTE512K)
13786 					continue;
13787 				if (mmu_page_sizes == max_mmu_page_sizes) {
13788 					if (TTE_CSZ(&old->tte_data) == TTE32M ||
13789 					    TTE_CSZ(&old->tte_data) == TTE256M)
13790 						continue;
13791 				}
13792 
13793 				/* clear the lower 22 bits of the va */
13794 				va = *(uint64_t *)old << 22;
13795 				/* turn va into a virtual pfn */
13796 				va >>= 22 - TSB_START_SIZE;
13797 				/*
13798 				 * or in bits from the offset in the tsb
13799 				 * to get the real virtual pfn. These
13800 				 * correspond to bits [21:13] in the va
13801 				 */
13802 				vpshift =
13803 				    TTE_BSZS_SHIFT(TTE_CSZ(&old->tte_data)) &
13804 				    0x1ff;
13805 				va |= (i << vpshift);
13806 				va >>= vpshift;
13807 				new_offset = va & (new_entries - 1);
13808 				new = new_base + new_offset;
13809 				prefetch_tsbe_write(new);
13810 				*new = *old;
13811 			}
13812 		}
13813 	}
13814 }
13815 
13816 /*
13817  * unused in sfmmu
13818  */
13819 void
13820 hat_dump(void)
13821 {
13822 }
13823 
13824 /*
13825  * Called when a thread is exiting and we have switched to the kernel address
13826  * space.  Perform the same VM initialization resume() uses when switching
13827  * processes.
13828  *
13829  * Note that sfmmu_load_mmustate() is currently a no-op for kernel threads, but
13830  * we call it anyway in case the semantics change in the future.
13831  */
13832 /*ARGSUSED*/
13833 void
13834 hat_thread_exit(kthread_t *thd)
13835 {
13836 	uint_t pgsz_cnum;
13837 	uint_t pstate_save;
13838 
13839 	ASSERT(thd->t_procp->p_as == &kas);
13840 
13841 	pgsz_cnum = KCONTEXT;
13842 #ifdef sun4u
13843 	pgsz_cnum |= (ksfmmup->sfmmu_cext << CTXREG_EXT_SHIFT);
13844 #endif
13845 
13846 	/*
13847 	 * Note that sfmmu_load_mmustate() is currently a no-op for
13848 	 * kernel threads. We need to disable interrupts here,
13849 	 * simply because otherwise sfmmu_load_mmustate() would panic
13850 	 * if the caller does not disable interrupts.
13851 	 */
13852 	pstate_save = sfmmu_disable_intrs();
13853 
13854 	/* Compatibility Note: hw takes care of MMU_SCONTEXT1 */
13855 	sfmmu_setctx_sec(pgsz_cnum);
13856 	sfmmu_load_mmustate(ksfmmup);
13857 	sfmmu_enable_intrs(pstate_save);
13858 }
13859 
13860 
13861 /*
13862  * SRD support
13863  */
13864 #define	SRD_HASH_FUNCTION(vp)	(((((uintptr_t)(vp)) >> 4) ^ \
13865 				    (((uintptr_t)(vp)) >> 11)) & \
13866 				    srd_hashmask)
13867 
13868 /*
13869  * Attach the process to the srd struct associated with the exec vnode
13870  * from which the process is started.
13871  */
13872 void
13873 hat_join_srd(struct hat *sfmmup, vnode_t *evp)
13874 {
13875 	uint_t hash = SRD_HASH_FUNCTION(evp);
13876 	sf_srd_t *srdp;
13877 	sf_srd_t *newsrdp;
13878 
13879 	ASSERT(sfmmup != ksfmmup);
13880 	ASSERT(sfmmup->sfmmu_srdp == NULL);
13881 
13882 	if (!shctx_on) {
13883 		return;
13884 	}
13885 
13886 	VN_HOLD(evp);
13887 
13888 	if (srd_buckets[hash].srdb_srdp != NULL) {
13889 		mutex_enter(&srd_buckets[hash].srdb_lock);
13890 		for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13891 		    srdp = srdp->srd_hash) {
13892 			if (srdp->srd_evp == evp) {
13893 				ASSERT(srdp->srd_refcnt >= 0);
13894 				sfmmup->sfmmu_srdp = srdp;
13895 				atomic_add_32(
13896 				    (volatile uint_t *)&srdp->srd_refcnt, 1);
13897 				mutex_exit(&srd_buckets[hash].srdb_lock);
13898 				return;
13899 			}
13900 		}
13901 		mutex_exit(&srd_buckets[hash].srdb_lock);
13902 	}
13903 	newsrdp = kmem_cache_alloc(srd_cache, KM_SLEEP);
13904 	ASSERT(newsrdp->srd_next_ismrid == 0 && newsrdp->srd_next_hmerid == 0);
13905 
13906 	newsrdp->srd_evp = evp;
13907 	newsrdp->srd_refcnt = 1;
13908 	newsrdp->srd_hmergnfree = NULL;
13909 	newsrdp->srd_ismrgnfree = NULL;
13910 
13911 	mutex_enter(&srd_buckets[hash].srdb_lock);
13912 	for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13913 	    srdp = srdp->srd_hash) {
13914 		if (srdp->srd_evp == evp) {
13915 			ASSERT(srdp->srd_refcnt >= 0);
13916 			sfmmup->sfmmu_srdp = srdp;
13917 			atomic_add_32((volatile uint_t *)&srdp->srd_refcnt, 1);
13918 			mutex_exit(&srd_buckets[hash].srdb_lock);
13919 			kmem_cache_free(srd_cache, newsrdp);
13920 			return;
13921 		}
13922 	}
13923 	newsrdp->srd_hash = srd_buckets[hash].srdb_srdp;
13924 	srd_buckets[hash].srdb_srdp = newsrdp;
13925 	sfmmup->sfmmu_srdp = newsrdp;
13926 
13927 	mutex_exit(&srd_buckets[hash].srdb_lock);
13928 
13929 }
13930 
13931 static void
13932 sfmmu_leave_srd(sfmmu_t *sfmmup)
13933 {
13934 	vnode_t *evp;
13935 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13936 	uint_t hash;
13937 	sf_srd_t **prev_srdpp;
13938 	sf_region_t *rgnp;
13939 	sf_region_t *nrgnp;
13940 #ifdef DEBUG
13941 	int rgns = 0;
13942 #endif
13943 	int i;
13944 
13945 	ASSERT(sfmmup != ksfmmup);
13946 	ASSERT(srdp != NULL);
13947 	ASSERT(srdp->srd_refcnt > 0);
13948 	ASSERT(sfmmup->sfmmu_scdp == NULL);
13949 	ASSERT(sfmmup->sfmmu_free == 1);
13950 
13951 	sfmmup->sfmmu_srdp = NULL;
13952 	evp = srdp->srd_evp;
13953 	ASSERT(evp != NULL);
13954 	if (atomic_add_32_nv(
13955 	    (volatile uint_t *)&srdp->srd_refcnt, -1)) {
13956 		VN_RELE(evp);
13957 		return;
13958 	}
13959 
13960 	hash = SRD_HASH_FUNCTION(evp);
13961 	mutex_enter(&srd_buckets[hash].srdb_lock);
13962 	for (prev_srdpp = &srd_buckets[hash].srdb_srdp;
13963 	    (srdp = *prev_srdpp) != NULL; prev_srdpp = &srdp->srd_hash) {
13964 		if (srdp->srd_evp == evp) {
13965 			break;
13966 		}
13967 	}
13968 	if (srdp == NULL || srdp->srd_refcnt) {
13969 		mutex_exit(&srd_buckets[hash].srdb_lock);
13970 		VN_RELE(evp);
13971 		return;
13972 	}
13973 	*prev_srdpp = srdp->srd_hash;
13974 	mutex_exit(&srd_buckets[hash].srdb_lock);
13975 
13976 	ASSERT(srdp->srd_refcnt == 0);
13977 	VN_RELE(evp);
13978 
13979 #ifdef DEBUG
13980 	for (i = 0; i < SFMMU_MAX_REGION_BUCKETS; i++) {
13981 		ASSERT(srdp->srd_rgnhash[i] == NULL);
13982 	}
13983 #endif /* DEBUG */
13984 
13985 	/* free each hme regions in the srd */
13986 	for (rgnp = srdp->srd_hmergnfree; rgnp != NULL; rgnp = nrgnp) {
13987 		nrgnp = rgnp->rgn_next;
13988 		ASSERT(rgnp->rgn_id < srdp->srd_next_hmerid);
13989 		ASSERT(rgnp->rgn_refcnt == 0);
13990 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13991 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13992 		ASSERT(rgnp->rgn_hmeflags == 0);
13993 		ASSERT(srdp->srd_hmergnp[rgnp->rgn_id] == rgnp);
13994 #ifdef DEBUG
13995 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13996 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13997 		}
13998 		rgns++;
13999 #endif /* DEBUG */
14000 		kmem_cache_free(region_cache, rgnp);
14001 	}
14002 	ASSERT(rgns == srdp->srd_next_hmerid);
14003 
14004 #ifdef DEBUG
14005 	rgns = 0;
14006 #endif
14007 	/* free each ism rgns in the srd */
14008 	for (rgnp = srdp->srd_ismrgnfree; rgnp != NULL; rgnp = nrgnp) {
14009 		nrgnp = rgnp->rgn_next;
14010 		ASSERT(rgnp->rgn_id < srdp->srd_next_ismrid);
14011 		ASSERT(rgnp->rgn_refcnt == 0);
14012 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
14013 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
14014 		ASSERT(srdp->srd_ismrgnp[rgnp->rgn_id] == rgnp);
14015 #ifdef DEBUG
14016 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
14017 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
14018 		}
14019 		rgns++;
14020 #endif /* DEBUG */
14021 		kmem_cache_free(region_cache, rgnp);
14022 	}
14023 	ASSERT(rgns == srdp->srd_next_ismrid);
14024 	ASSERT(srdp->srd_ismbusyrgns == 0);
14025 	ASSERT(srdp->srd_hmebusyrgns == 0);
14026 
14027 	srdp->srd_next_ismrid = 0;
14028 	srdp->srd_next_hmerid = 0;
14029 
14030 	bzero((void *)srdp->srd_ismrgnp,
14031 	    sizeof (sf_region_t *) * SFMMU_MAX_ISM_REGIONS);
14032 	bzero((void *)srdp->srd_hmergnp,
14033 	    sizeof (sf_region_t *) * SFMMU_MAX_HME_REGIONS);
14034 
14035 	ASSERT(srdp->srd_scdp == NULL);
14036 	kmem_cache_free(srd_cache, srdp);
14037 }
14038 
14039 /* ARGSUSED */
14040 static int
14041 sfmmu_srdcache_constructor(void *buf, void *cdrarg, int kmflags)
14042 {
14043 	sf_srd_t *srdp = (sf_srd_t *)buf;
14044 	bzero(buf, sizeof (*srdp));
14045 
14046 	mutex_init(&srdp->srd_mutex, NULL, MUTEX_DEFAULT, NULL);
14047 	mutex_init(&srdp->srd_scd_mutex, NULL, MUTEX_DEFAULT, NULL);
14048 	return (0);
14049 }
14050 
14051 /* ARGSUSED */
14052 static void
14053 sfmmu_srdcache_destructor(void *buf, void *cdrarg)
14054 {
14055 	sf_srd_t *srdp = (sf_srd_t *)buf;
14056 
14057 	mutex_destroy(&srdp->srd_mutex);
14058 	mutex_destroy(&srdp->srd_scd_mutex);
14059 }
14060 
14061 /*
14062  * The caller makes sure hat_join_region()/hat_leave_region() can't be called
14063  * at the same time for the same process and address range. This is ensured by
14064  * the fact that address space is locked as writer when a process joins the
14065  * regions. Therefore there's no need to hold an srd lock during the entire
14066  * execution of hat_join_region()/hat_leave_region().
14067  */
14068 
14069 #define	RGN_HASH_FUNCTION(obj)	(((((uintptr_t)(obj)) >> 4) ^ \
14070 				    (((uintptr_t)(obj)) >> 11)) & \
14071 					srd_rgn_hashmask)
14072 /*
14073  * This routine implements the shared context functionality required when
14074  * attaching a segment to an address space. It must be called from
14075  * hat_share() for D(ISM) segments and from segvn_create() for segments
14076  * with the MAP_PRIVATE and MAP_TEXT flags set. It returns a region_cookie
14077  * which is saved in the private segment data for hme segments and
14078  * the ism_map structure for ism segments.
14079  */
14080 hat_region_cookie_t
14081 hat_join_region(struct hat *sfmmup,
14082 	caddr_t r_saddr,
14083 	size_t r_size,
14084 	void *r_obj,
14085 	u_offset_t r_objoff,
14086 	uchar_t r_perm,
14087 	uchar_t r_pgszc,
14088 	hat_rgn_cb_func_t r_cb_function,
14089 	uint_t flags)
14090 {
14091 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14092 	uint_t rhash;
14093 	uint_t rid;
14094 	hatlock_t *hatlockp;
14095 	sf_region_t *rgnp;
14096 	sf_region_t *new_rgnp = NULL;
14097 	int i;
14098 	uint16_t *nextidp;
14099 	sf_region_t **freelistp;
14100 	int maxids;
14101 	sf_region_t **rarrp;
14102 	uint16_t *busyrgnsp;
14103 	ulong_t rttecnt;
14104 	uchar_t tteflag;
14105 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
14106 	int text = (r_type == HAT_REGION_TEXT);
14107 
14108 	if (srdp == NULL || r_size == 0) {
14109 		return (HAT_INVALID_REGION_COOKIE);
14110 	}
14111 
14112 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
14113 	ASSERT(sfmmup != ksfmmup);
14114 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
14115 	ASSERT(srdp->srd_refcnt > 0);
14116 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
14117 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
14118 	ASSERT(r_pgszc < mmu_page_sizes);
14119 	if (!IS_P2ALIGNED(r_saddr, TTEBYTES(r_pgszc)) ||
14120 	    !IS_P2ALIGNED(r_size, TTEBYTES(r_pgszc))) {
14121 		panic("hat_join_region: region addr or size is not aligned\n");
14122 	}
14123 
14124 
14125 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
14126 	    SFMMU_REGION_HME;
14127 	/*
14128 	 * Currently only support shared hmes for the read only main text
14129 	 * region.
14130 	 */
14131 	if (r_type == SFMMU_REGION_HME && ((r_obj != srdp->srd_evp) ||
14132 	    (r_perm & PROT_WRITE))) {
14133 		return (HAT_INVALID_REGION_COOKIE);
14134 	}
14135 
14136 	rhash = RGN_HASH_FUNCTION(r_obj);
14137 
14138 	if (r_type == SFMMU_REGION_ISM) {
14139 		nextidp = &srdp->srd_next_ismrid;
14140 		freelistp = &srdp->srd_ismrgnfree;
14141 		maxids = SFMMU_MAX_ISM_REGIONS;
14142 		rarrp = srdp->srd_ismrgnp;
14143 		busyrgnsp = &srdp->srd_ismbusyrgns;
14144 	} else {
14145 		nextidp = &srdp->srd_next_hmerid;
14146 		freelistp = &srdp->srd_hmergnfree;
14147 		maxids = SFMMU_MAX_HME_REGIONS;
14148 		rarrp = srdp->srd_hmergnp;
14149 		busyrgnsp = &srdp->srd_hmebusyrgns;
14150 	}
14151 
14152 	mutex_enter(&srdp->srd_mutex);
14153 
14154 	for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
14155 	    rgnp = rgnp->rgn_hash) {
14156 		if (rgnp->rgn_saddr == r_saddr && rgnp->rgn_size == r_size &&
14157 		    rgnp->rgn_obj == r_obj && rgnp->rgn_objoff == r_objoff &&
14158 		    rgnp->rgn_perm == r_perm && rgnp->rgn_pgszc == r_pgszc) {
14159 			break;
14160 		}
14161 	}
14162 
14163 rfound:
14164 	if (rgnp != NULL) {
14165 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14166 		ASSERT(rgnp->rgn_cb_function == r_cb_function);
14167 		ASSERT(rgnp->rgn_refcnt >= 0);
14168 		rid = rgnp->rgn_id;
14169 		ASSERT(rid < maxids);
14170 		ASSERT(rarrp[rid] == rgnp);
14171 		ASSERT(rid < *nextidp);
14172 		atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
14173 		mutex_exit(&srdp->srd_mutex);
14174 		if (new_rgnp != NULL) {
14175 			kmem_cache_free(region_cache, new_rgnp);
14176 		}
14177 		if (r_type == SFMMU_REGION_HME) {
14178 			int myjoin =
14179 			    (sfmmup == astosfmmu(curthread->t_procp->p_as));
14180 
14181 			sfmmu_link_to_hmeregion(sfmmup, rgnp);
14182 			/*
14183 			 * bitmap should be updated after linking sfmmu on
14184 			 * region list so that pageunload() doesn't skip
14185 			 * TSB/TLB flush. As soon as bitmap is updated another
14186 			 * thread in this process can already start accessing
14187 			 * this region.
14188 			 */
14189 			/*
14190 			 * Normally ttecnt accounting is done as part of
14191 			 * pagefault handling. But a process may not take any
14192 			 * pagefaults on shared hmeblks created by some other
14193 			 * process. To compensate for this assume that the
14194 			 * entire region will end up faulted in using
14195 			 * the region's pagesize.
14196 			 *
14197 			 */
14198 			if (r_pgszc > TTE8K) {
14199 				tteflag = 1 << r_pgszc;
14200 				if (disable_large_pages & tteflag) {
14201 					tteflag = 0;
14202 				}
14203 			} else {
14204 				tteflag = 0;
14205 			}
14206 			if (tteflag && !(sfmmup->sfmmu_rtteflags & tteflag)) {
14207 				hatlockp = sfmmu_hat_enter(sfmmup);
14208 				sfmmup->sfmmu_rtteflags |= tteflag;
14209 				sfmmu_hat_exit(hatlockp);
14210 			}
14211 			hatlockp = sfmmu_hat_enter(sfmmup);
14212 
14213 			/*
14214 			 * Preallocate 1/4 of ttecnt's in 8K TSB for >= 4M
14215 			 * region to allow for large page allocation failure.
14216 			 */
14217 			if (r_pgszc >= TTE4M) {
14218 				sfmmup->sfmmu_tsb0_4minflcnt +=
14219 				    r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14220 			}
14221 
14222 			/* update sfmmu_ttecnt with the shme rgn ttecnt */
14223 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14224 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14225 			    rttecnt);
14226 
14227 			if (text && r_pgszc >= TTE4M &&
14228 			    (tteflag || ((disable_large_pages >> TTE4M) &
14229 			    ((1 << (r_pgszc - TTE4M + 1)) - 1))) &&
14230 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
14231 				SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
14232 			}
14233 
14234 			sfmmu_hat_exit(hatlockp);
14235 			/*
14236 			 * On Panther we need to make sure TLB is programmed
14237 			 * to accept 32M/256M pages.  Call
14238 			 * sfmmu_check_page_sizes() now to make sure TLB is
14239 			 * setup before making hmeregions visible to other
14240 			 * threads.
14241 			 */
14242 			sfmmu_check_page_sizes(sfmmup, 1);
14243 			hatlockp = sfmmu_hat_enter(sfmmup);
14244 			SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14245 
14246 			/*
14247 			 * if context is invalid tsb miss exception code will
14248 			 * call sfmmu_check_page_sizes() and update tsbmiss
14249 			 * area later.
14250 			 */
14251 			kpreempt_disable();
14252 			if (myjoin &&
14253 			    (sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
14254 			    != INVALID_CONTEXT)) {
14255 				struct tsbmiss *tsbmp;
14256 
14257 				tsbmp = &tsbmiss_area[CPU->cpu_id];
14258 				ASSERT(sfmmup == tsbmp->usfmmup);
14259 				BT_SET(tsbmp->shmermap, rid);
14260 				if (r_pgszc > TTE64K) {
14261 					tsbmp->uhat_rtteflags |= tteflag;
14262 				}
14263 
14264 			}
14265 			kpreempt_enable();
14266 
14267 			sfmmu_hat_exit(hatlockp);
14268 			ASSERT((hat_region_cookie_t)((uint64_t)rid) !=
14269 			    HAT_INVALID_REGION_COOKIE);
14270 		} else {
14271 			hatlockp = sfmmu_hat_enter(sfmmup);
14272 			SF_RGNMAP_ADD(sfmmup->sfmmu_ismregion_map, rid);
14273 			sfmmu_hat_exit(hatlockp);
14274 		}
14275 		ASSERT(rid < maxids);
14276 
14277 		if (r_type == SFMMU_REGION_ISM) {
14278 			sfmmu_find_scd(sfmmup);
14279 		}
14280 		return ((hat_region_cookie_t)((uint64_t)rid));
14281 	}
14282 
14283 	ASSERT(new_rgnp == NULL);
14284 
14285 	if (*busyrgnsp >= maxids) {
14286 		mutex_exit(&srdp->srd_mutex);
14287 		return (HAT_INVALID_REGION_COOKIE);
14288 	}
14289 
14290 	ASSERT(MUTEX_HELD(&srdp->srd_mutex));
14291 	if (*freelistp != NULL) {
14292 		rgnp = *freelistp;
14293 		*freelistp = rgnp->rgn_next;
14294 		ASSERT(rgnp->rgn_id < *nextidp);
14295 		ASSERT(rgnp->rgn_id < maxids);
14296 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
14297 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK)
14298 		    == r_type);
14299 		ASSERT(rarrp[rgnp->rgn_id] == rgnp);
14300 		ASSERT(rgnp->rgn_hmeflags == 0);
14301 	} else {
14302 		/*
14303 		 * release local locks before memory allocation.
14304 		 */
14305 		mutex_exit(&srdp->srd_mutex);
14306 
14307 		new_rgnp = kmem_cache_alloc(region_cache, KM_SLEEP);
14308 
14309 		mutex_enter(&srdp->srd_mutex);
14310 		for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
14311 		    rgnp = rgnp->rgn_hash) {
14312 			if (rgnp->rgn_saddr == r_saddr &&
14313 			    rgnp->rgn_size == r_size &&
14314 			    rgnp->rgn_obj == r_obj &&
14315 			    rgnp->rgn_objoff == r_objoff &&
14316 			    rgnp->rgn_perm == r_perm &&
14317 			    rgnp->rgn_pgszc == r_pgszc) {
14318 				break;
14319 			}
14320 		}
14321 		if (rgnp != NULL) {
14322 			goto rfound;
14323 		}
14324 
14325 		if (*nextidp >= maxids) {
14326 			mutex_exit(&srdp->srd_mutex);
14327 			goto fail;
14328 		}
14329 		rgnp = new_rgnp;
14330 		new_rgnp = NULL;
14331 		rgnp->rgn_id = (*nextidp)++;
14332 		ASSERT(rgnp->rgn_id < maxids);
14333 		ASSERT(rarrp[rgnp->rgn_id] == NULL);
14334 		rarrp[rgnp->rgn_id] = rgnp;
14335 	}
14336 
14337 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14338 	ASSERT(rgnp->rgn_hmeflags == 0);
14339 #ifdef DEBUG
14340 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14341 		ASSERT(rgnp->rgn_ttecnt[i] == 0);
14342 	}
14343 #endif
14344 	rgnp->rgn_saddr = r_saddr;
14345 	rgnp->rgn_size = r_size;
14346 	rgnp->rgn_obj = r_obj;
14347 	rgnp->rgn_objoff = r_objoff;
14348 	rgnp->rgn_perm = r_perm;
14349 	rgnp->rgn_pgszc = r_pgszc;
14350 	rgnp->rgn_flags = r_type;
14351 	rgnp->rgn_refcnt = 0;
14352 	rgnp->rgn_cb_function = r_cb_function;
14353 	rgnp->rgn_hash = srdp->srd_rgnhash[rhash];
14354 	srdp->srd_rgnhash[rhash] = rgnp;
14355 	(*busyrgnsp)++;
14356 	ASSERT(*busyrgnsp <= maxids);
14357 	goto rfound;
14358 
14359 fail:
14360 	ASSERT(new_rgnp != NULL);
14361 	kmem_cache_free(region_cache, new_rgnp);
14362 	return (HAT_INVALID_REGION_COOKIE);
14363 }
14364 
14365 /*
14366  * This function implements the shared context functionality required
14367  * when detaching a segment from an address space. It must be called
14368  * from hat_unshare() for all D(ISM) segments and from segvn_unmap(),
14369  * for segments with a valid region_cookie.
14370  * It will also be called from all seg_vn routines which change a
14371  * segment's attributes such as segvn_setprot(), segvn_setpagesize(),
14372  * segvn_clrszc() & segvn_advise(), as well as in the case of COW fault
14373  * from segvn_fault().
14374  */
14375 void
14376 hat_leave_region(struct hat *sfmmup, hat_region_cookie_t rcookie, uint_t flags)
14377 {
14378 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14379 	sf_scd_t *scdp;
14380 	uint_t rhash;
14381 	uint_t rid = (uint_t)((uint64_t)rcookie);
14382 	hatlock_t *hatlockp = NULL;
14383 	sf_region_t *rgnp;
14384 	sf_region_t **prev_rgnpp;
14385 	sf_region_t *cur_rgnp;
14386 	void *r_obj;
14387 	int i;
14388 	caddr_t	r_saddr;
14389 	caddr_t r_eaddr;
14390 	size_t	r_size;
14391 	uchar_t	r_pgszc;
14392 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
14393 
14394 	ASSERT(sfmmup != ksfmmup);
14395 	ASSERT(srdp != NULL);
14396 	ASSERT(srdp->srd_refcnt > 0);
14397 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
14398 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
14399 	ASSERT(!sfmmup->sfmmu_free || sfmmup->sfmmu_scdp == NULL);
14400 
14401 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
14402 	    SFMMU_REGION_HME;
14403 
14404 	if (r_type == SFMMU_REGION_ISM) {
14405 		ASSERT(SFMMU_IS_ISMRID_VALID(rid));
14406 		ASSERT(rid < SFMMU_MAX_ISM_REGIONS);
14407 		rgnp = srdp->srd_ismrgnp[rid];
14408 	} else {
14409 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14410 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14411 		rgnp = srdp->srd_hmergnp[rid];
14412 	}
14413 	ASSERT(rgnp != NULL);
14414 	ASSERT(rgnp->rgn_id == rid);
14415 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14416 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14417 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
14418 
14419 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
14420 	if (r_type == SFMMU_REGION_HME && sfmmup->sfmmu_as->a_xhat != NULL) {
14421 		xhat_unload_callback_all(sfmmup->sfmmu_as, rgnp->rgn_saddr,
14422 		    rgnp->rgn_size, 0, NULL);
14423 	}
14424 
14425 	if (sfmmup->sfmmu_free) {
14426 		ulong_t rttecnt;
14427 		r_pgszc = rgnp->rgn_pgszc;
14428 		r_size = rgnp->rgn_size;
14429 
14430 		ASSERT(sfmmup->sfmmu_scdp == NULL);
14431 		if (r_type == SFMMU_REGION_ISM) {
14432 			SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14433 		} else {
14434 			/* update shme rgns ttecnt in sfmmu_ttecnt */
14435 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14436 			ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14437 
14438 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14439 			    -rttecnt);
14440 
14441 			SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14442 		}
14443 	} else if (r_type == SFMMU_REGION_ISM) {
14444 		hatlockp = sfmmu_hat_enter(sfmmup);
14445 		ASSERT(rid < srdp->srd_next_ismrid);
14446 		SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14447 		scdp = sfmmup->sfmmu_scdp;
14448 		if (scdp != NULL &&
14449 		    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
14450 			sfmmu_leave_scd(sfmmup, r_type);
14451 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14452 		}
14453 		sfmmu_hat_exit(hatlockp);
14454 	} else {
14455 		ulong_t rttecnt;
14456 		r_pgszc = rgnp->rgn_pgszc;
14457 		r_saddr = rgnp->rgn_saddr;
14458 		r_size = rgnp->rgn_size;
14459 		r_eaddr = r_saddr + r_size;
14460 
14461 		ASSERT(r_type == SFMMU_REGION_HME);
14462 		hatlockp = sfmmu_hat_enter(sfmmup);
14463 		ASSERT(rid < srdp->srd_next_hmerid);
14464 		SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14465 
14466 		/*
14467 		 * If region is part of an SCD call sfmmu_leave_scd().
14468 		 * Otherwise if process is not exiting and has valid context
14469 		 * just drop the context on the floor to lose stale TLB
14470 		 * entries and force the update of tsb miss area to reflect
14471 		 * the new region map. After that clean our TSB entries.
14472 		 */
14473 		scdp = sfmmup->sfmmu_scdp;
14474 		if (scdp != NULL &&
14475 		    SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
14476 			sfmmu_leave_scd(sfmmup, r_type);
14477 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14478 		}
14479 		sfmmu_invalidate_ctx(sfmmup);
14480 
14481 		i = TTE8K;
14482 		while (i < mmu_page_sizes) {
14483 			if (rgnp->rgn_ttecnt[i] != 0) {
14484 				sfmmu_unload_tsb_range(sfmmup, r_saddr,
14485 				    r_eaddr, i);
14486 				if (i < TTE4M) {
14487 					i = TTE4M;
14488 					continue;
14489 				} else {
14490 					break;
14491 				}
14492 			}
14493 			i++;
14494 		}
14495 		/* Remove the preallocated 1/4 8k ttecnt for 4M regions. */
14496 		if (r_pgszc >= TTE4M) {
14497 			rttecnt = r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14498 			ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
14499 			    rttecnt);
14500 			sfmmup->sfmmu_tsb0_4minflcnt -= rttecnt;
14501 		}
14502 
14503 		/* update shme rgns ttecnt in sfmmu_ttecnt */
14504 		rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14505 		ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14506 		atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc], -rttecnt);
14507 
14508 		sfmmu_hat_exit(hatlockp);
14509 		if (scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
14510 			/* sfmmup left the scd, grow private tsb */
14511 			sfmmu_check_page_sizes(sfmmup, 1);
14512 		} else {
14513 			sfmmu_check_page_sizes(sfmmup, 0);
14514 		}
14515 	}
14516 
14517 	if (r_type == SFMMU_REGION_HME) {
14518 		sfmmu_unlink_from_hmeregion(sfmmup, rgnp);
14519 	}
14520 
14521 	r_obj = rgnp->rgn_obj;
14522 	if (atomic_add_32_nv((volatile uint_t *)&rgnp->rgn_refcnt, -1)) {
14523 		return;
14524 	}
14525 
14526 	/*
14527 	 * looks like nobody uses this region anymore. Free it.
14528 	 */
14529 	rhash = RGN_HASH_FUNCTION(r_obj);
14530 	mutex_enter(&srdp->srd_mutex);
14531 	for (prev_rgnpp = &srdp->srd_rgnhash[rhash];
14532 	    (cur_rgnp = *prev_rgnpp) != NULL;
14533 	    prev_rgnpp = &cur_rgnp->rgn_hash) {
14534 		if (cur_rgnp == rgnp && cur_rgnp->rgn_refcnt == 0) {
14535 			break;
14536 		}
14537 	}
14538 
14539 	if (cur_rgnp == NULL) {
14540 		mutex_exit(&srdp->srd_mutex);
14541 		return;
14542 	}
14543 
14544 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14545 	*prev_rgnpp = rgnp->rgn_hash;
14546 	if (r_type == SFMMU_REGION_ISM) {
14547 		rgnp->rgn_flags |= SFMMU_REGION_FREE;
14548 		ASSERT(rid < srdp->srd_next_ismrid);
14549 		rgnp->rgn_next = srdp->srd_ismrgnfree;
14550 		srdp->srd_ismrgnfree = rgnp;
14551 		ASSERT(srdp->srd_ismbusyrgns > 0);
14552 		srdp->srd_ismbusyrgns--;
14553 		mutex_exit(&srdp->srd_mutex);
14554 		return;
14555 	}
14556 	mutex_exit(&srdp->srd_mutex);
14557 
14558 	/*
14559 	 * Destroy region's hmeblks.
14560 	 */
14561 	sfmmu_unload_hmeregion(srdp, rgnp);
14562 
14563 	rgnp->rgn_hmeflags = 0;
14564 
14565 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14566 	ASSERT(rgnp->rgn_id == rid);
14567 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14568 		rgnp->rgn_ttecnt[i] = 0;
14569 	}
14570 	rgnp->rgn_flags |= SFMMU_REGION_FREE;
14571 	mutex_enter(&srdp->srd_mutex);
14572 	ASSERT(rid < srdp->srd_next_hmerid);
14573 	rgnp->rgn_next = srdp->srd_hmergnfree;
14574 	srdp->srd_hmergnfree = rgnp;
14575 	ASSERT(srdp->srd_hmebusyrgns > 0);
14576 	srdp->srd_hmebusyrgns--;
14577 	mutex_exit(&srdp->srd_mutex);
14578 }
14579 
14580 /*
14581  * For now only called for hmeblk regions and not for ISM regions.
14582  */
14583 void
14584 hat_dup_region(struct hat *sfmmup, hat_region_cookie_t rcookie)
14585 {
14586 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14587 	uint_t rid = (uint_t)((uint64_t)rcookie);
14588 	sf_region_t *rgnp;
14589 	sf_rgn_link_t *rlink;
14590 	sf_rgn_link_t *hrlink;
14591 	ulong_t	rttecnt;
14592 
14593 	ASSERT(sfmmup != ksfmmup);
14594 	ASSERT(srdp != NULL);
14595 	ASSERT(srdp->srd_refcnt > 0);
14596 
14597 	ASSERT(rid < srdp->srd_next_hmerid);
14598 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14599 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14600 
14601 	rgnp = srdp->srd_hmergnp[rid];
14602 	ASSERT(rgnp->rgn_refcnt > 0);
14603 	ASSERT(rgnp->rgn_id == rid);
14604 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == SFMMU_REGION_HME);
14605 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14606 
14607 	atomic_add_32((volatile uint_t *)&rgnp->rgn_refcnt, 1);
14608 
14609 	/* LINTED: constant in conditional context */
14610 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 0);
14611 	ASSERT(rlink != NULL);
14612 	mutex_enter(&rgnp->rgn_mutex);
14613 	ASSERT(rgnp->rgn_sfmmu_head != NULL);
14614 	/* LINTED: constant in conditional context */
14615 	SFMMU_HMERID2RLINKP(rgnp->rgn_sfmmu_head, rid, hrlink, 0, 0);
14616 	ASSERT(hrlink != NULL);
14617 	ASSERT(hrlink->prev == NULL);
14618 	rlink->next = rgnp->rgn_sfmmu_head;
14619 	rlink->prev = NULL;
14620 	hrlink->prev = sfmmup;
14621 	/*
14622 	 * make sure rlink's next field is correct
14623 	 * before making this link visible.
14624 	 */
14625 	membar_stst();
14626 	rgnp->rgn_sfmmu_head = sfmmup;
14627 	mutex_exit(&rgnp->rgn_mutex);
14628 
14629 	/* update sfmmu_ttecnt with the shme rgn ttecnt */
14630 	rttecnt = rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
14631 	atomic_add_long(&sfmmup->sfmmu_ttecnt[rgnp->rgn_pgszc], rttecnt);
14632 	/* update tsb0 inflation count */
14633 	if (rgnp->rgn_pgszc >= TTE4M) {
14634 		sfmmup->sfmmu_tsb0_4minflcnt +=
14635 		    rgnp->rgn_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14636 	}
14637 	/*
14638 	 * Update regionid bitmask without hat lock since no other thread
14639 	 * can update this region bitmask right now.
14640 	 */
14641 	SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14642 }
14643 
14644 /* ARGSUSED */
14645 static int
14646 sfmmu_rgncache_constructor(void *buf, void *cdrarg, int kmflags)
14647 {
14648 	sf_region_t *rgnp = (sf_region_t *)buf;
14649 	bzero(buf, sizeof (*rgnp));
14650 
14651 	mutex_init(&rgnp->rgn_mutex, NULL, MUTEX_DEFAULT, NULL);
14652 
14653 	return (0);
14654 }
14655 
14656 /* ARGSUSED */
14657 static void
14658 sfmmu_rgncache_destructor(void *buf, void *cdrarg)
14659 {
14660 	sf_region_t *rgnp = (sf_region_t *)buf;
14661 	mutex_destroy(&rgnp->rgn_mutex);
14662 }
14663 
14664 static int
14665 sfrgnmap_isnull(sf_region_map_t *map)
14666 {
14667 	int i;
14668 
14669 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14670 		if (map->bitmap[i] != 0) {
14671 			return (0);
14672 		}
14673 	}
14674 	return (1);
14675 }
14676 
14677 static int
14678 sfhmergnmap_isnull(sf_hmeregion_map_t *map)
14679 {
14680 	int i;
14681 
14682 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
14683 		if (map->bitmap[i] != 0) {
14684 			return (0);
14685 		}
14686 	}
14687 	return (1);
14688 }
14689 
14690 #ifdef DEBUG
14691 static void
14692 check_scd_sfmmu_list(sfmmu_t **headp, sfmmu_t *sfmmup, int onlist)
14693 {
14694 	sfmmu_t *sp;
14695 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14696 
14697 	for (sp = *headp; sp != NULL; sp = sp->sfmmu_scd_link.next) {
14698 		ASSERT(srdp == sp->sfmmu_srdp);
14699 		if (sp == sfmmup) {
14700 			if (onlist) {
14701 				return;
14702 			} else {
14703 				panic("shctx: sfmmu 0x%p found on scd"
14704 				    "list 0x%p", (void *)sfmmup,
14705 				    (void *)*headp);
14706 			}
14707 		}
14708 	}
14709 	if (onlist) {
14710 		panic("shctx: sfmmu 0x%p not found on scd list 0x%p",
14711 		    (void *)sfmmup, (void *)*headp);
14712 	} else {
14713 		return;
14714 	}
14715 }
14716 #else /* DEBUG */
14717 #define	check_scd_sfmmu_list(headp, sfmmup, onlist)
14718 #endif /* DEBUG */
14719 
14720 /*
14721  * Removes an sfmmu from the SCD sfmmu list.
14722  */
14723 static void
14724 sfmmu_from_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14725 {
14726 	ASSERT(sfmmup->sfmmu_srdp != NULL);
14727 	check_scd_sfmmu_list(headp, sfmmup, 1);
14728 	if (sfmmup->sfmmu_scd_link.prev != NULL) {
14729 		ASSERT(*headp != sfmmup);
14730 		sfmmup->sfmmu_scd_link.prev->sfmmu_scd_link.next =
14731 		    sfmmup->sfmmu_scd_link.next;
14732 	} else {
14733 		ASSERT(*headp == sfmmup);
14734 		*headp = sfmmup->sfmmu_scd_link.next;
14735 	}
14736 	if (sfmmup->sfmmu_scd_link.next != NULL) {
14737 		sfmmup->sfmmu_scd_link.next->sfmmu_scd_link.prev =
14738 		    sfmmup->sfmmu_scd_link.prev;
14739 	}
14740 }
14741 
14742 
14743 /*
14744  * Adds an sfmmu to the start of the queue.
14745  */
14746 static void
14747 sfmmu_to_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14748 {
14749 	check_scd_sfmmu_list(headp, sfmmup, 0);
14750 	sfmmup->sfmmu_scd_link.prev = NULL;
14751 	sfmmup->sfmmu_scd_link.next = *headp;
14752 	if (*headp != NULL)
14753 		(*headp)->sfmmu_scd_link.prev = sfmmup;
14754 	*headp = sfmmup;
14755 }
14756 
14757 /*
14758  * Remove an scd from the start of the queue.
14759  */
14760 static void
14761 sfmmu_remove_scd(sf_scd_t **headp, sf_scd_t *scdp)
14762 {
14763 	if (scdp->scd_prev != NULL) {
14764 		ASSERT(*headp != scdp);
14765 		scdp->scd_prev->scd_next = scdp->scd_next;
14766 	} else {
14767 		ASSERT(*headp == scdp);
14768 		*headp = scdp->scd_next;
14769 	}
14770 
14771 	if (scdp->scd_next != NULL) {
14772 		scdp->scd_next->scd_prev = scdp->scd_prev;
14773 	}
14774 }
14775 
14776 /*
14777  * Add an scd to the start of the queue.
14778  */
14779 static void
14780 sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *scdp)
14781 {
14782 	scdp->scd_prev = NULL;
14783 	scdp->scd_next = *headp;
14784 	if (*headp != NULL) {
14785 		(*headp)->scd_prev = scdp;
14786 	}
14787 	*headp = scdp;
14788 }
14789 
14790 static int
14791 sfmmu_alloc_scd_tsbs(sf_srd_t *srdp, sf_scd_t *scdp)
14792 {
14793 	uint_t rid;
14794 	uint_t i;
14795 	uint_t j;
14796 	ulong_t w;
14797 	sf_region_t *rgnp;
14798 	ulong_t tte8k_cnt = 0;
14799 	ulong_t tte4m_cnt = 0;
14800 	uint_t tsb_szc;
14801 	sfmmu_t *scsfmmup = scdp->scd_sfmmup;
14802 	sfmmu_t	*ism_hatid;
14803 	struct tsb_info *newtsb;
14804 	int szc;
14805 
14806 	ASSERT(srdp != NULL);
14807 
14808 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14809 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14810 			continue;
14811 		}
14812 		j = 0;
14813 		while (w) {
14814 			if (!(w & 0x1)) {
14815 				j++;
14816 				w >>= 1;
14817 				continue;
14818 			}
14819 			rid = (i << BT_ULSHIFT) | j;
14820 			j++;
14821 			w >>= 1;
14822 
14823 			if (rid < SFMMU_MAX_HME_REGIONS) {
14824 				rgnp = srdp->srd_hmergnp[rid];
14825 				ASSERT(rgnp->rgn_id == rid);
14826 				ASSERT(rgnp->rgn_refcnt > 0);
14827 
14828 				if (rgnp->rgn_pgszc < TTE4M) {
14829 					tte8k_cnt += rgnp->rgn_size >>
14830 					    TTE_PAGE_SHIFT(TTE8K);
14831 				} else {
14832 					ASSERT(rgnp->rgn_pgszc >= TTE4M);
14833 					tte4m_cnt += rgnp->rgn_size >>
14834 					    TTE_PAGE_SHIFT(TTE4M);
14835 					/*
14836 					 * Inflate SCD tsb0 by preallocating
14837 					 * 1/4 8k ttecnt for 4M regions to
14838 					 * allow for lgpg alloc failure.
14839 					 */
14840 					tte8k_cnt += rgnp->rgn_size >>
14841 					    (TTE_PAGE_SHIFT(TTE8K) + 2);
14842 				}
14843 			} else {
14844 				rid -= SFMMU_MAX_HME_REGIONS;
14845 				rgnp = srdp->srd_ismrgnp[rid];
14846 				ASSERT(rgnp->rgn_id == rid);
14847 				ASSERT(rgnp->rgn_refcnt > 0);
14848 
14849 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14850 				ASSERT(ism_hatid->sfmmu_ismhat);
14851 
14852 				for (szc = 0; szc < TTE4M; szc++) {
14853 					tte8k_cnt +=
14854 					    ism_hatid->sfmmu_ttecnt[szc] <<
14855 					    TTE_BSZS_SHIFT(szc);
14856 				}
14857 
14858 				ASSERT(rgnp->rgn_pgszc >= TTE4M);
14859 				if (rgnp->rgn_pgszc >= TTE4M) {
14860 					tte4m_cnt += rgnp->rgn_size >>
14861 					    TTE_PAGE_SHIFT(TTE4M);
14862 				}
14863 			}
14864 		}
14865 	}
14866 
14867 	tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
14868 
14869 	/* Allocate both the SCD TSBs here. */
14870 	if (sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14871 	    tsb_szc, TSB8K|TSB64K|TSB512K, TSB_ALLOC, scsfmmup) &&
14872 	    (tsb_szc <= TSB_4M_SZCODE ||
14873 	    sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14874 	    TSB_4M_SZCODE, TSB8K|TSB64K|TSB512K,
14875 	    TSB_ALLOC, scsfmmup))) {
14876 
14877 		SFMMU_STAT(sf_scd_1sttsb_allocfail);
14878 		return (TSB_ALLOCFAIL);
14879 	} else {
14880 		scsfmmup->sfmmu_tsb->tsb_flags |= TSB_SHAREDCTX;
14881 
14882 		if (tte4m_cnt) {
14883 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
14884 			if (sfmmu_tsbinfo_alloc(&newtsb, tsb_szc,
14885 			    TSB4M|TSB32M|TSB256M, TSB_ALLOC, scsfmmup) &&
14886 			    (tsb_szc <= TSB_4M_SZCODE ||
14887 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
14888 			    TSB4M|TSB32M|TSB256M,
14889 			    TSB_ALLOC, scsfmmup))) {
14890 				/*
14891 				 * If we fail to allocate the 2nd shared tsb,
14892 				 * just free the 1st tsb, return failure.
14893 				 */
14894 				sfmmu_tsbinfo_free(scsfmmup->sfmmu_tsb);
14895 				SFMMU_STAT(sf_scd_2ndtsb_allocfail);
14896 				return (TSB_ALLOCFAIL);
14897 			} else {
14898 				ASSERT(scsfmmup->sfmmu_tsb->tsb_next == NULL);
14899 				newtsb->tsb_flags |= TSB_SHAREDCTX;
14900 				scsfmmup->sfmmu_tsb->tsb_next = newtsb;
14901 				SFMMU_STAT(sf_scd_2ndtsb_alloc);
14902 			}
14903 		}
14904 		SFMMU_STAT(sf_scd_1sttsb_alloc);
14905 	}
14906 	return (TSB_SUCCESS);
14907 }
14908 
14909 static void
14910 sfmmu_free_scd_tsbs(sfmmu_t *scd_sfmmu)
14911 {
14912 	while (scd_sfmmu->sfmmu_tsb != NULL) {
14913 		struct tsb_info *next = scd_sfmmu->sfmmu_tsb->tsb_next;
14914 		sfmmu_tsbinfo_free(scd_sfmmu->sfmmu_tsb);
14915 		scd_sfmmu->sfmmu_tsb = next;
14916 	}
14917 }
14918 
14919 /*
14920  * Link the sfmmu onto the hme region list.
14921  */
14922 void
14923 sfmmu_link_to_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14924 {
14925 	uint_t rid;
14926 	sf_rgn_link_t *rlink;
14927 	sfmmu_t *head;
14928 	sf_rgn_link_t *hrlink;
14929 
14930 	rid = rgnp->rgn_id;
14931 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14932 
14933 	/* LINTED: constant in conditional context */
14934 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 1);
14935 	ASSERT(rlink != NULL);
14936 	mutex_enter(&rgnp->rgn_mutex);
14937 	if ((head = rgnp->rgn_sfmmu_head) == NULL) {
14938 		rlink->next = NULL;
14939 		rlink->prev = NULL;
14940 		/*
14941 		 * make sure rlink's next field is NULL
14942 		 * before making this link visible.
14943 		 */
14944 		membar_stst();
14945 		rgnp->rgn_sfmmu_head = sfmmup;
14946 	} else {
14947 		/* LINTED: constant in conditional context */
14948 		SFMMU_HMERID2RLINKP(head, rid, hrlink, 0, 0);
14949 		ASSERT(hrlink != NULL);
14950 		ASSERT(hrlink->prev == NULL);
14951 		rlink->next = head;
14952 		rlink->prev = NULL;
14953 		hrlink->prev = sfmmup;
14954 		/*
14955 		 * make sure rlink's next field is correct
14956 		 * before making this link visible.
14957 		 */
14958 		membar_stst();
14959 		rgnp->rgn_sfmmu_head = sfmmup;
14960 	}
14961 	mutex_exit(&rgnp->rgn_mutex);
14962 }
14963 
14964 /*
14965  * Unlink the sfmmu from the hme region list.
14966  */
14967 void
14968 sfmmu_unlink_from_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14969 {
14970 	uint_t rid;
14971 	sf_rgn_link_t *rlink;
14972 
14973 	rid = rgnp->rgn_id;
14974 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14975 
14976 	/* LINTED: constant in conditional context */
14977 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
14978 	ASSERT(rlink != NULL);
14979 	mutex_enter(&rgnp->rgn_mutex);
14980 	if (rgnp->rgn_sfmmu_head == sfmmup) {
14981 		sfmmu_t *next = rlink->next;
14982 		rgnp->rgn_sfmmu_head = next;
14983 		/*
14984 		 * if we are stopped by xc_attention() after this
14985 		 * point the forward link walking in
14986 		 * sfmmu_rgntlb_demap() will work correctly since the
14987 		 * head correctly points to the next element.
14988 		 */
14989 		membar_stst();
14990 		rlink->next = NULL;
14991 		ASSERT(rlink->prev == NULL);
14992 		if (next != NULL) {
14993 			sf_rgn_link_t *nrlink;
14994 			/* LINTED: constant in conditional context */
14995 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14996 			ASSERT(nrlink != NULL);
14997 			ASSERT(nrlink->prev == sfmmup);
14998 			nrlink->prev = NULL;
14999 		}
15000 	} else {
15001 		sfmmu_t *next = rlink->next;
15002 		sfmmu_t *prev = rlink->prev;
15003 		sf_rgn_link_t *prlink;
15004 
15005 		ASSERT(prev != NULL);
15006 		/* LINTED: constant in conditional context */
15007 		SFMMU_HMERID2RLINKP(prev, rid, prlink, 0, 0);
15008 		ASSERT(prlink != NULL);
15009 		ASSERT(prlink->next == sfmmup);
15010 		prlink->next = next;
15011 		/*
15012 		 * if we are stopped by xc_attention()
15013 		 * after this point the forward link walking
15014 		 * will work correctly since the prev element
15015 		 * correctly points to the next element.
15016 		 */
15017 		membar_stst();
15018 		rlink->next = NULL;
15019 		rlink->prev = NULL;
15020 		if (next != NULL) {
15021 			sf_rgn_link_t *nrlink;
15022 			/* LINTED: constant in conditional context */
15023 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
15024 			ASSERT(nrlink != NULL);
15025 			ASSERT(nrlink->prev == sfmmup);
15026 			nrlink->prev = prev;
15027 		}
15028 	}
15029 	mutex_exit(&rgnp->rgn_mutex);
15030 }
15031 
15032 /*
15033  * Link scd sfmmu onto ism or hme region list for each region in the
15034  * scd region map.
15035  */
15036 void
15037 sfmmu_link_scd_to_regions(sf_srd_t *srdp, sf_scd_t *scdp)
15038 {
15039 	uint_t rid;
15040 	uint_t i;
15041 	uint_t j;
15042 	ulong_t w;
15043 	sf_region_t *rgnp;
15044 	sfmmu_t *scsfmmup;
15045 
15046 	scsfmmup = scdp->scd_sfmmup;
15047 	ASSERT(scsfmmup->sfmmu_scdhat);
15048 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
15049 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
15050 			continue;
15051 		}
15052 		j = 0;
15053 		while (w) {
15054 			if (!(w & 0x1)) {
15055 				j++;
15056 				w >>= 1;
15057 				continue;
15058 			}
15059 			rid = (i << BT_ULSHIFT) | j;
15060 			j++;
15061 			w >>= 1;
15062 
15063 			if (rid < SFMMU_MAX_HME_REGIONS) {
15064 				rgnp = srdp->srd_hmergnp[rid];
15065 				ASSERT(rgnp->rgn_id == rid);
15066 				ASSERT(rgnp->rgn_refcnt > 0);
15067 				sfmmu_link_to_hmeregion(scsfmmup, rgnp);
15068 			} else {
15069 				sfmmu_t *ism_hatid = NULL;
15070 				ism_ment_t *ism_ment;
15071 				rid -= SFMMU_MAX_HME_REGIONS;
15072 				rgnp = srdp->srd_ismrgnp[rid];
15073 				ASSERT(rgnp->rgn_id == rid);
15074 				ASSERT(rgnp->rgn_refcnt > 0);
15075 
15076 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
15077 				ASSERT(ism_hatid->sfmmu_ismhat);
15078 				ism_ment = &scdp->scd_ism_links[rid];
15079 				ism_ment->iment_hat = scsfmmup;
15080 				ism_ment->iment_base_va = rgnp->rgn_saddr;
15081 				mutex_enter(&ism_mlist_lock);
15082 				iment_add(ism_ment, ism_hatid);
15083 				mutex_exit(&ism_mlist_lock);
15084 
15085 			}
15086 		}
15087 	}
15088 }
15089 /*
15090  * Unlink scd sfmmu from ism or hme region list for each region in the
15091  * scd region map.
15092  */
15093 void
15094 sfmmu_unlink_scd_from_regions(sf_srd_t *srdp, sf_scd_t *scdp)
15095 {
15096 	uint_t rid;
15097 	uint_t i;
15098 	uint_t j;
15099 	ulong_t w;
15100 	sf_region_t *rgnp;
15101 	sfmmu_t *scsfmmup;
15102 
15103 	scsfmmup = scdp->scd_sfmmup;
15104 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
15105 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
15106 			continue;
15107 		}
15108 		j = 0;
15109 		while (w) {
15110 			if (!(w & 0x1)) {
15111 				j++;
15112 				w >>= 1;
15113 				continue;
15114 			}
15115 			rid = (i << BT_ULSHIFT) | j;
15116 			j++;
15117 			w >>= 1;
15118 
15119 			if (rid < SFMMU_MAX_HME_REGIONS) {
15120 				rgnp = srdp->srd_hmergnp[rid];
15121 				ASSERT(rgnp->rgn_id == rid);
15122 				ASSERT(rgnp->rgn_refcnt > 0);
15123 				sfmmu_unlink_from_hmeregion(scsfmmup,
15124 				    rgnp);
15125 
15126 			} else {
15127 				sfmmu_t *ism_hatid = NULL;
15128 				ism_ment_t *ism_ment;
15129 				rid -= SFMMU_MAX_HME_REGIONS;
15130 				rgnp = srdp->srd_ismrgnp[rid];
15131 				ASSERT(rgnp->rgn_id == rid);
15132 				ASSERT(rgnp->rgn_refcnt > 0);
15133 
15134 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
15135 				ASSERT(ism_hatid->sfmmu_ismhat);
15136 				ism_ment = &scdp->scd_ism_links[rid];
15137 				ASSERT(ism_ment->iment_hat == scdp->scd_sfmmup);
15138 				ASSERT(ism_ment->iment_base_va ==
15139 				    rgnp->rgn_saddr);
15140 				mutex_enter(&ism_mlist_lock);
15141 				iment_sub(ism_ment, ism_hatid);
15142 				mutex_exit(&ism_mlist_lock);
15143 
15144 			}
15145 		}
15146 	}
15147 }
15148 /*
15149  * Allocates and initialises a new SCD structure, this is called with
15150  * the srd_scd_mutex held and returns with the reference count
15151  * initialised to 1.
15152  */
15153 static sf_scd_t *
15154 sfmmu_alloc_scd(sf_srd_t *srdp, sf_region_map_t *new_map)
15155 {
15156 	sf_scd_t *new_scdp;
15157 	sfmmu_t *scsfmmup;
15158 	int i;
15159 
15160 	ASSERT(MUTEX_HELD(&srdp->srd_scd_mutex));
15161 	new_scdp = kmem_cache_alloc(scd_cache, KM_SLEEP);
15162 
15163 	scsfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
15164 	new_scdp->scd_sfmmup = scsfmmup;
15165 	scsfmmup->sfmmu_srdp = srdp;
15166 	scsfmmup->sfmmu_scdp = new_scdp;
15167 	scsfmmup->sfmmu_tsb0_4minflcnt = 0;
15168 	scsfmmup->sfmmu_scdhat = 1;
15169 	CPUSET_ALL(scsfmmup->sfmmu_cpusran);
15170 	bzero(scsfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
15171 
15172 	ASSERT(max_mmu_ctxdoms > 0);
15173 	for (i = 0; i < max_mmu_ctxdoms; i++) {
15174 		scsfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
15175 		scsfmmup->sfmmu_ctxs[i].gnum = 0;
15176 	}
15177 
15178 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
15179 		new_scdp->scd_rttecnt[i] = 0;
15180 	}
15181 
15182 	new_scdp->scd_region_map = *new_map;
15183 	new_scdp->scd_refcnt = 1;
15184 	if (sfmmu_alloc_scd_tsbs(srdp, new_scdp) != TSB_SUCCESS) {
15185 		kmem_cache_free(scd_cache, new_scdp);
15186 		kmem_cache_free(sfmmuid_cache, scsfmmup);
15187 		return (NULL);
15188 	}
15189 	if (&mmu_init_scd) {
15190 		mmu_init_scd(new_scdp);
15191 	}
15192 	return (new_scdp);
15193 }
15194 
15195 /*
15196  * The first phase of a process joining an SCD. The hat structure is
15197  * linked to the SCD queue and then the HAT_JOIN_SCD sfmmu flag is set
15198  * and a cross-call with context invalidation is used to cause the
15199  * remaining work to be carried out in the sfmmu_tsbmiss_exception()
15200  * routine.
15201  */
15202 static void
15203 sfmmu_join_scd(sf_scd_t *scdp, sfmmu_t *sfmmup)
15204 {
15205 	hatlock_t *hatlockp;
15206 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15207 	int i;
15208 	sf_scd_t *old_scdp;
15209 
15210 	ASSERT(srdp != NULL);
15211 	ASSERT(scdp != NULL);
15212 	ASSERT(scdp->scd_refcnt > 0);
15213 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15214 
15215 	if ((old_scdp = sfmmup->sfmmu_scdp) != NULL) {
15216 		ASSERT(old_scdp != scdp);
15217 
15218 		mutex_enter(&old_scdp->scd_mutex);
15219 		sfmmu_from_scd_list(&old_scdp->scd_sf_list, sfmmup);
15220 		mutex_exit(&old_scdp->scd_mutex);
15221 		/*
15222 		 * sfmmup leaves the old scd. Update sfmmu_ttecnt to
15223 		 * include the shme rgn ttecnt for rgns that
15224 		 * were in the old SCD
15225 		 */
15226 		for (i = 0; i < mmu_page_sizes; i++) {
15227 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15228 			    old_scdp->scd_rttecnt[i]);
15229 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15230 			    sfmmup->sfmmu_scdrttecnt[i]);
15231 		}
15232 	}
15233 
15234 	/*
15235 	 * Move sfmmu to the scd lists.
15236 	 */
15237 	mutex_enter(&scdp->scd_mutex);
15238 	sfmmu_to_scd_list(&scdp->scd_sf_list, sfmmup);
15239 	mutex_exit(&scdp->scd_mutex);
15240 	SF_SCD_INCR_REF(scdp);
15241 
15242 	hatlockp = sfmmu_hat_enter(sfmmup);
15243 	/*
15244 	 * For a multi-thread process, we must stop
15245 	 * all the other threads before joining the scd.
15246 	 */
15247 
15248 	SFMMU_FLAGS_SET(sfmmup, HAT_JOIN_SCD);
15249 
15250 	sfmmu_invalidate_ctx(sfmmup);
15251 	sfmmup->sfmmu_scdp = scdp;
15252 
15253 	/*
15254 	 * Copy scd_rttecnt into sfmmup's sfmmu_scdrttecnt, and update
15255 	 * sfmmu_ttecnt to not include the rgn ttecnt just joined in SCD.
15256 	 */
15257 	for (i = 0; i < mmu_page_sizes; i++) {
15258 		sfmmup->sfmmu_scdrttecnt[i] = scdp->scd_rttecnt[i];
15259 		ASSERT(sfmmup->sfmmu_ttecnt[i] >= scdp->scd_rttecnt[i]);
15260 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15261 		    -sfmmup->sfmmu_scdrttecnt[i]);
15262 	}
15263 	/* update tsb0 inflation count */
15264 	if (old_scdp != NULL) {
15265 		sfmmup->sfmmu_tsb0_4minflcnt +=
15266 		    old_scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15267 	}
15268 	ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
15269 	    scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt);
15270 	sfmmup->sfmmu_tsb0_4minflcnt -= scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15271 
15272 	sfmmu_hat_exit(hatlockp);
15273 
15274 	if (old_scdp != NULL) {
15275 		SF_SCD_DECR_REF(srdp, old_scdp);
15276 	}
15277 
15278 }
15279 
15280 /*
15281  * This routine is called by a process to become part of an SCD. It is called
15282  * from sfmmu_tsbmiss_exception() once most of the initial work has been
15283  * done by sfmmu_join_scd(). This routine must not drop the hat lock.
15284  */
15285 static void
15286 sfmmu_finish_join_scd(sfmmu_t *sfmmup)
15287 {
15288 	struct tsb_info	*tsbinfop;
15289 
15290 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15291 	ASSERT(sfmmup->sfmmu_scdp != NULL);
15292 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD));
15293 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15294 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID));
15295 
15296 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
15297 	    tsbinfop = tsbinfop->tsb_next) {
15298 		if (tsbinfop->tsb_flags & TSB_SWAPPED) {
15299 			continue;
15300 		}
15301 		ASSERT(!(tsbinfop->tsb_flags & TSB_RELOC_FLAG));
15302 
15303 		sfmmu_inv_tsb(tsbinfop->tsb_va,
15304 		    TSB_BYTES(tsbinfop->tsb_szc));
15305 	}
15306 
15307 	/* Set HAT_CTX1_FLAG for all SCD ISMs */
15308 	sfmmu_ism_hatflags(sfmmup, 1);
15309 
15310 	SFMMU_STAT(sf_join_scd);
15311 }
15312 
15313 /*
15314  * This routine is called in order to check if there is an SCD which matches
15315  * the process's region map if not then a new SCD may be created.
15316  */
15317 static void
15318 sfmmu_find_scd(sfmmu_t *sfmmup)
15319 {
15320 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15321 	sf_scd_t *scdp, *new_scdp;
15322 	int ret;
15323 
15324 	ASSERT(srdp != NULL);
15325 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15326 
15327 	mutex_enter(&srdp->srd_scd_mutex);
15328 	for (scdp = srdp->srd_scdp; scdp != NULL;
15329 	    scdp = scdp->scd_next) {
15330 		SF_RGNMAP_EQUAL(&scdp->scd_region_map,
15331 		    &sfmmup->sfmmu_region_map, ret);
15332 		if (ret == 1) {
15333 			SF_SCD_INCR_REF(scdp);
15334 			mutex_exit(&srdp->srd_scd_mutex);
15335 			sfmmu_join_scd(scdp, sfmmup);
15336 			ASSERT(scdp->scd_refcnt >= 2);
15337 			atomic_add_32((volatile uint32_t *)
15338 			    &scdp->scd_refcnt, -1);
15339 			return;
15340 		} else {
15341 			/*
15342 			 * If the sfmmu region map is a subset of the scd
15343 			 * region map, then the assumption is that this process
15344 			 * will continue attaching to ISM segments until the
15345 			 * region maps are equal.
15346 			 */
15347 			SF_RGNMAP_IS_SUBSET(&scdp->scd_region_map,
15348 			    &sfmmup->sfmmu_region_map, ret);
15349 			if (ret == 1) {
15350 				mutex_exit(&srdp->srd_scd_mutex);
15351 				return;
15352 			}
15353 		}
15354 	}
15355 
15356 	ASSERT(scdp == NULL);
15357 	/*
15358 	 * No matching SCD has been found, create a new one.
15359 	 */
15360 	if ((new_scdp = sfmmu_alloc_scd(srdp, &sfmmup->sfmmu_region_map)) ==
15361 	    NULL) {
15362 		mutex_exit(&srdp->srd_scd_mutex);
15363 		return;
15364 	}
15365 
15366 	/*
15367 	 * sfmmu_alloc_scd() returns with a ref count of 1 on the scd.
15368 	 */
15369 
15370 	/* Set scd_rttecnt for shme rgns in SCD */
15371 	sfmmu_set_scd_rttecnt(srdp, new_scdp);
15372 
15373 	/*
15374 	 * Link scd onto srd_scdp list and scd sfmmu onto region/iment lists.
15375 	 */
15376 	sfmmu_link_scd_to_regions(srdp, new_scdp);
15377 	sfmmu_add_scd(&srdp->srd_scdp, new_scdp);
15378 	SFMMU_STAT_ADD(sf_create_scd, 1);
15379 
15380 	mutex_exit(&srdp->srd_scd_mutex);
15381 	sfmmu_join_scd(new_scdp, sfmmup);
15382 	ASSERT(new_scdp->scd_refcnt >= 2);
15383 	atomic_add_32((volatile uint32_t *)&new_scdp->scd_refcnt, -1);
15384 }
15385 
15386 /*
15387  * This routine is called by a process to remove itself from an SCD. It is
15388  * either called when the processes has detached from a segment or from
15389  * hat_free_start() as a result of calling exit.
15390  */
15391 static void
15392 sfmmu_leave_scd(sfmmu_t *sfmmup, uchar_t r_type)
15393 {
15394 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15395 	sf_srd_t *srdp =  sfmmup->sfmmu_srdp;
15396 	hatlock_t *hatlockp = TSB_HASH(sfmmup);
15397 	int i;
15398 
15399 	ASSERT(scdp != NULL);
15400 	ASSERT(srdp != NULL);
15401 
15402 	if (sfmmup->sfmmu_free) {
15403 		/*
15404 		 * If the process is part of an SCD the sfmmu is unlinked
15405 		 * from scd_sf_list.
15406 		 */
15407 		mutex_enter(&scdp->scd_mutex);
15408 		sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15409 		mutex_exit(&scdp->scd_mutex);
15410 		/*
15411 		 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15412 		 * are about to leave the SCD
15413 		 */
15414 		for (i = 0; i < mmu_page_sizes; i++) {
15415 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15416 			    scdp->scd_rttecnt[i]);
15417 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15418 			    sfmmup->sfmmu_scdrttecnt[i]);
15419 			sfmmup->sfmmu_scdrttecnt[i] = 0;
15420 		}
15421 		sfmmup->sfmmu_scdp = NULL;
15422 
15423 		SF_SCD_DECR_REF(srdp, scdp);
15424 		return;
15425 	}
15426 
15427 	ASSERT(r_type != SFMMU_REGION_ISM ||
15428 	    SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15429 	ASSERT(scdp->scd_refcnt);
15430 	ASSERT(!sfmmup->sfmmu_free);
15431 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15432 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
15433 
15434 	/*
15435 	 * Wait for ISM maps to be updated.
15436 	 */
15437 	if (r_type != SFMMU_REGION_ISM) {
15438 		while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY) &&
15439 		    sfmmup->sfmmu_scdp != NULL) {
15440 			cv_wait(&sfmmup->sfmmu_tsb_cv,
15441 			    HATLOCK_MUTEXP(hatlockp));
15442 		}
15443 
15444 		if (sfmmup->sfmmu_scdp == NULL) {
15445 			sfmmu_hat_exit(hatlockp);
15446 			return;
15447 		}
15448 		SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
15449 	}
15450 
15451 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
15452 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
15453 		/*
15454 		 * Since HAT_JOIN_SCD was set our context
15455 		 * is still invalid.
15456 		 */
15457 	} else {
15458 		/*
15459 		 * For a multi-thread process, we must stop
15460 		 * all the other threads before leaving the scd.
15461 		 */
15462 
15463 		sfmmu_invalidate_ctx(sfmmup);
15464 	}
15465 
15466 	/* Clear all the rid's for ISM, delete flags, etc */
15467 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15468 	sfmmu_ism_hatflags(sfmmup, 0);
15469 
15470 	/*
15471 	 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15472 	 * are in SCD before this sfmmup leaves the SCD.
15473 	 */
15474 	for (i = 0; i < mmu_page_sizes; i++) {
15475 		ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15476 		    scdp->scd_rttecnt[i]);
15477 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15478 		    sfmmup->sfmmu_scdrttecnt[i]);
15479 		sfmmup->sfmmu_scdrttecnt[i] = 0;
15480 		/* update ismttecnt to include SCD ism before hat leaves SCD */
15481 		sfmmup->sfmmu_ismttecnt[i] += sfmmup->sfmmu_scdismttecnt[i];
15482 		sfmmup->sfmmu_scdismttecnt[i] = 0;
15483 	}
15484 	/* update tsb0 inflation count */
15485 	sfmmup->sfmmu_tsb0_4minflcnt += scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15486 
15487 	if (r_type != SFMMU_REGION_ISM) {
15488 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
15489 	}
15490 	sfmmup->sfmmu_scdp = NULL;
15491 
15492 	sfmmu_hat_exit(hatlockp);
15493 
15494 	/*
15495 	 * Unlink sfmmu from scd_sf_list this can be done without holding
15496 	 * the hat lock as we hold the sfmmu_as lock which prevents
15497 	 * hat_join_region from adding this thread to the scd again. Other
15498 	 * threads check if sfmmu_scdp is NULL under hat lock and if it's NULL
15499 	 * they won't get here, since sfmmu_leave_scd() clears sfmmu_scdp
15500 	 * while holding the hat lock.
15501 	 */
15502 	mutex_enter(&scdp->scd_mutex);
15503 	sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15504 	mutex_exit(&scdp->scd_mutex);
15505 	SFMMU_STAT(sf_leave_scd);
15506 
15507 	SF_SCD_DECR_REF(srdp, scdp);
15508 	hatlockp = sfmmu_hat_enter(sfmmup);
15509 
15510 }
15511 
15512 /*
15513  * Unlink and free up an SCD structure with a reference count of 0.
15514  */
15515 static void
15516 sfmmu_destroy_scd(sf_srd_t *srdp, sf_scd_t *scdp, sf_region_map_t *scd_rmap)
15517 {
15518 	sfmmu_t *scsfmmup;
15519 	sf_scd_t *sp;
15520 	hatlock_t *shatlockp;
15521 	int i, ret;
15522 
15523 	mutex_enter(&srdp->srd_scd_mutex);
15524 	for (sp = srdp->srd_scdp; sp != NULL; sp = sp->scd_next) {
15525 		if (sp == scdp)
15526 			break;
15527 	}
15528 	if (sp == NULL || sp->scd_refcnt) {
15529 		mutex_exit(&srdp->srd_scd_mutex);
15530 		return;
15531 	}
15532 
15533 	/*
15534 	 * It is possible that the scd has been freed and reallocated with a
15535 	 * different region map while we've been waiting for the srd_scd_mutex.
15536 	 */
15537 	SF_RGNMAP_EQUAL(scd_rmap, &sp->scd_region_map, ret);
15538 	if (ret != 1) {
15539 		mutex_exit(&srdp->srd_scd_mutex);
15540 		return;
15541 	}
15542 
15543 	ASSERT(scdp->scd_sf_list == NULL);
15544 	/*
15545 	 * Unlink scd from srd_scdp list.
15546 	 */
15547 	sfmmu_remove_scd(&srdp->srd_scdp, scdp);
15548 	mutex_exit(&srdp->srd_scd_mutex);
15549 
15550 	sfmmu_unlink_scd_from_regions(srdp, scdp);
15551 
15552 	/* Clear shared context tsb and release ctx */
15553 	scsfmmup = scdp->scd_sfmmup;
15554 
15555 	/*
15556 	 * create a barrier so that scd will not be destroyed
15557 	 * if other thread still holds the same shared hat lock.
15558 	 * E.g., sfmmu_tsbmiss_exception() needs to acquire the
15559 	 * shared hat lock before checking the shared tsb reloc flag.
15560 	 */
15561 	shatlockp = sfmmu_hat_enter(scsfmmup);
15562 	sfmmu_hat_exit(shatlockp);
15563 
15564 	sfmmu_free_scd_tsbs(scsfmmup);
15565 
15566 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
15567 		if (scsfmmup->sfmmu_hmeregion_links[i] != NULL) {
15568 			kmem_free(scsfmmup->sfmmu_hmeregion_links[i],
15569 			    SFMMU_L2_HMERLINKS_SIZE);
15570 			scsfmmup->sfmmu_hmeregion_links[i] = NULL;
15571 		}
15572 	}
15573 	kmem_cache_free(sfmmuid_cache, scsfmmup);
15574 	kmem_cache_free(scd_cache, scdp);
15575 	SFMMU_STAT(sf_destroy_scd);
15576 }
15577 
15578 /*
15579  * Modifies the HAT_CTX1_FLAG for each of the ISM segments which correspond to
15580  * bits which are set in the ism_region_map parameter. This flag indicates to
15581  * the tsbmiss handler that mapping for these segments should be loaded using
15582  * the shared context.
15583  */
15584 static void
15585 sfmmu_ism_hatflags(sfmmu_t *sfmmup, int addflag)
15586 {
15587 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15588 	ism_blk_t *ism_blkp;
15589 	ism_map_t *ism_map;
15590 	int i, rid;
15591 
15592 	ASSERT(sfmmup->sfmmu_iblk != NULL);
15593 	ASSERT(scdp != NULL);
15594 	/*
15595 	 * Note that the caller either set HAT_ISMBUSY flag or checked
15596 	 * under hat lock that HAT_ISMBUSY was not set by another thread.
15597 	 */
15598 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15599 
15600 	ism_blkp = sfmmup->sfmmu_iblk;
15601 	while (ism_blkp != NULL) {
15602 		ism_map = ism_blkp->iblk_maps;
15603 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
15604 			rid = ism_map[i].imap_rid;
15605 			if (rid == SFMMU_INVALID_ISMRID) {
15606 				continue;
15607 			}
15608 			ASSERT(rid >= 0 && rid < SFMMU_MAX_ISM_REGIONS);
15609 			if (SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid) &&
15610 			    addflag) {
15611 				ism_map[i].imap_hatflags |=
15612 				    HAT_CTX1_FLAG;
15613 			} else {
15614 				ism_map[i].imap_hatflags &=
15615 				    ~HAT_CTX1_FLAG;
15616 			}
15617 		}
15618 		ism_blkp = ism_blkp->iblk_next;
15619 	}
15620 }
15621 
15622 static int
15623 sfmmu_srd_lock_held(sf_srd_t *srdp)
15624 {
15625 	return (MUTEX_HELD(&srdp->srd_mutex));
15626 }
15627 
15628 /* ARGSUSED */
15629 static int
15630 sfmmu_scdcache_constructor(void *buf, void *cdrarg, int kmflags)
15631 {
15632 	sf_scd_t *scdp = (sf_scd_t *)buf;
15633 
15634 	bzero(buf, sizeof (sf_scd_t));
15635 	mutex_init(&scdp->scd_mutex, NULL, MUTEX_DEFAULT, NULL);
15636 	return (0);
15637 }
15638 
15639 /* ARGSUSED */
15640 static void
15641 sfmmu_scdcache_destructor(void *buf, void *cdrarg)
15642 {
15643 	sf_scd_t *scdp = (sf_scd_t *)buf;
15644 
15645 	mutex_destroy(&scdp->scd_mutex);
15646 }
15647 
15648 /*
15649  * The listp parameter is a pointer to a list of hmeblks which are partially
15650  * freed as result of calling sfmmu_hblk_hash_rm(), the last phase of the
15651  * freeing process is to cross-call all cpus to ensure that there are no
15652  * remaining cached references.
15653  *
15654  * If the local generation number is less than the global then we can free
15655  * hmeblks which are already on the pending queue as another cpu has completed
15656  * the cross-call.
15657  *
15658  * We cross-call to make sure that there are no threads on other cpus accessing
15659  * these hmblks and then complete the process of freeing them under the
15660  * following conditions:
15661  * 	The total number of pending hmeblks is greater than the threshold
15662  *	The reserve list has fewer than HBLK_RESERVE_CNT hmeblks
15663  *	It is at least 1 second since the last time we cross-called
15664  *
15665  * Otherwise, we add the hmeblks to the per-cpu pending queue.
15666  */
15667 static void
15668 sfmmu_hblks_list_purge(struct hme_blk **listp, int dontfree)
15669 {
15670 	struct hme_blk *hblkp, *pr_hblkp = NULL;
15671 	int		count = 0;
15672 	cpuset_t	cpuset = cpu_ready_set;
15673 	cpu_hme_pend_t	*cpuhp;
15674 	timestruc_t	now;
15675 	int		one_second_expired = 0;
15676 
15677 	gethrestime_lasttick(&now);
15678 
15679 	for (hblkp = *listp; hblkp != NULL; hblkp = hblkp->hblk_next) {
15680 		ASSERT(hblkp->hblk_shw_bit == 0);
15681 		ASSERT(hblkp->hblk_shared == 0);
15682 		count++;
15683 		pr_hblkp = hblkp;
15684 	}
15685 
15686 	cpuhp = &cpu_hme_pend[CPU->cpu_seqid];
15687 	mutex_enter(&cpuhp->chp_mutex);
15688 
15689 	if ((cpuhp->chp_count + count) == 0) {
15690 		mutex_exit(&cpuhp->chp_mutex);
15691 		return;
15692 	}
15693 
15694 	if ((now.tv_sec - cpuhp->chp_timestamp) > 1) {
15695 		one_second_expired  = 1;
15696 	}
15697 
15698 	if (!dontfree && (freehblkcnt < HBLK_RESERVE_CNT ||
15699 	    (cpuhp->chp_count + count) > cpu_hme_pend_thresh ||
15700 	    one_second_expired)) {
15701 		/* Append global list to local */
15702 		if (pr_hblkp == NULL) {
15703 			*listp = cpuhp->chp_listp;
15704 		} else {
15705 			pr_hblkp->hblk_next = cpuhp->chp_listp;
15706 		}
15707 		cpuhp->chp_listp = NULL;
15708 		cpuhp->chp_count = 0;
15709 		cpuhp->chp_timestamp = now.tv_sec;
15710 		mutex_exit(&cpuhp->chp_mutex);
15711 
15712 		kpreempt_disable();
15713 		CPUSET_DEL(cpuset, CPU->cpu_id);
15714 		xt_sync(cpuset);
15715 		xt_sync(cpuset);
15716 		kpreempt_enable();
15717 
15718 		/*
15719 		 * At this stage we know that no trap handlers on other
15720 		 * cpus can have references to hmeblks on the list.
15721 		 */
15722 		sfmmu_hblk_free(listp);
15723 	} else if (*listp != NULL) {
15724 		pr_hblkp->hblk_next = cpuhp->chp_listp;
15725 		cpuhp->chp_listp = *listp;
15726 		cpuhp->chp_count += count;
15727 		*listp = NULL;
15728 		mutex_exit(&cpuhp->chp_mutex);
15729 	} else {
15730 		mutex_exit(&cpuhp->chp_mutex);
15731 	}
15732 }
15733 
15734 /*
15735  * Add an hmeblk to the the hash list.
15736  */
15737 void
15738 sfmmu_hblk_hash_add(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15739 	uint64_t hblkpa)
15740 {
15741 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15742 #ifdef	DEBUG
15743 	if (hmebp->hmeblkp == NULL) {
15744 		ASSERT(hmebp->hmeh_nextpa == HMEBLK_ENDPA);
15745 	}
15746 #endif /* DEBUG */
15747 
15748 	hmeblkp->hblk_nextpa = hmebp->hmeh_nextpa;
15749 	/*
15750 	 * Since the TSB miss handler now does not lock the hash chain before
15751 	 * walking it, make sure that the hmeblks nextpa is globally visible
15752 	 * before we make the hmeblk globally visible by updating the chain root
15753 	 * pointer in the hash bucket.
15754 	 */
15755 	membar_producer();
15756 	hmebp->hmeh_nextpa = hblkpa;
15757 	hmeblkp->hblk_next = hmebp->hmeblkp;
15758 	hmebp->hmeblkp = hmeblkp;
15759 
15760 }
15761 
15762 /*
15763  * This function is the first part of a 2 part process to remove an hmeblk
15764  * from the hash chain. In this phase we unlink the hmeblk from the hash chain
15765  * but leave the next physical pointer unchanged. The hmeblk is then linked onto
15766  * a per-cpu pending list using the virtual address pointer.
15767  *
15768  * TSB miss trap handlers that start after this phase will no longer see
15769  * this hmeblk. TSB miss handlers that still cache this hmeblk in a register
15770  * can still use it for further chain traversal because we haven't yet modifed
15771  * the next physical pointer or freed it.
15772  *
15773  * In the second phase of hmeblk removal we'll issue a barrier xcall before
15774  * we reuse or free this hmeblk. This will make sure all lingering references to
15775  * the hmeblk after first phase disappear before we finally reclaim it.
15776  * This scheme eliminates the need for TSB miss handlers to lock hmeblk chains
15777  * during their traversal.
15778  *
15779  * The hmehash_mutex must be held when calling this function.
15780  *
15781  * Input:
15782  *	 hmebp - hme hash bucket pointer
15783  *	 hmeblkp - address of hmeblk to be removed
15784  *	 pr_hblk - virtual address of previous hmeblkp
15785  *	 listp - pointer to list of hmeblks linked by virtual address
15786  *	 free_now flag - indicates that a complete removal from the hash chains
15787  *			 is necessary.
15788  *
15789  * It is inefficient to use the free_now flag as a cross-call is required to
15790  * remove a single hmeblk from the hash chain but is necessary when hmeblks are
15791  * in short supply.
15792  */
15793 void
15794 sfmmu_hblk_hash_rm(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15795     struct hme_blk *pr_hblk, struct hme_blk **listp,
15796     int free_now)
15797 {
15798 	int shw_size, vshift;
15799 	struct hme_blk *shw_hblkp;
15800 	uint_t		shw_mask, newshw_mask;
15801 	caddr_t		vaddr;
15802 	int		size;
15803 	cpuset_t cpuset = cpu_ready_set;
15804 
15805 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15806 
15807 	if (hmebp->hmeblkp == hmeblkp) {
15808 		hmebp->hmeh_nextpa = hmeblkp->hblk_nextpa;
15809 		hmebp->hmeblkp = hmeblkp->hblk_next;
15810 	} else {
15811 		pr_hblk->hblk_nextpa = hmeblkp->hblk_nextpa;
15812 		pr_hblk->hblk_next = hmeblkp->hblk_next;
15813 	}
15814 
15815 	size = get_hblk_ttesz(hmeblkp);
15816 	shw_hblkp = hmeblkp->hblk_shadow;
15817 	if (shw_hblkp) {
15818 		ASSERT(hblktosfmmu(hmeblkp) != KHATID);
15819 		ASSERT(!hmeblkp->hblk_shared);
15820 #ifdef	DEBUG
15821 		if (mmu_page_sizes == max_mmu_page_sizes) {
15822 			ASSERT(size < TTE256M);
15823 		} else {
15824 			ASSERT(size < TTE4M);
15825 		}
15826 #endif /* DEBUG */
15827 
15828 		shw_size = get_hblk_ttesz(shw_hblkp);
15829 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
15830 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
15831 		ASSERT(vshift < 8);
15832 		/*
15833 		 * Atomically clear shadow mask bit
15834 		 */
15835 		do {
15836 			shw_mask = shw_hblkp->hblk_shw_mask;
15837 			ASSERT(shw_mask & (1 << vshift));
15838 			newshw_mask = shw_mask & ~(1 << vshift);
15839 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
15840 			    shw_mask, newshw_mask);
15841 		} while (newshw_mask != shw_mask);
15842 		hmeblkp->hblk_shadow = NULL;
15843 	}
15844 	hmeblkp->hblk_shw_bit = 0;
15845 
15846 	if (hmeblkp->hblk_shared) {
15847 #ifdef	DEBUG
15848 		sf_srd_t	*srdp;
15849 		sf_region_t	*rgnp;
15850 		uint_t		rid;
15851 
15852 		srdp = hblktosrd(hmeblkp);
15853 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
15854 		rid = hmeblkp->hblk_tag.htag_rid;
15855 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
15856 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
15857 		rgnp = srdp->srd_hmergnp[rid];
15858 		ASSERT(rgnp != NULL);
15859 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
15860 #endif /* DEBUG */
15861 		hmeblkp->hblk_shared = 0;
15862 	}
15863 	if (free_now) {
15864 		kpreempt_disable();
15865 		CPUSET_DEL(cpuset, CPU->cpu_id);
15866 		xt_sync(cpuset);
15867 		xt_sync(cpuset);
15868 		kpreempt_enable();
15869 
15870 		hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
15871 		hmeblkp->hblk_next = NULL;
15872 	} else {
15873 		/* Append hmeblkp to listp for processing later. */
15874 		hmeblkp->hblk_next = *listp;
15875 		*listp = hmeblkp;
15876 	}
15877 }
15878 
15879 /*
15880  * This routine is called when memory is in short supply and returns a free
15881  * hmeblk of the requested size from the cpu pending lists.
15882  */
15883 static struct hme_blk *
15884 sfmmu_check_pending_hblks(int size)
15885 {
15886 	int i;
15887 	struct hme_blk *hmeblkp = NULL, *last_hmeblkp;
15888 	int found_hmeblk;
15889 	cpuset_t cpuset = cpu_ready_set;
15890 	cpu_hme_pend_t *cpuhp;
15891 
15892 	/* Flush cpu hblk pending queues */
15893 	for (i = 0; i < NCPU; i++) {
15894 		cpuhp = &cpu_hme_pend[i];
15895 		if (cpuhp->chp_listp != NULL)  {
15896 			mutex_enter(&cpuhp->chp_mutex);
15897 			if (cpuhp->chp_listp == NULL)  {
15898 				mutex_exit(&cpuhp->chp_mutex);
15899 				continue;
15900 			}
15901 			found_hmeblk = 0;
15902 			last_hmeblkp = NULL;
15903 			for (hmeblkp = cpuhp->chp_listp; hmeblkp != NULL;
15904 			    hmeblkp = hmeblkp->hblk_next) {
15905 				if (get_hblk_ttesz(hmeblkp) == size) {
15906 					if (last_hmeblkp == NULL) {
15907 						cpuhp->chp_listp =
15908 						    hmeblkp->hblk_next;
15909 					} else {
15910 						last_hmeblkp->hblk_next =
15911 						    hmeblkp->hblk_next;
15912 					}
15913 					ASSERT(cpuhp->chp_count > 0);
15914 					cpuhp->chp_count--;
15915 					found_hmeblk = 1;
15916 					break;
15917 				} else {
15918 					last_hmeblkp = hmeblkp;
15919 				}
15920 			}
15921 			mutex_exit(&cpuhp->chp_mutex);
15922 
15923 			if (found_hmeblk) {
15924 				kpreempt_disable();
15925 				CPUSET_DEL(cpuset, CPU->cpu_id);
15926 				xt_sync(cpuset);
15927 				xt_sync(cpuset);
15928 				kpreempt_enable();
15929 				return (hmeblkp);
15930 			}
15931 		}
15932 	}
15933 	return (NULL);
15934 }
15935