xref: /titanic_41/usr/src/uts/i86pc/vm/hat_i86.c (revision 88df2d76721d60b8b7cad14f9380446d06569f7c)
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 extern int	vpm_enable;
3128 /*
3129  * Unload all translations to a page. If the page is a subpage of a large
3130  * page, the large page mappings are also removed.
3131  *
3132  * The forceflags are unused.
3133  */
3134 
3135 /*ARGSUSED*/
3136 static int
3137 hati_pageunload(struct page *pp, uint_t pg_szcd, uint_t forceflag)
3138 {
3139 	page_t		*cur_pp = pp;
3140 	hment_t		*hm;
3141 	hment_t		*prev;
3142 	htable_t	*ht;
3143 	uint_t		entry;
3144 	level_t		level;
3145 
3146 #if defined(__amd64)
3147 	/*
3148 	 * clear the vpm ref.
3149 	 */
3150 	if (vpm_enable) {
3151 		pp->p_vpmref = 0;
3152 	}
3153 #endif
3154 	/*
3155 	 * The loop with next_size handles pages with multiple pagesize mappings
3156 	 */
3157 next_size:
3158 	for (;;) {
3159 
3160 		/*
3161 		 * Get a mapping list entry
3162 		 */
3163 		x86_hm_enter(cur_pp);
3164 		for (prev = NULL; ; prev = hm) {
3165 			hm = hment_walk(cur_pp, &ht, &entry, prev);
3166 			if (hm == NULL) {
3167 				x86_hm_exit(cur_pp);
3168 
3169 				/*
3170 				 * If not part of a larger page, we're done.
3171 				 */
3172 				if (cur_pp->p_szc <= pg_szcd)
3173 					return (0);
3174 
3175 				/*
3176 				 * Else check the next larger page size.
3177 				 * hat_page_demote() may decrease p_szc
3178 				 * but that's ok we'll just take an extra
3179 				 * trip discover there're no larger mappings
3180 				 * and return.
3181 				 */
3182 				++pg_szcd;
3183 				cur_pp = PP_GROUPLEADER(cur_pp, pg_szcd);
3184 				goto next_size;
3185 			}
3186 
3187 			/*
3188 			 * If this mapping size matches, remove it.
3189 			 */
3190 			level = ht->ht_level;
3191 			if (level == pg_szcd)
3192 				break;
3193 		}
3194 
3195 		/*
3196 		 * Remove the mapping list entry for this page.
3197 		 * Note this does the x86_hm_exit() for us.
3198 		 */
3199 		hm = hati_page_unmap(cur_pp, ht, entry);
3200 		if (hm != NULL)
3201 			hment_free(hm);
3202 	}
3203 }
3204 
3205 int
3206 hat_pageunload(struct page *pp, uint_t forceflag)
3207 {
3208 	ASSERT(PAGE_EXCL(pp));
3209 	return (hati_pageunload(pp, 0, forceflag));
3210 }
3211 
3212 /*
3213  * Unload all large mappings to pp and reduce by 1 p_szc field of every large
3214  * page level that included pp.
3215  *
3216  * pp must be locked EXCL. Even though no other constituent pages are locked
3217  * it's legal to unload large mappings to pp because all constituent pages of
3218  * large locked mappings have to be locked SHARED.  therefore if we have EXCL
3219  * lock on one of constituent pages none of the large mappings to pp are
3220  * locked.
3221  *
3222  * Change (always decrease) p_szc field starting from the last constituent
3223  * page and ending with root constituent page so that root's pszc always shows
3224  * the area where hat_page_demote() may be active.
3225  *
3226  * This mechanism is only used for file system pages where it's not always
3227  * possible to get EXCL locks on all constituent pages to demote the size code
3228  * (as is done for anonymous or kernel large pages).
3229  */
3230 void
3231 hat_page_demote(page_t *pp)
3232 {
3233 	uint_t		pszc;
3234 	uint_t		rszc;
3235 	uint_t		szc;
3236 	page_t		*rootpp;
3237 	page_t		*firstpp;
3238 	page_t		*lastpp;
3239 	pgcnt_t		pgcnt;
3240 
3241 	ASSERT(PAGE_EXCL(pp));
3242 	ASSERT(!PP_ISFREE(pp));
3243 	ASSERT(page_szc_lock_assert(pp));
3244 
3245 	if (pp->p_szc == 0)
3246 		return;
3247 
3248 	rootpp = PP_GROUPLEADER(pp, 1);
3249 	(void) hati_pageunload(rootpp, 1, HAT_FORCE_PGUNLOAD);
3250 
3251 	/*
3252 	 * all large mappings to pp are gone
3253 	 * and no new can be setup since pp is locked exclusively.
3254 	 *
3255 	 * Lock the root to make sure there's only one hat_page_demote()
3256 	 * outstanding within the area of this root's pszc.
3257 	 *
3258 	 * Second potential hat_page_demote() is already eliminated by upper
3259 	 * VM layer via page_szc_lock() but we don't rely on it and use our
3260 	 * own locking (so that upper layer locking can be changed without
3261 	 * assumptions that hat depends on upper layer VM to prevent multiple
3262 	 * hat_page_demote() to be issued simultaneously to the same large
3263 	 * page).
3264 	 */
3265 again:
3266 	pszc = pp->p_szc;
3267 	if (pszc == 0)
3268 		return;
3269 	rootpp = PP_GROUPLEADER(pp, pszc);
3270 	x86_hm_enter(rootpp);
3271 	/*
3272 	 * If root's p_szc is different from pszc we raced with another
3273 	 * hat_page_demote().  Drop the lock and try to find the root again.
3274 	 * If root's p_szc is greater than pszc previous hat_page_demote() is
3275 	 * not done yet.  Take and release mlist lock of root's root to wait
3276 	 * for previous hat_page_demote() to complete.
3277 	 */
3278 	if ((rszc = rootpp->p_szc) != pszc) {
3279 		x86_hm_exit(rootpp);
3280 		if (rszc > pszc) {
3281 			/* p_szc of a locked non free page can't increase */
3282 			ASSERT(pp != rootpp);
3283 
3284 			rootpp = PP_GROUPLEADER(rootpp, rszc);
3285 			x86_hm_enter(rootpp);
3286 			x86_hm_exit(rootpp);
3287 		}
3288 		goto again;
3289 	}
3290 	ASSERT(pp->p_szc == pszc);
3291 
3292 	/*
3293 	 * Decrement by 1 p_szc of every constituent page of a region that
3294 	 * covered pp. For example if original szc is 3 it gets changed to 2
3295 	 * everywhere except in region 2 that covered pp. Region 2 that
3296 	 * covered pp gets demoted to 1 everywhere except in region 1 that
3297 	 * covered pp. The region 1 that covered pp is demoted to region
3298 	 * 0. It's done this way because from region 3 we removed level 3
3299 	 * mappings, from region 2 that covered pp we removed level 2 mappings
3300 	 * and from region 1 that covered pp we removed level 1 mappings.  All
3301 	 * changes are done from from high pfn's to low pfn's so that roots
3302 	 * are changed last allowing one to know the largest region where
3303 	 * hat_page_demote() is stil active by only looking at the root page.
3304 	 *
3305 	 * This algorithm is implemented in 2 while loops. First loop changes
3306 	 * p_szc of pages to the right of pp's level 1 region and second
3307 	 * loop changes p_szc of pages of level 1 region that covers pp
3308 	 * and all pages to the left of level 1 region that covers pp.
3309 	 * In the first loop p_szc keeps dropping with every iteration
3310 	 * and in the second loop it keeps increasing with every iteration.
3311 	 *
3312 	 * First loop description: Demote pages to the right of pp outside of
3313 	 * level 1 region that covers pp.  In every iteration of the while
3314 	 * loop below find the last page of szc region and the first page of
3315 	 * (szc - 1) region that is immediately to the right of (szc - 1)
3316 	 * region that covers pp.  From last such page to first such page
3317 	 * change every page's szc to szc - 1. Decrement szc and continue
3318 	 * looping until szc is 1. If pp belongs to the last (szc - 1) region
3319 	 * of szc region skip to the next iteration.
3320 	 */
3321 	szc = pszc;
3322 	while (szc > 1) {
3323 		lastpp = PP_GROUPLEADER(pp, szc);
3324 		pgcnt = page_get_pagecnt(szc);
3325 		lastpp += pgcnt - 1;
3326 		firstpp = PP_GROUPLEADER(pp, (szc - 1));
3327 		pgcnt = page_get_pagecnt(szc - 1);
3328 		if (lastpp - firstpp < pgcnt) {
3329 			szc--;
3330 			continue;
3331 		}
3332 		firstpp += pgcnt;
3333 		while (lastpp != firstpp) {
3334 			ASSERT(lastpp->p_szc == pszc);
3335 			lastpp->p_szc = szc - 1;
3336 			lastpp--;
3337 		}
3338 		firstpp->p_szc = szc - 1;
3339 		szc--;
3340 	}
3341 
3342 	/*
3343 	 * Second loop description:
3344 	 * First iteration changes p_szc to 0 of every
3345 	 * page of level 1 region that covers pp.
3346 	 * Subsequent iterations find last page of szc region
3347 	 * immediately to the left of szc region that covered pp
3348 	 * and first page of (szc + 1) region that covers pp.
3349 	 * From last to first page change p_szc of every page to szc.
3350 	 * Increment szc and continue looping until szc is pszc.
3351 	 * If pp belongs to the fist szc region of (szc + 1) region
3352 	 * skip to the next iteration.
3353 	 *
3354 	 */
3355 	szc = 0;
3356 	while (szc < pszc) {
3357 		firstpp = PP_GROUPLEADER(pp, (szc + 1));
3358 		if (szc == 0) {
3359 			pgcnt = page_get_pagecnt(1);
3360 			lastpp = firstpp + (pgcnt - 1);
3361 		} else {
3362 			lastpp = PP_GROUPLEADER(pp, szc);
3363 			if (firstpp == lastpp) {
3364 				szc++;
3365 				continue;
3366 			}
3367 			lastpp--;
3368 			pgcnt = page_get_pagecnt(szc);
3369 		}
3370 		while (lastpp != firstpp) {
3371 			ASSERT(lastpp->p_szc == pszc);
3372 			lastpp->p_szc = szc;
3373 			lastpp--;
3374 		}
3375 		firstpp->p_szc = szc;
3376 		if (firstpp == rootpp)
3377 			break;
3378 		szc++;
3379 	}
3380 	x86_hm_exit(rootpp);
3381 }
3382 
3383 /*
3384  * get hw stats from hardware into page struct and reset hw stats
3385  * returns attributes of page
3386  * Flags for hat_pagesync, hat_getstat, hat_sync
3387  *
3388  * define	HAT_SYNC_ZERORM		0x01
3389  *
3390  * Additional flags for hat_pagesync
3391  *
3392  * define	HAT_SYNC_STOPON_REF	0x02
3393  * define	HAT_SYNC_STOPON_MOD	0x04
3394  * define	HAT_SYNC_STOPON_RM	0x06
3395  * define	HAT_SYNC_STOPON_SHARED	0x08
3396  */
3397 uint_t
3398 hat_pagesync(struct page *pp, uint_t flags)
3399 {
3400 	hment_t		*hm = NULL;
3401 	htable_t	*ht;
3402 	uint_t		entry;
3403 	x86pte_t	old, save_old;
3404 	x86pte_t	new;
3405 	uchar_t		nrmbits = P_REF|P_MOD|P_RO;
3406 	extern ulong_t	po_share;
3407 	page_t		*save_pp = pp;
3408 	uint_t		pszc = 0;
3409 
3410 	ASSERT(PAGE_LOCKED(pp) || panicstr);
3411 
3412 	if (PP_ISRO(pp) && (flags & HAT_SYNC_STOPON_MOD))
3413 		return (pp->p_nrm & nrmbits);
3414 
3415 	if ((flags & HAT_SYNC_ZERORM) == 0) {
3416 
3417 		if ((flags & HAT_SYNC_STOPON_REF) != 0 && PP_ISREF(pp))
3418 			return (pp->p_nrm & nrmbits);
3419 
3420 		if ((flags & HAT_SYNC_STOPON_MOD) != 0 && PP_ISMOD(pp))
3421 			return (pp->p_nrm & nrmbits);
3422 
3423 		if ((flags & HAT_SYNC_STOPON_SHARED) != 0 &&
3424 		    hat_page_getshare(pp) > po_share) {
3425 			if (PP_ISRO(pp))
3426 				PP_SETREF(pp);
3427 			return (pp->p_nrm & nrmbits);
3428 		}
3429 	}
3430 
3431 next_size:
3432 	/*
3433 	 * walk thru the mapping list syncing (and clearing) ref/mod bits.
3434 	 */
3435 	x86_hm_enter(pp);
3436 	while ((hm = hment_walk(pp, &ht, &entry, hm)) != NULL) {
3437 		if (ht->ht_level < pszc)
3438 			continue;
3439 		old = x86pte_get(ht, entry);
3440 try_again:
3441 
3442 		ASSERT(PTE2PFN(old, ht->ht_level) == pp->p_pagenum);
3443 
3444 		if (PTE_GET(old, PT_REF | PT_MOD) == 0)
3445 			continue;
3446 
3447 		save_old = old;
3448 		if ((flags & HAT_SYNC_ZERORM) != 0) {
3449 
3450 			/*
3451 			 * Need to clear ref or mod bits. Need to demap
3452 			 * to make sure any executing TLBs see cleared bits.
3453 			 */
3454 			new = old;
3455 			PTE_CLR(new, PT_REF | PT_MOD);
3456 			old = hati_update_pte(ht, entry, old, new);
3457 			if (old != 0)
3458 				goto try_again;
3459 
3460 			old = save_old;
3461 		}
3462 
3463 		/*
3464 		 * Sync the PTE
3465 		 */
3466 		if (!(flags & HAT_SYNC_ZERORM) && PTE_GET(old, PT_NOSYNC) == 0)
3467 			hati_sync_pte_to_page(pp, old, ht->ht_level);
3468 
3469 		/*
3470 		 * can stop short if we found a ref'd or mod'd page
3471 		 */
3472 		if ((flags & HAT_SYNC_STOPON_MOD) && PP_ISMOD(save_pp) ||
3473 		    (flags & HAT_SYNC_STOPON_REF) && PP_ISREF(save_pp)) {
3474 			x86_hm_exit(pp);
3475 			return (save_pp->p_nrm & nrmbits);
3476 		}
3477 	}
3478 	x86_hm_exit(pp);
3479 	while (pszc < pp->p_szc) {
3480 		page_t *tpp;
3481 		pszc++;
3482 		tpp = PP_GROUPLEADER(pp, pszc);
3483 		if (pp != tpp) {
3484 			pp = tpp;
3485 			goto next_size;
3486 		}
3487 	}
3488 	return (save_pp->p_nrm & nrmbits);
3489 }
3490 
3491 /*
3492  * returns approx number of mappings to this pp.  A return of 0 implies
3493  * there are no mappings to the page.
3494  */
3495 ulong_t
3496 hat_page_getshare(page_t *pp)
3497 {
3498 	uint_t cnt;
3499 	cnt = hment_mapcnt(pp);
3500 #if defined(__amd64)
3501 	if (vpm_enable && pp->p_vpmref) {
3502 		cnt += 1;
3503 	}
3504 #endif
3505 	return (cnt);
3506 }
3507 
3508 /*
3509  * hat_softlock isn't supported anymore
3510  */
3511 /*ARGSUSED*/
3512 faultcode_t
3513 hat_softlock(
3514 	hat_t *hat,
3515 	caddr_t addr,
3516 	size_t *len,
3517 	struct page **page_array,
3518 	uint_t flags)
3519 {
3520 	return (FC_NOSUPPORT);
3521 }
3522 
3523 
3524 
3525 /*
3526  * Routine to expose supported HAT features to platform independent code.
3527  */
3528 /*ARGSUSED*/
3529 int
3530 hat_supported(enum hat_features feature, void *arg)
3531 {
3532 	switch (feature) {
3533 
3534 	case HAT_SHARED_PT:	/* this is really ISM */
3535 		return (1);
3536 
3537 	case HAT_DYNAMIC_ISM_UNMAP:
3538 		return (0);
3539 
3540 	case HAT_VMODSORT:
3541 		return (1);
3542 
3543 	default:
3544 		panic("hat_supported() - unknown feature");
3545 	}
3546 	return (0);
3547 }
3548 
3549 /*
3550  * Called when a thread is exiting and has been switched to the kernel AS
3551  */
3552 void
3553 hat_thread_exit(kthread_t *thd)
3554 {
3555 	ASSERT(thd->t_procp->p_as == &kas);
3556 	hat_switch(thd->t_procp->p_as->a_hat);
3557 }
3558 
3559 /*
3560  * Setup the given brand new hat structure as the new HAT on this cpu's mmu.
3561  */
3562 /*ARGSUSED*/
3563 void
3564 hat_setup(hat_t *hat, int flags)
3565 {
3566 	kpreempt_disable();
3567 
3568 	hat_switch(hat);
3569 
3570 	kpreempt_enable();
3571 }
3572 
3573 /*
3574  * Prepare for a CPU private mapping for the given address.
3575  *
3576  * The address can only be used from a single CPU and can be remapped
3577  * using hat_mempte_remap().  Return the address of the PTE.
3578  *
3579  * We do the htable_create() if necessary and increment the valid count so
3580  * the htable can't disappear.  We also hat_devload() the page table into
3581  * kernel so that the PTE is quickly accessed.
3582  */
3583 void *
3584 hat_mempte_kern_setup(caddr_t addr, void *pt)
3585 {
3586 	uintptr_t	va = (uintptr_t)addr;
3587 	htable_t	*ht;
3588 	uint_t		entry;
3589 	x86pte_t	oldpte;
3590 	caddr_t		p = (caddr_t)pt;
3591 
3592 	ASSERT(IS_PAGEALIGNED(va));
3593 	ASSERT(!IN_VA_HOLE(va));
3594 	ht = htable_getpte(kas.a_hat, va, &entry, &oldpte, 0);
3595 	if (ht == NULL) {
3596 		/*
3597 		 * Note that we don't need a hat_reserves_exit() check
3598 		 * for this htable_create(), since that'll be done by the
3599 		 * hat_devload() just below.
3600 		 */
3601 		ht = htable_create(kas.a_hat, va, 0, NULL);
3602 		entry = htable_va2entry(va, ht);
3603 		ASSERT(ht->ht_level == 0);
3604 		oldpte = x86pte_get(ht, entry);
3605 	}
3606 	if (PTE_ISVALID(oldpte))
3607 		panic("hat_mempte_setup(): address already mapped"
3608 		    "ht=%p, entry=%d, pte=" FMT_PTE, ht, entry, oldpte);
3609 
3610 	/*
3611 	 * increment ht_valid_cnt so that the pagetable can't disappear
3612 	 */
3613 	HTABLE_INC(ht->ht_valid_cnt);
3614 
3615 	/*
3616 	 * now we need to map the page holding the pagetable for va into
3617 	 * the kernel's address space.
3618 	 */
3619 	hat_devload(kas.a_hat, p, MMU_PAGESIZE, ht->ht_pfn,
3620 	    PROT_READ | PROT_WRITE | HAT_NOSYNC | HAT_UNORDERED_OK,
3621 	    HAT_LOAD | HAT_LOAD_NOCONSIST);
3622 
3623 	/*
3624 	 * return the PTE address to the caller.
3625 	 */
3626 	htable_release(ht);
3627 	p += entry << mmu.pte_size_shift;
3628 	return ((void *)p);
3629 }
3630 
3631 /*
3632  * Prepare for a CPU private mapping for the given address.
3633  */
3634 void *
3635 hat_mempte_setup(caddr_t addr)
3636 {
3637 	x86pte_t	*p;
3638 
3639 	p = vmem_alloc(heap_arena, MMU_PAGESIZE, VM_SLEEP);
3640 	return (hat_mempte_kern_setup(addr, p));
3641 }
3642 
3643 /*
3644  * Release a CPU private mapping for the given address.
3645  * We decrement the htable valid count so it might be destroyed.
3646  */
3647 void
3648 hat_mempte_release(caddr_t addr, void *pteptr)
3649 {
3650 	htable_t	*ht;
3651 	uintptr_t	va = ALIGN2PAGE(pteptr);
3652 
3653 	/*
3654 	 * first invalidate any left over mapping and decrement the
3655 	 * htable's mapping count
3656 	 */
3657 	if (mmu.pae_hat)
3658 		*(x86pte_t *)pteptr = 0;
3659 	else
3660 		*(x86pte32_t *)pteptr = 0;
3661 	mmu_tlbflush_entry(addr);
3662 	ht = htable_getpte(kas.a_hat, ALIGN2PAGE(addr), NULL, NULL, 0);
3663 	if (ht == NULL)
3664 		panic("hat_mempte_release(): invalid address");
3665 	ASSERT(ht->ht_level == 0);
3666 	HTABLE_DEC(ht->ht_valid_cnt);
3667 	htable_release(ht);
3668 
3669 	/*
3670 	 * now blow away the kernel mapping to the page table page
3671 	 * XX64 -- see comment in hat_mempte_setup()
3672 	 */
3673 	hat_unload_callback(kas.a_hat, (caddr_t)va, MMU_PAGESIZE,
3674 	    HAT_UNLOAD, NULL);
3675 }
3676 
3677 /*
3678  * Apply a temporary CPU private mapping to a page. We flush the TLB only
3679  * on this CPU, so this ought to have been called with preemption disabled.
3680  */
3681 void
3682 hat_mempte_remap(
3683 	pfn_t pfn,
3684 	caddr_t addr,
3685 	void *pteptr,
3686 	uint_t attr,
3687 	uint_t flags)
3688 {
3689 	uintptr_t	va = (uintptr_t)addr;
3690 	x86pte_t	pte;
3691 
3692 	/*
3693 	 * Remap the given PTE to the new page's PFN. Invalidate only
3694 	 * on this CPU.
3695 	 */
3696 #ifdef DEBUG
3697 	htable_t	*ht;
3698 	uint_t		entry;
3699 
3700 	ASSERT(IS_PAGEALIGNED(va));
3701 	ASSERT(!IN_VA_HOLE(va));
3702 	ht = htable_getpte(kas.a_hat, va, &entry, NULL, 0);
3703 	ASSERT(ht != NULL);
3704 	ASSERT(ht->ht_level == 0);
3705 	ASSERT(ht->ht_valid_cnt > 0);
3706 	htable_release(ht);
3707 #endif
3708 	pte = hati_mkpte(pfn, attr, 0, flags);
3709 	if (mmu.pae_hat)
3710 		*(x86pte_t *)pteptr = pte;
3711 	else
3712 		*(x86pte32_t *)pteptr = (x86pte32_t)pte;
3713 	mmu_tlbflush_entry(addr);
3714 }
3715 
3716 
3717 
3718 /*
3719  * Hat locking functions
3720  * XXX - these two functions are currently being used by hatstats
3721  * 	they can be removed by using a per-as mutex for hatstats.
3722  */
3723 void
3724 hat_enter(hat_t *hat)
3725 {
3726 	mutex_enter(&hat->hat_mutex);
3727 }
3728 
3729 void
3730 hat_exit(hat_t *hat)
3731 {
3732 	mutex_exit(&hat->hat_mutex);
3733 }
3734 
3735 
3736 /*
3737  * Used by hat_kern_setup() to create initial kernel HAT mappings from
3738  * the boot loader's mappings.
3739  *
3740  * - size is either PAGESIZE or some multiple of a level one pagesize
3741  * - there may not be page_t's for every pfn. (ie. the nucleus pages)
3742  * - pfn's are continguous for the given va range (va to va + size * cnt)
3743  */
3744 void
3745 hati_kern_setup_load(
3746 	uintptr_t va,	/* starting va of range to map */
3747 	size_t size,	/* either PAGESIZE or multiple of large page size */
3748 	pfn_t pfn,	/* starting PFN */
3749 	pgcnt_t cnt,	/* number of mappings, (cnt * size) == total size */
3750 	uint_t prot)	/* protections (PROT_READ, PROT_WRITE, PROT_EXEC) */
3751 {
3752 	level_t level = (size == MMU_PAGESIZE ? 0 : 1);
3753 	size_t bytes = size * cnt;
3754 	size_t pgsize = LEVEL_SIZE(level);
3755 	page_t *pp;
3756 	uint_t flags = HAT_LOAD;
3757 
3758 	/*
3759 	 * We're only going to throw away mappings below kernelbase or in
3760 	 * boot's special double-mapping region, so set noconsist to avoid
3761 	 * using hments
3762 	 */
3763 	if (BOOT_VA(va))
3764 		flags |= HAT_LOAD_NOCONSIST;
3765 
3766 	prot |= HAT_STORECACHING_OK;
3767 	while (bytes != 0) {
3768 		ASSERT(bytes >= pgsize);
3769 
3770 		pp = NULL;
3771 		if (pf_is_memory(pfn) && !BOOT_VA(va) && level == 0)
3772 			pp = page_numtopp_nolock(pfn);
3773 
3774 		hati_load_common(kas.a_hat, va, pp, prot, flags, level, pfn);
3775 
3776 		va += pgsize;
3777 		pfn += mmu_btop(pgsize);
3778 		bytes -= pgsize;
3779 	}
3780 }
3781 
3782 /*
3783  * HAT part of cpu intialization.
3784  */
3785 void
3786 hat_cpu_online(struct cpu *cpup)
3787 {
3788 	if (cpup != CPU) {
3789 		x86pte_cpu_init(cpup, NULL);
3790 		hat_vlp_setup(cpup);
3791 	}
3792 	CPUSET_ATOMIC_ADD(khat_cpuset, cpup->cpu_id);
3793 }
3794 
3795 /*
3796  * Function called after all CPUs are brought online.
3797  * Used to remove low address boot mappings.
3798  */
3799 void
3800 clear_boot_mappings(uintptr_t low, uintptr_t high)
3801 {
3802 	uintptr_t vaddr = low;
3803 	htable_t *ht = NULL;
3804 	level_t level;
3805 	uint_t entry;
3806 	x86pte_t pte;
3807 
3808 	/*
3809 	 * On 1st CPU we can unload the prom mappings, basically we blow away
3810 	 * all virtual mappings under kernelbase.
3811 	 */
3812 	while (vaddr < high) {
3813 		pte = htable_walk(kas.a_hat, &ht, &vaddr, high);
3814 		if (ht == NULL)
3815 			break;
3816 
3817 		level = ht->ht_level;
3818 		entry = htable_va2entry(vaddr, ht);
3819 		ASSERT(level <= mmu.max_page_level);
3820 		ASSERT(PTE_ISPAGE(pte, level));
3821 
3822 		/*
3823 		 * Unload the mapping from the page tables.
3824 		 */
3825 		(void) x86pte_set(ht, entry, 0, NULL);
3826 		ASSERT(ht->ht_valid_cnt > 0);
3827 		HTABLE_DEC(ht->ht_valid_cnt);
3828 		PGCNT_DEC(ht->ht_hat, ht->ht_level);
3829 
3830 		vaddr += LEVEL_SIZE(ht->ht_level);
3831 	}
3832 	if (ht)
3833 		htable_release(ht);
3834 
3835 	/*
3836 	 * cross call for a complete invalidate.
3837 	 */
3838 	hat_demap(kas.a_hat, DEMAP_ALL_ADDR);
3839 }
3840 
3841 /*
3842  * Initialize a special area in the kernel that always holds some PTEs for
3843  * faster performance. This always holds segmap's PTEs.
3844  * In the 32 bit kernel this maps the kernel heap too.
3845  */
3846 void
3847 hat_kmap_init(uintptr_t base, size_t len)
3848 {
3849 	uintptr_t map_addr;	/* base rounded down to large page size */
3850 	uintptr_t map_eaddr;	/* base + len rounded up */
3851 	size_t map_len;
3852 	caddr_t ptes;		/* mapping area in kernel as for ptes */
3853 	size_t window_size;	/* size of mapping area for ptes */
3854 	ulong_t htable_cnt;	/* # of page tables to cover map_len */
3855 	ulong_t i;
3856 	htable_t *ht;
3857 
3858 	/*
3859 	 * we have to map in an area that matches an entire page table
3860 	 */
3861 	map_addr = base & LEVEL_MASK(1);
3862 	map_eaddr = (base + len + LEVEL_SIZE(1) - 1) & LEVEL_MASK(1);
3863 	map_len = map_eaddr - map_addr;
3864 	window_size = mmu_btop(map_len) * mmu.pte_size;
3865 	htable_cnt = mmu_btop(map_len) / mmu.ptes_per_table;
3866 
3867 	/*
3868 	 * allocate vmem for the kmap_ptes
3869 	 */
3870 	ptes = vmem_xalloc(heap_arena, window_size, MMU_PAGESIZE, 0,
3871 	    0, NULL, NULL, VM_SLEEP);
3872 	mmu.kmap_htables =
3873 	    kmem_alloc(htable_cnt * sizeof (htable_t *), KM_SLEEP);
3874 
3875 	/*
3876 	 * Map the page tables that cover kmap into the allocated range.
3877 	 * Note we don't ever htable_release() the kmap page tables - they
3878 	 * can't ever be stolen, freed, etc.
3879 	 */
3880 	for (i = 0; i < htable_cnt; ++i) {
3881 		ht = htable_create(kas.a_hat, map_addr + i * LEVEL_SIZE(1),
3882 		    0, NULL);
3883 		mmu.kmap_htables[i] = ht;
3884 
3885 		hat_devload(kas.a_hat, ptes + i * MMU_PAGESIZE, MMU_PAGESIZE,
3886 		    ht->ht_pfn,
3887 		    PROT_READ | PROT_WRITE | HAT_NOSYNC | HAT_UNORDERED_OK,
3888 		    HAT_LOAD | HAT_LOAD_NOCONSIST);
3889 
3890 	}
3891 
3892 	/*
3893 	 * set information in mmu to activate handling of kmap
3894 	 */
3895 	mmu.kmap_addr = base;
3896 	mmu.kmap_eaddr = base + len;
3897 	mmu.kmap_ptes =
3898 	    (x86pte_t *)(ptes + mmu.pte_size * mmu_btop(base - map_addr));
3899 }
3900 
3901 /*
3902  * Atomically update a new translation for a single page.  If the
3903  * currently installed PTE doesn't match the value we expect to find,
3904  * it's not updated and we return the PTE we found.
3905  *
3906  * If activating nosync or NOWRITE and the page was modified we need to sync
3907  * with the page_t. Also sync with page_t if clearing ref/mod bits.
3908  */
3909 static x86pte_t
3910 hati_update_pte(htable_t *ht, uint_t entry, x86pte_t expected, x86pte_t new)
3911 {
3912 	page_t		*pp;
3913 	uint_t		rm = 0;
3914 	x86pte_t	replaced;
3915 
3916 	if (!PTE_GET(expected, PT_NOSYNC | PT_NOCONSIST) &&
3917 	    PTE_GET(expected, PT_MOD | PT_REF) &&
3918 	    (PTE_GET(new, PT_NOSYNC) || !PTE_GET(new, PT_WRITABLE) ||
3919 		!PTE_GET(new, PT_MOD | PT_REF))) {
3920 
3921 		pp = page_numtopp_nolock(PTE2PFN(expected, ht->ht_level));
3922 		ASSERT(pp != NULL);
3923 		if (PTE_GET(expected, PT_MOD))
3924 			rm |= P_MOD;
3925 		if (PTE_GET(expected, PT_REF))
3926 			rm |= P_REF;
3927 		PTE_CLR(new, PT_MOD | PT_REF);
3928 	}
3929 
3930 	replaced = x86pte_update(ht, entry, expected, new);
3931 	if (replaced != expected)
3932 		return (replaced);
3933 
3934 	if (rm) {
3935 		/*
3936 		 * sync to all constituent pages of a large page
3937 		 */
3938 		pgcnt_t pgcnt = page_get_pagecnt(ht->ht_level);
3939 		ASSERT(IS_P2ALIGNED(pp->p_pagenum, pgcnt));
3940 		while (pgcnt-- > 0) {
3941 			/*
3942 			 * hat_page_demote() can't decrease
3943 			 * pszc below this mapping size
3944 			 * since large mapping existed after we
3945 			 * took mlist lock.
3946 			 */
3947 			ASSERT(pp->p_szc >= ht->ht_level);
3948 			hat_page_setattr(pp, rm);
3949 			++pp;
3950 		}
3951 	}
3952 
3953 	return (0);
3954 }
3955 
3956 /*
3957  * Kernel Physical Mapping (kpm) facility
3958  *
3959  * Most of the routines needed to support segkpm are almost no-ops on the
3960  * x86 platform.  We map in the entire segment when it is created and leave
3961  * it mapped in, so there is no additional work required to set up and tear
3962  * down individual mappings.  All of these routines were created to support
3963  * SPARC platforms that have to avoid aliasing in their virtually indexed
3964  * caches.
3965  *
3966  * Most of the routines have sanity checks in them (e.g. verifying that the
3967  * passed-in page is locked).  We don't actually care about most of these
3968  * checks on x86, but we leave them in place to identify problems in the
3969  * upper levels.
3970  */
3971 
3972 /*
3973  * Map in a locked page and return the vaddr.
3974  */
3975 /*ARGSUSED*/
3976 caddr_t
3977 hat_kpm_mapin(struct page *pp, struct kpme *kpme)
3978 {
3979 	caddr_t		vaddr;
3980 
3981 #ifdef DEBUG
3982 	if (kpm_enable == 0) {
3983 		cmn_err(CE_WARN, "hat_kpm_mapin: kpm_enable not set\n");
3984 		return ((caddr_t)NULL);
3985 	}
3986 
3987 	if (pp == NULL || PAGE_LOCKED(pp) == 0) {
3988 		cmn_err(CE_WARN, "hat_kpm_mapin: pp zero or not locked\n");
3989 		return ((caddr_t)NULL);
3990 	}
3991 #endif
3992 
3993 	vaddr = hat_kpm_page2va(pp, 1);
3994 
3995 	return (vaddr);
3996 }
3997 
3998 /*
3999  * Mapout a locked page.
4000  */
4001 /*ARGSUSED*/
4002 void
4003 hat_kpm_mapout(struct page *pp, struct kpme *kpme, caddr_t vaddr)
4004 {
4005 #ifdef DEBUG
4006 	if (kpm_enable == 0) {
4007 		cmn_err(CE_WARN, "hat_kpm_mapout: kpm_enable not set\n");
4008 		return;
4009 	}
4010 
4011 	if (IS_KPM_ADDR(vaddr) == 0) {
4012 		cmn_err(CE_WARN, "hat_kpm_mapout: no kpm address\n");
4013 		return;
4014 	}
4015 
4016 	if (pp == NULL || PAGE_LOCKED(pp) == 0) {
4017 		cmn_err(CE_WARN, "hat_kpm_mapout: page zero or not locked\n");
4018 		return;
4019 	}
4020 #endif
4021 }
4022 
4023 /*
4024  * Return the kpm virtual address for a specific pfn
4025  */
4026 caddr_t
4027 hat_kpm_pfn2va(pfn_t pfn)
4028 {
4029 	uintptr_t vaddr;
4030 
4031 	ASSERT(kpm_enable);
4032 
4033 	vaddr = (uintptr_t)kpm_vbase + mmu_ptob(pfn);
4034 
4035 	return ((caddr_t)vaddr);
4036 }
4037 
4038 /*
4039  * Return the kpm virtual address for the page at pp.
4040  */
4041 /*ARGSUSED*/
4042 caddr_t
4043 hat_kpm_page2va(struct page *pp, int checkswap)
4044 {
4045 	return (hat_kpm_pfn2va(pp->p_pagenum));
4046 }
4047 
4048 /*
4049  * Return the page frame number for the kpm virtual address vaddr.
4050  */
4051 pfn_t
4052 hat_kpm_va2pfn(caddr_t vaddr)
4053 {
4054 	pfn_t		pfn;
4055 
4056 	ASSERT(IS_KPM_ADDR(vaddr));
4057 
4058 	pfn = (pfn_t)btop(vaddr - kpm_vbase);
4059 
4060 	return (pfn);
4061 }
4062 
4063 
4064 /*
4065  * Return the page for the kpm virtual address vaddr.
4066  */
4067 page_t *
4068 hat_kpm_vaddr2page(caddr_t vaddr)
4069 {
4070 	pfn_t		pfn;
4071 
4072 	ASSERT(IS_KPM_ADDR(vaddr));
4073 
4074 	pfn = hat_kpm_va2pfn(vaddr);
4075 
4076 	return (page_numtopp_nolock(pfn));
4077 }
4078 
4079 /*
4080  * hat_kpm_fault is called from segkpm_fault when we take a page fault on a
4081  * KPM page.  This should never happen on x86
4082  */
4083 int
4084 hat_kpm_fault(hat_t *hat, caddr_t vaddr)
4085 {
4086 	panic("pagefault in seg_kpm.  hat: 0x%p  vaddr: 0x%p", hat, vaddr);
4087 
4088 	return (0);
4089 }
4090 
4091 /*ARGSUSED*/
4092 void
4093 hat_kpm_mseghash_clear(int nentries)
4094 {}
4095 
4096 /*ARGSUSED*/
4097 void
4098 hat_kpm_mseghash_update(pgcnt_t inx, struct memseg *msp)
4099 {}
4100