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