xref: /illumos-gate/usr/src/uts/sfmmu/vm/hat_sfmmu.c (revision 4a6e2134)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 1993, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 /*
25  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
26  * Copyright 2016 Gary Mills
27  * Copyright 2019 Joyent, Inc.
28  */
29 
30 /*
31  * VM - Hardware Address Translation management for Spitfire MMU.
32  *
33  * This file implements the machine specific hardware translation
34  * needed by the VM system.  The machine independent interface is
35  * described in <vm/hat.h> while the machine dependent interface
36  * and data structures are described in <vm/hat_sfmmu.h>.
37  *
38  * The hat layer manages the address translation hardware as a cache
39  * driven by calls from the higher levels in the VM system.
40  */
41 
42 #include <sys/types.h>
43 #include <sys/kstat.h>
44 #include <vm/hat.h>
45 #include <vm/hat_sfmmu.h>
46 #include <vm/page.h>
47 #include <sys/pte.h>
48 #include <sys/systm.h>
49 #include <sys/mman.h>
50 #include <sys/sysmacros.h>
51 #include <sys/machparam.h>
52 #include <sys/vtrace.h>
53 #include <sys/kmem.h>
54 #include <sys/mmu.h>
55 #include <sys/cmn_err.h>
56 #include <sys/cpu.h>
57 #include <sys/cpuvar.h>
58 #include <sys/debug.h>
59 #include <sys/lgrp.h>
60 #include <sys/archsystm.h>
61 #include <sys/machsystm.h>
62 #include <sys/vmsystm.h>
63 #include <vm/as.h>
64 #include <vm/seg.h>
65 #include <vm/seg_kp.h>
66 #include <vm/seg_kmem.h>
67 #include <vm/seg_kpm.h>
68 #include <vm/rm.h>
69 #include <sys/t_lock.h>
70 #include <sys/obpdefs.h>
71 #include <sys/vm_machparam.h>
72 #include <sys/var.h>
73 #include <sys/trap.h>
74 #include <sys/machtrap.h>
75 #include <sys/scb.h>
76 #include <sys/bitmap.h>
77 #include <sys/machlock.h>
78 #include <sys/membar.h>
79 #include <sys/atomic.h>
80 #include <sys/cpu_module.h>
81 #include <sys/prom_debug.h>
82 #include <sys/ksynch.h>
83 #include <sys/mem_config.h>
84 #include <sys/mem_cage.h>
85 #include <vm/vm_dep.h>
86 #include <sys/fpu/fpusystm.h>
87 #include <vm/mach_kpm.h>
88 #include <sys/callb.h>
89 
90 #ifdef	DEBUG
91 #define	SFMMU_VALIDATE_HMERID(hat, rid, saddr, len)			\
92 	if (SFMMU_IS_SHMERID_VALID(rid)) {				\
93 		caddr_t _eaddr = (saddr) + (len);			\
94 		sf_srd_t *_srdp;					\
95 		sf_region_t *_rgnp;					\
96 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			\
97 		ASSERT(SF_RGNMAP_TEST(hat->sfmmu_hmeregion_map, rid));	\
98 		ASSERT((hat) != ksfmmup);				\
99 		_srdp = (hat)->sfmmu_srdp;				\
100 		ASSERT(_srdp != NULL);					\
101 		ASSERT(_srdp->srd_refcnt != 0);				\
102 		_rgnp = _srdp->srd_hmergnp[(rid)];			\
103 		ASSERT(_rgnp != NULL && _rgnp->rgn_id == rid);		\
104 		ASSERT(_rgnp->rgn_refcnt != 0);				\
105 		ASSERT(!(_rgnp->rgn_flags & SFMMU_REGION_FREE));	\
106 		ASSERT((_rgnp->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	\
107 		    SFMMU_REGION_HME);					\
108 		ASSERT((saddr) >= _rgnp->rgn_saddr);			\
109 		ASSERT((saddr) < _rgnp->rgn_saddr + _rgnp->rgn_size);	\
110 		ASSERT(_eaddr > _rgnp->rgn_saddr);			\
111 		ASSERT(_eaddr <= _rgnp->rgn_saddr + _rgnp->rgn_size);	\
112 	}
113 
114 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid)		\
115 {									\
116 		caddr_t _hsva;						\
117 		caddr_t _heva;						\
118 		caddr_t _rsva;						\
119 		caddr_t _reva;						\
120 		int	_ttesz = get_hblk_ttesz(hmeblkp);		\
121 		int	_flagtte;					\
122 		ASSERT((srdp)->srd_refcnt != 0);			\
123 		ASSERT((rid) < SFMMU_MAX_HME_REGIONS);			\
124 		ASSERT((rgnp)->rgn_id == rid);				\
125 		ASSERT(!((rgnp)->rgn_flags & SFMMU_REGION_FREE));	\
126 		ASSERT(((rgnp)->rgn_flags & SFMMU_REGION_TYPE_MASK) ==	\
127 		    SFMMU_REGION_HME);					\
128 		ASSERT(_ttesz <= (rgnp)->rgn_pgszc);			\
129 		_hsva = (caddr_t)get_hblk_base(hmeblkp);		\
130 		_heva = get_hblk_endaddr(hmeblkp);			\
131 		_rsva = (caddr_t)P2ALIGN(				\
132 		    (uintptr_t)(rgnp)->rgn_saddr, HBLK_MIN_BYTES);	\
133 		_reva = (caddr_t)P2ROUNDUP(				\
134 		    (uintptr_t)((rgnp)->rgn_saddr + (rgnp)->rgn_size),	\
135 		    HBLK_MIN_BYTES);					\
136 		ASSERT(_hsva >= _rsva);					\
137 		ASSERT(_hsva < _reva);					\
138 		ASSERT(_heva > _rsva);					\
139 		ASSERT(_heva <= _reva);					\
140 		_flagtte = (_ttesz < HBLK_MIN_TTESZ) ? HBLK_MIN_TTESZ : \
141 			_ttesz;						\
142 		ASSERT(rgnp->rgn_hmeflags & (0x1 << _flagtte));		\
143 }
144 
145 #else /* DEBUG */
146 #define	SFMMU_VALIDATE_HMERID(hat, rid, addr, len)
147 #define	SFMMU_VALIDATE_SHAREDHBLK(hmeblkp, srdp, rgnp, rid)
148 #endif /* DEBUG */
149 
150 #if defined(SF_ERRATA_57)
151 extern caddr_t errata57_limit;
152 #endif
153 
154 #define	HME8BLK_SZ_RND		((roundup(HME8BLK_SZ, sizeof (int64_t))) /  \
155 				(sizeof (int64_t)))
156 #define	HBLK_RESERVE		((struct hme_blk *)hblk_reserve)
157 
158 #define	HBLK_RESERVE_CNT	128
159 #define	HBLK_RESERVE_MIN	20
160 
161 static struct hme_blk		*freehblkp;
162 static kmutex_t			freehblkp_lock;
163 static int			freehblkcnt;
164 
165 static int64_t			hblk_reserve[HME8BLK_SZ_RND];
166 static kmutex_t			hblk_reserve_lock;
167 static kthread_t		*hblk_reserve_thread;
168 
169 static nucleus_hblk8_info_t	nucleus_hblk8;
170 static nucleus_hblk1_info_t	nucleus_hblk1;
171 
172 /*
173  * Data to manage per-cpu hmeblk pending queues, hmeblks are queued here
174  * after the initial phase of removing an hmeblk from the hash chain, see
175  * the detailed comment in sfmmu_hblk_hash_rm() for further details.
176  */
177 static cpu_hme_pend_t		*cpu_hme_pend;
178 static uint_t			cpu_hme_pend_thresh;
179 /*
180  * SFMMU specific hat functions
181  */
182 void	hat_pagecachectl(struct page *, int);
183 
184 /* flags for hat_pagecachectl */
185 #define	HAT_CACHE	0x1
186 #define	HAT_UNCACHE	0x2
187 #define	HAT_TMPNC	0x4
188 
189 /*
190  * Flag to allow the creation of non-cacheable translations
191  * to system memory. It is off by default. At the moment this
192  * flag is used by the ecache error injector. The error injector
193  * will turn it on when creating such a translation then shut it
194  * off when it's finished.
195  */
196 
197 int	sfmmu_allow_nc_trans = 0;
198 
199 /*
200  * Flag to disable large page support.
201  *	value of 1 => disable all large pages.
202  *	bits 1, 2, and 3 are to disable 64K, 512K and 4M pages respectively.
203  *
204  * For example, use the value 0x4 to disable 512K pages.
205  *
206  */
207 #define	LARGE_PAGES_OFF		0x1
208 
209 /*
210  * The disable_large_pages and disable_ism_large_pages variables control
211  * hat_memload_array and the page sizes to be used by ISM and the kernel.
212  *
213  * The disable_auto_data_large_pages and disable_auto_text_large_pages variables
214  * are only used to control which OOB pages to use at upper VM segment creation
215  * time, and are set in hat_init_pagesizes and used in the map_pgsz* routines.
216  * Their values may come from platform or CPU specific code to disable page
217  * sizes that should not be used.
218  *
219  * WARNING: 512K pages are currently not supported for ISM/DISM.
220  */
221 uint_t	disable_large_pages = 0;
222 uint_t	disable_ism_large_pages = (1 << TTE512K);
223 uint_t	disable_auto_data_large_pages = 0;
224 uint_t	disable_auto_text_large_pages = 0;
225 
226 /*
227  * Private sfmmu data structures for hat management
228  */
229 static struct kmem_cache *sfmmuid_cache;
230 static struct kmem_cache *mmuctxdom_cache;
231 
232 /*
233  * Private sfmmu data structures for tsb management
234  */
235 static struct kmem_cache *sfmmu_tsbinfo_cache;
236 static struct kmem_cache *sfmmu_tsb8k_cache;
237 static struct kmem_cache *sfmmu_tsb_cache[NLGRPS_MAX];
238 static vmem_t *kmem_bigtsb_arena;
239 static vmem_t *kmem_tsb_arena;
240 
241 /*
242  * sfmmu static variables for hmeblk resource management.
243  */
244 static vmem_t *hat_memload1_arena; /* HAT translation arena for sfmmu1_cache */
245 static struct kmem_cache *sfmmu8_cache;
246 static struct kmem_cache *sfmmu1_cache;
247 static struct kmem_cache *pa_hment_cache;
248 
249 static kmutex_t		ism_mlist_lock;	/* mutex for ism mapping list */
250 /*
251  * private data for ism
252  */
253 static struct kmem_cache *ism_blk_cache;
254 static struct kmem_cache *ism_ment_cache;
255 #define	ISMID_STARTADDR	NULL
256 
257 /*
258  * Region management data structures and function declarations.
259  */
260 
261 static void	sfmmu_leave_srd(sfmmu_t *);
262 static int	sfmmu_srdcache_constructor(void *, void *, int);
263 static void	sfmmu_srdcache_destructor(void *, void *);
264 static int	sfmmu_rgncache_constructor(void *, void *, int);
265 static void	sfmmu_rgncache_destructor(void *, void *);
266 static int	sfrgnmap_isnull(sf_region_map_t *);
267 static int	sfhmergnmap_isnull(sf_hmeregion_map_t *);
268 static int	sfmmu_scdcache_constructor(void *, void *, int);
269 static void	sfmmu_scdcache_destructor(void *, void *);
270 static void	sfmmu_rgn_cb_noop(caddr_t, caddr_t, caddr_t,
271     size_t, void *, u_offset_t);
272 
273 static uint_t srd_hashmask = SFMMU_MAX_SRD_BUCKETS - 1;
274 static sf_srd_bucket_t *srd_buckets;
275 static struct kmem_cache *srd_cache;
276 static uint_t srd_rgn_hashmask = SFMMU_MAX_REGION_BUCKETS - 1;
277 static struct kmem_cache *region_cache;
278 static struct kmem_cache *scd_cache;
279 
280 #ifdef sun4v
281 int use_bigtsb_arena = 1;
282 #else
283 int use_bigtsb_arena = 0;
284 #endif
285 
286 /* External /etc/system tunable, for turning on&off the shctx support */
287 int disable_shctx = 0;
288 /* Internal variable, set by MD if the HW supports shctx feature */
289 int shctx_on = 0;
290 
291 #ifdef DEBUG
292 static void check_scd_sfmmu_list(sfmmu_t **, sfmmu_t *, int);
293 #endif
294 static void sfmmu_to_scd_list(sfmmu_t **, sfmmu_t *);
295 static void sfmmu_from_scd_list(sfmmu_t **, sfmmu_t *);
296 
297 static sf_scd_t *sfmmu_alloc_scd(sf_srd_t *, sf_region_map_t *);
298 static void sfmmu_find_scd(sfmmu_t *);
299 static void sfmmu_join_scd(sf_scd_t *, sfmmu_t *);
300 static void sfmmu_finish_join_scd(sfmmu_t *);
301 static void sfmmu_leave_scd(sfmmu_t *, uchar_t);
302 static void sfmmu_destroy_scd(sf_srd_t *, sf_scd_t *, sf_region_map_t *);
303 static int sfmmu_alloc_scd_tsbs(sf_srd_t *, sf_scd_t *);
304 static void sfmmu_free_scd_tsbs(sfmmu_t *);
305 static void sfmmu_tsb_inv_ctx(sfmmu_t *);
306 static int find_ism_rid(sfmmu_t *, sfmmu_t *, caddr_t, uint_t *);
307 static void sfmmu_ism_hatflags(sfmmu_t *, int);
308 static int sfmmu_srd_lock_held(sf_srd_t *);
309 static void sfmmu_remove_scd(sf_scd_t **, sf_scd_t *);
310 static void sfmmu_add_scd(sf_scd_t **headp, sf_scd_t *);
311 static void sfmmu_link_scd_to_regions(sf_srd_t *, sf_scd_t *);
312 static void sfmmu_unlink_scd_from_regions(sf_srd_t *, sf_scd_t *);
313 static void sfmmu_link_to_hmeregion(sfmmu_t *, sf_region_t *);
314 static void sfmmu_unlink_from_hmeregion(sfmmu_t *, sf_region_t *);
315 
316 /*
317  * ``hat_lock'' is a hashed mutex lock for protecting sfmmu TSB lists,
318  * HAT flags, synchronizing TLB/TSB coherency, and context management.
319  * The lock is hashed on the sfmmup since the case where we need to lock
320  * all processes is rare but does occur (e.g. we need to unload a shared
321  * mapping from all processes using the mapping).  We have a lot of buckets,
322  * and each slab of sfmmu_t's can use about a quarter of them, giving us
323  * a fairly good distribution without wasting too much space and overhead
324  * when we have to grab them all.
325  */
326 #define	SFMMU_NUM_LOCK	128		/* must be power of two */
327 hatlock_t	hat_lock[SFMMU_NUM_LOCK];
328 
329 /*
330  * Hash algorithm optimized for a small number of slabs.
331  *  7 is (highbit((sizeof sfmmu_t)) - 1)
332  * This hash algorithm is based upon the knowledge that sfmmu_t's come from a
333  * kmem_cache, and thus they will be sequential within that cache.  In
334  * addition, each new slab will have a different "color" up to cache_maxcolor
335  * which will skew the hashing for each successive slab which is allocated.
336  * If the size of sfmmu_t changed to a larger size, this algorithm may need
337  * to be revisited.
338  */
339 #define	TSB_HASH_SHIFT_BITS (7)
340 #define	PTR_HASH(x) ((uintptr_t)x >> TSB_HASH_SHIFT_BITS)
341 
342 #ifdef DEBUG
343 int tsb_hash_debug = 0;
344 #define	TSB_HASH(sfmmup)	\
345 	(tsb_hash_debug ? &hat_lock[0] : \
346 	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)])
347 #else	/* DEBUG */
348 #define	TSB_HASH(sfmmup)	&hat_lock[PTR_HASH(sfmmup) & (SFMMU_NUM_LOCK-1)]
349 #endif	/* DEBUG */
350 
351 
352 /* sfmmu_replace_tsb() return codes. */
353 typedef enum tsb_replace_rc {
354 	TSB_SUCCESS,
355 	TSB_ALLOCFAIL,
356 	TSB_LOSTRACE,
357 	TSB_ALREADY_SWAPPED,
358 	TSB_CANTGROW
359 } tsb_replace_rc_t;
360 
361 /*
362  * Flags for TSB allocation routines.
363  */
364 #define	TSB_ALLOC	0x01
365 #define	TSB_FORCEALLOC	0x02
366 #define	TSB_GROW	0x04
367 #define	TSB_SHRINK	0x08
368 #define	TSB_SWAPIN	0x10
369 
370 /*
371  * Support for HAT callbacks.
372  */
373 #define	SFMMU_MAX_RELOC_CALLBACKS	10
374 int sfmmu_max_cb_id = SFMMU_MAX_RELOC_CALLBACKS;
375 static id_t sfmmu_cb_nextid = 0;
376 static id_t sfmmu_tsb_cb_id;
377 struct sfmmu_callback *sfmmu_cb_table;
378 
379 kmutex_t	kpr_mutex;
380 kmutex_t	kpr_suspendlock;
381 kthread_t	*kreloc_thread;
382 
383 /*
384  * Enable VA->PA translation sanity checking on DEBUG kernels.
385  * Disabled by default.  This is incompatible with some
386  * drivers (error injector, RSM) so if it breaks you get
387  * to keep both pieces.
388  */
389 int hat_check_vtop = 0;
390 
391 /*
392  * Private sfmmu routines (prototypes)
393  */
394 static struct hme_blk *sfmmu_shadow_hcreate(sfmmu_t *, caddr_t, int, uint_t);
395 static struct	hme_blk *sfmmu_hblk_alloc(sfmmu_t *, caddr_t,
396 			struct hmehash_bucket *, uint_t, hmeblk_tag, uint_t,
397 			uint_t);
398 static caddr_t	sfmmu_hblk_unload(struct hat *, struct hme_blk *, caddr_t,
399 			caddr_t, demap_range_t *, uint_t);
400 static caddr_t	sfmmu_hblk_sync(struct hat *, struct hme_blk *, caddr_t,
401 			caddr_t, int);
402 static void	sfmmu_hblk_free(struct hme_blk **);
403 static void	sfmmu_hblks_list_purge(struct hme_blk **, int);
404 static uint_t	sfmmu_get_free_hblk(struct hme_blk **, uint_t);
405 static uint_t	sfmmu_put_free_hblk(struct hme_blk *, uint_t);
406 static struct hme_blk *sfmmu_hblk_steal(int);
407 static int	sfmmu_steal_this_hblk(struct hmehash_bucket *,
408 			struct hme_blk *, uint64_t, struct hme_blk *);
409 static caddr_t	sfmmu_hblk_unlock(struct hme_blk *, caddr_t, caddr_t);
410 
411 static void	hat_do_memload_array(struct hat *, caddr_t, size_t,
412 		    struct page **, uint_t, uint_t, uint_t);
413 static void	hat_do_memload(struct hat *, caddr_t, struct page *,
414 		    uint_t, uint_t, uint_t);
415 static void	sfmmu_memload_batchsmall(struct hat *, caddr_t, page_t **,
416 		    uint_t, uint_t, pgcnt_t, uint_t);
417 void		sfmmu_tteload(struct hat *, tte_t *, caddr_t, page_t *,
418 			uint_t);
419 static int	sfmmu_tteload_array(sfmmu_t *, tte_t *, caddr_t, page_t **,
420 			uint_t, uint_t);
421 static struct hmehash_bucket *sfmmu_tteload_acquire_hashbucket(sfmmu_t *,
422 					caddr_t, int, uint_t);
423 static struct hme_blk *sfmmu_tteload_find_hmeblk(sfmmu_t *,
424 			struct hmehash_bucket *, caddr_t, uint_t, uint_t,
425 			uint_t);
426 static int	sfmmu_tteload_addentry(sfmmu_t *, struct hme_blk *, tte_t *,
427 			caddr_t, page_t **, uint_t, uint_t);
428 static void	sfmmu_tteload_release_hashbucket(struct hmehash_bucket *);
429 
430 static int	sfmmu_pagearray_setup(caddr_t, page_t **, tte_t *, int);
431 static pfn_t	sfmmu_uvatopfn(caddr_t, sfmmu_t *, tte_t *);
432 void		sfmmu_memtte(tte_t *, pfn_t, uint_t, int);
433 #ifdef VAC
434 static void	sfmmu_vac_conflict(struct hat *, caddr_t, page_t *);
435 static int	sfmmu_vacconflict_array(caddr_t, page_t *, int *);
436 int	tst_tnc(page_t *pp, pgcnt_t);
437 void	conv_tnc(page_t *pp, int);
438 #endif
439 
440 static void	sfmmu_get_ctx(sfmmu_t *);
441 static void	sfmmu_free_sfmmu(sfmmu_t *);
442 
443 static void	sfmmu_ttesync(struct hat *, caddr_t, tte_t *, page_t *);
444 static void	sfmmu_chgattr(struct hat *, caddr_t, size_t, uint_t, int);
445 
446 cpuset_t	sfmmu_pageunload(page_t *, struct sf_hment *, int);
447 static void	hat_pagereload(struct page *, struct page *);
448 static cpuset_t	sfmmu_pagesync(page_t *, struct sf_hment *, uint_t);
449 #ifdef VAC
450 void	sfmmu_page_cache_array(page_t *, int, int, pgcnt_t);
451 static void	sfmmu_page_cache(page_t *, int, int, int);
452 #endif
453 
454 cpuset_t	sfmmu_rgntlb_demap(caddr_t, sf_region_t *,
455     struct hme_blk *, int);
456 static void	sfmmu_tlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
457 			pfn_t, int, int, int, int);
458 static void	sfmmu_ismtlbcache_demap(caddr_t, sfmmu_t *, struct hme_blk *,
459 			pfn_t, int);
460 static void	sfmmu_tlb_demap(caddr_t, sfmmu_t *, struct hme_blk *, int, int);
461 static void	sfmmu_tlb_range_demap(demap_range_t *);
462 static void	sfmmu_invalidate_ctx(sfmmu_t *);
463 static void	sfmmu_sync_mmustate(sfmmu_t *);
464 
465 static void	sfmmu_tsbinfo_setup_phys(struct tsb_info *, pfn_t);
466 static int	sfmmu_tsbinfo_alloc(struct tsb_info **, int, int, uint_t,
467 			sfmmu_t *);
468 static void	sfmmu_tsb_free(struct tsb_info *);
469 static void	sfmmu_tsbinfo_free(struct tsb_info *);
470 static int	sfmmu_init_tsbinfo(struct tsb_info *, int, int, uint_t,
471 			sfmmu_t *);
472 static void	sfmmu_tsb_chk_reloc(sfmmu_t *, hatlock_t *);
473 static void	sfmmu_tsb_swapin(sfmmu_t *, hatlock_t *);
474 static int	sfmmu_select_tsb_szc(pgcnt_t);
475 static void	sfmmu_mod_tsb(sfmmu_t *, caddr_t, tte_t *, int);
476 #define		sfmmu_load_tsb(sfmmup, vaddr, tte, szc) \
477 	sfmmu_mod_tsb(sfmmup, vaddr, tte, szc)
478 #define		sfmmu_unload_tsb(sfmmup, vaddr, szc)    \
479 	sfmmu_mod_tsb(sfmmup, vaddr, NULL, szc)
480 static void	sfmmu_copy_tsb(struct tsb_info *, struct tsb_info *);
481 static tsb_replace_rc_t sfmmu_replace_tsb(sfmmu_t *, struct tsb_info *, uint_t,
482     hatlock_t *, uint_t);
483 static void	sfmmu_size_tsb(sfmmu_t *, int, uint64_t, uint64_t, int);
484 
485 #ifdef VAC
486 void	sfmmu_cache_flush(pfn_t, int);
487 void	sfmmu_cache_flushcolor(int, pfn_t);
488 #endif
489 static caddr_t	sfmmu_hblk_chgattr(sfmmu_t *, struct hme_blk *, caddr_t,
490 			caddr_t, demap_range_t *, uint_t, int);
491 
492 static uint64_t	sfmmu_vtop_attr(uint_t, int mode, tte_t *);
493 static uint_t	sfmmu_ptov_attr(tte_t *);
494 static caddr_t	sfmmu_hblk_chgprot(sfmmu_t *, struct hme_blk *, caddr_t,
495 			caddr_t, demap_range_t *, uint_t);
496 static uint_t	sfmmu_vtop_prot(uint_t, uint_t *);
497 static int	sfmmu_idcache_constructor(void *, void *, int);
498 static void	sfmmu_idcache_destructor(void *, void *);
499 static int	sfmmu_hblkcache_constructor(void *, void *, int);
500 static void	sfmmu_hblkcache_destructor(void *, void *);
501 static void	sfmmu_hblkcache_reclaim(void *);
502 static void	sfmmu_shadow_hcleanup(sfmmu_t *, struct hme_blk *,
503 			struct hmehash_bucket *);
504 static void	sfmmu_hblk_hash_rm(struct hmehash_bucket *, struct hme_blk *,
505 			struct hme_blk *, struct hme_blk **, int);
506 static void	sfmmu_hblk_hash_add(struct hmehash_bucket *, struct hme_blk *,
507 			uint64_t);
508 static struct hme_blk *sfmmu_check_pending_hblks(int);
509 static void	sfmmu_free_hblks(sfmmu_t *, caddr_t, caddr_t, int);
510 static void	sfmmu_cleanup_rhblk(sf_srd_t *, caddr_t, uint_t, int);
511 static void	sfmmu_unload_hmeregion_va(sf_srd_t *, uint_t, caddr_t, caddr_t,
512 			int, caddr_t *);
513 static void	sfmmu_unload_hmeregion(sf_srd_t *, sf_region_t *);
514 
515 static void	sfmmu_rm_large_mappings(page_t *, int);
516 
517 static void	hat_lock_init(void);
518 static void	hat_kstat_init(void);
519 static int	sfmmu_kstat_percpu_update(kstat_t *ksp, int rw);
520 static void	sfmmu_set_scd_rttecnt(sf_srd_t *, sf_scd_t *);
521 static	int	sfmmu_is_rgnva(sf_srd_t *, caddr_t, ulong_t, ulong_t);
522 static void	sfmmu_check_page_sizes(sfmmu_t *, int);
523 int	fnd_mapping_sz(page_t *);
524 static void	iment_add(struct ism_ment *,  struct hat *);
525 static void	iment_sub(struct ism_ment *, struct hat *);
526 static pgcnt_t	ism_tsb_entries(sfmmu_t *, int szc);
527 extern void	sfmmu_setup_tsbinfo(sfmmu_t *);
528 extern void	sfmmu_clear_utsbinfo(void);
529 
530 static void		sfmmu_ctx_wrap_around(mmu_ctx_t *, boolean_t);
531 
532 extern int vpm_enable;
533 
534 /* kpm globals */
535 #ifdef	DEBUG
536 /*
537  * Enable trap level tsbmiss handling
538  */
539 int	kpm_tsbmtl = 1;
540 
541 /*
542  * Flush the TLB on kpm mapout. Note: Xcalls are used (again) for the
543  * required TLB shootdowns in this case, so handle w/ care. Off by default.
544  */
545 int	kpm_tlb_flush;
546 #endif	/* DEBUG */
547 
548 static void	*sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *, size_t, int);
549 
550 #ifdef DEBUG
551 static void	sfmmu_check_hblk_flist();
552 #endif
553 
554 /*
555  * Semi-private sfmmu data structures.  Some of them are initialize in
556  * startup or in hat_init. Some of them are private but accessed by
557  * assembly code or mach_sfmmu.c
558  */
559 struct hmehash_bucket *uhme_hash;	/* user hmeblk hash table */
560 struct hmehash_bucket *khme_hash;	/* kernel hmeblk hash table */
561 uint64_t	uhme_hash_pa;		/* PA of uhme_hash */
562 uint64_t	khme_hash_pa;		/* PA of khme_hash */
563 int		uhmehash_num;		/* # of buckets in user hash table */
564 int		khmehash_num;		/* # of buckets in kernel hash table */
565 
566 uint_t		max_mmu_ctxdoms = 0;	/* max context domains in the system */
567 mmu_ctx_t	**mmu_ctxs_tbl;		/* global array of context domains */
568 uint64_t	mmu_saved_gnum = 0;	/* to init incoming MMUs' gnums */
569 
570 #define	DEFAULT_NUM_CTXS_PER_MMU 8192
571 static uint_t	nctxs = DEFAULT_NUM_CTXS_PER_MMU;
572 
573 int		cache;			/* describes system cache */
574 
575 caddr_t		ktsb_base;		/* kernel 8k-indexed tsb base address */
576 uint64_t	ktsb_pbase;		/* kernel 8k-indexed tsb phys address */
577 int		ktsb_szcode;		/* kernel 8k-indexed tsb size code */
578 int		ktsb_sz;		/* kernel 8k-indexed tsb size */
579 
580 caddr_t		ktsb4m_base;		/* kernel 4m-indexed tsb base address */
581 uint64_t	ktsb4m_pbase;		/* kernel 4m-indexed tsb phys address */
582 int		ktsb4m_szcode;		/* kernel 4m-indexed tsb size code */
583 int		ktsb4m_sz;		/* kernel 4m-indexed tsb size */
584 
585 uint64_t	kpm_tsbbase;		/* kernel seg_kpm 4M TSB base address */
586 int		kpm_tsbsz;		/* kernel seg_kpm 4M TSB size code */
587 uint64_t	kpmsm_tsbbase;		/* kernel seg_kpm 8K TSB base address */
588 int		kpmsm_tsbsz;		/* kernel seg_kpm 8K TSB size code */
589 
590 #ifndef sun4v
591 int		utsb_dtlb_ttenum = -1;	/* index in TLB for utsb locked TTE */
592 int		utsb4m_dtlb_ttenum = -1; /* index in TLB for 4M TSB TTE */
593 int		dtlb_resv_ttenum;	/* index in TLB of first reserved TTE */
594 caddr_t		utsb_vabase;		/* reserved kernel virtual memory */
595 caddr_t		utsb4m_vabase;		/* for trap handler TSB accesses */
596 #endif /* sun4v */
597 uint64_t	tsb_alloc_bytes = 0;	/* bytes allocated to TSBs */
598 vmem_t		*kmem_tsb_default_arena[NLGRPS_MAX];	/* For dynamic TSBs */
599 vmem_t		*kmem_bigtsb_default_arena[NLGRPS_MAX]; /* dynamic 256M TSBs */
600 
601 /*
602  * Size to use for TSB slabs.  Future platforms that support page sizes
603  * larger than 4M may wish to change these values, and provide their own
604  * assembly macros for building and decoding the TSB base register contents.
605  * Note disable_large_pages will override the value set here.
606  */
607 static	uint_t tsb_slab_ttesz = TTE4M;
608 size_t	tsb_slab_size = MMU_PAGESIZE4M;
609 uint_t	tsb_slab_shift = MMU_PAGESHIFT4M;
610 /* PFN mask for TTE */
611 size_t	tsb_slab_mask = MMU_PAGEOFFSET4M >> MMU_PAGESHIFT;
612 
613 /*
614  * Size to use for TSB slabs.  These are used only when 256M tsb arenas
615  * exist.
616  */
617 static uint_t	bigtsb_slab_ttesz = TTE256M;
618 static size_t	bigtsb_slab_size = MMU_PAGESIZE256M;
619 static uint_t	bigtsb_slab_shift = MMU_PAGESHIFT256M;
620 /* 256M page alignment for 8K pfn */
621 static size_t	bigtsb_slab_mask = MMU_PAGEOFFSET256M >> MMU_PAGESHIFT;
622 
623 /* largest TSB size to grow to, will be smaller on smaller memory systems */
624 static int	tsb_max_growsize = 0;
625 
626 /*
627  * Tunable parameters dealing with TSB policies.
628  */
629 
630 /*
631  * This undocumented tunable forces all 8K TSBs to be allocated from
632  * the kernel heap rather than from the kmem_tsb_default_arena arenas.
633  */
634 #ifdef	DEBUG
635 int	tsb_forceheap = 0;
636 #endif	/* DEBUG */
637 
638 /*
639  * Decide whether to use per-lgroup arenas, or one global set of
640  * TSB arenas.  The default is not to break up per-lgroup, since
641  * most platforms don't recognize any tangible benefit from it.
642  */
643 int	tsb_lgrp_affinity = 0;
644 
645 /*
646  * Used for growing the TSB based on the process RSS.
647  * tsb_rss_factor is based on the smallest TSB, and is
648  * shifted by the TSB size to determine if we need to grow.
649  * The default will grow the TSB if the number of TTEs for
650  * this page size exceeds 75% of the number of TSB entries,
651  * which should _almost_ eliminate all conflict misses
652  * (at the expense of using up lots and lots of memory).
653  */
654 #define	TSB_RSS_FACTOR		(TSB_ENTRIES(TSB_MIN_SZCODE) * 0.75)
655 #define	SFMMU_RSS_TSBSIZE(tsbszc)	(tsb_rss_factor << tsbszc)
656 #define	SELECT_TSB_SIZECODE(pgcnt) ( \
657 	(enable_tsb_rss_sizing)? sfmmu_select_tsb_szc(pgcnt) : \
658 	default_tsb_size)
659 #define	TSB_OK_SHRINK()	\
660 	(tsb_alloc_bytes > tsb_alloc_hiwater || freemem < desfree)
661 #define	TSB_OK_GROW()	\
662 	(tsb_alloc_bytes < tsb_alloc_hiwater && freemem > desfree)
663 
664 int	enable_tsb_rss_sizing = 1;
665 int	tsb_rss_factor	= (int)TSB_RSS_FACTOR;
666 
667 /* which TSB size code to use for new address spaces or if rss sizing off */
668 int default_tsb_size = TSB_8K_SZCODE;
669 
670 static uint64_t tsb_alloc_hiwater; /* limit TSB reserved memory */
671 uint64_t tsb_alloc_hiwater_factor; /* tsb_alloc_hiwater = physmem / this */
672 #define	TSB_ALLOC_HIWATER_FACTOR_DEFAULT	32
673 
674 #ifdef DEBUG
675 static int tsb_random_size = 0;	/* set to 1 to test random tsb sizes on alloc */
676 static int tsb_grow_stress = 0;	/* if set to 1, keep replacing TSB w/ random */
677 static int tsb_alloc_mtbf = 0;	/* fail allocation every n attempts */
678 static int tsb_alloc_fail_mtbf = 0;
679 static int tsb_alloc_count = 0;
680 #endif /* DEBUG */
681 
682 /* if set to 1, will remap valid TTEs when growing TSB. */
683 int tsb_remap_ttes = 1;
684 
685 /*
686  * If we have more than this many mappings, allocate a second TSB.
687  * This default is chosen because the I/D fully associative TLBs are
688  * assumed to have at least 8 available entries. Platforms with a
689  * larger fully-associative TLB could probably override the default.
690  */
691 
692 #ifdef sun4v
693 int tsb_sectsb_threshold = 0;
694 #else
695 int tsb_sectsb_threshold = 8;
696 #endif
697 
698 /*
699  * kstat data
700  */
701 struct sfmmu_global_stat sfmmu_global_stat;
702 struct sfmmu_tsbsize_stat sfmmu_tsbsize_stat;
703 
704 /*
705  * Global data
706  */
707 sfmmu_t		*ksfmmup;		/* kernel's hat id */
708 
709 #ifdef DEBUG
710 static void	chk_tte(tte_t *, tte_t *, tte_t *, struct hme_blk *);
711 #endif
712 
713 /* sfmmu locking operations */
714 static kmutex_t *sfmmu_mlspl_enter(struct page *, int);
715 static int	sfmmu_mlspl_held(struct page *, int);
716 
717 kmutex_t *sfmmu_page_enter(page_t *);
718 void	sfmmu_page_exit(kmutex_t *);
719 int	sfmmu_page_spl_held(struct page *);
720 
721 /* sfmmu internal locking operations - accessed directly */
722 static void	sfmmu_mlist_reloc_enter(page_t *, page_t *,
723 				kmutex_t **, kmutex_t **);
724 static void	sfmmu_mlist_reloc_exit(kmutex_t *, kmutex_t *);
725 static hatlock_t *
726 		sfmmu_hat_enter(sfmmu_t *);
727 static hatlock_t *
728 		sfmmu_hat_tryenter(sfmmu_t *);
729 static void	sfmmu_hat_exit(hatlock_t *);
730 static void	sfmmu_hat_lock_all(void);
731 static void	sfmmu_hat_unlock_all(void);
732 static void	sfmmu_ismhat_enter(sfmmu_t *, int);
733 static void	sfmmu_ismhat_exit(sfmmu_t *, int);
734 
735 kpm_hlk_t	*kpmp_table;
736 uint_t		kpmp_table_sz;	/* must be a power of 2 */
737 uchar_t		kpmp_shift;
738 
739 kpm_shlk_t	*kpmp_stable;
740 uint_t		kpmp_stable_sz;	/* must be a power of 2 */
741 
742 /*
743  * SPL_TABLE_SIZE is 2 * NCPU, but no smaller than 128.
744  * SPL_SHIFT is log2(SPL_TABLE_SIZE).
745  */
746 #if ((2*NCPU_P2) > 128)
747 #define	SPL_SHIFT	((unsigned)(NCPU_LOG2 + 1))
748 #else
749 #define	SPL_SHIFT	7U
750 #endif
751 #define	SPL_TABLE_SIZE	(1U << SPL_SHIFT)
752 #define	SPL_MASK	(SPL_TABLE_SIZE - 1)
753 
754 /*
755  * We shift by PP_SHIFT to take care of the low-order 0 bits of a page_t
756  * and by multiples of SPL_SHIFT to get as many varied bits as we can.
757  */
758 #define	SPL_INDEX(pp) \
759 	((((uintptr_t)(pp) >> PP_SHIFT) ^ \
760 	((uintptr_t)(pp) >> (PP_SHIFT + SPL_SHIFT)) ^ \
761 	((uintptr_t)(pp) >> (PP_SHIFT + SPL_SHIFT * 2)) ^ \
762 	((uintptr_t)(pp) >> (PP_SHIFT + SPL_SHIFT * 3))) & \
763 	SPL_MASK)
764 
765 #define	SPL_HASH(pp)    \
766 	(&sfmmu_page_lock[SPL_INDEX(pp)].pad_mutex)
767 
768 static	pad_mutex_t	sfmmu_page_lock[SPL_TABLE_SIZE];
769 
770 /* Array of mutexes protecting a page's mapping list and p_nrm field. */
771 
772 #define	MML_TABLE_SIZE	SPL_TABLE_SIZE
773 #define	MLIST_HASH(pp)	(&mml_table[SPL_INDEX(pp)].pad_mutex)
774 
775 static pad_mutex_t	mml_table[MML_TABLE_SIZE];
776 
777 /*
778  * hat_unload_callback() will group together callbacks in order
779  * to avoid xt_sync() calls.  This is the maximum size of the group.
780  */
781 #define	MAX_CB_ADDR	32
782 
783 tte_t	hw_tte;
784 static ulong_t sfmmu_dmr_maxbit = DMR_MAXBIT;
785 
786 static char	*mmu_ctx_kstat_names[] = {
787 	"mmu_ctx_tsb_exceptions",
788 	"mmu_ctx_tsb_raise_exception",
789 	"mmu_ctx_wrap_around",
790 };
791 
792 /*
793  * Wrapper for vmem_xalloc since vmem_create only allows limited
794  * parameters for vm_source_alloc functions.  This function allows us
795  * to specify alignment consistent with the size of the object being
796  * allocated.
797  */
798 static void *
sfmmu_vmem_xalloc_aligned_wrapper(vmem_t * vmp,size_t size,int vmflag)799 sfmmu_vmem_xalloc_aligned_wrapper(vmem_t *vmp, size_t size, int vmflag)
800 {
801 	return (vmem_xalloc(vmp, size, size, 0, 0, NULL, NULL, vmflag));
802 }
803 
804 /* Common code for setting tsb_alloc_hiwater. */
805 #define	SFMMU_SET_TSB_ALLOC_HIWATER(pages)	tsb_alloc_hiwater = \
806 		ptob(pages) / tsb_alloc_hiwater_factor
807 
808 /*
809  * Set tsb_max_growsize to allow at most all of physical memory to be mapped by
810  * a single TSB.  physmem is the number of physical pages so we need physmem 8K
811  * TTEs to represent all those physical pages.  We round this up by using
812  * 1<<highbit().  To figure out which size code to use, remember that the size
813  * code is just an amount to shift the smallest TSB size to get the size of
814  * this TSB.  So we subtract that size, TSB_START_SIZE, from highbit() (or
815  * highbit() - 1) to get the size code for the smallest TSB that can represent
816  * all of physical memory, while erring on the side of too much.
817  *
818  * Restrict tsb_max_growsize to make sure that:
819  *	1) TSBs can't grow larger than the TSB slab size
820  *	2) TSBs can't grow larger than UTSB_MAX_SZCODE.
821  */
822 #define	SFMMU_SET_TSB_MAX_GROWSIZE(pages) {				\
823 	int	_i, _szc, _slabszc, _tsbszc;				\
824 									\
825 	_i = highbit(pages);						\
826 	if ((1 << (_i - 1)) == (pages))					\
827 		_i--;		/* 2^n case, round down */              \
828 	_szc = _i - TSB_START_SIZE;					\
829 	_slabszc = bigtsb_slab_shift - (TSB_START_SIZE + TSB_ENTRY_SHIFT); \
830 	_tsbszc = MIN(_szc, _slabszc);                                  \
831 	tsb_max_growsize = MIN(_tsbszc, UTSB_MAX_SZCODE);               \
832 }
833 
834 /*
835  * Given a pointer to an sfmmu and a TTE size code, return a pointer to the
836  * tsb_info which handles that TTE size.
837  */
838 #define	SFMMU_GET_TSBINFO(tsbinfop, sfmmup, tte_szc) {			\
839 	(tsbinfop) = (sfmmup)->sfmmu_tsb;				\
840 	ASSERT(((tsbinfop)->tsb_flags & TSB_SHAREDCTX) ||		\
841 	    sfmmu_hat_lock_held(sfmmup));				\
842 	if ((tte_szc) >= TTE4M)	{					\
843 		ASSERT((tsbinfop) != NULL);				\
844 		(tsbinfop) = (tsbinfop)->tsb_next;			\
845 	}								\
846 }
847 
848 /*
849  * Macro to use to unload entries from the TSB.
850  * It has knowledge of which page sizes get replicated in the TSB
851  * and will call the appropriate unload routine for the appropriate size.
852  */
853 #define	SFMMU_UNLOAD_TSB(addr, sfmmup, hmeblkp, ismhat)		\
854 {									\
855 	int ttesz = get_hblk_ttesz(hmeblkp);				\
856 	if (ttesz == TTE8K || ttesz == TTE4M) {				\
857 		sfmmu_unload_tsb(sfmmup, addr, ttesz);			\
858 	} else {							\
859 		caddr_t sva = ismhat ? addr :				\
860 		    (caddr_t)get_hblk_base(hmeblkp);			\
861 		caddr_t eva = sva + get_hblk_span(hmeblkp);		\
862 		ASSERT(addr >= sva && addr < eva);			\
863 		sfmmu_unload_tsb_range(sfmmup, sva, eva, ttesz);	\
864 	}								\
865 }
866 
867 
868 /* Update tsb_alloc_hiwater after memory is configured. */
869 /*ARGSUSED*/
870 static void
sfmmu_update_post_add(void * arg,pgcnt_t delta_pages)871 sfmmu_update_post_add(void *arg, pgcnt_t delta_pages)
872 {
873 	/* Assumes physmem has already been updated. */
874 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
875 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
876 }
877 
878 /*
879  * Update tsb_alloc_hiwater before memory is deleted.  We'll do nothing here
880  * and update tsb_alloc_hiwater and tsb_max_growsize after the memory is
881  * deleted.
882  */
883 /*ARGSUSED*/
884 static int
sfmmu_update_pre_del(void * arg,pgcnt_t delta_pages)885 sfmmu_update_pre_del(void *arg, pgcnt_t delta_pages)
886 {
887 	return (0);
888 }
889 
890 /* Update tsb_alloc_hiwater after memory fails to be unconfigured. */
891 /*ARGSUSED*/
892 static void
sfmmu_update_post_del(void * arg,pgcnt_t delta_pages,int cancelled)893 sfmmu_update_post_del(void *arg, pgcnt_t delta_pages, int cancelled)
894 {
895 	/*
896 	 * Whether the delete was cancelled or not, just go ahead and update
897 	 * tsb_alloc_hiwater and tsb_max_growsize.
898 	 */
899 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
900 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
901 }
902 
903 static kphysm_setup_vector_t sfmmu_update_vec = {
904 	KPHYSM_SETUP_VECTOR_VERSION,	/* version */
905 	sfmmu_update_post_add,		/* post_add */
906 	sfmmu_update_pre_del,		/* pre_del */
907 	sfmmu_update_post_del		/* post_del */
908 };
909 
910 
911 /*
912  * HME_BLK HASH PRIMITIVES
913  */
914 
915 /*
916  * Enter a hme on the mapping list for page pp.
917  * When large pages are more prevalent in the system we might want to
918  * keep the mapping list in ascending order by the hment size. For now,
919  * small pages are more frequent, so don't slow it down.
920  */
921 #define	HME_ADD(hme, pp)					\
922 {								\
923 	ASSERT(sfmmu_mlist_held(pp));				\
924 								\
925 	hme->hme_prev = NULL;					\
926 	hme->hme_next = pp->p_mapping;				\
927 	hme->hme_page = pp;					\
928 	if (pp->p_mapping) {					\
929 		((struct sf_hment *)(pp->p_mapping))->hme_prev = hme;\
930 		ASSERT(pp->p_share > 0);			\
931 	} else  {						\
932 		/* EMPTY */					\
933 		ASSERT(pp->p_share == 0);			\
934 	}							\
935 	pp->p_mapping = hme;					\
936 	pp->p_share++;						\
937 }
938 
939 /*
940  * Enter a hme on the mapping list for page pp.
941  * If we are unmapping a large translation, we need to make sure that the
942  * change is reflect in the corresponding bit of the p_index field.
943  */
944 #define	HME_SUB(hme, pp)					\
945 {								\
946 	ASSERT(sfmmu_mlist_held(pp));				\
947 	ASSERT(hme->hme_page == pp || IS_PAHME(hme));		\
948 								\
949 	if (pp->p_mapping == NULL) {				\
950 		panic("hme_remove - no mappings");		\
951 	}							\
952 								\
953 	membar_stst();	/* ensure previous stores finish */	\
954 								\
955 	ASSERT(pp->p_share > 0);				\
956 	pp->p_share--;						\
957 								\
958 	if (hme->hme_prev) {					\
959 		ASSERT(pp->p_mapping != hme);			\
960 		ASSERT(hme->hme_prev->hme_page == pp ||		\
961 			IS_PAHME(hme->hme_prev));		\
962 		hme->hme_prev->hme_next = hme->hme_next;	\
963 	} else {						\
964 		ASSERT(pp->p_mapping == hme);			\
965 		pp->p_mapping = hme->hme_next;			\
966 		ASSERT((pp->p_mapping == NULL) ?		\
967 			(pp->p_share == 0) : 1);		\
968 	}							\
969 								\
970 	if (hme->hme_next) {					\
971 		ASSERT(hme->hme_next->hme_page == pp ||		\
972 			IS_PAHME(hme->hme_next));		\
973 		hme->hme_next->hme_prev = hme->hme_prev;	\
974 	}							\
975 								\
976 	/* zero out the entry */				\
977 	hme->hme_next = NULL;					\
978 	hme->hme_prev = NULL;					\
979 	hme->hme_page = NULL;					\
980 								\
981 	if (hme_size(hme) > TTE8K) {				\
982 		/* remove mappings for remainder of large pg */	\
983 		sfmmu_rm_large_mappings(pp, hme_size(hme));	\
984 	}							\
985 }
986 
987 /*
988  * This function returns the hment given the hme_blk and a vaddr.
989  * It assumes addr has already been checked to belong to hme_blk's
990  * range.
991  */
992 #define	HBLKTOHME(hment, hmeblkp, addr)					\
993 {									\
994 	int index;							\
995 	HBLKTOHME_IDX(hment, hmeblkp, addr, index)			\
996 }
997 
998 /*
999  * Version of HBLKTOHME that also returns the index in hmeblkp
1000  * of the hment.
1001  */
1002 #define	HBLKTOHME_IDX(hment, hmeblkp, addr, idx)			\
1003 {									\
1004 	ASSERT(in_hblk_range((hmeblkp), (addr)));			\
1005 									\
1006 	if (get_hblk_ttesz(hmeblkp) == TTE8K) {				\
1007 		idx = (((uintptr_t)(addr) >> MMU_PAGESHIFT) & (NHMENTS-1)); \
1008 	} else								\
1009 		idx = 0;						\
1010 									\
1011 	(hment) = &(hmeblkp)->hblk_hme[idx];				\
1012 }
1013 
1014 /*
1015  * Disable any page sizes not supported by the CPU
1016  */
1017 void
hat_init_pagesizes()1018 hat_init_pagesizes()
1019 {
1020 	int		i;
1021 
1022 	mmu_exported_page_sizes = 0;
1023 	for (i = TTE8K; i < max_mmu_page_sizes; i++) {
1024 
1025 		szc_2_userszc[i] = (uint_t)-1;
1026 		userszc_2_szc[i] = (uint_t)-1;
1027 
1028 		if ((mmu_exported_pagesize_mask & (1 << i)) == 0) {
1029 			disable_large_pages |= (1 << i);
1030 		} else {
1031 			szc_2_userszc[i] = mmu_exported_page_sizes;
1032 			userszc_2_szc[mmu_exported_page_sizes] = i;
1033 			mmu_exported_page_sizes++;
1034 		}
1035 	}
1036 
1037 	disable_ism_large_pages |= disable_large_pages;
1038 	disable_auto_data_large_pages = disable_large_pages;
1039 	disable_auto_text_large_pages = disable_large_pages;
1040 
1041 	/*
1042 	 * Initialize mmu-specific large page sizes.
1043 	 */
1044 	if (&mmu_large_pages_disabled) {
1045 		disable_large_pages |= mmu_large_pages_disabled(HAT_LOAD);
1046 		disable_ism_large_pages |=
1047 		    mmu_large_pages_disabled(HAT_LOAD_SHARE);
1048 		disable_auto_data_large_pages |=
1049 		    mmu_large_pages_disabled(HAT_AUTO_DATA);
1050 		disable_auto_text_large_pages |=
1051 		    mmu_large_pages_disabled(HAT_AUTO_TEXT);
1052 	}
1053 }
1054 
1055 /*
1056  * Initialize the hardware address translation structures.
1057  */
1058 void
hat_init(void)1059 hat_init(void)
1060 {
1061 	int		i;
1062 	uint_t		sz;
1063 	size_t		size;
1064 
1065 	hat_lock_init();
1066 	hat_kstat_init();
1067 
1068 	/*
1069 	 * Hardware-only bits in a TTE
1070 	 */
1071 	MAKE_TTE_MASK(&hw_tte);
1072 
1073 	hat_init_pagesizes();
1074 
1075 	/* Initialize the hash locks */
1076 	for (i = 0; i < khmehash_num; i++) {
1077 		mutex_init(&khme_hash[i].hmehash_mutex, NULL,
1078 		    MUTEX_DEFAULT, NULL);
1079 		khme_hash[i].hmeh_nextpa = HMEBLK_ENDPA;
1080 	}
1081 	for (i = 0; i < uhmehash_num; i++) {
1082 		mutex_init(&uhme_hash[i].hmehash_mutex, NULL,
1083 		    MUTEX_DEFAULT, NULL);
1084 		uhme_hash[i].hmeh_nextpa = HMEBLK_ENDPA;
1085 	}
1086 	khmehash_num--;		/* make sure counter starts from 0 */
1087 	uhmehash_num--;		/* make sure counter starts from 0 */
1088 
1089 	/*
1090 	 * Allocate context domain structures.
1091 	 *
1092 	 * A platform may choose to modify max_mmu_ctxdoms in
1093 	 * set_platform_defaults(). If a platform does not define
1094 	 * a set_platform_defaults() or does not choose to modify
1095 	 * max_mmu_ctxdoms, it gets one MMU context domain for every CPU.
1096 	 *
1097 	 * For all platforms that have CPUs sharing MMUs, this
1098 	 * value must be defined.
1099 	 */
1100 	if (max_mmu_ctxdoms == 0)
1101 		max_mmu_ctxdoms = max_ncpus;
1102 
1103 	size = max_mmu_ctxdoms * sizeof (mmu_ctx_t *);
1104 	mmu_ctxs_tbl = kmem_zalloc(size, KM_SLEEP);
1105 
1106 	/* mmu_ctx_t is 64 bytes aligned */
1107 	mmuctxdom_cache = kmem_cache_create("mmuctxdom_cache",
1108 	    sizeof (mmu_ctx_t), 64, NULL, NULL, NULL, NULL, NULL, 0);
1109 	/*
1110 	 * MMU context domain initialization for the Boot CPU.
1111 	 * This needs the context domains array allocated above.
1112 	 */
1113 	mutex_enter(&cpu_lock);
1114 	sfmmu_cpu_init(CPU);
1115 	mutex_exit(&cpu_lock);
1116 
1117 	/*
1118 	 * Intialize ism mapping list lock.
1119 	 */
1120 
1121 	mutex_init(&ism_mlist_lock, NULL, MUTEX_DEFAULT, NULL);
1122 
1123 	/*
1124 	 * Each sfmmu structure carries an array of MMU context info
1125 	 * structures, one per context domain. The size of this array depends
1126 	 * on the maximum number of context domains. So, the size of the
1127 	 * sfmmu structure varies per platform.
1128 	 *
1129 	 * sfmmu is allocated from static arena, because trap
1130 	 * handler at TL > 0 is not allowed to touch kernel relocatable
1131 	 * memory. sfmmu's alignment is changed to 64 bytes from
1132 	 * default 8 bytes, as the lower 6 bits will be used to pass
1133 	 * pgcnt to vtag_flush_pgcnt_tl1.
1134 	 */
1135 	size = sizeof (sfmmu_t) + sizeof (sfmmu_ctx_t) * (max_mmu_ctxdoms - 1);
1136 
1137 	sfmmuid_cache = kmem_cache_create("sfmmuid_cache", size,
1138 	    64, sfmmu_idcache_constructor, sfmmu_idcache_destructor,
1139 	    NULL, NULL, static_arena, 0);
1140 
1141 	sfmmu_tsbinfo_cache = kmem_cache_create("sfmmu_tsbinfo_cache",
1142 	    sizeof (struct tsb_info), 0, NULL, NULL, NULL, NULL, NULL, 0);
1143 
1144 	/*
1145 	 * Since we only use the tsb8k cache to "borrow" pages for TSBs
1146 	 * from the heap when low on memory or when TSB_FORCEALLOC is
1147 	 * specified, don't use magazines to cache them--we want to return
1148 	 * them to the system as quickly as possible.
1149 	 */
1150 	sfmmu_tsb8k_cache = kmem_cache_create("sfmmu_tsb8k_cache",
1151 	    MMU_PAGESIZE, MMU_PAGESIZE, NULL, NULL, NULL, NULL,
1152 	    static_arena, KMC_NOMAGAZINE);
1153 
1154 	/*
1155 	 * Set tsb_alloc_hiwater to 1/tsb_alloc_hiwater_factor of physical
1156 	 * memory, which corresponds to the old static reserve for TSBs.
1157 	 * tsb_alloc_hiwater_factor defaults to 32.  This caps the amount of
1158 	 * memory we'll allocate for TSB slabs; beyond this point TSB
1159 	 * allocations will be taken from the kernel heap (via
1160 	 * sfmmu_tsb8k_cache) and will be throttled as would any other kmem
1161 	 * consumer.
1162 	 */
1163 	if (tsb_alloc_hiwater_factor == 0) {
1164 		tsb_alloc_hiwater_factor = TSB_ALLOC_HIWATER_FACTOR_DEFAULT;
1165 	}
1166 	SFMMU_SET_TSB_ALLOC_HIWATER(physmem);
1167 
1168 	for (sz = tsb_slab_ttesz; sz > 0; sz--) {
1169 		if (!(disable_large_pages & (1 << sz)))
1170 			break;
1171 	}
1172 
1173 	if (sz < tsb_slab_ttesz) {
1174 		tsb_slab_ttesz = sz;
1175 		tsb_slab_shift = MMU_PAGESHIFT + (sz << 1) + sz;
1176 		tsb_slab_size = 1 << tsb_slab_shift;
1177 		tsb_slab_mask = (1 << (tsb_slab_shift - MMU_PAGESHIFT)) - 1;
1178 		use_bigtsb_arena = 0;
1179 	} else if (use_bigtsb_arena &&
1180 	    (disable_large_pages & (1 << bigtsb_slab_ttesz))) {
1181 		use_bigtsb_arena = 0;
1182 	}
1183 
1184 	if (!use_bigtsb_arena) {
1185 		bigtsb_slab_shift = tsb_slab_shift;
1186 	}
1187 	SFMMU_SET_TSB_MAX_GROWSIZE(physmem);
1188 
1189 	/*
1190 	 * On smaller memory systems, allocate TSB memory in smaller chunks
1191 	 * than the default 4M slab size. We also honor disable_large_pages
1192 	 * here.
1193 	 *
1194 	 * The trap handlers need to be patched with the final slab shift,
1195 	 * since they need to be able to construct the TSB pointer at runtime.
1196 	 */
1197 	if ((tsb_max_growsize <= TSB_512K_SZCODE) &&
1198 	    !(disable_large_pages & (1 << TTE512K))) {
1199 		tsb_slab_ttesz = TTE512K;
1200 		tsb_slab_shift = MMU_PAGESHIFT512K;
1201 		tsb_slab_size = MMU_PAGESIZE512K;
1202 		tsb_slab_mask = MMU_PAGEOFFSET512K >> MMU_PAGESHIFT;
1203 		use_bigtsb_arena = 0;
1204 	}
1205 
1206 	if (!use_bigtsb_arena) {
1207 		bigtsb_slab_ttesz = tsb_slab_ttesz;
1208 		bigtsb_slab_shift = tsb_slab_shift;
1209 		bigtsb_slab_size = tsb_slab_size;
1210 		bigtsb_slab_mask = tsb_slab_mask;
1211 	}
1212 
1213 
1214 	/*
1215 	 * Set up memory callback to update tsb_alloc_hiwater and
1216 	 * tsb_max_growsize.
1217 	 */
1218 	i = kphysm_setup_func_register(&sfmmu_update_vec, (void *) 0);
1219 	ASSERT(i == 0);
1220 
1221 	/*
1222 	 * kmem_tsb_arena is the source from which large TSB slabs are
1223 	 * drawn.  The quantum of this arena corresponds to the largest
1224 	 * TSB size we can dynamically allocate for user processes.
1225 	 * Currently it must also be a supported page size since we
1226 	 * use exactly one translation entry to map each slab page.
1227 	 *
1228 	 * The per-lgroup kmem_tsb_default_arena arenas are the arenas from
1229 	 * which most TSBs are allocated.  Since most TSB allocations are
1230 	 * typically 8K we have a kmem cache we stack on top of each
1231 	 * kmem_tsb_default_arena to speed up those allocations.
1232 	 *
1233 	 * Note the two-level scheme of arenas is required only
1234 	 * because vmem_create doesn't allow us to specify alignment
1235 	 * requirements.  If this ever changes the code could be
1236 	 * simplified to use only one level of arenas.
1237 	 *
1238 	 * If 256M page support exists on sun4v, 256MB kmem_bigtsb_arena
1239 	 * will be provided in addition to the 4M kmem_tsb_arena.
1240 	 */
1241 	if (use_bigtsb_arena) {
1242 		kmem_bigtsb_arena = vmem_create("kmem_bigtsb", NULL, 0,
1243 		    bigtsb_slab_size, sfmmu_vmem_xalloc_aligned_wrapper,
1244 		    vmem_xfree, heap_arena, 0, VM_SLEEP);
1245 	}
1246 
1247 	kmem_tsb_arena = vmem_create("kmem_tsb", NULL, 0, tsb_slab_size,
1248 	    sfmmu_vmem_xalloc_aligned_wrapper,
1249 	    vmem_xfree, heap_arena, 0, VM_SLEEP);
1250 
1251 	if (tsb_lgrp_affinity) {
1252 		char s[50];
1253 		for (i = 0; i < NLGRPS_MAX; i++) {
1254 			if (use_bigtsb_arena) {
1255 				(void) sprintf(s, "kmem_bigtsb_lgrp%d", i);
1256 				kmem_bigtsb_default_arena[i] = vmem_create(s,
1257 				    NULL, 0, 2 * tsb_slab_size,
1258 				    sfmmu_tsb_segkmem_alloc,
1259 				    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena,
1260 				    0, VM_SLEEP | VM_BESTFIT);
1261 			}
1262 
1263 			(void) sprintf(s, "kmem_tsb_lgrp%d", i);
1264 			kmem_tsb_default_arena[i] = vmem_create(s,
1265 			    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1266 			    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1267 			    VM_SLEEP | VM_BESTFIT);
1268 
1269 			(void) sprintf(s, "sfmmu_tsb_lgrp%d_cache", i);
1270 			sfmmu_tsb_cache[i] = kmem_cache_create(s,
1271 			    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1272 			    kmem_tsb_default_arena[i], 0);
1273 		}
1274 	} else {
1275 		if (use_bigtsb_arena) {
1276 			kmem_bigtsb_default_arena[0] =
1277 			    vmem_create("kmem_bigtsb_default", NULL, 0,
1278 			    2 * tsb_slab_size, sfmmu_tsb_segkmem_alloc,
1279 			    sfmmu_tsb_segkmem_free, kmem_bigtsb_arena, 0,
1280 			    VM_SLEEP | VM_BESTFIT);
1281 		}
1282 
1283 		kmem_tsb_default_arena[0] = vmem_create("kmem_tsb_default",
1284 		    NULL, 0, PAGESIZE, sfmmu_tsb_segkmem_alloc,
1285 		    sfmmu_tsb_segkmem_free, kmem_tsb_arena, 0,
1286 		    VM_SLEEP | VM_BESTFIT);
1287 		sfmmu_tsb_cache[0] = kmem_cache_create("sfmmu_tsb_cache",
1288 		    PAGESIZE, PAGESIZE, NULL, NULL, NULL, NULL,
1289 		    kmem_tsb_default_arena[0], 0);
1290 	}
1291 
1292 	sfmmu8_cache = kmem_cache_create("sfmmu8_cache", HME8BLK_SZ,
1293 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1294 	    sfmmu_hblkcache_destructor,
1295 	    sfmmu_hblkcache_reclaim, (void *)HME8BLK_SZ,
1296 	    hat_memload_arena, KMC_NOHASH);
1297 
1298 	hat_memload1_arena = vmem_create("hat_memload1", NULL, 0, PAGESIZE,
1299 	    segkmem_alloc_permanent, segkmem_free, heap_arena, 0,
1300 	    VMC_DUMPSAFE | VM_SLEEP);
1301 
1302 	sfmmu1_cache = kmem_cache_create("sfmmu1_cache", HME1BLK_SZ,
1303 	    HMEBLK_ALIGN, sfmmu_hblkcache_constructor,
1304 	    sfmmu_hblkcache_destructor,
1305 	    NULL, (void *)HME1BLK_SZ,
1306 	    hat_memload1_arena, KMC_NOHASH);
1307 
1308 	pa_hment_cache = kmem_cache_create("pa_hment_cache", PAHME_SZ,
1309 	    0, NULL, NULL, NULL, NULL, static_arena, KMC_NOHASH);
1310 
1311 	ism_blk_cache = kmem_cache_create("ism_blk_cache",
1312 	    sizeof (ism_blk_t), ecache_alignsize, NULL, NULL,
1313 	    NULL, NULL, static_arena, KMC_NOHASH);
1314 
1315 	ism_ment_cache = kmem_cache_create("ism_ment_cache",
1316 	    sizeof (ism_ment_t), 0, NULL, NULL,
1317 	    NULL, NULL, NULL, 0);
1318 
1319 	/*
1320 	 * We grab the first hat for the kernel,
1321 	 */
1322 	AS_LOCK_ENTER(&kas, RW_WRITER);
1323 	kas.a_hat = hat_alloc(&kas);
1324 	AS_LOCK_EXIT(&kas);
1325 
1326 	/*
1327 	 * Initialize hblk_reserve.
1328 	 */
1329 	((struct hme_blk *)hblk_reserve)->hblk_nextpa =
1330 	    va_to_pa((caddr_t)hblk_reserve);
1331 
1332 #ifndef UTSB_PHYS
1333 	/*
1334 	 * Reserve some kernel virtual address space for the locked TTEs
1335 	 * that allow us to probe the TSB from TL>0.
1336 	 */
1337 	utsb_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1338 	    0, 0, NULL, NULL, VM_SLEEP);
1339 	utsb4m_vabase = vmem_xalloc(heap_arena, tsb_slab_size, tsb_slab_size,
1340 	    0, 0, NULL, NULL, VM_SLEEP);
1341 #endif
1342 
1343 #ifdef VAC
1344 	/*
1345 	 * The big page VAC handling code assumes VAC
1346 	 * will not be bigger than the smallest big
1347 	 * page- which is 64K.
1348 	 */
1349 	if (TTEPAGES(TTE64K) < CACHE_NUM_COLOR) {
1350 		cmn_err(CE_PANIC, "VAC too big!");
1351 	}
1352 #endif
1353 
1354 	uhme_hash_pa = va_to_pa(uhme_hash);
1355 	khme_hash_pa = va_to_pa(khme_hash);
1356 
1357 	/*
1358 	 * Initialize relocation locks. kpr_suspendlock is held
1359 	 * at PIL_MAX to prevent interrupts from pinning the holder
1360 	 * of a suspended TTE which may access it leading to a
1361 	 * deadlock condition.
1362 	 */
1363 	mutex_init(&kpr_mutex, NULL, MUTEX_DEFAULT, NULL);
1364 	mutex_init(&kpr_suspendlock, NULL, MUTEX_SPIN, (void *)PIL_MAX);
1365 
1366 	/*
1367 	 * If Shared context support is disabled via /etc/system
1368 	 * set shctx_on to 0 here if it was set to 1 earlier in boot
1369 	 * sequence by cpu module initialization code.
1370 	 */
1371 	if (shctx_on && disable_shctx) {
1372 		shctx_on = 0;
1373 	}
1374 
1375 	if (shctx_on) {
1376 		srd_buckets = kmem_zalloc(SFMMU_MAX_SRD_BUCKETS *
1377 		    sizeof (srd_buckets[0]), KM_SLEEP);
1378 		for (i = 0; i < SFMMU_MAX_SRD_BUCKETS; i++) {
1379 			mutex_init(&srd_buckets[i].srdb_lock, NULL,
1380 			    MUTEX_DEFAULT, NULL);
1381 		}
1382 
1383 		srd_cache = kmem_cache_create("srd_cache", sizeof (sf_srd_t),
1384 		    0, sfmmu_srdcache_constructor, sfmmu_srdcache_destructor,
1385 		    NULL, NULL, NULL, 0);
1386 		region_cache = kmem_cache_create("region_cache",
1387 		    sizeof (sf_region_t), 0, sfmmu_rgncache_constructor,
1388 		    sfmmu_rgncache_destructor, NULL, NULL, NULL, 0);
1389 		scd_cache = kmem_cache_create("scd_cache", sizeof (sf_scd_t),
1390 		    0, sfmmu_scdcache_constructor,  sfmmu_scdcache_destructor,
1391 		    NULL, NULL, NULL, 0);
1392 	}
1393 
1394 	/*
1395 	 * Pre-allocate hrm_hashtab before enabling the collection of
1396 	 * refmod statistics.  Allocating on the fly would mean us
1397 	 * running the risk of suffering recursive mutex enters or
1398 	 * deadlocks.
1399 	 */
1400 	hrm_hashtab = kmem_zalloc(HRM_HASHSIZE * sizeof (struct hrmstat *),
1401 	    KM_SLEEP);
1402 
1403 	/* Allocate per-cpu pending freelist of hmeblks */
1404 	cpu_hme_pend = kmem_zalloc((NCPU * sizeof (cpu_hme_pend_t)) + 64,
1405 	    KM_SLEEP);
1406 	cpu_hme_pend = (cpu_hme_pend_t *)P2ROUNDUP(
1407 	    (uintptr_t)cpu_hme_pend, 64);
1408 
1409 	for (i = 0; i < NCPU; i++) {
1410 		mutex_init(&cpu_hme_pend[i].chp_mutex, NULL, MUTEX_DEFAULT,
1411 		    NULL);
1412 	}
1413 
1414 	if (cpu_hme_pend_thresh == 0) {
1415 		cpu_hme_pend_thresh = CPU_HME_PEND_THRESH;
1416 	}
1417 }
1418 
1419 /*
1420  * Initialize locking for the hat layer, called early during boot.
1421  */
1422 static void
hat_lock_init()1423 hat_lock_init()
1424 {
1425 	int i;
1426 
1427 	/*
1428 	 * initialize the array of mutexes protecting a page's mapping
1429 	 * list and p_nrm field.
1430 	 */
1431 	for (i = 0; i < MML_TABLE_SIZE; i++)
1432 		mutex_init(&mml_table[i].pad_mutex, NULL, MUTEX_DEFAULT, NULL);
1433 
1434 	if (kpm_enable) {
1435 		for (i = 0; i < kpmp_table_sz; i++) {
1436 			mutex_init(&kpmp_table[i].khl_mutex, NULL,
1437 			    MUTEX_DEFAULT, NULL);
1438 		}
1439 	}
1440 
1441 	/*
1442 	 * Initialize array of mutex locks that protects sfmmu fields and
1443 	 * TSB lists.
1444 	 */
1445 	for (i = 0; i < SFMMU_NUM_LOCK; i++)
1446 		mutex_init(HATLOCK_MUTEXP(&hat_lock[i]), NULL, MUTEX_DEFAULT,
1447 		    NULL);
1448 }
1449 
1450 #define	SFMMU_KERNEL_MAXVA \
1451 	(kmem64_base ? (uintptr_t)kmem64_end : (SYSLIMIT))
1452 
1453 /*
1454  * Allocate a hat structure.
1455  * Called when an address space first uses a hat.
1456  */
1457 struct hat *
hat_alloc(struct as * as)1458 hat_alloc(struct as *as)
1459 {
1460 	sfmmu_t *sfmmup;
1461 	int i;
1462 	uint64_t cnum;
1463 	extern uint_t get_color_start(struct as *);
1464 
1465 	ASSERT(AS_WRITE_HELD(as));
1466 	sfmmup = kmem_cache_alloc(sfmmuid_cache, KM_SLEEP);
1467 	sfmmup->sfmmu_as = as;
1468 	sfmmup->sfmmu_flags = 0;
1469 	sfmmup->sfmmu_tteflags = 0;
1470 	sfmmup->sfmmu_rtteflags = 0;
1471 	LOCK_INIT_CLEAR(&sfmmup->sfmmu_ctx_lock);
1472 
1473 	if (as == &kas) {
1474 		ksfmmup = sfmmup;
1475 		sfmmup->sfmmu_cext = 0;
1476 		cnum = KCONTEXT;
1477 
1478 		sfmmup->sfmmu_clrstart = 0;
1479 		sfmmup->sfmmu_tsb = NULL;
1480 		/*
1481 		 * hat_kern_setup() will call sfmmu_init_ktsbinfo()
1482 		 * to setup tsb_info for ksfmmup.
1483 		 */
1484 	} else {
1485 
1486 		/*
1487 		 * Just set to invalid ctx. When it faults, it will
1488 		 * get a valid ctx. This would avoid the situation
1489 		 * where we get a ctx, but it gets stolen and then
1490 		 * we fault when we try to run and so have to get
1491 		 * another ctx.
1492 		 */
1493 		sfmmup->sfmmu_cext = 0;
1494 		cnum = INVALID_CONTEXT;
1495 
1496 		/* initialize original physical page coloring bin */
1497 		sfmmup->sfmmu_clrstart = get_color_start(as);
1498 #ifdef DEBUG
1499 		if (tsb_random_size) {
1500 			uint32_t randval = (uint32_t)gettick() >> 4;
1501 			int size = randval % (tsb_max_growsize + 1);
1502 
1503 			/* chose a random tsb size for stress testing */
1504 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb, size,
1505 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1506 		} else
1507 #endif /* DEBUG */
1508 			(void) sfmmu_tsbinfo_alloc(&sfmmup->sfmmu_tsb,
1509 			    default_tsb_size,
1510 			    TSB8K|TSB64K|TSB512K, 0, sfmmup);
1511 		sfmmup->sfmmu_flags = HAT_SWAPPED | HAT_ALLCTX_INVALID;
1512 		ASSERT(sfmmup->sfmmu_tsb != NULL);
1513 	}
1514 
1515 	ASSERT(max_mmu_ctxdoms > 0);
1516 	for (i = 0; i < max_mmu_ctxdoms; i++) {
1517 		sfmmup->sfmmu_ctxs[i].cnum = cnum;
1518 		sfmmup->sfmmu_ctxs[i].gnum = 0;
1519 	}
1520 
1521 	for (i = 0; i < max_mmu_page_sizes; i++) {
1522 		sfmmup->sfmmu_ttecnt[i] = 0;
1523 		sfmmup->sfmmu_scdrttecnt[i] = 0;
1524 		sfmmup->sfmmu_ismttecnt[i] = 0;
1525 		sfmmup->sfmmu_scdismttecnt[i] = 0;
1526 		sfmmup->sfmmu_pgsz[i] = TTE8K;
1527 	}
1528 	sfmmup->sfmmu_tsb0_4minflcnt = 0;
1529 	sfmmup->sfmmu_iblk = NULL;
1530 	sfmmup->sfmmu_ismhat = 0;
1531 	sfmmup->sfmmu_scdhat = 0;
1532 	sfmmup->sfmmu_ismblkpa = (uint64_t)-1;
1533 	if (sfmmup == ksfmmup) {
1534 		CPUSET_ALL(sfmmup->sfmmu_cpusran);
1535 	} else {
1536 		CPUSET_ZERO(sfmmup->sfmmu_cpusran);
1537 	}
1538 	sfmmup->sfmmu_free = 0;
1539 	sfmmup->sfmmu_rmstat = 0;
1540 	sfmmup->sfmmu_clrbin = sfmmup->sfmmu_clrstart;
1541 	cv_init(&sfmmup->sfmmu_tsb_cv, NULL, CV_DEFAULT, NULL);
1542 	sfmmup->sfmmu_srdp = NULL;
1543 	SF_RGNMAP_ZERO(sfmmup->sfmmu_region_map);
1544 	bzero(sfmmup->sfmmu_hmeregion_links, SFMMU_L1_HMERLINKS_SIZE);
1545 	sfmmup->sfmmu_scdp = NULL;
1546 	sfmmup->sfmmu_scd_link.next = NULL;
1547 	sfmmup->sfmmu_scd_link.prev = NULL;
1548 	return (sfmmup);
1549 }
1550 
1551 /*
1552  * Create per-MMU context domain kstats for a given MMU ctx.
1553  */
1554 static void
sfmmu_mmu_kstat_create(mmu_ctx_t * mmu_ctxp)1555 sfmmu_mmu_kstat_create(mmu_ctx_t *mmu_ctxp)
1556 {
1557 	mmu_ctx_stat_t	stat;
1558 	kstat_t		*mmu_kstat;
1559 
1560 	ASSERT(MUTEX_HELD(&cpu_lock));
1561 	ASSERT(mmu_ctxp->mmu_kstat == NULL);
1562 
1563 	mmu_kstat = kstat_create("unix", mmu_ctxp->mmu_idx, "mmu_ctx",
1564 	    "hat", KSTAT_TYPE_NAMED, MMU_CTX_NUM_STATS, KSTAT_FLAG_VIRTUAL);
1565 
1566 	if (mmu_kstat == NULL) {
1567 		cmn_err(CE_WARN, "kstat_create for MMU %d failed",
1568 		    mmu_ctxp->mmu_idx);
1569 	} else {
1570 		mmu_kstat->ks_data = mmu_ctxp->mmu_kstat_data;
1571 		for (stat = 0; stat < MMU_CTX_NUM_STATS; stat++)
1572 			kstat_named_init(&mmu_ctxp->mmu_kstat_data[stat],
1573 			    mmu_ctx_kstat_names[stat], KSTAT_DATA_INT64);
1574 		mmu_ctxp->mmu_kstat = mmu_kstat;
1575 		kstat_install(mmu_kstat);
1576 	}
1577 }
1578 
1579 /*
1580  * plat_cpuid_to_mmu_ctx_info() is a platform interface that returns MMU
1581  * context domain information for a given CPU. If a platform does not
1582  * specify that interface, then the function below is used instead to return
1583  * default information. The defaults are as follows:
1584  *
1585  *	- The number of MMU context IDs supported on any CPU in the
1586  *	  system is 8K.
1587  *	- There is one MMU context domain per CPU.
1588  */
1589 /*ARGSUSED*/
1590 static void
sfmmu_cpuid_to_mmu_ctx_info(processorid_t cpuid,mmu_ctx_info_t * infop)1591 sfmmu_cpuid_to_mmu_ctx_info(processorid_t cpuid, mmu_ctx_info_t *infop)
1592 {
1593 	infop->mmu_nctxs = nctxs;
1594 	infop->mmu_idx = cpu[cpuid]->cpu_seqid;
1595 }
1596 
1597 /*
1598  * Called during CPU initialization to set the MMU context-related information
1599  * for a CPU.
1600  *
1601  * cpu_lock serializes accesses to mmu_ctxs and mmu_saved_gnum.
1602  */
1603 void
sfmmu_cpu_init(cpu_t * cp)1604 sfmmu_cpu_init(cpu_t *cp)
1605 {
1606 	mmu_ctx_info_t	info;
1607 	mmu_ctx_t	*mmu_ctxp;
1608 
1609 	ASSERT(MUTEX_HELD(&cpu_lock));
1610 
1611 	if (&plat_cpuid_to_mmu_ctx_info == NULL)
1612 		sfmmu_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1613 	else
1614 		plat_cpuid_to_mmu_ctx_info(cp->cpu_id, &info);
1615 
1616 	ASSERT(info.mmu_idx < max_mmu_ctxdoms);
1617 
1618 	if ((mmu_ctxp = mmu_ctxs_tbl[info.mmu_idx]) == NULL) {
1619 		/* Each mmu_ctx is cacheline aligned. */
1620 		mmu_ctxp = kmem_cache_alloc(mmuctxdom_cache, KM_SLEEP);
1621 		bzero(mmu_ctxp, sizeof (mmu_ctx_t));
1622 
1623 		mutex_init(&mmu_ctxp->mmu_lock, NULL, MUTEX_SPIN,
1624 		    (void *)ipltospl(DISP_LEVEL));
1625 		mmu_ctxp->mmu_idx = info.mmu_idx;
1626 		mmu_ctxp->mmu_nctxs = info.mmu_nctxs;
1627 		/*
1628 		 * Globally for lifetime of a system,
1629 		 * gnum must always increase.
1630 		 * mmu_saved_gnum is protected by the cpu_lock.
1631 		 */
1632 		mmu_ctxp->mmu_gnum = mmu_saved_gnum + 1;
1633 		mmu_ctxp->mmu_cnum = NUM_LOCKED_CTXS;
1634 
1635 		sfmmu_mmu_kstat_create(mmu_ctxp);
1636 
1637 		mmu_ctxs_tbl[info.mmu_idx] = mmu_ctxp;
1638 	} else {
1639 		ASSERT(mmu_ctxp->mmu_idx == info.mmu_idx);
1640 		ASSERT(mmu_ctxp->mmu_nctxs <= info.mmu_nctxs);
1641 	}
1642 
1643 	/*
1644 	 * The mmu_lock is acquired here to prevent races with
1645 	 * the wrap-around code.
1646 	 */
1647 	mutex_enter(&mmu_ctxp->mmu_lock);
1648 
1649 
1650 	mmu_ctxp->mmu_ncpus++;
1651 	CPUSET_ADD(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1652 	CPU_MMU_IDX(cp) = info.mmu_idx;
1653 	CPU_MMU_CTXP(cp) = mmu_ctxp;
1654 
1655 	mutex_exit(&mmu_ctxp->mmu_lock);
1656 }
1657 
1658 static void
sfmmu_ctxdom_free(mmu_ctx_t * mmu_ctxp)1659 sfmmu_ctxdom_free(mmu_ctx_t *mmu_ctxp)
1660 {
1661 	ASSERT(MUTEX_HELD(&cpu_lock));
1662 	ASSERT(!MUTEX_HELD(&mmu_ctxp->mmu_lock));
1663 
1664 	mutex_destroy(&mmu_ctxp->mmu_lock);
1665 
1666 	if (mmu_ctxp->mmu_kstat)
1667 		kstat_delete(mmu_ctxp->mmu_kstat);
1668 
1669 	/* mmu_saved_gnum is protected by the cpu_lock. */
1670 	if (mmu_saved_gnum < mmu_ctxp->mmu_gnum)
1671 		mmu_saved_gnum = mmu_ctxp->mmu_gnum;
1672 
1673 	kmem_cache_free(mmuctxdom_cache, mmu_ctxp);
1674 }
1675 
1676 /*
1677  * Called to perform MMU context-related cleanup for a CPU.
1678  */
1679 void
sfmmu_cpu_cleanup(cpu_t * cp)1680 sfmmu_cpu_cleanup(cpu_t *cp)
1681 {
1682 	mmu_ctx_t	*mmu_ctxp;
1683 
1684 	ASSERT(MUTEX_HELD(&cpu_lock));
1685 
1686 	mmu_ctxp = CPU_MMU_CTXP(cp);
1687 	ASSERT(mmu_ctxp != NULL);
1688 
1689 	/*
1690 	 * The mmu_lock is acquired here to prevent races with
1691 	 * the wrap-around code.
1692 	 */
1693 	mutex_enter(&mmu_ctxp->mmu_lock);
1694 
1695 	CPU_MMU_CTXP(cp) = NULL;
1696 
1697 	CPUSET_DEL(mmu_ctxp->mmu_cpuset, cp->cpu_id);
1698 	if (--mmu_ctxp->mmu_ncpus == 0) {
1699 		mmu_ctxs_tbl[mmu_ctxp->mmu_idx] = NULL;
1700 		mutex_exit(&mmu_ctxp->mmu_lock);
1701 		sfmmu_ctxdom_free(mmu_ctxp);
1702 		return;
1703 	}
1704 
1705 	mutex_exit(&mmu_ctxp->mmu_lock);
1706 }
1707 
1708 uint_t
sfmmu_ctxdom_nctxs(int idx)1709 sfmmu_ctxdom_nctxs(int idx)
1710 {
1711 	return (mmu_ctxs_tbl[idx]->mmu_nctxs);
1712 }
1713 
1714 #ifdef sun4v
1715 /*
1716  * sfmmu_ctxdoms_* is an interface provided to help keep context domains
1717  * consistant after suspend/resume on system that can resume on a different
1718  * hardware than it was suspended.
1719  *
1720  * sfmmu_ctxdom_lock(void) locks all context domains and prevents new contexts
1721  * from being allocated.  It acquires all hat_locks, which blocks most access to
1722  * context data, except for a few cases that are handled separately or are
1723  * harmless.  It wraps each domain to increment gnum and invalidate on-CPU
1724  * contexts, and forces cnum to its max.  As a result of this call all user
1725  * threads that are running on CPUs trap and try to perform wrap around but
1726  * can't because hat_locks are taken.  Threads that were not on CPUs but started
1727  * by scheduler go to sfmmu_alloc_ctx() to aquire context without checking
1728  * hat_lock, but fail, because cnum == nctxs, and therefore also trap and block
1729  * on hat_lock trying to wrap.  sfmmu_ctxdom_lock() must be called before CPUs
1730  * are paused, else it could deadlock acquiring locks held by paused CPUs.
1731  *
1732  * sfmmu_ctxdoms_remove() removes context domains from every CPUs and records
1733  * the CPUs that had them.  It must be called after CPUs have been paused. This
1734  * ensures that no threads are in sfmmu_alloc_ctx() accessing domain data,
1735  * because pause_cpus sends a mondo interrupt to every CPU, and sfmmu_alloc_ctx
1736  * runs with interrupts disabled.  When CPUs are later resumed, they may enter
1737  * sfmmu_alloc_ctx, but it will check for CPU_MMU_CTXP = NULL and immediately
1738  * return failure.  Or, they will be blocked trying to acquire hat_lock. Thus
1739  * after sfmmu_ctxdoms_remove returns, we are guaranteed that no one is
1740  * accessing the old context domains.
1741  *
1742  * sfmmu_ctxdoms_update(void) frees space used by old context domains and
1743  * allocates new context domains based on hardware layout.  It initializes
1744  * every CPU that had context domain before migration to have one again.
1745  * sfmmu_ctxdoms_update must be called after CPUs are resumed, else it
1746  * could deadlock acquiring locks held by paused CPUs.
1747  *
1748  * sfmmu_ctxdoms_unlock(void) releases all hat_locks after which user threads
1749  * acquire new context ids and continue execution.
1750  *
1751  * Therefore functions should be called in the following order:
1752  *       suspend_routine()
1753  *		sfmmu_ctxdom_lock()
1754  *		pause_cpus()
1755  *		suspend()
1756  *			if (suspend failed)
1757  *				sfmmu_ctxdom_unlock()
1758  *		...
1759  *		sfmmu_ctxdom_remove()
1760  *		resume_cpus()
1761  *		sfmmu_ctxdom_update()
1762  *		sfmmu_ctxdom_unlock()
1763  */
1764 static cpuset_t sfmmu_ctxdoms_pset;
1765 
1766 void
sfmmu_ctxdoms_remove()1767 sfmmu_ctxdoms_remove()
1768 {
1769 	processorid_t	id;
1770 	cpu_t		*cp;
1771 
1772 	/*
1773 	 * Record the CPUs that have domains in sfmmu_ctxdoms_pset, so they can
1774 	 * be restored post-migration. A CPU may be powered off and not have a
1775 	 * domain, for example.
1776 	 */
1777 	CPUSET_ZERO(sfmmu_ctxdoms_pset);
1778 
1779 	for (id = 0; id < NCPU; id++) {
1780 		if ((cp = cpu[id]) != NULL && CPU_MMU_CTXP(cp) != NULL) {
1781 			CPUSET_ADD(sfmmu_ctxdoms_pset, id);
1782 			CPU_MMU_CTXP(cp) = NULL;
1783 		}
1784 	}
1785 }
1786 
1787 void
sfmmu_ctxdoms_lock(void)1788 sfmmu_ctxdoms_lock(void)
1789 {
1790 	int		idx;
1791 	mmu_ctx_t	*mmu_ctxp;
1792 
1793 	sfmmu_hat_lock_all();
1794 
1795 	/*
1796 	 * At this point, no thread can be in sfmmu_ctx_wrap_around, because
1797 	 * hat_lock is always taken before calling it.
1798 	 *
1799 	 * For each domain, set mmu_cnum to max so no more contexts can be
1800 	 * allocated, and wrap to flush on-CPU contexts and force threads to
1801 	 * acquire a new context when we later drop hat_lock after migration.
1802 	 * Setting mmu_cnum may race with sfmmu_alloc_ctx which also sets cnum,
1803 	 * but the latter uses CAS and will miscompare and not overwrite it.
1804 	 */
1805 	kpreempt_disable(); /* required by sfmmu_ctx_wrap_around */
1806 	for (idx = 0; idx < max_mmu_ctxdoms; idx++) {
1807 		if ((mmu_ctxp = mmu_ctxs_tbl[idx]) != NULL) {
1808 			mutex_enter(&mmu_ctxp->mmu_lock);
1809 			mmu_ctxp->mmu_cnum = mmu_ctxp->mmu_nctxs;
1810 			/* make sure updated cnum visible */
1811 			membar_enter();
1812 			mutex_exit(&mmu_ctxp->mmu_lock);
1813 			sfmmu_ctx_wrap_around(mmu_ctxp, B_FALSE);
1814 		}
1815 	}
1816 	kpreempt_enable();
1817 }
1818 
1819 void
sfmmu_ctxdoms_unlock(void)1820 sfmmu_ctxdoms_unlock(void)
1821 {
1822 	sfmmu_hat_unlock_all();
1823 }
1824 
1825 void
sfmmu_ctxdoms_update(void)1826 sfmmu_ctxdoms_update(void)
1827 {
1828 	processorid_t	id;
1829 	cpu_t		*cp;
1830 	uint_t		idx;
1831 	mmu_ctx_t	*mmu_ctxp;
1832 
1833 	/*
1834 	 * Free all context domains.  As side effect, this increases
1835 	 * mmu_saved_gnum to the maximum gnum over all domains, which is used to
1836 	 * init gnum in the new domains, which therefore will be larger than the
1837 	 * sfmmu gnum for any process, guaranteeing that every process will see
1838 	 * a new generation and allocate a new context regardless of what new
1839 	 * domain it runs in.
1840 	 */
1841 	mutex_enter(&cpu_lock);
1842 
1843 	for (idx = 0; idx < max_mmu_ctxdoms; idx++) {
1844 		if (mmu_ctxs_tbl[idx] != NULL) {
1845 			mmu_ctxp = mmu_ctxs_tbl[idx];
1846 			mmu_ctxs_tbl[idx] = NULL;
1847 			sfmmu_ctxdom_free(mmu_ctxp);
1848 		}
1849 	}
1850 
1851 	for (id = 0; id < NCPU; id++) {
1852 		if (CPU_IN_SET(sfmmu_ctxdoms_pset, id) &&
1853 		    (cp = cpu[id]) != NULL)
1854 			sfmmu_cpu_init(cp);
1855 	}
1856 	mutex_exit(&cpu_lock);
1857 }
1858 #endif
1859 
1860 /*
1861  * Hat_setup, makes an address space context the current active one.
1862  * In sfmmu this translates to setting the secondary context with the
1863  * corresponding context.
1864  */
1865 void
hat_setup(struct hat * sfmmup,int allocflag)1866 hat_setup(struct hat *sfmmup, int allocflag)
1867 {
1868 	hatlock_t *hatlockp;
1869 
1870 	/* Init needs some special treatment. */
1871 	if (allocflag == HAT_INIT) {
1872 		/*
1873 		 * Make sure that we have
1874 		 * 1. a TSB
1875 		 * 2. a valid ctx that doesn't get stolen after this point.
1876 		 */
1877 		hatlockp = sfmmu_hat_enter(sfmmup);
1878 
1879 		/*
1880 		 * Swap in the TSB.  hat_init() allocates tsbinfos without
1881 		 * TSBs, but we need one for init, since the kernel does some
1882 		 * special things to set up its stack and needs the TSB to
1883 		 * resolve page faults.
1884 		 */
1885 		sfmmu_tsb_swapin(sfmmup, hatlockp);
1886 
1887 		sfmmu_get_ctx(sfmmup);
1888 
1889 		sfmmu_hat_exit(hatlockp);
1890 	} else {
1891 		ASSERT(allocflag == HAT_ALLOC);
1892 
1893 		hatlockp = sfmmu_hat_enter(sfmmup);
1894 		kpreempt_disable();
1895 
1896 		CPUSET_ADD(sfmmup->sfmmu_cpusran, CPU->cpu_id);
1897 		/*
1898 		 * sfmmu_setctx_sec takes <pgsz|cnum> as a parameter,
1899 		 * pagesize bits don't matter in this case since we are passing
1900 		 * INVALID_CONTEXT to it.
1901 		 * Compatibility Note: hw takes care of MMU_SCONTEXT1
1902 		 */
1903 		sfmmu_setctx_sec(INVALID_CONTEXT);
1904 		sfmmu_clear_utsbinfo();
1905 
1906 		kpreempt_enable();
1907 		sfmmu_hat_exit(hatlockp);
1908 	}
1909 }
1910 
1911 /*
1912  * Free all the translation resources for the specified address space.
1913  * Called from as_free when an address space is being destroyed.
1914  */
1915 void
hat_free_start(struct hat * sfmmup)1916 hat_free_start(struct hat *sfmmup)
1917 {
1918 	ASSERT(AS_WRITE_HELD(sfmmup->sfmmu_as));
1919 	ASSERT(sfmmup != ksfmmup);
1920 
1921 	sfmmup->sfmmu_free = 1;
1922 	if (sfmmup->sfmmu_scdp != NULL) {
1923 		sfmmu_leave_scd(sfmmup, 0);
1924 	}
1925 
1926 	ASSERT(sfmmup->sfmmu_scdp == NULL);
1927 }
1928 
1929 void
hat_free_end(struct hat * sfmmup)1930 hat_free_end(struct hat *sfmmup)
1931 {
1932 	int i;
1933 
1934 	ASSERT(sfmmup->sfmmu_free == 1);
1935 	ASSERT(sfmmup->sfmmu_ttecnt[TTE8K] == 0);
1936 	ASSERT(sfmmup->sfmmu_ttecnt[TTE64K] == 0);
1937 	ASSERT(sfmmup->sfmmu_ttecnt[TTE512K] == 0);
1938 	ASSERT(sfmmup->sfmmu_ttecnt[TTE4M] == 0);
1939 	ASSERT(sfmmup->sfmmu_ttecnt[TTE32M] == 0);
1940 	ASSERT(sfmmup->sfmmu_ttecnt[TTE256M] == 0);
1941 
1942 	if (sfmmup->sfmmu_rmstat) {
1943 		hat_freestat(sfmmup->sfmmu_as, 0);
1944 	}
1945 
1946 	while (sfmmup->sfmmu_tsb != NULL) {
1947 		struct tsb_info *next = sfmmup->sfmmu_tsb->tsb_next;
1948 		sfmmu_tsbinfo_free(sfmmup->sfmmu_tsb);
1949 		sfmmup->sfmmu_tsb = next;
1950 	}
1951 
1952 	if (sfmmup->sfmmu_srdp != NULL) {
1953 		sfmmu_leave_srd(sfmmup);
1954 		ASSERT(sfmmup->sfmmu_srdp == NULL);
1955 		for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1956 			if (sfmmup->sfmmu_hmeregion_links[i] != NULL) {
1957 				kmem_free(sfmmup->sfmmu_hmeregion_links[i],
1958 				    SFMMU_L2_HMERLINKS_SIZE);
1959 				sfmmup->sfmmu_hmeregion_links[i] = NULL;
1960 			}
1961 		}
1962 	}
1963 	sfmmu_free_sfmmu(sfmmup);
1964 
1965 #ifdef DEBUG
1966 	for (i = 0; i < SFMMU_L1_HMERLINKS; i++) {
1967 		ASSERT(sfmmup->sfmmu_hmeregion_links[i] == NULL);
1968 	}
1969 #endif
1970 
1971 	kmem_cache_free(sfmmuid_cache, sfmmup);
1972 }
1973 
1974 /*
1975  * Set up any translation structures, for the specified address space,
1976  * that are needed or preferred when the process is being swapped in.
1977  */
1978 /* ARGSUSED */
1979 void
hat_swapin(struct hat * hat)1980 hat_swapin(struct hat *hat)
1981 {
1982 }
1983 
1984 /*
1985  * Free all of the translation resources, for the specified address space,
1986  * that can be freed while the process is swapped out. Called from as_swapout.
1987  * Also, free up the ctx that this process was using.
1988  */
1989 void
hat_swapout(struct hat * sfmmup)1990 hat_swapout(struct hat *sfmmup)
1991 {
1992 	struct hmehash_bucket *hmebp;
1993 	struct hme_blk *hmeblkp;
1994 	struct hme_blk *pr_hblk = NULL;
1995 	struct hme_blk *nx_hblk;
1996 	int i;
1997 	struct hme_blk *list = NULL;
1998 	hatlock_t *hatlockp;
1999 	struct tsb_info *tsbinfop;
2000 	struct free_tsb {
2001 		struct free_tsb *next;
2002 		struct tsb_info *tsbinfop;
2003 	};			/* free list of TSBs */
2004 	struct free_tsb *freelist, *last, *next;
2005 
2006 	SFMMU_STAT(sf_swapout);
2007 
2008 	/*
2009 	 * There is no way to go from an as to all its translations in sfmmu.
2010 	 * Here is one of the times when we take the big hit and traverse
2011 	 * the hash looking for hme_blks to free up.  Not only do we free up
2012 	 * this as hme_blks but all those that are free.  We are obviously
2013 	 * swapping because we need memory so let's free up as much
2014 	 * as we can.
2015 	 *
2016 	 * Note that we don't flush TLB/TSB here -- it's not necessary
2017 	 * because:
2018 	 *  1) we free the ctx we're using and throw away the TSB(s);
2019 	 *  2) processes aren't runnable while being swapped out.
2020 	 */
2021 	ASSERT(sfmmup != KHATID);
2022 	for (i = 0; i <= UHMEHASH_SZ; i++) {
2023 		hmebp = &uhme_hash[i];
2024 		SFMMU_HASH_LOCK(hmebp);
2025 		hmeblkp = hmebp->hmeblkp;
2026 		pr_hblk = NULL;
2027 		while (hmeblkp) {
2028 
2029 			if ((hmeblkp->hblk_tag.htag_id == sfmmup) &&
2030 			    !hmeblkp->hblk_shw_bit && !hmeblkp->hblk_lckcnt) {
2031 				ASSERT(!hmeblkp->hblk_shared);
2032 				(void) sfmmu_hblk_unload(sfmmup, hmeblkp,
2033 				    (caddr_t)get_hblk_base(hmeblkp),
2034 				    get_hblk_endaddr(hmeblkp),
2035 				    NULL, HAT_UNLOAD);
2036 			}
2037 			nx_hblk = hmeblkp->hblk_next;
2038 			if (!hmeblkp->hblk_vcnt && !hmeblkp->hblk_hmecnt) {
2039 				ASSERT(!hmeblkp->hblk_lckcnt);
2040 				sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
2041 				    &list, 0);
2042 			} else {
2043 				pr_hblk = hmeblkp;
2044 			}
2045 			hmeblkp = nx_hblk;
2046 		}
2047 		SFMMU_HASH_UNLOCK(hmebp);
2048 	}
2049 
2050 	sfmmu_hblks_list_purge(&list, 0);
2051 
2052 	/*
2053 	 * Now free up the ctx so that others can reuse it.
2054 	 */
2055 	hatlockp = sfmmu_hat_enter(sfmmup);
2056 
2057 	sfmmu_invalidate_ctx(sfmmup);
2058 
2059 	/*
2060 	 * Free TSBs, but not tsbinfos, and set SWAPPED flag.
2061 	 * If TSBs were never swapped in, just return.
2062 	 * This implies that we don't support partial swapping
2063 	 * of TSBs -- either all are swapped out, or none are.
2064 	 *
2065 	 * We must hold the HAT lock here to prevent racing with another
2066 	 * thread trying to unmap TTEs from the TSB or running the post-
2067 	 * relocator after relocating the TSB's memory.  Unfortunately, we
2068 	 * can't free memory while holding the HAT lock or we could
2069 	 * deadlock, so we build a list of TSBs to be freed after marking
2070 	 * the tsbinfos as swapped out and free them after dropping the
2071 	 * lock.
2072 	 */
2073 	if (SFMMU_FLAGS_ISSET(sfmmup, HAT_SWAPPED)) {
2074 		sfmmu_hat_exit(hatlockp);
2075 		return;
2076 	}
2077 
2078 	SFMMU_FLAGS_SET(sfmmup, HAT_SWAPPED);
2079 	last = freelist = NULL;
2080 	for (tsbinfop = sfmmup->sfmmu_tsb; tsbinfop != NULL;
2081 	    tsbinfop = tsbinfop->tsb_next) {
2082 		ASSERT((tsbinfop->tsb_flags & TSB_SWAPPED) == 0);
2083 
2084 		/*
2085 		 * Cast the TSB into a struct free_tsb and put it on the free
2086 		 * list.
2087 		 */
2088 		if (freelist == NULL) {
2089 			last = freelist = (struct free_tsb *)tsbinfop->tsb_va;
2090 		} else {
2091 			last->next = (struct free_tsb *)tsbinfop->tsb_va;
2092 			last = last->next;
2093 		}
2094 		last->next = NULL;
2095 		last->tsbinfop = tsbinfop;
2096 		tsbinfop->tsb_flags |= TSB_SWAPPED;
2097 		/*
2098 		 * Zero out the TTE to clear the valid bit.
2099 		 * Note we can't use a value like 0xbad because we want to
2100 		 * ensure diagnostic bits are NEVER set on TTEs that might
2101 		 * be loaded.  The intent is to catch any invalid access
2102 		 * to the swapped TSB, such as a thread running with a valid
2103 		 * context without first calling sfmmu_tsb_swapin() to
2104 		 * allocate TSB memory.
2105 		 */
2106 		tsbinfop->tsb_tte.ll = 0;
2107 	}
2108 
2109 	/* Now we can drop the lock and free the TSB memory. */
2110 	sfmmu_hat_exit(hatlockp);
2111 	for (; freelist != NULL; freelist = next) {
2112 		next = freelist->next;
2113 		sfmmu_tsb_free(freelist->tsbinfop);
2114 	}
2115 }
2116 
2117 /*
2118  * Duplicate the translations of an as into another newas
2119  */
2120 /* ARGSUSED */
2121 int
hat_dup(struct hat * hat,struct hat * newhat,caddr_t addr,size_t len,uint_t flag)2122 hat_dup(struct hat *hat, struct hat *newhat, caddr_t addr, size_t len,
2123     uint_t flag)
2124 {
2125 	sf_srd_t *srdp;
2126 	sf_scd_t *scdp;
2127 	int i;
2128 	extern uint_t get_color_start(struct as *);
2129 
2130 	ASSERT((flag == 0) || (flag == HAT_DUP_ALL) || (flag == HAT_DUP_COW) ||
2131 	    (flag == HAT_DUP_SRD));
2132 	ASSERT(hat != ksfmmup);
2133 	ASSERT(newhat != ksfmmup);
2134 	ASSERT(flag != HAT_DUP_ALL || hat->sfmmu_srdp == newhat->sfmmu_srdp);
2135 
2136 	if (flag == HAT_DUP_COW) {
2137 		panic("hat_dup: HAT_DUP_COW not supported");
2138 	}
2139 
2140 	if (flag == HAT_DUP_SRD && ((srdp = hat->sfmmu_srdp) != NULL)) {
2141 		ASSERT(srdp->srd_evp != NULL);
2142 		VN_HOLD(srdp->srd_evp);
2143 		ASSERT(srdp->srd_refcnt > 0);
2144 		newhat->sfmmu_srdp = srdp;
2145 		atomic_inc_32((volatile uint_t *)&srdp->srd_refcnt);
2146 	}
2147 
2148 	/*
2149 	 * HAT_DUP_ALL flag is used after as duplication is done.
2150 	 */
2151 	if (flag == HAT_DUP_ALL && ((srdp = newhat->sfmmu_srdp) != NULL)) {
2152 		ASSERT(newhat->sfmmu_srdp->srd_refcnt >= 2);
2153 		newhat->sfmmu_rtteflags = hat->sfmmu_rtteflags;
2154 		if (hat->sfmmu_flags & HAT_4MTEXT_FLAG) {
2155 			newhat->sfmmu_flags |= HAT_4MTEXT_FLAG;
2156 		}
2157 
2158 		/* check if need to join scd */
2159 		if ((scdp = hat->sfmmu_scdp) != NULL &&
2160 		    newhat->sfmmu_scdp != scdp) {
2161 			int ret;
2162 			SF_RGNMAP_IS_SUBSET(&newhat->sfmmu_region_map,
2163 			    &scdp->scd_region_map, ret);
2164 			ASSERT(ret);
2165 			sfmmu_join_scd(scdp, newhat);
2166 			ASSERT(newhat->sfmmu_scdp == scdp &&
2167 			    scdp->scd_refcnt >= 2);
2168 			for (i = 0; i < max_mmu_page_sizes; i++) {
2169 				newhat->sfmmu_ismttecnt[i] =
2170 				    hat->sfmmu_ismttecnt[i];
2171 				newhat->sfmmu_scdismttecnt[i] =
2172 				    hat->sfmmu_scdismttecnt[i];
2173 			}
2174 		}
2175 
2176 		sfmmu_check_page_sizes(newhat, 1);
2177 	}
2178 
2179 	if (flag == HAT_DUP_ALL && consistent_coloring == 0 &&
2180 	    update_proc_pgcolorbase_after_fork != 0) {
2181 		hat->sfmmu_clrbin = get_color_start(hat->sfmmu_as);
2182 	}
2183 	return (0);
2184 }
2185 
2186 void
hat_memload(struct hat * hat,caddr_t addr,struct page * pp,uint_t attr,uint_t flags)2187 hat_memload(struct hat *hat, caddr_t addr, struct page *pp,
2188     uint_t attr, uint_t flags)
2189 {
2190 	hat_do_memload(hat, addr, pp, attr, flags,
2191 	    SFMMU_INVALID_SHMERID);
2192 }
2193 
2194 void
hat_memload_region(struct hat * hat,caddr_t addr,struct page * pp,uint_t attr,uint_t flags,hat_region_cookie_t rcookie)2195 hat_memload_region(struct hat *hat, caddr_t addr, struct page *pp,
2196     uint_t attr, uint_t flags, hat_region_cookie_t rcookie)
2197 {
2198 	uint_t rid;
2199 	if (rcookie == HAT_INVALID_REGION_COOKIE) {
2200 		hat_do_memload(hat, addr, pp, attr, flags,
2201 		    SFMMU_INVALID_SHMERID);
2202 		return;
2203 	}
2204 	rid = (uint_t)((uint64_t)rcookie);
2205 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2206 	hat_do_memload(hat, addr, pp, attr, flags, rid);
2207 }
2208 
2209 /*
2210  * Set up addr to map to page pp with protection prot.
2211  * As an optimization we also load the TSB with the
2212  * corresponding tte but it is no big deal if  the tte gets kicked out.
2213  */
2214 static void
hat_do_memload(struct hat * hat,caddr_t addr,struct page * pp,uint_t attr,uint_t flags,uint_t rid)2215 hat_do_memload(struct hat *hat, caddr_t addr, struct page *pp,
2216     uint_t attr, uint_t flags, uint_t rid)
2217 {
2218 	tte_t tte;
2219 
2220 
2221 	ASSERT(hat != NULL);
2222 	ASSERT(PAGE_LOCKED(pp));
2223 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2224 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2225 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2226 	SFMMU_VALIDATE_HMERID(hat, rid, addr, MMU_PAGESIZE);
2227 
2228 	if (PP_ISFREE(pp)) {
2229 		panic("hat_memload: loading a mapping to free page %p",
2230 		    (void *)pp);
2231 	}
2232 
2233 	ASSERT((hat == ksfmmup) || AS_LOCK_HELD(hat->sfmmu_as));
2234 
2235 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2236 		cmn_err(CE_NOTE, "hat_memload: unsupported flags %d",
2237 		    flags & ~SFMMU_LOAD_ALLFLAG);
2238 
2239 	if (hat->sfmmu_rmstat)
2240 		hat_resvstat(MMU_PAGESIZE, hat->sfmmu_as, addr);
2241 
2242 #if defined(SF_ERRATA_57)
2243 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2244 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2245 	    !(flags & HAT_LOAD_SHARE)) {
2246 		cmn_err(CE_WARN, "hat_memload: illegal attempt to make user "
2247 		    " page executable");
2248 		attr &= ~PROT_EXEC;
2249 	}
2250 #endif
2251 
2252 	sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2253 	(void) sfmmu_tteload_array(hat, &tte, addr, &pp, flags, rid);
2254 
2255 	/*
2256 	 * Check TSB and TLB page sizes.
2257 	 */
2258 	if ((flags & HAT_LOAD_SHARE) == 0) {
2259 		sfmmu_check_page_sizes(hat, 1);
2260 	}
2261 }
2262 
2263 /*
2264  * hat_devload can be called to map real memory (e.g.
2265  * /dev/kmem) and even though hat_devload will determine pf is
2266  * for memory, it will be unable to get a shared lock on the
2267  * page (because someone else has it exclusively) and will
2268  * pass dp = NULL.  If tteload doesn't get a non-NULL
2269  * page pointer it can't cache memory.
2270  */
2271 void
hat_devload(struct hat * hat,caddr_t addr,size_t len,pfn_t pfn,uint_t attr,int flags)2272 hat_devload(struct hat *hat, caddr_t addr, size_t len, pfn_t pfn,
2273     uint_t attr, int flags)
2274 {
2275 	tte_t tte;
2276 	struct page *pp = NULL;
2277 	int use_lgpg = 0;
2278 
2279 	ASSERT(hat != NULL);
2280 
2281 	ASSERT(!(flags & ~SFMMU_LOAD_ALLFLAG));
2282 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2283 	ASSERT((hat == ksfmmup) || AS_LOCK_HELD(hat->sfmmu_as));
2284 	if (len == 0)
2285 		panic("hat_devload: zero len");
2286 	if (flags & ~SFMMU_LOAD_ALLFLAG)
2287 		cmn_err(CE_NOTE, "hat_devload: unsupported flags %d",
2288 		    flags & ~SFMMU_LOAD_ALLFLAG);
2289 
2290 #if defined(SF_ERRATA_57)
2291 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2292 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2293 	    !(flags & HAT_LOAD_SHARE)) {
2294 		cmn_err(CE_WARN, "hat_devload: illegal attempt to make user "
2295 		    " page executable");
2296 		attr &= ~PROT_EXEC;
2297 	}
2298 #endif
2299 
2300 	/*
2301 	 * If it's a memory page find its pp
2302 	 */
2303 	if (!(flags & HAT_LOAD_NOCONSIST) && pf_is_memory(pfn)) {
2304 		pp = page_numtopp_nolock(pfn);
2305 		if (pp == NULL) {
2306 			flags |= HAT_LOAD_NOCONSIST;
2307 		} else {
2308 			if (PP_ISFREE(pp)) {
2309 				panic("hat_memload: loading "
2310 				    "a mapping to free page %p",
2311 				    (void *)pp);
2312 			}
2313 			if (!PAGE_LOCKED(pp) && !PP_ISNORELOC(pp)) {
2314 				panic("hat_memload: loading a mapping "
2315 				    "to unlocked relocatable page %p",
2316 				    (void *)pp);
2317 			}
2318 			ASSERT(len == MMU_PAGESIZE);
2319 		}
2320 	}
2321 
2322 	if (hat->sfmmu_rmstat)
2323 		hat_resvstat(len, hat->sfmmu_as, addr);
2324 
2325 	if (flags & HAT_LOAD_NOCONSIST) {
2326 		attr |= SFMMU_UNCACHEVTTE;
2327 		use_lgpg = 1;
2328 	}
2329 	if (!pf_is_memory(pfn)) {
2330 		attr |= SFMMU_UNCACHEPTTE | HAT_NOSYNC;
2331 		use_lgpg = 1;
2332 		switch (attr & HAT_ORDER_MASK) {
2333 			case HAT_STRICTORDER:
2334 			case HAT_UNORDERED_OK:
2335 				/*
2336 				 * we set the side effect bit for all non
2337 				 * memory mappings unless merging is ok
2338 				 */
2339 				attr |= SFMMU_SIDEFFECT;
2340 				break;
2341 			case HAT_MERGING_OK:
2342 			case HAT_LOADCACHING_OK:
2343 			case HAT_STORECACHING_OK:
2344 				break;
2345 			default:
2346 				panic("hat_devload: bad attr");
2347 				break;
2348 		}
2349 	}
2350 	while (len) {
2351 		if (!use_lgpg) {
2352 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2353 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2354 			    flags, SFMMU_INVALID_SHMERID);
2355 			len -= MMU_PAGESIZE;
2356 			addr += MMU_PAGESIZE;
2357 			pfn++;
2358 			continue;
2359 		}
2360 		/*
2361 		 *  try to use large pages, check va/pa alignments
2362 		 *  Note that 32M/256M page sizes are not (yet) supported.
2363 		 */
2364 		if ((len >= MMU_PAGESIZE4M) &&
2365 		    !((uintptr_t)addr & MMU_PAGEOFFSET4M) &&
2366 		    !(disable_large_pages & (1 << TTE4M)) &&
2367 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET4M)) {
2368 			sfmmu_memtte(&tte, pfn, attr, TTE4M);
2369 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2370 			    flags, SFMMU_INVALID_SHMERID);
2371 			len -= MMU_PAGESIZE4M;
2372 			addr += MMU_PAGESIZE4M;
2373 			pfn += MMU_PAGESIZE4M / MMU_PAGESIZE;
2374 		} else if ((len >= MMU_PAGESIZE512K) &&
2375 		    !((uintptr_t)addr & MMU_PAGEOFFSET512K) &&
2376 		    !(disable_large_pages & (1 << TTE512K)) &&
2377 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET512K)) {
2378 			sfmmu_memtte(&tte, pfn, attr, TTE512K);
2379 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2380 			    flags, SFMMU_INVALID_SHMERID);
2381 			len -= MMU_PAGESIZE512K;
2382 			addr += MMU_PAGESIZE512K;
2383 			pfn += MMU_PAGESIZE512K / MMU_PAGESIZE;
2384 		} else if ((len >= MMU_PAGESIZE64K) &&
2385 		    !((uintptr_t)addr & MMU_PAGEOFFSET64K) &&
2386 		    !(disable_large_pages & (1 << TTE64K)) &&
2387 		    !(mmu_ptob(pfn) & MMU_PAGEOFFSET64K)) {
2388 			sfmmu_memtte(&tte, pfn, attr, TTE64K);
2389 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2390 			    flags, SFMMU_INVALID_SHMERID);
2391 			len -= MMU_PAGESIZE64K;
2392 			addr += MMU_PAGESIZE64K;
2393 			pfn += MMU_PAGESIZE64K / MMU_PAGESIZE;
2394 		} else {
2395 			sfmmu_memtte(&tte, pfn, attr, TTE8K);
2396 			(void) sfmmu_tteload_array(hat, &tte, addr, &pp,
2397 			    flags, SFMMU_INVALID_SHMERID);
2398 			len -= MMU_PAGESIZE;
2399 			addr += MMU_PAGESIZE;
2400 			pfn++;
2401 		}
2402 	}
2403 
2404 	/*
2405 	 * Check TSB and TLB page sizes.
2406 	 */
2407 	if ((flags & HAT_LOAD_SHARE) == 0) {
2408 		sfmmu_check_page_sizes(hat, 1);
2409 	}
2410 }
2411 
2412 void
hat_memload_array(struct hat * hat,caddr_t addr,size_t len,struct page ** pps,uint_t attr,uint_t flags)2413 hat_memload_array(struct hat *hat, caddr_t addr, size_t len,
2414     struct page **pps, uint_t attr, uint_t flags)
2415 {
2416 	hat_do_memload_array(hat, addr, len, pps, attr, flags,
2417 	    SFMMU_INVALID_SHMERID);
2418 }
2419 
2420 void
hat_memload_array_region(struct hat * hat,caddr_t addr,size_t len,struct page ** pps,uint_t attr,uint_t flags,hat_region_cookie_t rcookie)2421 hat_memload_array_region(struct hat *hat, caddr_t addr, size_t len,
2422     struct page **pps, uint_t attr, uint_t flags,
2423     hat_region_cookie_t rcookie)
2424 {
2425 	uint_t rid;
2426 	if (rcookie == HAT_INVALID_REGION_COOKIE) {
2427 		hat_do_memload_array(hat, addr, len, pps, attr, flags,
2428 		    SFMMU_INVALID_SHMERID);
2429 		return;
2430 	}
2431 	rid = (uint_t)((uint64_t)rcookie);
2432 	ASSERT(rid < SFMMU_MAX_HME_REGIONS);
2433 	hat_do_memload_array(hat, addr, len, pps, attr, flags, rid);
2434 }
2435 
2436 /*
2437  * Map the largest extend possible out of the page array. The array may NOT
2438  * be in order.  The largest possible mapping a page can have
2439  * is specified in the p_szc field.  The p_szc field
2440  * cannot change as long as there any mappings (large or small)
2441  * to any of the pages that make up the large page. (ie. any
2442  * promotion/demotion of page size is not up to the hat but up to
2443  * the page free list manager).  The array
2444  * should consist of properly aligned contigous pages that are
2445  * part of a big page for a large mapping to be created.
2446  */
2447 static void
hat_do_memload_array(struct hat * hat,caddr_t addr,size_t len,struct page ** pps,uint_t attr,uint_t flags,uint_t rid)2448 hat_do_memload_array(struct hat *hat, caddr_t addr, size_t len,
2449     struct page **pps, uint_t attr, uint_t flags, uint_t rid)
2450 {
2451 	int  ttesz;
2452 	size_t mapsz;
2453 	pgcnt_t	numpg, npgs;
2454 	tte_t tte;
2455 	page_t *pp;
2456 	uint_t large_pages_disable;
2457 
2458 	ASSERT(!((uintptr_t)addr & MMU_PAGEOFFSET));
2459 	SFMMU_VALIDATE_HMERID(hat, rid, addr, len);
2460 
2461 	if (hat->sfmmu_rmstat)
2462 		hat_resvstat(len, hat->sfmmu_as, addr);
2463 
2464 #if defined(SF_ERRATA_57)
2465 	if ((hat != ksfmmup) && AS_TYPE_64BIT(hat->sfmmu_as) &&
2466 	    (addr < errata57_limit) && (attr & PROT_EXEC) &&
2467 	    !(flags & HAT_LOAD_SHARE)) {
2468 		cmn_err(CE_WARN, "hat_memload_array: illegal attempt to make "
2469 		    "user page executable");
2470 		attr &= ~PROT_EXEC;
2471 	}
2472 #endif
2473 
2474 	/* Get number of pages */
2475 	npgs = len >> MMU_PAGESHIFT;
2476 
2477 	if (flags & HAT_LOAD_SHARE) {
2478 		large_pages_disable = disable_ism_large_pages;
2479 	} else {
2480 		large_pages_disable = disable_large_pages;
2481 	}
2482 
2483 	if (npgs < NHMENTS || large_pages_disable == LARGE_PAGES_OFF) {
2484 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2485 		    rid);
2486 		return;
2487 	}
2488 
2489 	while (npgs >= NHMENTS) {
2490 		pp = *pps;
2491 		for (ttesz = pp->p_szc; ttesz != TTE8K; ttesz--) {
2492 			/*
2493 			 * Check if this page size is disabled.
2494 			 */
2495 			if (large_pages_disable & (1 << ttesz))
2496 				continue;
2497 
2498 			numpg = TTEPAGES(ttesz);
2499 			mapsz = numpg << MMU_PAGESHIFT;
2500 			if ((npgs >= numpg) &&
2501 			    IS_P2ALIGNED(addr, mapsz) &&
2502 			    IS_P2ALIGNED(pp->p_pagenum, numpg)) {
2503 				/*
2504 				 * At this point we have enough pages and
2505 				 * we know the virtual address and the pfn
2506 				 * are properly aligned.  We still need
2507 				 * to check for physical contiguity but since
2508 				 * it is very likely that this is the case
2509 				 * we will assume they are so and undo
2510 				 * the request if necessary.  It would
2511 				 * be great if we could get a hint flag
2512 				 * like HAT_CONTIG which would tell us
2513 				 * the pages are contigous for sure.
2514 				 */
2515 				sfmmu_memtte(&tte, (*pps)->p_pagenum,
2516 				    attr, ttesz);
2517 				if (!sfmmu_tteload_array(hat, &tte, addr,
2518 				    pps, flags, rid)) {
2519 					break;
2520 				}
2521 			}
2522 		}
2523 		if (ttesz == TTE8K) {
2524 			/*
2525 			 * We were not able to map array using a large page
2526 			 * batch a hmeblk or fraction at a time.
2527 			 */
2528 			numpg = ((uintptr_t)addr >> MMU_PAGESHIFT)
2529 			    & (NHMENTS-1);
2530 			numpg = NHMENTS - numpg;
2531 			ASSERT(numpg <= npgs);
2532 			mapsz = numpg * MMU_PAGESIZE;
2533 			sfmmu_memload_batchsmall(hat, addr, pps, attr, flags,
2534 			    numpg, rid);
2535 		}
2536 		addr += mapsz;
2537 		npgs -= numpg;
2538 		pps += numpg;
2539 	}
2540 
2541 	if (npgs) {
2542 		sfmmu_memload_batchsmall(hat, addr, pps, attr, flags, npgs,
2543 		    rid);
2544 	}
2545 
2546 	/*
2547 	 * Check TSB and TLB page sizes.
2548 	 */
2549 	if ((flags & HAT_LOAD_SHARE) == 0) {
2550 		sfmmu_check_page_sizes(hat, 1);
2551 	}
2552 }
2553 
2554 /*
2555  * Function tries to batch 8K pages into the same hme blk.
2556  */
2557 static void
sfmmu_memload_batchsmall(struct hat * hat,caddr_t vaddr,page_t ** pps,uint_t attr,uint_t flags,pgcnt_t npgs,uint_t rid)2558 sfmmu_memload_batchsmall(struct hat *hat, caddr_t vaddr, page_t **pps,
2559     uint_t attr, uint_t flags, pgcnt_t npgs, uint_t rid)
2560 {
2561 	tte_t	tte;
2562 	page_t *pp;
2563 	struct hmehash_bucket *hmebp;
2564 	struct hme_blk *hmeblkp;
2565 	int	index;
2566 
2567 	while (npgs) {
2568 		/*
2569 		 * Acquire the hash bucket.
2570 		 */
2571 		hmebp = sfmmu_tteload_acquire_hashbucket(hat, vaddr, TTE8K,
2572 		    rid);
2573 		ASSERT(hmebp);
2574 
2575 		/*
2576 		 * Find the hment block.
2577 		 */
2578 		hmeblkp = sfmmu_tteload_find_hmeblk(hat, hmebp, vaddr,
2579 		    TTE8K, flags, rid);
2580 		ASSERT(hmeblkp);
2581 
2582 		do {
2583 			/*
2584 			 * Make the tte.
2585 			 */
2586 			pp = *pps;
2587 			sfmmu_memtte(&tte, pp->p_pagenum, attr, TTE8K);
2588 
2589 			/*
2590 			 * Add the translation.
2591 			 */
2592 			(void) sfmmu_tteload_addentry(hat, hmeblkp, &tte,
2593 			    vaddr, pps, flags, rid);
2594 
2595 			/*
2596 			 * Goto next page.
2597 			 */
2598 			pps++;
2599 			npgs--;
2600 
2601 			/*
2602 			 * Goto next address.
2603 			 */
2604 			vaddr += MMU_PAGESIZE;
2605 
2606 			/*
2607 			 * Don't crossover into a different hmentblk.
2608 			 */
2609 			index = (int)(((uintptr_t)vaddr >> MMU_PAGESHIFT) &
2610 			    (NHMENTS-1));
2611 
2612 		} while (index != 0 && npgs != 0);
2613 
2614 		/*
2615 		 * Release the hash bucket.
2616 		 */
2617 
2618 		sfmmu_tteload_release_hashbucket(hmebp);
2619 	}
2620 }
2621 
2622 /*
2623  * Construct a tte for a page:
2624  *
2625  * tte_valid = 1
2626  * tte_size2 = size & TTE_SZ2_BITS (Panther and Olympus-C only)
2627  * tte_size = size
2628  * tte_nfo = attr & HAT_NOFAULT
2629  * tte_ie = attr & HAT_STRUCTURE_LE
2630  * tte_hmenum = hmenum
2631  * tte_pahi = pp->p_pagenum >> TTE_PASHIFT;
2632  * tte_palo = pp->p_pagenum & TTE_PALOMASK;
2633  * tte_ref = 1 (optimization)
2634  * tte_wr_perm = attr & PROT_WRITE;
2635  * tte_no_sync = attr & HAT_NOSYNC
2636  * tte_lock = attr & SFMMU_LOCKTTE
2637  * tte_cp = !(attr & SFMMU_UNCACHEPTTE)
2638  * tte_cv = !(attr & SFMMU_UNCACHEVTTE)
2639  * tte_e = attr & SFMMU_SIDEFFECT
2640  * tte_priv = !(attr & PROT_USER)
2641  * tte_hwwr = if nosync is set and it is writable we set the mod bit (opt)
2642  * tte_glb = 0
2643  */
2644 void
sfmmu_memtte(tte_t * ttep,pfn_t pfn,uint_t attr,int tte_sz)2645 sfmmu_memtte(tte_t *ttep, pfn_t pfn, uint_t attr, int tte_sz)
2646 {
2647 	ASSERT(!(attr & ~SFMMU_LOAD_ALLATTR));
2648 
2649 	ttep->tte_inthi = MAKE_TTE_INTHI(pfn, attr, tte_sz, 0 /* hmenum */);
2650 	ttep->tte_intlo = MAKE_TTE_INTLO(pfn, attr, tte_sz, 0 /* hmenum */);
2651 
2652 	if (TTE_IS_NOSYNC(ttep)) {
2653 		TTE_SET_REF(ttep);
2654 		if (TTE_IS_WRITABLE(ttep)) {
2655 			TTE_SET_MOD(ttep);
2656 		}
2657 	}
2658 	if (TTE_IS_NFO(ttep) && TTE_IS_EXECUTABLE(ttep)) {
2659 		panic("sfmmu_memtte: can't set both NFO and EXEC bits");
2660 	}
2661 }
2662 
2663 /*
2664  * This function will add a translation to the hme_blk and allocate the
2665  * hme_blk if one does not exist.
2666  * If a page structure is specified then it will add the
2667  * corresponding hment to the mapping list.
2668  * It will also update the hmenum field for the tte.
2669  *
2670  * Currently this function is only used for kernel mappings.
2671  * So pass invalid region to sfmmu_tteload_array().
2672  */
2673 void
sfmmu_tteload(struct hat * sfmmup,tte_t * ttep,caddr_t vaddr,page_t * pp,uint_t flags)2674 sfmmu_tteload(struct hat *sfmmup, tte_t *ttep, caddr_t vaddr, page_t *pp,
2675     uint_t flags)
2676 {
2677 	ASSERT(sfmmup == ksfmmup);
2678 	(void) sfmmu_tteload_array(sfmmup, ttep, vaddr, &pp, flags,
2679 	    SFMMU_INVALID_SHMERID);
2680 }
2681 
2682 /*
2683  * Load (ttep != NULL) or unload (ttep == NULL) one entry in the TSB.
2684  * Assumes that a particular page size may only be resident in one TSB.
2685  */
2686 static void
sfmmu_mod_tsb(sfmmu_t * sfmmup,caddr_t vaddr,tte_t * ttep,int ttesz)2687 sfmmu_mod_tsb(sfmmu_t *sfmmup, caddr_t vaddr, tte_t *ttep, int ttesz)
2688 {
2689 	struct tsb_info *tsbinfop = NULL;
2690 	uint64_t tag;
2691 	struct tsbe *tsbe_addr;
2692 	uint64_t tsb_base;
2693 	uint_t tsb_size;
2694 	int vpshift = MMU_PAGESHIFT;
2695 	int phys = 0;
2696 
2697 	if (sfmmup == ksfmmup) { /* No support for 32/256M ksfmmu pages */
2698 		phys = ktsb_phys;
2699 		if (ttesz >= TTE4M) {
2700 #ifndef sun4v
2701 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2702 #endif
2703 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2704 			tsb_size = ktsb4m_szcode;
2705 		} else {
2706 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2707 			tsb_size = ktsb_szcode;
2708 		}
2709 	} else {
2710 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2711 
2712 		/*
2713 		 * If there isn't a TSB for this page size, or the TSB is
2714 		 * swapped out, there is nothing to do.  Note that the latter
2715 		 * case seems impossible but can occur if hat_pageunload()
2716 		 * is called on an ISM mapping while the process is swapped
2717 		 * out.
2718 		 */
2719 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2720 			return;
2721 
2722 		/*
2723 		 * If another thread is in the middle of relocating a TSB
2724 		 * we can't unload the entry so set a flag so that the
2725 		 * TSB will be flushed before it can be accessed by the
2726 		 * process.
2727 		 */
2728 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2729 			if (ttep == NULL)
2730 				tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2731 			return;
2732 		}
2733 #if defined(UTSB_PHYS)
2734 		phys = 1;
2735 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2736 #else
2737 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2738 #endif
2739 		tsb_size = tsbinfop->tsb_szc;
2740 	}
2741 	if (ttesz >= TTE4M)
2742 		vpshift = MMU_PAGESHIFT4M;
2743 
2744 	tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2745 	tag = sfmmu_make_tsbtag(vaddr);
2746 
2747 	if (ttep == NULL) {
2748 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2749 	} else {
2750 		if (ttesz >= TTE4M) {
2751 			SFMMU_STAT(sf_tsb_load4m);
2752 		} else {
2753 			SFMMU_STAT(sf_tsb_load8k);
2754 		}
2755 
2756 		sfmmu_load_tsbe(tsbe_addr, tag, ttep, phys);
2757 	}
2758 }
2759 
2760 /*
2761  * Unmap all entries from [start, end) matching the given page size.
2762  *
2763  * This function is used primarily to unmap replicated 64K or 512K entries
2764  * from the TSB that are inserted using the base page size TSB pointer, but
2765  * it may also be called to unmap a range of addresses from the TSB.
2766  */
2767 void
sfmmu_unload_tsb_range(sfmmu_t * sfmmup,caddr_t start,caddr_t end,int ttesz)2768 sfmmu_unload_tsb_range(sfmmu_t *sfmmup, caddr_t start, caddr_t end, int ttesz)
2769 {
2770 	struct tsb_info *tsbinfop;
2771 	uint64_t tag;
2772 	struct tsbe *tsbe_addr;
2773 	caddr_t vaddr;
2774 	uint64_t tsb_base;
2775 	int vpshift, vpgsz;
2776 	uint_t tsb_size;
2777 	int phys = 0;
2778 
2779 	/*
2780 	 * Assumptions:
2781 	 *  If ttesz == 8K, 64K or 512K, we walk through the range 8K
2782 	 *  at a time shooting down any valid entries we encounter.
2783 	 *
2784 	 *  If ttesz >= 4M we walk the range 4M at a time shooting
2785 	 *  down any valid mappings we find.
2786 	 */
2787 	if (sfmmup == ksfmmup) {
2788 		phys = ktsb_phys;
2789 		if (ttesz >= TTE4M) {
2790 #ifndef sun4v
2791 			ASSERT((ttesz != TTE32M) && (ttesz != TTE256M));
2792 #endif
2793 			tsb_base = (phys)? ktsb4m_pbase : (uint64_t)ktsb4m_base;
2794 			tsb_size = ktsb4m_szcode;
2795 		} else {
2796 			tsb_base = (phys)? ktsb_pbase : (uint64_t)ktsb_base;
2797 			tsb_size = ktsb_szcode;
2798 		}
2799 	} else {
2800 		SFMMU_GET_TSBINFO(tsbinfop, sfmmup, ttesz);
2801 
2802 		/*
2803 		 * If there isn't a TSB for this page size, or the TSB is
2804 		 * swapped out, there is nothing to do.  Note that the latter
2805 		 * case seems impossible but can occur if hat_pageunload()
2806 		 * is called on an ISM mapping while the process is swapped
2807 		 * out.
2808 		 */
2809 		if (tsbinfop == NULL || (tsbinfop->tsb_flags & TSB_SWAPPED))
2810 			return;
2811 
2812 		/*
2813 		 * If another thread is in the middle of relocating a TSB
2814 		 * we can't unload the entry so set a flag so that the
2815 		 * TSB will be flushed before it can be accessed by the
2816 		 * process.
2817 		 */
2818 		if ((tsbinfop->tsb_flags & TSB_RELOC_FLAG) != 0) {
2819 			tsbinfop->tsb_flags |= TSB_FLUSH_NEEDED;
2820 			return;
2821 		}
2822 #if defined(UTSB_PHYS)
2823 		phys = 1;
2824 		tsb_base = (uint64_t)tsbinfop->tsb_pa;
2825 #else
2826 		tsb_base = (uint64_t)tsbinfop->tsb_va;
2827 #endif
2828 		tsb_size = tsbinfop->tsb_szc;
2829 	}
2830 	if (ttesz >= TTE4M) {
2831 		vpshift = MMU_PAGESHIFT4M;
2832 		vpgsz = MMU_PAGESIZE4M;
2833 	} else {
2834 		vpshift = MMU_PAGESHIFT;
2835 		vpgsz = MMU_PAGESIZE;
2836 	}
2837 
2838 	for (vaddr = start; vaddr < end; vaddr += vpgsz) {
2839 		tag = sfmmu_make_tsbtag(vaddr);
2840 		tsbe_addr = sfmmu_get_tsbe(tsb_base, vaddr, vpshift, tsb_size);
2841 		sfmmu_unload_tsbe(tsbe_addr, tag, phys);
2842 	}
2843 }
2844 
2845 /*
2846  * Select the optimum TSB size given the number of mappings
2847  * that need to be cached.
2848  */
2849 static int
sfmmu_select_tsb_szc(pgcnt_t pgcnt)2850 sfmmu_select_tsb_szc(pgcnt_t pgcnt)
2851 {
2852 	int szc = 0;
2853 
2854 #ifdef DEBUG
2855 	if (tsb_grow_stress) {
2856 		uint32_t randval = (uint32_t)gettick() >> 4;
2857 		return (randval % (tsb_max_growsize + 1));
2858 	}
2859 #endif	/* DEBUG */
2860 
2861 	while ((szc < tsb_max_growsize) && (pgcnt > SFMMU_RSS_TSBSIZE(szc)))
2862 		szc++;
2863 	return (szc);
2864 }
2865 
2866 /*
2867  * This function will add a translation to the hme_blk and allocate the
2868  * hme_blk if one does not exist.
2869  * If a page structure is specified then it will add the
2870  * corresponding hment to the mapping list.
2871  * It will also update the hmenum field for the tte.
2872  * Furthermore, it attempts to create a large page translation
2873  * for <addr,hat> at page array pps.  It assumes addr and first
2874  * pp is correctly aligned.  It returns 0 if successful and 1 otherwise.
2875  */
2876 static int
sfmmu_tteload_array(sfmmu_t * sfmmup,tte_t * ttep,caddr_t vaddr,page_t ** pps,uint_t flags,uint_t rid)2877 sfmmu_tteload_array(sfmmu_t *sfmmup, tte_t *ttep, caddr_t vaddr,
2878     page_t **pps, uint_t flags, uint_t rid)
2879 {
2880 	struct hmehash_bucket *hmebp;
2881 	struct hme_blk *hmeblkp;
2882 	int	ret;
2883 	uint_t	size;
2884 
2885 	/*
2886 	 * Get mapping size.
2887 	 */
2888 	size = TTE_CSZ(ttep);
2889 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
2890 
2891 	/*
2892 	 * Acquire the hash bucket.
2893 	 */
2894 	hmebp = sfmmu_tteload_acquire_hashbucket(sfmmup, vaddr, size, rid);
2895 	ASSERT(hmebp);
2896 
2897 	/*
2898 	 * Find the hment block.
2899 	 */
2900 	hmeblkp = sfmmu_tteload_find_hmeblk(sfmmup, hmebp, vaddr, size, flags,
2901 	    rid);
2902 	ASSERT(hmeblkp);
2903 
2904 	/*
2905 	 * Add the translation.
2906 	 */
2907 	ret = sfmmu_tteload_addentry(sfmmup, hmeblkp, ttep, vaddr, pps, flags,
2908 	    rid);
2909 
2910 	/*
2911 	 * Release the hash bucket.
2912 	 */
2913 	sfmmu_tteload_release_hashbucket(hmebp);
2914 
2915 	return (ret);
2916 }
2917 
2918 /*
2919  * Function locks and returns a pointer to the hash bucket for vaddr and size.
2920  */
2921 static struct hmehash_bucket *
sfmmu_tteload_acquire_hashbucket(sfmmu_t * sfmmup,caddr_t vaddr,int size,uint_t rid)2922 sfmmu_tteload_acquire_hashbucket(sfmmu_t *sfmmup, caddr_t vaddr, int size,
2923     uint_t rid)
2924 {
2925 	struct hmehash_bucket *hmebp;
2926 	int hmeshift;
2927 	void *htagid = sfmmutohtagid(sfmmup, rid);
2928 
2929 	ASSERT(htagid != NULL);
2930 
2931 	hmeshift = HME_HASH_SHIFT(size);
2932 
2933 	hmebp = HME_HASH_FUNCTION(htagid, vaddr, hmeshift);
2934 
2935 	SFMMU_HASH_LOCK(hmebp);
2936 
2937 	return (hmebp);
2938 }
2939 
2940 /*
2941  * Function returns a pointer to an hmeblk in the hash bucket, hmebp. If the
2942  * hmeblk doesn't exists for the [sfmmup, vaddr & size] signature, a hmeblk is
2943  * allocated.
2944  */
2945 static struct hme_blk *
sfmmu_tteload_find_hmeblk(sfmmu_t * sfmmup,struct hmehash_bucket * hmebp,caddr_t vaddr,uint_t size,uint_t flags,uint_t rid)2946 sfmmu_tteload_find_hmeblk(sfmmu_t *sfmmup, struct hmehash_bucket *hmebp,
2947     caddr_t vaddr, uint_t size, uint_t flags, uint_t rid)
2948 {
2949 	hmeblk_tag hblktag;
2950 	int hmeshift;
2951 	struct hme_blk *hmeblkp, *pr_hblk, *list = NULL;
2952 
2953 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
2954 
2955 	hblktag.htag_id = sfmmutohtagid(sfmmup, rid);
2956 	ASSERT(hblktag.htag_id != NULL);
2957 	hmeshift = HME_HASH_SHIFT(size);
2958 	hblktag.htag_bspage = HME_HASH_BSPAGE(vaddr, hmeshift);
2959 	hblktag.htag_rehash = HME_HASH_REHASH(size);
2960 	hblktag.htag_rid = rid;
2961 
2962 ttearray_realloc:
2963 
2964 	HME_HASH_SEARCH_PREV(hmebp, hblktag, hmeblkp, pr_hblk, &list);
2965 
2966 	/*
2967 	 * We block until hblk_reserve_lock is released; it's held by
2968 	 * the thread, temporarily using hblk_reserve, until hblk_reserve is
2969 	 * replaced by a hblk from sfmmu8_cache.
2970 	 */
2971 	if (hmeblkp == (struct hme_blk *)hblk_reserve &&
2972 	    hblk_reserve_thread != curthread) {
2973 		SFMMU_HASH_UNLOCK(hmebp);
2974 		mutex_enter(&hblk_reserve_lock);
2975 		mutex_exit(&hblk_reserve_lock);
2976 		SFMMU_STAT(sf_hblk_reserve_hit);
2977 		SFMMU_HASH_LOCK(hmebp);
2978 		goto ttearray_realloc;
2979 	}
2980 
2981 	if (hmeblkp == NULL) {
2982 		hmeblkp = sfmmu_hblk_alloc(sfmmup, vaddr, hmebp, size,
2983 		    hblktag, flags, rid);
2984 		ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
2985 		ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
2986 	} else {
2987 		/*
2988 		 * It is possible for 8k and 64k hblks to collide since they
2989 		 * have the same rehash value. This is because we
2990 		 * lazily free hblks and 8K/64K blks could be lingering.
2991 		 * If we find size mismatch we free the block and & try again.
2992 		 */
2993 		if (get_hblk_ttesz(hmeblkp) != size) {
2994 			ASSERT(!hmeblkp->hblk_vcnt);
2995 			ASSERT(!hmeblkp->hblk_hmecnt);
2996 			sfmmu_hblk_hash_rm(hmebp, hmeblkp, pr_hblk,
2997 			    &list, 0);
2998 			goto ttearray_realloc;
2999 		}
3000 		if (hmeblkp->hblk_shw_bit) {
3001 			/*
3002 			 * if the hblk was previously used as a shadow hblk then
3003 			 * we will change it to a normal hblk
3004 			 */
3005 			ASSERT(!hmeblkp->hblk_shared);
3006 			if (hmeblkp->hblk_shw_mask) {
3007 				sfmmu_shadow_hcleanup(sfmmup, hmeblkp, hmebp);
3008 				ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3009 				goto ttearray_realloc;
3010 			} else {
3011 				hmeblkp->hblk_shw_bit = 0;
3012 			}
3013 		}
3014 		SFMMU_STAT(sf_hblk_hit);
3015 	}
3016 
3017 	/*
3018 	 * hat_memload() should never call kmem_cache_free() for kernel hmeblks;
3019 	 * see block comment showing the stacktrace in sfmmu_hblk_alloc();
3020 	 * set the flag parameter to 1 so that sfmmu_hblks_list_purge() will
3021 	 * just add these hmeblks to the per-cpu pending queue.
3022 	 */
3023 	sfmmu_hblks_list_purge(&list, 1);
3024 
3025 	ASSERT(get_hblk_ttesz(hmeblkp) == size);
3026 	ASSERT(!hmeblkp->hblk_shw_bit);
3027 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3028 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3029 	ASSERT(hmeblkp->hblk_tag.htag_rid == rid);
3030 
3031 	return (hmeblkp);
3032 }
3033 
3034 /*
3035  * Function adds a tte entry into the hmeblk. It returns 0 if successful and 1
3036  * otherwise.
3037  */
3038 static int
sfmmu_tteload_addentry(sfmmu_t * sfmmup,struct hme_blk * hmeblkp,tte_t * ttep,caddr_t vaddr,page_t ** pps,uint_t flags,uint_t rid)3039 sfmmu_tteload_addentry(sfmmu_t *sfmmup, struct hme_blk *hmeblkp, tte_t *ttep,
3040     caddr_t vaddr, page_t **pps, uint_t flags, uint_t rid)
3041 {
3042 	page_t *pp = *pps;
3043 	int hmenum, size, remap;
3044 	tte_t tteold, flush_tte;
3045 #ifdef DEBUG
3046 	tte_t orig_old;
3047 #endif /* DEBUG */
3048 	struct sf_hment *sfhme;
3049 	kmutex_t *pml, *pmtx;
3050 	hatlock_t *hatlockp;
3051 	int myflt;
3052 
3053 	/*
3054 	 * remove this panic when we decide to let user virtual address
3055 	 * space be >= USERLIMIT.
3056 	 */
3057 	if (!TTE_IS_PRIVILEGED(ttep) && vaddr >= (caddr_t)USERLIMIT)
3058 		panic("user addr %p in kernel space", (void *)vaddr);
3059 #if defined(TTE_IS_GLOBAL)
3060 	if (TTE_IS_GLOBAL(ttep))
3061 		panic("sfmmu_tteload: creating global tte");
3062 #endif
3063 
3064 #ifdef DEBUG
3065 	if (pf_is_memory(sfmmu_ttetopfn(ttep, vaddr)) &&
3066 	    !TTE_IS_PCACHEABLE(ttep) && !sfmmu_allow_nc_trans)
3067 		panic("sfmmu_tteload: non cacheable memory tte");
3068 #endif /* DEBUG */
3069 
3070 	/* don't simulate dirty bit for writeable ISM/DISM mappings */
3071 	if ((flags & HAT_LOAD_SHARE) && TTE_IS_WRITABLE(ttep)) {
3072 		TTE_SET_REF(ttep);
3073 		TTE_SET_MOD(ttep);
3074 	}
3075 
3076 	if ((flags & HAT_LOAD_SHARE) || !TTE_IS_REF(ttep) ||
3077 	    !TTE_IS_MOD(ttep)) {
3078 		/*
3079 		 * Don't load TSB for dummy as in ISM.  Also don't preload
3080 		 * the TSB if the TTE isn't writable since we're likely to
3081 		 * fault on it again -- preloading can be fairly expensive.
3082 		 */
3083 		flags |= SFMMU_NO_TSBLOAD;
3084 	}
3085 
3086 	size = TTE_CSZ(ttep);
3087 	switch (size) {
3088 	case TTE8K:
3089 		SFMMU_STAT(sf_tteload8k);
3090 		break;
3091 	case TTE64K:
3092 		SFMMU_STAT(sf_tteload64k);
3093 		break;
3094 	case TTE512K:
3095 		SFMMU_STAT(sf_tteload512k);
3096 		break;
3097 	case TTE4M:
3098 		SFMMU_STAT(sf_tteload4m);
3099 		break;
3100 	case (TTE32M):
3101 		SFMMU_STAT(sf_tteload32m);
3102 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3103 		break;
3104 	case (TTE256M):
3105 		SFMMU_STAT(sf_tteload256m);
3106 		ASSERT(mmu_page_sizes == max_mmu_page_sizes);
3107 		break;
3108 	}
3109 
3110 	ASSERT(!((uintptr_t)vaddr & TTE_PAGE_OFFSET(size)));
3111 	SFMMU_VALIDATE_HMERID(sfmmup, rid, vaddr, TTEBYTES(size));
3112 	ASSERT(!SFMMU_IS_SHMERID_VALID(rid) || hmeblkp->hblk_shared);
3113 	ASSERT(SFMMU_IS_SHMERID_VALID(rid) || !hmeblkp->hblk_shared);
3114 
3115 	HBLKTOHME_IDX(sfhme, hmeblkp, vaddr, hmenum);
3116 
3117 	/*
3118 	 * Need to grab mlist lock here so that pageunload
3119 	 * will not change tte behind us.
3120 	 */
3121 	if (pp) {
3122 		pml = sfmmu_mlist_enter(pp);
3123 	}
3124 
3125 	sfmmu_copytte(&sfhme->hme_tte, &tteold);
3126 	/*
3127 	 * Look for corresponding hment and if valid verify
3128 	 * pfns are equal.
3129 	 */
3130 	remap = TTE_IS_VALID(&tteold);
3131 	if (remap) {
3132 		pfn_t	new_pfn, old_pfn;
3133 
3134 		old_pfn = TTE_TO_PFN(vaddr, &tteold);
3135 		new_pfn = TTE_TO_PFN(vaddr, ttep);
3136 
3137 		if (flags & HAT_LOAD_REMAP) {
3138 			/* make sure we are remapping same type of pages */
3139 			if (pf_is_memory(old_pfn) != pf_is_memory(new_pfn)) {
3140 				panic("sfmmu_tteload - tte remap io<->memory");
3141 			}
3142 			if (old_pfn != new_pfn &&
3143 			    (pp != NULL || sfhme->hme_page != NULL)) {
3144 				panic("sfmmu_tteload - tte remap pp != NULL");
3145 			}
3146 		} else if (old_pfn != new_pfn) {
3147 			panic("sfmmu_tteload - tte remap, hmeblkp 0x%p",
3148 			    (void *)hmeblkp);
3149 		}
3150 		ASSERT(TTE_CSZ(&tteold) == TTE_CSZ(ttep));
3151 	}
3152 
3153 	if (pp) {
3154 		if (size == TTE8K) {
3155 #ifdef VAC
3156 			/*
3157 			 * Handle VAC consistency
3158 			 */
3159 			if (!remap && (cache & CACHE_VAC) && !PP_ISNC(pp)) {
3160 				sfmmu_vac_conflict(sfmmup, vaddr, pp);
3161 			}
3162 #endif
3163 
3164 			if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3165 				pmtx = sfmmu_page_enter(pp);
3166 				PP_CLRRO(pp);
3167 				sfmmu_page_exit(pmtx);
3168 			} else if (!PP_ISMAPPED(pp) &&
3169 			    (!TTE_IS_WRITABLE(ttep)) && !(PP_ISMOD(pp))) {
3170 				pmtx = sfmmu_page_enter(pp);
3171 				if (!(PP_ISMOD(pp))) {
3172 					PP_SETRO(pp);
3173 				}
3174 				sfmmu_page_exit(pmtx);
3175 			}
3176 
3177 		} else if (sfmmu_pagearray_setup(vaddr, pps, ttep, remap)) {
3178 			/*
3179 			 * sfmmu_pagearray_setup failed so return
3180 			 */
3181 			sfmmu_mlist_exit(pml);
3182 			return (1);
3183 		}
3184 	}
3185 
3186 	/*
3187 	 * Make sure hment is not on a mapping list.
3188 	 */
3189 	ASSERT(remap || (sfhme->hme_page == NULL));
3190 
3191 	/* if it is not a remap then hme->next better be NULL */
3192 	ASSERT((!remap) ? sfhme->hme_next == NULL : 1);
3193 
3194 	if (flags & HAT_LOAD_LOCK) {
3195 		if ((hmeblkp->hblk_lckcnt + 1) >= MAX_HBLK_LCKCNT) {
3196 			panic("too high lckcnt-hmeblk %p",
3197 			    (void *)hmeblkp);
3198 		}
3199 		atomic_inc_32(&hmeblkp->hblk_lckcnt);
3200 
3201 		HBLK_STACK_TRACE(hmeblkp, HBLK_LOCK);
3202 	}
3203 
3204 #ifdef VAC
3205 	if (pp && PP_ISNC(pp)) {
3206 		/*
3207 		 * If the physical page is marked to be uncacheable, like
3208 		 * by a vac conflict, make sure the new mapping is also
3209 		 * uncacheable.
3210 		 */
3211 		TTE_CLR_VCACHEABLE(ttep);
3212 		ASSERT(PP_GET_VCOLOR(pp) == NO_VCOLOR);
3213 	}
3214 #endif
3215 	ttep->tte_hmenum = hmenum;
3216 
3217 #ifdef DEBUG
3218 	orig_old = tteold;
3219 #endif /* DEBUG */
3220 
3221 	while (sfmmu_modifytte_try(&tteold, ttep, &sfhme->hme_tte) < 0) {
3222 		if ((sfmmup == KHATID) &&
3223 		    (flags & (HAT_LOAD_LOCK | HAT_LOAD_REMAP))) {
3224 			sfmmu_copytte(&sfhme->hme_tte, &tteold);
3225 		}
3226 #ifdef DEBUG
3227 		chk_tte(&orig_old, &tteold, ttep, hmeblkp);
3228 #endif /* DEBUG */
3229 	}
3230 	ASSERT(TTE_IS_VALID(&sfhme->hme_tte));
3231 
3232 	if (!TTE_IS_VALID(&tteold)) {
3233 
3234 		atomic_inc_16(&hmeblkp->hblk_vcnt);
3235 		if (rid == SFMMU_INVALID_SHMERID) {
3236 			atomic_inc_ulong(&sfmmup->sfmmu_ttecnt[size]);
3237 		} else {
3238 			sf_srd_t *srdp = sfmmup->sfmmu_srdp;
3239 			sf_region_t *rgnp = srdp->srd_hmergnp[rid];
3240 			/*
3241 			 * We already accounted for region ttecnt's in sfmmu
3242 			 * during hat_join_region() processing. Here we
3243 			 * only update ttecnt's in region struture.
3244 			 */
3245 			atomic_inc_ulong(&rgnp->rgn_ttecnt[size]);
3246 		}
3247 	}
3248 
3249 	myflt = (astosfmmu(curthread->t_procp->p_as) == sfmmup);
3250 	if (size > TTE8K && (flags & HAT_LOAD_SHARE) == 0 &&
3251 	    sfmmup != ksfmmup) {
3252 		uchar_t tteflag = 1 << size;
3253 		if (rid == SFMMU_INVALID_SHMERID) {
3254 			if (!(sfmmup->sfmmu_tteflags & tteflag)) {
3255 				hatlockp = sfmmu_hat_enter(sfmmup);
3256 				sfmmup->sfmmu_tteflags |= tteflag;
3257 				sfmmu_hat_exit(hatlockp);
3258 			}
3259 		} else if (!(sfmmup->sfmmu_rtteflags & tteflag)) {
3260 			hatlockp = sfmmu_hat_enter(sfmmup);
3261 			sfmmup->sfmmu_rtteflags |= tteflag;
3262 			sfmmu_hat_exit(hatlockp);
3263 		}
3264 		/*
3265 		 * Update the current CPU tsbmiss area, so the current thread
3266 		 * won't need to take the tsbmiss for the new pagesize.
3267 		 * The other threads in the process will update their tsb
3268 		 * miss area lazily in sfmmu_tsbmiss_exception() when they
3269 		 * fail to find the translation for a newly added pagesize.
3270 		 */
3271 		if (size > TTE64K && myflt) {
3272 			struct tsbmiss *tsbmp;
3273 			kpreempt_disable();
3274 			tsbmp = &tsbmiss_area[CPU->cpu_id];
3275 			if (rid == SFMMU_INVALID_SHMERID) {
3276 				if (!(tsbmp->uhat_tteflags & tteflag)) {
3277 					tsbmp->uhat_tteflags |= tteflag;
3278 				}
3279 			} else {
3280 				if (!(tsbmp->uhat_rtteflags & tteflag)) {
3281 					tsbmp->uhat_rtteflags |= tteflag;
3282 				}
3283 			}
3284 			kpreempt_enable();
3285 		}
3286 	}
3287 
3288 	if (size >= TTE4M && (flags & HAT_LOAD_TEXT) &&
3289 	    !SFMMU_FLAGS_ISSET(sfmmup, HAT_4MTEXT_FLAG)) {
3290 		hatlockp = sfmmu_hat_enter(sfmmup);
3291 		SFMMU_FLAGS_SET(sfmmup, HAT_4MTEXT_FLAG);
3292 		sfmmu_hat_exit(hatlockp);
3293 	}
3294 
3295 	flush_tte.tte_intlo = (tteold.tte_intlo ^ ttep->tte_intlo) &
3296 	    hw_tte.tte_intlo;
3297 	flush_tte.tte_inthi = (tteold.tte_inthi ^ ttep->tte_inthi) &
3298 	    hw_tte.tte_inthi;
3299 
3300 	if (remap && (flush_tte.tte_inthi || flush_tte.tte_intlo)) {
3301 		/*
3302 		 * If remap and new tte differs from old tte we need
3303 		 * to sync the mod bit and flush TLB/TSB.  We don't
3304 		 * need to sync ref bit because we currently always set
3305 		 * ref bit in tteload.
3306 		 */
3307 		ASSERT(TTE_IS_REF(ttep));
3308 		if (TTE_IS_MOD(&tteold)) {
3309 			sfmmu_ttesync(sfmmup, vaddr, &tteold, pp);
3310 		}
3311 		/*
3312 		 * hwtte bits shouldn't change for SRD hmeblks as long as SRD
3313 		 * hmes are only used for read only text. Adding this code for
3314 		 * completeness and future use of shared hmeblks with writable
3315 		 * mappings of VMODSORT vnodes.
3316 		 */
3317 		if (hmeblkp->hblk_shared) {
3318 			cpuset_t cpuset = sfmmu_rgntlb_demap(vaddr,
3319 			    sfmmup->sfmmu_srdp->srd_hmergnp[rid], hmeblkp, 1);
3320 			xt_sync(cpuset);
3321 			SFMMU_STAT_ADD(sf_region_remap_demap, 1);
3322 		} else {
3323 			sfmmu_tlb_demap(vaddr, sfmmup, hmeblkp, 0, 0);
3324 			xt_sync(sfmmup->sfmmu_cpusran);
3325 		}
3326 	}
3327 
3328 	if ((flags & SFMMU_NO_TSBLOAD) == 0) {
3329 		/*
3330 		 * We only preload 8K and 4M mappings into the TSB, since
3331 		 * 64K and 512K mappings are replicated and hence don't
3332 		 * have a single, unique TSB entry. Ditto for 32M/256M.
3333 		 */
3334 		if (size == TTE8K || size == TTE4M) {
3335 			sf_scd_t *scdp;
3336 			hatlockp = sfmmu_hat_enter(sfmmup);
3337 			/*
3338 			 * Don't preload private TSB if the mapping is used
3339 			 * by the shctx in the SCD.
3340 			 */
3341 			scdp = sfmmup->sfmmu_scdp;
3342 			if (rid == SFMMU_INVALID_SHMERID || scdp == NULL ||
3343 			    !SF_RGNMAP_TEST(scdp->scd_hmeregion_map, rid)) {
3344 				sfmmu_load_tsb(sfmmup, vaddr, &sfhme->hme_tte,
3345 				    size);
3346 			}
3347 			sfmmu_hat_exit(hatlockp);
3348 		}
3349 	}
3350 	if (pp) {
3351 		if (!remap) {
3352 			HME_ADD(sfhme, pp);
3353 			atomic_inc_16(&hmeblkp->hblk_hmecnt);
3354 			ASSERT(hmeblkp->hblk_hmecnt > 0);
3355 
3356 			/*
3357 			 * Cannot ASSERT(hmeblkp->hblk_hmecnt <= NHMENTS)
3358 			 * see pageunload() for comment.
3359 			 */
3360 		}
3361 		sfmmu_mlist_exit(pml);
3362 	}
3363 
3364 	return (0);
3365 }
3366 /*
3367  * Function unlocks hash bucket.
3368  */
3369 static void
sfmmu_tteload_release_hashbucket(struct hmehash_bucket * hmebp)3370 sfmmu_tteload_release_hashbucket(struct hmehash_bucket *hmebp)
3371 {
3372 	ASSERT(SFMMU_HASH_LOCK_ISHELD(hmebp));
3373 	SFMMU_HASH_UNLOCK(hmebp);
3374 }
3375 
3376 /*
3377  * function which checks and sets up page array for a large
3378  * translation.  Will set p_vcolor, p_index, p_ro fields.
3379  * Assumes addr and pfnum of first page are properly aligned.
3380  * Will check for physical contiguity. If check fails it return
3381  * non null.
3382  */
3383 static int
sfmmu_pagearray_setup(caddr_t addr,page_t ** pps,tte_t * ttep,int remap)3384 sfmmu_pagearray_setup(caddr_t addr, page_t **pps, tte_t *ttep, int remap)
3385 {
3386 	int	i, index, ttesz;
3387 	pfn_t	pfnum;
3388 	pgcnt_t	npgs;
3389 	page_t *pp, *pp1;
3390 	kmutex_t *pmtx;
3391 #ifdef VAC
3392 	int osz;
3393 	int cflags = 0;
3394 	int vac_err = 0;
3395 #endif
3396 	int newidx = 0;
3397 
3398 	ttesz = TTE_CSZ(ttep);
3399 
3400 	ASSERT(ttesz > TTE8K);
3401 
3402 	npgs = TTEPAGES(ttesz);
3403 	index = PAGESZ_TO_INDEX(ttesz);
3404 
3405 	pfnum = (*pps)->p_pagenum;
3406 	ASSERT(IS_P2ALIGNED(pfnum, npgs));
3407 
3408 	/*
3409 	 * Save the first pp so we can do HAT_TMPNC at the end.
3410 	 */
3411 	pp1 = *pps;
3412 #ifdef VAC
3413 	osz = fnd_mapping_sz(pp1);
3414 #endif
3415 
3416 	for (i = 0; i < npgs; i++, pps++) {
3417 		pp = *pps;
3418 		ASSERT(PAGE_LOCKED(pp));
3419 		ASSERT(pp->p_szc >= ttesz);
3420 		ASSERT(pp->p_szc == pp1->p_szc);
3421 		ASSERT(sfmmu_mlist_held(pp));
3422 
3423 		/*
3424 		 * XXX is it possible to maintain P_RO on the root only?
3425 		 */
3426 		if (TTE_IS_WRITABLE(ttep) && PP_ISRO(pp)) {
3427 			pmtx = sfmmu_page_enter(pp);
3428 			PP_CLRRO(pp);
3429