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