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