xref: /illumos-gate/usr/src/uts/sfmmu/vm/hat_sfmmu.c (revision 668deb93650906efec36a69b7d09c98435d9cf24)
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  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
26  * Copyright 2016 Gary Mills
27  * Copyright 2019 Joyent, Inc.
28  */
29 
30 /*
31  * VM - Hardware Address Translation management for Spitfire MMU.
32  *
33  * This file implements the machine specific hardware translation
34  * needed by the VM system.  The machine independent interface is
35  * described in <vm/hat.h> while the machine dependent interface
36  * and data structures are described in <vm/hat_sfmmu.h>.
37  *
38  * The hat layer manages the address translation hardware as a cache
39  * driven by calls from the higher levels in the VM system.
40  */
41 
42 #include <sys/types.h>
43 #include <sys/kstat.h>
44 #include <vm/hat.h>
45 #include <vm/hat_sfmmu.h>
46 #include <vm/page.h>
47 #include <sys/pte.h>
48 #include <sys/systm.h>
49 #include <sys/mman.h>
50 #include <sys/sysmacros.h>
51 #include <sys/machparam.h>
52 #include <sys/vtrace.h>
53 #include <sys/kmem.h>
54 #include <sys/mmu.h>
55 #include <sys/cmn_err.h>
56 #include <sys/cpu.h>
57 #include <sys/cpuvar.h>
58 #include <sys/debug.h>
59 #include <sys/lgrp.h>
60 #include <sys/archsystm.h>
61 #include <sys/machsystm.h>
62 #include <sys/vmsystm.h>
63 #include <vm/as.h>
64 #include <vm/seg.h>
65 #include <vm/seg_kp.h>
66 #include <vm/seg_kmem.h>
67 #include <vm/seg_kpm.h>
68 #include <vm/rm.h>
69 #include <sys/t_lock.h>
70 #include <sys/obpdefs.h>
71 #include <sys/vm_machparam.h>
72 #include <sys/var.h>
73 #include <sys/trap.h>
74 #include <sys/machtrap.h>
75 #include <sys/scb.h>
76 #include <sys/bitmap.h>
77 #include <sys/machlock.h>
78 #include <sys/membar.h>
79 #include <sys/atomic.h>
80 #include <sys/cpu_module.h>
81 #include <sys/prom_debug.h>
82 #include <sys/ksynch.h>
83 #include <sys/mem_config.h>
84 #include <sys/mem_cage.h>
85 #include <vm/vm_dep.h>
86 #include <sys/fpu/fpusystm.h>
87 #include <vm/mach_kpm.h>
88 #include <sys/callb.h>
89 
90 #ifdef	DEBUG
91 #define	SFMMU_VALIDATE_HMERID(hat, rid, saddr, len)			\
92 	if (SFMMU_IS_SHMERID_VALID(rid)) {				\
93 		caddr_t _eaddr = (saddr) + (len);			\
94 		sf_srd_t *_srdp;					\
95 		sf_region_t *_rgnp;					\
96 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			\
97 		ASSERT(SF_RGNMAP_TEST(hat->sfmmu_hmeregion_map, rid));	\
98 		ASSERT((hat) != ksfmmup);				\
99 		_srdp = (hat)->sfmmu_srdp;				\
100 		ASSERT(_srdp != NULL);					\
101 		ASSERT(_srdp->srd_refcnt != 0);				\
102 		_rgnp = _srdp->srd_hmergnp[(rid)];			\
103 		ASSERT(_rgnp != NULL && _rgnp->rgn_id == rid);		\
104 		ASSERT(_rgnp->rgn_refcnt != 0);				\
105 		ASSERT(!(_rgnp->rgn_flags & SFMMU_REGION_FREE));	\
106 		ASSERT((_rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	\
107 		    SFMMU_REGION_HME);					\
108 		ASSERT((saddr) >= _rgnp->rgn_saddr);			\
109 		ASSERT((saddr) < _rgnp->rgn_saddr + _rgnp->rgn_size);	\
110 		ASSERT(_eaddr > _rgnp->rgn_saddr);			\
111 		ASSERT(_eaddr <= _rgnp->rgn_saddr + _rgnp->rgn_size);	\
112 	}
113 
114 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid)		\
115 {									\
116 		caddr_t _hsva;						\
117 		caddr_t _heva;						\
118 		caddr_t _rsva;						\
119 		caddr_t _reva;						\
120 		int	_ttesz = get_hblk_ttesz(hmeblkp);		\
121 		int	_flagtte;					\
122 		ASSERT((srdp)->srd_refcnt != 0);			\
123 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			\
124 		ASSERT((rgnp)->rgn_id == rid);				\
125 		ASSERT(!((rgnp)->rgn_flags & SFMMU_REGION_FREE));	\
126 		ASSERT(((rgnp)->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	\
127 		    SFMMU_REGION_HME);					\
128 		ASSERT(_ttesz <= (rgnp)->rgn_pgszc);			\
129 		_hsva = (caddr_t)get_hblk_base(hmeblkp);		\
130 		_heva = get_hblk_endaddr(hmeblkp);			\
131 		_rsva = (caddr_t)P2ALIGN(				\
132 		    (uintptr_t)(rgnp)->rgn_saddr, HBLK_MIN_BYTES);	\
133 		_reva = (caddr_t)P2ROUNDUP(				\
134 		    (uintptr_t)((rgnp)->rgn_saddr + (rgnp)->rgn_size),	\
135 		    HBLK_MIN_BYTES);					\
136 		ASSERT(_hsva >= _rsva);					\
137 		ASSERT(_hsva < _reva);					\
138 		ASSERT(_heva > _rsva);					\
139 		ASSERT(_heva <= _reva);					\
140 		_flagtte = (_ttesz < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ : \
141 			_ttesz;						\
142 		ASSERT(rgnp->rgn_hmeflags & (0x1 << _flagtte));		\
143 }
144 
145 #else /* DEBUG */
146 #define	SFMMU_VALIDATE_HMERID(hat, rid, addr, len)
147 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid)
148 #endif /* DEBUG */
149 
150 #if defined(SF_ERRATA_57)
151 extern caddr_t errata57_limit;
152 #endif
153 
154 #define	HME8BLK_SZ_RND		((roundup(HME8BLK_SZ, sizeof (int64_t))) /  \
155 				(sizeof (int64_t)))
156 #define	HBLK_RESERVE		((struct hme_blk *)hblk_reserve)
157 
158 #define	HBLK_RESERVE_CNT	128
159 #define	HBLK_RESERVE_MIN	20
160 
161 static struct hme_blk		*freehblkp;
162 static kmutex_t			freehblkp_lock;
163 static int			freehblkcnt;
164 
165 static int64_t			hblk_reserve[HME8BLK_SZ_RND];
166 static kmutex_t			hblk_reserve_lock;
167 static kthread_t		*hblk_reserve_thread;
168 
169 static nucleus_hblk8_info_t	nucleus_hblk8;
170 static nucleus_hblk1_info_t	nucleus_hblk1;
171 
172 /*
173  * Data to manage per-cpu hmeblk pending queues, hmeblks are queued here
174  * after the initial phase of removing an hmeblk from the hash chain, see
175  * the detailed comment in sfmmu_hblk_hash_rm() for further details.
176  */
177 static cpu_hme_pend_t		*cpu_hme_pend;
178 static uint_t			cpu_hme_pend_thresh;
179 /*
180  * SFMMU specific hat functions
181  */
182 void	hat_pagecachectl(struct page *, int);
183 
184 /* flags for hat_pagecachectl */
185 #define	HAT_CACHE	0x1
186 #define	HAT_UNCACHE	0x2
187 #define	HAT_TMPNC	0x4
188 
189 /*
190  * Flag to allow the creation of non-cacheable translations
191  * to system memory. It is off by default. At the moment this
192  * flag is used by the ecache error injector. The error injector
193  * will turn it on when creating such a translation then shut it
194  * off when it's finished.
195  */
196 
197 int	sfmmu_allow_nc_trans = 0;
198 
199 /*
200  * Flag to disable large page support.
201  *	value of 1 => disable all large pages.
202  *	bits 1, 2, and 3 are to disable 64K, 512K and 4M pages respectively.
203  *
204  * For example, use the value 0x4 to disable 512K pages.
205  *
206  */
207 #define	LARGE_PAGES_OFF		0x1
208 
209 /*
210  * The disable_large_pages and disable_ism_large_pages variables control
211  * hat_memload_array and the page sizes to be used by ISM and the kernel.
212  *
213  * The disable_auto_data_large_pages and disable_auto_text_large_pages variables
214  * are only used to control which OOB pages to use at upper VM segment creation
215  * time, and are set in hat_init_pagesizes and used in the map_pgsz* routines.
216  * Their values may come from platform or CPU specific code to disable page
217  * sizes that should not be used.
218  *
219  * WARNING: 512K pages are currently not supported for ISM/DISM.
220  */
221 uint_t	disable_large_pages = 0;
222 uint_t	disable_ism_large_pages = (1 << TTE512K);
223 uint_t	disable_auto_data_large_pages = 0;
224 uint_t	disable_auto_text_large_pages = 0;
225 
226 /*
227  * Private sfmmu data structures for hat management
228  */
229 static struct kmem_cache *sfmmuid_cache;
230 static struct kmem_cache *mmuctxdom_cache;
231 
232 /*
233  * Private sfmmu data structures for tsb management
234  */
235 static struct kmem_cache *sfmmu_tsbinfo_cache;
236 static struct kmem_cache *sfmmu_tsb8k_cache;
237 static struct kmem_cache *sfmmu_tsb_cache[NLGRPS_MAX];
238 static vmem_t *kmem_bigtsb_arena;
239 static vmem_t *kmem_tsb_arena;
240 
241 /*
242  * sfmmu static variables for hmeblk resource management.
243  */
244 static vmem_t *hat_memload1_arena; /* HAT translation arena for sfmmu1_cache */
245 static struct kmem_cache *sfmmu8_cache;
246 static struct kmem_cache *sfmmu1_cache;
247 static struct kmem_cache *pa_hment_cache;
248 
249 static kmutex_t		ism_mlist_lock;	/* mutex for ism mapping list */
250 /*
251  * private data for ism
252  */
253 static struct kmem_cache *ism_blk_cache;
254 static struct kmem_cache *ism_ment_cache;
255 #define	ISMID_STARTADDR	NULL
256 
257 /*
258  * Region management data structures and function declarations.
259  */
260 
261 static void	sfmmu_leave_srd(sfmmu_t *);
262 static int	sfmmu_srdcache_constructor(void *, void *, int);
263 static void	sfmmu_srdcache_destructor(void *, void *);
264 static int	sfmmu_rgncache_constructor(void *, void *, int);
265 static void	sfmmu_rgncache_destructor(void *, void *);
266 static int	sfrgnmap_isnull(sf_region_map_t *);
267 static int	sfhmergnmap_isnull(sf_hmeregion_map_t *);
268 static int	sfmmu_scdcache_constructor(void *, void *, int);
269 static void	sfmmu_scdcache_destructor(void *, void *);
270 static void	sfmmu_rgn_cb_noop(caddr_t, caddr_t, caddr_t,
271     size_t, void *, u_offset_t);
272 
273 static uint_t srd_hashmask = SFMMU_MAX_SRD_BUCKETS - 1;
274 static sf_srd_bucket_t *srd_buckets;
275 static struct kmem_cache *srd_cache;
276 static uint_t srd_rgn_hashmask = SFMMU_MAX_REGION_BUCKETS - 1;
277 static struct kmem_cache *region_cache;
278 static struct kmem_cache *scd_cache;
279 
280 #ifdef sun4v
281 int use_bigtsb_arena = 1;
282 #else
283 int use_bigtsb_arena = 0;
284 #endif
285 
286 /* External /etc/system tunable, for turning on&off the shctx support */
287 int disable_shctx = 0;
288 /* Internal variable, set by MD if the HW supports shctx feature */
289 int shctx_on = 0;
290 
291 #ifdef DEBUG
292 static void check_scd_sfmmu_list(sfmmu_t **, sfmmu_t *, int);
293 #endif
294 static void sfmmu_to_scd_list(sfmmu_t **, sfmmu_t *);
295 static void sfmmu_from_scd_list(sfmmu_t **, sfmmu_t *);
296 
297 static sf_scd_t *sfmmu_alloc_scd(sf_srd_t *, sf_region_map_t *);
298 static void sfmmu_find_scd(sfmmu_t *);
299 static void sfmmu_join_scd(sf_scd_t *, sfmmu_t *);
300 static void sfmmu_finish_join_scd(sfmmu_t *);
301 static void sfmmu_leave_scd(sfmmu_t *, uchar_t);
302 static void sfmmu_destroy_scd(sf_srd_t *, sf_scd_t *, sf_region_map_t *);
303 static int sfmmu_alloc_scd_tsbs(sf_srd_t *, sf_scd_t *);
304 static void sfmmu_free_scd_tsbs(sfmmu_t *);
305 static void sfmmu_tsb_inv_ctx(sfmmu_t *);
306 static int find_ism_rid(sfmmu_t *, sfmmu_t *, caddr_t, uint_t *);
307 static void sfmmu_ism_hatflags(sfmmu_t *, int);
308 static int sfmmu_srd_lock_held(sf_srd_t *);
309 static void sfmmu_remove_scd(sf_scd_t **, sf_scd_t *);
310 static void sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *);
311 static void sfmmu_link_scd_to_regions(sf_srd_t *, sf_scd_t *);
312 static void sfmmu_unlink_scd_from_regions(sf_srd_t *, sf_scd_t *);
313 static void sfmmu_link_to_hmeregion(sfmmu_t *, sf_region_t *);
314 static void sfmmu_unlink_from_hmeregion(sfmmu_t *, sf_region_t *);
315 
316 /*
317  * ``hat_lock'' is a hashed mutex lock for protecting sfmmu TSB lists,
318  * HAT flags, synchronizing TLB/TSB coherency, and context management.
319  * The lock is hashed on the sfmmup since the case where we need to lock
320  * all processes is rare but does occur (e.g. we need to unload a shared
321  * mapping from all processes using the mapping).  We have a lot of buckets,
322  * and each slab of sfmmu_t's can use about a quarter of them, giving us
323  * a fairly good distribution without wasting too much space and overhead
324  * when we have to grab them all.
325  */
326 #define	SFMMU_NUM_LOCK	128		/* must be power of two */
327 hatlock_t	hat_lock[SFMMU_NUM_LOCK];
328 
329 /*
330  * Hash algorithm optimized for a small number of slabs.
331  *  7 is (highbit((sizeof sfmmu_t)) - 1)
332  * This hash algorithm is based upon the knowledge that sfmmu_t's come from a
333  * kmem_cache, and thus they will be sequential within that cache.  In
334  * addition, each new slab will have a different "color" up to cache_maxcolor
335  * which will skew the hashing for each successive slab which is allocated.
336  * If the size of sfmmu_t changed to a larger size, this algorithm may need
337  * to be revisited.
338  */
339 #define	TSB_HASH_SHIFT_BITS (7)
340 #define	PTR_HASH(x) ((uintptr_t)x >> TSB_HASH_SHIFT_BITS)
341 
342 #ifdef DEBUG
343 int tsb_hash_debug = 0;
344 #define	TSB_HASH(sfmmup)	\
345 	(tsb_hash_debug ? &hat_lock[0] : \
346 	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)])
347 #else	/* DEBUG */
348 #define	TSB_HASH(sfmmup)	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)]
349 #endif	/* DEBUG */
350 
351 
352 /* sfmmu_replace_tsb() return codes. */
353 typedef enum tsb_replace_rc {
354 	TSB_SUCCESS,
355 	TSB_ALLOCFAIL,
356 	TSB_LOSTRACE,
357 	TSB_ALREADY_SWAPPED,
358 	TSB_CANTGROW
359 } tsb_replace_rc_t;
360 
361 /*
362  * Flags for TSB allocation routines.
363  */
364 #define	TSB_ALLOC	0x01
365 #define	TSB_FORCEALLOC	0x02
366 #define	TSB_GROW	0x04
367 #define	TSB_SHRINK	0x08
368 #define	TSB_SWAPIN	0x10
369 
370 /*
371  * Support for HAT callbacks.
372  */
373 #define	SFMMU_MAX_RELOC_CALLBACKS	10
374 int sfmmu_max_cb_id = SFMMU_MAX_RELOC_CALLBACKS;
375 static id_t sfmmu_cb_nextid = 0;
376 static id_t sfmmu_tsb_cb_id;
377 struct sfmmu_callback *sfmmu_cb_table;
378 
379 kmutex_t	kpr_mutex;
380 kmutex_t	kpr_suspendlock;
381 kthread_t	*kreloc_thread;
382 
383 /*
384  * Enable VA->PA translation sanity checking on DEBUG kernels.
385  * Disabled by default.  This is incompatible with some
386  * drivers (error injector, RSM) so if it breaks you get
387  * to keep both pieces.
388  */
389 int hat_check_vtop = 0;
390 
391 /*
392  * Private sfmmu routines (prototypes)
393  */
394 static struct hme_blk *sfmmu_shadow_hcreate(sfmmu_t *, caddr_t, int, uint_t);
395 static struct	hme_blk *sfmmu_hblk_alloc(sfmmu_t *, caddr_t,
396 			struct hmehash_bucket *, uint_t, hmeblk_tag, uint_t,
397 			uint_t);
398 static caddr_t	sfmmu_hblk_unload(struct hat *, struct hme_blk *, caddr_t,
399 			caddr_t, demap_range_t *, uint_t);
400 static caddr_t	sfmmu_hblk_sync(struct hat *, struct hme_blk *, caddr_t,
401 			caddr_t, int);
402 static void	sfmmu_hblk_free(struct hme_blk **);
403 static void	sfmmu_hblks_list_purge(struct hme_blk **, int);
404 static uint_t	sfmmu_get_free_hblk(struct hme_blk **, uint_t);
405 static uint_t	sfmmu_put_free_hblk(struct hme_blk *, uint_t);
406 static struct hme_blk *sfmmu_hblk_steal(int);
407 static int	sfmmu_steal_this_hblk(struct hmehash_bucket *,
408 			struct hme_blk *, uint64_t, struct hme_blk *);
409 static caddr_t	sfmmu_hblk_unlock(struct hme_blk *, caddr_t, caddr_t);
410 
411 static void	hat_do_memload_array(struct hat *, caddr_t, size_t,
412 		    struct page **, uint_t, uint_t, uint_t);
413 static void	hat_do_memload(struct hat *, caddr_t, struct page *,
414 		    uint_t, uint_t, uint_t);
415 static void	sfmmu_memload_batchsmall(struct hat *, caddr_t, page_t **,
416 		    uint_t, uint_t, pgcnt_t, uint_t);
417 void		sfmmu_tteload(struct hat *, tte_t *, caddr_t, page_t *,
418 			uint_t);
419 static int	sfmmu_tteload_array(sfmmu_t *, tte_t *, caddr_t, page_t **,
420 			uint_t, uint_t);
421 static struct hmehash_bucket *sfmmu_tteload_acquire_hashbucket(sfmmu_t *,
422 					caddr_t, int, uint_t);
423 static struct hme_blk *sfmmu_tteload_find_hmeblk(sfmmu_t *,
424 			struct hmehash_bucket *, caddr_t, uint_t, uint_t,
425 			uint_t);
426 static int	sfmmu_tteload_addentry(sfmmu_t *, struct hme_blk *, tte_t *,
427 			caddr_t, page_t **, uint_t, uint_t);
428 static void	sfmmu_tteload_release_hashbucket(struct hmehash_bucket *);
429 
430 static int	sfmmu_pagearray_setup(caddr_t, page_t **, tte_t *, int);
431 static pfn_t	sfmmu_uvatopfn(caddr_t, sfmmu_t *, tte_t *);
432 void		sfmmu_memtte(tte_t *, pfn_t, uint_t, int);
433 #ifdef VAC
434 static void	sfmmu_vac_conflict(struct hat *, caddr_t, page_t *);
435 static int	sfmmu_vacconflict_array(caddr_t, page_t *, int *);
436 int	tst_tnc(page_t *pp, pgcnt_t);
437 void	conv_tnc(page_t *pp, int);
438 #endif
439 
440 static void	sfmmu_get_ctx(sfmmu_t *);
441 static void	sfmmu_free_sfmmu(sfmmu_t *);
442 
443 static void	sfmmu_ttesync(struct hat *, caddr_t, tte_t *, page_t *);
444 static void	sfmmu_chgattr(struct hat *, caddr_t, size_t, uint_t, int);
445 
446 cpuset_t	sfmmu_pageunload(page_t *, struct sf_hment *, int);
447 static void	hat_pagereload(struct page *, struct page *);
448 static cpuset_t	sfmmu_pagesync(page_t *, struct sf_hment *, uint_t);
449 #ifdef VAC
450 void	sfmmu_page_cache_array(page_t *, int, int, pgcnt_t);
451 static void	sfmmu_page_cache(page_t *, int, int, int);
452 #endif
453 
454 cpuset_t	sfmmu_rgntlb_demap(caddr_t, sf_region_t *,
455     struct hme_blk *, int);
456 static void	sfmmu_tlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
457 			pfn_t, int, int, int, int);
458 static void	sfmmu_ismtlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
459 			pfn_t, int);
460 static void	sfmmu_tlb_demap(caddr_t, sfmmu_t *, struct hme_blk *, int, int);
461 static void	sfmmu_tlb_range_demap(demap_range_t *);
462 static void	sfmmu_invalidate_ctx(sfmmu_t *);
463 static void	sfmmu_sync_mmustate(sfmmu_t *);
464 
465 static void	sfmmu_tsbinfo_setup_phys(struct tsb_info *, pfn_t);
466 static int	sfmmu_tsbinfo_alloc(struct tsb_info **, int, int, uint_t,
467 			sfmmu_t *);
468 static void	sfmmu_tsb_free(struct tsb_info *);
469 static void	sfmmu_tsbinfo_free(struct tsb_info *);
470 static int	sfmmu_init_tsbinfo(struct tsb_info *, int, int, uint_t,
471 			sfmmu_t *);
472 static void	sfmmu_tsb_chk_reloc(sfmmu_t *, hatlock_t *);
473 static void	sfmmu_tsb_swapin(sfmmu_t *, hatlock_t *);
474 static int	sfmmu_select_tsb_szc(pgcnt_t);
475 static void	sfmmu_mod_tsb(sfmmu_t *, caddr_t, tte_t *, int);
476 #define		sfmmu_load_tsb(sfmmup, vaddr, tte, szc) \
477 	sfmmu_mod_tsb(sfmmup, vaddr, tte, szc)
478 #define		sfmmu_unload_tsb(sfmmup, vaddr, szc)    \
479 	sfmmu_mod_tsb(sfmmup, vaddr, NULL, szc)
480 static void	sfmmu_copy_tsb(struct tsb_info *, struct tsb_info *);
481 static tsb_replace_rc_t sfmmu_replace_tsb(sfmmu_t *, struct tsb_info *, uint_t,
482     hatlock_t *, uint_t);
483 static void	sfmmu_size_tsb(sfmmu_t *, int, uint64_t, uint64_t, int);
484 
485 #ifdef VAC
486 void	sfmmu_cache_flush(pfn_t, int);
487 void	sfmmu_cache_flushcolor(int, pfn_t);
488 #endif
489 static caddr_t	sfmmu_hblk_chgattr(sfmmu_t *, struct hme_blk *, caddr_t,
490 			caddr_t, demap_range_t *, uint_t, int);
491 
492 static uint64_t	sfmmu_vtop_attr(uint_t, int mode, tte_t *);
493 static uint_t	sfmmu_ptov_attr(tte_t *);
494 static caddr_t	sfmmu_hblk_chgprot(sfmmu_t *, struct hme_blk *, caddr_t,
495 			caddr_t, demap_range_t *, uint_t);
496 static uint_t	sfmmu_vtop_prot(uint_t, uint_t *);
497 static int	sfmmu_idcache_constructor(void *, void *, int);
498 static void	sfmmu_idcache_destructor(void *, void *);
499 static int	sfmmu_hblkcache_constructor(void *, void *, int);
500 static void	sfmmu_hblkcache_destructor(void *, void *);
501 static void	sfmmu_hblkcache_reclaim(void *);
502 static void	sfmmu_shadow_hcleanup(sfmmu_t *, struct hme_blk *,
503 			struct hmehash_bucket *);
504 static void	sfmmu_hblk_hash_rm(struct hmehash_bucket *, struct hme_blk *,
505 			struct hme_blk *, struct hme_blk **, int);
506 static void	sfmmu_hblk_hash_add(struct hmehash_bucket *, struct hme_blk *,
507 			uint64_t);
508 static struct hme_blk *sfmmu_check_pending_hblks(int);
509 static void	sfmmu_free_hblks(sfmmu_t *, caddr_t, caddr_t, int);
510 static void	sfmmu_cleanup_rhblk(sf_srd_t *, caddr_t, uint_t, int);
511 static void	sfmmu_unload_hmeregion_va(sf_srd_t *, uint_t, caddr_t, caddr_t,
512 			int, caddr_t *);
513 static void	sfmmu_unload_hmeregion(sf_srd_t *, sf_region_t *);
514 
515 static void	sfmmu_rm_large_mappings(page_t *, int);
516 
517 static void	hat_lock_init(void);
518 static void	hat_kstat_init(void);
519 static int	sfmmu_kstat_percpu_update(kstat_t *ksp, int rw);
520 static void	sfmmu_set_scd_rttecnt(sf_srd_t *, sf_scd_t *);
521 static	int	sfmmu_is_rgnva(sf_srd_t *, caddr_t, ulong_t, ulong_t);
522 static void	sfmmu_check_page_sizes(sfmmu_t *, int);
523 int	fnd_mapping_sz(page_t *);
524 static void	iment_add(struct ism_ment *,  struct hat *);
525 static void	iment_sub(struct ism_ment *, struct hat *);
526 static pgcnt_t	ism_tsb_entries(sfmmu_t *, int szc);
527 extern void	sfmmu_setup_tsbinfo(sfmmu_t *);
528 extern void	sfmmu_clear_utsbinfo(void);
529 
530 static void		sfmmu_ctx_wrap_around(mmu_ctx_t *, boolean_t);
531 
532 extern int vpm_enable;
533 
534 /* kpm globals */
535 #ifdef	DEBUG
536 /*
537  * Enable trap level tsbmiss handling
538  */
539 int	kpm_tsbmtl = 1;
540 
541 /*
542  * Flush the TLB on kpm mapout. Note: Xcalls are used (again) for the
543  * required TLB shootdowns in this case, so handle w/ care. Off by default.
544  */
545 int	kpm_tlb_flush;
546 #endif	/* DEBUG */
547 
548 static void	*sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *, size_t, int);
549 
550 #ifdef DEBUG
551 static void	sfmmu_check_hblk_flist();
552 #endif
553 
554 /*
555  * Semi-private sfmmu data structures.  Some of them are initialize in
556  * startup or in hat_init. Some of them are private but accessed by
557  * assembly code or mach_sfmmu.c
558  */
559 struct hmehash_bucket *uhme_hash;	/* user hmeblk hash table */
560 struct hmehash_bucket *khme_hash;	/* kernel hmeblk hash table */
561 uint64_t	uhme_hash_pa;		/* PA of uhme_hash */
562 uint64_t	khme_hash_pa;		/* PA of khme_hash */
563 int		uhmehash_num;		/* # of buckets in user hash table */
564 int		khmehash_num;		/* # of buckets in kernel hash table */
565 
566 uint_t		max_mmu_ctxdoms = 0;	/* max context domains in the system */
567 mmu_ctx_t	**mmu_ctxs_tbl;		/* global array of context domains */
568 uint64_t	mmu_saved_gnum = 0;	/* to init incoming MMUs' gnums */
569 
570 #define	DEFAULT_NUM_CTXS_PER_MMU 8192
571 static uint_t	nctxs = DEFAULT_NUM_CTXS_PER_MMU;
572 
573 int		cache;			/* describes system cache */
574 
575 caddr_t		ktsb_base;		/* kernel 8k-indexed tsb base address */
576 uint64_t	ktsb_pbase;		/* kernel 8k-indexed tsb phys address */
577 int		ktsb_szcode;		/* kernel 8k-indexed tsb size code */
578 int		ktsb_sz;		/* kernel 8k-indexed tsb size */
579 
580 caddr_t		ktsb4m_base;		/* kernel 4m-indexed tsb base address */
581 uint64_t	ktsb4m_pbase;		/* kernel 4m-indexed tsb phys address */
582 int		ktsb4m_szcode;		/* kernel 4m-indexed tsb size code */
583 int		ktsb4m_sz;		/* kernel 4m-indexed tsb size */
584 
585 uint64_t	kpm_tsbbase;		/* kernel seg_kpm 4M TSB base address */
586 int		kpm_tsbsz;		/* kernel seg_kpm 4M TSB size code */
587 uint64_t	kpmsm_tsbbase;		/* kernel seg_kpm 8K TSB base address */
588 int		kpmsm_tsbsz;		/* kernel seg_kpm 8K TSB size code */
589 
590 #ifndef sun4v
591 int		utsb_dtlb_ttenum = -1;	/* index in TLB for utsb locked TTE */
592 int		utsb4m_dtlb_ttenum = -1; /* index in TLB for 4M TSB TTE */
593 int		dtlb_resv_ttenum;	/* index in TLB of first reserved TTE */
594 caddr_t		utsb_vabase;		/* reserved kernel virtual memory */
595 caddr_t		utsb4m_vabase;		/* for trap handler TSB accesses */
596 #endif /* sun4v */
597 uint64_t	tsb_alloc_bytes = 0;	/* bytes allocated to TSBs */
598 vmem_t		*kmem_tsb_default_arena[NLGRPS_MAX];	/* For dynamic TSBs */
599 vmem_t		*kmem_bigtsb_default_arena[NLGRPS_MAX]; /* dynamic 256M TSBs */
600 
601 /*
602  * Size to use for TSB slabs.  Future platforms that support page sizes
603  * larger than 4M may wish to change these values, and provide their own
604  * assembly macros for building and decoding the TSB base register contents.
605  * Note disable_large_pages will override the value set here.
606  */
607 static	uint_t tsb_slab_ttesz = TTE4M;
608 size_t	tsb_slab_size = MMU_PAGESIZE4M;
609 uint_t	tsb_slab_shift = MMU_PAGESHIFT4M;
610 /* PFN mask for TTE */
611 size_t	tsb_slab_mask = MMU_PAGEOFFSET4M >> MMU_PAGESHIFT;
612 
613 /*
614  * Size to use for TSB slabs.  These are used only when 256M tsb arenas
615  * exist.
616  */
617 static uint_t	bigtsb_slab_ttesz = TTE256M;
618 static size_t	bigtsb_slab_size = MMU_PAGESIZE256M;
619 static uint_t	bigtsb_slab_shift = MMU_PAGESHIFT256M;
620 /* 256M page alignment for 8K pfn */
621 static size_t	bigtsb_slab_mask = MMU_PAGEOFFSET256M >> MMU_PAGESHIFT;
622 
623 /* largest TSB size to grow to, will be smaller on smaller memory systems */
624 static int	tsb_max_growsize = 0;
625 
626 /*
627  * Tunable parameters dealing with TSB policies.
628  */
629 
630 /*
631  * This undocumented tunable forces all 8K TSBs to be allocated from
632  * the kernel heap rather than from the kmem_tsb_default_arena arenas.
633  */
634 #ifdef	DEBUG
635 int	tsb_forceheap = 0;
636 #endif	/* DEBUG */
637 
638 /*
639  * Decide whether to use per-lgroup arenas, or one global set of
640  * TSB arenas.  The default is not to break up per-lgroup, since
641  * most platforms don't recognize any tangible benefit from it.
642  */
643 int	tsb_lgrp_affinity = 0;
644 
645 /*
646  * Used for growing the TSB based on the process RSS.
647  * tsb_rss_factor is based on the smallest TSB, and is
648  * shifted by the TSB size to determine if we need to grow.
649  * The default will grow the TSB if the number of TTEs for
650  * this page size exceeds 75% of the number of TSB entries,
651  * which should _almost_ eliminate all conflict misses
652  * (at the expense of using up lots and lots of memory).
653  */
654 #define	TSB_RSS_FACTOR		(TSB_ENTRIES(TSB_MIN_SZCODE) * 0.75)
655 #define	SFMMU_RSS_TSBSIZE(tsbszc)	(tsb_rss_factor << tsbszc)
656 #define	SELECT_TSB_SIZECODE(pgcnt) ( \
657 	(enable_tsb_rss_sizing)? sfmmu_select_tsb_szc(pgcnt) : \
658 	default_tsb_size)
659 #define	TSB_OK_SHRINK()	\
660 	(tsb_alloc_bytes > tsb_alloc_hiwater || freemem < desfree)
661 #define	TSB_OK_GROW()	\
662 	(tsb_alloc_bytes < tsb_alloc_hiwater && freemem > desfree)
663 
664 int	enable_tsb_rss_sizing = 1;
665 int	tsb_rss_factor	= (int)TSB_RSS_FACTOR;
666 
667 /* which TSB size code to use for new address spaces or if rss sizing off */
668 int default_tsb_size = TSB_8K_SZCODE;
669 
670 static uint64_t tsb_alloc_hiwater; /* limit TSB reserved memory */
671 uint64_t tsb_alloc_hiwater_factor; /* tsb_alloc_hiwater = physmem / this */
672 #define	TSB_ALLOC_HIWATER_FACTOR_DEFAULT	32
673 
674 #ifdef DEBUG
675 static int tsb_random_size = 0;	/* set to 1 to test random tsb sizes on alloc */
676 static int tsb_grow_stress = 0;	/* if set to 1, keep replacing TSB w/ random */
677 static int tsb_alloc_mtbf = 0;	/* fail allocation every n attempts */
678 static int tsb_alloc_fail_mtbf = 0;
679 static int tsb_alloc_count = 0;
680 #endif /* DEBUG */
681 
682 /* if set to 1, will remap valid TTEs when growing TSB. */
683 int tsb_remap_ttes = 1;
684 
685 /*
686  * If we have more than this many mappings, allocate a second TSB.
687  * This default is chosen because the I/D fully associative TLBs are
688  * assumed to have at least 8 available entries. Platforms with a
689  * larger fully-associative TLB could probably override the default.
690  */
691 
692 #ifdef sun4v
693 int tsb_sectsb_threshold = 0;
694 #else
695 int tsb_sectsb_threshold = 8;
696 #endif
697 
698 /*
699  * kstat data
700  */
701 struct sfmmu_global_stat sfmmu_global_stat;
702 struct sfmmu_tsbsize_stat sfmmu_tsbsize_stat;
703 
704 /*
705  * Global data
706  */
707 sfmmu_t		*ksfmmup;		/* kernel's hat id */
708 
709 #ifdef DEBUG
710 static void	chk_tte(tte_t *, tte_t *, tte_t *, struct hme_blk *);
711 #endif
712 
713 /* sfmmu locking operations */
714 static kmutex_t *sfmmu_mlspl_enter(struct page *, int);
715 static int	sfmmu_mlspl_held(struct page *, int);
716 
717 kmutex_t *sfmmu_page_enter(page_t *);
718 void	sfmmu_page_exit(kmutex_t *);
719 int	sfmmu_page_spl_held(struct page *);
720 
721 /* sfmmu internal locking operations - accessed directly */
722 static void	sfmmu_mlist_reloc_enter(page_t *, page_t *,
723 				kmutex_t **, kmutex_t **);
724 static void	sfmmu_mlist_reloc_exit(kmutex_t *, kmutex_t *);
725 static hatlock_t *
726 		sfmmu_hat_enter(sfmmu_t *);
727 static hatlock_t *
728 		sfmmu_hat_tryenter(sfmmu_t *);
729 static void	sfmmu_hat_exit(hatlock_t *);
730 static void	sfmmu_hat_lock_all(void);
731 static void	sfmmu_hat_unlock_all(void);
732 static void	sfmmu_ismhat_enter(sfmmu_t *, int);
733 static void	sfmmu_ismhat_exit(sfmmu_t *, int);
734 
735 kpm_hlk_t	*kpmp_table;
736 uint_t		kpmp_table_sz;	/* must be a power of 2 */
737 uchar_t		kpmp_shift;
738 
739 kpm_shlk_t	*kpmp_stable;
740 uint_t		kpmp_stable_sz;	/* must be a power of 2 */
741 
742 /*
743  * SPL_TABLE_SIZE is 2 * NCPU, but no smaller than 128.
744  * SPL_SHIFT is log2(SPL_TABLE_SIZE).
745  */
746 #if ((2*NCPU_P2) > 128)
747 #define	SPL_SHIFT	((unsigned)(NCPU_LOG2 + 1))
748 #else
749 #define	SPL_SHIFT	7U
750 #endif
751 #define	SPL_TABLE_SIZE	(1U << SPL_SHIFT)
752 #define	SPL_MASK	(SPL_TABLE_SIZE - 1)
753 
754 /*
755  * We shift by PP_SHIFT to take care of the low-order 0 bits of a page_t
756  * and by multiples of SPL_SHIFT to get as many varied bits as we can.
757  */
758 #define	SPL_INDEX(pp) \
759 	((((uintptr_t)(pp) >> PP_SHIFT) ^ \
760 	((uintptr_t)(pp) >> (PP_SHIFT + SPL_SHIFT)) ^ \
761 	((uintptr_t)(pp) >> (PP_SHIFT + SPL_SHIFT * 2)) ^ \
762 	((uintptr_t)(pp) >> (PP_SHIFT + SPL_SHIFT * 3))) & \
763 	SPL_MASK)
764 
765 #define	SPL_HASH(pp)    \
766 	(&sfmmu_page_lock[SPL_INDEX(pp)].pad_mutex)
767 
768 static	pad_mutex_t	sfmmu_page_lock[SPL_TABLE_SIZE];
769 
770 /* Array of mutexes protecting a page's mapping list and p_nrm field. */
771 
772 #define	MML_TABLE_SIZE	SPL_TABLE_SIZE
773 #define	MLIST_HASH(pp)	(&mml_table[SPL_INDEX(pp)].pad_mutex)
774 
775 static pad_mutex_t	mml_table[MML_TABLE_SIZE];
776 
777 /*
778  * hat_unload_callback() will group together callbacks in order
779  * to avoid xt_sync() calls.  This is the maximum size of the group.
780  */
781 #define	MAX_CB_ADDR	32
782 
783 tte_t	hw_tte;
784 static ulong_t sfmmu_dmr_maxbit = DMR_MAXBIT;
785 
786 static char	*mmu_ctx_kstat_names[] = {
787 	"mmu_ctx_tsb_exceptions",
788 	"mmu_ctx_tsb_raise_exception",
789 	"mmu_ctx_wrap_around",
790 };
791 
792 /*
793  * Wrapper for vmem_xalloc since vmem_create only allows limited
794  * parameters for vm_source_alloc functions.  This function allows us
795  * to specify alignment consistent with the size of the object being
796  * allocated.
797  */
798 static void *
799 sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *vmp, size_t size, int vmflag)
800 {
801 	return (vmem_xalloc(vmp, size, size, 0, 0, NULL, NULL, vmflag));
802 }
803 
804 /* Common code for setting tsb_alloc_hiwater. */
805 #define	SFMMU_SET_TSB_ALLOC_HIWATER(pages)	tsb_alloc_hiwater = \
806 		ptob(pages) / tsb_alloc_hiwater_factor
807 
808 /*
809  * Set tsb_max_growsize to allow at most all of physical memory to be mapped by
810  * a single TSB.  physmem is the number of physical pages so we need physmem 8K
811  * TTEs to represent all those physical pages.  We round this up by using
812  * 1<<highbit().  To figure out which size code to use, remember that the size
813  * code is just an amount to shift the smallest TSB size to get the size of
814  * this TSB.  So we subtract that size, TSB_START_SIZE, from highbit() (or
815  * highbit() - 1) to get the size code for the smallest TSB that can represent
816  * all of physical memory, while erring on the side of too much.
817  *
818  * Restrict tsb_max_growsize to make sure that:
819  *	1) TSBs can't grow larger than the TSB slab size
820  *	2) TSBs can't grow larger than UTSB_MAX_SZCODE.
821  */
822 #define	SFMMU_SET_TSB_MAX_GROWSIZE(pages) {				\
823 	int	_i, _szc, _slabszc, _tsbszc;				\
824 									\
825 	_i = highbit(pages);						\
826 	if ((1 << (_i - 1)) == (pages))					\
827 		_i--;		/* 2^n case, round down */              \
828 	_szc = _i - TSB_START_SIZE;					\
829 	_slabszc = bigtsb_slab_shift - (TSB_START_SIZE + TSB_ENTRY_SHIFT); \
830 	_tsbszc = MIN(_szc, _slabszc);                                  \
831 	tsb_max_growsize = MIN(_tsbszc, UTSB_MAX_SZCODE);               \
832 }
833 
834 /*
835  * Given a pointer to an sfmmu and a TTE size code, return a pointer to the
836  * tsb_info which handles that TTE size.
837  */
838 #define	SFMMU_GET_TSBINFO(tsbinfop, sfmmup, tte_szc) {			\
839 	(tsbinfop) = (sfmmup)->sfmmu_tsb;				\
840 	ASSERT(((tsbinfop)->tsb_flags & TSB_SHAREDCTX) ||		\
841 	    sfmmu_hat_lock_held(sfmmup));				\
842 	if ((tte_szc) >= TTE4M)	{					\
843 		ASSERT((tsbinfop) != NULL);				\
844 		(tsbinfop) = (tsbinfop)->tsb_next;			\
845 	}								\
846 }
847 
848 /*
849  * Macro to use to unload entries from the TSB.
850  * It has knowledge of which page sizes get replicated in the TSB
851  * and will call the appropriate unload routine for the appropriate size.
852  */
853 #define	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, ismhat)		\
854 {									\
855 	int ttesz = get_hblk_ttesz(hmeblkp);				\
856 	if (ttesz == TTE8K || ttesz == TTE4M) {				\
857 		sfmmu_unload_tsb(sfmmup, addr, ttesz);			\
858 	} else {							\
859 		caddr_t sva = ismhat ? addr :				\
860 		    (caddr_t)get_hblk_base(hmeblkp);			\
861 		caddr_t eva = sva + get_hblk_span(hmeblkp);		\
862 		ASSERT(addr >= sva && addr < eva);			\
863 		sfmmu_unload_tsb_range(sfmmup, sva, eva, ttesz);	\
864 	}								\
865 }
866 
867 
868 /* Update tsb_alloc_hiwater after memory is configured. */
869 /*ARGSUSED*/
870 static void
871 sfmmu_update_post_add(void *arg, pgcnt_t delta_pages)
872 {
873 	/* Assumes physmem has already been updated. */
874 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
875 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
876 }
877 
878 /*
879  * Update tsb_alloc_hiwater before memory is deleted.  We'll do nothing here
880  * and update tsb_alloc_hiwater and tsb_max_growsize after the memory is
881  * deleted.
882  */
883 /*ARGSUSED*/
884 static int
885 sfmmu_update_pre_del(void *arg, pgcnt_t delta_pages)
886 {
887 	return (0);
888 }
889 
890 /* Update tsb_alloc_hiwater after memory fails to be unconfigured. */
891 /*ARGSUSED*/
892 static void
893 sfmmu_update_post_del(void *arg, pgcnt_t delta_pages, int cancelled)
894 {
895 	/*
896 	 * Whether the delete was cancelled or not, just go ahead and update
897 	 * tsb_alloc_hiwater and tsb_max_growsize.
898 	 */
899 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
900 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
901 }
902 
903 static kphysm_setup_vector_t sfmmu_update_vec = {
904 	KPHYSM_SETUP_VECTOR_VERSION,	/* version */
905 	sfmmu_update_post_add,		/* post_add */
906 	sfmmu_update_pre_del,		/* pre_del */
907 	sfmmu_update_post_del		/* post_del */
908 };
909 
910 
911 /*
912  * HME_BLK HASH PRIMITIVES
913  */
914 
915 /*
916  * Enter a hme on the mapping list for page pp.
917  * When large pages are more prevalent in the system we might want to
918  * keep the mapping list in ascending order by the hment size. For now,
919  * small pages are more frequent, so don't slow it down.
920  */
921 #define	HME_ADD(hme, pp)					\
922 {								\
923 	ASSERT(sfmmu_mlist_held(pp));				\
924 								\
925 	hme->hme_prev = NULL;					\
926 	hme->hme_next = pp->p_mapping;				\
927 	hme->hme_page = pp;					\
928 	if (pp->p_mapping) {					\
929 		((struct sf_hment *)(pp->p_mapping))->hme_prev = hme;\
930 		ASSERT(pp->p_share > 0);			\
931 	} else  {						\
932 		/* EMPTY */					\
933 		ASSERT(pp->p_share == 0);			\
934 	}							\
935 	pp->p_mapping = hme;					\
936 	pp->p_share++;						\
937 }
938 
939 /*
940  * Enter a hme on the mapping list for page pp.
941  * If we are unmapping a large translation, we need to make sure that the
942  * change is reflect in the corresponding bit of the p_index field.
943  */
944 #define	HME_SUB(hme, pp)					\
945 {								\
946 	ASSERT(sfmmu_mlist_held(pp));				\
947 	ASSERT(hme->hme_page == pp || IS_PAHME(hme));		\
948 								\
949 	if (pp->p_mapping == NULL) {				\
950 		panic("hme_remove - no mappings");		\
951 	}							\
952 								\
953 	membar_stst();	/* ensure previous stores finish */	\
954 								\
955 	ASSERT(pp->p_share > 0);				\
956 	pp->p_share--;						\
957 								\
958 	if (hme->hme_prev) {					\
959 		ASSERT(pp->p_mapping != hme);			\
960 		ASSERT(hme->hme_prev->hme_page == pp ||		\
961 			IS_PAHME(hme->hme_prev));		\
962 		hme->hme_prev->hme_next = hme->hme_next;	\
963 	} else {						\
964 		ASSERT(pp->p_mapping == hme);			\
965 		pp->p_mapping = hme->hme_next;			\
966 		ASSERT((pp->p_mapping == NULL) ?		\
967 			(pp->p_share == 0) : 1);		\
968 	}							\
969 								\
970 	if (hme->hme_next) {					\
971 		ASSERT(hme->hme_next->hme_page == pp ||		\
972 			IS_PAHME(hme->hme_next));		\
973 		hme->hme_next->hme_prev = hme->hme_prev;	\
974 	}							\
975 								\
976 	/* zero out the entry */				\
977 	hme->hme_next = NULL;					\
978 	hme->hme_prev = NULL;					\
979 	hme->hme_page = NULL;					\
980 								\
981 	if (hme_size(hme) > TTE8K) {				\
982 		/* remove mappings for remainder of large pg */	\
983 		sfmmu_rm_large_mappings(pp, hme_size(hme));	\
984 	}							\
985 }
986 
987 /*
988  * This function returns the hment given the hme_blk and a vaddr.
989  * It assumes addr has already been checked to belong to hme_blk's
990  * range.
991  */
992 #define	HBLKTOHME(hment, hmeblkp, addr)					\
993 {									\
994 	int index;							\
995 	HBLKTOHME_IDX(hment, hmeblkp, addr, index)			\
996 }
997 
998 /*
999  * Version of HBLKTOHME that also returns the index in hmeblkp
1000  * of the hment.
1001  */
1002 #define	HBLKTOHME_IDX(hment, hmeblkp, addr, idx)			\
1003 {									\
1004 	ASSERT(in_hblk_range((hmeblkp), (addr)));			\
1005 									\
1006 	if (get_hblk_ttesz(hmeblkp) == TTE8K) {				\
1007 		idx = (((uintptr_t)(addr) >> MMU_PAGESHIFT) & (NHMENTS-1)); \
1008 	} else								\
1009 		idx = 0;						\
1010 									\
1011 	(hment) = &(hmeblkp)->hblk_hme[idx];				\
1012 }
1013 
1014 /*
1015  * Disable any page sizes not supported by the CPU
1016  */
1017 void
1018 hat_init_pagesizes()
1019 {
1020 	int		i;
1021 
1022 	mmu_exported_page_sizes = 0;
1023 	for (i = TTE8K; i < max_mmu_page_sizes; i++) {
1024 
1025 		szc_2_userszc[i] = (uint_t)-1;
1026 		userszc_2_szc[i] = (uint_t)-1;
1027 
1028 		if ((mmu_exported_pagesize_mask & (1 << i)) == 0) {
1029 			disable_large_pages |= (1 << i);
1030 		} else {
1031 			szc_2_userszc[i] = mmu_exported_page_sizes;
1032 			userszc_2_szc[mmu_exported_page_sizes] = i;
1033 			mmu_exported_page_sizes++;
1034 		}
1035 	}
1036 
1037 	disable_ism_large_pages |= disable_large_pages;
1038 	disable_auto_data_large_pages = disable_large_pages;
1039 	disable_auto_text_large_pages = disable_large_pages;
1040 
1041 	/*
1042 	 * Initialize mmu-specific large page sizes.
1043 	 */
1044 	if (&mmu_large_pages_disabled) {
1045 		disable_large_pages |= mmu_large_pages_disabled(HAT_LOAD);
1046 		disable_ism_large_pages |=
1047 		    mmu_large_pages_disabled(HAT_LOAD_SHARE);
1048 		disable_auto_data_large_pages |=
1049 		    mmu_large_pages_disabled(HAT_AUTO_DATA);
1050 		disable_auto_text_large_pages |=
1051 		    mmu_large_pages_disabled(HAT_AUTO_TEXT);
1052 	}
1053 }
1054 
1055 /*
1056  * Initialize the hardware address translation structures.
1057  */
1058 void
1059 hat_init(void)
1060 {
1061 	int		i;
1062 	uint_t		sz;
1063 	size_t		size;
1064 
1065 	hat_lock_init();
1066 	hat_kstat_init();
1067 
1068 	/*
1069 	 * Hardware-only bits in a TTE
1070 	 */
1071 	MAKE_TTE_MASK(&hw_tte);
1072 
1073 	hat_init_pagesizes();
1074 
1075 	/* Initialize the hash locks */
1076 	for (i = 0; i < khmehash_num; i++) {
1077 		mutex_init(&khme_hash[i].hmehash_mutex, NULL,
1078 		    MUTEX_DEFAULT, NULL);
1079 		khme_hash[i].hmeh_nextpa = HMEBLK_ENDPA;
1080 	}
1081 	for (i = 0; i < uhmehash_num; i++) {
1082 		mutex_init(&uhme_hash[i].hmehash_mutex, NULL,
1083 		    MUTEX_DEFAULT, NULL);
1084 		uhme_hash[i].hmeh_nextpa = HMEBLK_ENDPA;
1085 	}
1086 	khmehash_num--;		/* make sure counter starts from 0 */
1087 	uhmehash_num--;		/* make sure counter starts from 0 */
1088 
1089 	/*
1090 	 * Allocate context domain structures.
1091 	 *
1092 	 * A platform may choose to modify max_mmu_ctxdoms in
1093 	 * set_platform_defaults(). If a platform does not define
1094 	 * a set_platform_defaults() or does not choose to modify
1095 	 * max_mmu_ctxdoms, it gets one MMU context domain for every CPU.
1096 	 *
1097 	 * For all platforms that have CPUs sharing MMUs, this
1098 	 * value must be defined.
1099 	 */
1100 	if (max_mmu_ctxdoms == 0)
1101 		max_mmu_ctxdoms = max_ncpus;
1102 
1103 	size = max_mmu_ctxdoms * sizeof (mmu_ctx_t *);
1104 	mmu_ctxs_tbl = kmem_zalloc(size, KM_SLEEP);
1105 
1106 	/* mmu_ctx_t is 64 bytes aligned */
1107 	mmuctxdom_cache = kmem_cache_create("mmuctxdom_cache",
1108 	    sizeof (mmu_ctx_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
1109 	/*
1110 	 * MMU context domain initialization for the Boot CPU.
1111 	 * This needs the context domains array allocated above.
1112 	 */
1113 	mutex_enter(&cpu_lock);
1114 	sfmmu_cpu_init(CPU);
1115 	mutex_exit(&cpu_lock);
1116 
1117 	/*
1118 	 * Intialize ism mapping list lock.
1119 	 */
1120 
1121 	mutex_init(&ism_mlist_lock, NULL, MUTEX_DEFAULT, NULL);
1122 
1123 	/*
1124 	 * Each sfmmu structure carries an array of MMU context info
1125 	 * structures, one per context domain. The size of this array depends
1126 	 * on the maximum number of context domains. So, the size of the
1127 	 * sfmmu structure varies per platform.
1128 	 *
1129 	 * sfmmu is allocated from static arena, because trap
1130 	 * handler at TL > 0 is not allowed to touch kernel relocatable
1131 	 * memory. sfmmu's alignment is changed to 64 bytes from
1132 	 * default 8 bytes, as the lower 6 bits will be used to pass
1133 	 * pgcnt to vtag_flush_pgcnt_tl1.
1134 	 */
1135 	size = sizeof (sfmmu_t) + sizeof (sfmmu_ctx_t) * (max_mmu_ctxdoms - 1);
1136 
1137 	sfmmuid_cache = kmem_cache_create("sfmmuid_cache", size,
1138 	    64, sfmmu_idcache_constructor, sfmmu_idcache_destructor,
1139 	    NULL, NULL, static_arena, 0);
1140 
1141 	sfmmu_tsbinfo_cache = kmem_cache_create("sfmmu_tsbinfo_cache",
1142 	    sizeof (struct tsb_info), 0, NULL, NULL, NULL, NULL, NULL, 0);
1143 
1144 	/*
1145 	 * Since we only use the tsb8k cache to "borrow" pages for TSBs
1146 	 * from the heap when low on memory or when TSB_FORCEALLOC is
1147 	 * specified, don't use magazines to cache them--we want to return
1148 	 * them to the system as quickly as possible.
1149 	 */
1150 	sfmmu_tsb8k_cache = kmem_cache_create("sfmmu_tsb8k_cache",
1151 	    MMU_PAGESIZE, MMU_PAGESIZE, NULL, NULL, NULL, NULL,
1152 	    static_arena, KMC_NOMAGAZINE);
1153 
1154 	/*
1155 	 * Set tsb_alloc_hiwater to 1/tsb_alloc_hiwater_factor of physical
1156 	 * memory, which corresponds to the old static reserve for TSBs.
1157 	 * tsb_alloc_hiwater_factor defaults to 32.  This caps the amount of
1158 	 * memory we'll allocate for TSB slabs; beyond this point TSB
1159 	 * allocations will be taken from the kernel heap (via
1160 	 * sfmmu_tsb8k_cache) and will be throttled as would any other kmem
1161 	 * consumer.
1162 	 */
1163 	if (tsb_alloc_hiwater_factor == 0) {
1164 		tsb_alloc_hiwater_factor = TSB_ALLOC_HIWATER_FACTOR_DEFAULT;
1165 	}
1166 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
1167 
1168 	for (sz = tsb_slab_ttesz; sz > 0; sz--) {
1169 		if (!(disable_large_pages & (1 << sz)))
1170 			break;
1171 	}
1172 
1173 	if (sz < tsb_slab_ttesz) {
1174 		tsb_slab_ttesz = sz;
1175 		tsb_slab_shift = MMU_PAGESHIFT + (sz << 1) + sz;
1176 		tsb_slab_size = 1 << tsb_slab_shift;
1177 		tsb_slab_mask = (1 << (tsb_slab_shift - MMU_PAGESHIFT)) - 1;
1178 		use_bigtsb_arena = 0;
1179 	} else if (use_bigtsb_arena &&
1180 	    (disable_large_pages & (1 << bigtsb_slab_ttesz))) {
1181 		use_bigtsb_arena = 0;
1182 	}
1183 
1184 	if (!use_bigtsb_arena) {
1185 		bigtsb_slab_shift = tsb_slab_shift;
1186 	}
1187 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
1188 
1189 	/*
1190 	 * On smaller memory systems, allocate TSB memory in smaller chunks
1191 	 * than the default 4M slab size. We also honor disable_large_pages
1192 	 * here.
1193 	 *
1194 	 * The trap handlers need to be patched with the final slab shift,
1195 	 * since they need to be able to construct the TSB pointer at runtime.
1196 	 */
1197 	if ((tsb_max_growsize <= TSB_512K_SZCODE) &&
1198 	    !(disable_large_pages & (1 << TTE512K))) {
1199 		tsb_slab_ttesz = TTE512K;
1200 		tsb_slab_shift = MMU_PAGESHIFT512K;
1201 		tsb_slab_size = MMU_PAGESIZE512K;
1202 		tsb_slab_mask = MMU_PAGEOFFSET512K >> MMU_PAGESHIFT;
1203 		use_bigtsb_arena = 0;
1204 	}
1205 
1206 	if (!use_bigtsb_arena) {
1207 		bigtsb_slab_ttesz = tsb_slab_ttesz;
1208 		bigtsb_slab_shift = tsb_slab_shift;
1209 		bigtsb_slab_size = tsb_slab_size;
1210 		bigtsb_slab_mask = tsb_slab_mask;
1211 	}
1212 
1213 
1214 	/*
1215 	 * Set up memory callback to update tsb_alloc_hiwater and
1216 	 * tsb_max_growsize.
1217 	 */
1218 	i = kphysm_setup_func_register(&sfmmu_update_vec, (void *) 0);
1219 	ASSERT(i == 0);
1220 
1221 	/*
1222 	 * kmem_tsb_arena is the source from which large TSB slabs are
1223 	 * drawn.  The quantum of this arena corresponds to the largest
1224 	 * TSB size we can dynamically allocate for user processes.
1225 	 * Currently it must also be a supported page size since we
1226 	 * use exactly one translation entry to map each slab page.
1227 	 *
1228 	 * The per-lgroup kmem_tsb_default_arena arenas are the arenas from
1229 	 * which most TSBs are allocated.  Since most TSB allocations are
1230 	 * typically 8K we have a kmem cache we stack on top of each
1231 	 * kmem_tsb_default_arena to speed up those allocations.
1232 	 *
1233 	 * Note the two-level scheme of arenas is required only
1234 	 * because vmem_create doesn't allow us to specify alignment
1235 	 * requirements.  If this ever changes the code could be
1236 	 * simplified to use only one level of arenas.
1237 	 *
1238 	 * If 256M page support exists on sun4v, 256MB kmem_bigtsb_arena
1239 	 * will be provided in addition to the 4M kmem_tsb_arena.
1240 	 */
1241 	if (use_bigtsb_arena) {
1242 		kmem_bigtsb_arena = vmem_create("kmem_bigtsb", NULL, 0,
1243 		    bigtsb_slab_size, sfmmu_vmem_xalloc_aligned_wrapper,
1244 		    vmem_xfree, heap_arena, 0, VM_SLEEP);
1245 	}
1246 
1247 	kmem_tsb_arena = vmem_create("kmem_tsb", NULL, 0, tsb_slab_size,
1248 	    sfmmu_vmem_xalloc_aligned_wrapper,
1249 	    vmem_xfree, heap_arena, 0, VM_SLEEP);
1250 
1251 	if (tsb_lgrp_affinity) {
1252 		char s[50];
1253 		for (i = 0; i < NLGRPS_MAX; i++) {
1254 			if (use_bigtsb_arena) {
1255 				(void) sprintf(s, "kmem_bigtsb_lgrp%d", i);
1256 				kmem_bigtsb_default_arena[i] = vmem_create(s,
1257 				    NULL, 0, 2 * tsb_slab_size,
1258 				    sfmmu_tsb_segkmem_alloc,
1259 				    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena,
1260 				    0, VM_SLEEP | VM_BESTFIT);
1261 			}
1262 
1263 			(void) sprintf(s, "kmem_tsb_lgrp%d", i);
1264 			kmem_tsb_default_arena[i] = vmem_create(s,
1265 			    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1266 			    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1267 			    VM_SLEEP | VM_BESTFIT);
1268 
1269 			(void) sprintf(s, "sfmmu_tsb_lgrp%d_cache", i);
1270 			sfmmu_tsb_cache[i] = kmem_cache_create(s,
1271 			    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1272 			    kmem_tsb_default_arena[i], 0);
1273 		}
1274 	} else {
1275 		if (use_bigtsb_arena) {
1276 			kmem_bigtsb_default_arena[0] =
1277 			    vmem_create("kmem_bigtsb_default", NULL, 0,
1278 			    2 * tsb_slab_size, sfmmu_tsb_segkmem_alloc,
1279 			    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena, 0,
1280 			    VM_SLEEP | VM_BESTFIT);
1281 		}
1282 
1283 		kmem_tsb_default_arena[0] = vmem_create("kmem_tsb_default",
1284 		    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1285 		    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1286 		    VM_SLEEP | VM_BESTFIT);
1287 		sfmmu_tsb_cache[0] = kmem_cache_create("sfmmu_tsb_cache",
1288 		    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1289 		    kmem_tsb_default_arena[0], 0);
1290 	}
1291 
1292 	sfmmu8_cache = kmem_cache_create("sfmmu8_cache", HME8BLK_SZ,
1293 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1294 	    sfmmu_hblkcache_destructor,
1295 	    sfmmu_hblkcache_reclaim, (void *)HME8BLK_SZ,
1296 	    hat_memload_arena, KMC_NOHASH);
1297 
1298 	hat_memload1_arena = vmem_create("hat_memload1", NULL, 0, PAGESIZE,
1299 	    segkmem_alloc_permanent, segkmem_free, heap_arena, 0,
1300 	    VMC_DUMPSAFE | VM_SLEEP);
1301 
1302 	sfmmu1_cache = kmem_cache_create("sfmmu1_cache", HME1BLK_SZ,
1303 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1304 	    sfmmu_hblkcache_destructor,
1305 	    NULL, (void *)HME1BLK_SZ,
1306 	    hat_memload1_arena, KMC_NOHASH);
1307 
1308 	pa_hment_cache = kmem_cache_create("pa_hment_cache", PAHME_SZ,
1309 	    0, NULL, NULL, NULL, NULL, static_arena, KMC_NOHASH);
1310 
1311 	ism_blk_cache = kmem_cache_create("ism_blk_cache",
1312 	    sizeof (ism_blk_t), ecache_alignsize, NULL, NULL,
1313 	    NULL, NULL, static_arena, KMC_NOHASH);
1314 
1315 	ism_ment_cache = kmem_cache_create("ism_ment_cache",
1316 	    sizeof (ism_ment_t), 0, NULL, NULL,
1317 	    NULL, NULL, NULL, 0);
1318 
1319 	/*
1320 	 * We grab the first hat for the kernel,
1321 	 */
1322 	AS_LOCK_ENTER(&kas, RW_WRITER);
1323 	kas.a_hat = hat_alloc(&kas);
1324 	AS_LOCK_EXIT(&kas);
1325 
1326 	/*
1327 	 * Initialize hblk_reserve.
1328 	 */
1329 	((struct hme_blk *)hblk_reserve)->hblk_nextpa =
1330 	    va_to_pa((caddr_t)hblk_reserve);
1331 
1332 #ifndef UTSB_PHYS
1333 	/*
1334 	 * Reserve some kernel virtual address space for the locked TTEs
1335 	 * that allow us to probe the TSB from TL>0.
1336 	 */
1337 	utsb_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1338 	    0, 0, NULL, NULL, VM_SLEEP);
1339 	utsb4m_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1340 	    0, 0, NULL, NULL, VM_SLEEP);
1341 #endif
1342 
1343 #ifdef VAC
1344 	/*
1345 	 * The big page VAC handling code assumes VAC
1346 	 * will not be bigger than the smallest big
1347 	 * page- which is 64K.
1348 	 */
1349 	if (TTEPAGES(TTE64K) < CACHE_NUM_COLOR) {
1350 		cmn_err(CE_PANIC, "VAC too big!");
1351 	}
1352 #endif
1353 
1354 	uhme_hash_pa = va_to_pa(uhme_hash);
1355 	khme_hash_pa = va_to_pa(khme_hash);
1356 
1357 	/*
1358 	 * Initialize relocation locks. kpr_suspendlock is held
1359 	 * at PIL_MAX to prevent interrupts from pinning the holder
1360 	 * of a suspended TTE which may access it leading to a
1361 	 * deadlock condition.
1362 	 */
1363 	mutex_init(&kpr_mutex, NULL, MUTEX_DEFAULT, NULL);
1364 	mutex_init(&kpr_suspendlock, NULL, MUTEX_SPIN, (void *)PIL_MAX);
1365 
1366 	/*
1367 	 * If Shared context support is disabled via /etc/system
1368 	 * set shctx_on to 0 here if it was set to 1 earlier in boot
1369 	 * sequence by cpu module initialization code.
1370 	 */
1371 	if (shctx_on && disable_shctx) {
1372 		shctx_on = 0;
1373 	}
1374 
1375 	if (shctx_on) {
1376 		srd_buckets = kmem_zalloc(SFMMU_MAX_SRD_BUCKETS *
1377 		    sizeof (srd_buckets[0]), KM_SLEEP);
1378 		for (i = 0; i < SFMMU_MAX_SRD_BUCKETS; i++) {
1379 			mutex_init(&srd_buckets[i].srdb_lock, NULL,
1380 			    MUTEX_DEFAULT, NULL);
1381 		}
1382 
1383 		srd_cache = kmem_cache_create("srd_cache", sizeof (sf_srd_t),
1384 		    0, sfmmu_srdcache_constructor, sfmmu_srdcache_destructor,
1385 		    NULL, NULL, NULL, 0);
1386 		region_cache = kmem_cache_create("region_cache",
1387 		    sizeof (sf_region_t), 0, sfmmu_rgncache_constructor,
1388 		    sfmmu_rgncache_destructor, NULL, NULL, NULL, 0);
1389 		scd_cache = kmem_cache_create("scd_cache", sizeof (sf_scd_t),
1390 		    0, sfmmu_scdcache_constructor,  sfmmu_scdcache_destructor,
1391 		    NULL, NULL, NULL, 0);
1392 	}
1393 
1394 	/*
1395 	 * Pre-allocate hrm_hashtab before enabling the collection of
1396 	 * refmod statistics.  Allocating on the fly would mean us
1397 	 * running the risk of suffering recursive mutex enters or
1398 	 * deadlocks.
1399 	 */
1400 	hrm_hashtab = kmem_zalloc(HRM_HASHSIZE * sizeof (struct hrmstat *),
1401 	    KM_SLEEP);
1402 
1403 	/* Allocate per-cpu pending freelist of hmeblks */
1404 	cpu_hme_pend = kmem_zalloc((NCPU * sizeof (cpu_hme_pend_t)) + 64,
1405 	    KM_SLEEP);
1406 	cpu_hme_pend = (cpu_hme_pend_t *)P2ROUNDUP(
1407 	    (uintptr_t)cpu_hme_pend, 64);
1408 
1409 	for (i = 0; i < NCPU; i++) {
1410 		mutex_init(&cpu_hme_pend[i].chp_mutex, NULL, MUTEX_DEFAULT,
1411 		    NULL);
1412 	}
1413 
1414 	if (cpu_hme_pend_thresh == 0) {
1415 		cpu_hme_pend_thresh = CPU_HME_PEND_THRESH;
1416 	}
1417 }
1418 
1419 /*
1420  * Initialize locking for the hat layer, called early during boot.
1421  */
1422 static void
1423 hat_lock_init()
1424 {
1425 	int i;
1426 
1427 	/*
1428 	 * initialize the array of mutexes protecting a page's mapping
1429 	 * list and p_nrm field.
1430 	 */
1431 	for (i = 0; i < MML_TABLE_SIZE; i++)
1432 		mutex_init(&mml_table[i].pad_mutex, NULL, MUTEX_DEFAULT, NULL);
1433 
1434 	if (kpm_enable) {
1435 		for (i = 0; i < kpmp_table_sz; i++) {
1436 			mutex_init(&kpmp_table[i].khl_mutex, NULL,
1437 			    MUTEX_DEFAULT, NULL);
1438 		}
1439 	}
1440 
1441 	/*
1442 	 * Initialize array of mutex locks that protects sfmmu fields and
1443 	 * TSB lists.
1444 	 */
1445 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
1446 		mutex_init(HATLOCK_MUTEXP(&hat_lock[i]), NULL, MUTEX_DEFAULT,
1447 		    NULL);
1448 }
1449 
1450 #define	SFMMU_KERNEL_MAXVA \
1451 	(kmem64_base ? (uintptr_t)kmem64_end : (SYSLIMIT))
1452 
1453 /*
1454  * Allocate a hat structure.
1455  * Called when an address space first uses a hat.
1456  */
1457 struct hat *
1458 hat_alloc(struct as *as)
1459 {
1460 	sfmmu_t *sfmmup;
1461 	int i;
1462 	uint64_t cnum;
1463 	extern uint_t get_color_start(struct as *);
1464 
1465 	ASSERT(AS_WRITE_HELD(as));
1466 	sfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
1467 	sfmmup->sfmmu_as = as;
1468 	sfmmup->sfmmu_flags = 0;
1469 	sfmmup->sfmmu_tteflags = 0;
1470 	sfmmup->sfmmu_rtteflags = 0;
1471 	LOCK_INIT_CLEAR(&sfmmup->sfmmu_ctx_lock);
1472 
1473 	if (as == &kas) {
1474 		ksfmmup = sfmmup;
1475 		sfmmup->sfmmu_cext = 0;
1476 		cnum = KCONTEXT;
1477 
1478 		sfmmup->sfmmu_clrstart = 0;
1479 		sfmmup->sfmmu_tsb = NULL;
1480 		/*
1481 		 * hat_kern_setup() will call sfmmu_init_ktsbinfo()
1482 		 * to setup tsb_info for ksfmmup.
1483 		 */
1484 	} else {
1485 
1486 		/*
1487 		 * Just set to invalid ctx. When it faults, it will
1488 		 * get a valid ctx. This would avoid the situation
1489 		 * where we get a ctx, but it gets stolen and then
1490 		 * we fault when we try to run and so have to get
1491 		 * another ctx.
1492 		 */
1493 		sfmmup->sfmmu_cext = 0;
1494 		cnum = INVALID_CONTEXT;
1495 
1496 		/* initialize original physical page coloring bin */
1497 		sfmmup->sfmmu_clrstart = get_color_start(as);
1498 #ifdef DEBUG
1499 		if (tsb_random_size) {
1500 			uint32_t randval = (uint32_t)gettick() >> 4;
1501 			int size = randval % (tsb_max_growsize + 1);
1502 
1503 			/* chose a random tsb size for stress testing */
1504 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb, size,
1505 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1506 		} else
1507 #endif /* DEBUG */
1508 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb,
1509 			    default_tsb_size,
1510 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1511 		sfmmup->sfmmu_flags = HAT_SWAPPED | HAT_ALLCTX_INVALID;
1512 		ASSERT(sfmmup->sfmmu_tsb != NULL);
1513 	}
1514 
1515 	ASSERT(max_mmu_ctxdoms > 0);
1516 	for (i = 0; i < max_mmu_ctxdoms; i++) {
1517 		sfmmup->sfmmu_ctxs[i].cnum = cnum;
1518 		sfmmup->sfmmu_ctxs[i].gnum = 0;
1519 	}
1520 
1521 	for (i = 0; i < max_mmu_page_sizes; i++) {
1522 		sfmmup->sfmmu_ttecnt[i] = 0;
1523 		sfmmup->sfmmu_scdrttecnt[i] = 0;
1524 		sfmmup->sfmmu_ismttecnt[i] = 0;
1525 		sfmmup->sfmmu_scdismttecnt[i] = 0;
1526 		sfmmup->sfmmu_pgsz[i] = TTE8K;
1527 	}
1528 	sfmmup->sfmmu_tsb0_4minflcnt = 0;
1529 	sfmmup->sfmmu_iblk = NULL;
1530 	sfmmup->sfmmu_ismhat = 0;
1531 	sfmmup->sfmmu_scdhat = 0;
1532 	sfmmup->sfmmu_ismblkpa = (uint64_t)-1;
1533 	if (sfmmup == ksfmmup) {
1534 		CPUSET_ALL(sfmmup->sfmmu_cpusran);
1535 	} else {
1536 		CPUSET_ZERO(sfmmup->sfmmu_cpusran);
1537 	}
1538 	sfmmup->sfmmu_free = 0;
1539 	sfmmup->sfmmu_rmstat = 0;
1540 	sfmmup->sfmmu_clrbin = sfmmup->sfmmu_clrstart;
1541 	cv_init(&sfmmup->sfmmu_tsb_cv, NULL, CV_DEFAULT, NULL);
1542 	sfmmup->sfmmu_srdp = NULL;
1543 	SF_RGNMAP_ZERO(sfmmup->sfmmu_region_map);
1544 	bzero(sfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
1545 	sfmmup->sfmmu_scdp = NULL;
1546 	sfmmup->sfmmu_scd_link.next = NULL;
1547 	sfmmup->sfmmu_scd_link.prev = NULL;
1548 	return (sfmmup);
1549 }
1550 
1551 /*
1552  * Create per-MMU context domain kstats for a given MMU ctx.
1553  */
1554 static void
1555 sfmmu_mmu_kstat_create(mmu_ctx_t *mmu_ctxp)
1556 {
1557 	mmu_ctx_stat_t	stat;
1558 	kstat_t		*mmu_kstat;
1559 
1560 	ASSERT(MUTEX_HELD(&cpu_lock));
1561 	ASSERT(mmu_ctxp->mmu_kstat == NULL);
1562 
1563 	mmu_kstat = kstat_create("unix", mmu_ctxp->mmu_idx, "mmu_ctx",
1564 	    "hat", KSTAT_TYPE_NAMED, MMU_CTX_NUM_STATS, KSTAT_FLAG_VIRTUAL);
1565 
1566 	if (mmu_kstat == NULL) {
1567 		cmn_err(CE_WARN, "kstat_create for MMU %d failed",
1568 		    mmu_ctxp->mmu_idx);
1569 	} else {
1570 		mmu_kstat->ks_data = mmu_ctxp->mmu_kstat_data;
1571 		for (stat = 0; stat < MMU_CTX_NUM_STATS; stat++)
1572 			kstat_named_init(&mmu_ctxp->mmu_kstat_data[stat],
1573 			    mmu_ctx_kstat_names[stat], KSTAT_DATA_INT64);
1574 		mmu_ctxp->mmu_kstat = mmu_kstat;
1575 		kstat_install(mmu_kstat);
1576 	}
1577 }
1578 
1579 /*
1580  * plat_cpuid_to_mmu_ctx_info() is a platform interface that returns MMU
1581  * context domain information for a given CPU. If a platform does not
1582  * specify that interface, then the function below is used instead to return
1583  * default information. The defaults are as follows:
1584  *
1585  *	- The number of MMU context IDs supported on any CPU in the
1586  *	  system is 8K.
1587  *	- There is one MMU context domain per CPU.
1588  */
1589 /*ARGSUSED*/
1590 static void
1591 sfmmu_cpuid_to_mmu_ctx_info(processorid_t cpuid, mmu_ctx_info_t *infop)
1592 {
1593 	infop->mmu_nctxs = nctxs;
1594 	infop->mmu_idx = cpu[cpuid]->cpu_seqid;
1595 }
1596 
1597 /*
1598  * Called during CPU initialization to set the MMU context-related information
1599  * for a CPU.
1600  *
1601  * cpu_lock serializes accesses to mmu_ctxs and mmu_saved_gnum.
1602  */
1603 void
1604 sfmmu_cpu_init(cpu_t *cp)
1605 {
1606 	mmu_ctx_info_t	info;
1607 	mmu_ctx_t	*mmu_ctxp;
1608 
1609 	ASSERT(MUTEX_HELD(&cpu_lock));
1610 
1611 	if (&plat_cpuid_to_mmu_ctx_info == NULL)
1612 		sfmmu_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1613 	else
1614 		plat_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1615 
1616 	ASSERT(info.mmu_idx < max_mmu_ctxdoms);
1617 
1618 	if ((mmu_ctxp = mmu_ctxs_tbl[info.mmu_idx]) == NULL) {
1619 		/* Each mmu_ctx is cacheline aligned. */
1620 		mmu_ctxp = kmem_cache_alloc(mmuctxdom_cache, KM_SLEEP);
1621 		bzero(mmu_ctxp, sizeof (mmu_ctx_t));
1622 
1623 		mutex_init(&mmu_ctxp->mmu_lock, NULL, MUTEX_SPIN,
1624 		    (void *)ipltospl(DISP_LEVEL));
1625 		mmu_ctxp->mmu_idx = info.mmu_idx;
1626 		mmu_ctxp->mmu_nctxs = info.mmu_nctxs;
1627 		/*
1628 		 * Globally for lifetime of a system,
1629 		 * gnum must always increase.
1630 		 * mmu_saved_gnum is protected by the cpu_lock.
1631 		 */
1632 		mmu_ctxp->mmu_gnum = mmu_saved_gnum + 1;
1633 		mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
1634 
1635 		sfmmu_mmu_kstat_create(mmu_ctxp);
1636 
1637 		mmu_ctxs_tbl[info.mmu_idx] = mmu_ctxp;
1638 	} else {
1639 		ASSERT(mmu_ctxp->mmu_idx == info.mmu_idx);
1640 		ASSERT(mmu_ctxp->mmu_nctxs <= info.mmu_nctxs);
1641 	}
1642 
1643 	/*
1644 	 * The mmu_lock is acquired here to prevent races with
1645 	 * the wrap-around code.
1646 	 */
1647 	mutex_enter(&mmu_ctxp->mmu_lock);
1648 
1649 
1650 	mmu_ctxp->mmu_ncpus++;
1651 	CPUSET_ADD(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1652 	CPU_MMU_IDX(cp) = info.mmu_idx;
1653 	CPU_MMU_CTXP(cp) = mmu_ctxp;
1654 
1655 	mutex_exit(&mmu_ctxp->mmu_lock);
1656 }
1657 
1658 static void
1659 sfmmu_ctxdom_free(mmu_ctx_t *mmu_ctxp)
1660 {
1661 	ASSERT(MUTEX_HELD(&cpu_lock));
1662 	ASSERT(!MUTEX_HELD(&mmu_ctxp->mmu_lock));
1663 
1664 	mutex_destroy(&mmu_ctxp->mmu_lock);
1665 
1666 	if (mmu_ctxp->mmu_kstat)
1667 		kstat_delete(mmu_ctxp->mmu_kstat);
1668 
1669 	/* mmu_saved_gnum is protected by the cpu_lock. */
1670 	if (mmu_saved_gnum < mmu_ctxp->mmu_gnum)
1671 		mmu_saved_gnum = mmu_ctxp->mmu_gnum;
1672 
1673 	kmem_cache_free(mmuctxdom_cache, mmu_ctxp);
1674 }
1675 
1676 /*
1677  * Called to perform MMU context-related cleanup for a CPU.
1678  */
1679 void
1680 sfmmu_cpu_cleanup(cpu_t *cp)
1681 {
1682 	mmu_ctx_t	*mmu_ctxp;
1683 
1684 	ASSERT(MUTEX_HELD(&cpu_lock));
1685 
1686 	mmu_ctxp = CPU_MMU_CTXP(cp);
1687 	ASSERT(mmu_ctxp != NULL);
1688 
1689 	/*
1690 	 * The mmu_lock is acquired here to prevent races with
1691 	 * the wrap-around code.
1692 	 */
1693 	mutex_enter(&mmu_ctxp->mmu_lock);
1694 
1695 	CPU_MMU_CTXP(cp) = NULL;
1696 
1697 	CPUSET_DEL(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1698 	if (--mmu_ctxp->mmu_ncpus == 0) {
1699 		mmu_ctxs_tbl[mmu_ctxp->mmu_idx] = NULL;
1700 		mutex_exit(&mmu_ctxp->mmu_lock);
1701 		sfmmu_ctxdom_free(mmu_ctxp);
1702 		return;
1703 	}
1704 
1705 	mutex_exit(&mmu_ctxp->mmu_lock);
1706 }
1707 
1708 uint_t
1709 sfmmu_ctxdom_nctxs(int idx)
1710 {
1711 	return (mmu_ctxs_tbl[idx]->mmu_nctxs);
1712 }
1713 
1714 #ifdef sun4v
1715 /*
1716  * sfmmu_ctxdoms_* is an interface provided to help keep context domains
1717  * consistant after suspend/resume on system that can resume on a different
1718  * hardware than it was suspended.
1719  *
1720  * sfmmu_ctxdom_lock(void) locks all context domains and prevents new contexts
1721  * from being allocated.  It acquires all hat_locks, which blocks most access to
1722  * context data, except for a few cases that are handled separately or are
1723  * harmless.  It wraps each domain to increment gnum and invalidate on-CPU
1724  * contexts, and forces cnum to its max.  As a result of this call all user
1725  * threads that are running on CPUs trap and try to perform wrap around but
1726  * can't because hat_locks are taken.  Threads that were not on CPUs but started
1727  * by scheduler go to sfmmu_alloc_ctx() to aquire context without checking
1728  * hat_lock, but fail, because cnum == nctxs, and therefore also trap and block
1729  * on hat_lock trying to wrap.  sfmmu_ctxdom_lock() must be called before CPUs
1730  * are paused, else it could deadlock acquiring locks held by paused CPUs.
1731  *
1732  * sfmmu_ctxdoms_remove() removes context domains from every CPUs and records
1733  * the CPUs that had them.  It must be called after CPUs have been paused. This
1734  * ensures that no threads are in sfmmu_alloc_ctx() accessing domain data,
1735  * because pause_cpus sends a mondo interrupt to every CPU, and sfmmu_alloc_ctx
1736  * runs with interrupts disabled.  When CPUs are later resumed, they may enter
1737  * sfmmu_alloc_ctx, but it will check for CPU_MMU_CTXP = NULL and immediately
1738  * return failure.  Or, they will be blocked trying to acquire hat_lock. Thus
1739  * after sfmmu_ctxdoms_remove returns, we are guaranteed that no one is
1740  * accessing the old context domains.
1741  *
1742  * sfmmu_ctxdoms_update(void) frees space used by old context domains and
1743  * allocates new context domains based on hardware layout.  It initializes
1744  * every CPU that had context domain before migration to have one again.
1745  * sfmmu_ctxdoms_update must be called after CPUs are resumed, else it
1746  * could deadlock acquiring locks held by paused CPUs.
1747  *
1748  * sfmmu_ctxdoms_unlock(void) releases all hat_locks after which user threads
1749  * acquire new context ids and continue execution.
1750  *
1751  * Therefore functions should be called in the following order:
1752  *       suspend_routine()
1753  *		sfmmu_ctxdom_lock()
1754  *		pause_cpus()
1755  *		suspend()
1756  *			if (suspend failed)
1757  *				sfmmu_ctxdom_unlock()
1758  *		...
1759  *		sfmmu_ctxdom_remove()
1760  *		resume_cpus()
1761  *		sfmmu_ctxdom_update()
1762  *		sfmmu_ctxdom_unlock()
1763  */
1764 static cpuset_t sfmmu_ctxdoms_pset;
1765 
1766 void
1767 sfmmu_ctxdoms_remove()
1768 {
1769 	processorid_t	id;
1770 	cpu_t		*cp;
1771 
1772 	/*
1773 	 * Record the CPUs that have domains in sfmmu_ctxdoms_pset, so they can
1774 	 * be restored post-migration. A CPU may be powered off and not have a
1775 	 * domain, for example.
1776 	 */
1777 	CPUSET_ZERO(sfmmu_ctxdoms_pset);
1778 
1779 	for (id = 0; id < NCPU; id++) {
1780 		if ((cp = cpu[id]) != NULL && CPU_MMU_CTXP(cp) != NULL) {
1781 			CPUSET_ADD(sfmmu_ctxdoms_pset, id);
1782 			CPU_MMU_CTXP(cp) = NULL;
1783 		}
1784 	}
1785 }
1786 
1787 void
1788 sfmmu_ctxdoms_lock(void)
1789 {
1790 	int		idx;
1791 	mmu_ctx_t	*mmu_ctxp;
1792 
1793 	sfmmu_hat_lock_all();
1794 
1795 	/*
1796 	 * At this point, no thread can be in sfmmu_ctx_wrap_around, because
1797 	 * hat_lock is always taken before calling it.
1798 	 *
1799 	 * For each domain, set mmu_cnum to max so no more contexts can be
1800 	 * allocated, and wrap to flush on-CPU contexts and force threads to
1801 	 * acquire a new context when we later drop hat_lock after migration.
1802 	 * Setting mmu_cnum may race with sfmmu_alloc_ctx which also sets cnum,
1803 	 * but the latter uses CAS and will miscompare and not overwrite it.
1804 	 */
1805 	kpreempt_disable(); /* required by sfmmu_ctx_wrap_around */
1806 	for (idx = 0; idx < max_mmu_ctxdoms; idx++) {
1807 		if ((mmu_ctxp = mmu_ctxs_tbl[idx]) != NULL) {
1808 			mutex_enter(&mmu_ctxp->mmu_lock);
1809 			mmu_ctxp->mmu_cnum = mmu_ctxp->mmu_nctxs;
1810 			/* make sure updated cnum visible */
1811 			membar_enter();
1812 			mutex_exit(&mmu_ctxp->mmu_lock);
1813 			sfmmu_ctx_wrap_around(mmu_ctxp, B_FALSE);
1814 		}
1815 	}
1816 	kpreempt_enable();
1817 }
1818 
1819 void
1820 sfmmu_ctxdoms_unlock(void)
1821 {
1822 	sfmmu_hat_unlock_all();
1823 }
1824 
1825 void
1826 sfmmu_ctxdoms_update(void)
1827 {
1828 	processorid_t	id;
1829 	cpu_t		*cp;
1830 	uint_t		idx;
1831 	mmu_ctx_t	*mmu_ctxp;
1832 
1833 	/*
1834 	 * Free all context domains.  As side effect, this increases
1835 	 * mmu_saved_gnum to the maximum gnum over all domains, which is used to
1836 	 * init gnum in the new domains, which therefore will be larger than the
1837 	 * sfmmu gnum for any process, guaranteeing that every process will see
1838 	 * a new generation and allocate a new context regardless of what new
1839 	 * domain it runs in.
1840 	 */
1841 	mutex_enter(&cpu_lock);
1842 
1843 	for (idx = 0; idx < max_mmu_ctxdoms; idx++) {
1844 		if (mmu_ctxs_tbl[idx] != NULL) {
1845 			mmu_ctxp = mmu_ctxs_tbl[idx];
1846 			mmu_ctxs_tbl[idx] = NULL;
1847 			sfmmu_ctxdom_free(mmu_ctxp);
1848 		}
1849 	}
1850 
1851 	for (id = 0; id < NCPU; id++) {
1852 		if (CPU_IN_SET(sfmmu_ctxdoms_pset, id) &&
1853 		    (cp = cpu[id]) != NULL)
1854 			sfmmu_cpu_init(cp);
1855 	}
1856 	mutex_exit(&cpu_lock);
1857 }
1858 #endif
1859 
1860 /*
1861  * Hat_setup, makes an address space context the current active one.
1862  * In sfmmu this translates to setting the secondary context with the
1863  * corresponding context.
1864  */
1865 void
1866 hat_setup(struct hat *sfmmup, int allocflag)
1867 {
1868 	hatlock_t *hatlockp;
1869 
1870 	/* Init needs some special treatment. */
1871 	if (allocflag == HAT_INIT) {
1872 		/*
1873 		 * Make sure that we have
1874 		 * 1. a TSB
1875 		 * 2. a valid ctx that doesn't get stolen after this point.
1876 		 */
1877 		hatlockp = sfmmu_hat_enter(sfmmup);
1878 
1879 		/*
1880 		 * Swap in the TSB.  hat_init() allocates tsbinfos without
1881 		 * TSBs, but we need one for init, since the kernel does some
1882 		 * special things to set up its stack and needs the TSB to
1883 		 * resolve page faults.
1884 		 */
1885 		sfmmu_tsb_swapin(sfmmup, hatlockp);
1886 
1887 		sfmmu_get_ctx(sfmmup);
1888 
1889 		sfmmu_hat_exit(hatlockp);
1890 	} else {
1891 		ASSERT(allocflag == HAT_ALLOC);
1892 
1893 		hatlockp = sfmmu_hat_enter(sfmmup);
1894 		kpreempt_disable();
1895 
1896 		CPUSET_ADD(sfmmup->sfmmu_cpusran, CPU->cpu_id);
1897 		/*
1898 		 * sfmmu_setctx_sec takes <pgsz|cnum> as a parameter,
1899 		 * pagesize bits don't matter in this case since we are passing
1900 		 * INVALID_CONTEXT to it.
1901 		 * Compatibility Note: hw takes care of MMU_SCONTEXT1
1902 		 */
1903 		sfmmu_setctx_sec(INVALID_CONTEXT);
1904 		sfmmu_clear_utsbinfo();
1905 
1906 		kpreempt_enable();
1907 		sfmmu_hat_exit(hatlockp);
1908 	}
1909 }
1910 
1911 /*
1912  * Free all the translation resources for the specified address space.
1913  * Called from as_free when an address space is being destroyed.
1914  */
1915 void
1916 hat_free_start(struct hat *sfmmup)
1917 {
1918 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as));
1919 	ASSERT(sfmmup != ksfmmup);
1920 
1921 	sfmmup->sfmmu_free = 1;
1922 	if (sfmmup->sfmmu_scdp != NULL) {
1923 		sfmmu_leave_scd(sfmmup, 0);
1924 	}
1925 
1926 	ASSERT(sfmmup->sfmmu_scdp == NULL);
1927 }
1928 
1929 void
1930 hat_free_end(struct hat *sfmmup)
1931 {
1932 	int i;
1933 
1934 	ASSERT(sfmmup->sfmmu_free == 1);
1935 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
1936 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
1937 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
1938 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
1939 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
1940 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
1941 
1942 	if (sfmmup->sfmmu_rmstat) {
1943 		hat_freestat(sfmmup->sfmmu_as, NULL);
1944 	}
1945 
1946 	while (sfmmup->sfmmu_tsb != NULL) {
1947 		struct tsb_info *next = sfmmup->sfmmu_tsb->tsb_next;
1948 		sfmmu_tsbinfo_free(sfmmup->sfmmu_tsb);
1949 		sfmmup->sfmmu_tsb = next;
1950 	}
1951 
1952 	if (sfmmup->sfmmu_srdp != NULL) {
1953 		sfmmu_leave_srd(sfmmup);
1954 		ASSERT(sfmmup->sfmmu_srdp == NULL);
1955 		for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1956 			if (sfmmup->sfmmu_hmeregion_links[i] != NULL) {
1957 				kmem_free(sfmmup->sfmmu_hmeregion_links[i],
1958 				    SFMMU_L2_HMERLINKS_SIZE);
1959 				sfmmup->sfmmu_hmeregion_links[i] = NULL;
1960 			}
1961 		}
1962 	}
1963 	sfmmu_free_sfmmu(sfmmup);
1964 
1965 #ifdef DEBUG
1966 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1967 		ASSERT(sfmmup->sfmmu_hmeregion_links[i] == NULL);
1968 	}
1969 #endif
1970 
1971 	kmem_cache_free(sfmmuid_cache, sfmmup);
1972 }
1973 
1974 /*
1975  * Set up any translation structures, for the specified address space,
1976  * that are needed or preferred when the process is being swapped in.
1977  */
1978 /* ARGSUSED */
1979 void
1980 hat_swapin(struct hat *hat)
1981 {
1982 }
1983 
1984 /*
1985  * Free all of the translation resources, for the specified address space,
1986  * that can be freed while the process is swapped out. Called from as_swapout.
1987  * Also, free up the ctx that this process was using.
1988  */
1989 void
1990 hat_swapout(struct hat *sfmmup)
1991 {
1992 	struct hmehash_bucket *hmebp;
1993 	struct hme_blk *hmeblkp;
1994 	struct hme_blk *pr_hblk = NULL;
1995 	struct hme_blk *nx_hblk;
1996 	int i;
1997 	struct hme_blk *list = NULL;
1998 	hatlock_t *hatlockp;
1999 	struct tsb_info *tsbinfop;
2000 	struct free_tsb {
2001 		struct free_tsb *next;
2002 		struct tsb_info *tsbinfop;
2003 	};			/* free list of TSBs */
2004 	struct free_tsb *freelist, *last, *next;
2005 
2006 	SFMMU_STAT(sf_swapout);
2007 
2008 	/*
2009 	 * There is no way to go from an as to all its translations in sfmmu.
2010 	 * Here is one of the times when we take the big hit and traverse
2011 	 * the hash looking for hme_blks to free up.  Not only do we free up
2012 	 * this as hme_blks but all those that are free.  We are obviously
2013 	 * swapping because we need memory so let's free up as much
2014 	 * as we can.
2015 	 *
2016 	 * Note that we don't flush TLB/TSB here -- it's not necessary
2017 	 * because:
2018 	 *  1) we free the ctx we're using and throw away the TSB(s);
2019 	 *  2) processes aren't runnable while being swapped out.
2020 	 */
2021 	ASSERT(sfmmup != KHATID);
2022 	for (i = 0; i <= UHMEHASH_SZ; i++) {
2023 		hmebp = &uhme_hash[i];
2024 		SFMMU_HASH_LOCK(hmebp);
2025 		hmeblkp = hmebp->hmeblkp;
2026 		pr_hblk = NULL;
2027 		while (hmeblkp) {
2028 
2029 			if ((hmeblkp->hblk_tag.htag_id == sfmmup) &&
2030 			    !hmeblkp->hblk_shw_bit && !hmeblkp->hblk_lckcnt) {
2031 				ASSERT(!hmeblkp->hblk_shared);
2032 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
2033 				    (caddr_t)get_hblk_base(hmeblkp),
2034 				    get_hblk_endaddr(hmeblkp),
2035 				    NULL, HAT_UNLOAD);
2036 			}
2037 			nx_hblk = hmeblkp->hblk_next;
2038 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
2039 				ASSERT(!hmeblkp->hblk_lckcnt);
2040 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
2041 				    &list, 0);
2042 			} else {
2043 				pr_hblk = hmeblkp;
2044 			}
2045 			hmeblkp = nx_hblk;
2046 		}
2047 		SFMMU_HASH_UNLOCK(hmebp);
2048 	}
2049 
2050 	sfmmu_hblks_list_purge(&list, 0);
2051 
2052 	/*
2053 	 * Now free up the ctx so that others can reuse it.
2054 	 */
2055 	hatlockp = sfmmu_hat_enter(sfmmup);
2056 
2057 	sfmmu_invalidate_ctx(sfmmup);
2058 
2059 	/*
2060 	 * Free TSBs, but not tsbinfos, and set SWAPPED flag.
2061 	 * If TSBs were never swapped in, just return.
2062 	 * This implies that we don't support partial swapping
2063 	 * of TSBs -- either all are swapped out, or none are.
2064 	 *
2065 	 * We must hold the HAT lock here to prevent racing with another
2066 	 * thread trying to unmap TTEs from the TSB or running the post-
2067 	 * relocator after relocating the TSB's memory.  Unfortunately, we
2068 	 * can't free memory while holding the HAT lock or we could
2069 	 * deadlock, so we build a list of TSBs to be freed after marking
2070 	 * the tsbinfos as swapped out and free them after dropping the
2071 	 * lock.
2072 	 */
2073 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
2074 		sfmmu_hat_exit(hatlockp);
2075 		return;
2076 	}
2077 
2078 	SFMMU_FLAGS_SET(sfmmup, HAT_SWAPPED);
2079 	last = freelist = NULL;
2080 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
2081 	    tsbinfop = tsbinfop->tsb_next) {
2082 		ASSERT((tsbinfop->tsb_flags & TSB_SWAPPED) == 0);
2083 
2084 		/*
2085 		 * Cast the TSB into a struct free_tsb and put it on the free
2086 		 * list.
2087 		 */
2088 		if (freelist == NULL) {
2089 			last = freelist = (struct free_tsb *)tsbinfop->tsb_va;
2090 		} else {
2091 			last->next = (struct free_tsb *)tsbinfop->tsb_va;
2092 			last = last->next;
2093 		}
2094 		last->next = NULL;
2095 		last->tsbinfop = tsbinfop;
2096 		tsbinfop->tsb_flags |= TSB_SWAPPED;
2097 		/*
2098 		 * Zero out the TTE to clear the valid bit.
2099 		 * Note we can't use a value like 0xbad because we want to
2100 		 * ensure diagnostic bits are NEVER set on TTEs that might
2101 		 * be loaded.  The intent is to catch any invalid access
2102 		 * to the swapped TSB, such as a thread running with a valid
2103 		 * context without first calling sfmmu_tsb_swapin() to
2104 		 * allocate TSB memory.
2105 		 */
2106 		tsbinfop->tsb_tte.ll = 0;
2107 	}
2108 
2109 	/* Now we can drop the lock and free the TSB memory. */
2110 	sfmmu_hat_exit(hatlockp);
2111 	for (; freelist != NULL; freelist = next) {
2112 		next = freelist->next;
2113 		sfmmu_tsb_free(freelist->tsbinfop);
2114 	}
2115 }
2116 
2117 /*
2118  * Duplicate the translations of an as into another newas
2119  */
2120 /* ARGSUSED */
2121 int
2122 hat_dup(struct hat *hat, struct hat *newhat, caddr_t addr, size_t len,
2123     uint_t flag)
2124 {
2125 	sf_srd_t *srdp;
2126 	sf_scd_t *scdp;
2127 	int i;
2128 	extern uint_t get_color_start(struct as *);
2129 
2130 	ASSERT((flag == 0) || (flag == HAT_DUP_ALL) || (flag == HAT_DUP_COW) ||
2131 	    (flag == HAT_DUP_SRD));
2132 	ASSERT(hat != ksfmmup);
2133 	ASSERT(newhat != ksfmmup);
2134 	ASSERT(flag != HAT_DUP_ALL || hat->sfmmu_srdp == newhat->sfmmu_srdp);
2135 
2136 	if (flag == HAT_DUP_COW) {
2137 		panic("hat_dup: HAT_DUP_COW not supported");
2138 	}
2139 
2140 	if (flag == HAT_DUP_SRD && ((srdp = hat->sfmmu_srdp) != NULL)) {
2141 		ASSERT(srdp->srd_evp != NULL);
2142 		VN_HOLD(srdp->srd_evp);
2143 		ASSERT(srdp->srd_refcnt > 0);
2144 		newhat->sfmmu_srdp = srdp;
2145 		atomic_inc_32((volatile uint_t *)&srdp->srd_refcnt);
2146 	}
2147 
2148 	/*
2149 	 * HAT_DUP_ALL flag is used after as duplication is done.
2150 	 */
2151 	if (flag == HAT_DUP_ALL && ((srdp = newhat->sfmmu_srdp) != NULL)) {
2152 		ASSERT(newhat->sfmmu_srdp->srd_refcnt >= 2);
2153 		newhat->sfmmu_rtteflags = hat->sfmmu_rtteflags;
2154 		if (hat->sfmmu_flags & HAT_4MTEXT_FLAG) {
2155 			newhat->sfmmu_flags |= HAT_4MTEXT_FLAG;
2156 		}
2157 
2158 		/* check if need to join scd */
2159 		if ((scdp = hat->sfmmu_scdp) != NULL &&
2160 		    newhat->sfmmu_scdp != scdp) {
2161 			int ret;
2162 			SF_RGNMAP_IS_SUBSET(&newhat->sfmmu_region_map,
2163 			    &scdp->scd_region_map, ret);
2164 			ASSERT(ret);
2165 			sfmmu_join_scd(scdp, newhat);
2166 			ASSERT(newhat->sfmmu_scdp == scdp &&
2167 			    scdp->scd_refcnt >= 2);
2168 			for (i = 0; i < max_mmu_page_sizes; i++) {
2169 				newhat->sfmmu_ismttecnt[i] =
2170 				    hat->sfmmu_ismttecnt[i];
2171 				newhat->sfmmu_scdismttecnt[i] =
2172 				    hat->sfmmu_scdismttecnt[i];
2173 			}
2174 		}
2175 
2176 		sfmmu_check_page_sizes(newhat, 1);
2177 	}
2178 
2179 	if (flag == HAT_DUP_ALL && consistent_coloring == 0 &&
2180 	    update_proc_pgcolorbase_after_fork != 0) {
2181 		hat->sfmmu_clrbin = get_color_start(hat->sfmmu_as);
2182 	}
2183 	return (0);
2184 }
2185 
2186 void
2187 hat_memload(struct hat *hat, caddr_t addr, struct page *pp,
2188     uint_t attr, uint_t flags)
2189 {
2190 	hat_do_memload(hat, addr, pp, attr, flags,
2191 	    SFMMU_INVALID_SHMERID);
2192 }
2193 
2194 void
2195 hat_memload_region(struct hat *hat, caddr_t addr, struct page *pp,
2196     uint_t attr, uint_t flags, hat_region_cookie_t rcookie)
2197 {
2198 	uint_t rid;
2199 	if (rcookie == HAT_INVALID_REGION_COOKIE) {
2200 		hat_do_memload(hat, addr, pp, attr, flags,
2201 		    SFMMU_INVALID_SHMERID);
2202 		return;
2203 	}
2204 	rid = (uint_t)((uint64_t)rcookie);
2205 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2206 	hat_do_memload(hat, addr, pp, attr, flags, rid);
2207 }
2208 
2209 /*
2210  * Set up addr to map to page pp with protection prot.
2211  * As an optimization we also load the TSB with the
2212  * corresponding tte but it is no big deal if  the tte gets kicked out.
2213  */
2214 static void
2215 hat_do_memload(struct hat *hat, caddr_t addr, struct page *pp,
2216     uint_t attr, uint_t flags, uint_t rid)
2217 {
2218 	tte_t tte;
2219 
2220 
2221 	ASSERT(hat != NULL);
2222 	ASSERT(PAGE_LOCKED(pp));
2223 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2224 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2225 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2226 	SFMMU_VALIDATE_HMERID(hat, rid, addr, MMU_PAGESIZE);
2227 
2228 	if (PP_ISFREE(pp)) {
2229 		panic("hat_memload: loading a mapping to free page %p",
2230 		    (void *)pp);
2231 	}
2232 
2233 	ASSERT((hat == ksfmmup) || AS_LOCK_HELD(hat->sfmmu_as));
2234 
2235 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2236 		cmn_err(CE_NOTE, "hat_memload: unsupported flags %d",
2237 		    flags & ~SFMMU_LOAD_ALLFLAG);
2238 
2239 	if (hat->sfmmu_rmstat)
2240 		hat_resvstat(MMU_PAGESIZE, hat->sfmmu_as, addr);
2241 
2242 #if defined(SF_ERRATA_57)
2243 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2244 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2245 	    !(flags & HAT_LOAD_SHARE)) {
2246 		cmn_err(CE_WARN, "hat_memload: illegal attempt to make user "
2247 		    " page executable");
2248 		attr &= ~PROT_EXEC;
2249 	}
2250 #endif
2251 
2252 	sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2253 	(void) sfmmu_tteload_array(hat, &tte, addr, &pp, flags, rid);
2254 
2255 	/*
2256 	 * Check TSB and TLB page sizes.
2257 	 */
2258 	if ((flags & HAT_LOAD_SHARE) == 0) {
2259 		sfmmu_check_page_sizes(hat, 1);
2260 	}
2261 }
2262 
2263 /*
2264  * hat_devload can be called to map real memory (e.g.
2265  * /dev/kmem) and even though hat_devload will determine pf is
2266  * for memory, it will be unable to get a shared lock on the
2267  * page (because someone else has it exclusively) and will
2268  * pass dp = NULL.  If tteload doesn't get a non-NULL
2269  * page pointer it can't cache memory.
2270  */
2271 void
2272 hat_devload(struct hat *hat, caddr_t addr, size_t len, pfn_t pfn,
2273     uint_t attr, int flags)
2274 {
2275 	tte_t tte;
2276 	struct page *pp = NULL;
2277 	int use_lgpg = 0;
2278 
2279 	ASSERT(hat != NULL);
2280 
2281 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2282 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2283 	ASSERT((hat == ksfmmup) || AS_LOCK_HELD(hat->sfmmu_as));
2284 	if (len == 0)
2285 		panic("hat_devload: zero len");
2286 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2287 		cmn_err(CE_NOTE, "hat_devload: unsupported flags %d",
2288 		    flags & ~SFMMU_LOAD_ALLFLAG);
2289 
2290 #if defined(SF_ERRATA_57)
2291 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2292 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2293 	    !(flags & HAT_LOAD_SHARE)) {
2294 		cmn_err(CE_WARN, "hat_devload: illegal attempt to make user "
2295 		    " page executable");
2296 		attr &= ~PROT_EXEC;
2297 	}
2298 #endif
2299 
2300 	/*
2301 	 * If it's a memory page find its pp
2302 	 */
2303 	if (!(flags & HAT_LOAD_NOCONSIST) && pf_is_memory(pfn)) {
2304 		pp = page_numtopp_nolock(pfn);
2305 		if (pp == NULL) {
2306 			flags |= HAT_LOAD_NOCONSIST;
2307 		} else {
2308 			if (PP_ISFREE(pp)) {
2309 				panic("hat_memload: loading "
2310 				    "a mapping to free page %p",
2311 				    (void *)pp);
2312 			}
2313 			if (!PAGE_LOCKED(pp) && !PP_ISNORELOC(pp)) {
2314 				panic("hat_memload: loading a mapping "
2315 				    "to unlocked relocatable page %p",
2316 				    (void *)pp);
2317 			}
2318 			ASSERT(len == MMU_PAGESIZE);
2319 		}
2320 	}
2321 
2322 	if (hat->sfmmu_rmstat)
2323 		hat_resvstat(len, hat->sfmmu_as, addr);
2324 
2325 	if (flags & HAT_LOAD_NOCONSIST) {
2326 		attr |= SFMMU_UNCACHEVTTE;
2327 		use_lgpg = 1;
2328 	}
2329 	if (!pf_is_memory(pfn)) {
2330 		attr |= SFMMU_UNCACHEPTTE | HAT_NOSYNC;
2331 		use_lgpg = 1;
2332 		switch (attr & HAT_ORDER_MASK) {
2333 			case HAT_STRICTORDER:
2334 			case HAT_UNORDERED_OK:
2335 				/*
2336 				 * we set the side effect bit for all non
2337 				 * memory mappings unless merging is ok
2338 				 */
2339 				attr |= SFMMU_SIDEFFECT;
2340 				break;
2341 			case HAT_MERGING_OK:
2342 			case HAT_LOADCACHING_OK:
2343 			case HAT_STORECACHING_OK:
2344 				break;
2345 			default:
2346 				panic("hat_devload: bad attr");
2347 				break;
2348 		}
2349 	}
2350 	while (len) {
2351 		if (!use_lgpg) {
2352 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2353 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2354 			    flags, SFMMU_INVALID_SHMERID);
2355 			len -= MMU_PAGESIZE;
2356 			addr += MMU_PAGESIZE;
2357 			pfn++;
2358 			continue;
2359 		}
2360 		/*
2361 		 *  try to use large pages, check va/pa alignments
2362 		 *  Note that 32M/256M page sizes are not (yet) supported.
2363 		 */
2364 		if ((len >= MMU_PAGESIZE4M) &&
2365 		    !((uintptr_t)addr & MMU_PAGEOFFSET4M) &&
2366 		    !(disable_large_pages & (1 << TTE4M)) &&
2367 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET4M)) {
2368 			sfmmu_memtte(&tte, pfn, attr, TTE4M);
2369 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2370 			    flags, SFMMU_INVALID_SHMERID);
2371 			len -= MMU_PAGESIZE4M;
2372 			addr += MMU_PAGESIZE4M;
2373 			pfn += MMU_PAGESIZE4M / MMU_PAGESIZE;
2374 		} else if ((len >= MMU_PAGESIZE512K) &&
2375 		    !((uintptr_t)addr & MMU_PAGEOFFSET512K) &&
2376 		    !(disable_large_pages & (1 << TTE512K)) &&
2377 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET512K)) {
2378 			sfmmu_memtte(&tte, pfn, attr, TTE512K);
2379 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2380 			    flags, SFMMU_INVALID_SHMERID);
2381 			len -= MMU_PAGESIZE512K;
2382 			addr += MMU_PAGESIZE512K;
2383 			pfn += MMU_PAGESIZE512K / MMU_PAGESIZE;
2384 		} else if ((len >= MMU_PAGESIZE64K) &&
2385 		    !((uintptr_t)addr & MMU_PAGEOFFSET64K) &&
2386 		    !(disable_large_pages & (1 << TTE64K)) &&
2387 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET64K)) {
2388 			sfmmu_memtte(&tte, pfn, attr, TTE64K);
2389 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2390 			    flags, SFMMU_INVALID_SHMERID);
2391 			len -= MMU_PAGESIZE64K;
2392 			addr += MMU_PAGESIZE64K;
2393 			pfn += MMU_PAGESIZE64K / MMU_PAGESIZE;
2394 		} else {
2395 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2396 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2397 			    flags, SFMMU_INVALID_SHMERID);
2398 			len -= MMU_PAGESIZE;
2399 			addr += MMU_PAGESIZE;
2400 			pfn++;
2401 		}
2402 	}
2403 
2404 	/*
2405 	 * Check TSB and TLB page sizes.
2406 	 */
2407 	if ((flags & HAT_LOAD_SHARE) == 0) {
2408 		sfmmu_check_page_sizes(hat, 1);
2409 	}
2410 }
2411 
2412 void
2413 hat_memload_array(struct hat *hat, caddr_t addr, size_t len,
2414     struct page **pps, uint_t attr, uint_t flags)
2415 {
2416 	hat_do_memload_array(hat, addr, len, pps, attr, flags,
2417 	    SFMMU_INVALID_SHMERID);
2418 }
2419 
2420 void
2421 hat_memload_array_region(struct hat *hat, caddr_t addr, size_t len,
2422     struct page **pps, uint_t attr, uint_t flags,
2423     hat_region_cookie_t rcookie)
2424 {
2425 	uint_t rid;
2426 	if (rcookie == HAT_INVALID_REGION_COOKIE) {
2427 		hat_do_memload_array(hat, addr, len, pps, attr, flags,
2428 		    SFMMU_INVALID_SHMERID);
2429 		return;
2430 	}
2431 	rid = (uint_t)((uint64_t)rcookie);
2432 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2433 	hat_do_memload_array(hat, addr, len, pps, attr, flags, rid);
2434 }
2435 
2436 /*
2437  * Map the largest extend possible out of the page array. The array may NOT
2438  * be in order.  The largest possible mapping a page can have
2439  * is specified in the p_szc field.  The p_szc field
2440  * cannot change as long as there any mappings (large or small)
2441  * to any of the pages that make up the large page. (ie. any
2442  * promotion/demotion of page size is not up to the hat but up to
2443  * the page free list manager).  The array
2444  * should consist of properly aligned contigous pages that are
2445  * part of a big page for a large mapping to be created.
2446  */
2447 static void
2448 hat_do_memload_array(struct hat *hat, caddr_t addr, size_t len,
2449     struct page **pps, uint_t attr, uint_t flags, uint_t rid)
2450 {
2451 	int  ttesz;
2452 	size_t mapsz;
2453 	pgcnt_t	numpg, npgs;
2454 	tte_t tte;
2455 	page_t *pp;
2456 	uint_t large_pages_disable;
2457 
2458 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2459 	SFMMU_VALIDATE_HMERID(hat, rid, addr, len);
2460 
2461 	if (hat->sfmmu_rmstat)
2462 		hat_resvstat(len, hat->sfmmu_as, addr);
2463 
2464 #if defined(SF_ERRATA_57)
2465 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2466 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2467 	    !(flags & HAT_LOAD_SHARE)) {
2468 		cmn_err(CE_WARN, "hat_memload_array: illegal attempt to make "
2469 		    "user page executable");
2470 		attr &= ~PROT_EXEC;
2471 	}
2472 #endif
2473 
2474 	/* Get number of pages */
2475 	npgs = len >> MMU_PAGESHIFT;
2476 
2477 	if (flags & HAT_LOAD_SHARE) {
2478 		large_pages_disable = disable_ism_large_pages;
2479 	} else {
2480 		large_pages_disable = disable_large_pages;
2481 	}
2482 
2483 	if (npgs < NHMENTS || large_pages_disable == LARGE_PAGES_OFF) {
2484 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2485 		    rid);
2486 		return;
2487 	}
2488 
2489 	while (npgs >= NHMENTS) {
2490 		pp = *pps;
2491 		for (ttesz = pp->p_szc; ttesz != TTE8K; ttesz--) {
2492 			/*
2493 			 * Check if this page size is disabled.
2494 			 */
2495 			if (large_pages_disable & (1 << ttesz))
2496 				continue;
2497 
2498 			numpg = TTEPAGES(ttesz);
2499 			mapsz = numpg << MMU_PAGESHIFT;
2500 			if ((npgs >= numpg) &&
2501 			    IS_P2ALIGNED(addr, mapsz) &&
2502 			    IS_P2ALIGNED(pp->p_pagenum, numpg)) {
2503 				/*
2504 				 * At this point we have enough pages and
2505 				 * we know the virtual address and the pfn
2506 				 * are properly aligned.  We still need
2507 				 * to check for physical contiguity but since
2508 				 * it is very likely that this is the case
2509 				 * we will assume they are so and undo
2510 				 * the request if necessary.  It would
2511 				 * be great if we could get a hint flag
2512 				 * like HAT_CONTIG which would tell us
2513 				 * the pages are contigous for sure.
2514 				 */
2515 				sfmmu_memtte(&tte, (*pps)->p_pagenum,
2516 				    attr, ttesz);
2517 				if (!sfmmu_tteload_array(hat, &tte, addr,
2518 				    pps, flags, rid)) {
2519 					break;
2520 				}
2521 			}
2522 		}
2523 		if (ttesz == TTE8K) {
2524 			/*
2525 			 * We were not able to map array using a large page
2526 			 * batch a hmeblk or fraction at a time.
2527 			 */
2528 			numpg = ((uintptr_t)addr >> MMU_PAGESHIFT)
2529 			    & (NHMENTS-1);
2530 			numpg = NHMENTS - numpg;
2531 			ASSERT(numpg <= npgs);
2532 			mapsz = numpg * MMU_PAGESIZE;
2533 			sfmmu_memload_batchsmall(hat, addr, pps, attr, flags,
2534 			    numpg, rid);
2535 		}
2536 		addr += mapsz;
2537 		npgs -= numpg;
2538 		pps += numpg;
2539 	}
2540 
2541 	if (npgs) {
2542 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2543 		    rid);
2544 	}
2545 
2546 	/*
2547 	 * Check TSB and TLB page sizes.
2548 	 */
2549 	if ((flags & HAT_LOAD_SHARE) == 0) {
2550 		sfmmu_check_page_sizes(hat, 1);
2551 	}
2552 }
2553 
2554 /*
2555  * Function tries to batch 8K pages into the same hme blk.
2556  */
2557 static void
2558 sfmmu_memload_batchsmall(struct hat *hat, caddr_t vaddr, page_t **pps,
2559     uint_t attr, uint_t flags, pgcnt_t npgs, uint_t rid)
2560 {
2561 	tte_t	tte;
2562 	page_t *pp;
2563 	struct hmehash_bucket *hmebp;
2564 	struct hme_blk *hmeblkp;
2565 	int	index;
2566 
2567 	while (npgs) {
2568 		/*
2569 		 * Acquire the hash bucket.
2570 		 */
2571 		hmebp = sfmmu_tteload_acquire_hashbucket(hat, vaddr, TTE8K,
2572 		    rid);
2573 		ASSERT(hmebp);
2574 
2575 		/*
2576 		 * Find the hment block.
2577 		 */
2578 		hmeblkp = sfmmu_tteload_find_hmeblk(hat, hmebp, vaddr,
2579 		    TTE8K, flags, rid);
2580 		ASSERT(hmeblkp);
2581 
2582 		do {
2583 			/*
2584 			 * Make the tte.
2585 			 */
2586 			pp = *pps;
2587 			sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2588 
2589 			/*
2590 			 * Add the translation.
2591 			 */
2592 			(void) sfmmu_tteload_addentry(hat, hmeblkp, &tte,
2593 			    vaddr, pps, flags, rid);
2594 
2595 			/*
2596 			 * Goto next page.
2597 			 */
2598 			pps++;
2599 			npgs--;
2600 
2601 			/*
2602 			 * Goto next address.
2603 			 */
2604 			vaddr += MMU_PAGESIZE;
2605 
2606 			/*
2607 			 * Don't crossover into a different hmentblk.
2608 			 */
2609 			index = (int)(((uintptr_t)vaddr >> MMU_PAGESHIFT) &
2610 			    (NHMENTS-1));
2611 
2612 		} while (index != 0 && npgs != 0);
2613 
2614 		/*
2615 		 * Release the hash bucket.
2616 		 */
2617 
2618 		sfmmu_tteload_release_hashbucket(hmebp);
2619 	}
2620 }
2621 
2622 /*
2623  * Construct a tte for a page:
2624  *
2625  * tte_valid = 1
2626  * tte_size2 = size & TTE_SZ2_BITS (Panther and Olympus-C only)
2627  * tte_size = size
2628  * tte_nfo = attr & HAT_NOFAULT
2629  * tte_ie = attr & HAT_STRUCTURE_LE
2630  * tte_hmenum = hmenum
2631  * tte_pahi = pp->p_pagenum >> TTE_PASHIFT;
2632  * tte_palo = pp->p_pagenum & TTE_PALOMASK;
2633  * tte_ref = 1 (optimization)
2634  * tte_wr_perm = attr & PROT_WRITE;
2635  * tte_no_sync = attr & HAT_NOSYNC
2636  * tte_lock = attr & SFMMU_LOCKTTE
2637  * tte_cp = !(attr & SFMMU_UNCACHEPTTE)
2638  * tte_cv = !(attr & SFMMU_UNCACHEVTTE)
2639  * tte_e = attr & SFMMU_SIDEFFECT
2640  * tte_priv = !(attr & PROT_USER)
2641  * tte_hwwr = if nosync is set and it is writable we set the mod bit (opt)
2642  * tte_glb = 0
2643  */
2644 void
2645 sfmmu_memtte(tte_t *ttep, pfn_t pfn, uint_t attr, int tte_sz)
2646 {
2647 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2648 
2649 	ttep->tte_inthi = MAKE_TTE_INTHI(pfn, attr, tte_sz, 0 /* hmenum */);
2650 	ttep->tte_intlo = MAKE_TTE_INTLO(pfn, attr, tte_sz, 0 /* hmenum */);
2651 
2652 	if (TTE_IS_NOSYNC(ttep)) {
2653 		TTE_SET_REF(ttep);
2654 		if (TTE_IS_WRITABLE(ttep)) {
2655 			TTE_SET_MOD(ttep);
2656 		}
2657 	}
2658 	if (TTE_IS_NFO(ttep) && TTE_IS_EXECUTABLE(ttep)) {
2659 		panic("sfmmu_memtte: can't set both NFO and EXEC bits");
2660 	}
2661 }
2662 
2663 /*
2664  * This function will add a translation to the hme_blk and allocate the
2665  * hme_blk if one does not exist.
2666  * If a page structure is specified then it will add the
2667  * corresponding hment to the mapping list.
2668  * It will also update the hmenum field for the tte.
2669  *
2670  * Currently this function is only used for kernel mappings.
2671  * So pass invalid region to sfmmu_tteload_array().
2672  */
2673 void
2674 sfmmu_tteload(struct hat *sfmmup, tte_t *ttep, caddr_t vaddr, page_t *pp,
2675     uint_t flags)
2676 {
2677 	ASSERT(sfmmup == ksfmmup);
2678 	(void) sfmmu_tteload_array(sfmmup, ttep, vaddr, &pp, flags,
2679 	    SFMMU_INVALID_SHMERID);
2680 }
2681 
2682 /*
2683  * Load (ttep != NULL) or unload (ttep == NULL) one entry in the TSB.
2684  * Assumes that a particular page size may only be resident in one TSB.
2685  */
2686 static void
2687 sfmmu_mod_tsb(sfmmu_t *sfmmup, caddr_t vaddr, tte_t *ttep, int ttesz)
2688 {
2689 	struct tsb_info *tsbinfop = NULL;
2690 	uint64_t tag;
2691 	struct tsbe *tsbe_addr;
2692 	uint64_t tsb_base;
2693 	uint_t tsb_size;
2694 	int vpshift = MMU_PAGESHIFT;
2695 	int phys = 0;
2696 
2697 	if (sfmmup == ksfmmup) { /* No support for 32/256M ksfmmu pages */
2698 		phys = ktsb_phys;
2699 		if (ttesz >= TTE4M) {
2700 #ifndef sun4v
2701 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2702 #endif
2703 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2704 			tsb_size = ktsb4m_szcode;
2705 		} else {
2706 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2707 			tsb_size = ktsb_szcode;
2708 		}
2709 	} else {
2710 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2711 
2712 		/*
2713 		 * If there isn't a TSB for this page size, or the TSB is
2714 		 * swapped out, there is nothing to do.  Note that the latter
2715 		 * case seems impossible but can occur if hat_pageunload()
2716 		 * is called on an ISM mapping while the process is swapped
2717 		 * out.
2718 		 */
2719 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2720 			return;
2721 
2722 		/*
2723 		 * If another thread is in the middle of relocating a TSB
2724 		 * we can't unload the entry so set a flag so that the
2725 		 * TSB will be flushed before it can be accessed by the
2726 		 * process.
2727 		 */
2728 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2729 			if (ttep == NULL)
2730 				tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2731 			return;
2732 		}
2733 #if defined(UTSB_PHYS)
2734 		phys = 1;
2735 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2736 #else
2737 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2738 #endif
2739 		tsb_size = tsbinfop->tsb_szc;
2740 	}
2741 	if (ttesz >= TTE4M)
2742 		vpshift = MMU_PAGESHIFT4M;
2743 
2744 	tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2745 	tag = sfmmu_make_tsbtag(vaddr);
2746 
2747 	if (ttep == NULL) {
2748 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2749 	} else {
2750 		if (ttesz >= TTE4M) {
2751 			SFMMU_STAT(sf_tsb_load4m);
2752 		} else {
2753 			SFMMU_STAT(sf_tsb_load8k);
2754 		}
2755 
2756 		sfmmu_load_tsbe(tsbe_addr, tag, ttep, phys);
2757 	}
2758 }
2759 
2760 /*
2761  * Unmap all entries from [start, end) matching the given page size.
2762  *
2763  * This function is used primarily to unmap replicated 64K or 512K entries
2764  * from the TSB that are inserted using the base page size TSB pointer, but
2765  * it may also be called to unmap a range of addresses from the TSB.
2766  */
2767 void
2768 sfmmu_unload_tsb_range(sfmmu_t *sfmmup, caddr_t start, caddr_t end, int ttesz)
2769 {
2770 	struct tsb_info *tsbinfop;
2771 	uint64_t tag;
2772 	struct tsbe *tsbe_addr;
2773 	caddr_t vaddr;
2774 	uint64_t tsb_base;
2775 	int vpshift, vpgsz;
2776 	uint_t tsb_size;
2777 	int phys = 0;
2778 
2779 	/*
2780 	 * Assumptions:
2781 	 *  If ttesz == 8K, 64K or 512K, we walk through the range 8K
2782 	 *  at a time shooting down any valid entries we encounter.
2783 	 *
2784 	 *  If ttesz >= 4M we walk the range 4M at a time shooting
2785 	 *  down any valid mappings we find.
2786 	 */
2787 	if (sfmmup == ksfmmup) {
2788 		phys = ktsb_phys;
2789 		if (ttesz >= TTE4M) {
2790 #ifndef sun4v
2791 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2792 #endif
2793 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2794 			tsb_size = ktsb4m_szcode;
2795 		} else {
2796 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2797 			tsb_size = ktsb_szcode;
2798 		}
2799 	} else {
2800 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2801 
2802 		/*
2803 		 * If there isn't a TSB for this page size, or the TSB is
2804 		 * swapped out, there is nothing to do.  Note that the latter
2805 		 * case seems impossible but can occur if hat_pageunload()
2806 		 * is called on an ISM mapping while the process is swapped
2807 		 * out.
2808 		 */
2809 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2810 			return;
2811 
2812 		/*
2813 		 * If another thread is in the middle of relocating a TSB
2814 		 * we can't unload the entry so set a flag so that the
2815 		 * TSB will be flushed before it can be accessed by the
2816 		 * process.
2817 		 */
2818 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2819 			tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2820 			return;
2821 		}
2822 #if defined(UTSB_PHYS)
2823 		phys = 1;
2824 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2825 #else
2826 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2827 #endif
2828 		tsb_size = tsbinfop->tsb_szc;
2829 	}
2830 	if (ttesz >= TTE4M) {
2831 		vpshift = MMU_PAGESHIFT4M;
2832 		vpgsz = MMU_PAGESIZE4M;
2833 	} else {
2834 		vpshift = MMU_PAGESHIFT;
2835 		vpgsz = MMU_PAGESIZE;
2836 	}
2837 
2838 	for (vaddr = start; vaddr < end; vaddr += vpgsz) {
2839 		tag = sfmmu_make_tsbtag(vaddr);
2840 		tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2841 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2842 	}
2843 }
2844 
2845 /*
2846  * Select the optimum TSB size given the number of mappings
2847  * that need to be cached.
2848  */
2849 static int
2850 sfmmu_select_tsb_szc(pgcnt_t pgcnt)
2851 {
2852 	int szc = 0;
2853 
2854 #ifdef DEBUG
2855 	if (tsb_grow_stress) {
2856 		uint32_t randval = (uint32_t)gettick() >> 4;
2857 		return (randval % (tsb_max_growsize + 1));
2858 	}
2859 #endif	/* DEBUG */
2860 
2861 	while ((szc < tsb_max_growsize) && (pgcnt > SFMMU_RSS_TSBSIZE(szc)))
2862 		szc++;
2863 	return (szc);
2864 }
2865 
2866 /*
2867  * This function will add a translation to the hme_blk and allocate the
2868  * hme_blk if one does not exist.
2869  * If a page structure is specified then it will add the
2870  * corresponding hment to the mapping list.
2871  * It will also update the hmenum field for the tte.
2872  * Furthermore, it attempts to create a large page translation
2873  * for <addr,hat> at page array pps.  It assumes addr and first
2874  * pp is correctly aligned.  It returns 0 if successful and 1 otherwise.
2875  */
2876 static int
2877 sfmmu_tteload_array(sfmmu_t *sfmmup, tte_t *ttep, caddr_t vaddr,
2878     page_t **pps, uint_t flags, uint_t rid)
2879 {
2880 	struct hmehash_bucket *hmebp;
2881 	struct hme_blk *hmeblkp;
2882 	int	ret;
2883 	uint_t	size;
2884 
2885 	/*
2886 	 * Get mapping size.
2887 	 */
2888 	size = TTE_CSZ(ttep);
2889 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
2890 
2891 	/*
2892 	 * Acquire the hash bucket.
2893 	 */
2894 	hmebp = sfmmu_tteload_acquire_hashbucket(sfmmup, vaddr, size, rid);
2895 	ASSERT(hmebp);
2896 
2897 	/*
2898 	 * Find the hment block.
2899 	 */
2900 	hmeblkp = sfmmu_tteload_find_hmeblk(sfmmup, hmebp, vaddr, size, flags,
2901 	    rid);
2902 	ASSERT(hmeblkp);
2903 
2904 	/*
2905 	 * Add the translation.
2906 	 */
2907 	ret = sfmmu_tteload_addentry(sfmmup, hmeblkp, ttep, vaddr, pps, flags,
2908 	    rid);
2909 
2910 	/*
2911 	 * Release the hash bucket.
2912 	 */
2913 	sfmmu_tteload_release_hashbucket(hmebp);
2914 
2915 	return (ret);
2916 }
2917 
2918 /*
2919  * Function locks and returns a pointer to the hash bucket for vaddr and size.
2920  */
2921 static struct hmehash_bucket *
2922 sfmmu_tteload_acquire_hashbucket(sfmmu_t *sfmmup, caddr_t vaddr, int size,
2923     uint_t rid)
2924 {
2925 	struct hmehash_bucket *hmebp;
2926 	int hmeshift;
2927 	void *htagid = sfmmutohtagid(sfmmup, rid);
2928 
2929 	ASSERT(htagid != NULL);
2930 
2931 	hmeshift = HME_HASH_SHIFT(size);
2932 
2933 	hmebp = HME_HASH_FUNCTION(htagid, vaddr, hmeshift);
2934 
2935 	SFMMU_HASH_LOCK(hmebp);
2936 
2937 	return (hmebp);
2938 }
2939 
2940 /*
2941  * Function returns a pointer to an hmeblk in the hash bucket, hmebp. If the
2942  * hmeblk doesn't exists for the [sfmmup, vaddr & size] signature, a hmeblk is
2943  * allocated.
2944  */
2945 static struct hme_blk *
2946 sfmmu_tteload_find_hmeblk(sfmmu_t *sfmmup, struct hmehash_bucket *hmebp,
2947     caddr_t vaddr, uint_t size, uint_t flags, uint_t rid)
2948 {
2949 	hmeblk_tag hblktag;
2950 	int hmeshift;
2951 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
2952 
2953 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
2954 
2955 	hblktag.htag_id = sfmmutohtagid(sfmmup, rid);
2956 	ASSERT(hblktag.htag_id != NULL);
2957 	hmeshift = HME_HASH_SHIFT(size);
2958 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
2959 	hblktag.htag_rehash = HME_HASH_REHASH(size);
2960 	hblktag.htag_rid = rid;
2961 
2962 ttearray_realloc:
2963 
2964 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
2965 
2966 	/*
2967 	 * We block until hblk_reserve_lock is released; it's held by
2968 	 * the thread, temporarily using hblk_reserve, until hblk_reserve is
2969 	 * replaced by a hblk from sfmmu8_cache.
2970 	 */
2971 	if (hmeblkp == (struct hme_blk *)hblk_reserve &&
2972 	    hblk_reserve_thread != curthread) {
2973 		SFMMU_HASH_UNLOCK(hmebp);
2974 		mutex_enter(&hblk_reserve_lock);
2975 		mutex_exit(&hblk_reserve_lock);
2976 		SFMMU_STAT(sf_hblk_reserve_hit);
2977 		SFMMU_HASH_LOCK(hmebp);
2978 		goto ttearray_realloc;
2979 	}
2980 
2981 	if (hmeblkp == NULL) {
2982 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
2983 		    hblktag, flags, rid);
2984 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
2985 		ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
2986 	} else {
2987 		/*
2988 		 * It is possible for 8k and 64k hblks to collide since they
2989 		 * have the same rehash value. This is because we
2990 		 * lazily free hblks and 8K/64K blks could be lingering.
2991 		 * If we find size mismatch we free the block and & try again.
2992 		 */
2993 		if (get_hblk_ttesz(hmeblkp) != size) {
2994 			ASSERT(!hmeblkp->hblk_vcnt);
2995 			ASSERT(!hmeblkp->hblk_hmecnt);
2996 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
2997 			    &list, 0);
2998 			goto ttearray_realloc;
2999 		}
3000 		if (hmeblkp->hblk_shw_bit) {
3001 			/*
3002 			 * if the hblk was previously used as a shadow hblk then
3003 			 * we will change it to a normal hblk
3004 			 */
3005 			ASSERT(!hmeblkp->hblk_shared);
3006 			if (hmeblkp->hblk_shw_mask) {
3007 				sfmmu_shadow_hcleanup(sfmmup, hmeblkp, hmebp);
3008 				ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3009 				goto ttearray_realloc;
3010 			} else {
3011 				hmeblkp->hblk_shw_bit = 0;
3012 			}
3013 		}
3014 		SFMMU_STAT(sf_hblk_hit);
3015 	}
3016 
3017 	/*
3018 	 * hat_memload() should never call kmem_cache_free() for kernel hmeblks;
3019 	 * see block comment showing the stacktrace in sfmmu_hblk_alloc();
3020 	 * set the flag parameter to 1 so that sfmmu_hblks_list_purge() will
3021 	 * just add these hmeblks to the per-cpu pending queue.
3022 	 */
3023 	sfmmu_hblks_list_purge(&list, 1);
3024 
3025 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
3026 	ASSERT(!hmeblkp->hblk_shw_bit);
3027 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3028 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3029 	ASSERT(hmeblkp->hblk_tag.htag_rid == rid);
3030 
3031 	return (hmeblkp);
3032 }
3033 
3034 /*
3035  * Function adds a tte entry into the hmeblk. It returns 0 if successful and 1
3036  * otherwise.
3037  */
3038 static int
3039 sfmmu_tteload_addentry(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, tte_t *ttep,
3040     caddr_t vaddr, page_t **pps, uint_t flags, uint_t rid)
3041 {
3042 	page_t *pp = *pps;
3043 	int hmenum, size, remap;
3044 	tte_t tteold, flush_tte;
3045 #ifdef DEBUG
3046 	tte_t orig_old;
3047 #endif /* DEBUG */
3048 	struct sf_hment *sfhme;
3049 	kmutex_t *pml, *pmtx;
3050 	hatlock_t *hatlockp;
3051 	int myflt;
3052 
3053 	/*
3054 	 * remove this panic when we decide to let user virtual address
3055 	 * space be >= USERLIMIT.
3056 	 */
3057 	if (!TTE_IS_PRIVILEGED(ttep) && vaddr >= (caddr_t)USERLIMIT)
3058 		panic("user addr %p in kernel space", (void *)vaddr);
3059 #if defined(TTE_IS_GLOBAL)
3060 	if (TTE_IS_GLOBAL(ttep))
3061 		panic("sfmmu_tteload: creating global tte");
3062 #endif
3063 
3064 #ifdef DEBUG
3065 	if (pf_is_memory(sfmmu_ttetopfn(ttep, vaddr)) &&
3066 	    !TTE_IS_PCACHEABLE(ttep) && !sfmmu_allow_nc_trans)
3067 		panic("sfmmu_tteload: non cacheable memory tte");
3068 #endif /* DEBUG */
3069 
3070 	/* don't simulate dirty bit for writeable ISM/DISM mappings */
3071 	if ((flags & HAT_LOAD_SHARE) && TTE_IS_WRITABLE(ttep)) {
3072 		TTE_SET_REF(ttep);
3073 		TTE_SET_MOD(ttep);
3074 	}
3075 
3076 	if ((flags & HAT_LOAD_SHARE) || !TTE_IS_REF(ttep) ||
3077 	    !TTE_IS_MOD(ttep)) {
3078 		/*
3079 		 * Don't load TSB for dummy as in ISM.  Also don't preload
3080 		 * the TSB if the TTE isn't writable since we're likely to
3081 		 * fault on it again -- preloading can be fairly expensive.
3082 		 */
3083 		flags |= SFMMU_NO_TSBLOAD;
3084 	}
3085 
3086 	size = TTE_CSZ(ttep);
3087 	switch (size) {
3088 	case TTE8K:
3089 		SFMMU_STAT(sf_tteload8k);
3090 		break;
3091 	case TTE64K:
3092 		SFMMU_STAT(sf_tteload64k);
3093 		break;
3094 	case TTE512K:
3095 		SFMMU_STAT(sf_tteload512k);
3096 		break;
3097 	case TTE4M:
3098 		SFMMU_STAT(sf_tteload4m);
3099 		break;
3100 	case (TTE32M):
3101 		SFMMU_STAT(sf_tteload32m);
3102 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3103 		break;
3104 	case (TTE256M):
3105 		SFMMU_STAT(sf_tteload256m);
3106 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3107 		break;
3108 	}
3109 
3110 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
3111 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
3112 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3113 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3114 
3115 	HBLKTOHME_IDX(sfhme, hmeblkp, vaddr, hmenum);
3116 
3117 	/*
3118 	 * Need to grab mlist lock here so that pageunload
3119 	 * will not change tte behind us.
3120 	 */
3121 	if (pp) {
3122 		pml = sfmmu_mlist_enter(pp);
3123 	}
3124 
3125 	sfmmu_copytte(&sfhme->hme_tte, &tteold);
3126 	/*
3127 	 * Look for corresponding hment and if valid verify
3128 	 * pfns are equal.
3129 	 */
3130 	remap = TTE_IS_VALID(&tteold);
3131 	if (remap) {
3132 		pfn_t	new_pfn, old_pfn;
3133 
3134 		old_pfn = TTE_TO_PFN(vaddr, &tteold);
3135 		new_pfn = TTE_TO_PFN(vaddr, ttep);
3136 
3137 		if (flags & HAT_LOAD_REMAP) {
3138 			/* make sure we are remapping same type of pages */
3139 			if (pf_is_memory(old_pfn) != pf_is_memory(new_pfn)) {
3140 				panic("sfmmu_tteload - tte remap io<->memory");
3141 			}
3142 			if (old_pfn != new_pfn &&
3143 			    (pp != NULL || sfhme->hme_page != NULL)) {
3144 				panic("sfmmu_tteload - tte remap pp != NULL");
3145 			}
3146 		} else if (old_pfn != new_pfn) {
3147 			panic("sfmmu_tteload - tte remap, hmeblkp 0x%p",
3148 			    (void *)hmeblkp);
3149 		}
3150 		ASSERT(TTE_CSZ(&tteold) == TTE_CSZ(ttep));
3151 	}
3152 
3153 	if (pp) {
3154 		if (size == TTE8K) {
3155 #ifdef VAC
3156 			/*
3157 			 * Handle VAC consistency
3158 			 */
3159 			if (!remap && (cache & CACHE_VAC) && !PP_ISNC(pp)) {
3160 				sfmmu_vac_conflict(sfmmup, vaddr, pp);
3161 			}
3162 #endif
3163 
3164 			if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3165 				pmtx = sfmmu_page_enter(pp);
3166 				PP_CLRRO(pp);
3167 				sfmmu_page_exit(pmtx);
3168 			} else if (!PP_ISMAPPED(pp) &&
3169 			    (!TTE_IS_WRITABLE(ttep)) && !(PP_ISMOD(pp))) {
3170 				pmtx = sfmmu_page_enter(pp);
3171 				if (!(PP_ISMOD(pp))) {
3172 					PP_SETRO(pp);
3173 				}
3174 				sfmmu_page_exit(pmtx);
3175 			}
3176 
3177 		} else if (sfmmu_pagearray_setup(vaddr, pps, ttep, remap)) {
3178 			/*
3179 			 * sfmmu_pagearray_setup failed so return
3180 			 */
3181 			sfmmu_mlist_exit(pml);
3182 			return (1);
3183 		}
3184 	}
3185 
3186 	/*
3187 	 * Make sure hment is not on a mapping list.
3188 	 */
3189 	ASSERT(remap || (sfhme->hme_page == NULL));
3190 
3191 	/* if it is not a remap then hme->next better be NULL */
3192 	ASSERT((!remap) ? sfhme->hme_next == NULL : 1);
3193 
3194 	if (flags & HAT_LOAD_LOCK) {
3195 		if ((hmeblkp->hblk_lckcnt + 1) >= MAX_HBLK_LCKCNT) {
3196 			panic("too high lckcnt-hmeblk %p",
3197 			    (void *)hmeblkp);
3198 		}
3199 		atomic_inc_32(&hmeblkp->hblk_lckcnt);
3200 
3201 		HBLK_STACK_TRACE(hmeblkp, HBLK_LOCK);
3202 	}
3203 
3204 #ifdef VAC
3205 	if (pp && PP_ISNC(pp)) {
3206 		/*
3207 		 * If the physical page is marked to be uncacheable, like
3208 		 * by a vac conflict, make sure the new mapping is also
3209 		 * uncacheable.
3210 		 */
3211 		TTE_CLR_VCACHEABLE(ttep);
3212 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
3213 	}
3214 #endif
3215 	ttep->tte_hmenum = hmenum;
3216 
3217 #ifdef DEBUG
3218 	orig_old = tteold;
3219 #endif /* DEBUG */
3220 
3221 	while (sfmmu_modifytte_try(&tteold, ttep, &sfhme->hme_tte) < 0) {
3222 		if ((sfmmup == KHATID) &&
3223 		    (flags & (HAT_LOAD_LOCK | HAT_LOAD_REMAP))) {
3224 			sfmmu_copytte(&sfhme->hme_tte, &tteold);
3225 		}
3226 #ifdef DEBUG
3227 		chk_tte(&orig_old, &tteold, ttep, hmeblkp);
3228 #endif /* DEBUG */
3229 	}
3230 	ASSERT(TTE_IS_VALID(&sfhme->hme_tte));
3231 
3232 	if (!TTE_IS_VALID(&tteold)) {
3233 
3234 		atomic_inc_16(&hmeblkp->hblk_vcnt);
3235 		if (rid == SFMMU_INVALID_SHMERID) {
3236 			atomic_inc_ulong(&sfmmup->sfmmu_ttecnt[size]);
3237 		} else {
3238 			sf_srd_t *srdp = sfmmup->sfmmu_srdp;
3239 			sf_region_t *rgnp = srdp->srd_hmergnp[rid];
3240 			/*
3241 			 * We already accounted for region ttecnt's in sfmmu
3242 			 * during hat_join_region() processing. Here we
3243 			 * only update ttecnt's in region struture.
3244 			 */
3245 			atomic_inc_ulong(&rgnp->rgn_ttecnt[size]);
3246 		}
3247 	}
3248 
3249 	myflt = (astosfmmu(curthread->t_procp->p_as) == sfmmup);
3250 	if (size > TTE8K && (flags & HAT_LOAD_SHARE) == 0 &&
3251 	    sfmmup != ksfmmup) {
3252 		uchar_t tteflag = 1 << size;
3253 		if (rid == SFMMU_INVALID_SHMERID) {
3254 			if (!(sfmmup->sfmmu_tteflags & tteflag)) {
3255 				hatlockp = sfmmu_hat_enter(sfmmup);
3256 				sfmmup->sfmmu_tteflags |= tteflag;
3257 				sfmmu_hat_exit(hatlockp);
3258 			}
3259 		} else if (!(sfmmup->sfmmu_rtteflags & tteflag)) {
3260 			hatlockp = sfmmu_hat_enter(sfmmup);
3261 			sfmmup->sfmmu_rtteflags |= tteflag;
3262 			sfmmu_hat_exit(hatlockp);
3263 		}
3264 		/*
3265 		 * Update the current CPU tsbmiss area, so the current thread
3266 		 * won't need to take the tsbmiss for the new pagesize.
3267 		 * The other threads in the process will update their tsb
3268 		 * miss area lazily in sfmmu_tsbmiss_exception() when they
3269 		 * fail to find the translation for a newly added pagesize.
3270 		 */
3271 		if (size > TTE64K && myflt) {
3272 			struct tsbmiss *tsbmp;
3273 			kpreempt_disable();
3274 			tsbmp = &tsbmiss_area[CPU->cpu_id];
3275 			if (rid == SFMMU_INVALID_SHMERID) {
3276 				if (!(tsbmp->uhat_tteflags & tteflag)) {
3277 					tsbmp->uhat_tteflags |= tteflag;
3278 				}
3279 			} else {
3280 				if (!(tsbmp->uhat_rtteflags & tteflag)) {
3281 					tsbmp->uhat_rtteflags |= tteflag;
3282 				}
3283 			}
3284 			kpreempt_enable();
3285 		}
3286 	}
3287 
3288 	if (size >= TTE4M && (flags & HAT_LOAD_TEXT) &&
3289 	    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
3290 		hatlockp = sfmmu_hat_enter(sfmmup);
3291 		SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
3292 		sfmmu_hat_exit(hatlockp);
3293 	}
3294 
3295 	flush_tte.tte_intlo = (tteold.tte_intlo ^ ttep->tte_intlo) &
3296 	    hw_tte.tte_intlo;
3297 	flush_tte.tte_inthi = (tteold.tte_inthi ^ ttep->tte_inthi) &
3298 	    hw_tte.tte_inthi;
3299 
3300 	if (remap && (flush_tte.tte_inthi || flush_tte.tte_intlo)) {
3301 		/*
3302 		 * If remap and new tte differs from old tte we need
3303 		 * to sync the mod bit and flush TLB/TSB.  We don't
3304 		 * need to sync ref bit because we currently always set
3305 		 * ref bit in tteload.
3306 		 */
3307 		ASSERT(TTE_IS_REF(ttep));
3308 		if (TTE_IS_MOD(&tteold)) {
3309 			sfmmu_ttesync(sfmmup, vaddr, &tteold, pp);
3310 		}
3311 		/*
3312 		 * hwtte bits shouldn't change for SRD hmeblks as long as SRD
3313 		 * hmes are only used for read only text. Adding this code for
3314 		 * completeness and future use of shared hmeblks with writable
3315 		 * mappings of VMODSORT vnodes.
3316 		 */
3317 		if (hmeblkp->hblk_shared) {
3318 			cpuset_t cpuset = sfmmu_rgntlb_demap(vaddr,
3319 			    sfmmup->sfmmu_srdp->srd_hmergnp[rid], hmeblkp, 1);
3320 			xt_sync(cpuset);
3321 			SFMMU_STAT_ADD(sf_region_remap_demap, 1);
3322 		} else {
3323 			sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 0);
3324 			xt_sync(sfmmup->sfmmu_cpusran);
3325 		}
3326 	}
3327 
3328 	if ((flags & SFMMU_NO_TSBLOAD) == 0) {
3329 		/*
3330 		 * We only preload 8K and 4M mappings into the TSB, since
3331 		 * 64K and 512K mappings are replicated and hence don't
3332 		 * have a single, unique TSB entry. Ditto for 32M/256M.
3333 		 */
3334 		if (size == TTE8K || size == TTE4M) {
3335 			sf_scd_t *scdp;
3336 			hatlockp = sfmmu_hat_enter(sfmmup);
3337 			/*
3338 			 * Don't preload private TSB if the mapping is used
3339 			 * by the shctx in the SCD.
3340 			 */
3341 			scdp = sfmmup->sfmmu_scdp;
3342 			if (rid == SFMMU_INVALID_SHMERID || scdp == NULL ||
3343 			    !SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
3344 				sfmmu_load_tsb(sfmmup, vaddr, &sfhme->hme_tte,
3345 				    size);
3346 			}
3347 			sfmmu_hat_exit(hatlockp);
3348 		}
3349 	}
3350 	if (pp) {
3351 		if (!remap) {
3352 			HME_ADD(sfhme, pp);
3353 			atomic_inc_16(&hmeblkp->hblk_hmecnt);
3354 			ASSERT(hmeblkp->hblk_hmecnt > 0);
3355 
3356 			/*
3357 			 * Cannot ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
3358 			 * see pageunload() for comment.
3359 			 */
3360 		}
3361 		sfmmu_mlist_exit(pml);
3362 	}
3363 
3364 	return (0);
3365 }
3366 /*
3367  * Function unlocks hash bucket.
3368  */
3369 static void
3370 sfmmu_tteload_release_hashbucket(struct hmehash_bucket *hmebp)
3371 {
3372 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3373 	SFMMU_HASH_UNLOCK(hmebp);
3374 }
3375 
3376 /*
3377  * function which checks and sets up page array for a large
3378  * translation.  Will set p_vcolor, p_index, p_ro fields.
3379  * Assumes addr and pfnum of first page are properly aligned.
3380  * Will check for physical contiguity. If check fails it return
3381  * non null.
3382  */
3383 static int
3384 sfmmu_pagearray_setup(caddr_t addr, page_t **pps, tte_t *ttep, int remap)
3385 {
3386 	int	i, index, ttesz;
3387 	pfn_t	pfnum;
3388 	pgcnt_t	npgs;
3389 	page_t *pp, *pp1;
3390 	kmutex_t *pmtx;
3391 #ifdef VAC
3392 	int osz;
3393 	int cflags = 0;
3394 	int vac_err = 0;
3395 #endif
3396 	int newidx = 0;
3397 
3398 	ttesz = TTE_CSZ(ttep);
3399 
3400 	ASSERT(ttesz > TTE8K);
3401 
3402 	npgs = TTEPAGES(ttesz);
3403 	index = PAGESZ_TO_INDEX(ttesz);
3404 
3405 	pfnum = (*pps)->p_pagenum;
3406 	ASSERT(IS_P2ALIGNED(pfnum, npgs));
3407 
3408 	/*
3409 	 * Save the first pp so we can do HAT_TMPNC at the end.
3410 	 */
3411 	pp1 = *pps;
3412 #ifdef VAC
3413 	osz = fnd_mapping_sz(pp1);
3414 #endif
3415 
3416 	for (i = 0; i < npgs; i++, pps++) {
3417 		pp = *pps;
3418 		ASSERT(PAGE_LOCKED(pp));
3419 		ASSERT(pp->p_szc >= ttesz);
3420 		ASSERT(pp->p_szc == pp1->p_szc);
3421 		ASSERT(sfmmu_mlist_held(pp));
3422 
3423 		/*
3424 		 * XXX is it possible to maintain P_RO on the root only?
3425 		 */
3426 		if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3427 			pmtx = sfmmu_page_enter(pp);
3428 			PP_CLRRO(pp);
3429 			sfmmu_page_exit(pmtx);
3430 		} else if (!PP_ISMAPPED(pp) && !TTE_IS_WRITABLE(ttep) &&
3431 		    !PP_ISMOD(pp)) {
3432 			pmtx = sfmmu_page_enter(pp);
3433 			if (!(PP_ISMOD(pp))) {
3434 				PP_SETRO(pp);
3435 			}
3436 			sfmmu_page_exit(pmtx);
3437 		}
3438 
3439 		/*
3440 		 * If this is a remap we skip vac & contiguity checks.
3441 		 */
3442 		if (remap)
3443 			continue;
3444 
3445 		/*
3446 		 * set p_vcolor and detect any vac conflicts.
3447 		 */
3448 #ifdef VAC
3449 		if (vac_err == 0) {
3450 			vac_err = sfmmu_vacconflict_array(addr, pp, &cflags);
3451 
3452 		}
3453 #endif
3454 
3455 		/*
3456 		 * Save current index in case we need to undo it.
3457 		 * Note: "PAGESZ_TO_INDEX(sz)	(1 << (sz))"
3458 		 *	"SFMMU_INDEX_SHIFT	6"
3459 		 *	 "SFMMU_INDEX_MASK	((1 << SFMMU_INDEX_SHIFT) - 1)"
3460 		 *	 "PP_MAPINDEX(p_index)	(p_index & SFMMU_INDEX_MASK)"
3461 		 *
3462 		 * So:	index = PAGESZ_TO_INDEX(ttesz);
3463 		 *	if ttesz == 1 then index = 0x2
3464 		 *		    2 then index = 0x4
3465 		 *		    3 then index = 0x8
3466 		 *		    4 then index = 0x10
3467 		 *		    5 then index = 0x20
3468 		 * The code below checks if it's a new pagesize (ie, newidx)
3469 		 * in case we need to take it back out of p_index,
3470 		 * and then or's the new index into the existing index.
3471 		 */
3472 		if ((PP_MAPINDEX(pp) & index) == 0)
3473 			newidx = 1;
3474 		pp->p_index = (PP_MAPINDEX(pp) | index);
3475 
3476 		/*
3477 		 * contiguity check
3478 		 */
3479 		if (pp->p_pagenum != pfnum) {
3480 			/*
3481 			 * If we fail the contiguity test then
3482 			 * the only thing we need to fix is the p_index field.
3483 			 * We might get a few extra flushes but since this
3484 			 * path is rare that is ok.  The p_ro field will
3485 			 * get automatically fixed on the next tteload to
3486 			 * the page.  NO TNC bit is set yet.
3487 			 */
3488 			while (i >= 0) {
3489 				pp = *pps;
3490 				if (newidx)
3491 					pp->p_index = (PP_MAPINDEX(pp) &
3492 					    ~index);
3493 				pps--;
3494 				i--;
3495 			}
3496 			return (1);
3497 		}
3498 		pfnum++;
3499 		addr += MMU_PAGESIZE;
3500 	}
3501 
3502 #ifdef VAC
3503 	if (vac_err) {
3504 		if (ttesz > osz) {
3505 			/*
3506 			 * There are some smaller mappings that causes vac
3507 			 * conflicts. Convert all existing small mappings to
3508 			 * TNC.
3509 			 */
3510 			SFMMU_STAT_ADD(sf_uncache_conflict, npgs);
3511 			sfmmu_page_cache_array(pp1, HAT_TMPNC, CACHE_FLUSH,
3512 			    npgs);
3513 		} else {
3514 			/* EMPTY */
3515 			/*
3516 			 * If there exists an big page mapping,
3517 			 * that means the whole existing big page
3518 			 * has TNC setting already. No need to covert to
3519 			 * TNC again.
3520 			 */
3521 			ASSERT(PP_ISTNC(pp1));
3522 		}
3523 	}
3524 #endif	/* VAC */
3525 
3526 	return (0);
3527 }
3528 
3529 #ifdef VAC
3530 /*
3531  * Routine that detects vac consistency for a large page. It also
3532  * sets virtual color for all pp's for this big mapping.
3533  */
3534 static int
3535 sfmmu_vacconflict_array(caddr_t addr, page_t *pp, int *cflags)
3536 {
3537 	int vcolor, ocolor;
3538 
3539 	ASSERT(sfmmu_mlist_held(pp));
3540 
3541 	if (PP_ISNC(pp)) {
3542 		return (HAT_TMPNC);
3543 	}
3544 
3545 	vcolor = addr_to_vcolor(addr);
3546 	if (PP_NEWPAGE(pp)) {
3547 		PP_SET_VCOLOR(pp, vcolor);
3548 		return (0);
3549 	}
3550 
3551 	ocolor = PP_GET_VCOLOR(pp);
3552 	if (ocolor == vcolor) {
3553 		return (0);
3554 	}
3555 
3556 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
3557 		/*
3558 		 * Previous user of page had a differnet color
3559 		 * but since there are no current users
3560 		 * we just flush the cache and change the color.
3561 		 * As an optimization for large pages we flush the
3562 		 * entire cache of that color and set a flag.
3563 		 */
3564 		SFMMU_STAT(sf_pgcolor_conflict);
3565 		if (!CacheColor_IsFlushed(*cflags, ocolor)) {
3566 			CacheColor_SetFlushed(*cflags, ocolor);
3567 			sfmmu_cache_flushcolor(ocolor, pp->p_pagenum);
3568 		}
3569 		PP_SET_VCOLOR(pp, vcolor);
3570 		return (0);
3571 	}
3572 
3573 	/*
3574 	 * We got a real conflict with a current mapping.
3575 	 * set flags to start unencaching all mappings
3576 	 * and return failure so we restart looping
3577 	 * the pp array from the beginning.
3578 	 */
3579 	return (HAT_TMPNC);
3580 }
3581 #endif	/* VAC */
3582 
3583 /*
3584  * creates a large page shadow hmeblk for a tte.
3585  * The purpose of this routine is to allow us to do quick unloads because
3586  * the vm layer can easily pass a very large but sparsely populated range.
3587  */
3588 static struct hme_blk *
3589 sfmmu_shadow_hcreate(sfmmu_t *sfmmup, caddr_t vaddr, int ttesz, uint_t flags)
3590 {
3591 	struct hmehash_bucket *hmebp;
3592 	hmeblk_tag hblktag;
3593 	int hmeshift, size, vshift;
3594 	uint_t shw_mask, newshw_mask;
3595 	struct hme_blk *hmeblkp;
3596 
3597 	ASSERT(sfmmup != KHATID);
3598 	if (mmu_page_sizes == max_mmu_page_sizes) {
3599 		ASSERT(ttesz < TTE256M);
3600 	} else {
3601 		ASSERT(ttesz < TTE4M);
3602 		ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
3603 		ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
3604 	}
3605 
3606 	if (ttesz == TTE8K) {
3607 		size = TTE512K;
3608 	} else {
3609 		size = ++ttesz;
3610 	}
3611 
3612 	hblktag.htag_id = sfmmup;
3613 	hmeshift = HME_HASH_SHIFT(size);
3614 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
3615 	hblktag.htag_rehash = HME_HASH_REHASH(size);
3616 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3617 	hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
3618 
3619 	SFMMU_HASH_LOCK(hmebp);
3620 
3621 	HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
3622 	ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
3623 	if (hmeblkp == NULL) {
3624 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
3625 		    hblktag, flags, SFMMU_INVALID_SHMERID);
3626 	}
3627 	ASSERT(hmeblkp);
3628 	if (!hmeblkp->hblk_shw_mask) {
3629 		/*
3630 		 * if this is a unused hblk it was just allocated or could
3631 		 * potentially be a previous large page hblk so we need to
3632 		 * set the shadow bit.
3633 		 */
3634 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3635 		hmeblkp->hblk_shw_bit = 1;
3636 	} else if (hmeblkp->hblk_shw_bit == 0) {
3637 		panic("sfmmu_shadow_hcreate: shw bit not set in hmeblkp 0x%p",
3638 		    (void *)hmeblkp);
3639 	}
3640 	ASSERT(hmeblkp->hblk_shw_bit == 1);
3641 	ASSERT(!hmeblkp->hblk_shared);
3642 	vshift = vaddr_to_vshift(hblktag, vaddr, size);
3643 	ASSERT(vshift < 8);
3644 	/*
3645 	 * Atomically set shw mask bit
3646 	 */
3647 	do {
3648 		shw_mask = hmeblkp->hblk_shw_mask;
3649 		newshw_mask = shw_mask | (1 << vshift);
3650 		newshw_mask = atomic_cas_32(&hmeblkp->hblk_shw_mask, shw_mask,
3651 		    newshw_mask);
3652 	} while (newshw_mask != shw_mask);
3653 
3654 	SFMMU_HASH_UNLOCK(hmebp);
3655 
3656 	return (hmeblkp);
3657 }
3658 
3659 /*
3660  * This routine cleanup a previous shadow hmeblk and changes it to
3661  * a regular hblk.  This happens rarely but it is possible
3662  * when a process wants to use large pages and there are hblks still
3663  * lying around from the previous as that used these hmeblks.
3664  * The alternative was to cleanup the shadow hblks at unload time
3665  * but since so few user processes actually use large pages, it is
3666  * better to be lazy and cleanup at this time.
3667  */
3668 static void
3669 sfmmu_shadow_hcleanup(sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
3670     struct hmehash_bucket *hmebp)
3671 {
3672 	caddr_t addr, endaddr;
3673 	int hashno, size;
3674 
3675 	ASSERT(hmeblkp->hblk_shw_bit);
3676 	ASSERT(!hmeblkp->hblk_shared);
3677 
3678 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3679 
3680 	if (!hmeblkp->hblk_shw_mask) {
3681 		hmeblkp->hblk_shw_bit = 0;
3682 		return;
3683 	}
3684 	addr = (caddr_t)get_hblk_base(hmeblkp);
3685 	endaddr = get_hblk_endaddr(hmeblkp);
3686 	size = get_hblk_ttesz(hmeblkp);
3687 	hashno = size - 1;
3688 	ASSERT(hashno > 0);
3689 	SFMMU_HASH_UNLOCK(hmebp);
3690 
3691 	sfmmu_free_hblks(sfmmup, addr, endaddr, hashno);
3692 
3693 	SFMMU_HASH_LOCK(hmebp);
3694 }
3695 
3696 static void
3697 sfmmu_free_hblks(sfmmu_t *sfmmup, caddr_t addr, caddr_t endaddr,
3698     int hashno)
3699 {
3700 	int hmeshift, shadow = 0;
3701 	hmeblk_tag hblktag;
3702 	struct hmehash_bucket *hmebp;
3703 	struct hme_blk *hmeblkp;
3704 	struct hme_blk *nx_hblk, *pr_hblk, *list = NULL;
3705 
3706 	ASSERT(hashno > 0);
3707 	hblktag.htag_id = sfmmup;
3708 	hblktag.htag_rehash = hashno;
3709 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3710 
3711 	hmeshift = HME_HASH_SHIFT(hashno);
3712 
3713 	while (addr < endaddr) {
3714 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3715 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3716 		SFMMU_HASH_LOCK(hmebp);
3717 		/* inline HME_HASH_SEARCH */
3718 		hmeblkp = hmebp->hmeblkp;
3719 		pr_hblk = NULL;
3720 		while (hmeblkp) {
3721 			if (HTAGS_EQ(hmeblkp->hblk_tag, hblktag)) {
3722 				/* found hme_blk */
3723 				ASSERT(!hmeblkp->hblk_shared);
3724 				if (hmeblkp->hblk_shw_bit) {
3725 					if (hmeblkp->hblk_shw_mask) {
3726 						shadow = 1;
3727 						sfmmu_shadow_hcleanup(sfmmup,
3728 						    hmeblkp, hmebp);
3729 						break;
3730 					} else {
3731 						hmeblkp->hblk_shw_bit = 0;
3732 					}
3733 				}
3734 
3735 				/*
3736 				 * Hblk_hmecnt and hblk_vcnt could be non zero
3737 				 * since hblk_unload() does not gurantee that.
3738 				 *
3739 				 * XXX - this could cause tteload() to spin
3740 				 * where sfmmu_shadow_hcleanup() is called.
3741 				 */
3742 			}
3743 
3744 			nx_hblk = hmeblkp->hblk_next;
3745 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
3746 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3747 				    &list, 0);
3748 			} else {
3749 				pr_hblk = hmeblkp;
3750 			}
3751 			hmeblkp = nx_hblk;
3752 		}
3753 
3754 		SFMMU_HASH_UNLOCK(hmebp);
3755 
3756 		if (shadow) {
3757 			/*
3758 			 * We found another shadow hblk so cleaned its
3759 			 * children.  We need to go back and cleanup
3760 			 * the original hblk so we don't change the
3761 			 * addr.
3762 			 */
3763 			shadow = 0;
3764 		} else {
3765 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
3766 			    (1 << hmeshift));
3767 		}
3768 	}
3769 	sfmmu_hblks_list_purge(&list, 0);
3770 }
3771 
3772 /*
3773  * This routine's job is to delete stale invalid shared hmeregions hmeblks that
3774  * may still linger on after pageunload.
3775  */
3776 static void
3777 sfmmu_cleanup_rhblk(sf_srd_t *srdp, caddr_t addr, uint_t rid, int ttesz)
3778 {
3779 	int hmeshift;
3780 	hmeblk_tag hblktag;
3781 	struct hmehash_bucket *hmebp;
3782 	struct hme_blk *hmeblkp;
3783 	struct hme_blk *pr_hblk;
3784 	struct hme_blk *list = NULL;
3785 
3786 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3787 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3788 
3789 	hmeshift = HME_HASH_SHIFT(ttesz);
3790 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3791 	hblktag.htag_rehash = ttesz;
3792 	hblktag.htag_rid = rid;
3793 	hblktag.htag_id = srdp;
3794 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3795 
3796 	SFMMU_HASH_LOCK(hmebp);
3797 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
3798 	if (hmeblkp != NULL) {
3799 		ASSERT(hmeblkp->hblk_shared);
3800 		ASSERT(!hmeblkp->hblk_shw_bit);
3801 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3802 			panic("sfmmu_cleanup_rhblk: valid hmeblk");
3803 		}
3804 		ASSERT(!hmeblkp->hblk_lckcnt);
3805 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3806 		    &list, 0);
3807 	}
3808 	SFMMU_HASH_UNLOCK(hmebp);
3809 	sfmmu_hblks_list_purge(&list, 0);
3810 }
3811 
3812 /* ARGSUSED */
3813 static void
3814 sfmmu_rgn_cb_noop(caddr_t saddr, caddr_t eaddr, caddr_t r_saddr,
3815     size_t r_size, void *r_obj, u_offset_t r_objoff)
3816 {
3817 }
3818 
3819 /*
3820  * Searches for an hmeblk which maps addr, then unloads this mapping
3821  * and updates *eaddrp, if the hmeblk is found.
3822  */
3823 static void
3824 sfmmu_unload_hmeregion_va(sf_srd_t *srdp, uint_t rid, caddr_t addr,
3825     caddr_t eaddr, int ttesz, caddr_t *eaddrp)
3826 {
3827 	int hmeshift;
3828 	hmeblk_tag hblktag;
3829 	struct hmehash_bucket *hmebp;
3830 	struct hme_blk *hmeblkp;
3831 	struct hme_blk *pr_hblk;
3832 	struct hme_blk *list = NULL;
3833 
3834 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3835 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3836 	ASSERT(ttesz >= HBLK_MIN_TTESZ);
3837 
3838 	hmeshift = HME_HASH_SHIFT(ttesz);
3839 	hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3840 	hblktag.htag_rehash = ttesz;
3841 	hblktag.htag_rid = rid;
3842 	hblktag.htag_id = srdp;
3843 	hmebp = HME_HASH_FUNCTION(srdp, addr, hmeshift);
3844 
3845 	SFMMU_HASH_LOCK(hmebp);
3846 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
3847 	if (hmeblkp != NULL) {
3848 		ASSERT(hmeblkp->hblk_shared);
3849 		ASSERT(!hmeblkp->hblk_lckcnt);
3850 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
3851 			*eaddrp = sfmmu_hblk_unload(NULL, hmeblkp, addr,
3852 			    eaddr, NULL, HAT_UNLOAD);
3853 			ASSERT(*eaddrp > addr);
3854 		}
3855 		ASSERT(!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt);
3856 		sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
3857 		    &list, 0);
3858 	}
3859 	SFMMU_HASH_UNLOCK(hmebp);
3860 	sfmmu_hblks_list_purge(&list, 0);
3861 }
3862 
3863 static void
3864 sfmmu_unload_hmeregion(sf_srd_t *srdp, sf_region_t *rgnp)
3865 {
3866 	int ttesz = rgnp->rgn_pgszc;
3867 	size_t rsz = rgnp->rgn_size;
3868 	caddr_t rsaddr = rgnp->rgn_saddr;
3869 	caddr_t readdr = rsaddr + rsz;
3870 	caddr_t rhsaddr;
3871 	caddr_t va;
3872 	uint_t rid = rgnp->rgn_id;
3873 	caddr_t cbsaddr;
3874 	caddr_t cbeaddr;
3875 	hat_rgn_cb_func_t rcbfunc;
3876 	ulong_t cnt;
3877 
3878 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
3879 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
3880 
3881 	ASSERT(IS_P2ALIGNED(rsaddr, TTEBYTES(ttesz)));
3882 	ASSERT(IS_P2ALIGNED(rsz, TTEBYTES(ttesz)));
3883 	if (ttesz < HBLK_MIN_TTESZ) {
3884 		ttesz = HBLK_MIN_TTESZ;
3885 		rhsaddr = (caddr_t)P2ALIGN((uintptr_t)rsaddr, HBLK_MIN_BYTES);
3886 	} else {
3887 		rhsaddr = rsaddr;
3888 	}
3889 
3890 	if ((rcbfunc = rgnp->rgn_cb_function) == NULL) {
3891 		rcbfunc = sfmmu_rgn_cb_noop;
3892 	}
3893 
3894 	while (ttesz >= HBLK_MIN_TTESZ) {
3895 		cbsaddr = rsaddr;
3896 		cbeaddr = rsaddr;
3897 		if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
3898 			ttesz--;
3899 			continue;
3900 		}
3901 		cnt = 0;
3902 		va = rsaddr;
3903 		while (va < readdr) {
3904 			ASSERT(va >= rhsaddr);
3905 			if (va != cbeaddr) {
3906 				if (cbeaddr != cbsaddr) {
3907 					ASSERT(cbeaddr > cbsaddr);
3908 					(*rcbfunc)(cbsaddr, cbeaddr,
3909 					    rsaddr, rsz, rgnp->rgn_obj,
3910 					    rgnp->rgn_objoff);
3911 				}
3912 				cbsaddr = va;
3913 				cbeaddr = va;
3914 			}
3915 			sfmmu_unload_hmeregion_va(srdp, rid, va, readdr,
3916 			    ttesz, &cbeaddr);
3917 			cnt++;
3918 			va = rhsaddr + (cnt << TTE_PAGE_SHIFT(ttesz));
3919 		}
3920 		if (cbeaddr != cbsaddr) {
3921 			ASSERT(cbeaddr > cbsaddr);
3922 			(*rcbfunc)(cbsaddr, cbeaddr, rsaddr,
3923 			    rsz, rgnp->rgn_obj,
3924 			    rgnp->rgn_objoff);
3925 		}
3926 		ttesz--;
3927 	}
3928 }
3929 
3930 /*
3931  * Release one hardware address translation lock on the given address range.
3932  */
3933 void
3934 hat_unlock(struct hat *sfmmup, caddr_t addr, size_t len)
3935 {
3936 	struct hmehash_bucket *hmebp;
3937 	hmeblk_tag hblktag;
3938 	int hmeshift, hashno = 1;
3939 	struct hme_blk *hmeblkp, *list = NULL;
3940 	caddr_t endaddr;
3941 
3942 	ASSERT(sfmmup != NULL);
3943 
3944 	ASSERT((sfmmup == ksfmmup) || AS_LOCK_HELD(sfmmup->sfmmu_as));
3945 	ASSERT((len & MMU_PAGEOFFSET) == 0);
3946 	endaddr = addr + len;
3947 	hblktag.htag_id = sfmmup;
3948 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
3949 
3950 	/*
3951 	 * Spitfire supports 4 page sizes.
3952 	 * Most pages are expected to be of the smallest page size (8K) and
3953 	 * these will not need to be rehashed. 64K pages also don't need to be
3954 	 * rehashed because an hmeblk spans 64K of address space. 512K pages
3955 	 * might need 1 rehash and and 4M pages might need 2 rehashes.
3956 	 */
3957 	while (addr < endaddr) {
3958 		hmeshift = HME_HASH_SHIFT(hashno);
3959 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3960 		hblktag.htag_rehash = hashno;
3961 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3962 
3963 		SFMMU_HASH_LOCK(hmebp);
3964 
3965 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
3966 		if (hmeblkp != NULL) {
3967 			ASSERT(!hmeblkp->hblk_shared);
3968 			/*
3969 			 * If we encounter a shadow hmeblk then
3970 			 * we know there are no valid hmeblks mapping
3971 			 * this address at this size or larger.
3972 			 * Just increment address by the smallest
3973 			 * page size.
3974 			 */
3975 			if (hmeblkp->hblk_shw_bit) {
3976 				addr += MMU_PAGESIZE;
3977 			} else {
3978 				addr = sfmmu_hblk_unlock(hmeblkp, addr,
3979 				    endaddr);
3980 			}
3981 			SFMMU_HASH_UNLOCK(hmebp);
3982 			hashno = 1;
3983 			continue;
3984 		}
3985 		SFMMU_HASH_UNLOCK(hmebp);
3986 
3987 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
3988 			/*
3989 			 * We have traversed the whole list and rehashed
3990 			 * if necessary without finding the address to unlock
3991 			 * which should never happen.
3992 			 */
3993 			panic("sfmmu_unlock: addr not found. "
3994 			    "addr %p hat %p", (void *)addr, (void *)sfmmup);
3995 		} else {
3996 			hashno++;
3997 		}
3998 	}
3999 
4000 	sfmmu_hblks_list_purge(&list, 0);
4001 }
4002 
4003 void
4004 hat_unlock_region(struct hat *sfmmup, caddr_t addr, size_t len,
4005     hat_region_cookie_t rcookie)
4006 {
4007 	sf_srd_t *srdp;
4008 	sf_region_t *rgnp;
4009 	int ttesz;
4010 	uint_t rid;
4011 	caddr_t eaddr;
4012 	caddr_t va;
4013 	int hmeshift;
4014 	hmeblk_tag hblktag;
4015 	struct hmehash_bucket *hmebp;
4016 	struct hme_blk *hmeblkp;
4017 	struct hme_blk *pr_hblk;
4018 	struct hme_blk *list;
4019 
4020 	if (rcookie == HAT_INVALID_REGION_COOKIE) {
4021 		hat_unlock(sfmmup, addr, len);
4022 		return;
4023 	}
4024 
4025 	ASSERT(sfmmup != NULL);
4026 	ASSERT(sfmmup != ksfmmup);
4027 
4028 	srdp = sfmmup->sfmmu_srdp;
4029 	rid = (uint_t)((uint64_t)rcookie);
4030 	VERIFY3U(rid, <, SFMMU_MAX_HME_REGIONS);
4031 	eaddr = addr + len;
4032 	va = addr;
4033 	list = NULL;
4034 	rgnp = srdp->srd_hmergnp[rid];
4035 	SFMMU_VALIDATE_HMERID(sfmmup, rid, addr, len);
4036 
4037 	ASSERT(IS_P2ALIGNED(addr, TTEBYTES(rgnp->rgn_pgszc)));
4038 	ASSERT(IS_P2ALIGNED(len, TTEBYTES(rgnp->rgn_pgszc)));
4039 	if (rgnp->rgn_pgszc < HBLK_MIN_TTESZ) {
4040 		ttesz = HBLK_MIN_TTESZ;
4041 	} else {
4042 		ttesz = rgnp->rgn_pgszc;
4043 	}
4044 	while (va < eaddr) {
4045 		while (ttesz < rgnp->rgn_pgszc &&
4046 		    IS_P2ALIGNED(va, TTEBYTES(ttesz + 1))) {
4047 			ttesz++;
4048 		}
4049 		while (ttesz >= HBLK_MIN_TTESZ) {
4050 			if (!(rgnp->rgn_hmeflags & (1 << ttesz))) {
4051 				ttesz--;
4052 				continue;
4053 			}
4054 			hmeshift = HME_HASH_SHIFT(ttesz);
4055 			hblktag.htag_bspage = HME_HASH_BSPAGE(va, hmeshift);
4056 			hblktag.htag_rehash = ttesz;
4057 			hblktag.htag_rid = rid;
4058 			hblktag.htag_id = srdp;
4059 			hmebp = HME_HASH_FUNCTION(srdp, va, hmeshift);
4060 			SFMMU_HASH_LOCK(hmebp);
4061 			HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk,
4062 			    &list);
4063 			if (hmeblkp == NULL) {
4064 				SFMMU_HASH_UNLOCK(hmebp);
4065 				ttesz--;
4066 				continue;
4067 			}
4068 			ASSERT(hmeblkp->hblk_shared);
4069 			va = sfmmu_hblk_unlock(hmeblkp, va, eaddr);
4070 			ASSERT(va >= eaddr ||
4071 			    IS_P2ALIGNED((uintptr_t)va, TTEBYTES(ttesz)));
4072 			SFMMU_HASH_UNLOCK(hmebp);
4073 			break;
4074 		}
4075 		if (ttesz < HBLK_MIN_TTESZ) {
4076 			panic("hat_unlock_region: addr not found "
4077 			    "addr %p hat %p", (void *)va, (void *)sfmmup);
4078 		}
4079 	}
4080 	sfmmu_hblks_list_purge(&list, 0);
4081 }
4082 
4083 /*
4084  * Function to unlock a range of addresses in an hmeblk.  It returns the
4085  * next address that needs to be unlocked.
4086  * Should be called with the hash lock held.
4087  */
4088 static caddr_t
4089 sfmmu_hblk_unlock(struct hme_blk *hmeblkp, caddr_t addr, caddr_t endaddr)
4090 {
4091 	struct sf_hment *sfhme;
4092 	tte_t tteold, ttemod;
4093 	int ttesz, ret;
4094 
4095 	ASSERT(in_hblk_range(hmeblkp, addr));
4096 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4097 
4098 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4099 	ttesz = get_hblk_ttesz(hmeblkp);
4100 
4101 	HBLKTOHME(sfhme, hmeblkp, addr);
4102 	while (addr < endaddr) {
4103 readtte:
4104 		sfmmu_copytte(&sfhme->hme_tte, &tteold);
4105 		if (TTE_IS_VALID(&tteold)) {
4106 
4107 			ttemod = tteold;
4108 
4109 			ret = sfmmu_modifytte_try(&tteold, &ttemod,
4110 			    &sfhme->hme_tte);
4111 
4112 			if (ret < 0)
4113 				goto readtte;
4114 
4115 			if (hmeblkp->hblk_lckcnt == 0)
4116 				panic("zero hblk lckcnt");
4117 
4118 			if (((uintptr_t)addr + TTEBYTES(ttesz)) >
4119 			    (uintptr_t)endaddr)
4120 				panic("can't unlock large tte");
4121 
4122 			ASSERT(hmeblkp->hblk_lckcnt > 0);
4123 			atomic_dec_32(&hmeblkp->hblk_lckcnt);
4124 			HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
4125 		} else {
4126 			panic("sfmmu_hblk_unlock: invalid tte");
4127 		}
4128 		addr += TTEBYTES(ttesz);
4129 		sfhme++;
4130 	}
4131 	return (addr);
4132 }
4133 
4134 /*
4135  * Physical Address Mapping Framework
4136  *
4137  * General rules:
4138  *
4139  * (1) Applies only to seg_kmem memory pages. To make things easier,
4140  *     seg_kpm addresses are also accepted by the routines, but nothing
4141  *     is done with them since by definition their PA mappings are static.
4142  * (2) hat_add_callback() may only be called while holding the page lock
4143  *     SE_SHARED or SE_EXCL of the underlying page (e.g., as_pagelock()),
4144  *     or passing HAC_PAGELOCK flag.
4145  * (3) prehandler() and posthandler() may not call hat_add_callback() or
4146  *     hat_delete_callback(), nor should they allocate memory. Post quiesce
4147  *     callbacks may not sleep or acquire adaptive mutex locks.
4148  * (4) Either prehandler() or posthandler() (but not both) may be specified
4149  *     as being NULL.  Specifying an errhandler() is optional.
4150  *
4151  * Details of using the framework:
4152  *
4153  * registering a callback (hat_register_callback())
4154  *
4155  *	Pass prehandler, posthandler, errhandler addresses
4156  *	as described below. If capture_cpus argument is nonzero,
4157  *	suspend callback to the prehandler will occur with CPUs
4158  *	captured and executing xc_loop() and CPUs will remain
4159  *	captured until after the posthandler suspend callback
4160  *	occurs.
4161  *
4162  * adding a callback (hat_add_callback())
4163  *
4164  *      as_pagelock();
4165  *	hat_add_callback();
4166  *      save returned pfn in private data structures or program registers;
4167  *      as_pageunlock();
4168  *
4169  * prehandler()
4170  *
4171  *	Stop all accesses by physical address to this memory page.
4172  *	Called twice: the first, PRESUSPEND, is a context safe to acquire
4173  *	adaptive locks. The second, SUSPEND, is called at high PIL with
4174  *	CPUs captured so adaptive locks may NOT be acquired (and all spin
4175  *	locks must be XCALL_PIL or higher locks).
4176  *
4177  *	May return the following errors:
4178  *		EIO:	A fatal error has occurred. This will result in panic.
4179  *		EAGAIN:	The page cannot be suspended. This will fail the
4180  *			relocation.
4181  *		0:	Success.
4182  *
4183  * posthandler()
4184  *
4185  *      Save new pfn in private data structures or program registers;
4186  *	not allowed to fail (non-zero return values will result in panic).
4187  *
4188  * errhandler()
4189  *
4190  *	called when an error occurs related to the callback.  Currently
4191  *	the only such error is HAT_CB_ERR_LEAKED which indicates that
4192  *	a page is being freed, but there are still outstanding callback(s)
4193  *	registered on the page.
4194  *
4195  * removing a callback (hat_delete_callback(); e.g., prior to freeing memory)
4196  *
4197  *	stop using physical address
4198  *	hat_delete_callback();
4199  *
4200  */
4201 
4202 /*
4203  * Register a callback class.  Each subsystem should do this once and
4204  * cache the id_t returned for use in setting up and tearing down callbacks.
4205  *
4206  * There is no facility for removing callback IDs once they are created;
4207  * the "key" should be unique for each module, so in case a module is unloaded
4208  * and subsequently re-loaded, we can recycle the module's previous entry.
4209  */
4210 id_t
4211 hat_register_callback(int key,
4212     int (*prehandler)(caddr_t, uint_t, uint_t, void *),
4213     int (*posthandler)(caddr_t, uint_t, uint_t, void *, pfn_t),
4214     int (*errhandler)(caddr_t, uint_t, uint_t, void *),
4215     int capture_cpus)
4216 {
4217 	id_t id;
4218 
4219 	/*
4220 	 * Search the table for a pre-existing callback associated with
4221 	 * the identifier "key".  If one exists, we re-use that entry in
4222 	 * the table for this instance, otherwise we assign the next
4223 	 * available table slot.
4224 	 */
4225 	for (id = 0; id < sfmmu_max_cb_id; id++) {
4226 		if (sfmmu_cb_table[id].key == key)
4227 			break;
4228 	}
4229 
4230 	if (id == sfmmu_max_cb_id) {
4231 		id = sfmmu_cb_nextid++;
4232 		if (id >= sfmmu_max_cb_id)
4233 			panic("hat_register_callback: out of callback IDs");
4234 	}
4235 
4236 	ASSERT(prehandler != NULL || posthandler != NULL);
4237 
4238 	sfmmu_cb_table[id].key = key;
4239 	sfmmu_cb_table[id].prehandler = prehandler;
4240 	sfmmu_cb_table[id].posthandler = posthandler;
4241 	sfmmu_cb_table[id].errhandler = errhandler;
4242 	sfmmu_cb_table[id].capture_cpus = capture_cpus;
4243 
4244 	return (id);
4245 }
4246 
4247 #define	HAC_COOKIE_NONE	(void *)-1
4248 
4249 /*
4250  * Add relocation callbacks to the specified addr/len which will be called
4251  * when relocating the associated page. See the description of pre and
4252  * posthandler above for more details.
4253  *
4254  * If HAC_PAGELOCK is included in flags, the underlying memory page is
4255  * locked internally so the caller must be able to deal with the callback
4256  * running even before this function has returned.  If HAC_PAGELOCK is not
4257  * set, it is assumed that the underlying memory pages are locked.
4258  *
4259  * Since the caller must track the individual page boundaries anyway,
4260  * we only allow a callback to be added to a single page (large
4261  * or small).  Thus [addr, addr + len) MUST be contained within a single
4262  * page.
4263  *
4264  * Registering multiple callbacks on the same [addr, addr+len) is supported,
4265  * _provided_that_ a unique parameter is specified for each callback.
4266  * If multiple callbacks are registered on the same range the callback will
4267  * be invoked with each unique parameter. Registering the same callback with
4268  * the same argument more than once will result in corrupted kernel state.
4269  *
4270  * Returns the pfn of the underlying kernel page in *rpfn
4271  * on success, or PFN_INVALID on failure.
4272  *
4273  * cookiep (if passed) provides storage space for an opaque cookie
4274  * to return later to hat_delete_callback(). This cookie makes the callback
4275  * deletion significantly quicker by avoiding a potentially lengthy hash
4276  * search.
4277  *
4278  * Returns values:
4279  *    0:      success
4280  *    ENOMEM: memory allocation failure (e.g. flags was passed as HAC_NOSLEEP)
4281  *    EINVAL: callback ID is not valid
4282  *    ENXIO:  ["vaddr", "vaddr" + len) is not mapped in the kernel's address
4283  *            space
4284  *    ERANGE: ["vaddr", "vaddr" + len) crosses a page boundary
4285  */
4286 int
4287 hat_add_callback(id_t callback_id, caddr_t vaddr, uint_t len, uint_t flags,
4288     void *pvt, pfn_t *rpfn, void **cookiep)
4289 {
4290 	struct		hmehash_bucket *hmebp;
4291 	hmeblk_tag	hblktag;
4292 	struct hme_blk	*hmeblkp;
4293 	int		hmeshift, hashno;
4294 	caddr_t		saddr, eaddr, baseaddr;
4295 	struct pa_hment *pahmep;
4296 	struct sf_hment *sfhmep, *osfhmep;
4297 	kmutex_t	*pml;
4298 	tte_t		tte;
4299 	page_t		*pp;
4300 	vnode_t		*vp;
4301 	u_offset_t	off;
4302 	pfn_t		pfn;
4303 	int		kmflags = (flags & HAC_SLEEP)? KM_SLEEP : KM_NOSLEEP;
4304 	int		locked = 0;
4305 
4306 	/*
4307 	 * For KPM mappings, just return the physical address since we
4308 	 * don't need to register any callbacks.
4309 	 */
4310 	if (IS_KPM_ADDR(vaddr)) {
4311 		uint64_t paddr;
4312 		SFMMU_KPM_VTOP(vaddr, paddr);
4313 		*rpfn = btop(paddr);
4314 		if (cookiep != NULL)
4315 			*cookiep = HAC_COOKIE_NONE;
4316 		return (0);
4317 	}
4318 
4319 	if (callback_id < (id_t)0 || callback_id >= sfmmu_cb_nextid) {
4320 		*rpfn = PFN_INVALID;
4321 		return (EINVAL);
4322 	}
4323 
4324 	if ((pahmep = kmem_cache_alloc(pa_hment_cache, kmflags)) == NULL) {
4325 		*rpfn = PFN_INVALID;
4326 		return (ENOMEM);
4327 	}
4328 
4329 	sfhmep = &pahmep->sfment;
4330 
4331 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4332 	eaddr = saddr + len;
4333 
4334 rehash:
4335 	/* Find the mapping(s) for this page */
4336 	for (hashno = TTE64K, hmeblkp = NULL;
4337 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4338 	    hashno++) {
4339 		hmeshift = HME_HASH_SHIFT(hashno);
4340 		hblktag.htag_id = ksfmmup;
4341 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4342 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4343 		hblktag.htag_rehash = hashno;
4344 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4345 
4346 		SFMMU_HASH_LOCK(hmebp);
4347 
4348 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4349 
4350 		if (hmeblkp == NULL)
4351 			SFMMU_HASH_UNLOCK(hmebp);
4352 	}
4353 
4354 	if (hmeblkp == NULL) {
4355 		kmem_cache_free(pa_hment_cache, pahmep);
4356 		*rpfn = PFN_INVALID;
4357 		return (ENXIO);
4358 	}
4359 
4360 	ASSERT(!hmeblkp->hblk_shared);
4361 
4362 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4363 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4364 
4365 	if (!TTE_IS_VALID(&tte)) {
4366 		SFMMU_HASH_UNLOCK(hmebp);
4367 		kmem_cache_free(pa_hment_cache, pahmep);
4368 		*rpfn = PFN_INVALID;
4369 		return (ENXIO);
4370 	}
4371 
4372 	/*
4373 	 * Make sure the boundaries for the callback fall within this
4374 	 * single mapping.
4375 	 */
4376 	baseaddr = (caddr_t)get_hblk_base(hmeblkp);
4377 	ASSERT(saddr >= baseaddr);
4378 	if (eaddr > saddr + TTEBYTES(TTE_CSZ(&tte))) {
4379 		SFMMU_HASH_UNLOCK(hmebp);
4380 		kmem_cache_free(pa_hment_cache, pahmep);
4381 		*rpfn = PFN_INVALID;
4382 		return (ERANGE);
4383 	}
4384 
4385 	pfn = sfmmu_ttetopfn(&tte, vaddr);
4386 
4387 	/*
4388 	 * The pfn may not have a page_t underneath in which case we
4389 	 * just return it. This can happen if we are doing I/O to a
4390 	 * static portion of the kernel's address space, for instance.
4391 	 */
4392 	pp = osfhmep->hme_page;
4393 	if (pp == NULL) {
4394 		SFMMU_HASH_UNLOCK(hmebp);
4395 		kmem_cache_free(pa_hment_cache, pahmep);
4396 		*rpfn = pfn;
4397 		if (cookiep)
4398 			*cookiep = HAC_COOKIE_NONE;
4399 		return (0);
4400 	}
4401 	ASSERT(pp == PP_PAGEROOT(pp));
4402 
4403 	vp = pp->p_vnode;
4404 	off = pp->p_offset;
4405 
4406 	pml = sfmmu_mlist_enter(pp);
4407 
4408 	if (flags & HAC_PAGELOCK) {
4409 		if (!page_trylock(pp, SE_SHARED)) {
4410 			/*
4411 			 * Somebody is holding SE_EXCL lock. Might
4412 			 * even be hat_page_relocate(). Drop all
4413 			 * our locks, lookup the page in &kvp, and
4414 			 * retry. If it doesn't exist in &kvp and &zvp,
4415 			 * then we must be dealing with a kernel mapped
4416 			 * page which doesn't actually belong to
4417 			 * segkmem so we punt.
4418 			 */
4419 			sfmmu_mlist_exit(pml);
4420 			SFMMU_HASH_UNLOCK(hmebp);
4421 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4422 
4423 			/* check zvp before giving up */
4424 			if (pp == NULL)
4425 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4426 				    SE_SHARED);
4427 
4428 			/* Okay, we didn't find it, give up */
4429 			if (pp == NULL) {
4430 				kmem_cache_free(pa_hment_cache, pahmep);
4431 				*rpfn = pfn;
4432 				if (cookiep)
4433 					*cookiep = HAC_COOKIE_NONE;
4434 				return (0);
4435 			}
4436 			page_unlock(pp);
4437 			goto rehash;
4438 		}
4439 		locked = 1;
4440 	}
4441 
4442 	if (!PAGE_LOCKED(pp) && !panicstr)
4443 		panic("hat_add_callback: page 0x%p not locked", (void *)pp);
4444 
4445 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4446 	    pp->p_offset != off) {
4447 		/*
4448 		 * The page moved before we got our hands on it.  Drop
4449 		 * all the locks and try again.
4450 		 */
4451 		ASSERT((flags & HAC_PAGELOCK) != 0);
4452 		sfmmu_mlist_exit(pml);
4453 		SFMMU_HASH_UNLOCK(hmebp);
4454 		page_unlock(pp);
4455 		locked = 0;
4456 		goto rehash;
4457 	}
4458 
4459 	if (!VN_ISKAS(vp)) {
4460 		/*
4461 		 * This is not a segkmem page but another page which
4462 		 * has been kernel mapped. It had better have at least
4463 		 * a share lock on it. Return the pfn.
4464 		 */
4465 		sfmmu_mlist_exit(pml);
4466 		SFMMU_HASH_UNLOCK(hmebp);
4467 		if (locked)
4468 			page_unlock(pp);
4469 		kmem_cache_free(pa_hment_cache, pahmep);
4470 		ASSERT(PAGE_LOCKED(pp));
4471 		*rpfn = pfn;
4472 		if (cookiep)
4473 			*cookiep = HAC_COOKIE_NONE;
4474 		return (0);
4475 	}
4476 
4477 	/*
4478 	 * Setup this pa_hment and link its embedded dummy sf_hment into
4479 	 * the mapping list.
4480 	 */
4481 	pp->p_share++;
4482 	pahmep->cb_id = callback_id;
4483 	pahmep->addr = vaddr;
4484 	pahmep->len = len;
4485 	pahmep->refcnt = 1;
4486 	pahmep->flags = 0;
4487 	pahmep->pvt = pvt;
4488 
4489 	sfhmep->hme_tte.ll = 0;
4490 	sfhmep->hme_data = pahmep;
4491 	sfhmep->hme_prev = osfhmep;
4492 	sfhmep->hme_next = osfhmep->hme_next;
4493 
4494 	if (osfhmep->hme_next)
4495 		osfhmep->hme_next->hme_prev = sfhmep;
4496 
4497 	osfhmep->hme_next = sfhmep;
4498 
4499 	sfmmu_mlist_exit(pml);
4500 	SFMMU_HASH_UNLOCK(hmebp);
4501 
4502 	if (locked)
4503 		page_unlock(pp);
4504 
4505 	*rpfn = pfn;
4506 	if (cookiep)
4507 		*cookiep = (void *)pahmep;
4508 
4509 	return (0);
4510 }
4511 
4512 /*
4513  * Remove the relocation callbacks from the specified addr/len.
4514  */
4515 void
4516 hat_delete_callback(caddr_t vaddr, uint_t len, void *pvt, uint_t flags,
4517     void *cookie)
4518 {
4519 	struct		hmehash_bucket *hmebp;
4520 	hmeblk_tag	hblktag;
4521 	struct hme_blk	*hmeblkp;
4522 	int		hmeshift, hashno;
4523 	caddr_t		saddr;
4524 	struct pa_hment	*pahmep;
4525 	struct sf_hment	*sfhmep, *osfhmep;
4526 	kmutex_t	*pml;
4527 	tte_t		tte;
4528 	page_t		*pp;
4529 	vnode_t		*vp;
4530 	u_offset_t	off;
4531 	int		locked = 0;
4532 
4533 	/*
4534 	 * If the cookie is HAC_COOKIE_NONE then there is no pa_hment to
4535 	 * remove so just return.
4536 	 */
4537 	if (cookie == HAC_COOKIE_NONE || IS_KPM_ADDR(vaddr))
4538 		return;
4539 
4540 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
4541 
4542 rehash:
4543 	/* Find the mapping(s) for this page */
4544 	for (hashno = TTE64K, hmeblkp = NULL;
4545 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
4546 	    hashno++) {
4547 		hmeshift = HME_HASH_SHIFT(hashno);
4548 		hblktag.htag_id = ksfmmup;
4549 		hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4550 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
4551 		hblktag.htag_rehash = hashno;
4552 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
4553 
4554 		SFMMU_HASH_LOCK(hmebp);
4555 
4556 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
4557 
4558 		if (hmeblkp == NULL)
4559 			SFMMU_HASH_UNLOCK(hmebp);
4560 	}
4561 
4562 	if (hmeblkp == NULL)
4563 		return;
4564 
4565 	ASSERT(!hmeblkp->hblk_shared);
4566 
4567 	HBLKTOHME(osfhmep, hmeblkp, saddr);
4568 
4569 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
4570 	if (!TTE_IS_VALID(&tte)) {
4571 		SFMMU_HASH_UNLOCK(hmebp);
4572 		return;
4573 	}
4574 
4575 	pp = osfhmep->hme_page;
4576 	if (pp == NULL) {
4577 		SFMMU_HASH_UNLOCK(hmebp);
4578 		ASSERT(cookie == NULL);
4579 		return;
4580 	}
4581 
4582 	vp = pp->p_vnode;
4583 	off = pp->p_offset;
4584 
4585 	pml = sfmmu_mlist_enter(pp);
4586 
4587 	if (flags & HAC_PAGELOCK) {
4588 		if (!page_trylock(pp, SE_SHARED)) {
4589 			/*
4590 			 * Somebody is holding SE_EXCL lock. Might
4591 			 * even be hat_page_relocate(). Drop all
4592 			 * our locks, lookup the page in &kvp, and
4593 			 * retry. If it doesn't exist in &kvp and &zvp,
4594 			 * then we must be dealing with a kernel mapped
4595 			 * page which doesn't actually belong to
4596 			 * segkmem so we punt.
4597 			 */
4598 			sfmmu_mlist_exit(pml);
4599 			SFMMU_HASH_UNLOCK(hmebp);
4600 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
4601 			/* check zvp before giving up */
4602 			if (pp == NULL)
4603 				pp = page_lookup(&zvp, (u_offset_t)saddr,
4604 				    SE_SHARED);
4605 
4606 			if (pp == NULL) {
4607 				ASSERT(cookie == NULL);
4608 				return;
4609 			}
4610 			page_unlock(pp);
4611 			goto rehash;
4612 		}
4613 		locked = 1;
4614 	}
4615 
4616 	ASSERT(PAGE_LOCKED(pp));
4617 
4618 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
4619 	    pp->p_offset != off) {
4620 		/*
4621 		 * The page moved before we got our hands on it.  Drop
4622 		 * all the locks and try again.
4623 		 */
4624 		ASSERT((flags & HAC_PAGELOCK) != 0);
4625 		sfmmu_mlist_exit(pml);
4626 		SFMMU_HASH_UNLOCK(hmebp);
4627 		page_unlock(pp);
4628 		locked = 0;
4629 		goto rehash;
4630 	}
4631 
4632 	if (!VN_ISKAS(vp)) {
4633 		/*
4634 		 * This is not a segkmem page but another page which
4635 		 * has been kernel mapped.
4636 		 */
4637 		sfmmu_mlist_exit(pml);
4638 		SFMMU_HASH_UNLOCK(hmebp);
4639 		if (locked)
4640 			page_unlock(pp);
4641 		ASSERT(cookie == NULL);
4642 		return;
4643 	}
4644 
4645 	if (cookie != NULL) {
4646 		pahmep = (struct pa_hment *)cookie;
4647 		sfhmep = &pahmep->sfment;
4648 	} else {
4649 		for (sfhmep = pp->p_mapping; sfhmep != NULL;
4650 		    sfhmep = sfhmep->hme_next) {
4651 
4652 			/*
4653 			 * skip va<->pa mappings
4654 			 */
4655 			if (!IS_PAHME(sfhmep))
4656 				continue;
4657 
4658 			pahmep = sfhmep->hme_data;
4659 			ASSERT(pahmep != NULL);
4660 
4661 			/*
4662 			 * if pa_hment matches, remove it
4663 			 */
4664 			if ((pahmep->pvt == pvt) &&
4665 			    (pahmep->addr == vaddr) &&
4666 			    (pahmep->len == len)) {
4667 				break;
4668 			}
4669 		}
4670 	}
4671 
4672 	if (sfhmep == NULL) {
4673 		if (!panicstr) {
4674 			panic("hat_delete_callback: pa_hment not found, pp %p",
4675 			    (void *)pp);
4676 		}
4677 		return;
4678 	}
4679 
4680 	/*
4681 	 * Note: at this point a valid kernel mapping must still be
4682 	 * present on this page.
4683 	 */
4684 	pp->p_share--;
4685 	if (pp->p_share <= 0)
4686 		panic("hat_delete_callback: zero p_share");
4687 
4688 	if (--pahmep->refcnt == 0) {
4689 		if (pahmep->flags != 0)
4690 			panic("hat_delete_callback: pa_hment is busy");
4691 
4692 		/*
4693 		 * Remove sfhmep from the mapping list for the page.
4694 		 */
4695 		if (sfhmep->hme_prev) {
4696 			sfhmep->hme_prev->hme_next = sfhmep->hme_next;
4697 		} else {
4698 			pp->p_mapping = sfhmep->hme_next;
4699 		}
4700 
4701 		if (sfhmep->hme_next)
4702 			sfhmep->hme_next->hme_prev = sfhmep->hme_prev;
4703 
4704 		sfmmu_mlist_exit(pml);
4705 		SFMMU_HASH_UNLOCK(hmebp);
4706 
4707 		if (locked)
4708 			page_unlock(pp);
4709 
4710 		kmem_cache_free(pa_hment_cache, pahmep);
4711 		return;
4712 	}
4713 
4714 	sfmmu_mlist_exit(pml);
4715 	SFMMU_HASH_UNLOCK(hmebp);
4716 	if (locked)
4717 		page_unlock(pp);
4718 }
4719 
4720 /*
4721  * hat_probe returns 1 if the translation for the address 'addr' is
4722  * loaded, zero otherwise.
4723  *
4724  * hat_probe should be used only for advisorary purposes because it may
4725  * occasionally return the wrong value. The implementation must guarantee that
4726  * returning the wrong value is a very rare event. hat_probe is used
4727  * to implement optimizations in the segment drivers.
4728  *
4729  */
4730 int
4731 hat_probe(struct hat *sfmmup, caddr_t addr)
4732 {
4733 	pfn_t pfn;
4734 	tte_t tte;
4735 
4736 	ASSERT(sfmmup != NULL);
4737 
4738 	ASSERT((sfmmup == ksfmmup) || AS_LOCK_HELD(sfmmup->sfmmu_as));
4739 
4740 	if (sfmmup == ksfmmup) {
4741 		while ((pfn = sfmmu_vatopfn(addr, sfmmup, &tte))
4742 		    == PFN_SUSPENDED) {
4743 			sfmmu_vatopfn_suspended(addr, sfmmup, &tte);
4744 		}
4745 	} else {
4746 		pfn = sfmmu_uvatopfn(addr, sfmmup, NULL);
4747 	}
4748 
4749 	if (pfn != PFN_INVALID)
4750 		return (1);
4751 	else
4752 		return (0);
4753 }
4754 
4755 ssize_t
4756 hat_getpagesize(struct hat *sfmmup, caddr_t addr)
4757 {
4758 	tte_t tte;
4759 
4760 	if (sfmmup == ksfmmup) {
4761 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4762 			return (-1);
4763 		}
4764 	} else {
4765 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4766 			return (-1);
4767 		}
4768 	}
4769 
4770 	ASSERT(TTE_IS_VALID(&tte));
4771 	return (TTEBYTES(TTE_CSZ(&tte)));
4772 }
4773 
4774 uint_t
4775 hat_getattr(struct hat *sfmmup, caddr_t addr, uint_t *attr)
4776 {
4777 	tte_t tte;
4778 
4779 	if (sfmmup == ksfmmup) {
4780 		if (sfmmu_vatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4781 			tte.ll = 0;
4782 		}
4783 	} else {
4784 		if (sfmmu_uvatopfn(addr, sfmmup, &tte) == PFN_INVALID) {
4785 			tte.ll = 0;
4786 		}
4787 	}
4788 	if (TTE_IS_VALID(&tte)) {
4789 		*attr = sfmmu_ptov_attr(&tte);
4790 		return (0);
4791 	}
4792 	*attr = 0;
4793 	return ((uint_t)0xffffffff);
4794 }
4795 
4796 /*
4797  * Enables more attributes on specified address range (ie. logical OR)
4798  */
4799 void
4800 hat_setattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4801 {
4802 	ASSERT(hat->sfmmu_as != NULL);
4803 
4804 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_SETATTR);
4805 }
4806 
4807 /*
4808  * Assigns attributes to the specified address range.  All the attributes
4809  * are specified.
4810  */
4811 void
4812 hat_chgattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4813 {
4814 	ASSERT(hat->sfmmu_as != NULL);
4815 
4816 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CHGATTR);
4817 }
4818 
4819 /*
4820  * Remove attributes on the specified address range (ie. loginal NAND)
4821  */
4822 void
4823 hat_clrattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4824 {
4825 	ASSERT(hat->sfmmu_as != NULL);
4826 
4827 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CLRATTR);
4828 }
4829 
4830 /*
4831  * Change attributes on an address range to that specified by attr and mode.
4832  */
4833 static void
4834 sfmmu_chgattr(struct hat *sfmmup, caddr_t addr, size_t len, uint_t attr,
4835     int mode)
4836 {
4837 	struct hmehash_bucket *hmebp;
4838 	hmeblk_tag hblktag;
4839 	int hmeshift, hashno = 1;
4840 	struct hme_blk *hmeblkp, *list = NULL;
4841 	caddr_t endaddr;
4842 	cpuset_t cpuset;
4843 	demap_range_t dmr;
4844 
4845 	CPUSET_ZERO(cpuset);
4846 
4847 	ASSERT((sfmmup == ksfmmup) || AS_LOCK_HELD(sfmmup->sfmmu_as));
4848 	ASSERT((len & MMU_PAGEOFFSET) == 0);
4849 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
4850 
4851 	if ((attr & PROT_USER) && (mode != SFMMU_CLRATTR) &&
4852 	    ((addr + len) > (caddr_t)USERLIMIT)) {
4853 		panic("user addr %p in kernel space",
4854 		    (void *)addr);
4855 	}
4856 
4857 	endaddr = addr + len;
4858 	hblktag.htag_id = sfmmup;
4859 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
4860 	DEMAP_RANGE_INIT(sfmmup, &dmr);
4861 
4862 	while (addr < endaddr) {
4863 		hmeshift = HME_HASH_SHIFT(hashno);
4864 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
4865 		hblktag.htag_rehash = hashno;
4866 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
4867 
4868 		SFMMU_HASH_LOCK(hmebp);
4869 
4870 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
4871 		if (hmeblkp != NULL) {
4872 			ASSERT(!hmeblkp->hblk_shared);
4873 			/*
4874 			 * We've encountered a shadow hmeblk so skip the range
4875 			 * of the next smaller mapping size.
4876 			 */
4877 			if (hmeblkp->hblk_shw_bit) {
4878 				ASSERT(sfmmup != ksfmmup);
4879 				ASSERT(hashno > 1);
4880 				addr = (caddr_t)P2END((uintptr_t)addr,
4881 				    TTEBYTES(hashno - 1));
4882 			} else {
4883 				addr = sfmmu_hblk_chgattr(sfmmup,
4884 				    hmeblkp, addr, endaddr, &dmr, attr, mode);
4885 			}
4886 			SFMMU_HASH_UNLOCK(hmebp);
4887 			hashno = 1;
4888 			continue;
4889 		}
4890 		SFMMU_HASH_UNLOCK(hmebp);
4891 
4892 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
4893 			/*
4894 			 * We have traversed the whole list and rehashed
4895 			 * if necessary without finding the address to chgattr.
4896 			 * This is ok, so we increment the address by the
4897 			 * smallest hmeblk range for kernel mappings or for
4898 			 * user mappings with no large pages, and the largest
4899 			 * hmeblk range, to account for shadow hmeblks, for
4900 			 * user mappings with large pages and continue.
4901 			 */
4902 			if (sfmmup == ksfmmup)
4903 				addr = (caddr_t)P2END((uintptr_t)addr,
4904 				    TTEBYTES(1));
4905 			else
4906 				addr = (caddr_t)P2END((uintptr_t)addr,
4907 				    TTEBYTES(hashno));
4908 			hashno = 1;
4909 		} else {
4910 			hashno++;
4911 		}
4912 	}
4913 
4914 	sfmmu_hblks_list_purge(&list, 0);
4915 	DEMAP_RANGE_FLUSH(&dmr);
4916 	cpuset = sfmmup->sfmmu_cpusran;
4917 	xt_sync(cpuset);
4918 }
4919 
4920 /*
4921  * This function chgattr on a range of addresses in an hmeblk.  It returns the
4922  * next addres that needs to be chgattr.
4923  * It should be called with the hash lock held.
4924  * XXX It should be possible to optimize chgattr by not flushing every time but
4925  * on the other hand:
4926  * 1. do one flush crosscall.
4927  * 2. only flush if we are increasing permissions (make sure this will work)
4928  */
4929 static caddr_t
4930 sfmmu_hblk_chgattr(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
4931     caddr_t endaddr, demap_range_t *dmrp, uint_t attr, int mode)
4932 {
4933 	tte_t tte, tteattr, tteflags, ttemod;
4934 	struct sf_hment *sfhmep;
4935 	int ttesz;
4936 	struct page *pp = NULL;
4937 	kmutex_t *pml, *pmtx;
4938 	int ret;
4939 	int use_demap_range;
4940 #if defined(SF_ERRATA_57)
4941 	int check_exec;
4942 #endif
4943 
4944 	ASSERT(in_hblk_range(hmeblkp, addr));
4945 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4946 	ASSERT(!hmeblkp->hblk_shared);
4947 
4948 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4949 	ttesz = get_hblk_ttesz(hmeblkp);
4950 
4951 	/*
4952 	 * Flush the current demap region if addresses have been
4953 	 * skipped or the page size doesn't match.
4954 	 */
4955 	use_demap_range = (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp));
4956 	if (use_demap_range) {
4957 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
4958 	} else if (dmrp != NULL) {
4959 		DEMAP_RANGE_FLUSH(dmrp);
4960 	}
4961 
4962 	tteattr.ll = sfmmu_vtop_attr(attr, mode, &tteflags);
4963 #if defined(SF_ERRATA_57)
4964 	check_exec = (sfmmup != ksfmmup) &&
4965 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
4966 	    TTE_IS_EXECUTABLE(&tteattr);
4967 #endif
4968 	HBLKTOHME(sfhmep, hmeblkp, addr);
4969 	while (addr < endaddr) {
4970 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
4971 		if (TTE_IS_VALID(&tte)) {
4972 			if ((tte.ll & tteflags.ll) == tteattr.ll) {
4973 				/*
4974 				 * if the new attr is the same as old
4975 				 * continue
4976 				 */
4977 				goto next_addr;
4978 			}
4979 			if (!TTE_IS_WRITABLE(&tteattr)) {
4980 				/*
4981 				 * make sure we clear hw modify bit if we
4982 				 * removing write protections
4983 				 */
4984 				tteflags.tte_intlo |= TTE_HWWR_INT;
4985 			}
4986 
4987 			pml = NULL;
4988 			pp = sfhmep->hme_page;
4989 			if (pp) {
4990 				pml = sfmmu_mlist_enter(pp);
4991 			}
4992 
4993 			if (pp != sfhmep->hme_page) {
4994 				/*
4995 				 * tte must have been unloaded.
4996 				 */
4997 				ASSERT(pml);
4998 				sfmmu_mlist_exit(pml);
4999 				continue;
5000 			}
5001 
5002 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5003 
5004 			ttemod = tte;
5005 			ttemod.ll = (ttemod.ll & ~tteflags.ll) | tteattr.ll;
5006 			ASSERT(TTE_TO_TTEPFN(&ttemod) == TTE_TO_TTEPFN(&tte));
5007 
5008 #if defined(SF_ERRATA_57)
5009 			if (check_exec && addr < errata57_limit)
5010 				ttemod.tte_exec_perm = 0;
5011 #endif
5012 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5013 			    &sfhmep->hme_tte);
5014 
5015 			if (ret < 0) {
5016 				/* tte changed underneath us */
5017 				if (pml) {
5018 					sfmmu_mlist_exit(pml);
5019 				}
5020 				continue;
5021 			}
5022 
5023 			if (tteflags.tte_intlo & TTE_HWWR_INT) {
5024 				/*
5025 				 * need to sync if we are clearing modify bit.
5026 				 */
5027 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
5028 			}
5029 
5030 			if (pp && PP_ISRO(pp)) {
5031 				if (tteattr.tte_intlo & TTE_WRPRM_INT) {
5032 					pmtx = sfmmu_page_enter(pp);
5033 					PP_CLRRO(pp);
5034 					sfmmu_page_exit(pmtx);
5035 				}
5036 			}
5037 
5038 			if (ret > 0 && use_demap_range) {
5039 				DEMAP_RANGE_MARKPG(dmrp, addr);
5040 			} else if (ret > 0) {
5041 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
5042 			}
5043 
5044 			if (pml) {
5045 				sfmmu_mlist_exit(pml);
5046 			}
5047 		}
5048 next_addr:
5049 		addr += TTEBYTES(ttesz);
5050 		sfhmep++;
5051 		DEMAP_RANGE_NEXTPG(dmrp);
5052 	}
5053 	return (addr);
5054 }
5055 
5056 /*
5057  * This routine converts virtual attributes to physical ones.  It will
5058  * update the tteflags field with the tte mask corresponding to the attributes
5059  * affected and it returns the new attributes.  It will also clear the modify
5060  * bit if we are taking away write permission.  This is necessary since the
5061  * modify bit is the hardware permission bit and we need to clear it in order
5062  * to detect write faults.
5063  */
5064 static uint64_t
5065 sfmmu_vtop_attr(uint_t attr, int mode, tte_t *ttemaskp)
5066 {
5067 	tte_t ttevalue;
5068 
5069 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
5070 
5071 	switch (mode) {
5072 	case SFMMU_CHGATTR:
5073 		/* all attributes specified */
5074 		ttevalue.tte_inthi = MAKE_TTEATTR_INTHI(attr);
5075 		ttevalue.tte_intlo = MAKE_TTEATTR_INTLO(attr);
5076 		ttemaskp->tte_inthi = TTEINTHI_ATTR;
5077 		ttemaskp->tte_intlo = TTEINTLO_ATTR;
5078 		break;
5079 	case SFMMU_SETATTR:
5080 		ASSERT(!(attr & ~HAT_PROT_MASK));
5081 		ttemaskp->ll = 0;
5082 		ttevalue.ll = 0;
5083 		/*
5084 		 * a valid tte implies exec and read for sfmmu
5085 		 * so no need to do anything about them.
5086 		 * since priviledged access implies user access
5087 		 * PROT_USER doesn't make sense either.
5088 		 */
5089 		if (attr & PROT_WRITE) {
5090 			ttemaskp->tte_intlo |= TTE_WRPRM_INT;
5091 			ttevalue.tte_intlo |= TTE_WRPRM_INT;
5092 		}
5093 		break;
5094 	case SFMMU_CLRATTR:
5095 		/* attributes will be nand with current ones */
5096 		if (attr & ~(PROT_WRITE | PROT_USER)) {
5097 			panic("sfmmu: attr %x not supported", attr);
5098 		}
5099 		ttemaskp->ll = 0;
5100 		ttevalue.ll = 0;
5101 		if (attr & PROT_WRITE) {
5102 			/* clear both writable and modify bit */
5103 			ttemaskp->tte_intlo |= TTE_WRPRM_INT | TTE_HWWR_INT;
5104 		}
5105 		if (attr & PROT_USER) {
5106 			ttemaskp->tte_intlo |= TTE_PRIV_INT;
5107 			ttevalue.tte_intlo |= TTE_PRIV_INT;
5108 		}
5109 		break;
5110 	default:
5111 		panic("sfmmu_vtop_attr: bad mode %x", mode);
5112 	}
5113 	ASSERT(TTE_TO_TTEPFN(&ttevalue) == 0);
5114 	return (ttevalue.ll);
5115 }
5116 
5117 static uint_t
5118 sfmmu_ptov_attr(tte_t *ttep)
5119 {
5120 	uint_t attr;
5121 
5122 	ASSERT(TTE_IS_VALID(ttep));
5123 
5124 	attr = PROT_READ;
5125 
5126 	if (TTE_IS_WRITABLE(ttep)) {
5127 		attr |= PROT_WRITE;
5128 	}
5129 	if (TTE_IS_EXECUTABLE(ttep)) {
5130 		attr |= PROT_EXEC;
5131 	}
5132 	if (!TTE_IS_PRIVILEGED(ttep)) {
5133 		attr |= PROT_USER;
5134 	}
5135 	if (TTE_IS_NFO(ttep)) {
5136 		attr |= HAT_NOFAULT;
5137 	}
5138 	if (TTE_IS_NOSYNC(ttep)) {
5139 		attr |= HAT_NOSYNC;
5140 	}
5141 	if (TTE_IS_SIDEFFECT(ttep)) {
5142 		attr |= SFMMU_SIDEFFECT;
5143 	}
5144 	if (!TTE_IS_VCACHEABLE(ttep)) {
5145 		attr |= SFMMU_UNCACHEVTTE;
5146 	}
5147 	if (!TTE_IS_PCACHEABLE(ttep)) {
5148 		attr |= SFMMU_UNCACHEPTTE;
5149 	}
5150 	return (attr);
5151 }
5152 
5153 /*
5154  * hat_chgprot is a deprecated hat call.  New segment drivers
5155  * should store all attributes and use hat_*attr calls.
5156  *
5157  * Change the protections in the virtual address range
5158  * given to the specified virtual protection.  If vprot is ~PROT_WRITE,
5159  * then remove write permission, leaving the other
5160  * permissions unchanged.  If vprot is ~PROT_USER, remove user permissions.
5161  *
5162  */
5163 void
5164 hat_chgprot(struct hat *sfmmup, caddr_t addr, size_t len, uint_t vprot)
5165 {
5166 	struct hmehash_bucket *hmebp;
5167 	hmeblk_tag hblktag;
5168 	int hmeshift, hashno = 1;
5169 	struct hme_blk *hmeblkp, *list = NULL;
5170 	caddr_t endaddr;
5171 	cpuset_t cpuset;
5172 	demap_range_t dmr;
5173 
5174 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5175 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
5176 
5177 	ASSERT(sfmmup->sfmmu_as != NULL);
5178 
5179 	CPUSET_ZERO(cpuset);
5180 
5181 	if ((vprot != (uint_t)~PROT_WRITE) && (vprot & PROT_USER) &&
5182 	    ((addr + len) > (caddr_t)USERLIMIT)) {
5183 		panic("user addr %p vprot %x in kernel space",
5184 		    (void *)addr, vprot);
5185 	}
5186 	endaddr = addr + len;
5187 	hblktag.htag_id = sfmmup;
5188 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5189 	DEMAP_RANGE_INIT(sfmmup, &dmr);
5190 
5191 	while (addr < endaddr) {
5192 		hmeshift = HME_HASH_SHIFT(hashno);
5193 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5194 		hblktag.htag_rehash = hashno;
5195 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5196 
5197 		SFMMU_HASH_LOCK(hmebp);
5198 
5199 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
5200 		if (hmeblkp != NULL) {
5201 			ASSERT(!hmeblkp->hblk_shared);
5202 			/*
5203 			 * We've encountered a shadow hmeblk so skip the range
5204 			 * of the next smaller mapping size.
5205 			 */
5206 			if (hmeblkp->hblk_shw_bit) {
5207 				ASSERT(sfmmup != ksfmmup);
5208 				ASSERT(hashno > 1);
5209 				addr = (caddr_t)P2END((uintptr_t)addr,
5210 				    TTEBYTES(hashno - 1));
5211 			} else {
5212 				addr = sfmmu_hblk_chgprot(sfmmup, hmeblkp,
5213 				    addr, endaddr, &dmr, vprot);
5214 			}
5215 			SFMMU_HASH_UNLOCK(hmebp);
5216 			hashno = 1;
5217 			continue;
5218 		}
5219 		SFMMU_HASH_UNLOCK(hmebp);
5220 
5221 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
5222 			/*
5223 			 * We have traversed the whole list and rehashed
5224 			 * if necessary without finding the address to chgprot.
5225 			 * This is ok so we increment the address by the
5226 			 * smallest hmeblk range for kernel mappings and the
5227 			 * largest hmeblk range, to account for shadow hmeblks,
5228 			 * for user mappings and continue.
5229 			 */
5230 			if (sfmmup == ksfmmup)
5231 				addr = (caddr_t)P2END((uintptr_t)addr,
5232 				    TTEBYTES(1));
5233 			else
5234 				addr = (caddr_t)P2END((uintptr_t)addr,
5235 				    TTEBYTES(hashno));
5236 			hashno = 1;
5237 		} else {
5238 			hashno++;
5239 		}
5240 	}
5241 
5242 	sfmmu_hblks_list_purge(&list, 0);
5243 	DEMAP_RANGE_FLUSH(&dmr);
5244 	cpuset = sfmmup->sfmmu_cpusran;
5245 	xt_sync(cpuset);
5246 }
5247 
5248 /*
5249  * This function chgprots a range of addresses in an hmeblk.  It returns the
5250  * next addres that needs to be chgprot.
5251  * It should be called with the hash lock held.
5252  * XXX It shold be possible to optimize chgprot by not flushing every time but
5253  * on the other hand:
5254  * 1. do one flush crosscall.
5255  * 2. only flush if we are increasing permissions (make sure this will work)
5256  */
5257 static caddr_t
5258 sfmmu_hblk_chgprot(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5259     caddr_t endaddr, demap_range_t *dmrp, uint_t vprot)
5260 {
5261 	uint_t pprot;
5262 	tte_t tte, ttemod;
5263 	struct sf_hment *sfhmep;
5264 	uint_t tteflags;
5265 	int ttesz;
5266 	struct page *pp = NULL;
5267 	kmutex_t *pml, *pmtx;
5268 	int ret;
5269 	int use_demap_range;
5270 #if defined(SF_ERRATA_57)
5271 	int check_exec;
5272 #endif
5273 
5274 	ASSERT(in_hblk_range(hmeblkp, addr));
5275 	ASSERT(hmeblkp->hblk_shw_bit == 0);
5276 	ASSERT(!hmeblkp->hblk_shared);
5277 
5278 #ifdef DEBUG
5279 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5280 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5281 		panic("sfmmu_hblk_chgprot: partial chgprot of large page");
5282 	}
5283 #endif /* DEBUG */
5284 
5285 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5286 	ttesz = get_hblk_ttesz(hmeblkp);
5287 
5288 	pprot = sfmmu_vtop_prot(vprot, &tteflags);
5289 #if defined(SF_ERRATA_57)
5290 	check_exec = (sfmmup != ksfmmup) &&
5291 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
5292 	    ((vprot & PROT_EXEC) == PROT_EXEC);
5293 #endif
5294 	HBLKTOHME(sfhmep, hmeblkp, addr);
5295 
5296 	/*
5297 	 * Flush the current demap region if addresses have been
5298 	 * skipped or the page size doesn't match.
5299 	 */
5300 	use_demap_range = (TTEBYTES(ttesz) == MMU_PAGESIZE);
5301 	if (use_demap_range) {
5302 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5303 	} else if (dmrp != NULL) {
5304 		DEMAP_RANGE_FLUSH(dmrp);
5305 	}
5306 
5307 	while (addr < endaddr) {
5308 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5309 		if (TTE_IS_VALID(&tte)) {
5310 			if (TTE_GET_LOFLAGS(&tte, tteflags) == pprot) {
5311 				/*
5312 				 * if the new protection is the same as old
5313 				 * continue
5314 				 */
5315 				goto next_addr;
5316 			}
5317 			pml = NULL;
5318 			pp = sfhmep->hme_page;
5319 			if (pp) {
5320 				pml = sfmmu_mlist_enter(pp);
5321 			}
5322 			if (pp != sfhmep->hme_page) {
5323 				/*
5324 				 * tte most have been unloaded
5325 				 * underneath us.  Recheck
5326 				 */
5327 				ASSERT(pml);
5328 				sfmmu_mlist_exit(pml);
5329 				continue;
5330 			}
5331 
5332 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5333 
5334 			ttemod = tte;
5335 			TTE_SET_LOFLAGS(&ttemod, tteflags, pprot);
5336 #if defined(SF_ERRATA_57)
5337 			if (check_exec && addr < errata57_limit)
5338 				ttemod.tte_exec_perm = 0;
5339 #endif
5340 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5341 			    &sfhmep->hme_tte);
5342 
5343 			if (ret < 0) {
5344 				/* tte changed underneath us */
5345 				if (pml) {
5346 					sfmmu_mlist_exit(pml);
5347 				}
5348 				continue;
5349 			}
5350 
5351 			if (tteflags & TTE_HWWR_INT) {
5352 				/*
5353 				 * need to sync if we are clearing modify bit.
5354 				 */
5355 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
5356 			}
5357 
5358 			if (pp && PP_ISRO(pp)) {
5359 				if (pprot & TTE_WRPRM_INT) {
5360 					pmtx = sfmmu_page_enter(pp);
5361 					PP_CLRRO(pp);
5362 					sfmmu_page_exit(pmtx);
5363 				}
5364 			}
5365 
5366 			if (ret > 0 && use_demap_range) {
5367 				DEMAP_RANGE_MARKPG(dmrp, addr);
5368 			} else if (ret > 0) {
5369 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
5370 			}
5371 
5372 			if (pml) {
5373 				sfmmu_mlist_exit(pml);
5374 			}
5375 		}
5376 next_addr:
5377 		addr += TTEBYTES(ttesz);
5378 		sfhmep++;
5379 		DEMAP_RANGE_NEXTPG(dmrp);
5380 	}
5381 	return (addr);
5382 }
5383 
5384 /*
5385  * This routine is deprecated and should only be used by hat_chgprot.
5386  * The correct routine is sfmmu_vtop_attr.
5387  * This routine converts virtual page protections to physical ones.  It will
5388  * update the tteflags field with the tte mask corresponding to the protections
5389  * affected and it returns the new protections.  It will also clear the modify
5390  * bit if we are taking away write permission.  This is necessary since the
5391  * modify bit is the hardware permission bit and we need to clear it in order
5392  * to detect write faults.
5393  * It accepts the following special protections:
5394  * ~PROT_WRITE = remove write permissions.
5395  * ~PROT_USER = remove user permissions.
5396  */
5397 static uint_t
5398 sfmmu_vtop_prot(uint_t vprot, uint_t *tteflagsp)
5399 {
5400 	if (vprot == (uint_t)~PROT_WRITE) {
5401 		*tteflagsp = TTE_WRPRM_INT | TTE_HWWR_INT;
5402 		return (0);		/* will cause wrprm to be cleared */
5403 	}
5404 	if (vprot == (uint_t)~PROT_USER) {
5405 		*tteflagsp = TTE_PRIV_INT;
5406 		return (0);		/* will cause privprm to be cleared */
5407 	}
5408 	if ((vprot == 0) || (vprot == PROT_USER) ||
5409 	    ((vprot & PROT_ALL) != vprot)) {
5410 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5411 	}
5412 
5413 	switch (vprot) {
5414 	case (PROT_READ):
5415 	case (PROT_EXEC):
5416 	case (PROT_EXEC | PROT_READ):
5417 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5418 		return (TTE_PRIV_INT);		/* set prv and clr wrt */
5419 	case (PROT_WRITE):
5420 	case (PROT_WRITE | PROT_READ):
5421 	case (PROT_EXEC | PROT_WRITE):
5422 	case (PROT_EXEC | PROT_WRITE | PROT_READ):
5423 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5424 		return (TTE_PRIV_INT | TTE_WRPRM_INT);	/* set prv and wrt */
5425 	case (PROT_USER | PROT_READ):
5426 	case (PROT_USER | PROT_EXEC):
5427 	case (PROT_USER | PROT_EXEC | PROT_READ):
5428 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
5429 		return (0);			/* clr prv and wrt */
5430 	case (PROT_USER | PROT_WRITE):
5431 	case (PROT_USER | PROT_WRITE | PROT_READ):
5432 	case (PROT_USER | PROT_EXEC | PROT_WRITE):
5433 	case (PROT_USER | PROT_EXEC | PROT_WRITE | PROT_READ):
5434 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
5435 		return (TTE_WRPRM_INT);		/* clr prv and set wrt */
5436 	default:
5437 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
5438 	}
5439 	return (0);
5440 }
5441 
5442 /*
5443  * Alternate unload for very large virtual ranges. With a true 64 bit VA,
5444  * the normal algorithm would take too long for a very large VA range with
5445  * few real mappings. This routine just walks thru all HMEs in the global
5446  * hash table to find and remove mappings.
5447  */
5448 static void
5449 hat_unload_large_virtual(struct hat *sfmmup, caddr_t startaddr, size_t len,
5450     uint_t flags, hat_callback_t *callback)
5451 {
5452 	struct hmehash_bucket *hmebp;
5453 	struct hme_blk *hmeblkp;
5454 	struct hme_blk *pr_hblk = NULL;
5455 	struct hme_blk *nx_hblk;
5456 	struct hme_blk *list = NULL;
5457 	int i;
5458 	demap_range_t dmr, *dmrp;
5459 	cpuset_t cpuset;
5460 	caddr_t	endaddr = startaddr + len;
5461 	caddr_t	sa;
5462 	caddr_t	ea;
5463 	caddr_t	cb_sa[MAX_CB_ADDR];
5464 	caddr_t	cb_ea[MAX_CB_ADDR];
5465 	int	addr_cnt = 0;
5466 	int	a = 0;
5467 
5468 	if (sfmmup->sfmmu_free) {
5469 		dmrp = NULL;
5470 	} else {
5471 		dmrp = &dmr;
5472 		DEMAP_RANGE_INIT(sfmmup, dmrp);
5473 	}
5474 
5475 	/*
5476 	 * Loop through all the hash buckets of HME blocks looking for matches.
5477 	 */
5478 	for (i = 0; i <= UHMEHASH_SZ; i++) {
5479 		hmebp = &uhme_hash[i];
5480 		SFMMU_HASH_LOCK(hmebp);
5481 		hmeblkp = hmebp->hmeblkp;
5482 		pr_hblk = NULL;
5483 		while (hmeblkp) {
5484 			nx_hblk = hmeblkp->hblk_next;
5485 
5486 			/*
5487 			 * skip if not this context, if a shadow block or
5488 			 * if the mapping is not in the requested range
5489 			 */
5490 			if (hmeblkp->hblk_tag.htag_id != sfmmup ||
5491 			    hmeblkp->hblk_shw_bit ||
5492 			    (sa = (caddr_t)get_hblk_base(hmeblkp)) >= endaddr ||
5493 			    (ea = get_hblk_endaddr(hmeblkp)) <= startaddr) {
5494 				pr_hblk = hmeblkp;
5495 				goto next_block;
5496 			}
5497 
5498 			ASSERT(!hmeblkp->hblk_shared);
5499 			/*
5500 			 * unload if there are any current valid mappings
5501 			 */
5502 			if (hmeblkp->hblk_vcnt != 0 ||
5503 			    hmeblkp->hblk_hmecnt != 0)
5504 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
5505 				    sa, ea, dmrp, flags);
5506 
5507 			/*
5508 			 * on unmap we also release the HME block itself, once
5509 			 * all mappings are gone.
5510 			 */
5511 			if ((flags & HAT_UNLOAD_UNMAP) != 0 &&
5512 			    !hmeblkp->hblk_vcnt &&
5513 			    !hmeblkp->hblk_hmecnt) {
5514 				ASSERT(!hmeblkp->hblk_lckcnt);
5515 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
5516 				    &list, 0);
5517 			} else {
5518 				pr_hblk = hmeblkp;
5519 			}
5520 
5521 			if (callback == NULL)
5522 				goto next_block;
5523 
5524 			/*
5525 			 * HME blocks may span more than one page, but we may be
5526 			 * unmapping only one page, so check for a smaller range
5527 			 * for the callback
5528 			 */
5529 			if (sa < startaddr)
5530 				sa = startaddr;
5531 			if (--ea > endaddr)
5532 				ea = endaddr - 1;
5533 
5534 			cb_sa[addr_cnt] = sa;
5535 			cb_ea[addr_cnt] = ea;
5536 			if (++addr_cnt == MAX_CB_ADDR) {
5537 				if (dmrp != NULL) {
5538 					DEMAP_RANGE_FLUSH(dmrp);
5539 					cpuset = sfmmup->sfmmu_cpusran;
5540 					xt_sync(cpuset);
5541 				}
5542 
5543 				for (a = 0; a < MAX_CB_ADDR; ++a) {
5544 					callback->hcb_start_addr = cb_sa[a];
5545 					callback->hcb_end_addr = cb_ea[a];
5546 					callback->hcb_function(callback);
5547 				}
5548 				addr_cnt = 0;
5549 			}
5550 
5551 next_block:
5552 			hmeblkp = nx_hblk;
5553 		}
5554 		SFMMU_HASH_UNLOCK(hmebp);
5555 	}
5556 
5557 	sfmmu_hblks_list_purge(&list, 0);
5558 	if (dmrp != NULL) {
5559 		DEMAP_RANGE_FLUSH(dmrp);
5560 		cpuset = sfmmup->sfmmu_cpusran;
5561 		xt_sync(cpuset);
5562 	}
5563 
5564 	for (a = 0; a < addr_cnt; ++a) {
5565 		callback->hcb_start_addr = cb_sa[a];
5566 		callback->hcb_end_addr = cb_ea[a];
5567 		callback->hcb_function(callback);
5568 	}
5569 
5570 	/*
5571 	 * Check TSB and TLB page sizes if the process isn't exiting.
5572 	 */
5573 	if (!sfmmup->sfmmu_free)
5574 		sfmmu_check_page_sizes(sfmmup, 0);
5575 }
5576 
5577 /*
5578  * Unload all the mappings in the range [addr..addr+len). addr and len must
5579  * be MMU_PAGESIZE aligned.
5580  */
5581 
5582 extern struct seg *segkmap;
5583 #define	ISSEGKMAP(sfmmup, addr) (sfmmup == ksfmmup && \
5584 segkmap->s_base <= (addr) && (addr) < (segkmap->s_base + segkmap->s_size))
5585 
5586 
5587 void
5588 hat_unload_callback(struct hat *sfmmup, caddr_t addr, size_t len, uint_t flags,
5589     hat_callback_t *callback)
5590 {
5591 	struct hmehash_bucket *hmebp;
5592 	hmeblk_tag hblktag;
5593 	int hmeshift, hashno, iskernel;
5594 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
5595 	caddr_t endaddr;
5596 	cpuset_t cpuset;
5597 	int addr_count = 0;
5598 	int a;
5599 	caddr_t cb_start_addr[MAX_CB_ADDR];
5600 	caddr_t cb_end_addr[MAX_CB_ADDR];
5601 	int issegkmap = ISSEGKMAP(sfmmup, addr);
5602 	demap_range_t dmr, *dmrp;
5603 
5604 	ASSERT(sfmmup->sfmmu_as != NULL);
5605 
5606 	ASSERT((sfmmup == ksfmmup) || (flags & HAT_UNLOAD_OTHER) || \
5607 	    AS_LOCK_HELD(sfmmup->sfmmu_as));
5608 
5609 	ASSERT(sfmmup != NULL);
5610 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5611 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
5612 
5613 	/*
5614 	 * Probing through a large VA range (say 63 bits) will be slow, even
5615 	 * at 4 Meg steps between the probes. So, when the virtual address range
5616 	 * is very large, search the HME entries for what to unload.
5617 	 *
5618 	 *	len >> TTE_PAGE_SHIFT(TTE4M) is the # of 4Meg probes we'd need
5619 	 *
5620 	 *	UHMEHASH_SZ is number of hash buckets to examine
5621 	 *
5622 	 */
5623 	if (sfmmup != KHATID && (len >> TTE_PAGE_SHIFT(TTE4M)) > UHMEHASH_SZ) {
5624 		hat_unload_large_virtual(sfmmup, addr, len, flags, callback);
5625 		return;
5626 	}
5627 
5628 	CPUSET_ZERO(cpuset);
5629 
5630 	/*
5631 	 * If the process is exiting, we can save a lot of fuss since
5632 	 * we'll flush the TLB when we free the ctx anyway.
5633 	 */
5634 	if (sfmmup->sfmmu_free) {
5635 		dmrp = NULL;
5636 	} else {
5637 		dmrp = &dmr;
5638 		DEMAP_RANGE_INIT(sfmmup, dmrp);
5639 	}
5640 
5641 	endaddr = addr + len;
5642 	hblktag.htag_id = sfmmup;
5643 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
5644 
5645 	/*
5646 	 * It is likely for the vm to call unload over a wide range of
5647 	 * addresses that are actually very sparsely populated by
5648 	 * translations.  In order to speed this up the sfmmu hat supports
5649 	 * the concept of shadow hmeblks. Dummy large page hmeblks that
5650 	 * correspond to actual small translations are allocated at tteload
5651 	 * time and are referred to as shadow hmeblks.  Now, during unload
5652 	 * time, we first check if we have a shadow hmeblk for that
5653 	 * translation.  The absence of one means the corresponding address
5654 	 * range is empty and can be skipped.
5655 	 *
5656 	 * The kernel is an exception to above statement and that is why
5657 	 * we don't use shadow hmeblks and hash starting from the smallest
5658 	 * page size.
5659 	 */
5660 	if (sfmmup == KHATID) {
5661 		iskernel = 1;
5662 		hashno = TTE64K;
5663 	} else {
5664 		iskernel = 0;
5665 		if (mmu_page_sizes == max_mmu_page_sizes) {
5666 			hashno = TTE256M;
5667 		} else {
5668 			hashno = TTE4M;
5669 		}
5670 	}
5671 	while (addr < endaddr) {
5672 		hmeshift = HME_HASH_SHIFT(hashno);
5673 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5674 		hblktag.htag_rehash = hashno;
5675 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5676 
5677 		SFMMU_HASH_LOCK(hmebp);
5678 
5679 		HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
5680 		if (hmeblkp == NULL) {
5681 			/*
5682 			 * didn't find an hmeblk. skip the appropiate
5683 			 * address range.
5684 			 */
5685 			SFMMU_HASH_UNLOCK(hmebp);
5686 			if (iskernel) {
5687 				if (hashno < mmu_hashcnt) {
5688 					hashno++;
5689 					continue;
5690 				} else {
5691 					hashno = TTE64K;
5692 					addr = (caddr_t)roundup((uintptr_t)addr
5693 					    + 1, MMU_PAGESIZE64K);
5694 					continue;
5695 				}
5696 			}
5697 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5698 			    (1 << hmeshift));
5699 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5700 				ASSERT(hashno == TTE64K);
5701 				continue;
5702 			}
5703 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5704 				hashno = TTE512K;
5705 				continue;
5706 			}
5707 			if (mmu_page_sizes == max_mmu_page_sizes) {
5708 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5709 					hashno = TTE4M;
5710 					continue;
5711 				}
5712 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5713 					hashno = TTE32M;
5714 					continue;
5715 				}
5716 				hashno = TTE256M;
5717 				continue;
5718 			} else {
5719 				hashno = TTE4M;
5720 				continue;
5721 			}
5722 		}
5723 		ASSERT(hmeblkp);
5724 		ASSERT(!hmeblkp->hblk_shared);
5725 		if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5726 			/*
5727 			 * If the valid count is zero we can skip the range
5728 			 * mapped by this hmeblk.
5729 			 * We free hblks in the case of HAT_UNMAP.  HAT_UNMAP
5730 			 * is used by segment drivers as a hint
5731 			 * that the mapping resource won't be used any longer.
5732 			 * The best example of this is during exit().
5733 			 */
5734 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5735 			    get_hblk_span(hmeblkp));
5736 			if ((flags & HAT_UNLOAD_UNMAP) ||
5737 			    (iskernel && !issegkmap)) {
5738 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
5739 				    &list, 0);
5740 			}
5741 			SFMMU_HASH_UNLOCK(hmebp);
5742 
5743 			if (iskernel) {
5744 				hashno = TTE64K;
5745 				continue;
5746 			}
5747 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5748 				ASSERT(hashno == TTE64K);
5749 				continue;
5750 			}
5751 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5752 				hashno = TTE512K;
5753 				continue;
5754 			}
5755 			if (mmu_page_sizes == max_mmu_page_sizes) {
5756 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5757 					hashno = TTE4M;
5758 					continue;
5759 				}
5760 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5761 					hashno = TTE32M;
5762 					continue;
5763 				}
5764 				hashno = TTE256M;
5765 				continue;
5766 			} else {
5767 				hashno = TTE4M;
5768 				continue;
5769 			}
5770 		}
5771 		if (hmeblkp->hblk_shw_bit) {
5772 			/*
5773 			 * If we encounter a shadow hmeblk we know there is
5774 			 * smaller sized hmeblks mapping the same address space.
5775 			 * Decrement the hash size and rehash.
5776 			 */
5777 			ASSERT(sfmmup != KHATID);
5778 			hashno--;
5779 			SFMMU_HASH_UNLOCK(hmebp);
5780 			continue;
5781 		}
5782 
5783 		/*
5784 		 * track callback address ranges.
5785 		 * only start a new range when it's not contiguous
5786 		 */
5787 		if (callback != NULL) {
5788 			if (addr_count > 0 &&
5789 			    addr == cb_end_addr[addr_count - 1])
5790 				--addr_count;
5791 			else
5792 				cb_start_addr[addr_count] = addr;
5793 		}
5794 
5795 		addr = sfmmu_hblk_unload(sfmmup, hmeblkp, addr, endaddr,
5796 		    dmrp, flags);
5797 
5798 		if (callback != NULL)
5799 			cb_end_addr[addr_count++] = addr;
5800 
5801 		if (((flags & HAT_UNLOAD_UNMAP) || (iskernel && !issegkmap)) &&
5802 		    !hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5803 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk, &list, 0);
5804 		}
5805 		SFMMU_HASH_UNLOCK(hmebp);
5806 
5807 		/*
5808 		 * Notify our caller as to exactly which pages
5809 		 * have been unloaded. We do these in clumps,
5810 		 * to minimize the number of xt_sync()s that need to occur.
5811 		 */
5812 		if (callback != NULL && addr_count == MAX_CB_ADDR) {
5813 			if (dmrp != NULL) {
5814 				DEMAP_RANGE_FLUSH(dmrp);
5815 				cpuset = sfmmup->sfmmu_cpusran;
5816 				xt_sync(cpuset);
5817 			}
5818 
5819 			for (a = 0; a < MAX_CB_ADDR; ++a) {
5820 				callback->hcb_start_addr = cb_start_addr[a];
5821 				callback->hcb_end_addr = cb_end_addr[a];
5822 				callback->hcb_function(callback);
5823 			}
5824 			addr_count = 0;
5825 		}
5826 		if (iskernel) {
5827 			hashno = TTE64K;
5828 			continue;
5829 		}
5830 		if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5831 			ASSERT(hashno == TTE64K);
5832 			continue;
5833 		}
5834 		if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5835 			hashno = TTE512K;
5836 			continue;
5837 		}
5838 		if (mmu_page_sizes == max_mmu_page_sizes) {
5839 			if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5840 				hashno = TTE4M;
5841 				continue;
5842 			}
5843 			if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5844 				hashno = TTE32M;
5845 				continue;
5846 			}
5847 			hashno = TTE256M;
5848 		} else {
5849 			hashno = TTE4M;
5850 		}
5851 	}
5852 
5853 	sfmmu_hblks_list_purge(&list, 0);
5854 	if (dmrp != NULL) {
5855 		DEMAP_RANGE_FLUSH(dmrp);
5856 		cpuset = sfmmup->sfmmu_cpusran;
5857 		xt_sync(cpuset);
5858 	}
5859 	if (callback && addr_count != 0) {
5860 		for (a = 0; a < addr_count; ++a) {
5861 			callback->hcb_start_addr = cb_start_addr[a];
5862 			callback->hcb_end_addr = cb_end_addr[a];
5863 			callback->hcb_function(callback);
5864 		}
5865 	}
5866 
5867 	/*
5868 	 * Check TSB and TLB page sizes if the process isn't exiting.
5869 	 */
5870 	if (!sfmmup->sfmmu_free)
5871 		sfmmu_check_page_sizes(sfmmup, 0);
5872 }
5873 
5874 /*
5875  * Unload all the mappings in the range [addr..addr+len). addr and len must
5876  * be MMU_PAGESIZE aligned.
5877  */
5878 void
5879 hat_unload(struct hat *sfmmup, caddr_t addr, size_t len, uint_t flags)
5880 {
5881 	hat_unload_callback(sfmmup, addr, len, flags, NULL);
5882 }
5883 
5884 
5885 /*
5886  * Find the largest mapping size for this page.
5887  */
5888 int
5889 fnd_mapping_sz(page_t *pp)
5890 {
5891 	int sz;
5892 	int p_index;
5893 
5894 	p_index = PP_MAPINDEX(pp);
5895 
5896 	sz = 0;
5897 	p_index >>= 1;	/* don't care about 8K bit */
5898 	for (; p_index; p_index >>= 1) {
5899 		sz++;
5900 	}
5901 
5902 	return (sz);
5903 }
5904 
5905 /*
5906  * This function unloads a range of addresses for an hmeblk.
5907  * It returns the next address to be unloaded.
5908  * It should be called with the hash lock held.
5909  */
5910 static caddr_t
5911 sfmmu_hblk_unload(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5912     caddr_t endaddr, demap_range_t *dmrp, uint_t flags)
5913 {
5914 	tte_t	tte, ttemod;
5915 	struct	sf_hment *sfhmep;
5916 	int	ttesz;
5917 	long	ttecnt;
5918 	page_t *pp;
5919 	kmutex_t *pml;
5920 	int ret;
5921 	int use_demap_range;
5922 
5923 	ASSERT(in_hblk_range(hmeblkp, addr));
5924 	ASSERT(!hmeblkp->hblk_shw_bit);
5925 	ASSERT(sfmmup != NULL || hmeblkp->hblk_shared);
5926 	ASSERT(sfmmup == NULL || !hmeblkp->hblk_shared);
5927 	ASSERT(dmrp == NULL || !hmeblkp->hblk_shared);
5928 
5929 #ifdef DEBUG
5930 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5931 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5932 		panic("sfmmu_hblk_unload: partial unload of large page");
5933 	}
5934 #endif /* DEBUG */
5935 
5936 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5937 	ttesz = get_hblk_ttesz(hmeblkp);
5938 
5939 	use_demap_range = ((dmrp == NULL) ||
5940 	    (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp)));
5941 
5942 	if (use_demap_range) {
5943 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5944 	} else if (dmrp != NULL) {
5945 		DEMAP_RANGE_FLUSH(dmrp);
5946 	}
5947 	ttecnt = 0;
5948 	HBLKTOHME(sfhmep, hmeblkp, addr);
5949 
5950 	while (addr < endaddr) {
5951 		pml = NULL;
5952 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5953 		if (TTE_IS_VALID(&tte)) {
5954 			pp = sfhmep->hme_page;
5955 			if (pp != NULL) {
5956 				pml = sfmmu_mlist_enter(pp);
5957 			}
5958 
5959 			/*
5960 			 * Verify if hme still points to 'pp' now that
5961 			 * we have p_mapping lock.
5962 			 */
5963 			if (sfhmep->hme_page != pp) {
5964 				if (pp != NULL && sfhmep->hme_page != NULL) {
5965 					ASSERT(pml != NULL);
5966 					sfmmu_mlist_exit(pml);
5967 					/* Re-start this iteration. */
5968 					continue;
5969 				}
5970 				ASSERT((pp != NULL) &&
5971 				    (sfhmep->hme_page == NULL));
5972 				goto tte_unloaded;
5973 			}
5974 
5975 			/*
5976 			 * This point on we have both HASH and p_mapping
5977 			 * lock.
5978 			 */
5979 			ASSERT(pp == sfhmep->hme_page);
5980 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5981 
5982 			/*
5983 			 * We need to loop on modify tte because it is
5984 			 * possible for pagesync to come along and
5985 			 * change the software bits beneath us.
5986 			 *
5987 			 * Page_unload can also invalidate the tte after
5988 			 * we read tte outside of p_mapping lock.
5989 			 */
5990 again:
5991 			ttemod = tte;
5992 
5993 			TTE_SET_INVALID(&ttemod);
5994 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5995 			    &sfhmep->hme_tte);
5996 
5997 			if (ret <= 0) {
5998 				if (TTE_IS_VALID(&tte)) {
5999 					ASSERT(ret < 0);
6000 					goto again;
6001 				}
6002 				if (pp != NULL) {
6003 					panic("sfmmu_hblk_unload: pp = 0x%p "
6004 					    "tte became invalid under mlist"
6005 					    " lock = 0x%p", (void *)pp,
6006 					    (void *)pml);
6007 				}
6008 				continue;
6009 			}
6010 
6011 			if (!(flags & HAT_UNLOAD_NOSYNC)) {
6012 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
6013 			}
6014 
6015 			/*
6016 			 * Ok- we invalidated the tte. Do the rest of the job.
6017 			 */
6018 			ttecnt++;
6019 
6020 			if (flags & HAT_UNLOAD_UNLOCK) {
6021 				ASSERT(hmeblkp->hblk_lckcnt > 0);
6022 				atomic_dec_32(&hmeblkp->hblk_lckcnt);
6023 				HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
6024 			}
6025 
6026 			/*
6027 			 * Normally we would need to flush the page
6028 			 * from the virtual cache at this point in
6029 			 * order to prevent a potential cache alias
6030 			 * inconsistency.
6031 			 * The particular scenario we need to worry
6032 			 * about is:
6033 			 * Given:  va1 and va2 are two virtual address
6034 			 * that alias and map the same physical
6035 			 * address.
6036 			 * 1.   mapping exists from va1 to pa and data
6037 			 * has been read into the cache.
6038 			 * 2.   unload va1.
6039 			 * 3.   load va2 and modify data using va2.
6040 			 * 4    unload va2.
6041 			 * 5.   load va1 and reference data.  Unless we
6042 			 * flush the data cache when we unload we will
6043 			 * get stale data.
6044 			 * Fortunately, page coloring eliminates the
6045 			 * above scenario by remembering the color a
6046 			 * physical page was last or is currently
6047 			 * mapped to.  Now, we delay the flush until
6048 			 * the loading of translations.  Only when the
6049 			 * new translation is of a different color
6050 			 * are we forced to flush.
6051 			 */
6052 			if (use_demap_range) {
6053 				/*
6054 				 * Mark this page as needing a demap.
6055 				 */
6056 				DEMAP_RANGE_MARKPG(dmrp, addr);
6057 			} else {
6058 				ASSERT(sfmmup != NULL);
6059 				ASSERT(!hmeblkp->hblk_shared);
6060 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
6061 				    sfmmup->sfmmu_free, 0);
6062 			}
6063 
6064 			if (pp) {
6065 				/*
6066 				 * Remove the hment from the mapping list
6067 				 */
6068 				ASSERT(hmeblkp->hblk_hmecnt > 0);
6069 
6070 				/*
6071 				 * Again, we cannot
6072 				 * ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS);
6073 				 */
6074 				HME_SUB(sfhmep, pp);
6075 				membar_stst();
6076 				atomic_dec_16(&hmeblkp->hblk_hmecnt);
6077 			}
6078 
6079 			ASSERT(hmeblkp->hblk_vcnt > 0);
6080 			atomic_dec_16(&hmeblkp->hblk_vcnt);
6081 
6082 			ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
6083 			    !hmeblkp->hblk_lckcnt);
6084 
6085 #ifdef VAC
6086 			if (pp && (pp->p_nrm & (P_KPMC | P_KPMS | P_TNC))) {
6087 				if (PP_ISTNC(pp)) {
6088 					/*
6089 					 * If page was temporary
6090 					 * uncached, try to recache
6091 					 * it. Note that HME_SUB() was
6092 					 * called above so p_index and
6093 					 * mlist had been updated.
6094 					 */
6095 					conv_tnc(pp, ttesz);
6096 				} else if (pp->p_mapping == NULL) {
6097 					ASSERT(kpm_enable);
6098 					/*
6099 					 * Page is marked to be in VAC conflict
6100 					 * to an existing kpm mapping and/or is
6101 					 * kpm mapped using only the regular
6102 					 * pagesize.
6103 					 */
6104 					sfmmu_kpm_hme_unload(pp);
6105 				}
6106 			}
6107 #endif	/* VAC */
6108 		} else if ((pp = sfhmep->hme_page) != NULL) {
6109 				/*
6110 				 * TTE is invalid but the hme
6111 				 * still exists. let pageunload
6112 				 * complete its job.
6113 				 */
6114 				ASSERT(pml == NULL);
6115 				pml = sfmmu_mlist_enter(pp);
6116 				if (sfhmep->hme_page != NULL) {
6117 					sfmmu_mlist_exit(pml);
6118 					continue;
6119 				}
6120 				ASSERT(sfhmep->hme_page == NULL);
6121 		} else if (hmeblkp->hblk_hmecnt != 0) {
6122 			/*
6123 			 * pageunload may have not finished decrementing
6124 			 * hblk_vcnt and hblk_hmecnt. Find page_t if any and
6125 			 * wait for pageunload to finish. Rely on pageunload
6126 			 * to decrement hblk_hmecnt after hblk_vcnt.
6127 			 */
6128 			pfn_t pfn = TTE_TO_TTEPFN(&tte);
6129 			ASSERT(pml == NULL);
6130 			if (pf_is_memory(pfn)) {
6131 				pp = page_numtopp_nolock(pfn);
6132 				if (pp != NULL) {
6133 					pml = sfmmu_mlist_enter(pp);
6134 					sfmmu_mlist_exit(pml);
6135 					pml = NULL;
6136 				}
6137 			}
6138 		}
6139 
6140 tte_unloaded:
6141 		/*
6142 		 * At this point, the tte we are looking at
6143 		 * should be unloaded, and hme has been unlinked
6144 		 * from page too. This is important because in
6145 		 * pageunload, it does ttesync() then HME_SUB.
6146 		 * We need to make sure HME_SUB has been completed
6147 		 * so we know ttesync() has been completed. Otherwise,
6148 		 * at exit time, after return from hat layer, VM will
6149 		 * release as structure which hat_setstat() (called
6150 		 * by ttesync()) needs.
6151 		 */
6152 #ifdef DEBUG
6153 		{
6154 			tte_t	dtte;
6155 
6156 			ASSERT(sfhmep->hme_page == NULL);
6157 
6158 			sfmmu_copytte(&sfhmep->hme_tte, &dtte);
6159 			ASSERT(!TTE_IS_VALID(&dtte));
6160 		}
6161 #endif
6162 
6163 		if (pml) {
6164 			sfmmu_mlist_exit(pml);
6165 		}
6166 
6167 		addr += TTEBYTES(ttesz);
6168 		sfhmep++;
6169 		DEMAP_RANGE_NEXTPG(dmrp);
6170 	}
6171 	/*
6172 	 * For shared hmeblks this routine is only called when region is freed
6173 	 * and no longer referenced.  So no need to decrement ttecnt
6174 	 * in the region structure here.
6175 	 */
6176 	if (ttecnt > 0 && sfmmup != NULL) {
6177 		atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -ttecnt);
6178 	}
6179 	return (addr);
6180 }
6181 
6182 /*
6183  * Invalidate a virtual address range for the local CPU.
6184  * For best performance ensure that the va range is completely
6185  * mapped, otherwise the entire TLB will be flushed.
6186  */
6187 void
6188 hat_flush_range(struct hat *sfmmup, caddr_t va, size_t size)
6189 {
6190 	ssize_t sz;
6191 	caddr_t endva = va + size;
6192 
6193 	while (va < endva) {
6194 		sz = hat_getpagesize(sfmmup, va);
6195 		if (sz < 0) {
6196 			vtag_flushall();
6197 			break;
6198 		}
6199 		vtag_flushpage(va, (uint64_t)sfmmup);
6200 		va += sz;
6201 	}
6202 }
6203 
6204 /*
6205  * Synchronize all the mappings in the range [addr..addr+len).
6206  * Can be called with clearflag having two states:
6207  * HAT_SYNC_DONTZERO means just return the rm stats
6208  * HAT_SYNC_ZERORM means zero rm bits in the tte and return the stats
6209  */
6210 void
6211 hat_sync(struct hat *sfmmup, caddr_t addr, size_t len, uint_t clearflag)
6212 {
6213 	struct hmehash_bucket *hmebp;
6214 	hmeblk_tag hblktag;
6215 	int hmeshift, hashno = 1;
6216 	struct hme_blk *hmeblkp, *list = NULL;
6217 	caddr_t endaddr;
6218 	cpuset_t cpuset;
6219 
6220 	ASSERT((sfmmup == ksfmmup) || AS_LOCK_HELD(sfmmup->sfmmu_as));
6221 	ASSERT((len & MMU_PAGEOFFSET) == 0);
6222 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
6223 	    (clearflag == HAT_SYNC_ZERORM));
6224 
6225 	CPUSET_ZERO(cpuset);
6226 
6227 	endaddr = addr + len;
6228 	hblktag.htag_id = sfmmup;
6229 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
6230 
6231 	/*
6232 	 * Spitfire supports 4 page sizes.
6233 	 * Most pages are expected to be of the smallest page
6234 	 * size (8K) and these will not need to be rehashed. 64K
6235 	 * pages also don't need to be rehashed because the an hmeblk
6236 	 * spans 64K of address space. 512K pages might need 1 rehash and
6237 	 * and 4M pages 2 rehashes.
6238 	 */
6239 	while (addr < endaddr) {
6240 		hmeshift = HME_HASH_SHIFT(hashno);
6241 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
6242 		hblktag.htag_rehash = hashno;
6243 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
6244 
6245 		SFMMU_HASH_LOCK(hmebp);
6246 
6247 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
6248 		if (hmeblkp != NULL) {
6249 			ASSERT(!hmeblkp->hblk_shared);
6250 			/*
6251 			 * We've encountered a shadow hmeblk so skip the range
6252 			 * of the next smaller mapping size.
6253 			 */
6254 			if (hmeblkp->hblk_shw_bit) {
6255 				ASSERT(sfmmup != ksfmmup);
6256 				ASSERT(hashno > 1);
6257 				addr = (caddr_t)P2END((uintptr_t)addr,
6258 				    TTEBYTES(hashno - 1));
6259 			} else {
6260 				addr = sfmmu_hblk_sync(sfmmup, hmeblkp,
6261 				    addr, endaddr, clearflag);
6262 			}
6263 			SFMMU_HASH_UNLOCK(hmebp);
6264 			hashno = 1;
6265 			continue;
6266 		}
6267 		SFMMU_HASH_UNLOCK(hmebp);
6268 
6269 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
6270 			/*
6271 			 * We have traversed the whole list and rehashed
6272 			 * if necessary without finding the address to sync.
6273 			 * This is ok so we increment the address by the
6274 			 * smallest hmeblk range for kernel mappings and the
6275 			 * largest hmeblk range, to account for shadow hmeblks,
6276 			 * for user mappings and continue.
6277 			 */
6278 			if (sfmmup == ksfmmup)
6279 				addr = (caddr_t)P2END((uintptr_t)addr,
6280 				    TTEBYTES(1));
6281 			else
6282 				addr = (caddr_t)P2END((uintptr_t)addr,
6283 				    TTEBYTES(hashno));
6284 			hashno = 1;
6285 		} else {
6286 			hashno++;
6287 		}
6288 	}
6289 	sfmmu_hblks_list_purge(&list, 0);
6290 	cpuset = sfmmup->sfmmu_cpusran;
6291 	xt_sync(cpuset);
6292 }
6293 
6294 static caddr_t
6295 sfmmu_hblk_sync(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
6296     caddr_t endaddr, int clearflag)
6297 {
6298 	tte_t	tte, ttemod;
6299 	struct sf_hment *sfhmep;
6300 	int ttesz;
6301 	struct page *pp;
6302 	kmutex_t *pml;
6303 	int ret;
6304 
6305 	ASSERT(hmeblkp->hblk_shw_bit == 0);
6306 	ASSERT(!hmeblkp->hblk_shared);
6307 
6308 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
6309 
6310 	ttesz = get_hblk_ttesz(hmeblkp);
6311 	HBLKTOHME(sfhmep, hmeblkp, addr);
6312 
6313 	while (addr < endaddr) {
6314 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6315 		if (TTE_IS_VALID(&tte)) {
6316 			pml = NULL;
6317 			pp = sfhmep->hme_page;
6318 			if (pp) {
6319 				pml = sfmmu_mlist_enter(pp);
6320 			}
6321 			if (pp != sfhmep->hme_page) {
6322 				/*
6323 				 * tte most have been unloaded
6324 				 * underneath us.  Recheck
6325 				 */
6326 				ASSERT(pml);
6327 				sfmmu_mlist_exit(pml);
6328 				continue;
6329 			}
6330 
6331 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
6332 
6333 			if (clearflag == HAT_SYNC_ZERORM) {
6334 				ttemod = tte;
6335 				TTE_CLR_RM(&ttemod);
6336 				ret = sfmmu_modifytte_try(&tte, &ttemod,
6337 				    &sfhmep->hme_tte);
6338 				if (ret < 0) {
6339 					if (pml) {
6340 						sfmmu_mlist_exit(pml);
6341 					}
6342 					continue;
6343 				}
6344 
6345 				if (ret > 0) {
6346 					sfmmu_tlb_demap(addr, sfmmup,
6347 					    hmeblkp, 0, 0);
6348 				}
6349 			}
6350 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
6351 			if (pml) {
6352 				sfmmu_mlist_exit(pml);
6353 			}
6354 		}
6355 		addr += TTEBYTES(ttesz);
6356 		sfhmep++;
6357 	}
6358 	return (addr);
6359 }
6360 
6361 /*
6362  * This function will sync a tte to the page struct and it will
6363  * update the hat stats. Currently it allows us to pass a NULL pp
6364  * and we will simply update the stats.  We may want to change this
6365  * so we only keep stats for pages backed by pp's.
6366  */
6367 static void
6368 sfmmu_ttesync(struct hat *sfmmup, caddr_t addr, tte_t *ttep, page_t *pp)
6369 {
6370 	uint_t rm = 0;
6371 	int	sz;
6372 	pgcnt_t	npgs;
6373 
6374 	ASSERT(TTE_IS_VALID(ttep));
6375 
6376 	if (TTE_IS_NOSYNC(ttep)) {
6377 		return;
6378 	}
6379 
6380 	if (TTE_IS_REF(ttep))  {
6381 		rm = P_REF;
6382 	}
6383 	if (TTE_IS_MOD(ttep))  {
6384 		rm |= P_MOD;
6385 	}
6386 
6387 	if (rm == 0) {
6388 		return;
6389 	}
6390 
6391 	sz = TTE_CSZ(ttep);
6392 	if (sfmmup != NULL && sfmmup->sfmmu_rmstat) {
6393 		int i;
6394 		caddr_t	vaddr = addr;
6395 
6396 		for (i = 0; i < TTEPAGES(sz); i++, vaddr += MMU_PAGESIZE) {
6397 			hat_setstat(sfmmup->sfmmu_as, vaddr, MMU_PAGESIZE, rm);
6398 		}
6399 
6400 	}
6401 
6402 	/*
6403 	 * XXX I want to use cas to update nrm bits but they
6404 	 * currently belong in common/vm and not in hat where
6405 	 * they should be.
6406 	 * The nrm bits are protected by the same mutex as
6407 	 * the one that protects the page's mapping list.
6408 	 */
6409 	if (!pp)
6410 		return;
6411 	ASSERT(sfmmu_mlist_held(pp));
6412 	/*
6413 	 * If the tte is for a large page, we need to sync all the
6414 	 * pages covered by the tte.
6415 	 */
6416 	if (sz != TTE8K) {
6417 		ASSERT(pp->p_szc != 0);
6418 		pp = PP_GROUPLEADER(pp, sz);
6419 		ASSERT(sfmmu_mlist_held(pp));
6420 	}
6421 
6422 	/* Get number of pages from tte size. */
6423 	npgs = TTEPAGES(sz);
6424 
6425 	do {
6426 		ASSERT(pp);
6427 		ASSERT(sfmmu_mlist_held(pp));
6428 		if (((rm & P_REF) != 0 && !PP_ISREF(pp)) ||
6429 		    ((rm & P_MOD) != 0 && !PP_ISMOD(pp)))
6430 			hat_page_setattr(pp, rm);
6431 
6432 		/*
6433 		 * Are we done? If not, we must have a large mapping.
6434 		 * For large mappings we need to sync the rest of the pages
6435 		 * covered by this tte; goto the next page.
6436 		 */
6437 	} while (--npgs > 0 && (pp = PP_PAGENEXT(pp)));
6438 }
6439 
6440 /*
6441  * Execute pre-callback handler of each pa_hment linked to pp
6442  *
6443  * Inputs:
6444  *   flag: either HAT_PRESUSPEND or HAT_SUSPEND.
6445  *   capture_cpus: pointer to return value (below)
6446  *
6447  * Returns:
6448  *   Propagates the subsystem callback return values back to the caller;
6449  *   returns 0 on success.  If capture_cpus is non-NULL, the value returned
6450  *   is zero if all of the pa_hments are of a type that do not require
6451  *   capturing CPUs prior to suspending the mapping, else it is 1.
6452  */
6453 static int
6454 hat_pageprocess_precallbacks(struct page *pp, uint_t flag, int *capture_cpus)
6455 {
6456 	struct sf_hment	*sfhmep;
6457 	struct pa_hment *pahmep;
6458 	int (*f)(caddr_t, uint_t, uint_t, void *);
6459 	int		ret;
6460 	id_t		id;
6461 	int		locked = 0;
6462 	kmutex_t	*pml;
6463 
6464 	ASSERT(PAGE_EXCL(pp));
6465 	if (!sfmmu_mlist_held(pp)) {
6466 		pml = sfmmu_mlist_enter(pp);
6467 		locked = 1;
6468 	}
6469 
6470 	if (capture_cpus)
6471 		*capture_cpus = 0;
6472 
6473 top:
6474 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6475 		/*
6476 		 * skip sf_hments corresponding to VA<->PA mappings;
6477 		 * for pa_hment's, hme_tte.ll is zero
6478 		 */
6479 		if (!IS_PAHME(sfhmep))
6480 			continue;
6481 
6482 		pahmep = sfhmep->hme_data;
6483 		ASSERT(pahmep != NULL);
6484 
6485 		/*
6486 		 * skip if pre-handler has been called earlier in this loop
6487 		 */
6488 		if (pahmep->flags & flag)
6489 			continue;
6490 
6491 		id = pahmep->cb_id;
6492 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6493 		if (capture_cpus && sfmmu_cb_table[id].capture_cpus != 0)
6494 			*capture_cpus = 1;
6495 		if ((f = sfmmu_cb_table[id].prehandler) == NULL) {
6496 			pahmep->flags |= flag;
6497 			continue;
6498 		}
6499 
6500 		/*
6501 		 * Drop the mapping list lock to avoid locking order issues.
6502 		 */
6503 		if (locked)
6504 			sfmmu_mlist_exit(pml);
6505 
6506 		ret = f(pahmep->addr, pahmep->len, flag, pahmep->pvt);
6507 		if (ret != 0)
6508 			return (ret);	/* caller must do the cleanup */
6509 
6510 		if (locked) {
6511 			pml = sfmmu_mlist_enter(pp);
6512 			pahmep->flags |= flag;
6513 			goto top;
6514 		}
6515 
6516 		pahmep->flags |= flag;
6517 	}
6518 
6519 	if (locked)
6520 		sfmmu_mlist_exit(pml);
6521 
6522 	return (0);
6523 }
6524 
6525 /*
6526  * Execute post-callback handler of each pa_hment linked to pp
6527  *
6528  * Same overall assumptions and restrictions apply as for
6529  * hat_pageprocess_precallbacks().
6530  */
6531 static void
6532 hat_pageprocess_postcallbacks(struct page *pp, uint_t flag)
6533 {
6534 	pfn_t pgpfn = pp->p_pagenum;
6535 	pfn_t pgmask = btop(page_get_pagesize(pp->p_szc)) - 1;
6536 	pfn_t newpfn;
6537 	struct sf_hment *sfhmep;
6538 	struct pa_hment *pahmep;
6539 	int (*f)(caddr_t, uint_t, uint_t, void *, pfn_t);
6540 	id_t	id;
6541 	int	locked = 0;
6542 	kmutex_t *pml;
6543 
6544 	ASSERT(PAGE_EXCL(pp));
6545 	if (!sfmmu_mlist_held(pp)) {
6546 		pml = sfmmu_mlist_enter(pp);
6547 		locked = 1;
6548 	}
6549 
6550 top:
6551 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6552 		/*
6553 		 * skip sf_hments corresponding to VA<->PA mappings;
6554 		 * for pa_hment's, hme_tte.ll is zero
6555 		 */
6556 		if (!IS_PAHME(sfhmep))
6557 			continue;
6558 
6559 		pahmep = sfhmep->hme_data;
6560 		ASSERT(pahmep != NULL);
6561 
6562 		if ((pahmep->flags & flag) == 0)
6563 			continue;
6564 
6565 		pahmep->flags &= ~flag;
6566 
6567 		id = pahmep->cb_id;
6568 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
6569 		if ((f = sfmmu_cb_table[id].posthandler) == NULL)
6570 			continue;
6571 
6572 		/*
6573 		 * Convert the base page PFN into the constituent PFN
6574 		 * which is needed by the callback handler.
6575 		 */
6576 		newpfn = pgpfn | (btop((uintptr_t)pahmep->addr) & pgmask);
6577 
6578 		/*
6579 		 * Drop the mapping list lock to avoid locking order issues.
6580 		 */
6581 		if (locked)
6582 			sfmmu_mlist_exit(pml);
6583 
6584 		if (f(pahmep->addr, pahmep->len, flag, pahmep->pvt, newpfn)
6585 		    != 0)
6586 			panic("sfmmu: posthandler failed");
6587 
6588 		if (locked) {
6589 			pml = sfmmu_mlist_enter(pp);
6590 			goto top;
6591 		}
6592 	}
6593 
6594 	if (locked)
6595 		sfmmu_mlist_exit(pml);
6596 }
6597 
6598 /*
6599  * Suspend locked kernel mapping
6600  */
6601 void
6602 hat_pagesuspend(struct page *pp)
6603 {
6604 	struct sf_hment *sfhmep;
6605 	sfmmu_t *sfmmup;
6606 	tte_t tte, ttemod;
6607 	struct hme_blk *hmeblkp;
6608 	caddr_t addr;
6609 	int index, cons;
6610 	cpuset_t cpuset;
6611 
6612 	ASSERT(PAGE_EXCL(pp));
6613 	ASSERT(sfmmu_mlist_held(pp));
6614 
6615 	mutex_enter(&kpr_suspendlock);
6616 
6617 	/*
6618 	 * We're about to suspend a kernel mapping so mark this thread as
6619 	 * non-traceable by DTrace. This prevents us from running into issues
6620 	 * with probe context trying to touch a suspended page
6621 	 * in the relocation codepath itself.
6622 	 */
6623 	curthread->t_flag |= T_DONTDTRACE;
6624 
6625 	index = PP_MAPINDEX(pp);
6626 	cons = TTE8K;
6627 
6628 retry:
6629 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
6630 
6631 		if (IS_PAHME(sfhmep))
6632 			continue;
6633 
6634 		if (get_hblk_ttesz(sfmmu_hmetohblk(sfhmep)) != cons)
6635 			continue;
6636 
6637 		/*
6638 		 * Loop until we successfully set the suspend bit in
6639 		 * the TTE.
6640 		 */
6641 again:
6642 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
6643 		ASSERT(TTE_IS_VALID(&tte));
6644 
6645 		ttemod = tte;
6646 		TTE_SET_SUSPEND(&ttemod);
6647 		if (sfmmu_modifytte_try(&tte, &ttemod,
6648 		    &sfhmep->hme_tte) < 0)
6649 			goto again;
6650 
6651 		/*
6652 		 * Invalidate TSB entry
6653 		 */
6654 		hmeblkp = sfmmu_hmetohblk(sfhmep);
6655 
6656 		sfmmup = hblktosfmmu(hmeblkp);
6657 		ASSERT(sfmmup == ksfmmup);
6658 		ASSERT(!hmeblkp->hblk_shared);
6659 
6660 		addr = tte_to_vaddr(hmeblkp, tte);
6661 
6662 		/*
6663 		 * No need to make sure that the TSB for this sfmmu is
6664 		 * not being relocated since it is ksfmmup and thus it
6665 		 * will never be relocated.
6666 		 */
6667 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
6668 
6669 		/*
6670 		 * Update xcall stats
6671 		 */
6672 		cpuset = cpu_ready_set;
6673 		CPUSET_DEL(cpuset, CPU->cpu_id);
6674 
6675 		/* LINTED: constant in conditional context */
6676 		SFMMU_XCALL_STATS(ksfmmup);
6677 
6678 		/*
6679 		 * Flush TLB entry on remote CPU's
6680 		 */
6681 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
6682 		    (uint64_t)ksfmmup);
6683 		xt_sync(cpuset);
6684 
6685 		/*
6686 		 * Flush TLB entry on local CPU
6687 		 */
6688 		vtag_flushpage(addr, (uint64_t)ksfmmup);
6689 	}
6690 
6691 	while (index != 0) {
6692 		index = index >> 1;
6693 		if (index != 0)
6694 			cons++;
6695 		if (index & 0x1) {
6696 			pp = PP_GROUPLEADER(pp, cons);
6697 			goto retry;
6698 		}
6699 	}
6700 }
6701 
6702 #ifdef	DEBUG
6703 
6704 #define	N_PRLE	1024
6705 struct prle {
6706 	page_t *targ;
6707 	page_t *repl;
6708 	int status;
6709 	int pausecpus;
6710 	hrtime_t whence;
6711 };
6712 
6713 static struct prle page_relocate_log[N_PRLE];
6714 static int prl_entry;
6715 static kmutex_t prl_mutex;
6716 
6717 #define	PAGE_RELOCATE_LOG(t, r, s, p)					\
6718 	mutex_enter(&prl_mutex);					\
6719 	page_relocate_log[prl_entry].targ = *(t);			\
6720 	page_relocate_log[prl_entry].repl = *(r);			\
6721 	page_relocate_log[prl_entry].status = (s);			\
6722 	page_relocate_log[prl_entry].pausecpus = (p);			\
6723 	page_relocate_log[prl_entry].whence = gethrtime();		\
6724 	prl_entry = (prl_entry == (N_PRLE - 1))? 0 : prl_entry + 1;	\
6725 	mutex_exit(&prl_mutex);
6726 
6727 #else	/* !DEBUG */
6728 #define	PAGE_RELOCATE_LOG(t, r, s, p)
6729 #endif
6730 
6731 /*
6732  * Core Kernel Page Relocation Algorithm
6733  *
6734  * Input:
6735  *
6736  * target :	constituent pages are SE_EXCL locked.
6737  * replacement:	constituent pages are SE_EXCL locked.
6738  *
6739  * Output:
6740  *
6741  * nrelocp:	number of pages relocated
6742  */
6743 int
6744 hat_page_relocate(page_t **target, page_t **replacement, spgcnt_t *nrelocp)
6745 {
6746 	page_t		*targ, *repl;
6747 	page_t		*tpp, *rpp;
6748 	kmutex_t	*low, *high;
6749 	spgcnt_t	npages, i;
6750 	page_t		*pl = NULL;
6751 	int		old_pil;
6752 	cpuset_t	cpuset;
6753 	int		cap_cpus;
6754 	int		ret;
6755 #ifdef VAC
6756 	int		cflags = 0;
6757 #endif
6758 
6759 	if (!kcage_on || PP_ISNORELOC(*target)) {
6760 		PAGE_RELOCATE_LOG(target, replacement, EAGAIN, -1);
6761 		return (EAGAIN);
6762 	}
6763 
6764 	mutex_enter(&kpr_mutex);
6765 	kreloc_thread = curthread;
6766 
6767 	targ = *target;
6768 	repl = *replacement;
6769 	ASSERT(repl != NULL);
6770 	ASSERT(targ->p_szc == repl->p_szc);
6771 
6772 	npages = page_get_pagecnt(targ->p_szc);
6773 
6774 	/*
6775 	 * unload VA<->PA mappings that are not locked
6776 	 */
6777 	tpp = targ;
6778 	for (i = 0; i < npages; i++) {
6779 		(void) hat_pageunload(tpp, SFMMU_KERNEL_RELOC);
6780 		tpp++;
6781 	}
6782 
6783 	/*
6784 	 * Do "presuspend" callbacks, in a context from which we can still
6785 	 * block as needed. Note that we don't hold the mapping list lock
6786 	 * of "targ" at this point due to potential locking order issues;
6787 	 * we assume that between the hat_pageunload() above and holding
6788 	 * the SE_EXCL lock that the mapping list *cannot* change at this
6789 	 * point.
6790 	 */
6791 	ret = hat_pageprocess_precallbacks(targ, HAT_PRESUSPEND, &cap_cpus);
6792 	if (ret != 0) {
6793 		/*
6794 		 * EIO translates to fatal error, for all others cleanup
6795 		 * and return EAGAIN.
6796 		 */
6797 		ASSERT(ret != EIO);
6798 		hat_pageprocess_postcallbacks(targ, HAT_POSTUNSUSPEND);
6799 		PAGE_RELOCATE_LOG(target, replacement, ret, -1);
6800 		kreloc_thread = NULL;
6801 		mutex_exit(&kpr_mutex);
6802 		return (EAGAIN);
6803 	}
6804 
6805 	/*
6806 	 * acquire p_mapping list lock for both the target and replacement
6807 	 * root pages.
6808 	 *
6809 	 * low and high refer to the need to grab the mlist locks in a
6810 	 * specific order in order to prevent race conditions.  Thus the
6811 	 * lower lock must be grabbed before the higher lock.
6812 	 *
6813 	 * This will block hat_unload's accessing p_mapping list.  Since
6814 	 * we have SE_EXCL lock, hat_memload and hat_pageunload will be
6815 	 * blocked.  Thus, no one else will be accessing the p_mapping list
6816 	 * while we suspend and reload the locked mapping below.
6817 	 */
6818 	tpp = targ;
6819 	rpp = repl;
6820 	sfmmu_mlist_reloc_enter(tpp, rpp, &low, &high);
6821 
6822 	kpreempt_disable();
6823 
6824 	/*
6825 	 * We raise our PIL to 13 so that we don't get captured by
6826 	 * another CPU or pinned by an interrupt thread.  We can't go to
6827 	 * PIL 14 since the nexus driver(s) may need to interrupt at
6828 	 * that level in the case of IOMMU pseudo mappings.
6829 	 */
6830 	cpuset = cpu_ready_set;
6831 	CPUSET_DEL(cpuset, CPU->cpu_id);
6832 	if (!cap_cpus || CPUSET_ISNULL(cpuset)) {
6833 		old_pil = splr(XCALL_PIL);
6834 	} else {
6835 		old_pil = -1;
6836 		xc_attention(cpuset);
6837 	}
6838 	ASSERT(getpil() == XCALL_PIL);
6839 
6840 	/*
6841 	 * Now do suspend callbacks. In the case of an IOMMU mapping
6842 	 * this will suspend all DMA activity to the page while it is
6843 	 * being relocated. Since we are well above LOCK_LEVEL and CPUs
6844 	 * may be captured at this point we should have acquired any needed
6845 	 * locks in the presuspend callback.
6846 	 */
6847 	ret = hat_pageprocess_precallbacks(targ, HAT_SUSPEND, NULL);
6848 	if (ret != 0) {
6849 		repl = targ;
6850 		goto suspend_fail;
6851 	}
6852 
6853 	/*
6854 	 * Raise the PIL yet again, this time to block all high-level
6855 	 * interrupts on this CPU. This is necessary to prevent an
6856 	 * interrupt routine from pinning the thread which holds the
6857 	 * mapping suspended and then touching the suspended page.
6858 	 *
6859 	 * Once the page is suspended we also need to be careful to
6860 	 * avoid calling any functions which touch any seg_kmem memory
6861 	 * since that memory may be backed by the very page we are
6862 	 * relocating in here!
6863 	 */
6864 	hat_pagesuspend(targ);
6865 
6866 	/*
6867 	 * Now that we are confident everybody has stopped using this page,
6868 	 * copy the page contents.  Note we use a physical copy to prevent
6869 	 * locking issues and to avoid fpRAS because we can't handle it in
6870 	 * this context.
6871 	 */
6872 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6873 #ifdef VAC
6874 		/*
6875 		 * If the replacement has a different vcolor than
6876 		 * the one being replacd, we need to handle VAC
6877 		 * consistency for it just as we were setting up
6878 		 * a new mapping to it.
6879 		 */
6880 		if ((PP_GET_VCOLOR(rpp) != NO_VCOLOR) &&
6881 		    (tpp->p_vcolor != rpp->p_vcolor) &&
6882 		    !CacheColor_IsFlushed(cflags, PP_GET_VCOLOR(rpp))) {
6883 			CacheColor_SetFlushed(cflags, PP_GET_VCOLOR(rpp));
6884 			sfmmu_cache_flushcolor(PP_GET_VCOLOR(rpp),
6885 			    rpp->p_pagenum);
6886 		}
6887 #endif
6888 		/*
6889 		 * Copy the contents of the page.
6890 		 */
6891 		ppcopy_kernel(tpp, rpp);
6892 	}
6893 
6894 	tpp = targ;
6895 	rpp = repl;
6896 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6897 		/*
6898 		 * Copy attributes.  VAC consistency was handled above,
6899 		 * if required.
6900 		 */
6901 		rpp->p_nrm = tpp->p_nrm;
6902 		tpp->p_nrm = 0;
6903 		rpp->p_index = tpp->p_index;
6904 		tpp->p_index = 0;
6905 #ifdef VAC
6906 		rpp->p_vcolor = tpp->p_vcolor;
6907 #endif
6908 	}
6909 
6910 	/*
6911 	 * First, unsuspend the page, if we set the suspend bit, and transfer
6912 	 * the mapping list from the target page to the replacement page.
6913 	 * Next process postcallbacks; since pa_hment's are linked only to the
6914 	 * p_mapping list of root page, we don't iterate over the constituent
6915 	 * pages.
6916 	 */
6917 	hat_pagereload(targ, repl);
6918 
6919 suspend_fail:
6920 	hat_pageprocess_postcallbacks(repl, HAT_UNSUSPEND);
6921 
6922 	/*
6923 	 * Now lower our PIL and release any captured CPUs since we
6924 	 * are out of the "danger zone".  After this it will again be
6925 	 * safe to acquire adaptive mutex locks, or to drop them...
6926 	 */
6927 	if (old_pil != -1) {
6928 		splx(old_pil);
6929 	} else {
6930 		xc_dismissed(cpuset);
6931 	}
6932 
6933 	kpreempt_enable();
6934 
6935 	sfmmu_mlist_reloc_exit(low, high);
6936 
6937 	/*
6938 	 * Postsuspend callbacks should drop any locks held across
6939 	 * the suspend callbacks.  As before, we don't hold the mapping
6940 	 * list lock at this point.. our assumption is that the mapping
6941 	 * list still can't change due to our holding SE_EXCL lock and
6942 	 * there being no unlocked mappings left. Hence the restriction
6943 	 * on calling context to hat_delete_callback()
6944 	 */
6945 	hat_pageprocess_postcallbacks(repl, HAT_POSTUNSUSPEND);
6946 	if (ret != 0) {
6947 		/*
6948 		 * The second presuspend call failed: we got here through
6949 		 * the suspend_fail label above.
6950 		 */
6951 		ASSERT(ret != EIO);
6952 		PAGE_RELOCATE_LOG(target, replacement, ret, cap_cpus);
6953 		kreloc_thread = NULL;
6954 		mutex_exit(&kpr_mutex);
6955 		return (EAGAIN);
6956 	}
6957 
6958 	/*
6959 	 * Now that we're out of the performance critical section we can
6960 	 * take care of updating the hash table, since we still
6961 	 * hold all the pages locked SE_EXCL at this point we
6962 	 * needn't worry about things changing out from under us.
6963 	 */
6964 	tpp = targ;
6965 	rpp = repl;
6966 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6967 
6968 		/*
6969 		 * replace targ with replacement in page_hash table
6970 		 */
6971 		targ = tpp;
6972 		page_relocate_hash(rpp, targ);
6973 
6974 		/*
6975 		 * concatenate target; caller of platform_page_relocate()
6976 		 * expects target to be concatenated after returning.
6977 		 */
6978 		ASSERT(targ->p_next == targ);
6979 		ASSERT(targ->p_prev == targ);
6980 		page_list_concat(&pl, &targ);
6981 	}
6982 
6983 	ASSERT(*target == pl);
6984 	*nrelocp = npages;
6985 	PAGE_RELOCATE_LOG(target, replacement, 0, cap_cpus);
6986 	kreloc_thread = NULL;
6987 	mutex_exit(&kpr_mutex);
6988 	return (0);
6989 }
6990 
6991 /*
6992  * Called when stray pa_hments are found attached to a page which is
6993  * being freed.  Notify the subsystem which attached the pa_hment of
6994  * the error if it registered a suitable handler, else panic.
6995  */
6996 static void
6997 sfmmu_pahment_leaked(struct pa_hment *pahmep)
6998 {
6999 	id_t cb_id = pahmep->cb_id;
7000 
7001 	ASSERT(cb_id >= (id_t)0 && cb_id < sfmmu_cb_nextid);
7002 	if (sfmmu_cb_table[cb_id].errhandler != NULL) {
7003 		if (sfmmu_cb_table[cb_id].errhandler(pahmep->addr, pahmep->len,
7004 		    HAT_CB_ERR_LEAKED, pahmep->pvt) == 0)
7005 			return;		/* non-fatal */
7006 	}
7007 	panic("pa_hment leaked: 0x%p", (void *)pahmep);
7008 }
7009 
7010 /*
7011  * Remove all mappings to page 'pp'.
7012  */
7013 int
7014 hat_pageunload(struct page *pp, uint_t forceflag)
7015 {
7016 	struct page *origpp = pp;
7017 	struct sf_hment *sfhme, *tmphme;
7018 	struct hme_blk *hmeblkp;
7019 	kmutex_t *pml;
7020 #ifdef VAC
7021 	kmutex_t *pmtx;
7022 #endif
7023 	cpuset_t cpuset, tset;
7024 	int index, cons;
7025 	int pa_hments;
7026 
7027 	ASSERT(PAGE_EXCL(pp));
7028 
7029 	tmphme = NULL;
7030 	pa_hments = 0;
7031 	CPUSET_ZERO(cpuset);
7032 
7033 	pml = sfmmu_mlist_enter(pp);
7034 
7035 #ifdef VAC
7036 	if (pp->p_kpmref)
7037 		sfmmu_kpm_pageunload(pp);
7038 	ASSERT(!PP_ISMAPPED_KPM(pp));
7039 #endif
7040 	/*
7041 	 * Clear vpm reference. Since the page is exclusively locked
7042 	 * vpm cannot be referencing it.
7043 	 */
7044 	if (vpm_enable) {
7045 		pp->p_vpmref = 0;
7046 	}
7047 
7048 	index = PP_MAPINDEX(pp);
7049 	cons = TTE8K;
7050 retry:
7051 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7052 		tmphme = sfhme->hme_next;
7053 
7054 		if (IS_PAHME(sfhme)) {
7055 			ASSERT(sfhme->hme_data != NULL);
7056 			pa_hments++;
7057 			continue;
7058 		}
7059 
7060 		hmeblkp = sfmmu_hmetohblk(sfhme);
7061 
7062 		/*
7063 		 * If there are kernel mappings don't unload them, they will
7064 		 * be suspended.
7065 		 */
7066 		if (forceflag == SFMMU_KERNEL_RELOC && hmeblkp->hblk_lckcnt &&
7067 		    hmeblkp->hblk_tag.htag_id == ksfmmup)
7068 			continue;
7069 
7070 		tset = sfmmu_pageunload(pp, sfhme, cons);
7071 		CPUSET_OR(cpuset, tset);
7072 	}
7073 
7074 	while (index != 0) {
7075 		index = index >> 1;
7076 		if (index != 0)
7077 			cons++;
7078 		if (index & 0x1) {
7079 			/* Go to leading page */
7080 			pp = PP_GROUPLEADER(pp, cons);
7081 			ASSERT(sfmmu_mlist_held(pp));
7082 			goto retry;
7083 		}
7084 	}
7085 
7086 	/*
7087 	 * cpuset may be empty if the page was only mapped by segkpm,
7088 	 * in which case we won't actually cross-trap.
7089 	 */
7090 	xt_sync(cpuset);
7091 
7092 	/*
7093 	 * The page should have no mappings at this point, unless
7094 	 * we were called from hat_page_relocate() in which case we
7095 	 * leave the locked mappings which will be suspended later.
7096 	 */
7097 	ASSERT(!PP_ISMAPPED(origpp) || pa_hments ||
7098 	    (forceflag == SFMMU_KERNEL_RELOC));
7099 
7100 #ifdef VAC
7101 	if (PP_ISTNC(pp)) {
7102 		if (cons == TTE8K) {
7103 			pmtx = sfmmu_page_enter(pp);
7104 			PP_CLRTNC(pp);
7105 			sfmmu_page_exit(pmtx);
7106 		} else {
7107 			conv_tnc(pp, cons);
7108 		}
7109 	}
7110 #endif	/* VAC */
7111 
7112 	if (pa_hments && forceflag != SFMMU_KERNEL_RELOC) {
7113 		/*
7114 		 * Unlink any pa_hments and free them, calling back
7115 		 * the responsible subsystem to notify it of the error.
7116 		 * This can occur in situations such as drivers leaking
7117 		 * DMA handles: naughty, but common enough that we'd like
7118 		 * to keep the system running rather than bringing it
7119 		 * down with an obscure error like "pa_hment leaked"
7120 		 * which doesn't aid the user in debugging their driver.
7121 		 */
7122 		for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7123 			tmphme = sfhme->hme_next;
7124 			if (IS_PAHME(sfhme)) {
7125 				struct pa_hment *pahmep = sfhme->hme_data;
7126 				sfmmu_pahment_leaked(pahmep);
7127 				HME_SUB(sfhme, pp);
7128 				kmem_cache_free(pa_hment_cache, pahmep);
7129 			}
7130 		}
7131 
7132 		ASSERT(!PP_ISMAPPED(origpp));
7133 	}
7134 
7135 	sfmmu_mlist_exit(pml);
7136 
7137 	return (0);
7138 }
7139 
7140 cpuset_t
7141 sfmmu_pageunload(page_t *pp, struct sf_hment *sfhme, int cons)
7142 {
7143 	struct hme_blk *hmeblkp;
7144 	sfmmu_t *sfmmup;
7145 	tte_t tte, ttemod;
7146 #ifdef DEBUG
7147 	tte_t orig_old;
7148 #endif /* DEBUG */
7149 	caddr_t addr;
7150 	int ttesz;
7151 	int ret;
7152 	cpuset_t cpuset;
7153 
7154 	ASSERT(pp != NULL);
7155 	ASSERT(sfmmu_mlist_held(pp));
7156 	ASSERT(!PP_ISKAS(pp));
7157 
7158 	CPUSET_ZERO(cpuset);
7159 
7160 	hmeblkp = sfmmu_hmetohblk(sfhme);
7161 
7162 readtte:
7163 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7164 	if (TTE_IS_VALID(&tte)) {
7165 		sfmmup = hblktosfmmu(hmeblkp);
7166 		ttesz = get_hblk_ttesz(hmeblkp);
7167 		/*
7168 		 * Only unload mappings of 'cons' size.
7169 		 */
7170 		if (ttesz != cons)
7171 			return (cpuset);
7172 
7173 		/*
7174 		 * Note that we have p_mapping lock, but no hash lock here.
7175 		 * hblk_unload() has to have both hash lock AND p_mapping
7176 		 * lock before it tries to modify tte. So, the tte could
7177 		 * not become invalid in the sfmmu_modifytte_try() below.
7178 		 */
7179 		ttemod = tte;
7180 #ifdef DEBUG
7181 		orig_old = tte;
7182 #endif /* DEBUG */
7183 
7184 		TTE_SET_INVALID(&ttemod);
7185 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7186 		if (ret < 0) {
7187 #ifdef DEBUG
7188 			/* only R/M bits can change. */
7189 			chk_tte(&orig_old, &tte, &ttemod, hmeblkp);
7190 #endif /* DEBUG */
7191 			goto readtte;
7192 		}
7193 
7194 		if (ret == 0) {
7195 			panic("pageunload: cas failed?");
7196 		}
7197 
7198 		addr = tte_to_vaddr(hmeblkp, tte);
7199 
7200 		if (hmeblkp->hblk_shared) {
7201 			sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7202 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
7203 			sf_region_t *rgnp;
7204 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7205 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7206 			ASSERT(srdp != NULL);
7207 			rgnp = srdp->srd_hmergnp[rid];
7208 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
7209 			cpuset = sfmmu_rgntlb_demap(addr, rgnp, hmeblkp, 1);
7210 			sfmmu_ttesync(NULL, addr, &tte, pp);
7211 			ASSERT(rgnp->rgn_ttecnt[ttesz] > 0);
7212 			atomic_dec_ulong(&rgnp->rgn_ttecnt[ttesz]);
7213 		} else {
7214 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
7215 			atomic_dec_ulong(&sfmmup->sfmmu_ttecnt[ttesz]);
7216 
7217 			/*
7218 			 * We need to flush the page from the virtual cache
7219 			 * in order to prevent a virtual cache alias
7220 			 * inconsistency. The particular scenario we need
7221 			 * to worry about is:
7222 			 * Given:  va1 and va2 are two virtual address that
7223 			 * alias and will map the same physical address.
7224 			 * 1.   mapping exists from va1 to pa and data has
7225 			 *	been read into the cache.
7226 			 * 2.   unload va1.
7227 			 * 3.   load va2 and modify data using va2.
7228 			 * 4    unload va2.
7229 			 * 5.   load va1 and reference data.  Unless we flush
7230 			 *	the data cache when we unload we will get
7231 			 *	stale data.
7232 			 * This scenario is taken care of by using virtual
7233 			 * page coloring.
7234 			 */
7235 			if (sfmmup->sfmmu_ismhat) {
7236 				/*
7237 				 * Flush TSBs, TLBs and caches
7238 				 * of every process
7239 				 * sharing this ism segment.
7240 				 */
7241 				sfmmu_hat_lock_all();
7242 				mutex_enter(&ism_mlist_lock);
7243 				kpreempt_disable();
7244 				sfmmu_ismtlbcache_demap(addr, sfmmup, hmeblkp,
7245 				    pp->p_pagenum, CACHE_NO_FLUSH);
7246 				kpreempt_enable();
7247 				mutex_exit(&ism_mlist_lock);
7248 				sfmmu_hat_unlock_all();
7249 				cpuset = cpu_ready_set;
7250 			} else {
7251 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7252 				cpuset = sfmmup->sfmmu_cpusran;
7253 			}
7254 		}
7255 
7256 		/*
7257 		 * Hme_sub has to run after ttesync() and a_rss update.
7258 		 * See hblk_unload().
7259 		 */
7260 		HME_SUB(sfhme, pp);
7261 		membar_stst();
7262 
7263 		/*
7264 		 * We can not make ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
7265 		 * since pteload may have done a HME_ADD() right after
7266 		 * we did the HME_SUB() above. Hmecnt is now maintained
7267 		 * by cas only. no lock guranteed its value. The only
7268 		 * gurantee we have is the hmecnt should not be less than
7269 		 * what it should be so the hblk will not be taken away.
7270 		 * It's also important that we decremented the hmecnt after
7271 		 * we are done with hmeblkp so that this hmeblk won't be
7272 		 * stolen.
7273 		 */
7274 		ASSERT(hmeblkp->hblk_hmecnt > 0);
7275 		ASSERT(hmeblkp->hblk_vcnt > 0);
7276 		atomic_dec_16(&hmeblkp->hblk_vcnt);
7277 		atomic_dec_16(&hmeblkp->hblk_hmecnt);
7278 		/*
7279 		 * This is bug 4063182.
7280 		 * XXX: fixme
7281 		 * ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
7282 		 *	!hmeblkp->hblk_lckcnt);
7283 		 */
7284 	} else {
7285 		panic("invalid tte? pp %p &tte %p",
7286 		    (void *)pp, (void *)&tte);
7287 	}
7288 
7289 	return (cpuset);
7290 }
7291 
7292 /*
7293  * While relocating a kernel page, this function will move the mappings
7294  * from tpp to dpp and modify any associated data with these mappings.
7295  * It also unsuspends the suspended kernel mapping.
7296  */
7297 static void
7298 hat_pagereload(struct page *tpp, struct page *dpp)
7299 {
7300 	struct sf_hment *sfhme;
7301 	tte_t tte, ttemod;
7302 	int index, cons;
7303 
7304 	ASSERT(getpil() == PIL_MAX);
7305 	ASSERT(sfmmu_mlist_held(tpp));
7306 	ASSERT(sfmmu_mlist_held(dpp));
7307 
7308 	index = PP_MAPINDEX(tpp);
7309 	cons = TTE8K;
7310 
7311 	/* Update real mappings to the page */
7312 retry:
7313 	for (sfhme = tpp->p_mapping; sfhme != NULL; sfhme = sfhme->hme_next) {
7314 		if (IS_PAHME(sfhme))
7315 			continue;
7316 		sfmmu_copytte(&sfhme->hme_tte, &tte);
7317 		ttemod = tte;
7318 
7319 		/*
7320 		 * replace old pfn with new pfn in TTE
7321 		 */
7322 		PFN_TO_TTE(ttemod, dpp->p_pagenum);
7323 
7324 		/*
7325 		 * clear suspend bit
7326 		 */
7327 		ASSERT(TTE_IS_SUSPEND(&ttemod));
7328 		TTE_CLR_SUSPEND(&ttemod);
7329 
7330 		if (sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte) < 0)
7331 			panic("hat_pagereload(): sfmmu_modifytte_try() failed");
7332 
7333 		/*
7334 		 * set hme_page point to new page
7335 		 */
7336 		sfhme->hme_page = dpp;
7337 	}
7338 
7339 	/*
7340 	 * move p_mapping list from old page to new page
7341 	 */
7342 	dpp->p_mapping = tpp->p_mapping;
7343 	tpp->p_mapping = NULL;
7344 	dpp->p_share = tpp->p_share;
7345 	tpp->p_share = 0;
7346 
7347 	while (index != 0) {
7348 		index = index >> 1;
7349 		if (index != 0)
7350 			cons++;
7351 		if (index & 0x1) {
7352 			tpp = PP_GROUPLEADER(tpp, cons);
7353 			dpp = PP_GROUPLEADER(dpp, cons);
7354 			goto retry;
7355 		}
7356 	}
7357 
7358 	curthread->t_flag &= ~T_DONTDTRACE;
7359 	mutex_exit(&kpr_suspendlock);
7360 }
7361 
7362 uint_t
7363 hat_pagesync(struct page *pp, uint_t clearflag)
7364 {
7365 	struct sf_hment *sfhme, *tmphme = NULL;
7366 	struct hme_blk *hmeblkp;
7367 	kmutex_t *pml;
7368 	cpuset_t cpuset, tset;
7369 	int	index, cons;
7370 	extern	ulong_t po_share;
7371 	page_t	*save_pp = pp;
7372 	int	stop_on_sh = 0;
7373 	uint_t	shcnt;
7374 
7375 	CPUSET_ZERO(cpuset);
7376 
7377 	if (PP_ISRO(pp) && (clearflag & HAT_SYNC_STOPON_MOD)) {
7378 		return (PP_GENERIC_ATTR(pp));
7379 	}
7380 
7381 	if ((clearflag & HAT_SYNC_ZERORM) == 0) {
7382 		if ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(pp)) {
7383 			return (PP_GENERIC_ATTR(pp));
7384 		}
7385 		if ((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(pp)) {
7386 			return (PP_GENERIC_ATTR(pp));
7387 		}
7388 		if (clearflag & HAT_SYNC_STOPON_SHARED) {
7389 			if (pp->p_share > po_share) {
7390 				hat_page_setattr(pp, P_REF);
7391 				return (PP_GENERIC_ATTR(pp));
7392 			}
7393 			stop_on_sh = 1;
7394 			shcnt = 0;
7395 		}
7396 	}
7397 
7398 	clearflag &= ~HAT_SYNC_STOPON_SHARED;
7399 	pml = sfmmu_mlist_enter(pp);
7400 	index = PP_MAPINDEX(pp);
7401 	cons = TTE8K;
7402 retry:
7403 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7404 		/*
7405 		 * We need to save the next hment on the list since
7406 		 * it is possible for pagesync to remove an invalid hment
7407 		 * from the list.
7408 		 */
7409 		tmphme = sfhme->hme_next;
7410 		if (IS_PAHME(sfhme))
7411 			continue;
7412 		/*
7413 		 * If we are looking for large mappings and this hme doesn't
7414 		 * reach the range we are seeking, just ignore it.
7415 		 */
7416 		hmeblkp = sfmmu_hmetohblk(sfhme);
7417 
7418 		if (hme_size(sfhme) < cons)
7419 			continue;
7420 
7421 		if (stop_on_sh) {
7422 			if (hmeblkp->hblk_shared) {
7423 				sf_srd_t *srdp = hblktosrd(hmeblkp);
7424 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7425 				sf_region_t *rgnp;
7426 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7427 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7428 				ASSERT(srdp != NULL);
7429 				rgnp = srdp->srd_hmergnp[rid];
7430 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
7431 				    rgnp, rid);
7432 				shcnt += rgnp->rgn_refcnt;
7433 			} else {
7434 				shcnt++;
7435 			}
7436 			if (shcnt > po_share) {
7437 				/*
7438 				 * tell the pager to spare the page this time
7439 				 * around.
7440 				 */
7441 				hat_page_setattr(save_pp, P_REF);
7442 				index = 0;
7443 				break;
7444 			}
7445 		}
7446 		tset = sfmmu_pagesync(pp, sfhme,
7447 		    clearflag & ~HAT_SYNC_STOPON_RM);
7448 		CPUSET_OR(cpuset, tset);
7449 
7450 		/*
7451 		 * If clearflag is HAT_SYNC_DONTZERO, break out as soon
7452 		 * as the "ref" or "mod" is set or share cnt exceeds po_share.
7453 		 */
7454 		if ((clearflag & ~HAT_SYNC_STOPON_RM) == HAT_SYNC_DONTZERO &&
7455 		    (((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(save_pp)) ||
7456 		    ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(save_pp)))) {
7457 			index = 0;
7458 			break;
7459 		}
7460 	}
7461 
7462 	while (index) {
7463 		index = index >> 1;
7464 		cons++;
7465 		if (index & 0x1) {
7466 			/* Go to leading page */
7467 			pp = PP_GROUPLEADER(pp, cons);
7468 			goto retry;
7469 		}
7470 	}
7471 
7472 	xt_sync(cpuset);
7473 	sfmmu_mlist_exit(pml);
7474 	return (PP_GENERIC_ATTR(save_pp));
7475 }
7476 
7477 /*
7478  * Get all the hardware dependent attributes for a page struct
7479  */
7480 static cpuset_t
7481 sfmmu_pagesync(struct page *pp, struct sf_hment *sfhme,
7482     uint_t clearflag)
7483 {
7484 	caddr_t addr;
7485 	tte_t tte, ttemod;
7486 	struct hme_blk *hmeblkp;
7487 	int ret;
7488 	sfmmu_t *sfmmup;
7489 	cpuset_t cpuset;
7490 
7491 	ASSERT(pp != NULL);
7492 	ASSERT(sfmmu_mlist_held(pp));
7493 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
7494 	    (clearflag == HAT_SYNC_ZERORM));
7495 
7496 	SFMMU_STAT(sf_pagesync);
7497 
7498 	CPUSET_ZERO(cpuset);
7499 
7500 sfmmu_pagesync_retry:
7501 
7502 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7503 	if (TTE_IS_VALID(&tte)) {
7504 		hmeblkp = sfmmu_hmetohblk(sfhme);
7505 		sfmmup = hblktosfmmu(hmeblkp);
7506 		addr = tte_to_vaddr(hmeblkp, tte);
7507 		if (clearflag == HAT_SYNC_ZERORM) {
7508 			ttemod = tte;
7509 			TTE_CLR_RM(&ttemod);
7510 			ret = sfmmu_modifytte_try(&tte, &ttemod,
7511 			    &sfhme->hme_tte);
7512 			if (ret < 0) {
7513 				/*
7514 				 * cas failed and the new value is not what
7515 				 * we want.
7516 				 */
7517 				goto sfmmu_pagesync_retry;
7518 			}
7519 
7520 			if (ret > 0) {
7521 				/* we win the cas */
7522 				if (hmeblkp->hblk_shared) {
7523 					sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7524 					uint_t rid =
7525 					    hmeblkp->hblk_tag.htag_rid;
7526 					sf_region_t *rgnp;
7527 					ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7528 					ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7529 					ASSERT(srdp != NULL);
7530 					rgnp = srdp->srd_hmergnp[rid];
7531 					SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7532 					    srdp, rgnp, rid);
7533 					cpuset = sfmmu_rgntlb_demap(addr,
7534 					    rgnp, hmeblkp, 1);
7535 				} else {
7536 					sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
7537 					    0, 0);
7538 					cpuset = sfmmup->sfmmu_cpusran;
7539 				}
7540 			}
7541 		}
7542 		sfmmu_ttesync(hmeblkp->hblk_shared ? NULL : sfmmup, addr,
7543 		    &tte, pp);
7544 	}
7545 	return (cpuset);
7546 }
7547 
7548 /*
7549  * Remove write permission from a mappings to a page, so that
7550  * we can detect the next modification of it. This requires modifying
7551  * the TTE then invalidating (demap) any TLB entry using that TTE.
7552  * This code is similar to sfmmu_pagesync().
7553  */
7554 static cpuset_t
7555 sfmmu_pageclrwrt(struct page *pp, struct sf_hment *sfhme)
7556 {
7557 	caddr_t addr;
7558 	tte_t tte;
7559 	tte_t ttemod;
7560 	struct hme_blk *hmeblkp;
7561 	int ret;
7562 	sfmmu_t *sfmmup;
7563 	cpuset_t cpuset;
7564 
7565 	ASSERT(pp != NULL);
7566 	ASSERT(sfmmu_mlist_held(pp));
7567 
7568 	CPUSET_ZERO(cpuset);
7569 	SFMMU_STAT(sf_clrwrt);
7570 
7571 retry:
7572 
7573 	sfmmu_copytte(&sfhme->hme_tte, &tte);
7574 	if (TTE_IS_VALID(&tte) && TTE_IS_WRITABLE(&tte)) {
7575 		hmeblkp = sfmmu_hmetohblk(sfhme);
7576 		sfmmup = hblktosfmmu(hmeblkp);
7577 		addr = tte_to_vaddr(hmeblkp, tte);
7578 
7579 		ttemod = tte;
7580 		TTE_CLR_WRT(&ttemod);
7581 		TTE_CLR_MOD(&ttemod);
7582 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
7583 
7584 		/*
7585 		 * if cas failed and the new value is not what
7586 		 * we want retry
7587 		 */
7588 		if (ret < 0)
7589 			goto retry;
7590 
7591 		/* we win the cas */
7592 		if (ret > 0) {
7593 			if (hmeblkp->hblk_shared) {
7594 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
7595 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
7596 				sf_region_t *rgnp;
7597 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7598 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7599 				ASSERT(srdp != NULL);
7600 				rgnp = srdp->srd_hmergnp[rid];
7601 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
7602 				    srdp, rgnp, rid);
7603 				cpuset = sfmmu_rgntlb_demap(addr,
7604 				    rgnp, hmeblkp, 1);
7605 			} else {
7606 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
7607 				cpuset = sfmmup->sfmmu_cpusran;
7608 			}
7609 		}
7610 	}
7611 
7612 	return (cpuset);
7613 }
7614 
7615 /*
7616  * Walk all mappings of a page, removing write permission and clearing the
7617  * ref/mod bits. This code is similar to hat_pagesync()
7618  */
7619 static void
7620 hat_page_clrwrt(page_t *pp)
7621 {
7622 	struct sf_hment *sfhme;
7623 	struct sf_hment *tmphme = NULL;
7624 	kmutex_t *pml;
7625 	cpuset_t cpuset;
7626 	cpuset_t tset;
7627 	int	index;
7628 	int	 cons;
7629 
7630 	CPUSET_ZERO(cpuset);
7631 
7632 	pml = sfmmu_mlist_enter(pp);
7633 	index = PP_MAPINDEX(pp);
7634 	cons = TTE8K;
7635 retry:
7636 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
7637 		tmphme = sfhme->hme_next;
7638 
7639 		/*
7640 		 * If we are looking for large mappings and this hme doesn't
7641 		 * reach the range we are seeking, just ignore its.
7642 		 */
7643 
7644 		if (hme_size(sfhme) < cons)
7645 			continue;
7646 
7647 		tset = sfmmu_pageclrwrt(pp, sfhme);
7648 		CPUSET_OR(cpuset, tset);
7649 	}
7650 
7651 	while (index) {
7652 		index = index >> 1;
7653 		cons++;
7654 		if (index & 0x1) {
7655 			/* Go to leading page */
7656 			pp = PP_GROUPLEADER(pp, cons);
7657 			goto retry;
7658 		}
7659 	}
7660 
7661 	xt_sync(cpuset);
7662 	sfmmu_mlist_exit(pml);
7663 }
7664 
7665 /*
7666  * Set the given REF/MOD/RO bits for the given page.
7667  * For a vnode with a sorted v_pages list, we need to change
7668  * the attributes and the v_pages list together under page_vnode_mutex.
7669  */
7670 void
7671 hat_page_setattr(page_t *pp, uint_t flag)
7672 {
7673 	vnode_t		*vp = pp->p_vnode;
7674 	page_t		**listp;
7675 	kmutex_t	*pmtx;
7676 	kmutex_t	*vphm = NULL;
7677 	int		noshuffle;
7678 
7679 	noshuffle = flag & P_NSH;
7680 	flag &= ~P_NSH;
7681 
7682 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7683 
7684 	/*
7685 	 * nothing to do if attribute already set
7686 	 */
7687 	if ((pp->p_nrm & flag) == flag)
7688 		return;
7689 
7690 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp) &&
7691 	    !noshuffle) {
7692 		vphm = page_vnode_mutex(vp);
7693 		mutex_enter(vphm);
7694 	}
7695 
7696 	pmtx = sfmmu_page_enter(pp);
7697 	pp->p_nrm |= flag;
7698 	sfmmu_page_exit(pmtx);
7699 
7700 	if (vphm != NULL) {
7701 		/*
7702 		 * Some File Systems examine v_pages for NULL w/o
7703 		 * grabbing the vphm mutex. Must not let it become NULL when
7704 		 * pp is the only page on the list.
7705 		 */
7706 		if (pp->p_vpnext != pp) {
7707 			page_vpsub(&vp->v_pages, pp);
7708 			if (vp->v_pages != NULL)
7709 				listp = &vp->v_pages->p_vpprev->p_vpnext;
7710 			else
7711 				listp = &vp->v_pages;
7712 			page_vpadd(listp, pp);
7713 		}
7714 		mutex_exit(vphm);
7715 	}
7716 }
7717 
7718 void
7719 hat_page_clrattr(page_t *pp, uint_t flag)
7720 {
7721 	vnode_t		*vp = pp->p_vnode;
7722 	kmutex_t	*pmtx;
7723 
7724 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7725 
7726 	pmtx = sfmmu_page_enter(pp);
7727 
7728 	/*
7729 	 * Caller is expected to hold page's io lock for VMODSORT to work
7730 	 * correctly with pvn_vplist_dirty() and pvn_getdirty() when mod
7731 	 * bit is cleared.
7732 	 * We don't have assert to avoid tripping some existing third party
7733 	 * code. The dirty page is moved back to top of the v_page list
7734 	 * after IO is done in pvn_write_done().
7735 	 */
7736 	pp->p_nrm &= ~flag;
7737 	sfmmu_page_exit(pmtx);
7738 
7739 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
7740 
7741 		/*
7742 		 * VMODSORT works by removing write permissions and getting
7743 		 * a fault when a page is made dirty. At this point
7744 		 * we need to remove write permission from all mappings
7745 		 * to this page.
7746 		 */
7747 		hat_page_clrwrt(pp);
7748 	}
7749 }
7750 
7751 uint_t
7752 hat_page_getattr(page_t *pp, uint_t flag)
7753 {
7754 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7755 	return ((uint_t)(pp->p_nrm & flag));
7756 }
7757 
7758 /*
7759  * DEBUG kernels: verify that a kernel va<->pa translation
7760  * is safe by checking the underlying page_t is in a page
7761  * relocation-safe state.
7762  */
7763 #ifdef	DEBUG
7764 void
7765 sfmmu_check_kpfn(pfn_t pfn)
7766 {
7767 	page_t *pp;
7768 	int index, cons;
7769 
7770 	if (hat_check_vtop == 0)
7771 		return;
7772 
7773 	if (kvseg.s_base == NULL || panicstr)
7774 		return;
7775 
7776 	pp = page_numtopp_nolock(pfn);
7777 	if (!pp)
7778 		return;
7779 
7780 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7781 		return;
7782 
7783 	/*
7784 	 * Handed a large kernel page, we dig up the root page since we
7785 	 * know the root page might have the lock also.
7786 	 */
7787 	if (pp->p_szc != 0) {
7788 		index = PP_MAPINDEX(pp);
7789 		cons = TTE8K;
7790 again:
7791 		while (index != 0) {
7792 			index >>= 1;
7793 			if (index != 0)
7794 				cons++;
7795 			if (index & 0x1) {
7796 				pp = PP_GROUPLEADER(pp, cons);
7797 				goto again;
7798 			}
7799 		}
7800 	}
7801 
7802 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7803 		return;
7804 
7805 	/*
7806 	 * Pages need to be locked or allocated "permanent" (either from
7807 	 * static_arena arena or explicitly setting PG_NORELOC when calling
7808 	 * page_create_va()) for VA->PA translations to be valid.
7809 	 */
7810 	if (!PP_ISNORELOC(pp))
7811 		panic("Illegal VA->PA translation, pp 0x%p not permanent",
7812 		    (void *)pp);
7813 	else
7814 		panic("Illegal VA->PA translation, pp 0x%p not locked",
7815 		    (void *)pp);
7816 }
7817 #endif	/* DEBUG */
7818 
7819 /*
7820  * Returns a page frame number for a given virtual address.
7821  * Returns PFN_INVALID to indicate an invalid mapping
7822  */
7823 pfn_t
7824 hat_getpfnum(struct hat *hat, caddr_t addr)
7825 {
7826 	pfn_t pfn;
7827 	tte_t tte;
7828 
7829 	/*
7830 	 * We would like to
7831 	 * ASSERT(AS_LOCK_HELD(as));
7832 	 * but we can't because the iommu driver will call this
7833 	 * routine at interrupt time and it can't grab the as lock
7834 	 * or it will deadlock: A thread could have the as lock
7835 	 * and be waiting for io.  The io can't complete
7836 	 * because the interrupt thread is blocked trying to grab
7837 	 * the as lock.
7838 	 */
7839 
7840 	if (hat == ksfmmup) {
7841 		if (IS_KMEM_VA_LARGEPAGE(addr)) {
7842 			ASSERT(segkmem_lpszc > 0);
7843 			pfn = sfmmu_kvaszc2pfn(addr, segkmem_lpszc);
7844 			if (pfn != PFN_INVALID) {
7845 				sfmmu_check_kpfn(pfn);
7846 				return (pfn);
7847 			}
7848 		} else if (segkpm && IS_KPM_ADDR(addr)) {
7849 			return (sfmmu_kpm_vatopfn(addr));
7850 		}
7851 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7852 		    == PFN_SUSPENDED) {
7853 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7854 		}
7855 		sfmmu_check_kpfn(pfn);
7856 		return (pfn);
7857 	} else {
7858 		return (sfmmu_uvatopfn(addr, hat, NULL));
7859 	}
7860 }
7861 
7862 /*
7863  * This routine will return both pfn and tte for the vaddr.
7864  */
7865 static pfn_t
7866 sfmmu_uvatopfn(caddr_t vaddr, struct hat *sfmmup, tte_t *ttep)
7867 {
7868 	struct hmehash_bucket *hmebp;
7869 	hmeblk_tag hblktag;
7870 	int hmeshift, hashno = 1;
7871 	struct hme_blk *hmeblkp = NULL;
7872 	tte_t tte;
7873 
7874 	struct sf_hment *sfhmep;
7875 	pfn_t pfn;
7876 
7877 	/* support for ISM */
7878 	ism_map_t	*ism_map;
7879 	ism_blk_t	*ism_blkp;
7880 	int		i;
7881 	sfmmu_t *ism_hatid = NULL;
7882 	sfmmu_t *locked_hatid = NULL;
7883 	sfmmu_t	*sv_sfmmup = sfmmup;
7884 	caddr_t	sv_vaddr = vaddr;
7885 	sf_srd_t *srdp;
7886 
7887 	if (ttep == NULL) {
7888 		ttep = &tte;
7889 	} else {
7890 		ttep->ll = 0;
7891 	}
7892 
7893 	ASSERT(sfmmup != ksfmmup);
7894 	SFMMU_STAT(sf_user_vtop);
7895 	/*
7896 	 * Set ism_hatid if vaddr falls in a ISM segment.
7897 	 */
7898 	ism_blkp = sfmmup->sfmmu_iblk;
7899 	if (ism_blkp != NULL) {
7900 		sfmmu_ismhat_enter(sfmmup, 0);
7901 		locked_hatid = sfmmup;
7902 	}
7903 	while (ism_blkp != NULL && ism_hatid == NULL) {
7904 		ism_map = ism_blkp->iblk_maps;
7905 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
7906 			if (vaddr >= ism_start(ism_map[i]) &&
7907 			    vaddr < ism_end(ism_map[i])) {
7908 				sfmmup = ism_hatid = ism_map[i].imap_ismhat;
7909 				vaddr = (caddr_t)(vaddr -
7910 				    ism_start(ism_map[i]));
7911 				break;
7912 			}
7913 		}
7914 		ism_blkp = ism_blkp->iblk_next;
7915 	}
7916 	if (locked_hatid) {
7917 		sfmmu_ismhat_exit(locked_hatid, 0);
7918 	}
7919 
7920 	hblktag.htag_id = sfmmup;
7921 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
7922 	do {
7923 		hmeshift = HME_HASH_SHIFT(hashno);
7924 		hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
7925 		hblktag.htag_rehash = hashno;
7926 		hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
7927 
7928 		SFMMU_HASH_LOCK(hmebp);
7929 
7930 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
7931 		if (hmeblkp != NULL) {
7932 			ASSERT(!hmeblkp->hblk_shared);
7933 			HBLKTOHME(sfhmep, hmeblkp, vaddr);
7934 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
7935 			SFMMU_HASH_UNLOCK(hmebp);
7936 			if (TTE_IS_VALID(ttep)) {
7937 				pfn = TTE_TO_PFN(vaddr, ttep);
7938 				return (pfn);
7939 			}
7940 			break;
7941 		}
7942 		SFMMU_HASH_UNLOCK(hmebp);
7943 		hashno++;
7944 	} while (HME_REHASH(sfmmup) && (hashno <= mmu_hashcnt));
7945 
7946 	if (SF_HMERGNMAP_ISNULL(sv_sfmmup)) {
7947 		return (PFN_INVALID);
7948 	}
7949 	srdp = sv_sfmmup->sfmmu_srdp;
7950 	ASSERT(srdp != NULL);
7951 	ASSERT(srdp->srd_refcnt != 0);
7952 	hblktag.htag_id = srdp;
7953 	hashno = 1;
7954 	do {
7955 		hmeshift = HME_HASH_SHIFT(hashno);
7956 		hblktag.htag_bspage = HME_HASH_BSPAGE(sv_vaddr, hmeshift);
7957 		hblktag.htag_rehash = hashno;
7958 		hmebp = HME_HASH_FUNCTION(srdp, sv_vaddr, hmeshift);
7959 
7960 		SFMMU_HASH_LOCK(hmebp);
7961 		for (hmeblkp = hmebp->hmeblkp; hmeblkp != NULL;
7962 		    hmeblkp = hmeblkp->hblk_next) {
7963 			uint_t rid;
7964 			sf_region_t *rgnp;
7965 			caddr_t rsaddr;
7966 			caddr_t readdr;
7967 
7968 			if (!HTAGS_EQ_SHME(hmeblkp->hblk_tag, hblktag,
7969 			    sv_sfmmup->sfmmu_hmeregion_map)) {
7970 				continue;
7971 			}
7972 			ASSERT(hmeblkp->hblk_shared);
7973 			rid = hmeblkp->hblk_tag.htag_rid;
7974 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
7975 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
7976 			rgnp = srdp->srd_hmergnp[rid];
7977 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
7978 			HBLKTOHME(sfhmep, hmeblkp, sv_vaddr);
7979 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
7980 			rsaddr = rgnp->rgn_saddr;
7981 			readdr = rsaddr + rgnp->rgn_size;
7982 #ifdef DEBUG
7983 			if (TTE_IS_VALID(ttep) ||
7984 			    get_hblk_ttesz(hmeblkp) > TTE8K) {
7985 				caddr_t eva = tte_to_evaddr(hmeblkp, ttep);
7986 				ASSERT(eva > sv_vaddr);
7987 				ASSERT(sv_vaddr >= rsaddr);
7988 				ASSERT(sv_vaddr < readdr);
7989 				ASSERT(eva <= readdr);
7990 			}
7991 #endif /* DEBUG */
7992 			/*
7993 			 * Continue the search if we
7994 			 * found an invalid 8K tte outside of the area
7995 			 * covered by this hmeblk's region.
7996 			 */
7997 			if (TTE_IS_VALID(ttep)) {
7998 				SFMMU_HASH_UNLOCK(hmebp);
7999 				pfn = TTE_TO_PFN(sv_vaddr, ttep);
8000 				return (pfn);
8001 			} else if (get_hblk_ttesz(hmeblkp) > TTE8K ||
8002 			    (sv_vaddr >= rsaddr && sv_vaddr < readdr)) {
8003 				SFMMU_HASH_UNLOCK(hmebp);
8004 				pfn = PFN_INVALID;
8005 				return (pfn);
8006 			}
8007 		}
8008 		SFMMU_HASH_UNLOCK(hmebp);
8009 		hashno++;
8010 	} while (hashno <= mmu_hashcnt);
8011 	return (PFN_INVALID);
8012 }
8013 
8014 
8015 /*
8016  * For compatability with AT&T and later optimizations
8017  */
8018 /* ARGSUSED */
8019 void
8020 hat_map(struct hat *hat, caddr_t addr, size_t len, uint_t flags)
8021 {
8022 	ASSERT(hat != NULL);
8023 }
8024 
8025 /*
8026  * Return the number of mappings to a particular page.  This number is an
8027  * approximation of the number of people sharing the page.
8028  *
8029  * shared hmeblks or ism hmeblks are counted as 1 mapping here.
8030  * hat_page_checkshare() can be used to compare threshold to share
8031  * count that reflects the number of region sharers albeit at higher cost.
8032  */
8033 ulong_t
8034 hat_page_getshare(page_t *pp)
8035 {
8036 	page_t *spp = pp;	/* start page */
8037 	kmutex_t *pml;
8038 	ulong_t	cnt;
8039 	int index, sz = TTE64K;
8040 
8041 	/*
8042 	 * We need to grab the mlist lock to make sure any outstanding
8043 	 * load/unloads complete.  Otherwise we could return zero
8044 	 * even though the unload(s) hasn't finished yet.
8045 	 */
8046 	pml = sfmmu_mlist_enter(spp);
8047 	cnt = spp->p_share;
8048 
8049 #ifdef VAC
8050 	if (kpm_enable)
8051 		cnt += spp->p_kpmref;
8052 #endif
8053 	if (vpm_enable && pp->p_vpmref) {
8054 		cnt += 1;
8055 	}
8056 
8057 	/*
8058 	 * If we have any large mappings, we count the number of
8059 	 * mappings that this large page is part of.
8060 	 */
8061 	index = PP_MAPINDEX(spp);
8062 	index >>= 1;
8063 	while (index) {
8064 		pp = PP_GROUPLEADER(spp, sz);
8065 		if ((index & 0x1) && pp != spp) {
8066 			cnt += pp->p_share;
8067 			spp = pp;
8068 		}
8069 		index >>= 1;
8070 		sz++;
8071 	}
8072 	sfmmu_mlist_exit(pml);
8073 	return (cnt);
8074 }
8075 
8076 /*
8077  * Return 1 if the number of mappings exceeds sh_thresh. Return 0
8078  * otherwise. Count shared hmeblks by region's refcnt.
8079  */
8080 int
8081 hat_page_checkshare(page_t *pp, ulong_t sh_thresh)
8082 {
8083 	kmutex_t *pml;
8084 	ulong_t	cnt = 0;
8085 	int index, sz = TTE8K;
8086 	struct sf_hment *sfhme, *tmphme = NULL;
8087 	struct hme_blk *hmeblkp;
8088 
8089 	pml = sfmmu_mlist_enter(pp);
8090 
8091 #ifdef VAC
8092 	if (kpm_enable)
8093 		cnt = pp->p_kpmref;
8094 #endif
8095 
8096 	if (vpm_enable && pp->p_vpmref) {
8097 		cnt += 1;
8098 	}
8099 
8100 	if (pp->p_share + cnt > sh_thresh) {
8101 		sfmmu_mlist_exit(pml);
8102 		return (1);
8103 	}
8104 
8105 	index = PP_MAPINDEX(pp);
8106 
8107 again:
8108 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
8109 		tmphme = sfhme->hme_next;
8110 		if (IS_PAHME(sfhme)) {
8111 			continue;
8112 		}
8113 
8114 		hmeblkp = sfmmu_hmetohblk(sfhme);
8115 		if (hme_size(sfhme) != sz) {
8116 			continue;
8117 		}
8118 
8119 		if (hmeblkp->hblk_shared) {
8120 			sf_srd_t *srdp = hblktosrd(hmeblkp);
8121 			uint_t rid = hmeblkp->hblk_tag.htag_rid;
8122 			sf_region_t *rgnp;
8123 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
8124 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
8125 			ASSERT(srdp != NULL);
8126 			rgnp = srdp->srd_hmergnp[rid];
8127 			SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp,
8128 			    rgnp, rid);
8129 			cnt += rgnp->rgn_refcnt;
8130 		} else {
8131 			cnt++;
8132 		}
8133 		if (cnt > sh_thresh) {
8134 			sfmmu_mlist_exit(pml);
8135 			return (1);
8136 		}
8137 	}
8138 
8139 	index >>= 1;
8140 	sz++;
8141 	while (index) {
8142 		pp = PP_GROUPLEADER(pp, sz);
8143 		ASSERT(sfmmu_mlist_held(pp));
8144 		if (index & 0x1) {
8145 			goto again;
8146 		}
8147 		index >>= 1;
8148 		sz++;
8149 	}
8150 	sfmmu_mlist_exit(pml);
8151 	return (0);
8152 }
8153 
8154 /*
8155  * Unload all large mappings to the pp and reset the p_szc field of every
8156  * constituent page according to the remaining mappings.
8157  *
8158  * pp must be locked SE_EXCL. Even though no other constituent pages are
8159  * locked it's legal to unload the large mappings to the pp because all
8160  * constituent pages of large locked mappings have to be locked SE_SHARED.
8161  * This means if we have SE_EXCL lock on one of constituent pages none of the
8162  * large mappings to pp are locked.
8163  *
8164  * Decrease p_szc field starting from the last constituent page and ending
8165  * with the root page. This method is used because other threads rely on the
8166  * root's p_szc to find the lock to syncronize on. After a root page_t's p_szc
8167  * is demoted then other threads will succeed in sfmmu_mlspl_enter(). This
8168  * ensures that p_szc changes of the constituent pages appears atomic for all
8169  * threads that use sfmmu_mlspl_enter() to examine p_szc field.
8170  *
8171  * This mechanism is only used for file system pages where it's not always
8172  * possible to get SE_EXCL locks on all constituent pages to demote the size
8173  * code (as is done for anonymous or kernel large pages).
8174  *
8175  * See more comments in front of sfmmu_mlspl_enter().
8176  */
8177 void
8178 hat_page_demote(page_t *pp)
8179 {
8180 	int index;
8181 	int sz;
8182 	cpuset_t cpuset;
8183 	int sync = 0;
8184 	page_t *rootpp;
8185 	struct sf_hment *sfhme;
8186 	struct sf_hment *tmphme = NULL;
8187 	uint_t pszc;
8188 	page_t *lastpp;
8189 	cpuset_t tset;
8190 	pgcnt_t npgs;
8191 	kmutex_t *pml;
8192 	kmutex_t *pmtx = NULL;
8193 
8194 	ASSERT(PAGE_EXCL(pp));
8195 	ASSERT(!PP_ISFREE(pp));
8196 	ASSERT(!PP_ISKAS(pp));
8197 	ASSERT(page_szc_lock_assert(pp));
8198 	pml = sfmmu_mlist_enter(pp);
8199 
8200 	pszc = pp->p_szc;
8201 	if (pszc == 0) {
8202 		goto out;
8203 	}
8204 
8205 	index = PP_MAPINDEX(pp) >> 1;
8206 
8207 	if (index) {
8208 		CPUSET_ZERO(cpuset);
8209 		sz = TTE64K;
8210 		sync = 1;
8211 	}
8212 
8213 	while (index) {
8214 		if (!(index & 0x1)) {
8215 			index >>= 1;
8216 			sz++;
8217 			continue;
8218 		}
8219 		ASSERT(sz <= pszc);
8220 		rootpp = PP_GROUPLEADER(pp, sz);
8221 		for (sfhme = rootpp->p_mapping; sfhme; sfhme = tmphme) {
8222 			tmphme = sfhme->hme_next;
8223 			ASSERT(!IS_PAHME(sfhme));
8224 			if (hme_size(sfhme) != sz) {
8225 				continue;
8226 			}
8227 			tset = sfmmu_pageunload(rootpp, sfhme, sz);
8228 			CPUSET_OR(cpuset, tset);
8229 		}
8230 		if (index >>= 1) {
8231 			sz++;
8232 		}
8233 	}
8234 
8235 	ASSERT(!PP_ISMAPPED_LARGE(pp));
8236 
8237 	if (sync) {
8238 		xt_sync(cpuset);
8239 #ifdef VAC
8240 		if (PP_ISTNC(pp)) {
8241 			conv_tnc(rootpp, sz);
8242 		}
8243 #endif	/* VAC */
8244 	}
8245 
8246 	pmtx = sfmmu_page_enter(pp);
8247 
8248 	ASSERT(pp->p_szc == pszc);
8249 	rootpp = PP_PAGEROOT(pp);
8250 	ASSERT(rootpp->p_szc == pszc);
8251 	lastpp = PP_PAGENEXT_N(rootpp, TTEPAGES(pszc) - 1);
8252 
8253 	while (lastpp != rootpp) {
8254 		sz = PP_MAPINDEX(lastpp) ? fnd_mapping_sz(lastpp) : 0;
8255 		ASSERT(sz < pszc);
8256 		npgs = (sz == 0) ? 1 : TTEPAGES(sz);
8257 		ASSERT(P2PHASE(lastpp->p_pagenum, npgs) == npgs - 1);
8258 		while (--npgs > 0) {
8259 			lastpp->p_szc = (uchar_t)sz;
8260 			lastpp = PP_PAGEPREV(lastpp);
8261 		}
8262 		if (sz) {
8263 			/*
8264 			 * make sure before current root's pszc
8265 			 * is updated all updates to constituent pages pszc
8266 			 * fields are globally visible.
8267 			 */
8268 			membar_producer();
8269 		}
8270 		lastpp->p_szc = sz;
8271 		ASSERT(IS_P2ALIGNED(lastpp->p_pagenum, TTEPAGES(sz)));
8272 		if (lastpp != rootpp) {
8273 			lastpp = PP_PAGEPREV(lastpp);
8274 		}
8275 	}
8276 	if (sz == 0) {
8277 		/* the loop above doesn't cover this case */
8278 		rootpp->p_szc = 0;
8279 	}
8280 out:
8281 	ASSERT(pp->p_szc == 0);
8282 	if (pmtx != NULL) {
8283 		sfmmu_page_exit(pmtx);
8284 	}
8285 	sfmmu_mlist_exit(pml);
8286 }
8287 
8288 /*
8289  * Refresh the HAT ismttecnt[] element for size szc.
8290  * Caller must have set ISM busy flag to prevent mapping
8291  * lists from changing while we're traversing them.
8292  */
8293 pgcnt_t
8294 ism_tsb_entries(sfmmu_t *sfmmup, int szc)
8295 {
8296 	ism_blk_t	*ism_blkp = sfmmup->sfmmu_iblk;
8297 	ism_map_t	*ism_map;
8298 	pgcnt_t		npgs = 0;
8299 	pgcnt_t		npgs_scd = 0;
8300 	int		j;
8301 	sf_scd_t	*scdp;
8302 	uchar_t		rid;
8303 
8304 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
8305 	scdp = sfmmup->sfmmu_scdp;
8306 
8307 	for (; ism_blkp != NULL; ism_blkp = ism_blkp->iblk_next) {
8308 		ism_map = ism_blkp->iblk_maps;
8309 		for (j = 0; ism_map[j].imap_ismhat && j < ISM_MAP_SLOTS; j++) {
8310 			rid = ism_map[j].imap_rid;
8311 			ASSERT(rid == SFMMU_INVALID_ISMRID ||
8312 			    rid < sfmmup->sfmmu_srdp->srd_next_ismrid);
8313 
8314 			if (scdp != NULL && rid != SFMMU_INVALID_ISMRID &&
8315 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
8316 				/* ISM is in sfmmup's SCD */
8317 				npgs_scd +=
8318 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8319 			} else {
8320 				/* ISMs is not in SCD */
8321 				npgs +=
8322 				    ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
8323 			}
8324 		}
8325 	}
8326 	sfmmup->sfmmu_ismttecnt[szc] = npgs;
8327 	sfmmup->sfmmu_scdismttecnt[szc] = npgs_scd;
8328 	return (npgs);
8329 }
8330 
8331 /*
8332  * Yield the memory claim requirement for an address space.
8333  *
8334  * This is currently implemented as the number of bytes that have active
8335  * hardware translations that have page structures.  Therefore, it can
8336  * underestimate the traditional resident set size, eg, if the
8337  * physical page is present and the hardware translation is missing;
8338  * and it can overestimate the rss, eg, if there are active
8339  * translations to a frame buffer with page structs.
8340  * Also, it does not take sharing into account.
8341  *
8342  * Note that we don't acquire locks here since this function is most often
8343  * called from the clock thread.
8344  */
8345 size_t
8346 hat_get_mapped_size(struct hat *hat)
8347 {
8348 	size_t		assize = 0;
8349 	int		i;
8350 
8351 	if (hat == NULL)
8352 		return (0);
8353 
8354 	for (i = 0; i < mmu_page_sizes; i++)
8355 		assize += ((pgcnt_t)hat->sfmmu_ttecnt[i] +
8356 		    (pgcnt_t)hat->sfmmu_scdrttecnt[i]) * TTEBYTES(i);
8357 
8358 	if (hat->sfmmu_iblk == NULL)
8359 		return (assize);
8360 
8361 	for (i = 0; i < mmu_page_sizes; i++)
8362 		assize += ((pgcnt_t)hat->sfmmu_ismttecnt[i] +
8363 		    (pgcnt_t)hat->sfmmu_scdismttecnt[i]) * TTEBYTES(i);
8364 
8365 	return (assize);
8366 }
8367 
8368 int
8369 hat_stats_enable(struct hat *hat)
8370 {
8371 	hatlock_t	*hatlockp;
8372 
8373 	hatlockp = sfmmu_hat_enter(hat);
8374 	hat->sfmmu_rmstat++;
8375 	sfmmu_hat_exit(hatlockp);
8376 	return (1);
8377 }
8378 
8379 void
8380 hat_stats_disable(struct hat *hat)
8381 {
8382 	hatlock_t	*hatlockp;
8383 
8384 	hatlockp = sfmmu_hat_enter(hat);
8385 	hat->sfmmu_rmstat--;
8386 	sfmmu_hat_exit(hatlockp);
8387 }
8388 
8389 /*
8390  * Routines for entering or removing  ourselves from the
8391  * ism_hat's mapping list. This is used for both private and
8392  * SCD hats.
8393  */
8394 static void
8395 iment_add(struct ism_ment *iment,  struct hat *ism_hat)
8396 {
8397 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8398 
8399 	iment->iment_prev = NULL;
8400 	iment->iment_next = ism_hat->sfmmu_iment;
8401 	if (ism_hat->sfmmu_iment) {
8402 		ism_hat->sfmmu_iment->iment_prev = iment;
8403 	}
8404 	ism_hat->sfmmu_iment = iment;
8405 }
8406 
8407 static void
8408 iment_sub(struct ism_ment *iment, struct hat *ism_hat)
8409 {
8410 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
8411 
8412 	if (ism_hat->sfmmu_iment == NULL) {
8413 		panic("ism map entry remove - no entries");
8414 	}
8415 
8416 	if (iment->iment_prev) {
8417 		ASSERT(ism_hat->sfmmu_iment != iment);
8418 		iment->iment_prev->iment_next = iment->iment_next;
8419 	} else {
8420 		ASSERT(ism_hat->sfmmu_iment == iment);
8421 		ism_hat->sfmmu_iment = iment->iment_next;
8422 	}
8423 
8424 	if (iment->iment_next) {
8425 		iment->iment_next->iment_prev = iment->iment_prev;
8426 	}
8427 
8428 	/*
8429 	 * zero out the entry
8430 	 */
8431 	iment->iment_next = NULL;
8432 	iment->iment_prev = NULL;
8433 	iment->iment_hat =  NULL;
8434 	iment->iment_base_va = 0;
8435 }
8436 
8437 /*
8438  * Hat_share()/unshare() return an (non-zero) error
8439  * when saddr and daddr are not properly aligned.
8440  *
8441  * The top level mapping element determines the alignment
8442  * requirement for saddr and daddr, depending on different
8443  * architectures.
8444  *
8445  * When hat_share()/unshare() are not supported,
8446  * HATOP_SHARE()/UNSHARE() return 0
8447  */
8448 int
8449 hat_share(struct hat *sfmmup, caddr_t addr, struct hat *ism_hatid,
8450     caddr_t sptaddr, size_t len, uint_t ismszc)
8451 {
8452 	ism_blk_t	*ism_blkp;
8453 	ism_blk_t	*new_iblk;
8454 	ism_map_t	*ism_map;
8455 	ism_ment_t	*ism_ment;
8456 	int		i, added;
8457 	hatlock_t	*hatlockp;
8458 	int		reload_mmu = 0;
8459 	uint_t		ismshift = page_get_shift(ismszc);
8460 	size_t		ismpgsz = page_get_pagesize(ismszc);
8461 	uint_t		ismmask = (uint_t)ismpgsz - 1;
8462 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8463 	ushort_t	ismhatflag;
8464 	hat_region_cookie_t rcookie;
8465 	sf_scd_t	*old_scdp;
8466 
8467 #ifdef DEBUG
8468 	caddr_t		eaddr = addr + len;
8469 #endif /* DEBUG */
8470 
8471 	ASSERT(ism_hatid != NULL && sfmmup != NULL);
8472 	ASSERT(sptaddr == ISMID_STARTADDR);
8473 	/*
8474 	 * Check the alignment.
8475 	 */
8476 	if (!ISM_ALIGNED(ismshift, addr) || !ISM_ALIGNED(ismshift, sptaddr))
8477 		return (EINVAL);
8478 
8479 	/*
8480 	 * Check size alignment.
8481 	 */
8482 	if (!ISM_ALIGNED(ismshift, len))
8483 		return (EINVAL);
8484 
8485 	/*
8486 	 * Allocate ism_ment for the ism_hat's mapping list, and an
8487 	 * ism map blk in case we need one.  We must do our
8488 	 * allocations before acquiring locks to prevent a deadlock
8489 	 * in the kmem allocator on the mapping list lock.
8490 	 */
8491 	new_iblk = kmem_cache_alloc(ism_blk_cache, KM_SLEEP);
8492 	ism_ment = kmem_cache_alloc(ism_ment_cache, KM_SLEEP);
8493 
8494 	/*
8495 	 * Serialize ISM mappings with the ISM busy flag, and also the
8496 	 * trap handlers.
8497 	 */
8498 	sfmmu_ismhat_enter(sfmmup, 0);
8499 
8500 	/*
8501 	 * Allocate an ism map blk if necessary.
8502 	 */
8503 	if (sfmmup->sfmmu_iblk == NULL) {
8504 		sfmmup->sfmmu_iblk = new_iblk;
8505 		bzero(new_iblk, sizeof (*new_iblk));
8506 		new_iblk->iblk_nextpa = (uint64_t)-1;
8507 		membar_stst();	/* make sure next ptr visible to all CPUs */
8508 		sfmmup->sfmmu_ismblkpa = va_to_pa((caddr_t)new_iblk);
8509 		reload_mmu = 1;
8510 		new_iblk = NULL;
8511 	}
8512 
8513 #ifdef DEBUG
8514 	/*
8515 	 * Make sure mapping does not already exist.
8516 	 */
8517 	ism_blkp = sfmmup->sfmmu_iblk;
8518 	while (ism_blkp != NULL) {
8519 		ism_map = ism_blkp->iblk_maps;
8520 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
8521 			if ((addr >= ism_start(ism_map[i]) &&
8522 			    addr < ism_end(ism_map[i])) ||
8523 			    eaddr > ism_start(ism_map[i]) &&
8524 			    eaddr <= ism_end(ism_map[i])) {
8525 				panic("sfmmu_share: Already mapped!");
8526 			}
8527 		}
8528 		ism_blkp = ism_blkp->iblk_next;
8529 	}
8530 #endif /* DEBUG */
8531 
8532 	ASSERT(ismszc >= TTE4M);
8533 	if (ismszc == TTE4M) {
8534 		ismhatflag = HAT_4M_FLAG;
8535 	} else if (ismszc == TTE32M) {
8536 		ismhatflag = HAT_32M_FLAG;
8537 	} else if (ismszc == TTE256M) {
8538 		ismhatflag = HAT_256M_FLAG;
8539 	}
8540 	/*
8541 	 * Add mapping to first available mapping slot.
8542 	 */
8543 	ism_blkp = sfmmup->sfmmu_iblk;
8544 	added = 0;
8545 	while (!added) {
8546 		ism_map = ism_blkp->iblk_maps;
8547 		for (i = 0; i < ISM_MAP_SLOTS; i++)  {
8548 			if (ism_map[i].imap_ismhat == NULL) {
8549 
8550 				ism_map[i].imap_ismhat = ism_hatid;
8551 				ism_map[i].imap_vb_shift = (uchar_t)ismshift;
8552 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8553 				ism_map[i].imap_hatflags = ismhatflag;
8554 				ism_map[i].imap_sz_mask = ismmask;
8555 				/*
8556 				 * imap_seg is checked in ISM_CHECK to see if
8557 				 * non-NULL, then other info assumed valid.
8558 				 */
8559 				membar_stst();
8560 				ism_map[i].imap_seg = (uintptr_t)addr | sh_size;
8561 				ism_map[i].imap_ment = ism_ment;
8562 
8563 				/*
8564 				 * Now add ourselves to the ism_hat's
8565 				 * mapping list.
8566 				 */
8567 				ism_ment->iment_hat = sfmmup;
8568 				ism_ment->iment_base_va = addr;
8569 				ism_hatid->sfmmu_ismhat = 1;
8570 				mutex_enter(&ism_mlist_lock);
8571 				iment_add(ism_ment, ism_hatid);
8572 				mutex_exit(&ism_mlist_lock);
8573 				added = 1;
8574 				break;
8575 			}
8576 		}
8577 		if (!added && ism_blkp->iblk_next == NULL) {
8578 			ism_blkp->iblk_next = new_iblk;
8579 			new_iblk = NULL;
8580 			bzero(ism_blkp->iblk_next,
8581 			    sizeof (*ism_blkp->iblk_next));
8582 			ism_blkp->iblk_next->iblk_nextpa = (uint64_t)-1;
8583 			membar_stst();
8584 			ism_blkp->iblk_nextpa =
8585 			    va_to_pa((caddr_t)ism_blkp->iblk_next);
8586 		}
8587 		ism_blkp = ism_blkp->iblk_next;
8588 	}
8589 
8590 	/*
8591 	 * After calling hat_join_region, sfmmup may join a new SCD or
8592 	 * move from the old scd to a new scd, in which case, we want to
8593 	 * shrink the sfmmup's private tsb size, i.e., pass shrink to
8594 	 * sfmmu_check_page_sizes at the end of this routine.
8595 	 */
8596 	old_scdp = sfmmup->sfmmu_scdp;
8597 
8598 	rcookie = hat_join_region(sfmmup, addr, len, (void *)ism_hatid, 0,
8599 	    PROT_ALL, ismszc, NULL, HAT_REGION_ISM);
8600 	if (rcookie != HAT_INVALID_REGION_COOKIE) {
8601 		ism_map[i].imap_rid = (uchar_t)((uint64_t)rcookie);
8602 	}
8603 	/*
8604 	 * Update our counters for this sfmmup's ism mappings.
8605 	 */
8606 	for (i = 0; i <= ismszc; i++) {
8607 		if (!(disable_ism_large_pages & (1 << i)))
8608 			(void) ism_tsb_entries(sfmmup, i);
8609 	}
8610 
8611 	/*
8612 	 * For ISM and DISM we do not support 512K pages, so we only only
8613 	 * search the 4M and 8K/64K hashes for 4 pagesize cpus, and search the
8614 	 * 256M or 32M, and 4M and 8K/64K hashes for 6 pagesize cpus.
8615 	 *
8616 	 * Need to set 32M/256M ISM flags to make sure
8617 	 * sfmmu_check_page_sizes() enables them on Panther.
8618 	 */
8619 	ASSERT((disable_ism_large_pages & (1 << TTE512K)) != 0);
8620 
8621 	switch (ismszc) {
8622 	case TTE256M:
8623 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_256M_ISM)) {
8624 			hatlockp = sfmmu_hat_enter(sfmmup);
8625 			SFMMU_FLAGS_SET(sfmmup, HAT_256M_ISM);
8626 			sfmmu_hat_exit(hatlockp);
8627 		}
8628 		break;
8629 	case TTE32M:
8630 		if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_32M_ISM)) {
8631 			hatlockp = sfmmu_hat_enter(sfmmup);
8632 			SFMMU_FLAGS_SET(sfmmup, HAT_32M_ISM);
8633 			sfmmu_hat_exit(hatlockp);
8634 		}
8635 		break;
8636 	default:
8637 		break;
8638 	}
8639 
8640 	/*
8641 	 * If we updated the ismblkpa for this HAT we must make
8642 	 * sure all CPUs running this process reload their tsbmiss area.
8643 	 * Otherwise they will fail to load the mappings in the tsbmiss
8644 	 * handler and will loop calling pagefault().
8645 	 */
8646 	if (reload_mmu) {
8647 		hatlockp = sfmmu_hat_enter(sfmmup);
8648 		sfmmu_sync_mmustate(sfmmup);
8649 		sfmmu_hat_exit(hatlockp);
8650 	}
8651 
8652 	sfmmu_ismhat_exit(sfmmup, 0);
8653 
8654 	/*
8655 	 * Free up ismblk if we didn't use it.
8656 	 */
8657 	if (new_iblk != NULL)
8658 		kmem_cache_free(ism_blk_cache, new_iblk);
8659 
8660 	/*
8661 	 * Check TSB and TLB page sizes.
8662 	 */
8663 	if (sfmmup->sfmmu_scdp != NULL && old_scdp != sfmmup->sfmmu_scdp) {
8664 		sfmmu_check_page_sizes(sfmmup, 0);
8665 	} else {
8666 		sfmmu_check_page_sizes(sfmmup, 1);
8667 	}
8668 	return (0);
8669 }
8670 
8671 /*
8672  * hat_unshare removes exactly one ism_map from
8673  * this process's as.  It expects multiple calls
8674  * to hat_unshare for multiple shm segments.
8675  */
8676 void
8677 hat_unshare(struct hat *sfmmup, caddr_t addr, size_t len, uint_t ismszc)
8678 {
8679 	ism_map_t	*ism_map;
8680 	ism_ment_t	*free_ment = NULL;
8681 	ism_blk_t	*ism_blkp;
8682 	struct hat	*ism_hatid;
8683 	int		found, i;
8684 	hatlock_t	*hatlockp;
8685 	struct tsb_info	*tsbinfo;
8686 	uint_t		ismshift = page_get_shift(ismszc);
8687 	size_t		sh_size = ISM_SHIFT(ismshift, len);
8688 	uchar_t		ism_rid;
8689 	sf_scd_t	*old_scdp;
8690 
8691 	ASSERT(ISM_ALIGNED(ismshift, addr));
8692 	ASSERT(ISM_ALIGNED(ismshift, len));
8693 	ASSERT(sfmmup != NULL);
8694 	ASSERT(sfmmup != ksfmmup);
8695 
8696 	ASSERT(sfmmup->sfmmu_as != NULL);
8697 
8698 	/*
8699 	 * Make sure that during the entire time ISM mappings are removed,
8700 	 * the trap handlers serialize behind us, and that no one else
8701 	 * can be mucking with ISM mappings.  This also lets us get away
8702 	 * with not doing expensive cross calls to flush the TLB -- we
8703 	 * just discard the context, flush the entire TSB, and call it
8704 	 * a day.
8705 	 */
8706 	sfmmu_ismhat_enter(sfmmup, 0);
8707 
8708 	/*
8709 	 * Remove the mapping.
8710 	 *
8711 	 * We can't have any holes in the ism map.
8712 	 * The tsb miss code while searching the ism map will
8713 	 * stop on an empty map slot.  So we must move
8714 	 * everyone past the hole up 1 if any.
8715 	 *
8716 	 * Also empty ism map blks are not freed until the
8717 	 * process exits. This is to prevent a MT race condition
8718 	 * between sfmmu_unshare() and sfmmu_tsbmiss_exception().
8719 	 */
8720 	found = 0;
8721 	ism_blkp = sfmmup->sfmmu_iblk;
8722 	while (!found && ism_blkp != NULL) {
8723 		ism_map = ism_blkp->iblk_maps;
8724 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
8725 			if (addr == ism_start(ism_map[i]) &&
8726 			    sh_size == (size_t)(ism_size(ism_map[i]))) {
8727 				found = 1;
8728 				break;
8729 			}
8730 		}
8731 		if (!found)
8732 			ism_blkp = ism_blkp->iblk_next;
8733 	}
8734 
8735 	if (found) {
8736 		ism_hatid = ism_map[i].imap_ismhat;
8737 		ism_rid = ism_map[i].imap_rid;
8738 		ASSERT(ism_hatid != NULL);
8739 		ASSERT(ism_hatid->sfmmu_ismhat == 1);
8740 
8741 		/*
8742 		 * After hat_leave_region, the sfmmup may leave SCD,
8743 		 * in which case, we want to grow the private tsb size when
8744 		 * calling sfmmu_check_page_sizes at the end of the routine.
8745 		 */
8746 		old_scdp = sfmmup->sfmmu_scdp;
8747 		/*
8748 		 * Then remove ourselves from the region.
8749 		 */
8750 		if (ism_rid != SFMMU_INVALID_ISMRID) {
8751 			hat_leave_region(sfmmup, (void *)((uint64_t)ism_rid),
8752 			    HAT_REGION_ISM);
8753 		}
8754 
8755 		/*
8756 		 * And now guarantee that any other cpu
8757 		 * that tries to process an ISM miss
8758 		 * will go to tl=0.
8759 		 */
8760 		hatlockp = sfmmu_hat_enter(sfmmup);
8761 		sfmmu_invalidate_ctx(sfmmup);
8762 		sfmmu_hat_exit(hatlockp);
8763 
8764 		/*
8765 		 * Remove ourselves from the ism mapping list.
8766 		 */
8767 		mutex_enter(&ism_mlist_lock);
8768 		iment_sub(ism_map[i].imap_ment, ism_hatid);
8769 		mutex_exit(&ism_mlist_lock);
8770 		free_ment = ism_map[i].imap_ment;
8771 
8772 		/*
8773 		 * We delete the ism map by copying
8774 		 * the next map over the current one.
8775 		 * We will take the next one in the maps
8776 		 * array or from the next ism_blk.
8777 		 */
8778 		while (ism_blkp != NULL) {
8779 			ism_map = ism_blkp->iblk_maps;
8780 			while (i < (ISM_MAP_SLOTS - 1)) {
8781 				ism_map[i] = ism_map[i + 1];
8782 				i++;
8783 			}
8784 			/* i == (ISM_MAP_SLOTS - 1) */
8785 			ism_blkp = ism_blkp->iblk_next;
8786 			if (ism_blkp != NULL) {
8787 				ism_map[i] = ism_blkp->iblk_maps[0];
8788 				i = 0;
8789 			} else {
8790 				ism_map[i].imap_seg = 0;
8791 				ism_map[i].imap_vb_shift = 0;
8792 				ism_map[i].imap_rid = SFMMU_INVALID_ISMRID;
8793 				ism_map[i].imap_hatflags = 0;
8794 				ism_map[i].imap_sz_mask = 0;
8795 				ism_map[i].imap_ismhat = NULL;
8796 				ism_map[i].imap_ment = NULL;
8797 			}
8798 		}
8799 
8800 		/*
8801 		 * Now flush entire TSB for the process, since
8802 		 * demapping page by page can be too expensive.
8803 		 * We don't have to flush the TLB here anymore
8804 		 * since we switch to a new TLB ctx instead.
8805 		 * Also, there is no need to flush if the process
8806 		 * is exiting since the TSB will be freed later.
8807 		 */
8808 		if (!sfmmup->sfmmu_free) {
8809 			hatlockp = sfmmu_hat_enter(sfmmup);
8810 			for (tsbinfo = sfmmup->sfmmu_tsb; tsbinfo != NULL;
8811 			    tsbinfo = tsbinfo->tsb_next) {
8812 				if (tsbinfo->tsb_flags & TSB_SWAPPED)
8813 					continue;
8814 				if (tsbinfo->tsb_flags & TSB_RELOC_FLAG) {
8815 					tsbinfo->tsb_flags |=
8816 					    TSB_FLUSH_NEEDED;
8817 					continue;
8818 				}
8819 
8820 				sfmmu_inv_tsb(tsbinfo->tsb_va,
8821 				    TSB_BYTES(tsbinfo->tsb_szc));
8822 			}
8823 			sfmmu_hat_exit(hatlockp);
8824 		}
8825 	}
8826 
8827 	/*
8828 	 * Update our counters for this sfmmup's ism mappings.
8829 	 */
8830 	for (i = 0; i <= ismszc; i++) {
8831 		if (!(disable_ism_large_pages & (1 << i)))
8832 			(void) ism_tsb_entries(sfmmup, i);
8833 	}
8834 
8835 	sfmmu_ismhat_exit(sfmmup, 0);
8836 
8837 	/*
8838 	 * We must do our freeing here after dropping locks
8839 	 * to prevent a deadlock in the kmem allocator on the
8840 	 * mapping list lock.
8841 	 */
8842 	if (free_ment != NULL)
8843 		kmem_cache_free(ism_ment_cache, free_ment);
8844 
8845 	/*
8846 	 * Check TSB and TLB page sizes if the process isn't exiting.
8847 	 */
8848 	if (!sfmmup->sfmmu_free) {
8849 		if (found && old_scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
8850 			sfmmu_check_page_sizes(sfmmup, 1);
8851 		} else {
8852 			sfmmu_check_page_sizes(sfmmup, 0);
8853 		}
8854 	}
8855 }
8856 
8857 /* ARGSUSED */
8858 static int
8859 sfmmu_idcache_constructor(void *buf, void *cdrarg, int kmflags)
8860 {
8861 	/* void *buf is sfmmu_t pointer */
8862 	bzero(buf, sizeof (sfmmu_t));
8863 
8864 	return (0);
8865 }
8866 
8867 /* ARGSUSED */
8868 static void
8869 sfmmu_idcache_destructor(void *buf, void *cdrarg)
8870 {
8871 	/* void *buf is sfmmu_t pointer */
8872 }
8873 
8874 /*
8875  * setup kmem hmeblks by bzeroing all members and initializing the nextpa
8876  * field to be the pa of this hmeblk
8877  */
8878 /* ARGSUSED */
8879 static int
8880 sfmmu_hblkcache_constructor(void *buf, void *cdrarg, int kmflags)
8881 {
8882 	struct hme_blk *hmeblkp;
8883 
8884 	bzero(buf, (size_t)cdrarg);
8885 	hmeblkp = (struct hme_blk *)buf;
8886 	hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
8887 
8888 #ifdef	HBLK_TRACE
8889 	mutex_init(&hmeblkp->hblk_audit_lock, NULL, MUTEX_DEFAULT, NULL);
8890 #endif	/* HBLK_TRACE */
8891 
8892 	return (0);
8893 }
8894 
8895 /* ARGSUSED */
8896 static void
8897 sfmmu_hblkcache_destructor(void *buf, void *cdrarg)
8898 {
8899 
8900 #ifdef	HBLK_TRACE
8901 
8902 	struct hme_blk *hmeblkp;
8903 
8904 	hmeblkp = (struct hme_blk *)buf;
8905 	mutex_destroy(&hmeblkp->hblk_audit_lock);
8906 
8907 #endif	/* HBLK_TRACE */
8908 }
8909 
8910 #define	SFMMU_CACHE_RECLAIM_SCAN_RATIO 8
8911 static int sfmmu_cache_reclaim_scan_ratio = SFMMU_CACHE_RECLAIM_SCAN_RATIO;
8912 /*
8913  * The kmem allocator will callback into our reclaim routine when the system
8914  * is running low in memory.  We traverse the hash and free up all unused but
8915  * still cached hme_blks.  We also traverse the free list and free them up
8916  * as well.
8917  */
8918 /*ARGSUSED*/
8919 static void
8920 sfmmu_hblkcache_reclaim(void *cdrarg)
8921 {
8922 	int i;
8923 	struct hmehash_bucket *hmebp;
8924 	struct hme_blk *hmeblkp, *nx_hblk, *pr_hblk = NULL;
8925 	static struct hmehash_bucket *uhmehash_reclaim_hand;
8926 	static struct hmehash_bucket *khmehash_reclaim_hand;
8927 	struct hme_blk *list = NULL, *last_hmeblkp;
8928 	cpuset_t cpuset = cpu_ready_set;
8929 	cpu_hme_pend_t *cpuhp;
8930 
8931 	/* Free up hmeblks on the cpu pending lists */
8932 	for (i = 0; i < NCPU; i++) {
8933 		cpuhp = &cpu_hme_pend[i];
8934 		if (cpuhp->chp_listp != NULL)  {
8935 			mutex_enter(&cpuhp->chp_mutex);
8936 			if (cpuhp->chp_listp == NULL) {
8937 				mutex_exit(&cpuhp->chp_mutex);
8938 				continue;
8939 			}
8940 			for (last_hmeblkp = cpuhp->chp_listp;
8941 			    last_hmeblkp->hblk_next != NULL;
8942 			    last_hmeblkp = last_hmeblkp->hblk_next)
8943 				;
8944 			last_hmeblkp->hblk_next = list;
8945 			list = cpuhp->chp_listp;
8946 			cpuhp->chp_listp = NULL;
8947 			cpuhp->chp_count = 0;
8948 			mutex_exit(&cpuhp->chp_mutex);
8949 		}
8950 
8951 	}
8952 
8953 	if (list != NULL) {
8954 		kpreempt_disable();
8955 		CPUSET_DEL(cpuset, CPU->cpu_id);
8956 		xt_sync(cpuset);
8957 		xt_sync(cpuset);
8958 		kpreempt_enable();
8959 		sfmmu_hblk_free(&list);
8960 		list = NULL;
8961 	}
8962 
8963 	hmebp = uhmehash_reclaim_hand;
8964 	if (hmebp == NULL || hmebp > &uhme_hash[UHMEHASH_SZ])
8965 		uhmehash_reclaim_hand = hmebp = uhme_hash;
8966 	uhmehash_reclaim_hand += UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
8967 
8968 	for (i = UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
8969 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
8970 			hmeblkp = hmebp->hmeblkp;
8971 			pr_hblk = NULL;
8972 			while (hmeblkp) {
8973 				nx_hblk = hmeblkp->hblk_next;
8974 				if (!hmeblkp->hblk_vcnt &&
8975 				    !hmeblkp->hblk_hmecnt) {
8976 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
8977 					    pr_hblk, &list, 0);
8978 				} else {
8979 					pr_hblk = hmeblkp;
8980 				}
8981 				hmeblkp = nx_hblk;
8982 			}
8983 			SFMMU_HASH_UNLOCK(hmebp);
8984 		}
8985 		if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
8986 			hmebp = uhme_hash;
8987 	}
8988 
8989 	hmebp = khmehash_reclaim_hand;
8990 	if (hmebp == NULL || hmebp > &khme_hash[KHMEHASH_SZ])
8991 		khmehash_reclaim_hand = hmebp = khme_hash;
8992 	khmehash_reclaim_hand += KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
8993 
8994 	for (i = KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
8995 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
8996 			hmeblkp = hmebp->hmeblkp;
8997 			pr_hblk = NULL;
8998 			while (hmeblkp) {
8999 				nx_hblk = hmeblkp->hblk_next;
9000 				if (!hmeblkp->hblk_vcnt &&
9001 				    !hmeblkp->hblk_hmecnt) {
9002 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
9003 					    pr_hblk, &list, 0);
9004 				} else {
9005 					pr_hblk = hmeblkp;
9006 				}
9007 				hmeblkp = nx_hblk;
9008 			}
9009 			SFMMU_HASH_UNLOCK(hmebp);
9010 		}
9011 		if (hmebp++ == &khme_hash[KHMEHASH_SZ])
9012 			hmebp = khme_hash;
9013 	}
9014 	sfmmu_hblks_list_purge(&list, 0);
9015 }
9016 
9017 /*
9018  * sfmmu_get_ppvcolor should become a vm_machdep or hatop interface.
9019  * same goes for sfmmu_get_addrvcolor().
9020  *
9021  * This function will return the virtual color for the specified page. The
9022  * virtual color corresponds to this page current mapping or its last mapping.
9023  * It is used by memory allocators to choose addresses with the correct
9024  * alignment so vac consistency is automatically maintained.  If the page
9025  * has no color it returns -1.
9026  */
9027 /*ARGSUSED*/
9028 int
9029 sfmmu_get_ppvcolor(struct page *pp)
9030 {
9031 #ifdef VAC
9032 	int color;
9033 
9034 	if (!(cache & CACHE_VAC) || PP_NEWPAGE(pp)) {
9035 		return (-1);
9036 	}
9037 	color = PP_GET_VCOLOR(pp);
9038 	ASSERT(color < mmu_btop(shm_alignment));
9039 	return (color);
9040 #else
9041 	return (-1);
9042 #endif	/* VAC */
9043 }
9044 
9045 /*
9046  * This function will return the desired alignment for vac consistency
9047  * (vac color) given a virtual address.  If no vac is present it returns -1.
9048  */
9049 /*ARGSUSED*/
9050 int
9051 sfmmu_get_addrvcolor(caddr_t vaddr)
9052 {
9053 #ifdef VAC
9054 	if (cache & CACHE_VAC) {
9055 		return (addr_to_vcolor(vaddr));
9056 	} else {
9057 		return (-1);
9058 	}
9059 #else
9060 	return (-1);
9061 #endif	/* VAC */
9062 }
9063 
9064 #ifdef VAC
9065 /*
9066  * Check for conflicts.
9067  * A conflict exists if the new and existent mappings do not match in
9068  * their "shm_alignment fields. If conflicts exist, the existant mappings
9069  * are flushed unless one of them is locked. If one of them is locked, then
9070  * the mappings are flushed and converted to non-cacheable mappings.
9071  */
9072 static void
9073 sfmmu_vac_conflict(struct hat *hat, caddr_t addr, page_t *pp)
9074 {
9075 	struct hat *tmphat;
9076 	struct sf_hment *sfhmep, *tmphme = NULL;
9077 	struct hme_blk *hmeblkp;
9078 	int vcolor;
9079 	tte_t tte;
9080 
9081 	ASSERT(sfmmu_mlist_held(pp));
9082 	ASSERT(!PP_ISNC(pp));		/* page better be cacheable */
9083 
9084 	vcolor = addr_to_vcolor(addr);
9085 	if (PP_NEWPAGE(pp)) {
9086 		PP_SET_VCOLOR(pp, vcolor);
9087 		return;
9088 	}
9089 
9090 	if (PP_GET_VCOLOR(pp) == vcolor) {
9091 		return;
9092 	}
9093 
9094 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
9095 		/*
9096 		 * Previous user of page had a different color
9097 		 * but since there are no current users
9098 		 * we just flush the cache and change the color.
9099 		 */
9100 		SFMMU_STAT(sf_pgcolor_conflict);
9101 		sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9102 		PP_SET_VCOLOR(pp, vcolor);
9103 		return;
9104 	}
9105 
9106 	/*
9107 	 * If we get here we have a vac conflict with a current
9108 	 * mapping.  VAC conflict policy is as follows.
9109 	 * - The default is to unload the other mappings unless:
9110 	 * - If we have a large mapping we uncache the page.
9111 	 * We need to uncache the rest of the large page too.
9112 	 * - If any of the mappings are locked we uncache the page.
9113 	 * - If the requested mapping is inconsistent
9114 	 * with another mapping and that mapping
9115 	 * is in the same address space we have to
9116 	 * make it non-cached.  The default thing
9117 	 * to do is unload the inconsistent mapping
9118 	 * but if they are in the same address space
9119 	 * we run the risk of unmapping the pc or the
9120 	 * stack which we will use as we return to the user,
9121 	 * in which case we can then fault on the thing
9122 	 * we just unloaded and get into an infinite loop.
9123 	 */
9124 	if (PP_ISMAPPED_LARGE(pp)) {
9125 		int sz;
9126 
9127 		/*
9128 		 * Existing mapping is for big pages. We don't unload
9129 		 * existing big mappings to satisfy new mappings.
9130 		 * Always convert all mappings to TNC.
9131 		 */
9132 		sz = fnd_mapping_sz(pp);
9133 		pp = PP_GROUPLEADER(pp, sz);
9134 		SFMMU_STAT_ADD(sf_uncache_conflict, TTEPAGES(sz));
9135 		sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH,
9136 		    TTEPAGES(sz));
9137 
9138 		return;
9139 	}
9140 
9141 	/*
9142 	 * check if any mapping is in same as or if it is locked
9143 	 * since in that case we need to uncache.
9144 	 */
9145 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9146 		tmphme = sfhmep->hme_next;
9147 		if (IS_PAHME(sfhmep))
9148 			continue;
9149 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9150 		tmphat = hblktosfmmu(hmeblkp);
9151 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
9152 		ASSERT(TTE_IS_VALID(&tte));
9153 		if (hmeblkp->hblk_shared || tmphat == hat ||
9154 		    hmeblkp->hblk_lckcnt) {
9155 			/*
9156 			 * We have an uncache conflict
9157 			 */
9158 			SFMMU_STAT(sf_uncache_conflict);
9159 			sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH, 1);
9160 			return;
9161 		}
9162 	}
9163 
9164 	/*
9165 	 * We have an unload conflict
9166 	 * We have already checked for LARGE mappings, therefore
9167 	 * the remaining mapping(s) must be TTE8K.
9168 	 */
9169 	SFMMU_STAT(sf_unload_conflict);
9170 
9171 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
9172 		tmphme = sfhmep->hme_next;
9173 		if (IS_PAHME(sfhmep))
9174 			continue;
9175 		hmeblkp = sfmmu_hmetohblk(sfhmep);
9176 		ASSERT(!hmeblkp->hblk_shared);
9177 		(void) sfmmu_pageunload(pp, sfhmep, TTE8K);
9178 	}
9179 
9180 	if (PP_ISMAPPED_KPM(pp))
9181 		sfmmu_kpm_vac_unload(pp, addr);
9182 
9183 	/*
9184 	 * Unloads only do TLB flushes so we need to flush the
9185 	 * cache here.
9186 	 */
9187 	sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
9188 	PP_SET_VCOLOR(pp, vcolor);
9189 }
9190 
9191 /*
9192  * Whenever a mapping is unloaded and the page is in TNC state,
9193  * we see if the page can be made cacheable again. 'pp' is
9194  * the page that we just unloaded a mapping from, the size
9195  * of mapping that was unloaded is 'ottesz'.
9196  * Remark:
9197  * The recache policy for mpss pages can leave a performance problem
9198  * under the following circumstances:
9199  * . A large page in uncached mode has just been unmapped.
9200  * . All constituent pages are TNC due to a conflicting small mapping.
9201  * . There are many other, non conflicting, small mappings around for
9202  *   a lot of the constituent pages.
9203  * . We're called w/ the "old" groupleader page and the old ottesz,
9204  *   but this is irrelevant, since we're no more "PP_ISMAPPED_LARGE", so
9205  *   we end up w/ TTE8K or npages == 1.
9206  * . We call tst_tnc w/ the old groupleader only, and if there is no
9207  *   conflict, we re-cache only this page.
9208  * . All other small mappings are not checked and will be left in TNC mode.
9209  * The problem is not very serious because:
9210  * . mpss is actually only defined for heap and stack, so the probability
9211  *   is not very high that a large page mapping exists in parallel to a small
9212  *   one (this is possible, but seems to be bad programming style in the
9213  *   appl).
9214  * . The problem gets a little bit more serious, when those TNC pages
9215  *   have to be mapped into kernel space, e.g. for networking.
9216  * . When VAC alias conflicts occur in applications, this is regarded
9217  *   as an application bug. So if kstat's show them, the appl should
9218  *   be changed anyway.
9219  */
9220 void
9221 conv_tnc(page_t *pp, int ottesz)
9222 {
9223 	int cursz, dosz;
9224 	pgcnt_t curnpgs, dopgs;
9225 	pgcnt_t pg64k;
9226 	page_t *pp2;
9227 
9228 	/*
9229 	 * Determine how big a range we check for TNC and find
9230 	 * leader page. cursz is the size of the biggest
9231 	 * mapping that still exist on 'pp'.
9232 	 */
9233 	if (PP_ISMAPPED_LARGE(pp)) {
9234 		cursz = fnd_mapping_sz(pp);
9235 	} else {
9236 		cursz = TTE8K;
9237 	}
9238 
9239 	if (ottesz >= cursz) {
9240 		dosz = ottesz;
9241 		pp2 = pp;
9242 	} else {
9243 		dosz = cursz;
9244 		pp2 = PP_GROUPLEADER(pp, dosz);
9245 	}
9246 
9247 	pg64k = TTEPAGES(TTE64K);
9248 	dopgs = TTEPAGES(dosz);
9249 
9250 	ASSERT(dopgs == 1 || ((dopgs & (pg64k - 1)) == 0));
9251 
9252 	while (dopgs != 0) {
9253 		curnpgs = TTEPAGES(cursz);
9254 		if (tst_tnc(pp2, curnpgs)) {
9255 			SFMMU_STAT_ADD(sf_recache, curnpgs);
9256 			sfmmu_page_cache_array(pp2, HAT_CACHE, CACHE_NO_FLUSH,
9257 			    curnpgs);
9258 		}
9259 
9260 		ASSERT(dopgs >= curnpgs);
9261 		dopgs -= curnpgs;
9262 
9263 		if (dopgs == 0) {
9264 			break;
9265 		}
9266 
9267 		pp2 = PP_PAGENEXT_N(pp2, curnpgs);
9268 		if (((dopgs & (pg64k - 1)) == 0) && PP_ISMAPPED_LARGE(pp2)) {
9269 			cursz = fnd_mapping_sz(pp2);
9270 		} else {
9271 			cursz = TTE8K;
9272 		}
9273 	}
9274 }
9275 
9276 /*
9277  * Returns 1 if page(s) can be converted from TNC to cacheable setting,
9278  * returns 0 otherwise. Note that oaddr argument is valid for only
9279  * 8k pages.
9280  */
9281 int
9282 tst_tnc(page_t *pp, pgcnt_t npages)
9283 {
9284 	struct	sf_hment *sfhme;
9285 	struct	hme_blk *hmeblkp;
9286 	tte_t	tte;
9287 	caddr_t	vaddr;
9288 	int	clr_valid = 0;
9289 	int	color, color1, bcolor;
9290 	int	i, ncolors;
9291 
9292 	ASSERT(pp != NULL);
9293 	ASSERT(!(cache & CACHE_WRITEBACK));
9294 
9295 	if (npages > 1) {
9296 		ncolors = CACHE_NUM_COLOR;
9297 	}
9298 
9299 	for (i = 0; i < npages; i++) {
9300 		ASSERT(sfmmu_mlist_held(pp));
9301 		ASSERT(PP_ISTNC(pp));
9302 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
9303 
9304 		if (PP_ISPNC(pp)) {
9305 			return (0);
9306 		}
9307 
9308 		clr_valid = 0;
9309 		if (PP_ISMAPPED_KPM(pp)) {
9310 			caddr_t kpmvaddr;
9311 
9312 			ASSERT(kpm_enable);
9313 			kpmvaddr = hat_kpm_page2va(pp, 1);
9314 			ASSERT(!(npages > 1 && IS_KPM_ALIAS_RANGE(kpmvaddr)));
9315 			color1 = addr_to_vcolor(kpmvaddr);
9316 			clr_valid = 1;
9317 		}
9318 
9319 		for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9320 			if (IS_PAHME(sfhme))
9321 				continue;
9322 			hmeblkp = sfmmu_hmetohblk(sfhme);
9323 
9324 			sfmmu_copytte(&sfhme->hme_tte, &tte);
9325 			ASSERT(TTE_IS_VALID(&tte));
9326 
9327 			vaddr = tte_to_vaddr(hmeblkp, tte);
9328 			color = addr_to_vcolor(vaddr);
9329 
9330 			if (npages > 1) {
9331 				/*
9332 				 * If there is a big mapping, make sure
9333 				 * 8K mapping is consistent with the big
9334 				 * mapping.
9335 				 */
9336 				bcolor = i % ncolors;
9337 				if (color != bcolor) {
9338 					return (0);
9339 				}
9340 			}
9341 			if (!clr_valid) {
9342 				clr_valid = 1;
9343 				color1 = color;
9344 			}
9345 
9346 			if (color1 != color) {
9347 				return (0);
9348 			}
9349 		}
9350 
9351 		pp = PP_PAGENEXT(pp);
9352 	}
9353 
9354 	return (1);
9355 }
9356 
9357 void
9358 sfmmu_page_cache_array(page_t *pp, int flags, int cache_flush_flag,
9359     pgcnt_t npages)
9360 {
9361 	kmutex_t *pmtx;
9362 	int i, ncolors, bcolor;
9363 	kpm_hlk_t *kpmp;
9364 	cpuset_t cpuset;
9365 
9366 	ASSERT(pp != NULL);
9367 	ASSERT(!(cache & CACHE_WRITEBACK));
9368 
9369 	kpmp = sfmmu_kpm_kpmp_enter(pp, npages);
9370 	pmtx = sfmmu_page_enter(pp);
9371 
9372 	/*
9373 	 * Fast path caching single unmapped page
9374 	 */
9375 	if (npages == 1 && !PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp) &&
9376 	    flags == HAT_CACHE) {
9377 		PP_CLRTNC(pp);
9378 		PP_CLRPNC(pp);
9379 		sfmmu_page_exit(pmtx);
9380 		sfmmu_kpm_kpmp_exit(kpmp);
9381 		return;
9382 	}
9383 
9384 	/*
9385 	 * We need to capture all cpus in order to change cacheability
9386 	 * because we can't allow one cpu to access the same physical
9387 	 * page using a cacheable and a non-cachebale mapping at the same
9388 	 * time. Since we may end up walking the ism mapping list
9389 	 * have to grab it's lock now since we can't after all the
9390 	 * cpus have been captured.
9391 	 */
9392 	sfmmu_hat_lock_all();
9393 	mutex_enter(&ism_mlist_lock);
9394 	kpreempt_disable();
9395 	cpuset = cpu_ready_set;
9396 	xc_attention(cpuset);
9397 
9398 	if (npages > 1) {
9399 		/*
9400 		 * Make sure all colors are flushed since the
9401 		 * sfmmu_page_cache() only flushes one color-
9402 		 * it does not know big pages.
9403 		 */
9404 		ncolors = CACHE_NUM_COLOR;
9405 		if (flags & HAT_TMPNC) {
9406 			for (i = 0; i < ncolors; i++) {
9407 				sfmmu_cache_flushcolor(i, pp->p_pagenum);
9408 			}
9409 			cache_flush_flag = CACHE_NO_FLUSH;
9410 		}
9411 	}
9412 
9413 	for (i = 0; i < npages; i++) {
9414 
9415 		ASSERT(sfmmu_mlist_held(pp));
9416 
9417 		if (!(flags == HAT_TMPNC && PP_ISTNC(pp))) {
9418 
9419 			if (npages > 1) {
9420 				bcolor = i % ncolors;
9421 			} else {
9422 				bcolor = NO_VCOLOR;
9423 			}
9424 
9425 			sfmmu_page_cache(pp, flags, cache_flush_flag,
9426 			    bcolor);
9427 		}
9428 
9429 		pp = PP_PAGENEXT(pp);
9430 	}
9431 
9432 	xt_sync(cpuset);
9433 	xc_dismissed(cpuset);
9434 	mutex_exit(&ism_mlist_lock);
9435 	sfmmu_hat_unlock_all();
9436 	sfmmu_page_exit(pmtx);
9437 	sfmmu_kpm_kpmp_exit(kpmp);
9438 	kpreempt_enable();
9439 }
9440 
9441 /*
9442  * This function changes the virtual cacheability of all mappings to a
9443  * particular page.  When changing from uncache to cacheable the mappings will
9444  * only be changed if all of them have the same virtual color.
9445  * We need to flush the cache in all cpus.  It is possible that
9446  * a process referenced a page as cacheable but has sinced exited
9447  * and cleared the mapping list.  We still to flush it but have no
9448  * state so all cpus is the only alternative.
9449  */
9450 static void
9451 sfmmu_page_cache(page_t *pp, int flags, int cache_flush_flag, int bcolor)
9452 {
9453 	struct	sf_hment *sfhme;
9454 	struct	hme_blk *hmeblkp;
9455 	sfmmu_t *sfmmup;
9456 	tte_t	tte, ttemod;
9457 	caddr_t	vaddr;
9458 	int	ret, color;
9459 	pfn_t	pfn;
9460 
9461 	color = bcolor;
9462 	pfn = pp->p_pagenum;
9463 
9464 	for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
9465 
9466 		if (IS_PAHME(sfhme))
9467 			continue;
9468 		hmeblkp = sfmmu_hmetohblk(sfhme);
9469 
9470 		sfmmu_copytte(&sfhme->hme_tte, &tte);
9471 		ASSERT(TTE_IS_VALID(&tte));
9472 		vaddr = tte_to_vaddr(hmeblkp, tte);
9473 		color = addr_to_vcolor(vaddr);
9474 
9475 #ifdef DEBUG
9476 		if ((flags & HAT_CACHE) && bcolor != NO_VCOLOR) {
9477 			ASSERT(color == bcolor);
9478 		}
9479 #endif
9480 
9481 		ASSERT(flags != HAT_TMPNC || color == PP_GET_VCOLOR(pp));
9482 
9483 		ttemod = tte;
9484 		if (flags & (HAT_UNCACHE | HAT_TMPNC)) {
9485 			TTE_CLR_VCACHEABLE(&ttemod);
9486 		} else {	/* flags & HAT_CACHE */
9487 			TTE_SET_VCACHEABLE(&ttemod);
9488 		}
9489 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
9490 		if (ret < 0) {
9491 			/*
9492 			 * Since all cpus are captured modifytte should not
9493 			 * fail.
9494 			 */
9495 			panic("sfmmu_page_cache: write to tte failed");
9496 		}
9497 
9498 		sfmmup = hblktosfmmu(hmeblkp);
9499 		if (cache_flush_flag == CACHE_FLUSH) {
9500 			/*
9501 			 * Flush TSBs, TLBs and caches
9502 			 */
9503 			if (hmeblkp->hblk_shared) {
9504 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9505 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9506 				sf_region_t *rgnp;
9507 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9508 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9509 				ASSERT(srdp != NULL);
9510 				rgnp = srdp->srd_hmergnp[rid];
9511 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9512 				    srdp, rgnp, rid);
9513 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9514 				    hmeblkp, 0);
9515 				sfmmu_cache_flush(pfn, addr_to_vcolor(vaddr));
9516 			} else if (sfmmup->sfmmu_ismhat) {
9517 				if (flags & HAT_CACHE) {
9518 					SFMMU_STAT(sf_ism_recache);
9519 				} else {
9520 					SFMMU_STAT(sf_ism_uncache);
9521 				}
9522 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9523 				    pfn, CACHE_FLUSH);
9524 			} else {
9525 				sfmmu_tlbcache_demap(vaddr, sfmmup, hmeblkp,
9526 				    pfn, 0, FLUSH_ALL_CPUS, CACHE_FLUSH, 1);
9527 			}
9528 
9529 			/*
9530 			 * all cache entries belonging to this pfn are
9531 			 * now flushed.
9532 			 */
9533 			cache_flush_flag = CACHE_NO_FLUSH;
9534 		} else {
9535 			/*
9536 			 * Flush only TSBs and TLBs.
9537 			 */
9538 			if (hmeblkp->hblk_shared) {
9539 				sf_srd_t *srdp = (sf_srd_t *)sfmmup;
9540 				uint_t rid = hmeblkp->hblk_tag.htag_rid;
9541 				sf_region_t *rgnp;
9542 				ASSERT(SFMMU_IS_SHMERID_VALID(rid));
9543 				ASSERT(rid < SFMMU_MAX_HME_REGIONS);
9544 				ASSERT(srdp != NULL);
9545 				rgnp = srdp->srd_hmergnp[rid];
9546 				SFMMU_VALIDATE_SHAREDHBLK(hmeblkp,
9547 				    srdp, rgnp, rid);
9548 				(void) sfmmu_rgntlb_demap(vaddr, rgnp,
9549 				    hmeblkp, 0);
9550 			} else if (sfmmup->sfmmu_ismhat) {
9551 				if (flags & HAT_CACHE) {
9552 					SFMMU_STAT(sf_ism_recache);
9553 				} else {
9554 					SFMMU_STAT(sf_ism_uncache);
9555 				}
9556 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
9557 				    pfn, CACHE_NO_FLUSH);
9558 			} else {
9559 				sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 1);
9560 			}
9561 		}
9562 	}
9563 
9564 	if (PP_ISMAPPED_KPM(pp))
9565 		sfmmu_kpm_page_cache(pp, flags, cache_flush_flag);
9566 
9567 	switch (flags) {
9568 
9569 		default:
9570 			panic("sfmmu_pagecache: unknown flags");
9571 			break;
9572 
9573 		case HAT_CACHE:
9574 			PP_CLRTNC(pp);
9575 			PP_CLRPNC(pp);
9576 			PP_SET_VCOLOR(pp, color);
9577 			break;
9578 
9579 		case HAT_TMPNC:
9580 			PP_SETTNC(pp);
9581 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9582 			break;
9583 
9584 		case HAT_UNCACHE:
9585 			PP_SETPNC(pp);
9586 			PP_CLRTNC(pp);
9587 			PP_SET_VCOLOR(pp, NO_VCOLOR);
9588 			break;
9589 	}
9590 }
9591 #endif	/* VAC */
9592 
9593 
9594 /*
9595  * Wrapper routine used to return a context.
9596  *
9597  * It's the responsibility of the caller to guarantee that the
9598  * process serializes on calls here by taking the HAT lock for
9599  * the hat.
9600  *
9601  */
9602 static void
9603 sfmmu_get_ctx(sfmmu_t *sfmmup)
9604 {
9605 	mmu_ctx_t *mmu_ctxp;
9606 	uint_t pstate_save;
9607 	int ret;
9608 
9609 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9610 	ASSERT(sfmmup != ksfmmup);
9611 
9612 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID)) {
9613 		sfmmu_setup_tsbinfo(sfmmup);
9614 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ALLCTX_INVALID);
9615 	}
9616 
9617 	kpreempt_disable();
9618 
9619 	mmu_ctxp = CPU_MMU_CTXP(CPU);
9620 	ASSERT(mmu_ctxp);
9621 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
9622 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
9623 
9624 	/*
9625 	 * Do a wrap-around if cnum reaches the max # cnum supported by a MMU.
9626 	 */
9627 	if (mmu_ctxp->mmu_cnum == mmu_ctxp->mmu_nctxs)
9628 		sfmmu_ctx_wrap_around(mmu_ctxp, B_TRUE);
9629 
9630 	/*
9631 	 * Let the MMU set up the page sizes to use for
9632 	 * this context in the TLB. Don't program 2nd dtlb for ism hat.
9633 	 */
9634 	if ((&mmu_set_ctx_page_sizes) && (sfmmup->sfmmu_ismhat == 0)) {
9635 		mmu_set_ctx_page_sizes(sfmmup);
9636 	}
9637 
9638 	/*
9639 	 * sfmmu_alloc_ctx and sfmmu_load_mmustate will be performed with
9640 	 * interrupts disabled to prevent race condition with wrap-around
9641 	 * ctx invalidatation. In sun4v, ctx invalidation also involves
9642 	 * a HV call to set the number of TSBs to 0. If interrupts are not
9643 	 * disabled until after sfmmu_load_mmustate is complete TSBs may
9644 	 * become assigned to INVALID_CONTEXT. This is not allowed.
9645 	 */
9646 	pstate_save = sfmmu_disable_intrs();
9647 
9648 	if (sfmmu_alloc_ctx(sfmmup, 1, CPU, SFMMU_PRIVATE) &&
9649 	    sfmmup->sfmmu_scdp != NULL) {
9650 		sf_scd_t *scdp = sfmmup->sfmmu_scdp;
9651 		sfmmu_t *scsfmmup = scdp->scd_sfmmup;
9652 		ret = sfmmu_alloc_ctx(scsfmmup, 1, CPU, SFMMU_SHARED);
9653 		/* debug purpose only */
9654 		ASSERT(!ret || scsfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
9655 		    != INVALID_CONTEXT);
9656 	}
9657 	sfmmu_load_mmustate(sfmmup);
9658 
9659 	sfmmu_enable_intrs(pstate_save);
9660 
9661 	kpreempt_enable();
9662 }
9663 
9664 /*
9665  * When all cnums are used up in a MMU, cnum will wrap around to the
9666  * next generation and start from 2.
9667  */
9668 static void
9669 sfmmu_ctx_wrap_around(mmu_ctx_t *mmu_ctxp, boolean_t reset_cnum)
9670 {
9671 
9672 	/* caller must have disabled the preemption */
9673 	ASSERT(curthread->t_preempt >= 1);
9674 	ASSERT(mmu_ctxp != NULL);
9675 
9676 	/* acquire Per-MMU (PM) spin lock */
9677 	mutex_enter(&mmu_ctxp->mmu_lock);
9678 
9679 	/* re-check to see if wrap-around is needed */
9680 	if (mmu_ctxp->mmu_cnum < mmu_ctxp->mmu_nctxs)
9681 		goto done;
9682 
9683 	SFMMU_MMU_STAT(mmu_wrap_around);
9684 
9685 	/* update gnum */
9686 	ASSERT(mmu_ctxp->mmu_gnum != 0);
9687 	mmu_ctxp->mmu_gnum++;
9688 	if (mmu_ctxp->mmu_gnum == 0 ||
9689 	    mmu_ctxp->mmu_gnum > MAX_SFMMU_GNUM_VAL) {
9690 		cmn_err(CE_PANIC, "mmu_gnum of mmu_ctx 0x%p is out of bound.",
9691 		    (void *)mmu_ctxp);
9692 	}
9693 
9694 	if (mmu_ctxp->mmu_ncpus > 1) {
9695 		cpuset_t cpuset;
9696 
9697 		membar_enter(); /* make sure updated gnum visible */
9698 
9699 		SFMMU_XCALL_STATS(NULL);
9700 
9701 		/* xcall to others on the same MMU to invalidate ctx */
9702 		cpuset = mmu_ctxp->mmu_cpuset;
9703 		ASSERT(CPU_IN_SET(cpuset, CPU->cpu_id) || !reset_cnum);
9704 		CPUSET_DEL(cpuset, CPU->cpu_id);
9705 		CPUSET_AND(cpuset, cpu_ready_set);
9706 
9707 		/*
9708 		 * Pass in INVALID_CONTEXT as the first parameter to
9709 		 * sfmmu_raise_tsb_exception, which invalidates the context
9710 		 * of any process running on the CPUs in the MMU.
9711 		 */
9712 		xt_some(cpuset, sfmmu_raise_tsb_exception,
9713 		    INVALID_CONTEXT, INVALID_CONTEXT);
9714 		xt_sync(cpuset);
9715 
9716 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
9717 	}
9718 
9719 	if (sfmmu_getctx_sec() != INVALID_CONTEXT) {
9720 		sfmmu_setctx_sec(INVALID_CONTEXT);
9721 		sfmmu_clear_utsbinfo();
9722 	}
9723 
9724 	/*
9725 	 * No xcall is needed here. For sun4u systems all CPUs in context
9726 	 * domain share a single physical MMU therefore it's enough to flush
9727 	 * TLB on local CPU. On sun4v systems we use 1 global context
9728 	 * domain and flush all remote TLBs in sfmmu_raise_tsb_exception
9729 	 * handler. Note that vtag_flushall_uctxs() is called
9730 	 * for Ultra II machine, where the equivalent flushall functionality
9731 	 * is implemented in SW, and only user ctx TLB entries are flushed.
9732 	 */
9733 	if (&vtag_flushall_uctxs != NULL) {
9734 		vtag_flushall_uctxs();
9735 	} else {
9736 		vtag_flushall();
9737 	}
9738 
9739 	/* reset mmu cnum, skips cnum 0 and 1 */
9740 	if (reset_cnum == B_TRUE)
9741 		mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
9742 
9743 done:
9744 	mutex_exit(&mmu_ctxp->mmu_lock);
9745 }
9746 
9747 
9748 /*
9749  * For multi-threaded process, set the process context to INVALID_CONTEXT
9750  * so that it faults and reloads the MMU state from TL=0. For single-threaded
9751  * process, we can just load the MMU state directly without having to
9752  * set context invalid. Caller must hold the hat lock since we don't
9753  * acquire it here.
9754  */
9755 static void
9756 sfmmu_sync_mmustate(sfmmu_t *sfmmup)
9757 {
9758 	uint_t cnum;
9759 	uint_t pstate_save;
9760 
9761 	ASSERT(sfmmup != ksfmmup);
9762 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9763 
9764 	kpreempt_disable();
9765 
9766 	/*
9767 	 * We check whether the pass'ed-in sfmmup is the same as the
9768 	 * current running proc. This is to makes sure the current proc
9769 	 * stays single-threaded if it already is.
9770 	 */
9771 	if ((sfmmup == curthread->t_procp->p_as->a_hat) &&
9772 	    (curthread->t_procp->p_lwpcnt == 1)) {
9773 		/* single-thread */
9774 		cnum = sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum;
9775 		if (cnum != INVALID_CONTEXT) {
9776 			uint_t curcnum;
9777 			/*
9778 			 * Disable interrupts to prevent race condition
9779 			 * with sfmmu_ctx_wrap_around ctx invalidation.
9780 			 * In sun4v, ctx invalidation involves setting
9781 			 * TSB to NULL, hence, interrupts should be disabled
9782 			 * untill after sfmmu_load_mmustate is completed.
9783 			 */
9784 			pstate_save = sfmmu_disable_intrs();
9785 			curcnum = sfmmu_getctx_sec();
9786 			if (curcnum == cnum)
9787 				sfmmu_load_mmustate(sfmmup);
9788 			sfmmu_enable_intrs(pstate_save);
9789 			ASSERT(curcnum == cnum || curcnum == INVALID_CONTEXT);
9790 		}
9791 	} else {
9792 		/*
9793 		 * multi-thread
9794 		 * or when sfmmup is not the same as the curproc.
9795 		 */
9796 		sfmmu_invalidate_ctx(sfmmup);
9797 	}
9798 
9799 	kpreempt_enable();
9800 }
9801 
9802 
9803 /*
9804  * Replace the specified TSB with a new TSB.  This function gets called when
9805  * we grow, shrink or swapin a TSB.  When swapping in a TSB (TSB_SWAPIN), the
9806  * TSB_FORCEALLOC flag may be used to force allocation of a minimum-sized TSB
9807  * (8K).
9808  *
9809  * Caller must hold the HAT lock, but should assume any tsb_info
9810  * pointers it has are no longer valid after calling this function.
9811  *
9812  * Return values:
9813  *	TSB_ALLOCFAIL	Failed to allocate a TSB, due to memory constraints
9814  *	TSB_LOSTRACE	HAT is busy, i.e. another thread is already doing
9815  *			something to this tsbinfo/TSB
9816  *	TSB_SUCCESS	Operation succeeded
9817  */
9818 static tsb_replace_rc_t
9819 sfmmu_replace_tsb(sfmmu_t *sfmmup, struct tsb_info *old_tsbinfo, uint_t szc,
9820     hatlock_t *hatlockp, uint_t flags)
9821 {
9822 	struct tsb_info *new_tsbinfo = NULL;
9823 	struct tsb_info *curtsb, *prevtsb;
9824 	uint_t tte_sz_mask;
9825 	int i;
9826 
9827 	ASSERT(sfmmup != ksfmmup);
9828 	ASSERT(sfmmup->sfmmu_ismhat == 0);
9829 	ASSERT(sfmmu_hat_lock_held(sfmmup));
9830 	ASSERT(szc <= tsb_max_growsize);
9831 
9832 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_BUSY))
9833 		return (TSB_LOSTRACE);
9834 
9835 	/*
9836 	 * Find the tsb_info ahead of this one in the list, and
9837 	 * also make sure that the tsb_info passed in really
9838 	 * exists!
9839 	 */
9840 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9841 	    curtsb != old_tsbinfo && curtsb != NULL;
9842 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
9843 		;
9844 	ASSERT(curtsb != NULL);
9845 
9846 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9847 		/*
9848 		 * The process is swapped out, so just set the new size
9849 		 * code.  When it swaps back in, we'll allocate a new one
9850 		 * of the new chosen size.
9851 		 */
9852 		curtsb->tsb_szc = szc;
9853 		return (TSB_SUCCESS);
9854 	}
9855 	SFMMU_FLAGS_SET(sfmmup, HAT_BUSY);
9856 
9857 	tte_sz_mask = old_tsbinfo->tsb_ttesz_mask;
9858 
9859 	/*
9860 	 * All initialization is done inside of sfmmu_tsbinfo_alloc().
9861 	 * If we fail to allocate a TSB, exit.
9862 	 *
9863 	 * If tsb grows with new tsb size > 4M and old tsb size < 4M,
9864 	 * then try 4M slab after the initial alloc fails.
9865 	 *
9866 	 * If tsb swapin with tsb size > 4M, then try 4M after the
9867 	 * initial alloc fails.
9868 	 */
9869 	sfmmu_hat_exit(hatlockp);
9870 	if (sfmmu_tsbinfo_alloc(&new_tsbinfo, szc,
9871 	    tte_sz_mask, flags, sfmmup) &&
9872 	    (!(flags & (TSB_GROW | TSB_SWAPIN)) || (szc <= TSB_4M_SZCODE) ||
9873 	    (!(flags & TSB_SWAPIN) &&
9874 	    (old_tsbinfo->tsb_szc >= TSB_4M_SZCODE)) ||
9875 	    sfmmu_tsbinfo_alloc(&new_tsbinfo, TSB_4M_SZCODE,
9876 	    tte_sz_mask, flags, sfmmup))) {
9877 		(void) sfmmu_hat_enter(sfmmup);
9878 		if (!(flags & TSB_SWAPIN))
9879 			SFMMU_STAT(sf_tsb_resize_failures);
9880 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9881 		return (TSB_ALLOCFAIL);
9882 	}
9883 	(void) sfmmu_hat_enter(sfmmup);
9884 
9885 	/*
9886 	 * Re-check to make sure somebody else didn't muck with us while we
9887 	 * didn't hold the HAT lock.  If the process swapped out, fine, just
9888 	 * exit; this can happen if we try to shrink the TSB from the context
9889 	 * of another process (such as on an ISM unmap), though it is rare.
9890 	 */
9891 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
9892 		SFMMU_STAT(sf_tsb_resize_failures);
9893 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9894 		sfmmu_hat_exit(hatlockp);
9895 		sfmmu_tsbinfo_free(new_tsbinfo);
9896 		(void) sfmmu_hat_enter(sfmmup);
9897 		return (TSB_LOSTRACE);
9898 	}
9899 
9900 #ifdef	DEBUG
9901 	/* Reverify that the tsb_info still exists.. for debugging only */
9902 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
9903 	    curtsb != old_tsbinfo && curtsb != NULL;
9904 	    prevtsb = curtsb, curtsb = curtsb->tsb_next)
9905 		;
9906 	ASSERT(curtsb != NULL);
9907 #endif	/* DEBUG */
9908 
9909 	/*
9910 	 * Quiesce any CPUs running this process on their next TLB miss
9911 	 * so they atomically see the new tsb_info.  We temporarily set the
9912 	 * context to invalid context so new threads that come on processor
9913 	 * after we do the xcall to cpusran will also serialize behind the
9914 	 * HAT lock on TLB miss and will see the new TSB.  Since this short
9915 	 * race with a new thread coming on processor is relatively rare,
9916 	 * this synchronization mechanism should be cheaper than always
9917 	 * pausing all CPUs for the duration of the setup, which is what
9918 	 * the old implementation did.  This is particuarly true if we are
9919 	 * copying a huge chunk of memory around during that window.
9920 	 *
9921 	 * The memory barriers are to make sure things stay consistent
9922 	 * with resume() since it does not hold the HAT lock while
9923 	 * walking the list of tsb_info structures.
9924 	 */
9925 	if ((flags & TSB_SWAPIN) != TSB_SWAPIN) {
9926 		/* The TSB is either growing or shrinking. */
9927 		sfmmu_invalidate_ctx(sfmmup);
9928 	} else {
9929 		/*
9930 		 * It is illegal to swap in TSBs from a process other
9931 		 * than a process being swapped in.  This in turn
9932 		 * implies we do not have a valid MMU context here
9933 		 * since a process needs one to resolve translation
9934 		 * misses.
9935 		 */
9936 		ASSERT(curthread->t_procp->p_as->a_hat == sfmmup);
9937 	}
9938 
9939 #ifdef DEBUG
9940 	ASSERT(max_mmu_ctxdoms > 0);
9941 
9942 	/*
9943 	 * Process should have INVALID_CONTEXT on all MMUs
9944 	 */
9945 	for (i = 0; i < max_mmu_ctxdoms; i++) {
9946 
9947 		ASSERT(sfmmup->sfmmu_ctxs[i].cnum == INVALID_CONTEXT);
9948 	}
9949 #endif
9950 
9951 	new_tsbinfo->tsb_next = old_tsbinfo->tsb_next;
9952 	membar_stst();	/* strict ordering required */
9953 	if (prevtsb)
9954 		prevtsb->tsb_next = new_tsbinfo;
9955 	else
9956 		sfmmup->sfmmu_tsb = new_tsbinfo;
9957 	membar_enter();	/* make sure new TSB globally visible */
9958 
9959 	/*
9960 	 * We need to migrate TSB entries from the old TSB to the new TSB
9961 	 * if tsb_remap_ttes is set and the TSB is growing.
9962 	 */
9963 	if (tsb_remap_ttes && ((flags & TSB_GROW) == TSB_GROW))
9964 		sfmmu_copy_tsb(old_tsbinfo, new_tsbinfo);
9965 
9966 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9967 
9968 	/*
9969 	 * Drop the HAT lock to free our old tsb_info.
9970 	 */
9971 	sfmmu_hat_exit(hatlockp);
9972 
9973 	if ((flags & TSB_GROW) == TSB_GROW) {
9974 		SFMMU_STAT(sf_tsb_grow);
9975 	} else if ((flags & TSB_SHRINK) == TSB_SHRINK) {
9976 		SFMMU_STAT(sf_tsb_shrink);
9977 	}
9978 
9979 	sfmmu_tsbinfo_free(old_tsbinfo);
9980 
9981 	(void) sfmmu_hat_enter(sfmmup);
9982 	return (TSB_SUCCESS);
9983 }
9984 
9985 /*
9986  * This function will re-program hat pgsz array, and invalidate the
9987  * process' context, forcing the process to switch to another
9988  * context on the next TLB miss, and therefore start using the
9989  * TLB that is reprogrammed for the new page sizes.
9990  */
9991 void
9992 sfmmu_reprog_pgsz_arr(sfmmu_t *sfmmup, uint8_t *tmp_pgsz)
9993 {
9994 	int i;
9995 	hatlock_t *hatlockp = NULL;
9996 
9997 	hatlockp = sfmmu_hat_enter(sfmmup);
9998 	/* USIII+-IV+ optimization, requires hat lock */
9999 	if (tmp_pgsz) {
10000 		for (i = 0; i < mmu_page_sizes; i++)
10001 			sfmmup->sfmmu_pgsz[i] = tmp_pgsz[i];
10002 	}
10003 	SFMMU_STAT(sf_tlb_reprog_pgsz);
10004 
10005 	sfmmu_invalidate_ctx(sfmmup);
10006 
10007 	sfmmu_hat_exit(hatlockp);
10008 }
10009 
10010 /*
10011  * The scd_rttecnt field in the SCD must be updated to take account of the
10012  * regions which it contains.
10013  */
10014 static void
10015 sfmmu_set_scd_rttecnt(sf_srd_t *srdp, sf_scd_t *scdp)
10016 {
10017 	uint_t rid;
10018 	uint_t i, j;
10019 	ulong_t w;
10020 	sf_region_t *rgnp;
10021 
10022 	ASSERT(srdp != NULL);
10023 
10024 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
10025 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
10026 			continue;
10027 		}
10028 
10029 		j = 0;
10030 		while (w) {
10031 			if (!(w & 0x1)) {
10032 				j++;
10033 				w >>= 1;
10034 				continue;
10035 			}
10036 			rid = (i << BT_ULSHIFT) | j;
10037 			j++;
10038 			w >>= 1;
10039 
10040 			ASSERT(SFMMU_IS_SHMERID_VALID(rid));
10041 			ASSERT(rid < SFMMU_MAX_HME_REGIONS);
10042 			rgnp = srdp->srd_hmergnp[rid];
10043 			ASSERT(rgnp->rgn_refcnt > 0);
10044 			ASSERT(rgnp->rgn_id == rid);
10045 
10046 			scdp->scd_rttecnt[rgnp->rgn_pgszc] +=
10047 			    rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
10048 
10049 			/*
10050 			 * Maintain the tsb0 inflation cnt for the regions
10051 			 * in the SCD.
10052 			 */
10053 			if (rgnp->rgn_pgszc >= TTE4M) {
10054 				scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt +=
10055 				    rgnp->rgn_size >>
10056 				    (TTE_PAGE_SHIFT(TTE8K) + 2);
10057 			}
10058 		}
10059 	}
10060 }
10061 
10062 /*
10063  * This function assumes that there are either four or six supported page
10064  * sizes and at most two programmable TLBs, so we need to decide which
10065  * page sizes are most important and then tell the MMU layer so it
10066  * can adjust the TLB page sizes accordingly (if supported).
10067  *
10068  * If these assumptions change, this function will need to be
10069  * updated to support whatever the new limits are.
10070  *
10071  * The growing flag is nonzero if we are growing the address space,
10072  * and zero if it is shrinking.  This allows us to decide whether
10073  * to grow or shrink our TSB, depending upon available memory
10074  * conditions.
10075  */
10076 static void
10077 sfmmu_check_page_sizes(sfmmu_t *sfmmup, int growing)
10078 {
10079 	uint64_t ttecnt[MMU_PAGE_SIZES];
10080 	uint64_t tte8k_cnt, tte4m_cnt;
10081 	uint8_t i;
10082 	int sectsb_thresh;
10083 
10084 	/*
10085 	 * Kernel threads, processes with small address spaces not using
10086 	 * large pages, and dummy ISM HATs need not apply.
10087 	 */
10088 	if (sfmmup == ksfmmup || sfmmup->sfmmu_ismhat != NULL)
10089 		return;
10090 
10091 	if (!SFMMU_LGPGS_INUSE(sfmmup) &&
10092 	    sfmmup->sfmmu_ttecnt[TTE8K] <= tsb_rss_factor)
10093 		return;
10094 
10095 	for (i = 0; i < mmu_page_sizes; i++) {
10096 		ttecnt[i] = sfmmup->sfmmu_ttecnt[i] +
10097 		    sfmmup->sfmmu_ismttecnt[i];
10098 	}
10099 
10100 	/* Check pagesizes in use, and possibly reprogram DTLB. */
10101 	if (&mmu_check_page_sizes)
10102 		mmu_check_page_sizes(sfmmup, ttecnt);
10103 
10104 	/*
10105 	 * Calculate the number of 8k ttes to represent the span of these
10106 	 * pages.
10107 	 */
10108 	tte8k_cnt = ttecnt[TTE8K] +
10109 	    (ttecnt[TTE64K] << (MMU_PAGESHIFT64K - MMU_PAGESHIFT)) +
10110 	    (ttecnt[TTE512K] << (MMU_PAGESHIFT512K - MMU_PAGESHIFT));
10111 	if (mmu_page_sizes == max_mmu_page_sizes) {
10112 		tte4m_cnt = ttecnt[TTE4M] +
10113 		    (ttecnt[TTE32M] << (MMU_PAGESHIFT32M - MMU_PAGESHIFT4M)) +
10114 		    (ttecnt[TTE256M] << (MMU_PAGESHIFT256M - MMU_PAGESHIFT4M));
10115 	} else {
10116 		tte4m_cnt = ttecnt[TTE4M];
10117 	}
10118 
10119 	/*
10120 	 * Inflate tte8k_cnt to allow for region large page allocation failure.
10121 	 */
10122 	tte8k_cnt += sfmmup->sfmmu_tsb0_4minflcnt;
10123 
10124 	/*
10125 	 * Inflate TSB sizes by a factor of 2 if this process
10126 	 * uses 4M text pages to minimize extra conflict misses
10127 	 * in the first TSB since without counting text pages
10128 	 * 8K TSB may become too small.
10129 	 *
10130 	 * Also double the size of the second TSB to minimize
10131 	 * extra conflict misses due to competition between 4M text pages
10132 	 * and data pages.
10133 	 *
10134 	 * We need to adjust the second TSB allocation threshold by the
10135 	 * inflation factor, since there is no point in creating a second
10136 	 * TSB when we know all the mappings can fit in the I/D TLBs.
10137 	 */
10138 	sectsb_thresh = tsb_sectsb_threshold;
10139 	if (sfmmup->sfmmu_flags & HAT_4MTEXT_FLAG) {
10140 		tte8k_cnt <<= 1;
10141 		tte4m_cnt <<= 1;
10142 		sectsb_thresh <<= 1;
10143 	}
10144 
10145 	/*
10146 	 * Check to see if our TSB is the right size; we may need to
10147 	 * grow or shrink it.  If the process is small, our work is
10148 	 * finished at this point.
10149 	 */
10150 	if (tte8k_cnt <= tsb_rss_factor && tte4m_cnt <= sectsb_thresh) {
10151 		return;
10152 	}
10153 	sfmmu_size_tsb(sfmmup, growing, tte8k_cnt, tte4m_cnt, sectsb_thresh);
10154 }
10155 
10156 static void
10157 sfmmu_size_tsb(sfmmu_t *sfmmup, int growing, uint64_t tte8k_cnt,
10158     uint64_t tte4m_cnt, int sectsb_thresh)
10159 {
10160 	int tsb_bits;
10161 	uint_t tsb_szc;
10162 	struct tsb_info *tsbinfop;
10163 	hatlock_t *hatlockp = NULL;
10164 
10165 	hatlockp = sfmmu_hat_enter(sfmmup);
10166 	ASSERT(hatlockp != NULL);
10167 	tsbinfop = sfmmup->sfmmu_tsb;
10168 	ASSERT(tsbinfop != NULL);
10169 
10170 	/*
10171 	 * If we're growing, select the size based on RSS.  If we're
10172 	 * shrinking, leave some room so we don't have to turn around and
10173 	 * grow again immediately.
10174 	 */
10175 	if (growing)
10176 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
10177 	else
10178 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt << 1);
10179 
10180 	if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10181 	    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10182 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10183 		    hatlockp, TSB_SHRINK);
10184 	} else if (growing && tsb_szc > tsbinfop->tsb_szc && TSB_OK_GROW()) {
10185 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
10186 		    hatlockp, TSB_GROW);
10187 	}
10188 	tsbinfop = sfmmup->sfmmu_tsb;
10189 
10190 	/*
10191 	 * With the TLB and first TSB out of the way, we need to see if
10192 	 * we need a second TSB for 4M pages.  If we managed to reprogram
10193 	 * the TLB page sizes above, the process will start using this new
10194 	 * TSB right away; otherwise, it will start using it on the next
10195 	 * context switch.  Either way, it's no big deal so there's no
10196 	 * synchronization with the trap handlers here unless we grow the
10197 	 * TSB (in which case it's required to prevent using the old one
10198 	 * after it's freed). Note: second tsb is required for 32M/256M
10199 	 * page sizes.
10200 	 */
10201 	if (tte4m_cnt > sectsb_thresh) {
10202 		/*
10203 		 * If we're growing, select the size based on RSS.  If we're
10204 		 * shrinking, leave some room so we don't have to turn
10205 		 * around and grow again immediately.
10206 		 */
10207 		if (growing)
10208 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
10209 		else
10210 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt << 1);
10211 		if (tsbinfop->tsb_next == NULL) {
10212 			struct tsb_info *newtsb;
10213 			int allocflags = SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)?
10214 			    0 : TSB_ALLOC;
10215 
10216 			sfmmu_hat_exit(hatlockp);
10217 
10218 			/*
10219 			 * Try to allocate a TSB for 4[32|256]M pages.  If we
10220 			 * can't get the size we want, retry w/a minimum sized
10221 			 * TSB.  If that still didn't work, give up; we can
10222 			 * still run without one.
10223 			 */
10224 			tsb_bits = (mmu_page_sizes == max_mmu_page_sizes)?
10225 			    TSB4M|TSB32M|TSB256M:TSB4M;
10226 			if ((sfmmu_tsbinfo_alloc(&newtsb, tsb_szc, tsb_bits,
10227 			    allocflags, sfmmup)) &&
10228 			    (tsb_szc <= TSB_4M_SZCODE ||
10229 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
10230 			    tsb_bits, allocflags, sfmmup)) &&
10231 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_MIN_SZCODE,
10232 			    tsb_bits, allocflags, sfmmup)) {
10233 				return;
10234 			}
10235 
10236 			hatlockp = sfmmu_hat_enter(sfmmup);
10237 
10238 			sfmmu_invalidate_ctx(sfmmup);
10239 
10240 			if (sfmmup->sfmmu_tsb->tsb_next == NULL) {
10241 				sfmmup->sfmmu_tsb->tsb_next = newtsb;
10242 				SFMMU_STAT(sf_tsb_sectsb_create);
10243 				sfmmu_hat_exit(hatlockp);
10244 				return;
10245 			} else {
10246 				/*
10247 				 * It's annoying, but possible for us
10248 				 * to get here.. we dropped the HAT lock
10249 				 * because of locking order in the kmem
10250 				 * allocator, and while we were off getting
10251 				 * our memory, some other thread decided to
10252 				 * do us a favor and won the race to get a
10253 				 * second TSB for this process.  Sigh.
10254 				 */
10255 				sfmmu_hat_exit(hatlockp);
10256 				sfmmu_tsbinfo_free(newtsb);
10257 				return;
10258 			}
10259 		}
10260 
10261 		/*
10262 		 * We have a second TSB, see if it's big enough.
10263 		 */
10264 		tsbinfop = tsbinfop->tsb_next;
10265 
10266 		/*
10267 		 * Check to see if our second TSB is the right size;
10268 		 * we may need to grow or shrink it.
10269 		 * To prevent thrashing (e.g. growing the TSB on a
10270 		 * subsequent map operation), only try to shrink if
10271 		 * the TSB reach exceeds twice the virtual address
10272 		 * space size.
10273 		 */
10274 		if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
10275 		    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
10276 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10277 			    tsb_szc, hatlockp, TSB_SHRINK);
10278 		} else if (growing && tsb_szc > tsbinfop->tsb_szc &&
10279 		    TSB_OK_GROW()) {
10280 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
10281 			    tsb_szc, hatlockp, TSB_GROW);
10282 		}
10283 	}
10284 
10285 	sfmmu_hat_exit(hatlockp);
10286 }
10287 
10288 /*
10289  * Free up a sfmmu
10290  * Since the sfmmu is currently embedded in the hat struct we simply zero
10291  * out our fields and free up the ism map blk list if any.
10292  */
10293 static void
10294 sfmmu_free_sfmmu(sfmmu_t *sfmmup)
10295 {
10296 	ism_blk_t	*blkp, *nx_blkp;
10297 #ifdef	DEBUG
10298 	ism_map_t	*map;
10299 	int		i;
10300 #endif
10301 
10302 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
10303 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
10304 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
10305 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
10306 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
10307 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
10308 	ASSERT(SF_RGNMAP_ISNULL(sfmmup));
10309 
10310 	sfmmup->sfmmu_free = 0;
10311 	sfmmup->sfmmu_ismhat = 0;
10312 
10313 	blkp = sfmmup->sfmmu_iblk;
10314 	sfmmup->sfmmu_iblk = NULL;
10315 
10316 	while (blkp) {
10317 #ifdef	DEBUG
10318 		map = blkp->iblk_maps;
10319 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
10320 			ASSERT(map[i].imap_seg == 0);
10321 			ASSERT(map[i].imap_ismhat == NULL);
10322 			ASSERT(map[i].imap_ment == NULL);
10323 		}
10324 #endif
10325 		nx_blkp = blkp->iblk_next;
10326 		blkp->iblk_next = NULL;
10327 		blkp->iblk_nextpa = (uint64_t)-1;
10328 		kmem_cache_free(ism_blk_cache, blkp);
10329 		blkp = nx_blkp;
10330 	}
10331 }
10332 
10333 /*
10334  * Locking primitves accessed by HATLOCK macros
10335  */
10336 
10337 #define	SFMMU_SPL_MTX	(0x0)
10338 #define	SFMMU_ML_MTX	(0x1)
10339 
10340 #define	SFMMU_MLSPL_MTX(type, pg)	(((type) == SFMMU_SPL_MTX) ? \
10341 					    SPL_HASH(pg) : MLIST_HASH(pg))
10342 
10343 kmutex_t *
10344 sfmmu_page_enter(struct page *pp)
10345 {
10346 	return (sfmmu_mlspl_enter(pp, SFMMU_SPL_MTX));
10347 }
10348 
10349 void
10350 sfmmu_page_exit(kmutex_t *spl)
10351 {
10352 	mutex_exit(spl);
10353 }
10354 
10355 int
10356 sfmmu_page_spl_held(struct page *pp)
10357 {
10358 	return (sfmmu_mlspl_held(pp, SFMMU_SPL_MTX));
10359 }
10360 
10361 kmutex_t *
10362 sfmmu_mlist_enter(struct page *pp)
10363 {
10364 	return (sfmmu_mlspl_enter(pp, SFMMU_ML_MTX));
10365 }
10366 
10367 void
10368 sfmmu_mlist_exit(kmutex_t *mml)
10369 {
10370 	mutex_exit(mml);
10371 }
10372 
10373 int
10374 sfmmu_mlist_held(struct page *pp)
10375 {
10376 
10377 	return (sfmmu_mlspl_held(pp, SFMMU_ML_MTX));
10378 }
10379 
10380 /*
10381  * Common code for sfmmu_mlist_enter() and sfmmu_page_enter().  For
10382  * sfmmu_mlist_enter() case mml_table lock array is used and for
10383  * sfmmu_page_enter() sfmmu_page_lock lock array is used.
10384  *
10385  * The lock is taken on a root page so that it protects an operation on all
10386  * constituent pages of a large page pp belongs to.
10387  *
10388  * The routine takes a lock from the appropriate array. The lock is determined
10389  * by hashing the root page. After taking the lock this routine checks if the
10390  * root page has the same size code that was used to determine the root (i.e
10391  * that root hasn't changed).  If root page has the expected p_szc field we
10392  * have the right lock and it's returned to the caller. If root's p_szc
10393  * decreased we release the lock and retry from the beginning.  This case can
10394  * happen due to hat_page_demote() decreasing p_szc between our load of p_szc
10395  * value and taking the lock. The number of retries due to p_szc decrease is
10396  * limited by the maximum p_szc value. If p_szc is 0 we return the lock
10397  * determined by hashing pp itself.
10398  *
10399  * If our caller doesn't hold a SE_SHARED or SE_EXCL lock on pp it's also
10400  * possible that p_szc can increase. To increase p_szc a thread has to lock
10401  * all constituent pages EXCL and do hat_pageunload() on all of them. All the
10402  * callers that don't hold a page locked recheck if hmeblk through which pp
10403  * was found still maps this pp.  If it doesn't map it anymore returned lock
10404  * is immediately dropped. Therefore if sfmmu_mlspl_enter() hits the case of
10405  * p_szc increase after taking the lock it returns this lock without further
10406  * retries because in this case the caller doesn't care about which lock was
10407  * taken. The caller will drop it right away.
10408  *
10409  * After the routine returns it's guaranteed that hat_page_demote() can't
10410  * change p_szc field of any of constituent pages of a large page pp belongs
10411  * to as long as pp was either locked at least SHARED prior to this call or
10412  * the caller finds that hment that pointed to this pp still references this
10413  * pp (this also assumes that the caller holds hme hash bucket lock so that
10414  * the same pp can't be remapped into the same hmeblk after it was unmapped by
10415  * hat_pageunload()).
10416  */
10417 static kmutex_t *
10418 sfmmu_mlspl_enter(struct page *pp, int type)
10419 {
10420 	kmutex_t	*mtx;
10421 	uint_t		prev_rszc = UINT_MAX;
10422 	page_t		*rootpp;
10423 	uint_t		szc;
10424 	uint_t		rszc;
10425 	uint_t		pszc = pp->p_szc;
10426 
10427 	ASSERT(pp != NULL);
10428 
10429 again:
10430 	if (pszc == 0) {
10431 		mtx = SFMMU_MLSPL_MTX(type, pp);
10432 		mutex_enter(mtx);
10433 		return (mtx);
10434 	}
10435 
10436 	/* The lock lives in the root page */
10437 	rootpp = PP_GROUPLEADER(pp, pszc);
10438 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10439 	mutex_enter(mtx);
10440 
10441 	/*
10442 	 * Return mml in the following 3 cases:
10443 	 *
10444 	 * 1) If pp itself is root since if its p_szc decreased before we took
10445 	 * the lock pp is still the root of smaller szc page. And if its p_szc
10446 	 * increased it doesn't matter what lock we return (see comment in
10447 	 * front of this routine).
10448 	 *
10449 	 * 2) If pp's not root but rootpp is the root of a rootpp->p_szc size
10450 	 * large page we have the right lock since any previous potential
10451 	 * hat_page_demote() is done demoting from greater than current root's
10452 	 * p_szc because hat_page_demote() changes root's p_szc last. No
10453 	 * further hat_page_demote() can start or be in progress since it
10454 	 * would need the same lock we currently hold.
10455 	 *
10456 	 * 3) If rootpp's p_szc increased since previous iteration it doesn't
10457 	 * matter what lock we return (see comment in front of this routine).
10458 	 */
10459 	if (pp == rootpp || (rszc = rootpp->p_szc) == pszc ||
10460 	    rszc >= prev_rszc) {
10461 		return (mtx);
10462 	}
10463 
10464 	/*
10465 	 * hat_page_demote() could have decreased root's p_szc.
10466 	 * In this case pp's p_szc must also be smaller than pszc.
10467 	 * Retry.
10468 	 */
10469 	if (rszc < pszc) {
10470 		szc = pp->p_szc;
10471 		if (szc < pszc) {
10472 			mutex_exit(mtx);
10473 			pszc = szc;
10474 			goto again;
10475 		}
10476 		/*
10477 		 * pp's p_szc increased after it was decreased.
10478 		 * page cannot be mapped. Return current lock. The caller
10479 		 * will drop it right away.
10480 		 */
10481 		return (mtx);
10482 	}
10483 
10484 	/*
10485 	 * root's p_szc is greater than pp's p_szc.
10486 	 * hat_page_demote() is not done with all pages
10487 	 * yet. Wait for it to complete.
10488 	 */
10489 	mutex_exit(mtx);
10490 	rootpp = PP_GROUPLEADER(rootpp, rszc);
10491 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
10492 	mutex_enter(mtx);
10493 	mutex_exit(mtx);
10494 	prev_rszc = rszc;
10495 	goto again;
10496 }
10497 
10498 static int
10499 sfmmu_mlspl_held(struct page *pp, int type)
10500 {
10501 	kmutex_t	*mtx;
10502 
10503 	ASSERT(pp != NULL);
10504 	/* The lock lives in the root page */
10505 	pp = PP_PAGEROOT(pp);
10506 	ASSERT(pp != NULL);
10507 
10508 	mtx = SFMMU_MLSPL_MTX(type, pp);
10509 	return (MUTEX_HELD(mtx));
10510 }
10511 
10512 static uint_t
10513 sfmmu_get_free_hblk(struct hme_blk **hmeblkpp, uint_t critical)
10514 {
10515 	struct  hme_blk *hblkp;
10516 
10517 
10518 	if (freehblkp != NULL) {
10519 		mutex_enter(&freehblkp_lock);
10520 		if (freehblkp != NULL) {
10521 			/*
10522 			 * If the current thread is owning hblk_reserve OR
10523 			 * critical request from sfmmu_hblk_steal()
10524 			 * let it succeed even if freehblkcnt is really low.
10525 			 */
10526 			if (freehblkcnt <= HBLK_RESERVE_MIN && !critical) {
10527 				SFMMU_STAT(sf_get_free_throttle);
10528 				mutex_exit(&freehblkp_lock);
10529 				return (0);
10530 			}
10531 			freehblkcnt--;
10532 			*hmeblkpp = freehblkp;
10533 			hblkp = *hmeblkpp;
10534 			freehblkp = hblkp->hblk_next;
10535 			mutex_exit(&freehblkp_lock);
10536 			hblkp->hblk_next = NULL;
10537 			SFMMU_STAT(sf_get_free_success);
10538 
10539 			ASSERT(hblkp->hblk_hmecnt == 0);
10540 			ASSERT(hblkp->hblk_vcnt == 0);
10541 			ASSERT(hblkp->hblk_nextpa == va_to_pa((caddr_t)hblkp));
10542 
10543 			return (1);
10544 		}
10545 		mutex_exit(&freehblkp_lock);
10546 	}
10547 
10548 	/* Check cpu hblk pending queues */
10549 	if ((*hmeblkpp = sfmmu_check_pending_hblks(TTE8K)) != NULL) {
10550 		hblkp = *hmeblkpp;
10551 		hblkp->hblk_next = NULL;
10552 		hblkp->hblk_nextpa = va_to_pa((caddr_t)hblkp);
10553 
10554 		ASSERT(hblkp->hblk_hmecnt == 0);
10555 		ASSERT(hblkp->hblk_vcnt == 0);
10556 
10557 		return (1);
10558 	}
10559 
10560 	SFMMU_STAT(sf_get_free_fail);
10561 	return (0);
10562 }
10563 
10564 static uint_t
10565 sfmmu_put_free_hblk(struct hme_blk *hmeblkp, uint_t critical)
10566 {
10567 	struct  hme_blk *hblkp;
10568 
10569 	ASSERT(hmeblkp->hblk_hmecnt == 0);
10570 	ASSERT(hmeblkp->hblk_vcnt == 0);
10571 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
10572 
10573 	/*
10574 	 * If the current thread is mapping into kernel space,
10575 	 * let it succede even if freehblkcnt is max
10576 	 * so that it will avoid freeing it to kmem.
10577 	 * This will prevent stack overflow due to
10578 	 * possible recursion since kmem_cache_free()
10579 	 * might require creation of a slab which
10580 	 * in turn needs an hmeblk to map that slab;
10581 	 * let's break this vicious chain at the first
10582 	 * opportunity.
10583 	 */
10584 	if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10585 		mutex_enter(&freehblkp_lock);
10586 		if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
10587 			SFMMU_STAT(sf_put_free_success);
10588 			freehblkcnt++;
10589 			hmeblkp->hblk_next = freehblkp;
10590 			freehblkp = hmeblkp;
10591 			mutex_exit(&freehblkp_lock);
10592 			return (1);
10593 		}
10594 		mutex_exit(&freehblkp_lock);
10595 	}
10596 
10597 	/*
10598 	 * Bring down freehblkcnt to HBLK_RESERVE_CNT. We are here
10599 	 * only if freehblkcnt is at least HBLK_RESERVE_CNT *and*
10600 	 * we are not in the process of mapping into kernel space.
10601 	 */
10602 	ASSERT(!critical);
10603 	while (freehblkcnt > HBLK_RESERVE_CNT) {
10604 		mutex_enter(&freehblkp_lock);
10605 		if (freehblkcnt > HBLK_RESERVE_CNT) {
10606 			freehblkcnt--;
10607 			hblkp = freehblkp;
10608 			freehblkp = hblkp->hblk_next;
10609 			mutex_exit(&freehblkp_lock);
10610 			ASSERT(get_hblk_cache(hblkp) == sfmmu8_cache);
10611 			kmem_cache_free(sfmmu8_cache, hblkp);
10612 			continue;
10613 		}
10614 		mutex_exit(&freehblkp_lock);
10615 	}
10616 	SFMMU_STAT(sf_put_free_fail);
10617 	return (0);
10618 }
10619 
10620 static void
10621 sfmmu_hblk_swap(struct hme_blk *new)
10622 {
10623 	struct hme_blk *old, *hblkp, *prev;
10624 	uint64_t newpa;
10625 	caddr_t	base, vaddr, endaddr;
10626 	struct hmehash_bucket *hmebp;
10627 	struct sf_hment *osfhme, *nsfhme;
10628 	page_t *pp;
10629 	kmutex_t *pml;
10630 	tte_t tte;
10631 	struct hme_blk *list = NULL;
10632 
10633 #ifdef	DEBUG
10634 	hmeblk_tag		hblktag;
10635 	struct hme_blk		*found;
10636 #endif
10637 	old = HBLK_RESERVE;
10638 	ASSERT(!old->hblk_shared);
10639 
10640 	/*
10641 	 * save pa before bcopy clobbers it
10642 	 */
10643 	newpa = new->hblk_nextpa;
10644 
10645 	base = (caddr_t)get_hblk_base(old);
10646 	endaddr = base + get_hblk_span(old);
10647 
10648 	/*
10649 	 * acquire hash bucket lock.
10650 	 */
10651 	hmebp = sfmmu_tteload_acquire_hashbucket(ksfmmup, base, TTE8K,
10652 	    SFMMU_INVALID_SHMERID);
10653 
10654 	/*
10655 	 * copy contents from old to new
10656 	 */
10657 	bcopy((void *)old, (void *)new, HME8BLK_SZ);
10658 
10659 	/*
10660 	 * add new to hash chain
10661 	 */
10662 	sfmmu_hblk_hash_add(hmebp, new, newpa);
10663 
10664 	/*
10665 	 * search hash chain for hblk_reserve; this needs to be performed
10666 	 * after adding new, otherwise prev won't correspond to the hblk which
10667 	 * is prior to old in hash chain when we call sfmmu_hblk_hash_rm to
10668 	 * remove old later.
10669 	 */
10670 	for (prev = NULL,
10671 	    hblkp = hmebp->hmeblkp; hblkp != NULL && hblkp != old;
10672 	    prev = hblkp, hblkp = hblkp->hblk_next)
10673 		;
10674 
10675 	if (hblkp != old)
10676 		panic("sfmmu_hblk_swap: hblk_reserve not found");
10677 
10678 	/*
10679 	 * p_mapping list is still pointing to hments in hblk_reserve;
10680 	 * fix up p_mapping list so that they point to hments in new.
10681 	 *
10682 	 * Since all these mappings are created by hblk_reserve_thread
10683 	 * on the way and it's using at least one of the buffers from each of
10684 	 * the newly minted slabs, there is no danger of any of these
10685 	 * mappings getting unloaded by another thread.
10686 	 *
10687 	 * tsbmiss could only modify ref/mod bits of hments in old/new.
10688 	 * Since all of these hments hold mappings established by segkmem
10689 	 * and mappings in segkmem are setup with HAT_NOSYNC, ref/mod bits
10690 	 * have no meaning for the mappings in hblk_reserve.  hments in
10691 	 * old and new are identical except for ref/mod bits.
10692 	 */
10693 	for (vaddr = base; vaddr < endaddr; vaddr += TTEBYTES(TTE8K)) {
10694 
10695 		HBLKTOHME(osfhme, old, vaddr);
10696 		sfmmu_copytte(&osfhme->hme_tte, &tte);
10697 
10698 		if (TTE_IS_VALID(&tte)) {
10699 			if ((pp = osfhme->hme_page) == NULL)
10700 				panic("sfmmu_hblk_swap: page not mapped");
10701 
10702 			pml = sfmmu_mlist_enter(pp);
10703 
10704 			if (pp != osfhme->hme_page)
10705 				panic("sfmmu_hblk_swap: mapping changed");
10706 
10707 			HBLKTOHME(nsfhme, new, vaddr);
10708 
10709 			HME_ADD(nsfhme, pp);
10710 			HME_SUB(osfhme, pp);
10711 
10712 			sfmmu_mlist_exit(pml);
10713 		}
10714 	}
10715 
10716 	/*
10717 	 * remove old from hash chain
10718 	 */
10719 	sfmmu_hblk_hash_rm(hmebp, old, prev, &list, 1);
10720 
10721 #ifdef	DEBUG
10722 
10723 	hblktag.htag_id = ksfmmup;
10724 	hblktag.htag_rid = SFMMU_INVALID_SHMERID;
10725 	hblktag.htag_bspage = HME_HASH_BSPAGE(base, HME_HASH_SHIFT(TTE8K));
10726 	hblktag.htag_rehash = HME_HASH_REHASH(TTE8K);
10727 	HME_HASH_FAST_SEARCH(hmebp, hblktag, found);
10728 
10729 	if (found != new)
10730 		panic("sfmmu_hblk_swap: new hblk not found");
10731 #endif
10732 
10733 	SFMMU_HASH_UNLOCK(hmebp);
10734 
10735 	/*
10736 	 * Reset hblk_reserve
10737 	 */
10738 	bzero((void *)old, HME8BLK_SZ);
10739 	old->hblk_nextpa = va_to_pa((caddr_t)old);
10740 }
10741 
10742 /*
10743  * Grab the mlist mutex for both pages passed in.
10744  *
10745  * low and high will be returned as pointers to the mutexes for these pages.
10746  * low refers to the mutex residing in the lower bin of the mlist hash, while
10747  * high refers to the mutex residing in the higher bin of the mlist hash.  This
10748  * is due to the locking order restrictions on the same thread grabbing
10749  * multiple mlist mutexes.  The low lock must be acquired before the high lock.
10750  *
10751  * If both pages hash to the same mutex, only grab that single mutex, and
10752  * high will be returned as NULL
10753  * If the pages hash to different bins in the hash, grab the lower addressed
10754  * lock first and then the higher addressed lock in order to follow the locking
10755  * rules involved with the same thread grabbing multiple mlist mutexes.
10756  * low and high will both have non-NULL values.
10757  */
10758 static void
10759 sfmmu_mlist_reloc_enter(struct page *targ, struct page *repl,
10760     kmutex_t **low, kmutex_t **high)
10761 {
10762 	kmutex_t	*mml_targ, *mml_repl;
10763 
10764 	/*
10765 	 * no need to do the dance around szc as in sfmmu_mlist_enter()
10766 	 * because this routine is only called by hat_page_relocate() and all
10767 	 * targ and repl pages are already locked EXCL so szc can't change.
10768 	 */
10769 
10770 	mml_targ = MLIST_HASH(PP_PAGEROOT(targ));
10771 	mml_repl = MLIST_HASH(PP_PAGEROOT(repl));
10772 
10773 	if (mml_targ == mml_repl) {
10774 		*low = mml_targ;
10775 		*high = NULL;
10776 	} else {
10777 		if (mml_targ < mml_repl) {
10778 			*low = mml_targ;
10779 			*high = mml_repl;
10780 		} else {
10781 			*low = mml_repl;
10782 			*high = mml_targ;
10783 		}
10784 	}
10785 
10786 	mutex_enter(*low);
10787 	if (*high)
10788 		mutex_enter(*high);
10789 }
10790 
10791 static void
10792 sfmmu_mlist_reloc_exit(kmutex_t *low, kmutex_t *high)
10793 {
10794 	if (high)
10795 		mutex_exit(high);
10796 	mutex_exit(low);
10797 }
10798 
10799 static hatlock_t *
10800 sfmmu_hat_enter(sfmmu_t *sfmmup)
10801 {
10802 	hatlock_t	*hatlockp;
10803 
10804 	if (sfmmup != ksfmmup) {
10805 		hatlockp = TSB_HASH(sfmmup);
10806 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
10807 		return (hatlockp);
10808 	}
10809 	return (NULL);
10810 }
10811 
10812 static hatlock_t *
10813 sfmmu_hat_tryenter(sfmmu_t *sfmmup)
10814 {
10815 	hatlock_t	*hatlockp;
10816 
10817 	if (sfmmup != ksfmmup) {
10818 		hatlockp = TSB_HASH(sfmmup);
10819 		if (mutex_tryenter(HATLOCK_MUTEXP(hatlockp)) == 0)
10820 			return (NULL);
10821 		return (hatlockp);
10822 	}
10823 	return (NULL);
10824 }
10825 
10826 static void
10827 sfmmu_hat_exit(hatlock_t *hatlockp)
10828 {
10829 	if (hatlockp != NULL)
10830 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
10831 }
10832 
10833 static void
10834 sfmmu_hat_lock_all(void)
10835 {
10836 	int i;
10837 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
10838 		mutex_enter(HATLOCK_MUTEXP(&hat_lock[i]));
10839 }
10840 
10841 static void
10842 sfmmu_hat_unlock_all(void)
10843 {
10844 	int i;
10845 	for (i = SFMMU_NUM_LOCK - 1; i >= 0; i--)
10846 		mutex_exit(HATLOCK_MUTEXP(&hat_lock[i]));
10847 }
10848 
10849 int
10850 sfmmu_hat_lock_held(sfmmu_t *sfmmup)
10851 {
10852 	ASSERT(sfmmup != ksfmmup);
10853 	return (MUTEX_HELD(HATLOCK_MUTEXP(TSB_HASH(sfmmup))));
10854 }
10855 
10856 /*
10857  * Locking primitives to provide consistency between ISM unmap
10858  * and other operations.  Since ISM unmap can take a long time, we
10859  * use HAT_ISMBUSY flag (protected by the hatlock) to avoid creating
10860  * contention on the hatlock buckets while ISM segments are being
10861  * unmapped.  The tradeoff is that the flags don't prevent priority
10862  * inversion from occurring, so we must request kernel priority in
10863  * case we have to sleep to keep from getting buried while holding
10864  * the HAT_ISMBUSY flag set, which in turn could block other kernel
10865  * threads from running (for example, in sfmmu_uvatopfn()).
10866  */
10867 static void
10868 sfmmu_ismhat_enter(sfmmu_t *sfmmup, int hatlock_held)
10869 {
10870 	hatlock_t *hatlockp;
10871 
10872 	if (!hatlock_held)
10873 		hatlockp = sfmmu_hat_enter(sfmmup);
10874 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY))
10875 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
10876 	SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
10877 	if (!hatlock_held)
10878 		sfmmu_hat_exit(hatlockp);
10879 }
10880 
10881 static void
10882 sfmmu_ismhat_exit(sfmmu_t *sfmmup, int hatlock_held)
10883 {
10884 	hatlock_t *hatlockp;
10885 
10886 	if (!hatlock_held)
10887 		hatlockp = sfmmu_hat_enter(sfmmup);
10888 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
10889 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
10890 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
10891 	if (!hatlock_held)
10892 		sfmmu_hat_exit(hatlockp);
10893 }
10894 
10895 /*
10896  *
10897  * Algorithm:
10898  *
10899  * (1) if segkmem is not ready, allocate hblk from an array of pre-alloc'ed
10900  *	hblks.
10901  *
10902  * (2) if we are allocating an hblk for mapping a slab in sfmmu_cache,
10903  *
10904  *		(a) try to return an hblk from reserve pool of free hblks;
10905  *		(b) if the reserve pool is empty, acquire hblk_reserve_lock
10906  *		    and return hblk_reserve.
10907  *
10908  * (3) call kmem_cache_alloc() to allocate hblk;
10909  *
10910  *		(a) if hblk_reserve_lock is held by the current thread,
10911  *		    atomically replace hblk_reserve by the hblk that is
10912  *		    returned by kmem_cache_alloc; release hblk_reserve_lock
10913  *		    and call kmem_cache_alloc() again.
10914  *		(b) if reserve pool is not full, add the hblk that is
10915  *		    returned by kmem_cache_alloc to reserve pool and
10916  *		    call kmem_cache_alloc again.
10917  *
10918  */
10919 static struct hme_blk *
10920 sfmmu_hblk_alloc(sfmmu_t *sfmmup, caddr_t vaddr,
10921     struct hmehash_bucket *hmebp, uint_t size, hmeblk_tag hblktag,
10922     uint_t flags, uint_t rid)
10923 {
10924 	struct hme_blk *hmeblkp = NULL;
10925 	struct hme_blk *newhblkp;
10926 	struct hme_blk *shw_hblkp = NULL;
10927 	struct kmem_cache *sfmmu_cache = NULL;
10928 	uint64_t hblkpa;
10929 	ulong_t index;
10930 	uint_t owner;		/* set to 1 if using hblk_reserve */
10931 	uint_t forcefree;
10932 	int sleep;
10933 	sf_srd_t *srdp;
10934 	sf_region_t *rgnp;
10935 
10936 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
10937 	ASSERT(hblktag.htag_rid == rid);
10938 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
10939 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
10940 	    IS_P2ALIGNED(vaddr, TTEBYTES(size)));
10941 
10942 	/*
10943 	 * If segkmem is not created yet, allocate from static hmeblks
10944 	 * created at the end of startup_modules().  See the block comment
10945 	 * in startup_modules() describing how we estimate the number of
10946 	 * static hmeblks that will be needed during re-map.
10947 	 */
10948 	if (!hblk_alloc_dynamic) {
10949 
10950 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
10951 
10952 		if (size == TTE8K) {
10953 			index = nucleus_hblk8.index;
10954 			if (index >= nucleus_hblk8.len) {
10955 				/*
10956 				 * If we panic here, see startup_modules() to
10957 				 * make sure that we are calculating the
10958 				 * number of hblk8's that we need correctly.
10959 				 */
10960 				prom_panic("no nucleus hblk8 to allocate");
10961 			}
10962 			hmeblkp =
10963 			    (struct hme_blk *)&nucleus_hblk8.list[index];
10964 			nucleus_hblk8.index++;
10965 			SFMMU_STAT(sf_hblk8_nalloc);
10966 		} else {
10967 			index = nucleus_hblk1.index;
10968 			if (nucleus_hblk1.index >= nucleus_hblk1.len) {
10969 				/*
10970 				 * If we panic here, see startup_modules().
10971 				 * Most likely you need to update the
10972 				 * calculation of the number of hblk1 elements
10973 				 * that the kernel needs to boot.
10974 				 */
10975 				prom_panic("no nucleus hblk1 to allocate");
10976 			}
10977 			hmeblkp =
10978 			    (struct hme_blk *)&nucleus_hblk1.list[index];
10979 			nucleus_hblk1.index++;
10980 			SFMMU_STAT(sf_hblk1_nalloc);
10981 		}
10982 
10983 		goto hblk_init;
10984 	}
10985 
10986 	SFMMU_HASH_UNLOCK(hmebp);
10987 
10988 	if (sfmmup != KHATID && !SFMMU_IS_SHMERID_VALID(rid)) {
10989 		if (mmu_page_sizes == max_mmu_page_sizes) {
10990 			if (size < TTE256M)
10991 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
10992 				    size, flags);
10993 		} else {
10994 			if (size < TTE4M)
10995 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
10996 				    size, flags);
10997 		}
10998 	} else if (SFMMU_IS_SHMERID_VALID(rid)) {
10999 		/*
11000 		 * Shared hmes use per region bitmaps in rgn_hmeflag
11001 		 * rather than shadow hmeblks to keep track of the
11002 		 * mapping sizes which have been allocated for the region.
11003 		 * Here we cleanup old invalid hmeblks with this rid,
11004 		 * which may be left around by pageunload().
11005 		 */
11006 		int ttesz;
11007 		caddr_t va;
11008 		caddr_t	eva = vaddr + TTEBYTES(size);
11009 
11010 		ASSERT(sfmmup != KHATID);
11011 
11012 		srdp = sfmmup->sfmmu_srdp;
11013 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11014 		rgnp = srdp->srd_hmergnp[rid];
11015 		ASSERT(rgnp != NULL && rgnp->rgn_id == rid);
11016 		ASSERT(rgnp->rgn_refcnt != 0);
11017 		ASSERT(size <= rgnp->rgn_pgszc);
11018 
11019 		ttesz = HBLK_MIN_TTESZ;
11020 		do {
11021 			if (!(rgnp->rgn_hmeflags & (0x1 << ttesz))) {
11022 				continue;
11023 			}
11024 
11025 			if (ttesz > size && ttesz != HBLK_MIN_TTESZ) {
11026 				sfmmu_cleanup_rhblk(srdp, vaddr, rid, ttesz);
11027 			} else if (ttesz < size) {
11028 				for (va = vaddr; va < eva;
11029 				    va += TTEBYTES(ttesz)) {
11030 					sfmmu_cleanup_rhblk(srdp, va, rid,
11031 					    ttesz);
11032 				}
11033 			}
11034 		} while (++ttesz <= rgnp->rgn_pgszc);
11035 	}
11036 
11037 fill_hblk:
11038 	owner = (hblk_reserve_thread == curthread) ? 1 : 0;
11039 
11040 	if (owner && size == TTE8K) {
11041 
11042 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid));
11043 		/*
11044 		 * We are really in a tight spot. We already own
11045 		 * hblk_reserve and we need another hblk.  In anticipation
11046 		 * of this kind of scenario, we specifically set aside
11047 		 * HBLK_RESERVE_MIN number of hblks to be used exclusively
11048 		 * by owner of hblk_reserve.
11049 		 */
11050 		SFMMU_STAT(sf_hblk_recurse_cnt);
11051 
11052 		if (!sfmmu_get_free_hblk(&hmeblkp, 1))
11053 			panic("sfmmu_hblk_alloc: reserve list is empty");
11054 
11055 		goto hblk_verify;
11056 	}
11057 
11058 	ASSERT(!owner);
11059 
11060 	if ((flags & HAT_NO_KALLOC) == 0) {
11061 
11062 		sfmmu_cache = ((size == TTE8K) ? sfmmu8_cache : sfmmu1_cache);
11063 		sleep = ((sfmmup == KHATID) ? KM_NOSLEEP : KM_SLEEP);
11064 
11065 		if ((hmeblkp = kmem_cache_alloc(sfmmu_cache, sleep)) == NULL) {
11066 			hmeblkp = sfmmu_hblk_steal(size);
11067 		} else {
11068 			/*
11069 			 * if we are the owner of hblk_reserve,
11070 			 * swap hblk_reserve with hmeblkp and
11071 			 * start a fresh life.  Hope things go
11072 			 * better this time.
11073 			 */
11074 			if (hblk_reserve_thread == curthread) {
11075 				ASSERT(sfmmu_cache == sfmmu8_cache);
11076 				sfmmu_hblk_swap(hmeblkp);
11077 				hblk_reserve_thread = NULL;
11078 				mutex_exit(&hblk_reserve_lock);
11079 				goto fill_hblk;
11080 			}
11081 			/*
11082 			 * let's donate this hblk to our reserve list if
11083 			 * we are not mapping kernel range
11084 			 */
11085 			if (size == TTE8K && sfmmup != KHATID) {
11086 				if (sfmmu_put_free_hblk(hmeblkp, 0))
11087 					goto fill_hblk;
11088 			}
11089 		}
11090 	} else {
11091 		/*
11092 		 * We are here to map the slab in sfmmu8_cache; let's
11093 		 * check if we could tap our reserve list; if successful,
11094 		 * this will avoid the pain of going thru sfmmu_hblk_swap
11095 		 */
11096 		SFMMU_STAT(sf_hblk_slab_cnt);
11097 		if (!sfmmu_get_free_hblk(&hmeblkp, 0)) {
11098 			/*
11099 			 * let's start hblk_reserve dance
11100 			 */
11101 			SFMMU_STAT(sf_hblk_reserve_cnt);
11102 			owner = 1;
11103 			mutex_enter(&hblk_reserve_lock);
11104 			hmeblkp = HBLK_RESERVE;
11105 			hblk_reserve_thread = curthread;
11106 		}
11107 	}
11108 
11109 hblk_verify:
11110 	ASSERT(hmeblkp != NULL);
11111 	set_hblk_sz(hmeblkp, size);
11112 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
11113 	SFMMU_HASH_LOCK(hmebp);
11114 	HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11115 	if (newhblkp != NULL) {
11116 		SFMMU_HASH_UNLOCK(hmebp);
11117 		if (hmeblkp != HBLK_RESERVE) {
11118 			/*
11119 			 * This is really tricky!
11120 			 *
11121 			 * vmem_alloc(vmem_seg_arena)
11122 			 *  vmem_alloc(vmem_internal_arena)
11123 			 *   segkmem_alloc(heap_arena)
11124 			 *    vmem_alloc(heap_arena)
11125 			 *    page_create()
11126 			 *    hat_memload()
11127 			 *	kmem_cache_free()
11128 			 *	 kmem_cache_alloc()
11129 			 *	  kmem_slab_create()
11130 			 *	   vmem_alloc(kmem_internal_arena)
11131 			 *	    segkmem_alloc(heap_arena)
11132 			 *		vmem_alloc(heap_arena)
11133 			 *		page_create()
11134 			 *		hat_memload()
11135 			 *		  kmem_cache_free()
11136 			 *		...
11137 			 *
11138 			 * Thus, hat_memload() could call kmem_cache_free
11139 			 * for enough number of times that we could easily
11140 			 * hit the bottom of the stack or run out of reserve
11141 			 * list of vmem_seg structs.  So, we must donate
11142 			 * this hblk to reserve list if it's allocated
11143 			 * from sfmmu8_cache *and* mapping kernel range.
11144 			 * We don't need to worry about freeing hmeblk1's
11145 			 * to kmem since they don't map any kmem slabs.
11146 			 *
11147 			 * Note: When segkmem supports largepages, we must
11148 			 * free hmeblk1's to reserve list as well.
11149 			 */
11150 			forcefree = (sfmmup == KHATID) ? 1 : 0;
11151 			if (size == TTE8K &&
11152 			    sfmmu_put_free_hblk(hmeblkp, forcefree)) {
11153 				goto re_verify;
11154 			}
11155 			ASSERT(sfmmup != KHATID);
11156 			kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
11157 		} else {
11158 			/*
11159 			 * Hey! we don't need hblk_reserve any more.
11160 			 */
11161 			ASSERT(owner);
11162 			hblk_reserve_thread = NULL;
11163 			mutex_exit(&hblk_reserve_lock);
11164 			owner = 0;
11165 		}
11166 re_verify:
11167 		/*
11168 		 * let's check if the goodies are still present
11169 		 */
11170 		SFMMU_HASH_LOCK(hmebp);
11171 		HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
11172 		if (newhblkp != NULL) {
11173 			/*
11174 			 * return newhblkp if it's not hblk_reserve;
11175 			 * if newhblkp is hblk_reserve, return it
11176 			 * _only if_ we are the owner of hblk_reserve.
11177 			 */
11178 			if (newhblkp != HBLK_RESERVE || owner) {
11179 				ASSERT(!SFMMU_IS_SHMERID_VALID(rid) ||
11180 				    newhblkp->hblk_shared);
11181 				ASSERT(SFMMU_IS_SHMERID_VALID(rid) ||
11182 				    !newhblkp->hblk_shared);
11183 				return (newhblkp);
11184 			} else {
11185 				/*
11186 				 * we just hit hblk_reserve in the hash and
11187 				 * we are not the owner of that;
11188 				 *
11189 				 * block until hblk_reserve_thread completes
11190 				 * swapping hblk_reserve and try the dance
11191 				 * once again.
11192 				 */
11193 				SFMMU_HASH_UNLOCK(hmebp);
11194 				mutex_enter(&hblk_reserve_lock);
11195 				mutex_exit(&hblk_reserve_lock);
11196 				SFMMU_STAT(sf_hblk_reserve_hit);
11197 				goto fill_hblk;
11198 			}
11199 		} else {
11200 			/*
11201 			 * it's no more! try the dance once again.
11202 			 */
11203 			SFMMU_HASH_UNLOCK(hmebp);
11204 			goto fill_hblk;
11205 		}
11206 	}
11207 
11208 hblk_init:
11209 	if (SFMMU_IS_SHMERID_VALID(rid)) {
11210 		uint16_t tteflag = 0x1 <<
11211 		    ((size < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ : size);
11212 
11213 		if (!(rgnp->rgn_hmeflags & tteflag)) {
11214 			atomic_or_16(&rgnp->rgn_hmeflags, tteflag);
11215 		}
11216 		hmeblkp->hblk_shared = 1;
11217 	} else {
11218 		hmeblkp->hblk_shared = 0;
11219 	}
11220 	set_hblk_sz(hmeblkp, size);
11221 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11222 	hmeblkp->hblk_next = (struct hme_blk *)NULL;
11223 	hmeblkp->hblk_tag = hblktag;
11224 	hmeblkp->hblk_shadow = shw_hblkp;
11225 	hblkpa = hmeblkp->hblk_nextpa;
11226 	hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
11227 
11228 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
11229 	ASSERT(get_hblk_span(hmeblkp) == HMEBLK_SPAN(size));
11230 	ASSERT(hmeblkp->hblk_hmecnt == 0);
11231 	ASSERT(hmeblkp->hblk_vcnt == 0);
11232 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11233 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
11234 	sfmmu_hblk_hash_add(hmebp, hmeblkp, hblkpa);
11235 	return (hmeblkp);
11236 }
11237 
11238 /*
11239  * This function cleans up the hme_blk and returns it to the free list.
11240  */
11241 /* ARGSUSED */
11242 static void
11243 sfmmu_hblk_free(struct hme_blk **listp)
11244 {
11245 	struct hme_blk *hmeblkp, *next_hmeblkp;
11246 	int		size;
11247 	uint_t		critical;
11248 	uint64_t	hblkpa;
11249 
11250 	ASSERT(*listp != NULL);
11251 
11252 	hmeblkp = *listp;
11253 	while (hmeblkp != NULL) {
11254 		next_hmeblkp = hmeblkp->hblk_next;
11255 		ASSERT(!hmeblkp->hblk_hmecnt);
11256 		ASSERT(!hmeblkp->hblk_vcnt);
11257 		ASSERT(!hmeblkp->hblk_lckcnt);
11258 		ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
11259 		ASSERT(hmeblkp->hblk_shared == 0);
11260 		ASSERT(hmeblkp->hblk_shw_bit == 0);
11261 		ASSERT(hmeblkp->hblk_shadow == NULL);
11262 
11263 		hblkpa = va_to_pa((caddr_t)hmeblkp);
11264 		ASSERT(hblkpa != (uint64_t)-1);
11265 		critical = (hblktosfmmu(hmeblkp) == KHATID) ? 1 : 0;
11266 
11267 		size = get_hblk_ttesz(hmeblkp);
11268 		hmeblkp->hblk_next = NULL;
11269 		hmeblkp->hblk_nextpa = hblkpa;
11270 
11271 		if (hmeblkp->hblk_nuc_bit == 0) {
11272 
11273 			if (size != TTE8K ||
11274 			    !sfmmu_put_free_hblk(hmeblkp, critical))
11275 				kmem_cache_free(get_hblk_cache(hmeblkp),
11276 				    hmeblkp);
11277 		}
11278 		hmeblkp = next_hmeblkp;
11279 	}
11280 }
11281 
11282 #define	BUCKETS_TO_SEARCH_BEFORE_UNLOAD	30
11283 #define	SFMMU_HBLK_STEAL_THRESHOLD 5
11284 
11285 static uint_t sfmmu_hblk_steal_twice;
11286 static uint_t sfmmu_hblk_steal_count, sfmmu_hblk_steal_unload_count;
11287 
11288 /*
11289  * Steal a hmeblk from user or kernel hme hash lists.
11290  * For 8K tte grab one from reserve pool (freehblkp) before proceeding to
11291  * steal and if we fail to steal after SFMMU_HBLK_STEAL_THRESHOLD attempts
11292  * tap into critical reserve of freehblkp.
11293  * Note: We remain looping in this routine until we find one.
11294  */
11295 static struct hme_blk *
11296 sfmmu_hblk_steal(int size)
11297 {
11298 	static struct hmehash_bucket *uhmehash_steal_hand = NULL;
11299 	struct hmehash_bucket *hmebp;
11300 	struct hme_blk *hmeblkp = NULL, *pr_hblk;
11301 	uint64_t hblkpa;
11302 	int i;
11303 	uint_t loop_cnt = 0, critical;
11304 
11305 	for (;;) {
11306 		/* Check cpu hblk pending queues */
11307 		if ((hmeblkp = sfmmu_check_pending_hblks(size)) != NULL) {
11308 			hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
11309 			ASSERT(hmeblkp->hblk_hmecnt == 0);
11310 			ASSERT(hmeblkp->hblk_vcnt == 0);
11311 			return (hmeblkp);
11312 		}
11313 
11314 		if (size == TTE8K) {
11315 			critical =
11316 			    (++loop_cnt > SFMMU_HBLK_STEAL_THRESHOLD) ? 1 : 0;
11317 			if (sfmmu_get_free_hblk(&hmeblkp, critical))
11318 				return (hmeblkp);
11319 		}
11320 
11321 		hmebp = (uhmehash_steal_hand == NULL) ? uhme_hash :
11322 		    uhmehash_steal_hand;
11323 		ASSERT(hmebp >= uhme_hash && hmebp <= &uhme_hash[UHMEHASH_SZ]);
11324 
11325 		for (i = 0; hmeblkp == NULL && i <= UHMEHASH_SZ +
11326 		    BUCKETS_TO_SEARCH_BEFORE_UNLOAD; i++) {
11327 			SFMMU_HASH_LOCK(hmebp);
11328 			hmeblkp = hmebp->hmeblkp;
11329 			hblkpa = hmebp->hmeh_nextpa;
11330 			pr_hblk = NULL;
11331 			while (hmeblkp) {
11332 				/*
11333 				 * check if it is a hmeblk that is not locked
11334 				 * and not shared. skip shadow hmeblks with
11335 				 * shadow_mask set i.e valid count non zero.
11336 				 */
11337 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11338 				    (hmeblkp->hblk_shw_bit == 0 ||
11339 				    hmeblkp->hblk_vcnt == 0) &&
11340 				    (hmeblkp->hblk_lckcnt == 0)) {
11341 					/*
11342 					 * there is a high probability that we
11343 					 * will find a free one. search some
11344 					 * buckets for a free hmeblk initially
11345 					 * before unloading a valid hmeblk.
11346 					 */
11347 					if ((hmeblkp->hblk_vcnt == 0 &&
11348 					    hmeblkp->hblk_hmecnt == 0) || (i >=
11349 					    BUCKETS_TO_SEARCH_BEFORE_UNLOAD)) {
11350 						if (sfmmu_steal_this_hblk(hmebp,
11351 						    hmeblkp, hblkpa, pr_hblk)) {
11352 							/*
11353 							 * Hblk is unloaded
11354 							 * successfully
11355 							 */
11356 							break;
11357 						}
11358 					}
11359 				}
11360 				pr_hblk = hmeblkp;
11361 				hblkpa = hmeblkp->hblk_nextpa;
11362 				hmeblkp = hmeblkp->hblk_next;
11363 			}
11364 
11365 			SFMMU_HASH_UNLOCK(hmebp);
11366 			if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
11367 				hmebp = uhme_hash;
11368 		}
11369 		uhmehash_steal_hand = hmebp;
11370 
11371 		if (hmeblkp != NULL)
11372 			break;
11373 
11374 		/*
11375 		 * in the worst case, look for a free one in the kernel
11376 		 * hash table.
11377 		 */
11378 		for (i = 0, hmebp = khme_hash; i <= KHMEHASH_SZ; i++) {
11379 			SFMMU_HASH_LOCK(hmebp);
11380 			hmeblkp = hmebp->hmeblkp;
11381 			hblkpa = hmebp->hmeh_nextpa;
11382 			pr_hblk = NULL;
11383 			while (hmeblkp) {
11384 				/*
11385 				 * check if it is free hmeblk
11386 				 */
11387 				if ((get_hblk_ttesz(hmeblkp) == size) &&
11388 				    (hmeblkp->hblk_lckcnt == 0) &&
11389 				    (hmeblkp->hblk_vcnt == 0) &&
11390 				    (hmeblkp->hblk_hmecnt == 0)) {
11391 					if (sfmmu_steal_this_hblk(hmebp,
11392 					    hmeblkp, hblkpa, pr_hblk)) {
11393 						break;
11394 					} else {
11395 						/*
11396 						 * Cannot fail since we have
11397 						 * hash lock.
11398 						 */
11399 						panic("fail to steal?");
11400 					}
11401 				}
11402 
11403 				pr_hblk = hmeblkp;
11404 				hblkpa = hmeblkp->hblk_nextpa;
11405 				hmeblkp = hmeblkp->hblk_next;
11406 			}
11407 
11408 			SFMMU_HASH_UNLOCK(hmebp);
11409 			if (hmebp++ == &khme_hash[KHMEHASH_SZ])
11410 				hmebp = khme_hash;
11411 		}
11412 
11413 		if (hmeblkp != NULL)
11414 			break;
11415 		sfmmu_hblk_steal_twice++;
11416 	}
11417 	return (hmeblkp);
11418 }
11419 
11420 /*
11421  * This routine does real work to prepare a hblk to be "stolen" by
11422  * unloading the mappings, updating shadow counts ....
11423  * It returns 1 if the block is ready to be reused (stolen), or 0
11424  * means the block cannot be stolen yet- pageunload is still working
11425  * on this hblk.
11426  */
11427 static int
11428 sfmmu_steal_this_hblk(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
11429     uint64_t hblkpa, struct hme_blk *pr_hblk)
11430 {
11431 	int shw_size, vshift;
11432 	struct hme_blk *shw_hblkp;
11433 	caddr_t vaddr;
11434 	uint_t shw_mask, newshw_mask;
11435 	struct hme_blk *list = NULL;
11436 
11437 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
11438 
11439 	/*
11440 	 * check if the hmeblk is free, unload if necessary
11441 	 */
11442 	if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11443 		sfmmu_t *sfmmup;
11444 		demap_range_t dmr;
11445 
11446 		sfmmup = hblktosfmmu(hmeblkp);
11447 		if (hmeblkp->hblk_shared || sfmmup->sfmmu_ismhat) {
11448 			return (0);
11449 		}
11450 		DEMAP_RANGE_INIT(sfmmup, &dmr);
11451 		(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
11452 		    (caddr_t)get_hblk_base(hmeblkp),
11453 		    get_hblk_endaddr(hmeblkp), &dmr, HAT_UNLOAD);
11454 		DEMAP_RANGE_FLUSH(&dmr);
11455 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
11456 			/*
11457 			 * Pageunload is working on the same hblk.
11458 			 */
11459 			return (0);
11460 		}
11461 
11462 		sfmmu_hblk_steal_unload_count++;
11463 	}
11464 
11465 	ASSERT(hmeblkp->hblk_lckcnt == 0);
11466 	ASSERT(hmeblkp->hblk_vcnt == 0 && hmeblkp->hblk_hmecnt == 0);
11467 
11468 	sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk, &list, 1);
11469 	hmeblkp->hblk_nextpa = hblkpa;
11470 
11471 	shw_hblkp = hmeblkp->hblk_shadow;
11472 	if (shw_hblkp) {
11473 		ASSERT(!hmeblkp->hblk_shared);
11474 		shw_size = get_hblk_ttesz(shw_hblkp);
11475 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
11476 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
11477 		ASSERT(vshift < 8);
11478 		/*
11479 		 * Atomically clear shadow mask bit
11480 		 */
11481 		do {
11482 			shw_mask = shw_hblkp->hblk_shw_mask;
11483 			ASSERT(shw_mask & (1 << vshift));
11484 			newshw_mask = shw_mask & ~(1 << vshift);
11485 			newshw_mask = atomic_cas_32(&shw_hblkp->hblk_shw_mask,
11486 			    shw_mask, newshw_mask);
11487 		} while (newshw_mask != shw_mask);
11488 		hmeblkp->hblk_shadow = NULL;
11489 	}
11490 
11491 	/*
11492 	 * remove shadow bit if we are stealing an unused shadow hmeblk.
11493 	 * sfmmu_hblk_alloc needs it that way, will set shadow bit later if
11494 	 * we are indeed allocating a shadow hmeblk.
11495 	 */
11496 	hmeblkp->hblk_shw_bit = 0;
11497 
11498 	if (hmeblkp->hblk_shared) {
11499 		sf_srd_t	*srdp;
11500 		sf_region_t	*rgnp;
11501 		uint_t		rid;
11502 
11503 		srdp = hblktosrd(hmeblkp);
11504 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
11505 		rid = hmeblkp->hblk_tag.htag_rid;
11506 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11507 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11508 		rgnp = srdp->srd_hmergnp[rid];
11509 		ASSERT(rgnp != NULL);
11510 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
11511 		hmeblkp->hblk_shared = 0;
11512 	}
11513 
11514 	sfmmu_hblk_steal_count++;
11515 	SFMMU_STAT(sf_steal_count);
11516 
11517 	return (1);
11518 }
11519 
11520 struct hme_blk *
11521 sfmmu_hmetohblk(struct sf_hment *sfhme)
11522 {
11523 	struct hme_blk *hmeblkp;
11524 	struct sf_hment *sfhme0;
11525 	struct hme_blk *hblk_dummy = 0;
11526 
11527 	/*
11528 	 * No dummy sf_hments, please.
11529 	 */
11530 	ASSERT(sfhme->hme_tte.ll != 0);
11531 
11532 	sfhme0 = sfhme - sfhme->hme_tte.tte_hmenum;
11533 	hmeblkp = (struct hme_blk *)((uintptr_t)sfhme0 -
11534 	    (uintptr_t)&hblk_dummy->hblk_hme[0]);
11535 
11536 	return (hmeblkp);
11537 }
11538 
11539 /*
11540  * On swapin, get appropriately sized TSB(s) and clear the HAT_SWAPPED flag.
11541  * If we can't get appropriately sized TSB(s), try for 8K TSB(s) using
11542  * KM_SLEEP allocation.
11543  *
11544  * Return 0 on success, -1 otherwise.
11545  */
11546 static void
11547 sfmmu_tsb_swapin(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11548 {
11549 	struct tsb_info *tsbinfop, *next;
11550 	tsb_replace_rc_t rc;
11551 	boolean_t gotfirst = B_FALSE;
11552 
11553 	ASSERT(sfmmup != ksfmmup);
11554 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11555 
11556 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPIN)) {
11557 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
11558 	}
11559 
11560 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11561 		SFMMU_FLAGS_SET(sfmmup, HAT_SWAPIN);
11562 	} else {
11563 		return;
11564 	}
11565 
11566 	ASSERT(sfmmup->sfmmu_tsb != NULL);
11567 
11568 	/*
11569 	 * Loop over all tsbinfo's replacing them with ones that actually have
11570 	 * a TSB.  If any of the replacements ever fail, bail out of the loop.
11571 	 */
11572 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL; tsbinfop = next) {
11573 		ASSERT(tsbinfop->tsb_flags & TSB_SWAPPED);
11574 		next = tsbinfop->tsb_next;
11575 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, tsbinfop->tsb_szc,
11576 		    hatlockp, TSB_SWAPIN);
11577 		if (rc != TSB_SUCCESS) {
11578 			break;
11579 		}
11580 		gotfirst = B_TRUE;
11581 	}
11582 
11583 	switch (rc) {
11584 	case TSB_SUCCESS:
11585 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11586 		cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11587 		return;
11588 	case TSB_LOSTRACE:
11589 		break;
11590 	case TSB_ALLOCFAIL:
11591 		break;
11592 	default:
11593 		panic("sfmmu_replace_tsb returned unrecognized failure code "
11594 		    "%d", rc);
11595 	}
11596 
11597 	/*
11598 	 * In this case, we failed to get one of our TSBs.  If we failed to
11599 	 * get the first TSB, get one of minimum size (8KB).  Walk the list
11600 	 * and throw away the tsbinfos, starting where the allocation failed;
11601 	 * we can get by with just one TSB as long as we don't leave the
11602 	 * SWAPPED tsbinfo structures lying around.
11603 	 */
11604 	tsbinfop = sfmmup->sfmmu_tsb;
11605 	next = tsbinfop->tsb_next;
11606 	tsbinfop->tsb_next = NULL;
11607 
11608 	sfmmu_hat_exit(hatlockp);
11609 	for (tsbinfop = next; tsbinfop != NULL; tsbinfop = next) {
11610 		next = tsbinfop->tsb_next;
11611 		sfmmu_tsbinfo_free(tsbinfop);
11612 	}
11613 	hatlockp = sfmmu_hat_enter(sfmmup);
11614 
11615 	/*
11616 	 * If we don't have any TSBs, get a single 8K TSB for 8K, 64K and 512K
11617 	 * pages.
11618 	 */
11619 	if (!gotfirst) {
11620 		tsbinfop = sfmmup->sfmmu_tsb;
11621 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, TSB_MIN_SZCODE,
11622 		    hatlockp, TSB_SWAPIN | TSB_FORCEALLOC);
11623 		ASSERT(rc == TSB_SUCCESS);
11624 	}
11625 
11626 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
11627 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11628 }
11629 
11630 static int
11631 sfmmu_is_rgnva(sf_srd_t *srdp, caddr_t addr, ulong_t w, ulong_t bmw)
11632 {
11633 	ulong_t bix = 0;
11634 	uint_t rid;
11635 	sf_region_t *rgnp;
11636 
11637 	ASSERT(srdp != NULL);
11638 	ASSERT(srdp->srd_refcnt != 0);
11639 
11640 	w <<= BT_ULSHIFT;
11641 	while (bmw) {
11642 		if (!(bmw & 0x1)) {
11643 			bix++;
11644 			bmw >>= 1;
11645 			continue;
11646 		}
11647 		rid = w | bix;
11648 		rgnp = srdp->srd_hmergnp[rid];
11649 		ASSERT(rgnp->rgn_refcnt > 0);
11650 		ASSERT(rgnp->rgn_id == rid);
11651 		if (addr < rgnp->rgn_saddr ||
11652 		    addr >= (rgnp->rgn_saddr + rgnp->rgn_size)) {
11653 			bix++;
11654 			bmw >>= 1;
11655 		} else {
11656 			return (1);
11657 		}
11658 	}
11659 	return (0);
11660 }
11661 
11662 /*
11663  * Handle exceptions for low level tsb_handler.
11664  *
11665  * There are many scenarios that could land us here:
11666  *
11667  * If the context is invalid we land here. The context can be invalid
11668  * for 3 reasons: 1) we couldn't allocate a new context and now need to
11669  * perform a wrap around operation in order to allocate a new context.
11670  * 2) Context was invalidated to change pagesize programming 3) ISMs or
11671  * TSBs configuration is changeing for this process and we are forced into
11672  * here to do a syncronization operation. If the context is valid we can
11673  * be here from window trap hanlder. In this case just call trap to handle
11674  * the fault.
11675  *
11676  * Note that the process will run in INVALID_CONTEXT before
11677  * faulting into here and subsequently loading the MMU registers
11678  * (including the TSB base register) associated with this process.
11679  * For this reason, the trap handlers must all test for
11680  * INVALID_CONTEXT before attempting to access any registers other
11681  * than the context registers.
11682  */
11683 void
11684 sfmmu_tsbmiss_exception(struct regs *rp, uintptr_t tagaccess, uint_t traptype)
11685 {
11686 	sfmmu_t *sfmmup, *shsfmmup;
11687 	uint_t ctxtype;
11688 	klwp_id_t lwp;
11689 	char lwp_save_state;
11690 	hatlock_t *hatlockp, *shatlockp;
11691 	struct tsb_info *tsbinfop;
11692 	struct tsbmiss *tsbmp;
11693 	sf_scd_t *scdp;
11694 
11695 	SFMMU_STAT(sf_tsb_exceptions);
11696 	SFMMU_MMU_STAT(mmu_tsb_exceptions);
11697 	sfmmup = astosfmmu(curthread->t_procp->p_as);
11698 	/*
11699 	 * note that in sun4u, tagacces register contains ctxnum
11700 	 * while sun4v passes ctxtype in the tagaccess register.
11701 	 */
11702 	ctxtype = tagaccess & TAGACC_CTX_MASK;
11703 
11704 	ASSERT(sfmmup != ksfmmup && ctxtype != KCONTEXT);
11705 	ASSERT(sfmmup->sfmmu_ismhat == 0);
11706 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED) ||
11707 	    ctxtype == INVALID_CONTEXT);
11708 
11709 	if (ctxtype != INVALID_CONTEXT && traptype != T_DATA_PROT) {
11710 		/*
11711 		 * We may land here because shme bitmap and pagesize
11712 		 * flags are updated lazily in tsbmiss area on other cpus.
11713 		 * If we detect here that tsbmiss area is out of sync with
11714 		 * sfmmu update it and retry the trapped instruction.
11715 		 * Otherwise call trap().
11716 		 */
11717 		int ret = 0;
11718 		uchar_t tteflag_mask = (1 << TTE64K) | (1 << TTE8K);
11719 		caddr_t addr = (caddr_t)(tagaccess & TAGACC_VADDR_MASK);
11720 
11721 		/*
11722 		 * Must set lwp state to LWP_SYS before
11723 		 * trying to acquire any adaptive lock
11724 		 */
11725 		lwp = ttolwp(curthread);
11726 		ASSERT(lwp);
11727 		lwp_save_state = lwp->lwp_state;
11728 		lwp->lwp_state = LWP_SYS;
11729 
11730 		hatlockp = sfmmu_hat_enter(sfmmup);
11731 		kpreempt_disable();
11732 		tsbmp = &tsbmiss_area[CPU->cpu_id];
11733 		ASSERT(sfmmup == tsbmp->usfmmup);
11734 		if (((tsbmp->uhat_tteflags ^ sfmmup->sfmmu_tteflags) &
11735 		    ~tteflag_mask) ||
11736 		    ((tsbmp->uhat_rtteflags ^  sfmmup->sfmmu_rtteflags) &
11737 		    ~tteflag_mask)) {
11738 			tsbmp->uhat_tteflags = sfmmup->sfmmu_tteflags;
11739 			tsbmp->uhat_rtteflags = sfmmup->sfmmu_rtteflags;
11740 			ret = 1;
11741 		}
11742 		if (sfmmup->sfmmu_srdp != NULL) {
11743 			ulong_t *sm = sfmmup->sfmmu_hmeregion_map.bitmap;
11744 			ulong_t *tm = tsbmp->shmermap;
11745 			ulong_t i;
11746 			for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
11747 				ulong_t d = tm[i] ^ sm[i];
11748 				if (d) {
11749 					if (d & sm[i]) {
11750 						if (!ret && sfmmu_is_rgnva(
11751 						    sfmmup->sfmmu_srdp,
11752 						    addr, i, d & sm[i])) {
11753 							ret = 1;
11754 						}
11755 					}
11756 					tm[i] = sm[i];
11757 				}
11758 			}
11759 		}
11760 		kpreempt_enable();
11761 		sfmmu_hat_exit(hatlockp);
11762 		lwp->lwp_state = lwp_save_state;
11763 		if (ret) {
11764 			return;
11765 		}
11766 	} else if (ctxtype == INVALID_CONTEXT) {
11767 		/*
11768 		 * First, make sure we come out of here with a valid ctx,
11769 		 * since if we don't get one we'll simply loop on the
11770 		 * faulting instruction.
11771 		 *
11772 		 * If the ISM mappings are changing, the TSB is relocated,
11773 		 * the process is swapped, the process is joining SCD or
11774 		 * leaving SCD or shared regions we serialize behind the
11775 		 * controlling thread with hat lock, sfmmu_flags and
11776 		 * sfmmu_tsb_cv condition variable.
11777 		 */
11778 
11779 		/*
11780 		 * Must set lwp state to LWP_SYS before
11781 		 * trying to acquire any adaptive lock
11782 		 */
11783 		lwp = ttolwp(curthread);
11784 		ASSERT(lwp);
11785 		lwp_save_state = lwp->lwp_state;
11786 		lwp->lwp_state = LWP_SYS;
11787 
11788 		hatlockp = sfmmu_hat_enter(sfmmup);
11789 retry:
11790 		if ((scdp = sfmmup->sfmmu_scdp) != NULL) {
11791 			shsfmmup = scdp->scd_sfmmup;
11792 			ASSERT(shsfmmup != NULL);
11793 
11794 			for (tsbinfop = shsfmmup->sfmmu_tsb; tsbinfop != NULL;
11795 			    tsbinfop = tsbinfop->tsb_next) {
11796 				if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11797 					/* drop the private hat lock */
11798 					sfmmu_hat_exit(hatlockp);
11799 					/* acquire the shared hat lock */
11800 					shatlockp = sfmmu_hat_enter(shsfmmup);
11801 					/*
11802 					 * recheck to see if anything changed
11803 					 * after we drop the private hat lock.
11804 					 */
11805 					if (sfmmup->sfmmu_scdp == scdp &&
11806 					    shsfmmup == scdp->scd_sfmmup) {
11807 						sfmmu_tsb_chk_reloc(shsfmmup,
11808 						    shatlockp);
11809 					}
11810 					sfmmu_hat_exit(shatlockp);
11811 					hatlockp = sfmmu_hat_enter(sfmmup);
11812 					goto retry;
11813 				}
11814 			}
11815 		}
11816 
11817 		for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
11818 		    tsbinfop = tsbinfop->tsb_next) {
11819 			if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
11820 				cv_wait(&sfmmup->sfmmu_tsb_cv,
11821 				    HATLOCK_MUTEXP(hatlockp));
11822 				goto retry;
11823 			}
11824 		}
11825 
11826 		/*
11827 		 * Wait for ISM maps to be updated.
11828 		 */
11829 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
11830 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11831 			    HATLOCK_MUTEXP(hatlockp));
11832 			goto retry;
11833 		}
11834 
11835 		/* Is this process joining an SCD? */
11836 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
11837 			/*
11838 			 * Flush private TSB and setup shared TSB.
11839 			 * sfmmu_finish_join_scd() does not drop the
11840 			 * hat lock.
11841 			 */
11842 			sfmmu_finish_join_scd(sfmmup);
11843 			SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
11844 		}
11845 
11846 		/*
11847 		 * If we're swapping in, get TSB(s).  Note that we must do
11848 		 * this before we get a ctx or load the MMU state.  Once
11849 		 * we swap in we have to recheck to make sure the TSB(s) and
11850 		 * ISM mappings didn't change while we slept.
11851 		 */
11852 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
11853 			sfmmu_tsb_swapin(sfmmup, hatlockp);
11854 			goto retry;
11855 		}
11856 
11857 		sfmmu_get_ctx(sfmmup);
11858 
11859 		sfmmu_hat_exit(hatlockp);
11860 		/*
11861 		 * Must restore lwp_state if not calling
11862 		 * trap() for further processing. Restore
11863 		 * it anyway.
11864 		 */
11865 		lwp->lwp_state = lwp_save_state;
11866 		return;
11867 	}
11868 	trap(rp, (caddr_t)tagaccess, traptype, 0);
11869 }
11870 
11871 static void
11872 sfmmu_tsb_chk_reloc(sfmmu_t *sfmmup, hatlock_t *hatlockp)
11873 {
11874 	struct tsb_info *tp;
11875 
11876 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11877 
11878 	for (tp = sfmmup->sfmmu_tsb; tp != NULL; tp = tp->tsb_next) {
11879 		if (tp->tsb_flags & TSB_RELOC_FLAG) {
11880 			cv_wait(&sfmmup->sfmmu_tsb_cv,
11881 			    HATLOCK_MUTEXP(hatlockp));
11882 			break;
11883 		}
11884 	}
11885 }
11886 
11887 /*
11888  * sfmmu_vatopfn_suspended is called from GET_TTE when TL=0 and
11889  * TTE_SUSPENDED bit set in tte we block on aquiring a page lock
11890  * rather than spinning to avoid send mondo timeouts with
11891  * interrupts enabled. When the lock is acquired it is immediately
11892  * released and we return back to sfmmu_vatopfn just after
11893  * the GET_TTE call.
11894  */
11895 void
11896 sfmmu_vatopfn_suspended(caddr_t vaddr, sfmmu_t *sfmmu, tte_t *ttep)
11897 {
11898 	struct page	**pp;
11899 
11900 	(void) as_pagelock(sfmmu->sfmmu_as, &pp, vaddr, TTE_CSZ(ttep), S_WRITE);
11901 	as_pageunlock(sfmmu->sfmmu_as, pp, vaddr, TTE_CSZ(ttep), S_WRITE);
11902 }
11903 
11904 /*
11905  * sfmmu_tsbmiss_suspended is called from GET_TTE when TL>0 and
11906  * TTE_SUSPENDED bit set in tte. We do this so that we can handle
11907  * cross traps which cannot be handled while spinning in the
11908  * trap handlers. Simply enter and exit the kpr_suspendlock spin
11909  * mutex, which is held by the holder of the suspend bit, and then
11910  * retry the trapped instruction after unwinding.
11911  */
11912 /*ARGSUSED*/
11913 void
11914 sfmmu_tsbmiss_suspended(struct regs *rp, uintptr_t tagacc, uint_t traptype)
11915 {
11916 	ASSERT(curthread != kreloc_thread);
11917 	mutex_enter(&kpr_suspendlock);
11918 	mutex_exit(&kpr_suspendlock);
11919 }
11920 
11921 /*
11922  * This routine could be optimized to reduce the number of xcalls by flushing
11923  * the entire TLBs if region reference count is above some threshold but the
11924  * tradeoff will depend on the size of the TLB. So for now flush the specific
11925  * page a context at a time.
11926  *
11927  * If uselocks is 0 then it's called after all cpus were captured and all the
11928  * hat locks were taken. In this case don't take the region lock by relying on
11929  * the order of list region update operations in hat_join_region(),
11930  * hat_leave_region() and hat_dup_region(). The ordering in those routines
11931  * guarantees that list is always forward walkable and reaches active sfmmus
11932  * regardless of where xc_attention() captures a cpu.
11933  */
11934 cpuset_t
11935 sfmmu_rgntlb_demap(caddr_t addr, sf_region_t *rgnp,
11936     struct hme_blk *hmeblkp, int uselocks)
11937 {
11938 	sfmmu_t	*sfmmup;
11939 	cpuset_t cpuset;
11940 	cpuset_t rcpuset;
11941 	hatlock_t *hatlockp;
11942 	uint_t rid = rgnp->rgn_id;
11943 	sf_rgn_link_t *rlink;
11944 	sf_scd_t *scdp;
11945 
11946 	ASSERT(hmeblkp->hblk_shared);
11947 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
11948 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
11949 
11950 	CPUSET_ZERO(rcpuset);
11951 	if (uselocks) {
11952 		mutex_enter(&rgnp->rgn_mutex);
11953 	}
11954 	sfmmup = rgnp->rgn_sfmmu_head;
11955 	while (sfmmup != NULL) {
11956 		if (uselocks) {
11957 			hatlockp = sfmmu_hat_enter(sfmmup);
11958 		}
11959 
11960 		/*
11961 		 * When an SCD is created the SCD hat is linked on the sfmmu
11962 		 * region lists for each hme region which is part of the
11963 		 * SCD. If we find an SCD hat, when walking these lists,
11964 		 * then we flush the shared TSBs, if we find a private hat,
11965 		 * which is part of an SCD, but where the region
11966 		 * is not part of the SCD then we flush the private TSBs.
11967 		 */
11968 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
11969 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
11970 			scdp = sfmmup->sfmmu_scdp;
11971 			if (SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
11972 				if (uselocks) {
11973 					sfmmu_hat_exit(hatlockp);
11974 				}
11975 				goto next;
11976 			}
11977 		}
11978 
11979 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
11980 
11981 		kpreempt_disable();
11982 		cpuset = sfmmup->sfmmu_cpusran;
11983 		CPUSET_AND(cpuset, cpu_ready_set);
11984 		CPUSET_DEL(cpuset, CPU->cpu_id);
11985 		SFMMU_XCALL_STATS(sfmmup);
11986 		xt_some(cpuset, vtag_flushpage_tl1,
11987 		    (uint64_t)addr, (uint64_t)sfmmup);
11988 		vtag_flushpage(addr, (uint64_t)sfmmup);
11989 		if (uselocks) {
11990 			sfmmu_hat_exit(hatlockp);
11991 		}
11992 		kpreempt_enable();
11993 		CPUSET_OR(rcpuset, cpuset);
11994 
11995 next:
11996 		/* LINTED: constant in conditional context */
11997 		SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
11998 		ASSERT(rlink != NULL);
11999 		sfmmup = rlink->next;
12000 	}
12001 	if (uselocks) {
12002 		mutex_exit(&rgnp->rgn_mutex);
12003 	}
12004 	return (rcpuset);
12005 }
12006 
12007 /*
12008  * This routine takes an sfmmu pointer and the va for an adddress in an
12009  * ISM region as input and returns the corresponding region id in ism_rid.
12010  * The return value of 1 indicates that a region has been found and ism_rid
12011  * is valid, otherwise 0 is returned.
12012  */
12013 static int
12014 find_ism_rid(sfmmu_t *sfmmup, sfmmu_t *ism_sfmmup, caddr_t va, uint_t *ism_rid)
12015 {
12016 	ism_blk_t	*ism_blkp;
12017 	int		i;
12018 	ism_map_t	*ism_map;
12019 #ifdef DEBUG
12020 	struct hat	*ism_hatid;
12021 #endif
12022 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12023 
12024 	ism_blkp = sfmmup->sfmmu_iblk;
12025 	while (ism_blkp != NULL) {
12026 		ism_map = ism_blkp->iblk_maps;
12027 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
12028 			if ((va >= ism_start(ism_map[i])) &&
12029 			    (va < ism_end(ism_map[i]))) {
12030 
12031 				*ism_rid = ism_map[i].imap_rid;
12032 #ifdef DEBUG
12033 				ism_hatid = ism_map[i].imap_ismhat;
12034 				ASSERT(ism_hatid == ism_sfmmup);
12035 				ASSERT(ism_hatid->sfmmu_ismhat);
12036 #endif
12037 				return (1);
12038 			}
12039 		}
12040 		ism_blkp = ism_blkp->iblk_next;
12041 	}
12042 	return (0);
12043 }
12044 
12045 /*
12046  * Special routine to flush out ism mappings- TSBs, TLBs and D-caches.
12047  * This routine may be called with all cpu's captured. Therefore, the
12048  * caller is responsible for holding all locks and disabling kernel
12049  * preemption.
12050  */
12051 /* ARGSUSED */
12052 static void
12053 sfmmu_ismtlbcache_demap(caddr_t addr, sfmmu_t *ism_sfmmup,
12054     struct hme_blk *hmeblkp, pfn_t pfnum, int cache_flush_flag)
12055 {
12056 	cpuset_t	cpuset;
12057 	caddr_t		va;
12058 	ism_ment_t	*ment;
12059 	sfmmu_t		*sfmmup;
12060 #ifdef VAC
12061 	int		vcolor;
12062 #endif
12063 
12064 	sf_scd_t	*scdp;
12065 	uint_t		ism_rid;
12066 
12067 	ASSERT(!hmeblkp->hblk_shared);
12068 	/*
12069 	 * Walk the ism_hat's mapping list and flush the page
12070 	 * from every hat sharing this ism_hat. This routine
12071 	 * may be called while all cpu's have been captured.
12072 	 * Therefore we can't attempt to grab any locks. For now
12073 	 * this means we will protect the ism mapping list under
12074 	 * a single lock which will be grabbed by the caller.
12075 	 * If hat_share/unshare scalibility becomes a performance
12076 	 * problem then we may need to re-think ism mapping list locking.
12077 	 */
12078 	ASSERT(ism_sfmmup->sfmmu_ismhat);
12079 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
12080 	addr = addr - ISMID_STARTADDR;
12081 
12082 	for (ment = ism_sfmmup->sfmmu_iment; ment; ment = ment->iment_next) {
12083 
12084 		sfmmup = ment->iment_hat;
12085 
12086 		va = ment->iment_base_va;
12087 		va = (caddr_t)((uintptr_t)va  + (uintptr_t)addr);
12088 
12089 		/*
12090 		 * When an SCD is created the SCD hat is linked on the ism
12091 		 * mapping lists for each ISM segment which is part of the
12092 		 * SCD. If we find an SCD hat, when walking these lists,
12093 		 * then we flush the shared TSBs, if we find a private hat,
12094 		 * which is part of an SCD, but where the region
12095 		 * corresponding to this va is not part of the SCD then we
12096 		 * flush the private TSBs.
12097 		 */
12098 		if (!sfmmup->sfmmu_scdhat && sfmmup->sfmmu_scdp != NULL &&
12099 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD) &&
12100 		    !SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
12101 			if (!find_ism_rid(sfmmup, ism_sfmmup, va,
12102 			    &ism_rid)) {
12103 				cmn_err(CE_PANIC,
12104 				    "can't find matching ISM rid!");
12105 			}
12106 
12107 			scdp = sfmmup->sfmmu_scdp;
12108 			if (SFMMU_IS_ISMRID_VALID(ism_rid) &&
12109 			    SF_RGNMAP_TEST(scdp->scd_ismregion_map,
12110 			    ism_rid)) {
12111 				continue;
12112 			}
12113 		}
12114 		SFMMU_UNLOAD_TSB(va, sfmmup, hmeblkp, 1);
12115 
12116 		cpuset = sfmmup->sfmmu_cpusran;
12117 		CPUSET_AND(cpuset, cpu_ready_set);
12118 		CPUSET_DEL(cpuset, CPU->cpu_id);
12119 		SFMMU_XCALL_STATS(sfmmup);
12120 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)va,
12121 		    (uint64_t)sfmmup);
12122 		vtag_flushpage(va, (uint64_t)sfmmup);
12123 
12124 #ifdef VAC
12125 		/*
12126 		 * Flush D$
12127 		 * When flushing D$ we must flush all
12128 		 * cpu's. See sfmmu_cache_flush().
12129 		 */
12130 		if (cache_flush_flag == CACHE_FLUSH) {
12131 			cpuset = cpu_ready_set;
12132 			CPUSET_DEL(cpuset, CPU->cpu_id);
12133 
12134 			SFMMU_XCALL_STATS(sfmmup);
12135 			vcolor = addr_to_vcolor(va);
12136 			xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12137 			vac_flushpage(pfnum, vcolor);
12138 		}
12139 #endif	/* VAC */
12140 	}
12141 }
12142 
12143 /*
12144  * Demaps the TSB, CPU caches, and flushes all TLBs on all CPUs of
12145  * a particular virtual address and ctx.  If noflush is set we do not
12146  * flush the TLB/TSB.  This function may or may not be called with the
12147  * HAT lock held.
12148  */
12149 static void
12150 sfmmu_tlbcache_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12151     pfn_t pfnum, int tlb_noflush, int cpu_flag, int cache_flush_flag,
12152     int hat_lock_held)
12153 {
12154 #ifdef VAC
12155 	int vcolor;
12156 #endif
12157 	cpuset_t cpuset;
12158 	hatlock_t *hatlockp;
12159 
12160 	ASSERT(!hmeblkp->hblk_shared);
12161 
12162 #if defined(lint) && !defined(VAC)
12163 	pfnum = pfnum;
12164 	cpu_flag = cpu_flag;
12165 	cache_flush_flag = cache_flush_flag;
12166 #endif
12167 
12168 	/*
12169 	 * There is no longer a need to protect against ctx being
12170 	 * stolen here since we don't store the ctx in the TSB anymore.
12171 	 */
12172 #ifdef VAC
12173 	vcolor = addr_to_vcolor(addr);
12174 #endif
12175 
12176 	/*
12177 	 * We must hold the hat lock during the flush of TLB,
12178 	 * to avoid a race with sfmmu_invalidate_ctx(), where
12179 	 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12180 	 * causing TLB demap routine to skip flush on that MMU.
12181 	 * If the context on a MMU has already been set to
12182 	 * INVALID_CONTEXT, we just get an extra flush on
12183 	 * that MMU.
12184 	 */
12185 	if (!hat_lock_held && !tlb_noflush)
12186 		hatlockp = sfmmu_hat_enter(sfmmup);
12187 
12188 	kpreempt_disable();
12189 	if (!tlb_noflush) {
12190 		/*
12191 		 * Flush the TSB and TLB.
12192 		 */
12193 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12194 
12195 		cpuset = sfmmup->sfmmu_cpusran;
12196 		CPUSET_AND(cpuset, cpu_ready_set);
12197 		CPUSET_DEL(cpuset, CPU->cpu_id);
12198 
12199 		SFMMU_XCALL_STATS(sfmmup);
12200 
12201 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
12202 		    (uint64_t)sfmmup);
12203 
12204 		vtag_flushpage(addr, (uint64_t)sfmmup);
12205 	}
12206 
12207 	if (!hat_lock_held && !tlb_noflush)
12208 		sfmmu_hat_exit(hatlockp);
12209 
12210 #ifdef VAC
12211 	/*
12212 	 * Flush the D$
12213 	 *
12214 	 * Even if the ctx is stolen, we need to flush the
12215 	 * cache. Our ctx stealer only flushes the TLBs.
12216 	 */
12217 	if (cache_flush_flag == CACHE_FLUSH) {
12218 		if (cpu_flag & FLUSH_ALL_CPUS) {
12219 			cpuset = cpu_ready_set;
12220 		} else {
12221 			cpuset = sfmmup->sfmmu_cpusran;
12222 			CPUSET_AND(cpuset, cpu_ready_set);
12223 		}
12224 		CPUSET_DEL(cpuset, CPU->cpu_id);
12225 		SFMMU_XCALL_STATS(sfmmup);
12226 		xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12227 		vac_flushpage(pfnum, vcolor);
12228 	}
12229 #endif	/* VAC */
12230 	kpreempt_enable();
12231 }
12232 
12233 /*
12234  * Demaps the TSB and flushes all TLBs on all cpus for a particular virtual
12235  * address and ctx.  If noflush is set we do not currently do anything.
12236  * This function may or may not be called with the HAT lock held.
12237  */
12238 static void
12239 sfmmu_tlb_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
12240     int tlb_noflush, int hat_lock_held)
12241 {
12242 	cpuset_t cpuset;
12243 	hatlock_t *hatlockp;
12244 
12245 	ASSERT(!hmeblkp->hblk_shared);
12246 
12247 	/*
12248 	 * If the process is exiting we have nothing to do.
12249 	 */
12250 	if (tlb_noflush)
12251 		return;
12252 
12253 	/*
12254 	 * Flush TSB.
12255 	 */
12256 	if (!hat_lock_held)
12257 		hatlockp = sfmmu_hat_enter(sfmmup);
12258 	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, 0);
12259 
12260 	kpreempt_disable();
12261 
12262 	cpuset = sfmmup->sfmmu_cpusran;
12263 	CPUSET_AND(cpuset, cpu_ready_set);
12264 	CPUSET_DEL(cpuset, CPU->cpu_id);
12265 
12266 	SFMMU_XCALL_STATS(sfmmup);
12267 	xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr, (uint64_t)sfmmup);
12268 
12269 	vtag_flushpage(addr, (uint64_t)sfmmup);
12270 
12271 	if (!hat_lock_held)
12272 		sfmmu_hat_exit(hatlockp);
12273 
12274 	kpreempt_enable();
12275 
12276 }
12277 
12278 /*
12279  * Special case of sfmmu_tlb_demap for MMU_PAGESIZE hblks. Use the xcall
12280  * call handler that can flush a range of pages to save on xcalls.
12281  */
12282 static int sfmmu_xcall_save;
12283 
12284 /*
12285  * this routine is never used for demaping addresses backed by SRD hmeblks.
12286  */
12287 static void
12288 sfmmu_tlb_range_demap(demap_range_t *dmrp)
12289 {
12290 	sfmmu_t *sfmmup = dmrp->dmr_sfmmup;
12291 	hatlock_t *hatlockp;
12292 	cpuset_t cpuset;
12293 	uint64_t sfmmu_pgcnt;
12294 	pgcnt_t pgcnt = 0;
12295 	int pgunload = 0;
12296 	int dirtypg = 0;
12297 	caddr_t addr = dmrp->dmr_addr;
12298 	caddr_t eaddr;
12299 	uint64_t bitvec = dmrp->dmr_bitvec;
12300 
12301 	ASSERT(bitvec & 1);
12302 
12303 	/*
12304 	 * Flush TSB and calculate number of pages to flush.
12305 	 */
12306 	while (bitvec != 0) {
12307 		dirtypg = 0;
12308 		/*
12309 		 * Find the first page to flush and then count how many
12310 		 * pages there are after it that also need to be flushed.
12311 		 * This way the number of TSB flushes is minimized.
12312 		 */
12313 		while ((bitvec & 1) == 0) {
12314 			pgcnt++;
12315 			addr += MMU_PAGESIZE;
12316 			bitvec >>= 1;
12317 		}
12318 		while (bitvec & 1) {
12319 			dirtypg++;
12320 			bitvec >>= 1;
12321 		}
12322 		eaddr = addr + ptob(dirtypg);
12323 		hatlockp = sfmmu_hat_enter(sfmmup);
12324 		sfmmu_unload_tsb_range(sfmmup, addr, eaddr, TTE8K);
12325 		sfmmu_hat_exit(hatlockp);
12326 		pgunload += dirtypg;
12327 		addr = eaddr;
12328 		pgcnt += dirtypg;
12329 	}
12330 
12331 	ASSERT((pgcnt<<MMU_PAGESHIFT) <= dmrp->dmr_endaddr - dmrp->dmr_addr);
12332 	if (sfmmup->sfmmu_free == 0) {
12333 		addr = dmrp->dmr_addr;
12334 		bitvec = dmrp->dmr_bitvec;
12335 
12336 		/*
12337 		 * make sure it has SFMMU_PGCNT_SHIFT bits only,
12338 		 * as it will be used to pack argument for xt_some
12339 		 */
12340 		ASSERT((pgcnt > 0) &&
12341 		    (pgcnt <= (1 << SFMMU_PGCNT_SHIFT)));
12342 
12343 		/*
12344 		 * Encode pgcnt as (pgcnt -1 ), and pass (pgcnt - 1) in
12345 		 * the low 6 bits of sfmmup. This is doable since pgcnt
12346 		 * always >= 1.
12347 		 */
12348 		ASSERT(!((uint64_t)sfmmup & SFMMU_PGCNT_MASK));
12349 		sfmmu_pgcnt = (uint64_t)sfmmup |
12350 		    ((pgcnt - 1) & SFMMU_PGCNT_MASK);
12351 
12352 		/*
12353 		 * We must hold the hat lock during the flush of TLB,
12354 		 * to avoid a race with sfmmu_invalidate_ctx(), where
12355 		 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
12356 		 * causing TLB demap routine to skip flush on that MMU.
12357 		 * If the context on a MMU has already been set to
12358 		 * INVALID_CONTEXT, we just get an extra flush on
12359 		 * that MMU.
12360 		 */
12361 		hatlockp = sfmmu_hat_enter(sfmmup);
12362 		kpreempt_disable();
12363 
12364 		cpuset = sfmmup->sfmmu_cpusran;
12365 		CPUSET_AND(cpuset, cpu_ready_set);
12366 		CPUSET_DEL(cpuset, CPU->cpu_id);
12367 
12368 		SFMMU_XCALL_STATS(sfmmup);
12369 		xt_some(cpuset, vtag_flush_pgcnt_tl1, (uint64_t)addr,
12370 		    sfmmu_pgcnt);
12371 
12372 		for (; bitvec != 0; bitvec >>= 1) {
12373 			if (bitvec & 1)
12374 				vtag_flushpage(addr, (uint64_t)sfmmup);
12375 			addr += MMU_PAGESIZE;
12376 		}
12377 		kpreempt_enable();
12378 		sfmmu_hat_exit(hatlockp);
12379 
12380 		sfmmu_xcall_save += (pgunload-1);
12381 	}
12382 	dmrp->dmr_bitvec = 0;
12383 }
12384 
12385 /*
12386  * In cases where we need to synchronize with TLB/TSB miss trap
12387  * handlers, _and_ need to flush the TLB, it's a lot easier to
12388  * throw away the context from the process than to do a
12389  * special song and dance to keep things consistent for the
12390  * handlers.
12391  *
12392  * Since the process suddenly ends up without a context and our caller
12393  * holds the hat lock, threads that fault after this function is called
12394  * will pile up on the lock.  We can then do whatever we need to
12395  * atomically from the context of the caller.  The first blocked thread
12396  * to resume executing will get the process a new context, and the
12397  * process will resume executing.
12398  *
12399  * One added advantage of this approach is that on MMUs that
12400  * support a "flush all" operation, we will delay the flush until
12401  * cnum wrap-around, and then flush the TLB one time.  This
12402  * is rather rare, so it's a lot less expensive than making 8000
12403  * x-calls to flush the TLB 8000 times.
12404  *
12405  * A per-process (PP) lock is used to synchronize ctx allocations in
12406  * resume() and ctx invalidations here.
12407  */
12408 static void
12409 sfmmu_invalidate_ctx(sfmmu_t *sfmmup)
12410 {
12411 	cpuset_t cpuset;
12412 	int cnum, currcnum;
12413 	mmu_ctx_t *mmu_ctxp;
12414 	int i;
12415 	uint_t pstate_save;
12416 
12417 	SFMMU_STAT(sf_ctx_inv);
12418 
12419 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12420 	ASSERT(sfmmup != ksfmmup);
12421 
12422 	kpreempt_disable();
12423 
12424 	mmu_ctxp = CPU_MMU_CTXP(CPU);
12425 	ASSERT(mmu_ctxp);
12426 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
12427 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
12428 
12429 	currcnum = sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum;
12430 
12431 	pstate_save = sfmmu_disable_intrs();
12432 
12433 	lock_set(&sfmmup->sfmmu_ctx_lock);	/* acquire PP lock */
12434 	/* set HAT cnum invalid across all context domains. */
12435 	for (i = 0; i < max_mmu_ctxdoms; i++) {
12436 
12437 		cnum = sfmmup->sfmmu_ctxs[i].cnum;
12438 		if (cnum == INVALID_CONTEXT) {
12439 			continue;
12440 		}
12441 
12442 		sfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
12443 	}
12444 	membar_enter();	/* make sure globally visible to all CPUs */
12445 	lock_clear(&sfmmup->sfmmu_ctx_lock);	/* release PP lock */
12446 
12447 	sfmmu_enable_intrs(pstate_save);
12448 
12449 	cpuset = sfmmup->sfmmu_cpusran;
12450 	CPUSET_DEL(cpuset, CPU->cpu_id);
12451 	CPUSET_AND(cpuset, cpu_ready_set);
12452 	if (!CPUSET_ISNULL(cpuset)) {
12453 		SFMMU_XCALL_STATS(sfmmup);
12454 		xt_some(cpuset, sfmmu_raise_tsb_exception,
12455 		    (uint64_t)sfmmup, INVALID_CONTEXT);
12456 		xt_sync(cpuset);
12457 		SFMMU_STAT(sf_tsb_raise_exception);
12458 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
12459 	}
12460 
12461 	/*
12462 	 * If the hat to-be-invalidated is the same as the current
12463 	 * process on local CPU we need to invalidate
12464 	 * this CPU context as well.
12465 	 */
12466 	if ((sfmmu_getctx_sec() == currcnum) &&
12467 	    (currcnum != INVALID_CONTEXT)) {
12468 		/* sets shared context to INVALID too */
12469 		sfmmu_setctx_sec(INVALID_CONTEXT);
12470 		sfmmu_clear_utsbinfo();
12471 	}
12472 
12473 	SFMMU_FLAGS_SET(sfmmup, HAT_ALLCTX_INVALID);
12474 
12475 	kpreempt_enable();
12476 
12477 	/*
12478 	 * we hold the hat lock, so nobody should allocate a context
12479 	 * for us yet
12480 	 */
12481 	ASSERT(sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum == INVALID_CONTEXT);
12482 }
12483 
12484 #ifdef VAC
12485 /*
12486  * We need to flush the cache in all cpus.  It is possible that
12487  * a process referenced a page as cacheable but has sinced exited
12488  * and cleared the mapping list.  We still to flush it but have no
12489  * state so all cpus is the only alternative.
12490  */
12491 void
12492 sfmmu_cache_flush(pfn_t pfnum, int vcolor)
12493 {
12494 	cpuset_t cpuset;
12495 
12496 	kpreempt_disable();
12497 	cpuset = cpu_ready_set;
12498 	CPUSET_DEL(cpuset, CPU->cpu_id);
12499 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12500 	xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
12501 	xt_sync(cpuset);
12502 	vac_flushpage(pfnum, vcolor);
12503 	kpreempt_enable();
12504 }
12505 
12506 void
12507 sfmmu_cache_flushcolor(int vcolor, pfn_t pfnum)
12508 {
12509 	cpuset_t cpuset;
12510 
12511 	ASSERT(vcolor >= 0);
12512 
12513 	kpreempt_disable();
12514 	cpuset = cpu_ready_set;
12515 	CPUSET_DEL(cpuset, CPU->cpu_id);
12516 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
12517 	xt_some(cpuset, vac_flushcolor_tl1, vcolor, pfnum);
12518 	xt_sync(cpuset);
12519 	vac_flushcolor(vcolor, pfnum);
12520 	kpreempt_enable();
12521 }
12522 #endif	/* VAC */
12523 
12524 /*
12525  * We need to prevent processes from accessing the TSB using a cached physical
12526  * address.  It's alright if they try to access the TSB via virtual address
12527  * since they will just fault on that virtual address once the mapping has
12528  * been suspended.
12529  */
12530 #pragma weak sendmondo_in_recover
12531 
12532 /* ARGSUSED */
12533 static int
12534 sfmmu_tsb_pre_relocator(caddr_t va, uint_t tsbsz, uint_t flags, void *tsbinfo)
12535 {
12536 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12537 	sfmmu_t *sfmmup = tsbinfop->tsb_sfmmu;
12538 	hatlock_t *hatlockp;
12539 	sf_scd_t *scdp;
12540 
12541 	if (flags != HAT_PRESUSPEND)
12542 		return (0);
12543 
12544 	/*
12545 	 * If tsb is a shared TSB with TSB_SHAREDCTX set, sfmmup must
12546 	 * be a shared hat, then set SCD's tsbinfo's flag.
12547 	 * If tsb is not shared, sfmmup is a private hat, then set
12548 	 * its private tsbinfo's flag.
12549 	 */
12550 	hatlockp = sfmmu_hat_enter(sfmmup);
12551 	tsbinfop->tsb_flags |= TSB_RELOC_FLAG;
12552 
12553 	if (!(tsbinfop->tsb_flags & TSB_SHAREDCTX)) {
12554 		sfmmu_tsb_inv_ctx(sfmmup);
12555 		sfmmu_hat_exit(hatlockp);
12556 	} else {
12557 		/* release lock on the shared hat */
12558 		sfmmu_hat_exit(hatlockp);
12559 		/* sfmmup is a shared hat */
12560 		ASSERT(sfmmup->sfmmu_scdhat);
12561 		scdp = sfmmup->sfmmu_scdp;
12562 		ASSERT(scdp != NULL);
12563 		/* get private hat from the scd list */
12564 		mutex_enter(&scdp->scd_mutex);
12565 		sfmmup = scdp->scd_sf_list;
12566 		while (sfmmup != NULL) {
12567 			hatlockp = sfmmu_hat_enter(sfmmup);
12568 			/*
12569 			 * We do not call sfmmu_tsb_inv_ctx here because
12570 			 * sendmondo_in_recover check is only needed for
12571 			 * sun4u.
12572 			 */
12573 			sfmmu_invalidate_ctx(sfmmup);
12574 			sfmmu_hat_exit(hatlockp);
12575 			sfmmup = sfmmup->sfmmu_scd_link.next;
12576 
12577 		}
12578 		mutex_exit(&scdp->scd_mutex);
12579 	}
12580 	return (0);
12581 }
12582 
12583 static void
12584 sfmmu_tsb_inv_ctx(sfmmu_t *sfmmup)
12585 {
12586 	extern uint32_t sendmondo_in_recover;
12587 
12588 	ASSERT(sfmmu_hat_lock_held(sfmmup));
12589 
12590 	/*
12591 	 * For Cheetah+ Erratum 25:
12592 	 * Wait for any active recovery to finish.  We can't risk
12593 	 * relocating the TSB of the thread running mondo_recover_proc()
12594 	 * since, if we did that, we would deadlock.  The scenario we are
12595 	 * trying to avoid is as follows:
12596 	 *
12597 	 * THIS CPU			RECOVER CPU
12598 	 * --------			-----------
12599 	 *				Begins recovery, walking through TSB
12600 	 * hat_pagesuspend() TSB TTE
12601 	 *				TLB miss on TSB TTE, spins at TL1
12602 	 * xt_sync()
12603 	 *	send_mondo_timeout()
12604 	 *	mondo_recover_proc()
12605 	 *	((deadlocked))
12606 	 *
12607 	 * The second half of the workaround is that mondo_recover_proc()
12608 	 * checks to see if the tsb_info has the RELOC flag set, and if it
12609 	 * does, it skips over that TSB without ever touching tsbinfop->tsb_va
12610 	 * and hence avoiding the TLB miss that could result in a deadlock.
12611 	 */
12612 	if (&sendmondo_in_recover) {
12613 		membar_enter();	/* make sure RELOC flag visible */
12614 		while (sendmondo_in_recover) {
12615 			drv_usecwait(1);
12616 			membar_consumer();
12617 		}
12618 	}
12619 
12620 	sfmmu_invalidate_ctx(sfmmup);
12621 }
12622 
12623 /* ARGSUSED */
12624 static int
12625 sfmmu_tsb_post_relocator(caddr_t va, uint_t tsbsz, uint_t flags,
12626     void *tsbinfo, pfn_t newpfn)
12627 {
12628 	hatlock_t *hatlockp;
12629 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
12630 	sfmmu_t	*sfmmup = tsbinfop->tsb_sfmmu;
12631 
12632 	if (flags != HAT_POSTUNSUSPEND)
12633 		return (0);
12634 
12635 	hatlockp = sfmmu_hat_enter(sfmmup);
12636 
12637 	SFMMU_STAT(sf_tsb_reloc);
12638 
12639 	/*
12640 	 * The process may have swapped out while we were relocating one
12641 	 * of its TSBs.  If so, don't bother doing the setup since the
12642 	 * process can't be using the memory anymore.
12643 	 */
12644 	if ((tsbinfop->tsb_flags & TSB_SWAPPED) == 0) {
12645 		ASSERT(va == tsbinfop->tsb_va);
12646 		sfmmu_tsbinfo_setup_phys(tsbinfop, newpfn);
12647 
12648 		if (tsbinfop->tsb_flags & TSB_FLUSH_NEEDED) {
12649 			sfmmu_inv_tsb(tsbinfop->tsb_va,
12650 			    TSB_BYTES(tsbinfop->tsb_szc));
12651 			tsbinfop->tsb_flags &= ~TSB_FLUSH_NEEDED;
12652 		}
12653 	}
12654 
12655 	membar_exit();
12656 	tsbinfop->tsb_flags &= ~TSB_RELOC_FLAG;
12657 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
12658 
12659 	sfmmu_hat_exit(hatlockp);
12660 
12661 	return (0);
12662 }
12663 
12664 /*
12665  * Allocate and initialize a tsb_info structure.  Note that we may or may not
12666  * allocate a TSB here, depending on the flags passed in.
12667  */
12668 static int
12669 sfmmu_tsbinfo_alloc(struct tsb_info **tsbinfopp, int tsb_szc, int tte_sz_mask,
12670     uint_t flags, sfmmu_t *sfmmup)
12671 {
12672 	int err;
12673 
12674 	*tsbinfopp = (struct tsb_info *)kmem_cache_alloc(
12675 	    sfmmu_tsbinfo_cache, KM_SLEEP);
12676 
12677 	if ((err = sfmmu_init_tsbinfo(*tsbinfopp, tte_sz_mask,
12678 	    tsb_szc, flags, sfmmup)) != 0) {
12679 		kmem_cache_free(sfmmu_tsbinfo_cache, *tsbinfopp);
12680 		SFMMU_STAT(sf_tsb_allocfail);
12681 		*tsbinfopp = NULL;
12682 		return (err);
12683 	}
12684 	SFMMU_STAT(sf_tsb_alloc);
12685 
12686 	/*
12687 	 * Bump the TSB size counters for this TSB size.
12688 	 */
12689 	(*(((int *)&sfmmu_tsbsize_stat) + tsb_szc))++;
12690 	return (0);
12691 }
12692 
12693 static void
12694 sfmmu_tsb_free(struct tsb_info *tsbinfo)
12695 {
12696 	caddr_t tsbva = tsbinfo->tsb_va;
12697 	uint_t tsb_size = TSB_BYTES(tsbinfo->tsb_szc);
12698 	struct kmem_cache *kmem_cachep = tsbinfo->tsb_cache;
12699 	vmem_t	*vmp = tsbinfo->tsb_vmp;
12700 
12701 	/*
12702 	 * If we allocated this TSB from relocatable kernel memory, then we
12703 	 * need to uninstall the callback handler.
12704 	 */
12705 	if (tsbinfo->tsb_cache != sfmmu_tsb8k_cache) {
12706 		uintptr_t slab_mask;
12707 		caddr_t slab_vaddr;
12708 		page_t **ppl;
12709 		int ret;
12710 
12711 		ASSERT(tsb_size <= MMU_PAGESIZE4M || use_bigtsb_arena);
12712 		if (tsb_size > MMU_PAGESIZE4M)
12713 			slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12714 		else
12715 			slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12716 		slab_vaddr = (caddr_t)((uintptr_t)tsbva & slab_mask);
12717 
12718 		ret = as_pagelock(&kas, &ppl, slab_vaddr, PAGESIZE, S_WRITE);
12719 		ASSERT(ret == 0);
12720 		hat_delete_callback(tsbva, (uint_t)tsb_size, (void *)tsbinfo,
12721 		    0, NULL);
12722 		as_pageunlock(&kas, ppl, slab_vaddr, PAGESIZE, S_WRITE);
12723 	}
12724 
12725 	if (kmem_cachep != NULL) {
12726 		kmem_cache_free(kmem_cachep, tsbva);
12727 	} else {
12728 		vmem_xfree(vmp, (void *)tsbva, tsb_size);
12729 	}
12730 	tsbinfo->tsb_va = (caddr_t)0xbad00bad;
12731 	atomic_add_64(&tsb_alloc_bytes, -(int64_t)tsb_size);
12732 }
12733 
12734 static void
12735 sfmmu_tsbinfo_free(struct tsb_info *tsbinfo)
12736 {
12737 	if ((tsbinfo->tsb_flags & TSB_SWAPPED) == 0) {
12738 		sfmmu_tsb_free(tsbinfo);
12739 	}
12740 	kmem_cache_free(sfmmu_tsbinfo_cache, tsbinfo);
12741 
12742 }
12743 
12744 /*
12745  * Setup all the references to physical memory for this tsbinfo.
12746  * The underlying page(s) must be locked.
12747  */
12748 static void
12749 sfmmu_tsbinfo_setup_phys(struct tsb_info *tsbinfo, pfn_t pfn)
12750 {
12751 	ASSERT(pfn != PFN_INVALID);
12752 	ASSERT(pfn == va_to_pfn(tsbinfo->tsb_va));
12753 
12754 #ifndef sun4v
12755 	if (tsbinfo->tsb_szc == 0) {
12756 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn,
12757 		    PROT_WRITE|PROT_READ, TTE8K);
12758 	} else {
12759 		/*
12760 		 * Round down PA and use a large mapping; the handlers will
12761 		 * compute the TSB pointer at the correct offset into the
12762 		 * big virtual page.  NOTE: this assumes all TSBs larger
12763 		 * than 8K must come from physically contiguous slabs of
12764 		 * size tsb_slab_size.
12765 		 */
12766 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn & ~tsb_slab_mask,
12767 		    PROT_WRITE|PROT_READ, tsb_slab_ttesz);
12768 	}
12769 	tsbinfo->tsb_pa = ptob(pfn);
12770 
12771 	TTE_SET_LOCKED(&tsbinfo->tsb_tte); /* lock the tte into dtlb */
12772 	TTE_SET_MOD(&tsbinfo->tsb_tte);    /* enable writes */
12773 
12774 	ASSERT(TTE_IS_PRIVILEGED(&tsbinfo->tsb_tte));
12775 	ASSERT(TTE_IS_LOCKED(&tsbinfo->tsb_tte));
12776 #else /* sun4v */
12777 	tsbinfo->tsb_pa = ptob(pfn);
12778 #endif /* sun4v */
12779 }
12780 
12781 
12782 /*
12783  * Returns zero on success, ENOMEM if over the high water mark,
12784  * or EAGAIN if the caller needs to retry with a smaller TSB
12785  * size (or specify TSB_FORCEALLOC if the allocation can't fail).
12786  *
12787  * This call cannot fail to allocate a TSB if TSB_FORCEALLOC
12788  * is specified and the TSB requested is PAGESIZE, though it
12789  * may sleep waiting for memory if sufficient memory is not
12790  * available.
12791  */
12792 static int
12793 sfmmu_init_tsbinfo(struct tsb_info *tsbinfo, int tteszmask,
12794     int tsbcode, uint_t flags, sfmmu_t *sfmmup)
12795 {
12796 	caddr_t vaddr = NULL;
12797 	caddr_t slab_vaddr;
12798 	uintptr_t slab_mask;
12799 	int tsbbytes = TSB_BYTES(tsbcode);
12800 	int lowmem = 0;
12801 	struct kmem_cache *kmem_cachep = NULL;
12802 	vmem_t *vmp = NULL;
12803 	lgrp_id_t lgrpid = LGRP_NONE;
12804 	pfn_t pfn;
12805 	uint_t cbflags = HAC_SLEEP;
12806 	page_t **pplist;
12807 	int ret;
12808 
12809 	ASSERT(tsbbytes <= MMU_PAGESIZE4M || use_bigtsb_arena);
12810 	if (tsbbytes > MMU_PAGESIZE4M)
12811 		slab_mask = ~((uintptr_t)bigtsb_slab_mask) << PAGESHIFT;
12812 	else
12813 		slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
12814 
12815 	if (flags & (TSB_FORCEALLOC | TSB_SWAPIN | TSB_GROW | TSB_SHRINK))
12816 		flags |= TSB_ALLOC;
12817 
12818 	ASSERT((flags & TSB_FORCEALLOC) == 0 || tsbcode == TSB_MIN_SZCODE);
12819 
12820 	tsbinfo->tsb_sfmmu = sfmmup;
12821 
12822 	/*
12823 	 * If not allocating a TSB, set up the tsbinfo, set TSB_SWAPPED, and
12824 	 * return.
12825 	 */
12826 	if ((flags & TSB_ALLOC) == 0) {
12827 		tsbinfo->tsb_szc = tsbcode;
12828 		tsbinfo->tsb_ttesz_mask = tteszmask;
12829 		tsbinfo->tsb_va = (caddr_t)0xbadbadbeef;
12830 		tsbinfo->tsb_pa = -1;
12831 		tsbinfo->tsb_tte.ll = 0;
12832 		tsbinfo->tsb_next = NULL;
12833 		tsbinfo->tsb_flags = TSB_SWAPPED;
12834 		tsbinfo->tsb_cache = NULL;
12835 		tsbinfo->tsb_vmp = NULL;
12836 		return (0);
12837 	}
12838 
12839 #ifdef DEBUG
12840 	/*
12841 	 * For debugging:
12842 	 * Randomly force allocation failures every tsb_alloc_mtbf
12843 	 * tries if TSB_FORCEALLOC is not specified.  This will
12844 	 * return ENOMEM if tsb_alloc_mtbf is odd, or EAGAIN if
12845 	 * it is even, to allow testing of both failure paths...
12846 	 */
12847 	if (tsb_alloc_mtbf && ((flags & TSB_FORCEALLOC) == 0) &&
12848 	    (tsb_alloc_count++ == tsb_alloc_mtbf)) {
12849 		tsb_alloc_count = 0;
12850 		tsb_alloc_fail_mtbf++;
12851 		return ((tsb_alloc_mtbf & 1)? ENOMEM : EAGAIN);
12852 	}
12853 #endif	/* DEBUG */
12854 
12855 	/*
12856 	 * Enforce high water mark if we are not doing a forced allocation
12857 	 * and are not shrinking a process' TSB.
12858 	 */
12859 	if ((flags & TSB_SHRINK) == 0 &&
12860 	    (tsbbytes + tsb_alloc_bytes) > tsb_alloc_hiwater) {
12861 		if ((flags & TSB_FORCEALLOC) == 0)
12862 			return (ENOMEM);
12863 		lowmem = 1;
12864 	}
12865 
12866 	/*
12867 	 * Allocate from the correct location based upon the size of the TSB
12868 	 * compared to the base page size, and what memory conditions dictate.
12869 	 * Note we always do nonblocking allocations from the TSB arena since
12870 	 * we don't want memory fragmentation to cause processes to block
12871 	 * indefinitely waiting for memory; until the kernel algorithms that
12872 	 * coalesce large pages are improved this is our best option.
12873 	 *
12874 	 * Algorithm:
12875 	 *	If allocating a "large" TSB (>8K), allocate from the
12876 	 *		appropriate kmem_tsb_default_arena vmem arena
12877 	 *	else if low on memory or the TSB_FORCEALLOC flag is set or
12878 	 *	tsb_forceheap is set
12879 	 *		Allocate from kernel heap via sfmmu_tsb8k_cache with
12880 	 *		KM_SLEEP (never fails)
12881 	 *	else
12882 	 *		Allocate from appropriate sfmmu_tsb_cache with
12883 	 *		KM_NOSLEEP
12884 	 *	endif
12885 	 */
12886 	if (tsb_lgrp_affinity)
12887 		lgrpid = lgrp_home_id(curthread);
12888 	if (lgrpid == LGRP_NONE)
12889 		lgrpid = 0;	/* use lgrp of boot CPU */
12890 
12891 	if (tsbbytes > MMU_PAGESIZE) {
12892 		if (tsbbytes > MMU_PAGESIZE4M) {
12893 			vmp = kmem_bigtsb_default_arena[lgrpid];
12894 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
12895 			    0, 0, NULL, NULL, VM_NOSLEEP);
12896 		} else {
12897 			vmp = kmem_tsb_default_arena[lgrpid];
12898 			vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes,
12899 			    0, 0, NULL, NULL, VM_NOSLEEP);
12900 		}
12901 #ifdef	DEBUG
12902 	} else if (lowmem || (flags & TSB_FORCEALLOC) || tsb_forceheap) {
12903 #else	/* !DEBUG */
12904 	} else if (lowmem || (flags & TSB_FORCEALLOC)) {
12905 #endif	/* DEBUG */
12906 		kmem_cachep = sfmmu_tsb8k_cache;
12907 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_SLEEP);
12908 		ASSERT(vaddr != NULL);
12909 	} else {
12910 		kmem_cachep = sfmmu_tsb_cache[lgrpid];
12911 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_NOSLEEP);
12912 	}
12913 
12914 	tsbinfo->tsb_cache = kmem_cachep;
12915 	tsbinfo->tsb_vmp = vmp;
12916 
12917 	if (vaddr == NULL) {
12918 		return (EAGAIN);
12919 	}
12920 
12921 	atomic_add_64(&tsb_alloc_bytes, (int64_t)tsbbytes);
12922 	kmem_cachep = tsbinfo->tsb_cache;
12923 
12924 	/*
12925 	 * If we are allocating from outside the cage, then we need to
12926 	 * register a relocation callback handler.  Note that for now
12927 	 * since pseudo mappings always hang off of the slab's root page,
12928 	 * we need only lock the first 8K of the TSB slab.  This is a bit
12929 	 * hacky but it is good for performance.
12930 	 */
12931 	if (kmem_cachep != sfmmu_tsb8k_cache) {
12932 		slab_vaddr = (caddr_t)((uintptr_t)vaddr & slab_mask);
12933 		ret = as_pagelock(&kas, &pplist, slab_vaddr, PAGESIZE, S_WRITE);
12934 		ASSERT(ret == 0);
12935 		ret = hat_add_callback(sfmmu_tsb_cb_id, vaddr, (uint_t)tsbbytes,
12936 		    cbflags, (void *)tsbinfo, &pfn, NULL);
12937 
12938 		/*
12939 		 * Need to free up resources if we could not successfully
12940 		 * add the callback function and return an error condition.
12941 		 */
12942 		if (ret != 0) {
12943 			if (kmem_cachep) {
12944 				kmem_cache_free(kmem_cachep, vaddr);
12945 			} else {
12946 				vmem_xfree(vmp, (void *)vaddr, tsbbytes);
12947 			}
12948 			as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE,
12949 			    S_WRITE);
12950 			return (EAGAIN);
12951 		}
12952 	} else {
12953 		/*
12954 		 * Since allocation of 8K TSBs from heap is rare and occurs
12955 		 * during memory pressure we allocate them from permanent
12956 		 * memory rather than using callbacks to get the PFN.
12957 		 */
12958 		pfn = hat_getpfnum(kas.a_hat, vaddr);
12959 	}
12960 
12961 	tsbinfo->tsb_va = vaddr;
12962 	tsbinfo->tsb_szc = tsbcode;
12963 	tsbinfo->tsb_ttesz_mask = tteszmask;
12964 	tsbinfo->tsb_next = NULL;
12965 	tsbinfo->tsb_flags = 0;
12966 
12967 	sfmmu_tsbinfo_setup_phys(tsbinfo, pfn);
12968 
12969 	sfmmu_inv_tsb(vaddr, tsbbytes);
12970 
12971 	if (kmem_cachep != sfmmu_tsb8k_cache) {
12972 		as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE, S_WRITE);
12973 	}
12974 
12975 	return (0);
12976 }
12977 
12978 /*
12979  * Initialize per cpu tsb and per cpu tsbmiss_area
12980  */
12981 void
12982 sfmmu_init_tsbs(void)
12983 {
12984 	int i;
12985 	struct tsbmiss	*tsbmissp;
12986 	struct kpmtsbm	*kpmtsbmp;
12987 #ifndef sun4v
12988 	extern int	dcache_line_mask;
12989 #endif /* sun4v */
12990 	extern uint_t	vac_colors;
12991 
12992 	/*
12993 	 * Init. tsb miss area.
12994 	 */
12995 	tsbmissp = tsbmiss_area;
12996 
12997 	for (i = 0; i < NCPU; tsbmissp++, i++) {
12998 		/*
12999 		 * initialize the tsbmiss area.
13000 		 * Do this for all possible CPUs as some may be added
13001 		 * while the system is running. There is no cost to this.
13002 		 */
13003 		tsbmissp->ksfmmup = ksfmmup;
13004 #ifndef sun4v
13005 		tsbmissp->dcache_line_mask = (uint16_t)dcache_line_mask;
13006 #endif /* sun4v */
13007 		tsbmissp->khashstart =
13008 		    (struct hmehash_bucket *)va_to_pa((caddr_t)khme_hash);
13009 		tsbmissp->uhashstart =
13010 		    (struct hmehash_bucket *)va_to_pa((caddr_t)uhme_hash);
13011 		tsbmissp->khashsz = khmehash_num;
13012 		tsbmissp->uhashsz = uhmehash_num;
13013 	}
13014 
13015 	sfmmu_tsb_cb_id = hat_register_callback('T'<<16 | 'S' << 8 | 'B',
13016 	    sfmmu_tsb_pre_relocator, sfmmu_tsb_post_relocator, NULL, 0);
13017 
13018 	if (kpm_enable == 0)
13019 		return;
13020 
13021 	/* -- Begin KPM specific init -- */
13022 
13023 	if (kpm_smallpages) {
13024 		/*
13025 		 * If we're using base pagesize pages for seg_kpm
13026 		 * mappings, we use the kernel TSB since we can't afford
13027 		 * to allocate a second huge TSB for these mappings.
13028 		 */
13029 		kpm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13030 		kpm_tsbsz = ktsb_szcode;
13031 		kpmsm_tsbbase = kpm_tsbbase;
13032 		kpmsm_tsbsz = kpm_tsbsz;
13033 	} else {
13034 		/*
13035 		 * In VAC conflict case, just put the entries in the
13036 		 * kernel 8K indexed TSB for now so we can find them.
13037 		 * This could really be changed in the future if we feel
13038 		 * the need...
13039 		 */
13040 		kpmsm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
13041 		kpmsm_tsbsz = ktsb_szcode;
13042 		kpm_tsbbase = ktsb_phys? ktsb4m_pbase : (uint64_t)ktsb4m_base;
13043 		kpm_tsbsz = ktsb4m_szcode;
13044 	}
13045 
13046 	kpmtsbmp = kpmtsbm_area;
13047 	for (i = 0; i < NCPU; kpmtsbmp++, i++) {
13048 		/*
13049 		 * Initialize the kpmtsbm area.
13050 		 * Do this for all possible CPUs as some may be added
13051 		 * while the system is running. There is no cost to this.
13052 		 */
13053 		kpmtsbmp->vbase = kpm_vbase;
13054 		kpmtsbmp->vend = kpm_vbase + kpm_size * vac_colors;
13055 		kpmtsbmp->sz_shift = kpm_size_shift;
13056 		kpmtsbmp->kpmp_shift = kpmp_shift;
13057 		kpmtsbmp->kpmp2pshft = (uchar_t)kpmp2pshft;
13058 		if (kpm_smallpages == 0) {
13059 			kpmtsbmp->kpmp_table_sz = kpmp_table_sz;
13060 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_table);
13061 		} else {
13062 			kpmtsbmp->kpmp_table_sz = kpmp_stable_sz;
13063 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_stable);
13064 		}
13065 		kpmtsbmp->msegphashpa = va_to_pa(memseg_phash);
13066 		kpmtsbmp->flags = KPMTSBM_ENABLE_FLAG;
13067 #ifdef	DEBUG
13068 		kpmtsbmp->flags |= (kpm_tsbmtl) ?  KPMTSBM_TLTSBM_FLAG : 0;
13069 #endif	/* DEBUG */
13070 		if (ktsb_phys)
13071 			kpmtsbmp->flags |= KPMTSBM_TSBPHYS_FLAG;
13072 	}
13073 
13074 	/* -- End KPM specific init -- */
13075 }
13076 
13077 /* Avoid using sfmmu_tsbinfo_alloc() to avoid kmem_alloc - no real reason */
13078 struct tsb_info ktsb_info[2];
13079 
13080 /*
13081  * Called from hat_kern_setup() to setup the tsb_info for ksfmmup.
13082  */
13083 void
13084 sfmmu_init_ktsbinfo()
13085 {
13086 	ASSERT(ksfmmup != NULL);
13087 	ASSERT(ksfmmup->sfmmu_tsb == NULL);
13088 	/*
13089 	 * Allocate tsbinfos for kernel and copy in data
13090 	 * to make debug easier and sun4v setup easier.
13091 	 */
13092 	ktsb_info[0].tsb_sfmmu = ksfmmup;
13093 	ktsb_info[0].tsb_szc = ktsb_szcode;
13094 	ktsb_info[0].tsb_ttesz_mask = TSB8K|TSB64K|TSB512K;
13095 	ktsb_info[0].tsb_va = ktsb_base;
13096 	ktsb_info[0].tsb_pa = ktsb_pbase;
13097 	ktsb_info[0].tsb_flags = 0;
13098 	ktsb_info[0].tsb_tte.ll = 0;
13099 	ktsb_info[0].tsb_cache = NULL;
13100 
13101 	ktsb_info[1].tsb_sfmmu = ksfmmup;
13102 	ktsb_info[1].tsb_szc = ktsb4m_szcode;
13103 	ktsb_info[1].tsb_ttesz_mask = TSB4M;
13104 	ktsb_info[1].tsb_va = ktsb4m_base;
13105 	ktsb_info[1].tsb_pa = ktsb4m_pbase;
13106 	ktsb_info[1].tsb_flags = 0;
13107 	ktsb_info[1].tsb_tte.ll = 0;
13108 	ktsb_info[1].tsb_cache = NULL;
13109 
13110 	/* Link them into ksfmmup. */
13111 	ktsb_info[0].tsb_next = &ktsb_info[1];
13112 	ktsb_info[1].tsb_next = NULL;
13113 	ksfmmup->sfmmu_tsb = &ktsb_info[0];
13114 
13115 	sfmmu_setup_tsbinfo(ksfmmup);
13116 }
13117 
13118 /*
13119  * Cache the last value returned from va_to_pa().  If the VA specified
13120  * in the current call to cached_va_to_pa() maps to the same Page (as the
13121  * previous call to cached_va_to_pa()), then compute the PA using
13122  * cached info, else call va_to_pa().
13123  *
13124  * Note: this function is neither MT-safe nor consistent in the presence
13125  * of multiple, interleaved threads.  This function was created to enable
13126  * an optimization used during boot (at a point when there's only one thread
13127  * executing on the "boot CPU", and before startup_vm() has been called).
13128  */
13129 static uint64_t
13130 cached_va_to_pa(void *vaddr)
13131 {
13132 	static uint64_t prev_vaddr_base = 0;
13133 	static uint64_t prev_pfn = 0;
13134 
13135 	if ((((uint64_t)vaddr) & MMU_PAGEMASK) == prev_vaddr_base) {
13136 		return (prev_pfn | ((uint64_t)vaddr & MMU_PAGEOFFSET));
13137 	} else {
13138 		uint64_t pa = va_to_pa(vaddr);
13139 
13140 		if (pa != ((uint64_t)-1)) {
13141 			/*
13142 			 * Computed physical address is valid.  Cache its
13143 			 * related info for the next cached_va_to_pa() call.
13144 			 */
13145 			prev_pfn = pa & MMU_PAGEMASK;
13146 			prev_vaddr_base = ((uint64_t)vaddr) & MMU_PAGEMASK;
13147 		}
13148 
13149 		return (pa);
13150 	}
13151 }
13152 
13153 /*
13154  * Carve up our nucleus hblk region.  We may allocate more hblks than
13155  * asked due to rounding errors but we are guaranteed to have at least
13156  * enough space to allocate the requested number of hblk8's and hblk1's.
13157  */
13158 void
13159 sfmmu_init_nucleus_hblks(caddr_t addr, size_t size, int nhblk8, int nhblk1)
13160 {
13161 	struct hme_blk *hmeblkp;
13162 	size_t hme8blk_sz, hme1blk_sz;
13163 	size_t i;
13164 	size_t hblk8_bound;
13165 	ulong_t j = 0, k = 0;
13166 
13167 	ASSERT(addr != NULL && size != 0);
13168 
13169 	/* Need to use proper structure alignment */
13170 	hme8blk_sz = roundup(HME8BLK_SZ, sizeof (int64_t));
13171 	hme1blk_sz = roundup(HME1BLK_SZ, sizeof (int64_t));
13172 
13173 	nucleus_hblk8.list = (void *)addr;
13174 	nucleus_hblk8.index = 0;
13175 
13176 	/*
13177 	 * Use as much memory as possible for hblk8's since we
13178 	 * expect all bop_alloc'ed memory to be allocated in 8k chunks.
13179 	 * We need to hold back enough space for the hblk1's which
13180 	 * we'll allocate next.
13181 	 */
13182 	hblk8_bound = size - (nhblk1 * hme1blk_sz) - hme8blk_sz;
13183 	for (i = 0; i <= hblk8_bound; i += hme8blk_sz, j++) {
13184 		hmeblkp = (struct hme_blk *)addr;
13185 		addr += hme8blk_sz;
13186 		hmeblkp->hblk_nuc_bit = 1;
13187 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13188 	}
13189 	nucleus_hblk8.len = j;
13190 	ASSERT(j >= nhblk8);
13191 	SFMMU_STAT_ADD(sf_hblk8_ncreate, j);
13192 
13193 	nucleus_hblk1.list = (void *)addr;
13194 	nucleus_hblk1.index = 0;
13195 	for (; i <= (size - hme1blk_sz); i += hme1blk_sz, k++) {
13196 		hmeblkp = (struct hme_blk *)addr;
13197 		addr += hme1blk_sz;
13198 		hmeblkp->hblk_nuc_bit = 1;
13199 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
13200 	}
13201 	ASSERT(k >= nhblk1);
13202 	nucleus_hblk1.len = k;
13203 	SFMMU_STAT_ADD(sf_hblk1_ncreate, k);
13204 }
13205 
13206 /*
13207  * This function is currently not supported on this platform. For what
13208  * it's supposed to do, see hat.c and hat_srmmu.c
13209  */
13210 /* ARGSUSED */
13211 faultcode_t
13212 hat_softlock(struct hat *hat, caddr_t addr, size_t *lenp, page_t **ppp,
13213     uint_t flags)
13214 {
13215 	return (FC_NOSUPPORT);
13216 }
13217 
13218 /*
13219  * Searchs the mapping list of the page for a mapping of the same size. If not
13220  * found the corresponding bit is cleared in the p_index field. When large
13221  * pages are more prevalent in the system, we can maintain the mapping list
13222  * in order and we don't have to traverse the list each time. Just check the
13223  * next and prev entries, and if both are of different size, we clear the bit.
13224  */
13225 static void
13226 sfmmu_rm_large_mappings(page_t *pp, int ttesz)
13227 {
13228 	struct sf_hment *sfhmep;
13229 	int	index;
13230 	pgcnt_t	npgs;
13231 
13232 	ASSERT(ttesz > TTE8K);
13233 
13234 	ASSERT(sfmmu_mlist_held(pp));
13235 
13236 	ASSERT(PP_ISMAPPED_LARGE(pp));
13237 
13238 	/*
13239 	 * Traverse mapping list looking for another mapping of same size.
13240 	 * since we only want to clear index field if all mappings of
13241 	 * that size are gone.
13242 	 */
13243 
13244 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
13245 		if (IS_PAHME(sfhmep))
13246 			continue;
13247 		if (hme_size(sfhmep) == ttesz) {
13248 			/*
13249 			 * another mapping of the same size. don't clear index.
13250 			 */
13251 			return;
13252 		}
13253 	}
13254 
13255 	/*
13256 	 * Clear the p_index bit for large page.
13257 	 */
13258 	index = PAGESZ_TO_INDEX(ttesz);
13259 	npgs = TTEPAGES(ttesz);
13260 	while (npgs-- > 0) {
13261 		ASSERT(pp->p_index & index);
13262 		pp->p_index &= ~index;
13263 		pp = PP_PAGENEXT(pp);
13264 	}
13265 }
13266 
13267 /*
13268  * return supported features
13269  */
13270 /* ARGSUSED */
13271 int
13272 hat_supported(enum hat_features feature, void *arg)
13273 {
13274 	switch (feature) {
13275 	case    HAT_SHARED_PT:
13276 	case	HAT_DYNAMIC_ISM_UNMAP:
13277 	case	HAT_VMODSORT:
13278 		return (1);
13279 	case	HAT_SHARED_REGIONS:
13280 		if (shctx_on)
13281 			return (1);
13282 		else
13283 			return (0);
13284 	default:
13285 		return (0);
13286 	}
13287 }
13288 
13289 void
13290 hat_enter(struct hat *hat)
13291 {
13292 	hatlock_t	*hatlockp;
13293 
13294 	if (hat != ksfmmup) {
13295 		hatlockp = TSB_HASH(hat);
13296 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
13297 	}
13298 }
13299 
13300 void
13301 hat_exit(struct hat *hat)
13302 {
13303 	hatlock_t	*hatlockp;
13304 
13305 	if (hat != ksfmmup) {
13306 		hatlockp = TSB_HASH(hat);
13307 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
13308 	}
13309 }
13310 
13311 /*ARGSUSED*/
13312 void
13313 hat_reserve(struct as *as, caddr_t addr, size_t len)
13314 {
13315 }
13316 
13317 static void
13318 hat_kstat_init(void)
13319 {
13320 	kstat_t *ksp;
13321 
13322 	ksp = kstat_create("unix", 0, "sfmmu_global_stat", "hat",
13323 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_global_stat),
13324 	    KSTAT_FLAG_VIRTUAL);
13325 	if (ksp) {
13326 		ksp->ks_data = (void *) &sfmmu_global_stat;
13327 		kstat_install(ksp);
13328 	}
13329 	ksp = kstat_create("unix", 0, "sfmmu_tsbsize_stat", "hat",
13330 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_tsbsize_stat),
13331 	    KSTAT_FLAG_VIRTUAL);
13332 	if (ksp) {
13333 		ksp->ks_data = (void *) &sfmmu_tsbsize_stat;
13334 		kstat_install(ksp);
13335 	}
13336 	ksp = kstat_create("unix", 0, "sfmmu_percpu_stat", "hat",
13337 	    KSTAT_TYPE_RAW, sizeof (struct sfmmu_percpu_stat) * NCPU,
13338 	    KSTAT_FLAG_WRITABLE);
13339 	if (ksp) {
13340 		ksp->ks_update = sfmmu_kstat_percpu_update;
13341 		kstat_install(ksp);
13342 	}
13343 }
13344 
13345 /* ARGSUSED */
13346 static int
13347 sfmmu_kstat_percpu_update(kstat_t *ksp, int rw)
13348 {
13349 	struct sfmmu_percpu_stat *cpu_kstat = ksp->ks_data;
13350 	struct tsbmiss *tsbm = tsbmiss_area;
13351 	struct kpmtsbm *kpmtsbm = kpmtsbm_area;
13352 	int i;
13353 
13354 	ASSERT(cpu_kstat);
13355 	if (rw == KSTAT_READ) {
13356 		for (i = 0; i < NCPU; cpu_kstat++, tsbm++, kpmtsbm++, i++) {
13357 			cpu_kstat->sf_itlb_misses = 0;
13358 			cpu_kstat->sf_dtlb_misses = 0;
13359 			cpu_kstat->sf_utsb_misses = tsbm->utsb_misses -
13360 			    tsbm->uprot_traps;
13361 			cpu_kstat->sf_ktsb_misses = tsbm->ktsb_misses +
13362 			    kpmtsbm->kpm_tsb_misses - tsbm->kprot_traps;
13363 			cpu_kstat->sf_tsb_hits = 0;
13364 			cpu_kstat->sf_umod_faults = tsbm->uprot_traps;
13365 			cpu_kstat->sf_kmod_faults = tsbm->kprot_traps;
13366 		}
13367 	} else {
13368 		/* KSTAT_WRITE is used to clear stats */
13369 		for (i = 0; i < NCPU; tsbm++, kpmtsbm++, i++) {
13370 			tsbm->utsb_misses = 0;
13371 			tsbm->ktsb_misses = 0;
13372 			tsbm->uprot_traps = 0;
13373 			tsbm->kprot_traps = 0;
13374 			kpmtsbm->kpm_dtlb_misses = 0;
13375 			kpmtsbm->kpm_tsb_misses = 0;
13376 		}
13377 	}
13378 	return (0);
13379 }
13380 
13381 #ifdef	DEBUG
13382 
13383 tte_t  *gorig[NCPU], *gcur[NCPU], *gnew[NCPU];
13384 
13385 /*
13386  * A tte checker. *orig_old is the value we read before cas.
13387  *	*cur is the value returned by cas.
13388  *	*new is the desired value when we do the cas.
13389  *
13390  *	*hmeblkp is currently unused.
13391  */
13392 
13393 /* ARGSUSED */
13394 void
13395 chk_tte(tte_t *orig_old, tte_t *cur, tte_t *new, struct hme_blk *hmeblkp)
13396 {
13397 	pfn_t i, j, k;
13398 	int cpuid = CPU->cpu_id;
13399 
13400 	gorig[cpuid] = orig_old;
13401 	gcur[cpuid] = cur;
13402 	gnew[cpuid] = new;
13403 
13404 #ifdef lint
13405 	hmeblkp = hmeblkp;
13406 #endif
13407 
13408 	if (TTE_IS_VALID(orig_old)) {
13409 		if (TTE_IS_VALID(cur)) {
13410 			i = TTE_TO_TTEPFN(orig_old);
13411 			j = TTE_TO_TTEPFN(cur);
13412 			k = TTE_TO_TTEPFN(new);
13413 			if (i != j) {
13414 				/* remap error? */
13415 				panic("chk_tte: bad pfn, 0x%lx, 0x%lx", i, j);
13416 			}
13417 
13418 			if (i != k) {
13419 				/* remap error? */
13420 				panic("chk_tte: bad pfn2, 0x%lx, 0x%lx", i, k);
13421 			}
13422 		} else {
13423 			if (TTE_IS_VALID(new)) {
13424 				panic("chk_tte: invalid cur? ");
13425 			}
13426 
13427 			i = TTE_TO_TTEPFN(orig_old);
13428 			k = TTE_TO_TTEPFN(new);
13429 			if (i != k) {
13430 				panic("chk_tte: bad pfn3, 0x%lx, 0x%lx", i, k);
13431 			}
13432 		}
13433 	} else {
13434 		if (TTE_IS_VALID(cur)) {
13435 			j = TTE_TO_TTEPFN(cur);
13436 			if (TTE_IS_VALID(new)) {
13437 				k = TTE_TO_TTEPFN(new);
13438 				if (j != k) {
13439 					panic("chk_tte: bad pfn4, 0x%lx, 0x%lx",
13440 					    j, k);
13441 				}
13442 			} else {
13443 				panic("chk_tte: why here?");
13444 			}
13445 		} else {
13446 			if (!TTE_IS_VALID(new)) {
13447 				panic("chk_tte: why here2 ?");
13448 			}
13449 		}
13450 	}
13451 }
13452 
13453 #endif /* DEBUG */
13454 
13455 extern void prefetch_tsbe_read(struct tsbe *);
13456 extern void prefetch_tsbe_write(struct tsbe *);
13457 
13458 
13459 /*
13460  * We want to prefetch 7 cache lines ahead for our read prefetch.  This gives
13461  * us optimal performance on Cheetah+.  You can only have 8 outstanding
13462  * prefetches at any one time, so we opted for 7 read prefetches and 1 write
13463  * prefetch to make the most utilization of the prefetch capability.
13464  */
13465 #define	TSBE_PREFETCH_STRIDE (7)
13466 
13467 void
13468 sfmmu_copy_tsb(struct tsb_info *old_tsbinfo, struct tsb_info *new_tsbinfo)
13469 {
13470 	int old_bytes = TSB_BYTES(old_tsbinfo->tsb_szc);
13471 	int new_bytes = TSB_BYTES(new_tsbinfo->tsb_szc);
13472 	int old_entries = TSB_ENTRIES(old_tsbinfo->tsb_szc);
13473 	int new_entries = TSB_ENTRIES(new_tsbinfo->tsb_szc);
13474 	struct tsbe *old;
13475 	struct tsbe *new;
13476 	struct tsbe *new_base = (struct tsbe *)new_tsbinfo->tsb_va;
13477 	uint64_t va;
13478 	int new_offset;
13479 	int i;
13480 	int vpshift;
13481 	int last_prefetch;
13482 
13483 	if (old_bytes == new_bytes) {
13484 		bcopy(old_tsbinfo->tsb_va, new_tsbinfo->tsb_va, new_bytes);
13485 	} else {
13486 
13487 		/*
13488 		 * A TSBE is 16 bytes which means there are four TSBE's per
13489 		 * P$ line (64 bytes), thus every 4 TSBE's we prefetch.
13490 		 */
13491 		old = (struct tsbe *)old_tsbinfo->tsb_va;
13492 		last_prefetch = old_entries - (4*(TSBE_PREFETCH_STRIDE+1));
13493 		for (i = 0; i < old_entries; i++, old++) {
13494 			if (((i & (4-1)) == 0) && (i < last_prefetch))
13495 				prefetch_tsbe_read(old);
13496 			if (!old->tte_tag.tag_invalid) {
13497 				/*
13498 				 * We have a valid TTE to remap.  Check the
13499 				 * size.  We won't remap 64K or 512K TTEs
13500 				 * because they span more than one TSB entry
13501 				 * and are indexed using an 8K virt. page.
13502 				 * Ditto for 32M and 256M TTEs.
13503 				 */
13504 				if (TTE_CSZ(&old->tte_data) == TTE64K ||
13505 				    TTE_CSZ(&old->tte_data) == TTE512K)
13506 					continue;
13507 				if (mmu_page_sizes == max_mmu_page_sizes) {
13508 					if (TTE_CSZ(&old->tte_data) == TTE32M ||
13509 					    TTE_CSZ(&old->tte_data) == TTE256M)
13510 						continue;
13511 				}
13512 
13513 				/* clear the lower 22 bits of the va */
13514 				va = *(uint64_t *)old << 22;
13515 				/* turn va into a virtual pfn */
13516 				va >>= 22 - TSB_START_SIZE;
13517 				/*
13518 				 * or in bits from the offset in the tsb
13519 				 * to get the real virtual pfn. These
13520 				 * correspond to bits [21:13] in the va
13521 				 */
13522 				vpshift =
13523 				    TTE_BSZS_SHIFT(TTE_CSZ(&old->tte_data)) &
13524 				    0x1ff;
13525 				va |= (i << vpshift);
13526 				va >>= vpshift;
13527 				new_offset = va & (new_entries - 1);
13528 				new = new_base + new_offset;
13529 				prefetch_tsbe_write(new);
13530 				*new = *old;
13531 			}
13532 		}
13533 	}
13534 }
13535 
13536 /*
13537  * unused in sfmmu
13538  */
13539 void
13540 hat_dump(void)
13541 {
13542 }
13543 
13544 /*
13545  * Called when a thread is exiting and we have switched to the kernel address
13546  * space.  Perform the same VM initialization resume() uses when switching
13547  * processes.
13548  *
13549  * Note that sfmmu_load_mmustate() is currently a no-op for kernel threads, but
13550  * we call it anyway in case the semantics change in the future.
13551  */
13552 /*ARGSUSED*/
13553 void
13554 hat_thread_exit(kthread_t *thd)
13555 {
13556 	uint_t pgsz_cnum;
13557 	uint_t pstate_save;
13558 
13559 	ASSERT(thd->t_procp->p_as == &kas);
13560 
13561 	pgsz_cnum = KCONTEXT;
13562 #ifdef sun4u
13563 	pgsz_cnum |= (ksfmmup->sfmmu_cext << CTXREG_EXT_SHIFT);
13564 #endif
13565 
13566 	/*
13567 	 * Note that sfmmu_load_mmustate() is currently a no-op for
13568 	 * kernel threads. We need to disable interrupts here,
13569 	 * simply because otherwise sfmmu_load_mmustate() would panic
13570 	 * if the caller does not disable interrupts.
13571 	 */
13572 	pstate_save = sfmmu_disable_intrs();
13573 
13574 	/* Compatibility Note: hw takes care of MMU_SCONTEXT1 */
13575 	sfmmu_setctx_sec(pgsz_cnum);
13576 	sfmmu_load_mmustate(ksfmmup);
13577 	sfmmu_enable_intrs(pstate_save);
13578 }
13579 
13580 
13581 /*
13582  * SRD support
13583  */
13584 #define	SRD_HASH_FUNCTION(vp)	(((((uintptr_t)(vp)) >> 4) ^ \
13585 				    (((uintptr_t)(vp)) >> 11)) & \
13586 				    srd_hashmask)
13587 
13588 /*
13589  * Attach the process to the srd struct associated with the exec vnode
13590  * from which the process is started.
13591  */
13592 void
13593 hat_join_srd(struct hat *sfmmup, vnode_t *evp)
13594 {
13595 	uint_t hash = SRD_HASH_FUNCTION(evp);
13596 	sf_srd_t *srdp;
13597 	sf_srd_t *newsrdp;
13598 
13599 	ASSERT(sfmmup != ksfmmup);
13600 	ASSERT(sfmmup->sfmmu_srdp == NULL);
13601 
13602 	if (!shctx_on) {
13603 		return;
13604 	}
13605 
13606 	VN_HOLD(evp);
13607 
13608 	if (srd_buckets[hash].srdb_srdp != NULL) {
13609 		mutex_enter(&srd_buckets[hash].srdb_lock);
13610 		for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13611 		    srdp = srdp->srd_hash) {
13612 			if (srdp->srd_evp == evp) {
13613 				ASSERT(srdp->srd_refcnt >= 0);
13614 				sfmmup->sfmmu_srdp = srdp;
13615 				atomic_inc_32(
13616 				    (volatile uint_t *)&srdp->srd_refcnt);
13617 				mutex_exit(&srd_buckets[hash].srdb_lock);
13618 				return;
13619 			}
13620 		}
13621 		mutex_exit(&srd_buckets[hash].srdb_lock);
13622 	}
13623 	newsrdp = kmem_cache_alloc(srd_cache, KM_SLEEP);
13624 	ASSERT(newsrdp->srd_next_ismrid == 0 && newsrdp->srd_next_hmerid == 0);
13625 
13626 	newsrdp->srd_evp = evp;
13627 	newsrdp->srd_refcnt = 1;
13628 	newsrdp->srd_hmergnfree = NULL;
13629 	newsrdp->srd_ismrgnfree = NULL;
13630 
13631 	mutex_enter(&srd_buckets[hash].srdb_lock);
13632 	for (srdp = srd_buckets[hash].srdb_srdp; srdp != NULL;
13633 	    srdp = srdp->srd_hash) {
13634 		if (srdp->srd_evp == evp) {
13635 			ASSERT(srdp->srd_refcnt >= 0);
13636 			sfmmup->sfmmu_srdp = srdp;
13637 			atomic_inc_32((volatile uint_t *)&srdp->srd_refcnt);
13638 			mutex_exit(&srd_buckets[hash].srdb_lock);
13639 			kmem_cache_free(srd_cache, newsrdp);
13640 			return;
13641 		}
13642 	}
13643 	newsrdp->srd_hash = srd_buckets[hash].srdb_srdp;
13644 	srd_buckets[hash].srdb_srdp = newsrdp;
13645 	sfmmup->sfmmu_srdp = newsrdp;
13646 
13647 	mutex_exit(&srd_buckets[hash].srdb_lock);
13648 
13649 }
13650 
13651 static void
13652 sfmmu_leave_srd(sfmmu_t *sfmmup)
13653 {
13654 	vnode_t *evp;
13655 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13656 	uint_t hash;
13657 	sf_srd_t **prev_srdpp;
13658 	sf_region_t *rgnp;
13659 	sf_region_t *nrgnp;
13660 #ifdef DEBUG
13661 	int rgns = 0;
13662 #endif
13663 	int i;
13664 
13665 	ASSERT(sfmmup != ksfmmup);
13666 	ASSERT(srdp != NULL);
13667 	ASSERT(srdp->srd_refcnt > 0);
13668 	ASSERT(sfmmup->sfmmu_scdp == NULL);
13669 	ASSERT(sfmmup->sfmmu_free == 1);
13670 
13671 	sfmmup->sfmmu_srdp = NULL;
13672 	evp = srdp->srd_evp;
13673 	ASSERT(evp != NULL);
13674 	if (atomic_dec_32_nv((volatile uint_t *)&srdp->srd_refcnt)) {
13675 		VN_RELE(evp);
13676 		return;
13677 	}
13678 
13679 	hash = SRD_HASH_FUNCTION(evp);
13680 	mutex_enter(&srd_buckets[hash].srdb_lock);
13681 	for (prev_srdpp = &srd_buckets[hash].srdb_srdp;
13682 	    (srdp = *prev_srdpp) != NULL; prev_srdpp = &srdp->srd_hash) {
13683 		if (srdp->srd_evp == evp) {
13684 			break;
13685 		}
13686 	}
13687 	if (srdp == NULL || srdp->srd_refcnt) {
13688 		mutex_exit(&srd_buckets[hash].srdb_lock);
13689 		VN_RELE(evp);
13690 		return;
13691 	}
13692 	*prev_srdpp = srdp->srd_hash;
13693 	mutex_exit(&srd_buckets[hash].srdb_lock);
13694 
13695 	ASSERT(srdp->srd_refcnt == 0);
13696 	VN_RELE(evp);
13697 
13698 #ifdef DEBUG
13699 	for (i = 0; i < SFMMU_MAX_REGION_BUCKETS; i++) {
13700 		ASSERT(srdp->srd_rgnhash[i] == NULL);
13701 	}
13702 #endif /* DEBUG */
13703 
13704 	/* free each hme regions in the srd */
13705 	for (rgnp = srdp->srd_hmergnfree; rgnp != NULL; rgnp = nrgnp) {
13706 		nrgnp = rgnp->rgn_next;
13707 		ASSERT(rgnp->rgn_id < srdp->srd_next_hmerid);
13708 		ASSERT(rgnp->rgn_refcnt == 0);
13709 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13710 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13711 		ASSERT(rgnp->rgn_hmeflags == 0);
13712 		ASSERT(srdp->srd_hmergnp[rgnp->rgn_id] == rgnp);
13713 #ifdef DEBUG
13714 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13715 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13716 		}
13717 		rgns++;
13718 #endif /* DEBUG */
13719 		kmem_cache_free(region_cache, rgnp);
13720 	}
13721 	ASSERT(rgns == srdp->srd_next_hmerid);
13722 
13723 #ifdef DEBUG
13724 	rgns = 0;
13725 #endif
13726 	/* free each ism rgns in the srd */
13727 	for (rgnp = srdp->srd_ismrgnfree; rgnp != NULL; rgnp = nrgnp) {
13728 		nrgnp = rgnp->rgn_next;
13729 		ASSERT(rgnp->rgn_id < srdp->srd_next_ismrid);
13730 		ASSERT(rgnp->rgn_refcnt == 0);
13731 		ASSERT(rgnp->rgn_sfmmu_head == NULL);
13732 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
13733 		ASSERT(srdp->srd_ismrgnp[rgnp->rgn_id] == rgnp);
13734 #ifdef DEBUG
13735 		for (i = 0; i < MMU_PAGE_SIZES; i++) {
13736 			ASSERT(rgnp->rgn_ttecnt[i] == 0);
13737 		}
13738 		rgns++;
13739 #endif /* DEBUG */
13740 		kmem_cache_free(region_cache, rgnp);
13741 	}
13742 	ASSERT(rgns == srdp->srd_next_ismrid);
13743 	ASSERT(srdp->srd_ismbusyrgns == 0);
13744 	ASSERT(srdp->srd_hmebusyrgns == 0);
13745 
13746 	srdp->srd_next_ismrid = 0;
13747 	srdp->srd_next_hmerid = 0;
13748 
13749 	bzero((void *)srdp->srd_ismrgnp,
13750 	    sizeof (sf_region_t *) * SFMMU_MAX_ISM_REGIONS);
13751 	bzero((void *)srdp->srd_hmergnp,
13752 	    sizeof (sf_region_t *) * SFMMU_MAX_HME_REGIONS);
13753 
13754 	ASSERT(srdp->srd_scdp == NULL);
13755 	kmem_cache_free(srd_cache, srdp);
13756 }
13757 
13758 /* ARGSUSED */
13759 static int
13760 sfmmu_srdcache_constructor(void *buf, void *cdrarg, int kmflags)
13761 {
13762 	sf_srd_t *srdp = (sf_srd_t *)buf;
13763 	bzero(buf, sizeof (*srdp));
13764 
13765 	mutex_init(&srdp->srd_mutex, NULL, MUTEX_DEFAULT, NULL);
13766 	mutex_init(&srdp->srd_scd_mutex, NULL, MUTEX_DEFAULT, NULL);
13767 	return (0);
13768 }
13769 
13770 /* ARGSUSED */
13771 static void
13772 sfmmu_srdcache_destructor(void *buf, void *cdrarg)
13773 {
13774 	sf_srd_t *srdp = (sf_srd_t *)buf;
13775 
13776 	mutex_destroy(&srdp->srd_mutex);
13777 	mutex_destroy(&srdp->srd_scd_mutex);
13778 }
13779 
13780 /*
13781  * The caller makes sure hat_join_region()/hat_leave_region() can't be called
13782  * at the same time for the same process and address range. This is ensured by
13783  * the fact that address space is locked as writer when a process joins the
13784  * regions. Therefore there's no need to hold an srd lock during the entire
13785  * execution of hat_join_region()/hat_leave_region().
13786  */
13787 
13788 #define	RGN_HASH_FUNCTION(obj)	(((((uintptr_t)(obj)) >> 4) ^ \
13789 				    (((uintptr_t)(obj)) >> 11)) & \
13790 					srd_rgn_hashmask)
13791 /*
13792  * This routine implements the shared context functionality required when
13793  * attaching a segment to an address space. It must be called from
13794  * hat_share() for D(ISM) segments and from segvn_create() for segments
13795  * with the MAP_PRIVATE and MAP_TEXT flags set. It returns a region_cookie
13796  * which is saved in the private segment data for hme segments and
13797  * the ism_map structure for ism segments.
13798  */
13799 hat_region_cookie_t
13800 hat_join_region(struct hat *sfmmup, caddr_t r_saddr, size_t r_size,
13801     void *r_obj, u_offset_t r_objoff, uchar_t r_perm, uchar_t r_pgszc,
13802     hat_rgn_cb_func_t r_cb_function, uint_t flags)
13803 {
13804 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
13805 	uint_t rhash;
13806 	uint_t rid;
13807 	hatlock_t *hatlockp;
13808 	sf_region_t *rgnp;
13809 	sf_region_t *new_rgnp = NULL;
13810 	int i;
13811 	uint16_t *nextidp;
13812 	sf_region_t **freelistp;
13813 	int maxids;
13814 	sf_region_t **rarrp;
13815 	uint16_t *busyrgnsp;
13816 	ulong_t rttecnt;
13817 	uchar_t tteflag;
13818 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
13819 	int text = (r_type == HAT_REGION_TEXT);
13820 
13821 	if (srdp == NULL || r_size == 0) {
13822 		return (HAT_INVALID_REGION_COOKIE);
13823 	}
13824 
13825 	ASSERT(sfmmup != ksfmmup);
13826 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as));
13827 	ASSERT(srdp->srd_refcnt > 0);
13828 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
13829 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
13830 	ASSERT(r_pgszc < mmu_page_sizes);
13831 	if (!IS_P2ALIGNED(r_saddr, TTEBYTES(r_pgszc)) ||
13832 	    !IS_P2ALIGNED(r_size, TTEBYTES(r_pgszc))) {
13833 		panic("hat_join_region: region addr or size is not aligned\n");
13834 	}
13835 
13836 
13837 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
13838 	    SFMMU_REGION_HME;
13839 	/*
13840 	 * Currently only support shared hmes for the read only main text
13841 	 * region.
13842 	 */
13843 	if (r_type == SFMMU_REGION_HME && ((r_obj != srdp->srd_evp) ||
13844 	    (r_perm & PROT_WRITE))) {
13845 		return (HAT_INVALID_REGION_COOKIE);
13846 	}
13847 
13848 	rhash = RGN_HASH_FUNCTION(r_obj);
13849 
13850 	if (r_type == SFMMU_REGION_ISM) {
13851 		nextidp = &srdp->srd_next_ismrid;
13852 		freelistp = &srdp->srd_ismrgnfree;
13853 		maxids = SFMMU_MAX_ISM_REGIONS;
13854 		rarrp = srdp->srd_ismrgnp;
13855 		busyrgnsp = &srdp->srd_ismbusyrgns;
13856 	} else {
13857 		nextidp = &srdp->srd_next_hmerid;
13858 		freelistp = &srdp->srd_hmergnfree;
13859 		maxids = SFMMU_MAX_HME_REGIONS;
13860 		rarrp = srdp->srd_hmergnp;
13861 		busyrgnsp = &srdp->srd_hmebusyrgns;
13862 	}
13863 
13864 	mutex_enter(&srdp->srd_mutex);
13865 
13866 	for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
13867 	    rgnp = rgnp->rgn_hash) {
13868 		if (rgnp->rgn_saddr == r_saddr && rgnp->rgn_size == r_size &&
13869 		    rgnp->rgn_obj == r_obj && rgnp->rgn_objoff == r_objoff &&
13870 		    rgnp->rgn_perm == r_perm && rgnp->rgn_pgszc == r_pgszc) {
13871 			break;
13872 		}
13873 	}
13874 
13875 rfound:
13876 	if (rgnp != NULL) {
13877 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
13878 		ASSERT(rgnp->rgn_cb_function == r_cb_function);
13879 		ASSERT(rgnp->rgn_refcnt >= 0);
13880 		rid = rgnp->rgn_id;
13881 		ASSERT(rid < maxids);
13882 		ASSERT(rarrp[rid] == rgnp);
13883 		ASSERT(rid < *nextidp);
13884 		atomic_inc_32((volatile uint_t *)&rgnp->rgn_refcnt);
13885 		mutex_exit(&srdp->srd_mutex);
13886 		if (new_rgnp != NULL) {
13887 			kmem_cache_free(region_cache, new_rgnp);
13888 		}
13889 		if (r_type == SFMMU_REGION_HME) {
13890 			int myjoin =
13891 			    (sfmmup == astosfmmu(curthread->t_procp->p_as));
13892 
13893 			sfmmu_link_to_hmeregion(sfmmup, rgnp);
13894 			/*
13895 			 * bitmap should be updated after linking sfmmu on
13896 			 * region list so that pageunload() doesn't skip
13897 			 * TSB/TLB flush. As soon as bitmap is updated another
13898 			 * thread in this process can already start accessing
13899 			 * this region.
13900 			 */
13901 			/*
13902 			 * Normally ttecnt accounting is done as part of
13903 			 * pagefault handling. But a process may not take any
13904 			 * pagefaults on shared hmeblks created by some other
13905 			 * process. To compensate for this assume that the
13906 			 * entire region will end up faulted in using
13907 			 * the region's pagesize.
13908 			 *
13909 			 */
13910 			if (r_pgszc > TTE8K) {
13911 				tteflag = 1 << r_pgszc;
13912 				if (disable_large_pages & tteflag) {
13913 					tteflag = 0;
13914 				}
13915 			} else {
13916 				tteflag = 0;
13917 			}
13918 			if (tteflag && !(sfmmup->sfmmu_rtteflags & tteflag)) {
13919 				hatlockp = sfmmu_hat_enter(sfmmup);
13920 				sfmmup->sfmmu_rtteflags |= tteflag;
13921 				sfmmu_hat_exit(hatlockp);
13922 			}
13923 			hatlockp = sfmmu_hat_enter(sfmmup);
13924 
13925 			/*
13926 			 * Preallocate 1/4 of ttecnt's in 8K TSB for >= 4M
13927 			 * region to allow for large page allocation failure.
13928 			 */
13929 			if (r_pgszc >= TTE4M) {
13930 				sfmmup->sfmmu_tsb0_4minflcnt +=
13931 				    r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
13932 			}
13933 
13934 			/* update sfmmu_ttecnt with the shme rgn ttecnt */
13935 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
13936 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
13937 			    rttecnt);
13938 
13939 			if (text && r_pgszc >= TTE4M &&
13940 			    (tteflag || ((disable_large_pages >> TTE4M) &
13941 			    ((1 << (r_pgszc - TTE4M + 1)) - 1))) &&
13942 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
13943 				SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
13944 			}
13945 
13946 			sfmmu_hat_exit(hatlockp);
13947 			/*
13948 			 * On Panther we need to make sure TLB is programmed
13949 			 * to accept 32M/256M pages.  Call
13950 			 * sfmmu_check_page_sizes() now to make sure TLB is
13951 			 * setup before making hmeregions visible to other
13952 			 * threads.
13953 			 */
13954 			sfmmu_check_page_sizes(sfmmup, 1);
13955 			hatlockp = sfmmu_hat_enter(sfmmup);
13956 			SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
13957 
13958 			/*
13959 			 * if context is invalid tsb miss exception code will
13960 			 * call sfmmu_check_page_sizes() and update tsbmiss
13961 			 * area later.
13962 			 */
13963 			kpreempt_disable();
13964 			if (myjoin &&
13965 			    (sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum
13966 			    != INVALID_CONTEXT)) {
13967 				struct tsbmiss *tsbmp;
13968 
13969 				tsbmp = &tsbmiss_area[CPU->cpu_id];
13970 				ASSERT(sfmmup == tsbmp->usfmmup);
13971 				BT_SET(tsbmp->shmermap, rid);
13972 				if (r_pgszc > TTE64K) {
13973 					tsbmp->uhat_rtteflags |= tteflag;
13974 				}
13975 
13976 			}
13977 			kpreempt_enable();
13978 
13979 			sfmmu_hat_exit(hatlockp);
13980 			ASSERT((hat_region_cookie_t)((uint64_t)rid) !=
13981 			    HAT_INVALID_REGION_COOKIE);
13982 		} else {
13983 			hatlockp = sfmmu_hat_enter(sfmmup);
13984 			SF_RGNMAP_ADD(sfmmup->sfmmu_ismregion_map, rid);
13985 			sfmmu_hat_exit(hatlockp);
13986 		}
13987 		ASSERT(rid < maxids);
13988 
13989 		if (r_type == SFMMU_REGION_ISM) {
13990 			sfmmu_find_scd(sfmmup);
13991 		}
13992 		return ((hat_region_cookie_t)((uint64_t)rid));
13993 	}
13994 
13995 	ASSERT(new_rgnp == NULL);
13996 
13997 	if (*busyrgnsp >= maxids) {
13998 		mutex_exit(&srdp->srd_mutex);
13999 		return (HAT_INVALID_REGION_COOKIE);
14000 	}
14001 
14002 	ASSERT(MUTEX_HELD(&srdp->srd_mutex));
14003 	if (*freelistp != NULL) {
14004 		rgnp = *freelistp;
14005 		*freelistp = rgnp->rgn_next;
14006 		ASSERT(rgnp->rgn_id < *nextidp);
14007 		ASSERT(rgnp->rgn_id < maxids);
14008 		ASSERT(rgnp->rgn_flags & SFMMU_REGION_FREE);
14009 		ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK)
14010 		    == r_type);
14011 		ASSERT(rarrp[rgnp->rgn_id] == rgnp);
14012 		ASSERT(rgnp->rgn_hmeflags == 0);
14013 	} else {
14014 		/*
14015 		 * release local locks before memory allocation.
14016 		 */
14017 		mutex_exit(&srdp->srd_mutex);
14018 
14019 		new_rgnp = kmem_cache_alloc(region_cache, KM_SLEEP);
14020 
14021 		mutex_enter(&srdp->srd_mutex);
14022 		for (rgnp = srdp->srd_rgnhash[rhash]; rgnp != NULL;
14023 		    rgnp = rgnp->rgn_hash) {
14024 			if (rgnp->rgn_saddr == r_saddr &&
14025 			    rgnp->rgn_size == r_size &&
14026 			    rgnp->rgn_obj == r_obj &&
14027 			    rgnp->rgn_objoff == r_objoff &&
14028 			    rgnp->rgn_perm == r_perm &&
14029 			    rgnp->rgn_pgszc == r_pgszc) {
14030 				break;
14031 			}
14032 		}
14033 		if (rgnp != NULL) {
14034 			goto rfound;
14035 		}
14036 
14037 		if (*nextidp >= maxids) {
14038 			mutex_exit(&srdp->srd_mutex);
14039 			goto fail;
14040 		}
14041 		rgnp = new_rgnp;
14042 		new_rgnp = NULL;
14043 		rgnp->rgn_id = (*nextidp)++;
14044 		ASSERT(rgnp->rgn_id < maxids);
14045 		ASSERT(rarrp[rgnp->rgn_id] == NULL);
14046 		rarrp[rgnp->rgn_id] = rgnp;
14047 	}
14048 
14049 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14050 	ASSERT(rgnp->rgn_hmeflags == 0);
14051 #ifdef DEBUG
14052 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14053 		ASSERT(rgnp->rgn_ttecnt[i] == 0);
14054 	}
14055 #endif
14056 	rgnp->rgn_saddr = r_saddr;
14057 	rgnp->rgn_size = r_size;
14058 	rgnp->rgn_obj = r_obj;
14059 	rgnp->rgn_objoff = r_objoff;
14060 	rgnp->rgn_perm = r_perm;
14061 	rgnp->rgn_pgszc = r_pgszc;
14062 	rgnp->rgn_flags = r_type;
14063 	rgnp->rgn_refcnt = 0;
14064 	rgnp->rgn_cb_function = r_cb_function;
14065 	rgnp->rgn_hash = srdp->srd_rgnhash[rhash];
14066 	srdp->srd_rgnhash[rhash] = rgnp;
14067 	(*busyrgnsp)++;
14068 	ASSERT(*busyrgnsp <= maxids);
14069 	goto rfound;
14070 
14071 fail:
14072 	ASSERT(new_rgnp != NULL);
14073 	kmem_cache_free(region_cache, new_rgnp);
14074 	return (HAT_INVALID_REGION_COOKIE);
14075 }
14076 
14077 /*
14078  * This function implements the shared context functionality required
14079  * when detaching a segment from an address space. It must be called
14080  * from hat_unshare() for all D(ISM) segments and from segvn_unmap(),
14081  * for segments with a valid region_cookie.
14082  * It will also be called from all seg_vn routines which change a
14083  * segment's attributes such as segvn_setprot(), segvn_setpagesize(),
14084  * segvn_clrszc() & segvn_advise(), as well as in the case of COW fault
14085  * from segvn_fault().
14086  */
14087 void
14088 hat_leave_region(struct hat *sfmmup, hat_region_cookie_t rcookie, uint_t flags)
14089 {
14090 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14091 	sf_scd_t *scdp;
14092 	uint_t rhash;
14093 	uint_t rid = (uint_t)((uint64_t)rcookie);
14094 	hatlock_t *hatlockp = NULL;
14095 	sf_region_t *rgnp;
14096 	sf_region_t **prev_rgnpp;
14097 	sf_region_t *cur_rgnp;
14098 	void *r_obj;
14099 	int i;
14100 	caddr_t	r_saddr;
14101 	caddr_t r_eaddr;
14102 	size_t	r_size;
14103 	uchar_t	r_pgszc;
14104 	uchar_t r_type = flags & HAT_REGION_TYPE_MASK;
14105 
14106 	ASSERT(sfmmup != ksfmmup);
14107 	ASSERT(srdp != NULL);
14108 	ASSERT(srdp->srd_refcnt > 0);
14109 	ASSERT(!(flags & ~HAT_REGION_TYPE_MASK));
14110 	ASSERT(flags == HAT_REGION_TEXT || flags == HAT_REGION_ISM);
14111 	ASSERT(!sfmmup->sfmmu_free || sfmmup->sfmmu_scdp == NULL);
14112 
14113 	r_type = (r_type == HAT_REGION_ISM) ? SFMMU_REGION_ISM :
14114 	    SFMMU_REGION_HME;
14115 
14116 	if (r_type == SFMMU_REGION_ISM) {
14117 		ASSERT(SFMMU_IS_ISMRID_VALID(rid));
14118 		ASSERT(rid < SFMMU_MAX_ISM_REGIONS);
14119 		rgnp = srdp->srd_ismrgnp[rid];
14120 	} else {
14121 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14122 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14123 		rgnp = srdp->srd_hmergnp[rid];
14124 	}
14125 	ASSERT(rgnp != NULL);
14126 	ASSERT(rgnp->rgn_id == rid);
14127 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14128 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14129 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as));
14130 
14131 	if (sfmmup->sfmmu_free) {
14132 		ulong_t rttecnt;
14133 		r_pgszc = rgnp->rgn_pgszc;
14134 		r_size = rgnp->rgn_size;
14135 
14136 		ASSERT(sfmmup->sfmmu_scdp == NULL);
14137 		if (r_type == SFMMU_REGION_ISM) {
14138 			SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14139 		} else {
14140 			/* update shme rgns ttecnt in sfmmu_ttecnt */
14141 			rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14142 			ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14143 
14144 			atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc],
14145 			    -rttecnt);
14146 
14147 			SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14148 		}
14149 	} else if (r_type == SFMMU_REGION_ISM) {
14150 		hatlockp = sfmmu_hat_enter(sfmmup);
14151 		ASSERT(rid < srdp->srd_next_ismrid);
14152 		SF_RGNMAP_DEL(sfmmup->sfmmu_ismregion_map, rid);
14153 		scdp = sfmmup->sfmmu_scdp;
14154 		if (scdp != NULL &&
14155 		    SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid)) {
14156 			sfmmu_leave_scd(sfmmup, r_type);
14157 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14158 		}
14159 		sfmmu_hat_exit(hatlockp);
14160 	} else {
14161 		ulong_t rttecnt;
14162 		r_pgszc = rgnp->rgn_pgszc;
14163 		r_saddr = rgnp->rgn_saddr;
14164 		r_size = rgnp->rgn_size;
14165 		r_eaddr = r_saddr + r_size;
14166 
14167 		ASSERT(r_type == SFMMU_REGION_HME);
14168 		hatlockp = sfmmu_hat_enter(sfmmup);
14169 		ASSERT(rid < srdp->srd_next_hmerid);
14170 		SF_RGNMAP_DEL(sfmmup->sfmmu_hmeregion_map, rid);
14171 
14172 		/*
14173 		 * If region is part of an SCD call sfmmu_leave_scd().
14174 		 * Otherwise if process is not exiting and has valid context
14175 		 * just drop the context on the floor to lose stale TLB
14176 		 * entries and force the update of tsb miss area to reflect
14177 		 * the new region map. After that clean our TSB entries.
14178 		 */
14179 		scdp = sfmmup->sfmmu_scdp;
14180 		if (scdp != NULL &&
14181 		    SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
14182 			sfmmu_leave_scd(sfmmup, r_type);
14183 			ASSERT(sfmmu_hat_lock_held(sfmmup));
14184 		}
14185 		sfmmu_invalidate_ctx(sfmmup);
14186 
14187 		i = TTE8K;
14188 		while (i < mmu_page_sizes) {
14189 			if (rgnp->rgn_ttecnt[i] != 0) {
14190 				sfmmu_unload_tsb_range(sfmmup, r_saddr,
14191 				    r_eaddr, i);
14192 				if (i < TTE4M) {
14193 					i = TTE4M;
14194 					continue;
14195 				} else {
14196 					break;
14197 				}
14198 			}
14199 			i++;
14200 		}
14201 		/* Remove the preallocated 1/4 8k ttecnt for 4M regions. */
14202 		if (r_pgszc >= TTE4M) {
14203 			rttecnt = r_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14204 			ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
14205 			    rttecnt);
14206 			sfmmup->sfmmu_tsb0_4minflcnt -= rttecnt;
14207 		}
14208 
14209 		/* update shme rgns ttecnt in sfmmu_ttecnt */
14210 		rttecnt = r_size >> TTE_PAGE_SHIFT(r_pgszc);
14211 		ASSERT(sfmmup->sfmmu_ttecnt[r_pgszc] >= rttecnt);
14212 		atomic_add_long(&sfmmup->sfmmu_ttecnt[r_pgszc], -rttecnt);
14213 
14214 		sfmmu_hat_exit(hatlockp);
14215 		if (scdp != NULL && sfmmup->sfmmu_scdp == NULL) {
14216 			/* sfmmup left the scd, grow private tsb */
14217 			sfmmu_check_page_sizes(sfmmup, 1);
14218 		} else {
14219 			sfmmu_check_page_sizes(sfmmup, 0);
14220 		}
14221 	}
14222 
14223 	if (r_type == SFMMU_REGION_HME) {
14224 		sfmmu_unlink_from_hmeregion(sfmmup, rgnp);
14225 	}
14226 
14227 	r_obj = rgnp->rgn_obj;
14228 	if (atomic_dec_32_nv((volatile uint_t *)&rgnp->rgn_refcnt)) {
14229 		return;
14230 	}
14231 
14232 	/*
14233 	 * looks like nobody uses this region anymore. Free it.
14234 	 */
14235 	rhash = RGN_HASH_FUNCTION(r_obj);
14236 	mutex_enter(&srdp->srd_mutex);
14237 	for (prev_rgnpp = &srdp->srd_rgnhash[rhash];
14238 	    (cur_rgnp = *prev_rgnpp) != NULL;
14239 	    prev_rgnpp = &cur_rgnp->rgn_hash) {
14240 		if (cur_rgnp == rgnp && cur_rgnp->rgn_refcnt == 0) {
14241 			break;
14242 		}
14243 	}
14244 
14245 	if (cur_rgnp == NULL) {
14246 		mutex_exit(&srdp->srd_mutex);
14247 		return;
14248 	}
14249 
14250 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == r_type);
14251 	*prev_rgnpp = rgnp->rgn_hash;
14252 	if (r_type == SFMMU_REGION_ISM) {
14253 		rgnp->rgn_flags |= SFMMU_REGION_FREE;
14254 		ASSERT(rid < srdp->srd_next_ismrid);
14255 		rgnp->rgn_next = srdp->srd_ismrgnfree;
14256 		srdp->srd_ismrgnfree = rgnp;
14257 		ASSERT(srdp->srd_ismbusyrgns > 0);
14258 		srdp->srd_ismbusyrgns--;
14259 		mutex_exit(&srdp->srd_mutex);
14260 		return;
14261 	}
14262 	mutex_exit(&srdp->srd_mutex);
14263 
14264 	/*
14265 	 * Destroy region's hmeblks.
14266 	 */
14267 	sfmmu_unload_hmeregion(srdp, rgnp);
14268 
14269 	rgnp->rgn_hmeflags = 0;
14270 
14271 	ASSERT(rgnp->rgn_sfmmu_head == NULL);
14272 	ASSERT(rgnp->rgn_id == rid);
14273 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14274 		rgnp->rgn_ttecnt[i] = 0;
14275 	}
14276 	rgnp->rgn_flags |= SFMMU_REGION_FREE;
14277 	mutex_enter(&srdp->srd_mutex);
14278 	ASSERT(rid < srdp->srd_next_hmerid);
14279 	rgnp->rgn_next = srdp->srd_hmergnfree;
14280 	srdp->srd_hmergnfree = rgnp;
14281 	ASSERT(srdp->srd_hmebusyrgns > 0);
14282 	srdp->srd_hmebusyrgns--;
14283 	mutex_exit(&srdp->srd_mutex);
14284 }
14285 
14286 /*
14287  * For now only called for hmeblk regions and not for ISM regions.
14288  */
14289 void
14290 hat_dup_region(struct hat *sfmmup, hat_region_cookie_t rcookie)
14291 {
14292 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14293 	uint_t rid = (uint_t)((uint64_t)rcookie);
14294 	sf_region_t *rgnp;
14295 	sf_rgn_link_t *rlink;
14296 	sf_rgn_link_t *hrlink;
14297 	ulong_t	rttecnt;
14298 
14299 	ASSERT(sfmmup != ksfmmup);
14300 	ASSERT(srdp != NULL);
14301 	ASSERT(srdp->srd_refcnt > 0);
14302 
14303 	ASSERT(rid < srdp->srd_next_hmerid);
14304 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14305 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
14306 
14307 	rgnp = srdp->srd_hmergnp[rid];
14308 	ASSERT(rgnp->rgn_refcnt > 0);
14309 	ASSERT(rgnp->rgn_id == rid);
14310 	ASSERT((rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) == SFMMU_REGION_HME);
14311 	ASSERT(!(rgnp->rgn_flags & SFMMU_REGION_FREE));
14312 
14313 	atomic_inc_32((volatile uint_t *)&rgnp->rgn_refcnt);
14314 
14315 	/* LINTED: constant in conditional context */
14316 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 0);
14317 	ASSERT(rlink != NULL);
14318 	mutex_enter(&rgnp->rgn_mutex);
14319 	ASSERT(rgnp->rgn_sfmmu_head != NULL);
14320 	/* LINTED: constant in conditional context */
14321 	SFMMU_HMERID2RLINKP(rgnp->rgn_sfmmu_head, rid, hrlink, 0, 0);
14322 	ASSERT(hrlink != NULL);
14323 	ASSERT(hrlink->prev == NULL);
14324 	rlink->next = rgnp->rgn_sfmmu_head;
14325 	rlink->prev = NULL;
14326 	hrlink->prev = sfmmup;
14327 	/*
14328 	 * make sure rlink's next field is correct
14329 	 * before making this link visible.
14330 	 */
14331 	membar_stst();
14332 	rgnp->rgn_sfmmu_head = sfmmup;
14333 	mutex_exit(&rgnp->rgn_mutex);
14334 
14335 	/* update sfmmu_ttecnt with the shme rgn ttecnt */
14336 	rttecnt = rgnp->rgn_size >> TTE_PAGE_SHIFT(rgnp->rgn_pgszc);
14337 	atomic_add_long(&sfmmup->sfmmu_ttecnt[rgnp->rgn_pgszc], rttecnt);
14338 	/* update tsb0 inflation count */
14339 	if (rgnp->rgn_pgszc >= TTE4M) {
14340 		sfmmup->sfmmu_tsb0_4minflcnt +=
14341 		    rgnp->rgn_size >> (TTE_PAGE_SHIFT(TTE8K) + 2);
14342 	}
14343 	/*
14344 	 * Update regionid bitmask without hat lock since no other thread
14345 	 * can update this region bitmask right now.
14346 	 */
14347 	SF_RGNMAP_ADD(sfmmup->sfmmu_hmeregion_map, rid);
14348 }
14349 
14350 /* ARGSUSED */
14351 static int
14352 sfmmu_rgncache_constructor(void *buf, void *cdrarg, int kmflags)
14353 {
14354 	sf_region_t *rgnp = (sf_region_t *)buf;
14355 	bzero(buf, sizeof (*rgnp));
14356 
14357 	mutex_init(&rgnp->rgn_mutex, NULL, MUTEX_DEFAULT, NULL);
14358 
14359 	return (0);
14360 }
14361 
14362 /* ARGSUSED */
14363 static void
14364 sfmmu_rgncache_destructor(void *buf, void *cdrarg)
14365 {
14366 	sf_region_t *rgnp = (sf_region_t *)buf;
14367 	mutex_destroy(&rgnp->rgn_mutex);
14368 }
14369 
14370 static int
14371 sfrgnmap_isnull(sf_region_map_t *map)
14372 {
14373 	int i;
14374 
14375 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14376 		if (map->bitmap[i] != 0) {
14377 			return (0);
14378 		}
14379 	}
14380 	return (1);
14381 }
14382 
14383 static int
14384 sfhmergnmap_isnull(sf_hmeregion_map_t *map)
14385 {
14386 	int i;
14387 
14388 	for (i = 0; i < SFMMU_HMERGNMAP_WORDS; i++) {
14389 		if (map->bitmap[i] != 0) {
14390 			return (0);
14391 		}
14392 	}
14393 	return (1);
14394 }
14395 
14396 #ifdef DEBUG
14397 static void
14398 check_scd_sfmmu_list(sfmmu_t **headp, sfmmu_t *sfmmup, int onlist)
14399 {
14400 	sfmmu_t *sp;
14401 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14402 
14403 	for (sp = *headp; sp != NULL; sp = sp->sfmmu_scd_link.next) {
14404 		ASSERT(srdp == sp->sfmmu_srdp);
14405 		if (sp == sfmmup) {
14406 			if (onlist) {
14407 				return;
14408 			} else {
14409 				panic("shctx: sfmmu 0x%p found on scd"
14410 				    "list 0x%p", (void *)sfmmup,
14411 				    (void *)*headp);
14412 			}
14413 		}
14414 	}
14415 	if (onlist) {
14416 		panic("shctx: sfmmu 0x%p not found on scd list 0x%p",
14417 		    (void *)sfmmup, (void *)*headp);
14418 	} else {
14419 		return;
14420 	}
14421 }
14422 #else /* DEBUG */
14423 #define	check_scd_sfmmu_list(headp, sfmmup, onlist)
14424 #endif /* DEBUG */
14425 
14426 /*
14427  * Removes an sfmmu from the SCD sfmmu list.
14428  */
14429 static void
14430 sfmmu_from_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14431 {
14432 	ASSERT(sfmmup->sfmmu_srdp != NULL);
14433 	check_scd_sfmmu_list(headp, sfmmup, 1);
14434 	if (sfmmup->sfmmu_scd_link.prev != NULL) {
14435 		ASSERT(*headp != sfmmup);
14436 		sfmmup->sfmmu_scd_link.prev->sfmmu_scd_link.next =
14437 		    sfmmup->sfmmu_scd_link.next;
14438 	} else {
14439 		ASSERT(*headp == sfmmup);
14440 		*headp = sfmmup->sfmmu_scd_link.next;
14441 	}
14442 	if (sfmmup->sfmmu_scd_link.next != NULL) {
14443 		sfmmup->sfmmu_scd_link.next->sfmmu_scd_link.prev =
14444 		    sfmmup->sfmmu_scd_link.prev;
14445 	}
14446 }
14447 
14448 
14449 /*
14450  * Adds an sfmmu to the start of the queue.
14451  */
14452 static void
14453 sfmmu_to_scd_list(sfmmu_t **headp, sfmmu_t *sfmmup)
14454 {
14455 	check_scd_sfmmu_list(headp, sfmmup, 0);
14456 	sfmmup->sfmmu_scd_link.prev = NULL;
14457 	sfmmup->sfmmu_scd_link.next = *headp;
14458 	if (*headp != NULL)
14459 		(*headp)->sfmmu_scd_link.prev = sfmmup;
14460 	*headp = sfmmup;
14461 }
14462 
14463 /*
14464  * Remove an scd from the start of the queue.
14465  */
14466 static void
14467 sfmmu_remove_scd(sf_scd_t **headp, sf_scd_t *scdp)
14468 {
14469 	if (scdp->scd_prev != NULL) {
14470 		ASSERT(*headp != scdp);
14471 		scdp->scd_prev->scd_next = scdp->scd_next;
14472 	} else {
14473 		ASSERT(*headp == scdp);
14474 		*headp = scdp->scd_next;
14475 	}
14476 
14477 	if (scdp->scd_next != NULL) {
14478 		scdp->scd_next->scd_prev = scdp->scd_prev;
14479 	}
14480 }
14481 
14482 /*
14483  * Add an scd to the start of the queue.
14484  */
14485 static void
14486 sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *scdp)
14487 {
14488 	scdp->scd_prev = NULL;
14489 	scdp->scd_next = *headp;
14490 	if (*headp != NULL) {
14491 		(*headp)->scd_prev = scdp;
14492 	}
14493 	*headp = scdp;
14494 }
14495 
14496 static int
14497 sfmmu_alloc_scd_tsbs(sf_srd_t *srdp, sf_scd_t *scdp)
14498 {
14499 	uint_t rid;
14500 	uint_t i;
14501 	uint_t j;
14502 	ulong_t w;
14503 	sf_region_t *rgnp;
14504 	ulong_t tte8k_cnt = 0;
14505 	ulong_t tte4m_cnt = 0;
14506 	uint_t tsb_szc;
14507 	sfmmu_t *scsfmmup = scdp->scd_sfmmup;
14508 	sfmmu_t	*ism_hatid;
14509 	struct tsb_info *newtsb;
14510 	int szc;
14511 
14512 	ASSERT(srdp != NULL);
14513 
14514 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14515 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14516 			continue;
14517 		}
14518 		j = 0;
14519 		while (w) {
14520 			if (!(w & 0x1)) {
14521 				j++;
14522 				w >>= 1;
14523 				continue;
14524 			}
14525 			rid = (i << BT_ULSHIFT) | j;
14526 			j++;
14527 			w >>= 1;
14528 
14529 			if (rid < SFMMU_MAX_HME_REGIONS) {
14530 				rgnp = srdp->srd_hmergnp[rid];
14531 				ASSERT(rgnp->rgn_id == rid);
14532 				ASSERT(rgnp->rgn_refcnt > 0);
14533 
14534 				if (rgnp->rgn_pgszc < TTE4M) {
14535 					tte8k_cnt += rgnp->rgn_size >>
14536 					    TTE_PAGE_SHIFT(TTE8K);
14537 				} else {
14538 					ASSERT(rgnp->rgn_pgszc >= TTE4M);
14539 					tte4m_cnt += rgnp->rgn_size >>
14540 					    TTE_PAGE_SHIFT(TTE4M);
14541 					/*
14542 					 * Inflate SCD tsb0 by preallocating
14543 					 * 1/4 8k ttecnt for 4M regions to
14544 					 * allow for lgpg alloc failure.
14545 					 */
14546 					tte8k_cnt += rgnp->rgn_size >>
14547 					    (TTE_PAGE_SHIFT(TTE8K) + 2);
14548 				}
14549 			} else {
14550 				rid -= SFMMU_MAX_HME_REGIONS;
14551 				rgnp = srdp->srd_ismrgnp[rid];
14552 				ASSERT(rgnp->rgn_id == rid);
14553 				ASSERT(rgnp->rgn_refcnt > 0);
14554 
14555 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14556 				ASSERT(ism_hatid->sfmmu_ismhat);
14557 
14558 				for (szc = 0; szc < TTE4M; szc++) {
14559 					tte8k_cnt +=
14560 					    ism_hatid->sfmmu_ttecnt[szc] <<
14561 					    TTE_BSZS_SHIFT(szc);
14562 				}
14563 
14564 				ASSERT(rgnp->rgn_pgszc >= TTE4M);
14565 				if (rgnp->rgn_pgszc >= TTE4M) {
14566 					tte4m_cnt += rgnp->rgn_size >>
14567 					    TTE_PAGE_SHIFT(TTE4M);
14568 				}
14569 			}
14570 		}
14571 	}
14572 
14573 	tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
14574 
14575 	/* Allocate both the SCD TSBs here. */
14576 	if (sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14577 	    tsb_szc, TSB8K|TSB64K|TSB512K, TSB_ALLOC, scsfmmup) &&
14578 	    (tsb_szc <= TSB_4M_SZCODE ||
14579 	    sfmmu_tsbinfo_alloc(&scsfmmup->sfmmu_tsb,
14580 	    TSB_4M_SZCODE, TSB8K|TSB64K|TSB512K,
14581 	    TSB_ALLOC, scsfmmup))) {
14582 
14583 		SFMMU_STAT(sf_scd_1sttsb_allocfail);
14584 		return (TSB_ALLOCFAIL);
14585 	} else {
14586 		scsfmmup->sfmmu_tsb->tsb_flags |= TSB_SHAREDCTX;
14587 
14588 		if (tte4m_cnt) {
14589 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
14590 			if (sfmmu_tsbinfo_alloc(&newtsb, tsb_szc,
14591 			    TSB4M|TSB32M|TSB256M, TSB_ALLOC, scsfmmup) &&
14592 			    (tsb_szc <= TSB_4M_SZCODE ||
14593 			    sfmmu_tsbinfo_alloc(&newtsb, TSB_4M_SZCODE,
14594 			    TSB4M|TSB32M|TSB256M,
14595 			    TSB_ALLOC, scsfmmup))) {
14596 				/*
14597 				 * If we fail to allocate the 2nd shared tsb,
14598 				 * just free the 1st tsb, return failure.
14599 				 */
14600 				sfmmu_tsbinfo_free(scsfmmup->sfmmu_tsb);
14601 				SFMMU_STAT(sf_scd_2ndtsb_allocfail);
14602 				return (TSB_ALLOCFAIL);
14603 			} else {
14604 				ASSERT(scsfmmup->sfmmu_tsb->tsb_next == NULL);
14605 				newtsb->tsb_flags |= TSB_SHAREDCTX;
14606 				scsfmmup->sfmmu_tsb->tsb_next = newtsb;
14607 				SFMMU_STAT(sf_scd_2ndtsb_alloc);
14608 			}
14609 		}
14610 		SFMMU_STAT(sf_scd_1sttsb_alloc);
14611 	}
14612 	return (TSB_SUCCESS);
14613 }
14614 
14615 static void
14616 sfmmu_free_scd_tsbs(sfmmu_t *scd_sfmmu)
14617 {
14618 	while (scd_sfmmu->sfmmu_tsb != NULL) {
14619 		struct tsb_info *next = scd_sfmmu->sfmmu_tsb->tsb_next;
14620 		sfmmu_tsbinfo_free(scd_sfmmu->sfmmu_tsb);
14621 		scd_sfmmu->sfmmu_tsb = next;
14622 	}
14623 }
14624 
14625 /*
14626  * Link the sfmmu onto the hme region list.
14627  */
14628 void
14629 sfmmu_link_to_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14630 {
14631 	uint_t rid;
14632 	sf_rgn_link_t *rlink;
14633 	sfmmu_t *head;
14634 	sf_rgn_link_t *hrlink;
14635 
14636 	rid = rgnp->rgn_id;
14637 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14638 
14639 	/* LINTED: constant in conditional context */
14640 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 1, 1);
14641 	ASSERT(rlink != NULL);
14642 	mutex_enter(&rgnp->rgn_mutex);
14643 	if ((head = rgnp->rgn_sfmmu_head) == NULL) {
14644 		rlink->next = NULL;
14645 		rlink->prev = NULL;
14646 		/*
14647 		 * make sure rlink's next field is NULL
14648 		 * before making this link visible.
14649 		 */
14650 		membar_stst();
14651 		rgnp->rgn_sfmmu_head = sfmmup;
14652 	} else {
14653 		/* LINTED: constant in conditional context */
14654 		SFMMU_HMERID2RLINKP(head, rid, hrlink, 0, 0);
14655 		ASSERT(hrlink != NULL);
14656 		ASSERT(hrlink->prev == NULL);
14657 		rlink->next = head;
14658 		rlink->prev = NULL;
14659 		hrlink->prev = sfmmup;
14660 		/*
14661 		 * make sure rlink's next field is correct
14662 		 * before making this link visible.
14663 		 */
14664 		membar_stst();
14665 		rgnp->rgn_sfmmu_head = sfmmup;
14666 	}
14667 	mutex_exit(&rgnp->rgn_mutex);
14668 }
14669 
14670 /*
14671  * Unlink the sfmmu from the hme region list.
14672  */
14673 void
14674 sfmmu_unlink_from_hmeregion(sfmmu_t *sfmmup, sf_region_t *rgnp)
14675 {
14676 	uint_t rid;
14677 	sf_rgn_link_t *rlink;
14678 
14679 	rid = rgnp->rgn_id;
14680 	ASSERT(SFMMU_IS_SHMERID_VALID(rid));
14681 
14682 	/* LINTED: constant in conditional context */
14683 	SFMMU_HMERID2RLINKP(sfmmup, rid, rlink, 0, 0);
14684 	ASSERT(rlink != NULL);
14685 	mutex_enter(&rgnp->rgn_mutex);
14686 	if (rgnp->rgn_sfmmu_head == sfmmup) {
14687 		sfmmu_t *next = rlink->next;
14688 		rgnp->rgn_sfmmu_head = next;
14689 		/*
14690 		 * if we are stopped by xc_attention() after this
14691 		 * point the forward link walking in
14692 		 * sfmmu_rgntlb_demap() will work correctly since the
14693 		 * head correctly points to the next element.
14694 		 */
14695 		membar_stst();
14696 		rlink->next = NULL;
14697 		ASSERT(rlink->prev == NULL);
14698 		if (next != NULL) {
14699 			sf_rgn_link_t *nrlink;
14700 			/* LINTED: constant in conditional context */
14701 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14702 			ASSERT(nrlink != NULL);
14703 			ASSERT(nrlink->prev == sfmmup);
14704 			nrlink->prev = NULL;
14705 		}
14706 	} else {
14707 		sfmmu_t *next = rlink->next;
14708 		sfmmu_t *prev = rlink->prev;
14709 		sf_rgn_link_t *prlink;
14710 
14711 		ASSERT(prev != NULL);
14712 		/* LINTED: constant in conditional context */
14713 		SFMMU_HMERID2RLINKP(prev, rid, prlink, 0, 0);
14714 		ASSERT(prlink != NULL);
14715 		ASSERT(prlink->next == sfmmup);
14716 		prlink->next = next;
14717 		/*
14718 		 * if we are stopped by xc_attention()
14719 		 * after this point the forward link walking
14720 		 * will work correctly since the prev element
14721 		 * correctly points to the next element.
14722 		 */
14723 		membar_stst();
14724 		rlink->next = NULL;
14725 		rlink->prev = NULL;
14726 		if (next != NULL) {
14727 			sf_rgn_link_t *nrlink;
14728 			/* LINTED: constant in conditional context */
14729 			SFMMU_HMERID2RLINKP(next, rid, nrlink, 0, 0);
14730 			ASSERT(nrlink != NULL);
14731 			ASSERT(nrlink->prev == sfmmup);
14732 			nrlink->prev = prev;
14733 		}
14734 	}
14735 	mutex_exit(&rgnp->rgn_mutex);
14736 }
14737 
14738 /*
14739  * Link scd sfmmu onto ism or hme region list for each region in the
14740  * scd region map.
14741  */
14742 void
14743 sfmmu_link_scd_to_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14744 {
14745 	uint_t rid;
14746 	uint_t i;
14747 	uint_t j;
14748 	ulong_t w;
14749 	sf_region_t *rgnp;
14750 	sfmmu_t *scsfmmup;
14751 
14752 	scsfmmup = scdp->scd_sfmmup;
14753 	ASSERT(scsfmmup->sfmmu_scdhat);
14754 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14755 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14756 			continue;
14757 		}
14758 		j = 0;
14759 		while (w) {
14760 			if (!(w & 0x1)) {
14761 				j++;
14762 				w >>= 1;
14763 				continue;
14764 			}
14765 			rid = (i << BT_ULSHIFT) | j;
14766 			j++;
14767 			w >>= 1;
14768 
14769 			if (rid < SFMMU_MAX_HME_REGIONS) {
14770 				rgnp = srdp->srd_hmergnp[rid];
14771 				ASSERT(rgnp->rgn_id == rid);
14772 				ASSERT(rgnp->rgn_refcnt > 0);
14773 				sfmmu_link_to_hmeregion(scsfmmup, rgnp);
14774 			} else {
14775 				sfmmu_t *ism_hatid = NULL;
14776 				ism_ment_t *ism_ment;
14777 				rid -= SFMMU_MAX_HME_REGIONS;
14778 				rgnp = srdp->srd_ismrgnp[rid];
14779 				ASSERT(rgnp->rgn_id == rid);
14780 				ASSERT(rgnp->rgn_refcnt > 0);
14781 
14782 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14783 				ASSERT(ism_hatid->sfmmu_ismhat);
14784 				ism_ment = &scdp->scd_ism_links[rid];
14785 				ism_ment->iment_hat = scsfmmup;
14786 				ism_ment->iment_base_va = rgnp->rgn_saddr;
14787 				mutex_enter(&ism_mlist_lock);
14788 				iment_add(ism_ment, ism_hatid);
14789 				mutex_exit(&ism_mlist_lock);
14790 
14791 			}
14792 		}
14793 	}
14794 }
14795 /*
14796  * Unlink scd sfmmu from ism or hme region list for each region in the
14797  * scd region map.
14798  */
14799 void
14800 sfmmu_unlink_scd_from_regions(sf_srd_t *srdp, sf_scd_t *scdp)
14801 {
14802 	uint_t rid;
14803 	uint_t i;
14804 	uint_t j;
14805 	ulong_t w;
14806 	sf_region_t *rgnp;
14807 	sfmmu_t *scsfmmup;
14808 
14809 	scsfmmup = scdp->scd_sfmmup;
14810 	for (i = 0; i < SFMMU_RGNMAP_WORDS; i++) {
14811 		if ((w = scdp->scd_region_map.bitmap[i]) == 0) {
14812 			continue;
14813 		}
14814 		j = 0;
14815 		while (w) {
14816 			if (!(w & 0x1)) {
14817 				j++;
14818 				w >>= 1;
14819 				continue;
14820 			}
14821 			rid = (i << BT_ULSHIFT) | j;
14822 			j++;
14823 			w >>= 1;
14824 
14825 			if (rid < SFMMU_MAX_HME_REGIONS) {
14826 				rgnp = srdp->srd_hmergnp[rid];
14827 				ASSERT(rgnp->rgn_id == rid);
14828 				ASSERT(rgnp->rgn_refcnt > 0);
14829 				sfmmu_unlink_from_hmeregion(scsfmmup,
14830 				    rgnp);
14831 
14832 			} else {
14833 				sfmmu_t *ism_hatid = NULL;
14834 				ism_ment_t *ism_ment;
14835 				rid -= SFMMU_MAX_HME_REGIONS;
14836 				rgnp = srdp->srd_ismrgnp[rid];
14837 				ASSERT(rgnp->rgn_id == rid);
14838 				ASSERT(rgnp->rgn_refcnt > 0);
14839 
14840 				ism_hatid = (sfmmu_t *)rgnp->rgn_obj;
14841 				ASSERT(ism_hatid->sfmmu_ismhat);
14842 				ism_ment = &scdp->scd_ism_links[rid];
14843 				ASSERT(ism_ment->iment_hat == scdp->scd_sfmmup);
14844 				ASSERT(ism_ment->iment_base_va ==
14845 				    rgnp->rgn_saddr);
14846 				mutex_enter(&ism_mlist_lock);
14847 				iment_sub(ism_ment, ism_hatid);
14848 				mutex_exit(&ism_mlist_lock);
14849 
14850 			}
14851 		}
14852 	}
14853 }
14854 /*
14855  * Allocates and initialises a new SCD structure, this is called with
14856  * the srd_scd_mutex held and returns with the reference count
14857  * initialised to 1.
14858  */
14859 static sf_scd_t *
14860 sfmmu_alloc_scd(sf_srd_t *srdp, sf_region_map_t *new_map)
14861 {
14862 	sf_scd_t *new_scdp;
14863 	sfmmu_t *scsfmmup;
14864 	int i;
14865 
14866 	ASSERT(MUTEX_HELD(&srdp->srd_scd_mutex));
14867 	new_scdp = kmem_cache_alloc(scd_cache, KM_SLEEP);
14868 
14869 	scsfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
14870 	new_scdp->scd_sfmmup = scsfmmup;
14871 	scsfmmup->sfmmu_srdp = srdp;
14872 	scsfmmup->sfmmu_scdp = new_scdp;
14873 	scsfmmup->sfmmu_tsb0_4minflcnt = 0;
14874 	scsfmmup->sfmmu_scdhat = 1;
14875 	CPUSET_ALL(scsfmmup->sfmmu_cpusran);
14876 	bzero(scsfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
14877 
14878 	ASSERT(max_mmu_ctxdoms > 0);
14879 	for (i = 0; i < max_mmu_ctxdoms; i++) {
14880 		scsfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
14881 		scsfmmup->sfmmu_ctxs[i].gnum = 0;
14882 	}
14883 
14884 	for (i = 0; i < MMU_PAGE_SIZES; i++) {
14885 		new_scdp->scd_rttecnt[i] = 0;
14886 	}
14887 
14888 	new_scdp->scd_region_map = *new_map;
14889 	new_scdp->scd_refcnt = 1;
14890 	if (sfmmu_alloc_scd_tsbs(srdp, new_scdp) != TSB_SUCCESS) {
14891 		kmem_cache_free(scd_cache, new_scdp);
14892 		kmem_cache_free(sfmmuid_cache, scsfmmup);
14893 		return (NULL);
14894 	}
14895 	if (&mmu_init_scd) {
14896 		mmu_init_scd(new_scdp);
14897 	}
14898 	return (new_scdp);
14899 }
14900 
14901 /*
14902  * The first phase of a process joining an SCD. The hat structure is
14903  * linked to the SCD queue and then the HAT_JOIN_SCD sfmmu flag is set
14904  * and a cross-call with context invalidation is used to cause the
14905  * remaining work to be carried out in the sfmmu_tsbmiss_exception()
14906  * routine.
14907  */
14908 static void
14909 sfmmu_join_scd(sf_scd_t *scdp, sfmmu_t *sfmmup)
14910 {
14911 	hatlock_t *hatlockp;
14912 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
14913 	int i;
14914 	sf_scd_t *old_scdp;
14915 
14916 	ASSERT(srdp != NULL);
14917 	ASSERT(scdp != NULL);
14918 	ASSERT(scdp->scd_refcnt > 0);
14919 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as));
14920 
14921 	if ((old_scdp = sfmmup->sfmmu_scdp) != NULL) {
14922 		ASSERT(old_scdp != scdp);
14923 
14924 		mutex_enter(&old_scdp->scd_mutex);
14925 		sfmmu_from_scd_list(&old_scdp->scd_sf_list, sfmmup);
14926 		mutex_exit(&old_scdp->scd_mutex);
14927 		/*
14928 		 * sfmmup leaves the old scd. Update sfmmu_ttecnt to
14929 		 * include the shme rgn ttecnt for rgns that
14930 		 * were in the old SCD
14931 		 */
14932 		for (i = 0; i < mmu_page_sizes; i++) {
14933 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
14934 			    old_scdp->scd_rttecnt[i]);
14935 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
14936 			    sfmmup->sfmmu_scdrttecnt[i]);
14937 		}
14938 	}
14939 
14940 	/*
14941 	 * Move sfmmu to the scd lists.
14942 	 */
14943 	mutex_enter(&scdp->scd_mutex);
14944 	sfmmu_to_scd_list(&scdp->scd_sf_list, sfmmup);
14945 	mutex_exit(&scdp->scd_mutex);
14946 	SF_SCD_INCR_REF(scdp);
14947 
14948 	hatlockp = sfmmu_hat_enter(sfmmup);
14949 	/*
14950 	 * For a multi-thread process, we must stop
14951 	 * all the other threads before joining the scd.
14952 	 */
14953 
14954 	SFMMU_FLAGS_SET(sfmmup, HAT_JOIN_SCD);
14955 
14956 	sfmmu_invalidate_ctx(sfmmup);
14957 	sfmmup->sfmmu_scdp = scdp;
14958 
14959 	/*
14960 	 * Copy scd_rttecnt into sfmmup's sfmmu_scdrttecnt, and update
14961 	 * sfmmu_ttecnt to not include the rgn ttecnt just joined in SCD.
14962 	 */
14963 	for (i = 0; i < mmu_page_sizes; i++) {
14964 		sfmmup->sfmmu_scdrttecnt[i] = scdp->scd_rttecnt[i];
14965 		ASSERT(sfmmup->sfmmu_ttecnt[i] >= scdp->scd_rttecnt[i]);
14966 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
14967 		    -sfmmup->sfmmu_scdrttecnt[i]);
14968 	}
14969 	/* update tsb0 inflation count */
14970 	if (old_scdp != NULL) {
14971 		sfmmup->sfmmu_tsb0_4minflcnt +=
14972 		    old_scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
14973 	}
14974 	ASSERT(sfmmup->sfmmu_tsb0_4minflcnt >=
14975 	    scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt);
14976 	sfmmup->sfmmu_tsb0_4minflcnt -= scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
14977 
14978 	sfmmu_hat_exit(hatlockp);
14979 
14980 	if (old_scdp != NULL) {
14981 		SF_SCD_DECR_REF(srdp, old_scdp);
14982 	}
14983 
14984 }
14985 
14986 /*
14987  * This routine is called by a process to become part of an SCD. It is called
14988  * from sfmmu_tsbmiss_exception() once most of the initial work has been
14989  * done by sfmmu_join_scd(). This routine must not drop the hat lock.
14990  */
14991 static void
14992 sfmmu_finish_join_scd(sfmmu_t *sfmmup)
14993 {
14994 	struct tsb_info	*tsbinfop;
14995 
14996 	ASSERT(sfmmu_hat_lock_held(sfmmup));
14997 	ASSERT(sfmmup->sfmmu_scdp != NULL);
14998 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD));
14999 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15000 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ALLCTX_INVALID));
15001 
15002 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
15003 	    tsbinfop = tsbinfop->tsb_next) {
15004 		if (tsbinfop->tsb_flags & TSB_SWAPPED) {
15005 			continue;
15006 		}
15007 		ASSERT(!(tsbinfop->tsb_flags & TSB_RELOC_FLAG));
15008 
15009 		sfmmu_inv_tsb(tsbinfop->tsb_va,
15010 		    TSB_BYTES(tsbinfop->tsb_szc));
15011 	}
15012 
15013 	/* Set HAT_CTX1_FLAG for all SCD ISMs */
15014 	sfmmu_ism_hatflags(sfmmup, 1);
15015 
15016 	SFMMU_STAT(sf_join_scd);
15017 }
15018 
15019 /*
15020  * This routine is called in order to check if there is an SCD which matches
15021  * the process's region map if not then a new SCD may be created.
15022  */
15023 static void
15024 sfmmu_find_scd(sfmmu_t *sfmmup)
15025 {
15026 	sf_srd_t *srdp = sfmmup->sfmmu_srdp;
15027 	sf_scd_t *scdp, *new_scdp;
15028 	int ret;
15029 
15030 	ASSERT(srdp != NULL);
15031 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as));
15032 
15033 	mutex_enter(&srdp->srd_scd_mutex);
15034 	for (scdp = srdp->srd_scdp; scdp != NULL;
15035 	    scdp = scdp->scd_next) {
15036 		SF_RGNMAP_EQUAL(&scdp->scd_region_map,
15037 		    &sfmmup->sfmmu_region_map, ret);
15038 		if (ret == 1) {
15039 			SF_SCD_INCR_REF(scdp);
15040 			mutex_exit(&srdp->srd_scd_mutex);
15041 			sfmmu_join_scd(scdp, sfmmup);
15042 			ASSERT(scdp->scd_refcnt >= 2);
15043 			atomic_dec_32((volatile uint32_t *)&scdp->scd_refcnt);
15044 			return;
15045 		} else {
15046 			/*
15047 			 * If the sfmmu region map is a subset of the scd
15048 			 * region map, then the assumption is that this process
15049 			 * will continue attaching to ISM segments until the
15050 			 * region maps are equal.
15051 			 */
15052 			SF_RGNMAP_IS_SUBSET(&scdp->scd_region_map,
15053 			    &sfmmup->sfmmu_region_map, ret);
15054 			if (ret == 1) {
15055 				mutex_exit(&srdp->srd_scd_mutex);
15056 				return;
15057 			}
15058 		}
15059 	}
15060 
15061 	ASSERT(scdp == NULL);
15062 	/*
15063 	 * No matching SCD has been found, create a new one.
15064 	 */
15065 	if ((new_scdp = sfmmu_alloc_scd(srdp, &sfmmup->sfmmu_region_map)) ==
15066 	    NULL) {
15067 		mutex_exit(&srdp->srd_scd_mutex);
15068 		return;
15069 	}
15070 
15071 	/*
15072 	 * sfmmu_alloc_scd() returns with a ref count of 1 on the scd.
15073 	 */
15074 
15075 	/* Set scd_rttecnt for shme rgns in SCD */
15076 	sfmmu_set_scd_rttecnt(srdp, new_scdp);
15077 
15078 	/*
15079 	 * Link scd onto srd_scdp list and scd sfmmu onto region/iment lists.
15080 	 */
15081 	sfmmu_link_scd_to_regions(srdp, new_scdp);
15082 	sfmmu_add_scd(&srdp->srd_scdp, new_scdp);
15083 	SFMMU_STAT_ADD(sf_create_scd, 1);
15084 
15085 	mutex_exit(&srdp->srd_scd_mutex);
15086 	sfmmu_join_scd(new_scdp, sfmmup);
15087 	ASSERT(new_scdp->scd_refcnt >= 2);
15088 	atomic_dec_32((volatile uint32_t *)&new_scdp->scd_refcnt);
15089 }
15090 
15091 /*
15092  * This routine is called by a process to remove itself from an SCD. It is
15093  * either called when the processes has detached from a segment or from
15094  * hat_free_start() as a result of calling exit.
15095  */
15096 static void
15097 sfmmu_leave_scd(sfmmu_t *sfmmup, uchar_t r_type)
15098 {
15099 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15100 	sf_srd_t *srdp =  sfmmup->sfmmu_srdp;
15101 	hatlock_t *hatlockp = TSB_HASH(sfmmup);
15102 	int i;
15103 
15104 	ASSERT(scdp != NULL);
15105 	ASSERT(srdp != NULL);
15106 
15107 	if (sfmmup->sfmmu_free) {
15108 		/*
15109 		 * If the process is part of an SCD the sfmmu is unlinked
15110 		 * from scd_sf_list.
15111 		 */
15112 		mutex_enter(&scdp->scd_mutex);
15113 		sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15114 		mutex_exit(&scdp->scd_mutex);
15115 		/*
15116 		 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15117 		 * are about to leave the SCD
15118 		 */
15119 		for (i = 0; i < mmu_page_sizes; i++) {
15120 			ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15121 			    scdp->scd_rttecnt[i]);
15122 			atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15123 			    sfmmup->sfmmu_scdrttecnt[i]);
15124 			sfmmup->sfmmu_scdrttecnt[i] = 0;
15125 		}
15126 		sfmmup->sfmmu_scdp = NULL;
15127 
15128 		SF_SCD_DECR_REF(srdp, scdp);
15129 		return;
15130 	}
15131 
15132 	ASSERT(r_type != SFMMU_REGION_ISM ||
15133 	    SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15134 	ASSERT(scdp->scd_refcnt);
15135 	ASSERT(!sfmmup->sfmmu_free);
15136 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15137 	ASSERT(AS_LOCK_HELD(sfmmup->sfmmu_as));
15138 
15139 	/*
15140 	 * Wait for ISM maps to be updated.
15141 	 */
15142 	if (r_type != SFMMU_REGION_ISM) {
15143 		while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY) &&
15144 		    sfmmup->sfmmu_scdp != NULL) {
15145 			cv_wait(&sfmmup->sfmmu_tsb_cv,
15146 			    HATLOCK_MUTEXP(hatlockp));
15147 		}
15148 
15149 		if (sfmmup->sfmmu_scdp == NULL) {
15150 			sfmmu_hat_exit(hatlockp);
15151 			return;
15152 		}
15153 		SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
15154 	}
15155 
15156 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_JOIN_SCD)) {
15157 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_JOIN_SCD);
15158 		/*
15159 		 * Since HAT_JOIN_SCD was set our context
15160 		 * is still invalid.
15161 		 */
15162 	} else {
15163 		/*
15164 		 * For a multi-thread process, we must stop
15165 		 * all the other threads before leaving the scd.
15166 		 */
15167 
15168 		sfmmu_invalidate_ctx(sfmmup);
15169 	}
15170 
15171 	/* Clear all the rid's for ISM, delete flags, etc */
15172 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
15173 	sfmmu_ism_hatflags(sfmmup, 0);
15174 
15175 	/*
15176 	 * Update sfmmu_ttecnt to include the rgn ttecnt for rgns that
15177 	 * are in SCD before this sfmmup leaves the SCD.
15178 	 */
15179 	for (i = 0; i < mmu_page_sizes; i++) {
15180 		ASSERT(sfmmup->sfmmu_scdrttecnt[i] ==
15181 		    scdp->scd_rttecnt[i]);
15182 		atomic_add_long(&sfmmup->sfmmu_ttecnt[i],
15183 		    sfmmup->sfmmu_scdrttecnt[i]);
15184 		sfmmup->sfmmu_scdrttecnt[i] = 0;
15185 		/* update ismttecnt to include SCD ism before hat leaves SCD */
15186 		sfmmup->sfmmu_ismttecnt[i] += sfmmup->sfmmu_scdismttecnt[i];
15187 		sfmmup->sfmmu_scdismttecnt[i] = 0;
15188 	}
15189 	/* update tsb0 inflation count */
15190 	sfmmup->sfmmu_tsb0_4minflcnt += scdp->scd_sfmmup->sfmmu_tsb0_4minflcnt;
15191 
15192 	if (r_type != SFMMU_REGION_ISM) {
15193 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
15194 	}
15195 	sfmmup->sfmmu_scdp = NULL;
15196 
15197 	sfmmu_hat_exit(hatlockp);
15198 
15199 	/*
15200 	 * Unlink sfmmu from scd_sf_list this can be done without holding
15201 	 * the hat lock as we hold the sfmmu_as lock which prevents
15202 	 * hat_join_region from adding this thread to the scd again. Other
15203 	 * threads check if sfmmu_scdp is NULL under hat lock and if it's NULL
15204 	 * they won't get here, since sfmmu_leave_scd() clears sfmmu_scdp
15205 	 * while holding the hat lock.
15206 	 */
15207 	mutex_enter(&scdp->scd_mutex);
15208 	sfmmu_from_scd_list(&scdp->scd_sf_list, sfmmup);
15209 	mutex_exit(&scdp->scd_mutex);
15210 	SFMMU_STAT(sf_leave_scd);
15211 
15212 	SF_SCD_DECR_REF(srdp, scdp);
15213 	hatlockp = sfmmu_hat_enter(sfmmup);
15214 
15215 }
15216 
15217 /*
15218  * Unlink and free up an SCD structure with a reference count of 0.
15219  */
15220 static void
15221 sfmmu_destroy_scd(sf_srd_t *srdp, sf_scd_t *scdp, sf_region_map_t *scd_rmap)
15222 {
15223 	sfmmu_t *scsfmmup;
15224 	sf_scd_t *sp;
15225 	hatlock_t *shatlockp;
15226 	int i, ret;
15227 
15228 	mutex_enter(&srdp->srd_scd_mutex);
15229 	for (sp = srdp->srd_scdp; sp != NULL; sp = sp->scd_next) {
15230 		if (sp == scdp)
15231 			break;
15232 	}
15233 	if (sp == NULL || sp->scd_refcnt) {
15234 		mutex_exit(&srdp->srd_scd_mutex);
15235 		return;
15236 	}
15237 
15238 	/*
15239 	 * It is possible that the scd has been freed and reallocated with a
15240 	 * different region map while we've been waiting for the srd_scd_mutex.
15241 	 */
15242 	SF_RGNMAP_EQUAL(scd_rmap, &sp->scd_region_map, ret);
15243 	if (ret != 1) {
15244 		mutex_exit(&srdp->srd_scd_mutex);
15245 		return;
15246 	}
15247 
15248 	ASSERT(scdp->scd_sf_list == NULL);
15249 	/*
15250 	 * Unlink scd from srd_scdp list.
15251 	 */
15252 	sfmmu_remove_scd(&srdp->srd_scdp, scdp);
15253 	mutex_exit(&srdp->srd_scd_mutex);
15254 
15255 	sfmmu_unlink_scd_from_regions(srdp, scdp);
15256 
15257 	/* Clear shared context tsb and release ctx */
15258 	scsfmmup = scdp->scd_sfmmup;
15259 
15260 	/*
15261 	 * create a barrier so that scd will not be destroyed
15262 	 * if other thread still holds the same shared hat lock.
15263 	 * E.g., sfmmu_tsbmiss_exception() needs to acquire the
15264 	 * shared hat lock before checking the shared tsb reloc flag.
15265 	 */
15266 	shatlockp = sfmmu_hat_enter(scsfmmup);
15267 	sfmmu_hat_exit(shatlockp);
15268 
15269 	sfmmu_free_scd_tsbs(scsfmmup);
15270 
15271 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
15272 		if (scsfmmup->sfmmu_hmeregion_links[i] != NULL) {
15273 			kmem_free(scsfmmup->sfmmu_hmeregion_links[i],
15274 			    SFMMU_L2_HMERLINKS_SIZE);
15275 			scsfmmup->sfmmu_hmeregion_links[i] = NULL;
15276 		}
15277 	}
15278 	kmem_cache_free(sfmmuid_cache, scsfmmup);
15279 	kmem_cache_free(scd_cache, scdp);
15280 	SFMMU_STAT(sf_destroy_scd);
15281 }
15282 
15283 /*
15284  * Modifies the HAT_CTX1_FLAG for each of the ISM segments which correspond to
15285  * bits which are set in the ism_region_map parameter. This flag indicates to
15286  * the tsbmiss handler that mapping for these segments should be loaded using
15287  * the shared context.
15288  */
15289 static void
15290 sfmmu_ism_hatflags(sfmmu_t *sfmmup, int addflag)
15291 {
15292 	sf_scd_t *scdp = sfmmup->sfmmu_scdp;
15293 	ism_blk_t *ism_blkp;
15294 	ism_map_t *ism_map;
15295 	int i, rid;
15296 
15297 	ASSERT(sfmmup->sfmmu_iblk != NULL);
15298 	ASSERT(scdp != NULL);
15299 	/*
15300 	 * Note that the caller either set HAT_ISMBUSY flag or checked
15301 	 * under hat lock that HAT_ISMBUSY was not set by another thread.
15302 	 */
15303 	ASSERT(sfmmu_hat_lock_held(sfmmup));
15304 
15305 	ism_blkp = sfmmup->sfmmu_iblk;
15306 	while (ism_blkp != NULL) {
15307 		ism_map = ism_blkp->iblk_maps;
15308 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
15309 			rid = ism_map[i].imap_rid;
15310 			if (rid == SFMMU_INVALID_ISMRID) {
15311 				continue;
15312 			}
15313 			ASSERT(rid >= 0 && rid < SFMMU_MAX_ISM_REGIONS);
15314 			if (SF_RGNMAP_TEST(scdp->scd_ismregion_map, rid) &&
15315 			    addflag) {
15316 				ism_map[i].imap_hatflags |=
15317 				    HAT_CTX1_FLAG;
15318 			} else {
15319 				ism_map[i].imap_hatflags &=
15320 				    ~HAT_CTX1_FLAG;
15321 			}
15322 		}
15323 		ism_blkp = ism_blkp->iblk_next;
15324 	}
15325 }
15326 
15327 static int
15328 sfmmu_srd_lock_held(sf_srd_t *srdp)
15329 {
15330 	return (MUTEX_HELD(&srdp->srd_mutex));
15331 }
15332 
15333 /* ARGSUSED */
15334 static int
15335 sfmmu_scdcache_constructor(void *buf, void *cdrarg, int kmflags)
15336 {
15337 	sf_scd_t *scdp = (sf_scd_t *)buf;
15338 
15339 	bzero(buf, sizeof (sf_scd_t));
15340 	mutex_init(&scdp->scd_mutex, NULL, MUTEX_DEFAULT, NULL);
15341 	return (0);
15342 }
15343 
15344 /* ARGSUSED */
15345 static void
15346 sfmmu_scdcache_destructor(void *buf, void *cdrarg)
15347 {
15348 	sf_scd_t *scdp = (sf_scd_t *)buf;
15349 
15350 	mutex_destroy(&scdp->scd_mutex);
15351 }
15352 
15353 /*
15354  * The listp parameter is a pointer to a list of hmeblks which are partially
15355  * freed as result of calling sfmmu_hblk_hash_rm(), the last phase of the
15356  * freeing process is to cross-call all cpus to ensure that there are no
15357  * remaining cached references.
15358  *
15359  * If the local generation number is less than the global then we can free
15360  * hmeblks which are already on the pending queue as another cpu has completed
15361  * the cross-call.
15362  *
15363  * We cross-call to make sure that there are no threads on other cpus accessing
15364  * these hmblks and then complete the process of freeing them under the
15365  * following conditions:
15366  *	The total number of pending hmeblks is greater than the threshold
15367  *	The reserve list has fewer than HBLK_RESERVE_CNT hmeblks
15368  *	It is at least 1 second since the last time we cross-called
15369  *
15370  * Otherwise, we add the hmeblks to the per-cpu pending queue.
15371  */
15372 static void
15373 sfmmu_hblks_list_purge(struct hme_blk **listp, int dontfree)
15374 {
15375 	struct hme_blk *hblkp, *pr_hblkp = NULL;
15376 	int		count = 0;
15377 	cpuset_t	cpuset = cpu_ready_set;
15378 	cpu_hme_pend_t	*cpuhp;
15379 	timestruc_t	now;
15380 	int		one_second_expired = 0;
15381 
15382 	gethrestime_lasttick(&now);
15383 
15384 	for (hblkp = *listp; hblkp != NULL; hblkp = hblkp->hblk_next) {
15385 		ASSERT(hblkp->hblk_shw_bit == 0);
15386 		ASSERT(hblkp->hblk_shared == 0);
15387 		count++;
15388 		pr_hblkp = hblkp;
15389 	}
15390 
15391 	cpuhp = &cpu_hme_pend[CPU->cpu_seqid];
15392 	mutex_enter(&cpuhp->chp_mutex);
15393 
15394 	if ((cpuhp->chp_count + count) == 0) {
15395 		mutex_exit(&cpuhp->chp_mutex);
15396 		return;
15397 	}
15398 
15399 	if ((now.tv_sec - cpuhp->chp_timestamp) > 1) {
15400 		one_second_expired  = 1;
15401 	}
15402 
15403 	if (!dontfree && (freehblkcnt < HBLK_RESERVE_CNT ||
15404 	    (cpuhp->chp_count + count) > cpu_hme_pend_thresh ||
15405 	    one_second_expired)) {
15406 		/* Append global list to local */
15407 		if (pr_hblkp == NULL) {
15408 			*listp = cpuhp->chp_listp;
15409 		} else {
15410 			pr_hblkp->hblk_next = cpuhp->chp_listp;
15411 		}
15412 		cpuhp->chp_listp = NULL;
15413 		cpuhp->chp_count = 0;
15414 		cpuhp->chp_timestamp = now.tv_sec;
15415 		mutex_exit(&cpuhp->chp_mutex);
15416 
15417 		kpreempt_disable();
15418 		CPUSET_DEL(cpuset, CPU->cpu_id);
15419 		xt_sync(cpuset);
15420 		xt_sync(cpuset);
15421 		kpreempt_enable();
15422 
15423 		/*
15424 		 * At this stage we know that no trap handlers on other
15425 		 * cpus can have references to hmeblks on the list.
15426 		 */
15427 		sfmmu_hblk_free(listp);
15428 	} else if (*listp != NULL) {
15429 		pr_hblkp->hblk_next = cpuhp->chp_listp;
15430 		cpuhp->chp_listp = *listp;
15431 		cpuhp->chp_count += count;
15432 		*listp = NULL;
15433 		mutex_exit(&cpuhp->chp_mutex);
15434 	} else {
15435 		mutex_exit(&cpuhp->chp_mutex);
15436 	}
15437 }
15438 
15439 /*
15440  * Add an hmeblk to the the hash list.
15441  */
15442 void
15443 sfmmu_hblk_hash_add(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15444     uint64_t hblkpa)
15445 {
15446 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15447 #ifdef	DEBUG
15448 	if (hmebp->hmeblkp == NULL) {
15449 		ASSERT(hmebp->hmeh_nextpa == HMEBLK_ENDPA);
15450 	}
15451 #endif /* DEBUG */
15452 
15453 	hmeblkp->hblk_nextpa = hmebp->hmeh_nextpa;
15454 	/*
15455 	 * Since the TSB miss handler now does not lock the hash chain before
15456 	 * walking it, make sure that the hmeblks nextpa is globally visible
15457 	 * before we make the hmeblk globally visible by updating the chain root
15458 	 * pointer in the hash bucket.
15459 	 */
15460 	membar_producer();
15461 	hmebp->hmeh_nextpa = hblkpa;
15462 	hmeblkp->hblk_next = hmebp->hmeblkp;
15463 	hmebp->hmeblkp = hmeblkp;
15464 
15465 }
15466 
15467 /*
15468  * This function is the first part of a 2 part process to remove an hmeblk
15469  * from the hash chain. In this phase we unlink the hmeblk from the hash chain
15470  * but leave the next physical pointer unchanged. The hmeblk is then linked onto
15471  * a per-cpu pending list using the virtual address pointer.
15472  *
15473  * TSB miss trap handlers that start after this phase will no longer see
15474  * this hmeblk. TSB miss handlers that still cache this hmeblk in a register
15475  * can still use it for further chain traversal because we haven't yet modifed
15476  * the next physical pointer or freed it.
15477  *
15478  * In the second phase of hmeblk removal we'll issue a barrier xcall before
15479  * we reuse or free this hmeblk. This will make sure all lingering references to
15480  * the hmeblk after first phase disappear before we finally reclaim it.
15481  * This scheme eliminates the need for TSB miss handlers to lock hmeblk chains
15482  * during their traversal.
15483  *
15484  * The hmehash_mutex must be held when calling this function.
15485  *
15486  * Input:
15487  *	 hmebp - hme hash bucket pointer
15488  *	 hmeblkp - address of hmeblk to be removed
15489  *	 pr_hblk - virtual address of previous hmeblkp
15490  *	 listp - pointer to list of hmeblks linked by virtual address
15491  *	 free_now flag - indicates that a complete removal from the hash chains
15492  *			 is necessary.
15493  *
15494  * It is inefficient to use the free_now flag as a cross-call is required to
15495  * remove a single hmeblk from the hash chain but is necessary when hmeblks are
15496  * in short supply.
15497  */
15498 void
15499 sfmmu_hblk_hash_rm(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
15500     struct hme_blk *pr_hblk, struct hme_blk **listp, int free_now)
15501 {
15502 	int shw_size, vshift;
15503 	struct hme_blk *shw_hblkp;
15504 	uint_t		shw_mask, newshw_mask;
15505 	caddr_t		vaddr;
15506 	int		size;
15507 	cpuset_t cpuset = cpu_ready_set;
15508 
15509 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
15510 
15511 	if (hmebp->hmeblkp == hmeblkp) {
15512 		hmebp->hmeh_nextpa = hmeblkp->hblk_nextpa;
15513 		hmebp->hmeblkp = hmeblkp->hblk_next;
15514 	} else {
15515 		pr_hblk->hblk_nextpa = hmeblkp->hblk_nextpa;
15516 		pr_hblk->hblk_next = hmeblkp->hblk_next;
15517 	}
15518 
15519 	size = get_hblk_ttesz(hmeblkp);
15520 	shw_hblkp = hmeblkp->hblk_shadow;
15521 	if (shw_hblkp) {
15522 		ASSERT(hblktosfmmu(hmeblkp) != KHATID);
15523 		ASSERT(!hmeblkp->hblk_shared);
15524 #ifdef	DEBUG
15525 		if (mmu_page_sizes == max_mmu_page_sizes) {
15526 			ASSERT(size < TTE256M);
15527 		} else {
15528 			ASSERT(size < TTE4M);
15529 		}
15530 #endif /* DEBUG */
15531 
15532 		shw_size = get_hblk_ttesz(shw_hblkp);
15533 		vaddr = (caddr_t)get_hblk_base(hmeblkp);
15534 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
15535 		ASSERT(vshift < 8);
15536 		/*
15537 		 * Atomically clear shadow mask bit
15538 		 */
15539 		do {
15540 			shw_mask = shw_hblkp->hblk_shw_mask;
15541 			ASSERT(shw_mask & (1 << vshift));
15542 			newshw_mask = shw_mask & ~(1 << vshift);
15543 			newshw_mask = atomic_cas_32(&shw_hblkp->hblk_shw_mask,
15544 			    shw_mask, newshw_mask);
15545 		} while (newshw_mask != shw_mask);
15546 		hmeblkp->hblk_shadow = NULL;
15547 	}
15548 	hmeblkp->hblk_shw_bit = 0;
15549 
15550 	if (hmeblkp->hblk_shared) {
15551 #ifdef	DEBUG
15552 		sf_srd_t	*srdp;
15553 		sf_region_t	*rgnp;
15554 		uint_t		rid;
15555 
15556 		srdp = hblktosrd(hmeblkp);
15557 		ASSERT(srdp != NULL && srdp->srd_refcnt != 0);
15558 		rid = hmeblkp->hblk_tag.htag_rid;
15559 		ASSERT(SFMMU_IS_SHMERID_VALID(rid));
15560 		ASSERT(rid < SFMMU_MAX_HME_REGIONS);
15561 		rgnp = srdp->srd_hmergnp[rid];
15562 		ASSERT(rgnp != NULL);
15563 		SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid);
15564 #endif /* DEBUG */
15565 		hmeblkp->hblk_shared = 0;
15566 	}
15567 	if (free_now) {
15568 		kpreempt_disable();
15569 		CPUSET_DEL(cpuset, CPU->cpu_id);
15570 		xt_sync(cpuset);
15571 		xt_sync(cpuset);
15572 		kpreempt_enable();
15573 
15574 		hmeblkp->hblk_nextpa = HMEBLK_ENDPA;
15575 		hmeblkp->hblk_next = NULL;
15576 	} else {
15577 		/* Append hmeblkp to listp for processing later. */
15578 		hmeblkp->hblk_next = *listp;
15579 		*listp = hmeblkp;
15580 	}
15581 }
15582 
15583 /*
15584  * This routine is called when memory is in short supply and returns a free
15585  * hmeblk of the requested size from the cpu pending lists.
15586  */
15587 static struct hme_blk *
15588 sfmmu_check_pending_hblks(int size)
15589 {
15590 	int i;
15591 	struct hme_blk *hmeblkp = NULL, *last_hmeblkp;
15592 	int found_hmeblk;
15593 	cpuset_t cpuset = cpu_ready_set;
15594 	cpu_hme_pend_t *cpuhp;
15595 
15596 	/* Flush cpu hblk pending queues */
15597 	for (i = 0; i < NCPU; i++) {
15598 		cpuhp = &cpu_hme_pend[i];
15599 		if (cpuhp->chp_listp != NULL)  {
15600 			mutex_enter(&cpuhp->chp_mutex);
15601 			if (cpuhp->chp_listp == NULL)  {
15602 				mutex_exit(&cpuhp->chp_mutex);
15603 				continue;
15604 			}
15605 			found_hmeblk = 0;
15606 			last_hmeblkp = NULL;
15607 			for (hmeblkp = cpuhp->chp_listp; hmeblkp != NULL;
15608 			    hmeblkp = hmeblkp->hblk_next) {
15609 				if (get_hblk_ttesz(hmeblkp) == size) {
15610 					if (last_hmeblkp == NULL) {
15611 						cpuhp->chp_listp =
15612 						    hmeblkp->hblk_next;
15613 					} else {
15614 						last_hmeblkp->hblk_next =
15615 						    hmeblkp->hblk_next;
15616 					}
15617 					ASSERT(cpuhp->chp_count > 0);
15618 					cpuhp->chp_count--;
15619 					found_hmeblk = 1;
15620 					break;
15621 				} else {
15622 					last_hmeblkp = hmeblkp;
15623 				}
15624 			}
15625 			mutex_exit(&cpuhp->chp_mutex);
15626 
15627 			if (found_hmeblk) {
15628 				kpreempt_disable();
15629 				CPUSET_DEL(cpuset, CPU->cpu_id);
15630 				xt_sync(cpuset);
15631 				xt_sync(cpuset);
15632 				kpreempt_enable();
15633 				return (hmeblkp);
15634 			}
15635 		}
15636 	}
15637 	return (NULL);
15638 }
15639