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