xref: /illumos-gate/usr/src/uts/i86pc/vm/hat_i86.c (revision 10a4fa49f51ed9ae1c857a626de6ce9ebf41661a)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * VM - Hardware Address Translation management for i386 and amd64
30  *
31  * Implementation of the interfaces described in <common/vm/hat.h>
32  *
33  * Nearly all the details of how the hardware is managed should not be
34  * visible outside this layer except for misc. machine specific functions
35  * that work in conjunction with this code.
36  *
37  * Routines used only inside of i86pc/vm start with hati_ for HAT Internal.
38  */
39 
40 #include <sys/machparam.h>
41 #include <sys/machsystm.h>
42 #include <sys/mman.h>
43 #include <sys/types.h>
44 #include <sys/systm.h>
45 #include <sys/cpuvar.h>
46 #include <sys/thread.h>
47 #include <sys/proc.h>
48 #include <sys/cpu.h>
49 #include <sys/kmem.h>
50 #include <sys/disp.h>
51 #include <sys/shm.h>
52 #include <sys/sysmacros.h>
53 #include <sys/machparam.h>
54 #include <sys/vmem.h>
55 #include <sys/vmsystm.h>
56 #include <sys/promif.h>
57 #include <sys/var.h>
58 #include <sys/x86_archext.h>
59 #include <sys/atomic.h>
60 #include <sys/bitmap.h>
61 
62 #include <vm/seg_kmem.h>
63 #include <vm/hat_i86.h>
64 #include <vm/as.h>
65 #include <vm/seg.h>
66 #include <vm/page.h>
67 #include <vm/seg_kp.h>
68 #include <vm/seg_kpm.h>
69 #include <vm/vm_dep.h>
70 
71 #include <sys/cmn_err.h>
72 
73 
74 /*
75  * Basic parameters for hat operation.
76  */
77 struct hat_mmu_info mmu;
78 uint_t force_pae_off = 0;	/* for testing, change with kernel debugger */
79 uint_t force_pae_on = 0;	/* for testing, change with kernel debugger */
80 
81 /*
82  * The page that is the kernel's top level pagetable.
83  *
84  * For 32 bit VLP support, the kernel hat will use the 1st 4 entries
85  * on this 4K page for its top level page table. The remaining groups of
86  * 4 entries are used for per processor copies of user VLP pagetables for
87  * running threads.  See hat_switch() and reload_pae32() for details.
88  *
89  * vlp_page[0] - 0th level==2 PTE for kernel HAT (will be zero)
90  * vlp_page[1] - 1st level==2 PTE for kernel HAT (will be zero)
91  * vlp_page[2] - 2nd level==2 PTE for kernel HAT (zero for small memory)
92  * vlp_page[3] - 3rd level==2 PTE for kernel
93  *
94  * vlp_page[4] - 0th level==2 PTE for user thread on cpu 0
95  * vlp_page[5] - 1st level==2 PTE for user thread on cpu 0
96  * vlp_page[6] - 2nd level==2 PTE for user thread on cpu 0
97  * vlp_page[7] - probably copy of kernel PTE
98  *
99  * vlp_page[8]  - 0th level==2 PTE for user thread on cpu 1
100  * vlp_page[9]  - 1st level==2 PTE for user thread on cpu 1
101  * vlp_page[10] - 2nd level==2 PTE for user thread on cpu 1
102  * vlp_page[11] - probably copy of kernel PTE
103  * ...
104  *
105  * when / where the kernel PTE's are (entry 2 or 3 or none) depends
106  * on kernelbase.
107  */
108 static x86pte_t *vlp_page;
109 
110 /*
111  * forward declaration of internal utility routines
112  */
113 static x86pte_t hati_update_pte(htable_t *ht, uint_t entry, x86pte_t expected,
114 	x86pte_t new);
115 
116 /*
117  * The kernel address space exists in all HATs. To implement this the
118  * kernel reserves a fixed number of entries in every topmost level page
119  * table. The values are setup in hat_init() and then copied to every hat
120  * created by hat_alloc(). This means that kernelbase must be:
121  *
122  *	  4Meg aligned for 32 bit kernels
123  *	512Gig aligned for x86_64 64 bit kernel
124  *
125  * The PAE 32 bit hat is handled as a special case. Otherwise requiring 1Gig
126  * alignment would use too much VA for the kernel.
127  *
128  */
129 static uint_t	khat_start;	/* index of 1st entry in kernel's top ptable */
130 static uint_t	khat_entries;	/* number of entries in kernel's top ptable */
131 
132 #if defined(__i386)
133 
134 static htable_t	*khat_pae32_htable = NULL;
135 static uint_t	khat_pae32_start;
136 static uint_t	khat_pae32_entries;
137 
138 #endif
139 
140 /*
141  * Locks, etc. to control use of the hat reserves when recursively
142  * allocating pagetables for the hat data structures.
143  */
144 static kmutex_t hat_reserves_lock;
145 static kcondvar_t hat_reserves_cv;
146 kthread_t *hat_reserves_thread;
147 uint_t use_boot_reserve = 1;	/* cleared after early boot process */
148 uint_t can_steal_post_boot = 0;	/* set late in boot to enable stealing */
149 
150 /*
151  * A cpuset for all cpus. This is used for kernel address cross calls, since
152  * the kernel addresses apply to all cpus.
153  */
154 cpuset_t khat_cpuset;
155 
156 /*
157  * management stuff for hat structures
158  */
159 kmutex_t	hat_list_lock;
160 kcondvar_t	hat_list_cv;
161 kmem_cache_t	*hat_cache;
162 kmem_cache_t	*hat_hash_cache;
163 kmem_cache_t	*vlp_hash_cache;
164 
165 /*
166  * Simple statistics
167  */
168 struct hatstats hatstat;
169 
170 /*
171  * macros to detect addresses in use by kernel only during boot
172  */
173 #if defined(__amd64)
174 
175 #define	BOOT_VA(va) ((va) < kernelbase ||			\
176 	((va) >= BOOT_DOUBLEMAP_BASE &&				\
177 	(va) < BOOT_DOUBLEMAP_BASE + BOOT_DOUBLEMAP_SIZE))
178 
179 #elif defined(__i386)
180 
181 #define	BOOT_VA(va) ((va) < kernelbase)
182 
183 #endif	/* __i386 */
184 
185 /*
186  * useful stuff for atomic access/clearing/setting REF/MOD/RO bits in page_t's.
187  */
188 extern void atomic_orb(uchar_t *addr, uchar_t val);
189 extern void atomic_andb(uchar_t *addr, uchar_t val);
190 
191 #define	PP_GETRM(pp, rmmask)    (pp->p_nrm & rmmask)
192 #define	PP_ISMOD(pp)		PP_GETRM(pp, P_MOD)
193 #define	PP_ISREF(pp)		PP_GETRM(pp, P_REF)
194 #define	PP_ISRO(pp)		PP_GETRM(pp, P_RO)
195 
196 #define	PP_SETRM(pp, rm)	atomic_orb(&(pp->p_nrm), rm)
197 #define	PP_SETMOD(pp)		PP_SETRM(pp, P_MOD)
198 #define	PP_SETREF(pp)		PP_SETRM(pp, P_REF)
199 #define	PP_SETRO(pp)		PP_SETRM(pp, P_RO)
200 
201 #define	PP_CLRRM(pp, rm)	atomic_andb(&(pp->p_nrm), ~(rm))
202 #define	PP_CLRMOD(pp)   	PP_CLRRM(pp, P_MOD)
203 #define	PP_CLRREF(pp)   	PP_CLRRM(pp, P_REF)
204 #define	PP_CLRRO(pp)    	PP_CLRRM(pp, P_RO)
205 #define	PP_CLRALL(pp)		PP_CLRRM(pp, P_MOD | P_REF | P_RO)
206 
207 /*
208  * some useful tracing macros
209  */
210 
211 int hattrace = 0;
212 #ifdef DEBUG
213 
214 #define	HATIN(r, h, a, l)	\
215 	if (hattrace) prom_printf("->%s hat=%p, adr=%p, len=%lx\n", #r, h, a, l)
216 
217 #define	HATOUT(r, h, a)		\
218 	if (hattrace) prom_printf("<-%s hat=%p, adr=%p\n", #r, h, a)
219 #else
220 
221 #define	HATIN(r, h, a, l)
222 #define	HATOUT(r, h, a)
223 
224 #endif
225 
226 
227 /*
228  * kmem cache constructor for struct hat
229  */
230 /*ARGSUSED*/
231 static int
232 hati_constructor(void *buf, void *handle, int kmflags)
233 {
234 	hat_t	*hat = buf;
235 
236 	mutex_init(&hat->hat_mutex, NULL, MUTEX_DEFAULT, NULL);
237 	bzero(hat->hat_pages_mapped,
238 	    sizeof (pgcnt_t) * (mmu.max_page_level + 1));
239 	hat->hat_stats = 0;
240 	hat->hat_flags = 0;
241 	mutex_init(&hat->hat_switch_mutex, NULL, MUTEX_DRIVER,
242 	    (void *)ipltospl(DISP_LEVEL));
243 	CPUSET_ZERO(hat->hat_cpus);
244 	hat->hat_htable = NULL;
245 	hat->hat_ht_hash = NULL;
246 	return (0);
247 }
248 
249 /*
250  * Allocate a hat structure for as. We also create the top level
251  * htable and initialize it to contain the kernel hat entries.
252  */
253 hat_t *
254 hat_alloc(struct as *as)
255 {
256 	hat_t		*hat;
257 	htable_t	*ht;	/* top level htable */
258 	uint_t		use_vlp;
259 
260 	/*
261 	 * Once we start creating user process HATs we can enable
262 	 * the htable_steal() code.
263 	 */
264 	if (can_steal_post_boot == 0)
265 		can_steal_post_boot = 1;
266 
267 	ASSERT(AS_WRITE_HELD(as, &as->a_lock));
268 	hat = kmem_cache_alloc(hat_cache, KM_SLEEP);
269 	hat->hat_as = as;
270 	mutex_init(&hat->hat_mutex, NULL, MUTEX_DEFAULT, NULL);
271 	ASSERT(hat->hat_flags == 0);
272 
273 	/*
274 	 * a 32 bit process uses a VLP style hat when using PAE
275 	 */
276 #if defined(__amd64)
277 	use_vlp = (ttoproc(curthread)->p_model == DATAMODEL_ILP32);
278 #elif defined(__i386)
279 	use_vlp = mmu.pae_hat;
280 #endif
281 	if (use_vlp) {
282 		hat->hat_flags = HAT_VLP;
283 		bzero(hat->hat_vlp_ptes, VLP_SIZE);
284 	}
285 
286 	/*
287 	 * Allocate the htable hash
288 	 */
289 	if ((hat->hat_flags & HAT_VLP)) {
290 		hat->hat_num_hash = mmu.vlp_hash_cnt;
291 		hat->hat_ht_hash = kmem_cache_alloc(vlp_hash_cache, KM_SLEEP);
292 	} else {
293 		hat->hat_num_hash = mmu.hash_cnt;
294 		hat->hat_ht_hash = kmem_cache_alloc(hat_hash_cache, KM_SLEEP);
295 	}
296 	bzero(hat->hat_ht_hash, hat->hat_num_hash * sizeof (htable_t *));
297 
298 	/*
299 	 * Initialize Kernel HAT entries at the top of the top level page
300 	 * table for the new hat.
301 	 *
302 	 * Note that we don't call htable_release() for the top level, that
303 	 * happens when the hat is destroyed in hat_free_end()
304 	 */
305 	hat->hat_htable = NULL;
306 	hat->hat_ht_cached = NULL;
307 	ht = htable_create(hat, (uintptr_t)0, TOP_LEVEL(hat), NULL);
308 	if (!(hat->hat_flags & HAT_VLP))
309 		x86pte_copy(kas.a_hat->hat_htable, ht, khat_start,
310 		    khat_entries);
311 #if defined(__i386)
312 	else if (khat_entries > 0)
313 		bcopy(vlp_page + khat_start, hat->hat_vlp_ptes + khat_start,
314 		    khat_entries * sizeof (x86pte_t));
315 #endif
316 	hat->hat_htable = ht;
317 
318 #if defined(__i386)
319 	/*
320 	 * PAE32 HAT alignment is less restrictive than the others to keep
321 	 * the kernel from using too much VA. Because of this we may need
322 	 * one layer further down when kernelbase isn't 1Gig aligned.
323 	 * See hat_free_end() for the htable_release() that goes with this
324 	 * htable_create()
325 	 */
326 	if (khat_pae32_htable != NULL) {
327 		ht = htable_create(hat, kernelbase,
328 		    khat_pae32_htable->ht_level, NULL);
329 		x86pte_copy(khat_pae32_htable, ht, khat_pae32_start,
330 		    khat_pae32_entries);
331 		ht->ht_valid_cnt = khat_pae32_entries;
332 	}
333 #endif
334 
335 	/*
336 	 * Put it at the start of the global list of all hats (used by stealing)
337 	 *
338 	 * kas.a_hat is not in the list but is instead used to find the
339 	 * first and last items in the list.
340 	 *
341 	 * - kas.a_hat->hat_next points to the start of the user hats.
342 	 *   The list ends where hat->hat_next == NULL
343 	 *
344 	 * - kas.a_hat->hat_prev points to the last of the user hats.
345 	 *   The list begins where hat->hat_prev == NULL
346 	 */
347 	mutex_enter(&hat_list_lock);
348 	hat->hat_prev = NULL;
349 	hat->hat_next = kas.a_hat->hat_next;
350 	if (hat->hat_next)
351 		hat->hat_next->hat_prev = hat;
352 	else
353 		kas.a_hat->hat_prev = hat;
354 	kas.a_hat->hat_next = hat;
355 	mutex_exit(&hat_list_lock);
356 
357 	return (hat);
358 }
359 
360 /*
361  * process has finished executing but as has not been cleaned up yet.
362  */
363 /*ARGSUSED*/
364 void
365 hat_free_start(hat_t *hat)
366 {
367 	ASSERT(AS_WRITE_HELD(hat->hat_as, &hat->hat_as->a_lock));
368 
369 	/*
370 	 * If the hat is currently a stealing victim, wait for the stealing
371 	 * to finish.  Once we mark it as HAT_FREEING, htable_steal()
372 	 * won't look at its pagetables anymore.
373 	 */
374 	mutex_enter(&hat_list_lock);
375 	while (hat->hat_flags & HAT_VICTIM)
376 		cv_wait(&hat_list_cv, &hat_list_lock);
377 	hat->hat_flags |= HAT_FREEING;
378 	mutex_exit(&hat_list_lock);
379 }
380 
381 /*
382  * An address space is being destroyed, so we destroy the associated hat.
383  */
384 void
385 hat_free_end(hat_t *hat)
386 {
387 	int i;
388 	kmem_cache_t *cache;
389 
390 #ifdef DEBUG
391 	for (i = 0; i <= mmu.max_page_level; i++)
392 		ASSERT(hat->hat_pages_mapped[i] == 0);
393 #endif
394 	ASSERT(hat->hat_flags & HAT_FREEING);
395 
396 	/*
397 	 * must not be running on the given hat
398 	 */
399 	ASSERT(CPU->cpu_current_hat != hat);
400 
401 	/*
402 	 * Remove it from the list of HATs
403 	 */
404 	mutex_enter(&hat_list_lock);
405 	if (hat->hat_prev)
406 		hat->hat_prev->hat_next = hat->hat_next;
407 	else
408 		kas.a_hat->hat_next = hat->hat_next;
409 	if (hat->hat_next)
410 		hat->hat_next->hat_prev = hat->hat_prev;
411 	else
412 		kas.a_hat->hat_prev = hat->hat_prev;
413 	mutex_exit(&hat_list_lock);
414 	hat->hat_next = hat->hat_prev = NULL;
415 
416 	/*
417 	 * Make a pass through the htables freeing them all up.
418 	 */
419 	htable_purge_hat(hat);
420 
421 	/*
422 	 * Decide which kmem cache the hash table came from, then free it.
423 	 */
424 	if (hat->hat_flags & HAT_VLP)
425 		cache = vlp_hash_cache;
426 	else
427 		cache = hat_hash_cache;
428 	kmem_cache_free(cache, hat->hat_ht_hash);
429 	hat->hat_ht_hash = NULL;
430 
431 	hat->hat_flags = 0;
432 	kmem_cache_free(hat_cache, hat);
433 }
434 
435 /*
436  * round kernelbase down to a supported value to use for _userlimit
437  *
438  * userlimit must be aligned down to an entry in the top level htable.
439  * The one exception is for 32 bit HAT's running PAE.
440  */
441 uintptr_t
442 hat_kernelbase(uintptr_t va)
443 {
444 #if defined(__i386)
445 	va &= LEVEL_MASK(1);
446 #endif
447 	if (IN_VA_HOLE(va))
448 		panic("_userlimit %p will fall in VA hole\n", (void *)va);
449 	return (va);
450 }
451 
452 /*
453  * Initialize hat data structures based on processor MMU information.
454  */
455 void
456 mmu_init(void)
457 {
458 	uint_t max_htables;
459 	uint_t pa_bits;
460 	uint_t va_bits;
461 	int i;
462 
463 	/*
464 	 * if CPU enabled the page table global bit, use it for the kernel
465 	 * This is bit 7 in CR4 (PGE - Page Global Enable)
466 	 */
467 	if ((x86_feature & X86_PGE) != 0 && (getcr4() & 0x80) != 0)
468 		mmu.pt_global = PT_GLOBAL;
469 
470 	/*
471 	 * We use PAE except when we aren't on an AMD64 and this is
472 	 * a 32 bit kernel with all physical addresses less than 4 Gig.
473 	 */
474 	mmu.pae_hat = 1;
475 	if (x86_feature & X86_NX) {
476 		mmu.pt_nx = PT_NX;
477 	} else {
478 		mmu.pt_nx = 0;
479 #if defined(__i386)
480 		if (!PFN_ABOVE4G(physmax))
481 			mmu.pae_hat = 0;
482 #endif
483 	}
484 
485 #if defined(__i386)
486 	/*
487 	 * Setting one of these two lets you force testing of the different
488 	 * hat modes for 32 bit, regardless of the hardware setup.
489 	 */
490 	if (force_pae_on) {
491 		mmu.pae_hat = 1;
492 	} else if (force_pae_off) {
493 		mmu.pae_hat = 0;
494 		mmu.pt_nx = 0;
495 	}
496 #endif
497 
498 	/*
499 	 * Use CPU info to set various MMU parameters
500 	 */
501 	cpuid_get_addrsize(CPU, &pa_bits, &va_bits);
502 
503 	if (va_bits < sizeof (void *) * NBBY) {
504 		mmu.hole_start = (1ul << (va_bits - 1));
505 		mmu.hole_end = 0ul - mmu.hole_start - 1;
506 	} else {
507 		mmu.hole_end = 0;
508 		mmu.hole_start = mmu.hole_end - 1;
509 	}
510 #if defined(OPTERON_ERRATUM_121)
511 	/*
512 	 * If erratum 121 has already been detected at this time, hole_start
513 	 * contains the value to be subtracted from mmu.hole_start.
514 	 */
515 	ASSERT(hole_start == 0 || opteron_erratum_121 != 0);
516 	hole_start = mmu.hole_start - hole_start;
517 #else
518 	hole_start = mmu.hole_start;
519 #endif
520 	hole_end = mmu.hole_end;
521 
522 	mmu.highest_pfn = mmu_btop((1ull << pa_bits) - 1);
523 	if (mmu.pae_hat == 0 && pa_bits > 32)
524 		mmu.highest_pfn = PFN_4G - 1;
525 
526 	if (mmu.pae_hat) {
527 		mmu.pte_size = 8;	/* 8 byte PTEs */
528 		mmu.pte_size_shift = 3;
529 	} else {
530 		mmu.pte_size = 4;	/* 4 byte PTEs */
531 		mmu.pte_size_shift = 2;
532 	}
533 
534 	if (mmu.pae_hat && (x86_feature & X86_PAE) == 0)
535 		panic("Processor does not support PAE");
536 
537 	if ((x86_feature & X86_CX8) == 0)
538 		panic("Processor does not support cmpxchg8b instruction");
539 
540 	/*
541 	 * Initialize parameters based on the 64 or 32 bit kernels and
542 	 * for the 32 bit kernel decide if we should use PAE.
543 	 */
544 	if (x86_feature & X86_LARGEPAGE)
545 		mmu.max_page_level = 1;
546 	else
547 		mmu.max_page_level = 0;
548 	mmu_page_sizes = mmu.max_page_level + 1;
549 	mmu_exported_page_sizes = mmu_page_sizes;
550 
551 #if defined(__amd64)
552 
553 	mmu.num_level = 4;
554 	mmu.max_level = 3;
555 	mmu.ptes_per_table = 512;
556 	mmu.top_level_count = 512;
557 
558 	mmu.level_shift[0] = 12;
559 	mmu.level_shift[1] = 21;
560 	mmu.level_shift[2] = 30;
561 	mmu.level_shift[3] = 39;
562 
563 #elif defined(__i386)
564 
565 	if (mmu.pae_hat) {
566 		mmu.num_level = 3;
567 		mmu.max_level = 2;
568 		mmu.ptes_per_table = 512;
569 		mmu.top_level_count = 4;
570 
571 		mmu.level_shift[0] = 12;
572 		mmu.level_shift[1] = 21;
573 		mmu.level_shift[2] = 30;
574 
575 	} else {
576 		mmu.num_level = 2;
577 		mmu.max_level = 1;
578 		mmu.ptes_per_table = 1024;
579 		mmu.top_level_count = 1024;
580 
581 		mmu.level_shift[0] = 12;
582 		mmu.level_shift[1] = 22;
583 	}
584 
585 #endif	/* __i386 */
586 
587 	for (i = 0; i < mmu.num_level; ++i) {
588 		mmu.level_size[i] = 1UL << mmu.level_shift[i];
589 		mmu.level_offset[i] = mmu.level_size[i] - 1;
590 		mmu.level_mask[i] = ~mmu.level_offset[i];
591 	}
592 
593 	mmu.pte_bits[0] = PT_VALID;
594 	for (i = 1; i <= mmu.max_page_level; ++i)
595 		mmu.pte_bits[i] = PT_VALID | PT_PAGESIZE;
596 
597 	/*
598 	 * NOTE Legacy 32 bit PAE mode only has the P_VALID bit at top level.
599 	 */
600 	for (i = 1; i < mmu.num_level; ++i)
601 		mmu.ptp_bits[i] = PT_PTPBITS;
602 #if defined(__i386)
603 	mmu.ptp_bits[2] = PT_VALID;
604 #endif
605 
606 	/*
607 	 * Compute how many hash table entries to have per process for htables.
608 	 * We start with 1 page's worth of entries.
609 	 *
610 	 * If physical memory is small, reduce the amount need to cover it.
611 	 */
612 	max_htables = physmax / mmu.ptes_per_table;
613 	mmu.hash_cnt = MMU_PAGESIZE / sizeof (htable_t *);
614 	while (mmu.hash_cnt > 16 && mmu.hash_cnt >= max_htables)
615 		mmu.hash_cnt >>= 1;
616 	mmu.vlp_hash_cnt = mmu.hash_cnt;
617 
618 #if defined(__amd64)
619 	/*
620 	 * If running in 64 bits and physical memory is large,
621 	 * increase the size of the cache to cover all of memory for
622 	 * a 64 bit process.
623 	 */
624 #define	HASH_MAX_LENGTH 4
625 	while (mmu.hash_cnt * HASH_MAX_LENGTH < max_htables)
626 		mmu.hash_cnt <<= 1;
627 #endif
628 
629 	/*
630 	 * This code knows that there are only 2 pagesizes.
631 	 * We ignore 4MB (non-PAE) for now. The value is only used
632 	 * for optimizing demaps across large ranges.
633 	 * These return zero if no information is known.
634 	 */
635 	mmu.tlb_entries[0] = cpuid_get_dtlb_nent(NULL, MMU_PAGESIZE);
636 	mmu.tlb_entries[1] = cpuid_get_dtlb_nent(NULL, 2 * 1024 * 1024);
637 }
638 
639 
640 /*
641  * initialize hat data structures
642  */
643 void
644 hat_init()
645 {
646 #if defined(__i386)
647 	/*
648 	 * _userlimit must be aligned correctly
649 	 */
650 	if ((_userlimit & LEVEL_MASK(1)) != _userlimit) {
651 		prom_printf("hat_init(): _userlimit=%p, not aligned at %p\n",
652 		    (void *)_userlimit, (void *)LEVEL_SIZE(1));
653 		halt("hat_init(): Unable to continue");
654 	}
655 #endif
656 
657 	cv_init(&hat_list_cv, NULL, CV_DEFAULT, NULL);
658 
659 	/*
660 	 * initialize kmem caches
661 	 */
662 	htable_init();
663 	hment_init();
664 
665 	hat_cache = kmem_cache_create("hat_t",
666 	    sizeof (hat_t), 0, hati_constructor, NULL, NULL,
667 	    NULL, 0, 0);
668 
669 	hat_hash_cache = kmem_cache_create("HatHash",
670 	    mmu.hash_cnt * sizeof (htable_t *), 0, NULL, NULL, NULL,
671 	    NULL, 0, 0);
672 
673 	/*
674 	 * VLP hats can use a smaller hash table size on large memroy machines
675 	 */
676 	if (mmu.hash_cnt == mmu.vlp_hash_cnt) {
677 		vlp_hash_cache = hat_hash_cache;
678 	} else {
679 		vlp_hash_cache = kmem_cache_create("HatVlpHash",
680 		    mmu.vlp_hash_cnt * sizeof (htable_t *), 0, NULL, NULL, NULL,
681 		    NULL, 0, 0);
682 	}
683 
684 	/*
685 	 * Set up the kernel's hat
686 	 */
687 	AS_LOCK_ENTER(&kas, &kas.a_lock, RW_WRITER);
688 	kas.a_hat = kmem_cache_alloc(hat_cache, KM_NOSLEEP);
689 	mutex_init(&kas.a_hat->hat_mutex, NULL, MUTEX_DEFAULT, NULL);
690 	kas.a_hat->hat_as = &kas;
691 	kas.a_hat->hat_flags = 0;
692 	AS_LOCK_EXIT(&kas, &kas.a_lock);
693 
694 	CPUSET_ZERO(khat_cpuset);
695 	CPUSET_ADD(khat_cpuset, CPU->cpu_id);
696 
697 	/*
698 	 * The kernel hat's next pointer serves as the head of the hat list .
699 	 * The kernel hat's prev pointer tracks the last hat on the list for
700 	 * htable_steal() to use.
701 	 */
702 	kas.a_hat->hat_next = NULL;
703 	kas.a_hat->hat_prev = NULL;
704 
705 	/*
706 	 * Allocate an htable hash bucket for the kernel
707 	 * XX64 - tune for 64 bit procs
708 	 */
709 	kas.a_hat->hat_num_hash = mmu.hash_cnt;
710 	kas.a_hat->hat_ht_hash = kmem_cache_alloc(hat_hash_cache, KM_NOSLEEP);
711 	bzero(kas.a_hat->hat_ht_hash, mmu.hash_cnt * sizeof (htable_t *));
712 
713 	/*
714 	 * zero out the top level and cached htable pointers
715 	 */
716 	kas.a_hat->hat_ht_cached = NULL;
717 	kas.a_hat->hat_htable = NULL;
718 }
719 
720 /*
721  * Prepare CPU specific pagetables for VLP processes on 64 bit kernels.
722  *
723  * Each CPU has a set of 2 pagetables that are reused for any 32 bit
724  * process it runs. They are the top level pagetable, hci_vlp_l3ptes, and
725  * the next to top level table for the bottom 512 Gig, hci_vlp_l2ptes.
726  */
727 /*ARGSUSED*/
728 static void
729 hat_vlp_setup(struct cpu *cpu)
730 {
731 #if defined(__amd64)
732 	struct hat_cpu_info *hci = cpu->cpu_hat_info;
733 	pfn_t pfn;
734 
735 	/*
736 	 * allocate the level==2 page table for the bottom most
737 	 * 512Gig of address space (this is where 32 bit apps live)
738 	 */
739 	ASSERT(hci != NULL);
740 	hci->hci_vlp_l2ptes = kmem_zalloc(MMU_PAGESIZE, KM_SLEEP);
741 
742 	/*
743 	 * Allocate a top level pagetable and copy the kernel's
744 	 * entries into it. Then link in hci_vlp_l2ptes in the 1st entry.
745 	 */
746 	hci->hci_vlp_l3ptes = kmem_zalloc(MMU_PAGESIZE, KM_SLEEP);
747 	hci->hci_vlp_pfn =
748 	    hat_getpfnum(kas.a_hat, (caddr_t)hci->hci_vlp_l3ptes);
749 	ASSERT(hci->hci_vlp_pfn != PFN_INVALID);
750 	bcopy(vlp_page + khat_start, hci->hci_vlp_l3ptes + khat_start,
751 	    khat_entries * sizeof (x86pte_t));
752 
753 	pfn = hat_getpfnum(kas.a_hat, (caddr_t)hci->hci_vlp_l2ptes);
754 	ASSERT(pfn != PFN_INVALID);
755 	hci->hci_vlp_l3ptes[0] = MAKEPTP(pfn, 2);
756 #endif /* __amd64 */
757 }
758 
759 /*
760  * Finish filling in the kernel hat.
761  * Pre fill in all top level kernel page table entries for the kernel's
762  * part of the address range.  From this point on we can't use any new
763  * kernel large pages if they need PTE's at max_level
764  */
765 void
766 hat_init_finish(void)
767 {
768 	htable_t	*top = kas.a_hat->hat_htable;
769 	htable_t	*ht;
770 	uint_t		e;
771 	x86pte_t	pte;
772 	uintptr_t	va = kernelbase;
773 
774 
775 #if defined(__i386)
776 	ASSERT((va & LEVEL_MASK(1)) == va);
777 
778 	/*
779 	 * Deal with kernelbase not 1Gig aligned for 32 bit PAE hats.
780 	 */
781 	if (!mmu.pae_hat || (va & LEVEL_OFFSET(mmu.max_level)) == 0) {
782 		khat_pae32_htable = NULL;
783 	} else {
784 		ASSERT(mmu.max_level == 2);
785 		ASSERT((va & LEVEL_OFFSET(mmu.max_level - 1)) == 0);
786 		khat_pae32_htable =
787 		    htable_create(kas.a_hat, va, mmu.max_level - 1, NULL);
788 		khat_pae32_start = htable_va2entry(va, khat_pae32_htable);
789 		khat_pae32_entries = mmu.ptes_per_table - khat_pae32_start;
790 		for (e = khat_pae32_start; e < mmu.ptes_per_table;
791 		    ++e, va += LEVEL_SIZE(mmu.max_level - 1)) {
792 			pte = x86pte_get(khat_pae32_htable, e);
793 			if (PTE_ISVALID(pte))
794 				continue;
795 			ht = htable_create(kas.a_hat, va, mmu.max_level - 2,
796 			    NULL);
797 			ASSERT(ht != NULL);
798 		}
799 	}
800 #endif
801 
802 	/*
803 	 * The kernel hat will need fixed values in the highest level
804 	 * ptable for copying to all other hat's. This implies
805 	 * alignment restrictions on _userlimit.
806 	 *
807 	 * Note we don't htable_release() these htables. This keeps them
808 	 * from ever being stolen or free'd.
809 	 *
810 	 * top_level_count is used instead of ptes_per_table, since
811 	 * on 32-bit PAE we only have 4 usable entries at the top level ptable.
812 	 */
813 	if (va == 0)
814 		khat_start = mmu.top_level_count;
815 	else
816 		khat_start = htable_va2entry(va, kas.a_hat->hat_htable);
817 	khat_entries = mmu.top_level_count - khat_start;
818 	for (e = khat_start; e < mmu.top_level_count;
819 	    ++e, va += LEVEL_SIZE(mmu.max_level)) {
820 		pte = x86pte_get(top, e);
821 		if (PTE_ISVALID(pte))
822 			continue;
823 		ht = htable_create(kas.a_hat, va, mmu.max_level - 1, NULL);
824 		ASSERT(ht != NULL);
825 	}
826 
827 	/*
828 	 * We are now effectively running on the kernel hat.
829 	 * Clearing use_boot_reserve shuts off using the pre-allocated boot
830 	 * reserve for all HAT allocations.  From here on, the reserves are
831 	 * only used when mapping in memory for the hat's own allocations.
832 	 */
833 	use_boot_reserve = 0;
834 	htable_adjust_reserve();
835 
836 	/*
837 	 * 32 bit kernels use only 4 of the 512 entries in its top level
838 	 * pagetable. We'll use the remainder for the "per CPU" page tables
839 	 * for VLP processes.
840 	 *
841 	 * We map the top level kernel pagetable into the kernel's AS to make
842 	 * it easy to use bcopy for kernel entry PTEs.
843 	 *
844 	 * We were guaranteed to get a physical address < 4Gig, since the 32 bit
845 	 * boot loader uses non-PAE page tables.
846 	 */
847 	if (mmu.pae_hat) {
848 		vlp_page = vmem_alloc(heap_arena, MMU_PAGESIZE, VM_SLEEP);
849 		hat_devload(kas.a_hat, (caddr_t)vlp_page, MMU_PAGESIZE,
850 		    kas.a_hat->hat_htable->ht_pfn,
851 		    PROT_READ | PROT_WRITE | HAT_NOSYNC | HAT_UNORDERED_OK,
852 		    HAT_LOAD | HAT_LOAD_NOCONSIST);
853 	}
854 	hat_vlp_setup(CPU);
855 }
856 
857 /*
858  * On 32 bit PAE mode, PTE's are 64 bits, but ordinary atomic memory references
859  * are 32 bit, so for safety we must use cas64() to install these.
860  */
861 #ifdef __i386
862 static void
863 reload_pae32(hat_t *hat, cpu_t *cpu)
864 {
865 	x86pte_t *src;
866 	x86pte_t *dest;
867 	x86pte_t pte;
868 	int i;
869 
870 	/*
871 	 * Load the 4 entries of the level 2 page table into this
872 	 * cpu's range of the vlp_page and point cr3 at them.
873 	 */
874 	ASSERT(mmu.pae_hat);
875 	src = hat->hat_vlp_ptes;
876 	dest = vlp_page + (cpu->cpu_id + 1) * VLP_NUM_PTES;
877 	for (i = 0; i < VLP_NUM_PTES; ++i) {
878 		for (;;) {
879 			pte = dest[i];
880 			if (pte == src[i])
881 				break;
882 			if (cas64(dest + i, pte, src[i]) != src[i])
883 				break;
884 		}
885 	}
886 }
887 #endif
888 
889 /*
890  * Switch to a new active hat, maintaining bit masks to track active CPUs.
891  */
892 void
893 hat_switch(hat_t *hat)
894 {
895 	uintptr_t	newcr3;
896 	cpu_t		*cpu = CPU;
897 	hat_t		*old = cpu->cpu_current_hat;
898 
899 	/*
900 	 * set up this information first, so we don't miss any cross calls
901 	 */
902 	if (old != NULL) {
903 		if (old == hat)
904 			return;
905 		if (old != kas.a_hat)
906 			CPUSET_ATOMIC_DEL(old->hat_cpus, cpu->cpu_id);
907 	}
908 
909 	/*
910 	 * Wait for any in flight pagetable invalidates on this hat to finish.
911 	 * This is a spin lock at DISP_LEVEL
912 	 */
913 	if (hat != kas.a_hat) {
914 		mutex_enter(&hat->hat_switch_mutex);
915 		CPUSET_ATOMIC_ADD(hat->hat_cpus, cpu->cpu_id);
916 		mutex_exit(&hat->hat_switch_mutex);
917 	}
918 	cpu->cpu_current_hat = hat;
919 
920 	/*
921 	 * now go ahead and load cr3
922 	 */
923 	if (hat->hat_flags & HAT_VLP) {
924 #if defined(__amd64)
925 		x86pte_t *vlpptep = cpu->cpu_hat_info->hci_vlp_l2ptes;
926 
927 		VLP_COPY(hat->hat_vlp_ptes, vlpptep);
928 		newcr3 = MAKECR3(cpu->cpu_hat_info->hci_vlp_pfn);
929 #elif defined(__i386)
930 		reload_pae32(hat, cpu);
931 		newcr3 = MAKECR3(kas.a_hat->hat_htable->ht_pfn) +
932 		    (cpu->cpu_id + 1) * VLP_SIZE;
933 #endif
934 	} else {
935 		newcr3 = MAKECR3(hat->hat_htable->ht_pfn);
936 	}
937 	setcr3(newcr3);
938 	ASSERT(cpu == CPU);
939 }
940 
941 /*
942  * Utility to return a valid x86pte_t from protections, pfn, and level number
943  */
944 static x86pte_t
945 hati_mkpte(pfn_t pfn, uint_t attr, level_t level, uint_t flags)
946 {
947 	x86pte_t	pte;
948 	uint_t		cache_attr = attr & HAT_ORDER_MASK;
949 
950 	pte = MAKEPTE(pfn, level);
951 
952 	if (attr & PROT_WRITE)
953 		PTE_SET(pte, PT_WRITABLE);
954 
955 	if (attr & PROT_USER)
956 		PTE_SET(pte, PT_USER);
957 
958 	if (!(attr & PROT_EXEC))
959 		PTE_SET(pte, mmu.pt_nx);
960 
961 	/*
962 	 * set the software bits used track ref/mod sync's and hments
963 	 */
964 	if (attr & HAT_NOSYNC)
965 		PTE_SET(pte, PT_NOSYNC);
966 	if (flags & HAT_LOAD_NOCONSIST)
967 		PTE_SET(pte, PT_NOCONSIST | PT_NOSYNC);
968 
969 	/*
970 	 * Set the caching attributes in the PTE. The combination
971 	 * of attributes are poorly defined, so we pay attention
972 	 * to them in the given order.
973 	 *
974 	 * The test for HAT_STRICTORDER is different because it's defined
975 	 * as "0" - which was a stupid thing to do, but is too late to change!
976 	 */
977 	if (cache_attr == HAT_STRICTORDER) {
978 		PTE_SET(pte, PT_NOCACHE);
979 	/*LINTED [Lint hates empty ifs, but it's the obvious way to do this] */
980 	} else if (cache_attr & (HAT_UNORDERED_OK | HAT_STORECACHING_OK)) {
981 		/* nothing to set */;
982 	} else if (cache_attr & (HAT_MERGING_OK | HAT_LOADCACHING_OK)) {
983 		PTE_SET(pte, PT_NOCACHE);
984 		if (x86_feature & X86_PAT)
985 			PTE_SET(pte, (level == 0) ? PT_PAT_4K : PT_PAT_LARGE);
986 		else
987 			PTE_SET(pte, PT_WRITETHRU);
988 	} else {
989 		panic("hati_mkpte(): bad caching attributes: %x\n", cache_attr);
990 	}
991 
992 	return (pte);
993 }
994 
995 /*
996  * Duplicate address translations of the parent to the child.
997  * This function really isn't used anymore.
998  */
999 /*ARGSUSED*/
1000 int
1001 hat_dup(hat_t *old, hat_t *new, caddr_t addr, size_t len, uint_t flag)
1002 {
1003 	ASSERT((uintptr_t)addr < kernelbase);
1004 	ASSERT(new != kas.a_hat);
1005 	ASSERT(old != kas.a_hat);
1006 	return (0);
1007 }
1008 
1009 /*
1010  * Allocate any hat resources required for a process being swapped in.
1011  */
1012 /*ARGSUSED*/
1013 void
1014 hat_swapin(hat_t *hat)
1015 {
1016 	/* do nothing - we let everything fault back in */
1017 }
1018 
1019 /*
1020  * Unload all translations associated with an address space of a process
1021  * that is being swapped out.
1022  */
1023 void
1024 hat_swapout(hat_t *hat)
1025 {
1026 	uintptr_t	vaddr = (uintptr_t)0;
1027 	uintptr_t	eaddr = _userlimit;
1028 	htable_t	*ht = NULL;
1029 	level_t		l;
1030 
1031 	/*
1032 	 * We can't just call hat_unload(hat, 0, _userlimit...)  here, because
1033 	 * seg_spt and shared pagetables can't be swapped out.
1034 	 * Take a look at segspt_shmswapout() - it's a big no-op.
1035 	 *
1036 	 * Instead we'll walk through all the address space and unload
1037 	 * any mappings which we are sure are not shared, not locked.
1038 	 */
1039 	ASSERT(IS_PAGEALIGNED(vaddr));
1040 	ASSERT(IS_PAGEALIGNED(eaddr));
1041 	ASSERT(AS_LOCK_HELD(hat->hat_as, &hat->hat_as->a_lock));
1042 	if ((uintptr_t)hat->hat_as->a_userlimit < eaddr)
1043 		eaddr = (uintptr_t)hat->hat_as->a_userlimit;
1044 
1045 	while (vaddr < eaddr) {
1046 		(void) htable_walk(hat, &ht, &vaddr, eaddr);
1047 		if (ht == NULL)
1048 			break;
1049 
1050 		ASSERT(!IN_VA_HOLE(vaddr));
1051 
1052 		/*
1053 		 * If the page table is shared skip its entire range.
1054 		 * This code knows that only level 0 page tables are shared
1055 		 */
1056 		l = ht->ht_level;
1057 		if (ht->ht_flags & HTABLE_SHARED_PFN) {
1058 			ASSERT(l == 0);
1059 			vaddr = ht->ht_vaddr + LEVEL_SIZE(1);
1060 			htable_release(ht);
1061 			ht = NULL;
1062 			continue;
1063 		}
1064 
1065 		/*
1066 		 * If the page table has no locked entries, unload this one.
1067 		 */
1068 		if (ht->ht_lock_cnt == 0)
1069 			hat_unload(hat, (caddr_t)vaddr, LEVEL_SIZE(l),
1070 			    HAT_UNLOAD_UNMAP);
1071 
1072 		/*
1073 		 * If we have a level 0 page table with locked entries,
1074 		 * skip the entire page table, otherwise skip just one entry.
1075 		 */
1076 		if (ht->ht_lock_cnt > 0 && l == 0)
1077 			vaddr = ht->ht_vaddr + LEVEL_SIZE(1);
1078 		else
1079 			vaddr += LEVEL_SIZE(l);
1080 	}
1081 	if (ht)
1082 		htable_release(ht);
1083 
1084 	/*
1085 	 * We're in swapout because the system is low on memory, so
1086 	 * go back and flush all the htables off the cached list.
1087 	 */
1088 	htable_purge_hat(hat);
1089 }
1090 
1091 /*
1092  * returns number of bytes that have valid mappings in hat.
1093  */
1094 size_t
1095 hat_get_mapped_size(hat_t *hat)
1096 {
1097 	size_t total = 0;
1098 	int l;
1099 
1100 	for (l = 0; l <= mmu.max_page_level; l++)
1101 		total += (hat->hat_pages_mapped[l] << LEVEL_SHIFT(l));
1102 
1103 	return (total);
1104 }
1105 
1106 /*
1107  * enable/disable collection of stats for hat.
1108  */
1109 int
1110 hat_stats_enable(hat_t *hat)
1111 {
1112 	atomic_add_32(&hat->hat_stats, 1);
1113 	return (1);
1114 }
1115 
1116 void
1117 hat_stats_disable(hat_t *hat)
1118 {
1119 	atomic_add_32(&hat->hat_stats, -1);
1120 }
1121 
1122 /*
1123  * Utility to sync the ref/mod bits from a page table entry to the page_t
1124  * We must be holding the mapping list lock when this is called.
1125  */
1126 static void
1127 hati_sync_pte_to_page(page_t *pp, x86pte_t pte, level_t level)
1128 {
1129 	uint_t	rm = 0;
1130 	pgcnt_t	pgcnt;
1131 
1132 	if (PTE_GET(pte, PT_NOSYNC))
1133 		return;
1134 
1135 	if (PTE_GET(pte, PT_REF))
1136 		rm |= P_REF;
1137 
1138 	if (PTE_GET(pte, PT_MOD))
1139 		rm |= P_MOD;
1140 
1141 	if (rm == 0)
1142 		return;
1143 
1144 	/*
1145 	 * sync to all constituent pages of a large page
1146 	 */
1147 	ASSERT(x86_hm_held(pp));
1148 	pgcnt = page_get_pagecnt(level);
1149 	ASSERT(IS_P2ALIGNED(pp->p_pagenum, pgcnt));
1150 	for (; pgcnt > 0; --pgcnt) {
1151 		/*
1152 		 * hat_page_demote() can't decrease
1153 		 * pszc below this mapping size
1154 		 * since this large mapping existed after we
1155 		 * took mlist lock.
1156 		 */
1157 		ASSERT(pp->p_szc >= level);
1158 		hat_page_setattr(pp, rm);
1159 		++pp;
1160 	}
1161 }
1162 
1163 /*
1164  * This the set of PTE bits for PFN, permissions and caching
1165  * that require a TLB flush (hat_demap) if changed on a HAT_LOAD_REMAP
1166  */
1167 #define	PT_REMAP_BITS							\
1168 	(PT_PADDR | PT_NX | PT_WRITABLE | PT_WRITETHRU |		\
1169 	PT_NOCACHE | PT_PAT_4K | PT_PAT_LARGE)
1170 
1171 #define	REMAPASSERT(EX)	if (!(EX)) panic("hati_pte_map: " #EX)
1172 /*
1173  * Do the low-level work to get a mapping entered into a HAT's pagetables
1174  * and in the mapping list of the associated page_t.
1175  */
1176 static void
1177 hati_pte_map(
1178 	htable_t	*ht,
1179 	uint_t		entry,
1180 	page_t		*pp,
1181 	x86pte_t	pte,
1182 	int		flags,
1183 	void		*pte_ptr)
1184 {
1185 	hat_t		*hat = ht->ht_hat;
1186 	x86pte_t	old_pte;
1187 	level_t		l = ht->ht_level;
1188 	hment_t		*hm;
1189 	uint_t		is_consist;
1190 
1191 	/*
1192 	 * Is this a consistant (ie. need mapping list lock) mapping?
1193 	 */
1194 	is_consist = (pp != NULL && (flags & HAT_LOAD_NOCONSIST) == 0);
1195 
1196 	/*
1197 	 * Track locked mapping count in the htable.  Do this first,
1198 	 * as we track locking even if there already is a mapping present.
1199 	 */
1200 	if ((flags & HAT_LOAD_LOCK) != 0 && hat != kas.a_hat)
1201 		HTABLE_LOCK_INC(ht);
1202 
1203 	/*
1204 	 * Acquire the page's mapping list lock and get an hment to use.
1205 	 * Note that hment_prepare() might return NULL.
1206 	 */
1207 	if (is_consist) {
1208 		x86_hm_enter(pp);
1209 		hm = hment_prepare(ht, entry, pp);
1210 	}
1211 
1212 	/*
1213 	 * Set the new pte, retrieving the old one at the same time.
1214 	 */
1215 	old_pte = x86pte_set(ht, entry, pte, pte_ptr);
1216 
1217 	/*
1218 	 * If the mapping didn't change there is nothing more to do.
1219 	 */
1220 	if (PTE_EQUIV(pte, old_pte)) {
1221 		if (is_consist) {
1222 			x86_hm_exit(pp);
1223 			if (hm != NULL)
1224 				hment_free(hm);
1225 		}
1226 		return;
1227 	}
1228 
1229 	/*
1230 	 * Install a new mapping in the page's mapping list
1231 	 */
1232 	if (!PTE_ISVALID(old_pte)) {
1233 		if (is_consist) {
1234 			hment_assign(ht, entry, pp, hm);
1235 			x86_hm_exit(pp);
1236 		} else {
1237 			ASSERT(flags & HAT_LOAD_NOCONSIST);
1238 		}
1239 		HTABLE_INC(ht->ht_valid_cnt);
1240 		PGCNT_INC(hat, l);
1241 		return;
1242 	}
1243 
1244 	/*
1245 	 * Remap's are more complicated:
1246 	 *  - HAT_LOAD_REMAP must be specified if changing the pfn.
1247 	 *    We also require that NOCONSIST be specified.
1248 	 *  - Otherwise only permission or caching bits may change.
1249 	 */
1250 	if (!PTE_ISPAGE(old_pte, l))
1251 		panic("non-null/page mapping pte=" FMT_PTE, old_pte);
1252 
1253 	if (PTE2PFN(old_pte, l) != PTE2PFN(pte, l)) {
1254 		REMAPASSERT(flags & HAT_LOAD_REMAP);
1255 		REMAPASSERT(flags & HAT_LOAD_NOCONSIST);
1256 		REMAPASSERT(PTE_GET(old_pte, PT_NOCONSIST));
1257 		REMAPASSERT(pf_is_memory(PTE2PFN(old_pte, l)) ==
1258 		    pf_is_memory(PTE2PFN(pte, l)));
1259 		REMAPASSERT(!is_consist);
1260 	}
1261 
1262 	/*
1263 	 * We only let remaps change the bits for PFNs, permissions
1264 	 * or caching type.
1265 	 */
1266 	ASSERT(PTE_GET(old_pte, ~(PT_REMAP_BITS | PT_REF | PT_MOD)) ==
1267 	    PTE_GET(pte, ~PT_REMAP_BITS));
1268 
1269 	/*
1270 	 * A remap requires invalidating the TLBs, since remapping the
1271 	 * same PFN requires NOCONSIST, we don't have to sync R/M bits.
1272 	 */
1273 	hat_demap(hat, htable_e2va(ht, entry));
1274 
1275 	/*
1276 	 * We don't create any mapping list entries on a remap, so release
1277 	 * any allocated hment after we drop the mapping list lock.
1278 	 */
1279 	if (is_consist) {
1280 		x86_hm_exit(pp);
1281 		if (hm != NULL)
1282 			hment_free(hm);
1283 	}
1284 }
1285 
1286 /*
1287  * The t_hatdepth field is an 8-bit counter.  We use the lower seven bits
1288  * to track exactly how deep we are in the memload->kmem_alloc recursion.
1289  * If the depth is greater than 1, that indicates that we are performing a
1290  * hat operation to satisfy another hat operation.  To prevent infinite
1291  * recursion, we switch over to using pre-allocated "reserves" of htables
1292  * and hments.
1293  *
1294  * The uppermost bit is used to indicate that we are transitioning away
1295  * from being the reserves thread.  See hati_reserves_exit() for the
1296  * details.
1297  */
1298 #define	EXITING_FLAG		(1 << 7)
1299 #define	DEPTH_MASK		(~EXITING_FLAG)
1300 #define	HAT_DEPTH(t)		((t)->t_hatdepth & DEPTH_MASK)
1301 #define	EXITING_RESERVES(t)	((t)->t_hatdepth & EXITING_FLAG)
1302 
1303 /*
1304  * Access to reserves for HAT_NO_KALLOC is single threaded.
1305  * If someone else is in the reserves, we'll politely wait for them
1306  * to finish. This keeps normal hat_memload()s from eating up
1307  * the mappings needed to replenish the reserve.
1308  */
1309 static void
1310 hati_reserves_enter(uint_t kmem_for_hat)
1311 {
1312 	/*
1313 	 * 64 is an arbitrary number to catch serious problems.  I'm not
1314 	 * sure what the absolute maximum depth is, but it should be
1315 	 * substantially less than this.
1316 	 */
1317 	ASSERT(HAT_DEPTH(curthread) < 64);
1318 
1319 	/*
1320 	 * If we are doing a memload to satisfy a kmem operation, we enter
1321 	 * the reserves immediately; we don't wait to recurse to a second
1322 	 * level of memload.
1323 	 */
1324 	ASSERT(kmem_for_hat < 2);
1325 	curthread->t_hatdepth += (1 + kmem_for_hat);
1326 
1327 	if (hat_reserves_thread == curthread || use_boot_reserve)
1328 		return;
1329 
1330 	if (HAT_DEPTH(curthread) > 1 || hat_reserves_thread != NULL) {
1331 		mutex_enter(&hat_reserves_lock);
1332 		while (hat_reserves_thread != NULL)
1333 			cv_wait(&hat_reserves_cv, &hat_reserves_lock);
1334 
1335 		if (HAT_DEPTH(curthread) > 1)
1336 			hat_reserves_thread = curthread;
1337 
1338 		mutex_exit(&hat_reserves_lock);
1339 	}
1340 }
1341 
1342 /*
1343  * If we are the reserves_thread and we've finally finished with all our
1344  * memloads (ie. no longer doing hat slabs), we can release our use of the
1345  * reserve.
1346  */
1347 static void
1348 hati_reserves_exit(uint_t kmem_for_hat)
1349 {
1350 	ASSERT(kmem_for_hat < 2);
1351 	curthread->t_hatdepth -= (1 + kmem_for_hat);
1352 
1353 	/*
1354 	 * Simple case: either we are not the reserves thread, or we are
1355 	 * the reserves thread and we are nested deeply enough that we
1356 	 * should still be the reserves thread.
1357 	 *
1358 	 * Note: we may not become the reserves thread after we recursively
1359 	 * enter our second HAT routine, but we don't stop being the
1360 	 * reserves thread until we exit the toplevel HAT routine.  This is
1361 	 * to work around vmem's inability to determine when an allocation
1362 	 * should be satisfied from the hat_memload arena, which can lead
1363 	 * to an infinite loop of memload->vmem_populate->memload->.
1364 	 */
1365 	if (curthread != hat_reserves_thread || HAT_DEPTH(curthread) > 0 ||
1366 	    use_boot_reserve)
1367 		return;
1368 
1369 	mutex_enter(&hat_reserves_lock);
1370 	ASSERT(hat_reserves_thread == curthread);
1371 	hat_reserves_thread = NULL;
1372 	cv_broadcast(&hat_reserves_cv);
1373 	mutex_exit(&hat_reserves_lock);
1374 
1375 	/*
1376 	 * As we leave the reserves, we want to be sure the reserve lists
1377 	 * aren't overstocked.  Freeing excess reserves requires that we
1378 	 * call kmem_free(), which may require additional allocations,
1379 	 * causing us to re-enter the reserves.  To avoid infinite
1380 	 * recursion, we only try to adjust reserves at the very top level.
1381 	 */
1382 	if (!kmem_for_hat && !EXITING_RESERVES(curthread)) {
1383 		curthread->t_hatdepth |= EXITING_FLAG;
1384 		htable_adjust_reserve();
1385 		hment_adjust_reserve();
1386 		curthread->t_hatdepth &= (~EXITING_FLAG);
1387 	}
1388 
1389 	/*
1390 	 * just in case something went wrong in doing adjust reserves
1391 	 */
1392 	ASSERT(hat_reserves_thread != curthread);
1393 }
1394 
1395 /*
1396  * Internal routine to load a single page table entry.
1397  */
1398 static void
1399 hati_load_common(
1400 	hat_t		*hat,
1401 	uintptr_t	va,
1402 	page_t		*pp,
1403 	uint_t		attr,
1404 	uint_t		flags,
1405 	level_t		level,
1406 	pfn_t		pfn)
1407 {
1408 	htable_t	*ht;
1409 	uint_t		entry;
1410 	x86pte_t	pte;
1411 	uint_t		kmem_for_hat = (flags & HAT_NO_KALLOC) ? 1 : 0;
1412 
1413 	ASSERT(hat == kas.a_hat ||
1414 	    AS_LOCK_HELD(hat->hat_as, &hat->hat_as->a_lock));
1415 
1416 	if (flags & HAT_LOAD_SHARE)
1417 		hat->hat_flags |= HAT_SHARED;
1418 
1419 	/*
1420 	 * Find the page table that maps this page if it already exists.
1421 	 */
1422 	ht = htable_lookup(hat, va, level);
1423 
1424 	/*
1425 	 * All threads go through hati_reserves_enter() to at least wait
1426 	 * for any existing reserves user to finish. This helps reduce
1427 	 * pressure on the reserves. In addition, if this thread needs
1428 	 * to become the new reserve user it will.
1429 	 */
1430 	hati_reserves_enter(kmem_for_hat);
1431 
1432 	ASSERT(HAT_DEPTH(curthread) == 1 || va >= kernelbase);
1433 
1434 	/*
1435 	 * Kernel memloads for HAT data should never use hments!
1436 	 * If it did that would seriously complicate the reserves system, since
1437 	 * hment_alloc() would need to know about HAT_NO_KALLOC.
1438 	 *
1439 	 * We also must have HAT_LOAD_NOCONSIST if page_t is NULL.
1440 	 */
1441 	if (HAT_DEPTH(curthread) > 1 || pp == NULL)
1442 		flags |= HAT_LOAD_NOCONSIST;
1443 
1444 	if (ht == NULL) {
1445 		ht = htable_create(hat, va, level, NULL);
1446 		ASSERT(ht != NULL);
1447 	}
1448 	entry = htable_va2entry(va, ht);
1449 
1450 	/*
1451 	 * a bunch of paranoid error checking
1452 	 */
1453 	ASSERT(ht->ht_busy > 0);
1454 	if (ht->ht_vaddr > va || va > HTABLE_LAST_PAGE(ht))
1455 		panic("hati_load_common: bad htable %p, va %p", ht, (void *)va);
1456 	ASSERT(ht->ht_level == level);
1457 
1458 	/*
1459 	 * construct the new PTE
1460 	 */
1461 	if (hat == kas.a_hat)
1462 		attr &= ~PROT_USER;
1463 	pte = hati_mkpte(pfn, attr, level, flags);
1464 	if (hat == kas.a_hat && va >= kernelbase)
1465 		PTE_SET(pte, mmu.pt_global);
1466 
1467 	/*
1468 	 * establish the mapping
1469 	 */
1470 	hati_pte_map(ht, entry, pp, pte, flags, NULL);
1471 
1472 	/*
1473 	 * release the htable and any reserves
1474 	 */
1475 	htable_release(ht);
1476 	hati_reserves_exit(kmem_for_hat);
1477 }
1478 
1479 /*
1480  * special case of hat_memload to deal with some kernel addrs for performance
1481  */
1482 static void
1483 hat_kmap_load(
1484 	caddr_t		addr,
1485 	page_t		*pp,
1486 	uint_t		attr,
1487 	uint_t		flags)
1488 {
1489 	uintptr_t	va = (uintptr_t)addr;
1490 	x86pte_t	pte;
1491 	pfn_t		pfn = page_pptonum(pp);
1492 	pgcnt_t		pg_off = mmu_btop(va - mmu.kmap_addr);
1493 	htable_t	*ht;
1494 	uint_t		entry;
1495 	void		*pte_ptr;
1496 
1497 	/*
1498 	 * construct the requested PTE
1499 	 */
1500 	attr &= ~PROT_USER;
1501 	attr |= HAT_STORECACHING_OK;
1502 	pte = hati_mkpte(pfn, attr, 0, flags);
1503 	PTE_SET(pte, mmu.pt_global);
1504 
1505 	/*
1506 	 * Figure out the pte_ptr and htable and use common code to finish up
1507 	 */
1508 	if (mmu.pae_hat)
1509 		pte_ptr = mmu.kmap_ptes + pg_off;
1510 	else
1511 		pte_ptr = (x86pte32_t *)mmu.kmap_ptes + pg_off;
1512 	ht = mmu.kmap_htables[(va - mmu.kmap_htables[0]->ht_vaddr) >>
1513 	    LEVEL_SHIFT(1)];
1514 	entry = htable_va2entry(va, ht);
1515 	hati_pte_map(ht, entry, pp, pte, flags, pte_ptr);
1516 }
1517 
1518 /*
1519  * hat_memload() - load a translation to the given page struct
1520  *
1521  * Flags for hat_memload/hat_devload/hat_*attr.
1522  *
1523  * 	HAT_LOAD	Default flags to load a translation to the page.
1524  *
1525  * 	HAT_LOAD_LOCK	Lock down mapping resources; hat_map(), hat_memload(),
1526  *			and hat_devload().
1527  *
1528  *	HAT_LOAD_NOCONSIST Do not add mapping to page_t mapping list.
1529  *			sets PT_NOCONSIST (soft bit)
1530  *
1531  *	HAT_LOAD_SHARE	A flag to hat_memload() to indicate h/w page tables
1532  *			that map some user pages (not kas) is shared by more
1533  *			than one process (eg. ISM).
1534  *
1535  *	HAT_LOAD_REMAP	Reload a valid pte with a different page frame.
1536  *
1537  *	HAT_NO_KALLOC	Do not kmem_alloc while creating the mapping; at this
1538  *			point, it's setting up mapping to allocate internal
1539  *			hat layer data structures.  This flag forces hat layer
1540  *			to tap its reserves in order to prevent infinite
1541  *			recursion.
1542  *
1543  * The following is a protection attribute (like PROT_READ, etc.)
1544  *
1545  *	HAT_NOSYNC	set PT_NOSYNC (soft bit) - this mapping's ref/mod bits
1546  *			are never cleared.
1547  *
1548  * Installing new valid PTE's and creation of the mapping list
1549  * entry are controlled under the same lock. It's derived from the
1550  * page_t being mapped.
1551  */
1552 static uint_t supported_memload_flags =
1553 	HAT_LOAD | HAT_LOAD_LOCK | HAT_LOAD_ADV | HAT_LOAD_NOCONSIST |
1554 	HAT_LOAD_SHARE | HAT_NO_KALLOC | HAT_LOAD_REMAP | HAT_LOAD_TEXT;
1555 
1556 void
1557 hat_memload(
1558 	hat_t		*hat,
1559 	caddr_t		addr,
1560 	page_t		*pp,
1561 	uint_t		attr,
1562 	uint_t		flags)
1563 {
1564 	uintptr_t	va = (uintptr_t)addr;
1565 	level_t		level = 0;
1566 	pfn_t		pfn = page_pptonum(pp);
1567 
1568 	HATIN(hat_memload, hat, addr, (size_t)MMU_PAGESIZE);
1569 	ASSERT(IS_PAGEALIGNED(va));
1570 	ASSERT(hat == kas.a_hat || va <= kernelbase);
1571 	ASSERT(hat == kas.a_hat ||
1572 	    AS_LOCK_HELD(hat->hat_as, &hat->hat_as->a_lock));
1573 	ASSERT((flags & supported_memload_flags) == flags);
1574 
1575 	ASSERT(!IN_VA_HOLE(va));
1576 	ASSERT(!PP_ISFREE(pp));
1577 
1578 	/*
1579 	 * kernel address special case for performance.
1580 	 */
1581 	if (mmu.kmap_addr <= va && va < mmu.kmap_eaddr) {
1582 		ASSERT(hat == kas.a_hat);
1583 		hat_kmap_load(addr, pp, attr, flags);
1584 		return;
1585 	}
1586 
1587 	/*
1588 	 * This is used for memory with normal caching enabled, so
1589 	 * always set HAT_STORECACHING_OK.
1590 	 */
1591 	attr |= HAT_STORECACHING_OK;
1592 	hati_load_common(hat, va, pp, attr, flags, level, pfn);
1593 	HATOUT(hat_memload, hat, addr);
1594 }
1595 
1596 /*
1597  * Load the given array of page structs using large pages when possible
1598  */
1599 void
1600 hat_memload_array(
1601 	hat_t		*hat,
1602 	caddr_t		addr,
1603 	size_t		len,
1604 	page_t		**pages,
1605 	uint_t		attr,
1606 	uint_t		flags)
1607 {
1608 	uintptr_t	va = (uintptr_t)addr;
1609 	uintptr_t	eaddr = va + len;
1610 	level_t		level;
1611 	size_t		pgsize;
1612 	pgcnt_t		pgindx = 0;
1613 	pfn_t		pfn;
1614 	pgcnt_t		i;
1615 
1616 	HATIN(hat_memload_array, hat, addr, len);
1617 	ASSERT(IS_PAGEALIGNED(va));
1618 	ASSERT(hat == kas.a_hat || va + len <= kernelbase);
1619 	ASSERT(hat == kas.a_hat ||
1620 	    AS_LOCK_HELD(hat->hat_as, &hat->hat_as->a_lock));
1621 	ASSERT((flags & supported_memload_flags) == flags);
1622 
1623 	/*
1624 	 * memload is used for memory with full caching enabled, so
1625 	 * set HAT_STORECACHING_OK.
1626 	 */
1627 	attr |= HAT_STORECACHING_OK;
1628 
1629 	/*
1630 	 * handle all pages using largest possible pagesize
1631 	 */
1632 	while (va < eaddr) {
1633 		/*
1634 		 * decide what level mapping to use (ie. pagesize)
1635 		 */
1636 		pfn = page_pptonum(pages[pgindx]);
1637 		for (level = mmu.max_page_level; ; --level) {
1638 			pgsize = LEVEL_SIZE(level);
1639 			if (level == 0)
1640 				break;
1641 			if (!IS_P2ALIGNED(va, pgsize) ||
1642 			    (eaddr - va) < pgsize ||
1643 			    !IS_P2ALIGNED(pfn << MMU_PAGESHIFT, pgsize))
1644 				continue;
1645 
1646 			/*
1647 			 * To use a large mapping of this size, all the
1648 			 * pages we are passed must be sequential subpages
1649 			 * of the large page.
1650 			 * hat_page_demote() can't change p_szc because
1651 			 * all pages are locked.
1652 			 */
1653 			if (pages[pgindx]->p_szc >= level) {
1654 				for (i = 0; i < mmu_btop(pgsize); ++i) {
1655 					if (pfn + i !=
1656 					    page_pptonum(pages[pgindx + i]))
1657 						break;
1658 					ASSERT(pages[pgindx + i]->p_szc >=
1659 					    level);
1660 					ASSERT(pages[pgindx] + i ==
1661 					    pages[pgindx + i]);
1662 				}
1663 				if (i == mmu_btop(pgsize))
1664 					break;
1665 			}
1666 		}
1667 
1668 		/*
1669 		 * Shared page tables for DISM might have a pre-existing
1670 		 * level 0 page table that wasn't unlinked from all the
1671 		 * sharing hats. If we hit this for a large page, back off
1672 		 * to using level 0 pages.
1673 		 *
1674 		 * This can't be made better (ie. use large pages) until we
1675 		 * track all the htable's sharing and rewrite hat_pageunload().
1676 		 * Note that would cost a pointer in htable_t for a rare case.
1677 		 *
1678 		 * Since the 32 bit kernel caches empty page tables, check
1679 		 * the kernel too.
1680 		 */
1681 		if ((hat == kas.a_hat || (hat->hat_flags & HAT_SHARED)) &&
1682 		    level > 0) {
1683 			htable_t *lower;
1684 
1685 			lower = htable_getpte(hat, va, NULL, NULL, level - 1);
1686 			if (lower != NULL) {
1687 				level = 0;
1688 				pgsize = LEVEL_SIZE(0);
1689 				htable_release(lower);
1690 			}
1691 		}
1692 
1693 		/*
1694 		 * load this page mapping
1695 		 */
1696 		ASSERT(!IN_VA_HOLE(va));
1697 		hati_load_common(hat, va, pages[pgindx], attr, flags,
1698 		    level, pfn);
1699 
1700 		/*
1701 		 * move to next page
1702 		 */
1703 		va += pgsize;
1704 		pgindx += mmu_btop(pgsize);
1705 	}
1706 	HATOUT(hat_memload_array, hat, addr);
1707 }
1708 
1709 /*
1710  * void hat_devload(hat, addr, len, pf, attr, flags)
1711  *	load/lock the given page frame number
1712  *
1713  * Advisory ordering attributes. Apply only to device mappings.
1714  *
1715  * HAT_STRICTORDER: the CPU must issue the references in order, as the
1716  *	programmer specified.  This is the default.
1717  * HAT_UNORDERED_OK: the CPU may reorder the references (this is all kinds
1718  *	of reordering; store or load with store or load).
1719  * HAT_MERGING_OK: merging and batching: the CPU may merge individual stores
1720  *	to consecutive locations (for example, turn two consecutive byte
1721  *	stores into one halfword store), and it may batch individual loads
1722  *	(for example, turn two consecutive byte loads into one halfword load).
1723  *	This also implies re-ordering.
1724  * HAT_LOADCACHING_OK: the CPU may cache the data it fetches and reuse it
1725  *	until another store occurs.  The default is to fetch new data
1726  *	on every load.  This also implies merging.
1727  * HAT_STORECACHING_OK: the CPU may keep the data in the cache and push it to
1728  *	the device (perhaps with other data) at a later time.  The default is
1729  *	to push the data right away.  This also implies load caching.
1730  *
1731  * Equivalent of hat_memload(), but can be used for device memory where
1732  * there are no page_t's and we support additional flags (write merging, etc).
1733  * Note that we can have large page mappings with this interface.
1734  */
1735 int supported_devload_flags = HAT_LOAD | HAT_LOAD_LOCK |
1736 	HAT_LOAD_NOCONSIST | HAT_STRICTORDER | HAT_UNORDERED_OK |
1737 	HAT_MERGING_OK | HAT_LOADCACHING_OK | HAT_STORECACHING_OK;
1738 
1739 void
1740 hat_devload(
1741 	hat_t		*hat,
1742 	caddr_t		addr,
1743 	size_t		len,
1744 	pfn_t		pfn,
1745 	uint_t		attr,
1746 	int		flags)
1747 {
1748 	uintptr_t	va = ALIGN2PAGE(addr);
1749 	uintptr_t	eva = va + len;
1750 	level_t		level;
1751 	size_t		pgsize;
1752 	page_t		*pp;
1753 	int		f;	/* per PTE copy of flags  - maybe modified */
1754 	uint_t		a;	/* per PTE copy of attr */
1755 
1756 	HATIN(hat_devload, hat, addr, len);
1757 	ASSERT(IS_PAGEALIGNED(va));
1758 	ASSERT(hat == kas.a_hat || eva <= kernelbase);
1759 	ASSERT(hat == kas.a_hat ||
1760 	    AS_LOCK_HELD(hat->hat_as, &hat->hat_as->a_lock));
1761 	ASSERT((flags & supported_devload_flags) == flags);
1762 
1763 	/*
1764 	 * handle all pages
1765 	 */
1766 	while (va < eva) {
1767 
1768 		/*
1769 		 * decide what level mapping to use (ie. pagesize)
1770 		 */
1771 		for (level = mmu.max_page_level; ; --level) {
1772 			pgsize = LEVEL_SIZE(level);
1773 			if (level == 0)
1774 				break;
1775 			if (IS_P2ALIGNED(va, pgsize) &&
1776 			    (eva - va) >= pgsize &&
1777 			    IS_P2ALIGNED(pfn, mmu_btop(pgsize)))
1778 				break;
1779 		}
1780 
1781 		/*
1782 		 * Some kernel addresses have permanently existing page tables,
1783 		 * so be sure to use a compatible pagesize.
1784 		 */
1785 		if (hat == kas.a_hat && level > 0) {
1786 			htable_t *lower;
1787 
1788 			lower = htable_getpte(hat, va, NULL, NULL, level - 1);
1789 			if (lower != NULL) {
1790 				level = 0;
1791 				pgsize = LEVEL_SIZE(0);
1792 				htable_release(lower);
1793 			}
1794 		}
1795 
1796 		/*
1797 		 * If it is memory get page_t and allow caching (this happens
1798 		 * for the nucleus pages) - though HAT_PLAT_NOCACHE can be used
1799 		 * to override that. If we don't have a page_t, make sure
1800 		 * NOCONSIST is set.
1801 		 */
1802 		a = attr;
1803 		f = flags;
1804 		if (pf_is_memory(pfn)) {
1805 			if (!(a & HAT_PLAT_NOCACHE))
1806 				a |= HAT_STORECACHING_OK;
1807 
1808 			if (f & HAT_LOAD_NOCONSIST)
1809 				pp = NULL;
1810 			else
1811 				pp = page_numtopp_nolock(pfn);
1812 		} else {
1813 			pp = NULL;
1814 			f |= HAT_LOAD_NOCONSIST;
1815 		}
1816 
1817 		/*
1818 		 * load this page mapping
1819 		 */
1820 		ASSERT(!IN_VA_HOLE(va));
1821 		hati_load_common(hat, va, pp, a, f, level, pfn);
1822 
1823 		/*
1824 		 * move to next page
1825 		 */
1826 		va += pgsize;
1827 		pfn += mmu_btop(pgsize);
1828 	}
1829 	HATOUT(hat_devload, hat, addr);
1830 }
1831 
1832 /*
1833  * void hat_unlock(hat, addr, len)
1834  *	unlock the mappings to a given range of addresses
1835  *
1836  * Locks are tracked by ht_lock_cnt in the htable.
1837  */
1838 void
1839 hat_unlock(hat_t *hat, caddr_t addr, size_t len)
1840 {
1841 	uintptr_t	vaddr = (uintptr_t)addr;
1842 	uintptr_t	eaddr = vaddr + len;
1843 	htable_t	*ht = NULL;
1844 
1845 	/*
1846 	 * kernel entries are always locked, we don't track lock counts
1847 	 */
1848 	ASSERT(hat == kas.a_hat || eaddr <= kernelbase);
1849 	ASSERT(IS_PAGEALIGNED(vaddr));
1850 	ASSERT(IS_PAGEALIGNED(eaddr));
1851 	if (hat == kas.a_hat)
1852 		return;
1853 	if (eaddr > _userlimit)
1854 		panic("hat_unlock() address out of range - above _userlimit");
1855 
1856 	ASSERT(AS_LOCK_HELD(hat->hat_as, &hat->hat_as->a_lock));
1857 	while (vaddr < eaddr) {
1858 		(void) htable_walk(hat, &ht, &vaddr, eaddr);
1859 		if (ht == NULL)
1860 			break;
1861 
1862 		ASSERT(!IN_VA_HOLE(vaddr));
1863 
1864 		if (ht->ht_lock_cnt < 1)
1865 			panic("hat_unlock(): lock_cnt < 1, "
1866 			    "htable=%p, vaddr=%p\n", ht, (caddr_t)vaddr);
1867 		HTABLE_LOCK_DEC(ht);
1868 
1869 		vaddr += LEVEL_SIZE(ht->ht_level);
1870 	}
1871 	if (ht)
1872 		htable_release(ht);
1873 }
1874 
1875 /*
1876  * Cross call service routine to demap a virtual page on
1877  * the current CPU or flush all mappings in TLB.
1878  */
1879 /*ARGSUSED*/
1880 static int
1881 hati_demap_func(xc_arg_t a1, xc_arg_t a2, xc_arg_t a3)
1882 {
1883 	hat_t	*hat = (hat_t *)a1;
1884 	caddr_t	addr = (caddr_t)a2;
1885 
1886 	/*
1887 	 * If the target hat isn't the kernel and this CPU isn't operating
1888 	 * in the target hat, we can ignore the cross call.
1889 	 */
1890 	if (hat != kas.a_hat && hat != CPU->cpu_current_hat)
1891 		return (0);
1892 
1893 	/*
1894 	 * For a normal address, we just flush one page mapping
1895 	 */
1896 	if ((uintptr_t)addr != DEMAP_ALL_ADDR) {
1897 		mmu_tlbflush_entry((caddr_t)addr);
1898 		return (0);
1899 	}
1900 
1901 	/*
1902 	 * Otherwise we reload cr3 to effect a complete TLB flush.
1903 	 *
1904 	 * A reload of cr3 on a VLP process also means we must also recopy in
1905 	 * the pte values from the struct hat
1906 	 */
1907 	if (hat->hat_flags & HAT_VLP) {
1908 #if defined(__amd64)
1909 		x86pte_t *vlpptep = CPU->cpu_hat_info->hci_vlp_l2ptes;
1910 
1911 		VLP_COPY(hat->hat_vlp_ptes, vlpptep);
1912 #elif defined(__i386)
1913 		reload_pae32(hat, CPU);
1914 #endif
1915 	}
1916 	reload_cr3();
1917 	return (0);
1918 }
1919 
1920 /*
1921  * Internal routine to do cross calls to invalidate a range of pages on
1922  * all CPUs using a given hat.
1923  */
1924 void
1925 hat_demap(hat_t *hat, uintptr_t va)
1926 {
1927 	extern int	flushes_require_xcalls;	/* from mp_startup.c */
1928 	cpuset_t	justme;
1929 
1930 	/*
1931 	 * If the hat is being destroyed, there are no more users, so
1932 	 * demap need not do anything.
1933 	 */
1934 	if (hat->hat_flags & HAT_FREEING)
1935 		return;
1936 
1937 	/*
1938 	 * If demapping from a shared pagetable, we best demap the
1939 	 * entire set of user TLBs, since we don't know what addresses
1940 	 * these were shared at.
1941 	 */
1942 	if (hat->hat_flags & HAT_SHARED) {
1943 		hat = kas.a_hat;
1944 		va = DEMAP_ALL_ADDR;
1945 	}
1946 
1947 	/*
1948 	 * if not running with multiple CPUs, don't use cross calls
1949 	 */
1950 	if (panicstr || !flushes_require_xcalls) {
1951 		(void) hati_demap_func((xc_arg_t)hat, (xc_arg_t)va, NULL);
1952 		return;
1953 	}
1954 
1955 
1956 	/*
1957 	 * All CPUs must see kernel hat changes.
1958 	 */
1959 	if (hat == kas.a_hat) {
1960 		kpreempt_disable();
1961 		xc_call((xc_arg_t)hat, (xc_arg_t)va, NULL,
1962 		    X_CALL_HIPRI, khat_cpuset, hati_demap_func);
1963 		kpreempt_enable();
1964 		return;
1965 	}
1966 
1967 	/*
1968 	 * Otherwise we notify CPUs currently running in this HAT
1969 	 */
1970 	mutex_enter(&hat->hat_switch_mutex);
1971 	kpreempt_disable();
1972 	CPUSET_ONLY(justme, CPU->cpu_id);
1973 	if (CPUSET_ISEQUAL(hat->hat_cpus, justme))
1974 		(void) hati_demap_func((xc_arg_t)hat, (xc_arg_t)va, NULL);
1975 	else
1976 		xc_call((xc_arg_t)hat, (xc_arg_t)va, NULL,
1977 		    X_CALL_HIPRI, hat->hat_cpus, hati_demap_func);
1978 	kpreempt_enable();
1979 	mutex_exit(&hat->hat_switch_mutex);
1980 }
1981 
1982 /*
1983  * Interior routine for HAT_UNLOADs from hat_unload_callback(),
1984  * hat_kmap_unload() OR from hat_steal() code.  This routine doesn't
1985  * handle releasing of the htables.
1986  */
1987 void
1988 hat_pte_unmap(
1989 	htable_t	*ht,
1990 	uint_t		entry,
1991 	uint_t		flags,
1992 	x86pte_t	old_pte,
1993 	void		*pte_ptr)
1994 {
1995 	hat_t		*hat = ht->ht_hat;
1996 	hment_t		*hm = NULL;
1997 	page_t		*pp = NULL;
1998 	level_t		l = ht->ht_level;
1999 	pfn_t		pfn;
2000 
2001 	/*
2002 	 * We always track the locking counts, even if nothing is unmapped
2003 	 */
2004 	if ((flags & HAT_UNLOAD_UNLOCK) != 0 && hat != kas.a_hat) {
2005 		ASSERT(ht->ht_lock_cnt > 0);
2006 		HTABLE_LOCK_DEC(ht);
2007 	}
2008 
2009 	/*
2010 	 * Figure out which page's mapping list lock to acquire using the PFN
2011 	 * passed in "old" PTE. We then attempt to invalidate the PTE.
2012 	 * If another thread, probably a hat_pageunload, has asynchronously
2013 	 * unmapped/remapped this address we'll loop here.
2014 	 */
2015 	ASSERT(ht->ht_busy > 0);
2016 	while (PTE_ISVALID(old_pte)) {
2017 		pfn = PTE2PFN(old_pte, l);
2018 		if (PTE_GET(old_pte, PT_NOCONSIST)) {
2019 			pp = NULL;
2020 		} else {
2021 			pp = page_numtopp_nolock(pfn);
2022 			if (pp == NULL) {
2023 				panic("no page_t, not NOCONSIST: old_pte="
2024 				    FMT_PTE " ht=%lx entry=0x%x pte_ptr=%lx",
2025 				    old_pte, (uintptr_t)ht, entry,
2026 				    (uintptr_t)pte_ptr);
2027 			}
2028 			x86_hm_enter(pp);
2029 		}
2030 
2031 		/*
2032 		 * If freeing the address space, check that the PTE
2033 		 * hasn't changed, as the mappings are no longer in use by
2034 		 * any thread, invalidation is unnecessary.
2035 		 * If not freeing, do a full invalidate.
2036 		 */
2037 		if (hat->hat_flags & HAT_FREEING)
2038 			old_pte = x86pte_get(ht, entry);
2039 		else
2040 			old_pte =
2041 			    x86pte_invalidate_pfn(ht, entry, pfn, pte_ptr);
2042 
2043 		/*
2044 		 * If the page hadn't changed we've unmapped it and can proceed
2045 		 */
2046 		if (PTE_ISVALID(old_pte) && PTE2PFN(old_pte, l) == pfn)
2047 			break;
2048 
2049 		/*
2050 		 * Otherwise, we'll have to retry with the current old_pte.
2051 		 * Drop the hment lock, since the pfn may have changed.
2052 		 */
2053 		if (pp != NULL) {
2054 			x86_hm_exit(pp);
2055 			pp = NULL;
2056 		} else {
2057 			ASSERT(PTE_GET(old_pte, PT_NOCONSIST));
2058 		}
2059 	}
2060 
2061 	/*
2062 	 * If the old mapping wasn't valid, there's nothing more to do
2063 	 */
2064 	if (!PTE_ISVALID(old_pte)) {
2065 		if (pp != NULL)
2066 			x86_hm_exit(pp);
2067 		return;
2068 	}
2069 
2070 	/*
2071 	 * Take care of syncing any MOD/REF bits and removing the hment.
2072 	 */
2073 	if (pp != NULL) {
2074 		if (!(flags & HAT_UNLOAD_NOSYNC))
2075 			hati_sync_pte_to_page(pp, old_pte, l);
2076 		hm = hment_remove(pp, ht, entry);
2077 		x86_hm_exit(pp);
2078 		if (hm != NULL)
2079 			hment_free(hm);
2080 	}
2081 
2082 	/*
2083 	 * Handle book keeping in the htable and hat
2084 	 */
2085 	ASSERT(ht->ht_valid_cnt > 0);
2086 	HTABLE_DEC(ht->ht_valid_cnt);
2087 	PGCNT_DEC(hat, l);
2088 }
2089 
2090 /*
2091  * very cheap unload implementation to special case some kernel addresses
2092  */
2093 static void
2094 hat_kmap_unload(caddr_t addr, size_t len, uint_t flags)
2095 {
2096 	uintptr_t	va = (uintptr_t)addr;
2097 	uintptr_t	eva = va + len;
2098 	pgcnt_t		pg_off;
2099 	htable_t	*ht;
2100 	uint_t		entry;
2101 	void		*pte_ptr;
2102 	x86pte_t	old_pte;
2103 
2104 	for (; va < eva; va += MMU_PAGESIZE) {
2105 		/*
2106 		 * Get the PTE
2107 		 */
2108 		pg_off = mmu_btop(va - mmu.kmap_addr);
2109 		if (mmu.pae_hat) {
2110 			pte_ptr = mmu.kmap_ptes + pg_off;
2111 			ATOMIC_LOAD64((x86pte_t *)pte_ptr, old_pte);
2112 		} else {
2113 			pte_ptr = (x86pte32_t *)mmu.kmap_ptes + pg_off;
2114 			old_pte = *(x86pte32_t *)pte_ptr;
2115 		}
2116 
2117 		/*
2118 		 * get the htable / entry
2119 		 */
2120 		ht = mmu.kmap_htables[(va - mmu.kmap_htables[0]->ht_vaddr)
2121 		    >> LEVEL_SHIFT(1)];
2122 		entry = htable_va2entry(va, ht);
2123 
2124 		/*
2125 		 * use mostly common code to unmap it.
2126 		 */
2127 		hat_pte_unmap(ht, entry, flags, old_pte, pte_ptr);
2128 	}
2129 }
2130 
2131 
2132 /*
2133  * unload a range of virtual address space (no callback)
2134  */
2135 void
2136 hat_unload(hat_t *hat, caddr_t addr, size_t len, uint_t flags)
2137 {
2138 	uintptr_t va = (uintptr_t)addr;
2139 	ASSERT(hat == kas.a_hat || va + len <= kernelbase);
2140 
2141 	/*
2142 	 * special case for performance.
2143 	 */
2144 	if (mmu.kmap_addr <= va && va < mmu.kmap_eaddr) {
2145 		ASSERT(hat == kas.a_hat);
2146 		hat_kmap_unload(addr, len, flags);
2147 		return;
2148 	}
2149 	hat_unload_callback(hat, addr, len, flags, NULL);
2150 }
2151 
2152 /*
2153  * Do the callbacks for ranges being unloaded.
2154  */
2155 typedef struct range_info {
2156 	uintptr_t	rng_va;
2157 	ulong_t		rng_cnt;
2158 	level_t		rng_level;
2159 } range_info_t;
2160 
2161 static void
2162 handle_ranges(hat_callback_t *cb, uint_t cnt, range_info_t *range)
2163 {
2164 	/*
2165 	 * do callbacks to upper level VM system
2166 	 */
2167 	while (cb != NULL && cnt > 0) {
2168 		--cnt;
2169 		cb->hcb_start_addr = (caddr_t)range[cnt].rng_va;
2170 		cb->hcb_end_addr = cb->hcb_start_addr;
2171 		cb->hcb_end_addr +=
2172 		    range[cnt].rng_cnt << LEVEL_SIZE(range[cnt].rng_level);
2173 		cb->hcb_function(cb);
2174 	}
2175 }
2176 
2177 /*
2178  * Unload a given range of addresses (has optional callback)
2179  *
2180  * Flags:
2181  * define	HAT_UNLOAD		0x00
2182  * define	HAT_UNLOAD_NOSYNC	0x02
2183  * define	HAT_UNLOAD_UNLOCK	0x04
2184  * define	HAT_UNLOAD_OTHER	0x08 - not used
2185  * define	HAT_UNLOAD_UNMAP	0x10 - same as HAT_UNLOAD
2186  */
2187 #define	MAX_UNLOAD_CNT (8)
2188 void
2189 hat_unload_callback(
2190 	hat_t		*hat,
2191 	caddr_t		addr,
2192 	size_t		len,
2193 	uint_t		flags,
2194 	hat_callback_t	*cb)
2195 {
2196 	uintptr_t	vaddr = (uintptr_t)addr;
2197 	uintptr_t	eaddr = vaddr + len;
2198 	htable_t	*ht = NULL;
2199 	uint_t		entry;
2200 	uintptr_t	contig_va = (uintptr_t)-1L;
2201 	range_info_t	r[MAX_UNLOAD_CNT];
2202 	uint_t		r_cnt = 0;
2203 	x86pte_t	old_pte;
2204 
2205 	HATIN(hat_unload_callback, hat, addr, len);
2206 	ASSERT(hat == kas.a_hat || eaddr <= kernelbase);
2207 	ASSERT(IS_PAGEALIGNED(vaddr));
2208 	ASSERT(IS_PAGEALIGNED(eaddr));
2209 
2210 	while (vaddr < eaddr) {
2211 		old_pte = htable_walk(hat, &ht, &vaddr, eaddr);
2212 		if (ht == NULL)
2213 			break;
2214 
2215 		ASSERT(!IN_VA_HOLE(vaddr));
2216 
2217 		if (vaddr < (uintptr_t)addr)
2218 			panic("hat_unload_callback(): unmap inside large page");
2219 
2220 		/*
2221 		 * We'll do the call backs for contiguous ranges
2222 		 */
2223 		if (vaddr != contig_va ||
2224 		    (r_cnt > 0 && r[r_cnt - 1].rng_level != ht->ht_level)) {
2225 			if (r_cnt == MAX_UNLOAD_CNT) {
2226 				handle_ranges(cb, r_cnt, r);
2227 				r_cnt = 0;
2228 			}
2229 			r[r_cnt].rng_va = vaddr;
2230 			r[r_cnt].rng_cnt = 0;
2231 			r[r_cnt].rng_level = ht->ht_level;
2232 			++r_cnt;
2233 		}
2234 
2235 		/*
2236 		 * Unload one mapping from the page tables.
2237 		 */
2238 		entry = htable_va2entry(vaddr, ht);
2239 		hat_pte_unmap(ht, entry, flags, old_pte, NULL);
2240 
2241 		ASSERT(ht->ht_level <= mmu.max_page_level);
2242 		vaddr += LEVEL_SIZE(ht->ht_level);
2243 		contig_va = vaddr;
2244 		++r[r_cnt - 1].rng_cnt;
2245 	}
2246 	if (ht)
2247 		htable_release(ht);
2248 
2249 	/*
2250 	 * handle last range for callbacks
2251 	 */
2252 	if (r_cnt > 0)
2253 		handle_ranges(cb, r_cnt, r);
2254 
2255 	HATOUT(hat_unload_callback, hat, addr);
2256 }
2257 
2258 /*
2259  * synchronize mapping with software data structures
2260  *
2261  * This interface is currently only used by the working set monitor
2262  * driver.
2263  */
2264 /*ARGSUSED*/
2265 void
2266 hat_sync(hat_t *hat, caddr_t addr, size_t len, uint_t flags)
2267 {
2268 	uintptr_t	vaddr = (uintptr_t)addr;
2269 	uintptr_t	eaddr = vaddr + len;
2270 	htable_t	*ht = NULL;
2271 	uint_t		entry;
2272 	x86pte_t	pte;
2273 	x86pte_t	save_pte;
2274 	x86pte_t	new;
2275 	page_t		*pp;
2276 
2277 	ASSERT(!IN_VA_HOLE(vaddr));
2278 	ASSERT(IS_PAGEALIGNED(vaddr));
2279 	ASSERT(IS_PAGEALIGNED(eaddr));
2280 	ASSERT(hat == kas.a_hat || eaddr <= kernelbase);
2281 
2282 	for (; vaddr < eaddr; vaddr += LEVEL_SIZE(ht->ht_level)) {
2283 try_again:
2284 		pte = htable_walk(hat, &ht, &vaddr, eaddr);
2285 		if (ht == NULL)
2286 			break;
2287 		entry = htable_va2entry(vaddr, ht);
2288 
2289 		if (PTE_GET(pte, PT_NOSYNC) ||
2290 		    PTE_GET(pte, PT_REF | PT_MOD) == 0)
2291 			continue;
2292 
2293 		/*
2294 		 * We need to acquire the mapping list lock to protect
2295 		 * against hat_pageunload(), hat_unload(), etc.
2296 		 */
2297 		pp = page_numtopp_nolock(PTE2PFN(pte, ht->ht_level));
2298 		if (pp == NULL)
2299 			break;
2300 		x86_hm_enter(pp);
2301 		save_pte = pte;
2302 		pte = x86pte_get(ht, entry);
2303 		if (pte != save_pte) {
2304 			x86_hm_exit(pp);
2305 			goto try_again;
2306 		}
2307 		if (PTE_GET(pte, PT_NOSYNC) ||
2308 		    PTE_GET(pte, PT_REF | PT_MOD) == 0) {
2309 			x86_hm_exit(pp);
2310 			continue;
2311 		}
2312 
2313 		/*
2314 		 * Need to clear ref or mod bits. We may compete with
2315 		 * hardware updating the R/M bits and have to try again.
2316 		 */
2317 		if (flags == HAT_SYNC_ZERORM) {
2318 			new = pte;
2319 			PTE_CLR(new, PT_REF | PT_MOD);
2320 			pte = hati_update_pte(ht, entry, pte, new);
2321 			if (pte != 0) {
2322 				x86_hm_exit(pp);
2323 				goto try_again;
2324 			}
2325 		} else {
2326 			/*
2327 			 * sync the PTE to the page_t
2328 			 */
2329 			hati_sync_pte_to_page(pp, save_pte, ht->ht_level);
2330 		}
2331 		x86_hm_exit(pp);
2332 	}
2333 	if (ht)
2334 		htable_release(ht);
2335 }
2336 
2337 /*
2338  * void	hat_map(hat, addr, len, flags)
2339  */
2340 /*ARGSUSED*/
2341 void
2342 hat_map(hat_t *hat, caddr_t addr, size_t len, uint_t flags)
2343 {
2344 	/* does nothing */
2345 }
2346 
2347 /*
2348  * uint_t hat_getattr(hat, addr, *attr)
2349  *	returns attr for <hat,addr> in *attr.  returns 0 if there was a
2350  *	mapping and *attr is valid, nonzero if there was no mapping and
2351  *	*attr is not valid.
2352  */
2353 uint_t
2354 hat_getattr(hat_t *hat, caddr_t addr, uint_t *attr)
2355 {
2356 	uintptr_t	vaddr = ALIGN2PAGE(addr);
2357 	htable_t	*ht = NULL;
2358 	x86pte_t	pte;
2359 
2360 	ASSERT(hat == kas.a_hat || vaddr < kernelbase);
2361 
2362 	if (IN_VA_HOLE(vaddr))
2363 		return ((uint_t)-1);
2364 
2365 	ht = htable_getpte(hat, vaddr, NULL, &pte, MAX_PAGE_LEVEL);
2366 	if (ht == NULL)
2367 		return ((uint_t)-1);
2368 
2369 	if (!PTE_ISVALID(pte) || !PTE_ISPAGE(pte, ht->ht_level)) {
2370 		htable_release(ht);
2371 		return ((uint_t)-1);
2372 	}
2373 
2374 	*attr = PROT_READ;
2375 	if (PTE_GET(pte, PT_WRITABLE))
2376 		*attr |= PROT_WRITE;
2377 	if (PTE_GET(pte, PT_USER))
2378 		*attr |= PROT_USER;
2379 	if (!PTE_GET(pte, mmu.pt_nx))
2380 		*attr |= PROT_EXEC;
2381 	if (PTE_GET(pte, PT_NOSYNC))
2382 		*attr |= HAT_NOSYNC;
2383 	htable_release(ht);
2384 	return (0);
2385 }
2386 
2387 /*
2388  * hat_updateattr() applies the given attribute change to an existing mapping
2389  */
2390 #define	HAT_LOAD_ATTR		1
2391 #define	HAT_SET_ATTR		2
2392 #define	HAT_CLR_ATTR		3
2393 
2394 static void
2395 hat_updateattr(hat_t *hat, caddr_t addr, size_t len, uint_t attr, int what)
2396 {
2397 	uintptr_t	vaddr = (uintptr_t)addr;
2398 	uintptr_t	eaddr = (uintptr_t)addr + len;
2399 	htable_t	*ht = NULL;
2400 	uint_t		entry;
2401 	x86pte_t	oldpte, newpte;
2402 	page_t		*pp;
2403 
2404 	ASSERT(IS_PAGEALIGNED(vaddr));
2405 	ASSERT(IS_PAGEALIGNED(eaddr));
2406 	ASSERT(hat == kas.a_hat ||
2407 	    AS_LOCK_HELD(hat->hat_as, &hat->hat_as->a_lock));
2408 	for (; vaddr < eaddr; vaddr += LEVEL_SIZE(ht->ht_level)) {
2409 try_again:
2410 		oldpte = htable_walk(hat, &ht, &vaddr, eaddr);
2411 		if (ht == NULL)
2412 			break;
2413 		if (PTE_GET(oldpte, PT_NOCONSIST))
2414 			continue;
2415 
2416 		pp = page_numtopp_nolock(PTE2PFN(oldpte, ht->ht_level));
2417 		if (pp == NULL)
2418 			continue;
2419 		x86_hm_enter(pp);
2420 
2421 		newpte = oldpte;
2422 		/*
2423 		 * We found a page table entry in the desired range,
2424 		 * figure out the new attributes.
2425 		 */
2426 		if (what == HAT_SET_ATTR || what == HAT_LOAD_ATTR) {
2427 			if ((attr & PROT_WRITE) &&
2428 			    !PTE_GET(oldpte, PT_WRITABLE))
2429 				newpte |= PT_WRITABLE;
2430 
2431 			if ((attr & HAT_NOSYNC) && !PTE_GET(oldpte, PT_NOSYNC))
2432 				newpte |= PT_NOSYNC;
2433 
2434 			if ((attr & PROT_EXEC) && PTE_GET(oldpte, mmu.pt_nx))
2435 				newpte &= ~mmu.pt_nx;
2436 		}
2437 
2438 		if (what == HAT_LOAD_ATTR) {
2439 			if (!(attr & PROT_WRITE) &&
2440 			    PTE_GET(oldpte, PT_WRITABLE))
2441 				newpte &= ~PT_WRITABLE;
2442 
2443 			if (!(attr & HAT_NOSYNC) && PTE_GET(oldpte, PT_NOSYNC))
2444 				newpte &= ~PT_NOSYNC;
2445 
2446 			if (!(attr & PROT_EXEC) && !PTE_GET(oldpte, mmu.pt_nx))
2447 				newpte |= mmu.pt_nx;
2448 		}
2449 
2450 		if (what == HAT_CLR_ATTR) {
2451 			if ((attr & PROT_WRITE) && PTE_GET(oldpte, PT_WRITABLE))
2452 				newpte &= ~PT_WRITABLE;
2453 
2454 			if ((attr & HAT_NOSYNC) && PTE_GET(oldpte, PT_NOSYNC))
2455 				newpte &= ~PT_NOSYNC;
2456 
2457 			if ((attr & PROT_EXEC) && !PTE_GET(oldpte, mmu.pt_nx))
2458 				newpte |= mmu.pt_nx;
2459 		}
2460 
2461 		/*
2462 		 * what about PROT_READ or others? this code only handles:
2463 		 * EXEC, WRITE, NOSYNC
2464 		 */
2465 
2466 		/*
2467 		 * If new PTE really changed, update the table.
2468 		 */
2469 		if (newpte != oldpte) {
2470 			entry = htable_va2entry(vaddr, ht);
2471 			oldpte = hati_update_pte(ht, entry, oldpte, newpte);
2472 			if (oldpte != 0) {
2473 				x86_hm_exit(pp);
2474 				goto try_again;
2475 			}
2476 		}
2477 		x86_hm_exit(pp);
2478 	}
2479 	if (ht)
2480 		htable_release(ht);
2481 }
2482 
2483 /*
2484  * Various wrappers for hat_updateattr()
2485  */
2486 void
2487 hat_setattr(hat_t *hat, caddr_t addr, size_t len, uint_t attr)
2488 {
2489 	ASSERT(hat == kas.a_hat || (uintptr_t)addr + len <= kernelbase);
2490 	hat_updateattr(hat, addr, len, attr, HAT_SET_ATTR);
2491 }
2492 
2493 void
2494 hat_clrattr(hat_t *hat, caddr_t addr, size_t len, uint_t attr)
2495 {
2496 	ASSERT(hat == kas.a_hat || (uintptr_t)addr + len <= kernelbase);
2497 	hat_updateattr(hat, addr, len, attr, HAT_CLR_ATTR);
2498 }
2499 
2500 void
2501 hat_chgattr(hat_t *hat, caddr_t addr, size_t len, uint_t attr)
2502 {
2503 	ASSERT(hat == kas.a_hat || (uintptr_t)addr + len <= kernelbase);
2504 	hat_updateattr(hat, addr, len, attr, HAT_LOAD_ATTR);
2505 }
2506 
2507 void
2508 hat_chgprot(hat_t *hat, caddr_t addr, size_t len, uint_t vprot)
2509 {
2510 	ASSERT(hat == kas.a_hat || (uintptr_t)addr + len <= kernelbase);
2511 	hat_updateattr(hat, addr, len, vprot & HAT_PROT_MASK, HAT_LOAD_ATTR);
2512 }
2513 
2514 /*ARGSUSED*/
2515 void
2516 hat_chgattr_pagedir(hat_t *hat, caddr_t addr, size_t len, uint_t attr)
2517 {
2518 	panic("hat_chgattr_pgdir() not supported - used by 80387 emulation");
2519 }
2520 
2521 /*
2522  * size_t hat_getpagesize(hat, addr)
2523  *	returns pagesize in bytes for <hat, addr>. returns -1 of there is
2524  *	no mapping. This is an advisory call.
2525  */
2526 ssize_t
2527 hat_getpagesize(hat_t *hat, caddr_t addr)
2528 {
2529 	uintptr_t	vaddr = ALIGN2PAGE(addr);
2530 	htable_t	*ht;
2531 	size_t		pagesize;
2532 
2533 	ASSERT(hat == kas.a_hat || vaddr < kernelbase);
2534 	if (IN_VA_HOLE(vaddr))
2535 		return (-1);
2536 	ht = htable_getpage(hat, vaddr, NULL);
2537 	if (ht == NULL)
2538 		return (-1);
2539 	pagesize = LEVEL_SIZE(ht->ht_level);
2540 	htable_release(ht);
2541 	return (pagesize);
2542 }
2543 
2544 
2545 
2546 /*
2547  * pfn_t hat_getpfnum(hat, addr)
2548  *	returns pfn for <hat, addr> or PFN_INVALID if mapping is invalid.
2549  */
2550 pfn_t
2551 hat_getpfnum(hat_t *hat, caddr_t addr)
2552 {
2553 	uintptr_t	vaddr = ALIGN2PAGE(addr);
2554 	htable_t	*ht;
2555 	uint_t		entry;
2556 	pfn_t		pfn = PFN_INVALID;
2557 
2558 	ASSERT(hat == kas.a_hat || vaddr < kernelbase);
2559 	if (khat_running == 0)
2560 		panic("hat_getpfnum(): called too early\n");
2561 
2562 	if (IN_VA_HOLE(vaddr))
2563 		return (PFN_INVALID);
2564 
2565 	/*
2566 	 * A very common use of hat_getpfnum() is from the DDI for kernel pages.
2567 	 * Use the kmap_ptes (which also covers the 32 bit heap) to speed
2568 	 * this up.
2569 	 */
2570 	if (mmu.kmap_addr <= vaddr && vaddr < mmu.kmap_eaddr) {
2571 		x86pte_t pte;
2572 		pgcnt_t pg_off;
2573 
2574 		pg_off = mmu_btop(vaddr - mmu.kmap_addr);
2575 		if (mmu.pae_hat) {
2576 			ATOMIC_LOAD64(mmu.kmap_ptes + pg_off, pte);
2577 		} else {
2578 			pte = ((x86pte32_t *)mmu.kmap_ptes)[pg_off];
2579 		}
2580 		if (!PTE_ISVALID(pte))
2581 			return (PFN_INVALID);
2582 		/*LINTED [use of constant 0 causes a silly lint warning] */
2583 		return (PTE2PFN(pte, 0));
2584 	}
2585 
2586 	ht = htable_getpage(hat, vaddr, &entry);
2587 	if (ht == NULL)
2588 		return (PFN_INVALID);
2589 	ASSERT(vaddr >= ht->ht_vaddr);
2590 	ASSERT(vaddr <= HTABLE_LAST_PAGE(ht));
2591 	pfn = PTE2PFN(x86pte_get(ht, entry), ht->ht_level);
2592 	if (ht->ht_level > 0)
2593 		pfn += mmu_btop(vaddr & LEVEL_OFFSET(ht->ht_level));
2594 	htable_release(ht);
2595 	return (pfn);
2596 }
2597 
2598 /*
2599  * hat_getkpfnum() is an obsolete DDI routine, and its use is discouraged.
2600  * Use hat_getpfnum(kas.a_hat, ...) instead.
2601  *
2602  * We'd like to return PFN_INVALID if the mappings have underlying page_t's
2603  * but can't right now due to the fact that some software has grown to use
2604  * this interface incorrectly. So for now when the interface is misused,
2605  * return a warning to the user that in the future it won't work in the
2606  * way they're abusing it, and carry on.
2607  *
2608  * Note that hat_getkpfnum() is never supported on amd64.
2609  */
2610 #if !defined(__amd64)
2611 pfn_t
2612 hat_getkpfnum(caddr_t addr)
2613 {
2614 	pfn_t	pfn;
2615 	int badcaller = 0;
2616 
2617 
2618 	if (khat_running == 0)
2619 		panic("hat_getkpfnum(): called too early\n");
2620 	if ((uintptr_t)addr < kernelbase)
2621 		return (PFN_INVALID);
2622 
2623 
2624 	if (segkpm && IS_KPM_ADDR(addr)) {
2625 		badcaller = 1;
2626 		pfn = hat_kpm_va2pfn(addr);
2627 	} else {
2628 		pfn = hat_getpfnum(kas.a_hat, addr);
2629 		badcaller = pf_is_memory(pfn);
2630 	}
2631 
2632 	if (badcaller)
2633 		hat_getkpfnum_badcall(caller());
2634 	return (pfn);
2635 }
2636 #endif /* __amd64 */
2637 
2638 /*
2639  * int hat_probe(hat, addr)
2640  *	return 0 if no valid mapping is present.  Faster version
2641  *	of hat_getattr in certain architectures.
2642  */
2643 int
2644 hat_probe(hat_t *hat, caddr_t addr)
2645 {
2646 	uintptr_t	vaddr = ALIGN2PAGE(addr);
2647 	uint_t		entry;
2648 	htable_t	*ht;
2649 	pgcnt_t		pg_off;
2650 
2651 	ASSERT(hat == kas.a_hat || vaddr < kernelbase);
2652 	ASSERT(hat == kas.a_hat ||
2653 	    AS_LOCK_HELD(hat->hat_as, &hat->hat_as->a_lock));
2654 	if (IN_VA_HOLE(vaddr))
2655 		return (0);
2656 
2657 	/*
2658 	 * Most common use of hat_probe is from segmap. We special case it
2659 	 * for performance.
2660 	 */
2661 	if (mmu.kmap_addr <= vaddr && vaddr < mmu.kmap_eaddr) {
2662 		pg_off = mmu_btop(vaddr - mmu.kmap_addr);
2663 		if (mmu.pae_hat)
2664 			return (PTE_ISVALID(mmu.kmap_ptes[pg_off]));
2665 		else
2666 			return (PTE_ISVALID(
2667 			    ((x86pte32_t *)mmu.kmap_ptes)[pg_off]));
2668 	}
2669 
2670 	ht = htable_getpage(hat, vaddr, &entry);
2671 	if (ht == NULL)
2672 		return (0);
2673 	htable_release(ht);
2674 	return (1);
2675 }
2676 
2677 /*
2678  * Simple implementation of ISM. hat_share() is just like hat_memload_array(),
2679  * except that we use the ism_hat's existing mappings to determine the pages
2680  * and protections to use for this hat. In case we find a properly aligned
2681  * and sized pagetable of 4K mappings, we will attempt to share the pagetable
2682  * itself.
2683  */
2684 /*ARGSUSED*/
2685 int
2686 hat_share(
2687 	hat_t		*hat,
2688 	caddr_t		addr,
2689 	hat_t		*ism_hat,
2690 	caddr_t		src_addr,
2691 	size_t		len,	/* almost useless value, see below.. */
2692 	uint_t		ismszc)
2693 {
2694 	uintptr_t	vaddr_start = (uintptr_t)addr;
2695 	uintptr_t	vaddr;
2696 	uintptr_t	pt_vaddr;
2697 	uintptr_t	eaddr = vaddr_start + len;
2698 	uintptr_t	ism_addr_start = (uintptr_t)src_addr;
2699 	uintptr_t	ism_addr = ism_addr_start;
2700 	uintptr_t	e_ism_addr = ism_addr + len;
2701 	htable_t	*ism_ht = NULL;
2702 	htable_t	*ht;
2703 	x86pte_t	pte;
2704 	page_t		*pp;
2705 	pfn_t		pfn;
2706 	level_t		l;
2707 	pgcnt_t		pgcnt;
2708 	uint_t		prot;
2709 	uint_t		valid_cnt;
2710 
2711 	/*
2712 	 * We might be asked to share an empty DISM hat by as_dup()
2713 	 */
2714 	ASSERT(hat != kas.a_hat);
2715 	ASSERT(eaddr <= kernelbase);
2716 	if (!(ism_hat->hat_flags & HAT_SHARED)) {
2717 		ASSERT(hat_get_mapped_size(ism_hat) == 0);
2718 		return (0);
2719 	}
2720 
2721 	/*
2722 	 * The SPT segment driver often passes us a size larger than there are
2723 	 * valid mappings. That's because it rounds the segment size up to a
2724 	 * large pagesize, even if the actual memory mapped by ism_hat is less.
2725 	 */
2726 	HATIN(hat_share, hat, addr, len);
2727 	ASSERT(IS_PAGEALIGNED(vaddr_start));
2728 	ASSERT(IS_PAGEALIGNED(ism_addr_start));
2729 	ASSERT(ism_hat->hat_flags & HAT_SHARED);
2730 	while (ism_addr < e_ism_addr) {
2731 		/*
2732 		 * use htable_walk to get the next valid ISM mapping
2733 		 */
2734 		pte = htable_walk(ism_hat, &ism_ht, &ism_addr, e_ism_addr);
2735 		if (ism_ht == NULL)
2736 			break;
2737 
2738 		/*
2739 		 * Find the largest page size we can use, based on the
2740 		 * ISM mapping size, our address alignment and the remaining
2741 		 * map length.
2742 		 */
2743 		vaddr = vaddr_start + (ism_addr - ism_addr_start);
2744 		for (l = ism_ht->ht_level; l > 0; --l) {
2745 			if (LEVEL_SIZE(l) <= eaddr - vaddr &&
2746 			    (vaddr & LEVEL_OFFSET(l)) == 0)
2747 				break;
2748 		}
2749 
2750 		/*
2751 		 * attempt to share the pagetable
2752 		 *
2753 		 * - only 4K pagetables are shared (ie. level == 0)
2754 		 * - the hat_share() length must cover the whole pagetable
2755 		 * - the shared address must align at level 1
2756 		 * - a shared PTE for this address already exists OR
2757 		 * - no page table for this address exists yet
2758 		 */
2759 		pt_vaddr =
2760 		    vaddr_start + (ism_ht->ht_vaddr - ism_addr_start);
2761 		if (ism_ht->ht_level == 0 &&
2762 		    ism_ht->ht_vaddr + LEVEL_SIZE(1) <= e_ism_addr &&
2763 		    (pt_vaddr & LEVEL_OFFSET(1)) == 0) {
2764 
2765 			ht = htable_lookup(hat, pt_vaddr, 0);
2766 			if (ht == NULL)
2767 				ht = htable_create(hat, pt_vaddr, 0, ism_ht);
2768 
2769 			if (ht->ht_level > 0 ||
2770 			    !(ht->ht_flags & HTABLE_SHARED_PFN)) {
2771 
2772 				htable_release(ht);
2773 
2774 			} else {
2775 
2776 				/*
2777 				 * share the page table
2778 				 */
2779 				ASSERT(ht->ht_level == 0);
2780 				ASSERT(ht->ht_shares == ism_ht);
2781 				valid_cnt = ism_ht->ht_valid_cnt;
2782 				atomic_add_long(&hat->hat_pages_mapped[0],
2783 				    valid_cnt - ht->ht_valid_cnt);
2784 				ht->ht_valid_cnt = valid_cnt;
2785 				htable_release(ht);
2786 				ism_addr = ism_ht->ht_vaddr + LEVEL_SIZE(1);
2787 				htable_release(ism_ht);
2788 				ism_ht = NULL;
2789 				continue;
2790 			}
2791 		}
2792 
2793 		/*
2794 		 * Unable to share the page table. Instead we will
2795 		 * create new mappings from the values in the ISM mappings.
2796 		 *
2797 		 * The ISM mapping might be larger than the share area,
2798 		 * be careful to trunctate it if needed.
2799 		 */
2800 		if (eaddr - vaddr >= LEVEL_SIZE(ism_ht->ht_level)) {
2801 			pgcnt = mmu_btop(LEVEL_SIZE(ism_ht->ht_level));
2802 		} else {
2803 			pgcnt = mmu_btop(eaddr - vaddr);
2804 			l = 0;
2805 		}
2806 
2807 		pfn = PTE2PFN(pte, ism_ht->ht_level);
2808 		ASSERT(pfn != PFN_INVALID);
2809 		while (pgcnt > 0) {
2810 			/*
2811 			 * Make a new pte for the PFN for this level.
2812 			 * Copy protections for the pte from the ISM pte.
2813 			 */
2814 			pp = page_numtopp_nolock(pfn);
2815 			ASSERT(pp != NULL);
2816 
2817 			prot = PROT_USER | PROT_READ | HAT_UNORDERED_OK;
2818 			if (PTE_GET(pte, PT_WRITABLE))
2819 				prot |= PROT_WRITE;
2820 			if (!PTE_GET(pte, PT_NX))
2821 				prot |= PROT_EXEC;
2822 
2823 			/*
2824 			 * XX64 -- can shm ever be written to swap?
2825 			 * if not we could use HAT_NOSYNC here.
2826 			 */
2827 			hati_load_common(hat, vaddr, pp, prot,
2828 			    HAT_LOAD, l, pfn);
2829 
2830 			vaddr += LEVEL_SIZE(l);
2831 			ism_addr += LEVEL_SIZE(l);
2832 			pfn += mmu_btop(LEVEL_SIZE(l));
2833 			pgcnt -= mmu_btop(LEVEL_SIZE(l));
2834 		}
2835 	}
2836 	if (ism_ht != NULL)
2837 		htable_release(ism_ht);
2838 
2839 	HATOUT(hat_share, hat, addr);
2840 	return (0);
2841 }
2842 
2843 
2844 /*
2845  * hat_unshare() is similar to hat_unload_callback(), but
2846  * we have to look for empty shared pagetables. Note that
2847  * hat_unshare() is always invoked against an entire segment.
2848  */
2849 /*ARGSUSED*/
2850 void
2851 hat_unshare(hat_t *hat, caddr_t addr, size_t len, uint_t ismszc)
2852 {
2853 	uintptr_t	vaddr = (uintptr_t)addr;
2854 	uintptr_t	eaddr = vaddr + len;
2855 	htable_t	*ht = NULL;
2856 	uint_t		need_demaps = 0;
2857 
2858 	ASSERT(hat != kas.a_hat);
2859 	ASSERT(eaddr <= kernelbase);
2860 	HATIN(hat_unshare, hat, addr, len);
2861 	ASSERT(IS_PAGEALIGNED(vaddr));
2862 	ASSERT(IS_PAGEALIGNED(eaddr));
2863 
2864 	/*
2865 	 * First go through and remove any shared pagetables.
2866 	 *
2867 	 * Note that it's ok to delay the demap until the entire range is
2868 	 * finished, because if hat_pageunload() were to unload a shared
2869 	 * pagetable page, its hat_demap() will do a global user TLB invalidate.
2870 	 */
2871 	while (vaddr < eaddr) {
2872 		ASSERT(!IN_VA_HOLE(vaddr));
2873 		/*
2874 		 * find the pagetable that would map the current address
2875 		 */
2876 		ht = htable_lookup(hat, vaddr, 0);
2877 		if (ht != NULL) {
2878 			if (ht->ht_flags & HTABLE_SHARED_PFN) {
2879 				/*
2880 				 * clear mapped pages count, set valid_cnt to 0
2881 				 * and let htable_release() finish the job
2882 				 */
2883 				atomic_add_long(&hat->hat_pages_mapped[0],
2884 				    -ht->ht_valid_cnt);
2885 				ht->ht_valid_cnt = 0;
2886 				need_demaps = 1;
2887 			}
2888 			htable_release(ht);
2889 		}
2890 		vaddr = (vaddr & LEVEL_MASK(1)) + LEVEL_SIZE(1);
2891 	}
2892 
2893 	/*
2894 	 * flush the TLBs - since we're probably dealing with MANY mappings
2895 	 * we do just one CR3 reload.
2896 	 */
2897 	if (!(hat->hat_flags & HAT_FREEING) && need_demaps)
2898 		hat_demap(hat, DEMAP_ALL_ADDR);
2899 
2900 	/*
2901 	 * Now go back and clean up any unaligned mappings that
2902 	 * couldn't share pagetables.
2903 	 */
2904 	hat_unload(hat, addr, len, HAT_UNLOAD_UNMAP);
2905 
2906 	HATOUT(hat_unshare, hat, addr);
2907 }
2908 
2909 
2910 /*
2911  * hat_reserve() does nothing
2912  */
2913 /*ARGSUSED*/
2914 void
2915 hat_reserve(struct as *as, caddr_t addr, size_t len)
2916 {
2917 }
2918 
2919 
2920 /*
2921  * Called when all mappings to a page should have write permission removed.
2922  * Mostly stolem from hat_pagesync()
2923  */
2924 static void
2925 hati_page_clrwrt(struct page *pp)
2926 {
2927 	hment_t		*hm = NULL;
2928 	htable_t	*ht;
2929 	uint_t		entry;
2930 	x86pte_t	old;
2931 	x86pte_t	new;
2932 	uint_t		pszc = 0;
2933 
2934 next_size:
2935 	/*
2936 	 * walk thru the mapping list clearing write permission
2937 	 */
2938 	x86_hm_enter(pp);
2939 	while ((hm = hment_walk(pp, &ht, &entry, hm)) != NULL) {
2940 		if (ht->ht_level < pszc)
2941 			continue;
2942 		old = x86pte_get(ht, entry);
2943 
2944 		for (;;) {
2945 			/*
2946 			 * Is this mapping of interest?
2947 			 */
2948 			if (PTE2PFN(old, ht->ht_level) != pp->p_pagenum ||
2949 			    PTE_GET(old, PT_WRITABLE) == 0)
2950 				break;
2951 
2952 			/*
2953 			 * Clear ref/mod writable bits. This requires cross
2954 			 * calls to ensure any executing TLBs see cleared bits.
2955 			 */
2956 			new = old;
2957 			PTE_CLR(new, PT_REF | PT_MOD | PT_WRITABLE);
2958 			old = hati_update_pte(ht, entry, old, new);
2959 			if (old != 0)
2960 				continue;
2961 
2962 			break;
2963 		}
2964 	}
2965 	x86_hm_exit(pp);
2966 	while (pszc < pp->p_szc) {
2967 		page_t *tpp;
2968 		pszc++;
2969 		tpp = PP_GROUPLEADER(pp, pszc);
2970 		if (pp != tpp) {
2971 			pp = tpp;
2972 			goto next_size;
2973 		}
2974 	}
2975 }
2976 
2977 /*
2978  * void hat_page_setattr(pp, flag)
2979  * void hat_page_clrattr(pp, flag)
2980  *	used to set/clr ref/mod bits.
2981  */
2982 void
2983 hat_page_setattr(struct page *pp, uint_t flag)
2984 {
2985 	vnode_t		*vp = pp->p_vnode;
2986 	kmutex_t	*vphm = NULL;
2987 	page_t		**listp;
2988 
2989 	if (PP_GETRM(pp, flag) == flag)
2990 		return;
2991 
2992 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
2993 		vphm = page_vnode_mutex(vp);
2994 		mutex_enter(vphm);
2995 	}
2996 
2997 	PP_SETRM(pp, flag);
2998 
2999 	if (vphm != NULL) {
3000 
3001 		/*
3002 		 * Some File Systems examine v_pages for NULL w/o
3003 		 * grabbing the vphm mutex. Must not let it become NULL when
3004 		 * pp is the only page on the list.
3005 		 */
3006 		if (pp->p_vpnext != pp) {
3007 			page_vpsub(&vp->v_pages, pp);
3008 			if (vp->v_pages != NULL)
3009 				listp = &vp->v_pages->p_vpprev->p_vpnext;
3010 			else
3011 				listp = &vp->v_pages;
3012 			page_vpadd(listp, pp);
3013 		}
3014 		mutex_exit(vphm);
3015 	}
3016 }
3017 
3018 void
3019 hat_page_clrattr(struct page *pp, uint_t flag)
3020 {
3021 	vnode_t		*vp = pp->p_vnode;
3022 	kmutex_t	*vphm = NULL;
3023 	ASSERT(!(flag & ~(P_MOD | P_REF | P_RO)));
3024 
3025 	/*
3026 	 * for vnode with a sorted v_pages list, we need to change
3027 	 * the attributes and the v_pages list together under page_vnode_mutex.
3028 	 */
3029 	if ((flag & P_MOD) != 0 && vp != NULL && IS_VMODSORT(vp)) {
3030 		vphm = page_vnode_mutex(vp);
3031 		mutex_enter(vphm);
3032 	}
3033 
3034 	PP_CLRRM(pp, flag);
3035 
3036 	if (vphm != NULL) {
3037 
3038 		/*
3039 		 * Some File Systems examine v_pages for NULL w/o
3040 		 * grabbing the vphm mutex. Must not let it become NULL when
3041 		 * pp is the only page on the list.
3042 		 */
3043 		if (pp->p_vpnext != pp) {
3044 			page_vpsub(&vp->v_pages, pp);
3045 			page_vpadd(&vp->v_pages, pp);
3046 		}
3047 		mutex_exit(vphm);
3048 
3049 		/*
3050 		 * VMODSORT works by removing write permissions and getting
3051 		 * a fault when a page is made dirty. At this point
3052 		 * we need to remove write permission from all mappings
3053 		 * to this page.
3054 		 */
3055 		hati_page_clrwrt(pp);
3056 	}
3057 }
3058 
3059 /*
3060  *	If flag is specified, returns 0 if attribute is disabled
3061  *	and non zero if enabled.  If flag specifes multiple attributs
3062  *	then returns 0 if ALL atriibutes are disabled.  This is an advisory
3063  *	call.
3064  */
3065 uint_t
3066 hat_page_getattr(struct page *pp, uint_t flag)
3067 {
3068 	return (PP_GETRM(pp, flag));
3069 }
3070 
3071 
3072 /*
3073  * common code used by hat_pageunload() and hment_steal()
3074  */
3075 hment_t *
3076 hati_page_unmap(page_t *pp, htable_t *ht, uint_t entry)
3077 {
3078 	x86pte_t old_pte;
3079 	pfn_t pfn = pp->p_pagenum;
3080 	hment_t *hm;
3081 
3082 	/*
3083 	 * We need to acquire a hold on the htable in order to
3084 	 * do the invalidate. We know the htable must exist, since
3085 	 * unmap's don't release the htable until after removing any
3086 	 * hment. Having x86_hm_enter() keeps that from proceeding.
3087 	 */
3088 	htable_acquire(ht);
3089 
3090 	/*
3091 	 * Invalidate the PTE and remove the hment.
3092 	 */
3093 	old_pte = x86pte_invalidate_pfn(ht, entry, pfn, NULL);
3094 	if (PTE2PFN(old_pte, ht->ht_level) != pfn) {
3095 		panic("x86pte_invalidate_pfn() failure found PTE = " FMT_PTE
3096 		    " pfn being unmapped is %lx ht=0x%lx entry=0x%x",
3097 		    old_pte, pfn, (uintptr_t)ht, entry);
3098 	}
3099 
3100 	/*
3101 	 * Clean up all the htable information for this mapping
3102 	 */
3103 	ASSERT(ht->ht_valid_cnt > 0);
3104 	HTABLE_DEC(ht->ht_valid_cnt);
3105 	PGCNT_DEC(ht->ht_hat, ht->ht_level);
3106 
3107 	/*
3108 	 * sync ref/mod bits to the page_t
3109 	 */
3110 	if (PTE_GET(old_pte, PT_NOSYNC) == 0)
3111 		hati_sync_pte_to_page(pp, old_pte, ht->ht_level);
3112 
3113 	/*
3114 	 * Remove the mapping list entry for this page.
3115 	 */
3116 	hm = hment_remove(pp, ht, entry);
3117 
3118 	/*
3119 	 * drop the mapping list lock so that we might free the
3120 	 * hment and htable.
3121 	 */
3122 	x86_hm_exit(pp);
3123 	htable_release(ht);
3124 	return (hm);
3125 }
3126 
3127 /*
3128  * Unload all translations to a page. If the page is a subpage of a large
3129  * page, the large page mappings are also removed.
3130  *
3131  * The forceflags are unused.
3132  */
3133 
3134 /*ARGSUSED*/
3135 static int
3136 hati_pageunload(struct page *pp, uint_t pg_szcd, uint_t forceflag)
3137 {
3138 	page_t		*cur_pp = pp;
3139 	hment_t		*hm;
3140 	hment_t		*prev;
3141 	htable_t	*ht;
3142 	uint_t		entry;
3143 	level_t		level;
3144 
3145 	/*
3146 	 * The loop with next_size handles pages with multiple pagesize mappings
3147 	 */
3148 next_size:
3149 	for (;;) {
3150 
3151 		/*
3152 		 * Get a mapping list entry
3153 		 */
3154 		x86_hm_enter(cur_pp);
3155 		for (prev = NULL; ; prev = hm) {
3156 			hm = hment_walk(cur_pp, &ht, &entry, prev);
3157 			if (hm == NULL) {
3158 				x86_hm_exit(cur_pp);
3159 
3160 				/*
3161 				 * If not part of a larger page, we're done.
3162 				 */
3163 				if (cur_pp->p_szc <= pg_szcd)
3164 					return (0);
3165 
3166 				/*
3167 				 * Else check the next larger page size.
3168 				 * hat_page_demote() may decrease p_szc
3169 				 * but that's ok we'll just take an extra
3170 				 * trip discover there're no larger mappings
3171 				 * and return.
3172 				 */
3173 				++pg_szcd;
3174 				cur_pp = PP_GROUPLEADER(cur_pp, pg_szcd);
3175 				goto next_size;
3176 			}
3177 
3178 			/*
3179 			 * If this mapping size matches, remove it.
3180 			 */
3181 			level = ht->ht_level;
3182 			if (level == pg_szcd)
3183 				break;
3184 		}
3185 
3186 		/*
3187 		 * Remove the mapping list entry for this page.
3188 		 * Note this does the x86_hm_exit() for us.
3189 		 */
3190 		hm = hati_page_unmap(cur_pp, ht, entry);
3191 		if (hm != NULL)
3192 			hment_free(hm);
3193 	}
3194 }
3195 
3196 int
3197 hat_pageunload(struct page *pp, uint_t forceflag)
3198 {
3199 	ASSERT(PAGE_EXCL(pp));
3200 	return (hati_pageunload(pp, 0, forceflag));
3201 }
3202 
3203 /*
3204  * Unload all large mappings to pp and reduce by 1 p_szc field of every large
3205  * page level that included pp.
3206  *
3207  * pp must be locked EXCL. Even though no other constituent pages are locked
3208  * it's legal to unload large mappings to pp because all constituent pages of
3209  * large locked mappings have to be locked SHARED.  therefore if we have EXCL
3210  * lock on one of constituent pages none of the large mappings to pp are
3211  * locked.
3212  *
3213  * Change (always decrease) p_szc field starting from the last constituent
3214  * page and ending with root constituent page so that root's pszc always shows
3215  * the area where hat_page_demote() may be active.
3216  *
3217  * This mechanism is only used for file system pages where it's not always
3218  * possible to get EXCL locks on all constituent pages to demote the size code
3219  * (as is done for anonymous or kernel large pages).
3220  */
3221 void
3222 hat_page_demote(page_t *pp)
3223 {
3224 	uint_t		pszc;
3225 	uint_t		rszc;
3226 	uint_t		szc;
3227 	page_t		*rootpp;
3228 	page_t		*firstpp;
3229 	page_t		*lastpp;
3230 	pgcnt_t		pgcnt;
3231 
3232 	ASSERT(PAGE_EXCL(pp));
3233 	ASSERT(!PP_ISFREE(pp));
3234 	ASSERT(page_szc_lock_assert(pp));
3235 
3236 	if (pp->p_szc == 0)
3237 		return;
3238 
3239 	rootpp = PP_GROUPLEADER(pp, 1);
3240 	(void) hati_pageunload(rootpp, 1, HAT_FORCE_PGUNLOAD);
3241 
3242 	/*
3243 	 * all large mappings to pp are gone
3244 	 * and no new can be setup since pp is locked exclusively.
3245 	 *
3246 	 * Lock the root to make sure there's only one hat_page_demote()
3247 	 * outstanding within the area of this root's pszc.
3248 	 *
3249 	 * Second potential hat_page_demote() is already eliminated by upper
3250 	 * VM layer via page_szc_lock() but we don't rely on it and use our
3251 	 * own locking (so that upper layer locking can be changed without
3252 	 * assumptions that hat depends on upper layer VM to prevent multiple
3253 	 * hat_page_demote() to be issued simultaneously to the same large
3254 	 * page).
3255 	 */
3256 again:
3257 	pszc = pp->p_szc;
3258 	if (pszc == 0)
3259 		return;
3260 	rootpp = PP_GROUPLEADER(pp, pszc);
3261 	x86_hm_enter(rootpp);
3262 	/*
3263 	 * If root's p_szc is different from pszc we raced with another
3264 	 * hat_page_demote().  Drop the lock and try to find the root again.
3265 	 * If root's p_szc is greater than pszc previous hat_page_demote() is
3266 	 * not done yet.  Take and release mlist lock of root's root to wait
3267 	 * for previous hat_page_demote() to complete.
3268 	 */
3269 	if ((rszc = rootpp->p_szc) != pszc) {
3270 		x86_hm_exit(rootpp);
3271 		if (rszc > pszc) {
3272 			/* p_szc of a locked non free page can't increase */
3273 			ASSERT(pp != rootpp);
3274 
3275 			rootpp = PP_GROUPLEADER(rootpp, rszc);
3276 			x86_hm_enter(rootpp);
3277 			x86_hm_exit(rootpp);
3278 		}
3279 		goto again;
3280 	}
3281 	ASSERT(pp->p_szc == pszc);
3282 
3283 	/*
3284 	 * Decrement by 1 p_szc of every constituent page of a region that
3285 	 * covered pp. For example if original szc is 3 it gets changed to 2
3286 	 * everywhere except in region 2 that covered pp. Region 2 that
3287 	 * covered pp gets demoted to 1 everywhere except in region 1 that
3288 	 * covered pp. The region 1 that covered pp is demoted to region
3289 	 * 0. It's done this way because from region 3 we removed level 3
3290 	 * mappings, from region 2 that covered pp we removed level 2 mappings
3291 	 * and from region 1 that covered pp we removed level 1 mappings.  All
3292 	 * changes are done from from high pfn's to low pfn's so that roots
3293 	 * are changed last allowing one to know the largest region where
3294 	 * hat_page_demote() is stil active by only looking at the root page.
3295 	 *
3296 	 * This algorithm is implemented in 2 while loops. First loop changes
3297 	 * p_szc of pages to the right of pp's level 1 region and second
3298 	 * loop changes p_szc of pages of level 1 region that covers pp
3299 	 * and all pages to the left of level 1 region that covers pp.
3300 	 * In the first loop p_szc keeps dropping with every iteration
3301 	 * and in the second loop it keeps increasing with every iteration.
3302 	 *
3303 	 * First loop description: Demote pages to the right of pp outside of
3304 	 * level 1 region that covers pp.  In every iteration of the while
3305 	 * loop below find the last page of szc region and the first page of
3306 	 * (szc - 1) region that is immediately to the right of (szc - 1)
3307 	 * region that covers pp.  From last such page to first such page
3308 	 * change every page's szc to szc - 1. Decrement szc and continue
3309 	 * looping until szc is 1. If pp belongs to the last (szc - 1) region
3310 	 * of szc region skip to the next iteration.
3311 	 */
3312 	szc = pszc;
3313 	while (szc > 1) {
3314 		lastpp = PP_GROUPLEADER(pp, szc);
3315 		pgcnt = page_get_pagecnt(szc);
3316 		lastpp += pgcnt - 1;
3317 		firstpp = PP_GROUPLEADER(pp, (szc - 1));
3318 		pgcnt = page_get_pagecnt(szc - 1);
3319 		if (lastpp - firstpp < pgcnt) {
3320 			szc--;
3321 			continue;
3322 		}
3323 		firstpp += pgcnt;
3324 		while (lastpp != firstpp) {
3325 			ASSERT(lastpp->p_szc == pszc);
3326 			lastpp->p_szc = szc - 1;
3327 			lastpp--;
3328 		}
3329 		firstpp->p_szc = szc - 1;
3330 		szc--;
3331 	}
3332 
3333 	/*
3334 	 * Second loop description:
3335 	 * First iteration changes p_szc to 0 of every
3336 	 * page of level 1 region that covers pp.
3337 	 * Subsequent iterations find last page of szc region
3338 	 * immediately to the left of szc region that covered pp
3339 	 * and first page of (szc + 1) region that covers pp.
3340 	 * From last to first page change p_szc of every page to szc.
3341 	 * Increment szc and continue looping until szc is pszc.
3342 	 * If pp belongs to the fist szc region of (szc + 1) region
3343 	 * skip to the next iteration.
3344 	 *
3345 	 */
3346 	szc = 0;
3347 	while (szc < pszc) {
3348 		firstpp = PP_GROUPLEADER(pp, (szc + 1));
3349 		if (szc == 0) {
3350 			pgcnt = page_get_pagecnt(1);
3351 			lastpp = firstpp + (pgcnt - 1);
3352 		} else {
3353 			lastpp = PP_GROUPLEADER(pp, szc);
3354 			if (firstpp == lastpp) {
3355 				szc++;
3356 				continue;
3357 			}
3358 			lastpp--;
3359 			pgcnt = page_get_pagecnt(szc);
3360 		}
3361 		while (lastpp != firstpp) {
3362 			ASSERT(lastpp->p_szc == pszc);
3363 			lastpp->p_szc = szc;
3364 			lastpp--;
3365 		}
3366 		firstpp->p_szc = szc;
3367 		if (firstpp == rootpp)
3368 			break;
3369 		szc++;
3370 	}
3371 	x86_hm_exit(rootpp);
3372 }
3373 
3374 /*
3375  * get hw stats from hardware into page struct and reset hw stats
3376  * returns attributes of page
3377  * Flags for hat_pagesync, hat_getstat, hat_sync
3378  *
3379  * define	HAT_SYNC_ZERORM		0x01
3380  *
3381  * Additional flags for hat_pagesync
3382  *
3383  * define	HAT_SYNC_STOPON_REF	0x02
3384  * define	HAT_SYNC_STOPON_MOD	0x04
3385  * define	HAT_SYNC_STOPON_RM	0x06
3386  * define	HAT_SYNC_STOPON_SHARED	0x08
3387  */
3388 uint_t
3389 hat_pagesync(struct page *pp, uint_t flags)
3390 {
3391 	hment_t		*hm = NULL;
3392 	htable_t	*ht;
3393 	uint_t		entry;
3394 	x86pte_t	old, save_old;
3395 	x86pte_t	new;
3396 	uchar_t		nrmbits = P_REF|P_MOD|P_RO;
3397 	extern ulong_t	po_share;
3398 	page_t		*save_pp = pp;
3399 	uint_t		pszc = 0;
3400 
3401 	ASSERT(PAGE_LOCKED(pp) || panicstr);
3402 
3403 	if (PP_ISRO(pp) && (flags & HAT_SYNC_STOPON_MOD))
3404 		return (pp->p_nrm & nrmbits);
3405 
3406 	if ((flags & HAT_SYNC_ZERORM) == 0) {
3407 
3408 		if ((flags & HAT_SYNC_STOPON_REF) != 0 && PP_ISREF(pp))
3409 			return (pp->p_nrm & nrmbits);
3410 
3411 		if ((flags & HAT_SYNC_STOPON_MOD) != 0 && PP_ISMOD(pp))
3412 			return (pp->p_nrm & nrmbits);
3413 
3414 		if ((flags & HAT_SYNC_STOPON_SHARED) != 0 &&
3415 		    hat_page_getshare(pp) > po_share) {
3416 			if (PP_ISRO(pp))
3417 				PP_SETREF(pp);
3418 			return (pp->p_nrm & nrmbits);
3419 		}
3420 	}
3421 
3422 next_size:
3423 	/*
3424 	 * walk thru the mapping list syncing (and clearing) ref/mod bits.
3425 	 */
3426 	x86_hm_enter(pp);
3427 	while ((hm = hment_walk(pp, &ht, &entry, hm)) != NULL) {
3428 		if (ht->ht_level < pszc)
3429 			continue;
3430 		old = x86pte_get(ht, entry);
3431 try_again:
3432 
3433 		ASSERT(PTE2PFN(old, ht->ht_level) == pp->p_pagenum);
3434 
3435 		if (PTE_GET(old, PT_REF | PT_MOD) == 0)
3436 			continue;
3437 
3438 		save_old = old;
3439 		if ((flags & HAT_SYNC_ZERORM) != 0) {
3440 
3441 			/*
3442 			 * Need to clear ref or mod bits. Need to demap
3443 			 * to make sure any executing TLBs see cleared bits.
3444 			 */
3445 			new = old;
3446 			PTE_CLR(new, PT_REF | PT_MOD);
3447 			old = hati_update_pte(ht, entry, old, new);
3448 			if (old != 0)
3449 				goto try_again;
3450 
3451 			old = save_old;
3452 		}
3453 
3454 		/*
3455 		 * Sync the PTE
3456 		 */
3457 		if (!(flags & HAT_SYNC_ZERORM) && PTE_GET(old, PT_NOSYNC) == 0)
3458 			hati_sync_pte_to_page(pp, old, ht->ht_level);
3459 
3460 		/*
3461 		 * can stop short if we found a ref'd or mod'd page
3462 		 */
3463 		if ((flags & HAT_SYNC_STOPON_MOD) && PP_ISMOD(save_pp) ||
3464 		    (flags & HAT_SYNC_STOPON_REF) && PP_ISREF(save_pp)) {
3465 			x86_hm_exit(pp);
3466 			return (save_pp->p_nrm & nrmbits);
3467 		}
3468 	}
3469 	x86_hm_exit(pp);
3470 	while (pszc < pp->p_szc) {
3471 		page_t *tpp;
3472 		pszc++;
3473 		tpp = PP_GROUPLEADER(pp, pszc);
3474 		if (pp != tpp) {
3475 			pp = tpp;
3476 			goto next_size;
3477 		}
3478 	}
3479 	return (save_pp->p_nrm & nrmbits);
3480 }
3481 
3482 /*
3483  * returns approx number of mappings to this pp.  A return of 0 implies
3484  * there are no mappings to the page.
3485  */
3486 ulong_t
3487 hat_page_getshare(page_t *pp)
3488 {
3489 	uint_t cnt;
3490 	cnt = hment_mapcnt(pp);
3491 	return (cnt);
3492 }
3493 
3494 /*
3495  * hat_softlock isn't supported anymore
3496  */
3497 /*ARGSUSED*/
3498 faultcode_t
3499 hat_softlock(
3500 	hat_t *hat,
3501 	caddr_t addr,
3502 	size_t *len,
3503 	struct page **page_array,
3504 	uint_t flags)
3505 {
3506 	return (FC_NOSUPPORT);
3507 }
3508 
3509 
3510 
3511 /*
3512  * Routine to expose supported HAT features to platform independent code.
3513  */
3514 /*ARGSUSED*/
3515 int
3516 hat_supported(enum hat_features feature, void *arg)
3517 {
3518 	switch (feature) {
3519 
3520 	case HAT_SHARED_PT:	/* this is really ISM */
3521 		return (1);
3522 
3523 	case HAT_DYNAMIC_ISM_UNMAP:
3524 		return (0);
3525 
3526 	case HAT_VMODSORT:
3527 		return (1);
3528 
3529 	default:
3530 		panic("hat_supported() - unknown feature");
3531 	}
3532 	return (0);
3533 }
3534 
3535 /*
3536  * Called when a thread is exiting and has been switched to the kernel AS
3537  */
3538 void
3539 hat_thread_exit(kthread_t *thd)
3540 {
3541 	ASSERT(thd->t_procp->p_as == &kas);
3542 	hat_switch(thd->t_procp->p_as->a_hat);
3543 }
3544 
3545 /*
3546  * Setup the given brand new hat structure as the new HAT on this cpu's mmu.
3547  */
3548 /*ARGSUSED*/
3549 void
3550 hat_setup(hat_t *hat, int flags)
3551 {
3552 	kpreempt_disable();
3553 
3554 	hat_switch(hat);
3555 
3556 	kpreempt_enable();
3557 }
3558 
3559 /*
3560  * Prepare for a CPU private mapping for the given address.
3561  *
3562  * The address can only be used from a single CPU and can be remapped
3563  * using hat_mempte_remap().  Return the address of the PTE.
3564  *
3565  * We do the htable_create() if necessary and increment the valid count so
3566  * the htable can't disappear.  We also hat_devload() the page table into
3567  * kernel so that the PTE is quickly accessed.
3568  */
3569 void *
3570 hat_mempte_kern_setup(caddr_t addr, void *pt)
3571 {
3572 	uintptr_t	va = (uintptr_t)addr;
3573 	htable_t	*ht;
3574 	uint_t		entry;
3575 	x86pte_t	oldpte;
3576 	caddr_t		p = (caddr_t)pt;
3577 
3578 	ASSERT(IS_PAGEALIGNED(va));
3579 	ASSERT(!IN_VA_HOLE(va));
3580 	ht = htable_getpte(kas.a_hat, va, &entry, &oldpte, 0);
3581 	if (ht == NULL) {
3582 		/*
3583 		 * Note that we don't need a hat_reserves_exit() check
3584 		 * for this htable_create(), since that'll be done by the
3585 		 * hat_devload() just below.
3586 		 */
3587 		ht = htable_create(kas.a_hat, va, 0, NULL);
3588 		entry = htable_va2entry(va, ht);
3589 		ASSERT(ht->ht_level == 0);
3590 		oldpte = x86pte_get(ht, entry);
3591 	}
3592 	if (PTE_ISVALID(oldpte))
3593 		panic("hat_mempte_setup(): address already mapped"
3594 		    "ht=%p, entry=%d, pte=" FMT_PTE, ht, entry, oldpte);
3595 
3596 	/*
3597 	 * increment ht_valid_cnt so that the pagetable can't disappear
3598 	 */
3599 	HTABLE_INC(ht->ht_valid_cnt);
3600 
3601 	/*
3602 	 * now we need to map the page holding the pagetable for va into
3603 	 * the kernel's address space.
3604 	 */
3605 	hat_devload(kas.a_hat, p, MMU_PAGESIZE, ht->ht_pfn,
3606 	    PROT_READ | PROT_WRITE | HAT_NOSYNC | HAT_UNORDERED_OK,
3607 	    HAT_LOAD | HAT_LOAD_NOCONSIST);
3608 
3609 	/*
3610 	 * return the PTE address to the caller.
3611 	 */
3612 	htable_release(ht);
3613 	p += entry << mmu.pte_size_shift;
3614 	return ((void *)p);
3615 }
3616 
3617 /*
3618  * Prepare for a CPU private mapping for the given address.
3619  */
3620 void *
3621 hat_mempte_setup(caddr_t addr)
3622 {
3623 	x86pte_t	*p;
3624 
3625 	p = vmem_alloc(heap_arena, MMU_PAGESIZE, VM_SLEEP);
3626 	return (hat_mempte_kern_setup(addr, p));
3627 }
3628 
3629 /*
3630  * Release a CPU private mapping for the given address.
3631  * We decrement the htable valid count so it might be destroyed.
3632  */
3633 void
3634 hat_mempte_release(caddr_t addr, void *pteptr)
3635 {
3636 	htable_t	*ht;
3637 	uintptr_t	va = ALIGN2PAGE(pteptr);
3638 
3639 	/*
3640 	 * first invalidate any left over mapping and decrement the
3641 	 * htable's mapping count
3642 	 */
3643 	if (mmu.pae_hat)
3644 		*(x86pte_t *)pteptr = 0;
3645 	else
3646 		*(x86pte32_t *)pteptr = 0;
3647 	mmu_tlbflush_entry(addr);
3648 	ht = htable_getpte(kas.a_hat, ALIGN2PAGE(addr), NULL, NULL, 0);
3649 	if (ht == NULL)
3650 		panic("hat_mempte_release(): invalid address");
3651 	ASSERT(ht->ht_level == 0);
3652 	HTABLE_DEC(ht->ht_valid_cnt);
3653 	htable_release(ht);
3654 
3655 	/*
3656 	 * now blow away the kernel mapping to the page table page
3657 	 * XX64 -- see comment in hat_mempte_setup()
3658 	 */
3659 	hat_unload_callback(kas.a_hat, (caddr_t)va, MMU_PAGESIZE,
3660 	    HAT_UNLOAD, NULL);
3661 }
3662 
3663 /*
3664  * Apply a temporary CPU private mapping to a page. We flush the TLB only
3665  * on this CPU, so this ought to have been called with preemption disabled.
3666  */
3667 void
3668 hat_mempte_remap(
3669 	pfn_t pfn,
3670 	caddr_t addr,
3671 	void *pteptr,
3672 	uint_t attr,
3673 	uint_t flags)
3674 {
3675 	uintptr_t	va = (uintptr_t)addr;
3676 	x86pte_t	pte;
3677 
3678 	/*
3679 	 * Remap the given PTE to the new page's PFN. Invalidate only
3680 	 * on this CPU.
3681 	 */
3682 #ifdef DEBUG
3683 	htable_t	*ht;
3684 	uint_t		entry;
3685 
3686 	ASSERT(IS_PAGEALIGNED(va));
3687 	ASSERT(!IN_VA_HOLE(va));
3688 	ht = htable_getpte(kas.a_hat, va, &entry, NULL, 0);
3689 	ASSERT(ht != NULL);
3690 	ASSERT(ht->ht_level == 0);
3691 	ASSERT(ht->ht_valid_cnt > 0);
3692 	htable_release(ht);
3693 #endif
3694 	pte = hati_mkpte(pfn, attr, 0, flags);
3695 	if (mmu.pae_hat)
3696 		*(x86pte_t *)pteptr = pte;
3697 	else
3698 		*(x86pte32_t *)pteptr = (x86pte32_t)pte;
3699 	mmu_tlbflush_entry(addr);
3700 }
3701 
3702 
3703 
3704 /*
3705  * Hat locking functions
3706  * XXX - these two functions are currently being used by hatstats
3707  * 	they can be removed by using a per-as mutex for hatstats.
3708  */
3709 void
3710 hat_enter(hat_t *hat)
3711 {
3712 	mutex_enter(&hat->hat_mutex);
3713 }
3714 
3715 void
3716 hat_exit(hat_t *hat)
3717 {
3718 	mutex_exit(&hat->hat_mutex);
3719 }
3720 
3721 
3722 /*
3723  * Used by hat_kern_setup() to create initial kernel HAT mappings from
3724  * the boot loader's mappings.
3725  *
3726  * - size is either PAGESIZE or some multiple of a level one pagesize
3727  * - there may not be page_t's for every pfn. (ie. the nucleus pages)
3728  * - pfn's are continguous for the given va range (va to va + size * cnt)
3729  */
3730 void
3731 hati_kern_setup_load(
3732 	uintptr_t va,	/* starting va of range to map */
3733 	size_t size,	/* either PAGESIZE or multiple of large page size */
3734 	pfn_t pfn,	/* starting PFN */
3735 	pgcnt_t cnt,	/* number of mappings, (cnt * size) == total size */
3736 	uint_t prot)	/* protections (PROT_READ, PROT_WRITE, PROT_EXEC) */
3737 {
3738 	level_t level = (size == MMU_PAGESIZE ? 0 : 1);
3739 	size_t bytes = size * cnt;
3740 	size_t pgsize = LEVEL_SIZE(level);
3741 	page_t *pp;
3742 	uint_t flags = HAT_LOAD;
3743 
3744 	/*
3745 	 * We're only going to throw away mappings below kernelbase or in
3746 	 * boot's special double-mapping region, so set noconsist to avoid
3747 	 * using hments
3748 	 */
3749 	if (BOOT_VA(va))
3750 		flags |= HAT_LOAD_NOCONSIST;
3751 
3752 	prot |= HAT_STORECACHING_OK;
3753 	while (bytes != 0) {
3754 		ASSERT(bytes >= pgsize);
3755 
3756 		pp = NULL;
3757 		if (pf_is_memory(pfn) && !BOOT_VA(va) && level == 0)
3758 			pp = page_numtopp_nolock(pfn);
3759 
3760 		hati_load_common(kas.a_hat, va, pp, prot, flags, level, pfn);
3761 
3762 		va += pgsize;
3763 		pfn += mmu_btop(pgsize);
3764 		bytes -= pgsize;
3765 	}
3766 }
3767 
3768 /*
3769  * HAT part of cpu intialization.
3770  */
3771 void
3772 hat_cpu_online(struct cpu *cpup)
3773 {
3774 	if (cpup != CPU) {
3775 		x86pte_cpu_init(cpup, NULL);
3776 		hat_vlp_setup(cpup);
3777 	}
3778 	CPUSET_ATOMIC_ADD(khat_cpuset, cpup->cpu_id);
3779 }
3780 
3781 /*
3782  * Function called after all CPUs are brought online.
3783  * Used to remove low address boot mappings.
3784  */
3785 void
3786 clear_boot_mappings(uintptr_t low, uintptr_t high)
3787 {
3788 	uintptr_t vaddr = low;
3789 	htable_t *ht = NULL;
3790 	level_t level;
3791 	uint_t entry;
3792 	x86pte_t pte;
3793 
3794 	/*
3795 	 * On 1st CPU we can unload the prom mappings, basically we blow away
3796 	 * all virtual mappings under kernelbase.
3797 	 */
3798 	while (vaddr < high) {
3799 		pte = htable_walk(kas.a_hat, &ht, &vaddr, high);
3800 		if (ht == NULL)
3801 			break;
3802 
3803 		level = ht->ht_level;
3804 		entry = htable_va2entry(vaddr, ht);
3805 		ASSERT(level <= mmu.max_page_level);
3806 		ASSERT(PTE_ISPAGE(pte, level));
3807 
3808 		/*
3809 		 * Unload the mapping from the page tables.
3810 		 */
3811 		(void) x86pte_set(ht, entry, 0, NULL);
3812 		ASSERT(ht->ht_valid_cnt > 0);
3813 		HTABLE_DEC(ht->ht_valid_cnt);
3814 		PGCNT_DEC(ht->ht_hat, ht->ht_level);
3815 
3816 		vaddr += LEVEL_SIZE(ht->ht_level);
3817 	}
3818 	if (ht)
3819 		htable_release(ht);
3820 
3821 	/*
3822 	 * cross call for a complete invalidate.
3823 	 */
3824 	hat_demap(kas.a_hat, DEMAP_ALL_ADDR);
3825 }
3826 
3827 /*
3828  * Initialize a special area in the kernel that always holds some PTEs for
3829  * faster performance. This always holds segmap's PTEs.
3830  * In the 32 bit kernel this maps the kernel heap too.
3831  */
3832 void
3833 hat_kmap_init(uintptr_t base, size_t len)
3834 {
3835 	uintptr_t map_addr;	/* base rounded down to large page size */
3836 	uintptr_t map_eaddr;	/* base + len rounded up */
3837 	size_t map_len;
3838 	caddr_t ptes;		/* mapping area in kernel as for ptes */
3839 	size_t window_size;	/* size of mapping area for ptes */
3840 	ulong_t htable_cnt;	/* # of page tables to cover map_len */
3841 	ulong_t i;
3842 	htable_t *ht;
3843 
3844 	/*
3845 	 * we have to map in an area that matches an entire page table
3846 	 */
3847 	map_addr = base & LEVEL_MASK(1);
3848 	map_eaddr = (base + len + LEVEL_SIZE(1) - 1) & LEVEL_MASK(1);
3849 	map_len = map_eaddr - map_addr;
3850 	window_size = mmu_btop(map_len) * mmu.pte_size;
3851 	htable_cnt = mmu_btop(map_len) / mmu.ptes_per_table;
3852 
3853 	/*
3854 	 * allocate vmem for the kmap_ptes
3855 	 */
3856 	ptes = vmem_xalloc(heap_arena, window_size, MMU_PAGESIZE, 0,
3857 	    0, NULL, NULL, VM_SLEEP);
3858 	mmu.kmap_htables =
3859 	    kmem_alloc(htable_cnt * sizeof (htable_t *), KM_SLEEP);
3860 
3861 	/*
3862 	 * Map the page tables that cover kmap into the allocated range.
3863 	 * Note we don't ever htable_release() the kmap page tables - they
3864 	 * can't ever be stolen, freed, etc.
3865 	 */
3866 	for (i = 0; i < htable_cnt; ++i) {
3867 		ht = htable_create(kas.a_hat, map_addr + i * LEVEL_SIZE(1),
3868 		    0, NULL);
3869 		mmu.kmap_htables[i] = ht;
3870 
3871 		hat_devload(kas.a_hat, ptes + i * MMU_PAGESIZE, MMU_PAGESIZE,
3872 		    ht->ht_pfn,
3873 		    PROT_READ | PROT_WRITE | HAT_NOSYNC | HAT_UNORDERED_OK,
3874 		    HAT_LOAD | HAT_LOAD_NOCONSIST);
3875 
3876 	}
3877 
3878 	/*
3879 	 * set information in mmu to activate handling of kmap
3880 	 */
3881 	mmu.kmap_addr = base;
3882 	mmu.kmap_eaddr = base + len;
3883 	mmu.kmap_ptes =
3884 	    (x86pte_t *)(ptes + mmu.pte_size * mmu_btop(base - map_addr));
3885 }
3886 
3887 /*
3888  * Atomically update a new translation for a single page.  If the
3889  * currently installed PTE doesn't match the value we expect to find,
3890  * it's not updated and we return the PTE we found.
3891  *
3892  * If activating nosync or NOWRITE and the page was modified we need to sync
3893  * with the page_t. Also sync with page_t if clearing ref/mod bits.
3894  */
3895 static x86pte_t
3896 hati_update_pte(htable_t *ht, uint_t entry, x86pte_t expected, x86pte_t new)
3897 {
3898 	page_t		*pp;
3899 	uint_t		rm = 0;
3900 	x86pte_t	replaced;
3901 
3902 	if (!PTE_GET(expected, PT_NOSYNC | PT_NOCONSIST) &&
3903 	    PTE_GET(expected, PT_MOD | PT_REF) &&
3904 	    (PTE_GET(new, PT_NOSYNC) || !PTE_GET(new, PT_WRITABLE) ||
3905 		!PTE_GET(new, PT_MOD | PT_REF))) {
3906 
3907 		pp = page_numtopp_nolock(PTE2PFN(expected, ht->ht_level));
3908 		ASSERT(pp != NULL);
3909 		if (PTE_GET(expected, PT_MOD))
3910 			rm |= P_MOD;
3911 		if (PTE_GET(expected, PT_REF))
3912 			rm |= P_REF;
3913 		PTE_CLR(new, PT_MOD | PT_REF);
3914 	}
3915 
3916 	replaced = x86pte_update(ht, entry, expected, new);
3917 	if (replaced != expected)
3918 		return (replaced);
3919 
3920 	if (rm) {
3921 		/*
3922 		 * sync to all constituent pages of a large page
3923 		 */
3924 		pgcnt_t pgcnt = page_get_pagecnt(ht->ht_level);
3925 		ASSERT(IS_P2ALIGNED(pp->p_pagenum, pgcnt));
3926 		while (pgcnt-- > 0) {
3927 			/*
3928 			 * hat_page_demote() can't decrease
3929 			 * pszc below this mapping size
3930 			 * since large mapping existed after we
3931 			 * took mlist lock.
3932 			 */
3933 			ASSERT(pp->p_szc >= ht->ht_level);
3934 			hat_page_setattr(pp, rm);
3935 			++pp;
3936 		}
3937 	}
3938 
3939 	return (0);
3940 }
3941 
3942 /*
3943  * Kernel Physical Mapping (kpm) facility
3944  *
3945  * Most of the routines needed to support segkpm are almost no-ops on the
3946  * x86 platform.  We map in the entire segment when it is created and leave
3947  * it mapped in, so there is no additional work required to set up and tear
3948  * down individual mappings.  All of these routines were created to support
3949  * SPARC platforms that have to avoid aliasing in their virtually indexed
3950  * caches.
3951  *
3952  * Most of the routines have sanity checks in them (e.g. verifying that the
3953  * passed-in page is locked).  We don't actually care about most of these
3954  * checks on x86, but we leave them in place to identify problems in the
3955  * upper levels.
3956  */
3957 
3958 /*
3959  * Map in a locked page and return the vaddr.
3960  */
3961 /*ARGSUSED*/
3962 caddr_t
3963 hat_kpm_mapin(struct page *pp, struct kpme *kpme)
3964 {
3965 	caddr_t		vaddr;
3966 
3967 #ifdef DEBUG
3968 	if (kpm_enable == 0) {
3969 		cmn_err(CE_WARN, "hat_kpm_mapin: kpm_enable not set\n");
3970 		return ((caddr_t)NULL);
3971 	}
3972 
3973 	if (pp == NULL || PAGE_LOCKED(pp) == 0) {
3974 		cmn_err(CE_WARN, "hat_kpm_mapin: pp zero or not locked\n");
3975 		return ((caddr_t)NULL);
3976 	}
3977 #endif
3978 
3979 	vaddr = hat_kpm_page2va(pp, 1);
3980 
3981 	return (vaddr);
3982 }
3983 
3984 /*
3985  * Mapout a locked page.
3986  */
3987 /*ARGSUSED*/
3988 void
3989 hat_kpm_mapout(struct page *pp, struct kpme *kpme, caddr_t vaddr)
3990 {
3991 #ifdef DEBUG
3992 	if (kpm_enable == 0) {
3993 		cmn_err(CE_WARN, "hat_kpm_mapout: kpm_enable not set\n");
3994 		return;
3995 	}
3996 
3997 	if (IS_KPM_ADDR(vaddr) == 0) {
3998 		cmn_err(CE_WARN, "hat_kpm_mapout: no kpm address\n");
3999 		return;
4000 	}
4001 
4002 	if (pp == NULL || PAGE_LOCKED(pp) == 0) {
4003 		cmn_err(CE_WARN, "hat_kpm_mapout: page zero or not locked\n");
4004 		return;
4005 	}
4006 #endif
4007 }
4008 
4009 /*
4010  * Return the kpm virtual address for a specific pfn
4011  */
4012 caddr_t
4013 hat_kpm_pfn2va(pfn_t pfn)
4014 {
4015 	uintptr_t vaddr;
4016 
4017 	ASSERT(kpm_enable);
4018 
4019 	vaddr = (uintptr_t)kpm_vbase + mmu_ptob(pfn);
4020 
4021 	return ((caddr_t)vaddr);
4022 }
4023 
4024 /*
4025  * Return the kpm virtual address for the page at pp.
4026  */
4027 /*ARGSUSED*/
4028 caddr_t
4029 hat_kpm_page2va(struct page *pp, int checkswap)
4030 {
4031 	return (hat_kpm_pfn2va(pp->p_pagenum));
4032 }
4033 
4034 /*
4035  * Return the page frame number for the kpm virtual address vaddr.
4036  */
4037 pfn_t
4038 hat_kpm_va2pfn(caddr_t vaddr)
4039 {
4040 	pfn_t		pfn;
4041 
4042 	ASSERT(IS_KPM_ADDR(vaddr));
4043 
4044 	pfn = (pfn_t)btop(vaddr - kpm_vbase);
4045 
4046 	return (pfn);
4047 }
4048 
4049 
4050 /*
4051  * Return the page for the kpm virtual address vaddr.
4052  */
4053 page_t *
4054 hat_kpm_vaddr2page(caddr_t vaddr)
4055 {
4056 	pfn_t		pfn;
4057 
4058 	ASSERT(IS_KPM_ADDR(vaddr));
4059 
4060 	pfn = hat_kpm_va2pfn(vaddr);
4061 
4062 	return (page_numtopp_nolock(pfn));
4063 }
4064 
4065 /*
4066  * hat_kpm_fault is called from segkpm_fault when we take a page fault on a
4067  * KPM page.  This should never happen on x86
4068  */
4069 int
4070 hat_kpm_fault(hat_t *hat, caddr_t vaddr)
4071 {
4072 	panic("pagefault in seg_kpm.  hat: 0x%p  vaddr: 0x%p", hat, vaddr);
4073 
4074 	return (0);
4075 }
4076 
4077 /*ARGSUSED*/
4078 void
4079 hat_kpm_mseghash_clear(int nentries)
4080 {}
4081 
4082 /*ARGSUSED*/
4083 void
4084 hat_kpm_mseghash_update(pgcnt_t inx, struct memseg *msp)
4085 {}
4086