xref: /titanic_51/usr/src/uts/sfmmu/vm/hat_sfmmu.c (revision 0ce6acb835f8cec2ed5d14a190db6e2f98ed6d69)
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 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * VM - Hardware Address Translation management for Spitfire MMU.
30  *
31  * This file implements the machine specific hardware translation
32  * needed by the VM system.  The machine independent interface is
33  * described in <vm/hat.h> while the machine dependent interface
34  * and data structures are described in <vm/hat_sfmmu.h>.
35  *
36  * The hat layer manages the address translation hardware as a cache
37  * driven by calls from the higher levels in the VM system.
38  */
39 
40 #include <sys/types.h>
41 #include <sys/kstat.h>
42 #include <vm/hat.h>
43 #include <vm/hat_sfmmu.h>
44 #include <vm/page.h>
45 #include <sys/pte.h>
46 #include <sys/systm.h>
47 #include <sys/mman.h>
48 #include <sys/sysmacros.h>
49 #include <sys/machparam.h>
50 #include <sys/vtrace.h>
51 #include <sys/kmem.h>
52 #include <sys/mmu.h>
53 #include <sys/cmn_err.h>
54 #include <sys/cpu.h>
55 #include <sys/cpuvar.h>
56 #include <sys/debug.h>
57 #include <sys/lgrp.h>
58 #include <sys/archsystm.h>
59 #include <sys/machsystm.h>
60 #include <sys/vmsystm.h>
61 #include <vm/as.h>
62 #include <vm/seg.h>
63 #include <vm/seg_kp.h>
64 #include <vm/seg_kmem.h>
65 #include <vm/seg_kpm.h>
66 #include <vm/rm.h>
67 #include <sys/t_lock.h>
68 #include <sys/obpdefs.h>
69 #include <sys/vm_machparam.h>
70 #include <sys/var.h>
71 #include <sys/trap.h>
72 #include <sys/machtrap.h>
73 #include <sys/scb.h>
74 #include <sys/bitmap.h>
75 #include <sys/machlock.h>
76 #include <sys/membar.h>
77 #include <sys/atomic.h>
78 #include <sys/cpu_module.h>
79 #include <sys/prom_debug.h>
80 #include <sys/ksynch.h>
81 #include <sys/mem_config.h>
82 #include <sys/mem_cage.h>
83 #include <sys/dtrace.h>
84 #include <vm/vm_dep.h>
85 #include <vm/xhat_sfmmu.h>
86 #include <sys/fpu/fpusystm.h>
87 #include <vm/mach_kpm.h>
88 
89 #if defined(SF_ERRATA_57)
90 extern caddr_t errata57_limit;
91 #endif
92 
93 #define	HME8BLK_SZ_RND		((roundup(HME8BLK_SZ, sizeof (int64_t))) /  \
94 				(sizeof (int64_t)))
95 #define	HBLK_RESERVE		((struct hme_blk *)hblk_reserve)
96 
97 #define	HBLK_RESERVE_CNT	128
98 #define	HBLK_RESERVE_MIN	20
99 
100 static struct hme_blk		*freehblkp;
101 static kmutex_t			freehblkp_lock;
102 static int			freehblkcnt;
103 
104 static int64_t			hblk_reserve[HME8BLK_SZ_RND];
105 static kmutex_t			hblk_reserve_lock;
106 static kthread_t		*hblk_reserve_thread;
107 
108 static nucleus_hblk8_info_t	nucleus_hblk8;
109 static nucleus_hblk1_info_t	nucleus_hblk1;
110 
111 /*
112  * SFMMU specific hat functions
113  */
114 void	hat_pagecachectl(struct page *, int);
115 
116 /* flags for hat_pagecachectl */
117 #define	HAT_CACHE	0x1
118 #define	HAT_UNCACHE	0x2
119 #define	HAT_TMPNC	0x4
120 
121 /*
122  * Flag to allow the creation of non-cacheable translations
123  * to system memory. It is off by default. At the moment this
124  * flag is used by the ecache error injector. The error injector
125  * will turn it on when creating such a translation then shut it
126  * off when it's finished.
127  */
128 
129 int	sfmmu_allow_nc_trans = 0;
130 
131 /*
132  * Flag to disable large page support.
133  * 	value of 1 => disable all large pages.
134  *	bits 1, 2, and 3 are to disable 64K, 512K and 4M pages respectively.
135  *
136  * For example, use the value 0x4 to disable 512K pages.
137  *
138  */
139 #define	LARGE_PAGES_OFF		0x1
140 
141 /*
142  * WARNING: 512K pages MUST be disabled for ISM/DISM. If not
143  * a process would page fault indefinitely if it tried to
144  * access a 512K page.
145  */
146 int	disable_ism_large_pages = (1 << TTE512K);
147 int	disable_large_pages = 0;
148 int	disable_auto_large_pages = 0;
149 
150 /*
151  * Private sfmmu data structures for hat management
152  */
153 static struct kmem_cache *sfmmuid_cache;
154 static struct kmem_cache *mmuctxdom_cache;
155 
156 /*
157  * Private sfmmu data structures for tsb management
158  */
159 static struct kmem_cache *sfmmu_tsbinfo_cache;
160 static struct kmem_cache *sfmmu_tsb8k_cache;
161 static struct kmem_cache *sfmmu_tsb_cache[NLGRPS_MAX];
162 static vmem_t *kmem_tsb_arena;
163 
164 /*
165  * sfmmu static variables for hmeblk resource management.
166  */
167 static vmem_t *hat_memload1_arena; /* HAT translation arena for sfmmu1_cache */
168 static struct kmem_cache *sfmmu8_cache;
169 static struct kmem_cache *sfmmu1_cache;
170 static struct kmem_cache *pa_hment_cache;
171 
172 static kmutex_t 	ism_mlist_lock;	/* mutex for ism mapping list */
173 /*
174  * private data for ism
175  */
176 static struct kmem_cache *ism_blk_cache;
177 static struct kmem_cache *ism_ment_cache;
178 #define	ISMID_STARTADDR	NULL
179 
180 /*
181  * Whether to delay TLB flushes and use Cheetah's flush-all support
182  * when removing contexts from the dirty list.
183  */
184 int delay_tlb_flush;
185 int disable_delay_tlb_flush;
186 
187 /*
188  * ``hat_lock'' is a hashed mutex lock for protecting sfmmu TSB lists,
189  * HAT flags, synchronizing TLB/TSB coherency, and context management.
190  * The lock is hashed on the sfmmup since the case where we need to lock
191  * all processes is rare but does occur (e.g. we need to unload a shared
192  * mapping from all processes using the mapping).  We have a lot of buckets,
193  * and each slab of sfmmu_t's can use about a quarter of them, giving us
194  * a fairly good distribution without wasting too much space and overhead
195  * when we have to grab them all.
196  */
197 #define	SFMMU_NUM_LOCK	128		/* must be power of two */
198 hatlock_t	hat_lock[SFMMU_NUM_LOCK];
199 
200 /*
201  * Hash algorithm optimized for a small number of slabs.
202  *  7 is (highbit((sizeof sfmmu_t)) - 1)
203  * This hash algorithm is based upon the knowledge that sfmmu_t's come from a
204  * kmem_cache, and thus they will be sequential within that cache.  In
205  * addition, each new slab will have a different "color" up to cache_maxcolor
206  * which will skew the hashing for each successive slab which is allocated.
207  * If the size of sfmmu_t changed to a larger size, this algorithm may need
208  * to be revisited.
209  */
210 #define	TSB_HASH_SHIFT_BITS (7)
211 #define	PTR_HASH(x) ((uintptr_t)x >> TSB_HASH_SHIFT_BITS)
212 
213 #ifdef DEBUG
214 int tsb_hash_debug = 0;
215 #define	TSB_HASH(sfmmup)	\
216 	(tsb_hash_debug ? &hat_lock[0] : \
217 	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)])
218 #else	/* DEBUG */
219 #define	TSB_HASH(sfmmup)	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)]
220 #endif	/* DEBUG */
221 
222 
223 /* sfmmu_replace_tsb() return codes. */
224 typedef enum tsb_replace_rc {
225 	TSB_SUCCESS,
226 	TSB_ALLOCFAIL,
227 	TSB_LOSTRACE,
228 	TSB_ALREADY_SWAPPED,
229 	TSB_CANTGROW
230 } tsb_replace_rc_t;
231 
232 /*
233  * Flags for TSB allocation routines.
234  */
235 #define	TSB_ALLOC	0x01
236 #define	TSB_FORCEALLOC	0x02
237 #define	TSB_GROW	0x04
238 #define	TSB_SHRINK	0x08
239 #define	TSB_SWAPIN	0x10
240 
241 /*
242  * Support for HAT callbacks.
243  */
244 #define	SFMMU_MAX_RELOC_CALLBACKS	10
245 int sfmmu_max_cb_id = SFMMU_MAX_RELOC_CALLBACKS;
246 static id_t sfmmu_cb_nextid = 0;
247 static id_t sfmmu_tsb_cb_id;
248 struct sfmmu_callback *sfmmu_cb_table;
249 
250 /*
251  * Kernel page relocation is enabled by default for non-caged
252  * kernel pages.  This has little effect unless segkmem_reloc is
253  * set, since by default kernel memory comes from inside the
254  * kernel cage.
255  */
256 int hat_kpr_enabled = 1;
257 
258 kmutex_t	kpr_mutex;
259 kmutex_t	kpr_suspendlock;
260 kthread_t	*kreloc_thread;
261 
262 /*
263  * Enable VA->PA translation sanity checking on DEBUG kernels.
264  * Disabled by default.  This is incompatible with some
265  * drivers (error injector, RSM) so if it breaks you get
266  * to keep both pieces.
267  */
268 int hat_check_vtop = 0;
269 
270 /*
271  * Private sfmmu routines (prototypes)
272  */
273 static struct hme_blk *sfmmu_shadow_hcreate(sfmmu_t *, caddr_t, int, uint_t);
274 static struct 	hme_blk *sfmmu_hblk_alloc(sfmmu_t *, caddr_t,
275 			struct hmehash_bucket *, uint_t, hmeblk_tag, uint_t);
276 static caddr_t	sfmmu_hblk_unload(struct hat *, struct hme_blk *, caddr_t,
277 			caddr_t, demap_range_t *, uint_t);
278 static caddr_t	sfmmu_hblk_sync(struct hat *, struct hme_blk *, caddr_t,
279 			caddr_t, int);
280 static void	sfmmu_hblk_free(struct hmehash_bucket *, struct hme_blk *,
281 			uint64_t, struct hme_blk **);
282 static void	sfmmu_hblks_list_purge(struct hme_blk **);
283 static uint_t	sfmmu_get_free_hblk(struct hme_blk **, uint_t);
284 static uint_t	sfmmu_put_free_hblk(struct hme_blk *, uint_t);
285 static struct hme_blk *sfmmu_hblk_steal(int);
286 static int	sfmmu_steal_this_hblk(struct hmehash_bucket *,
287 			struct hme_blk *, uint64_t, uint64_t,
288 			struct hme_blk *);
289 static caddr_t	sfmmu_hblk_unlock(struct hme_blk *, caddr_t, caddr_t);
290 
291 static void	sfmmu_memload_batchsmall(struct hat *, caddr_t, page_t **,
292 		    uint_t, uint_t, pgcnt_t);
293 void		sfmmu_tteload(struct hat *, tte_t *, caddr_t, page_t *,
294 			uint_t);
295 static int	sfmmu_tteload_array(sfmmu_t *, tte_t *, caddr_t, page_t **,
296 			uint_t);
297 static struct hmehash_bucket *sfmmu_tteload_acquire_hashbucket(sfmmu_t *,
298 					caddr_t, int);
299 static struct hme_blk *sfmmu_tteload_find_hmeblk(sfmmu_t *,
300 			struct hmehash_bucket *, caddr_t, uint_t, uint_t);
301 static int	sfmmu_tteload_addentry(sfmmu_t *, struct hme_blk *, tte_t *,
302 			caddr_t, page_t **, uint_t);
303 static void	sfmmu_tteload_release_hashbucket(struct hmehash_bucket *);
304 
305 static int	sfmmu_pagearray_setup(caddr_t, page_t **, tte_t *, int);
306 pfn_t		sfmmu_uvatopfn(caddr_t, sfmmu_t *);
307 void		sfmmu_memtte(tte_t *, pfn_t, uint_t, int);
308 #ifdef VAC
309 static void	sfmmu_vac_conflict(struct hat *, caddr_t, page_t *);
310 static int	sfmmu_vacconflict_array(caddr_t, page_t *, int *);
311 int	tst_tnc(page_t *pp, pgcnt_t);
312 void	conv_tnc(page_t *pp, int);
313 #endif
314 
315 static void	sfmmu_get_ctx(sfmmu_t *);
316 static void	sfmmu_free_sfmmu(sfmmu_t *);
317 
318 static void	sfmmu_gettte(struct hat *, caddr_t, tte_t *);
319 static void	sfmmu_ttesync(struct hat *, caddr_t, tte_t *, page_t *);
320 static void	sfmmu_chgattr(struct hat *, caddr_t, size_t, uint_t, int);
321 
322 cpuset_t	sfmmu_pageunload(page_t *, struct sf_hment *, int);
323 static void	hat_pagereload(struct page *, struct page *);
324 static cpuset_t	sfmmu_pagesync(page_t *, struct sf_hment *, uint_t);
325 #ifdef VAC
326 void	sfmmu_page_cache_array(page_t *, int, int, pgcnt_t);
327 static void	sfmmu_page_cache(page_t *, int, int, int);
328 #endif
329 
330 static void	sfmmu_tlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
331 			pfn_t, int, int, int, int);
332 static void	sfmmu_ismtlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
333 			pfn_t, int);
334 static void	sfmmu_tlb_demap(caddr_t, sfmmu_t *, struct hme_blk *, int, int);
335 static void	sfmmu_tlb_range_demap(demap_range_t *);
336 static void	sfmmu_invalidate_ctx(sfmmu_t *);
337 static void	sfmmu_sync_mmustate(sfmmu_t *);
338 
339 static void 	sfmmu_tsbinfo_setup_phys(struct tsb_info *, pfn_t);
340 static int	sfmmu_tsbinfo_alloc(struct tsb_info **, int, int, uint_t,
341 			sfmmu_t *);
342 static void	sfmmu_tsb_free(struct tsb_info *);
343 static void	sfmmu_tsbinfo_free(struct tsb_info *);
344 static int	sfmmu_init_tsbinfo(struct tsb_info *, int, int, uint_t,
345 			sfmmu_t *);
346 
347 static void	sfmmu_tsb_swapin(sfmmu_t *, hatlock_t *);
348 static int	sfmmu_select_tsb_szc(pgcnt_t);
349 static void	sfmmu_mod_tsb(sfmmu_t *, caddr_t, tte_t *, int);
350 #define		sfmmu_load_tsb(sfmmup, vaddr, tte, szc) \
351 	sfmmu_mod_tsb(sfmmup, vaddr, tte, szc)
352 #define		sfmmu_unload_tsb(sfmmup, vaddr, szc)    \
353 	sfmmu_mod_tsb(sfmmup, vaddr, NULL, szc)
354 static void	sfmmu_copy_tsb(struct tsb_info *, struct tsb_info *);
355 static tsb_replace_rc_t sfmmu_replace_tsb(sfmmu_t *, struct tsb_info *, uint_t,
356     hatlock_t *, uint_t);
357 static void	sfmmu_size_tsb(sfmmu_t *, int, uint64_t, uint64_t, int);
358 
359 #ifdef VAC
360 void	sfmmu_cache_flush(pfn_t, int);
361 void	sfmmu_cache_flushcolor(int, pfn_t);
362 #endif
363 static caddr_t	sfmmu_hblk_chgattr(sfmmu_t *, struct hme_blk *, caddr_t,
364 			caddr_t, demap_range_t *, uint_t, int);
365 
366 static uint64_t	sfmmu_vtop_attr(uint_t, int mode, tte_t *);
367 static uint_t	sfmmu_ptov_attr(tte_t *);
368 static caddr_t	sfmmu_hblk_chgprot(sfmmu_t *, struct hme_blk *, caddr_t,
369 			caddr_t, demap_range_t *, uint_t);
370 static uint_t	sfmmu_vtop_prot(uint_t, uint_t *);
371 static int	sfmmu_idcache_constructor(void *, void *, int);
372 static void	sfmmu_idcache_destructor(void *, void *);
373 static int	sfmmu_hblkcache_constructor(void *, void *, int);
374 static void	sfmmu_hblkcache_destructor(void *, void *);
375 static void	sfmmu_hblkcache_reclaim(void *);
376 static void	sfmmu_shadow_hcleanup(sfmmu_t *, struct hme_blk *,
377 			struct hmehash_bucket *);
378 static void	sfmmu_free_hblks(sfmmu_t *, caddr_t, caddr_t, int);
379 static void	sfmmu_rm_large_mappings(page_t *, int);
380 
381 static void	hat_lock_init(void);
382 static void	hat_kstat_init(void);
383 static int	sfmmu_kstat_percpu_update(kstat_t *ksp, int rw);
384 static void	sfmmu_check_page_sizes(sfmmu_t *, int);
385 int	fnd_mapping_sz(page_t *);
386 static void	iment_add(struct ism_ment *,  struct hat *);
387 static void	iment_sub(struct ism_ment *, struct hat *);
388 static pgcnt_t	ism_tsb_entries(sfmmu_t *, int szc);
389 extern void	sfmmu_setup_tsbinfo(sfmmu_t *);
390 extern void	sfmmu_clear_utsbinfo(void);
391 
392 static void	sfmmu_ctx_wrap_around(mmu_ctx_t *);
393 
394 /* kpm globals */
395 #ifdef	DEBUG
396 /*
397  * Enable trap level tsbmiss handling
398  */
399 int	kpm_tsbmtl = 1;
400 
401 /*
402  * Flush the TLB on kpm mapout. Note: Xcalls are used (again) for the
403  * required TLB shootdowns in this case, so handle w/ care. Off by default.
404  */
405 int	kpm_tlb_flush;
406 #endif	/* DEBUG */
407 
408 static void	*sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *, size_t, int);
409 
410 #ifdef DEBUG
411 static void	sfmmu_check_hblk_flist();
412 #endif
413 
414 /*
415  * Semi-private sfmmu data structures.  Some of them are initialize in
416  * startup or in hat_init. Some of them are private but accessed by
417  * assembly code or mach_sfmmu.c
418  */
419 struct hmehash_bucket *uhme_hash;	/* user hmeblk hash table */
420 struct hmehash_bucket *khme_hash;	/* kernel hmeblk hash table */
421 uint64_t	uhme_hash_pa;		/* PA of uhme_hash */
422 uint64_t	khme_hash_pa;		/* PA of khme_hash */
423 int 		uhmehash_num;		/* # of buckets in user hash table */
424 int 		khmehash_num;		/* # of buckets in kernel hash table */
425 
426 uint_t		max_mmu_ctxdoms = 0;	/* max context domains in the system */
427 mmu_ctx_t	**mmu_ctxs_tbl;		/* global array of context domains */
428 uint64_t	mmu_saved_gnum = 0;	/* to init incoming MMUs' gnums */
429 
430 #define	DEFAULT_NUM_CTXS_PER_MMU 8192
431 static uint_t	nctxs = DEFAULT_NUM_CTXS_PER_MMU;
432 
433 int		cache;			/* describes system cache */
434 
435 caddr_t		ktsb_base;		/* kernel 8k-indexed tsb base address */
436 uint64_t	ktsb_pbase;		/* kernel 8k-indexed tsb phys address */
437 int		ktsb_szcode;		/* kernel 8k-indexed tsb size code */
438 int		ktsb_sz;		/* kernel 8k-indexed tsb size */
439 
440 caddr_t		ktsb4m_base;		/* kernel 4m-indexed tsb base address */
441 uint64_t	ktsb4m_pbase;		/* kernel 4m-indexed tsb phys address */
442 int		ktsb4m_szcode;		/* kernel 4m-indexed tsb size code */
443 int		ktsb4m_sz;		/* kernel 4m-indexed tsb size */
444 
445 uint64_t	kpm_tsbbase;		/* kernel seg_kpm 4M TSB base address */
446 int		kpm_tsbsz;		/* kernel seg_kpm 4M TSB size code */
447 uint64_t	kpmsm_tsbbase;		/* kernel seg_kpm 8K TSB base address */
448 int		kpmsm_tsbsz;		/* kernel seg_kpm 8K TSB size code */
449 
450 #ifndef sun4v
451 int		utsb_dtlb_ttenum = -1;	/* index in TLB for utsb locked TTE */
452 int		utsb4m_dtlb_ttenum = -1; /* index in TLB for 4M TSB TTE */
453 int		dtlb_resv_ttenum;	/* index in TLB of first reserved TTE */
454 caddr_t		utsb_vabase;		/* reserved kernel virtual memory */
455 caddr_t		utsb4m_vabase;		/* for trap handler TSB accesses */
456 #endif /* sun4v */
457 uint64_t	tsb_alloc_bytes = 0;	/* bytes allocated to TSBs */
458 vmem_t		*kmem_tsb_default_arena[NLGRPS_MAX];	/* For dynamic TSBs */
459 
460 /*
461  * Size to use for TSB slabs.  Future platforms that support page sizes
462  * larger than 4M may wish to change these values, and provide their own
463  * assembly macros for building and decoding the TSB base register contents.
464  * Note disable_large_pages will override the value set here.
465  */
466 uint_t	tsb_slab_ttesz = TTE4M;
467 uint_t	tsb_slab_size;
468 uint_t	tsb_slab_shift;
469 uint_t	tsb_slab_mask;	/* PFN mask for TTE */
470 
471 /* largest TSB size to grow to, will be smaller on smaller memory systems */
472 int	tsb_max_growsize = UTSB_MAX_SZCODE;
473 
474 /*
475  * Tunable parameters dealing with TSB policies.
476  */
477 
478 /*
479  * This undocumented tunable forces all 8K TSBs to be allocated from
480  * the kernel heap rather than from the kmem_tsb_default_arena arenas.
481  */
482 #ifdef	DEBUG
483 int	tsb_forceheap = 0;
484 #endif	/* DEBUG */
485 
486 /*
487  * Decide whether to use per-lgroup arenas, or one global set of
488  * TSB arenas.  The default is not to break up per-lgroup, since
489  * most platforms don't recognize any tangible benefit from it.
490  */
491 int	tsb_lgrp_affinity = 0;
492 
493 /*
494  * Used for growing the TSB based on the process RSS.
495  * tsb_rss_factor is based on the smallest TSB, and is
496  * shifted by the TSB size to determine if we need to grow.
497  * The default will grow the TSB if the number of TTEs for
498  * this page size exceeds 75% of the number of TSB entries,
499  * which should _almost_ eliminate all conflict misses
500  * (at the expense of using up lots and lots of memory).
501  */
502 #define	TSB_RSS_FACTOR		(TSB_ENTRIES(TSB_MIN_SZCODE) * 0.75)
503 #define	SFMMU_RSS_TSBSIZE(tsbszc)	(tsb_rss_factor << tsbszc)
504 #define	SELECT_TSB_SIZECODE(pgcnt) ( \
505 	(enable_tsb_rss_sizing)? sfmmu_select_tsb_szc(pgcnt) : \
506 	default_tsb_size)
507 #define	TSB_OK_SHRINK()	\
508 	(tsb_alloc_bytes > tsb_alloc_hiwater || freemem < desfree)
509 #define	TSB_OK_GROW()	\
510 	(tsb_alloc_bytes < tsb_alloc_hiwater && freemem > desfree)
511 
512 int	enable_tsb_rss_sizing = 1;
513 int	tsb_rss_factor	= (int)TSB_RSS_FACTOR;
514 
515 /* which TSB size code to use for new address spaces or if rss sizing off */
516 int default_tsb_size = TSB_8K_SZCODE;
517 
518 static uint64_t tsb_alloc_hiwater; /* limit TSB reserved memory */
519 uint64_t tsb_alloc_hiwater_factor; /* tsb_alloc_hiwater = physmem / this */
520 #define	TSB_ALLOC_HIWATER_FACTOR_DEFAULT	32
521 
522 #ifdef DEBUG
523 static int tsb_random_size = 0;	/* set to 1 to test random tsb sizes on alloc */
524 static int tsb_grow_stress = 0;	/* if set to 1, keep replacing TSB w/ random */
525 static int tsb_alloc_mtbf = 0;	/* fail allocation every n attempts */
526 static int tsb_alloc_fail_mtbf = 0;
527 static int tsb_alloc_count = 0;
528 #endif /* DEBUG */
529 
530 /* if set to 1, will remap valid TTEs when growing TSB. */
531 int tsb_remap_ttes = 1;
532 
533 /*
534  * If we have more than this many mappings, allocate a second TSB.
535  * This default is chosen because the I/D fully associative TLBs are
536  * assumed to have at least 8 available entries. Platforms with a
537  * larger fully-associative TLB could probably override the default.
538  */
539 int tsb_sectsb_threshold = 8;
540 
541 /*
542  * kstat data
543  */
544 struct sfmmu_global_stat sfmmu_global_stat;
545 struct sfmmu_tsbsize_stat sfmmu_tsbsize_stat;
546 
547 /*
548  * Global data
549  */
550 sfmmu_t 	*ksfmmup;		/* kernel's hat id */
551 
552 #ifdef DEBUG
553 static void	chk_tte(tte_t *, tte_t *, tte_t *, struct hme_blk *);
554 #endif
555 
556 /* sfmmu locking operations */
557 static kmutex_t *sfmmu_mlspl_enter(struct page *, int);
558 static int	sfmmu_mlspl_held(struct page *, int);
559 
560 kmutex_t *sfmmu_page_enter(page_t *);
561 void	sfmmu_page_exit(kmutex_t *);
562 int	sfmmu_page_spl_held(struct page *);
563 
564 /* sfmmu internal locking operations - accessed directly */
565 static void	sfmmu_mlist_reloc_enter(page_t *, page_t *,
566 				kmutex_t **, kmutex_t **);
567 static void	sfmmu_mlist_reloc_exit(kmutex_t *, kmutex_t *);
568 static hatlock_t *
569 		sfmmu_hat_enter(sfmmu_t *);
570 static hatlock_t *
571 		sfmmu_hat_tryenter(sfmmu_t *);
572 static void	sfmmu_hat_exit(hatlock_t *);
573 static void	sfmmu_hat_lock_all(void);
574 static void	sfmmu_hat_unlock_all(void);
575 static void	sfmmu_ismhat_enter(sfmmu_t *, int);
576 static void	sfmmu_ismhat_exit(sfmmu_t *, int);
577 
578 /*
579  * Array of mutexes protecting a page's mapping list and p_nrm field.
580  *
581  * The hash function looks complicated, but is made up so that:
582  *
583  * "pp" not shifted, so adjacent pp values will hash to different cache lines
584  *  (8 byte alignment * 8 bytes/mutes == 64 byte coherency subblock)
585  *
586  * "pp" >> mml_shift, incorporates more source bits into the hash result
587  *
588  *  "& (mml_table_size - 1), should be faster than using remainder "%"
589  *
590  * Hopefully, mml_table, mml_table_size and mml_shift are all in the same
591  * cacheline, since they get declared next to each other below. We'll trust
592  * ld not to do something random.
593  */
594 #ifdef	DEBUG
595 int mlist_hash_debug = 0;
596 #define	MLIST_HASH(pp)	(mlist_hash_debug ? &mml_table[0] : \
597 	&mml_table[((uintptr_t)(pp) + \
598 	((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)])
599 #else	/* !DEBUG */
600 #define	MLIST_HASH(pp)   &mml_table[ \
601 	((uintptr_t)(pp) + ((uintptr_t)(pp) >> mml_shift)) & (mml_table_sz - 1)]
602 #endif	/* !DEBUG */
603 
604 kmutex_t		*mml_table;
605 uint_t			mml_table_sz;	/* must be a power of 2 */
606 uint_t			mml_shift;	/* log2(mml_table_sz) + 3 for align */
607 
608 kpm_hlk_t	*kpmp_table;
609 uint_t		kpmp_table_sz;	/* must be a power of 2 */
610 uchar_t		kpmp_shift;
611 
612 kpm_shlk_t	*kpmp_stable;
613 uint_t		kpmp_stable_sz;	/* must be a power of 2 */
614 
615 /*
616  * SPL_HASH was improved to avoid false cache line sharing
617  */
618 #define	SPL_TABLE_SIZE	128
619 #define	SPL_MASK	(SPL_TABLE_SIZE - 1)
620 #define	SPL_SHIFT	7		/* log2(SPL_TABLE_SIZE) */
621 
622 #define	SPL_INDEX(pp) \
623 	((((uintptr_t)(pp) >> SPL_SHIFT) ^ \
624 	((uintptr_t)(pp) >> (SPL_SHIFT << 1))) & \
625 	(SPL_TABLE_SIZE - 1))
626 
627 #define	SPL_HASH(pp)    \
628 	(&sfmmu_page_lock[SPL_INDEX(pp) & SPL_MASK].pad_mutex)
629 
630 static	pad_mutex_t	sfmmu_page_lock[SPL_TABLE_SIZE];
631 
632 
633 /*
634  * hat_unload_callback() will group together callbacks in order
635  * to avoid xt_sync() calls.  This is the maximum size of the group.
636  */
637 #define	MAX_CB_ADDR	32
638 
639 tte_t	hw_tte;
640 static ulong_t sfmmu_dmr_maxbit = DMR_MAXBIT;
641 
642 static char	*mmu_ctx_kstat_names[] = {
643 	"mmu_ctx_tsb_exceptions",
644 	"mmu_ctx_tsb_raise_exception",
645 	"mmu_ctx_wrap_around",
646 };
647 
648 /*
649  * Wrapper for vmem_xalloc since vmem_create only allows limited
650  * parameters for vm_source_alloc functions.  This function allows us
651  * to specify alignment consistent with the size of the object being
652  * allocated.
653  */
654 static void *
655 sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *vmp, size_t size, int vmflag)
656 {
657 	return (vmem_xalloc(vmp, size, size, 0, 0, NULL, NULL, vmflag));
658 }
659 
660 /* Common code for setting tsb_alloc_hiwater. */
661 #define	SFMMU_SET_TSB_ALLOC_HIWATER(pages)	tsb_alloc_hiwater = \
662 		ptob(pages) / tsb_alloc_hiwater_factor
663 
664 /*
665  * Set tsb_max_growsize to allow at most all of physical memory to be mapped by
666  * a single TSB.  physmem is the number of physical pages so we need physmem 8K
667  * TTEs to represent all those physical pages.  We round this up by using
668  * 1<<highbit().  To figure out which size code to use, remember that the size
669  * code is just an amount to shift the smallest TSB size to get the size of
670  * this TSB.  So we subtract that size, TSB_START_SIZE, from highbit() (or
671  * highbit() - 1) to get the size code for the smallest TSB that can represent
672  * all of physical memory, while erring on the side of too much.
673  *
674  * If the computed size code is less than the current tsb_max_growsize, we set
675  * tsb_max_growsize to the computed size code.  In the case where the computed
676  * size code is greater than tsb_max_growsize, we have these restrictions that
677  * apply to increasing tsb_max_growsize:
678  *	1) TSBs can't grow larger than the TSB slab size
679  *	2) TSBs can't grow larger than UTSB_MAX_SZCODE.
680  */
681 #define	SFMMU_SET_TSB_MAX_GROWSIZE(pages) {				\
682 	int	i, szc;							\
683 									\
684 	i = highbit(pages);						\
685 	if ((1 << (i - 1)) == (pages))					\
686 		i--;		/* 2^n case, round down */		\
687 	szc = i - TSB_START_SIZE;					\
688 	if (szc < tsb_max_growsize)					\
689 		tsb_max_growsize = szc;					\
690 	else if ((szc > tsb_max_growsize) &&				\
691 	    (szc <= tsb_slab_shift - (TSB_START_SIZE + TSB_ENTRY_SHIFT))) \
692 		tsb_max_growsize = MIN(szc, UTSB_MAX_SZCODE);		\
693 }
694 
695 /*
696  * Given a pointer to an sfmmu and a TTE size code, return a pointer to the
697  * tsb_info which handles that TTE size.
698  */
699 #define	SFMMU_GET_TSBINFO(tsbinfop, sfmmup, tte_szc)			\
700 	(tsbinfop) = (sfmmup)->sfmmu_tsb;				\
701 	ASSERT(sfmmu_hat_lock_held(sfmmup));				\
702 	if ((tte_szc) >= TTE4M)						\
703 		(tsbinfop) = (tsbinfop)->tsb_next;
704 
705 /*
706  * Return the number of mappings present in the HAT
707  * for a particular process and page size.
708  */
709 #define	SFMMU_TTE_CNT(sfmmup, szc)					\
710 	(sfmmup)->sfmmu_iblk?						\
711 	    (sfmmup)->sfmmu_ismttecnt[(szc)] +				\
712 	    (sfmmup)->sfmmu_ttecnt[(szc)] :				\
713 	    (sfmmup)->sfmmu_ttecnt[(szc)];
714 
715 /*
716  * Macro to use to unload entries from the TSB.
717  * It has knowledge of which page sizes get replicated in the TSB
718  * and will call the appropriate unload routine for the appropriate size.
719  */
720 #define	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp)				\
721 {									\
722 	int ttesz = get_hblk_ttesz(hmeblkp);				\
723 	if (ttesz == TTE8K || ttesz == TTE4M) {				\
724 		sfmmu_unload_tsb(sfmmup, addr, ttesz);			\
725 	} else {							\
726 		caddr_t sva = (caddr_t)get_hblk_base(hmeblkp);		\
727 		caddr_t eva = sva + get_hblk_span(hmeblkp);		\
728 		ASSERT(addr >= sva && addr < eva);			\
729 		sfmmu_unload_tsb_range(sfmmup, sva, eva, ttesz);	\
730 	}								\
731 }
732 
733 
734 /* Update tsb_alloc_hiwater after memory is configured. */
735 /*ARGSUSED*/
736 static void
737 sfmmu_update_tsb_post_add(void *arg, pgcnt_t delta_pages)
738 {
739 	/* Assumes physmem has already been updated. */
740 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
741 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
742 }
743 
744 /*
745  * Update tsb_alloc_hiwater before memory is deleted.  We'll do nothing here
746  * and update tsb_alloc_hiwater and tsb_max_growsize after the memory is
747  * deleted.
748  */
749 /*ARGSUSED*/
750 static int
751 sfmmu_update_tsb_pre_del(void *arg, pgcnt_t delta_pages)
752 {
753 	return (0);
754 }
755 
756 /* Update tsb_alloc_hiwater after memory fails to be unconfigured. */
757 /*ARGSUSED*/
758 static void
759 sfmmu_update_tsb_post_del(void *arg, pgcnt_t delta_pages, int cancelled)
760 {
761 	/*
762 	 * Whether the delete was cancelled or not, just go ahead and update
763 	 * tsb_alloc_hiwater and tsb_max_growsize.
764 	 */
765 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
766 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
767 }
768 
769 static kphysm_setup_vector_t sfmmu_update_tsb_vec = {
770 	KPHYSM_SETUP_VECTOR_VERSION,	/* version */
771 	sfmmu_update_tsb_post_add,	/* post_add */
772 	sfmmu_update_tsb_pre_del,	/* pre_del */
773 	sfmmu_update_tsb_post_del	/* post_del */
774 };
775 
776 
777 /*
778  * HME_BLK HASH PRIMITIVES
779  */
780 
781 /*
782  * Enter a hme on the mapping list for page pp.
783  * When large pages are more prevalent in the system we might want to
784  * keep the mapping list in ascending order by the hment size. For now,
785  * small pages are more frequent, so don't slow it down.
786  */
787 #define	HME_ADD(hme, pp)					\
788 {								\
789 	ASSERT(sfmmu_mlist_held(pp));				\
790 								\
791 	hme->hme_prev = NULL;					\
792 	hme->hme_next = pp->p_mapping;				\
793 	hme->hme_page = pp;					\
794 	if (pp->p_mapping) {					\
795 		((struct sf_hment *)(pp->p_mapping))->hme_prev = hme;\
796 		ASSERT(pp->p_share > 0);			\
797 	} else  {						\
798 		/* EMPTY */					\
799 		ASSERT(pp->p_share == 0);			\
800 	}							\
801 	pp->p_mapping = hme;					\
802 	pp->p_share++;						\
803 }
804 
805 /*
806  * Enter a hme on the mapping list for page pp.
807  * If we are unmapping a large translation, we need to make sure that the
808  * change is reflect in the corresponding bit of the p_index field.
809  */
810 #define	HME_SUB(hme, pp)					\
811 {								\
812 	ASSERT(sfmmu_mlist_held(pp));				\
813 	ASSERT(hme->hme_page == pp || IS_PAHME(hme));		\
814 								\
815 	if (pp->p_mapping == NULL) {				\
816 		panic("hme_remove - no mappings");		\
817 	}							\
818 								\
819 	membar_stst();	/* ensure previous stores finish */	\
820 								\
821 	ASSERT(pp->p_share > 0);				\
822 	pp->p_share--;						\
823 								\
824 	if (hme->hme_prev) {					\
825 		ASSERT(pp->p_mapping != hme);			\
826 		ASSERT(hme->hme_prev->hme_page == pp ||		\
827 			IS_PAHME(hme->hme_prev));		\
828 		hme->hme_prev->hme_next = hme->hme_next;	\
829 	} else {						\
830 		ASSERT(pp->p_mapping == hme);			\
831 		pp->p_mapping = hme->hme_next;			\
832 		ASSERT((pp->p_mapping == NULL) ?		\
833 			(pp->p_share == 0) : 1);		\
834 	}							\
835 								\
836 	if (hme->hme_next) {					\
837 		ASSERT(hme->hme_next->hme_page == pp ||		\
838 			IS_PAHME(hme->hme_next));		\
839 		hme->hme_next->hme_prev = hme->hme_prev;	\
840 	}							\
841 								\
842 	/* zero out the entry */				\
843 	hme->hme_next = NULL;					\
844 	hme->hme_prev = NULL;					\
845 	hme->hme_page = NULL;					\
846 								\
847 	if (hme_size(hme) > TTE8K) {				\
848 		/* remove mappings for remainder of large pg */	\
849 		sfmmu_rm_large_mappings(pp, hme_size(hme));	\
850 	}							\
851 }
852 
853 /*
854  * This function returns the hment given the hme_blk and a vaddr.
855  * It assumes addr has already been checked to belong to hme_blk's
856  * range.
857  */
858 #define	HBLKTOHME(hment, hmeblkp, addr)					\
859 {									\
860 	int index;							\
861 	HBLKTOHME_IDX(hment, hmeblkp, addr, index)			\
862 }
863 
864 /*
865  * Version of HBLKTOHME that also returns the index in hmeblkp
866  * of the hment.
867  */
868 #define	HBLKTOHME_IDX(hment, hmeblkp, addr, idx)			\
869 {									\
870 	ASSERT(in_hblk_range((hmeblkp), (addr)));			\
871 									\
872 	if (get_hblk_ttesz(hmeblkp) == TTE8K) {				\
873 		idx = (((uintptr_t)(addr) >> MMU_PAGESHIFT) & (NHMENTS-1)); \
874 	} else								\
875 		idx = 0;						\
876 									\
877 	(hment) = &(hmeblkp)->hblk_hme[idx];				\
878 }
879 
880 /*
881  * Disable any page sizes not supported by the CPU
882  */
883 void
884 hat_init_pagesizes()
885 {
886 	int 		i;
887 
888 	mmu_exported_page_sizes = 0;
889 	for (i = TTE8K; i < max_mmu_page_sizes; i++) {
890 		extern int	disable_text_largepages;
891 		extern int	disable_initdata_largepages;
892 
893 		szc_2_userszc[i] = (uint_t)-1;
894 		userszc_2_szc[i] = (uint_t)-1;
895 
896 		if ((mmu_exported_pagesize_mask & (1 << i)) == 0) {
897 			disable_large_pages |= (1 << i);
898 			disable_ism_large_pages |= (1 << i);
899 			disable_text_largepages |= (1 << i);
900 			disable_initdata_largepages |= (1 << i);
901 		} else {
902 			szc_2_userszc[i] = mmu_exported_page_sizes;
903 			userszc_2_szc[mmu_exported_page_sizes] = i;
904 			mmu_exported_page_sizes++;
905 		}
906 	}
907 
908 	disable_auto_large_pages = disable_large_pages;
909 
910 	/*
911 	 * Initialize mmu-specific large page sizes.
912 	 */
913 	if ((mmu_page_sizes == max_mmu_page_sizes) &&
914 	    (&mmu_large_pages_disabled)) {
915 		disable_large_pages |= mmu_large_pages_disabled(HAT_LOAD);
916 		disable_ism_large_pages |=
917 		    mmu_large_pages_disabled(HAT_LOAD_SHARE);
918 		disable_auto_large_pages |=
919 		    mmu_large_pages_disabled(HAT_LOAD_AUTOLPG);
920 	}
921 
922 }
923 
924 /*
925  * Initialize the hardware address translation structures.
926  */
927 void
928 hat_init(void)
929 {
930 	int 		i;
931 	uint_t		sz;
932 	uint_t		maxtsb;
933 	size_t		size;
934 
935 	hat_lock_init();
936 	hat_kstat_init();
937 
938 	/*
939 	 * Hardware-only bits in a TTE
940 	 */
941 	MAKE_TTE_MASK(&hw_tte);
942 
943 	hat_init_pagesizes();
944 
945 	/* Initialize the hash locks */
946 	for (i = 0; i < khmehash_num; i++) {
947 		mutex_init(&khme_hash[i].hmehash_mutex, NULL,
948 		    MUTEX_DEFAULT, NULL);
949 	}
950 	for (i = 0; i < uhmehash_num; i++) {
951 		mutex_init(&uhme_hash[i].hmehash_mutex, NULL,
952 		    MUTEX_DEFAULT, NULL);
953 	}
954 	khmehash_num--;		/* make sure counter starts from 0 */
955 	uhmehash_num--;		/* make sure counter starts from 0 */
956 
957 	/*
958 	 * Allocate context domain structures.
959 	 *
960 	 * A platform may choose to modify max_mmu_ctxdoms in
961 	 * set_platform_defaults(). If a platform does not define
962 	 * a set_platform_defaults() or does not choose to modify
963 	 * max_mmu_ctxdoms, it gets one MMU context domain for every CPU.
964 	 *
965 	 * For sun4v, there will be one global context domain, this is to
966 	 * avoid the ldom cpu substitution problem.
967 	 *
968 	 * For all platforms that have CPUs sharing MMUs, this
969 	 * value must be defined.
970 	 */
971 	if (max_mmu_ctxdoms == 0) {
972 #ifndef sun4v
973 		max_mmu_ctxdoms = max_ncpus;
974 #else /* sun4v */
975 		max_mmu_ctxdoms = 1;
976 #endif /* sun4v */
977 	}
978 
979 	size = max_mmu_ctxdoms * sizeof (mmu_ctx_t *);
980 	mmu_ctxs_tbl = kmem_zalloc(size, KM_SLEEP);
981 
982 	/* mmu_ctx_t is 64 bytes aligned */
983 	mmuctxdom_cache = kmem_cache_create("mmuctxdom_cache",
984 	    sizeof (mmu_ctx_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
985 	/*
986 	 * MMU context domain initialization for the Boot CPU.
987 	 * This needs the context domains array allocated above.
988 	 */
989 	mutex_enter(&cpu_lock);
990 	sfmmu_cpu_init(CPU);
991 	mutex_exit(&cpu_lock);
992 
993 	/*
994 	 * Intialize ism mapping list lock.
995 	 */
996 
997 	mutex_init(&ism_mlist_lock, NULL, MUTEX_DEFAULT, NULL);
998 
999 	/*
1000 	 * Each sfmmu structure carries an array of MMU context info
1001 	 * structures, one per context domain. The size of this array depends
1002 	 * on the maximum number of context domains. So, the size of the
1003 	 * sfmmu structure varies per platform.
1004 	 *
1005 	 * sfmmu is allocated from static arena, because trap
1006 	 * handler at TL > 0 is not allowed to touch kernel relocatable
1007 	 * memory. sfmmu's alignment is changed to 64 bytes from
1008 	 * default 8 bytes, as the lower 6 bits will be used to pass
1009 	 * pgcnt to vtag_flush_pgcnt_tl1.
1010 	 */
1011 	size = sizeof (sfmmu_t) + sizeof (sfmmu_ctx_t) * (max_mmu_ctxdoms - 1);
1012 
1013 	sfmmuid_cache = kmem_cache_create("sfmmuid_cache", size,
1014 	    64, sfmmu_idcache_constructor, sfmmu_idcache_destructor,
1015 	    NULL, NULL, static_arena, 0);
1016 
1017 	sfmmu_tsbinfo_cache = kmem_cache_create("sfmmu_tsbinfo_cache",
1018 	    sizeof (struct tsb_info), 0, NULL, NULL, NULL, NULL, NULL, 0);
1019 
1020 	/*
1021 	 * Since we only use the tsb8k cache to "borrow" pages for TSBs
1022 	 * from the heap when low on memory or when TSB_FORCEALLOC is
1023 	 * specified, don't use magazines to cache them--we want to return
1024 	 * them to the system as quickly as possible.
1025 	 */
1026 	sfmmu_tsb8k_cache = kmem_cache_create("sfmmu_tsb8k_cache",
1027 	    MMU_PAGESIZE, MMU_PAGESIZE, NULL, NULL, NULL, NULL,
1028 	    static_arena, KMC_NOMAGAZINE);
1029 
1030 	/*
1031 	 * Set tsb_alloc_hiwater to 1/tsb_alloc_hiwater_factor of physical
1032 	 * memory, which corresponds to the old static reserve for TSBs.
1033 	 * tsb_alloc_hiwater_factor defaults to 32.  This caps the amount of
1034 	 * memory we'll allocate for TSB slabs; beyond this point TSB
1035 	 * allocations will be taken from the kernel heap (via
1036 	 * sfmmu_tsb8k_cache) and will be throttled as would any other kmem
1037 	 * consumer.
1038 	 */
1039 	if (tsb_alloc_hiwater_factor == 0) {
1040 		tsb_alloc_hiwater_factor = TSB_ALLOC_HIWATER_FACTOR_DEFAULT;
1041 	}
1042 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
1043 
1044 	/* Set tsb_max_growsize. */
1045 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
1046 
1047 	/*
1048 	 * On smaller memory systems, allocate TSB memory in smaller chunks
1049 	 * than the default 4M slab size. We also honor disable_large_pages
1050 	 * here.
1051 	 *
1052 	 * The trap handlers need to be patched with the final slab shift,
1053 	 * since they need to be able to construct the TSB pointer at runtime.
1054 	 */
1055 	if (tsb_max_growsize <= TSB_512K_SZCODE)
1056 		tsb_slab_ttesz = TTE512K;
1057 
1058 	for (sz = tsb_slab_ttesz; sz > 0; sz--) {
1059 		if (!(disable_large_pages & (1 << sz)))
1060 			break;
1061 	}
1062 
1063 	tsb_slab_ttesz = sz;
1064 	tsb_slab_shift = MMU_PAGESHIFT + (sz << 1) + sz;
1065 	tsb_slab_size = 1 << tsb_slab_shift;
1066 	tsb_slab_mask = (1 << (tsb_slab_shift - MMU_PAGESHIFT)) - 1;
1067 
1068 	maxtsb = tsb_slab_shift - (TSB_START_SIZE + TSB_ENTRY_SHIFT);
1069 	if (tsb_max_growsize > maxtsb)
1070 		tsb_max_growsize = maxtsb;
1071 
1072 	/*
1073 	 * Set up memory callback to update tsb_alloc_hiwater and
1074 	 * tsb_max_growsize.
1075 	 */
1076 	i = kphysm_setup_func_register(&sfmmu_update_tsb_vec, (void *) 0);
1077 	ASSERT(i == 0);
1078 
1079 	/*
1080 	 * kmem_tsb_arena is the source from which large TSB slabs are
1081 	 * drawn.  The quantum of this arena corresponds to the largest
1082 	 * TSB size we can dynamically allocate for user processes.
1083 	 * Currently it must also be a supported page size since we
1084 	 * use exactly one translation entry to map each slab page.
1085 	 *
1086 	 * The per-lgroup kmem_tsb_default_arena arenas are the arenas from
1087 	 * which most TSBs are allocated.  Since most TSB allocations are
1088 	 * typically 8K we have a kmem cache we stack on top of each
1089 	 * kmem_tsb_default_arena to speed up those allocations.
1090 	 *
1091 	 * Note the two-level scheme of arenas is required only
1092 	 * because vmem_create doesn't allow us to specify alignment
1093 	 * requirements.  If this ever changes the code could be
1094 	 * simplified to use only one level of arenas.
1095 	 */
1096 	kmem_tsb_arena = vmem_create("kmem_tsb", NULL, 0, tsb_slab_size,
1097 	    sfmmu_vmem_xalloc_aligned_wrapper, vmem_xfree, heap_arena,
1098 	    0, VM_SLEEP);
1099 
1100 	if (tsb_lgrp_affinity) {
1101 		char s[50];
1102 		for (i = 0; i < NLGRPS_MAX; i++) {
1103 			(void) sprintf(s, "kmem_tsb_lgrp%d", i);
1104 			kmem_tsb_default_arena[i] =
1105 			    vmem_create(s, NULL, 0, PAGESIZE,
1106 			    sfmmu_tsb_segkmem_alloc, sfmmu_tsb_segkmem_free,
1107 			    kmem_tsb_arena, 0, VM_SLEEP | VM_BESTFIT);
1108 			(void) sprintf(s, "sfmmu_tsb_lgrp%d_cache", i);
1109 			sfmmu_tsb_cache[i] = kmem_cache_create(s, PAGESIZE,
1110 			    PAGESIZE, NULL, NULL, NULL, NULL,
1111 			    kmem_tsb_default_arena[i], 0);
1112 		}
1113 	} else {
1114 		kmem_tsb_default_arena[0] = vmem_create("kmem_tsb_default",
1115 		    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1116 		    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1117 		    VM_SLEEP | VM_BESTFIT);
1118 
1119 		sfmmu_tsb_cache[0] = kmem_cache_create("sfmmu_tsb_cache",
1120 		    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1121 		    kmem_tsb_default_arena[0], 0);
1122 	}
1123 
1124 	sfmmu8_cache = kmem_cache_create("sfmmu8_cache", HME8BLK_SZ,
1125 		HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1126 		sfmmu_hblkcache_destructor,
1127 		sfmmu_hblkcache_reclaim, (void *)HME8BLK_SZ,
1128 		hat_memload_arena, KMC_NOHASH);
1129 
1130 	hat_memload1_arena = vmem_create("hat_memload1", NULL, 0, PAGESIZE,
1131 	    segkmem_alloc_permanent, segkmem_free, heap_arena, 0, VM_SLEEP);
1132 
1133 	sfmmu1_cache = kmem_cache_create("sfmmu1_cache", HME1BLK_SZ,
1134 		HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1135 		sfmmu_hblkcache_destructor,
1136 		NULL, (void *)HME1BLK_SZ,
1137 		hat_memload1_arena, KMC_NOHASH);
1138 
1139 	pa_hment_cache = kmem_cache_create("pa_hment_cache", PAHME_SZ,
1140 		0, NULL, NULL, NULL, NULL, static_arena, KMC_NOHASH);
1141 
1142 	ism_blk_cache = kmem_cache_create("ism_blk_cache",
1143 		sizeof (ism_blk_t), ecache_alignsize, NULL, NULL,
1144 		NULL, NULL, static_arena, KMC_NOHASH);
1145 
1146 	ism_ment_cache = kmem_cache_create("ism_ment_cache",
1147 		sizeof (ism_ment_t), 0, NULL, NULL,
1148 		NULL, NULL, NULL, 0);
1149 
1150 	/*
1151 	 * We grab the first hat for the kernel,
1152 	 */
1153 	AS_LOCK_ENTER(&kas, &kas.a_lock, RW_WRITER);
1154 	kas.a_hat = hat_alloc(&kas);
1155 	AS_LOCK_EXIT(&kas, &kas.a_lock);
1156 
1157 	/*
1158 	 * Initialize hblk_reserve.
1159 	 */
1160 	((struct hme_blk *)hblk_reserve)->hblk_nextpa =
1161 				va_to_pa((caddr_t)hblk_reserve);
1162 
1163 #ifndef UTSB_PHYS
1164 	/*
1165 	 * Reserve some kernel virtual address space for the locked TTEs
1166 	 * that allow us to probe the TSB from TL>0.
1167 	 */
1168 	utsb_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1169 		0, 0, NULL, NULL, VM_SLEEP);
1170 	utsb4m_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1171 		0, 0, NULL, NULL, VM_SLEEP);
1172 #endif
1173 
1174 #ifdef VAC
1175 	/*
1176 	 * The big page VAC handling code assumes VAC
1177 	 * will not be bigger than the smallest big
1178 	 * page- which is 64K.
1179 	 */
1180 	if (TTEPAGES(TTE64K) < CACHE_NUM_COLOR) {
1181 		cmn_err(CE_PANIC, "VAC too big!");
1182 	}
1183 #endif
1184 
1185 	(void) xhat_init();
1186 
1187 	uhme_hash_pa = va_to_pa(uhme_hash);
1188 	khme_hash_pa = va_to_pa(khme_hash);
1189 
1190 	/*
1191 	 * Initialize relocation locks. kpr_suspendlock is held
1192 	 * at PIL_MAX to prevent interrupts from pinning the holder
1193 	 * of a suspended TTE which may access it leading to a
1194 	 * deadlock condition.
1195 	 */
1196 	mutex_init(&kpr_mutex, NULL, MUTEX_DEFAULT, NULL);
1197 	mutex_init(&kpr_suspendlock, NULL, MUTEX_SPIN, (void *)PIL_MAX);
1198 }
1199 
1200 /*
1201  * Initialize locking for the hat layer, called early during boot.
1202  */
1203 static void
1204 hat_lock_init()
1205 {
1206 	int i;
1207 
1208 	/*
1209 	 * initialize the array of mutexes protecting a page's mapping
1210 	 * list and p_nrm field.
1211 	 */
1212 	for (i = 0; i < mml_table_sz; i++)
1213 		mutex_init(&mml_table[i], NULL, MUTEX_DEFAULT, NULL);
1214 
1215 	if (kpm_enable) {
1216 		for (i = 0; i < kpmp_table_sz; i++) {
1217 			mutex_init(&kpmp_table[i].khl_mutex, NULL,
1218 			    MUTEX_DEFAULT, NULL);
1219 		}
1220 	}
1221 
1222 	/*
1223 	 * Initialize array of mutex locks that protects sfmmu fields and
1224 	 * TSB lists.
1225 	 */
1226 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
1227 		mutex_init(HATLOCK_MUTEXP(&hat_lock[i]), NULL, MUTEX_DEFAULT,
1228 		    NULL);
1229 }
1230 
1231 extern caddr_t kmem64_base, kmem64_end;
1232 
1233 #define	SFMMU_KERNEL_MAXVA \
1234 	(kmem64_base ? (uintptr_t)kmem64_end : (SYSLIMIT))
1235 
1236 /*
1237  * Allocate a hat structure.
1238  * Called when an address space first uses a hat.
1239  */
1240 struct hat *
1241 hat_alloc(struct as *as)
1242 {
1243 	sfmmu_t *sfmmup;
1244 	int i;
1245 	uint64_t cnum;
1246 	extern uint_t get_color_start(struct as *);
1247 
1248 	ASSERT(AS_WRITE_HELD(as, &as->a_lock));
1249 	sfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
1250 	sfmmup->sfmmu_as = as;
1251 	sfmmup->sfmmu_flags = 0;
1252 	LOCK_INIT_CLEAR(&sfmmup->sfmmu_ctx_lock);
1253 
1254 	if (as == &kas) {
1255 		ksfmmup = sfmmup;
1256 		sfmmup->sfmmu_cext = 0;
1257 		cnum = KCONTEXT;
1258 
1259 		sfmmup->sfmmu_clrstart = 0;
1260 		sfmmup->sfmmu_tsb = NULL;
1261 		/*
1262 		 * hat_kern_setup() will call sfmmu_init_ktsbinfo()
1263 		 * to setup tsb_info for ksfmmup.
1264 		 */
1265 	} else {
1266 
1267 		/*
1268 		 * Just set to invalid ctx. When it faults, it will
1269 		 * get a valid ctx. This would avoid the situation
1270 		 * where we get a ctx, but it gets stolen and then
1271 		 * we fault when we try to run and so have to get
1272 		 * another ctx.
1273 		 */
1274 		sfmmup->sfmmu_cext = 0;
1275 		cnum = INVALID_CONTEXT;
1276 
1277 		/* initialize original physical page coloring bin */
1278 		sfmmup->sfmmu_clrstart = get_color_start(as);
1279 #ifdef DEBUG
1280 		if (tsb_random_size) {
1281 			uint32_t randval = (uint32_t)gettick() >> 4;
1282 			int size = randval % (tsb_max_growsize + 1);
1283 
1284 			/* chose a random tsb size for stress testing */
1285 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb, size,
1286 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1287 		} else
1288 #endif /* DEBUG */
1289 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb,
1290 			    default_tsb_size,
1291 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1292 		sfmmup->sfmmu_flags = HAT_SWAPPED;
1293 		ASSERT(sfmmup->sfmmu_tsb != NULL);
1294 	}
1295 
1296 	ASSERT(max_mmu_ctxdoms > 0);
1297 	for (i = 0; i < max_mmu_ctxdoms; i++) {
1298 		sfmmup->sfmmu_ctxs[i].cnum = cnum;
1299 		sfmmup->sfmmu_ctxs[i].gnum = 0;
1300 	}
1301 
1302 	sfmmu_setup_tsbinfo(sfmmup);
1303 	for (i = 0; i < max_mmu_page_sizes; i++) {
1304 		sfmmup->sfmmu_ttecnt[i] = 0;
1305 		sfmmup->sfmmu_ismttecnt[i] = 0;
1306 		sfmmup->sfmmu_pgsz[i] = TTE8K;
1307 	}
1308 
1309 	sfmmup->sfmmu_iblk = NULL;
1310 	sfmmup->sfmmu_ismhat = 0;
1311 	sfmmup->sfmmu_ismblkpa = (uint64_t)-1;
1312 	if (sfmmup == ksfmmup) {
1313 		CPUSET_ALL(sfmmup->sfmmu_cpusran);
1314 	} else {
1315 		CPUSET_ZERO(sfmmup->sfmmu_cpusran);
1316 	}
1317 	sfmmup->sfmmu_free = 0;
1318 	sfmmup->sfmmu_rmstat = 0;
1319 	sfmmup->sfmmu_clrbin = sfmmup->sfmmu_clrstart;
1320 	sfmmup->sfmmu_xhat_provider = NULL;
1321 	cv_init(&sfmmup->sfmmu_tsb_cv, NULL, CV_DEFAULT, NULL);
1322 	return (sfmmup);
1323 }
1324 
1325 /*
1326  * Create per-MMU context domain kstats for a given MMU ctx.
1327  */
1328 static void
1329 sfmmu_mmu_kstat_create(mmu_ctx_t *mmu_ctxp)
1330 {
1331 	mmu_ctx_stat_t	stat;
1332 	kstat_t		*mmu_kstat;
1333 
1334 	ASSERT(MUTEX_HELD(&cpu_lock));
1335 	ASSERT(mmu_ctxp->mmu_kstat == NULL);
1336 
1337 	mmu_kstat = kstat_create("unix", mmu_ctxp->mmu_idx, "mmu_ctx",
1338 	    "hat", KSTAT_TYPE_NAMED, MMU_CTX_NUM_STATS, KSTAT_FLAG_VIRTUAL);
1339 
1340 	if (mmu_kstat == NULL) {
1341 		cmn_err(CE_WARN, "kstat_create for MMU %d failed",
1342 		    mmu_ctxp->mmu_idx);
1343 	} else {
1344 		mmu_kstat->ks_data = mmu_ctxp->mmu_kstat_data;
1345 		for (stat = 0; stat < MMU_CTX_NUM_STATS; stat++)
1346 			kstat_named_init(&mmu_ctxp->mmu_kstat_data[stat],
1347 			    mmu_ctx_kstat_names[stat], KSTAT_DATA_INT64);
1348 		mmu_ctxp->mmu_kstat = mmu_kstat;
1349 		kstat_install(mmu_kstat);
1350 	}
1351 }
1352 
1353 /*
1354  * plat_cpuid_to_mmu_ctx_info() is a platform interface that returns MMU
1355  * context domain information for a given CPU. If a platform does not
1356  * specify that interface, then the function below is used instead to return
1357  * default information. The defaults are as follows:
1358  *
1359  *	- For sun4u systems there's one MMU context domain per CPU.
1360  *	  This default is used by all sun4u systems except OPL. OPL systems
1361  *	  provide platform specific interface to map CPU ids to MMU ids
1362  *	  because on OPL more than 1 CPU shares a single MMU.
1363  *        Note that on sun4v, there is one global context domain for
1364  *	  the entire system. This is to avoid running into potential problem
1365  *	  with ldom physical cpu substitution feature.
1366  *	- The number of MMU context IDs supported on any CPU in the
1367  *	  system is 8K.
1368  */
1369 /*ARGSUSED*/
1370 static void
1371 sfmmu_cpuid_to_mmu_ctx_info(processorid_t cpuid, mmu_ctx_info_t *infop)
1372 {
1373 	infop->mmu_nctxs = nctxs;
1374 #ifndef sun4v
1375 	infop->mmu_idx = cpu[cpuid]->cpu_seqid;
1376 #else /* sun4v */
1377 	infop->mmu_idx = 0;
1378 #endif /* sun4v */
1379 }
1380 
1381 /*
1382  * Called during CPU initialization to set the MMU context-related information
1383  * for a CPU.
1384  *
1385  * cpu_lock serializes accesses to mmu_ctxs and mmu_saved_gnum.
1386  */
1387 void
1388 sfmmu_cpu_init(cpu_t *cp)
1389 {
1390 	mmu_ctx_info_t	info;
1391 	mmu_ctx_t	*mmu_ctxp;
1392 
1393 	ASSERT(MUTEX_HELD(&cpu_lock));
1394 
1395 	if (&plat_cpuid_to_mmu_ctx_info == NULL)
1396 		sfmmu_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1397 	else
1398 		plat_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1399 
1400 	ASSERT(info.mmu_idx < max_mmu_ctxdoms);
1401 
1402 	if ((mmu_ctxp = mmu_ctxs_tbl[info.mmu_idx]) == NULL) {
1403 		/* Each mmu_ctx is cacheline aligned. */
1404 		mmu_ctxp = kmem_cache_alloc(mmuctxdom_cache, KM_SLEEP);
1405 		bzero(mmu_ctxp, sizeof (mmu_ctx_t));
1406 
1407 		mutex_init(&mmu_ctxp->mmu_lock, NULL, MUTEX_SPIN,
1408 		    (void *)ipltospl(DISP_LEVEL));
1409 		mmu_ctxp->mmu_idx = info.mmu_idx;
1410 		mmu_ctxp->mmu_nctxs = info.mmu_nctxs;
1411 		/*
1412 		 * Globally for lifetime of a system,
1413 		 * gnum must always increase.
1414 		 * mmu_saved_gnum is protected by the cpu_lock.
1415 		 */
1416 		mmu_ctxp->mmu_gnum = mmu_saved_gnum + 1;
1417 		mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
1418 
1419 		sfmmu_mmu_kstat_create(mmu_ctxp);
1420 
1421 		mmu_ctxs_tbl[info.mmu_idx] = mmu_ctxp;
1422 	} else {
1423 		ASSERT(mmu_ctxp->mmu_idx == info.mmu_idx);
1424 	}
1425 
1426 	/*
1427 	 * The mmu_lock is acquired here to prevent races with
1428 	 * the wrap-around code.
1429 	 */
1430 	mutex_enter(&mmu_ctxp->mmu_lock);
1431 
1432 
1433 	mmu_ctxp->mmu_ncpus++;
1434 	CPUSET_ADD(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1435 	CPU_MMU_IDX(cp) = info.mmu_idx;
1436 	CPU_MMU_CTXP(cp) = mmu_ctxp;
1437 
1438 	mutex_exit(&mmu_ctxp->mmu_lock);
1439 }
1440 
1441 /*
1442  * Called to perform MMU context-related cleanup for a CPU.
1443  */
1444 void
1445 sfmmu_cpu_cleanup(cpu_t *cp)
1446 {
1447 	mmu_ctx_t	*mmu_ctxp;
1448 
1449 	ASSERT(MUTEX_HELD(&cpu_lock));
1450 
1451 	mmu_ctxp = CPU_MMU_CTXP(cp);
1452 	ASSERT(mmu_ctxp != NULL);
1453 
1454 	/*
1455 	 * The mmu_lock is acquired here to prevent races with
1456 	 * the wrap-around code.
1457 	 */
1458 	mutex_enter(&mmu_ctxp->mmu_lock);
1459 
1460 	CPU_MMU_CTXP(cp) = NULL;
1461 
1462 	CPUSET_DEL(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1463 	if (--mmu_ctxp->mmu_ncpus == 0) {
1464 		mmu_ctxs_tbl[mmu_ctxp->mmu_idx] = NULL;
1465 		mutex_exit(&mmu_ctxp->mmu_lock);
1466 		mutex_destroy(&mmu_ctxp->mmu_lock);
1467 
1468 		if (mmu_ctxp->mmu_kstat)
1469 			kstat_delete(mmu_ctxp->mmu_kstat);
1470 
1471 		/* mmu_saved_gnum is protected by the cpu_lock. */
1472 		if (mmu_saved_gnum < mmu_ctxp->mmu_gnum)
1473 			mmu_saved_gnum = mmu_ctxp->mmu_gnum;
1474 
1475 		kmem_cache_free(mmuctxdom_cache, mmu_ctxp);
1476 
1477 		return;
1478 	}
1479 
1480 	mutex_exit(&mmu_ctxp->mmu_lock);
1481 }
1482 
1483 /*
1484  * Hat_setup, makes an address space context the current active one.
1485  * In sfmmu this translates to setting the secondary context with the
1486  * corresponding context.
1487  */
1488 void
1489 hat_setup(struct hat *sfmmup, int allocflag)
1490 {
1491 	hatlock_t *hatlockp;
1492 
1493 	/* Init needs some special treatment. */
1494 	if (allocflag == HAT_INIT) {
1495 		/*
1496 		 * Make sure that we have
1497 		 * 1. a TSB
1498 		 * 2. a valid ctx that doesn't get stolen after this point.
1499 		 */
1500 		hatlockp = sfmmu_hat_enter(sfmmup);
1501 
1502 		/*
1503 		 * Swap in the TSB.  hat_init() allocates tsbinfos without
1504 		 * TSBs, but we need one for init, since the kernel does some
1505 		 * special things to set up its stack and needs the TSB to
1506 		 * resolve page faults.
1507 		 */
1508 		sfmmu_tsb_swapin(sfmmup, hatlockp);
1509 
1510 		sfmmu_get_ctx(sfmmup);
1511 
1512 		sfmmu_hat_exit(hatlockp);
1513 	} else {
1514 		ASSERT(allocflag == HAT_ALLOC);
1515 
1516 		hatlockp = sfmmu_hat_enter(sfmmup);
1517 		kpreempt_disable();
1518 
1519 		CPUSET_ADD(sfmmup->sfmmu_cpusran, CPU->cpu_id);
1520 
1521 		/*
1522 		 * sfmmu_setctx_sec takes <pgsz|cnum> as a parameter,
1523 		 * pagesize bits don't matter in this case since we are passing
1524 		 * INVALID_CONTEXT to it.
1525 		 */
1526 		sfmmu_setctx_sec(INVALID_CONTEXT);
1527 		sfmmu_clear_utsbinfo();
1528 
1529 		kpreempt_enable();
1530 		sfmmu_hat_exit(hatlockp);
1531 	}
1532 }
1533 
1534 /*
1535  * Free all the translation resources for the specified address space.
1536  * Called from as_free when an address space is being destroyed.
1537  */
1538 void
1539 hat_free_start(struct hat *sfmmup)
1540 {
1541 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
1542 	ASSERT(sfmmup != ksfmmup);
1543 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1544 
1545 	sfmmup->sfmmu_free = 1;
1546 }
1547 
1548 void
1549 hat_free_end(struct hat *sfmmup)
1550 {
1551 	int i;
1552 
1553 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1554 	if (sfmmup->sfmmu_ismhat) {
1555 		for (i = 0; i < mmu_page_sizes; i++) {
1556 			sfmmup->sfmmu_ttecnt[i] = 0;
1557 			sfmmup->sfmmu_ismttecnt[i] = 0;
1558 		}
1559 	} else {
1560 		/* EMPTY */
1561 		ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
1562 		ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
1563 		ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
1564 		ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
1565 		ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
1566 		ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
1567 	}
1568 
1569 	if (sfmmup->sfmmu_rmstat) {
1570 		hat_freestat(sfmmup->sfmmu_as, NULL);
1571 	}
1572 
1573 	while (sfmmup->sfmmu_tsb != NULL) {
1574 		struct tsb_info *next = sfmmup->sfmmu_tsb->tsb_next;
1575 		sfmmu_tsbinfo_free(sfmmup->sfmmu_tsb);
1576 		sfmmup->sfmmu_tsb = next;
1577 	}
1578 	sfmmu_free_sfmmu(sfmmup);
1579 
1580 	kmem_cache_free(sfmmuid_cache, sfmmup);
1581 }
1582 
1583 /*
1584  * Set up any translation structures, for the specified address space,
1585  * that are needed or preferred when the process is being swapped in.
1586  */
1587 /* ARGSUSED */
1588 void
1589 hat_swapin(struct hat *hat)
1590 {
1591 	ASSERT(hat->sfmmu_xhat_provider == NULL);
1592 }
1593 
1594 /*
1595  * Free all of the translation resources, for the specified address space,
1596  * that can be freed while the process is swapped out. Called from as_swapout.
1597  * Also, free up the ctx that this process was using.
1598  */
1599 void
1600 hat_swapout(struct hat *sfmmup)
1601 {
1602 	struct hmehash_bucket *hmebp;
1603 	struct hme_blk *hmeblkp;
1604 	struct hme_blk *pr_hblk = NULL;
1605 	struct hme_blk *nx_hblk;
1606 	int i;
1607 	uint64_t hblkpa, prevpa, nx_pa;
1608 	struct hme_blk *list = NULL;
1609 	hatlock_t *hatlockp;
1610 	struct tsb_info *tsbinfop;
1611 	struct free_tsb {
1612 		struct free_tsb *next;
1613 		struct tsb_info *tsbinfop;
1614 	};			/* free list of TSBs */
1615 	struct free_tsb *freelist, *last, *next;
1616 
1617 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
1618 	SFMMU_STAT(sf_swapout);
1619 
1620 	/*
1621 	 * There is no way to go from an as to all its translations in sfmmu.
1622 	 * Here is one of the times when we take the big hit and traverse
1623 	 * the hash looking for hme_blks to free up.  Not only do we free up
1624 	 * this as hme_blks but all those that are free.  We are obviously
1625 	 * swapping because we need memory so let's free up as much
1626 	 * as we can.
1627 	 *
1628 	 * Note that we don't flush TLB/TSB here -- it's not necessary
1629 	 * because:
1630 	 *  1) we free the ctx we're using and throw away the TSB(s);
1631 	 *  2) processes aren't runnable while being swapped out.
1632 	 */
1633 	ASSERT(sfmmup != KHATID);
1634 	for (i = 0; i <= UHMEHASH_SZ; i++) {
1635 		hmebp = &uhme_hash[i];
1636 		SFMMU_HASH_LOCK(hmebp);
1637 		hmeblkp = hmebp->hmeblkp;
1638 		hblkpa = hmebp->hmeh_nextpa;
1639 		prevpa = 0;
1640 		pr_hblk = NULL;
1641 		while (hmeblkp) {
1642 
1643 			ASSERT(!hmeblkp->hblk_xhat_bit);
1644 
1645 			if ((hmeblkp->hblk_tag.htag_id == sfmmup) &&
1646 			    !hmeblkp->hblk_shw_bit && !hmeblkp->hblk_lckcnt) {
1647 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
1648 					(caddr_t)get_hblk_base(hmeblkp),
1649 					get_hblk_endaddr(hmeblkp),
1650 					NULL, HAT_UNLOAD);
1651 			}
1652 			nx_hblk = hmeblkp->hblk_next;
1653 			nx_pa = hmeblkp->hblk_nextpa;
1654 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
1655 				ASSERT(!hmeblkp->hblk_lckcnt);
1656 				sfmmu_hblk_hash_rm(hmebp, hmeblkp,
1657 					prevpa, pr_hblk);
1658 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
1659 			} else {
1660 				pr_hblk = hmeblkp;
1661 				prevpa = hblkpa;
1662 			}
1663 			hmeblkp = nx_hblk;
1664 			hblkpa = nx_pa;
1665 		}
1666 		SFMMU_HASH_UNLOCK(hmebp);
1667 	}
1668 
1669 	sfmmu_hblks_list_purge(&list);
1670 
1671 	/*
1672 	 * Now free up the ctx so that others can reuse it.
1673 	 */
1674 	hatlockp = sfmmu_hat_enter(sfmmup);
1675 
1676 	sfmmu_invalidate_ctx(sfmmup);
1677 
1678 	/*
1679 	 * Free TSBs, but not tsbinfos, and set SWAPPED flag.
1680 	 * If TSBs were never swapped in, just return.
1681 	 * This implies that we don't support partial swapping
1682 	 * of TSBs -- either all are swapped out, or none are.
1683 	 *
1684 	 * We must hold the HAT lock here to prevent racing with another
1685 	 * thread trying to unmap TTEs from the TSB or running the post-
1686 	 * relocator after relocating the TSB's memory.  Unfortunately, we
1687 	 * can't free memory while holding the HAT lock or we could
1688 	 * deadlock, so we build a list of TSBs to be freed after marking
1689 	 * the tsbinfos as swapped out and free them after dropping the
1690 	 * lock.
1691 	 */
1692 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
1693 		sfmmu_hat_exit(hatlockp);
1694 		return;
1695 	}
1696 
1697 	SFMMU_FLAGS_SET(sfmmup, HAT_SWAPPED);
1698 	last = freelist = NULL;
1699 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
1700 	    tsbinfop = tsbinfop->tsb_next) {
1701 		ASSERT((tsbinfop->tsb_flags & TSB_SWAPPED) == 0);
1702 
1703 		/*
1704 		 * Cast the TSB into a struct free_tsb and put it on the free
1705 		 * list.
1706 		 */
1707 		if (freelist == NULL) {
1708 			last = freelist = (struct free_tsb *)tsbinfop->tsb_va;
1709 		} else {
1710 			last->next = (struct free_tsb *)tsbinfop->tsb_va;
1711 			last = last->next;
1712 		}
1713 		last->next = NULL;
1714 		last->tsbinfop = tsbinfop;
1715 		tsbinfop->tsb_flags |= TSB_SWAPPED;
1716 		/*
1717 		 * Zero out the TTE to clear the valid bit.
1718 		 * Note we can't use a value like 0xbad because we want to
1719 		 * ensure diagnostic bits are NEVER set on TTEs that might
1720 		 * be loaded.  The intent is to catch any invalid access
1721 		 * to the swapped TSB, such as a thread running with a valid
1722 		 * context without first calling sfmmu_tsb_swapin() to
1723 		 * allocate TSB memory.
1724 		 */
1725 		tsbinfop->tsb_tte.ll = 0;
1726 	}
1727 
1728 	/* Now we can drop the lock and free the TSB memory. */
1729 	sfmmu_hat_exit(hatlockp);
1730 	for (; freelist != NULL; freelist = next) {
1731 		next = freelist->next;
1732 		sfmmu_tsb_free(freelist->tsbinfop);
1733 	}
1734 }
1735 
1736 /*
1737  * Duplicate the translations of an as into another newas
1738  */
1739 /* ARGSUSED */
1740 int
1741 hat_dup(struct hat *hat, struct hat *newhat, caddr_t addr, size_t len,
1742 	uint_t flag)
1743 {
1744 	ASSERT(hat->sfmmu_xhat_provider == NULL);
1745 	ASSERT((flag == 0) || (flag == HAT_DUP_ALL) || (flag == HAT_DUP_COW));
1746 
1747 	if (flag == HAT_DUP_COW) {
1748 		panic("hat_dup: HAT_DUP_COW not supported");
1749 	}
1750 	return (0);
1751 }
1752 
1753 /*
1754  * Set up addr to map to page pp with protection prot.
1755  * As an optimization we also load the TSB with the
1756  * corresponding tte but it is no big deal if  the tte gets kicked out.
1757  */
1758 void
1759 hat_memload(struct hat *hat, caddr_t addr, struct page *pp,
1760 	uint_t attr, uint_t flags)
1761 {
1762 	tte_t tte;
1763 
1764 
1765 	ASSERT(hat != NULL);
1766 	ASSERT(PAGE_LOCKED(pp));
1767 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
1768 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
1769 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
1770 
1771 	if (PP_ISFREE(pp)) {
1772 		panic("hat_memload: loading a mapping to free page %p",
1773 		    (void *)pp);
1774 	}
1775 
1776 	if (hat->sfmmu_xhat_provider) {
1777 		XHAT_MEMLOAD(hat, addr, pp, attr, flags);
1778 		return;
1779 	}
1780 
1781 	ASSERT((hat == ksfmmup) ||
1782 		AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
1783 
1784 	if (flags & ~SFMMU_LOAD_ALLFLAG)
1785 		cmn_err(CE_NOTE, "hat_memload: unsupported flags %d",
1786 		    flags & ~SFMMU_LOAD_ALLFLAG);
1787 
1788 	if (hat->sfmmu_rmstat)
1789 		hat_resvstat(MMU_PAGESIZE, hat->sfmmu_as, addr);
1790 
1791 #if defined(SF_ERRATA_57)
1792 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
1793 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
1794 	    !(flags & HAT_LOAD_SHARE)) {
1795 		cmn_err(CE_WARN, "hat_memload: illegal attempt to make user "
1796 		    " page executable");
1797 		attr &= ~PROT_EXEC;
1798 	}
1799 #endif
1800 
1801 	sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
1802 	(void) sfmmu_tteload_array(hat, &tte, addr, &pp, flags);
1803 
1804 	/*
1805 	 * Check TSB and TLB page sizes.
1806 	 */
1807 	if ((flags & HAT_LOAD_SHARE) == 0) {
1808 		sfmmu_check_page_sizes(hat, 1);
1809 	}
1810 }
1811 
1812 /*
1813  * hat_devload can be called to map real memory (e.g.
1814  * /dev/kmem) and even though hat_devload will determine pf is
1815  * for memory, it will be unable to get a shared lock on the
1816  * page (because someone else has it exclusively) and will
1817  * pass dp = NULL.  If tteload doesn't get a non-NULL
1818  * page pointer it can't cache memory.
1819  */
1820 void
1821 hat_devload(struct hat *hat, caddr_t addr, size_t len, pfn_t pfn,
1822 	uint_t attr, int flags)
1823 {
1824 	tte_t tte;
1825 	struct page *pp = NULL;
1826 	int use_lgpg = 0;
1827 
1828 	ASSERT(hat != NULL);
1829 
1830 	if (hat->sfmmu_xhat_provider) {
1831 		XHAT_DEVLOAD(hat, addr, len, pfn, attr, flags);
1832 		return;
1833 	}
1834 
1835 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
1836 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
1837 	ASSERT((hat == ksfmmup) ||
1838 		AS_LOCK_HELD(hat->sfmmu_as, &hat->sfmmu_as->a_lock));
1839 	if (len == 0)
1840 		panic("hat_devload: zero len");
1841 	if (flags & ~SFMMU_LOAD_ALLFLAG)
1842 		cmn_err(CE_NOTE, "hat_devload: unsupported flags %d",
1843 		    flags & ~SFMMU_LOAD_ALLFLAG);
1844 
1845 #if defined(SF_ERRATA_57)
1846 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
1847 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
1848 	    !(flags & HAT_LOAD_SHARE)) {
1849 		cmn_err(CE_WARN, "hat_devload: illegal attempt to make user "
1850 		    " page executable");
1851 		attr &= ~PROT_EXEC;
1852 	}
1853 #endif
1854 
1855 	/*
1856 	 * If it's a memory page find its pp
1857 	 */
1858 	if (!(flags & HAT_LOAD_NOCONSIST) && pf_is_memory(pfn)) {
1859 		pp = page_numtopp_nolock(pfn);
1860 		if (pp == NULL) {
1861 			flags |= HAT_LOAD_NOCONSIST;
1862 		} else {
1863 			if (PP_ISFREE(pp)) {
1864 				panic("hat_memload: loading "
1865 				    "a mapping to free page %p",
1866 				    (void *)pp);
1867 			}
1868 			if (!PAGE_LOCKED(pp) && !PP_ISNORELOC(pp)) {
1869 				panic("hat_memload: loading a mapping "
1870 				    "to unlocked relocatable page %p",
1871 				    (void *)pp);
1872 			}
1873 			ASSERT(len == MMU_PAGESIZE);
1874 		}
1875 	}
1876 
1877 	if (hat->sfmmu_rmstat)
1878 		hat_resvstat(len, hat->sfmmu_as, addr);
1879 
1880 	if (flags & HAT_LOAD_NOCONSIST) {
1881 		attr |= SFMMU_UNCACHEVTTE;
1882 		use_lgpg = 1;
1883 	}
1884 	if (!pf_is_memory(pfn)) {
1885 		attr |= SFMMU_UNCACHEPTTE | HAT_NOSYNC;
1886 		use_lgpg = 1;
1887 		switch (attr & HAT_ORDER_MASK) {
1888 			case HAT_STRICTORDER:
1889 			case HAT_UNORDERED_OK:
1890 				/*
1891 				 * we set the side effect bit for all non
1892 				 * memory mappings unless merging is ok
1893 				 */
1894 				attr |= SFMMU_SIDEFFECT;
1895 				break;
1896 			case HAT_MERGING_OK:
1897 			case HAT_LOADCACHING_OK:
1898 			case HAT_STORECACHING_OK:
1899 				break;
1900 			default:
1901 				panic("hat_devload: bad attr");
1902 				break;
1903 		}
1904 	}
1905 	while (len) {
1906 		if (!use_lgpg) {
1907 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
1908 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
1909 			    flags);
1910 			len -= MMU_PAGESIZE;
1911 			addr += MMU_PAGESIZE;
1912 			pfn++;
1913 			continue;
1914 		}
1915 		/*
1916 		 *  try to use large pages, check va/pa alignments
1917 		 *  Note that 32M/256M page sizes are not (yet) supported.
1918 		 */
1919 		if ((len >= MMU_PAGESIZE4M) &&
1920 		    !((uintptr_t)addr & MMU_PAGEOFFSET4M) &&
1921 		    !(disable_large_pages & (1 << TTE4M)) &&
1922 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET4M)) {
1923 			sfmmu_memtte(&tte, pfn, attr, TTE4M);
1924 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
1925 			    flags);
1926 			len -= MMU_PAGESIZE4M;
1927 			addr += MMU_PAGESIZE4M;
1928 			pfn += MMU_PAGESIZE4M / MMU_PAGESIZE;
1929 		} else if ((len >= MMU_PAGESIZE512K) &&
1930 		    !((uintptr_t)addr & MMU_PAGEOFFSET512K) &&
1931 		    !(disable_large_pages & (1 << TTE512K)) &&
1932 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET512K)) {
1933 			sfmmu_memtte(&tte, pfn, attr, TTE512K);
1934 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
1935 			    flags);
1936 			len -= MMU_PAGESIZE512K;
1937 			addr += MMU_PAGESIZE512K;
1938 			pfn += MMU_PAGESIZE512K / MMU_PAGESIZE;
1939 		} else if ((len >= MMU_PAGESIZE64K) &&
1940 		    !((uintptr_t)addr & MMU_PAGEOFFSET64K) &&
1941 		    !(disable_large_pages & (1 << TTE64K)) &&
1942 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET64K)) {
1943 			sfmmu_memtte(&tte, pfn, attr, TTE64K);
1944 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
1945 			    flags);
1946 			len -= MMU_PAGESIZE64K;
1947 			addr += MMU_PAGESIZE64K;
1948 			pfn += MMU_PAGESIZE64K / MMU_PAGESIZE;
1949 		} else {
1950 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
1951 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
1952 			    flags);
1953 			len -= MMU_PAGESIZE;
1954 			addr += MMU_PAGESIZE;
1955 			pfn++;
1956 		}
1957 	}
1958 
1959 	/*
1960 	 * Check TSB and TLB page sizes.
1961 	 */
1962 	if ((flags & HAT_LOAD_SHARE) == 0) {
1963 		sfmmu_check_page_sizes(hat, 1);
1964 	}
1965 }
1966 
1967 /*
1968  * Map the largest extend possible out of the page array. The array may NOT
1969  * be in order.  The largest possible mapping a page can have
1970  * is specified in the p_szc field.  The p_szc field
1971  * cannot change as long as there any mappings (large or small)
1972  * to any of the pages that make up the large page. (ie. any
1973  * promotion/demotion of page size is not up to the hat but up to
1974  * the page free list manager).  The array
1975  * should consist of properly aligned contigous pages that are
1976  * part of a big page for a large mapping to be created.
1977  */
1978 void
1979 hat_memload_array(struct hat *hat, caddr_t addr, size_t len,
1980 	struct page **pps, uint_t attr, uint_t flags)
1981 {
1982 	int  ttesz;
1983 	size_t mapsz;
1984 	pgcnt_t	numpg, npgs;
1985 	tte_t tte;
1986 	page_t *pp;
1987 	int large_pages_disable;
1988 
1989 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
1990 
1991 	if (hat->sfmmu_xhat_provider) {
1992 		XHAT_MEMLOAD_ARRAY(hat, addr, len, pps, attr, flags);
1993 		return;
1994 	}
1995 
1996 	if (hat->sfmmu_rmstat)
1997 		hat_resvstat(len, hat->sfmmu_as, addr);
1998 
1999 #if defined(SF_ERRATA_57)
2000 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2001 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2002 	    !(flags & HAT_LOAD_SHARE)) {
2003 		cmn_err(CE_WARN, "hat_memload_array: illegal attempt to make "
2004 		    "user page executable");
2005 		attr &= ~PROT_EXEC;
2006 	}
2007 #endif
2008 
2009 	/* Get number of pages */
2010 	npgs = len >> MMU_PAGESHIFT;
2011 
2012 	if (flags & HAT_LOAD_SHARE) {
2013 		large_pages_disable = disable_ism_large_pages;
2014 	} else {
2015 		large_pages_disable = disable_large_pages;
2016 	}
2017 
2018 	if (npgs < NHMENTS || large_pages_disable == LARGE_PAGES_OFF) {
2019 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs);
2020 		return;
2021 	}
2022 
2023 	while (npgs >= NHMENTS) {
2024 		pp = *pps;
2025 		for (ttesz = pp->p_szc; ttesz != TTE8K; ttesz--) {
2026 			/*
2027 			 * Check if this page size is disabled.
2028 			 */
2029 			if (large_pages_disable & (1 << ttesz))
2030 				continue;
2031 
2032 			numpg = TTEPAGES(ttesz);
2033 			mapsz = numpg << MMU_PAGESHIFT;
2034 			if ((npgs >= numpg) &&
2035 			    IS_P2ALIGNED(addr, mapsz) &&
2036 			    IS_P2ALIGNED(pp->p_pagenum, numpg)) {
2037 				/*
2038 				 * At this point we have enough pages and
2039 				 * we know the virtual address and the pfn
2040 				 * are properly aligned.  We still need
2041 				 * to check for physical contiguity but since
2042 				 * it is very likely that this is the case
2043 				 * we will assume they are so and undo
2044 				 * the request if necessary.  It would
2045 				 * be great if we could get a hint flag
2046 				 * like HAT_CONTIG which would tell us
2047 				 * the pages are contigous for sure.
2048 				 */
2049 				sfmmu_memtte(&tte, (*pps)->p_pagenum,
2050 					attr, ttesz);
2051 				if (!sfmmu_tteload_array(hat, &tte, addr,
2052 				    pps, flags)) {
2053 					break;
2054 				}
2055 			}
2056 		}
2057 		if (ttesz == TTE8K) {
2058 			/*
2059 			 * We were not able to map array using a large page
2060 			 * batch a hmeblk or fraction at a time.
2061 			 */
2062 			numpg = ((uintptr_t)addr >> MMU_PAGESHIFT)
2063 				& (NHMENTS-1);
2064 			numpg = NHMENTS - numpg;
2065 			ASSERT(numpg <= npgs);
2066 			mapsz = numpg * MMU_PAGESIZE;
2067 			sfmmu_memload_batchsmall(hat, addr, pps, attr, flags,
2068 							numpg);
2069 		}
2070 		addr += mapsz;
2071 		npgs -= numpg;
2072 		pps += numpg;
2073 	}
2074 
2075 	if (npgs) {
2076 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs);
2077 	}
2078 
2079 	/*
2080 	 * Check TSB and TLB page sizes.
2081 	 */
2082 	if ((flags & HAT_LOAD_SHARE) == 0) {
2083 		sfmmu_check_page_sizes(hat, 1);
2084 	}
2085 }
2086 
2087 /*
2088  * Function tries to batch 8K pages into the same hme blk.
2089  */
2090 static void
2091 sfmmu_memload_batchsmall(struct hat *hat, caddr_t vaddr, page_t **pps,
2092 		    uint_t attr, uint_t flags, pgcnt_t npgs)
2093 {
2094 	tte_t	tte;
2095 	page_t *pp;
2096 	struct hmehash_bucket *hmebp;
2097 	struct hme_blk *hmeblkp;
2098 	int	index;
2099 
2100 	while (npgs) {
2101 		/*
2102 		 * Acquire the hash bucket.
2103 		 */
2104 		hmebp = sfmmu_tteload_acquire_hashbucket(hat, vaddr, TTE8K);
2105 		ASSERT(hmebp);
2106 
2107 		/*
2108 		 * Find the hment block.
2109 		 */
2110 		hmeblkp = sfmmu_tteload_find_hmeblk(hat, hmebp, vaddr,
2111 				TTE8K, flags);
2112 		ASSERT(hmeblkp);
2113 
2114 		do {
2115 			/*
2116 			 * Make the tte.
2117 			 */
2118 			pp = *pps;
2119 			sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2120 
2121 			/*
2122 			 * Add the translation.
2123 			 */
2124 			(void) sfmmu_tteload_addentry(hat, hmeblkp, &tte,
2125 					vaddr, pps, flags);
2126 
2127 			/*
2128 			 * Goto next page.
2129 			 */
2130 			pps++;
2131 			npgs--;
2132 
2133 			/*
2134 			 * Goto next address.
2135 			 */
2136 			vaddr += MMU_PAGESIZE;
2137 
2138 			/*
2139 			 * Don't crossover into a different hmentblk.
2140 			 */
2141 			index = (int)(((uintptr_t)vaddr >> MMU_PAGESHIFT) &
2142 			    (NHMENTS-1));
2143 
2144 		} while (index != 0 && npgs != 0);
2145 
2146 		/*
2147 		 * Release the hash bucket.
2148 		 */
2149 
2150 		sfmmu_tteload_release_hashbucket(hmebp);
2151 	}
2152 }
2153 
2154 /*
2155  * Construct a tte for a page:
2156  *
2157  * tte_valid = 1
2158  * tte_size2 = size & TTE_SZ2_BITS (Panther and Olympus-C only)
2159  * tte_size = size
2160  * tte_nfo = attr & HAT_NOFAULT
2161  * tte_ie = attr & HAT_STRUCTURE_LE
2162  * tte_hmenum = hmenum
2163  * tte_pahi = pp->p_pagenum >> TTE_PASHIFT;
2164  * tte_palo = pp->p_pagenum & TTE_PALOMASK;
2165  * tte_ref = 1 (optimization)
2166  * tte_wr_perm = attr & PROT_WRITE;
2167  * tte_no_sync = attr & HAT_NOSYNC
2168  * tte_lock = attr & SFMMU_LOCKTTE
2169  * tte_cp = !(attr & SFMMU_UNCACHEPTTE)
2170  * tte_cv = !(attr & SFMMU_UNCACHEVTTE)
2171  * tte_e = attr & SFMMU_SIDEFFECT
2172  * tte_priv = !(attr & PROT_USER)
2173  * tte_hwwr = if nosync is set and it is writable we set the mod bit (opt)
2174  * tte_glb = 0
2175  */
2176 void
2177 sfmmu_memtte(tte_t *ttep, pfn_t pfn, uint_t attr, int tte_sz)
2178 {
2179 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2180 
2181 	ttep->tte_inthi = MAKE_TTE_INTHI(pfn, attr, tte_sz, 0 /* hmenum */);
2182 	ttep->tte_intlo = MAKE_TTE_INTLO(pfn, attr, tte_sz, 0 /* hmenum */);
2183 
2184 	if (TTE_IS_NOSYNC(ttep)) {
2185 		TTE_SET_REF(ttep);
2186 		if (TTE_IS_WRITABLE(ttep)) {
2187 			TTE_SET_MOD(ttep);
2188 		}
2189 	}
2190 	if (TTE_IS_NFO(ttep) && TTE_IS_EXECUTABLE(ttep)) {
2191 		panic("sfmmu_memtte: can't set both NFO and EXEC bits");
2192 	}
2193 }
2194 
2195 /*
2196  * This function will add a translation to the hme_blk and allocate the
2197  * hme_blk if one does not exist.
2198  * If a page structure is specified then it will add the
2199  * corresponding hment to the mapping list.
2200  * It will also update the hmenum field for the tte.
2201  */
2202 void
2203 sfmmu_tteload(struct hat *sfmmup, tte_t *ttep, caddr_t vaddr, page_t *pp,
2204 	uint_t flags)
2205 {
2206 	(void) sfmmu_tteload_array(sfmmup, ttep, vaddr, &pp, flags);
2207 }
2208 
2209 /*
2210  * Load (ttep != NULL) or unload (ttep == NULL) one entry in the TSB.
2211  * Assumes that a particular page size may only be resident in one TSB.
2212  */
2213 static void
2214 sfmmu_mod_tsb(sfmmu_t *sfmmup, caddr_t vaddr, tte_t *ttep, int ttesz)
2215 {
2216 	struct tsb_info *tsbinfop = NULL;
2217 	uint64_t tag;
2218 	struct tsbe *tsbe_addr;
2219 	uint64_t tsb_base;
2220 	uint_t tsb_size;
2221 	int vpshift = MMU_PAGESHIFT;
2222 	int phys = 0;
2223 
2224 	if (sfmmup == ksfmmup) { /* No support for 32/256M ksfmmu pages */
2225 		phys = ktsb_phys;
2226 		if (ttesz >= TTE4M) {
2227 #ifndef sun4v
2228 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2229 #endif
2230 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2231 			tsb_size = ktsb4m_szcode;
2232 		} else {
2233 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2234 			tsb_size = ktsb_szcode;
2235 		}
2236 	} else {
2237 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2238 
2239 		/*
2240 		 * If there isn't a TSB for this page size, or the TSB is
2241 		 * swapped out, there is nothing to do.  Note that the latter
2242 		 * case seems impossible but can occur if hat_pageunload()
2243 		 * is called on an ISM mapping while the process is swapped
2244 		 * out.
2245 		 */
2246 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2247 			return;
2248 
2249 		/*
2250 		 * If another thread is in the middle of relocating a TSB
2251 		 * we can't unload the entry so set a flag so that the
2252 		 * TSB will be flushed before it can be accessed by the
2253 		 * process.
2254 		 */
2255 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2256 			if (ttep == NULL)
2257 				tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2258 			return;
2259 		}
2260 #if defined(UTSB_PHYS)
2261 		phys = 1;
2262 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2263 #else
2264 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2265 #endif
2266 		tsb_size = tsbinfop->tsb_szc;
2267 	}
2268 	if (ttesz >= TTE4M)
2269 		vpshift = MMU_PAGESHIFT4M;
2270 
2271 	tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2272 	tag = sfmmu_make_tsbtag(vaddr);
2273 
2274 	if (ttep == NULL) {
2275 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2276 	} else {
2277 		if (ttesz >= TTE4M) {
2278 			SFMMU_STAT(sf_tsb_load4m);
2279 		} else {
2280 			SFMMU_STAT(sf_tsb_load8k);
2281 		}
2282 
2283 		sfmmu_load_tsbe(tsbe_addr, tag, ttep, phys);
2284 	}
2285 }
2286 
2287 /*
2288  * Unmap all entries from [start, end) matching the given page size.
2289  *
2290  * This function is used primarily to unmap replicated 64K or 512K entries
2291  * from the TSB that are inserted using the base page size TSB pointer, but
2292  * it may also be called to unmap a range of addresses from the TSB.
2293  */
2294 void
2295 sfmmu_unload_tsb_range(sfmmu_t *sfmmup, caddr_t start, caddr_t end, int ttesz)
2296 {
2297 	struct tsb_info *tsbinfop;
2298 	uint64_t tag;
2299 	struct tsbe *tsbe_addr;
2300 	caddr_t vaddr;
2301 	uint64_t tsb_base;
2302 	int vpshift, vpgsz;
2303 	uint_t tsb_size;
2304 	int phys = 0;
2305 
2306 	/*
2307 	 * Assumptions:
2308 	 *  If ttesz == 8K, 64K or 512K, we walk through the range 8K
2309 	 *  at a time shooting down any valid entries we encounter.
2310 	 *
2311 	 *  If ttesz >= 4M we walk the range 4M at a time shooting
2312 	 *  down any valid mappings we find.
2313 	 */
2314 	if (sfmmup == ksfmmup) {
2315 		phys = ktsb_phys;
2316 		if (ttesz >= TTE4M) {
2317 #ifndef sun4v
2318 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2319 #endif
2320 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2321 			tsb_size = ktsb4m_szcode;
2322 		} else {
2323 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2324 			tsb_size = ktsb_szcode;
2325 		}
2326 	} else {
2327 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2328 
2329 		/*
2330 		 * If there isn't a TSB for this page size, or the TSB is
2331 		 * swapped out, there is nothing to do.  Note that the latter
2332 		 * case seems impossible but can occur if hat_pageunload()
2333 		 * is called on an ISM mapping while the process is swapped
2334 		 * out.
2335 		 */
2336 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2337 			return;
2338 
2339 		/*
2340 		 * If another thread is in the middle of relocating a TSB
2341 		 * we can't unload the entry so set a flag so that the
2342 		 * TSB will be flushed before it can be accessed by the
2343 		 * process.
2344 		 */
2345 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2346 			tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2347 			return;
2348 		}
2349 #if defined(UTSB_PHYS)
2350 		phys = 1;
2351 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2352 #else
2353 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2354 #endif
2355 		tsb_size = tsbinfop->tsb_szc;
2356 	}
2357 	if (ttesz >= TTE4M) {
2358 		vpshift = MMU_PAGESHIFT4M;
2359 		vpgsz = MMU_PAGESIZE4M;
2360 	} else {
2361 		vpshift = MMU_PAGESHIFT;
2362 		vpgsz = MMU_PAGESIZE;
2363 	}
2364 
2365 	for (vaddr = start; vaddr < end; vaddr += vpgsz) {
2366 		tag = sfmmu_make_tsbtag(vaddr);
2367 		tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2368 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2369 	}
2370 }
2371 
2372 /*
2373  * Select the optimum TSB size given the number of mappings
2374  * that need to be cached.
2375  */
2376 static int
2377 sfmmu_select_tsb_szc(pgcnt_t pgcnt)
2378 {
2379 	int szc = 0;
2380 
2381 #ifdef DEBUG
2382 	if (tsb_grow_stress) {
2383 		uint32_t randval = (uint32_t)gettick() >> 4;
2384 		return (randval % (tsb_max_growsize + 1));
2385 	}
2386 #endif	/* DEBUG */
2387 
2388 	while ((szc < tsb_max_growsize) && (pgcnt > SFMMU_RSS_TSBSIZE(szc)))
2389 		szc++;
2390 	return (szc);
2391 }
2392 
2393 /*
2394  * This function will add a translation to the hme_blk and allocate the
2395  * hme_blk if one does not exist.
2396  * If a page structure is specified then it will add the
2397  * corresponding hment to the mapping list.
2398  * It will also update the hmenum field for the tte.
2399  * Furthermore, it attempts to create a large page translation
2400  * for <addr,hat> at page array pps.  It assumes addr and first
2401  * pp is correctly aligned.  It returns 0 if successful and 1 otherwise.
2402  */
2403 static int
2404 sfmmu_tteload_array(sfmmu_t *sfmmup, tte_t *ttep, caddr_t vaddr,
2405 	page_t **pps, uint_t flags)
2406 {
2407 	struct hmehash_bucket *hmebp;
2408 	struct hme_blk *hmeblkp;
2409 	int 	ret;
2410 	uint_t	size;
2411 
2412 	/*
2413 	 * Get mapping size.
2414 	 */
2415 	size = TTE_CSZ(ttep);
2416 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
2417 
2418 	/*
2419 	 * Acquire the hash bucket.
2420 	 */
2421 	hmebp = sfmmu_tteload_acquire_hashbucket(sfmmup, vaddr, size);
2422 	ASSERT(hmebp);
2423 
2424 	/*
2425 	 * Find the hment block.
2426 	 */
2427 	hmeblkp = sfmmu_tteload_find_hmeblk(sfmmup, hmebp, vaddr, size, flags);
2428 	ASSERT(hmeblkp);
2429 
2430 	/*
2431 	 * Add the translation.
2432 	 */
2433 	ret = sfmmu_tteload_addentry(sfmmup, hmeblkp, ttep, vaddr, pps, flags);
2434 
2435 	/*
2436 	 * Release the hash bucket.
2437 	 */
2438 	sfmmu_tteload_release_hashbucket(hmebp);
2439 
2440 	return (ret);
2441 }
2442 
2443 /*
2444  * Function locks and returns a pointer to the hash bucket for vaddr and size.
2445  */
2446 static struct hmehash_bucket *
2447 sfmmu_tteload_acquire_hashbucket(sfmmu_t *sfmmup, caddr_t vaddr, int size)
2448 {
2449 	struct hmehash_bucket *hmebp;
2450 	int hmeshift;
2451 
2452 	hmeshift = HME_HASH_SHIFT(size);
2453 
2454 	hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
2455 
2456 	SFMMU_HASH_LOCK(hmebp);
2457 
2458 	return (hmebp);
2459 }
2460 
2461 /*
2462  * Function returns a pointer to an hmeblk in the hash bucket, hmebp. If the
2463  * hmeblk doesn't exists for the [sfmmup, vaddr & size] signature, a hmeblk is
2464  * allocated.
2465  */
2466 static struct hme_blk *
2467 sfmmu_tteload_find_hmeblk(sfmmu_t *sfmmup, struct hmehash_bucket *hmebp,
2468 	caddr_t vaddr, uint_t size, uint_t flags)
2469 {
2470 	hmeblk_tag hblktag;
2471 	int hmeshift;
2472 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
2473 	uint64_t hblkpa, prevpa;
2474 	struct kmem_cache *sfmmu_cache;
2475 	uint_t forcefree;
2476 
2477 	hblktag.htag_id = sfmmup;
2478 	hmeshift = HME_HASH_SHIFT(size);
2479 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
2480 	hblktag.htag_rehash = HME_HASH_REHASH(size);
2481 
2482 ttearray_realloc:
2483 
2484 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa,
2485 	    pr_hblk, prevpa, &list);
2486 
2487 	/*
2488 	 * We block until hblk_reserve_lock is released; it's held by
2489 	 * the thread, temporarily using hblk_reserve, until hblk_reserve is
2490 	 * replaced by a hblk from sfmmu8_cache.
2491 	 */
2492 	if (hmeblkp == (struct hme_blk *)hblk_reserve &&
2493 	    hblk_reserve_thread != curthread) {
2494 		SFMMU_HASH_UNLOCK(hmebp);
2495 		mutex_enter(&hblk_reserve_lock);
2496 		mutex_exit(&hblk_reserve_lock);
2497 		SFMMU_STAT(sf_hblk_reserve_hit);
2498 		SFMMU_HASH_LOCK(hmebp);
2499 		goto ttearray_realloc;
2500 	}
2501 
2502 	if (hmeblkp == NULL) {
2503 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
2504 		    hblktag, flags);
2505 	} else {
2506 		/*
2507 		 * It is possible for 8k and 64k hblks to collide since they
2508 		 * have the same rehash value. This is because we
2509 		 * lazily free hblks and 8K/64K blks could be lingering.
2510 		 * If we find size mismatch we free the block and & try again.
2511 		 */
2512 		if (get_hblk_ttesz(hmeblkp) != size) {
2513 			ASSERT(!hmeblkp->hblk_vcnt);
2514 			ASSERT(!hmeblkp->hblk_hmecnt);
2515 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
2516 			sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
2517 			goto ttearray_realloc;
2518 		}
2519 		if (hmeblkp->hblk_shw_bit) {
2520 			/*
2521 			 * if the hblk was previously used as a shadow hblk then
2522 			 * we will change it to a normal hblk
2523 			 */
2524 			if (hmeblkp->hblk_shw_mask) {
2525 				sfmmu_shadow_hcleanup(sfmmup, hmeblkp, hmebp);
2526 				ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
2527 				goto ttearray_realloc;
2528 			} else {
2529 				hmeblkp->hblk_shw_bit = 0;
2530 			}
2531 		}
2532 		SFMMU_STAT(sf_hblk_hit);
2533 	}
2534 
2535 	/*
2536 	 * hat_memload() should never call kmem_cache_free(); see block
2537 	 * comment showing the stacktrace in sfmmu_hblk_alloc();
2538 	 * enqueue each hblk in the list to reserve list if it's created
2539 	 * from sfmmu8_cache *and* sfmmup == KHATID.
2540 	 */
2541 	forcefree = (sfmmup == KHATID) ? 1 : 0;
2542 	while ((pr_hblk = list) != NULL) {
2543 		list = pr_hblk->hblk_next;
2544 		sfmmu_cache = get_hblk_cache(pr_hblk);
2545 		if ((sfmmu_cache == sfmmu8_cache) &&
2546 		    sfmmu_put_free_hblk(pr_hblk, forcefree))
2547 			continue;
2548 
2549 		ASSERT(sfmmup != KHATID);
2550 		kmem_cache_free(sfmmu_cache, pr_hblk);
2551 	}
2552 
2553 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
2554 	ASSERT(!hmeblkp->hblk_shw_bit);
2555 
2556 	return (hmeblkp);
2557 }
2558 
2559 /*
2560  * Function adds a tte entry into the hmeblk. It returns 0 if successful and 1
2561  * otherwise.
2562  */
2563 static int
2564 sfmmu_tteload_addentry(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, tte_t *ttep,
2565 	caddr_t vaddr, page_t **pps, uint_t flags)
2566 {
2567 	page_t *pp = *pps;
2568 	int hmenum, size, remap;
2569 	tte_t tteold, flush_tte;
2570 #ifdef DEBUG
2571 	tte_t orig_old;
2572 #endif /* DEBUG */
2573 	struct sf_hment *sfhme;
2574 	kmutex_t *pml, *pmtx;
2575 	hatlock_t *hatlockp;
2576 
2577 	/*
2578 	 * remove this panic when we decide to let user virtual address
2579 	 * space be >= USERLIMIT.
2580 	 */
2581 	if (!TTE_IS_PRIVILEGED(ttep) && vaddr >= (caddr_t)USERLIMIT)
2582 		panic("user addr %p in kernel space", vaddr);
2583 #if defined(TTE_IS_GLOBAL)
2584 	if (TTE_IS_GLOBAL(ttep))
2585 		panic("sfmmu_tteload: creating global tte");
2586 #endif
2587 
2588 #ifdef DEBUG
2589 	if (pf_is_memory(sfmmu_ttetopfn(ttep, vaddr)) &&
2590 	    !TTE_IS_PCACHEABLE(ttep) && !sfmmu_allow_nc_trans)
2591 		panic("sfmmu_tteload: non cacheable memory tte");
2592 #endif /* DEBUG */
2593 
2594 	if ((flags & HAT_LOAD_SHARE) || !TTE_IS_REF(ttep) ||
2595 	    !TTE_IS_MOD(ttep)) {
2596 		/*
2597 		 * Don't load TSB for dummy as in ISM.  Also don't preload
2598 		 * the TSB if the TTE isn't writable since we're likely to
2599 		 * fault on it again -- preloading can be fairly expensive.
2600 		 */
2601 		flags |= SFMMU_NO_TSBLOAD;
2602 	}
2603 
2604 	size = TTE_CSZ(ttep);
2605 	switch (size) {
2606 	case TTE8K:
2607 		SFMMU_STAT(sf_tteload8k);
2608 		break;
2609 	case TTE64K:
2610 		SFMMU_STAT(sf_tteload64k);
2611 		break;
2612 	case TTE512K:
2613 		SFMMU_STAT(sf_tteload512k);
2614 		break;
2615 	case TTE4M:
2616 		SFMMU_STAT(sf_tteload4m);
2617 		break;
2618 	case (TTE32M):
2619 		SFMMU_STAT(sf_tteload32m);
2620 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
2621 		break;
2622 	case (TTE256M):
2623 		SFMMU_STAT(sf_tteload256m);
2624 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
2625 		break;
2626 	}
2627 
2628 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
2629 
2630 	HBLKTOHME_IDX(sfhme, hmeblkp, vaddr, hmenum);
2631 
2632 	/*
2633 	 * Need to grab mlist lock here so that pageunload
2634 	 * will not change tte behind us.
2635 	 */
2636 	if (pp) {
2637 		pml = sfmmu_mlist_enter(pp);
2638 	}
2639 
2640 	sfmmu_copytte(&sfhme->hme_tte, &tteold);
2641 	/*
2642 	 * Look for corresponding hment and if valid verify
2643 	 * pfns are equal.
2644 	 */
2645 	remap = TTE_IS_VALID(&tteold);
2646 	if (remap) {
2647 		pfn_t	new_pfn, old_pfn;
2648 
2649 		old_pfn = TTE_TO_PFN(vaddr, &tteold);
2650 		new_pfn = TTE_TO_PFN(vaddr, ttep);
2651 
2652 		if (flags & HAT_LOAD_REMAP) {
2653 			/* make sure we are remapping same type of pages */
2654 			if (pf_is_memory(old_pfn) != pf_is_memory(new_pfn)) {
2655 				panic("sfmmu_tteload - tte remap io<->memory");
2656 			}
2657 			if (old_pfn != new_pfn &&
2658 			    (pp != NULL || sfhme->hme_page != NULL)) {
2659 				panic("sfmmu_tteload - tte remap pp != NULL");
2660 			}
2661 		} else if (old_pfn != new_pfn) {
2662 			panic("sfmmu_tteload - tte remap, hmeblkp 0x%p",
2663 			    (void *)hmeblkp);
2664 		}
2665 		ASSERT(TTE_CSZ(&tteold) == TTE_CSZ(ttep));
2666 	}
2667 
2668 	if (pp) {
2669 		if (size == TTE8K) {
2670 #ifdef VAC
2671 			/*
2672 			 * Handle VAC consistency
2673 			 */
2674 			if (!remap && (cache & CACHE_VAC) && !PP_ISNC(pp)) {
2675 				sfmmu_vac_conflict(sfmmup, vaddr, pp);
2676 			}
2677 #endif
2678 
2679 			if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
2680 				pmtx = sfmmu_page_enter(pp);
2681 				PP_CLRRO(pp);
2682 				sfmmu_page_exit(pmtx);
2683 			} else if (!PP_ISMAPPED(pp) &&
2684 			    (!TTE_IS_WRITABLE(ttep)) && !(PP_ISMOD(pp))) {
2685 				pmtx = sfmmu_page_enter(pp);
2686 				if (!(PP_ISMOD(pp))) {
2687 					PP_SETRO(pp);
2688 				}
2689 				sfmmu_page_exit(pmtx);
2690 			}
2691 
2692 		} else if (sfmmu_pagearray_setup(vaddr, pps, ttep, remap)) {
2693 			/*
2694 			 * sfmmu_pagearray_setup failed so return
2695 			 */
2696 			sfmmu_mlist_exit(pml);
2697 			return (1);
2698 		}
2699 	}
2700 
2701 	/*
2702 	 * Make sure hment is not on a mapping list.
2703 	 */
2704 	ASSERT(remap || (sfhme->hme_page == NULL));
2705 
2706 	/* if it is not a remap then hme->next better be NULL */
2707 	ASSERT((!remap) ? sfhme->hme_next == NULL : 1);
2708 
2709 	if (flags & HAT_LOAD_LOCK) {
2710 		if (((int)hmeblkp->hblk_lckcnt + 1) >= MAX_HBLK_LCKCNT) {
2711 			panic("too high lckcnt-hmeblk %p",
2712 			    (void *)hmeblkp);
2713 		}
2714 		atomic_add_16(&hmeblkp->hblk_lckcnt, 1);
2715 
2716 		HBLK_STACK_TRACE(hmeblkp, HBLK_LOCK);
2717 	}
2718 
2719 #ifdef VAC
2720 	if (pp && PP_ISNC(pp)) {
2721 		/*
2722 		 * If the physical page is marked to be uncacheable, like
2723 		 * by a vac conflict, make sure the new mapping is also
2724 		 * uncacheable.
2725 		 */
2726 		TTE_CLR_VCACHEABLE(ttep);
2727 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
2728 	}
2729 #endif
2730 	ttep->tte_hmenum = hmenum;
2731 
2732 #ifdef DEBUG
2733 	orig_old = tteold;
2734 #endif /* DEBUG */
2735 
2736 	while (sfmmu_modifytte_try(&tteold, ttep, &sfhme->hme_tte) < 0) {
2737 		if ((sfmmup == KHATID) &&
2738 		    (flags & (HAT_LOAD_LOCK | HAT_LOAD_REMAP))) {
2739 			sfmmu_copytte(&sfhme->hme_tte, &tteold);
2740 		}
2741 #ifdef DEBUG
2742 		chk_tte(&orig_old, &tteold, ttep, hmeblkp);
2743 #endif /* DEBUG */
2744 	}
2745 
2746 	if (!TTE_IS_VALID(&tteold)) {
2747 
2748 		atomic_add_16(&hmeblkp->hblk_vcnt, 1);
2749 		atomic_add_long(&sfmmup->sfmmu_ttecnt[size], 1);
2750 
2751 		/*
2752 		 * HAT_RELOAD_SHARE has been deprecated with lpg DISM.
2753 		 */
2754 
2755 		if (size > TTE8K && (flags & HAT_LOAD_SHARE) == 0 &&
2756 		    sfmmup != ksfmmup) {
2757 			/*
2758 			 * If this is the first large mapping for the process
2759 			 * we must force any CPUs running this process to TL=0
2760 			 * where they will reload the HAT flags from the
2761 			 * tsbmiss area.  This is necessary to make the large
2762 			 * mappings we are about to load visible to those CPUs;
2763 			 * otherwise they'll loop forever calling pagefault()
2764 			 * since we don't search large hash chains by default.
2765 			 */
2766 			hatlockp = sfmmu_hat_enter(sfmmup);
2767 			if (size == TTE512K &&
2768 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_512K_FLAG)) {
2769 				SFMMU_FLAGS_SET(sfmmup, HAT_512K_FLAG);
2770 				sfmmu_sync_mmustate(sfmmup);
2771 			} else if (size == TTE4M &&
2772 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4M_FLAG)) {
2773 				SFMMU_FLAGS_SET(sfmmup, HAT_4M_FLAG);
2774 				sfmmu_sync_mmustate(sfmmup);
2775 			} else if (size == TTE64K &&
2776 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_64K_FLAG)) {
2777 				SFMMU_FLAGS_SET(sfmmup, HAT_64K_FLAG);
2778 				/* no sync mmustate; 64K shares 8K hashes */
2779 			} else if (mmu_page_sizes == max_mmu_page_sizes) {
2780 			    if (size == TTE32M &&
2781 				!SFMMU_FLAGS_ISSET(sfmmup, HAT_32M_FLAG)) {
2782 				SFMMU_FLAGS_SET(sfmmup, HAT_32M_FLAG);
2783 				sfmmu_sync_mmustate(sfmmup);
2784 			    } else if (size == TTE256M &&
2785 				!SFMMU_FLAGS_ISSET(sfmmup, HAT_256M_FLAG)) {
2786 				SFMMU_FLAGS_SET(sfmmup, HAT_256M_FLAG);
2787 				sfmmu_sync_mmustate(sfmmup);
2788 			    }
2789 			}
2790 			if (size >= TTE4M && (flags & HAT_LOAD_TEXT) &&
2791 			    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
2792 				SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
2793 			}
2794 			sfmmu_hat_exit(hatlockp);
2795 		}
2796 	}
2797 	ASSERT(TTE_IS_VALID(&sfhme->hme_tte));
2798 
2799 	flush_tte.tte_intlo = (tteold.tte_intlo ^ ttep->tte_intlo) &
2800 	    hw_tte.tte_intlo;
2801 	flush_tte.tte_inthi = (tteold.tte_inthi ^ ttep->tte_inthi) &
2802 	    hw_tte.tte_inthi;
2803 
2804 	if (remap && (flush_tte.tte_inthi || flush_tte.tte_intlo)) {
2805 		/*
2806 		 * If remap and new tte differs from old tte we need
2807 		 * to sync the mod bit and flush TLB/TSB.  We don't
2808 		 * need to sync ref bit because we currently always set
2809 		 * ref bit in tteload.
2810 		 */
2811 		ASSERT(TTE_IS_REF(ttep));
2812 		if (TTE_IS_MOD(&tteold)) {
2813 			sfmmu_ttesync(sfmmup, vaddr, &tteold, pp);
2814 		}
2815 		sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 0);
2816 		xt_sync(sfmmup->sfmmu_cpusran);
2817 	}
2818 
2819 	if ((flags & SFMMU_NO_TSBLOAD) == 0) {
2820 		/*
2821 		 * We only preload 8K and 4M mappings into the TSB, since
2822 		 * 64K and 512K mappings are replicated and hence don't
2823 		 * have a single, unique TSB entry. Ditto for 32M/256M.
2824 		 */
2825 		if (size == TTE8K || size == TTE4M) {
2826 			hatlockp = sfmmu_hat_enter(sfmmup);
2827 			sfmmu_load_tsb(sfmmup, vaddr, &sfhme->hme_tte, size);
2828 			sfmmu_hat_exit(hatlockp);
2829 		}
2830 	}
2831 	if (pp) {
2832 		if (!remap) {
2833 			HME_ADD(sfhme, pp);
2834 			atomic_add_16(&hmeblkp->hblk_hmecnt, 1);
2835 			ASSERT(hmeblkp->hblk_hmecnt > 0);
2836 
2837 			/*
2838 			 * Cannot ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
2839 			 * see pageunload() for comment.
2840 			 */
2841 		}
2842 		sfmmu_mlist_exit(pml);
2843 	}
2844 
2845 	return (0);
2846 }
2847 /*
2848  * Function unlocks hash bucket.
2849  */
2850 static void
2851 sfmmu_tteload_release_hashbucket(struct hmehash_bucket *hmebp)
2852 {
2853 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
2854 	SFMMU_HASH_UNLOCK(hmebp);
2855 }
2856 
2857 /*
2858  * function which checks and sets up page array for a large
2859  * translation.  Will set p_vcolor, p_index, p_ro fields.
2860  * Assumes addr and pfnum of first page are properly aligned.
2861  * Will check for physical contiguity. If check fails it return
2862  * non null.
2863  */
2864 static int
2865 sfmmu_pagearray_setup(caddr_t addr, page_t **pps, tte_t *ttep, int remap)
2866 {
2867 	int 	i, index, ttesz;
2868 	pfn_t	pfnum;
2869 	pgcnt_t	npgs;
2870 	page_t *pp, *pp1;
2871 	kmutex_t *pmtx;
2872 #ifdef VAC
2873 	int osz;
2874 	int cflags = 0;
2875 	int vac_err = 0;
2876 #endif
2877 	int newidx = 0;
2878 
2879 	ttesz = TTE_CSZ(ttep);
2880 
2881 	ASSERT(ttesz > TTE8K);
2882 
2883 	npgs = TTEPAGES(ttesz);
2884 	index = PAGESZ_TO_INDEX(ttesz);
2885 
2886 	pfnum = (*pps)->p_pagenum;
2887 	ASSERT(IS_P2ALIGNED(pfnum, npgs));
2888 
2889 	/*
2890 	 * Save the first pp so we can do HAT_TMPNC at the end.
2891 	 */
2892 	pp1 = *pps;
2893 #ifdef VAC
2894 	osz = fnd_mapping_sz(pp1);
2895 #endif
2896 
2897 	for (i = 0; i < npgs; i++, pps++) {
2898 		pp = *pps;
2899 		ASSERT(PAGE_LOCKED(pp));
2900 		ASSERT(pp->p_szc >= ttesz);
2901 		ASSERT(pp->p_szc == pp1->p_szc);
2902 		ASSERT(sfmmu_mlist_held(pp));
2903 
2904 		/*
2905 		 * XXX is it possible to maintain P_RO on the root only?
2906 		 */
2907 		if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
2908 			pmtx = sfmmu_page_enter(pp);
2909 			PP_CLRRO(pp);
2910 			sfmmu_page_exit(pmtx);
2911 		} else if (!PP_ISMAPPED(pp) && !TTE_IS_WRITABLE(ttep) &&
2912 		    !PP_ISMOD(pp)) {
2913 			pmtx = sfmmu_page_enter(pp);
2914 			if (!(PP_ISMOD(pp))) {
2915 				PP_SETRO(pp);
2916 			}
2917 			sfmmu_page_exit(pmtx);
2918 		}
2919 
2920 		/*
2921 		 * If this is a remap we skip vac & contiguity checks.
2922 		 */
2923 		if (remap)
2924 			continue;
2925 
2926 		/*
2927 		 * set p_vcolor and detect any vac conflicts.
2928 		 */
2929 #ifdef VAC
2930 		if (vac_err == 0) {
2931 			vac_err = sfmmu_vacconflict_array(addr, pp, &cflags);
2932 
2933 		}
2934 #endif
2935 
2936 		/*
2937 		 * Save current index in case we need to undo it.
2938 		 * Note: "PAGESZ_TO_INDEX(sz)	(1 << (sz))"
2939 		 *	"SFMMU_INDEX_SHIFT	6"
2940 		 *	 "SFMMU_INDEX_MASK	((1 << SFMMU_INDEX_SHIFT) - 1)"
2941 		 *	 "PP_MAPINDEX(p_index)	(p_index & SFMMU_INDEX_MASK)"
2942 		 *
2943 		 * So:	index = PAGESZ_TO_INDEX(ttesz);
2944 		 *	if ttesz == 1 then index = 0x2
2945 		 *		    2 then index = 0x4
2946 		 *		    3 then index = 0x8
2947 		 *		    4 then index = 0x10
2948 		 *		    5 then index = 0x20
2949 		 * The code below checks if it's a new pagesize (ie, newidx)
2950 		 * in case we need to take it back out of p_index,
2951 		 * and then or's the new index into the existing index.
2952 		 */
2953 		if ((PP_MAPINDEX(pp) & index) == 0)
2954 			newidx = 1;
2955 		pp->p_index = (PP_MAPINDEX(pp) | index);
2956 
2957 		/*
2958 		 * contiguity check
2959 		 */
2960 		if (pp->p_pagenum != pfnum) {
2961 			/*
2962 			 * If we fail the contiguity test then
2963 			 * the only thing we need to fix is the p_index field.
2964 			 * We might get a few extra flushes but since this
2965 			 * path is rare that is ok.  The p_ro field will
2966 			 * get automatically fixed on the next tteload to
2967 			 * the page.  NO TNC bit is set yet.
2968 			 */
2969 			while (i >= 0) {
2970 				pp = *pps;
2971 				if (newidx)
2972 					pp->p_index = (PP_MAPINDEX(pp) &
2973 					    ~index);
2974 				pps--;
2975 				i--;
2976 			}
2977 			return (1);
2978 		}
2979 		pfnum++;
2980 		addr += MMU_PAGESIZE;
2981 	}
2982 
2983 #ifdef VAC
2984 	if (vac_err) {
2985 		if (ttesz > osz) {
2986 			/*
2987 			 * There are some smaller mappings that causes vac
2988 			 * conflicts. Convert all existing small mappings to
2989 			 * TNC.
2990 			 */
2991 			SFMMU_STAT_ADD(sf_uncache_conflict, npgs);
2992 			sfmmu_page_cache_array(pp1, HAT_TMPNC, CACHE_FLUSH,
2993 				npgs);
2994 		} else {
2995 			/* EMPTY */
2996 			/*
2997 			 * If there exists an big page mapping,
2998 			 * that means the whole existing big page
2999 			 * has TNC setting already. No need to covert to
3000 			 * TNC again.
3001 			 */
3002 			ASSERT(PP_ISTNC(pp1));
3003 		}
3004 	}
3005 #endif	/* VAC */
3006 
3007 	return (0);
3008 }
3009 
3010 #ifdef VAC
3011 /*
3012  * Routine that detects vac consistency for a large page. It also
3013  * sets virtual color for all pp's for this big mapping.
3014  */
3015 static int
3016 sfmmu_vacconflict_array(caddr_t addr, page_t *pp, int *cflags)
3017 {
3018 	int vcolor, ocolor;
3019 
3020 	ASSERT(sfmmu_mlist_held(pp));
3021 
3022 	if (PP_ISNC(pp)) {
3023 		return (HAT_TMPNC);
3024 	}
3025 
3026 	vcolor = addr_to_vcolor(addr);
3027 	if (PP_NEWPAGE(pp)) {
3028 		PP_SET_VCOLOR(pp, vcolor);
3029 		return (0);
3030 	}
3031 
3032 	ocolor = PP_GET_VCOLOR(pp);
3033 	if (ocolor == vcolor) {
3034 		return (0);
3035 	}
3036 
3037 	if (!PP_ISMAPPED(pp)) {
3038 		/*
3039 		 * Previous user of page had a differnet color
3040 		 * but since there are no current users
3041 		 * we just flush the cache and change the color.
3042 		 * As an optimization for large pages we flush the
3043 		 * entire cache of that color and set a flag.
3044 		 */
3045 		SFMMU_STAT(sf_pgcolor_conflict);
3046 		if (!CacheColor_IsFlushed(*cflags, ocolor)) {
3047 			CacheColor_SetFlushed(*cflags, ocolor);
3048 			sfmmu_cache_flushcolor(ocolor, pp->p_pagenum);
3049 		}
3050 		PP_SET_VCOLOR(pp, vcolor);
3051 		return (0);
3052 	}
3053 
3054 	/*
3055 	 * We got a real conflict with a current mapping.
3056 	 * set flags to start unencaching all mappings
3057 	 * and return failure so we restart looping
3058 	 * the pp array from the beginning.
3059 	 */
3060 	return (HAT_TMPNC);
3061 }
3062 #endif	/* VAC */
3063 
3064 /*
3065  * creates a large page shadow hmeblk for a tte.
3066  * The purpose of this routine is to allow us to do quick unloads because
3067  * the vm layer can easily pass a very large but sparsely populated range.
3068  */
3069 static struct hme_blk *
3070 sfmmu_shadow_hcreate(sfmmu_t *sfmmup, caddr_t vaddr, int ttesz, uint_t flags)
3071 {
3072 	struct hmehash_bucket *hmebp;
3073 	hmeblk_tag hblktag;
3074 	int hmeshift, size, vshift;
3075 	uint_t shw_mask, newshw_mask;
3076 	struct hme_blk *hmeblkp;
3077 
3078 	ASSERT(sfmmup != KHATID);
3079 	if (mmu_page_sizes == max_mmu_page_sizes) {
3080 		ASSERT(ttesz < TTE256M);
3081 	} else {
3082 		ASSERT(ttesz < TTE4M);
3083 		ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
3084 		ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
3085 	}
3086 
3087 	if (ttesz == TTE8K) {
3088 		size = TTE512K;
3089 	} else {
3090 		size = ++ttesz;
3091 	}
3092 
3093 	hblktag.htag_id = sfmmup;
3094 	hmeshift = HME_HASH_SHIFT(size);
3095 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
3096 	hblktag.htag_rehash = HME_HASH_REHASH(size);
3097 	hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
3098 
3099 	SFMMU_HASH_LOCK(hmebp);
3100 
3101 	HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
3102 	ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
3103 	if (hmeblkp == NULL) {
3104 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
3105 			hblktag, flags);
3106 	}
3107 	ASSERT(hmeblkp);
3108 	if (!hmeblkp->hblk_shw_mask) {
3109 		/*
3110 		 * if this is a unused hblk it was just allocated or could
3111 		 * potentially be a previous large page hblk so we need to
3112 		 * set the shadow bit.
3113 		 */
3114 		hmeblkp->hblk_shw_bit = 1;
3115 	}
3116 	ASSERT(hmeblkp->hblk_shw_bit == 1);
3117 	vshift = vaddr_to_vshift(hblktag, vaddr, size);
3118 	ASSERT(vshift < 8);
3119 	/*
3120 	 * Atomically set shw mask bit
3121 	 */
3122 	do {
3123 		shw_mask = hmeblkp->hblk_shw_mask;
3124 		newshw_mask = shw_mask | (1 << vshift);
3125 		newshw_mask = cas32(&hmeblkp->hblk_shw_mask, shw_mask,
3126 		    newshw_mask);
3127 	} while (newshw_mask != shw_mask);
3128 
3129 	SFMMU_HASH_UNLOCK(hmebp);
3130 
3131 	return (hmeblkp);
3132 }
3133 
3134 /*
3135  * This routine cleanup a previous shadow hmeblk and changes it to
3136  * a regular hblk.  This happens rarely but it is possible
3137  * when a process wants to use large pages and there are hblks still
3138  * lying around from the previous as that used these hmeblks.
3139  * The alternative was to cleanup the shadow hblks at unload time
3140  * but since so few user processes actually use large pages, it is
3141  * better to be lazy and cleanup at this time.
3142  */
3143 static void
3144 sfmmu_shadow_hcleanup(sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
3145 	struct hmehash_bucket *hmebp)
3146 {
3147 	caddr_t addr, endaddr;
3148 	int hashno, size;
3149 
3150 	ASSERT(hmeblkp->hblk_shw_bit);
3151 
3152 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3153 
3154 	if (!hmeblkp->hblk_shw_mask) {
3155 		hmeblkp->hblk_shw_bit = 0;
3156 		return;
3157 	}
3158 	addr = (caddr_t)get_hblk_base(hmeblkp);
3159 	endaddr = get_hblk_endaddr(hmeblkp);
3160 	size = get_hblk_ttesz(hmeblkp);
3161 	hashno = size - 1;
3162 	ASSERT(hashno > 0);
3163 	SFMMU_HASH_UNLOCK(hmebp);
3164 
3165 	sfmmu_free_hblks(sfmmup, addr, endaddr, hashno);
3166 
3167 	SFMMU_HASH_LOCK(hmebp);
3168 }
3169 
3170 static void
3171 sfmmu_free_hblks(sfmmu_t *sfmmup, caddr_t addr, caddr_t endaddr,
3172 	int hashno)
3173 {
3174 	int hmeshift, shadow = 0;
3175 	hmeblk_tag hblktag;
3176 	struct hmehash_bucket *hmebp;
3177 	struct hme_blk *hmeblkp;
3178 	struct hme_blk *nx_hblk, *pr_hblk, *list = NULL;
3179 	uint64_t hblkpa, prevpa, nx_pa;
3180 
3181 	ASSERT(hashno > 0);
3182 	hblktag.htag_id = sfmmup;
3183 	hblktag.htag_rehash = hashno;
3184 
3185 	hmeshift = HME_HASH_SHIFT(hashno);
3186 
3187 	while (addr < endaddr) {
3188 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3189 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3190 		SFMMU_HASH_LOCK(hmebp);
3191 		/* inline HME_HASH_SEARCH */
3192 		hmeblkp = hmebp->hmeblkp;
3193 		hblkpa = hmebp->hmeh_nextpa;
3194 		prevpa = 0;
3195 		pr_hblk = NULL;
3196 		while (hmeblkp) {
3197 			ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
3198 			if (HTAGS_EQ(hmeblkp->hblk_tag, hblktag)) {
3199 				/* found hme_blk */
3200 				if (hmeblkp->hblk_shw_bit) {
3201 					if (hmeblkp->hblk_shw_mask) {
3202 						shadow = 1;
3203 						sfmmu_shadow_hcleanup(sfmmup,
3204 						    hmeblkp, hmebp);
3205 						break;
3206 					} else {
3207 						hmeblkp->hblk_shw_bit = 0;
3208 					}
3209 				}
3210 
3211 				/*
3212 				 * Hblk_hmecnt and hblk_vcnt could be non zero
3213 				 * since hblk_unload() does not gurantee that.
3214 				 *
3215 				 * XXX - this could cause tteload() to spin
3216 				 * where sfmmu_shadow_hcleanup() is called.
3217 				 */
3218 			}
3219 
3220 			nx_hblk = hmeblkp->hblk_next;
3221 			nx_pa = hmeblkp->hblk_nextpa;
3222 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
3223 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa,
3224 					pr_hblk);
3225 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
3226 			} else {
3227 				pr_hblk = hmeblkp;
3228 				prevpa = hblkpa;
3229 			}
3230 			hmeblkp = nx_hblk;
3231 			hblkpa = nx_pa;
3232 		}
3233 
3234 		SFMMU_HASH_UNLOCK(hmebp);
3235 
3236 		if (shadow) {
3237 			/*
3238 			 * We found another shadow hblk so cleaned its
3239 			 * children.  We need to go back and cleanup
3240 			 * the original hblk so we don't change the
3241 			 * addr.
3242 			 */
3243 			shadow = 0;
3244 		} else {
3245 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
3246 				(1 << hmeshift));
3247 		}
3248 	}
3249 	sfmmu_hblks_list_purge(&list);
3250 }
3251 
3252 /*
3253  * Release one hardware address translation lock on the given address range.
3254  */
3255 void
3256 hat_unlock(struct hat *sfmmup, caddr_t addr, size_t len)
3257 {
3258 	struct hmehash_bucket *hmebp;
3259 	hmeblk_tag hblktag;
3260 	int hmeshift, hashno = 1;
3261 	struct hme_blk *hmeblkp, *list = NULL;
3262 	caddr_t endaddr;
3263 
3264 	ASSERT(sfmmup != NULL);
3265 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
3266 
3267 	ASSERT((sfmmup == ksfmmup) ||
3268 		AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
3269 	ASSERT((len & MMU_PAGEOFFSET) == 0);
3270 	endaddr = addr + len;
3271 	hblktag.htag_id = sfmmup;
3272 
3273 	/*
3274 	 * Spitfire supports 4 page sizes.
3275 	 * Most pages are expected to be of the smallest page size (8K) and
3276 	 * these will not need to be rehashed. 64K pages also don't need to be
3277 	 * rehashed because an hmeblk spans 64K of address space. 512K pages
3278 	 * might need 1 rehash and and 4M pages might need 2 rehashes.
3279 	 */
3280 	while (addr < endaddr) {
3281 		hmeshift = HME_HASH_SHIFT(hashno);
3282 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
3283 		hblktag.htag_rehash = hashno;
3284 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
3285 
3286 		SFMMU_HASH_LOCK(hmebp);
3287 
3288 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
3289 		if (hmeblkp != NULL) {
3290 			/*
3291 			 * If we encounter a shadow hmeblk then
3292 			 * we know there are no valid hmeblks mapping
3293 			 * this address at this size or larger.
3294 			 * Just increment address by the smallest
3295 			 * page size.
3296 			 */
3297 			if (hmeblkp->hblk_shw_bit) {
3298 				addr += MMU_PAGESIZE;
3299 			} else {
3300 				addr = sfmmu_hblk_unlock(hmeblkp, addr,
3301 				    endaddr);
3302 			}
3303 			SFMMU_HASH_UNLOCK(hmebp);
3304 			hashno = 1;
3305 			continue;
3306 		}
3307 		SFMMU_HASH_UNLOCK(hmebp);
3308 
3309 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
3310 			/*
3311 			 * We have traversed the whole list and rehashed
3312 			 * if necessary without finding the address to unlock
3313 			 * which should never happen.
3314 			 */
3315 			panic("sfmmu_unlock: addr not found. "
3316 			    "addr %p hat %p", (void *)addr, (void *)sfmmup);
3317 		} else {
3318 			hashno++;
3319 		}
3320 	}
3321 
3322 	sfmmu_hblks_list_purge(&list);
3323 }
3324 
3325 /*
3326  * Function to unlock a range of addresses in an hmeblk.  It returns the
3327  * next address that needs to be unlocked.
3328  * Should be called with the hash lock held.
3329  */
3330 static caddr_t
3331 sfmmu_hblk_unlock(struct hme_blk *hmeblkp, caddr_t addr, caddr_t endaddr)
3332 {
3333 	struct sf_hment *sfhme;
3334 	tte_t tteold, ttemod;
3335 	int ttesz, ret;
3336 
3337 	ASSERT(in_hblk_range(hmeblkp, addr));
3338 	ASSERT(hmeblkp->hblk_shw_bit == 0);
3339 
3340 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
3341 	ttesz = get_hblk_ttesz(hmeblkp);
3342 
3343 	HBLKTOHME(sfhme, hmeblkp, addr);
3344 	while (addr < endaddr) {
3345 readtte:
3346 		sfmmu_copytte(&sfhme->hme_tte, &tteold);
3347 		if (TTE_IS_VALID(&tteold)) {
3348 
3349 			ttemod = tteold;
3350 
3351 			ret = sfmmu_modifytte_try(&tteold, &ttemod,
3352 			    &sfhme->hme_tte);
3353 
3354 			if (ret < 0)
3355 				goto readtte;
3356 
3357 			if (hmeblkp->hblk_lckcnt == 0)
3358 				panic("zero hblk lckcnt");
3359 
3360 			if (((uintptr_t)addr + TTEBYTES(ttesz)) >
3361 			    (uintptr_t)endaddr)
3362 				panic("can't unlock large tte");
3363 
3364 			ASSERT(hmeblkp->hblk_lckcnt > 0);
3365 			atomic_add_16(&hmeblkp->hblk_lckcnt, -1);
3366 			HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
3367 		} else {
3368 			panic("sfmmu_hblk_unlock: invalid tte");
3369 		}
3370 		addr += TTEBYTES(ttesz);
3371 		sfhme++;
3372 	}
3373 	return (addr);
3374 }
3375 
3376 /*
3377  * Physical Address Mapping Framework
3378  *
3379  * General rules:
3380  *
3381  * (1) Applies only to seg_kmem memory pages. To make things easier,
3382  *     seg_kpm addresses are also accepted by the routines, but nothing
3383  *     is done with them since by definition their PA mappings are static.
3384  * (2) hat_add_callback() may only be called while holding the page lock
3385  *     SE_SHARED or SE_EXCL of the underlying page (e.g., as_pagelock()),
3386  *     or passing HAC_PAGELOCK flag.
3387  * (3) prehandler() and posthandler() may not call hat_add_callback() or
3388  *     hat_delete_callback(), nor should they allocate memory. Post quiesce
3389  *     callbacks may not sleep or acquire adaptive mutex locks.
3390  * (4) Either prehandler() or posthandler() (but not both) may be specified
3391  *     as being NULL.  Specifying an errhandler() is optional.
3392  *
3393  * Details of using the framework:
3394  *
3395  * registering a callback (hat_register_callback())
3396  *
3397  *	Pass prehandler, posthandler, errhandler addresses
3398  *	as described below. If capture_cpus argument is nonzero,
3399  *	suspend callback to the prehandler will occur with CPUs
3400  *	captured and executing xc_loop() and CPUs will remain
3401  *	captured until after the posthandler suspend callback
3402  *	occurs.
3403  *
3404  * adding a callback (hat_add_callback())
3405  *
3406  *      as_pagelock();
3407  *	hat_add_callback();
3408  *      save returned pfn in private data structures or program registers;
3409  *      as_pageunlock();
3410  *
3411  * prehandler()
3412  *
3413  *	Stop all accesses by physical address to this memory page.
3414  *	Called twice: the first, PRESUSPEND, is a context safe to acquire
3415  *	adaptive locks. The second, SUSPEND, is called at high PIL with
3416  *	CPUs captured so adaptive locks may NOT be acquired (and all spin
3417  *	locks must be XCALL_PIL or higher locks).
3418  *
3419  *	May return the following errors:
3420  *		EIO:	A fatal error has occurred. This will result in panic.
3421  *		EAGAIN:	The page cannot be suspended. This will fail the
3422  *			relocation.
3423  *		0:	Success.
3424  *
3425  * posthandler()
3426  *
3427  *      Save new pfn in private data structures or program registers;
3428  *	not allowed to fail (non-zero return values will result in panic).
3429  *
3430  * errhandler()
3431  *
3432  *	called when an error occurs related to the callback.  Currently
3433  *	the only such error is HAT_CB_ERR_LEAKED which indicates that
3434  *	a page is being freed, but there are still outstanding callback(s)
3435  *	registered on the page.
3436  *
3437  * removing a callback (hat_delete_callback(); e.g., prior to freeing memory)
3438  *
3439  *	stop using physical address
3440  *	hat_delete_callback();
3441  *
3442  */
3443 
3444 /*
3445  * Register a callback class.  Each subsystem should do this once and
3446  * cache the id_t returned for use in setting up and tearing down callbacks.
3447  *
3448  * There is no facility for removing callback IDs once they are created;
3449  * the "key" should be unique for each module, so in case a module is unloaded
3450  * and subsequently re-loaded, we can recycle the module's previous entry.
3451  */
3452 id_t
3453 hat_register_callback(int key,
3454 	int (*prehandler)(caddr_t, uint_t, uint_t, void *),
3455 	int (*posthandler)(caddr_t, uint_t, uint_t, void *, pfn_t),
3456 	int (*errhandler)(caddr_t, uint_t, uint_t, void *),
3457 	int capture_cpus)
3458 {
3459 	id_t id;
3460 
3461 	/*
3462 	 * Search the table for a pre-existing callback associated with
3463 	 * the identifier "key".  If one exists, we re-use that entry in
3464 	 * the table for this instance, otherwise we assign the next
3465 	 * available table slot.
3466 	 */
3467 	for (id = 0; id < sfmmu_max_cb_id; id++) {
3468 		if (sfmmu_cb_table[id].key == key)
3469 			break;
3470 	}
3471 
3472 	if (id == sfmmu_max_cb_id) {
3473 		id = sfmmu_cb_nextid++;
3474 		if (id >= sfmmu_max_cb_id)
3475 			panic("hat_register_callback: out of callback IDs");
3476 	}
3477 
3478 	ASSERT(prehandler != NULL || posthandler != NULL);
3479 
3480 	sfmmu_cb_table[id].key = key;
3481 	sfmmu_cb_table[id].prehandler = prehandler;
3482 	sfmmu_cb_table[id].posthandler = posthandler;
3483 	sfmmu_cb_table[id].errhandler = errhandler;
3484 	sfmmu_cb_table[id].capture_cpus = capture_cpus;
3485 
3486 	return (id);
3487 }
3488 
3489 #define	HAC_COOKIE_NONE	(void *)-1
3490 
3491 /*
3492  * Add relocation callbacks to the specified addr/len which will be called
3493  * when relocating the associated page. See the description of pre and
3494  * posthandler above for more details.
3495  *
3496  * If HAC_PAGELOCK is included in flags, the underlying memory page is
3497  * locked internally so the caller must be able to deal with the callback
3498  * running even before this function has returned.  If HAC_PAGELOCK is not
3499  * set, it is assumed that the underlying memory pages are locked.
3500  *
3501  * Since the caller must track the individual page boundaries anyway,
3502  * we only allow a callback to be added to a single page (large
3503  * or small).  Thus [addr, addr + len) MUST be contained within a single
3504  * page.
3505  *
3506  * Registering multiple callbacks on the same [addr, addr+len) is supported,
3507  * _provided_that_ a unique parameter is specified for each callback.
3508  * If multiple callbacks are registered on the same range the callback will
3509  * be invoked with each unique parameter. Registering the same callback with
3510  * the same argument more than once will result in corrupted kernel state.
3511  *
3512  * Returns the pfn of the underlying kernel page in *rpfn
3513  * on success, or PFN_INVALID on failure.
3514  *
3515  * cookiep (if passed) provides storage space for an opaque cookie
3516  * to return later to hat_delete_callback(). This cookie makes the callback
3517  * deletion significantly quicker by avoiding a potentially lengthy hash
3518  * search.
3519  *
3520  * Returns values:
3521  *    0:      success
3522  *    ENOMEM: memory allocation failure (e.g. flags was passed as HAC_NOSLEEP)
3523  *    EINVAL: callback ID is not valid
3524  *    ENXIO:  ["vaddr", "vaddr" + len) is not mapped in the kernel's address
3525  *            space
3526  *    ERANGE: ["vaddr", "vaddr" + len) crosses a page boundary
3527  */
3528 int
3529 hat_add_callback(id_t callback_id, caddr_t vaddr, uint_t len, uint_t flags,
3530 	void *pvt, pfn_t *rpfn, void **cookiep)
3531 {
3532 	struct 		hmehash_bucket *hmebp;
3533 	hmeblk_tag 	hblktag;
3534 	struct hme_blk	*hmeblkp;
3535 	int 		hmeshift, hashno;
3536 	caddr_t 	saddr, eaddr, baseaddr;
3537 	struct pa_hment *pahmep;
3538 	struct sf_hment *sfhmep, *osfhmep;
3539 	kmutex_t	*pml;
3540 	tte_t   	tte;
3541 	page_t		*pp;
3542 	vnode_t		*vp;
3543 	u_offset_t	off;
3544 	pfn_t		pfn;
3545 	int		kmflags = (flags & HAC_SLEEP)? KM_SLEEP : KM_NOSLEEP;
3546 	int		locked = 0;
3547 
3548 	/*
3549 	 * For KPM mappings, just return the physical address since we
3550 	 * don't need to register any callbacks.
3551 	 */
3552 	if (IS_KPM_ADDR(vaddr)) {
3553 		uint64_t paddr;
3554 		SFMMU_KPM_VTOP(vaddr, paddr);
3555 		*rpfn = btop(paddr);
3556 		if (cookiep != NULL)
3557 			*cookiep = HAC_COOKIE_NONE;
3558 		return (0);
3559 	}
3560 
3561 	if (callback_id < (id_t)0 || callback_id >= sfmmu_cb_nextid) {
3562 		*rpfn = PFN_INVALID;
3563 		return (EINVAL);
3564 	}
3565 
3566 	if ((pahmep = kmem_cache_alloc(pa_hment_cache, kmflags)) == NULL) {
3567 		*rpfn = PFN_INVALID;
3568 		return (ENOMEM);
3569 	}
3570 
3571 	sfhmep = &pahmep->sfment;
3572 
3573 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
3574 	eaddr = saddr + len;
3575 
3576 rehash:
3577 	/* Find the mapping(s) for this page */
3578 	for (hashno = TTE64K, hmeblkp = NULL;
3579 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
3580 	    hashno++) {
3581 		hmeshift = HME_HASH_SHIFT(hashno);
3582 		hblktag.htag_id = ksfmmup;
3583 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
3584 		hblktag.htag_rehash = hashno;
3585 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
3586 
3587 		SFMMU_HASH_LOCK(hmebp);
3588 
3589 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
3590 
3591 		if (hmeblkp == NULL)
3592 			SFMMU_HASH_UNLOCK(hmebp);
3593 	}
3594 
3595 	if (hmeblkp == NULL) {
3596 		kmem_cache_free(pa_hment_cache, pahmep);
3597 		*rpfn = PFN_INVALID;
3598 		return (ENXIO);
3599 	}
3600 
3601 	HBLKTOHME(osfhmep, hmeblkp, saddr);
3602 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
3603 
3604 	if (!TTE_IS_VALID(&tte)) {
3605 		SFMMU_HASH_UNLOCK(hmebp);
3606 		kmem_cache_free(pa_hment_cache, pahmep);
3607 		*rpfn = PFN_INVALID;
3608 		return (ENXIO);
3609 	}
3610 
3611 	/*
3612 	 * Make sure the boundaries for the callback fall within this
3613 	 * single mapping.
3614 	 */
3615 	baseaddr = (caddr_t)get_hblk_base(hmeblkp);
3616 	ASSERT(saddr >= baseaddr);
3617 	if (eaddr > saddr + TTEBYTES(TTE_CSZ(&tte))) {
3618 		SFMMU_HASH_UNLOCK(hmebp);
3619 		kmem_cache_free(pa_hment_cache, pahmep);
3620 		*rpfn = PFN_INVALID;
3621 		return (ERANGE);
3622 	}
3623 
3624 	pfn = sfmmu_ttetopfn(&tte, vaddr);
3625 
3626 	/*
3627 	 * The pfn may not have a page_t underneath in which case we
3628 	 * just return it. This can happen if we are doing I/O to a
3629 	 * static portion of the kernel's address space, for instance.
3630 	 */
3631 	pp = osfhmep->hme_page;
3632 	if (pp == NULL) {
3633 		SFMMU_HASH_UNLOCK(hmebp);
3634 		kmem_cache_free(pa_hment_cache, pahmep);
3635 		*rpfn = pfn;
3636 		if (cookiep)
3637 			*cookiep = HAC_COOKIE_NONE;
3638 		return (0);
3639 	}
3640 	ASSERT(pp == PP_PAGEROOT(pp));
3641 
3642 	vp = pp->p_vnode;
3643 	off = pp->p_offset;
3644 
3645 	pml = sfmmu_mlist_enter(pp);
3646 
3647 	if (flags & HAC_PAGELOCK) {
3648 		if (!page_trylock(pp, SE_SHARED)) {
3649 			/*
3650 			 * Somebody is holding SE_EXCL lock. Might
3651 			 * even be hat_page_relocate(). Drop all
3652 			 * our locks, lookup the page in &kvp, and
3653 			 * retry. If it doesn't exist in &kvp, then
3654 			 * we must be dealing with a kernel mapped
3655 			 * page which doesn't actually belong to
3656 			 * segkmem so we punt.
3657 			 */
3658 			sfmmu_mlist_exit(pml);
3659 			SFMMU_HASH_UNLOCK(hmebp);
3660 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
3661 			if (pp == NULL) {
3662 				kmem_cache_free(pa_hment_cache, pahmep);
3663 				*rpfn = pfn;
3664 				if (cookiep)
3665 					*cookiep = HAC_COOKIE_NONE;
3666 				return (0);
3667 			}
3668 			page_unlock(pp);
3669 			goto rehash;
3670 		}
3671 		locked = 1;
3672 	}
3673 
3674 	if (!PAGE_LOCKED(pp) && !panicstr)
3675 		panic("hat_add_callback: page 0x%p not locked", pp);
3676 
3677 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
3678 	    pp->p_offset != off) {
3679 		/*
3680 		 * The page moved before we got our hands on it.  Drop
3681 		 * all the locks and try again.
3682 		 */
3683 		ASSERT((flags & HAC_PAGELOCK) != 0);
3684 		sfmmu_mlist_exit(pml);
3685 		SFMMU_HASH_UNLOCK(hmebp);
3686 		page_unlock(pp);
3687 		locked = 0;
3688 		goto rehash;
3689 	}
3690 
3691 	if (vp != &kvp) {
3692 		/*
3693 		 * This is not a segkmem page but another page which
3694 		 * has been kernel mapped. It had better have at least
3695 		 * a share lock on it. Return the pfn.
3696 		 */
3697 		sfmmu_mlist_exit(pml);
3698 		SFMMU_HASH_UNLOCK(hmebp);
3699 		if (locked)
3700 			page_unlock(pp);
3701 		kmem_cache_free(pa_hment_cache, pahmep);
3702 		ASSERT(PAGE_LOCKED(pp));
3703 		*rpfn = pfn;
3704 		if (cookiep)
3705 			*cookiep = HAC_COOKIE_NONE;
3706 		return (0);
3707 	}
3708 
3709 	/*
3710 	 * Setup this pa_hment and link its embedded dummy sf_hment into
3711 	 * the mapping list.
3712 	 */
3713 	pp->p_share++;
3714 	pahmep->cb_id = callback_id;
3715 	pahmep->addr = vaddr;
3716 	pahmep->len = len;
3717 	pahmep->refcnt = 1;
3718 	pahmep->flags = 0;
3719 	pahmep->pvt = pvt;
3720 
3721 	sfhmep->hme_tte.ll = 0;
3722 	sfhmep->hme_data = pahmep;
3723 	sfhmep->hme_prev = osfhmep;
3724 	sfhmep->hme_next = osfhmep->hme_next;
3725 
3726 	if (osfhmep->hme_next)
3727 		osfhmep->hme_next->hme_prev = sfhmep;
3728 
3729 	osfhmep->hme_next = sfhmep;
3730 
3731 	sfmmu_mlist_exit(pml);
3732 	SFMMU_HASH_UNLOCK(hmebp);
3733 
3734 	if (locked)
3735 		page_unlock(pp);
3736 
3737 	*rpfn = pfn;
3738 	if (cookiep)
3739 		*cookiep = (void *)pahmep;
3740 
3741 	return (0);
3742 }
3743 
3744 /*
3745  * Remove the relocation callbacks from the specified addr/len.
3746  */
3747 void
3748 hat_delete_callback(caddr_t vaddr, uint_t len, void *pvt, uint_t flags,
3749 	void *cookie)
3750 {
3751 	struct		hmehash_bucket *hmebp;
3752 	hmeblk_tag	hblktag;
3753 	struct hme_blk	*hmeblkp;
3754 	int		hmeshift, hashno;
3755 	caddr_t		saddr;
3756 	struct pa_hment	*pahmep;
3757 	struct sf_hment	*sfhmep, *osfhmep;
3758 	kmutex_t	*pml;
3759 	tte_t		tte;
3760 	page_t		*pp;
3761 	vnode_t		*vp;
3762 	u_offset_t	off;
3763 	int		locked = 0;
3764 
3765 	/*
3766 	 * If the cookie is HAC_COOKIE_NONE then there is no pa_hment to
3767 	 * remove so just return.
3768 	 */
3769 	if (cookie == HAC_COOKIE_NONE || IS_KPM_ADDR(vaddr))
3770 		return;
3771 
3772 	saddr = (caddr_t)((uintptr_t)vaddr & MMU_PAGEMASK);
3773 
3774 rehash:
3775 	/* Find the mapping(s) for this page */
3776 	for (hashno = TTE64K, hmeblkp = NULL;
3777 	    hmeblkp == NULL && hashno <= mmu_hashcnt;
3778 	    hashno++) {
3779 		hmeshift = HME_HASH_SHIFT(hashno);
3780 		hblktag.htag_id = ksfmmup;
3781 		hblktag.htag_bspage = HME_HASH_BSPAGE(saddr, hmeshift);
3782 		hblktag.htag_rehash = hashno;
3783 		hmebp = HME_HASH_FUNCTION(ksfmmup, saddr, hmeshift);
3784 
3785 		SFMMU_HASH_LOCK(hmebp);
3786 
3787 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
3788 
3789 		if (hmeblkp == NULL)
3790 			SFMMU_HASH_UNLOCK(hmebp);
3791 	}
3792 
3793 	if (hmeblkp == NULL)
3794 		return;
3795 
3796 	HBLKTOHME(osfhmep, hmeblkp, saddr);
3797 
3798 	sfmmu_copytte(&osfhmep->hme_tte, &tte);
3799 	if (!TTE_IS_VALID(&tte)) {
3800 		SFMMU_HASH_UNLOCK(hmebp);
3801 		return;
3802 	}
3803 
3804 	pp = osfhmep->hme_page;
3805 	if (pp == NULL) {
3806 		SFMMU_HASH_UNLOCK(hmebp);
3807 		ASSERT(cookie == NULL);
3808 		return;
3809 	}
3810 
3811 	vp = pp->p_vnode;
3812 	off = pp->p_offset;
3813 
3814 	pml = sfmmu_mlist_enter(pp);
3815 
3816 	if (flags & HAC_PAGELOCK) {
3817 		if (!page_trylock(pp, SE_SHARED)) {
3818 			/*
3819 			 * Somebody is holding SE_EXCL lock. Might
3820 			 * even be hat_page_relocate(). Drop all
3821 			 * our locks, lookup the page in &kvp, and
3822 			 * retry. If it doesn't exist in &kvp, then
3823 			 * we must be dealing with a kernel mapped
3824 			 * page which doesn't actually belong to
3825 			 * segkmem so we punt.
3826 			 */
3827 			sfmmu_mlist_exit(pml);
3828 			SFMMU_HASH_UNLOCK(hmebp);
3829 			pp = page_lookup(&kvp, (u_offset_t)saddr, SE_SHARED);
3830 			if (pp == NULL) {
3831 				ASSERT(cookie == NULL);
3832 				return;
3833 			}
3834 			page_unlock(pp);
3835 			goto rehash;
3836 		}
3837 		locked = 1;
3838 	}
3839 
3840 	ASSERT(PAGE_LOCKED(pp));
3841 
3842 	if (osfhmep->hme_page != pp || pp->p_vnode != vp ||
3843 	    pp->p_offset != off) {
3844 		/*
3845 		 * The page moved before we got our hands on it.  Drop
3846 		 * all the locks and try again.
3847 		 */
3848 		ASSERT((flags & HAC_PAGELOCK) != 0);
3849 		sfmmu_mlist_exit(pml);
3850 		SFMMU_HASH_UNLOCK(hmebp);
3851 		page_unlock(pp);
3852 		locked = 0;
3853 		goto rehash;
3854 	}
3855 
3856 	if (vp != &kvp) {
3857 		/*
3858 		 * This is not a segkmem page but another page which
3859 		 * has been kernel mapped.
3860 		 */
3861 		sfmmu_mlist_exit(pml);
3862 		SFMMU_HASH_UNLOCK(hmebp);
3863 		if (locked)
3864 			page_unlock(pp);
3865 		ASSERT(cookie == NULL);
3866 		return;
3867 	}
3868 
3869 	if (cookie != NULL) {
3870 		pahmep = (struct pa_hment *)cookie;
3871 		sfhmep = &pahmep->sfment;
3872 	} else {
3873 		for (sfhmep = pp->p_mapping; sfhmep != NULL;
3874 		    sfhmep = sfhmep->hme_next) {
3875 
3876 			/*
3877 			 * skip va<->pa mappings
3878 			 */
3879 			if (!IS_PAHME(sfhmep))
3880 				continue;
3881 
3882 			pahmep = sfhmep->hme_data;
3883 			ASSERT(pahmep != NULL);
3884 
3885 			/*
3886 			 * if pa_hment matches, remove it
3887 			 */
3888 			if ((pahmep->pvt == pvt) &&
3889 			    (pahmep->addr == vaddr) &&
3890 			    (pahmep->len == len)) {
3891 				break;
3892 			}
3893 		}
3894 	}
3895 
3896 	if (sfhmep == NULL) {
3897 		if (!panicstr) {
3898 			panic("hat_delete_callback: pa_hment not found, pp %p",
3899 			    (void *)pp);
3900 		}
3901 		return;
3902 	}
3903 
3904 	/*
3905 	 * Note: at this point a valid kernel mapping must still be
3906 	 * present on this page.
3907 	 */
3908 	pp->p_share--;
3909 	if (pp->p_share <= 0)
3910 		panic("hat_delete_callback: zero p_share");
3911 
3912 	if (--pahmep->refcnt == 0) {
3913 		if (pahmep->flags != 0)
3914 			panic("hat_delete_callback: pa_hment is busy");
3915 
3916 		/*
3917 		 * Remove sfhmep from the mapping list for the page.
3918 		 */
3919 		if (sfhmep->hme_prev) {
3920 			sfhmep->hme_prev->hme_next = sfhmep->hme_next;
3921 		} else {
3922 			pp->p_mapping = sfhmep->hme_next;
3923 		}
3924 
3925 		if (sfhmep->hme_next)
3926 			sfhmep->hme_next->hme_prev = sfhmep->hme_prev;
3927 
3928 		sfmmu_mlist_exit(pml);
3929 		SFMMU_HASH_UNLOCK(hmebp);
3930 
3931 		if (locked)
3932 			page_unlock(pp);
3933 
3934 		kmem_cache_free(pa_hment_cache, pahmep);
3935 		return;
3936 	}
3937 
3938 	sfmmu_mlist_exit(pml);
3939 	SFMMU_HASH_UNLOCK(hmebp);
3940 	if (locked)
3941 		page_unlock(pp);
3942 }
3943 
3944 /*
3945  * hat_probe returns 1 if the translation for the address 'addr' is
3946  * loaded, zero otherwise.
3947  *
3948  * hat_probe should be used only for advisorary purposes because it may
3949  * occasionally return the wrong value. The implementation must guarantee that
3950  * returning the wrong value is a very rare event. hat_probe is used
3951  * to implement optimizations in the segment drivers.
3952  *
3953  */
3954 int
3955 hat_probe(struct hat *sfmmup, caddr_t addr)
3956 {
3957 	pfn_t pfn;
3958 	tte_t tte;
3959 
3960 	ASSERT(sfmmup != NULL);
3961 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
3962 
3963 	ASSERT((sfmmup == ksfmmup) ||
3964 		AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
3965 
3966 	if (sfmmup == ksfmmup) {
3967 		while ((pfn = sfmmu_vatopfn(addr, sfmmup, &tte))
3968 		    == PFN_SUSPENDED) {
3969 			sfmmu_vatopfn_suspended(addr, sfmmup, &tte);
3970 		}
3971 	} else {
3972 		pfn = sfmmu_uvatopfn(addr, sfmmup);
3973 	}
3974 
3975 	if (pfn != PFN_INVALID)
3976 		return (1);
3977 	else
3978 		return (0);
3979 }
3980 
3981 ssize_t
3982 hat_getpagesize(struct hat *sfmmup, caddr_t addr)
3983 {
3984 	tte_t tte;
3985 
3986 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
3987 
3988 	sfmmu_gettte(sfmmup, addr, &tte);
3989 	if (TTE_IS_VALID(&tte)) {
3990 		return (TTEBYTES(TTE_CSZ(&tte)));
3991 	}
3992 	return (-1);
3993 }
3994 
3995 static void
3996 sfmmu_gettte(struct hat *sfmmup, caddr_t addr, tte_t *ttep)
3997 {
3998 	struct hmehash_bucket *hmebp;
3999 	hmeblk_tag hblktag;
4000 	int hmeshift, hashno = 1;
4001 	struct hme_blk *hmeblkp, *list = NULL;
4002 	struct sf_hment *sfhmep;
4003 
4004 	/* support for ISM */
4005 	ism_map_t	*ism_map;
4006 	ism_blk_t	*ism_blkp;
4007 	int		i;
4008 	sfmmu_t		*ism_hatid = NULL;
4009 	sfmmu_t		*locked_hatid = NULL;
4010 
4011 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
4012 
4013 	ism_blkp = sfmmup->sfmmu_iblk;
4014 	if (ism_blkp) {
4015 		sfmmu_ismhat_enter(sfmmup, 0);
4016 		locked_hatid = sfmmup;
4017 	}
4018 	while (ism_blkp && ism_hatid == NULL) {
4019 		ism_map = ism_blkp->iblk_maps;
4020 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
4021 			if (addr >= ism_start(ism_map[i]) &&
4022 			    addr < ism_end(ism_map[i])) {
4023 				sfmmup = ism_hatid = ism_map[i].imap_ismhat;
4024 				addr = (caddr_t)(addr -
4025 					ism_start(ism_map[i]));
4026 				break;
4027 			}
4028 		}
4029 		ism_blkp = ism_blkp->iblk_next;
4030 	}
4031 	if (locked_hatid) {
4032 		sfmmu_ismhat_exit(locked_hatid, 0);
4033 	}
4034 
4035 	hblktag.htag_id = sfmmup;
4036 	ttep->ll = 0;
4037 
4038 	do {
4039 		hmeshift = HME_HASH_SHIFT(hashno);
4040 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
4041 		hblktag.htag_rehash = hashno;
4042 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
4043 
4044 		SFMMU_HASH_LOCK(hmebp);
4045 
4046 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
4047 		if (hmeblkp != NULL) {
4048 			HBLKTOHME(sfhmep, hmeblkp, addr);
4049 			sfmmu_copytte(&sfhmep->hme_tte, ttep);
4050 			SFMMU_HASH_UNLOCK(hmebp);
4051 			break;
4052 		}
4053 		SFMMU_HASH_UNLOCK(hmebp);
4054 		hashno++;
4055 	} while (HME_REHASH(sfmmup) && (hashno <= mmu_hashcnt));
4056 
4057 	sfmmu_hblks_list_purge(&list);
4058 }
4059 
4060 uint_t
4061 hat_getattr(struct hat *sfmmup, caddr_t addr, uint_t *attr)
4062 {
4063 	tte_t tte;
4064 
4065 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
4066 
4067 	sfmmu_gettte(sfmmup, addr, &tte);
4068 	if (TTE_IS_VALID(&tte)) {
4069 		*attr = sfmmu_ptov_attr(&tte);
4070 		return (0);
4071 	}
4072 	*attr = 0;
4073 	return ((uint_t)0xffffffff);
4074 }
4075 
4076 /*
4077  * Enables more attributes on specified address range (ie. logical OR)
4078  */
4079 void
4080 hat_setattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4081 {
4082 	if (hat->sfmmu_xhat_provider) {
4083 		XHAT_SETATTR(hat, addr, len, attr);
4084 		return;
4085 	} else {
4086 		/*
4087 		 * This must be a CPU HAT. If the address space has
4088 		 * XHATs attached, change attributes for all of them,
4089 		 * just in case
4090 		 */
4091 		ASSERT(hat->sfmmu_as != NULL);
4092 		if (hat->sfmmu_as->a_xhat != NULL)
4093 			xhat_setattr_all(hat->sfmmu_as, addr, len, attr);
4094 	}
4095 
4096 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_SETATTR);
4097 }
4098 
4099 /*
4100  * Assigns attributes to the specified address range.  All the attributes
4101  * are specified.
4102  */
4103 void
4104 hat_chgattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4105 {
4106 	if (hat->sfmmu_xhat_provider) {
4107 		XHAT_CHGATTR(hat, addr, len, attr);
4108 		return;
4109 	} else {
4110 		/*
4111 		 * This must be a CPU HAT. If the address space has
4112 		 * XHATs attached, change attributes for all of them,
4113 		 * just in case
4114 		 */
4115 		ASSERT(hat->sfmmu_as != NULL);
4116 		if (hat->sfmmu_as->a_xhat != NULL)
4117 			xhat_chgattr_all(hat->sfmmu_as, addr, len, attr);
4118 	}
4119 
4120 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CHGATTR);
4121 }
4122 
4123 /*
4124  * Remove attributes on the specified address range (ie. loginal NAND)
4125  */
4126 void
4127 hat_clrattr(struct hat *hat, caddr_t addr, size_t len, uint_t attr)
4128 {
4129 	if (hat->sfmmu_xhat_provider) {
4130 		XHAT_CLRATTR(hat, addr, len, attr);
4131 		return;
4132 	} else {
4133 		/*
4134 		 * This must be a CPU HAT. If the address space has
4135 		 * XHATs attached, change attributes for all of them,
4136 		 * just in case
4137 		 */
4138 		ASSERT(hat->sfmmu_as != NULL);
4139 		if (hat->sfmmu_as->a_xhat != NULL)
4140 			xhat_clrattr_all(hat->sfmmu_as, addr, len, attr);
4141 	}
4142 
4143 	sfmmu_chgattr(hat, addr, len, attr, SFMMU_CLRATTR);
4144 }
4145 
4146 /*
4147  * Change attributes on an address range to that specified by attr and mode.
4148  */
4149 static void
4150 sfmmu_chgattr(struct hat *sfmmup, caddr_t addr, size_t len, uint_t attr,
4151 	int mode)
4152 {
4153 	struct hmehash_bucket *hmebp;
4154 	hmeblk_tag hblktag;
4155 	int hmeshift, hashno = 1;
4156 	struct hme_blk *hmeblkp, *list = NULL;
4157 	caddr_t endaddr;
4158 	cpuset_t cpuset;
4159 	demap_range_t dmr;
4160 
4161 	CPUSET_ZERO(cpuset);
4162 
4163 	ASSERT((sfmmup == ksfmmup) ||
4164 		AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4165 	ASSERT((len & MMU_PAGEOFFSET) == 0);
4166 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
4167 
4168 	if ((attr & PROT_USER) && (mode != SFMMU_CLRATTR) &&
4169 	    ((addr + len) > (caddr_t)USERLIMIT)) {
4170 		panic("user addr %p in kernel space",
4171 		    (void *)addr);
4172 	}
4173 
4174 	endaddr = addr + len;
4175 	hblktag.htag_id = sfmmup;
4176 	DEMAP_RANGE_INIT(sfmmup, &dmr);
4177 
4178 	while (addr < endaddr) {
4179 		hmeshift = HME_HASH_SHIFT(hashno);
4180 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
4181 		hblktag.htag_rehash = hashno;
4182 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
4183 
4184 		SFMMU_HASH_LOCK(hmebp);
4185 
4186 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
4187 		if (hmeblkp != NULL) {
4188 			/*
4189 			 * We've encountered a shadow hmeblk so skip the range
4190 			 * of the next smaller mapping size.
4191 			 */
4192 			if (hmeblkp->hblk_shw_bit) {
4193 				ASSERT(sfmmup != ksfmmup);
4194 				ASSERT(hashno > 1);
4195 				addr = (caddr_t)P2END((uintptr_t)addr,
4196 					    TTEBYTES(hashno - 1));
4197 			} else {
4198 				addr = sfmmu_hblk_chgattr(sfmmup,
4199 				    hmeblkp, addr, endaddr, &dmr, attr, mode);
4200 			}
4201 			SFMMU_HASH_UNLOCK(hmebp);
4202 			hashno = 1;
4203 			continue;
4204 		}
4205 		SFMMU_HASH_UNLOCK(hmebp);
4206 
4207 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
4208 			/*
4209 			 * We have traversed the whole list and rehashed
4210 			 * if necessary without finding the address to chgattr.
4211 			 * This is ok, so we increment the address by the
4212 			 * smallest hmeblk range for kernel mappings or for
4213 			 * user mappings with no large pages, and the largest
4214 			 * hmeblk range, to account for shadow hmeblks, for
4215 			 * user mappings with large pages and continue.
4216 			 */
4217 			if (sfmmup == ksfmmup)
4218 				addr = (caddr_t)P2END((uintptr_t)addr,
4219 					    TTEBYTES(1));
4220 			else
4221 				addr = (caddr_t)P2END((uintptr_t)addr,
4222 					    TTEBYTES(hashno));
4223 			hashno = 1;
4224 		} else {
4225 			hashno++;
4226 		}
4227 	}
4228 
4229 	sfmmu_hblks_list_purge(&list);
4230 	DEMAP_RANGE_FLUSH(&dmr);
4231 	cpuset = sfmmup->sfmmu_cpusran;
4232 	xt_sync(cpuset);
4233 }
4234 
4235 /*
4236  * This function chgattr on a range of addresses in an hmeblk.  It returns the
4237  * next addres that needs to be chgattr.
4238  * It should be called with the hash lock held.
4239  * XXX It should be possible to optimize chgattr by not flushing every time but
4240  * on the other hand:
4241  * 1. do one flush crosscall.
4242  * 2. only flush if we are increasing permissions (make sure this will work)
4243  */
4244 static caddr_t
4245 sfmmu_hblk_chgattr(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
4246 	caddr_t endaddr, demap_range_t *dmrp, uint_t attr, int mode)
4247 {
4248 	tte_t tte, tteattr, tteflags, ttemod;
4249 	struct sf_hment *sfhmep;
4250 	int ttesz;
4251 	struct page *pp = NULL;
4252 	kmutex_t *pml, *pmtx;
4253 	int ret;
4254 	int use_demap_range;
4255 #if defined(SF_ERRATA_57)
4256 	int check_exec;
4257 #endif
4258 
4259 	ASSERT(in_hblk_range(hmeblkp, addr));
4260 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4261 
4262 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4263 	ttesz = get_hblk_ttesz(hmeblkp);
4264 
4265 	/*
4266 	 * Flush the current demap region if addresses have been
4267 	 * skipped or the page size doesn't match.
4268 	 */
4269 	use_demap_range = (TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp));
4270 	if (use_demap_range) {
4271 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
4272 	} else {
4273 		DEMAP_RANGE_FLUSH(dmrp);
4274 	}
4275 
4276 	tteattr.ll = sfmmu_vtop_attr(attr, mode, &tteflags);
4277 #if defined(SF_ERRATA_57)
4278 	check_exec = (sfmmup != ksfmmup) &&
4279 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
4280 	    TTE_IS_EXECUTABLE(&tteattr);
4281 #endif
4282 	HBLKTOHME(sfhmep, hmeblkp, addr);
4283 	while (addr < endaddr) {
4284 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
4285 		if (TTE_IS_VALID(&tte)) {
4286 			if ((tte.ll & tteflags.ll) == tteattr.ll) {
4287 				/*
4288 				 * if the new attr is the same as old
4289 				 * continue
4290 				 */
4291 				goto next_addr;
4292 			}
4293 			if (!TTE_IS_WRITABLE(&tteattr)) {
4294 				/*
4295 				 * make sure we clear hw modify bit if we
4296 				 * removing write protections
4297 				 */
4298 				tteflags.tte_intlo |= TTE_HWWR_INT;
4299 			}
4300 
4301 			pml = NULL;
4302 			pp = sfhmep->hme_page;
4303 			if (pp) {
4304 				pml = sfmmu_mlist_enter(pp);
4305 			}
4306 
4307 			if (pp != sfhmep->hme_page) {
4308 				/*
4309 				 * tte must have been unloaded.
4310 				 */
4311 				ASSERT(pml);
4312 				sfmmu_mlist_exit(pml);
4313 				continue;
4314 			}
4315 
4316 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
4317 
4318 			ttemod = tte;
4319 			ttemod.ll = (ttemod.ll & ~tteflags.ll) | tteattr.ll;
4320 			ASSERT(TTE_TO_TTEPFN(&ttemod) == TTE_TO_TTEPFN(&tte));
4321 
4322 #if defined(SF_ERRATA_57)
4323 			if (check_exec && addr < errata57_limit)
4324 				ttemod.tte_exec_perm = 0;
4325 #endif
4326 			ret = sfmmu_modifytte_try(&tte, &ttemod,
4327 			    &sfhmep->hme_tte);
4328 
4329 			if (ret < 0) {
4330 				/* tte changed underneath us */
4331 				if (pml) {
4332 					sfmmu_mlist_exit(pml);
4333 				}
4334 				continue;
4335 			}
4336 
4337 			if (tteflags.tte_intlo & TTE_HWWR_INT) {
4338 				/*
4339 				 * need to sync if we are clearing modify bit.
4340 				 */
4341 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
4342 			}
4343 
4344 			if (pp && PP_ISRO(pp)) {
4345 				if (tteattr.tte_intlo & TTE_WRPRM_INT) {
4346 					pmtx = sfmmu_page_enter(pp);
4347 					PP_CLRRO(pp);
4348 					sfmmu_page_exit(pmtx);
4349 				}
4350 			}
4351 
4352 			if (ret > 0 && use_demap_range) {
4353 				DEMAP_RANGE_MARKPG(dmrp, addr);
4354 			} else if (ret > 0) {
4355 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
4356 			}
4357 
4358 			if (pml) {
4359 				sfmmu_mlist_exit(pml);
4360 			}
4361 		}
4362 next_addr:
4363 		addr += TTEBYTES(ttesz);
4364 		sfhmep++;
4365 		DEMAP_RANGE_NEXTPG(dmrp);
4366 	}
4367 	return (addr);
4368 }
4369 
4370 /*
4371  * This routine converts virtual attributes to physical ones.  It will
4372  * update the tteflags field with the tte mask corresponding to the attributes
4373  * affected and it returns the new attributes.  It will also clear the modify
4374  * bit if we are taking away write permission.  This is necessary since the
4375  * modify bit is the hardware permission bit and we need to clear it in order
4376  * to detect write faults.
4377  */
4378 static uint64_t
4379 sfmmu_vtop_attr(uint_t attr, int mode, tte_t *ttemaskp)
4380 {
4381 	tte_t ttevalue;
4382 
4383 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
4384 
4385 	switch (mode) {
4386 	case SFMMU_CHGATTR:
4387 		/* all attributes specified */
4388 		ttevalue.tte_inthi = MAKE_TTEATTR_INTHI(attr);
4389 		ttevalue.tte_intlo = MAKE_TTEATTR_INTLO(attr);
4390 		ttemaskp->tte_inthi = TTEINTHI_ATTR;
4391 		ttemaskp->tte_intlo = TTEINTLO_ATTR;
4392 		break;
4393 	case SFMMU_SETATTR:
4394 		ASSERT(!(attr & ~HAT_PROT_MASK));
4395 		ttemaskp->ll = 0;
4396 		ttevalue.ll = 0;
4397 		/*
4398 		 * a valid tte implies exec and read for sfmmu
4399 		 * so no need to do anything about them.
4400 		 * since priviledged access implies user access
4401 		 * PROT_USER doesn't make sense either.
4402 		 */
4403 		if (attr & PROT_WRITE) {
4404 			ttemaskp->tte_intlo |= TTE_WRPRM_INT;
4405 			ttevalue.tte_intlo |= TTE_WRPRM_INT;
4406 		}
4407 		break;
4408 	case SFMMU_CLRATTR:
4409 		/* attributes will be nand with current ones */
4410 		if (attr & ~(PROT_WRITE | PROT_USER)) {
4411 			panic("sfmmu: attr %x not supported", attr);
4412 		}
4413 		ttemaskp->ll = 0;
4414 		ttevalue.ll = 0;
4415 		if (attr & PROT_WRITE) {
4416 			/* clear both writable and modify bit */
4417 			ttemaskp->tte_intlo |= TTE_WRPRM_INT | TTE_HWWR_INT;
4418 		}
4419 		if (attr & PROT_USER) {
4420 			ttemaskp->tte_intlo |= TTE_PRIV_INT;
4421 			ttevalue.tte_intlo |= TTE_PRIV_INT;
4422 		}
4423 		break;
4424 	default:
4425 		panic("sfmmu_vtop_attr: bad mode %x", mode);
4426 	}
4427 	ASSERT(TTE_TO_TTEPFN(&ttevalue) == 0);
4428 	return (ttevalue.ll);
4429 }
4430 
4431 static uint_t
4432 sfmmu_ptov_attr(tte_t *ttep)
4433 {
4434 	uint_t attr;
4435 
4436 	ASSERT(TTE_IS_VALID(ttep));
4437 
4438 	attr = PROT_READ;
4439 
4440 	if (TTE_IS_WRITABLE(ttep)) {
4441 		attr |= PROT_WRITE;
4442 	}
4443 	if (TTE_IS_EXECUTABLE(ttep)) {
4444 		attr |= PROT_EXEC;
4445 	}
4446 	if (!TTE_IS_PRIVILEGED(ttep)) {
4447 		attr |= PROT_USER;
4448 	}
4449 	if (TTE_IS_NFO(ttep)) {
4450 		attr |= HAT_NOFAULT;
4451 	}
4452 	if (TTE_IS_NOSYNC(ttep)) {
4453 		attr |= HAT_NOSYNC;
4454 	}
4455 	if (TTE_IS_SIDEFFECT(ttep)) {
4456 		attr |= SFMMU_SIDEFFECT;
4457 	}
4458 	if (!TTE_IS_VCACHEABLE(ttep)) {
4459 		attr |= SFMMU_UNCACHEVTTE;
4460 	}
4461 	if (!TTE_IS_PCACHEABLE(ttep)) {
4462 		attr |= SFMMU_UNCACHEPTTE;
4463 	}
4464 	return (attr);
4465 }
4466 
4467 /*
4468  * hat_chgprot is a deprecated hat call.  New segment drivers
4469  * should store all attributes and use hat_*attr calls.
4470  *
4471  * Change the protections in the virtual address range
4472  * given to the specified virtual protection.  If vprot is ~PROT_WRITE,
4473  * then remove write permission, leaving the other
4474  * permissions unchanged.  If vprot is ~PROT_USER, remove user permissions.
4475  *
4476  */
4477 void
4478 hat_chgprot(struct hat *sfmmup, caddr_t addr, size_t len, uint_t vprot)
4479 {
4480 	struct hmehash_bucket *hmebp;
4481 	hmeblk_tag hblktag;
4482 	int hmeshift, hashno = 1;
4483 	struct hme_blk *hmeblkp, *list = NULL;
4484 	caddr_t endaddr;
4485 	cpuset_t cpuset;
4486 	demap_range_t dmr;
4487 
4488 	ASSERT((len & MMU_PAGEOFFSET) == 0);
4489 	ASSERT(((uintptr_t)addr & MMU_PAGEOFFSET) == 0);
4490 
4491 	if (sfmmup->sfmmu_xhat_provider) {
4492 		XHAT_CHGPROT(sfmmup, addr, len, vprot);
4493 		return;
4494 	} else {
4495 		/*
4496 		 * This must be a CPU HAT. If the address space has
4497 		 * XHATs attached, change attributes for all of them,
4498 		 * just in case
4499 		 */
4500 		ASSERT(sfmmup->sfmmu_as != NULL);
4501 		if (sfmmup->sfmmu_as->a_xhat != NULL)
4502 			xhat_chgprot_all(sfmmup->sfmmu_as, addr, len, vprot);
4503 	}
4504 
4505 	CPUSET_ZERO(cpuset);
4506 
4507 	if ((vprot != (uint_t)~PROT_WRITE) && (vprot & PROT_USER) &&
4508 	    ((addr + len) > (caddr_t)USERLIMIT)) {
4509 		panic("user addr %p vprot %x in kernel space",
4510 		    (void *)addr, vprot);
4511 	}
4512 	endaddr = addr + len;
4513 	hblktag.htag_id = sfmmup;
4514 	DEMAP_RANGE_INIT(sfmmup, &dmr);
4515 
4516 	while (addr < endaddr) {
4517 		hmeshift = HME_HASH_SHIFT(hashno);
4518 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
4519 		hblktag.htag_rehash = hashno;
4520 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
4521 
4522 		SFMMU_HASH_LOCK(hmebp);
4523 
4524 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
4525 		if (hmeblkp != NULL) {
4526 			/*
4527 			 * We've encountered a shadow hmeblk so skip the range
4528 			 * of the next smaller mapping size.
4529 			 */
4530 			if (hmeblkp->hblk_shw_bit) {
4531 				ASSERT(sfmmup != ksfmmup);
4532 				ASSERT(hashno > 1);
4533 				addr = (caddr_t)P2END((uintptr_t)addr,
4534 					    TTEBYTES(hashno - 1));
4535 			} else {
4536 				addr = sfmmu_hblk_chgprot(sfmmup, hmeblkp,
4537 					addr, endaddr, &dmr, vprot);
4538 			}
4539 			SFMMU_HASH_UNLOCK(hmebp);
4540 			hashno = 1;
4541 			continue;
4542 		}
4543 		SFMMU_HASH_UNLOCK(hmebp);
4544 
4545 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
4546 			/*
4547 			 * We have traversed the whole list and rehashed
4548 			 * if necessary without finding the address to chgprot.
4549 			 * This is ok so we increment the address by the
4550 			 * smallest hmeblk range for kernel mappings and the
4551 			 * largest hmeblk range, to account for shadow hmeblks,
4552 			 * for user mappings and continue.
4553 			 */
4554 			if (sfmmup == ksfmmup)
4555 				addr = (caddr_t)P2END((uintptr_t)addr,
4556 					    TTEBYTES(1));
4557 			else
4558 				addr = (caddr_t)P2END((uintptr_t)addr,
4559 					    TTEBYTES(hashno));
4560 			hashno = 1;
4561 		} else {
4562 			hashno++;
4563 		}
4564 	}
4565 
4566 	sfmmu_hblks_list_purge(&list);
4567 	DEMAP_RANGE_FLUSH(&dmr);
4568 	cpuset = sfmmup->sfmmu_cpusran;
4569 	xt_sync(cpuset);
4570 }
4571 
4572 /*
4573  * This function chgprots a range of addresses in an hmeblk.  It returns the
4574  * next addres that needs to be chgprot.
4575  * It should be called with the hash lock held.
4576  * XXX It shold be possible to optimize chgprot by not flushing every time but
4577  * on the other hand:
4578  * 1. do one flush crosscall.
4579  * 2. only flush if we are increasing permissions (make sure this will work)
4580  */
4581 static caddr_t
4582 sfmmu_hblk_chgprot(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
4583 	caddr_t endaddr, demap_range_t *dmrp, uint_t vprot)
4584 {
4585 	uint_t pprot;
4586 	tte_t tte, ttemod;
4587 	struct sf_hment *sfhmep;
4588 	uint_t tteflags;
4589 	int ttesz;
4590 	struct page *pp = NULL;
4591 	kmutex_t *pml, *pmtx;
4592 	int ret;
4593 	int use_demap_range;
4594 #if defined(SF_ERRATA_57)
4595 	int check_exec;
4596 #endif
4597 
4598 	ASSERT(in_hblk_range(hmeblkp, addr));
4599 	ASSERT(hmeblkp->hblk_shw_bit == 0);
4600 
4601 #ifdef DEBUG
4602 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
4603 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
4604 		panic("sfmmu_hblk_chgprot: partial chgprot of large page");
4605 	}
4606 #endif /* DEBUG */
4607 
4608 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
4609 	ttesz = get_hblk_ttesz(hmeblkp);
4610 
4611 	pprot = sfmmu_vtop_prot(vprot, &tteflags);
4612 #if defined(SF_ERRATA_57)
4613 	check_exec = (sfmmup != ksfmmup) &&
4614 	    AS_TYPE_64BIT(sfmmup->sfmmu_as) &&
4615 	    ((vprot & PROT_EXEC) == PROT_EXEC);
4616 #endif
4617 	HBLKTOHME(sfhmep, hmeblkp, addr);
4618 
4619 	/*
4620 	 * Flush the current demap region if addresses have been
4621 	 * skipped or the page size doesn't match.
4622 	 */
4623 	use_demap_range = (TTEBYTES(ttesz) == MMU_PAGESIZE);
4624 	if (use_demap_range) {
4625 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
4626 	} else {
4627 		DEMAP_RANGE_FLUSH(dmrp);
4628 	}
4629 
4630 	while (addr < endaddr) {
4631 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
4632 		if (TTE_IS_VALID(&tte)) {
4633 			if (TTE_GET_LOFLAGS(&tte, tteflags) == pprot) {
4634 				/*
4635 				 * if the new protection is the same as old
4636 				 * continue
4637 				 */
4638 				goto next_addr;
4639 			}
4640 			pml = NULL;
4641 			pp = sfhmep->hme_page;
4642 			if (pp) {
4643 				pml = sfmmu_mlist_enter(pp);
4644 			}
4645 			if (pp != sfhmep->hme_page) {
4646 				/*
4647 				 * tte most have been unloaded
4648 				 * underneath us.  Recheck
4649 				 */
4650 				ASSERT(pml);
4651 				sfmmu_mlist_exit(pml);
4652 				continue;
4653 			}
4654 
4655 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
4656 
4657 			ttemod = tte;
4658 			TTE_SET_LOFLAGS(&ttemod, tteflags, pprot);
4659 #if defined(SF_ERRATA_57)
4660 			if (check_exec && addr < errata57_limit)
4661 				ttemod.tte_exec_perm = 0;
4662 #endif
4663 			ret = sfmmu_modifytte_try(&tte, &ttemod,
4664 			    &sfhmep->hme_tte);
4665 
4666 			if (ret < 0) {
4667 				/* tte changed underneath us */
4668 				if (pml) {
4669 					sfmmu_mlist_exit(pml);
4670 				}
4671 				continue;
4672 			}
4673 
4674 			if (tteflags & TTE_HWWR_INT) {
4675 				/*
4676 				 * need to sync if we are clearing modify bit.
4677 				 */
4678 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
4679 			}
4680 
4681 			if (pp && PP_ISRO(pp)) {
4682 				if (pprot & TTE_WRPRM_INT) {
4683 					pmtx = sfmmu_page_enter(pp);
4684 					PP_CLRRO(pp);
4685 					sfmmu_page_exit(pmtx);
4686 				}
4687 			}
4688 
4689 			if (ret > 0 && use_demap_range) {
4690 				DEMAP_RANGE_MARKPG(dmrp, addr);
4691 			} else if (ret > 0) {
4692 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
4693 			}
4694 
4695 			if (pml) {
4696 				sfmmu_mlist_exit(pml);
4697 			}
4698 		}
4699 next_addr:
4700 		addr += TTEBYTES(ttesz);
4701 		sfhmep++;
4702 		DEMAP_RANGE_NEXTPG(dmrp);
4703 	}
4704 	return (addr);
4705 }
4706 
4707 /*
4708  * This routine is deprecated and should only be used by hat_chgprot.
4709  * The correct routine is sfmmu_vtop_attr.
4710  * This routine converts virtual page protections to physical ones.  It will
4711  * update the tteflags field with the tte mask corresponding to the protections
4712  * affected and it returns the new protections.  It will also clear the modify
4713  * bit if we are taking away write permission.  This is necessary since the
4714  * modify bit is the hardware permission bit and we need to clear it in order
4715  * to detect write faults.
4716  * It accepts the following special protections:
4717  * ~PROT_WRITE = remove write permissions.
4718  * ~PROT_USER = remove user permissions.
4719  */
4720 static uint_t
4721 sfmmu_vtop_prot(uint_t vprot, uint_t *tteflagsp)
4722 {
4723 	if (vprot == (uint_t)~PROT_WRITE) {
4724 		*tteflagsp = TTE_WRPRM_INT | TTE_HWWR_INT;
4725 		return (0);		/* will cause wrprm to be cleared */
4726 	}
4727 	if (vprot == (uint_t)~PROT_USER) {
4728 		*tteflagsp = TTE_PRIV_INT;
4729 		return (0);		/* will cause privprm to be cleared */
4730 	}
4731 	if ((vprot == 0) || (vprot == PROT_USER) ||
4732 		((vprot & PROT_ALL) != vprot)) {
4733 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
4734 	}
4735 
4736 	switch (vprot) {
4737 	case (PROT_READ):
4738 	case (PROT_EXEC):
4739 	case (PROT_EXEC | PROT_READ):
4740 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
4741 		return (TTE_PRIV_INT); 		/* set prv and clr wrt */
4742 	case (PROT_WRITE):
4743 	case (PROT_WRITE | PROT_READ):
4744 	case (PROT_EXEC | PROT_WRITE):
4745 	case (PROT_EXEC | PROT_WRITE | PROT_READ):
4746 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
4747 		return (TTE_PRIV_INT | TTE_WRPRM_INT); 	/* set prv and wrt */
4748 	case (PROT_USER | PROT_READ):
4749 	case (PROT_USER | PROT_EXEC):
4750 	case (PROT_USER | PROT_EXEC | PROT_READ):
4751 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT | TTE_HWWR_INT;
4752 		return (0); 			/* clr prv and wrt */
4753 	case (PROT_USER | PROT_WRITE):
4754 	case (PROT_USER | PROT_WRITE | PROT_READ):
4755 	case (PROT_USER | PROT_EXEC | PROT_WRITE):
4756 	case (PROT_USER | PROT_EXEC | PROT_WRITE | PROT_READ):
4757 		*tteflagsp = TTE_PRIV_INT | TTE_WRPRM_INT;
4758 		return (TTE_WRPRM_INT); 	/* clr prv and set wrt */
4759 	default:
4760 		panic("sfmmu_vtop_prot -- bad prot %x", vprot);
4761 	}
4762 	return (0);
4763 }
4764 
4765 /*
4766  * Alternate unload for very large virtual ranges. With a true 64 bit VA,
4767  * the normal algorithm would take too long for a very large VA range with
4768  * few real mappings. This routine just walks thru all HMEs in the global
4769  * hash table to find and remove mappings.
4770  */
4771 static void
4772 hat_unload_large_virtual(
4773 	struct hat		*sfmmup,
4774 	caddr_t			startaddr,
4775 	size_t			len,
4776 	uint_t			flags,
4777 	hat_callback_t		*callback)
4778 {
4779 	struct hmehash_bucket *hmebp;
4780 	struct hme_blk *hmeblkp;
4781 	struct hme_blk *pr_hblk = NULL;
4782 	struct hme_blk *nx_hblk;
4783 	struct hme_blk *list = NULL;
4784 	int i;
4785 	uint64_t hblkpa, prevpa, nx_pa;
4786 	demap_range_t dmr, *dmrp;
4787 	cpuset_t cpuset;
4788 	caddr_t	endaddr = startaddr + len;
4789 	caddr_t	sa;
4790 	caddr_t	ea;
4791 	caddr_t	cb_sa[MAX_CB_ADDR];
4792 	caddr_t	cb_ea[MAX_CB_ADDR];
4793 	int	addr_cnt = 0;
4794 	int	a = 0;
4795 
4796 	if (sfmmup->sfmmu_free) {
4797 		dmrp = NULL;
4798 	} else {
4799 		dmrp = &dmr;
4800 		DEMAP_RANGE_INIT(sfmmup, dmrp);
4801 	}
4802 
4803 	/*
4804 	 * Loop through all the hash buckets of HME blocks looking for matches.
4805 	 */
4806 	for (i = 0; i <= UHMEHASH_SZ; i++) {
4807 		hmebp = &uhme_hash[i];
4808 		SFMMU_HASH_LOCK(hmebp);
4809 		hmeblkp = hmebp->hmeblkp;
4810 		hblkpa = hmebp->hmeh_nextpa;
4811 		prevpa = 0;
4812 		pr_hblk = NULL;
4813 		while (hmeblkp) {
4814 			nx_hblk = hmeblkp->hblk_next;
4815 			nx_pa = hmeblkp->hblk_nextpa;
4816 
4817 			/*
4818 			 * skip if not this context, if a shadow block or
4819 			 * if the mapping is not in the requested range
4820 			 */
4821 			if (hmeblkp->hblk_tag.htag_id != sfmmup ||
4822 			    hmeblkp->hblk_shw_bit ||
4823 			    (sa = (caddr_t)get_hblk_base(hmeblkp)) >= endaddr ||
4824 			    (ea = get_hblk_endaddr(hmeblkp)) <= startaddr) {
4825 				pr_hblk = hmeblkp;
4826 				prevpa = hblkpa;
4827 				goto next_block;
4828 			}
4829 
4830 			/*
4831 			 * unload if there are any current valid mappings
4832 			 */
4833 			if (hmeblkp->hblk_vcnt != 0 ||
4834 			    hmeblkp->hblk_hmecnt != 0)
4835 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
4836 				    sa, ea, dmrp, flags);
4837 
4838 			/*
4839 			 * on unmap we also release the HME block itself, once
4840 			 * all mappings are gone.
4841 			 */
4842 			if ((flags & HAT_UNLOAD_UNMAP) != 0 &&
4843 			    !hmeblkp->hblk_vcnt &&
4844 			    !hmeblkp->hblk_hmecnt) {
4845 				ASSERT(!hmeblkp->hblk_lckcnt);
4846 				sfmmu_hblk_hash_rm(hmebp, hmeblkp,
4847 					prevpa, pr_hblk);
4848 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
4849 			} else {
4850 				pr_hblk = hmeblkp;
4851 				prevpa = hblkpa;
4852 			}
4853 
4854 			if (callback == NULL)
4855 				goto next_block;
4856 
4857 			/*
4858 			 * HME blocks may span more than one page, but we may be
4859 			 * unmapping only one page, so check for a smaller range
4860 			 * for the callback
4861 			 */
4862 			if (sa < startaddr)
4863 				sa = startaddr;
4864 			if (--ea > endaddr)
4865 				ea = endaddr - 1;
4866 
4867 			cb_sa[addr_cnt] = sa;
4868 			cb_ea[addr_cnt] = ea;
4869 			if (++addr_cnt == MAX_CB_ADDR) {
4870 				if (dmrp != NULL) {
4871 					DEMAP_RANGE_FLUSH(dmrp);
4872 					cpuset = sfmmup->sfmmu_cpusran;
4873 					xt_sync(cpuset);
4874 				}
4875 
4876 				for (a = 0; a < MAX_CB_ADDR; ++a) {
4877 					callback->hcb_start_addr = cb_sa[a];
4878 					callback->hcb_end_addr = cb_ea[a];
4879 					callback->hcb_function(callback);
4880 				}
4881 				addr_cnt = 0;
4882 			}
4883 
4884 next_block:
4885 			hmeblkp = nx_hblk;
4886 			hblkpa = nx_pa;
4887 		}
4888 		SFMMU_HASH_UNLOCK(hmebp);
4889 	}
4890 
4891 	sfmmu_hblks_list_purge(&list);
4892 	if (dmrp != NULL) {
4893 		DEMAP_RANGE_FLUSH(dmrp);
4894 		cpuset = sfmmup->sfmmu_cpusran;
4895 		xt_sync(cpuset);
4896 	}
4897 
4898 	for (a = 0; a < addr_cnt; ++a) {
4899 		callback->hcb_start_addr = cb_sa[a];
4900 		callback->hcb_end_addr = cb_ea[a];
4901 		callback->hcb_function(callback);
4902 	}
4903 
4904 	/*
4905 	 * Check TSB and TLB page sizes if the process isn't exiting.
4906 	 */
4907 	if (!sfmmup->sfmmu_free)
4908 		sfmmu_check_page_sizes(sfmmup, 0);
4909 }
4910 
4911 /*
4912  * Unload all the mappings in the range [addr..addr+len). addr and len must
4913  * be MMU_PAGESIZE aligned.
4914  */
4915 
4916 extern struct seg *segkmap;
4917 #define	ISSEGKMAP(sfmmup, addr) (sfmmup == ksfmmup && \
4918 segkmap->s_base <= (addr) && (addr) < (segkmap->s_base + segkmap->s_size))
4919 
4920 
4921 void
4922 hat_unload_callback(
4923 	struct hat *sfmmup,
4924 	caddr_t addr,
4925 	size_t len,
4926 	uint_t flags,
4927 	hat_callback_t *callback)
4928 {
4929 	struct hmehash_bucket *hmebp;
4930 	hmeblk_tag hblktag;
4931 	int hmeshift, hashno, iskernel;
4932 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
4933 	caddr_t endaddr;
4934 	cpuset_t cpuset;
4935 	uint64_t hblkpa, prevpa;
4936 	int addr_count = 0;
4937 	int a;
4938 	caddr_t cb_start_addr[MAX_CB_ADDR];
4939 	caddr_t cb_end_addr[MAX_CB_ADDR];
4940 	int issegkmap = ISSEGKMAP(sfmmup, addr);
4941 	demap_range_t dmr, *dmrp;
4942 
4943 	if (sfmmup->sfmmu_xhat_provider) {
4944 		XHAT_UNLOAD_CALLBACK(sfmmup, addr, len, flags, callback);
4945 		return;
4946 	} else {
4947 		/*
4948 		 * This must be a CPU HAT. If the address space has
4949 		 * XHATs attached, unload the mappings for all of them,
4950 		 * just in case
4951 		 */
4952 		ASSERT(sfmmup->sfmmu_as != NULL);
4953 		if (sfmmup->sfmmu_as->a_xhat != NULL)
4954 			xhat_unload_callback_all(sfmmup->sfmmu_as, addr,
4955 			    len, flags, callback);
4956 	}
4957 
4958 	ASSERT((sfmmup == ksfmmup) || (flags & HAT_UNLOAD_OTHER) || \
4959 	    AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
4960 
4961 	ASSERT(sfmmup != NULL);
4962 	ASSERT((len & MMU_PAGEOFFSET) == 0);
4963 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
4964 
4965 	/*
4966 	 * Probing through a large VA range (say 63 bits) will be slow, even
4967 	 * at 4 Meg steps between the probes. So, when the virtual address range
4968 	 * is very large, search the HME entries for what to unload.
4969 	 *
4970 	 *	len >> TTE_PAGE_SHIFT(TTE4M) is the # of 4Meg probes we'd need
4971 	 *
4972 	 *	UHMEHASH_SZ is number of hash buckets to examine
4973 	 *
4974 	 */
4975 	if (sfmmup != KHATID && (len >> TTE_PAGE_SHIFT(TTE4M)) > UHMEHASH_SZ) {
4976 		hat_unload_large_virtual(sfmmup, addr, len, flags, callback);
4977 		return;
4978 	}
4979 
4980 	CPUSET_ZERO(cpuset);
4981 
4982 	/*
4983 	 * If the process is exiting, we can save a lot of fuss since
4984 	 * we'll flush the TLB when we free the ctx anyway.
4985 	 */
4986 	if (sfmmup->sfmmu_free)
4987 		dmrp = NULL;
4988 	else
4989 		dmrp = &dmr;
4990 
4991 	DEMAP_RANGE_INIT(sfmmup, dmrp);
4992 	endaddr = addr + len;
4993 	hblktag.htag_id = sfmmup;
4994 
4995 	/*
4996 	 * It is likely for the vm to call unload over a wide range of
4997 	 * addresses that are actually very sparsely populated by
4998 	 * translations.  In order to speed this up the sfmmu hat supports
4999 	 * the concept of shadow hmeblks. Dummy large page hmeblks that
5000 	 * correspond to actual small translations are allocated at tteload
5001 	 * time and are referred to as shadow hmeblks.  Now, during unload
5002 	 * time, we first check if we have a shadow hmeblk for that
5003 	 * translation.  The absence of one means the corresponding address
5004 	 * range is empty and can be skipped.
5005 	 *
5006 	 * The kernel is an exception to above statement and that is why
5007 	 * we don't use shadow hmeblks and hash starting from the smallest
5008 	 * page size.
5009 	 */
5010 	if (sfmmup == KHATID) {
5011 		iskernel = 1;
5012 		hashno = TTE64K;
5013 	} else {
5014 		iskernel = 0;
5015 		if (mmu_page_sizes == max_mmu_page_sizes) {
5016 			hashno = TTE256M;
5017 		} else {
5018 			hashno = TTE4M;
5019 		}
5020 	}
5021 	while (addr < endaddr) {
5022 		hmeshift = HME_HASH_SHIFT(hashno);
5023 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5024 		hblktag.htag_rehash = hashno;
5025 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5026 
5027 		SFMMU_HASH_LOCK(hmebp);
5028 
5029 		HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, hblkpa, pr_hblk,
5030 			prevpa, &list);
5031 		if (hmeblkp == NULL) {
5032 			/*
5033 			 * didn't find an hmeblk. skip the appropiate
5034 			 * address range.
5035 			 */
5036 			SFMMU_HASH_UNLOCK(hmebp);
5037 			if (iskernel) {
5038 				if (hashno < mmu_hashcnt) {
5039 					hashno++;
5040 					continue;
5041 				} else {
5042 					hashno = TTE64K;
5043 					addr = (caddr_t)roundup((uintptr_t)addr
5044 						+ 1, MMU_PAGESIZE64K);
5045 					continue;
5046 				}
5047 			}
5048 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5049 				(1 << hmeshift));
5050 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5051 				ASSERT(hashno == TTE64K);
5052 				continue;
5053 			}
5054 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5055 				hashno = TTE512K;
5056 				continue;
5057 			}
5058 			if (mmu_page_sizes == max_mmu_page_sizes) {
5059 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5060 					hashno = TTE4M;
5061 					continue;
5062 				}
5063 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5064 					hashno = TTE32M;
5065 					continue;
5066 				}
5067 				hashno = TTE256M;
5068 				continue;
5069 			} else {
5070 				hashno = TTE4M;
5071 				continue;
5072 			}
5073 		}
5074 		ASSERT(hmeblkp);
5075 		if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5076 			/*
5077 			 * If the valid count is zero we can skip the range
5078 			 * mapped by this hmeblk.
5079 			 * We free hblks in the case of HAT_UNMAP.  HAT_UNMAP
5080 			 * is used by segment drivers as a hint
5081 			 * that the mapping resource won't be used any longer.
5082 			 * The best example of this is during exit().
5083 			 */
5084 			addr = (caddr_t)roundup((uintptr_t)addr + 1,
5085 				get_hblk_span(hmeblkp));
5086 			if ((flags & HAT_UNLOAD_UNMAP) ||
5087 			    (iskernel && !issegkmap)) {
5088 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa,
5089 				    pr_hblk);
5090 				sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
5091 			}
5092 			SFMMU_HASH_UNLOCK(hmebp);
5093 
5094 			if (iskernel) {
5095 				hashno = TTE64K;
5096 				continue;
5097 			}
5098 			if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5099 				ASSERT(hashno == TTE64K);
5100 				continue;
5101 			}
5102 			if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5103 				hashno = TTE512K;
5104 				continue;
5105 			}
5106 			if (mmu_page_sizes == max_mmu_page_sizes) {
5107 				if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5108 					hashno = TTE4M;
5109 					continue;
5110 				}
5111 				if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5112 					hashno = TTE32M;
5113 					continue;
5114 				}
5115 				hashno = TTE256M;
5116 				continue;
5117 			} else {
5118 				hashno = TTE4M;
5119 				continue;
5120 			}
5121 		}
5122 		if (hmeblkp->hblk_shw_bit) {
5123 			/*
5124 			 * If we encounter a shadow hmeblk we know there is
5125 			 * smaller sized hmeblks mapping the same address space.
5126 			 * Decrement the hash size and rehash.
5127 			 */
5128 			ASSERT(sfmmup != KHATID);
5129 			hashno--;
5130 			SFMMU_HASH_UNLOCK(hmebp);
5131 			continue;
5132 		}
5133 
5134 		/*
5135 		 * track callback address ranges.
5136 		 * only start a new range when it's not contiguous
5137 		 */
5138 		if (callback != NULL) {
5139 			if (addr_count > 0 &&
5140 			    addr == cb_end_addr[addr_count - 1])
5141 				--addr_count;
5142 			else
5143 				cb_start_addr[addr_count] = addr;
5144 		}
5145 
5146 		addr = sfmmu_hblk_unload(sfmmup, hmeblkp, addr, endaddr,
5147 				dmrp, flags);
5148 
5149 		if (callback != NULL)
5150 			cb_end_addr[addr_count++] = addr;
5151 
5152 		if (((flags & HAT_UNLOAD_UNMAP) || (iskernel && !issegkmap)) &&
5153 		    !hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
5154 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa,
5155 			    pr_hblk);
5156 			sfmmu_hblk_free(hmebp, hmeblkp, hblkpa, &list);
5157 		}
5158 		SFMMU_HASH_UNLOCK(hmebp);
5159 
5160 		/*
5161 		 * Notify our caller as to exactly which pages
5162 		 * have been unloaded. We do these in clumps,
5163 		 * to minimize the number of xt_sync()s that need to occur.
5164 		 */
5165 		if (callback != NULL && addr_count == MAX_CB_ADDR) {
5166 			DEMAP_RANGE_FLUSH(dmrp);
5167 			if (dmrp != NULL) {
5168 				cpuset = sfmmup->sfmmu_cpusran;
5169 				xt_sync(cpuset);
5170 			}
5171 
5172 			for (a = 0; a < MAX_CB_ADDR; ++a) {
5173 				callback->hcb_start_addr = cb_start_addr[a];
5174 				callback->hcb_end_addr = cb_end_addr[a];
5175 				callback->hcb_function(callback);
5176 			}
5177 			addr_count = 0;
5178 		}
5179 		if (iskernel) {
5180 			hashno = TTE64K;
5181 			continue;
5182 		}
5183 		if ((uintptr_t)addr & MMU_PAGEOFFSET512K) {
5184 			ASSERT(hashno == TTE64K);
5185 			continue;
5186 		}
5187 		if ((uintptr_t)addr & MMU_PAGEOFFSET4M) {
5188 			hashno = TTE512K;
5189 			continue;
5190 		}
5191 		if (mmu_page_sizes == max_mmu_page_sizes) {
5192 			if ((uintptr_t)addr & MMU_PAGEOFFSET32M) {
5193 				hashno = TTE4M;
5194 				continue;
5195 			}
5196 			if ((uintptr_t)addr & MMU_PAGEOFFSET256M) {
5197 				hashno = TTE32M;
5198 				continue;
5199 			}
5200 			hashno = TTE256M;
5201 		} else {
5202 			hashno = TTE4M;
5203 		}
5204 	}
5205 
5206 	sfmmu_hblks_list_purge(&list);
5207 	DEMAP_RANGE_FLUSH(dmrp);
5208 	if (dmrp != NULL) {
5209 		cpuset = sfmmup->sfmmu_cpusran;
5210 		xt_sync(cpuset);
5211 	}
5212 	if (callback && addr_count != 0) {
5213 		for (a = 0; a < addr_count; ++a) {
5214 			callback->hcb_start_addr = cb_start_addr[a];
5215 			callback->hcb_end_addr = cb_end_addr[a];
5216 			callback->hcb_function(callback);
5217 		}
5218 	}
5219 
5220 	/*
5221 	 * Check TSB and TLB page sizes if the process isn't exiting.
5222 	 */
5223 	if (!sfmmup->sfmmu_free)
5224 		sfmmu_check_page_sizes(sfmmup, 0);
5225 }
5226 
5227 /*
5228  * Unload all the mappings in the range [addr..addr+len). addr and len must
5229  * be MMU_PAGESIZE aligned.
5230  */
5231 void
5232 hat_unload(struct hat *sfmmup, caddr_t addr, size_t len, uint_t flags)
5233 {
5234 	if (sfmmup->sfmmu_xhat_provider) {
5235 		XHAT_UNLOAD(sfmmup, addr, len, flags);
5236 		return;
5237 	}
5238 	hat_unload_callback(sfmmup, addr, len, flags, NULL);
5239 }
5240 
5241 
5242 /*
5243  * Find the largest mapping size for this page.
5244  */
5245 int
5246 fnd_mapping_sz(page_t *pp)
5247 {
5248 	int sz;
5249 	int p_index;
5250 
5251 	p_index = PP_MAPINDEX(pp);
5252 
5253 	sz = 0;
5254 	p_index >>= 1;	/* don't care about 8K bit */
5255 	for (; p_index; p_index >>= 1) {
5256 		sz++;
5257 	}
5258 
5259 	return (sz);
5260 }
5261 
5262 /*
5263  * This function unloads a range of addresses for an hmeblk.
5264  * It returns the next address to be unloaded.
5265  * It should be called with the hash lock held.
5266  */
5267 static caddr_t
5268 sfmmu_hblk_unload(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5269 	caddr_t endaddr, demap_range_t *dmrp, uint_t flags)
5270 {
5271 	tte_t	tte, ttemod;
5272 	struct	sf_hment *sfhmep;
5273 	int	ttesz;
5274 	long	ttecnt;
5275 	page_t *pp;
5276 	kmutex_t *pml;
5277 	int ret;
5278 	int use_demap_range;
5279 
5280 	ASSERT(in_hblk_range(hmeblkp, addr));
5281 	ASSERT(!hmeblkp->hblk_shw_bit);
5282 #ifdef DEBUG
5283 	if (get_hblk_ttesz(hmeblkp) != TTE8K &&
5284 	    (endaddr < get_hblk_endaddr(hmeblkp))) {
5285 		panic("sfmmu_hblk_unload: partial unload of large page");
5286 	}
5287 #endif /* DEBUG */
5288 
5289 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5290 	ttesz = get_hblk_ttesz(hmeblkp);
5291 
5292 	use_demap_range = (do_virtual_coloring &&
5293 	    ((dmrp == NULL) || TTEBYTES(ttesz) == DEMAP_RANGE_PGSZ(dmrp)));
5294 	if (use_demap_range) {
5295 		DEMAP_RANGE_CONTINUE(dmrp, addr, endaddr);
5296 	} else {
5297 		DEMAP_RANGE_FLUSH(dmrp);
5298 	}
5299 	ttecnt = 0;
5300 	HBLKTOHME(sfhmep, hmeblkp, addr);
5301 
5302 	while (addr < endaddr) {
5303 		pml = NULL;
5304 again:
5305 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5306 		if (TTE_IS_VALID(&tte)) {
5307 			pp = sfhmep->hme_page;
5308 			if (pp && pml == NULL) {
5309 				pml = sfmmu_mlist_enter(pp);
5310 			}
5311 
5312 			/*
5313 			 * Verify if hme still points to 'pp' now that
5314 			 * we have p_mapping lock.
5315 			 */
5316 			if (sfhmep->hme_page != pp) {
5317 				if (pp != NULL && sfhmep->hme_page != NULL) {
5318 					if (pml) {
5319 						sfmmu_mlist_exit(pml);
5320 					}
5321 					/* Re-start this iteration. */
5322 					continue;
5323 				}
5324 				ASSERT((pp != NULL) &&
5325 				    (sfhmep->hme_page == NULL));
5326 				goto tte_unloaded;
5327 			}
5328 
5329 			/*
5330 			 * This point on we have both HASH and p_mapping
5331 			 * lock.
5332 			 */
5333 			ASSERT(pp == sfhmep->hme_page);
5334 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5335 
5336 			/*
5337 			 * We need to loop on modify tte because it is
5338 			 * possible for pagesync to come along and
5339 			 * change the software bits beneath us.
5340 			 *
5341 			 * Page_unload can also invalidate the tte after
5342 			 * we read tte outside of p_mapping lock.
5343 			 */
5344 			ttemod = tte;
5345 
5346 			TTE_SET_INVALID(&ttemod);
5347 			ret = sfmmu_modifytte_try(&tte, &ttemod,
5348 			    &sfhmep->hme_tte);
5349 
5350 			if (ret <= 0) {
5351 				if (TTE_IS_VALID(&tte)) {
5352 					goto again;
5353 				} else {
5354 					/*
5355 					 * We read in a valid pte, but it
5356 					 * is unloaded by page_unload.
5357 					 * hme_page has become NULL and
5358 					 * we hold no p_mapping lock.
5359 					 */
5360 					ASSERT(pp == NULL && pml == NULL);
5361 					goto tte_unloaded;
5362 				}
5363 			}
5364 
5365 			if (!(flags & HAT_UNLOAD_NOSYNC)) {
5366 				sfmmu_ttesync(sfmmup, addr, &tte, pp);
5367 			}
5368 
5369 			/*
5370 			 * Ok- we invalidated the tte. Do the rest of the job.
5371 			 */
5372 			ttecnt++;
5373 
5374 			if (flags & HAT_UNLOAD_UNLOCK) {
5375 				ASSERT(hmeblkp->hblk_lckcnt > 0);
5376 				atomic_add_16(&hmeblkp->hblk_lckcnt, -1);
5377 				HBLK_STACK_TRACE(hmeblkp, HBLK_UNLOCK);
5378 			}
5379 
5380 			/*
5381 			 * Normally we would need to flush the page
5382 			 * from the virtual cache at this point in
5383 			 * order to prevent a potential cache alias
5384 			 * inconsistency.
5385 			 * The particular scenario we need to worry
5386 			 * about is:
5387 			 * Given:  va1 and va2 are two virtual address
5388 			 * that alias and map the same physical
5389 			 * address.
5390 			 * 1.	mapping exists from va1 to pa and data
5391 			 * has been read into the cache.
5392 			 * 2.	unload va1.
5393 			 * 3.	load va2 and modify data using va2.
5394 			 * 4	unload va2.
5395 			 * 5.	load va1 and reference data.  Unless we
5396 			 * flush the data cache when we unload we will
5397 			 * get stale data.
5398 			 * Fortunately, page coloring eliminates the
5399 			 * above scenario by remembering the color a
5400 			 * physical page was last or is currently
5401 			 * mapped to.  Now, we delay the flush until
5402 			 * the loading of translations.  Only when the
5403 			 * new translation is of a different color
5404 			 * are we forced to flush.
5405 			 */
5406 			if (use_demap_range) {
5407 				/*
5408 				 * Mark this page as needing a demap.
5409 				 */
5410 				DEMAP_RANGE_MARKPG(dmrp, addr);
5411 			} else {
5412 				if (do_virtual_coloring) {
5413 					sfmmu_tlb_demap(addr, sfmmup, hmeblkp,
5414 					    sfmmup->sfmmu_free, 0);
5415 				} else {
5416 					pfn_t pfnum;
5417 
5418 					pfnum = TTE_TO_PFN(addr, &tte);
5419 					sfmmu_tlbcache_demap(addr, sfmmup,
5420 					    hmeblkp, pfnum, sfmmup->sfmmu_free,
5421 					    FLUSH_NECESSARY_CPUS,
5422 					    CACHE_FLUSH, 0);
5423 				}
5424 			}
5425 
5426 			if (pp) {
5427 				/*
5428 				 * Remove the hment from the mapping list
5429 				 */
5430 				ASSERT(hmeblkp->hblk_hmecnt > 0);
5431 
5432 				/*
5433 				 * Again, we cannot
5434 				 * ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS);
5435 				 */
5436 				HME_SUB(sfhmep, pp);
5437 				membar_stst();
5438 				atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
5439 			}
5440 
5441 			ASSERT(hmeblkp->hblk_vcnt > 0);
5442 			atomic_add_16(&hmeblkp->hblk_vcnt, -1);
5443 
5444 			ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
5445 			    !hmeblkp->hblk_lckcnt);
5446 
5447 #ifdef VAC
5448 			if (pp && (pp->p_nrm & (P_KPMC | P_KPMS | P_TNC))) {
5449 				if (PP_ISTNC(pp)) {
5450 					/*
5451 					 * If page was temporary
5452 					 * uncached, try to recache
5453 					 * it. Note that HME_SUB() was
5454 					 * called above so p_index and
5455 					 * mlist had been updated.
5456 					 */
5457 					conv_tnc(pp, ttesz);
5458 				} else if (pp->p_mapping == NULL) {
5459 					ASSERT(kpm_enable);
5460 					/*
5461 					 * Page is marked to be in VAC conflict
5462 					 * to an existing kpm mapping and/or is
5463 					 * kpm mapped using only the regular
5464 					 * pagesize.
5465 					 */
5466 					sfmmu_kpm_hme_unload(pp);
5467 				}
5468 			}
5469 #endif	/* VAC */
5470 		} else if ((pp = sfhmep->hme_page) != NULL) {
5471 				/*
5472 				 * TTE is invalid but the hme
5473 				 * still exists. let pageunload
5474 				 * complete its job.
5475 				 */
5476 				ASSERT(pml == NULL);
5477 				pml = sfmmu_mlist_enter(pp);
5478 				if (sfhmep->hme_page != NULL) {
5479 					sfmmu_mlist_exit(pml);
5480 					pml = NULL;
5481 					goto again;
5482 				}
5483 				ASSERT(sfhmep->hme_page == NULL);
5484 		} else if (hmeblkp->hblk_hmecnt != 0) {
5485 			/*
5486 			 * pageunload may have not finished decrementing
5487 			 * hblk_vcnt and hblk_hmecnt. Find page_t if any and
5488 			 * wait for pageunload to finish. Rely on pageunload
5489 			 * to decrement hblk_hmecnt after hblk_vcnt.
5490 			 */
5491 			pfn_t pfn = TTE_TO_TTEPFN(&tte);
5492 			ASSERT(pml == NULL);
5493 			if (pf_is_memory(pfn)) {
5494 				pp = page_numtopp_nolock(pfn);
5495 				if (pp != NULL) {
5496 					pml = sfmmu_mlist_enter(pp);
5497 					sfmmu_mlist_exit(pml);
5498 					pml = NULL;
5499 				}
5500 			}
5501 		}
5502 
5503 tte_unloaded:
5504 		/*
5505 		 * At this point, the tte we are looking at
5506 		 * should be unloaded, and hme has been unlinked
5507 		 * from page too. This is important because in
5508 		 * pageunload, it does ttesync() then HME_SUB.
5509 		 * We need to make sure HME_SUB has been completed
5510 		 * so we know ttesync() has been completed. Otherwise,
5511 		 * at exit time, after return from hat layer, VM will
5512 		 * release as structure which hat_setstat() (called
5513 		 * by ttesync()) needs.
5514 		 */
5515 #ifdef DEBUG
5516 		{
5517 			tte_t	dtte;
5518 
5519 			ASSERT(sfhmep->hme_page == NULL);
5520 
5521 			sfmmu_copytte(&sfhmep->hme_tte, &dtte);
5522 			ASSERT(!TTE_IS_VALID(&dtte));
5523 		}
5524 #endif
5525 
5526 		if (pml) {
5527 			sfmmu_mlist_exit(pml);
5528 		}
5529 
5530 		addr += TTEBYTES(ttesz);
5531 		sfhmep++;
5532 		DEMAP_RANGE_NEXTPG(dmrp);
5533 	}
5534 	if (ttecnt > 0)
5535 		atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -ttecnt);
5536 	return (addr);
5537 }
5538 
5539 /*
5540  * Synchronize all the mappings in the range [addr..addr+len).
5541  * Can be called with clearflag having two states:
5542  * HAT_SYNC_DONTZERO means just return the rm stats
5543  * HAT_SYNC_ZERORM means zero rm bits in the tte and return the stats
5544  */
5545 void
5546 hat_sync(struct hat *sfmmup, caddr_t addr, size_t len, uint_t clearflag)
5547 {
5548 	struct hmehash_bucket *hmebp;
5549 	hmeblk_tag hblktag;
5550 	int hmeshift, hashno = 1;
5551 	struct hme_blk *hmeblkp, *list = NULL;
5552 	caddr_t endaddr;
5553 	cpuset_t cpuset;
5554 
5555 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
5556 	ASSERT((sfmmup == ksfmmup) ||
5557 		AS_LOCK_HELD(sfmmup->sfmmu_as, &sfmmup->sfmmu_as->a_lock));
5558 	ASSERT((len & MMU_PAGEOFFSET) == 0);
5559 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
5560 		(clearflag == HAT_SYNC_ZERORM));
5561 
5562 	CPUSET_ZERO(cpuset);
5563 
5564 	endaddr = addr + len;
5565 	hblktag.htag_id = sfmmup;
5566 	/*
5567 	 * Spitfire supports 4 page sizes.
5568 	 * Most pages are expected to be of the smallest page
5569 	 * size (8K) and these will not need to be rehashed. 64K
5570 	 * pages also don't need to be rehashed because the an hmeblk
5571 	 * spans 64K of address space. 512K pages might need 1 rehash and
5572 	 * and 4M pages 2 rehashes.
5573 	 */
5574 	while (addr < endaddr) {
5575 		hmeshift = HME_HASH_SHIFT(hashno);
5576 		hblktag.htag_bspage = HME_HASH_BSPAGE(addr, hmeshift);
5577 		hblktag.htag_rehash = hashno;
5578 		hmebp = HME_HASH_FUNCTION(sfmmup, addr, hmeshift);
5579 
5580 		SFMMU_HASH_LOCK(hmebp);
5581 
5582 		HME_HASH_SEARCH(hmebp, hblktag, hmeblkp, &list);
5583 		if (hmeblkp != NULL) {
5584 			/*
5585 			 * We've encountered a shadow hmeblk so skip the range
5586 			 * of the next smaller mapping size.
5587 			 */
5588 			if (hmeblkp->hblk_shw_bit) {
5589 				ASSERT(sfmmup != ksfmmup);
5590 				ASSERT(hashno > 1);
5591 				addr = (caddr_t)P2END((uintptr_t)addr,
5592 					    TTEBYTES(hashno - 1));
5593 			} else {
5594 				addr = sfmmu_hblk_sync(sfmmup, hmeblkp,
5595 				    addr, endaddr, clearflag);
5596 			}
5597 			SFMMU_HASH_UNLOCK(hmebp);
5598 			hashno = 1;
5599 			continue;
5600 		}
5601 		SFMMU_HASH_UNLOCK(hmebp);
5602 
5603 		if (!HME_REHASH(sfmmup) || (hashno >= mmu_hashcnt)) {
5604 			/*
5605 			 * We have traversed the whole list and rehashed
5606 			 * if necessary without finding the address to sync.
5607 			 * This is ok so we increment the address by the
5608 			 * smallest hmeblk range for kernel mappings and the
5609 			 * largest hmeblk range, to account for shadow hmeblks,
5610 			 * for user mappings and continue.
5611 			 */
5612 			if (sfmmup == ksfmmup)
5613 				addr = (caddr_t)P2END((uintptr_t)addr,
5614 					    TTEBYTES(1));
5615 			else
5616 				addr = (caddr_t)P2END((uintptr_t)addr,
5617 					    TTEBYTES(hashno));
5618 			hashno = 1;
5619 		} else {
5620 			hashno++;
5621 		}
5622 	}
5623 	sfmmu_hblks_list_purge(&list);
5624 	cpuset = sfmmup->sfmmu_cpusran;
5625 	xt_sync(cpuset);
5626 }
5627 
5628 static caddr_t
5629 sfmmu_hblk_sync(struct hat *sfmmup, struct hme_blk *hmeblkp, caddr_t addr,
5630 	caddr_t endaddr, int clearflag)
5631 {
5632 	tte_t	tte, ttemod;
5633 	struct sf_hment *sfhmep;
5634 	int ttesz;
5635 	struct page *pp;
5636 	kmutex_t *pml;
5637 	int ret;
5638 
5639 	ASSERT(hmeblkp->hblk_shw_bit == 0);
5640 
5641 	endaddr = MIN(endaddr, get_hblk_endaddr(hmeblkp));
5642 
5643 	ttesz = get_hblk_ttesz(hmeblkp);
5644 	HBLKTOHME(sfhmep, hmeblkp, addr);
5645 
5646 	while (addr < endaddr) {
5647 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5648 		if (TTE_IS_VALID(&tte)) {
5649 			pml = NULL;
5650 			pp = sfhmep->hme_page;
5651 			if (pp) {
5652 				pml = sfmmu_mlist_enter(pp);
5653 			}
5654 			if (pp != sfhmep->hme_page) {
5655 				/*
5656 				 * tte most have been unloaded
5657 				 * underneath us.  Recheck
5658 				 */
5659 				ASSERT(pml);
5660 				sfmmu_mlist_exit(pml);
5661 				continue;
5662 			}
5663 
5664 			ASSERT(pp == NULL || sfmmu_mlist_held(pp));
5665 
5666 			if (clearflag == HAT_SYNC_ZERORM) {
5667 				ttemod = tte;
5668 				TTE_CLR_RM(&ttemod);
5669 				ret = sfmmu_modifytte_try(&tte, &ttemod,
5670 				    &sfhmep->hme_tte);
5671 				if (ret < 0) {
5672 					if (pml) {
5673 						sfmmu_mlist_exit(pml);
5674 					}
5675 					continue;
5676 				}
5677 
5678 				if (ret > 0) {
5679 					sfmmu_tlb_demap(addr, sfmmup,
5680 						hmeblkp, 0, 0);
5681 				}
5682 			}
5683 			sfmmu_ttesync(sfmmup, addr, &tte, pp);
5684 			if (pml) {
5685 				sfmmu_mlist_exit(pml);
5686 			}
5687 		}
5688 		addr += TTEBYTES(ttesz);
5689 		sfhmep++;
5690 	}
5691 	return (addr);
5692 }
5693 
5694 /*
5695  * This function will sync a tte to the page struct and it will
5696  * update the hat stats. Currently it allows us to pass a NULL pp
5697  * and we will simply update the stats.  We may want to change this
5698  * so we only keep stats for pages backed by pp's.
5699  */
5700 static void
5701 sfmmu_ttesync(struct hat *sfmmup, caddr_t addr, tte_t *ttep, page_t *pp)
5702 {
5703 	uint_t rm = 0;
5704 	int   	sz;
5705 	pgcnt_t	npgs;
5706 
5707 	ASSERT(TTE_IS_VALID(ttep));
5708 
5709 	if (TTE_IS_NOSYNC(ttep)) {
5710 		return;
5711 	}
5712 
5713 	if (TTE_IS_REF(ttep))  {
5714 		rm = P_REF;
5715 	}
5716 	if (TTE_IS_MOD(ttep))  {
5717 		rm |= P_MOD;
5718 	}
5719 
5720 	if (rm == 0) {
5721 		return;
5722 	}
5723 
5724 	sz = TTE_CSZ(ttep);
5725 	if (sfmmup->sfmmu_rmstat) {
5726 		int i;
5727 		caddr_t	vaddr = addr;
5728 
5729 		for (i = 0; i < TTEPAGES(sz); i++, vaddr += MMU_PAGESIZE) {
5730 			hat_setstat(sfmmup->sfmmu_as, vaddr, MMU_PAGESIZE, rm);
5731 		}
5732 
5733 	}
5734 
5735 	/*
5736 	 * XXX I want to use cas to update nrm bits but they
5737 	 * currently belong in common/vm and not in hat where
5738 	 * they should be.
5739 	 * The nrm bits are protected by the same mutex as
5740 	 * the one that protects the page's mapping list.
5741 	 */
5742 	if (!pp)
5743 		return;
5744 	ASSERT(sfmmu_mlist_held(pp));
5745 	/*
5746 	 * If the tte is for a large page, we need to sync all the
5747 	 * pages covered by the tte.
5748 	 */
5749 	if (sz != TTE8K) {
5750 		ASSERT(pp->p_szc != 0);
5751 		pp = PP_GROUPLEADER(pp, sz);
5752 		ASSERT(sfmmu_mlist_held(pp));
5753 	}
5754 
5755 	/* Get number of pages from tte size. */
5756 	npgs = TTEPAGES(sz);
5757 
5758 	do {
5759 		ASSERT(pp);
5760 		ASSERT(sfmmu_mlist_held(pp));
5761 		if (((rm & P_REF) != 0 && !PP_ISREF(pp)) ||
5762 		    ((rm & P_MOD) != 0 && !PP_ISMOD(pp)))
5763 			hat_page_setattr(pp, rm);
5764 
5765 		/*
5766 		 * Are we done? If not, we must have a large mapping.
5767 		 * For large mappings we need to sync the rest of the pages
5768 		 * covered by this tte; goto the next page.
5769 		 */
5770 	} while (--npgs > 0 && (pp = PP_PAGENEXT(pp)));
5771 }
5772 
5773 /*
5774  * Execute pre-callback handler of each pa_hment linked to pp
5775  *
5776  * Inputs:
5777  *   flag: either HAT_PRESUSPEND or HAT_SUSPEND.
5778  *   capture_cpus: pointer to return value (below)
5779  *
5780  * Returns:
5781  *   Propagates the subsystem callback return values back to the caller;
5782  *   returns 0 on success.  If capture_cpus is non-NULL, the value returned
5783  *   is zero if all of the pa_hments are of a type that do not require
5784  *   capturing CPUs prior to suspending the mapping, else it is 1.
5785  */
5786 static int
5787 hat_pageprocess_precallbacks(struct page *pp, uint_t flag, int *capture_cpus)
5788 {
5789 	struct sf_hment	*sfhmep;
5790 	struct pa_hment *pahmep;
5791 	int (*f)(caddr_t, uint_t, uint_t, void *);
5792 	int		ret;
5793 	id_t		id;
5794 	int		locked = 0;
5795 	kmutex_t	*pml;
5796 
5797 	ASSERT(PAGE_EXCL(pp));
5798 	if (!sfmmu_mlist_held(pp)) {
5799 		pml = sfmmu_mlist_enter(pp);
5800 		locked = 1;
5801 	}
5802 
5803 	if (capture_cpus)
5804 		*capture_cpus = 0;
5805 
5806 top:
5807 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
5808 		/*
5809 		 * skip sf_hments corresponding to VA<->PA mappings;
5810 		 * for pa_hment's, hme_tte.ll is zero
5811 		 */
5812 		if (!IS_PAHME(sfhmep))
5813 			continue;
5814 
5815 		pahmep = sfhmep->hme_data;
5816 		ASSERT(pahmep != NULL);
5817 
5818 		/*
5819 		 * skip if pre-handler has been called earlier in this loop
5820 		 */
5821 		if (pahmep->flags & flag)
5822 			continue;
5823 
5824 		id = pahmep->cb_id;
5825 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
5826 		if (capture_cpus && sfmmu_cb_table[id].capture_cpus != 0)
5827 			*capture_cpus = 1;
5828 		if ((f = sfmmu_cb_table[id].prehandler) == NULL) {
5829 			pahmep->flags |= flag;
5830 			continue;
5831 		}
5832 
5833 		/*
5834 		 * Drop the mapping list lock to avoid locking order issues.
5835 		 */
5836 		if (locked)
5837 			sfmmu_mlist_exit(pml);
5838 
5839 		ret = f(pahmep->addr, pahmep->len, flag, pahmep->pvt);
5840 		if (ret != 0)
5841 			return (ret);	/* caller must do the cleanup */
5842 
5843 		if (locked) {
5844 			pml = sfmmu_mlist_enter(pp);
5845 			pahmep->flags |= flag;
5846 			goto top;
5847 		}
5848 
5849 		pahmep->flags |= flag;
5850 	}
5851 
5852 	if (locked)
5853 		sfmmu_mlist_exit(pml);
5854 
5855 	return (0);
5856 }
5857 
5858 /*
5859  * Execute post-callback handler of each pa_hment linked to pp
5860  *
5861  * Same overall assumptions and restrictions apply as for
5862  * hat_pageprocess_precallbacks().
5863  */
5864 static void
5865 hat_pageprocess_postcallbacks(struct page *pp, uint_t flag)
5866 {
5867 	pfn_t pgpfn = pp->p_pagenum;
5868 	pfn_t pgmask = btop(page_get_pagesize(pp->p_szc)) - 1;
5869 	pfn_t newpfn;
5870 	struct sf_hment *sfhmep;
5871 	struct pa_hment *pahmep;
5872 	int (*f)(caddr_t, uint_t, uint_t, void *, pfn_t);
5873 	id_t	id;
5874 	int	locked = 0;
5875 	kmutex_t *pml;
5876 
5877 	ASSERT(PAGE_EXCL(pp));
5878 	if (!sfmmu_mlist_held(pp)) {
5879 		pml = sfmmu_mlist_enter(pp);
5880 		locked = 1;
5881 	}
5882 
5883 top:
5884 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
5885 		/*
5886 		 * skip sf_hments corresponding to VA<->PA mappings;
5887 		 * for pa_hment's, hme_tte.ll is zero
5888 		 */
5889 		if (!IS_PAHME(sfhmep))
5890 			continue;
5891 
5892 		pahmep = sfhmep->hme_data;
5893 		ASSERT(pahmep != NULL);
5894 
5895 		if ((pahmep->flags & flag) == 0)
5896 			continue;
5897 
5898 		pahmep->flags &= ~flag;
5899 
5900 		id = pahmep->cb_id;
5901 		ASSERT(id >= (id_t)0 && id < sfmmu_cb_nextid);
5902 		if ((f = sfmmu_cb_table[id].posthandler) == NULL)
5903 			continue;
5904 
5905 		/*
5906 		 * Convert the base page PFN into the constituent PFN
5907 		 * which is needed by the callback handler.
5908 		 */
5909 		newpfn = pgpfn | (btop((uintptr_t)pahmep->addr) & pgmask);
5910 
5911 		/*
5912 		 * Drop the mapping list lock to avoid locking order issues.
5913 		 */
5914 		if (locked)
5915 			sfmmu_mlist_exit(pml);
5916 
5917 		if (f(pahmep->addr, pahmep->len, flag, pahmep->pvt, newpfn)
5918 		    != 0)
5919 			panic("sfmmu: posthandler failed");
5920 
5921 		if (locked) {
5922 			pml = sfmmu_mlist_enter(pp);
5923 			goto top;
5924 		}
5925 	}
5926 
5927 	if (locked)
5928 		sfmmu_mlist_exit(pml);
5929 }
5930 
5931 /*
5932  * Suspend locked kernel mapping
5933  */
5934 void
5935 hat_pagesuspend(struct page *pp)
5936 {
5937 	struct sf_hment *sfhmep;
5938 	sfmmu_t *sfmmup;
5939 	tte_t tte, ttemod;
5940 	struct hme_blk *hmeblkp;
5941 	caddr_t addr;
5942 	int index, cons;
5943 	cpuset_t cpuset;
5944 
5945 	ASSERT(PAGE_EXCL(pp));
5946 	ASSERT(sfmmu_mlist_held(pp));
5947 
5948 	mutex_enter(&kpr_suspendlock);
5949 
5950 	/*
5951 	 * Call into dtrace to tell it we're about to suspend a
5952 	 * kernel mapping. This prevents us from running into issues
5953 	 * with probe context trying to touch a suspended page
5954 	 * in the relocation codepath itself.
5955 	 */
5956 	if (dtrace_kreloc_init)
5957 		(*dtrace_kreloc_init)();
5958 
5959 	index = PP_MAPINDEX(pp);
5960 	cons = TTE8K;
5961 
5962 retry:
5963 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
5964 
5965 		if (IS_PAHME(sfhmep))
5966 			continue;
5967 
5968 		if (get_hblk_ttesz(sfmmu_hmetohblk(sfhmep)) != cons)
5969 			continue;
5970 
5971 		/*
5972 		 * Loop until we successfully set the suspend bit in
5973 		 * the TTE.
5974 		 */
5975 again:
5976 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
5977 		ASSERT(TTE_IS_VALID(&tte));
5978 
5979 		ttemod = tte;
5980 		TTE_SET_SUSPEND(&ttemod);
5981 		if (sfmmu_modifytte_try(&tte, &ttemod,
5982 		    &sfhmep->hme_tte) < 0)
5983 			goto again;
5984 
5985 		/*
5986 		 * Invalidate TSB entry
5987 		 */
5988 		hmeblkp = sfmmu_hmetohblk(sfhmep);
5989 
5990 		sfmmup = hblktosfmmu(hmeblkp);
5991 		ASSERT(sfmmup == ksfmmup);
5992 
5993 		addr = tte_to_vaddr(hmeblkp, tte);
5994 
5995 		/*
5996 		 * No need to make sure that the TSB for this sfmmu is
5997 		 * not being relocated since it is ksfmmup and thus it
5998 		 * will never be relocated.
5999 		 */
6000 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp);
6001 
6002 		/*
6003 		 * Update xcall stats
6004 		 */
6005 		cpuset = cpu_ready_set;
6006 		CPUSET_DEL(cpuset, CPU->cpu_id);
6007 
6008 		/* LINTED: constant in conditional context */
6009 		SFMMU_XCALL_STATS(ksfmmup);
6010 
6011 		/*
6012 		 * Flush TLB entry on remote CPU's
6013 		 */
6014 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
6015 		    (uint64_t)ksfmmup);
6016 		xt_sync(cpuset);
6017 
6018 		/*
6019 		 * Flush TLB entry on local CPU
6020 		 */
6021 		vtag_flushpage(addr, (uint64_t)ksfmmup);
6022 	}
6023 
6024 	while (index != 0) {
6025 		index = index >> 1;
6026 		if (index != 0)
6027 			cons++;
6028 		if (index & 0x1) {
6029 			pp = PP_GROUPLEADER(pp, cons);
6030 			goto retry;
6031 		}
6032 	}
6033 }
6034 
6035 #ifdef	DEBUG
6036 
6037 #define	N_PRLE	1024
6038 struct prle {
6039 	page_t *targ;
6040 	page_t *repl;
6041 	int status;
6042 	int pausecpus;
6043 	hrtime_t whence;
6044 };
6045 
6046 static struct prle page_relocate_log[N_PRLE];
6047 static int prl_entry;
6048 static kmutex_t prl_mutex;
6049 
6050 #define	PAGE_RELOCATE_LOG(t, r, s, p)					\
6051 	mutex_enter(&prl_mutex);					\
6052 	page_relocate_log[prl_entry].targ = *(t);			\
6053 	page_relocate_log[prl_entry].repl = *(r);			\
6054 	page_relocate_log[prl_entry].status = (s);			\
6055 	page_relocate_log[prl_entry].pausecpus = (p);			\
6056 	page_relocate_log[prl_entry].whence = gethrtime();		\
6057 	prl_entry = (prl_entry == (N_PRLE - 1))? 0 : prl_entry + 1;	\
6058 	mutex_exit(&prl_mutex);
6059 
6060 #else	/* !DEBUG */
6061 #define	PAGE_RELOCATE_LOG(t, r, s, p)
6062 #endif
6063 
6064 /*
6065  * Core Kernel Page Relocation Algorithm
6066  *
6067  * Input:
6068  *
6069  * target : 	constituent pages are SE_EXCL locked.
6070  * replacement:	constituent pages are SE_EXCL locked.
6071  *
6072  * Output:
6073  *
6074  * nrelocp:	number of pages relocated
6075  */
6076 int
6077 hat_page_relocate(page_t **target, page_t **replacement, spgcnt_t *nrelocp)
6078 {
6079 	page_t		*targ, *repl;
6080 	page_t		*tpp, *rpp;
6081 	kmutex_t	*low, *high;
6082 	spgcnt_t	npages, i;
6083 	page_t		*pl = NULL;
6084 	int		old_pil;
6085 	cpuset_t	cpuset;
6086 	int		cap_cpus;
6087 	int		ret;
6088 
6089 	if (hat_kpr_enabled == 0 || !kcage_on || PP_ISNORELOC(*target)) {
6090 		PAGE_RELOCATE_LOG(target, replacement, EAGAIN, -1);
6091 		return (EAGAIN);
6092 	}
6093 
6094 	mutex_enter(&kpr_mutex);
6095 	kreloc_thread = curthread;
6096 
6097 	targ = *target;
6098 	repl = *replacement;
6099 	ASSERT(repl != NULL);
6100 	ASSERT(targ->p_szc == repl->p_szc);
6101 
6102 	npages = page_get_pagecnt(targ->p_szc);
6103 
6104 	/*
6105 	 * unload VA<->PA mappings that are not locked
6106 	 */
6107 	tpp = targ;
6108 	for (i = 0; i < npages; i++) {
6109 		(void) hat_pageunload(tpp, SFMMU_KERNEL_RELOC);
6110 		tpp++;
6111 	}
6112 
6113 	/*
6114 	 * Do "presuspend" callbacks, in a context from which we can still
6115 	 * block as needed. Note that we don't hold the mapping list lock
6116 	 * of "targ" at this point due to potential locking order issues;
6117 	 * we assume that between the hat_pageunload() above and holding
6118 	 * the SE_EXCL lock that the mapping list *cannot* change at this
6119 	 * point.
6120 	 */
6121 	ret = hat_pageprocess_precallbacks(targ, HAT_PRESUSPEND, &cap_cpus);
6122 	if (ret != 0) {
6123 		/*
6124 		 * EIO translates to fatal error, for all others cleanup
6125 		 * and return EAGAIN.
6126 		 */
6127 		ASSERT(ret != EIO);
6128 		hat_pageprocess_postcallbacks(targ, HAT_POSTUNSUSPEND);
6129 		PAGE_RELOCATE_LOG(target, replacement, ret, -1);
6130 		kreloc_thread = NULL;
6131 		mutex_exit(&kpr_mutex);
6132 		return (EAGAIN);
6133 	}
6134 
6135 	/*
6136 	 * acquire p_mapping list lock for both the target and replacement
6137 	 * root pages.
6138 	 *
6139 	 * low and high refer to the need to grab the mlist locks in a
6140 	 * specific order in order to prevent race conditions.  Thus the
6141 	 * lower lock must be grabbed before the higher lock.
6142 	 *
6143 	 * This will block hat_unload's accessing p_mapping list.  Since
6144 	 * we have SE_EXCL lock, hat_memload and hat_pageunload will be
6145 	 * blocked.  Thus, no one else will be accessing the p_mapping list
6146 	 * while we suspend and reload the locked mapping below.
6147 	 */
6148 	tpp = targ;
6149 	rpp = repl;
6150 	sfmmu_mlist_reloc_enter(tpp, rpp, &low, &high);
6151 
6152 	kpreempt_disable();
6153 
6154 #ifdef VAC
6155 	/*
6156 	 * If the replacement page is of a different virtual color
6157 	 * than the page it is replacing, we need to handle the VAC
6158 	 * consistency for it just as we would if we were setting up
6159 	 * a new mapping to a page.
6160 	 */
6161 	if ((tpp->p_szc == 0) && (PP_GET_VCOLOR(rpp) != NO_VCOLOR)) {
6162 		if (tpp->p_vcolor != rpp->p_vcolor) {
6163 			sfmmu_cache_flushcolor(PP_GET_VCOLOR(rpp),
6164 			    rpp->p_pagenum);
6165 		}
6166 	}
6167 #endif
6168 
6169 	/*
6170 	 * We raise our PIL to 13 so that we don't get captured by
6171 	 * another CPU or pinned by an interrupt thread.  We can't go to
6172 	 * PIL 14 since the nexus driver(s) may need to interrupt at
6173 	 * that level in the case of IOMMU pseudo mappings.
6174 	 */
6175 	cpuset = cpu_ready_set;
6176 	CPUSET_DEL(cpuset, CPU->cpu_id);
6177 	if (!cap_cpus || CPUSET_ISNULL(cpuset)) {
6178 		old_pil = splr(XCALL_PIL);
6179 	} else {
6180 		old_pil = -1;
6181 		xc_attention(cpuset);
6182 	}
6183 	ASSERT(getpil() == XCALL_PIL);
6184 
6185 	/*
6186 	 * Now do suspend callbacks. In the case of an IOMMU mapping
6187 	 * this will suspend all DMA activity to the page while it is
6188 	 * being relocated. Since we are well above LOCK_LEVEL and CPUs
6189 	 * may be captured at this point we should have acquired any needed
6190 	 * locks in the presuspend callback.
6191 	 */
6192 	ret = hat_pageprocess_precallbacks(targ, HAT_SUSPEND, NULL);
6193 	if (ret != 0) {
6194 		repl = targ;
6195 		goto suspend_fail;
6196 	}
6197 
6198 	/*
6199 	 * Raise the PIL yet again, this time to block all high-level
6200 	 * interrupts on this CPU. This is necessary to prevent an
6201 	 * interrupt routine from pinning the thread which holds the
6202 	 * mapping suspended and then touching the suspended page.
6203 	 *
6204 	 * Once the page is suspended we also need to be careful to
6205 	 * avoid calling any functions which touch any seg_kmem memory
6206 	 * since that memory may be backed by the very page we are
6207 	 * relocating in here!
6208 	 */
6209 	hat_pagesuspend(targ);
6210 
6211 	/*
6212 	 * Now that we are confident everybody has stopped using this page,
6213 	 * copy the page contents.  Note we use a physical copy to prevent
6214 	 * locking issues and to avoid fpRAS because we can't handle it in
6215 	 * this context.
6216 	 */
6217 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6218 		/*
6219 		 * Copy the contents of the page.
6220 		 */
6221 		ppcopy_kernel(tpp, rpp);
6222 	}
6223 
6224 	tpp = targ;
6225 	rpp = repl;
6226 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6227 		/*
6228 		 * Copy attributes.  VAC consistency was handled above,
6229 		 * if required.
6230 		 */
6231 		rpp->p_nrm = tpp->p_nrm;
6232 		tpp->p_nrm = 0;
6233 		rpp->p_index = tpp->p_index;
6234 		tpp->p_index = 0;
6235 #ifdef VAC
6236 		rpp->p_vcolor = tpp->p_vcolor;
6237 #endif
6238 	}
6239 
6240 	/*
6241 	 * First, unsuspend the page, if we set the suspend bit, and transfer
6242 	 * the mapping list from the target page to the replacement page.
6243 	 * Next process postcallbacks; since pa_hment's are linked only to the
6244 	 * p_mapping list of root page, we don't iterate over the constituent
6245 	 * pages.
6246 	 */
6247 	hat_pagereload(targ, repl);
6248 
6249 suspend_fail:
6250 	hat_pageprocess_postcallbacks(repl, HAT_UNSUSPEND);
6251 
6252 	/*
6253 	 * Now lower our PIL and release any captured CPUs since we
6254 	 * are out of the "danger zone".  After this it will again be
6255 	 * safe to acquire adaptive mutex locks, or to drop them...
6256 	 */
6257 	if (old_pil != -1) {
6258 		splx(old_pil);
6259 	} else {
6260 		xc_dismissed(cpuset);
6261 	}
6262 
6263 	kpreempt_enable();
6264 
6265 	sfmmu_mlist_reloc_exit(low, high);
6266 
6267 	/*
6268 	 * Postsuspend callbacks should drop any locks held across
6269 	 * the suspend callbacks.  As before, we don't hold the mapping
6270 	 * list lock at this point.. our assumption is that the mapping
6271 	 * list still can't change due to our holding SE_EXCL lock and
6272 	 * there being no unlocked mappings left. Hence the restriction
6273 	 * on calling context to hat_delete_callback()
6274 	 */
6275 	hat_pageprocess_postcallbacks(repl, HAT_POSTUNSUSPEND);
6276 	if (ret != 0) {
6277 		/*
6278 		 * The second presuspend call failed: we got here through
6279 		 * the suspend_fail label above.
6280 		 */
6281 		ASSERT(ret != EIO);
6282 		PAGE_RELOCATE_LOG(target, replacement, ret, cap_cpus);
6283 		kreloc_thread = NULL;
6284 		mutex_exit(&kpr_mutex);
6285 		return (EAGAIN);
6286 	}
6287 
6288 	/*
6289 	 * Now that we're out of the performance critical section we can
6290 	 * take care of updating the hash table, since we still
6291 	 * hold all the pages locked SE_EXCL at this point we
6292 	 * needn't worry about things changing out from under us.
6293 	 */
6294 	tpp = targ;
6295 	rpp = repl;
6296 	for (i = 0; i < npages; i++, tpp++, rpp++) {
6297 
6298 		/*
6299 		 * replace targ with replacement in page_hash table
6300 		 */
6301 		targ = tpp;
6302 		page_relocate_hash(rpp, targ);
6303 
6304 		/*
6305 		 * concatenate target; caller of platform_page_relocate()
6306 		 * expects target to be concatenated after returning.
6307 		 */
6308 		ASSERT(targ->p_next == targ);
6309 		ASSERT(targ->p_prev == targ);
6310 		page_list_concat(&pl, &targ);
6311 	}
6312 
6313 	ASSERT(*target == pl);
6314 	*nrelocp = npages;
6315 	PAGE_RELOCATE_LOG(target, replacement, 0, cap_cpus);
6316 	kreloc_thread = NULL;
6317 	mutex_exit(&kpr_mutex);
6318 	return (0);
6319 }
6320 
6321 /*
6322  * Called when stray pa_hments are found attached to a page which is
6323  * being freed.  Notify the subsystem which attached the pa_hment of
6324  * the error if it registered a suitable handler, else panic.
6325  */
6326 static void
6327 sfmmu_pahment_leaked(struct pa_hment *pahmep)
6328 {
6329 	id_t cb_id = pahmep->cb_id;
6330 
6331 	ASSERT(cb_id >= (id_t)0 && cb_id < sfmmu_cb_nextid);
6332 	if (sfmmu_cb_table[cb_id].errhandler != NULL) {
6333 		if (sfmmu_cb_table[cb_id].errhandler(pahmep->addr, pahmep->len,
6334 		    HAT_CB_ERR_LEAKED, pahmep->pvt) == 0)
6335 			return;		/* non-fatal */
6336 	}
6337 	panic("pa_hment leaked: 0x%p", pahmep);
6338 }
6339 
6340 /*
6341  * Remove all mappings to page 'pp'.
6342  */
6343 int
6344 hat_pageunload(struct page *pp, uint_t forceflag)
6345 {
6346 	struct page *origpp = pp;
6347 	struct sf_hment *sfhme, *tmphme;
6348 	struct hme_blk *hmeblkp;
6349 	kmutex_t *pml;
6350 #ifdef VAC
6351 	kmutex_t *pmtx;
6352 #endif
6353 	cpuset_t cpuset, tset;
6354 	int index, cons;
6355 	int xhme_blks;
6356 	int pa_hments;
6357 
6358 	ASSERT(PAGE_EXCL(pp));
6359 
6360 retry_xhat:
6361 	tmphme = NULL;
6362 	xhme_blks = 0;
6363 	pa_hments = 0;
6364 	CPUSET_ZERO(cpuset);
6365 
6366 	pml = sfmmu_mlist_enter(pp);
6367 
6368 	if (pp->p_kpmref)
6369 		sfmmu_kpm_pageunload(pp);
6370 	ASSERT(!PP_ISMAPPED_KPM(pp));
6371 
6372 	index = PP_MAPINDEX(pp);
6373 	cons = TTE8K;
6374 retry:
6375 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
6376 		tmphme = sfhme->hme_next;
6377 
6378 		if (IS_PAHME(sfhme)) {
6379 			ASSERT(sfhme->hme_data != NULL);
6380 			pa_hments++;
6381 			continue;
6382 		}
6383 
6384 		hmeblkp = sfmmu_hmetohblk(sfhme);
6385 		if (hmeblkp->hblk_xhat_bit) {
6386 			struct xhat_hme_blk *xblk =
6387 			    (struct xhat_hme_blk *)hmeblkp;
6388 
6389 			(void) XHAT_PAGEUNLOAD(xblk->xhat_hme_blk_hat,
6390 			    pp, forceflag, XBLK2PROVBLK(xblk));
6391 
6392 			xhme_blks = 1;
6393 			continue;
6394 		}
6395 
6396 		/*
6397 		 * If there are kernel mappings don't unload them, they will
6398 		 * be suspended.
6399 		 */
6400 		if (forceflag == SFMMU_KERNEL_RELOC && hmeblkp->hblk_lckcnt &&
6401 		    hmeblkp->hblk_tag.htag_id == ksfmmup)
6402 			continue;
6403 
6404 		tset = sfmmu_pageunload(pp, sfhme, cons);
6405 		CPUSET_OR(cpuset, tset);
6406 	}
6407 
6408 	while (index != 0) {
6409 		index = index >> 1;
6410 		if (index != 0)
6411 			cons++;
6412 		if (index & 0x1) {
6413 			/* Go to leading page */
6414 			pp = PP_GROUPLEADER(pp, cons);
6415 			ASSERT(sfmmu_mlist_held(pp));
6416 			goto retry;
6417 		}
6418 	}
6419 
6420 	/*
6421 	 * cpuset may be empty if the page was only mapped by segkpm,
6422 	 * in which case we won't actually cross-trap.
6423 	 */
6424 	xt_sync(cpuset);
6425 
6426 	/*
6427 	 * The page should have no mappings at this point, unless
6428 	 * we were called from hat_page_relocate() in which case we
6429 	 * leave the locked mappings which will be suspended later.
6430 	 */
6431 	ASSERT(!PP_ISMAPPED(origpp) || xhme_blks || pa_hments ||
6432 	    (forceflag == SFMMU_KERNEL_RELOC));
6433 
6434 #ifdef VAC
6435 	if (PP_ISTNC(pp)) {
6436 		if (cons == TTE8K) {
6437 			pmtx = sfmmu_page_enter(pp);
6438 			PP_CLRTNC(pp);
6439 			sfmmu_page_exit(pmtx);
6440 		} else {
6441 			conv_tnc(pp, cons);
6442 		}
6443 	}
6444 #endif	/* VAC */
6445 
6446 	if (pa_hments && forceflag != SFMMU_KERNEL_RELOC) {
6447 		/*
6448 		 * Unlink any pa_hments and free them, calling back
6449 		 * the responsible subsystem to notify it of the error.
6450 		 * This can occur in situations such as drivers leaking
6451 		 * DMA handles: naughty, but common enough that we'd like
6452 		 * to keep the system running rather than bringing it
6453 		 * down with an obscure error like "pa_hment leaked"
6454 		 * which doesn't aid the user in debugging their driver.
6455 		 */
6456 		for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
6457 			tmphme = sfhme->hme_next;
6458 			if (IS_PAHME(sfhme)) {
6459 				struct pa_hment *pahmep = sfhme->hme_data;
6460 				sfmmu_pahment_leaked(pahmep);
6461 				HME_SUB(sfhme, pp);
6462 				kmem_cache_free(pa_hment_cache, pahmep);
6463 			}
6464 		}
6465 
6466 		ASSERT(!PP_ISMAPPED(origpp) || xhme_blks);
6467 	}
6468 
6469 	sfmmu_mlist_exit(pml);
6470 
6471 	/*
6472 	 * XHAT may not have finished unloading pages
6473 	 * because some other thread was waiting for
6474 	 * mlist lock and XHAT_PAGEUNLOAD let it do
6475 	 * the job.
6476 	 */
6477 	if (xhme_blks) {
6478 		pp = origpp;
6479 		goto retry_xhat;
6480 	}
6481 
6482 	return (0);
6483 }
6484 
6485 cpuset_t
6486 sfmmu_pageunload(page_t *pp, struct sf_hment *sfhme, int cons)
6487 {
6488 	struct hme_blk *hmeblkp;
6489 	sfmmu_t *sfmmup;
6490 	tte_t tte, ttemod;
6491 #ifdef DEBUG
6492 	tte_t orig_old;
6493 #endif /* DEBUG */
6494 	caddr_t addr;
6495 	int ttesz;
6496 	int ret;
6497 	cpuset_t cpuset;
6498 
6499 	ASSERT(pp != NULL);
6500 	ASSERT(sfmmu_mlist_held(pp));
6501 	ASSERT(pp->p_vnode != &kvp);
6502 
6503 	CPUSET_ZERO(cpuset);
6504 
6505 	hmeblkp = sfmmu_hmetohblk(sfhme);
6506 
6507 readtte:
6508 	sfmmu_copytte(&sfhme->hme_tte, &tte);
6509 	if (TTE_IS_VALID(&tte)) {
6510 		sfmmup = hblktosfmmu(hmeblkp);
6511 		ttesz = get_hblk_ttesz(hmeblkp);
6512 		/*
6513 		 * Only unload mappings of 'cons' size.
6514 		 */
6515 		if (ttesz != cons)
6516 			return (cpuset);
6517 
6518 		/*
6519 		 * Note that we have p_mapping lock, but no hash lock here.
6520 		 * hblk_unload() has to have both hash lock AND p_mapping
6521 		 * lock before it tries to modify tte. So, the tte could
6522 		 * not become invalid in the sfmmu_modifytte_try() below.
6523 		 */
6524 		ttemod = tte;
6525 #ifdef DEBUG
6526 		orig_old = tte;
6527 #endif /* DEBUG */
6528 
6529 		TTE_SET_INVALID(&ttemod);
6530 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
6531 		if (ret < 0) {
6532 #ifdef DEBUG
6533 			/* only R/M bits can change. */
6534 			chk_tte(&orig_old, &tte, &ttemod, hmeblkp);
6535 #endif /* DEBUG */
6536 			goto readtte;
6537 		}
6538 
6539 		if (ret == 0) {
6540 			panic("pageunload: cas failed?");
6541 		}
6542 
6543 		addr = tte_to_vaddr(hmeblkp, tte);
6544 
6545 		sfmmu_ttesync(sfmmup, addr, &tte, pp);
6546 
6547 		atomic_add_long(&sfmmup->sfmmu_ttecnt[ttesz], -1);
6548 
6549 		/*
6550 		 * We need to flush the page from the virtual cache
6551 		 * in order to prevent a virtual cache alias
6552 		 * inconsistency. The particular scenario we need
6553 		 * to worry about is:
6554 		 * Given:  va1 and va2 are two virtual address that
6555 		 * alias and will map the same physical address.
6556 		 * 1.	mapping exists from va1 to pa and data has
6557 		 *	been read into the cache.
6558 		 * 2.	unload va1.
6559 		 * 3.	load va2 and modify data using va2.
6560 		 * 4	unload va2.
6561 		 * 5.	load va1 and reference data.  Unless we flush
6562 		 *	the data cache when we unload we will get
6563 		 *	stale data.
6564 		 * This scenario is taken care of by using virtual
6565 		 * page coloring.
6566 		 */
6567 		if (sfmmup->sfmmu_ismhat) {
6568 			/*
6569 			 * Flush TSBs, TLBs and caches
6570 			 * of every process
6571 			 * sharing this ism segment.
6572 			 */
6573 			sfmmu_hat_lock_all();
6574 			mutex_enter(&ism_mlist_lock);
6575 			kpreempt_disable();
6576 			if (do_virtual_coloring)
6577 				sfmmu_ismtlbcache_demap(addr, sfmmup, hmeblkp,
6578 					pp->p_pagenum, CACHE_NO_FLUSH);
6579 			else
6580 				sfmmu_ismtlbcache_demap(addr, sfmmup, hmeblkp,
6581 					pp->p_pagenum, CACHE_FLUSH);
6582 			kpreempt_enable();
6583 			mutex_exit(&ism_mlist_lock);
6584 			sfmmu_hat_unlock_all();
6585 			cpuset = cpu_ready_set;
6586 		} else if (do_virtual_coloring) {
6587 			sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
6588 			cpuset = sfmmup->sfmmu_cpusran;
6589 		} else {
6590 			sfmmu_tlbcache_demap(addr, sfmmup, hmeblkp,
6591 				pp->p_pagenum, 0, FLUSH_NECESSARY_CPUS,
6592 				CACHE_FLUSH, 0);
6593 			cpuset = sfmmup->sfmmu_cpusran;
6594 		}
6595 
6596 		/*
6597 		 * Hme_sub has to run after ttesync() and a_rss update.
6598 		 * See hblk_unload().
6599 		 */
6600 		HME_SUB(sfhme, pp);
6601 		membar_stst();
6602 
6603 		/*
6604 		 * We can not make ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
6605 		 * since pteload may have done a HME_ADD() right after
6606 		 * we did the HME_SUB() above. Hmecnt is now maintained
6607 		 * by cas only. no lock guranteed its value. The only
6608 		 * gurantee we have is the hmecnt should not be less than
6609 		 * what it should be so the hblk will not be taken away.
6610 		 * It's also important that we decremented the hmecnt after
6611 		 * we are done with hmeblkp so that this hmeblk won't be
6612 		 * stolen.
6613 		 */
6614 		ASSERT(hmeblkp->hblk_hmecnt > 0);
6615 		ASSERT(hmeblkp->hblk_vcnt > 0);
6616 		atomic_add_16(&hmeblkp->hblk_vcnt, -1);
6617 		atomic_add_16(&hmeblkp->hblk_hmecnt, -1);
6618 		/*
6619 		 * This is bug 4063182.
6620 		 * XXX: fixme
6621 		 * ASSERT(hmeblkp->hblk_hmecnt || hmeblkp->hblk_vcnt ||
6622 		 *	!hmeblkp->hblk_lckcnt);
6623 		 */
6624 	} else {
6625 		panic("invalid tte? pp %p &tte %p",
6626 		    (void *)pp, (void *)&tte);
6627 	}
6628 
6629 	return (cpuset);
6630 }
6631 
6632 /*
6633  * While relocating a kernel page, this function will move the mappings
6634  * from tpp to dpp and modify any associated data with these mappings.
6635  * It also unsuspends the suspended kernel mapping.
6636  */
6637 static void
6638 hat_pagereload(struct page *tpp, struct page *dpp)
6639 {
6640 	struct sf_hment *sfhme;
6641 	tte_t tte, ttemod;
6642 	int index, cons;
6643 
6644 	ASSERT(getpil() == PIL_MAX);
6645 	ASSERT(sfmmu_mlist_held(tpp));
6646 	ASSERT(sfmmu_mlist_held(dpp));
6647 
6648 	index = PP_MAPINDEX(tpp);
6649 	cons = TTE8K;
6650 
6651 	/* Update real mappings to the page */
6652 retry:
6653 	for (sfhme = tpp->p_mapping; sfhme != NULL; sfhme = sfhme->hme_next) {
6654 		if (IS_PAHME(sfhme))
6655 			continue;
6656 		sfmmu_copytte(&sfhme->hme_tte, &tte);
6657 		ttemod = tte;
6658 
6659 		/*
6660 		 * replace old pfn with new pfn in TTE
6661 		 */
6662 		PFN_TO_TTE(ttemod, dpp->p_pagenum);
6663 
6664 		/*
6665 		 * clear suspend bit
6666 		 */
6667 		ASSERT(TTE_IS_SUSPEND(&ttemod));
6668 		TTE_CLR_SUSPEND(&ttemod);
6669 
6670 		if (sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte) < 0)
6671 			panic("hat_pagereload(): sfmmu_modifytte_try() failed");
6672 
6673 		/*
6674 		 * set hme_page point to new page
6675 		 */
6676 		sfhme->hme_page = dpp;
6677 	}
6678 
6679 	/*
6680 	 * move p_mapping list from old page to new page
6681 	 */
6682 	dpp->p_mapping = tpp->p_mapping;
6683 	tpp->p_mapping = NULL;
6684 	dpp->p_share = tpp->p_share;
6685 	tpp->p_share = 0;
6686 
6687 	while (index != 0) {
6688 		index = index >> 1;
6689 		if (index != 0)
6690 			cons++;
6691 		if (index & 0x1) {
6692 			tpp = PP_GROUPLEADER(tpp, cons);
6693 			dpp = PP_GROUPLEADER(dpp, cons);
6694 			goto retry;
6695 		}
6696 	}
6697 
6698 	if (dtrace_kreloc_fini)
6699 		(*dtrace_kreloc_fini)();
6700 	mutex_exit(&kpr_suspendlock);
6701 }
6702 
6703 uint_t
6704 hat_pagesync(struct page *pp, uint_t clearflag)
6705 {
6706 	struct sf_hment *sfhme, *tmphme = NULL;
6707 	struct hme_blk *hmeblkp;
6708 	kmutex_t *pml;
6709 	cpuset_t cpuset, tset;
6710 	int	index, cons;
6711 	extern	ulong_t po_share;
6712 	page_t	*save_pp = pp;
6713 
6714 	CPUSET_ZERO(cpuset);
6715 
6716 	if (PP_ISRO(pp) && (clearflag & HAT_SYNC_STOPON_MOD)) {
6717 		return (PP_GENERIC_ATTR(pp));
6718 	}
6719 
6720 	if ((clearflag == (HAT_SYNC_STOPON_REF | HAT_SYNC_DONTZERO)) &&
6721 	    PP_ISREF(pp)) {
6722 		return (PP_GENERIC_ATTR(pp));
6723 	}
6724 
6725 	if ((clearflag == (HAT_SYNC_STOPON_MOD | HAT_SYNC_DONTZERO)) &&
6726 	    PP_ISMOD(pp)) {
6727 		return (PP_GENERIC_ATTR(pp));
6728 	}
6729 
6730 	if ((clearflag & HAT_SYNC_STOPON_SHARED) != 0 &&
6731 	    (pp->p_share > po_share) &&
6732 	    !(clearflag & HAT_SYNC_ZERORM)) {
6733 		if (PP_ISRO(pp))
6734 			hat_page_setattr(pp, P_REF);
6735 		return (PP_GENERIC_ATTR(pp));
6736 	}
6737 
6738 	clearflag &= ~HAT_SYNC_STOPON_SHARED;
6739 	pml = sfmmu_mlist_enter(pp);
6740 	index = PP_MAPINDEX(pp);
6741 	cons = TTE8K;
6742 retry:
6743 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
6744 		/*
6745 		 * We need to save the next hment on the list since
6746 		 * it is possible for pagesync to remove an invalid hment
6747 		 * from the list.
6748 		 */
6749 		tmphme = sfhme->hme_next;
6750 		/*
6751 		 * If we are looking for large mappings and this hme doesn't
6752 		 * reach the range we are seeking, just ignore its.
6753 		 */
6754 		hmeblkp = sfmmu_hmetohblk(sfhme);
6755 		if (hmeblkp->hblk_xhat_bit)
6756 			continue;
6757 
6758 		if (hme_size(sfhme) < cons)
6759 			continue;
6760 		tset = sfmmu_pagesync(pp, sfhme,
6761 			clearflag & ~HAT_SYNC_STOPON_RM);
6762 		CPUSET_OR(cpuset, tset);
6763 		/*
6764 		 * If clearflag is HAT_SYNC_DONTZERO, break out as soon
6765 		 * as the "ref" or "mod" is set.
6766 		 */
6767 		if ((clearflag & ~HAT_SYNC_STOPON_RM) == HAT_SYNC_DONTZERO &&
6768 		    ((clearflag & HAT_SYNC_STOPON_MOD) && PP_ISMOD(save_pp)) ||
6769 		    ((clearflag & HAT_SYNC_STOPON_REF) && PP_ISREF(save_pp))) {
6770 			index = 0;
6771 			break;
6772 		}
6773 	}
6774 
6775 	while (index) {
6776 		index = index >> 1;
6777 		cons++;
6778 		if (index & 0x1) {
6779 			/* Go to leading page */
6780 			pp = PP_GROUPLEADER(pp, cons);
6781 			goto retry;
6782 		}
6783 	}
6784 
6785 	xt_sync(cpuset);
6786 	sfmmu_mlist_exit(pml);
6787 	return (PP_GENERIC_ATTR(save_pp));
6788 }
6789 
6790 /*
6791  * Get all the hardware dependent attributes for a page struct
6792  */
6793 static cpuset_t
6794 sfmmu_pagesync(struct page *pp, struct sf_hment *sfhme,
6795 	uint_t clearflag)
6796 {
6797 	caddr_t addr;
6798 	tte_t tte, ttemod;
6799 	struct hme_blk *hmeblkp;
6800 	int ret;
6801 	sfmmu_t *sfmmup;
6802 	cpuset_t cpuset;
6803 
6804 	ASSERT(pp != NULL);
6805 	ASSERT(sfmmu_mlist_held(pp));
6806 	ASSERT((clearflag == HAT_SYNC_DONTZERO) ||
6807 		(clearflag == HAT_SYNC_ZERORM));
6808 
6809 	SFMMU_STAT(sf_pagesync);
6810 
6811 	CPUSET_ZERO(cpuset);
6812 
6813 sfmmu_pagesync_retry:
6814 
6815 	sfmmu_copytte(&sfhme->hme_tte, &tte);
6816 	if (TTE_IS_VALID(&tte)) {
6817 		hmeblkp = sfmmu_hmetohblk(sfhme);
6818 		sfmmup = hblktosfmmu(hmeblkp);
6819 		addr = tte_to_vaddr(hmeblkp, tte);
6820 		if (clearflag == HAT_SYNC_ZERORM) {
6821 			ttemod = tte;
6822 			TTE_CLR_RM(&ttemod);
6823 			ret = sfmmu_modifytte_try(&tte, &ttemod,
6824 				&sfhme->hme_tte);
6825 			if (ret < 0) {
6826 				/*
6827 				 * cas failed and the new value is not what
6828 				 * we want.
6829 				 */
6830 				goto sfmmu_pagesync_retry;
6831 			}
6832 
6833 			if (ret > 0) {
6834 				/* we win the cas */
6835 				sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
6836 				cpuset = sfmmup->sfmmu_cpusran;
6837 			}
6838 		}
6839 
6840 		sfmmu_ttesync(sfmmup, addr, &tte, pp);
6841 	}
6842 	return (cpuset);
6843 }
6844 
6845 /*
6846  * Remove write permission from a mappings to a page, so that
6847  * we can detect the next modification of it. This requires modifying
6848  * the TTE then invalidating (demap) any TLB entry using that TTE.
6849  * This code is similar to sfmmu_pagesync().
6850  */
6851 static cpuset_t
6852 sfmmu_pageclrwrt(struct page *pp, struct sf_hment *sfhme)
6853 {
6854 	caddr_t addr;
6855 	tte_t tte;
6856 	tte_t ttemod;
6857 	struct hme_blk *hmeblkp;
6858 	int ret;
6859 	sfmmu_t *sfmmup;
6860 	cpuset_t cpuset;
6861 
6862 	ASSERT(pp != NULL);
6863 	ASSERT(sfmmu_mlist_held(pp));
6864 
6865 	CPUSET_ZERO(cpuset);
6866 	SFMMU_STAT(sf_clrwrt);
6867 
6868 retry:
6869 
6870 	sfmmu_copytte(&sfhme->hme_tte, &tte);
6871 	if (TTE_IS_VALID(&tte) && TTE_IS_WRITABLE(&tte)) {
6872 		hmeblkp = sfmmu_hmetohblk(sfhme);
6873 
6874 		/*
6875 		 * xhat mappings should never be to a VMODSORT page.
6876 		 */
6877 		ASSERT(hmeblkp->hblk_xhat_bit == 0);
6878 
6879 		sfmmup = hblktosfmmu(hmeblkp);
6880 		addr = tte_to_vaddr(hmeblkp, tte);
6881 
6882 		ttemod = tte;
6883 		TTE_CLR_WRT(&ttemod);
6884 		TTE_CLR_MOD(&ttemod);
6885 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
6886 
6887 		/*
6888 		 * if cas failed and the new value is not what
6889 		 * we want retry
6890 		 */
6891 		if (ret < 0)
6892 			goto retry;
6893 
6894 		/* we win the cas */
6895 		if (ret > 0) {
6896 			sfmmu_tlb_demap(addr, sfmmup, hmeblkp, 0, 0);
6897 			cpuset = sfmmup->sfmmu_cpusran;
6898 		}
6899 	}
6900 
6901 	return (cpuset);
6902 }
6903 
6904 /*
6905  * Walk all mappings of a page, removing write permission and clearing the
6906  * ref/mod bits. This code is similar to hat_pagesync()
6907  */
6908 static void
6909 hat_page_clrwrt(page_t *pp)
6910 {
6911 	struct sf_hment *sfhme;
6912 	struct sf_hment *tmphme = NULL;
6913 	kmutex_t *pml;
6914 	cpuset_t cpuset;
6915 	cpuset_t tset;
6916 	int	index;
6917 	int	 cons;
6918 
6919 	CPUSET_ZERO(cpuset);
6920 
6921 	pml = sfmmu_mlist_enter(pp);
6922 	index = PP_MAPINDEX(pp);
6923 	cons = TTE8K;
6924 retry:
6925 	for (sfhme = pp->p_mapping; sfhme; sfhme = tmphme) {
6926 		tmphme = sfhme->hme_next;
6927 
6928 		/*
6929 		 * If we are looking for large mappings and this hme doesn't
6930 		 * reach the range we are seeking, just ignore its.
6931 		 */
6932 
6933 		if (hme_size(sfhme) < cons)
6934 			continue;
6935 
6936 		tset = sfmmu_pageclrwrt(pp, sfhme);
6937 		CPUSET_OR(cpuset, tset);
6938 	}
6939 
6940 	while (index) {
6941 		index = index >> 1;
6942 		cons++;
6943 		if (index & 0x1) {
6944 			/* Go to leading page */
6945 			pp = PP_GROUPLEADER(pp, cons);
6946 			goto retry;
6947 		}
6948 	}
6949 
6950 	xt_sync(cpuset);
6951 	sfmmu_mlist_exit(pml);
6952 }
6953 
6954 /*
6955  * Set the given REF/MOD/RO bits for the given page.
6956  * For a vnode with a sorted v_pages list, we need to change
6957  * the attributes and the v_pages list together under page_vnode_mutex.
6958  */
6959 void
6960 hat_page_setattr(page_t *pp, uint_t flag)
6961 {
6962 	vnode_t		*vp = pp->p_vnode;
6963 	page_t		**listp;
6964 	kmutex_t	*pmtx;
6965 	kmutex_t	*vphm = NULL;
6966 
6967 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
6968 
6969 	/*
6970 	 * nothing to do if attribute already set
6971 	 */
6972 	if ((pp->p_nrm & flag) == flag)
6973 		return;
6974 
6975 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
6976 		vphm = page_vnode_mutex(vp);
6977 		mutex_enter(vphm);
6978 	}
6979 
6980 	pmtx = sfmmu_page_enter(pp);
6981 	pp->p_nrm |= flag;
6982 	sfmmu_page_exit(pmtx);
6983 
6984 	if (vphm != NULL) {
6985 		/*
6986 		 * Some File Systems examine v_pages for NULL w/o
6987 		 * grabbing the vphm mutex. Must not let it become NULL when
6988 		 * pp is the only page on the list.
6989 		 */
6990 		if (pp->p_vpnext != pp) {
6991 			page_vpsub(&vp->v_pages, pp);
6992 			if (vp->v_pages != NULL)
6993 				listp = &vp->v_pages->p_vpprev->p_vpnext;
6994 			else
6995 				listp = &vp->v_pages;
6996 			page_vpadd(listp, pp);
6997 		}
6998 		mutex_exit(vphm);
6999 	}
7000 }
7001 
7002 void
7003 hat_page_clrattr(page_t *pp, uint_t flag)
7004 {
7005 	vnode_t		*vp = pp->p_vnode;
7006 	kmutex_t	*vphm = NULL;
7007 	kmutex_t	*pmtx;
7008 
7009 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7010 
7011 	/*
7012 	 * For vnode with a sorted v_pages list, we need to change
7013 	 * the attributes and the v_pages list together under page_vnode_mutex.
7014 	 */
7015 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
7016 		vphm = page_vnode_mutex(vp);
7017 		mutex_enter(vphm);
7018 	}
7019 
7020 	pmtx = sfmmu_page_enter(pp);
7021 	pp->p_nrm &= ~flag;
7022 	sfmmu_page_exit(pmtx);
7023 
7024 	if (vphm != NULL) {
7025 		/*
7026 		 * Some File Systems examine v_pages for NULL w/o
7027 		 * grabbing the vphm mutex. Must not let it become NULL when
7028 		 * pp is the only page on the list.
7029 		 */
7030 		if (pp->p_vpnext != pp) {
7031 			page_vpsub(&vp->v_pages, pp);
7032 			page_vpadd(&vp->v_pages, pp);
7033 		}
7034 		mutex_exit(vphm);
7035 
7036 		/*
7037 		 * VMODSORT works by removing write permissions and getting
7038 		 * a fault when a page is made dirty. At this point
7039 		 * we need to remove write permission from all mappings
7040 		 * to this page.
7041 		 */
7042 		hat_page_clrwrt(pp);
7043 	}
7044 }
7045 
7046 
7047 uint_t
7048 hat_page_getattr(page_t *pp, uint_t flag)
7049 {
7050 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
7051 	return ((uint_t)(pp->p_nrm & flag));
7052 }
7053 
7054 /*
7055  * DEBUG kernels: verify that a kernel va<->pa translation
7056  * is safe by checking the underlying page_t is in a page
7057  * relocation-safe state.
7058  */
7059 #ifdef	DEBUG
7060 void
7061 sfmmu_check_kpfn(pfn_t pfn)
7062 {
7063 	page_t *pp;
7064 	int index, cons;
7065 
7066 	if (hat_check_vtop == 0)
7067 		return;
7068 
7069 	if (hat_kpr_enabled == 0 || kvseg.s_base == NULL || panicstr)
7070 		return;
7071 
7072 	pp = page_numtopp_nolock(pfn);
7073 	if (!pp)
7074 		return;
7075 
7076 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7077 		return;
7078 
7079 	/*
7080 	 * Handed a large kernel page, we dig up the root page since we
7081 	 * know the root page might have the lock also.
7082 	 */
7083 	if (pp->p_szc != 0) {
7084 		index = PP_MAPINDEX(pp);
7085 		cons = TTE8K;
7086 again:
7087 		while (index != 0) {
7088 			index >>= 1;
7089 			if (index != 0)
7090 				cons++;
7091 			if (index & 0x1) {
7092 				pp = PP_GROUPLEADER(pp, cons);
7093 				goto again;
7094 			}
7095 		}
7096 	}
7097 
7098 	if (PAGE_LOCKED(pp) || PP_ISNORELOC(pp))
7099 		return;
7100 
7101 	/*
7102 	 * Pages need to be locked or allocated "permanent" (either from
7103 	 * static_arena arena or explicitly setting PG_NORELOC when calling
7104 	 * page_create_va()) for VA->PA translations to be valid.
7105 	 */
7106 	if (!PP_ISNORELOC(pp))
7107 		panic("Illegal VA->PA translation, pp 0x%p not permanent", pp);
7108 	else
7109 		panic("Illegal VA->PA translation, pp 0x%p not locked", pp);
7110 }
7111 #endif	/* DEBUG */
7112 
7113 /*
7114  * Returns a page frame number for a given virtual address.
7115  * Returns PFN_INVALID to indicate an invalid mapping
7116  */
7117 pfn_t
7118 hat_getpfnum(struct hat *hat, caddr_t addr)
7119 {
7120 	pfn_t pfn;
7121 	tte_t tte;
7122 
7123 	/*
7124 	 * We would like to
7125 	 * ASSERT(AS_LOCK_HELD(as, &as->a_lock));
7126 	 * but we can't because the iommu driver will call this
7127 	 * routine at interrupt time and it can't grab the as lock
7128 	 * or it will deadlock: A thread could have the as lock
7129 	 * and be waiting for io.  The io can't complete
7130 	 * because the interrupt thread is blocked trying to grab
7131 	 * the as lock.
7132 	 */
7133 
7134 	ASSERT(hat->sfmmu_xhat_provider == NULL);
7135 
7136 	if (hat == ksfmmup) {
7137 		if (segkpm && IS_KPM_ADDR(addr))
7138 			return (sfmmu_kpm_vatopfn(addr));
7139 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7140 		    == PFN_SUSPENDED) {
7141 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7142 		}
7143 		sfmmu_check_kpfn(pfn);
7144 		return (pfn);
7145 	} else {
7146 		return (sfmmu_uvatopfn(addr, hat));
7147 	}
7148 }
7149 
7150 /*
7151  * hat_getkpfnum() is an obsolete DDI routine, and its use is discouraged.
7152  * Use hat_getpfnum(kas.a_hat, ...) instead.
7153  *
7154  * We'd like to return PFN_INVALID if the mappings have underlying page_t's
7155  * but can't right now due to the fact that some software has grown to use
7156  * this interface incorrectly. So for now when the interface is misused,
7157  * return a warning to the user that in the future it won't work in the
7158  * way they're abusing it, and carry on (after disabling page relocation).
7159  */
7160 pfn_t
7161 hat_getkpfnum(caddr_t addr)
7162 {
7163 	pfn_t pfn;
7164 	tte_t tte;
7165 	int badcaller = 0;
7166 	extern int segkmem_reloc;
7167 
7168 	if (segkpm && IS_KPM_ADDR(addr)) {
7169 		badcaller = 1;
7170 		pfn = sfmmu_kpm_vatopfn(addr);
7171 	} else {
7172 		while ((pfn = sfmmu_vatopfn(addr, ksfmmup, &tte))
7173 		    == PFN_SUSPENDED) {
7174 			sfmmu_vatopfn_suspended(addr, ksfmmup, &tte);
7175 		}
7176 		badcaller = pf_is_memory(pfn);
7177 	}
7178 
7179 	if (badcaller) {
7180 		/*
7181 		 * We can't return PFN_INVALID or the caller may panic
7182 		 * or corrupt the system.  The only alternative is to
7183 		 * disable page relocation at this point for all kernel
7184 		 * memory.  This will impact any callers of page_relocate()
7185 		 * such as FMA or DR.
7186 		 *
7187 		 * RFE: Add junk here to spit out an ereport so the sysadmin
7188 		 * can be advised that he should upgrade his device driver
7189 		 * so that this doesn't happen.
7190 		 */
7191 		hat_getkpfnum_badcall(caller());
7192 		if (hat_kpr_enabled && segkmem_reloc) {
7193 			hat_kpr_enabled = 0;
7194 			segkmem_reloc = 0;
7195 			cmn_err(CE_WARN, "Kernel Page Relocation is DISABLED");
7196 		}
7197 	}
7198 	return (pfn);
7199 }
7200 
7201 pfn_t
7202 sfmmu_uvatopfn(caddr_t vaddr, struct hat *sfmmup)
7203 {
7204 	struct hmehash_bucket *hmebp;
7205 	hmeblk_tag hblktag;
7206 	int hmeshift, hashno = 1;
7207 	struct hme_blk *hmeblkp = NULL;
7208 
7209 	struct sf_hment *sfhmep;
7210 	tte_t tte;
7211 	pfn_t pfn;
7212 
7213 	/* support for ISM */
7214 	ism_map_t	*ism_map;
7215 	ism_blk_t	*ism_blkp;
7216 	int		i;
7217 	sfmmu_t *ism_hatid = NULL;
7218 	sfmmu_t *locked_hatid = NULL;
7219 
7220 
7221 	ASSERT(sfmmup != ksfmmup);
7222 	SFMMU_STAT(sf_user_vtop);
7223 	/*
7224 	 * Set ism_hatid if vaddr falls in a ISM segment.
7225 	 */
7226 	ism_blkp = sfmmup->sfmmu_iblk;
7227 	if (ism_blkp) {
7228 		sfmmu_ismhat_enter(sfmmup, 0);
7229 		locked_hatid = sfmmup;
7230 	}
7231 	while (ism_blkp && ism_hatid == NULL) {
7232 		ism_map = ism_blkp->iblk_maps;
7233 		for (i = 0; ism_map[i].imap_ismhat && i < ISM_MAP_SLOTS; i++) {
7234 			if (vaddr >= ism_start(ism_map[i]) &&
7235 			    vaddr < ism_end(ism_map[i])) {
7236 				sfmmup = ism_hatid = ism_map[i].imap_ismhat;
7237 				vaddr = (caddr_t)(vaddr -
7238 					ism_start(ism_map[i]));
7239 				break;
7240 			}
7241 		}
7242 		ism_blkp = ism_blkp->iblk_next;
7243 	}
7244 	if (locked_hatid) {
7245 		sfmmu_ismhat_exit(locked_hatid, 0);
7246 	}
7247 
7248 	hblktag.htag_id = sfmmup;
7249 	do {
7250 		hmeshift = HME_HASH_SHIFT(hashno);
7251 		hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
7252 		hblktag.htag_rehash = hashno;
7253 		hmebp = HME_HASH_FUNCTION(sfmmup, vaddr, hmeshift);
7254 
7255 		SFMMU_HASH_LOCK(hmebp);
7256 
7257 		HME_HASH_FAST_SEARCH(hmebp, hblktag, hmeblkp);
7258 		if (hmeblkp != NULL) {
7259 			HBLKTOHME(sfhmep, hmeblkp, vaddr);
7260 			sfmmu_copytte(&sfhmep->hme_tte, &tte);
7261 			if (TTE_IS_VALID(&tte)) {
7262 				pfn = TTE_TO_PFN(vaddr, &tte);
7263 			} else {
7264 				pfn = PFN_INVALID;
7265 			}
7266 			SFMMU_HASH_UNLOCK(hmebp);
7267 			return (pfn);
7268 		}
7269 		SFMMU_HASH_UNLOCK(hmebp);
7270 		hashno++;
7271 	} while (HME_REHASH(sfmmup) && (hashno <= mmu_hashcnt));
7272 	return (PFN_INVALID);
7273 }
7274 
7275 
7276 /*
7277  * For compatability with AT&T and later optimizations
7278  */
7279 /* ARGSUSED */
7280 void
7281 hat_map(struct hat *hat, caddr_t addr, size_t len, uint_t flags)
7282 {
7283 	ASSERT(hat != NULL);
7284 	ASSERT(hat->sfmmu_xhat_provider == NULL);
7285 }
7286 
7287 /*
7288  * Return the number of mappings to a particular page.
7289  * This number is an approximation of the number of
7290  * number of people sharing the page.
7291  */
7292 ulong_t
7293 hat_page_getshare(page_t *pp)
7294 {
7295 	page_t *spp = pp;	/* start page */
7296 	kmutex_t *pml;
7297 	ulong_t	cnt;
7298 	int index, sz = TTE64K;
7299 
7300 	/*
7301 	 * We need to grab the mlist lock to make sure any outstanding
7302 	 * load/unloads complete.  Otherwise we could return zero
7303 	 * even though the unload(s) hasn't finished yet.
7304 	 */
7305 	pml = sfmmu_mlist_enter(spp);
7306 	cnt = spp->p_share;
7307 
7308 	if (kpm_enable)
7309 		cnt += spp->p_kpmref;
7310 
7311 	/*
7312 	 * If we have any large mappings, we count the number of
7313 	 * mappings that this large page is part of.
7314 	 */
7315 	index = PP_MAPINDEX(spp);
7316 	index >>= 1;
7317 	while (index) {
7318 		pp = PP_GROUPLEADER(spp, sz);
7319 		if ((index & 0x1) && pp != spp) {
7320 			cnt += pp->p_share;
7321 			spp = pp;
7322 		}
7323 		index >>= 1;
7324 		sz++;
7325 	}
7326 	sfmmu_mlist_exit(pml);
7327 	return (cnt);
7328 }
7329 
7330 /*
7331  * Unload all large mappings to the pp and reset the p_szc field of every
7332  * constituent page according to the remaining mappings.
7333  *
7334  * pp must be locked SE_EXCL. Even though no other constituent pages are
7335  * locked it's legal to unload the large mappings to the pp because all
7336  * constituent pages of large locked mappings have to be locked SE_SHARED.
7337  * This means if we have SE_EXCL lock on one of constituent pages none of the
7338  * large mappings to pp are locked.
7339  *
7340  * Decrease p_szc field starting from the last constituent page and ending
7341  * with the root page. This method is used because other threads rely on the
7342  * root's p_szc to find the lock to syncronize on. After a root page_t's p_szc
7343  * is demoted then other threads will succeed in sfmmu_mlspl_enter(). This
7344  * ensures that p_szc changes of the constituent pages appears atomic for all
7345  * threads that use sfmmu_mlspl_enter() to examine p_szc field.
7346  *
7347  * This mechanism is only used for file system pages where it's not always
7348  * possible to get SE_EXCL locks on all constituent pages to demote the size
7349  * code (as is done for anonymous or kernel large pages).
7350  *
7351  * See more comments in front of sfmmu_mlspl_enter().
7352  */
7353 void
7354 hat_page_demote(page_t *pp)
7355 {
7356 	int index;
7357 	int sz;
7358 	cpuset_t cpuset;
7359 	int sync = 0;
7360 	page_t *rootpp;
7361 	struct sf_hment *sfhme;
7362 	struct sf_hment *tmphme = NULL;
7363 	struct hme_blk *hmeblkp;
7364 	uint_t pszc;
7365 	page_t *lastpp;
7366 	cpuset_t tset;
7367 	pgcnt_t npgs;
7368 	kmutex_t *pml;
7369 	kmutex_t *pmtx = NULL;
7370 
7371 	ASSERT(PAGE_EXCL(pp));
7372 	ASSERT(!PP_ISFREE(pp));
7373 	ASSERT(page_szc_lock_assert(pp));
7374 	pml = sfmmu_mlist_enter(pp);
7375 
7376 	pszc = pp->p_szc;
7377 	if (pszc == 0) {
7378 		goto out;
7379 	}
7380 
7381 	index = PP_MAPINDEX(pp) >> 1;
7382 
7383 	if (index) {
7384 		CPUSET_ZERO(cpuset);
7385 		sz = TTE64K;
7386 		sync = 1;
7387 	}
7388 
7389 	while (index) {
7390 		if (!(index & 0x1)) {
7391 			index >>= 1;
7392 			sz++;
7393 			continue;
7394 		}
7395 		ASSERT(sz <= pszc);
7396 		rootpp = PP_GROUPLEADER(pp, sz);
7397 		for (sfhme = rootpp->p_mapping; sfhme; sfhme = tmphme) {
7398 			tmphme = sfhme->hme_next;
7399 			hmeblkp = sfmmu_hmetohblk(sfhme);
7400 			if (hme_size(sfhme) != sz) {
7401 				continue;
7402 			}
7403 			if (hmeblkp->hblk_xhat_bit) {
7404 				cmn_err(CE_PANIC,
7405 				    "hat_page_demote: xhat hmeblk");
7406 			}
7407 			tset = sfmmu_pageunload(rootpp, sfhme, sz);
7408 			CPUSET_OR(cpuset, tset);
7409 		}
7410 		if (index >>= 1) {
7411 			sz++;
7412 		}
7413 	}
7414 
7415 	ASSERT(!PP_ISMAPPED_LARGE(pp));
7416 
7417 	if (sync) {
7418 		xt_sync(cpuset);
7419 #ifdef VAC
7420 		if (PP_ISTNC(pp)) {
7421 			conv_tnc(rootpp, sz);
7422 		}
7423 #endif	/* VAC */
7424 	}
7425 
7426 	pmtx = sfmmu_page_enter(pp);
7427 
7428 	ASSERT(pp->p_szc == pszc);
7429 	rootpp = PP_PAGEROOT(pp);
7430 	ASSERT(rootpp->p_szc == pszc);
7431 	lastpp = PP_PAGENEXT_N(rootpp, TTEPAGES(pszc) - 1);
7432 
7433 	while (lastpp != rootpp) {
7434 		sz = PP_MAPINDEX(lastpp) ? fnd_mapping_sz(lastpp) : 0;
7435 		ASSERT(sz < pszc);
7436 		npgs = (sz == 0) ? 1 : TTEPAGES(sz);
7437 		ASSERT(P2PHASE(lastpp->p_pagenum, npgs) == npgs - 1);
7438 		while (--npgs > 0) {
7439 			lastpp->p_szc = (uchar_t)sz;
7440 			lastpp = PP_PAGEPREV(lastpp);
7441 		}
7442 		if (sz) {
7443 			/*
7444 			 * make sure before current root's pszc
7445 			 * is updated all updates to constituent pages pszc
7446 			 * fields are globally visible.
7447 			 */
7448 			membar_producer();
7449 		}
7450 		lastpp->p_szc = sz;
7451 		ASSERT(IS_P2ALIGNED(lastpp->p_pagenum, TTEPAGES(sz)));
7452 		if (lastpp != rootpp) {
7453 			lastpp = PP_PAGEPREV(lastpp);
7454 		}
7455 	}
7456 	if (sz == 0) {
7457 		/* the loop above doesn't cover this case */
7458 		rootpp->p_szc = 0;
7459 	}
7460 out:
7461 	ASSERT(pp->p_szc == 0);
7462 	if (pmtx != NULL) {
7463 		sfmmu_page_exit(pmtx);
7464 	}
7465 	sfmmu_mlist_exit(pml);
7466 }
7467 
7468 /*
7469  * Refresh the HAT ismttecnt[] element for size szc.
7470  * Caller must have set ISM busy flag to prevent mapping
7471  * lists from changing while we're traversing them.
7472  */
7473 pgcnt_t
7474 ism_tsb_entries(sfmmu_t *sfmmup, int szc)
7475 {
7476 	ism_blk_t	*ism_blkp = sfmmup->sfmmu_iblk;
7477 	ism_map_t	*ism_map;
7478 	pgcnt_t		npgs = 0;
7479 	int		j;
7480 
7481 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
7482 	for (; ism_blkp != NULL; ism_blkp = ism_blkp->iblk_next) {
7483 		ism_map = ism_blkp->iblk_maps;
7484 		for (j = 0; ism_map[j].imap_ismhat && j < ISM_MAP_SLOTS; j++)
7485 			npgs += ism_map[j].imap_ismhat->sfmmu_ttecnt[szc];
7486 	}
7487 	sfmmup->sfmmu_ismttecnt[szc] = npgs;
7488 	return (npgs);
7489 }
7490 
7491 /*
7492  * Yield the memory claim requirement for an address space.
7493  *
7494  * This is currently implemented as the number of bytes that have active
7495  * hardware translations that have page structures.  Therefore, it can
7496  * underestimate the traditional resident set size, eg, if the
7497  * physical page is present and the hardware translation is missing;
7498  * and it can overestimate the rss, eg, if there are active
7499  * translations to a frame buffer with page structs.
7500  * Also, it does not take sharing into account.
7501  *
7502  * Note that we don't acquire locks here since this function is most often
7503  * called from the clock thread.
7504  */
7505 size_t
7506 hat_get_mapped_size(struct hat *hat)
7507 {
7508 	size_t		assize = 0;
7509 	int 		i;
7510 
7511 	if (hat == NULL)
7512 		return (0);
7513 
7514 	ASSERT(hat->sfmmu_xhat_provider == NULL);
7515 
7516 	for (i = 0; i < mmu_page_sizes; i++)
7517 		assize += (pgcnt_t)hat->sfmmu_ttecnt[i] * TTEBYTES(i);
7518 
7519 	if (hat->sfmmu_iblk == NULL)
7520 		return (assize);
7521 
7522 	for (i = 0; i < mmu_page_sizes; i++)
7523 		assize += (pgcnt_t)hat->sfmmu_ismttecnt[i] * TTEBYTES(i);
7524 
7525 	return (assize);
7526 }
7527 
7528 int
7529 hat_stats_enable(struct hat *hat)
7530 {
7531 	hatlock_t	*hatlockp;
7532 
7533 	ASSERT(hat->sfmmu_xhat_provider == NULL);
7534 
7535 	hatlockp = sfmmu_hat_enter(hat);
7536 	hat->sfmmu_rmstat++;
7537 	sfmmu_hat_exit(hatlockp);
7538 	return (1);
7539 }
7540 
7541 void
7542 hat_stats_disable(struct hat *hat)
7543 {
7544 	hatlock_t	*hatlockp;
7545 
7546 	ASSERT(hat->sfmmu_xhat_provider == NULL);
7547 
7548 	hatlockp = sfmmu_hat_enter(hat);
7549 	hat->sfmmu_rmstat--;
7550 	sfmmu_hat_exit(hatlockp);
7551 }
7552 
7553 /*
7554  * Routines for entering or removing  ourselves from the
7555  * ism_hat's mapping list.
7556  */
7557 static void
7558 iment_add(struct ism_ment *iment,  struct hat *ism_hat)
7559 {
7560 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
7561 
7562 	iment->iment_prev = NULL;
7563 	iment->iment_next = ism_hat->sfmmu_iment;
7564 	if (ism_hat->sfmmu_iment) {
7565 		ism_hat->sfmmu_iment->iment_prev = iment;
7566 	}
7567 	ism_hat->sfmmu_iment = iment;
7568 }
7569 
7570 static void
7571 iment_sub(struct ism_ment *iment, struct hat *ism_hat)
7572 {
7573 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
7574 
7575 	if (ism_hat->sfmmu_iment == NULL) {
7576 		panic("ism map entry remove - no entries");
7577 	}
7578 
7579 	if (iment->iment_prev) {
7580 		ASSERT(ism_hat->sfmmu_iment != iment);
7581 		iment->iment_prev->iment_next = iment->iment_next;
7582 	} else {
7583 		ASSERT(ism_hat->sfmmu_iment == iment);
7584 		ism_hat->sfmmu_iment = iment->iment_next;
7585 	}
7586 
7587 	if (iment->iment_next) {
7588 		iment->iment_next->iment_prev = iment->iment_prev;
7589 	}
7590 
7591 	/*
7592 	 * zero out the entry
7593 	 */
7594 	iment->iment_next = NULL;
7595 	iment->iment_prev = NULL;
7596 	iment->iment_hat =  NULL;
7597 }
7598 
7599 /*
7600  * Hat_share()/unshare() return an (non-zero) error
7601  * when saddr and daddr are not properly aligned.
7602  *
7603  * The top level mapping element determines the alignment
7604  * requirement for saddr and daddr, depending on different
7605  * architectures.
7606  *
7607  * When hat_share()/unshare() are not supported,
7608  * HATOP_SHARE()/UNSHARE() return 0
7609  */
7610 int
7611 hat_share(struct hat *sfmmup, caddr_t addr,
7612 	struct hat *ism_hatid, caddr_t sptaddr, size_t len, uint_t ismszc)
7613 {
7614 	ism_blk_t	*ism_blkp;
7615 	ism_blk_t	*new_iblk;
7616 	ism_map_t 	*ism_map;
7617 	ism_ment_t	*ism_ment;
7618 	int		i, added;
7619 	hatlock_t	*hatlockp;
7620 	int		reload_mmu = 0;
7621 	uint_t		ismshift = page_get_shift(ismszc);
7622 	size_t		ismpgsz = page_get_pagesize(ismszc);
7623 	uint_t		ismmask = (uint_t)ismpgsz - 1;
7624 	size_t		sh_size = ISM_SHIFT(ismshift, len);
7625 	ushort_t	ismhatflag;
7626 
7627 #ifdef DEBUG
7628 	caddr_t		eaddr = addr + len;
7629 #endif /* DEBUG */
7630 
7631 	ASSERT(ism_hatid != NULL && sfmmup != NULL);
7632 	ASSERT(sptaddr == ISMID_STARTADDR);
7633 	/*
7634 	 * Check the alignment.
7635 	 */
7636 	if (!ISM_ALIGNED(ismshift, addr) || !ISM_ALIGNED(ismshift, sptaddr))
7637 		return (EINVAL);
7638 
7639 	/*
7640 	 * Check size alignment.
7641 	 */
7642 	if (!ISM_ALIGNED(ismshift, len))
7643 		return (EINVAL);
7644 
7645 	ASSERT(sfmmup->sfmmu_xhat_provider == NULL);
7646 
7647 	/*
7648 	 * Allocate ism_ment for the ism_hat's mapping list, and an
7649 	 * ism map blk in case we need one.  We must do our
7650 	 * allocations before acquiring locks to prevent a deadlock
7651 	 * in the kmem allocator on the mapping list lock.
7652 	 */
7653 	new_iblk = kmem_cache_alloc(ism_blk_cache, KM_SLEEP);
7654 	ism_ment = kmem_cache_alloc(ism_ment_cache, KM_SLEEP);
7655 
7656 	/*
7657 	 * Serialize ISM mappings with the ISM busy flag, and also the
7658 	 * trap handlers.
7659 	 */
7660 	sfmmu_ismhat_enter(sfmmup, 0);
7661 
7662 	/*
7663 	 * Allocate an ism map blk if necessary.
7664 	 */
7665 	if (sfmmup->sfmmu_iblk == NULL) {
7666 		sfmmup->sfmmu_iblk = new_iblk;
7667 		bzero(new_iblk, sizeof (*new_iblk));
7668 		new_iblk->iblk_nextpa = (uint64_t)-1;
7669 		membar_stst();	/* make sure next ptr visible to all CPUs */
7670 		sfmmup->sfmmu_ismblkpa = va_to_pa((caddr_t)new_iblk);
7671 		reload_mmu = 1;
7672 		new_iblk = NULL;
7673 	}
7674 
7675 #ifdef DEBUG
7676 	/*
7677 	 * Make sure mapping does not already exist.
7678 	 */
7679 	ism_blkp = sfmmup->sfmmu_iblk;
7680 	while (ism_blkp) {
7681 		ism_map = ism_blkp->iblk_maps;
7682 		for (i = 0; i < ISM_MAP_SLOTS && ism_map[i].imap_ismhat; i++) {
7683 			if ((addr >= ism_start(ism_map[i]) &&
7684 			    addr < ism_end(ism_map[i])) ||
7685 			    eaddr > ism_start(ism_map[i]) &&
7686 			    eaddr <= ism_end(ism_map[i])) {
7687 				panic("sfmmu_share: Already mapped!");
7688 			}
7689 		}
7690 		ism_blkp = ism_blkp->iblk_next;
7691 	}
7692 #endif /* DEBUG */
7693 
7694 	ASSERT(ismszc >= TTE4M);
7695 	if (ismszc == TTE4M) {
7696 		ismhatflag = HAT_4M_FLAG;
7697 	} else if (ismszc == TTE32M) {
7698 		ismhatflag = HAT_32M_FLAG;
7699 	} else if (ismszc == TTE256M) {
7700 		ismhatflag = HAT_256M_FLAG;
7701 	}
7702 	/*
7703 	 * Add mapping to first available mapping slot.
7704 	 */
7705 	ism_blkp = sfmmup->sfmmu_iblk;
7706 	added = 0;
7707 	while (!added) {
7708 		ism_map = ism_blkp->iblk_maps;
7709 		for (i = 0; i < ISM_MAP_SLOTS; i++)  {
7710 			if (ism_map[i].imap_ismhat == NULL) {
7711 
7712 				ism_map[i].imap_ismhat = ism_hatid;
7713 				ism_map[i].imap_vb_shift = (ushort_t)ismshift;
7714 				ism_map[i].imap_hatflags = ismhatflag;
7715 				ism_map[i].imap_sz_mask = ismmask;
7716 				/*
7717 				 * imap_seg is checked in ISM_CHECK to see if
7718 				 * non-NULL, then other info assumed valid.
7719 				 */
7720 				membar_stst();
7721 				ism_map[i].imap_seg = (uintptr_t)addr | sh_size;
7722 				ism_map[i].imap_ment = ism_ment;
7723 
7724 				/*
7725 				 * Now add ourselves to the ism_hat's
7726 				 * mapping list.
7727 				 */
7728 				ism_ment->iment_hat = sfmmup;
7729 				ism_ment->iment_base_va = addr;
7730 				ism_hatid->sfmmu_ismhat = 1;
7731 				ism_hatid->sfmmu_flags = 0;
7732 				mutex_enter(&ism_mlist_lock);
7733 				iment_add(ism_ment, ism_hatid);
7734 				mutex_exit(&ism_mlist_lock);
7735 				added = 1;
7736 				break;
7737 			}
7738 		}
7739 		if (!added && ism_blkp->iblk_next == NULL) {
7740 			ism_blkp->iblk_next = new_iblk;
7741 			new_iblk = NULL;
7742 			bzero(ism_blkp->iblk_next,
7743 			    sizeof (*ism_blkp->iblk_next));
7744 			ism_blkp->iblk_next->iblk_nextpa = (uint64_t)-1;
7745 			membar_stst();
7746 			ism_blkp->iblk_nextpa =
7747 				va_to_pa((caddr_t)ism_blkp->iblk_next);
7748 		}
7749 		ism_blkp = ism_blkp->iblk_next;
7750 	}
7751 
7752 	/*
7753 	 * Update our counters for this sfmmup's ism mappings.
7754 	 */
7755 	for (i = 0; i <= ismszc; i++) {
7756 		if (!(disable_ism_large_pages & (1 << i)))
7757 			(void) ism_tsb_entries(sfmmup, i);
7758 	}
7759 
7760 	hatlockp = sfmmu_hat_enter(sfmmup);
7761 
7762 	/*
7763 	 * For ISM and DISM we do not support 512K pages, so we only
7764 	 * only search the 4M and 8K/64K hashes for 4 pagesize cpus, and search
7765 	 * the 256M or 32M, and 4M and 8K/64K hashes for 6 pagesize cpus.
7766 	 */
7767 	ASSERT((disable_ism_large_pages & (1 << TTE512K)) != 0);
7768 
7769 	if (ismszc > TTE4M && !SFMMU_FLAGS_ISSET(sfmmup, HAT_4M_FLAG))
7770 		SFMMU_FLAGS_SET(sfmmup, HAT_4M_FLAG);
7771 
7772 	if (!SFMMU_FLAGS_ISSET(sfmmup, HAT_64K_FLAG))
7773 		SFMMU_FLAGS_SET(sfmmup, HAT_64K_FLAG);
7774 
7775 	/*
7776 	 * If we updated the ismblkpa for this HAT or we need
7777 	 * to start searching the 256M or 32M or 4M hash, we must
7778 	 * make sure all CPUs running this process reload their
7779 	 * tsbmiss area.  Otherwise they will fail to load the mappings
7780 	 * in the tsbmiss handler and will loop calling pagefault().
7781 	 */
7782 	switch (ismszc) {
7783 	case TTE256M:
7784 		if (reload_mmu || !SFMMU_FLAGS_ISSET(sfmmup, HAT_256M_FLAG)) {
7785 			SFMMU_FLAGS_SET(sfmmup, HAT_256M_FLAG);
7786 			sfmmu_sync_mmustate(sfmmup);
7787 		}
7788 		break;
7789 	case TTE32M:
7790 		if (reload_mmu || !SFMMU_FLAGS_ISSET(sfmmup, HAT_32M_FLAG)) {
7791 			SFMMU_FLAGS_SET(sfmmup, HAT_32M_FLAG);
7792 			sfmmu_sync_mmustate(sfmmup);
7793 		}
7794 		break;
7795 	case TTE4M:
7796 		if (reload_mmu || !SFMMU_FLAGS_ISSET(sfmmup, HAT_4M_FLAG)) {
7797 			SFMMU_FLAGS_SET(sfmmup, HAT_4M_FLAG);
7798 			sfmmu_sync_mmustate(sfmmup);
7799 		}
7800 		break;
7801 	default:
7802 		break;
7803 	}
7804 
7805 	/*
7806 	 * Now we can drop the locks.
7807 	 */
7808 	sfmmu_ismhat_exit(sfmmup, 1);
7809 	sfmmu_hat_exit(hatlockp);
7810 
7811 	/*
7812 	 * Free up ismblk if we didn't use it.
7813 	 */
7814 	if (new_iblk != NULL)
7815 		kmem_cache_free(ism_blk_cache, new_iblk);
7816 
7817 	/*
7818 	 * Check TSB and TLB page sizes.
7819 	 */
7820 	sfmmu_check_page_sizes(sfmmup, 1);
7821 
7822 	return (0);
7823 }
7824 
7825 /*
7826  * hat_unshare removes exactly one ism_map from
7827  * this process's as.  It expects multiple calls
7828  * to hat_unshare for multiple shm segments.
7829  */
7830 void
7831 hat_unshare(struct hat *sfmmup, caddr_t addr, size_t len, uint_t ismszc)
7832 {
7833 	ism_map_t 	*ism_map;
7834 	ism_ment_t	*free_ment = NULL;
7835 	ism_blk_t	*ism_blkp;
7836 	struct hat	*ism_hatid;
7837 	int 		found, i;
7838 	hatlock_t	*hatlockp;
7839 	struct tsb_info	*tsbinfo;
7840 	uint_t		ismshift = page_get_shift(ismszc);
7841 	size_t		sh_size = ISM_SHIFT(ismshift, len);
7842 
7843 	ASSERT(ISM_ALIGNED(ismshift, addr));
7844 	ASSERT(ISM_ALIGNED(ismshift, len));
7845 	ASSERT(sfmmup != NULL);
7846 	ASSERT(sfmmup != ksfmmup);
7847 
7848 	if (sfmmup->sfmmu_xhat_provider) {
7849 		XHAT_UNSHARE(sfmmup, addr, len);
7850 		return;
7851 	} else {
7852 		/*
7853 		 * This must be a CPU HAT. If the address space has
7854 		 * XHATs attached, inform all XHATs that ISM segment
7855 		 * is going away
7856 		 */
7857 		ASSERT(sfmmup->sfmmu_as != NULL);
7858 		if (sfmmup->sfmmu_as->a_xhat != NULL)
7859 			xhat_unshare_all(sfmmup->sfmmu_as, addr, len);
7860 	}
7861 
7862 	/*
7863 	 * Make sure that during the entire time ISM mappings are removed,
7864 	 * the trap handlers serialize behind us, and that no one else
7865 	 * can be mucking with ISM mappings.  This also lets us get away
7866 	 * with not doing expensive cross calls to flush the TLB -- we
7867 	 * just discard the context, flush the entire TSB, and call it
7868 	 * a day.
7869 	 */
7870 	sfmmu_ismhat_enter(sfmmup, 0);
7871 
7872 	/*
7873 	 * Remove the mapping.
7874 	 *
7875 	 * We can't have any holes in the ism map.
7876 	 * The tsb miss code while searching the ism map will
7877 	 * stop on an empty map slot.  So we must move
7878 	 * everyone past the hole up 1 if any.
7879 	 *
7880 	 * Also empty ism map blks are not freed until the
7881 	 * process exits. This is to prevent a MT race condition
7882 	 * between sfmmu_unshare() and sfmmu_tsbmiss_exception().
7883 	 */
7884 	found = 0;
7885 	ism_blkp = sfmmup->sfmmu_iblk;
7886 	while (!found && ism_blkp) {
7887 		ism_map = ism_blkp->iblk_maps;
7888 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
7889 			if (addr == ism_start(ism_map[i]) &&
7890 			    sh_size == (size_t)(ism_size(ism_map[i]))) {
7891 				found = 1;
7892 				break;
7893 			}
7894 		}
7895 		if (!found)
7896 			ism_blkp = ism_blkp->iblk_next;
7897 	}
7898 
7899 	if (found) {
7900 		ism_hatid = ism_map[i].imap_ismhat;
7901 		ASSERT(ism_hatid != NULL);
7902 		ASSERT(ism_hatid->sfmmu_ismhat == 1);
7903 
7904 		/*
7905 		 * First remove ourselves from the ism mapping list.
7906 		 */
7907 		mutex_enter(&ism_mlist_lock);
7908 		iment_sub(ism_map[i].imap_ment, ism_hatid);
7909 		mutex_exit(&ism_mlist_lock);
7910 		free_ment = ism_map[i].imap_ment;
7911 
7912 		/*
7913 		 * Now gurantee that any other cpu
7914 		 * that tries to process an ISM miss
7915 		 * will go to tl=0.
7916 		 */
7917 		hatlockp = sfmmu_hat_enter(sfmmup);
7918 
7919 		sfmmu_invalidate_ctx(sfmmup);
7920 
7921 		sfmmu_hat_exit(hatlockp);
7922 
7923 		/*
7924 		 * We delete the ism map by copying
7925 		 * the next map over the current one.
7926 		 * We will take the next one in the maps
7927 		 * array or from the next ism_blk.
7928 		 */
7929 		while (ism_blkp) {
7930 			ism_map = ism_blkp->iblk_maps;
7931 			while (i < (ISM_MAP_SLOTS - 1)) {
7932 				ism_map[i] = ism_map[i + 1];
7933 				i++;
7934 			}
7935 			/* i == (ISM_MAP_SLOTS - 1) */
7936 			ism_blkp = ism_blkp->iblk_next;
7937 			if (ism_blkp) {
7938 				ism_map[i] = ism_blkp->iblk_maps[0];
7939 				i = 0;
7940 			} else {
7941 				ism_map[i].imap_seg = 0;
7942 				ism_map[i].imap_vb_shift = 0;
7943 				ism_map[i].imap_hatflags = 0;
7944 				ism_map[i].imap_sz_mask = 0;
7945 				ism_map[i].imap_ismhat = NULL;
7946 				ism_map[i].imap_ment = NULL;
7947 			}
7948 		}
7949 
7950 		/*
7951 		 * Now flush entire TSB for the process, since
7952 		 * demapping page by page can be too expensive.
7953 		 * We don't have to flush the TLB here anymore
7954 		 * since we switch to a new TLB ctx instead.
7955 		 * Also, there is no need to flush if the process
7956 		 * is exiting since the TSB will be freed later.
7957 		 */
7958 		if (!sfmmup->sfmmu_free) {
7959 			hatlockp = sfmmu_hat_enter(sfmmup);
7960 			for (tsbinfo = sfmmup->sfmmu_tsb; tsbinfo != NULL;
7961 			    tsbinfo = tsbinfo->tsb_next) {
7962 				if (tsbinfo->tsb_flags & TSB_SWAPPED)
7963 					continue;
7964 				sfmmu_inv_tsb(tsbinfo->tsb_va,
7965 				    TSB_BYTES(tsbinfo->tsb_szc));
7966 			}
7967 			sfmmu_hat_exit(hatlockp);
7968 		}
7969 	}
7970 
7971 	/*
7972 	 * Update our counters for this sfmmup's ism mappings.
7973 	 */
7974 	for (i = 0; i <= ismszc; i++) {
7975 		if (!(disable_ism_large_pages & (1 << i)))
7976 			(void) ism_tsb_entries(sfmmup, i);
7977 	}
7978 
7979 	sfmmu_ismhat_exit(sfmmup, 0);
7980 
7981 	/*
7982 	 * We must do our freeing here after dropping locks
7983 	 * to prevent a deadlock in the kmem allocator on the
7984 	 * mapping list lock.
7985 	 */
7986 	if (free_ment != NULL)
7987 		kmem_cache_free(ism_ment_cache, free_ment);
7988 
7989 	/*
7990 	 * Check TSB and TLB page sizes if the process isn't exiting.
7991 	 */
7992 	if (!sfmmup->sfmmu_free)
7993 		sfmmu_check_page_sizes(sfmmup, 0);
7994 }
7995 
7996 /* ARGSUSED */
7997 static int
7998 sfmmu_idcache_constructor(void *buf, void *cdrarg, int kmflags)
7999 {
8000 	/* void *buf is sfmmu_t pointer */
8001 	return (0);
8002 }
8003 
8004 /* ARGSUSED */
8005 static void
8006 sfmmu_idcache_destructor(void *buf, void *cdrarg)
8007 {
8008 	/* void *buf is sfmmu_t pointer */
8009 }
8010 
8011 /*
8012  * setup kmem hmeblks by bzeroing all members and initializing the nextpa
8013  * field to be the pa of this hmeblk
8014  */
8015 /* ARGSUSED */
8016 static int
8017 sfmmu_hblkcache_constructor(void *buf, void *cdrarg, int kmflags)
8018 {
8019 	struct hme_blk *hmeblkp;
8020 
8021 	bzero(buf, (size_t)cdrarg);
8022 	hmeblkp = (struct hme_blk *)buf;
8023 	hmeblkp->hblk_nextpa = va_to_pa((caddr_t)hmeblkp);
8024 
8025 #ifdef	HBLK_TRACE
8026 	mutex_init(&hmeblkp->hblk_audit_lock, NULL, MUTEX_DEFAULT, NULL);
8027 #endif	/* HBLK_TRACE */
8028 
8029 	return (0);
8030 }
8031 
8032 /* ARGSUSED */
8033 static void
8034 sfmmu_hblkcache_destructor(void *buf, void *cdrarg)
8035 {
8036 
8037 #ifdef	HBLK_TRACE
8038 
8039 	struct hme_blk *hmeblkp;
8040 
8041 	hmeblkp = (struct hme_blk *)buf;
8042 	mutex_destroy(&hmeblkp->hblk_audit_lock);
8043 
8044 #endif	/* HBLK_TRACE */
8045 }
8046 
8047 #define	SFMMU_CACHE_RECLAIM_SCAN_RATIO 8
8048 static int sfmmu_cache_reclaim_scan_ratio = SFMMU_CACHE_RECLAIM_SCAN_RATIO;
8049 /*
8050  * The kmem allocator will callback into our reclaim routine when the system
8051  * is running low in memory.  We traverse the hash and free up all unused but
8052  * still cached hme_blks.  We also traverse the free list and free them up
8053  * as well.
8054  */
8055 /*ARGSUSED*/
8056 static void
8057 sfmmu_hblkcache_reclaim(void *cdrarg)
8058 {
8059 	int i;
8060 	uint64_t hblkpa, prevpa, nx_pa;
8061 	struct hmehash_bucket *hmebp;
8062 	struct hme_blk *hmeblkp, *nx_hblk, *pr_hblk = NULL;
8063 	static struct hmehash_bucket *uhmehash_reclaim_hand;
8064 	static struct hmehash_bucket *khmehash_reclaim_hand;
8065 	struct hme_blk *list = NULL;
8066 
8067 	hmebp = uhmehash_reclaim_hand;
8068 	if (hmebp == NULL || hmebp > &uhme_hash[UHMEHASH_SZ])
8069 		uhmehash_reclaim_hand = hmebp = uhme_hash;
8070 	uhmehash_reclaim_hand += UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
8071 
8072 	for (i = UHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
8073 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
8074 			hmeblkp = hmebp->hmeblkp;
8075 			hblkpa = hmebp->hmeh_nextpa;
8076 			prevpa = 0;
8077 			pr_hblk = NULL;
8078 			while (hmeblkp) {
8079 				nx_hblk = hmeblkp->hblk_next;
8080 				nx_pa = hmeblkp->hblk_nextpa;
8081 				if (!hmeblkp->hblk_vcnt &&
8082 				    !hmeblkp->hblk_hmecnt) {
8083 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
8084 						prevpa, pr_hblk);
8085 					sfmmu_hblk_free(hmebp, hmeblkp,
8086 					    hblkpa, &list);
8087 				} else {
8088 					pr_hblk = hmeblkp;
8089 					prevpa = hblkpa;
8090 				}
8091 				hmeblkp = nx_hblk;
8092 				hblkpa = nx_pa;
8093 			}
8094 			SFMMU_HASH_UNLOCK(hmebp);
8095 		}
8096 		if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
8097 			hmebp = uhme_hash;
8098 	}
8099 
8100 	hmebp = khmehash_reclaim_hand;
8101 	if (hmebp == NULL || hmebp > &khme_hash[KHMEHASH_SZ])
8102 		khmehash_reclaim_hand = hmebp = khme_hash;
8103 	khmehash_reclaim_hand += KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio;
8104 
8105 	for (i = KHMEHASH_SZ / sfmmu_cache_reclaim_scan_ratio; i; i--) {
8106 		if (SFMMU_HASH_LOCK_TRYENTER(hmebp) != 0) {
8107 			hmeblkp = hmebp->hmeblkp;
8108 			hblkpa = hmebp->hmeh_nextpa;
8109 			prevpa = 0;
8110 			pr_hblk = NULL;
8111 			while (hmeblkp) {
8112 				nx_hblk = hmeblkp->hblk_next;
8113 				nx_pa = hmeblkp->hblk_nextpa;
8114 				if (!hmeblkp->hblk_vcnt &&
8115 				    !hmeblkp->hblk_hmecnt) {
8116 					sfmmu_hblk_hash_rm(hmebp, hmeblkp,
8117 						prevpa, pr_hblk);
8118 					sfmmu_hblk_free(hmebp, hmeblkp,
8119 					    hblkpa, &list);
8120 				} else {
8121 					pr_hblk = hmeblkp;
8122 					prevpa = hblkpa;
8123 				}
8124 				hmeblkp = nx_hblk;
8125 				hblkpa = nx_pa;
8126 			}
8127 			SFMMU_HASH_UNLOCK(hmebp);
8128 		}
8129 		if (hmebp++ == &khme_hash[KHMEHASH_SZ])
8130 			hmebp = khme_hash;
8131 	}
8132 	sfmmu_hblks_list_purge(&list);
8133 }
8134 
8135 /*
8136  * sfmmu_get_ppvcolor should become a vm_machdep or hatop interface.
8137  * same goes for sfmmu_get_addrvcolor().
8138  *
8139  * This function will return the virtual color for the specified page. The
8140  * virtual color corresponds to this page current mapping or its last mapping.
8141  * It is used by memory allocators to choose addresses with the correct
8142  * alignment so vac consistency is automatically maintained.  If the page
8143  * has no color it returns -1.
8144  */
8145 /*ARGSUSED*/
8146 int
8147 sfmmu_get_ppvcolor(struct page *pp)
8148 {
8149 #ifdef VAC
8150 	int color;
8151 
8152 	if (!(cache & CACHE_VAC) || PP_NEWPAGE(pp)) {
8153 		return (-1);
8154 	}
8155 	color = PP_GET_VCOLOR(pp);
8156 	ASSERT(color < mmu_btop(shm_alignment));
8157 	return (color);
8158 #else
8159 	return (-1);
8160 #endif	/* VAC */
8161 }
8162 
8163 /*
8164  * This function will return the desired alignment for vac consistency
8165  * (vac color) given a virtual address.  If no vac is present it returns -1.
8166  */
8167 /*ARGSUSED*/
8168 int
8169 sfmmu_get_addrvcolor(caddr_t vaddr)
8170 {
8171 #ifdef VAC
8172 	if (cache & CACHE_VAC) {
8173 		return (addr_to_vcolor(vaddr));
8174 	} else {
8175 		return (-1);
8176 	}
8177 #else
8178 	return (-1);
8179 #endif	/* VAC */
8180 }
8181 
8182 #ifdef VAC
8183 /*
8184  * Check for conflicts.
8185  * A conflict exists if the new and existent mappings do not match in
8186  * their "shm_alignment fields. If conflicts exist, the existant mappings
8187  * are flushed unless one of them is locked. If one of them is locked, then
8188  * the mappings are flushed and converted to non-cacheable mappings.
8189  */
8190 static void
8191 sfmmu_vac_conflict(struct hat *hat, caddr_t addr, page_t *pp)
8192 {
8193 	struct hat *tmphat;
8194 	struct sf_hment *sfhmep, *tmphme = NULL;
8195 	struct hme_blk *hmeblkp;
8196 	int vcolor;
8197 	tte_t tte;
8198 
8199 	ASSERT(sfmmu_mlist_held(pp));
8200 	ASSERT(!PP_ISNC(pp));		/* page better be cacheable */
8201 
8202 	vcolor = addr_to_vcolor(addr);
8203 	if (PP_NEWPAGE(pp)) {
8204 		PP_SET_VCOLOR(pp, vcolor);
8205 		return;
8206 	}
8207 
8208 	if (PP_GET_VCOLOR(pp) == vcolor) {
8209 		return;
8210 	}
8211 
8212 	if (!PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp)) {
8213 		/*
8214 		 * Previous user of page had a different color
8215 		 * but since there are no current users
8216 		 * we just flush the cache and change the color.
8217 		 */
8218 		SFMMU_STAT(sf_pgcolor_conflict);
8219 		sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
8220 		PP_SET_VCOLOR(pp, vcolor);
8221 		return;
8222 	}
8223 
8224 	/*
8225 	 * If we get here we have a vac conflict with a current
8226 	 * mapping.  VAC conflict policy is as follows.
8227 	 * - The default is to unload the other mappings unless:
8228 	 * - If we have a large mapping we uncache the page.
8229 	 * We need to uncache the rest of the large page too.
8230 	 * - If any of the mappings are locked we uncache the page.
8231 	 * - If the requested mapping is inconsistent
8232 	 * with another mapping and that mapping
8233 	 * is in the same address space we have to
8234 	 * make it non-cached.  The default thing
8235 	 * to do is unload the inconsistent mapping
8236 	 * but if they are in the same address space
8237 	 * we run the risk of unmapping the pc or the
8238 	 * stack which we will use as we return to the user,
8239 	 * in which case we can then fault on the thing
8240 	 * we just unloaded and get into an infinite loop.
8241 	 */
8242 	if (PP_ISMAPPED_LARGE(pp)) {
8243 		int sz;
8244 
8245 		/*
8246 		 * Existing mapping is for big pages. We don't unload
8247 		 * existing big mappings to satisfy new mappings.
8248 		 * Always convert all mappings to TNC.
8249 		 */
8250 		sz = fnd_mapping_sz(pp);
8251 		pp = PP_GROUPLEADER(pp, sz);
8252 		SFMMU_STAT_ADD(sf_uncache_conflict, TTEPAGES(sz));
8253 		sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH,
8254 			TTEPAGES(sz));
8255 
8256 		return;
8257 	}
8258 
8259 	/*
8260 	 * check if any mapping is in same as or if it is locked
8261 	 * since in that case we need to uncache.
8262 	 */
8263 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
8264 		tmphme = sfhmep->hme_next;
8265 		hmeblkp = sfmmu_hmetohblk(sfhmep);
8266 		if (hmeblkp->hblk_xhat_bit)
8267 			continue;
8268 		tmphat = hblktosfmmu(hmeblkp);
8269 		sfmmu_copytte(&sfhmep->hme_tte, &tte);
8270 		ASSERT(TTE_IS_VALID(&tte));
8271 		if ((tmphat == hat) || hmeblkp->hblk_lckcnt) {
8272 			/*
8273 			 * We have an uncache conflict
8274 			 */
8275 			SFMMU_STAT(sf_uncache_conflict);
8276 			sfmmu_page_cache_array(pp, HAT_TMPNC, CACHE_FLUSH, 1);
8277 			return;
8278 		}
8279 	}
8280 
8281 	/*
8282 	 * We have an unload conflict
8283 	 * We have already checked for LARGE mappings, therefore
8284 	 * the remaining mapping(s) must be TTE8K.
8285 	 */
8286 	SFMMU_STAT(sf_unload_conflict);
8287 
8288 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = tmphme) {
8289 		tmphme = sfhmep->hme_next;
8290 		hmeblkp = sfmmu_hmetohblk(sfhmep);
8291 		if (hmeblkp->hblk_xhat_bit)
8292 			continue;
8293 		(void) sfmmu_pageunload(pp, sfhmep, TTE8K);
8294 	}
8295 
8296 	if (PP_ISMAPPED_KPM(pp))
8297 		sfmmu_kpm_vac_unload(pp, addr);
8298 
8299 	/*
8300 	 * Unloads only do TLB flushes so we need to flush the
8301 	 * cache here.
8302 	 */
8303 	sfmmu_cache_flush(pp->p_pagenum, PP_GET_VCOLOR(pp));
8304 	PP_SET_VCOLOR(pp, vcolor);
8305 }
8306 
8307 /*
8308  * Whenever a mapping is unloaded and the page is in TNC state,
8309  * we see if the page can be made cacheable again. 'pp' is
8310  * the page that we just unloaded a mapping from, the size
8311  * of mapping that was unloaded is 'ottesz'.
8312  * Remark:
8313  * The recache policy for mpss pages can leave a performance problem
8314  * under the following circumstances:
8315  * . A large page in uncached mode has just been unmapped.
8316  * . All constituent pages are TNC due to a conflicting small mapping.
8317  * . There are many other, non conflicting, small mappings around for
8318  *   a lot of the constituent pages.
8319  * . We're called w/ the "old" groupleader page and the old ottesz,
8320  *   but this is irrelevant, since we're no more "PP_ISMAPPED_LARGE", so
8321  *   we end up w/ TTE8K or npages == 1.
8322  * . We call tst_tnc w/ the old groupleader only, and if there is no
8323  *   conflict, we re-cache only this page.
8324  * . All other small mappings are not checked and will be left in TNC mode.
8325  * The problem is not very serious because:
8326  * . mpss is actually only defined for heap and stack, so the probability
8327  *   is not very high that a large page mapping exists in parallel to a small
8328  *   one (this is possible, but seems to be bad programming style in the
8329  *   appl).
8330  * . The problem gets a little bit more serious, when those TNC pages
8331  *   have to be mapped into kernel space, e.g. for networking.
8332  * . When VAC alias conflicts occur in applications, this is regarded
8333  *   as an application bug. So if kstat's show them, the appl should
8334  *   be changed anyway.
8335  */
8336 void
8337 conv_tnc(page_t *pp, int ottesz)
8338 {
8339 	int cursz, dosz;
8340 	pgcnt_t curnpgs, dopgs;
8341 	pgcnt_t pg64k;
8342 	page_t *pp2;
8343 
8344 	/*
8345 	 * Determine how big a range we check for TNC and find
8346 	 * leader page. cursz is the size of the biggest
8347 	 * mapping that still exist on 'pp'.
8348 	 */
8349 	if (PP_ISMAPPED_LARGE(pp)) {
8350 		cursz = fnd_mapping_sz(pp);
8351 	} else {
8352 		cursz = TTE8K;
8353 	}
8354 
8355 	if (ottesz >= cursz) {
8356 		dosz = ottesz;
8357 		pp2 = pp;
8358 	} else {
8359 		dosz = cursz;
8360 		pp2 = PP_GROUPLEADER(pp, dosz);
8361 	}
8362 
8363 	pg64k = TTEPAGES(TTE64K);
8364 	dopgs = TTEPAGES(dosz);
8365 
8366 	ASSERT(dopgs == 1 || ((dopgs & (pg64k - 1)) == 0));
8367 
8368 	while (dopgs != 0) {
8369 		curnpgs = TTEPAGES(cursz);
8370 		if (tst_tnc(pp2, curnpgs)) {
8371 			SFMMU_STAT_ADD(sf_recache, curnpgs);
8372 			sfmmu_page_cache_array(pp2, HAT_CACHE, CACHE_NO_FLUSH,
8373 				curnpgs);
8374 		}
8375 
8376 		ASSERT(dopgs >= curnpgs);
8377 		dopgs -= curnpgs;
8378 
8379 		if (dopgs == 0) {
8380 			break;
8381 		}
8382 
8383 		pp2 = PP_PAGENEXT_N(pp2, curnpgs);
8384 		if (((dopgs & (pg64k - 1)) == 0) && PP_ISMAPPED_LARGE(pp2)) {
8385 			cursz = fnd_mapping_sz(pp2);
8386 		} else {
8387 			cursz = TTE8K;
8388 		}
8389 	}
8390 }
8391 
8392 /*
8393  * Returns 1 if page(s) can be converted from TNC to cacheable setting,
8394  * returns 0 otherwise. Note that oaddr argument is valid for only
8395  * 8k pages.
8396  */
8397 int
8398 tst_tnc(page_t *pp, pgcnt_t npages)
8399 {
8400 	struct	sf_hment *sfhme;
8401 	struct	hme_blk *hmeblkp;
8402 	tte_t	tte;
8403 	caddr_t	vaddr;
8404 	int	clr_valid = 0;
8405 	int 	color, color1, bcolor;
8406 	int	i, ncolors;
8407 
8408 	ASSERT(pp != NULL);
8409 	ASSERT(!(cache & CACHE_WRITEBACK));
8410 
8411 	if (npages > 1) {
8412 		ncolors = CACHE_NUM_COLOR;
8413 	}
8414 
8415 	for (i = 0; i < npages; i++) {
8416 		ASSERT(sfmmu_mlist_held(pp));
8417 		ASSERT(PP_ISTNC(pp));
8418 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
8419 
8420 		if (PP_ISPNC(pp)) {
8421 			return (0);
8422 		}
8423 
8424 		clr_valid = 0;
8425 		if (PP_ISMAPPED_KPM(pp)) {
8426 			caddr_t kpmvaddr;
8427 
8428 			ASSERT(kpm_enable);
8429 			kpmvaddr = hat_kpm_page2va(pp, 1);
8430 			ASSERT(!(npages > 1 && IS_KPM_ALIAS_RANGE(kpmvaddr)));
8431 			color1 = addr_to_vcolor(kpmvaddr);
8432 			clr_valid = 1;
8433 		}
8434 
8435 		for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
8436 			hmeblkp = sfmmu_hmetohblk(sfhme);
8437 			if (hmeblkp->hblk_xhat_bit)
8438 				continue;
8439 
8440 			sfmmu_copytte(&sfhme->hme_tte, &tte);
8441 			ASSERT(TTE_IS_VALID(&tte));
8442 
8443 			vaddr = tte_to_vaddr(hmeblkp, tte);
8444 			color = addr_to_vcolor(vaddr);
8445 
8446 			if (npages > 1) {
8447 				/*
8448 				 * If there is a big mapping, make sure
8449 				 * 8K mapping is consistent with the big
8450 				 * mapping.
8451 				 */
8452 				bcolor = i % ncolors;
8453 				if (color != bcolor) {
8454 					return (0);
8455 				}
8456 			}
8457 			if (!clr_valid) {
8458 				clr_valid = 1;
8459 				color1 = color;
8460 			}
8461 
8462 			if (color1 != color) {
8463 				return (0);
8464 			}
8465 		}
8466 
8467 		pp = PP_PAGENEXT(pp);
8468 	}
8469 
8470 	return (1);
8471 }
8472 
8473 void
8474 sfmmu_page_cache_array(page_t *pp, int flags, int cache_flush_flag,
8475 	pgcnt_t npages)
8476 {
8477 	kmutex_t *pmtx;
8478 	int i, ncolors, bcolor;
8479 	kpm_hlk_t *kpmp;
8480 	cpuset_t cpuset;
8481 
8482 	ASSERT(pp != NULL);
8483 	ASSERT(!(cache & CACHE_WRITEBACK));
8484 
8485 	kpmp = sfmmu_kpm_kpmp_enter(pp, npages);
8486 	pmtx = sfmmu_page_enter(pp);
8487 
8488 	/*
8489 	 * Fast path caching single unmapped page
8490 	 */
8491 	if (npages == 1 && !PP_ISMAPPED(pp) && !PP_ISMAPPED_KPM(pp) &&
8492 	    flags == HAT_CACHE) {
8493 		PP_CLRTNC(pp);
8494 		PP_CLRPNC(pp);
8495 		sfmmu_page_exit(pmtx);
8496 		sfmmu_kpm_kpmp_exit(kpmp);
8497 		return;
8498 	}
8499 
8500 	/*
8501 	 * We need to capture all cpus in order to change cacheability
8502 	 * because we can't allow one cpu to access the same physical
8503 	 * page using a cacheable and a non-cachebale mapping at the same
8504 	 * time. Since we may end up walking the ism mapping list
8505 	 * have to grab it's lock now since we can't after all the
8506 	 * cpus have been captured.
8507 	 */
8508 	sfmmu_hat_lock_all();
8509 	mutex_enter(&ism_mlist_lock);
8510 	kpreempt_disable();
8511 	cpuset = cpu_ready_set;
8512 	xc_attention(cpuset);
8513 
8514 	if (npages > 1) {
8515 		/*
8516 		 * Make sure all colors are flushed since the
8517 		 * sfmmu_page_cache() only flushes one color-
8518 		 * it does not know big pages.
8519 		 */
8520 		ncolors = CACHE_NUM_COLOR;
8521 		if (flags & HAT_TMPNC) {
8522 			for (i = 0; i < ncolors; i++) {
8523 				sfmmu_cache_flushcolor(i, pp->p_pagenum);
8524 			}
8525 			cache_flush_flag = CACHE_NO_FLUSH;
8526 		}
8527 	}
8528 
8529 	for (i = 0; i < npages; i++) {
8530 
8531 		ASSERT(sfmmu_mlist_held(pp));
8532 
8533 		if (!(flags == HAT_TMPNC && PP_ISTNC(pp))) {
8534 
8535 			if (npages > 1) {
8536 				bcolor = i % ncolors;
8537 			} else {
8538 				bcolor = NO_VCOLOR;
8539 			}
8540 
8541 			sfmmu_page_cache(pp, flags, cache_flush_flag,
8542 			    bcolor);
8543 		}
8544 
8545 		pp = PP_PAGENEXT(pp);
8546 	}
8547 
8548 	xt_sync(cpuset);
8549 	xc_dismissed(cpuset);
8550 	mutex_exit(&ism_mlist_lock);
8551 	sfmmu_hat_unlock_all();
8552 	sfmmu_page_exit(pmtx);
8553 	sfmmu_kpm_kpmp_exit(kpmp);
8554 	kpreempt_enable();
8555 }
8556 
8557 /*
8558  * This function changes the virtual cacheability of all mappings to a
8559  * particular page.  When changing from uncache to cacheable the mappings will
8560  * only be changed if all of them have the same virtual color.
8561  * We need to flush the cache in all cpus.  It is possible that
8562  * a process referenced a page as cacheable but has sinced exited
8563  * and cleared the mapping list.  We still to flush it but have no
8564  * state so all cpus is the only alternative.
8565  */
8566 static void
8567 sfmmu_page_cache(page_t *pp, int flags, int cache_flush_flag, int bcolor)
8568 {
8569 	struct	sf_hment *sfhme;
8570 	struct	hme_blk *hmeblkp;
8571 	sfmmu_t *sfmmup;
8572 	tte_t	tte, ttemod;
8573 	caddr_t	vaddr;
8574 	int	ret, color;
8575 	pfn_t	pfn;
8576 
8577 	color = bcolor;
8578 	pfn = pp->p_pagenum;
8579 
8580 	for (sfhme = pp->p_mapping; sfhme; sfhme = sfhme->hme_next) {
8581 
8582 		hmeblkp = sfmmu_hmetohblk(sfhme);
8583 
8584 		if (hmeblkp->hblk_xhat_bit)
8585 			continue;
8586 
8587 		sfmmu_copytte(&sfhme->hme_tte, &tte);
8588 		ASSERT(TTE_IS_VALID(&tte));
8589 		vaddr = tte_to_vaddr(hmeblkp, tte);
8590 		color = addr_to_vcolor(vaddr);
8591 
8592 #ifdef DEBUG
8593 		if ((flags & HAT_CACHE) && bcolor != NO_VCOLOR) {
8594 			ASSERT(color == bcolor);
8595 		}
8596 #endif
8597 
8598 		ASSERT(flags != HAT_TMPNC || color == PP_GET_VCOLOR(pp));
8599 
8600 		ttemod = tte;
8601 		if (flags & (HAT_UNCACHE | HAT_TMPNC)) {
8602 			TTE_CLR_VCACHEABLE(&ttemod);
8603 		} else {	/* flags & HAT_CACHE */
8604 			TTE_SET_VCACHEABLE(&ttemod);
8605 		}
8606 		ret = sfmmu_modifytte_try(&tte, &ttemod, &sfhme->hme_tte);
8607 		if (ret < 0) {
8608 			/*
8609 			 * Since all cpus are captured modifytte should not
8610 			 * fail.
8611 			 */
8612 			panic("sfmmu_page_cache: write to tte failed");
8613 		}
8614 
8615 		sfmmup = hblktosfmmu(hmeblkp);
8616 		if (cache_flush_flag == CACHE_FLUSH) {
8617 			/*
8618 			 * Flush TSBs, TLBs and caches
8619 			 */
8620 			if (sfmmup->sfmmu_ismhat) {
8621 				if (flags & HAT_CACHE) {
8622 					SFMMU_STAT(sf_ism_recache);
8623 				} else {
8624 					SFMMU_STAT(sf_ism_uncache);
8625 				}
8626 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
8627 				    pfn, CACHE_FLUSH);
8628 			} else {
8629 				sfmmu_tlbcache_demap(vaddr, sfmmup, hmeblkp,
8630 				    pfn, 0, FLUSH_ALL_CPUS, CACHE_FLUSH, 1);
8631 			}
8632 
8633 			/*
8634 			 * all cache entries belonging to this pfn are
8635 			 * now flushed.
8636 			 */
8637 			cache_flush_flag = CACHE_NO_FLUSH;
8638 		} else {
8639 
8640 			/*
8641 			 * Flush only TSBs and TLBs.
8642 			 */
8643 			if (sfmmup->sfmmu_ismhat) {
8644 				if (flags & HAT_CACHE) {
8645 					SFMMU_STAT(sf_ism_recache);
8646 				} else {
8647 					SFMMU_STAT(sf_ism_uncache);
8648 				}
8649 				sfmmu_ismtlbcache_demap(vaddr, sfmmup, hmeblkp,
8650 				    pfn, CACHE_NO_FLUSH);
8651 			} else {
8652 				sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 1);
8653 			}
8654 		}
8655 	}
8656 
8657 	if (PP_ISMAPPED_KPM(pp))
8658 		sfmmu_kpm_page_cache(pp, flags, cache_flush_flag);
8659 
8660 	switch (flags) {
8661 
8662 		default:
8663 			panic("sfmmu_pagecache: unknown flags");
8664 			break;
8665 
8666 		case HAT_CACHE:
8667 			PP_CLRTNC(pp);
8668 			PP_CLRPNC(pp);
8669 			PP_SET_VCOLOR(pp, color);
8670 			break;
8671 
8672 		case HAT_TMPNC:
8673 			PP_SETTNC(pp);
8674 			PP_SET_VCOLOR(pp, NO_VCOLOR);
8675 			break;
8676 
8677 		case HAT_UNCACHE:
8678 			PP_SETPNC(pp);
8679 			PP_CLRTNC(pp);
8680 			PP_SET_VCOLOR(pp, NO_VCOLOR);
8681 			break;
8682 	}
8683 }
8684 #endif	/* VAC */
8685 
8686 
8687 /*
8688  * Wrapper routine used to return a context.
8689  *
8690  * It's the responsibility of the caller to guarantee that the
8691  * process serializes on calls here by taking the HAT lock for
8692  * the hat.
8693  *
8694  */
8695 static void
8696 sfmmu_get_ctx(sfmmu_t *sfmmup)
8697 {
8698 	mmu_ctx_t *mmu_ctxp;
8699 	uint_t pstate_save;
8700 
8701 	ASSERT(sfmmu_hat_lock_held(sfmmup));
8702 	ASSERT(sfmmup != ksfmmup);
8703 
8704 	kpreempt_disable();
8705 
8706 	mmu_ctxp = CPU_MMU_CTXP(CPU);
8707 	ASSERT(mmu_ctxp);
8708 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
8709 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
8710 
8711 	/*
8712 	 * Do a wrap-around if cnum reaches the max # cnum supported by a MMU.
8713 	 */
8714 	if (mmu_ctxp->mmu_cnum == mmu_ctxp->mmu_nctxs)
8715 		sfmmu_ctx_wrap_around(mmu_ctxp);
8716 
8717 	/*
8718 	 * Let the MMU set up the page sizes to use for
8719 	 * this context in the TLB. Don't program 2nd dtlb for ism hat.
8720 	 */
8721 	if ((&mmu_set_ctx_page_sizes) && (sfmmup->sfmmu_ismhat == 0)) {
8722 		mmu_set_ctx_page_sizes(sfmmup);
8723 	}
8724 
8725 	/*
8726 	 * sfmmu_alloc_ctx and sfmmu_load_mmustate will be performed with
8727 	 * interrupts disabled to prevent race condition with wrap-around
8728 	 * ctx invalidatation. In sun4v, ctx invalidation also involves
8729 	 * a HV call to set the number of TSBs to 0. If interrupts are not
8730 	 * disabled until after sfmmu_load_mmustate is complete TSBs may
8731 	 * become assigned to INVALID_CONTEXT. This is not allowed.
8732 	 */
8733 	pstate_save = sfmmu_disable_intrs();
8734 
8735 	sfmmu_alloc_ctx(sfmmup, 1, CPU);
8736 	sfmmu_load_mmustate(sfmmup);
8737 
8738 	sfmmu_enable_intrs(pstate_save);
8739 
8740 	kpreempt_enable();
8741 }
8742 
8743 /*
8744  * When all cnums are used up in a MMU, cnum will wrap around to the
8745  * next generation and start from 2.
8746  */
8747 static void
8748 sfmmu_ctx_wrap_around(mmu_ctx_t *mmu_ctxp)
8749 {
8750 
8751 	/* caller must have disabled the preemption */
8752 	ASSERT(curthread->t_preempt >= 1);
8753 	ASSERT(mmu_ctxp != NULL);
8754 
8755 	/* acquire Per-MMU (PM) spin lock */
8756 	mutex_enter(&mmu_ctxp->mmu_lock);
8757 
8758 	/* re-check to see if wrap-around is needed */
8759 	if (mmu_ctxp->mmu_cnum < mmu_ctxp->mmu_nctxs)
8760 		goto done;
8761 
8762 	SFMMU_MMU_STAT(mmu_wrap_around);
8763 
8764 	/* update gnum */
8765 	ASSERT(mmu_ctxp->mmu_gnum != 0);
8766 	mmu_ctxp->mmu_gnum++;
8767 	if (mmu_ctxp->mmu_gnum == 0 ||
8768 	    mmu_ctxp->mmu_gnum > MAX_SFMMU_GNUM_VAL) {
8769 		cmn_err(CE_PANIC, "mmu_gnum of mmu_ctx 0x%p is out of bound.",
8770 		    (void *)mmu_ctxp);
8771 	}
8772 
8773 	if (mmu_ctxp->mmu_ncpus > 1) {
8774 		cpuset_t cpuset;
8775 
8776 		membar_enter(); /* make sure updated gnum visible */
8777 
8778 		SFMMU_XCALL_STATS(NULL);
8779 
8780 		/* xcall to others on the same MMU to invalidate ctx */
8781 		cpuset = mmu_ctxp->mmu_cpuset;
8782 		ASSERT(CPU_IN_SET(cpuset, CPU->cpu_id));
8783 		CPUSET_DEL(cpuset, CPU->cpu_id);
8784 		CPUSET_AND(cpuset, cpu_ready_set);
8785 
8786 		/*
8787 		 * Pass in INVALID_CONTEXT as the first parameter to
8788 		 * sfmmu_raise_tsb_exception, which invalidates the context
8789 		 * of any process running on the CPUs in the MMU.
8790 		 */
8791 		xt_some(cpuset, sfmmu_raise_tsb_exception,
8792 		    INVALID_CONTEXT, INVALID_CONTEXT);
8793 		xt_sync(cpuset);
8794 
8795 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
8796 	}
8797 
8798 	if (sfmmu_getctx_sec() != INVALID_CONTEXT) {
8799 		sfmmu_setctx_sec(INVALID_CONTEXT);
8800 		sfmmu_clear_utsbinfo();
8801 	}
8802 
8803 	/*
8804 	 * No xcall is needed here. For sun4u systems all CPUs in context
8805 	 * domain share a single physical MMU therefore it's enough to flush
8806 	 * TLB on local CPU. On sun4v systems we use 1 global context
8807 	 * domain and flush all remote TLBs in sfmmu_raise_tsb_exception
8808 	 * handler. Note that vtag_flushall_uctxs() is called
8809 	 * for Ultra II machine, where the equivalent flushall functionality
8810 	 * is implemented in SW, and only user ctx TLB entries are flushed.
8811 	 */
8812 	if (&vtag_flushall_uctxs != NULL) {
8813 		vtag_flushall_uctxs();
8814 	} else {
8815 		vtag_flushall();
8816 	}
8817 
8818 	/* reset mmu cnum, skips cnum 0 and 1 */
8819 	mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
8820 
8821 done:
8822 	mutex_exit(&mmu_ctxp->mmu_lock);
8823 }
8824 
8825 
8826 /*
8827  * For multi-threaded process, set the process context to INVALID_CONTEXT
8828  * so that it faults and reloads the MMU state from TL=0. For single-threaded
8829  * process, we can just load the MMU state directly without having to
8830  * set context invalid. Caller must hold the hat lock since we don't
8831  * acquire it here.
8832  */
8833 static void
8834 sfmmu_sync_mmustate(sfmmu_t *sfmmup)
8835 {
8836 	uint_t cnum;
8837 	uint_t pstate_save;
8838 
8839 	ASSERT(sfmmup != ksfmmup);
8840 	ASSERT(sfmmu_hat_lock_held(sfmmup));
8841 
8842 	kpreempt_disable();
8843 
8844 	/*
8845 	 * We check whether the pass'ed-in sfmmup is the same as the
8846 	 * current running proc. This is to makes sure the current proc
8847 	 * stays single-threaded if it already is.
8848 	 */
8849 	if ((sfmmup == curthread->t_procp->p_as->a_hat) &&
8850 	    (curthread->t_procp->p_lwpcnt == 1)) {
8851 		/* single-thread */
8852 		cnum = sfmmup->sfmmu_ctxs[CPU_MMU_IDX(CPU)].cnum;
8853 		if (cnum != INVALID_CONTEXT) {
8854 			uint_t curcnum;
8855 			/*
8856 			 * Disable interrupts to prevent race condition
8857 			 * with sfmmu_ctx_wrap_around ctx invalidation.
8858 			 * In sun4v, ctx invalidation involves setting
8859 			 * TSB to NULL, hence, interrupts should be disabled
8860 			 * untill after sfmmu_load_mmustate is completed.
8861 			 */
8862 			pstate_save = sfmmu_disable_intrs();
8863 			curcnum = sfmmu_getctx_sec();
8864 			if (curcnum == cnum)
8865 				sfmmu_load_mmustate(sfmmup);
8866 			sfmmu_enable_intrs(pstate_save);
8867 			ASSERT(curcnum == cnum || curcnum == INVALID_CONTEXT);
8868 		}
8869 	} else {
8870 		/*
8871 		 * multi-thread
8872 		 * or when sfmmup is not the same as the curproc.
8873 		 */
8874 		sfmmu_invalidate_ctx(sfmmup);
8875 	}
8876 
8877 	kpreempt_enable();
8878 }
8879 
8880 
8881 /*
8882  * Replace the specified TSB with a new TSB.  This function gets called when
8883  * we grow, shrink or swapin a TSB.  When swapping in a TSB (TSB_SWAPIN), the
8884  * TSB_FORCEALLOC flag may be used to force allocation of a minimum-sized TSB
8885  * (8K).
8886  *
8887  * Caller must hold the HAT lock, but should assume any tsb_info
8888  * pointers it has are no longer valid after calling this function.
8889  *
8890  * Return values:
8891  *	TSB_ALLOCFAIL	Failed to allocate a TSB, due to memory constraints
8892  *	TSB_LOSTRACE	HAT is busy, i.e. another thread is already doing
8893  *			something to this tsbinfo/TSB
8894  *	TSB_SUCCESS	Operation succeeded
8895  */
8896 static tsb_replace_rc_t
8897 sfmmu_replace_tsb(sfmmu_t *sfmmup, struct tsb_info *old_tsbinfo, uint_t szc,
8898     hatlock_t *hatlockp, uint_t flags)
8899 {
8900 	struct tsb_info *new_tsbinfo = NULL;
8901 	struct tsb_info *curtsb, *prevtsb;
8902 	uint_t tte_sz_mask;
8903 	int i;
8904 
8905 	ASSERT(sfmmup != ksfmmup);
8906 	ASSERT(sfmmup->sfmmu_ismhat == 0);
8907 	ASSERT(sfmmu_hat_lock_held(sfmmup));
8908 	ASSERT(szc <= tsb_max_growsize);
8909 
8910 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_BUSY))
8911 		return (TSB_LOSTRACE);
8912 
8913 	/*
8914 	 * Find the tsb_info ahead of this one in the list, and
8915 	 * also make sure that the tsb_info passed in really
8916 	 * exists!
8917 	 */
8918 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
8919 	    curtsb != old_tsbinfo && curtsb != NULL;
8920 	    prevtsb = curtsb, curtsb = curtsb->tsb_next);
8921 	ASSERT(curtsb != NULL);
8922 
8923 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
8924 		/*
8925 		 * The process is swapped out, so just set the new size
8926 		 * code.  When it swaps back in, we'll allocate a new one
8927 		 * of the new chosen size.
8928 		 */
8929 		curtsb->tsb_szc = szc;
8930 		return (TSB_SUCCESS);
8931 	}
8932 	SFMMU_FLAGS_SET(sfmmup, HAT_BUSY);
8933 
8934 	tte_sz_mask = old_tsbinfo->tsb_ttesz_mask;
8935 
8936 	/*
8937 	 * All initialization is done inside of sfmmu_tsbinfo_alloc().
8938 	 * If we fail to allocate a TSB, exit.
8939 	 */
8940 	sfmmu_hat_exit(hatlockp);
8941 	if (sfmmu_tsbinfo_alloc(&new_tsbinfo, szc, tte_sz_mask,
8942 	    flags, sfmmup)) {
8943 		(void) sfmmu_hat_enter(sfmmup);
8944 		if (!(flags & TSB_SWAPIN))
8945 			SFMMU_STAT(sf_tsb_resize_failures);
8946 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
8947 		return (TSB_ALLOCFAIL);
8948 	}
8949 	(void) sfmmu_hat_enter(sfmmup);
8950 
8951 	/*
8952 	 * Re-check to make sure somebody else didn't muck with us while we
8953 	 * didn't hold the HAT lock.  If the process swapped out, fine, just
8954 	 * exit; this can happen if we try to shrink the TSB from the context
8955 	 * of another process (such as on an ISM unmap), though it is rare.
8956 	 */
8957 	if (!(flags & TSB_SWAPIN) && SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
8958 		SFMMU_STAT(sf_tsb_resize_failures);
8959 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
8960 		sfmmu_hat_exit(hatlockp);
8961 		sfmmu_tsbinfo_free(new_tsbinfo);
8962 		(void) sfmmu_hat_enter(sfmmup);
8963 		return (TSB_LOSTRACE);
8964 	}
8965 
8966 #ifdef	DEBUG
8967 	/* Reverify that the tsb_info still exists.. for debugging only */
8968 	for (prevtsb = NULL, curtsb = sfmmup->sfmmu_tsb;
8969 	    curtsb != old_tsbinfo && curtsb != NULL;
8970 	    prevtsb = curtsb, curtsb = curtsb->tsb_next);
8971 	ASSERT(curtsb != NULL);
8972 #endif	/* DEBUG */
8973 
8974 	/*
8975 	 * Quiesce any CPUs running this process on their next TLB miss
8976 	 * so they atomically see the new tsb_info.  We temporarily set the
8977 	 * context to invalid context so new threads that come on processor
8978 	 * after we do the xcall to cpusran will also serialize behind the
8979 	 * HAT lock on TLB miss and will see the new TSB.  Since this short
8980 	 * race with a new thread coming on processor is relatively rare,
8981 	 * this synchronization mechanism should be cheaper than always
8982 	 * pausing all CPUs for the duration of the setup, which is what
8983 	 * the old implementation did.  This is particuarly true if we are
8984 	 * copying a huge chunk of memory around during that window.
8985 	 *
8986 	 * The memory barriers are to make sure things stay consistent
8987 	 * with resume() since it does not hold the HAT lock while
8988 	 * walking the list of tsb_info structures.
8989 	 */
8990 	if ((flags & TSB_SWAPIN) != TSB_SWAPIN) {
8991 		/* The TSB is either growing or shrinking. */
8992 		sfmmu_invalidate_ctx(sfmmup);
8993 	} else {
8994 		/*
8995 		 * It is illegal to swap in TSBs from a process other
8996 		 * than a process being swapped in.  This in turn
8997 		 * implies we do not have a valid MMU context here
8998 		 * since a process needs one to resolve translation
8999 		 * misses.
9000 		 */
9001 		ASSERT(curthread->t_procp->p_as->a_hat == sfmmup);
9002 	}
9003 
9004 #ifdef DEBUG
9005 	ASSERT(max_mmu_ctxdoms > 0);
9006 
9007 	/*
9008 	 * Process should have INVALID_CONTEXT on all MMUs
9009 	 */
9010 	for (i = 0; i < max_mmu_ctxdoms; i++) {
9011 
9012 		ASSERT(sfmmup->sfmmu_ctxs[i].cnum == INVALID_CONTEXT);
9013 	}
9014 #endif
9015 
9016 	new_tsbinfo->tsb_next = old_tsbinfo->tsb_next;
9017 	membar_stst();	/* strict ordering required */
9018 	if (prevtsb)
9019 		prevtsb->tsb_next = new_tsbinfo;
9020 	else
9021 		sfmmup->sfmmu_tsb = new_tsbinfo;
9022 	membar_enter();	/* make sure new TSB globally visible */
9023 	sfmmu_setup_tsbinfo(sfmmup);
9024 
9025 	/*
9026 	 * We need to migrate TSB entries from the old TSB to the new TSB
9027 	 * if tsb_remap_ttes is set and the TSB is growing.
9028 	 */
9029 	if (tsb_remap_ttes && ((flags & TSB_GROW) == TSB_GROW))
9030 		sfmmu_copy_tsb(old_tsbinfo, new_tsbinfo);
9031 
9032 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_BUSY);
9033 
9034 	/*
9035 	 * Drop the HAT lock to free our old tsb_info.
9036 	 */
9037 	sfmmu_hat_exit(hatlockp);
9038 
9039 	if ((flags & TSB_GROW) == TSB_GROW) {
9040 		SFMMU_STAT(sf_tsb_grow);
9041 	} else if ((flags & TSB_SHRINK) == TSB_SHRINK) {
9042 		SFMMU_STAT(sf_tsb_shrink);
9043 	}
9044 
9045 	sfmmu_tsbinfo_free(old_tsbinfo);
9046 
9047 	(void) sfmmu_hat_enter(sfmmup);
9048 	return (TSB_SUCCESS);
9049 }
9050 
9051 /*
9052  * This function will re-program hat pgsz array, and invalidate the
9053  * process' context, forcing the process to switch to another
9054  * context on the next TLB miss, and therefore start using the
9055  * TLB that is reprogrammed for the new page sizes.
9056  */
9057 void
9058 sfmmu_reprog_pgsz_arr(sfmmu_t *sfmmup, uint8_t *tmp_pgsz)
9059 {
9060 	int i;
9061 	hatlock_t *hatlockp = NULL;
9062 
9063 	hatlockp = sfmmu_hat_enter(sfmmup);
9064 	/* USIII+-IV+ optimization, requires hat lock */
9065 	if (tmp_pgsz) {
9066 		for (i = 0; i < mmu_page_sizes; i++)
9067 			sfmmup->sfmmu_pgsz[i] = tmp_pgsz[i];
9068 	}
9069 	SFMMU_STAT(sf_tlb_reprog_pgsz);
9070 
9071 	sfmmu_invalidate_ctx(sfmmup);
9072 
9073 	sfmmu_hat_exit(hatlockp);
9074 }
9075 
9076 /*
9077  * This function assumes that there are either four or six supported page
9078  * sizes and at most two programmable TLBs, so we need to decide which
9079  * page sizes are most important and then tell the MMU layer so it
9080  * can adjust the TLB page sizes accordingly (if supported).
9081  *
9082  * If these assumptions change, this function will need to be
9083  * updated to support whatever the new limits are.
9084  *
9085  * The growing flag is nonzero if we are growing the address space,
9086  * and zero if it is shrinking.  This allows us to decide whether
9087  * to grow or shrink our TSB, depending upon available memory
9088  * conditions.
9089  */
9090 static void
9091 sfmmu_check_page_sizes(sfmmu_t *sfmmup, int growing)
9092 {
9093 	uint64_t ttecnt[MMU_PAGE_SIZES];
9094 	uint64_t tte8k_cnt, tte4m_cnt;
9095 	uint8_t i;
9096 	int sectsb_thresh;
9097 
9098 	/*
9099 	 * Kernel threads, processes with small address spaces not using
9100 	 * large pages, and dummy ISM HATs need not apply.
9101 	 */
9102 	if (sfmmup == ksfmmup || sfmmup->sfmmu_ismhat != NULL)
9103 		return;
9104 
9105 	if ((sfmmup->sfmmu_flags & HAT_LGPG_FLAGS) == 0 &&
9106 	    sfmmup->sfmmu_ttecnt[TTE8K] <= tsb_rss_factor)
9107 		return;
9108 
9109 	for (i = 0; i < mmu_page_sizes; i++) {
9110 		ttecnt[i] = SFMMU_TTE_CNT(sfmmup, i);
9111 	}
9112 
9113 	/* Check pagesizes in use, and possibly reprogram DTLB. */
9114 	if (&mmu_check_page_sizes)
9115 		mmu_check_page_sizes(sfmmup, ttecnt);
9116 
9117 	/*
9118 	 * Calculate the number of 8k ttes to represent the span of these
9119 	 * pages.
9120 	 */
9121 	tte8k_cnt = ttecnt[TTE8K] +
9122 	    (ttecnt[TTE64K] << (MMU_PAGESHIFT64K - MMU_PAGESHIFT)) +
9123 	    (ttecnt[TTE512K] << (MMU_PAGESHIFT512K - MMU_PAGESHIFT));
9124 	if (mmu_page_sizes == max_mmu_page_sizes) {
9125 		tte4m_cnt = ttecnt[TTE4M] +
9126 		    (ttecnt[TTE32M] << (MMU_PAGESHIFT32M - MMU_PAGESHIFT4M)) +
9127 		    (ttecnt[TTE256M] << (MMU_PAGESHIFT256M - MMU_PAGESHIFT4M));
9128 	} else {
9129 		tte4m_cnt = ttecnt[TTE4M];
9130 	}
9131 
9132 	/*
9133 	 * Inflate TSB sizes by a factor of 2 if this process
9134 	 * uses 4M text pages to minimize extra conflict misses
9135 	 * in the first TSB since without counting text pages
9136 	 * 8K TSB may become too small.
9137 	 *
9138 	 * Also double the size of the second TSB to minimize
9139 	 * extra conflict misses due to competition between 4M text pages
9140 	 * and data pages.
9141 	 *
9142 	 * We need to adjust the second TSB allocation threshold by the
9143 	 * inflation factor, since there is no point in creating a second
9144 	 * TSB when we know all the mappings can fit in the I/D TLBs.
9145 	 */
9146 	sectsb_thresh = tsb_sectsb_threshold;
9147 	if (sfmmup->sfmmu_flags & HAT_4MTEXT_FLAG) {
9148 		tte8k_cnt <<= 1;
9149 		tte4m_cnt <<= 1;
9150 		sectsb_thresh <<= 1;
9151 	}
9152 
9153 	/*
9154 	 * Check to see if our TSB is the right size; we may need to
9155 	 * grow or shrink it.  If the process is small, our work is
9156 	 * finished at this point.
9157 	 */
9158 	if (tte8k_cnt <= tsb_rss_factor && tte4m_cnt <= sectsb_thresh) {
9159 		return;
9160 	}
9161 	sfmmu_size_tsb(sfmmup, growing, tte8k_cnt, tte4m_cnt, sectsb_thresh);
9162 }
9163 
9164 static void
9165 sfmmu_size_tsb(sfmmu_t *sfmmup, int growing, uint64_t tte8k_cnt,
9166 	uint64_t tte4m_cnt, int sectsb_thresh)
9167 {
9168 	int tsb_bits;
9169 	uint_t tsb_szc;
9170 	struct tsb_info *tsbinfop;
9171 	hatlock_t *hatlockp = NULL;
9172 
9173 	hatlockp = sfmmu_hat_enter(sfmmup);
9174 	ASSERT(hatlockp != NULL);
9175 	tsbinfop = sfmmup->sfmmu_tsb;
9176 	ASSERT(tsbinfop != NULL);
9177 
9178 	/*
9179 	 * If we're growing, select the size based on RSS.  If we're
9180 	 * shrinking, leave some room so we don't have to turn around and
9181 	 * grow again immediately.
9182 	 */
9183 	if (growing)
9184 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt);
9185 	else
9186 		tsb_szc = SELECT_TSB_SIZECODE(tte8k_cnt << 1);
9187 
9188 	if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
9189 	    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
9190 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
9191 		    hatlockp, TSB_SHRINK);
9192 	} else if (growing && tsb_szc > tsbinfop->tsb_szc && TSB_OK_GROW()) {
9193 		(void) sfmmu_replace_tsb(sfmmup, tsbinfop, tsb_szc,
9194 		    hatlockp, TSB_GROW);
9195 	}
9196 	tsbinfop = sfmmup->sfmmu_tsb;
9197 
9198 	/*
9199 	 * With the TLB and first TSB out of the way, we need to see if
9200 	 * we need a second TSB for 4M pages.  If we managed to reprogram
9201 	 * the TLB page sizes above, the process will start using this new
9202 	 * TSB right away; otherwise, it will start using it on the next
9203 	 * context switch.  Either way, it's no big deal so there's no
9204 	 * synchronization with the trap handlers here unless we grow the
9205 	 * TSB (in which case it's required to prevent using the old one
9206 	 * after it's freed). Note: second tsb is required for 32M/256M
9207 	 * page sizes.
9208 	 */
9209 	if (tte4m_cnt > sectsb_thresh) {
9210 		/*
9211 		 * If we're growing, select the size based on RSS.  If we're
9212 		 * shrinking, leave some room so we don't have to turn
9213 		 * around and grow again immediately.
9214 		 */
9215 		if (growing)
9216 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt);
9217 		else
9218 			tsb_szc = SELECT_TSB_SIZECODE(tte4m_cnt << 1);
9219 		if (tsbinfop->tsb_next == NULL) {
9220 			struct tsb_info *newtsb;
9221 			int allocflags = SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)?
9222 			    0 : TSB_ALLOC;
9223 
9224 			sfmmu_hat_exit(hatlockp);
9225 
9226 			/*
9227 			 * Try to allocate a TSB for 4[32|256]M pages.  If we
9228 			 * can't get the size we want, retry w/a minimum sized
9229 			 * TSB.  If that still didn't work, give up; we can
9230 			 * still run without one.
9231 			 */
9232 			tsb_bits = (mmu_page_sizes == max_mmu_page_sizes)?
9233 			    TSB4M|TSB32M|TSB256M:TSB4M;
9234 			if ((sfmmu_tsbinfo_alloc(&newtsb, tsb_szc, tsb_bits,
9235 			    allocflags, sfmmup) != 0) &&
9236 			    (sfmmu_tsbinfo_alloc(&newtsb, TSB_MIN_SZCODE,
9237 			    tsb_bits, allocflags, sfmmup) != 0)) {
9238 				return;
9239 			}
9240 
9241 			hatlockp = sfmmu_hat_enter(sfmmup);
9242 
9243 			if (sfmmup->sfmmu_tsb->tsb_next == NULL) {
9244 				sfmmup->sfmmu_tsb->tsb_next = newtsb;
9245 				SFMMU_STAT(sf_tsb_sectsb_create);
9246 				sfmmu_setup_tsbinfo(sfmmup);
9247 				sfmmu_hat_exit(hatlockp);
9248 				return;
9249 			} else {
9250 				/*
9251 				 * It's annoying, but possible for us
9252 				 * to get here.. we dropped the HAT lock
9253 				 * because of locking order in the kmem
9254 				 * allocator, and while we were off getting
9255 				 * our memory, some other thread decided to
9256 				 * do us a favor and won the race to get a
9257 				 * second TSB for this process.  Sigh.
9258 				 */
9259 				sfmmu_hat_exit(hatlockp);
9260 				sfmmu_tsbinfo_free(newtsb);
9261 				return;
9262 			}
9263 		}
9264 
9265 		/*
9266 		 * We have a second TSB, see if it's big enough.
9267 		 */
9268 		tsbinfop = tsbinfop->tsb_next;
9269 
9270 		/*
9271 		 * Check to see if our second TSB is the right size;
9272 		 * we may need to grow or shrink it.
9273 		 * To prevent thrashing (e.g. growing the TSB on a
9274 		 * subsequent map operation), only try to shrink if
9275 		 * the TSB reach exceeds twice the virtual address
9276 		 * space size.
9277 		 */
9278 		if (!growing && (tsb_szc < tsbinfop->tsb_szc) &&
9279 		    (tsb_szc >= default_tsb_size) && TSB_OK_SHRINK()) {
9280 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
9281 			    tsb_szc, hatlockp, TSB_SHRINK);
9282 		} else if (growing && tsb_szc > tsbinfop->tsb_szc &&
9283 		    TSB_OK_GROW()) {
9284 			(void) sfmmu_replace_tsb(sfmmup, tsbinfop,
9285 			    tsb_szc, hatlockp, TSB_GROW);
9286 		}
9287 	}
9288 
9289 	sfmmu_hat_exit(hatlockp);
9290 }
9291 
9292 /*
9293  * Get the preferred page size code for a hat.
9294  * This is only advice, so locking is not done;
9295  * this transitory information could change
9296  * following the call anyway.  This interface is
9297  * sun4 private.
9298  */
9299 /*ARGSUSED*/
9300 uint_t
9301 hat_preferred_pgsz(struct hat *hat, caddr_t vaddr, size_t maplen, int maptype)
9302 {
9303 	sfmmu_t *sfmmup = (sfmmu_t *)hat;
9304 	uint_t szc, maxszc = mmu_page_sizes - 1;
9305 	size_t pgsz;
9306 
9307 	if (maptype == MAPPGSZ_ISM) {
9308 		for (szc = maxszc; szc >= TTE4M; szc--) {
9309 			if (disable_ism_large_pages & (1 << szc))
9310 				continue;
9311 
9312 			pgsz = hw_page_array[szc].hp_size;
9313 			if ((maplen >= pgsz) && IS_P2ALIGNED(vaddr, pgsz))
9314 				return (szc);
9315 		}
9316 		return (TTE4M);
9317 	} else if (&mmu_preferred_pgsz) { /* USIII+-USIV+ */
9318 		return (mmu_preferred_pgsz(sfmmup, vaddr, maplen));
9319 	} else {	/* USIII, USII, Niagara */
9320 		for (szc = maxszc; szc > TTE8K; szc--) {
9321 			if (disable_large_pages & (1 << szc))
9322 				continue;
9323 
9324 			pgsz = hw_page_array[szc].hp_size;
9325 			if ((maplen >= pgsz) && IS_P2ALIGNED(vaddr, pgsz))
9326 				return (szc);
9327 		}
9328 		return (TTE8K);
9329 	}
9330 }
9331 
9332 /*
9333  * Free up a sfmmu
9334  * Since the sfmmu is currently embedded in the hat struct we simply zero
9335  * out our fields and free up the ism map blk list if any.
9336  */
9337 static void
9338 sfmmu_free_sfmmu(sfmmu_t *sfmmup)
9339 {
9340 	ism_blk_t	*blkp, *nx_blkp;
9341 #ifdef	DEBUG
9342 	ism_map_t	*map;
9343 	int 		i;
9344 #endif
9345 
9346 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
9347 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
9348 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
9349 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
9350 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
9351 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
9352 
9353 	sfmmup->sfmmu_free = 0;
9354 	sfmmup->sfmmu_ismhat = 0;
9355 
9356 	blkp = sfmmup->sfmmu_iblk;
9357 	sfmmup->sfmmu_iblk = NULL;
9358 
9359 	while (blkp) {
9360 #ifdef	DEBUG
9361 		map = blkp->iblk_maps;
9362 		for (i = 0; i < ISM_MAP_SLOTS; i++) {
9363 			ASSERT(map[i].imap_seg == 0);
9364 			ASSERT(map[i].imap_ismhat == NULL);
9365 			ASSERT(map[i].imap_ment == NULL);
9366 		}
9367 #endif
9368 		nx_blkp = blkp->iblk_next;
9369 		blkp->iblk_next = NULL;
9370 		blkp->iblk_nextpa = (uint64_t)-1;
9371 		kmem_cache_free(ism_blk_cache, blkp);
9372 		blkp = nx_blkp;
9373 	}
9374 }
9375 
9376 /*
9377  * Locking primitves accessed by HATLOCK macros
9378  */
9379 
9380 #define	SFMMU_SPL_MTX	(0x0)
9381 #define	SFMMU_ML_MTX	(0x1)
9382 
9383 #define	SFMMU_MLSPL_MTX(type, pg)	(((type) == SFMMU_SPL_MTX) ? \
9384 					    SPL_HASH(pg) : MLIST_HASH(pg))
9385 
9386 kmutex_t *
9387 sfmmu_page_enter(struct page *pp)
9388 {
9389 	return (sfmmu_mlspl_enter(pp, SFMMU_SPL_MTX));
9390 }
9391 
9392 void
9393 sfmmu_page_exit(kmutex_t *spl)
9394 {
9395 	mutex_exit(spl);
9396 }
9397 
9398 int
9399 sfmmu_page_spl_held(struct page *pp)
9400 {
9401 	return (sfmmu_mlspl_held(pp, SFMMU_SPL_MTX));
9402 }
9403 
9404 kmutex_t *
9405 sfmmu_mlist_enter(struct page *pp)
9406 {
9407 	return (sfmmu_mlspl_enter(pp, SFMMU_ML_MTX));
9408 }
9409 
9410 void
9411 sfmmu_mlist_exit(kmutex_t *mml)
9412 {
9413 	mutex_exit(mml);
9414 }
9415 
9416 int
9417 sfmmu_mlist_held(struct page *pp)
9418 {
9419 
9420 	return (sfmmu_mlspl_held(pp, SFMMU_ML_MTX));
9421 }
9422 
9423 /*
9424  * Common code for sfmmu_mlist_enter() and sfmmu_page_enter().  For
9425  * sfmmu_mlist_enter() case mml_table lock array is used and for
9426  * sfmmu_page_enter() sfmmu_page_lock lock array is used.
9427  *
9428  * The lock is taken on a root page so that it protects an operation on all
9429  * constituent pages of a large page pp belongs to.
9430  *
9431  * The routine takes a lock from the appropriate array. The lock is determined
9432  * by hashing the root page. After taking the lock this routine checks if the
9433  * root page has the same size code that was used to determine the root (i.e
9434  * that root hasn't changed).  If root page has the expected p_szc field we
9435  * have the right lock and it's returned to the caller. If root's p_szc
9436  * decreased we release the lock and retry from the beginning.  This case can
9437  * happen due to hat_page_demote() decreasing p_szc between our load of p_szc
9438  * value and taking the lock. The number of retries due to p_szc decrease is
9439  * limited by the maximum p_szc value. If p_szc is 0 we return the lock
9440  * determined by hashing pp itself.
9441  *
9442  * If our caller doesn't hold a SE_SHARED or SE_EXCL lock on pp it's also
9443  * possible that p_szc can increase. To increase p_szc a thread has to lock
9444  * all constituent pages EXCL and do hat_pageunload() on all of them. All the
9445  * callers that don't hold a page locked recheck if hmeblk through which pp
9446  * was found still maps this pp.  If it doesn't map it anymore returned lock
9447  * is immediately dropped. Therefore if sfmmu_mlspl_enter() hits the case of
9448  * p_szc increase after taking the lock it returns this lock without further
9449  * retries because in this case the caller doesn't care about which lock was
9450  * taken. The caller will drop it right away.
9451  *
9452  * After the routine returns it's guaranteed that hat_page_demote() can't
9453  * change p_szc field of any of constituent pages of a large page pp belongs
9454  * to as long as pp was either locked at least SHARED prior to this call or
9455  * the caller finds that hment that pointed to this pp still references this
9456  * pp (this also assumes that the caller holds hme hash bucket lock so that
9457  * the same pp can't be remapped into the same hmeblk after it was unmapped by
9458  * hat_pageunload()).
9459  */
9460 static kmutex_t *
9461 sfmmu_mlspl_enter(struct page *pp, int type)
9462 {
9463 	kmutex_t	*mtx;
9464 	uint_t		prev_rszc = UINT_MAX;
9465 	page_t		*rootpp;
9466 	uint_t		szc;
9467 	uint_t		rszc;
9468 	uint_t		pszc = pp->p_szc;
9469 
9470 	ASSERT(pp != NULL);
9471 
9472 again:
9473 	if (pszc == 0) {
9474 		mtx = SFMMU_MLSPL_MTX(type, pp);
9475 		mutex_enter(mtx);
9476 		return (mtx);
9477 	}
9478 
9479 	/* The lock lives in the root page */
9480 	rootpp = PP_GROUPLEADER(pp, pszc);
9481 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
9482 	mutex_enter(mtx);
9483 
9484 	/*
9485 	 * Return mml in the following 3 cases:
9486 	 *
9487 	 * 1) If pp itself is root since if its p_szc decreased before we took
9488 	 * the lock pp is still the root of smaller szc page. And if its p_szc
9489 	 * increased it doesn't matter what lock we return (see comment in
9490 	 * front of this routine).
9491 	 *
9492 	 * 2) If pp's not root but rootpp is the root of a rootpp->p_szc size
9493 	 * large page we have the right lock since any previous potential
9494 	 * hat_page_demote() is done demoting from greater than current root's
9495 	 * p_szc because hat_page_demote() changes root's p_szc last. No
9496 	 * further hat_page_demote() can start or be in progress since it
9497 	 * would need the same lock we currently hold.
9498 	 *
9499 	 * 3) If rootpp's p_szc increased since previous iteration it doesn't
9500 	 * matter what lock we return (see comment in front of this routine).
9501 	 */
9502 	if (pp == rootpp || (rszc = rootpp->p_szc) == pszc ||
9503 	    rszc >= prev_rszc) {
9504 		return (mtx);
9505 	}
9506 
9507 	/*
9508 	 * hat_page_demote() could have decreased root's p_szc.
9509 	 * In this case pp's p_szc must also be smaller than pszc.
9510 	 * Retry.
9511 	 */
9512 	if (rszc < pszc) {
9513 		szc = pp->p_szc;
9514 		if (szc < pszc) {
9515 			mutex_exit(mtx);
9516 			pszc = szc;
9517 			goto again;
9518 		}
9519 		/*
9520 		 * pp's p_szc increased after it was decreased.
9521 		 * page cannot be mapped. Return current lock. The caller
9522 		 * will drop it right away.
9523 		 */
9524 		return (mtx);
9525 	}
9526 
9527 	/*
9528 	 * root's p_szc is greater than pp's p_szc.
9529 	 * hat_page_demote() is not done with all pages
9530 	 * yet. Wait for it to complete.
9531 	 */
9532 	mutex_exit(mtx);
9533 	rootpp = PP_GROUPLEADER(rootpp, rszc);
9534 	mtx = SFMMU_MLSPL_MTX(type, rootpp);
9535 	mutex_enter(mtx);
9536 	mutex_exit(mtx);
9537 	prev_rszc = rszc;
9538 	goto again;
9539 }
9540 
9541 static int
9542 sfmmu_mlspl_held(struct page *pp, int type)
9543 {
9544 	kmutex_t	*mtx;
9545 
9546 	ASSERT(pp != NULL);
9547 	/* The lock lives in the root page */
9548 	pp = PP_PAGEROOT(pp);
9549 	ASSERT(pp != NULL);
9550 
9551 	mtx = SFMMU_MLSPL_MTX(type, pp);
9552 	return (MUTEX_HELD(mtx));
9553 }
9554 
9555 static uint_t
9556 sfmmu_get_free_hblk(struct hme_blk **hmeblkpp, uint_t critical)
9557 {
9558 	struct  hme_blk *hblkp;
9559 
9560 	if (freehblkp != NULL) {
9561 		mutex_enter(&freehblkp_lock);
9562 		if (freehblkp != NULL) {
9563 			/*
9564 			 * If the current thread is owning hblk_reserve,
9565 			 * let it succede even if freehblkcnt is really low.
9566 			 */
9567 			if (freehblkcnt <= HBLK_RESERVE_MIN && !critical) {
9568 				SFMMU_STAT(sf_get_free_throttle);
9569 				mutex_exit(&freehblkp_lock);
9570 				return (0);
9571 			}
9572 			freehblkcnt--;
9573 			*hmeblkpp = freehblkp;
9574 			hblkp = *hmeblkpp;
9575 			freehblkp = hblkp->hblk_next;
9576 			mutex_exit(&freehblkp_lock);
9577 			hblkp->hblk_next = NULL;
9578 			SFMMU_STAT(sf_get_free_success);
9579 			return (1);
9580 		}
9581 		mutex_exit(&freehblkp_lock);
9582 	}
9583 	SFMMU_STAT(sf_get_free_fail);
9584 	return (0);
9585 }
9586 
9587 static uint_t
9588 sfmmu_put_free_hblk(struct hme_blk *hmeblkp, uint_t critical)
9589 {
9590 	struct  hme_blk *hblkp;
9591 
9592 	/*
9593 	 * If the current thread is mapping into kernel space,
9594 	 * let it succede even if freehblkcnt is max
9595 	 * so that it will avoid freeing it to kmem.
9596 	 * This will prevent stack overflow due to
9597 	 * possible recursion since kmem_cache_free()
9598 	 * might require creation of a slab which
9599 	 * in turn needs an hmeblk to map that slab;
9600 	 * let's break this vicious chain at the first
9601 	 * opportunity.
9602 	 */
9603 	if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
9604 		mutex_enter(&freehblkp_lock);
9605 		if (freehblkcnt < HBLK_RESERVE_CNT || critical) {
9606 			SFMMU_STAT(sf_put_free_success);
9607 			freehblkcnt++;
9608 			hmeblkp->hblk_next = freehblkp;
9609 			freehblkp = hmeblkp;
9610 			mutex_exit(&freehblkp_lock);
9611 			return (1);
9612 		}
9613 		mutex_exit(&freehblkp_lock);
9614 	}
9615 
9616 	/*
9617 	 * Bring down freehblkcnt to HBLK_RESERVE_CNT. We are here
9618 	 * only if freehblkcnt is at least HBLK_RESERVE_CNT *and*
9619 	 * we are not in the process of mapping into kernel space.
9620 	 */
9621 	ASSERT(!critical);
9622 	while (freehblkcnt > HBLK_RESERVE_CNT) {
9623 		mutex_enter(&freehblkp_lock);
9624 		if (freehblkcnt > HBLK_RESERVE_CNT) {
9625 			freehblkcnt--;
9626 			hblkp = freehblkp;
9627 			freehblkp = hblkp->hblk_next;
9628 			mutex_exit(&freehblkp_lock);
9629 			ASSERT(get_hblk_cache(hblkp) == sfmmu8_cache);
9630 			kmem_cache_free(sfmmu8_cache, hblkp);
9631 			continue;
9632 		}
9633 		mutex_exit(&freehblkp_lock);
9634 	}
9635 	SFMMU_STAT(sf_put_free_fail);
9636 	return (0);
9637 }
9638 
9639 static void
9640 sfmmu_hblk_swap(struct hme_blk *new)
9641 {
9642 	struct hme_blk *old, *hblkp, *prev;
9643 	uint64_t hblkpa, prevpa, newpa;
9644 	caddr_t	base, vaddr, endaddr;
9645 	struct hmehash_bucket *hmebp;
9646 	struct sf_hment *osfhme, *nsfhme;
9647 	page_t *pp;
9648 	kmutex_t *pml;
9649 	tte_t tte;
9650 
9651 #ifdef	DEBUG
9652 	hmeblk_tag		hblktag;
9653 	struct hme_blk		*found;
9654 #endif
9655 	old = HBLK_RESERVE;
9656 
9657 	/*
9658 	 * save pa before bcopy clobbers it
9659 	 */
9660 	newpa = new->hblk_nextpa;
9661 
9662 	base = (caddr_t)get_hblk_base(old);
9663 	endaddr = base + get_hblk_span(old);
9664 
9665 	/*
9666 	 * acquire hash bucket lock.
9667 	 */
9668 	hmebp = sfmmu_tteload_acquire_hashbucket(ksfmmup, base, TTE8K);
9669 
9670 	/*
9671 	 * copy contents from old to new
9672 	 */
9673 	bcopy((void *)old, (void *)new, HME8BLK_SZ);
9674 
9675 	/*
9676 	 * add new to hash chain
9677 	 */
9678 	sfmmu_hblk_hash_add(hmebp, new, newpa);
9679 
9680 	/*
9681 	 * search hash chain for hblk_reserve; this needs to be performed
9682 	 * after adding new, otherwise prevpa and prev won't correspond
9683 	 * to the hblk which is prior to old in hash chain when we call
9684 	 * sfmmu_hblk_hash_rm to remove old later.
9685 	 */
9686 	for (prevpa = 0, prev = NULL,
9687 	    hblkpa = hmebp->hmeh_nextpa, hblkp = hmebp->hmeblkp;
9688 	    hblkp != NULL && hblkp != old;
9689 	    prevpa = hblkpa, prev = hblkp,
9690 	    hblkpa = hblkp->hblk_nextpa, hblkp = hblkp->hblk_next);
9691 
9692 	if (hblkp != old)
9693 		panic("sfmmu_hblk_swap: hblk_reserve not found");
9694 
9695 	/*
9696 	 * p_mapping list is still pointing to hments in hblk_reserve;
9697 	 * fix up p_mapping list so that they point to hments in new.
9698 	 *
9699 	 * Since all these mappings are created by hblk_reserve_thread
9700 	 * on the way and it's using at least one of the buffers from each of
9701 	 * the newly minted slabs, there is no danger of any of these
9702 	 * mappings getting unloaded by another thread.
9703 	 *
9704 	 * tsbmiss could only modify ref/mod bits of hments in old/new.
9705 	 * Since all of these hments hold mappings established by segkmem
9706 	 * and mappings in segkmem are setup with HAT_NOSYNC, ref/mod bits
9707 	 * have no meaning for the mappings in hblk_reserve.  hments in
9708 	 * old and new are identical except for ref/mod bits.
9709 	 */
9710 	for (vaddr = base; vaddr < endaddr; vaddr += TTEBYTES(TTE8K)) {
9711 
9712 		HBLKTOHME(osfhme, old, vaddr);
9713 		sfmmu_copytte(&osfhme->hme_tte, &tte);
9714 
9715 		if (TTE_IS_VALID(&tte)) {
9716 			if ((pp = osfhme->hme_page) == NULL)
9717 				panic("sfmmu_hblk_swap: page not mapped");
9718 
9719 			pml = sfmmu_mlist_enter(pp);
9720 
9721 			if (pp != osfhme->hme_page)
9722 				panic("sfmmu_hblk_swap: mapping changed");
9723 
9724 			HBLKTOHME(nsfhme, new, vaddr);
9725 
9726 			HME_ADD(nsfhme, pp);
9727 			HME_SUB(osfhme, pp);
9728 
9729 			sfmmu_mlist_exit(pml);
9730 		}
9731 	}
9732 
9733 	/*
9734 	 * remove old from hash chain
9735 	 */
9736 	sfmmu_hblk_hash_rm(hmebp, old, prevpa, prev);
9737 
9738 #ifdef	DEBUG
9739 
9740 	hblktag.htag_id = ksfmmup;
9741 	hblktag.htag_bspage = HME_HASH_BSPAGE(base, HME_HASH_SHIFT(TTE8K));
9742 	hblktag.htag_rehash = HME_HASH_REHASH(TTE8K);
9743 	HME_HASH_FAST_SEARCH(hmebp, hblktag, found);
9744 
9745 	if (found != new)
9746 		panic("sfmmu_hblk_swap: new hblk not found");
9747 #endif
9748 
9749 	SFMMU_HASH_UNLOCK(hmebp);
9750 
9751 	/*
9752 	 * Reset hblk_reserve
9753 	 */
9754 	bzero((void *)old, HME8BLK_SZ);
9755 	old->hblk_nextpa = va_to_pa((caddr_t)old);
9756 }
9757 
9758 /*
9759  * Grab the mlist mutex for both pages passed in.
9760  *
9761  * low and high will be returned as pointers to the mutexes for these pages.
9762  * low refers to the mutex residing in the lower bin of the mlist hash, while
9763  * high refers to the mutex residing in the higher bin of the mlist hash.  This
9764  * is due to the locking order restrictions on the same thread grabbing
9765  * multiple mlist mutexes.  The low lock must be acquired before the high lock.
9766  *
9767  * If both pages hash to the same mutex, only grab that single mutex, and
9768  * high will be returned as NULL
9769  * If the pages hash to different bins in the hash, grab the lower addressed
9770  * lock first and then the higher addressed lock in order to follow the locking
9771  * rules involved with the same thread grabbing multiple mlist mutexes.
9772  * low and high will both have non-NULL values.
9773  */
9774 static void
9775 sfmmu_mlist_reloc_enter(struct page *targ, struct page *repl,
9776     kmutex_t **low, kmutex_t **high)
9777 {
9778 	kmutex_t	*mml_targ, *mml_repl;
9779 
9780 	/*
9781 	 * no need to do the dance around szc as in sfmmu_mlist_enter()
9782 	 * because this routine is only called by hat_page_relocate() and all
9783 	 * targ and repl pages are already locked EXCL so szc can't change.
9784 	 */
9785 
9786 	mml_targ = MLIST_HASH(PP_PAGEROOT(targ));
9787 	mml_repl = MLIST_HASH(PP_PAGEROOT(repl));
9788 
9789 	if (mml_targ == mml_repl) {
9790 		*low = mml_targ;
9791 		*high = NULL;
9792 	} else {
9793 		if (mml_targ < mml_repl) {
9794 			*low = mml_targ;
9795 			*high = mml_repl;
9796 		} else {
9797 			*low = mml_repl;
9798 			*high = mml_targ;
9799 		}
9800 	}
9801 
9802 	mutex_enter(*low);
9803 	if (*high)
9804 		mutex_enter(*high);
9805 }
9806 
9807 static void
9808 sfmmu_mlist_reloc_exit(kmutex_t *low, kmutex_t *high)
9809 {
9810 	if (high)
9811 		mutex_exit(high);
9812 	mutex_exit(low);
9813 }
9814 
9815 static hatlock_t *
9816 sfmmu_hat_enter(sfmmu_t *sfmmup)
9817 {
9818 	hatlock_t	*hatlockp;
9819 
9820 	if (sfmmup != ksfmmup) {
9821 		hatlockp = TSB_HASH(sfmmup);
9822 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
9823 		return (hatlockp);
9824 	}
9825 	return (NULL);
9826 }
9827 
9828 static hatlock_t *
9829 sfmmu_hat_tryenter(sfmmu_t *sfmmup)
9830 {
9831 	hatlock_t	*hatlockp;
9832 
9833 	if (sfmmup != ksfmmup) {
9834 		hatlockp = TSB_HASH(sfmmup);
9835 		if (mutex_tryenter(HATLOCK_MUTEXP(hatlockp)) == 0)
9836 			return (NULL);
9837 		return (hatlockp);
9838 	}
9839 	return (NULL);
9840 }
9841 
9842 static void
9843 sfmmu_hat_exit(hatlock_t *hatlockp)
9844 {
9845 	if (hatlockp != NULL)
9846 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
9847 }
9848 
9849 static void
9850 sfmmu_hat_lock_all(void)
9851 {
9852 	int i;
9853 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
9854 		mutex_enter(HATLOCK_MUTEXP(&hat_lock[i]));
9855 }
9856 
9857 static void
9858 sfmmu_hat_unlock_all(void)
9859 {
9860 	int i;
9861 	for (i = SFMMU_NUM_LOCK - 1; i >= 0; i--)
9862 		mutex_exit(HATLOCK_MUTEXP(&hat_lock[i]));
9863 }
9864 
9865 int
9866 sfmmu_hat_lock_held(sfmmu_t *sfmmup)
9867 {
9868 	ASSERT(sfmmup != ksfmmup);
9869 	return (MUTEX_HELD(HATLOCK_MUTEXP(TSB_HASH(sfmmup))));
9870 }
9871 
9872 /*
9873  * Locking primitives to provide consistency between ISM unmap
9874  * and other operations.  Since ISM unmap can take a long time, we
9875  * use HAT_ISMBUSY flag (protected by the hatlock) to avoid creating
9876  * contention on the hatlock buckets while ISM segments are being
9877  * unmapped.  The tradeoff is that the flags don't prevent priority
9878  * inversion from occurring, so we must request kernel priority in
9879  * case we have to sleep to keep from getting buried while holding
9880  * the HAT_ISMBUSY flag set, which in turn could block other kernel
9881  * threads from running (for example, in sfmmu_uvatopfn()).
9882  */
9883 static void
9884 sfmmu_ismhat_enter(sfmmu_t *sfmmup, int hatlock_held)
9885 {
9886 	hatlock_t *hatlockp;
9887 
9888 	THREAD_KPRI_REQUEST();
9889 	if (!hatlock_held)
9890 		hatlockp = sfmmu_hat_enter(sfmmup);
9891 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY))
9892 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
9893 	SFMMU_FLAGS_SET(sfmmup, HAT_ISMBUSY);
9894 	if (!hatlock_held)
9895 		sfmmu_hat_exit(hatlockp);
9896 }
9897 
9898 static void
9899 sfmmu_ismhat_exit(sfmmu_t *sfmmup, int hatlock_held)
9900 {
9901 	hatlock_t *hatlockp;
9902 
9903 	if (!hatlock_held)
9904 		hatlockp = sfmmu_hat_enter(sfmmup);
9905 	ASSERT(SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY));
9906 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_ISMBUSY);
9907 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
9908 	if (!hatlock_held)
9909 		sfmmu_hat_exit(hatlockp);
9910 	THREAD_KPRI_RELEASE();
9911 }
9912 
9913 /*
9914  *
9915  * Algorithm:
9916  *
9917  * (1) if segkmem is not ready, allocate hblk from an array of pre-alloc'ed
9918  *	hblks.
9919  *
9920  * (2) if we are allocating an hblk for mapping a slab in sfmmu_cache,
9921  *
9922  * 		(a) try to return an hblk from reserve pool of free hblks;
9923  *		(b) if the reserve pool is empty, acquire hblk_reserve_lock
9924  *		    and return hblk_reserve.
9925  *
9926  * (3) call kmem_cache_alloc() to allocate hblk;
9927  *
9928  *		(a) if hblk_reserve_lock is held by the current thread,
9929  *		    atomically replace hblk_reserve by the hblk that is
9930  *		    returned by kmem_cache_alloc; release hblk_reserve_lock
9931  *		    and call kmem_cache_alloc() again.
9932  *		(b) if reserve pool is not full, add the hblk that is
9933  *		    returned by kmem_cache_alloc to reserve pool and
9934  *		    call kmem_cache_alloc again.
9935  *
9936  */
9937 static struct hme_blk *
9938 sfmmu_hblk_alloc(sfmmu_t *sfmmup, caddr_t vaddr,
9939 	struct hmehash_bucket *hmebp, uint_t size, hmeblk_tag hblktag,
9940 	uint_t flags)
9941 {
9942 	struct hme_blk *hmeblkp = NULL;
9943 	struct hme_blk *newhblkp;
9944 	struct hme_blk *shw_hblkp = NULL;
9945 	struct kmem_cache *sfmmu_cache = NULL;
9946 	uint64_t hblkpa;
9947 	ulong_t index;
9948 	uint_t owner;		/* set to 1 if using hblk_reserve */
9949 	uint_t forcefree;
9950 	int sleep;
9951 
9952 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
9953 
9954 	/*
9955 	 * If segkmem is not created yet, allocate from static hmeblks
9956 	 * created at the end of startup_modules().  See the block comment
9957 	 * in startup_modules() describing how we estimate the number of
9958 	 * static hmeblks that will be needed during re-map.
9959 	 */
9960 	if (!hblk_alloc_dynamic) {
9961 
9962 		if (size == TTE8K) {
9963 			index = nucleus_hblk8.index;
9964 			if (index >= nucleus_hblk8.len) {
9965 				/*
9966 				 * If we panic here, see startup_modules() to
9967 				 * make sure that we are calculating the
9968 				 * number of hblk8's that we need correctly.
9969 				 */
9970 				panic("no nucleus hblk8 to allocate");
9971 			}
9972 			hmeblkp =
9973 			    (struct hme_blk *)&nucleus_hblk8.list[index];
9974 			nucleus_hblk8.index++;
9975 			SFMMU_STAT(sf_hblk8_nalloc);
9976 		} else {
9977 			index = nucleus_hblk1.index;
9978 			if (nucleus_hblk1.index >= nucleus_hblk1.len) {
9979 				/*
9980 				 * If we panic here, see startup_modules()
9981 				 * and H8TOH1; most likely you need to
9982 				 * update the calculation of the number
9983 				 * of hblk1's the kernel needs to boot.
9984 				 */
9985 				panic("no nucleus hblk1 to allocate");
9986 			}
9987 			hmeblkp =
9988 			    (struct hme_blk *)&nucleus_hblk1.list[index];
9989 			nucleus_hblk1.index++;
9990 			SFMMU_STAT(sf_hblk1_nalloc);
9991 		}
9992 
9993 		goto hblk_init;
9994 	}
9995 
9996 	SFMMU_HASH_UNLOCK(hmebp);
9997 
9998 	if (sfmmup != KHATID) {
9999 		if (mmu_page_sizes == max_mmu_page_sizes) {
10000 			if (size < TTE256M)
10001 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
10002 				    size, flags);
10003 		} else {
10004 			if (size < TTE4M)
10005 				shw_hblkp = sfmmu_shadow_hcreate(sfmmup, vaddr,
10006 				    size, flags);
10007 		}
10008 	}
10009 
10010 fill_hblk:
10011 	owner = (hblk_reserve_thread == curthread) ? 1 : 0;
10012 
10013 	if (owner && size == TTE8K) {
10014 
10015 		/*
10016 		 * We are really in a tight spot. We already own
10017 		 * hblk_reserve and we need another hblk.  In anticipation
10018 		 * of this kind of scenario, we specifically set aside
10019 		 * HBLK_RESERVE_MIN number of hblks to be used exclusively
10020 		 * by owner of hblk_reserve.
10021 		 */
10022 		SFMMU_STAT(sf_hblk_recurse_cnt);
10023 
10024 		if (!sfmmu_get_free_hblk(&hmeblkp, 1))
10025 			panic("sfmmu_hblk_alloc: reserve list is empty");
10026 
10027 		goto hblk_verify;
10028 	}
10029 
10030 	ASSERT(!owner);
10031 
10032 	if ((flags & HAT_NO_KALLOC) == 0) {
10033 
10034 		sfmmu_cache = ((size == TTE8K) ? sfmmu8_cache : sfmmu1_cache);
10035 		sleep = ((sfmmup == KHATID) ? KM_NOSLEEP : KM_SLEEP);
10036 
10037 		if ((hmeblkp = kmem_cache_alloc(sfmmu_cache, sleep)) == NULL) {
10038 			hmeblkp = sfmmu_hblk_steal(size);
10039 		} else {
10040 			/*
10041 			 * if we are the owner of hblk_reserve,
10042 			 * swap hblk_reserve with hmeblkp and
10043 			 * start a fresh life.  Hope things go
10044 			 * better this time.
10045 			 */
10046 			if (hblk_reserve_thread == curthread) {
10047 				ASSERT(sfmmu_cache == sfmmu8_cache);
10048 				sfmmu_hblk_swap(hmeblkp);
10049 				hblk_reserve_thread = NULL;
10050 				mutex_exit(&hblk_reserve_lock);
10051 				goto fill_hblk;
10052 			}
10053 			/*
10054 			 * let's donate this hblk to our reserve list if
10055 			 * we are not mapping kernel range
10056 			 */
10057 			if (size == TTE8K && sfmmup != KHATID)
10058 				if (sfmmu_put_free_hblk(hmeblkp, 0))
10059 					goto fill_hblk;
10060 		}
10061 	} else {
10062 		/*
10063 		 * We are here to map the slab in sfmmu8_cache; let's
10064 		 * check if we could tap our reserve list; if successful,
10065 		 * this will avoid the pain of going thru sfmmu_hblk_swap
10066 		 */
10067 		SFMMU_STAT(sf_hblk_slab_cnt);
10068 		if (!sfmmu_get_free_hblk(&hmeblkp, 0)) {
10069 			/*
10070 			 * let's start hblk_reserve dance
10071 			 */
10072 			SFMMU_STAT(sf_hblk_reserve_cnt);
10073 			owner = 1;
10074 			mutex_enter(&hblk_reserve_lock);
10075 			hmeblkp = HBLK_RESERVE;
10076 			hblk_reserve_thread = curthread;
10077 		}
10078 	}
10079 
10080 hblk_verify:
10081 	ASSERT(hmeblkp != NULL);
10082 	set_hblk_sz(hmeblkp, size);
10083 	ASSERT(hmeblkp->hblk_nextpa == va_to_pa((caddr_t)hmeblkp));
10084 	SFMMU_HASH_LOCK(hmebp);
10085 	HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
10086 	if (newhblkp != NULL) {
10087 		SFMMU_HASH_UNLOCK(hmebp);
10088 		if (hmeblkp != HBLK_RESERVE) {
10089 			/*
10090 			 * This is really tricky!
10091 			 *
10092 			 * vmem_alloc(vmem_seg_arena)
10093 			 *  vmem_alloc(vmem_internal_arena)
10094 			 *   segkmem_alloc(heap_arena)
10095 			 *    vmem_alloc(heap_arena)
10096 			 *    page_create()
10097 			 *    hat_memload()
10098 			 *	kmem_cache_free()
10099 			 *	 kmem_cache_alloc()
10100 			 *	  kmem_slab_create()
10101 			 *	   vmem_alloc(kmem_internal_arena)
10102 			 *	    segkmem_alloc(heap_arena)
10103 			 *		vmem_alloc(heap_arena)
10104 			 *		page_create()
10105 			 *		hat_memload()
10106 			 *		  kmem_cache_free()
10107 			 *		...
10108 			 *
10109 			 * Thus, hat_memload() could call kmem_cache_free
10110 			 * for enough number of times that we could easily
10111 			 * hit the bottom of the stack or run out of reserve
10112 			 * list of vmem_seg structs.  So, we must donate
10113 			 * this hblk to reserve list if it's allocated
10114 			 * from sfmmu8_cache *and* mapping kernel range.
10115 			 * We don't need to worry about freeing hmeblk1's
10116 			 * to kmem since they don't map any kmem slabs.
10117 			 *
10118 			 * Note: When segkmem supports largepages, we must
10119 			 * free hmeblk1's to reserve list as well.
10120 			 */
10121 			forcefree = (sfmmup == KHATID) ? 1 : 0;
10122 			if (size == TTE8K &&
10123 			    sfmmu_put_free_hblk(hmeblkp, forcefree)) {
10124 				goto re_verify;
10125 			}
10126 			ASSERT(sfmmup != KHATID);
10127 			kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
10128 		} else {
10129 			/*
10130 			 * Hey! we don't need hblk_reserve any more.
10131 			 */
10132 			ASSERT(owner);
10133 			hblk_reserve_thread = NULL;
10134 			mutex_exit(&hblk_reserve_lock);
10135 			owner = 0;
10136 		}
10137 re_verify:
10138 		/*
10139 		 * let's check if the goodies are still present
10140 		 */
10141 		SFMMU_HASH_LOCK(hmebp);
10142 		HME_HASH_FAST_SEARCH(hmebp, hblktag, newhblkp);
10143 		if (newhblkp != NULL) {
10144 			/*
10145 			 * return newhblkp if it's not hblk_reserve;
10146 			 * if newhblkp is hblk_reserve, return it
10147 			 * _only if_ we are the owner of hblk_reserve.
10148 			 */
10149 			if (newhblkp != HBLK_RESERVE || owner) {
10150 				return (newhblkp);
10151 			} else {
10152 				/*
10153 				 * we just hit hblk_reserve in the hash and
10154 				 * we are not the owner of that;
10155 				 *
10156 				 * block until hblk_reserve_thread completes
10157 				 * swapping hblk_reserve and try the dance
10158 				 * once again.
10159 				 */
10160 				SFMMU_HASH_UNLOCK(hmebp);
10161 				mutex_enter(&hblk_reserve_lock);
10162 				mutex_exit(&hblk_reserve_lock);
10163 				SFMMU_STAT(sf_hblk_reserve_hit);
10164 				goto fill_hblk;
10165 			}
10166 		} else {
10167 			/*
10168 			 * it's no more! try the dance once again.
10169 			 */
10170 			SFMMU_HASH_UNLOCK(hmebp);
10171 			goto fill_hblk;
10172 		}
10173 	}
10174 
10175 hblk_init:
10176 	set_hblk_sz(hmeblkp, size);
10177 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
10178 	hmeblkp->hblk_next = (struct hme_blk *)NULL;
10179 	hmeblkp->hblk_tag = hblktag;
10180 	hmeblkp->hblk_shadow = shw_hblkp;
10181 	hblkpa = hmeblkp->hblk_nextpa;
10182 	hmeblkp->hblk_nextpa = 0;
10183 
10184 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
10185 	ASSERT(get_hblk_span(hmeblkp) == HMEBLK_SPAN(size));
10186 	ASSERT(hmeblkp->hblk_hmecnt == 0);
10187 	ASSERT(hmeblkp->hblk_vcnt == 0);
10188 	ASSERT(hmeblkp->hblk_lckcnt == 0);
10189 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
10190 	sfmmu_hblk_hash_add(hmebp, hmeblkp, hblkpa);
10191 	return (hmeblkp);
10192 }
10193 
10194 /*
10195  * This function performs any cleanup required on the hme_blk
10196  * and returns it to the free list.
10197  */
10198 /* ARGSUSED */
10199 static void
10200 sfmmu_hblk_free(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
10201 	uint64_t hblkpa, struct hme_blk **listp)
10202 {
10203 	int shw_size, vshift;
10204 	struct hme_blk *shw_hblkp;
10205 	uint_t		shw_mask, newshw_mask;
10206 	uintptr_t	vaddr;
10207 	int		size;
10208 	uint_t		critical;
10209 
10210 	ASSERT(hmeblkp);
10211 	ASSERT(!hmeblkp->hblk_hmecnt);
10212 	ASSERT(!hmeblkp->hblk_vcnt);
10213 	ASSERT(!hmeblkp->hblk_lckcnt);
10214 	ASSERT(hblkpa == va_to_pa((caddr_t)hmeblkp));
10215 	ASSERT(hmeblkp != (struct hme_blk *)hblk_reserve);
10216 
10217 	critical = (hblktosfmmu(hmeblkp) == KHATID) ? 1 : 0;
10218 
10219 	size = get_hblk_ttesz(hmeblkp);
10220 	shw_hblkp = hmeblkp->hblk_shadow;
10221 	if (shw_hblkp) {
10222 		ASSERT(hblktosfmmu(hmeblkp) != KHATID);
10223 		if (mmu_page_sizes == max_mmu_page_sizes) {
10224 			ASSERT(size < TTE256M);
10225 		} else {
10226 			ASSERT(size < TTE4M);
10227 		}
10228 
10229 		shw_size = get_hblk_ttesz(shw_hblkp);
10230 		vaddr = get_hblk_base(hmeblkp);
10231 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
10232 		ASSERT(vshift < 8);
10233 		/*
10234 		 * Atomically clear shadow mask bit
10235 		 */
10236 		do {
10237 			shw_mask = shw_hblkp->hblk_shw_mask;
10238 			ASSERT(shw_mask & (1 << vshift));
10239 			newshw_mask = shw_mask & ~(1 << vshift);
10240 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
10241 				shw_mask, newshw_mask);
10242 		} while (newshw_mask != shw_mask);
10243 		hmeblkp->hblk_shadow = NULL;
10244 	}
10245 	hmeblkp->hblk_next = NULL;
10246 	hmeblkp->hblk_nextpa = hblkpa;
10247 	hmeblkp->hblk_shw_bit = 0;
10248 
10249 	if (hmeblkp->hblk_nuc_bit == 0) {
10250 
10251 		if (size == TTE8K && sfmmu_put_free_hblk(hmeblkp, critical))
10252 			return;
10253 
10254 		hmeblkp->hblk_next = *listp;
10255 		*listp = hmeblkp;
10256 	}
10257 }
10258 
10259 static void
10260 sfmmu_hblks_list_purge(struct hme_blk **listp)
10261 {
10262 	struct hme_blk	*hmeblkp;
10263 
10264 	while ((hmeblkp = *listp) != NULL) {
10265 		*listp = hmeblkp->hblk_next;
10266 		kmem_cache_free(get_hblk_cache(hmeblkp), hmeblkp);
10267 	}
10268 }
10269 
10270 #define	BUCKETS_TO_SEARCH_BEFORE_UNLOAD	30
10271 
10272 static uint_t sfmmu_hblk_steal_twice;
10273 static uint_t sfmmu_hblk_steal_count, sfmmu_hblk_steal_unload_count;
10274 
10275 /*
10276  * Steal a hmeblk
10277  * Enough hmeblks were allocated at startup (nucleus hmeblks) and also
10278  * hmeblks were added dynamically. We should never ever not be able to
10279  * find one. Look for an unused/unlocked hmeblk in user hash table.
10280  */
10281 static struct hme_blk *
10282 sfmmu_hblk_steal(int size)
10283 {
10284 	static struct hmehash_bucket *uhmehash_steal_hand = NULL;
10285 	struct hmehash_bucket *hmebp;
10286 	struct hme_blk *hmeblkp = NULL, *pr_hblk;
10287 	uint64_t hblkpa, prevpa;
10288 	int i;
10289 
10290 	for (;;) {
10291 		hmebp = (uhmehash_steal_hand == NULL) ? uhme_hash :
10292 			uhmehash_steal_hand;
10293 		ASSERT(hmebp >= uhme_hash && hmebp <= &uhme_hash[UHMEHASH_SZ]);
10294 
10295 		for (i = 0; hmeblkp == NULL && i <= UHMEHASH_SZ +
10296 		    BUCKETS_TO_SEARCH_BEFORE_UNLOAD; i++) {
10297 			SFMMU_HASH_LOCK(hmebp);
10298 			hmeblkp = hmebp->hmeblkp;
10299 			hblkpa = hmebp->hmeh_nextpa;
10300 			prevpa = 0;
10301 			pr_hblk = NULL;
10302 			while (hmeblkp) {
10303 				/*
10304 				 * check if it is a hmeblk that is not locked
10305 				 * and not shared. skip shadow hmeblks with
10306 				 * shadow_mask set i.e valid count non zero.
10307 				 */
10308 				if ((get_hblk_ttesz(hmeblkp) == size) &&
10309 				    (hmeblkp->hblk_shw_bit == 0 ||
10310 					hmeblkp->hblk_vcnt == 0) &&
10311 				    (hmeblkp->hblk_lckcnt == 0)) {
10312 					/*
10313 					 * there is a high probability that we
10314 					 * will find a free one. search some
10315 					 * buckets for a free hmeblk initially
10316 					 * before unloading a valid hmeblk.
10317 					 */
10318 					if ((hmeblkp->hblk_vcnt == 0 &&
10319 					    hmeblkp->hblk_hmecnt == 0) || (i >=
10320 					    BUCKETS_TO_SEARCH_BEFORE_UNLOAD)) {
10321 						if (sfmmu_steal_this_hblk(hmebp,
10322 						    hmeblkp, hblkpa, prevpa,
10323 						    pr_hblk)) {
10324 							/*
10325 							 * Hblk is unloaded
10326 							 * successfully
10327 							 */
10328 							break;
10329 						}
10330 					}
10331 				}
10332 				pr_hblk = hmeblkp;
10333 				prevpa = hblkpa;
10334 				hblkpa = hmeblkp->hblk_nextpa;
10335 				hmeblkp = hmeblkp->hblk_next;
10336 			}
10337 
10338 			SFMMU_HASH_UNLOCK(hmebp);
10339 			if (hmebp++ == &uhme_hash[UHMEHASH_SZ])
10340 				hmebp = uhme_hash;
10341 		}
10342 		uhmehash_steal_hand = hmebp;
10343 
10344 		if (hmeblkp != NULL)
10345 			break;
10346 
10347 		/*
10348 		 * in the worst case, look for a free one in the kernel
10349 		 * hash table.
10350 		 */
10351 		for (i = 0, hmebp = khme_hash; i <= KHMEHASH_SZ; i++) {
10352 			SFMMU_HASH_LOCK(hmebp);
10353 			hmeblkp = hmebp->hmeblkp;
10354 			hblkpa = hmebp->hmeh_nextpa;
10355 			prevpa = 0;
10356 			pr_hblk = NULL;
10357 			while (hmeblkp) {
10358 				/*
10359 				 * check if it is free hmeblk
10360 				 */
10361 				if ((get_hblk_ttesz(hmeblkp) == size) &&
10362 				    (hmeblkp->hblk_lckcnt == 0) &&
10363 				    (hmeblkp->hblk_vcnt == 0) &&
10364 				    (hmeblkp->hblk_hmecnt == 0)) {
10365 					if (sfmmu_steal_this_hblk(hmebp,
10366 					    hmeblkp, hblkpa, prevpa, pr_hblk)) {
10367 						break;
10368 					} else {
10369 						/*
10370 						 * Cannot fail since we have
10371 						 * hash lock.
10372 						 */
10373 						panic("fail to steal?");
10374 					}
10375 				}
10376 
10377 				pr_hblk = hmeblkp;
10378 				prevpa = hblkpa;
10379 				hblkpa = hmeblkp->hblk_nextpa;
10380 				hmeblkp = hmeblkp->hblk_next;
10381 			}
10382 
10383 			SFMMU_HASH_UNLOCK(hmebp);
10384 			if (hmebp++ == &khme_hash[KHMEHASH_SZ])
10385 				hmebp = khme_hash;
10386 		}
10387 
10388 		if (hmeblkp != NULL)
10389 			break;
10390 		sfmmu_hblk_steal_twice++;
10391 	}
10392 	return (hmeblkp);
10393 }
10394 
10395 /*
10396  * This routine does real work to prepare a hblk to be "stolen" by
10397  * unloading the mappings, updating shadow counts ....
10398  * It returns 1 if the block is ready to be reused (stolen), or 0
10399  * means the block cannot be stolen yet- pageunload is still working
10400  * on this hblk.
10401  */
10402 static int
10403 sfmmu_steal_this_hblk(struct hmehash_bucket *hmebp, struct hme_blk *hmeblkp,
10404 	uint64_t hblkpa, uint64_t prevpa, struct hme_blk *pr_hblk)
10405 {
10406 	int shw_size, vshift;
10407 	struct hme_blk *shw_hblkp;
10408 	uintptr_t vaddr;
10409 	uint_t shw_mask, newshw_mask;
10410 
10411 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
10412 
10413 	/*
10414 	 * check if the hmeblk is free, unload if necessary
10415 	 */
10416 	if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
10417 		sfmmu_t *sfmmup;
10418 		demap_range_t dmr;
10419 
10420 		sfmmup = hblktosfmmu(hmeblkp);
10421 		DEMAP_RANGE_INIT(sfmmup, &dmr);
10422 		(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
10423 		    (caddr_t)get_hblk_base(hmeblkp),
10424 		    get_hblk_endaddr(hmeblkp), &dmr, HAT_UNLOAD);
10425 		DEMAP_RANGE_FLUSH(&dmr);
10426 		if (hmeblkp->hblk_vcnt || hmeblkp->hblk_hmecnt) {
10427 			/*
10428 			 * Pageunload is working on the same hblk.
10429 			 */
10430 			return (0);
10431 		}
10432 
10433 		sfmmu_hblk_steal_unload_count++;
10434 	}
10435 
10436 	ASSERT(hmeblkp->hblk_lckcnt == 0);
10437 	ASSERT(hmeblkp->hblk_vcnt == 0 && hmeblkp->hblk_hmecnt == 0);
10438 
10439 	sfmmu_hblk_hash_rm(hmebp, hmeblkp, prevpa, pr_hblk);
10440 	hmeblkp->hblk_nextpa = hblkpa;
10441 
10442 	shw_hblkp = hmeblkp->hblk_shadow;
10443 	if (shw_hblkp) {
10444 		shw_size = get_hblk_ttesz(shw_hblkp);
10445 		vaddr = get_hblk_base(hmeblkp);
10446 		vshift = vaddr_to_vshift(shw_hblkp->hblk_tag, vaddr, shw_size);
10447 		ASSERT(vshift < 8);
10448 		/*
10449 		 * Atomically clear shadow mask bit
10450 		 */
10451 		do {
10452 			shw_mask = shw_hblkp->hblk_shw_mask;
10453 			ASSERT(shw_mask & (1 << vshift));
10454 			newshw_mask = shw_mask & ~(1 << vshift);
10455 			newshw_mask = cas32(&shw_hblkp->hblk_shw_mask,
10456 				shw_mask, newshw_mask);
10457 		} while (newshw_mask != shw_mask);
10458 		hmeblkp->hblk_shadow = NULL;
10459 	}
10460 
10461 	/*
10462 	 * remove shadow bit if we are stealing an unused shadow hmeblk.
10463 	 * sfmmu_hblk_alloc needs it that way, will set shadow bit later if
10464 	 * we are indeed allocating a shadow hmeblk.
10465 	 */
10466 	hmeblkp->hblk_shw_bit = 0;
10467 
10468 	sfmmu_hblk_steal_count++;
10469 	SFMMU_STAT(sf_steal_count);
10470 
10471 	return (1);
10472 }
10473 
10474 struct hme_blk *
10475 sfmmu_hmetohblk(struct sf_hment *sfhme)
10476 {
10477 	struct hme_blk *hmeblkp;
10478 	struct sf_hment *sfhme0;
10479 	struct hme_blk *hblk_dummy = 0;
10480 
10481 	/*
10482 	 * No dummy sf_hments, please.
10483 	 */
10484 	ASSERT(sfhme->hme_tte.ll != 0);
10485 
10486 	sfhme0 = sfhme - sfhme->hme_tte.tte_hmenum;
10487 	hmeblkp = (struct hme_blk *)((uintptr_t)sfhme0 -
10488 		(uintptr_t)&hblk_dummy->hblk_hme[0]);
10489 
10490 	return (hmeblkp);
10491 }
10492 
10493 /*
10494  * On swapin, get appropriately sized TSB(s) and clear the HAT_SWAPPED flag.
10495  * If we can't get appropriately sized TSB(s), try for 8K TSB(s) using
10496  * KM_SLEEP allocation.
10497  *
10498  * Return 0 on success, -1 otherwise.
10499  */
10500 static void
10501 sfmmu_tsb_swapin(sfmmu_t *sfmmup, hatlock_t *hatlockp)
10502 {
10503 	struct tsb_info *tsbinfop, *next;
10504 	tsb_replace_rc_t rc;
10505 	boolean_t gotfirst = B_FALSE;
10506 
10507 	ASSERT(sfmmup != ksfmmup);
10508 	ASSERT(sfmmu_hat_lock_held(sfmmup));
10509 
10510 	while (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPIN)) {
10511 		cv_wait(&sfmmup->sfmmu_tsb_cv, HATLOCK_MUTEXP(hatlockp));
10512 	}
10513 
10514 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
10515 		SFMMU_FLAGS_SET(sfmmup, HAT_SWAPIN);
10516 	} else {
10517 		return;
10518 	}
10519 
10520 	ASSERT(sfmmup->sfmmu_tsb != NULL);
10521 
10522 	/*
10523 	 * Loop over all tsbinfo's replacing them with ones that actually have
10524 	 * a TSB.  If any of the replacements ever fail, bail out of the loop.
10525 	 */
10526 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL; tsbinfop = next) {
10527 		ASSERT(tsbinfop->tsb_flags & TSB_SWAPPED);
10528 		next = tsbinfop->tsb_next;
10529 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, tsbinfop->tsb_szc,
10530 		    hatlockp, TSB_SWAPIN);
10531 		if (rc != TSB_SUCCESS) {
10532 			break;
10533 		}
10534 		gotfirst = B_TRUE;
10535 	}
10536 
10537 	switch (rc) {
10538 	case TSB_SUCCESS:
10539 		SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
10540 		cv_broadcast(&sfmmup->sfmmu_tsb_cv);
10541 		return;
10542 	case TSB_ALLOCFAIL:
10543 		break;
10544 	default:
10545 		panic("sfmmu_replace_tsb returned unrecognized failure code "
10546 		    "%d", rc);
10547 	}
10548 
10549 	/*
10550 	 * In this case, we failed to get one of our TSBs.  If we failed to
10551 	 * get the first TSB, get one of minimum size (8KB).  Walk the list
10552 	 * and throw away the tsbinfos, starting where the allocation failed;
10553 	 * we can get by with just one TSB as long as we don't leave the
10554 	 * SWAPPED tsbinfo structures lying around.
10555 	 */
10556 	tsbinfop = sfmmup->sfmmu_tsb;
10557 	next = tsbinfop->tsb_next;
10558 	tsbinfop->tsb_next = NULL;
10559 
10560 	sfmmu_hat_exit(hatlockp);
10561 	for (tsbinfop = next; tsbinfop != NULL; tsbinfop = next) {
10562 		next = tsbinfop->tsb_next;
10563 		sfmmu_tsbinfo_free(tsbinfop);
10564 	}
10565 	hatlockp = sfmmu_hat_enter(sfmmup);
10566 
10567 	/*
10568 	 * If we don't have any TSBs, get a single 8K TSB for 8K, 64K and 512K
10569 	 * pages.
10570 	 */
10571 	if (!gotfirst) {
10572 		tsbinfop = sfmmup->sfmmu_tsb;
10573 		rc = sfmmu_replace_tsb(sfmmup, tsbinfop, TSB_MIN_SZCODE,
10574 		    hatlockp, TSB_SWAPIN | TSB_FORCEALLOC);
10575 		ASSERT(rc == TSB_SUCCESS);
10576 	}
10577 
10578 	SFMMU_FLAGS_CLEAR(sfmmup, HAT_SWAPPED|HAT_SWAPIN);
10579 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
10580 }
10581 
10582 /*
10583  * Handle exceptions for low level tsb_handler.
10584  *
10585  * There are many scenarios that could land us here:
10586  *
10587  * If the context is invalid we land here. The context can be invalid
10588  * for 3 reasons: 1) we couldn't allocate a new context and now need to
10589  * perform a wrap around operation in order to allocate a new context.
10590  * 2) Context was invalidated to change pagesize programming 3) ISMs or
10591  * TSBs configuration is changeing for this process and we are forced into
10592  * here to do a syncronization operation. If the context is valid we can
10593  * be here from window trap hanlder. In this case just call trap to handle
10594  * the fault.
10595  *
10596  * Note that the process will run in INVALID_CONTEXT before
10597  * faulting into here and subsequently loading the MMU registers
10598  * (including the TSB base register) associated with this process.
10599  * For this reason, the trap handlers must all test for
10600  * INVALID_CONTEXT before attempting to access any registers other
10601  * than the context registers.
10602  */
10603 void
10604 sfmmu_tsbmiss_exception(struct regs *rp, uintptr_t tagaccess, uint_t traptype)
10605 {
10606 	sfmmu_t *sfmmup;
10607 	uint_t ctxnum;
10608 	klwp_id_t lwp;
10609 	char lwp_save_state;
10610 	hatlock_t *hatlockp;
10611 	struct tsb_info *tsbinfop;
10612 
10613 	SFMMU_STAT(sf_tsb_exceptions);
10614 	SFMMU_MMU_STAT(mmu_tsb_exceptions);
10615 	sfmmup = astosfmmu(curthread->t_procp->p_as);
10616 	ctxnum = tagaccess & TAGACC_CTX_MASK;
10617 
10618 	ASSERT(sfmmup != ksfmmup && ctxnum != KCONTEXT);
10619 	ASSERT(sfmmup->sfmmu_ismhat == 0);
10620 	/*
10621 	 * First, make sure we come out of here with a valid ctx,
10622 	 * since if we don't get one we'll simply loop on the
10623 	 * faulting instruction.
10624 	 *
10625 	 * If the ISM mappings are changing, the TSB is being relocated, or
10626 	 * the process is swapped out we serialize behind the controlling
10627 	 * thread with the sfmmu_flags and sfmmu_tsb_cv condition variable.
10628 	 * Otherwise we synchronize with the context stealer or the thread
10629 	 * that required us to change out our MMU registers (such
10630 	 * as a thread changing out our TSB while we were running) by
10631 	 * locking the HAT and grabbing the rwlock on the context as a
10632 	 * reader temporarily.
10633 	 */
10634 	ASSERT(!SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED) ||
10635 	    ctxnum == INVALID_CONTEXT);
10636 
10637 	if (ctxnum == INVALID_CONTEXT) {
10638 		/*
10639 		 * Must set lwp state to LWP_SYS before
10640 		 * trying to acquire any adaptive lock
10641 		 */
10642 		lwp = ttolwp(curthread);
10643 		ASSERT(lwp);
10644 		lwp_save_state = lwp->lwp_state;
10645 		lwp->lwp_state = LWP_SYS;
10646 
10647 		hatlockp = sfmmu_hat_enter(sfmmup);
10648 retry:
10649 		for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
10650 		    tsbinfop = tsbinfop->tsb_next) {
10651 			if (tsbinfop->tsb_flags & TSB_RELOC_FLAG) {
10652 				cv_wait(&sfmmup->sfmmu_tsb_cv,
10653 				    HATLOCK_MUTEXP(hatlockp));
10654 				goto retry;
10655 			}
10656 		}
10657 
10658 		/*
10659 		 * Wait for ISM maps to be updated.
10660 		 */
10661 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_ISMBUSY)) {
10662 			cv_wait(&sfmmup->sfmmu_tsb_cv,
10663 			    HATLOCK_MUTEXP(hatlockp));
10664 			goto retry;
10665 		}
10666 
10667 		/*
10668 		 * If we're swapping in, get TSB(s).  Note that we must do
10669 		 * this before we get a ctx or load the MMU state.  Once
10670 		 * we swap in we have to recheck to make sure the TSB(s) and
10671 		 * ISM mappings didn't change while we slept.
10672 		 */
10673 		if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
10674 			sfmmu_tsb_swapin(sfmmup, hatlockp);
10675 			goto retry;
10676 		}
10677 
10678 		sfmmu_get_ctx(sfmmup);
10679 
10680 		sfmmu_hat_exit(hatlockp);
10681 		/*
10682 		 * Must restore lwp_state if not calling
10683 		 * trap() for further processing. Restore
10684 		 * it anyway.
10685 		 */
10686 		lwp->lwp_state = lwp_save_state;
10687 		if (sfmmup->sfmmu_ttecnt[TTE8K] != 0 ||
10688 		    sfmmup->sfmmu_ttecnt[TTE64K] != 0 ||
10689 		    sfmmup->sfmmu_ttecnt[TTE512K] != 0 ||
10690 		    sfmmup->sfmmu_ttecnt[TTE4M] != 0 ||
10691 		    sfmmup->sfmmu_ttecnt[TTE32M] != 0 ||
10692 		    sfmmup->sfmmu_ttecnt[TTE256M] != 0) {
10693 			return;
10694 		}
10695 		if (traptype == T_DATA_PROT) {
10696 			traptype = T_DATA_MMU_MISS;
10697 		}
10698 	}
10699 	trap(rp, (caddr_t)tagaccess, traptype, 0);
10700 }
10701 
10702 /*
10703  * sfmmu_vatopfn_suspended is called from GET_TTE when TL=0 and
10704  * TTE_SUSPENDED bit set in tte we block on aquiring a page lock
10705  * rather than spinning to avoid send mondo timeouts with
10706  * interrupts enabled. When the lock is acquired it is immediately
10707  * released and we return back to sfmmu_vatopfn just after
10708  * the GET_TTE call.
10709  */
10710 void
10711 sfmmu_vatopfn_suspended(caddr_t vaddr, sfmmu_t *sfmmu, tte_t *ttep)
10712 {
10713 	struct page	**pp;
10714 
10715 	(void) as_pagelock(sfmmu->sfmmu_as, &pp, vaddr, TTE_CSZ(ttep), S_WRITE);
10716 	as_pageunlock(sfmmu->sfmmu_as, pp, vaddr, TTE_CSZ(ttep), S_WRITE);
10717 }
10718 
10719 /*
10720  * sfmmu_tsbmiss_suspended is called from GET_TTE when TL>0 and
10721  * TTE_SUSPENDED bit set in tte. We do this so that we can handle
10722  * cross traps which cannot be handled while spinning in the
10723  * trap handlers. Simply enter and exit the kpr_suspendlock spin
10724  * mutex, which is held by the holder of the suspend bit, and then
10725  * retry the trapped instruction after unwinding.
10726  */
10727 /*ARGSUSED*/
10728 void
10729 sfmmu_tsbmiss_suspended(struct regs *rp, uintptr_t tagacc, uint_t traptype)
10730 {
10731 	ASSERT(curthread != kreloc_thread);
10732 	mutex_enter(&kpr_suspendlock);
10733 	mutex_exit(&kpr_suspendlock);
10734 }
10735 
10736 /*
10737  * Special routine to flush out ism mappings- TSBs, TLBs and D-caches.
10738  * This routine may be called with all cpu's captured. Therefore, the
10739  * caller is responsible for holding all locks and disabling kernel
10740  * preemption.
10741  */
10742 /* ARGSUSED */
10743 static void
10744 sfmmu_ismtlbcache_demap(caddr_t addr, sfmmu_t *ism_sfmmup,
10745 	struct hme_blk *hmeblkp, pfn_t pfnum, int cache_flush_flag)
10746 {
10747 	cpuset_t 	cpuset;
10748 	caddr_t 	va;
10749 	ism_ment_t	*ment;
10750 	sfmmu_t		*sfmmup;
10751 #ifdef VAC
10752 	int 		vcolor;
10753 #endif
10754 	int		ttesz;
10755 
10756 	/*
10757 	 * Walk the ism_hat's mapping list and flush the page
10758 	 * from every hat sharing this ism_hat. This routine
10759 	 * may be called while all cpu's have been captured.
10760 	 * Therefore we can't attempt to grab any locks. For now
10761 	 * this means we will protect the ism mapping list under
10762 	 * a single lock which will be grabbed by the caller.
10763 	 * If hat_share/unshare scalibility becomes a performance
10764 	 * problem then we may need to re-think ism mapping list locking.
10765 	 */
10766 	ASSERT(ism_sfmmup->sfmmu_ismhat);
10767 	ASSERT(MUTEX_HELD(&ism_mlist_lock));
10768 	addr = addr - ISMID_STARTADDR;
10769 	for (ment = ism_sfmmup->sfmmu_iment; ment; ment = ment->iment_next) {
10770 
10771 		sfmmup = ment->iment_hat;
10772 
10773 		va = ment->iment_base_va;
10774 		va = (caddr_t)((uintptr_t)va  + (uintptr_t)addr);
10775 
10776 		/*
10777 		 * Flush TSB of ISM mappings.
10778 		 */
10779 		ttesz = get_hblk_ttesz(hmeblkp);
10780 		if (ttesz == TTE8K || ttesz == TTE4M) {
10781 			sfmmu_unload_tsb(sfmmup, va, ttesz);
10782 		} else {
10783 			caddr_t sva = va;
10784 			caddr_t eva;
10785 			ASSERT(addr == (caddr_t)get_hblk_base(hmeblkp));
10786 			eva = sva + get_hblk_span(hmeblkp);
10787 			sfmmu_unload_tsb_range(sfmmup, sva, eva, ttesz);
10788 		}
10789 
10790 		cpuset = sfmmup->sfmmu_cpusran;
10791 		CPUSET_AND(cpuset, cpu_ready_set);
10792 		CPUSET_DEL(cpuset, CPU->cpu_id);
10793 
10794 		SFMMU_XCALL_STATS(sfmmup);
10795 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)va,
10796 		    (uint64_t)sfmmup);
10797 
10798 		vtag_flushpage(va, (uint64_t)sfmmup);
10799 
10800 #ifdef VAC
10801 		/*
10802 		 * Flush D$
10803 		 * When flushing D$ we must flush all
10804 		 * cpu's. See sfmmu_cache_flush().
10805 		 */
10806 		if (cache_flush_flag == CACHE_FLUSH) {
10807 			cpuset = cpu_ready_set;
10808 			CPUSET_DEL(cpuset, CPU->cpu_id);
10809 
10810 			SFMMU_XCALL_STATS(sfmmup);
10811 			vcolor = addr_to_vcolor(va);
10812 			xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
10813 			vac_flushpage(pfnum, vcolor);
10814 		}
10815 #endif	/* VAC */
10816 	}
10817 }
10818 
10819 /*
10820  * Demaps the TSB, CPU caches, and flushes all TLBs on all CPUs of
10821  * a particular virtual address and ctx.  If noflush is set we do not
10822  * flush the TLB/TSB.  This function may or may not be called with the
10823  * HAT lock held.
10824  */
10825 static void
10826 sfmmu_tlbcache_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
10827 	pfn_t pfnum, int tlb_noflush, int cpu_flag, int cache_flush_flag,
10828 	int hat_lock_held)
10829 {
10830 #ifdef VAC
10831 	int vcolor;
10832 #endif
10833 	cpuset_t cpuset;
10834 	hatlock_t *hatlockp;
10835 
10836 #if defined(lint) && !defined(VAC)
10837 	pfnum = pfnum;
10838 	cpu_flag = cpu_flag;
10839 	cache_flush_flag = cache_flush_flag;
10840 #endif
10841 	/*
10842 	 * There is no longer a need to protect against ctx being
10843 	 * stolen here since we don't store the ctx in the TSB anymore.
10844 	 */
10845 #ifdef VAC
10846 	vcolor = addr_to_vcolor(addr);
10847 #endif
10848 
10849 	/*
10850 	 * We must hold the hat lock during the flush of TLB,
10851 	 * to avoid a race with sfmmu_invalidate_ctx(), where
10852 	 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
10853 	 * causing TLB demap routine to skip flush on that MMU.
10854 	 * If the context on a MMU has already been set to
10855 	 * INVALID_CONTEXT, we just get an extra flush on
10856 	 * that MMU.
10857 	 */
10858 	if (!hat_lock_held && !tlb_noflush)
10859 		hatlockp = sfmmu_hat_enter(sfmmup);
10860 
10861 	kpreempt_disable();
10862 	if (!tlb_noflush) {
10863 		/*
10864 		 * Flush the TSB and TLB.
10865 		 */
10866 		SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp);
10867 
10868 		cpuset = sfmmup->sfmmu_cpusran;
10869 		CPUSET_AND(cpuset, cpu_ready_set);
10870 		CPUSET_DEL(cpuset, CPU->cpu_id);
10871 
10872 		SFMMU_XCALL_STATS(sfmmup);
10873 
10874 		xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr,
10875 		    (uint64_t)sfmmup);
10876 
10877 		vtag_flushpage(addr, (uint64_t)sfmmup);
10878 	}
10879 
10880 	if (!hat_lock_held && !tlb_noflush)
10881 		sfmmu_hat_exit(hatlockp);
10882 
10883 #ifdef VAC
10884 	/*
10885 	 * Flush the D$
10886 	 *
10887 	 * Even if the ctx is stolen, we need to flush the
10888 	 * cache. Our ctx stealer only flushes the TLBs.
10889 	 */
10890 	if (cache_flush_flag == CACHE_FLUSH) {
10891 		if (cpu_flag & FLUSH_ALL_CPUS) {
10892 			cpuset = cpu_ready_set;
10893 		} else {
10894 			cpuset = sfmmup->sfmmu_cpusran;
10895 			CPUSET_AND(cpuset, cpu_ready_set);
10896 		}
10897 		CPUSET_DEL(cpuset, CPU->cpu_id);
10898 		SFMMU_XCALL_STATS(sfmmup);
10899 		xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
10900 		vac_flushpage(pfnum, vcolor);
10901 	}
10902 #endif	/* VAC */
10903 	kpreempt_enable();
10904 }
10905 
10906 /*
10907  * Demaps the TSB and flushes all TLBs on all cpus for a particular virtual
10908  * address and ctx.  If noflush is set we do not currently do anything.
10909  * This function may or may not be called with the HAT lock held.
10910  */
10911 static void
10912 sfmmu_tlb_demap(caddr_t addr, sfmmu_t *sfmmup, struct hme_blk *hmeblkp,
10913 	int tlb_noflush, int hat_lock_held)
10914 {
10915 	cpuset_t cpuset;
10916 	hatlock_t *hatlockp;
10917 
10918 	/*
10919 	 * If the process is exiting we have nothing to do.
10920 	 */
10921 	if (tlb_noflush)
10922 		return;
10923 
10924 	/*
10925 	 * Flush TSB.
10926 	 */
10927 	if (!hat_lock_held)
10928 		hatlockp = sfmmu_hat_enter(sfmmup);
10929 	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp);
10930 
10931 	kpreempt_disable();
10932 
10933 	cpuset = sfmmup->sfmmu_cpusran;
10934 	CPUSET_AND(cpuset, cpu_ready_set);
10935 	CPUSET_DEL(cpuset, CPU->cpu_id);
10936 
10937 	SFMMU_XCALL_STATS(sfmmup);
10938 	xt_some(cpuset, vtag_flushpage_tl1, (uint64_t)addr, (uint64_t)sfmmup);
10939 
10940 	vtag_flushpage(addr, (uint64_t)sfmmup);
10941 
10942 	if (!hat_lock_held)
10943 		sfmmu_hat_exit(hatlockp);
10944 
10945 	kpreempt_enable();
10946 
10947 }
10948 
10949 /*
10950  * Special case of sfmmu_tlb_demap for MMU_PAGESIZE hblks. Use the xcall
10951  * call handler that can flush a range of pages to save on xcalls.
10952  */
10953 static int sfmmu_xcall_save;
10954 
10955 static void
10956 sfmmu_tlb_range_demap(demap_range_t *dmrp)
10957 {
10958 	sfmmu_t *sfmmup = dmrp->dmr_sfmmup;
10959 	hatlock_t *hatlockp;
10960 	cpuset_t cpuset;
10961 	uint64_t sfmmu_pgcnt;
10962 	pgcnt_t pgcnt = 0;
10963 	int pgunload = 0;
10964 	int dirtypg = 0;
10965 	caddr_t addr = dmrp->dmr_addr;
10966 	caddr_t eaddr;
10967 	uint64_t bitvec = dmrp->dmr_bitvec;
10968 
10969 	ASSERT(bitvec & 1);
10970 
10971 	/*
10972 	 * Flush TSB and calculate number of pages to flush.
10973 	 */
10974 	while (bitvec != 0) {
10975 		dirtypg = 0;
10976 		/*
10977 		 * Find the first page to flush and then count how many
10978 		 * pages there are after it that also need to be flushed.
10979 		 * This way the number of TSB flushes is minimized.
10980 		 */
10981 		while ((bitvec & 1) == 0) {
10982 			pgcnt++;
10983 			addr += MMU_PAGESIZE;
10984 			bitvec >>= 1;
10985 		}
10986 		while (bitvec & 1) {
10987 			dirtypg++;
10988 			bitvec >>= 1;
10989 		}
10990 		eaddr = addr + ptob(dirtypg);
10991 		hatlockp = sfmmu_hat_enter(sfmmup);
10992 		sfmmu_unload_tsb_range(sfmmup, addr, eaddr, TTE8K);
10993 		sfmmu_hat_exit(hatlockp);
10994 		pgunload += dirtypg;
10995 		addr = eaddr;
10996 		pgcnt += dirtypg;
10997 	}
10998 
10999 	ASSERT((pgcnt<<MMU_PAGESHIFT) <= dmrp->dmr_endaddr - dmrp->dmr_addr);
11000 	if (sfmmup->sfmmu_free == 0) {
11001 		addr = dmrp->dmr_addr;
11002 		bitvec = dmrp->dmr_bitvec;
11003 
11004 		/*
11005 		 * make sure it has SFMMU_PGCNT_SHIFT bits only,
11006 		 * as it will be used to pack argument for xt_some
11007 		 */
11008 		ASSERT((pgcnt > 0) &&
11009 		    (pgcnt <= (1 << SFMMU_PGCNT_SHIFT)));
11010 
11011 		/*
11012 		 * Encode pgcnt as (pgcnt -1 ), and pass (pgcnt - 1) in
11013 		 * the low 6 bits of sfmmup. This is doable since pgcnt
11014 		 * always >= 1.
11015 		 */
11016 		ASSERT(!((uint64_t)sfmmup & SFMMU_PGCNT_MASK));
11017 		sfmmu_pgcnt = (uint64_t)sfmmup |
11018 		    ((pgcnt - 1) & SFMMU_PGCNT_MASK);
11019 
11020 		/*
11021 		 * We must hold the hat lock during the flush of TLB,
11022 		 * to avoid a race with sfmmu_invalidate_ctx(), where
11023 		 * sfmmu_cnum on a MMU could be set to INVALID_CONTEXT,
11024 		 * causing TLB demap routine to skip flush on that MMU.
11025 		 * If the context on a MMU has already been set to
11026 		 * INVALID_CONTEXT, we just get an extra flush on
11027 		 * that MMU.
11028 		 */
11029 		hatlockp = sfmmu_hat_enter(sfmmup);
11030 		kpreempt_disable();
11031 
11032 		cpuset = sfmmup->sfmmu_cpusran;
11033 		CPUSET_AND(cpuset, cpu_ready_set);
11034 		CPUSET_DEL(cpuset, CPU->cpu_id);
11035 
11036 		SFMMU_XCALL_STATS(sfmmup);
11037 		xt_some(cpuset, vtag_flush_pgcnt_tl1, (uint64_t)addr,
11038 		    sfmmu_pgcnt);
11039 
11040 		for (; bitvec != 0; bitvec >>= 1) {
11041 			if (bitvec & 1)
11042 				vtag_flushpage(addr, (uint64_t)sfmmup);
11043 			addr += MMU_PAGESIZE;
11044 		}
11045 		kpreempt_enable();
11046 		sfmmu_hat_exit(hatlockp);
11047 
11048 		sfmmu_xcall_save += (pgunload-1);
11049 	}
11050 	dmrp->dmr_bitvec = 0;
11051 }
11052 
11053 /*
11054  * In cases where we need to synchronize with TLB/TSB miss trap
11055  * handlers, _and_ need to flush the TLB, it's a lot easier to
11056  * throw away the context from the process than to do a
11057  * special song and dance to keep things consistent for the
11058  * handlers.
11059  *
11060  * Since the process suddenly ends up without a context and our caller
11061  * holds the hat lock, threads that fault after this function is called
11062  * will pile up on the lock.  We can then do whatever we need to
11063  * atomically from the context of the caller.  The first blocked thread
11064  * to resume executing will get the process a new context, and the
11065  * process will resume executing.
11066  *
11067  * One added advantage of this approach is that on MMUs that
11068  * support a "flush all" operation, we will delay the flush until
11069  * cnum wrap-around, and then flush the TLB one time.  This
11070  * is rather rare, so it's a lot less expensive than making 8000
11071  * x-calls to flush the TLB 8000 times.
11072  *
11073  * A per-process (PP) lock is used to synchronize ctx allocations in
11074  * resume() and ctx invalidations here.
11075  */
11076 static void
11077 sfmmu_invalidate_ctx(sfmmu_t *sfmmup)
11078 {
11079 	cpuset_t cpuset;
11080 	int cnum, currcnum;
11081 	mmu_ctx_t *mmu_ctxp;
11082 	int i;
11083 	uint_t pstate_save;
11084 
11085 	SFMMU_STAT(sf_ctx_inv);
11086 
11087 	ASSERT(sfmmu_hat_lock_held(sfmmup));
11088 	ASSERT(sfmmup != ksfmmup);
11089 
11090 	kpreempt_disable();
11091 
11092 	mmu_ctxp = CPU_MMU_CTXP(CPU);
11093 	ASSERT(mmu_ctxp);
11094 	ASSERT(mmu_ctxp->mmu_idx < max_mmu_ctxdoms);
11095 	ASSERT(mmu_ctxp == mmu_ctxs_tbl[mmu_ctxp->mmu_idx]);
11096 
11097 	currcnum = sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum;
11098 
11099 	pstate_save = sfmmu_disable_intrs();
11100 
11101 	lock_set(&sfmmup->sfmmu_ctx_lock);	/* acquire PP lock */
11102 	/* set HAT cnum invalid across all context domains. */
11103 	for (i = 0; i < max_mmu_ctxdoms; i++) {
11104 
11105 		cnum = 	sfmmup->sfmmu_ctxs[i].cnum;
11106 		if (cnum == INVALID_CONTEXT) {
11107 			continue;
11108 		}
11109 
11110 		sfmmup->sfmmu_ctxs[i].cnum = INVALID_CONTEXT;
11111 	}
11112 	membar_enter();	/* make sure globally visible to all CPUs */
11113 	lock_clear(&sfmmup->sfmmu_ctx_lock);	/* release PP lock */
11114 
11115 	sfmmu_enable_intrs(pstate_save);
11116 
11117 	cpuset = sfmmup->sfmmu_cpusran;
11118 	CPUSET_DEL(cpuset, CPU->cpu_id);
11119 	CPUSET_AND(cpuset, cpu_ready_set);
11120 	if (!CPUSET_ISNULL(cpuset)) {
11121 		SFMMU_XCALL_STATS(sfmmup);
11122 		xt_some(cpuset, sfmmu_raise_tsb_exception,
11123 		    (uint64_t)sfmmup, INVALID_CONTEXT);
11124 		xt_sync(cpuset);
11125 		SFMMU_STAT(sf_tsb_raise_exception);
11126 		SFMMU_MMU_STAT(mmu_tsb_raise_exception);
11127 	}
11128 
11129 	/*
11130 	 * If the hat to-be-invalidated is the same as the current
11131 	 * process on local CPU we need to invalidate
11132 	 * this CPU context as well.
11133 	 */
11134 	if ((sfmmu_getctx_sec() == currcnum) &&
11135 	    (currcnum != INVALID_CONTEXT)) {
11136 		sfmmu_setctx_sec(INVALID_CONTEXT);
11137 		sfmmu_clear_utsbinfo();
11138 	}
11139 
11140 	kpreempt_enable();
11141 
11142 	/*
11143 	 * we hold the hat lock, so nobody should allocate a context
11144 	 * for us yet
11145 	 */
11146 	ASSERT(sfmmup->sfmmu_ctxs[mmu_ctxp->mmu_idx].cnum == INVALID_CONTEXT);
11147 }
11148 
11149 #ifdef VAC
11150 /*
11151  * We need to flush the cache in all cpus.  It is possible that
11152  * a process referenced a page as cacheable but has sinced exited
11153  * and cleared the mapping list.  We still to flush it but have no
11154  * state so all cpus is the only alternative.
11155  */
11156 void
11157 sfmmu_cache_flush(pfn_t pfnum, int vcolor)
11158 {
11159 	cpuset_t cpuset;
11160 
11161 	kpreempt_disable();
11162 	cpuset = cpu_ready_set;
11163 	CPUSET_DEL(cpuset, CPU->cpu_id);
11164 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
11165 	xt_some(cpuset, vac_flushpage_tl1, pfnum, vcolor);
11166 	xt_sync(cpuset);
11167 	vac_flushpage(pfnum, vcolor);
11168 	kpreempt_enable();
11169 }
11170 
11171 void
11172 sfmmu_cache_flushcolor(int vcolor, pfn_t pfnum)
11173 {
11174 	cpuset_t cpuset;
11175 
11176 	ASSERT(vcolor >= 0);
11177 
11178 	kpreempt_disable();
11179 	cpuset = cpu_ready_set;
11180 	CPUSET_DEL(cpuset, CPU->cpu_id);
11181 	SFMMU_XCALL_STATS(NULL);	/* account to any ctx */
11182 	xt_some(cpuset, vac_flushcolor_tl1, vcolor, pfnum);
11183 	xt_sync(cpuset);
11184 	vac_flushcolor(vcolor, pfnum);
11185 	kpreempt_enable();
11186 }
11187 #endif	/* VAC */
11188 
11189 /*
11190  * We need to prevent processes from accessing the TSB using a cached physical
11191  * address.  It's alright if they try to access the TSB via virtual address
11192  * since they will just fault on that virtual address once the mapping has
11193  * been suspended.
11194  */
11195 #pragma weak sendmondo_in_recover
11196 
11197 /* ARGSUSED */
11198 static int
11199 sfmmu_tsb_pre_relocator(caddr_t va, uint_t tsbsz, uint_t flags, void *tsbinfo)
11200 {
11201 	hatlock_t *hatlockp;
11202 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
11203 	sfmmu_t *sfmmup = tsbinfop->tsb_sfmmu;
11204 	extern uint32_t sendmondo_in_recover;
11205 
11206 	if (flags != HAT_PRESUSPEND)
11207 		return (0);
11208 
11209 	hatlockp = sfmmu_hat_enter(sfmmup);
11210 
11211 	tsbinfop->tsb_flags |= TSB_RELOC_FLAG;
11212 
11213 	/*
11214 	 * For Cheetah+ Erratum 25:
11215 	 * Wait for any active recovery to finish.  We can't risk
11216 	 * relocating the TSB of the thread running mondo_recover_proc()
11217 	 * since, if we did that, we would deadlock.  The scenario we are
11218 	 * trying to avoid is as follows:
11219 	 *
11220 	 * THIS CPU			RECOVER CPU
11221 	 * --------			-----------
11222 	 *				Begins recovery, walking through TSB
11223 	 * hat_pagesuspend() TSB TTE
11224 	 *				TLB miss on TSB TTE, spins at TL1
11225 	 * xt_sync()
11226 	 *	send_mondo_timeout()
11227 	 *	mondo_recover_proc()
11228 	 *	((deadlocked))
11229 	 *
11230 	 * The second half of the workaround is that mondo_recover_proc()
11231 	 * checks to see if the tsb_info has the RELOC flag set, and if it
11232 	 * does, it skips over that TSB without ever touching tsbinfop->tsb_va
11233 	 * and hence avoiding the TLB miss that could result in a deadlock.
11234 	 */
11235 	if (&sendmondo_in_recover) {
11236 		membar_enter();	/* make sure RELOC flag visible */
11237 		while (sendmondo_in_recover) {
11238 			drv_usecwait(1);
11239 			membar_consumer();
11240 		}
11241 	}
11242 
11243 	sfmmu_invalidate_ctx(sfmmup);
11244 	sfmmu_hat_exit(hatlockp);
11245 
11246 	return (0);
11247 }
11248 
11249 /* ARGSUSED */
11250 static int
11251 sfmmu_tsb_post_relocator(caddr_t va, uint_t tsbsz, uint_t flags,
11252 	void *tsbinfo, pfn_t newpfn)
11253 {
11254 	hatlock_t *hatlockp;
11255 	struct tsb_info *tsbinfop = (struct tsb_info *)tsbinfo;
11256 	sfmmu_t	*sfmmup = tsbinfop->tsb_sfmmu;
11257 
11258 	if (flags != HAT_POSTUNSUSPEND)
11259 		return (0);
11260 
11261 	hatlockp = sfmmu_hat_enter(sfmmup);
11262 
11263 	SFMMU_STAT(sf_tsb_reloc);
11264 
11265 	/*
11266 	 * The process may have swapped out while we were relocating one
11267 	 * of its TSBs.  If so, don't bother doing the setup since the
11268 	 * process can't be using the memory anymore.
11269 	 */
11270 	if ((tsbinfop->tsb_flags & TSB_SWAPPED) == 0) {
11271 		ASSERT(va == tsbinfop->tsb_va);
11272 		sfmmu_tsbinfo_setup_phys(tsbinfop, newpfn);
11273 		sfmmu_setup_tsbinfo(sfmmup);
11274 
11275 		if (tsbinfop->tsb_flags & TSB_FLUSH_NEEDED) {
11276 			sfmmu_inv_tsb(tsbinfop->tsb_va,
11277 			    TSB_BYTES(tsbinfop->tsb_szc));
11278 			tsbinfop->tsb_flags &= ~TSB_FLUSH_NEEDED;
11279 		}
11280 	}
11281 
11282 	membar_exit();
11283 	tsbinfop->tsb_flags &= ~TSB_RELOC_FLAG;
11284 	cv_broadcast(&sfmmup->sfmmu_tsb_cv);
11285 
11286 	sfmmu_hat_exit(hatlockp);
11287 
11288 	return (0);
11289 }
11290 
11291 /*
11292  * Allocate and initialize a tsb_info structure.  Note that we may or may not
11293  * allocate a TSB here, depending on the flags passed in.
11294  */
11295 static int
11296 sfmmu_tsbinfo_alloc(struct tsb_info **tsbinfopp, int tsb_szc, int tte_sz_mask,
11297 	uint_t flags, sfmmu_t *sfmmup)
11298 {
11299 	int err;
11300 
11301 	*tsbinfopp = (struct tsb_info *)kmem_cache_alloc(
11302 	    sfmmu_tsbinfo_cache, KM_SLEEP);
11303 
11304 	if ((err = sfmmu_init_tsbinfo(*tsbinfopp, tte_sz_mask,
11305 	    tsb_szc, flags, sfmmup)) != 0) {
11306 		kmem_cache_free(sfmmu_tsbinfo_cache, *tsbinfopp);
11307 		SFMMU_STAT(sf_tsb_allocfail);
11308 		*tsbinfopp = NULL;
11309 		return (err);
11310 	}
11311 	SFMMU_STAT(sf_tsb_alloc);
11312 
11313 	/*
11314 	 * Bump the TSB size counters for this TSB size.
11315 	 */
11316 	(*(((int *)&sfmmu_tsbsize_stat) + tsb_szc))++;
11317 	return (0);
11318 }
11319 
11320 static void
11321 sfmmu_tsb_free(struct tsb_info *tsbinfo)
11322 {
11323 	caddr_t tsbva = tsbinfo->tsb_va;
11324 	uint_t tsb_size = TSB_BYTES(tsbinfo->tsb_szc);
11325 	struct kmem_cache *kmem_cachep = tsbinfo->tsb_cache;
11326 	vmem_t	*vmp = tsbinfo->tsb_vmp;
11327 
11328 	/*
11329 	 * If we allocated this TSB from relocatable kernel memory, then we
11330 	 * need to uninstall the callback handler.
11331 	 */
11332 	if (tsbinfo->tsb_cache != sfmmu_tsb8k_cache) {
11333 		uintptr_t slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
11334 		caddr_t slab_vaddr = (caddr_t)((uintptr_t)tsbva & slab_mask);
11335 		page_t **ppl;
11336 		int ret;
11337 
11338 		ret = as_pagelock(&kas, &ppl, slab_vaddr, PAGESIZE, S_WRITE);
11339 		ASSERT(ret == 0);
11340 		hat_delete_callback(tsbva, (uint_t)tsb_size, (void *)tsbinfo,
11341 		    0, NULL);
11342 		as_pageunlock(&kas, ppl, slab_vaddr, PAGESIZE, S_WRITE);
11343 	}
11344 
11345 	if (kmem_cachep != NULL) {
11346 		kmem_cache_free(kmem_cachep, tsbva);
11347 	} else {
11348 		vmem_xfree(vmp, (void *)tsbva, tsb_size);
11349 	}
11350 	tsbinfo->tsb_va = (caddr_t)0xbad00bad;
11351 	atomic_add_64(&tsb_alloc_bytes, -(int64_t)tsb_size);
11352 }
11353 
11354 static void
11355 sfmmu_tsbinfo_free(struct tsb_info *tsbinfo)
11356 {
11357 	if ((tsbinfo->tsb_flags & TSB_SWAPPED) == 0) {
11358 		sfmmu_tsb_free(tsbinfo);
11359 	}
11360 	kmem_cache_free(sfmmu_tsbinfo_cache, tsbinfo);
11361 
11362 }
11363 
11364 /*
11365  * Setup all the references to physical memory for this tsbinfo.
11366  * The underlying page(s) must be locked.
11367  */
11368 static void
11369 sfmmu_tsbinfo_setup_phys(struct tsb_info *tsbinfo, pfn_t pfn)
11370 {
11371 	ASSERT(pfn != PFN_INVALID);
11372 	ASSERT(pfn == va_to_pfn(tsbinfo->tsb_va));
11373 
11374 #ifndef sun4v
11375 	if (tsbinfo->tsb_szc == 0) {
11376 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn,
11377 		    PROT_WRITE|PROT_READ, TTE8K);
11378 	} else {
11379 		/*
11380 		 * Round down PA and use a large mapping; the handlers will
11381 		 * compute the TSB pointer at the correct offset into the
11382 		 * big virtual page.  NOTE: this assumes all TSBs larger
11383 		 * than 8K must come from physically contiguous slabs of
11384 		 * size tsb_slab_size.
11385 		 */
11386 		sfmmu_memtte(&tsbinfo->tsb_tte, pfn & ~tsb_slab_mask,
11387 		    PROT_WRITE|PROT_READ, tsb_slab_ttesz);
11388 	}
11389 	tsbinfo->tsb_pa = ptob(pfn);
11390 
11391 	TTE_SET_LOCKED(&tsbinfo->tsb_tte); /* lock the tte into dtlb */
11392 	TTE_SET_MOD(&tsbinfo->tsb_tte);    /* enable writes */
11393 
11394 	ASSERT(TTE_IS_PRIVILEGED(&tsbinfo->tsb_tte));
11395 	ASSERT(TTE_IS_LOCKED(&tsbinfo->tsb_tte));
11396 #else /* sun4v */
11397 	tsbinfo->tsb_pa = ptob(pfn);
11398 #endif /* sun4v */
11399 }
11400 
11401 
11402 /*
11403  * Returns zero on success, ENOMEM if over the high water mark,
11404  * or EAGAIN if the caller needs to retry with a smaller TSB
11405  * size (or specify TSB_FORCEALLOC if the allocation can't fail).
11406  *
11407  * This call cannot fail to allocate a TSB if TSB_FORCEALLOC
11408  * is specified and the TSB requested is PAGESIZE, though it
11409  * may sleep waiting for memory if sufficient memory is not
11410  * available.
11411  */
11412 static int
11413 sfmmu_init_tsbinfo(struct tsb_info *tsbinfo, int tteszmask,
11414     int tsbcode, uint_t flags, sfmmu_t *sfmmup)
11415 {
11416 	caddr_t vaddr = NULL;
11417 	caddr_t slab_vaddr;
11418 	uintptr_t slab_mask = ~((uintptr_t)tsb_slab_mask) << PAGESHIFT;
11419 	int tsbbytes = TSB_BYTES(tsbcode);
11420 	int lowmem = 0;
11421 	struct kmem_cache *kmem_cachep = NULL;
11422 	vmem_t *vmp = NULL;
11423 	lgrp_id_t lgrpid = LGRP_NONE;
11424 	pfn_t pfn;
11425 	uint_t cbflags = HAC_SLEEP;
11426 	page_t **pplist;
11427 	int ret;
11428 
11429 	if (flags & (TSB_FORCEALLOC | TSB_SWAPIN | TSB_GROW | TSB_SHRINK))
11430 		flags |= TSB_ALLOC;
11431 
11432 	ASSERT((flags & TSB_FORCEALLOC) == 0 || tsbcode == TSB_MIN_SZCODE);
11433 
11434 	tsbinfo->tsb_sfmmu = sfmmup;
11435 
11436 	/*
11437 	 * If not allocating a TSB, set up the tsbinfo, set TSB_SWAPPED, and
11438 	 * return.
11439 	 */
11440 	if ((flags & TSB_ALLOC) == 0) {
11441 		tsbinfo->tsb_szc = tsbcode;
11442 		tsbinfo->tsb_ttesz_mask = tteszmask;
11443 		tsbinfo->tsb_va = (caddr_t)0xbadbadbeef;
11444 		tsbinfo->tsb_pa = -1;
11445 		tsbinfo->tsb_tte.ll = 0;
11446 		tsbinfo->tsb_next = NULL;
11447 		tsbinfo->tsb_flags = TSB_SWAPPED;
11448 		tsbinfo->tsb_cache = NULL;
11449 		tsbinfo->tsb_vmp = NULL;
11450 		return (0);
11451 	}
11452 
11453 #ifdef DEBUG
11454 	/*
11455 	 * For debugging:
11456 	 * Randomly force allocation failures every tsb_alloc_mtbf
11457 	 * tries if TSB_FORCEALLOC is not specified.  This will
11458 	 * return ENOMEM if tsb_alloc_mtbf is odd, or EAGAIN if
11459 	 * it is even, to allow testing of both failure paths...
11460 	 */
11461 	if (tsb_alloc_mtbf && ((flags & TSB_FORCEALLOC) == 0) &&
11462 	    (tsb_alloc_count++ == tsb_alloc_mtbf)) {
11463 		tsb_alloc_count = 0;
11464 		tsb_alloc_fail_mtbf++;
11465 		return ((tsb_alloc_mtbf & 1)? ENOMEM : EAGAIN);
11466 	}
11467 #endif	/* DEBUG */
11468 
11469 	/*
11470 	 * Enforce high water mark if we are not doing a forced allocation
11471 	 * and are not shrinking a process' TSB.
11472 	 */
11473 	if ((flags & TSB_SHRINK) == 0 &&
11474 	    (tsbbytes + tsb_alloc_bytes) > tsb_alloc_hiwater) {
11475 		if ((flags & TSB_FORCEALLOC) == 0)
11476 			return (ENOMEM);
11477 		lowmem = 1;
11478 	}
11479 
11480 	/*
11481 	 * Allocate from the correct location based upon the size of the TSB
11482 	 * compared to the base page size, and what memory conditions dictate.
11483 	 * Note we always do nonblocking allocations from the TSB arena since
11484 	 * we don't want memory fragmentation to cause processes to block
11485 	 * indefinitely waiting for memory; until the kernel algorithms that
11486 	 * coalesce large pages are improved this is our best option.
11487 	 *
11488 	 * Algorithm:
11489 	 *	If allocating a "large" TSB (>8K), allocate from the
11490 	 *		appropriate kmem_tsb_default_arena vmem arena
11491 	 *	else if low on memory or the TSB_FORCEALLOC flag is set or
11492 	 *	tsb_forceheap is set
11493 	 *		Allocate from kernel heap via sfmmu_tsb8k_cache with
11494 	 *		KM_SLEEP (never fails)
11495 	 *	else
11496 	 *		Allocate from appropriate sfmmu_tsb_cache with
11497 	 *		KM_NOSLEEP
11498 	 *	endif
11499 	 */
11500 	if (tsb_lgrp_affinity)
11501 		lgrpid = lgrp_home_id(curthread);
11502 	if (lgrpid == LGRP_NONE)
11503 		lgrpid = 0;	/* use lgrp of boot CPU */
11504 
11505 	if (tsbbytes > MMU_PAGESIZE) {
11506 		vmp = kmem_tsb_default_arena[lgrpid];
11507 		vaddr = (caddr_t)vmem_xalloc(vmp, tsbbytes, tsbbytes, 0, 0,
11508 		    NULL, NULL, VM_NOSLEEP);
11509 #ifdef	DEBUG
11510 	} else if (lowmem || (flags & TSB_FORCEALLOC) || tsb_forceheap) {
11511 #else	/* !DEBUG */
11512 	} else if (lowmem || (flags & TSB_FORCEALLOC)) {
11513 #endif	/* DEBUG */
11514 		kmem_cachep = sfmmu_tsb8k_cache;
11515 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_SLEEP);
11516 		ASSERT(vaddr != NULL);
11517 	} else {
11518 		kmem_cachep = sfmmu_tsb_cache[lgrpid];
11519 		vaddr = (caddr_t)kmem_cache_alloc(kmem_cachep, KM_NOSLEEP);
11520 	}
11521 
11522 	tsbinfo->tsb_cache = kmem_cachep;
11523 	tsbinfo->tsb_vmp = vmp;
11524 
11525 	if (vaddr == NULL) {
11526 		return (EAGAIN);
11527 	}
11528 
11529 	atomic_add_64(&tsb_alloc_bytes, (int64_t)tsbbytes);
11530 	kmem_cachep = tsbinfo->tsb_cache;
11531 
11532 	/*
11533 	 * If we are allocating from outside the cage, then we need to
11534 	 * register a relocation callback handler.  Note that for now
11535 	 * since pseudo mappings always hang off of the slab's root page,
11536 	 * we need only lock the first 8K of the TSB slab.  This is a bit
11537 	 * hacky but it is good for performance.
11538 	 */
11539 	if (kmem_cachep != sfmmu_tsb8k_cache) {
11540 		slab_vaddr = (caddr_t)((uintptr_t)vaddr & slab_mask);
11541 		ret = as_pagelock(&kas, &pplist, slab_vaddr, PAGESIZE, S_WRITE);
11542 		ASSERT(ret == 0);
11543 		ret = hat_add_callback(sfmmu_tsb_cb_id, vaddr, (uint_t)tsbbytes,
11544 		    cbflags, (void *)tsbinfo, &pfn, NULL);
11545 
11546 		/*
11547 		 * Need to free up resources if we could not successfully
11548 		 * add the callback function and return an error condition.
11549 		 */
11550 		if (ret != 0) {
11551 			if (kmem_cachep) {
11552 				kmem_cache_free(kmem_cachep, vaddr);
11553 			} else {
11554 				vmem_xfree(vmp, (void *)vaddr, tsbbytes);
11555 			}
11556 			as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE,
11557 			    S_WRITE);
11558 			return (EAGAIN);
11559 		}
11560 	} else {
11561 		/*
11562 		 * Since allocation of 8K TSBs from heap is rare and occurs
11563 		 * during memory pressure we allocate them from permanent
11564 		 * memory rather than using callbacks to get the PFN.
11565 		 */
11566 		pfn = hat_getpfnum(kas.a_hat, vaddr);
11567 	}
11568 
11569 	tsbinfo->tsb_va = vaddr;
11570 	tsbinfo->tsb_szc = tsbcode;
11571 	tsbinfo->tsb_ttesz_mask = tteszmask;
11572 	tsbinfo->tsb_next = NULL;
11573 	tsbinfo->tsb_flags = 0;
11574 
11575 	sfmmu_tsbinfo_setup_phys(tsbinfo, pfn);
11576 
11577 	if (kmem_cachep != sfmmu_tsb8k_cache) {
11578 		as_pageunlock(&kas, pplist, slab_vaddr, PAGESIZE, S_WRITE);
11579 	}
11580 
11581 	sfmmu_inv_tsb(vaddr, tsbbytes);
11582 	return (0);
11583 }
11584 
11585 /*
11586  * Initialize per cpu tsb and per cpu tsbmiss_area
11587  */
11588 void
11589 sfmmu_init_tsbs(void)
11590 {
11591 	int i;
11592 	struct tsbmiss	*tsbmissp;
11593 	struct kpmtsbm	*kpmtsbmp;
11594 #ifndef sun4v
11595 	extern int	dcache_line_mask;
11596 #endif /* sun4v */
11597 	extern uint_t	vac_colors;
11598 
11599 	/*
11600 	 * Init. tsb miss area.
11601 	 */
11602 	tsbmissp = tsbmiss_area;
11603 
11604 	for (i = 0; i < NCPU; tsbmissp++, i++) {
11605 		/*
11606 		 * initialize the tsbmiss area.
11607 		 * Do this for all possible CPUs as some may be added
11608 		 * while the system is running. There is no cost to this.
11609 		 */
11610 		tsbmissp->ksfmmup = ksfmmup;
11611 #ifndef sun4v
11612 		tsbmissp->dcache_line_mask = (uint16_t)dcache_line_mask;
11613 #endif /* sun4v */
11614 		tsbmissp->khashstart =
11615 		    (struct hmehash_bucket *)va_to_pa((caddr_t)khme_hash);
11616 		tsbmissp->uhashstart =
11617 		    (struct hmehash_bucket *)va_to_pa((caddr_t)uhme_hash);
11618 		tsbmissp->khashsz = khmehash_num;
11619 		tsbmissp->uhashsz = uhmehash_num;
11620 	}
11621 
11622 	sfmmu_tsb_cb_id = hat_register_callback('T'<<16 | 'S' << 8 | 'B',
11623 	    sfmmu_tsb_pre_relocator, sfmmu_tsb_post_relocator, NULL, 0);
11624 
11625 	if (kpm_enable == 0)
11626 		return;
11627 
11628 	/* -- Begin KPM specific init -- */
11629 
11630 	if (kpm_smallpages) {
11631 		/*
11632 		 * If we're using base pagesize pages for seg_kpm
11633 		 * mappings, we use the kernel TSB since we can't afford
11634 		 * to allocate a second huge TSB for these mappings.
11635 		 */
11636 		kpm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
11637 		kpm_tsbsz = ktsb_szcode;
11638 		kpmsm_tsbbase = kpm_tsbbase;
11639 		kpmsm_tsbsz = kpm_tsbsz;
11640 	} else {
11641 		/*
11642 		 * In VAC conflict case, just put the entries in the
11643 		 * kernel 8K indexed TSB for now so we can find them.
11644 		 * This could really be changed in the future if we feel
11645 		 * the need...
11646 		 */
11647 		kpmsm_tsbbase = ktsb_phys? ktsb_pbase : (uint64_t)ktsb_base;
11648 		kpmsm_tsbsz = ktsb_szcode;
11649 		kpm_tsbbase = ktsb_phys? ktsb4m_pbase : (uint64_t)ktsb4m_base;
11650 		kpm_tsbsz = ktsb4m_szcode;
11651 	}
11652 
11653 	kpmtsbmp = kpmtsbm_area;
11654 	for (i = 0; i < NCPU; kpmtsbmp++, i++) {
11655 		/*
11656 		 * Initialize the kpmtsbm area.
11657 		 * Do this for all possible CPUs as some may be added
11658 		 * while the system is running. There is no cost to this.
11659 		 */
11660 		kpmtsbmp->vbase = kpm_vbase;
11661 		kpmtsbmp->vend = kpm_vbase + kpm_size * vac_colors;
11662 		kpmtsbmp->sz_shift = kpm_size_shift;
11663 		kpmtsbmp->kpmp_shift = kpmp_shift;
11664 		kpmtsbmp->kpmp2pshft = (uchar_t)kpmp2pshft;
11665 		if (kpm_smallpages == 0) {
11666 			kpmtsbmp->kpmp_table_sz = kpmp_table_sz;
11667 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_table);
11668 		} else {
11669 			kpmtsbmp->kpmp_table_sz = kpmp_stable_sz;
11670 			kpmtsbmp->kpmp_tablepa = va_to_pa(kpmp_stable);
11671 		}
11672 		kpmtsbmp->msegphashpa = va_to_pa(memseg_phash);
11673 		kpmtsbmp->flags = KPMTSBM_ENABLE_FLAG;
11674 #ifdef	DEBUG
11675 		kpmtsbmp->flags |= (kpm_tsbmtl) ?  KPMTSBM_TLTSBM_FLAG : 0;
11676 #endif	/* DEBUG */
11677 		if (ktsb_phys)
11678 			kpmtsbmp->flags |= KPMTSBM_TSBPHYS_FLAG;
11679 	}
11680 
11681 	/* -- End KPM specific init -- */
11682 }
11683 
11684 /* Avoid using sfmmu_tsbinfo_alloc() to avoid kmem_alloc - no real reason */
11685 struct tsb_info ktsb_info[2];
11686 
11687 /*
11688  * Called from hat_kern_setup() to setup the tsb_info for ksfmmup.
11689  */
11690 void
11691 sfmmu_init_ktsbinfo()
11692 {
11693 	ASSERT(ksfmmup != NULL);
11694 	ASSERT(ksfmmup->sfmmu_tsb == NULL);
11695 	/*
11696 	 * Allocate tsbinfos for kernel and copy in data
11697 	 * to make debug easier and sun4v setup easier.
11698 	 */
11699 	ktsb_info[0].tsb_sfmmu = ksfmmup;
11700 	ktsb_info[0].tsb_szc = ktsb_szcode;
11701 	ktsb_info[0].tsb_ttesz_mask = TSB8K|TSB64K|TSB512K;
11702 	ktsb_info[0].tsb_va = ktsb_base;
11703 	ktsb_info[0].tsb_pa = ktsb_pbase;
11704 	ktsb_info[0].tsb_flags = 0;
11705 	ktsb_info[0].tsb_tte.ll = 0;
11706 	ktsb_info[0].tsb_cache = NULL;
11707 
11708 	ktsb_info[1].tsb_sfmmu = ksfmmup;
11709 	ktsb_info[1].tsb_szc = ktsb4m_szcode;
11710 	ktsb_info[1].tsb_ttesz_mask = TSB4M;
11711 	ktsb_info[1].tsb_va = ktsb4m_base;
11712 	ktsb_info[1].tsb_pa = ktsb4m_pbase;
11713 	ktsb_info[1].tsb_flags = 0;
11714 	ktsb_info[1].tsb_tte.ll = 0;
11715 	ktsb_info[1].tsb_cache = NULL;
11716 
11717 	/* Link them into ksfmmup. */
11718 	ktsb_info[0].tsb_next = &ktsb_info[1];
11719 	ktsb_info[1].tsb_next = NULL;
11720 	ksfmmup->sfmmu_tsb = &ktsb_info[0];
11721 
11722 	sfmmu_setup_tsbinfo(ksfmmup);
11723 }
11724 
11725 /*
11726  * Cache the last value returned from va_to_pa().  If the VA specified
11727  * in the current call to cached_va_to_pa() maps to the same Page (as the
11728  * previous call to cached_va_to_pa()), then compute the PA using
11729  * cached info, else call va_to_pa().
11730  *
11731  * Note: this function is neither MT-safe nor consistent in the presence
11732  * of multiple, interleaved threads.  This function was created to enable
11733  * an optimization used during boot (at a point when there's only one thread
11734  * executing on the "boot CPU", and before startup_vm() has been called).
11735  */
11736 static uint64_t
11737 cached_va_to_pa(void *vaddr)
11738 {
11739 	static uint64_t prev_vaddr_base = 0;
11740 	static uint64_t prev_pfn = 0;
11741 
11742 	if ((((uint64_t)vaddr) & MMU_PAGEMASK) == prev_vaddr_base) {
11743 		return (prev_pfn | ((uint64_t)vaddr & MMU_PAGEOFFSET));
11744 	} else {
11745 		uint64_t pa = va_to_pa(vaddr);
11746 
11747 		if (pa != ((uint64_t)-1)) {
11748 			/*
11749 			 * Computed physical address is valid.  Cache its
11750 			 * related info for the next cached_va_to_pa() call.
11751 			 */
11752 			prev_pfn = pa & MMU_PAGEMASK;
11753 			prev_vaddr_base = ((uint64_t)vaddr) & MMU_PAGEMASK;
11754 		}
11755 
11756 		return (pa);
11757 	}
11758 }
11759 
11760 /*
11761  * Carve up our nucleus hblk region.  We may allocate more hblks than
11762  * asked due to rounding errors but we are guaranteed to have at least
11763  * enough space to allocate the requested number of hblk8's and hblk1's.
11764  */
11765 void
11766 sfmmu_init_nucleus_hblks(caddr_t addr, size_t size, int nhblk8, int nhblk1)
11767 {
11768 	struct hme_blk *hmeblkp;
11769 	size_t hme8blk_sz, hme1blk_sz;
11770 	size_t i;
11771 	size_t hblk8_bound;
11772 	ulong_t j = 0, k = 0;
11773 
11774 	ASSERT(addr != NULL && size != 0);
11775 
11776 	/* Need to use proper structure alignment */
11777 	hme8blk_sz = roundup(HME8BLK_SZ, sizeof (int64_t));
11778 	hme1blk_sz = roundup(HME1BLK_SZ, sizeof (int64_t));
11779 
11780 	nucleus_hblk8.list = (void *)addr;
11781 	nucleus_hblk8.index = 0;
11782 
11783 	/*
11784 	 * Use as much memory as possible for hblk8's since we
11785 	 * expect all bop_alloc'ed memory to be allocated in 8k chunks.
11786 	 * We need to hold back enough space for the hblk1's which
11787 	 * we'll allocate next.
11788 	 */
11789 	hblk8_bound = size - (nhblk1 * hme1blk_sz) - hme8blk_sz;
11790 	for (i = 0; i <= hblk8_bound; i += hme8blk_sz, j++) {
11791 		hmeblkp = (struct hme_blk *)addr;
11792 		addr += hme8blk_sz;
11793 		hmeblkp->hblk_nuc_bit = 1;
11794 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
11795 	}
11796 	nucleus_hblk8.len = j;
11797 	ASSERT(j >= nhblk8);
11798 	SFMMU_STAT_ADD(sf_hblk8_ncreate, j);
11799 
11800 	nucleus_hblk1.list = (void *)addr;
11801 	nucleus_hblk1.index = 0;
11802 	for (; i <= (size - hme1blk_sz); i += hme1blk_sz, k++) {
11803 		hmeblkp = (struct hme_blk *)addr;
11804 		addr += hme1blk_sz;
11805 		hmeblkp->hblk_nuc_bit = 1;
11806 		hmeblkp->hblk_nextpa = cached_va_to_pa((caddr_t)hmeblkp);
11807 	}
11808 	ASSERT(k >= nhblk1);
11809 	nucleus_hblk1.len = k;
11810 	SFMMU_STAT_ADD(sf_hblk1_ncreate, k);
11811 }
11812 
11813 /*
11814  * This function is currently not supported on this platform. For what
11815  * it's supposed to do, see hat.c and hat_srmmu.c
11816  */
11817 /* ARGSUSED */
11818 faultcode_t
11819 hat_softlock(struct hat *hat, caddr_t addr, size_t *lenp, page_t **ppp,
11820     uint_t flags)
11821 {
11822 	ASSERT(hat->sfmmu_xhat_provider == NULL);
11823 	return (FC_NOSUPPORT);
11824 }
11825 
11826 /*
11827  * Searchs the mapping list of the page for a mapping of the same size. If not
11828  * found the corresponding bit is cleared in the p_index field. When large
11829  * pages are more prevalent in the system, we can maintain the mapping list
11830  * in order and we don't have to traverse the list each time. Just check the
11831  * next and prev entries, and if both are of different size, we clear the bit.
11832  */
11833 static void
11834 sfmmu_rm_large_mappings(page_t *pp, int ttesz)
11835 {
11836 	struct sf_hment *sfhmep;
11837 	struct hme_blk *hmeblkp;
11838 	int	index;
11839 	pgcnt_t	npgs;
11840 
11841 	ASSERT(ttesz > TTE8K);
11842 
11843 	ASSERT(sfmmu_mlist_held(pp));
11844 
11845 	ASSERT(PP_ISMAPPED_LARGE(pp));
11846 
11847 	/*
11848 	 * Traverse mapping list looking for another mapping of same size.
11849 	 * since we only want to clear index field if all mappings of
11850 	 * that size are gone.
11851 	 */
11852 
11853 	for (sfhmep = pp->p_mapping; sfhmep; sfhmep = sfhmep->hme_next) {
11854 		hmeblkp = sfmmu_hmetohblk(sfhmep);
11855 		if (hmeblkp->hblk_xhat_bit)
11856 			continue;
11857 		if (hme_size(sfhmep) == ttesz) {
11858 			/*
11859 			 * another mapping of the same size. don't clear index.
11860 			 */
11861 			return;
11862 		}
11863 	}
11864 
11865 	/*
11866 	 * Clear the p_index bit for large page.
11867 	 */
11868 	index = PAGESZ_TO_INDEX(ttesz);
11869 	npgs = TTEPAGES(ttesz);
11870 	while (npgs-- > 0) {
11871 		ASSERT(pp->p_index & index);
11872 		pp->p_index &= ~index;
11873 		pp = PP_PAGENEXT(pp);
11874 	}
11875 }
11876 
11877 /*
11878  * return supported features
11879  */
11880 /* ARGSUSED */
11881 int
11882 hat_supported(enum hat_features feature, void *arg)
11883 {
11884 	switch (feature) {
11885 	case    HAT_SHARED_PT:
11886 	case	HAT_DYNAMIC_ISM_UNMAP:
11887 	case	HAT_VMODSORT:
11888 		return (1);
11889 	default:
11890 		return (0);
11891 	}
11892 }
11893 
11894 void
11895 hat_enter(struct hat *hat)
11896 {
11897 	hatlock_t	*hatlockp;
11898 
11899 	if (hat != ksfmmup) {
11900 		hatlockp = TSB_HASH(hat);
11901 		mutex_enter(HATLOCK_MUTEXP(hatlockp));
11902 	}
11903 }
11904 
11905 void
11906 hat_exit(struct hat *hat)
11907 {
11908 	hatlock_t	*hatlockp;
11909 
11910 	if (hat != ksfmmup) {
11911 		hatlockp = TSB_HASH(hat);
11912 		mutex_exit(HATLOCK_MUTEXP(hatlockp));
11913 	}
11914 }
11915 
11916 /*ARGSUSED*/
11917 void
11918 hat_reserve(struct as *as, caddr_t addr, size_t len)
11919 {
11920 }
11921 
11922 static void
11923 hat_kstat_init(void)
11924 {
11925 	kstat_t *ksp;
11926 
11927 	ksp = kstat_create("unix", 0, "sfmmu_global_stat", "hat",
11928 		KSTAT_TYPE_RAW, sizeof (struct sfmmu_global_stat),
11929 		KSTAT_FLAG_VIRTUAL);
11930 	if (ksp) {
11931 		ksp->ks_data = (void *) &sfmmu_global_stat;
11932 		kstat_install(ksp);
11933 	}
11934 	ksp = kstat_create("unix", 0, "sfmmu_tsbsize_stat", "hat",
11935 		KSTAT_TYPE_RAW, sizeof (struct sfmmu_tsbsize_stat),
11936 		KSTAT_FLAG_VIRTUAL);
11937 	if (ksp) {
11938 		ksp->ks_data = (void *) &sfmmu_tsbsize_stat;
11939 		kstat_install(ksp);
11940 	}
11941 	ksp = kstat_create("unix", 0, "sfmmu_percpu_stat", "hat",
11942 		KSTAT_TYPE_RAW, sizeof (struct sfmmu_percpu_stat) * NCPU,
11943 		KSTAT_FLAG_WRITABLE);
11944 	if (ksp) {
11945 		ksp->ks_update = sfmmu_kstat_percpu_update;
11946 		kstat_install(ksp);
11947 	}
11948 }
11949 
11950 /* ARGSUSED */
11951 static int
11952 sfmmu_kstat_percpu_update(kstat_t *ksp, int rw)
11953 {
11954 	struct sfmmu_percpu_stat *cpu_kstat = ksp->ks_data;
11955 	struct tsbmiss *tsbm = tsbmiss_area;
11956 	struct kpmtsbm *kpmtsbm = kpmtsbm_area;
11957 	int i;
11958 
11959 	ASSERT(cpu_kstat);
11960 	if (rw == KSTAT_READ) {
11961 		for (i = 0; i < NCPU; cpu_kstat++, tsbm++, kpmtsbm++, i++) {
11962 			cpu_kstat->sf_itlb_misses = tsbm->itlb_misses;
11963 			cpu_kstat->sf_dtlb_misses = tsbm->dtlb_misses;
11964 			cpu_kstat->sf_utsb_misses = tsbm->utsb_misses -
11965 				tsbm->uprot_traps;
11966 			cpu_kstat->sf_ktsb_misses = tsbm->ktsb_misses +
11967 				kpmtsbm->kpm_tsb_misses - tsbm->kprot_traps;
11968 
11969 			if (tsbm->itlb_misses > 0 && tsbm->dtlb_misses > 0) {
11970 				cpu_kstat->sf_tsb_hits =
11971 				(tsbm->itlb_misses + tsbm->dtlb_misses) -
11972 				(tsbm->utsb_misses + tsbm->ktsb_misses +
11973 				kpmtsbm->kpm_tsb_misses);
11974 			} else {
11975 				cpu_kstat->sf_tsb_hits = 0;
11976 			}
11977 			cpu_kstat->sf_umod_faults = tsbm->uprot_traps;
11978 			cpu_kstat->sf_kmod_faults = tsbm->kprot_traps;
11979 		}
11980 	} else {
11981 		/* KSTAT_WRITE is used to clear stats */
11982 		for (i = 0; i < NCPU; tsbm++, kpmtsbm++, i++) {
11983 			tsbm->itlb_misses = 0;
11984 			tsbm->dtlb_misses = 0;
11985 			tsbm->utsb_misses = 0;
11986 			tsbm->ktsb_misses = 0;
11987 			tsbm->uprot_traps = 0;
11988 			tsbm->kprot_traps = 0;
11989 			kpmtsbm->kpm_dtlb_misses = 0;
11990 			kpmtsbm->kpm_tsb_misses = 0;
11991 		}
11992 	}
11993 	return (0);
11994 }
11995 
11996 #ifdef	DEBUG
11997 
11998 tte_t  *gorig[NCPU], *gcur[NCPU], *gnew[NCPU];
11999 
12000 /*
12001  * A tte checker. *orig_old is the value we read before cas.
12002  *	*cur is the value returned by cas.
12003  *	*new is the desired value when we do the cas.
12004  *
12005  *	*hmeblkp is currently unused.
12006  */
12007 
12008 /* ARGSUSED */
12009 void
12010 chk_tte(tte_t *orig_old, tte_t *cur, tte_t *new, struct hme_blk *hmeblkp)
12011 {
12012 	pfn_t i, j, k;
12013 	int cpuid = CPU->cpu_id;
12014 
12015 	gorig[cpuid] = orig_old;
12016 	gcur[cpuid] = cur;
12017 	gnew[cpuid] = new;
12018 
12019 #ifdef lint
12020 	hmeblkp = hmeblkp;
12021 #endif
12022 
12023 	if (TTE_IS_VALID(orig_old)) {
12024 		if (TTE_IS_VALID(cur)) {
12025 			i = TTE_TO_TTEPFN(orig_old);
12026 			j = TTE_TO_TTEPFN(cur);
12027 			k = TTE_TO_TTEPFN(new);
12028 			if (i != j) {
12029 				/* remap error? */
12030 				panic("chk_tte: bad pfn, 0x%lx, 0x%lx", i, j);
12031 			}
12032 
12033 			if (i != k) {
12034 				/* remap error? */
12035 				panic("chk_tte: bad pfn2, 0x%lx, 0x%lx", i, k);
12036 			}
12037 		} else {
12038 			if (TTE_IS_VALID(new)) {
12039 				panic("chk_tte: invalid cur? ");
12040 			}
12041 
12042 			i = TTE_TO_TTEPFN(orig_old);
12043 			k = TTE_TO_TTEPFN(new);
12044 			if (i != k) {
12045 				panic("chk_tte: bad pfn3, 0x%lx, 0x%lx", i, k);
12046 			}
12047 		}
12048 	} else {
12049 		if (TTE_IS_VALID(cur)) {
12050 			j = TTE_TO_TTEPFN(cur);
12051 			if (TTE_IS_VALID(new)) {
12052 				k = TTE_TO_TTEPFN(new);
12053 				if (j != k) {
12054 					panic("chk_tte: bad pfn4, 0x%lx, 0x%lx",
12055 					    j, k);
12056 				}
12057 			} else {
12058 				panic("chk_tte: why here?");
12059 			}
12060 		} else {
12061 			if (!TTE_IS_VALID(new)) {
12062 				panic("chk_tte: why here2 ?");
12063 			}
12064 		}
12065 	}
12066 }
12067 
12068 #endif /* DEBUG */
12069 
12070 extern void prefetch_tsbe_read(struct tsbe *);
12071 extern void prefetch_tsbe_write(struct tsbe *);
12072 
12073 
12074 /*
12075  * We want to prefetch 7 cache lines ahead for our read prefetch.  This gives
12076  * us optimal performance on Cheetah+.  You can only have 8 outstanding
12077  * prefetches at any one time, so we opted for 7 read prefetches and 1 write
12078  * prefetch to make the most utilization of the prefetch capability.
12079  */
12080 #define	TSBE_PREFETCH_STRIDE (7)
12081 
12082 void
12083 sfmmu_copy_tsb(struct tsb_info *old_tsbinfo, struct tsb_info *new_tsbinfo)
12084 {
12085 	int old_bytes = TSB_BYTES(old_tsbinfo->tsb_szc);
12086 	int new_bytes = TSB_BYTES(new_tsbinfo->tsb_szc);
12087 	int old_entries = TSB_ENTRIES(old_tsbinfo->tsb_szc);
12088 	int new_entries = TSB_ENTRIES(new_tsbinfo->tsb_szc);
12089 	struct tsbe *old;
12090 	struct tsbe *new;
12091 	struct tsbe *new_base = (struct tsbe *)new_tsbinfo->tsb_va;
12092 	uint64_t va;
12093 	int new_offset;
12094 	int i;
12095 	int vpshift;
12096 	int last_prefetch;
12097 
12098 	if (old_bytes == new_bytes) {
12099 		bcopy(old_tsbinfo->tsb_va, new_tsbinfo->tsb_va, new_bytes);
12100 	} else {
12101 
12102 		/*
12103 		 * A TSBE is 16 bytes which means there are four TSBE's per
12104 		 * P$ line (64 bytes), thus every 4 TSBE's we prefetch.
12105 		 */
12106 		old = (struct tsbe *)old_tsbinfo->tsb_va;
12107 		last_prefetch = old_entries - (4*(TSBE_PREFETCH_STRIDE+1));
12108 		for (i = 0; i < old_entries; i++, old++) {
12109 			if (((i & (4-1)) == 0) && (i < last_prefetch))
12110 				prefetch_tsbe_read(old);
12111 			if (!old->tte_tag.tag_invalid) {
12112 				/*
12113 				 * We have a valid TTE to remap.  Check the
12114 				 * size.  We won't remap 64K or 512K TTEs
12115 				 * because they span more than one TSB entry
12116 				 * and are indexed using an 8K virt. page.
12117 				 * Ditto for 32M and 256M TTEs.
12118 				 */
12119 				if (TTE_CSZ(&old->tte_data) == TTE64K ||
12120 				    TTE_CSZ(&old->tte_data) == TTE512K)
12121 					continue;
12122 				if (mmu_page_sizes == max_mmu_page_sizes) {
12123 				    if (TTE_CSZ(&old->tte_data) == TTE32M ||
12124 					TTE_CSZ(&old->tte_data) == TTE256M)
12125 					    continue;
12126 				}
12127 
12128 				/* clear the lower 22 bits of the va */
12129 				va = *(uint64_t *)old << 22;
12130 				/* turn va into a virtual pfn */
12131 				va >>= 22 - TSB_START_SIZE;
12132 				/*
12133 				 * or in bits from the offset in the tsb
12134 				 * to get the real virtual pfn. These
12135 				 * correspond to bits [21:13] in the va
12136 				 */
12137 				vpshift =
12138 				    TTE_BSZS_SHIFT(TTE_CSZ(&old->tte_data)) &
12139 				    0x1ff;
12140 				va |= (i << vpshift);
12141 				va >>= vpshift;
12142 				new_offset = va & (new_entries - 1);
12143 				new = new_base + new_offset;
12144 				prefetch_tsbe_write(new);
12145 				*new = *old;
12146 			}
12147 		}
12148 	}
12149 }
12150 
12151 /*
12152  * unused in sfmmu
12153  */
12154 void
12155 hat_dump(void)
12156 {
12157 }
12158 
12159 /*
12160  * Called when a thread is exiting and we have switched to the kernel address
12161  * space.  Perform the same VM initialization resume() uses when switching
12162  * processes.
12163  *
12164  * Note that sfmmu_load_mmustate() is currently a no-op for kernel threads, but
12165  * we call it anyway in case the semantics change in the future.
12166  */
12167 /*ARGSUSED*/
12168 void
12169 hat_thread_exit(kthread_t *thd)
12170 {
12171 	uint64_t pgsz_cnum;
12172 	uint_t pstate_save;
12173 
12174 	ASSERT(thd->t_procp->p_as == &kas);
12175 
12176 	pgsz_cnum = KCONTEXT;
12177 #ifdef sun4u
12178 	pgsz_cnum |= (ksfmmup->sfmmu_cext << CTXREG_EXT_SHIFT);
12179 #endif
12180 	/*
12181 	 * Note that sfmmu_load_mmustate() is currently a no-op for
12182 	 * kernel threads. We need to disable interrupts here,
12183 	 * simply because otherwise sfmmu_load_mmustate() would panic
12184 	 * if the caller does not disable interrupts.
12185 	 */
12186 	pstate_save = sfmmu_disable_intrs();
12187 	sfmmu_setctx_sec(pgsz_cnum);
12188 	sfmmu_load_mmustate(ksfmmup);
12189 	sfmmu_enable_intrs(pstate_save);
12190 }
12191