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