xref: /illumos-gate/usr/src/uts/i86pc/vm/htable.c (revision a92282e44f968185a6bba094d1e5fece2da819cf)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2014 by Delphix. All rights reserved.
25  * Copyright 2018 Joyent, Inc.
26  */
27 
28 #include <sys/types.h>
29 #include <sys/sysmacros.h>
30 #include <sys/kmem.h>
31 #include <sys/atomic.h>
32 #include <sys/bitmap.h>
33 #include <sys/machparam.h>
34 #include <sys/machsystm.h>
35 #include <sys/mman.h>
36 #include <sys/systm.h>
37 #include <sys/cpuvar.h>
38 #include <sys/thread.h>
39 #include <sys/proc.h>
40 #include <sys/cpu.h>
41 #include <sys/kmem.h>
42 #include <sys/disp.h>
43 #include <sys/vmem.h>
44 #include <sys/vmsystm.h>
45 #include <sys/promif.h>
46 #include <sys/var.h>
47 #include <sys/x86_archext.h>
48 #include <sys/archsystm.h>
49 #include <sys/bootconf.h>
50 #include <sys/dumphdr.h>
51 #include <vm/seg_kmem.h>
52 #include <vm/seg_kpm.h>
53 #include <vm/hat.h>
54 #include <vm/hat_i86.h>
55 #include <sys/cmn_err.h>
56 #include <sys/panic.h>
57 
58 #ifdef __xpv
59 #include <sys/hypervisor.h>
60 #include <sys/xpv_panic.h>
61 #endif
62 
63 #include <sys/bootinfo.h>
64 #include <vm/kboot_mmu.h>
65 
66 static void x86pte_zero(htable_t *dest, uint_t entry, uint_t count);
67 
68 kmem_cache_t *htable_cache;
69 
70 /*
71  * The variable htable_reserve_amount, rather than HTABLE_RESERVE_AMOUNT,
72  * is used in order to facilitate testing of the htable_steal() code.
73  * By resetting htable_reserve_amount to a lower value, we can force
74  * stealing to occur.  The reserve amount is a guess to get us through boot.
75  */
76 #define	HTABLE_RESERVE_AMOUNT	(200)
77 uint_t htable_reserve_amount = HTABLE_RESERVE_AMOUNT;
78 kmutex_t htable_reserve_mutex;
79 uint_t htable_reserve_cnt;
80 htable_t *htable_reserve_pool;
81 
82 /*
83  * Used to hand test htable_steal().
84  */
85 #ifdef DEBUG
86 ulong_t force_steal = 0;
87 ulong_t ptable_cnt = 0;
88 #endif
89 
90 /*
91  * This variable is so that we can tune this via /etc/system
92  * Any value works, but a power of two <= mmu.ptes_per_table is best.
93  */
94 uint_t htable_steal_passes = 8;
95 
96 /*
97  * mutex stuff for access to htable hash
98  */
99 #define	NUM_HTABLE_MUTEX 128
100 kmutex_t htable_mutex[NUM_HTABLE_MUTEX];
101 #define	HTABLE_MUTEX_HASH(h) ((h) & (NUM_HTABLE_MUTEX - 1))
102 
103 #define	HTABLE_ENTER(h)	mutex_enter(&htable_mutex[HTABLE_MUTEX_HASH(h)]);
104 #define	HTABLE_EXIT(h)	mutex_exit(&htable_mutex[HTABLE_MUTEX_HASH(h)]);
105 
106 /*
107  * forward declarations
108  */
109 static void link_ptp(htable_t *higher, htable_t *new, uintptr_t vaddr);
110 static void unlink_ptp(htable_t *higher, htable_t *old, uintptr_t vaddr);
111 static void htable_free(htable_t *ht);
112 static x86pte_t *x86pte_access_pagetable(htable_t *ht, uint_t index);
113 static void x86pte_release_pagetable(htable_t *ht);
114 static x86pte_t x86pte_cas(htable_t *ht, uint_t entry, x86pte_t old,
115 	x86pte_t new);
116 
117 /*
118  * A counter to track if we are stealing or reaping htables. When non-zero
119  * htable_free() will directly free htables (either to the reserve or kmem)
120  * instead of putting them in a hat's htable cache.
121  */
122 uint32_t htable_dont_cache = 0;
123 
124 /*
125  * Track the number of active pagetables, so we can know how many to reap
126  */
127 static uint32_t active_ptables = 0;
128 
129 #ifdef __xpv
130 /*
131  * Deal with hypervisor complications.
132  */
133 void
134 xen_flush_va(caddr_t va)
135 {
136 	struct mmuext_op t;
137 	uint_t count;
138 
139 	if (IN_XPV_PANIC()) {
140 		mmu_flush_tlb_page((uintptr_t)va);
141 	} else {
142 		t.cmd = MMUEXT_INVLPG_LOCAL;
143 		t.arg1.linear_addr = (uintptr_t)va;
144 		if (HYPERVISOR_mmuext_op(&t, 1, &count, DOMID_SELF) < 0)
145 			panic("HYPERVISOR_mmuext_op() failed");
146 		ASSERT(count == 1);
147 	}
148 }
149 
150 void
151 xen_gflush_va(caddr_t va, cpuset_t cpus)
152 {
153 	struct mmuext_op t;
154 	uint_t count;
155 
156 	if (IN_XPV_PANIC()) {
157 		mmu_flush_tlb_page((uintptr_t)va);
158 		return;
159 	}
160 
161 	t.cmd = MMUEXT_INVLPG_MULTI;
162 	t.arg1.linear_addr = (uintptr_t)va;
163 	/*LINTED: constant in conditional context*/
164 	set_xen_guest_handle(t.arg2.vcpumask, &cpus);
165 	if (HYPERVISOR_mmuext_op(&t, 1, &count, DOMID_SELF) < 0)
166 		panic("HYPERVISOR_mmuext_op() failed");
167 	ASSERT(count == 1);
168 }
169 
170 void
171 xen_flush_tlb()
172 {
173 	struct mmuext_op t;
174 	uint_t count;
175 
176 	if (IN_XPV_PANIC()) {
177 		xpv_panic_reload_cr3();
178 	} else {
179 		t.cmd = MMUEXT_TLB_FLUSH_LOCAL;
180 		if (HYPERVISOR_mmuext_op(&t, 1, &count, DOMID_SELF) < 0)
181 			panic("HYPERVISOR_mmuext_op() failed");
182 		ASSERT(count == 1);
183 	}
184 }
185 
186 void
187 xen_gflush_tlb(cpuset_t cpus)
188 {
189 	struct mmuext_op t;
190 	uint_t count;
191 
192 	ASSERT(!IN_XPV_PANIC());
193 	t.cmd = MMUEXT_TLB_FLUSH_MULTI;
194 	/*LINTED: constant in conditional context*/
195 	set_xen_guest_handle(t.arg2.vcpumask, &cpus);
196 	if (HYPERVISOR_mmuext_op(&t, 1, &count, DOMID_SELF) < 0)
197 		panic("HYPERVISOR_mmuext_op() failed");
198 	ASSERT(count == 1);
199 }
200 
201 /*
202  * Install/Adjust a kpm mapping under the hypervisor.
203  * Value of "how" should be:
204  *	PT_WRITABLE | PT_VALID - regular kpm mapping
205  *	PT_VALID - make mapping read-only
206  *	0	- remove mapping
207  *
208  * returns 0 on success. non-zero for failure.
209  */
210 int
211 xen_kpm_page(pfn_t pfn, uint_t how)
212 {
213 	paddr_t pa = mmu_ptob((paddr_t)pfn);
214 	x86pte_t pte = PT_NOCONSIST | PT_REF | PT_MOD;
215 
216 	if (kpm_vbase == NULL)
217 		return (0);
218 
219 	if (how)
220 		pte |= pa_to_ma(pa) | how;
221 	else
222 		pte = 0;
223 	return (HYPERVISOR_update_va_mapping((uintptr_t)kpm_vbase + pa,
224 	    pte, UVMF_INVLPG | UVMF_ALL));
225 }
226 
227 void
228 xen_pin(pfn_t pfn, level_t lvl)
229 {
230 	struct mmuext_op t;
231 	uint_t count;
232 
233 	t.cmd = MMUEXT_PIN_L1_TABLE + lvl;
234 	t.arg1.mfn = pfn_to_mfn(pfn);
235 	if (HYPERVISOR_mmuext_op(&t, 1, &count, DOMID_SELF) < 0)
236 		panic("HYPERVISOR_mmuext_op() failed");
237 	ASSERT(count == 1);
238 }
239 
240 void
241 xen_unpin(pfn_t pfn)
242 {
243 	struct mmuext_op t;
244 	uint_t count;
245 
246 	t.cmd = MMUEXT_UNPIN_TABLE;
247 	t.arg1.mfn = pfn_to_mfn(pfn);
248 	if (HYPERVISOR_mmuext_op(&t, 1, &count, DOMID_SELF) < 0)
249 		panic("HYPERVISOR_mmuext_op() failed");
250 	ASSERT(count == 1);
251 }
252 
253 static void
254 xen_map(uint64_t pte, caddr_t va)
255 {
256 	if (HYPERVISOR_update_va_mapping((uintptr_t)va, pte,
257 	    UVMF_INVLPG | UVMF_LOCAL))
258 		panic("HYPERVISOR_update_va_mapping() failed");
259 }
260 #endif /* __xpv */
261 
262 /*
263  * Allocate a memory page for a hardware page table.
264  *
265  * A wrapper around page_get_physical(), with some extra checks.
266  */
267 static pfn_t
268 ptable_alloc(uintptr_t seed)
269 {
270 	pfn_t pfn;
271 	page_t *pp;
272 
273 	pfn = PFN_INVALID;
274 
275 	/*
276 	 * The first check is to see if there is memory in the system. If we
277 	 * drop to throttlefree, then fail the ptable_alloc() and let the
278 	 * stealing code kick in. Note that we have to do this test here,
279 	 * since the test in page_create_throttle() would let the NOSLEEP
280 	 * allocation go through and deplete the page reserves.
281 	 *
282 	 * The !NOMEMWAIT() lets pageout, fsflush, etc. skip this check.
283 	 */
284 	if (!NOMEMWAIT() && freemem <= throttlefree + 1)
285 		return (PFN_INVALID);
286 
287 #ifdef DEBUG
288 	/*
289 	 * This code makes htable_steal() easier to test. By setting
290 	 * force_steal we force pagetable allocations to fall
291 	 * into the stealing code. Roughly 1 in ever "force_steal"
292 	 * page table allocations will fail.
293 	 */
294 	if (proc_pageout != NULL && force_steal > 1 &&
295 	    ++ptable_cnt > force_steal) {
296 		ptable_cnt = 0;
297 		return (PFN_INVALID);
298 	}
299 #endif /* DEBUG */
300 
301 	pp = page_get_physical(seed);
302 	if (pp == NULL)
303 		return (PFN_INVALID);
304 	ASSERT(PAGE_SHARED(pp));
305 	pfn = pp->p_pagenum;
306 	if (pfn == PFN_INVALID)
307 		panic("ptable_alloc(): Invalid PFN!!");
308 	atomic_inc_32(&active_ptables);
309 	HATSTAT_INC(hs_ptable_allocs);
310 	return (pfn);
311 }
312 
313 /*
314  * Free an htable's associated page table page.  See the comments
315  * for ptable_alloc().
316  */
317 static void
318 ptable_free(pfn_t pfn)
319 {
320 	page_t *pp = page_numtopp_nolock(pfn);
321 
322 	/*
323 	 * need to destroy the page used for the pagetable
324 	 */
325 	ASSERT(pfn != PFN_INVALID);
326 	HATSTAT_INC(hs_ptable_frees);
327 	atomic_dec_32(&active_ptables);
328 	if (pp == NULL)
329 		panic("ptable_free(): no page for pfn!");
330 	ASSERT(PAGE_SHARED(pp));
331 	ASSERT(pfn == pp->p_pagenum);
332 	ASSERT(!IN_XPV_PANIC());
333 
334 	/*
335 	 * Get an exclusive lock, might have to wait for a kmem reader.
336 	 */
337 	if (!page_tryupgrade(pp)) {
338 		u_offset_t off = pp->p_offset;
339 		page_unlock(pp);
340 		pp = page_lookup(&kvp, off, SE_EXCL);
341 		if (pp == NULL)
342 			panic("page not found");
343 	}
344 #ifdef __xpv
345 	if (kpm_vbase && xen_kpm_page(pfn, PT_VALID | PT_WRITABLE) < 0)
346 		panic("failure making kpm r/w pfn=0x%lx", pfn);
347 #endif
348 	page_hashout(pp, NULL);
349 	page_free(pp, 1);
350 	page_unresv(1);
351 }
352 
353 /*
354  * Put one htable on the reserve list.
355  */
356 static void
357 htable_put_reserve(htable_t *ht)
358 {
359 	ht->ht_hat = NULL;		/* no longer tied to a hat */
360 	ASSERT(ht->ht_pfn == PFN_INVALID);
361 	HATSTAT_INC(hs_htable_rputs);
362 	mutex_enter(&htable_reserve_mutex);
363 	ht->ht_next = htable_reserve_pool;
364 	htable_reserve_pool = ht;
365 	++htable_reserve_cnt;
366 	mutex_exit(&htable_reserve_mutex);
367 }
368 
369 /*
370  * Take one htable from the reserve.
371  */
372 static htable_t *
373 htable_get_reserve(void)
374 {
375 	htable_t *ht = NULL;
376 
377 	mutex_enter(&htable_reserve_mutex);
378 	if (htable_reserve_cnt != 0) {
379 		ht = htable_reserve_pool;
380 		ASSERT(ht != NULL);
381 		ASSERT(ht->ht_pfn == PFN_INVALID);
382 		htable_reserve_pool = ht->ht_next;
383 		--htable_reserve_cnt;
384 		HATSTAT_INC(hs_htable_rgets);
385 	}
386 	mutex_exit(&htable_reserve_mutex);
387 	return (ht);
388 }
389 
390 /*
391  * Allocate initial htables and put them on the reserve list
392  */
393 void
394 htable_initial_reserve(uint_t count)
395 {
396 	htable_t *ht;
397 
398 	count += HTABLE_RESERVE_AMOUNT;
399 	while (count > 0) {
400 		ht = kmem_cache_alloc(htable_cache, KM_NOSLEEP);
401 		ASSERT(ht != NULL);
402 
403 		ASSERT(use_boot_reserve);
404 		ht->ht_pfn = PFN_INVALID;
405 		htable_put_reserve(ht);
406 		--count;
407 	}
408 }
409 
410 /*
411  * Readjust the reserves after a thread finishes using them.
412  */
413 void
414 htable_adjust_reserve()
415 {
416 	htable_t *ht;
417 
418 	/*
419 	 * Free any excess htables in the reserve list
420 	 */
421 	while (htable_reserve_cnt > htable_reserve_amount &&
422 	    !USE_HAT_RESERVES()) {
423 		ht = htable_get_reserve();
424 		if (ht == NULL)
425 			return;
426 		ASSERT(ht->ht_pfn == PFN_INVALID);
427 		kmem_cache_free(htable_cache, ht);
428 	}
429 }
430 
431 /*
432  * Search the active htables for one to steal. Start at a different hash
433  * bucket every time to help spread the pain of stealing
434  */
435 static void
436 htable_steal_active(hat_t *hat, uint_t cnt, uint_t threshold,
437     uint_t *stolen, htable_t **list)
438 {
439 	static uint_t	h_seed = 0;
440 	htable_t	*higher, *ht;
441 	uint_t		h, e, h_start;
442 	uintptr_t	va;
443 	x86pte_t	pte;
444 
445 	h = h_start = h_seed++ % hat->hat_num_hash;
446 	do {
447 		higher = NULL;
448 		HTABLE_ENTER(h);
449 		for (ht = hat->hat_ht_hash[h]; ht; ht = ht->ht_next) {
450 
451 			/*
452 			 * Can we rule out reaping?
453 			 */
454 			if (ht->ht_busy != 0 ||
455 			    (ht->ht_flags & HTABLE_SHARED_PFN) ||
456 			    ht->ht_level > 0 || ht->ht_valid_cnt > threshold ||
457 			    ht->ht_lock_cnt != 0)
458 				continue;
459 
460 			/*
461 			 * Increment busy so the htable can't disappear. We
462 			 * drop the htable mutex to avoid deadlocks with
463 			 * hat_pageunload() and the hment mutex while we
464 			 * call hat_pte_unmap()
465 			 */
466 			++ht->ht_busy;
467 			HTABLE_EXIT(h);
468 
469 			/*
470 			 * Try stealing.
471 			 * - unload and invalidate all PTEs
472 			 */
473 			for (e = 0, va = ht->ht_vaddr;
474 			    e < HTABLE_NUM_PTES(ht) && ht->ht_valid_cnt > 0 &&
475 			    ht->ht_busy == 1 && ht->ht_lock_cnt == 0;
476 			    ++e, va += MMU_PAGESIZE) {
477 				pte = x86pte_get(ht, e);
478 				if (!PTE_ISVALID(pte))
479 					continue;
480 				hat_pte_unmap(ht, e, HAT_UNLOAD, pte, NULL,
481 				    B_TRUE);
482 			}
483 
484 			/*
485 			 * Reacquire htable lock. If we didn't remove all
486 			 * mappings in the table, or another thread added a new
487 			 * mapping behind us, give up on this table.
488 			 */
489 			HTABLE_ENTER(h);
490 			if (ht->ht_busy != 1 || ht->ht_valid_cnt != 0 ||
491 			    ht->ht_lock_cnt != 0) {
492 				--ht->ht_busy;
493 				continue;
494 			}
495 
496 			/*
497 			 * Steal it and unlink the page table.
498 			 */
499 			higher = ht->ht_parent;
500 			unlink_ptp(higher, ht, ht->ht_vaddr);
501 
502 			/*
503 			 * remove from the hash list
504 			 */
505 			if (ht->ht_next)
506 				ht->ht_next->ht_prev = ht->ht_prev;
507 
508 			if (ht->ht_prev) {
509 				ht->ht_prev->ht_next = ht->ht_next;
510 			} else {
511 				ASSERT(hat->hat_ht_hash[h] == ht);
512 				hat->hat_ht_hash[h] = ht->ht_next;
513 			}
514 
515 			/*
516 			 * Break to outer loop to release the
517 			 * higher (ht_parent) pagetable. This
518 			 * spreads out the pain caused by
519 			 * pagefaults.
520 			 */
521 			ht->ht_next = *list;
522 			*list = ht;
523 			++*stolen;
524 			break;
525 		}
526 		HTABLE_EXIT(h);
527 		if (higher != NULL)
528 			htable_release(higher);
529 		if (++h == hat->hat_num_hash)
530 			h = 0;
531 	} while (*stolen < cnt && h != h_start);
532 }
533 
534 /*
535  * Move hat to the end of the kas list
536  */
537 static void
538 move_victim(hat_t *hat)
539 {
540 	ASSERT(MUTEX_HELD(&hat_list_lock));
541 
542 	/* unlink victim hat */
543 	if (hat->hat_prev)
544 		hat->hat_prev->hat_next = hat->hat_next;
545 	else
546 		kas.a_hat->hat_next = hat->hat_next;
547 
548 	if (hat->hat_next)
549 		hat->hat_next->hat_prev = hat->hat_prev;
550 	else
551 		kas.a_hat->hat_prev = hat->hat_prev;
552 	/* relink at end of hat list */
553 	hat->hat_next = NULL;
554 	hat->hat_prev = kas.a_hat->hat_prev;
555 	if (hat->hat_prev)
556 		hat->hat_prev->hat_next = hat;
557 	else
558 		kas.a_hat->hat_next = hat;
559 
560 	kas.a_hat->hat_prev = hat;
561 }
562 
563 /*
564  * This routine steals htables from user processes.  Called by htable_reap
565  * (reap=TRUE) or htable_alloc (reap=FALSE).
566  */
567 static htable_t *
568 htable_steal(uint_t cnt, boolean_t reap)
569 {
570 	hat_t		*hat = kas.a_hat;	/* list starts with khat */
571 	htable_t	*list = NULL;
572 	htable_t	*ht;
573 	uint_t		stolen = 0;
574 	uint_t		pass, passes;
575 	uint_t		threshold;
576 
577 	/*
578 	 * Limit htable_steal_passes to something reasonable
579 	 */
580 	if (htable_steal_passes == 0)
581 		htable_steal_passes = 1;
582 	if (htable_steal_passes > mmu.ptes_per_table)
583 		htable_steal_passes = mmu.ptes_per_table;
584 
585 	/*
586 	 * If we're stealing merely as part of kmem reaping (versus stealing
587 	 * to assure forward progress), we don't want to actually steal any
588 	 * active htables.  (Stealing active htables merely to give memory
589 	 * back to the system can inadvertently kick off an htable crime wave
590 	 * as active processes repeatedly steal htables from one another,
591 	 * plummeting the system into a kind of HAT lawlessness that can
592 	 * become so violent as to impede the one thing that can end it:  the
593 	 * freeing of memory via ARC reclaim and other means.)  So if we're
594 	 * reaping, we limit ourselves to the first pass that steals cached
595 	 * htables that aren't in use -- which gives memory back, but averts
596 	 * the entire breakdown of social order.
597 	 */
598 	passes = reap ? 0 : htable_steal_passes;
599 
600 	/*
601 	 * Loop through all user hats. The 1st pass takes cached htables that
602 	 * aren't in use. The later passes steal by removing mappings, too.
603 	 */
604 	atomic_inc_32(&htable_dont_cache);
605 	for (pass = 0; pass <= passes && stolen < cnt; ++pass) {
606 		threshold = pass * mmu.ptes_per_table / htable_steal_passes;
607 
608 		mutex_enter(&hat_list_lock);
609 
610 		/* skip the first hat (kernel) */
611 		hat = kas.a_hat->hat_next;
612 		for (;;) {
613 			/*
614 			 * Skip any hat that is already being stolen from.
615 			 *
616 			 * We skip SHARED hats, as these are dummy
617 			 * hats that host ISM shared page tables.
618 			 *
619 			 * We also skip if HAT_FREEING because hat_pte_unmap()
620 			 * won't zero out the PTE's. That would lead to hitting
621 			 * stale PTEs either here or under hat_unload() when we
622 			 * steal and unload the same page table in competing
623 			 * threads.
624 			 *
625 			 * We skip HATs that belong to CPUs, to make our lives
626 			 * simpler.
627 			 */
628 			while (hat != NULL && (hat->hat_flags &
629 			    (HAT_VICTIM | HAT_SHARED | HAT_FREEING |
630 			    HAT_PCP)) != 0) {
631 				hat = hat->hat_next;
632 			}
633 
634 			if (hat == NULL)
635 				break;
636 
637 			/*
638 			 * Mark the HAT as a stealing victim so that it is
639 			 * not freed from under us, e.g. in as_free()
640 			 */
641 			hat->hat_flags |= HAT_VICTIM;
642 			mutex_exit(&hat_list_lock);
643 
644 			/*
645 			 * Take any htables from the hat's cached "free" list.
646 			 */
647 			hat_enter(hat);
648 			while ((ht = hat->hat_ht_cached) != NULL &&
649 			    stolen < cnt) {
650 				hat->hat_ht_cached = ht->ht_next;
651 				ht->ht_next = list;
652 				list = ht;
653 				++stolen;
654 			}
655 			hat_exit(hat);
656 
657 			/*
658 			 * Don't steal active htables on first pass.
659 			 */
660 			if (pass != 0 && (stolen < cnt))
661 				htable_steal_active(hat, cnt, threshold,
662 				    &stolen, &list);
663 
664 			/*
665 			 * do synchronous teardown for the reap case so that
666 			 * we can forget hat; at this time, hat is
667 			 * guaranteed to be around because HAT_VICTIM is set
668 			 * (see htable_free() for similar code)
669 			 */
670 			for (ht = list; (ht) && (reap); ht = ht->ht_next) {
671 				if (ht->ht_hat == NULL)
672 					continue;
673 				ASSERT(ht->ht_hat == hat);
674 #if defined(__xpv) && defined(__amd64)
675 				ASSERT(!(ht->ht_flags & HTABLE_COPIED));
676 				if (ht->ht_level == mmu.max_level) {
677 					ptable_free(hat->hat_user_ptable);
678 					hat->hat_user_ptable = PFN_INVALID;
679 				}
680 #endif
681 				/*
682 				 * forget the hat
683 				 */
684 				ht->ht_hat = NULL;
685 			}
686 
687 			mutex_enter(&hat_list_lock);
688 
689 			/*
690 			 * Are we finished?
691 			 */
692 			if (stolen == cnt) {
693 				/*
694 				 * Try to spread the pain of stealing,
695 				 * move victim HAT to the end of the HAT list.
696 				 */
697 				if (pass >= 1 && cnt == 1 &&
698 				    kas.a_hat->hat_prev != hat)
699 					move_victim(hat);
700 				/*
701 				 * We are finished
702 				 */
703 			}
704 
705 			/*
706 			 * Clear the victim flag, hat can go away now (once
707 			 * the lock is dropped)
708 			 */
709 			if (hat->hat_flags & HAT_VICTIM) {
710 				ASSERT(hat != kas.a_hat);
711 				hat->hat_flags &= ~HAT_VICTIM;
712 				cv_broadcast(&hat_list_cv);
713 			}
714 
715 			/* move on to the next hat */
716 			hat = hat->hat_next;
717 		}
718 
719 		mutex_exit(&hat_list_lock);
720 
721 	}
722 	ASSERT(!MUTEX_HELD(&hat_list_lock));
723 
724 	atomic_dec_32(&htable_dont_cache);
725 	return (list);
726 }
727 
728 /*
729  * This is invoked from kmem when the system is low on memory.  We try
730  * to free hments, htables, and ptables to improve the memory situation.
731  */
732 /*ARGSUSED*/
733 static void
734 htable_reap(void *handle)
735 {
736 	uint_t		reap_cnt;
737 	htable_t	*list;
738 	htable_t	*ht;
739 
740 	HATSTAT_INC(hs_reap_attempts);
741 	if (!can_steal_post_boot)
742 		return;
743 
744 	/*
745 	 * Try to reap 5% of the page tables bounded by a maximum of
746 	 * 5% of physmem and a minimum of 10.
747 	 */
748 	reap_cnt = MAX(MIN(physmem / 20, active_ptables / 20), 10);
749 
750 	/*
751 	 * Note: htable_dont_cache should be set at the time of
752 	 * invoking htable_free()
753 	 */
754 	atomic_inc_32(&htable_dont_cache);
755 	/*
756 	 * Let htable_steal() do the work, we just call htable_free()
757 	 */
758 	XPV_DISALLOW_MIGRATE();
759 	list = htable_steal(reap_cnt, B_TRUE);
760 	XPV_ALLOW_MIGRATE();
761 	while ((ht = list) != NULL) {
762 		list = ht->ht_next;
763 		HATSTAT_INC(hs_reaped);
764 		htable_free(ht);
765 	}
766 	atomic_dec_32(&htable_dont_cache);
767 
768 	/*
769 	 * Free up excess reserves
770 	 */
771 	htable_adjust_reserve();
772 	hment_adjust_reserve();
773 }
774 
775 /*
776  * Allocate an htable, stealing one or using the reserve if necessary
777  */
778 static htable_t *
779 htable_alloc(
780 	hat_t		*hat,
781 	uintptr_t	vaddr,
782 	level_t		level,
783 	htable_t	*shared)
784 {
785 	htable_t	*ht = NULL;
786 	uint_t		is_copied;
787 	uint_t		is_bare = 0;
788 	uint_t		need_to_zero = 1;
789 	int		kmflags = (can_steal_post_boot ? KM_NOSLEEP : KM_SLEEP);
790 
791 	if (level < 0 || level > TOP_LEVEL(hat))
792 		panic("htable_alloc(): level %d out of range\n", level);
793 
794 	is_copied = (hat->hat_flags & HAT_COPIED) &&
795 	    level == hat->hat_max_level;
796 	if (is_copied || shared != NULL)
797 		is_bare = 1;
798 
799 	/*
800 	 * First reuse a cached htable from the hat_ht_cached field, this
801 	 * avoids unnecessary trips through kmem/page allocators.
802 	 */
803 	if (hat->hat_ht_cached != NULL && !is_bare) {
804 		hat_enter(hat);
805 		ht = hat->hat_ht_cached;
806 		if (ht != NULL) {
807 			hat->hat_ht_cached = ht->ht_next;
808 			need_to_zero = 0;
809 			/* XX64 ASSERT() they're all zero somehow */
810 			ASSERT(ht->ht_pfn != PFN_INVALID);
811 		}
812 		hat_exit(hat);
813 	}
814 
815 	if (ht == NULL) {
816 		/*
817 		 * Allocate an htable, possibly refilling the reserves.
818 		 */
819 		if (USE_HAT_RESERVES()) {
820 			ht = htable_get_reserve();
821 		} else {
822 			/*
823 			 * Donate successful htable allocations to the reserve.
824 			 */
825 			for (;;) {
826 				ht = kmem_cache_alloc(htable_cache, kmflags);
827 				if (ht == NULL)
828 					break;
829 				ht->ht_pfn = PFN_INVALID;
830 				if (USE_HAT_RESERVES() ||
831 				    htable_reserve_cnt >= htable_reserve_amount)
832 					break;
833 				htable_put_reserve(ht);
834 			}
835 		}
836 
837 		/*
838 		 * allocate a page for the hardware page table if needed
839 		 */
840 		if (ht != NULL && !is_bare) {
841 			ht->ht_hat = hat;
842 			ht->ht_pfn = ptable_alloc((uintptr_t)ht);
843 			if (ht->ht_pfn == PFN_INVALID) {
844 				if (USE_HAT_RESERVES())
845 					htable_put_reserve(ht);
846 				else
847 					kmem_cache_free(htable_cache, ht);
848 				ht = NULL;
849 			}
850 		}
851 	}
852 
853 	/*
854 	 * If allocations failed, kick off a kmem_reap() and resort to
855 	 * htable steal(). We may spin here if the system is very low on
856 	 * memory. If the kernel itself has consumed all memory and kmem_reap()
857 	 * can't free up anything, then we'll really get stuck here.
858 	 * That should only happen in a system where the administrator has
859 	 * misconfigured VM parameters via /etc/system.
860 	 */
861 	while (ht == NULL && can_steal_post_boot) {
862 		kmem_reap();
863 		ht = htable_steal(1, B_FALSE);
864 		HATSTAT_INC(hs_steals);
865 
866 		/*
867 		 * If we stole for a bare htable, release the pagetable page.
868 		 */
869 		if (ht != NULL) {
870 			if (is_bare) {
871 				ptable_free(ht->ht_pfn);
872 				ht->ht_pfn = PFN_INVALID;
873 #if defined(__xpv) && defined(__amd64)
874 			/*
875 			 * make stolen page table writable again in kpm
876 			 */
877 			} else if (kpm_vbase && xen_kpm_page(ht->ht_pfn,
878 			    PT_VALID | PT_WRITABLE) < 0) {
879 				panic("failure making kpm r/w pfn=0x%lx",
880 				    ht->ht_pfn);
881 #endif
882 			}
883 		}
884 	}
885 
886 	/*
887 	 * All attempts to allocate or steal failed. This should only happen
888 	 * if we run out of memory during boot, due perhaps to a huge
889 	 * boot_archive. At this point there's no way to continue.
890 	 */
891 	if (ht == NULL)
892 		panic("htable_alloc(): couldn't steal\n");
893 
894 #if defined(__amd64) && defined(__xpv)
895 	/*
896 	 * Under the 64-bit hypervisor, we have 2 top level page tables.
897 	 * If this allocation fails, we'll resort to stealing.
898 	 * We use the stolen page indirectly, by freeing the
899 	 * stolen htable first.
900 	 */
901 	if (level == mmu.max_level) {
902 		for (;;) {
903 			htable_t *stolen;
904 
905 			hat->hat_user_ptable = ptable_alloc((uintptr_t)ht + 1);
906 			if (hat->hat_user_ptable != PFN_INVALID)
907 				break;
908 			stolen = htable_steal(1, B_FALSE);
909 			if (stolen == NULL)
910 				panic("2nd steal ptable failed\n");
911 			htable_free(stolen);
912 		}
913 		block_zero_no_xmm(kpm_vbase + pfn_to_pa(hat->hat_user_ptable),
914 		    MMU_PAGESIZE);
915 	}
916 #endif
917 
918 	/*
919 	 * Shared page tables have all entries locked and entries may not
920 	 * be added or deleted.
921 	 */
922 	ht->ht_flags = 0;
923 	if (shared != NULL) {
924 		ASSERT(shared->ht_valid_cnt > 0);
925 		ht->ht_flags |= HTABLE_SHARED_PFN;
926 		ht->ht_pfn = shared->ht_pfn;
927 		ht->ht_lock_cnt = 0;
928 		ht->ht_valid_cnt = 0;		/* updated in hat_share() */
929 		ht->ht_shares = shared;
930 		need_to_zero = 0;
931 	} else {
932 		ht->ht_shares = NULL;
933 		ht->ht_lock_cnt = 0;
934 		ht->ht_valid_cnt = 0;
935 	}
936 
937 	/*
938 	 * setup flags, etc. for copied page tables.
939 	 */
940 	if (is_copied) {
941 		ht->ht_flags |= HTABLE_COPIED;
942 		ASSERT(ht->ht_pfn == PFN_INVALID);
943 		need_to_zero = 0;
944 	}
945 
946 	/*
947 	 * fill in the htable
948 	 */
949 	ht->ht_hat = hat;
950 	ht->ht_parent = NULL;
951 	ht->ht_vaddr = vaddr;
952 	ht->ht_level = level;
953 	ht->ht_busy = 1;
954 	ht->ht_next = NULL;
955 	ht->ht_prev = NULL;
956 
957 	/*
958 	 * Zero out any freshly allocated page table
959 	 */
960 	if (need_to_zero)
961 		x86pte_zero(ht, 0, mmu.ptes_per_table);
962 
963 #if defined(__amd64) && defined(__xpv)
964 	if (!is_bare && kpm_vbase) {
965 		(void) xen_kpm_page(ht->ht_pfn, PT_VALID);
966 		if (level == mmu.max_level)
967 			(void) xen_kpm_page(hat->hat_user_ptable, PT_VALID);
968 	}
969 #endif
970 
971 	return (ht);
972 }
973 
974 /*
975  * Free up an htable, either to a hat's cached list, the reserves or
976  * back to kmem.
977  */
978 static void
979 htable_free(htable_t *ht)
980 {
981 	hat_t *hat = ht->ht_hat;
982 
983 	/*
984 	 * If the process isn't exiting, cache the free htable in the hat
985 	 * structure. We always do this for the boot time reserve. We don't
986 	 * do this if the hat is exiting or we are stealing/reaping htables.
987 	 */
988 	if (hat != NULL &&
989 	    !(ht->ht_flags & HTABLE_SHARED_PFN) &&
990 	    (use_boot_reserve ||
991 	    (!(hat->hat_flags & HAT_FREEING) && !htable_dont_cache))) {
992 		ASSERT((ht->ht_flags & HTABLE_COPIED) == 0);
993 		ASSERT(ht->ht_pfn != PFN_INVALID);
994 		hat_enter(hat);
995 		ht->ht_next = hat->hat_ht_cached;
996 		hat->hat_ht_cached = ht;
997 		hat_exit(hat);
998 		return;
999 	}
1000 
1001 	/*
1002 	 * If we have a hardware page table, free it.
1003 	 * We don't free page tables that are accessed by sharing.
1004 	 */
1005 	if (ht->ht_flags & HTABLE_SHARED_PFN) {
1006 		ASSERT(ht->ht_pfn != PFN_INVALID);
1007 	} else if (!(ht->ht_flags & HTABLE_COPIED)) {
1008 		ptable_free(ht->ht_pfn);
1009 #if defined(__amd64) && defined(__xpv)
1010 		if (ht->ht_level == mmu.max_level && hat != NULL) {
1011 			ptable_free(hat->hat_user_ptable);
1012 			hat->hat_user_ptable = PFN_INVALID;
1013 		}
1014 #endif
1015 	}
1016 	ht->ht_pfn = PFN_INVALID;
1017 
1018 	/*
1019 	 * Free it or put into reserves.
1020 	 */
1021 	if (USE_HAT_RESERVES() || htable_reserve_cnt < htable_reserve_amount) {
1022 		htable_put_reserve(ht);
1023 	} else {
1024 		kmem_cache_free(htable_cache, ht);
1025 		htable_adjust_reserve();
1026 	}
1027 }
1028 
1029 
1030 /*
1031  * This is called when a hat is being destroyed or swapped out. We reap all
1032  * the remaining htables in the hat cache. If destroying all left over
1033  * htables are also destroyed.
1034  *
1035  * We also don't need to invalidate any of the PTPs nor do any demapping.
1036  */
1037 void
1038 htable_purge_hat(hat_t *hat)
1039 {
1040 	htable_t *ht;
1041 	int h;
1042 
1043 	/*
1044 	 * Purge the htable cache if just reaping.
1045 	 */
1046 	if (!(hat->hat_flags & HAT_FREEING)) {
1047 		atomic_inc_32(&htable_dont_cache);
1048 		for (;;) {
1049 			hat_enter(hat);
1050 			ht = hat->hat_ht_cached;
1051 			if (ht == NULL) {
1052 				hat_exit(hat);
1053 				break;
1054 			}
1055 			hat->hat_ht_cached = ht->ht_next;
1056 			hat_exit(hat);
1057 			htable_free(ht);
1058 		}
1059 		atomic_dec_32(&htable_dont_cache);
1060 		return;
1061 	}
1062 
1063 	/*
1064 	 * if freeing, no locking is needed
1065 	 */
1066 	while ((ht = hat->hat_ht_cached) != NULL) {
1067 		hat->hat_ht_cached = ht->ht_next;
1068 		htable_free(ht);
1069 	}
1070 
1071 	/*
1072 	 * walk thru the htable hash table and free all the htables in it.
1073 	 */
1074 	for (h = 0; h < hat->hat_num_hash; ++h) {
1075 		while ((ht = hat->hat_ht_hash[h]) != NULL) {
1076 			if (ht->ht_next)
1077 				ht->ht_next->ht_prev = ht->ht_prev;
1078 
1079 			if (ht->ht_prev) {
1080 				ht->ht_prev->ht_next = ht->ht_next;
1081 			} else {
1082 				ASSERT(hat->hat_ht_hash[h] == ht);
1083 				hat->hat_ht_hash[h] = ht->ht_next;
1084 			}
1085 			htable_free(ht);
1086 		}
1087 	}
1088 }
1089 
1090 /*
1091  * Unlink an entry for a table at vaddr and level out of the existing table
1092  * one level higher. We are always holding the HASH_ENTER() when doing this.
1093  */
1094 static void
1095 unlink_ptp(htable_t *higher, htable_t *old, uintptr_t vaddr)
1096 {
1097 	uint_t		entry = htable_va2entry(vaddr, higher);
1098 	x86pte_t	expect = MAKEPTP(old->ht_pfn, old->ht_level);
1099 	x86pte_t	found;
1100 	hat_t		*hat = old->ht_hat;
1101 
1102 	ASSERT(higher->ht_busy > 0);
1103 	ASSERT(higher->ht_valid_cnt > 0);
1104 	ASSERT(old->ht_valid_cnt == 0);
1105 	found = x86pte_cas(higher, entry, expect, 0);
1106 #ifdef __xpv
1107 	/*
1108 	 * This is weird, but Xen apparently automatically unlinks empty
1109 	 * pagetables from the upper page table. So allow PTP to be 0 already.
1110 	 */
1111 	if (found != expect && found != 0)
1112 #else
1113 	if (found != expect)
1114 #endif
1115 		panic("Bad PTP found=" FMT_PTE ", expected=" FMT_PTE,
1116 		    found, expect);
1117 
1118 	/*
1119 	 * When a top level PTE changes for a copied htable, we must trigger a
1120 	 * hat_pcp_update() on all HAT CPUs.
1121 	 *
1122 	 * If we don't need do do that, then we still have to INVLPG against an
1123 	 * address covered by the inner page table, as the latest processors
1124 	 * have TLB-like caches for non-leaf page table entries.
1125 	 */
1126 	if (!(hat->hat_flags & HAT_FREEING)) {
1127 		hat_tlb_inval(hat, (higher->ht_flags & HTABLE_COPIED) ?
1128 		    DEMAP_ALL_ADDR : old->ht_vaddr);
1129 	}
1130 
1131 	HTABLE_DEC(higher->ht_valid_cnt);
1132 }
1133 
1134 /*
1135  * Link an entry for a new table at vaddr and level into the existing table
1136  * one level higher. We are always holding the HASH_ENTER() when doing this.
1137  */
1138 static void
1139 link_ptp(htable_t *higher, htable_t *new, uintptr_t vaddr)
1140 {
1141 	uint_t		entry = htable_va2entry(vaddr, higher);
1142 	x86pte_t	newptp = MAKEPTP(new->ht_pfn, new->ht_level);
1143 	x86pte_t	found;
1144 
1145 	ASSERT(higher->ht_busy > 0);
1146 
1147 	ASSERT(new->ht_level != mmu.max_level);
1148 
1149 	HTABLE_INC(higher->ht_valid_cnt);
1150 
1151 	found = x86pte_cas(higher, entry, 0, newptp);
1152 	if ((found & ~PT_REF) != 0)
1153 		panic("HAT: ptp not 0, found=" FMT_PTE, found);
1154 
1155 	/*
1156 	 * When a top level PTE changes for a copied htable, we must trigger a
1157 	 * hat_pcp_update() on all HAT CPUs.
1158 	 *
1159 	 * We also need to do this for the kernel hat on PAE 32 bit kernel.
1160 	 */
1161 	if (
1162 #ifdef __i386
1163 	    (higher->ht_hat == kas.a_hat &&
1164 	    higher->ht_level == higher->ht_hat->hat_max_level) ||
1165 #endif
1166 	    (higher->ht_flags & HTABLE_COPIED))
1167 		hat_tlb_inval(higher->ht_hat, DEMAP_ALL_ADDR);
1168 }
1169 
1170 /*
1171  * Release of hold on an htable. If this is the last use and the pagetable
1172  * is empty we may want to free it, then recursively look at the pagetable
1173  * above it. The recursion is handled by the outer while() loop.
1174  *
1175  * On the metal, during process exit, we don't bother unlinking the tables from
1176  * upper level pagetables. They are instead handled in bulk by hat_free_end().
1177  * We can't do this on the hypervisor as we need the page table to be
1178  * implicitly unpinnned before it goes to the free page lists. This can't
1179  * happen unless we fully unlink it from the page table hierarchy.
1180  */
1181 void
1182 htable_release(htable_t *ht)
1183 {
1184 	uint_t		hashval;
1185 	htable_t	*shared;
1186 	htable_t	*higher;
1187 	hat_t		*hat;
1188 	uintptr_t	va;
1189 	level_t		level;
1190 
1191 	while (ht != NULL) {
1192 		shared = NULL;
1193 		for (;;) {
1194 			hat = ht->ht_hat;
1195 			va = ht->ht_vaddr;
1196 			level = ht->ht_level;
1197 			hashval = HTABLE_HASH(hat, va, level);
1198 
1199 			/*
1200 			 * The common case is that this isn't the last use of
1201 			 * an htable so we don't want to free the htable.
1202 			 */
1203 			HTABLE_ENTER(hashval);
1204 			ASSERT(ht->ht_valid_cnt >= 0);
1205 			ASSERT(ht->ht_busy > 0);
1206 			if (ht->ht_valid_cnt > 0)
1207 				break;
1208 			if (ht->ht_busy > 1)
1209 				break;
1210 			ASSERT(ht->ht_lock_cnt == 0);
1211 
1212 #if !defined(__xpv)
1213 			/*
1214 			 * we always release empty shared htables
1215 			 */
1216 			if (!(ht->ht_flags & HTABLE_SHARED_PFN)) {
1217 
1218 				/*
1219 				 * don't release if in address space tear down
1220 				 */
1221 				if (hat->hat_flags & HAT_FREEING)
1222 					break;
1223 
1224 				/*
1225 				 * At and above max_page_level, free if it's for
1226 				 * a boot-time kernel mapping below kernelbase.
1227 				 */
1228 				if (level >= mmu.max_page_level &&
1229 				    (hat != kas.a_hat || va >= kernelbase))
1230 					break;
1231 			}
1232 #endif /* __xpv */
1233 
1234 			/*
1235 			 * Remember if we destroy an htable that shares its PFN
1236 			 * from elsewhere.
1237 			 */
1238 			if (ht->ht_flags & HTABLE_SHARED_PFN) {
1239 				ASSERT(shared == NULL);
1240 				shared = ht->ht_shares;
1241 				HATSTAT_INC(hs_htable_unshared);
1242 			}
1243 
1244 			/*
1245 			 * Handle release of a table and freeing the htable_t.
1246 			 * Unlink it from the table higher (ie. ht_parent).
1247 			 */
1248 			higher = ht->ht_parent;
1249 			ASSERT(higher != NULL);
1250 
1251 			/*
1252 			 * Unlink the pagetable.
1253 			 */
1254 			unlink_ptp(higher, ht, va);
1255 
1256 			/*
1257 			 * remove this htable from its hash list
1258 			 */
1259 			if (ht->ht_next)
1260 				ht->ht_next->ht_prev = ht->ht_prev;
1261 
1262 			if (ht->ht_prev) {
1263 				ht->ht_prev->ht_next = ht->ht_next;
1264 			} else {
1265 				ASSERT(hat->hat_ht_hash[hashval] == ht);
1266 				hat->hat_ht_hash[hashval] = ht->ht_next;
1267 			}
1268 			HTABLE_EXIT(hashval);
1269 			htable_free(ht);
1270 			ht = higher;
1271 		}
1272 
1273 		ASSERT(ht->ht_busy >= 1);
1274 		--ht->ht_busy;
1275 		HTABLE_EXIT(hashval);
1276 
1277 		/*
1278 		 * If we released a shared htable, do a release on the htable
1279 		 * from which it shared
1280 		 */
1281 		ht = shared;
1282 	}
1283 }
1284 
1285 /*
1286  * Find the htable for the pagetable at the given level for the given address.
1287  * If found acquires a hold that eventually needs to be htable_release()d
1288  */
1289 htable_t *
1290 htable_lookup(hat_t *hat, uintptr_t vaddr, level_t level)
1291 {
1292 	uintptr_t	base;
1293 	uint_t		hashval;
1294 	htable_t	*ht = NULL;
1295 
1296 	ASSERT(level >= 0);
1297 	ASSERT(level <= TOP_LEVEL(hat));
1298 
1299 	if (level == TOP_LEVEL(hat)) {
1300 #if defined(__amd64)
1301 		/*
1302 		 * 32 bit address spaces on 64 bit kernels need to check
1303 		 * for overflow of the 32 bit address space
1304 		 */
1305 		if ((hat->hat_flags & HAT_COPIED_32) &&
1306 		    vaddr >= ((uint64_t)1 << 32))
1307 			return (NULL);
1308 #endif
1309 		base = 0;
1310 	} else {
1311 		base = vaddr & LEVEL_MASK(level + 1);
1312 	}
1313 
1314 	hashval = HTABLE_HASH(hat, base, level);
1315 	HTABLE_ENTER(hashval);
1316 	for (ht = hat->hat_ht_hash[hashval]; ht; ht = ht->ht_next) {
1317 		if (ht->ht_hat == hat &&
1318 		    ht->ht_vaddr == base &&
1319 		    ht->ht_level == level)
1320 			break;
1321 	}
1322 	if (ht)
1323 		++ht->ht_busy;
1324 
1325 	HTABLE_EXIT(hashval);
1326 	return (ht);
1327 }
1328 
1329 /*
1330  * Acquires a hold on a known htable (from a locked hment entry).
1331  */
1332 void
1333 htable_acquire(htable_t *ht)
1334 {
1335 	hat_t		*hat = ht->ht_hat;
1336 	level_t		level = ht->ht_level;
1337 	uintptr_t	base = ht->ht_vaddr;
1338 	uint_t		hashval = HTABLE_HASH(hat, base, level);
1339 
1340 	HTABLE_ENTER(hashval);
1341 #ifdef DEBUG
1342 	/*
1343 	 * make sure the htable is there
1344 	 */
1345 	{
1346 		htable_t	*h;
1347 
1348 		for (h = hat->hat_ht_hash[hashval];
1349 		    h && h != ht;
1350 		    h = h->ht_next)
1351 			;
1352 		ASSERT(h == ht);
1353 	}
1354 #endif /* DEBUG */
1355 	++ht->ht_busy;
1356 	HTABLE_EXIT(hashval);
1357 }
1358 
1359 /*
1360  * Find the htable for the pagetable at the given level for the given address.
1361  * If found acquires a hold that eventually needs to be htable_release()d
1362  * If not found the table is created.
1363  *
1364  * Since we can't hold a hash table mutex during allocation, we have to
1365  * drop it and redo the search on a create. Then we may have to free the newly
1366  * allocated htable if another thread raced in and created it ahead of us.
1367  */
1368 htable_t *
1369 htable_create(
1370 	hat_t		*hat,
1371 	uintptr_t	vaddr,
1372 	level_t		level,
1373 	htable_t	*shared)
1374 {
1375 	uint_t		h;
1376 	level_t		l;
1377 	uintptr_t	base;
1378 	htable_t	*ht;
1379 	htable_t	*higher = NULL;
1380 	htable_t	*new = NULL;
1381 
1382 	if (level < 0 || level > TOP_LEVEL(hat))
1383 		panic("htable_create(): level %d out of range\n", level);
1384 
1385 	ht = NULL;
1386 	/*
1387 	 * Create the page tables in top down order.
1388 	 */
1389 	for (l = TOP_LEVEL(hat); l >= level; --l) {
1390 		new = NULL;
1391 		if (l == TOP_LEVEL(hat))
1392 			base = 0;
1393 		else
1394 			base = vaddr & LEVEL_MASK(l + 1);
1395 
1396 		h = HTABLE_HASH(hat, base, l);
1397 try_again:
1398 		/*
1399 		 * look up the htable at this level
1400 		 */
1401 		HTABLE_ENTER(h);
1402 		if (l == TOP_LEVEL(hat)) {
1403 			ht = hat->hat_htable;
1404 		} else {
1405 			for (ht = hat->hat_ht_hash[h]; ht; ht = ht->ht_next) {
1406 				ASSERT(ht->ht_hat == hat);
1407 				if (ht->ht_vaddr == base &&
1408 				    ht->ht_level == l)
1409 					break;
1410 			}
1411 		}
1412 
1413 		/*
1414 		 * if we found the htable, increment its busy cnt
1415 		 * and if we had allocated a new htable, free it.
1416 		 */
1417 		if (ht != NULL) {
1418 			/*
1419 			 * If we find a pre-existing shared table, it must
1420 			 * share from the same place.
1421 			 */
1422 			if (l == level && shared && ht->ht_shares &&
1423 			    ht->ht_shares != shared) {
1424 				panic("htable shared from wrong place "
1425 				    "found htable=%p shared=%p",
1426 				    (void *)ht, (void *)shared);
1427 			}
1428 			++ht->ht_busy;
1429 			HTABLE_EXIT(h);
1430 			if (new)
1431 				htable_free(new);
1432 			if (higher != NULL)
1433 				htable_release(higher);
1434 			higher = ht;
1435 
1436 		/*
1437 		 * if we didn't find it on the first search
1438 		 * allocate a new one and search again
1439 		 */
1440 		} else if (new == NULL) {
1441 			HTABLE_EXIT(h);
1442 			new = htable_alloc(hat, base, l,
1443 			    l == level ? shared : NULL);
1444 			goto try_again;
1445 
1446 		/*
1447 		 * 2nd search and still not there, use "new" table
1448 		 * Link new table into higher, when not at top level.
1449 		 */
1450 		} else {
1451 			ht = new;
1452 			if (higher != NULL) {
1453 				link_ptp(higher, ht, base);
1454 				ht->ht_parent = higher;
1455 			}
1456 			ht->ht_next = hat->hat_ht_hash[h];
1457 			ASSERT(ht->ht_prev == NULL);
1458 			if (hat->hat_ht_hash[h])
1459 				hat->hat_ht_hash[h]->ht_prev = ht;
1460 			hat->hat_ht_hash[h] = ht;
1461 			HTABLE_EXIT(h);
1462 
1463 			/*
1464 			 * Note we don't do htable_release(higher).
1465 			 * That happens recursively when "new" is removed by
1466 			 * htable_release() or htable_steal().
1467 			 */
1468 			higher = ht;
1469 
1470 			/*
1471 			 * If we just created a new shared page table we
1472 			 * increment the shared htable's busy count, so that
1473 			 * it can't be the victim of a steal even if it's empty.
1474 			 */
1475 			if (l == level && shared) {
1476 				(void) htable_lookup(shared->ht_hat,
1477 				    shared->ht_vaddr, shared->ht_level);
1478 				HATSTAT_INC(hs_htable_shared);
1479 			}
1480 		}
1481 	}
1482 
1483 	return (ht);
1484 }
1485 
1486 /*
1487  * Inherit initial pagetables from the boot program. On the 64-bit
1488  * hypervisor we also temporarily mark the p_index field of page table
1489  * pages, so we know not to try making them writable in seg_kpm.
1490  */
1491 void
1492 htable_attach(
1493 	hat_t *hat,
1494 	uintptr_t base,
1495 	level_t level,
1496 	htable_t *parent,
1497 	pfn_t pfn)
1498 {
1499 	htable_t	*ht;
1500 	uint_t		h;
1501 	uint_t		i;
1502 	x86pte_t	pte;
1503 	x86pte_t	*ptep;
1504 	page_t		*pp;
1505 	extern page_t	*boot_claim_page(pfn_t);
1506 
1507 	ht = htable_get_reserve();
1508 	if (level == mmu.max_level)
1509 		kas.a_hat->hat_htable = ht;
1510 	ht->ht_hat = hat;
1511 	ht->ht_parent = parent;
1512 	ht->ht_vaddr = base;
1513 	ht->ht_level = level;
1514 	ht->ht_busy = 1;
1515 	ht->ht_next = NULL;
1516 	ht->ht_prev = NULL;
1517 	ht->ht_flags = 0;
1518 	ht->ht_pfn = pfn;
1519 	ht->ht_lock_cnt = 0;
1520 	ht->ht_valid_cnt = 0;
1521 	if (parent != NULL)
1522 		++parent->ht_busy;
1523 
1524 	h = HTABLE_HASH(hat, base, level);
1525 	HTABLE_ENTER(h);
1526 	ht->ht_next = hat->hat_ht_hash[h];
1527 	ASSERT(ht->ht_prev == NULL);
1528 	if (hat->hat_ht_hash[h])
1529 		hat->hat_ht_hash[h]->ht_prev = ht;
1530 	hat->hat_ht_hash[h] = ht;
1531 	HTABLE_EXIT(h);
1532 
1533 	/*
1534 	 * make sure the page table physical page is not FREE
1535 	 */
1536 	if (page_resv(1, KM_NOSLEEP) == 0)
1537 		panic("page_resv() failed in ptable alloc");
1538 
1539 	pp = boot_claim_page(pfn);
1540 	ASSERT(pp != NULL);
1541 
1542 	/*
1543 	 * Page table pages that were allocated by dboot or
1544 	 * in very early startup didn't go through boot_mapin()
1545 	 * and so won't have vnode/offsets. Fix that here.
1546 	 */
1547 	if (pp->p_vnode == NULL) {
1548 		/* match offset calculation in page_get_physical() */
1549 		u_offset_t offset = (uintptr_t)ht;
1550 		if (offset > kernelbase)
1551 			offset -= kernelbase;
1552 		offset <<= MMU_PAGESHIFT;
1553 #if defined(__amd64)
1554 		offset += mmu.hole_start;	/* something in VA hole */
1555 #else
1556 		offset += 1ULL << 40;		/* something > 4 Gig */
1557 #endif
1558 		ASSERT(page_exists(&kvp, offset) == NULL);
1559 		(void) page_hashin(pp, &kvp, offset, NULL);
1560 	}
1561 	page_downgrade(pp);
1562 #if defined(__xpv) && defined(__amd64)
1563 	/*
1564 	 * Record in the page_t that is a pagetable for segkpm setup.
1565 	 */
1566 	if (kpm_vbase)
1567 		pp->p_index = 1;
1568 #endif
1569 
1570 	/*
1571 	 * Count valid mappings and recursively attach lower level pagetables.
1572 	 */
1573 	ptep = kbm_remap_window(pfn_to_pa(pfn), 0);
1574 	for (i = 0; i < HTABLE_NUM_PTES(ht); ++i) {
1575 		if (mmu.pae_hat)
1576 			pte = ptep[i];
1577 		else
1578 			pte = ((x86pte32_t *)ptep)[i];
1579 		if (!IN_HYPERVISOR_VA(base) && PTE_ISVALID(pte)) {
1580 			++ht->ht_valid_cnt;
1581 			if (!PTE_ISPAGE(pte, level)) {
1582 				htable_attach(hat, base, level - 1,
1583 				    ht, PTE2PFN(pte, level));
1584 				ptep = kbm_remap_window(pfn_to_pa(pfn), 0);
1585 			}
1586 		}
1587 		base += LEVEL_SIZE(level);
1588 		if (base == mmu.hole_start)
1589 			base = (mmu.hole_end + MMU_PAGEOFFSET) & MMU_PAGEMASK;
1590 	}
1591 
1592 	/*
1593 	 * As long as all the mappings we had were below kernel base
1594 	 * we can release the htable.
1595 	 */
1596 	if (base < kernelbase)
1597 		htable_release(ht);
1598 }
1599 
1600 /*
1601  * Walk through a given htable looking for the first valid entry.  This
1602  * routine takes both a starting and ending address.  The starting address
1603  * is required to be within the htable provided by the caller, but there is
1604  * no such restriction on the ending address.
1605  *
1606  * If the routine finds a valid entry in the htable (at or beyond the
1607  * starting address), the PTE (and its address) will be returned.
1608  * This PTE may correspond to either a page or a pagetable - it is the
1609  * caller's responsibility to determine which.  If no valid entry is
1610  * found, 0 (and invalid PTE) and the next unexamined address will be
1611  * returned.
1612  *
1613  * The loop has been carefully coded for optimization.
1614  */
1615 static x86pte_t
1616 htable_scan(htable_t *ht, uintptr_t *vap, uintptr_t eaddr)
1617 {
1618 	uint_t e;
1619 	x86pte_t found_pte = (x86pte_t)0;
1620 	caddr_t pte_ptr;
1621 	caddr_t end_pte_ptr;
1622 	int l = ht->ht_level;
1623 	uintptr_t va = *vap & LEVEL_MASK(l);
1624 	size_t pgsize = LEVEL_SIZE(l);
1625 
1626 	ASSERT(va >= ht->ht_vaddr);
1627 	ASSERT(va <= HTABLE_LAST_PAGE(ht));
1628 
1629 	/*
1630 	 * Compute the starting index and ending virtual address
1631 	 */
1632 	e = htable_va2entry(va, ht);
1633 
1634 	/*
1635 	 * The following page table scan code knows that the valid
1636 	 * bit of a PTE is in the lowest byte AND that x86 is little endian!!
1637 	 */
1638 	pte_ptr = (caddr_t)x86pte_access_pagetable(ht, 0);
1639 	end_pte_ptr = (caddr_t)PT_INDEX_PTR(pte_ptr, HTABLE_NUM_PTES(ht));
1640 	pte_ptr = (caddr_t)PT_INDEX_PTR((x86pte_t *)pte_ptr, e);
1641 	while (!PTE_ISVALID(*pte_ptr)) {
1642 		va += pgsize;
1643 		if (va >= eaddr)
1644 			break;
1645 		pte_ptr += mmu.pte_size;
1646 		ASSERT(pte_ptr <= end_pte_ptr);
1647 		if (pte_ptr == end_pte_ptr)
1648 			break;
1649 	}
1650 
1651 	/*
1652 	 * if we found a valid PTE, load the entire PTE
1653 	 */
1654 	if (va < eaddr && pte_ptr != end_pte_ptr)
1655 		found_pte = GET_PTE((x86pte_t *)pte_ptr);
1656 	x86pte_release_pagetable(ht);
1657 
1658 #if defined(__amd64)
1659 	/*
1660 	 * deal with VA hole on amd64
1661 	 */
1662 	if (l == mmu.max_level && va >= mmu.hole_start && va <= mmu.hole_end)
1663 		va = mmu.hole_end + va - mmu.hole_start;
1664 #endif /* __amd64 */
1665 
1666 	*vap = va;
1667 	return (found_pte);
1668 }
1669 
1670 /*
1671  * Find the address and htable for the first populated translation at or
1672  * above the given virtual address.  The caller may also specify an upper
1673  * limit to the address range to search.  Uses level information to quickly
1674  * skip unpopulated sections of virtual address spaces.
1675  *
1676  * If not found returns NULL. When found, returns the htable and virt addr
1677  * and has a hold on the htable.
1678  */
1679 x86pte_t
1680 htable_walk(
1681 	struct hat *hat,
1682 	htable_t **htp,
1683 	uintptr_t *vaddr,
1684 	uintptr_t eaddr)
1685 {
1686 	uintptr_t va = *vaddr;
1687 	htable_t *ht;
1688 	htable_t *prev = *htp;
1689 	level_t l;
1690 	level_t max_mapped_level;
1691 	x86pte_t pte;
1692 
1693 	ASSERT(eaddr > va);
1694 
1695 	/*
1696 	 * If this is a user address, then we know we need not look beyond
1697 	 * kernelbase.
1698 	 */
1699 	ASSERT(hat == kas.a_hat || eaddr <= kernelbase ||
1700 	    eaddr == HTABLE_WALK_TO_END);
1701 	if (hat != kas.a_hat && eaddr == HTABLE_WALK_TO_END)
1702 		eaddr = kernelbase;
1703 
1704 	/*
1705 	 * If we're coming in with a previous page table, search it first
1706 	 * without doing an htable_lookup(), this should be frequent.
1707 	 */
1708 	if (prev) {
1709 		ASSERT(prev->ht_busy > 0);
1710 		ASSERT(prev->ht_vaddr <= va);
1711 		l = prev->ht_level;
1712 		if (va <= HTABLE_LAST_PAGE(prev)) {
1713 			pte = htable_scan(prev, &va, eaddr);
1714 
1715 			if (PTE_ISPAGE(pte, l)) {
1716 				*vaddr = va;
1717 				*htp = prev;
1718 				return (pte);
1719 			}
1720 		}
1721 
1722 		/*
1723 		 * We found nothing in the htable provided by the caller,
1724 		 * so fall through and do the full search
1725 		 */
1726 		htable_release(prev);
1727 	}
1728 
1729 	/*
1730 	 * Find the level of the largest pagesize used by this HAT.
1731 	 */
1732 	if (hat->hat_ism_pgcnt > 0) {
1733 		max_mapped_level = mmu.umax_page_level;
1734 	} else {
1735 		max_mapped_level = 0;
1736 		for (l = 1; l <= mmu.max_page_level; ++l)
1737 			if (hat->hat_pages_mapped[l] != 0)
1738 				max_mapped_level = l;
1739 	}
1740 
1741 	while (va < eaddr && va >= *vaddr) {
1742 		/*
1743 		 *  Find lowest table with any entry for given address.
1744 		 */
1745 		for (l = 0; l <= TOP_LEVEL(hat); ++l) {
1746 			ht = htable_lookup(hat, va, l);
1747 			if (ht != NULL) {
1748 				pte = htable_scan(ht, &va, eaddr);
1749 				if (PTE_ISPAGE(pte, l)) {
1750 					VERIFY(!IN_VA_HOLE(va));
1751 					*vaddr = va;
1752 					*htp = ht;
1753 					return (pte);
1754 				}
1755 				htable_release(ht);
1756 				break;
1757 			}
1758 
1759 			/*
1760 			 * No htable at this level for the address. If there
1761 			 * is no larger page size that could cover it, we can
1762 			 * skip right to the start of the next page table.
1763 			 */
1764 			ASSERT(l < TOP_LEVEL(hat));
1765 			if (l >= max_mapped_level) {
1766 				va = NEXT_ENTRY_VA(va, l + 1);
1767 				if (va >= eaddr)
1768 					break;
1769 			}
1770 		}
1771 	}
1772 
1773 	*vaddr = 0;
1774 	*htp = NULL;
1775 	return (0);
1776 }
1777 
1778 /*
1779  * Find the htable and page table entry index of the given virtual address
1780  * with pagesize at or below given level.
1781  * If not found returns NULL. When found, returns the htable, sets
1782  * entry, and has a hold on the htable.
1783  */
1784 htable_t *
1785 htable_getpte(
1786 	struct hat *hat,
1787 	uintptr_t vaddr,
1788 	uint_t *entry,
1789 	x86pte_t *pte,
1790 	level_t level)
1791 {
1792 	htable_t	*ht;
1793 	level_t		l;
1794 	uint_t		e;
1795 
1796 	ASSERT(level <= mmu.max_page_level);
1797 
1798 	for (l = 0; l <= level; ++l) {
1799 		ht = htable_lookup(hat, vaddr, l);
1800 		if (ht == NULL)
1801 			continue;
1802 		e = htable_va2entry(vaddr, ht);
1803 		if (entry != NULL)
1804 			*entry = e;
1805 		if (pte != NULL)
1806 			*pte = x86pte_get(ht, e);
1807 		return (ht);
1808 	}
1809 	return (NULL);
1810 }
1811 
1812 /*
1813  * Find the htable and page table entry index of the given virtual address.
1814  * There must be a valid page mapped at the given address.
1815  * If not found returns NULL. When found, returns the htable, sets
1816  * entry, and has a hold on the htable.
1817  */
1818 htable_t *
1819 htable_getpage(struct hat *hat, uintptr_t vaddr, uint_t *entry)
1820 {
1821 	htable_t	*ht;
1822 	uint_t		e;
1823 	x86pte_t	pte;
1824 
1825 	ht = htable_getpte(hat, vaddr, &e, &pte, mmu.max_page_level);
1826 	if (ht == NULL)
1827 		return (NULL);
1828 
1829 	if (entry)
1830 		*entry = e;
1831 
1832 	if (PTE_ISPAGE(pte, ht->ht_level))
1833 		return (ht);
1834 	htable_release(ht);
1835 	return (NULL);
1836 }
1837 
1838 
1839 void
1840 htable_init()
1841 {
1842 	/*
1843 	 * To save on kernel VA usage, we avoid debug information in 32 bit
1844 	 * kernels.
1845 	 */
1846 #if defined(__amd64)
1847 	int	kmem_flags = KMC_NOHASH;
1848 #elif defined(__i386)
1849 	int	kmem_flags = KMC_NOHASH | KMC_NODEBUG;
1850 #endif
1851 
1852 	/*
1853 	 * initialize kmem caches
1854 	 */
1855 	htable_cache = kmem_cache_create("htable_t",
1856 	    sizeof (htable_t), 0, NULL, NULL,
1857 	    htable_reap, NULL, hat_memload_arena, kmem_flags);
1858 }
1859 
1860 /*
1861  * get the pte index for the virtual address in the given htable's pagetable
1862  */
1863 uint_t
1864 htable_va2entry(uintptr_t va, htable_t *ht)
1865 {
1866 	level_t	l = ht->ht_level;
1867 
1868 	ASSERT(va >= ht->ht_vaddr);
1869 	ASSERT(va <= HTABLE_LAST_PAGE(ht));
1870 	return ((va >> LEVEL_SHIFT(l)) & (HTABLE_NUM_PTES(ht) - 1));
1871 }
1872 
1873 /*
1874  * Given an htable and the index of a pte in it, return the virtual address
1875  * of the page.
1876  */
1877 uintptr_t
1878 htable_e2va(htable_t *ht, uint_t entry)
1879 {
1880 	level_t	l = ht->ht_level;
1881 	uintptr_t va;
1882 
1883 	ASSERT(entry < HTABLE_NUM_PTES(ht));
1884 	va = ht->ht_vaddr + ((uintptr_t)entry << LEVEL_SHIFT(l));
1885 
1886 	/*
1887 	 * Need to skip over any VA hole in top level table
1888 	 */
1889 #if defined(__amd64)
1890 	if (ht->ht_level == mmu.max_level && va >= mmu.hole_start)
1891 		va += ((mmu.hole_end - mmu.hole_start) + 1);
1892 #endif
1893 
1894 	return (va);
1895 }
1896 
1897 /*
1898  * The code uses compare and swap instructions to read/write PTE's to
1899  * avoid atomicity problems, since PTEs can be 8 bytes on 32 bit systems.
1900  * will naturally be atomic.
1901  *
1902  * The combination of using kpreempt_disable()/_enable() and the hci_mutex
1903  * are used to ensure that an interrupt won't overwrite a temporary mapping
1904  * while it's in use. If an interrupt thread tries to access a PTE, it will
1905  * yield briefly back to the pinned thread which holds the cpu's hci_mutex.
1906  */
1907 void
1908 x86pte_cpu_init(cpu_t *cpu)
1909 {
1910 	struct hat_cpu_info *hci;
1911 
1912 	hci = kmem_zalloc(sizeof (*hci), KM_SLEEP);
1913 	mutex_init(&hci->hci_mutex, NULL, MUTEX_DEFAULT, NULL);
1914 	cpu->cpu_hat_info = hci;
1915 }
1916 
1917 void
1918 x86pte_cpu_fini(cpu_t *cpu)
1919 {
1920 	struct hat_cpu_info *hci = cpu->cpu_hat_info;
1921 
1922 	kmem_free(hci, sizeof (*hci));
1923 	cpu->cpu_hat_info = NULL;
1924 }
1925 
1926 #ifdef __i386
1927 /*
1928  * On 32 bit kernels, loading a 64 bit PTE is a little tricky
1929  */
1930 x86pte_t
1931 get_pte64(x86pte_t *ptr)
1932 {
1933 	volatile uint32_t *p = (uint32_t *)ptr;
1934 	x86pte_t t;
1935 
1936 	ASSERT(mmu.pae_hat != 0);
1937 	for (;;) {
1938 		t = p[0];
1939 		t |= (uint64_t)p[1] << 32;
1940 		if ((t & 0xffffffff) == p[0])
1941 			return (t);
1942 	}
1943 }
1944 #endif /* __i386 */
1945 
1946 /*
1947  * Disable preemption and establish a mapping to the pagetable with the
1948  * given pfn. This is optimized for there case where it's the same
1949  * pfn as we last used referenced from this CPU.
1950  */
1951 static x86pte_t *
1952 x86pte_access_pagetable(htable_t *ht, uint_t index)
1953 {
1954 	/*
1955 	 * HTABLE_COPIED pagetables are contained in the hat_t
1956 	 */
1957 	if (ht->ht_flags & HTABLE_COPIED) {
1958 		ASSERT3U(index, <, ht->ht_hat->hat_num_copied);
1959 		return (PT_INDEX_PTR(ht->ht_hat->hat_copied_ptes, index));
1960 	}
1961 	return (x86pte_mapin(ht->ht_pfn, index, ht));
1962 }
1963 
1964 /*
1965  * map the given pfn into the page table window.
1966  */
1967 /*ARGSUSED*/
1968 x86pte_t *
1969 x86pte_mapin(pfn_t pfn, uint_t index, htable_t *ht)
1970 {
1971 	x86pte_t *pteptr;
1972 	x86pte_t pte = 0;
1973 	x86pte_t newpte;
1974 	int x;
1975 
1976 	ASSERT(pfn != PFN_INVALID);
1977 
1978 	if (!khat_running) {
1979 		caddr_t va = kbm_remap_window(pfn_to_pa(pfn), 1);
1980 		return (PT_INDEX_PTR(va, index));
1981 	}
1982 
1983 	/*
1984 	 * If kpm is available, use it.
1985 	 */
1986 	if (kpm_vbase)
1987 		return (PT_INDEX_PTR(hat_kpm_pfn2va(pfn), index));
1988 
1989 	/*
1990 	 * Disable preemption and grab the CPU's hci_mutex
1991 	 */
1992 	kpreempt_disable();
1993 
1994 	ASSERT(CPU->cpu_hat_info != NULL);
1995 	ASSERT(!(getcr4() & CR4_PCIDE));
1996 
1997 	mutex_enter(&CPU->cpu_hat_info->hci_mutex);
1998 	x = PWIN_TABLE(CPU->cpu_id);
1999 	pteptr = (x86pte_t *)PWIN_PTE_VA(x);
2000 #ifndef __xpv
2001 	if (mmu.pae_hat)
2002 		pte = *pteptr;
2003 	else
2004 		pte = *(x86pte32_t *)pteptr;
2005 #endif
2006 
2007 	newpte = MAKEPTE(pfn, 0) | mmu.pt_global | mmu.pt_nx;
2008 
2009 	/*
2010 	 * For hardware we can use a writable mapping.
2011 	 */
2012 #ifdef __xpv
2013 	if (IN_XPV_PANIC())
2014 #endif
2015 		newpte |= PT_WRITABLE;
2016 
2017 	if (!PTE_EQUIV(newpte, pte)) {
2018 
2019 #ifdef __xpv
2020 		if (!IN_XPV_PANIC()) {
2021 			xen_map(newpte, PWIN_VA(x));
2022 		} else
2023 #endif
2024 		{
2025 			XPV_ALLOW_PAGETABLE_UPDATES();
2026 			if (mmu.pae_hat)
2027 				*pteptr = newpte;
2028 			else
2029 				*(x86pte32_t *)pteptr = newpte;
2030 			XPV_DISALLOW_PAGETABLE_UPDATES();
2031 			mmu_flush_tlb_kpage((uintptr_t)PWIN_VA(x));
2032 		}
2033 	}
2034 	return (PT_INDEX_PTR(PWIN_VA(x), index));
2035 }
2036 
2037 /*
2038  * Release access to a page table.
2039  */
2040 static void
2041 x86pte_release_pagetable(htable_t *ht)
2042 {
2043 	if (ht->ht_flags & HTABLE_COPIED)
2044 		return;
2045 
2046 	x86pte_mapout();
2047 }
2048 
2049 void
2050 x86pte_mapout(void)
2051 {
2052 	if (kpm_vbase != NULL || !khat_running)
2053 		return;
2054 
2055 	/*
2056 	 * Drop the CPU's hci_mutex and restore preemption.
2057 	 */
2058 #ifdef __xpv
2059 	if (!IN_XPV_PANIC()) {
2060 		uintptr_t va;
2061 
2062 		/*
2063 		 * We need to always clear the mapping in case a page
2064 		 * that was once a page table page is ballooned out.
2065 		 */
2066 		va = (uintptr_t)PWIN_VA(PWIN_TABLE(CPU->cpu_id));
2067 		(void) HYPERVISOR_update_va_mapping(va, 0,
2068 		    UVMF_INVLPG | UVMF_LOCAL);
2069 	}
2070 #endif
2071 	mutex_exit(&CPU->cpu_hat_info->hci_mutex);
2072 	kpreempt_enable();
2073 }
2074 
2075 /*
2076  * Atomic retrieval of a pagetable entry
2077  */
2078 x86pte_t
2079 x86pte_get(htable_t *ht, uint_t entry)
2080 {
2081 	x86pte_t	pte;
2082 	x86pte_t	*ptep;
2083 
2084 	/*
2085 	 * Be careful that loading PAE entries in 32 bit kernel is atomic.
2086 	 */
2087 	ASSERT(entry < mmu.ptes_per_table);
2088 	ptep = x86pte_access_pagetable(ht, entry);
2089 	pte = GET_PTE(ptep);
2090 	x86pte_release_pagetable(ht);
2091 	return (pte);
2092 }
2093 
2094 /*
2095  * Atomic unconditional set of a page table entry, it returns the previous
2096  * value. For pre-existing mappings if the PFN changes, then we don't care
2097  * about the old pte's REF / MOD bits. If the PFN remains the same, we leave
2098  * the MOD/REF bits unchanged.
2099  *
2100  * If asked to overwrite a link to a lower page table with a large page
2101  * mapping, this routine returns the special value of LPAGE_ERROR. This
2102  * allows the upper HAT layers to retry with a smaller mapping size.
2103  */
2104 x86pte_t
2105 x86pte_set(htable_t *ht, uint_t entry, x86pte_t new, void *ptr)
2106 {
2107 	x86pte_t	old;
2108 	x86pte_t	prev;
2109 	x86pte_t	*ptep;
2110 	level_t		l = ht->ht_level;
2111 	x86pte_t	pfn_mask = (l != 0) ? PT_PADDR_LGPG : PT_PADDR;
2112 	x86pte_t	n;
2113 	uintptr_t	addr = htable_e2va(ht, entry);
2114 	hat_t		*hat = ht->ht_hat;
2115 
2116 	ASSERT(new != 0); /* don't use to invalidate a PTE, see x86pte_update */
2117 	ASSERT(!(ht->ht_flags & HTABLE_SHARED_PFN));
2118 	if (ptr == NULL)
2119 		ptep = x86pte_access_pagetable(ht, entry);
2120 	else
2121 		ptep = ptr;
2122 
2123 	/*
2124 	 * Install the new PTE. If remapping the same PFN, then
2125 	 * copy existing REF/MOD bits to new mapping.
2126 	 */
2127 	do {
2128 		prev = GET_PTE(ptep);
2129 		n = new;
2130 		if (PTE_ISVALID(n) && (prev & pfn_mask) == (new & pfn_mask))
2131 			n |= prev & (PT_REF | PT_MOD);
2132 
2133 		/*
2134 		 * Another thread may have installed this mapping already,
2135 		 * flush the local TLB and be done.
2136 		 */
2137 		if (prev == n) {
2138 			old = new;
2139 #ifdef __xpv
2140 			if (!IN_XPV_PANIC())
2141 				xen_flush_va((caddr_t)addr);
2142 			else
2143 #endif
2144 				mmu_flush_tlb_page(addr);
2145 			goto done;
2146 		}
2147 
2148 		/*
2149 		 * Detect if we have a collision of installing a large
2150 		 * page mapping where there already is a lower page table.
2151 		 */
2152 		if (l > 0 && (prev & PT_VALID) && !(prev & PT_PAGESIZE)) {
2153 			old = LPAGE_ERROR;
2154 			goto done;
2155 		}
2156 
2157 		XPV_ALLOW_PAGETABLE_UPDATES();
2158 		old = CAS_PTE(ptep, prev, n);
2159 		XPV_DISALLOW_PAGETABLE_UPDATES();
2160 	} while (old != prev);
2161 
2162 	/*
2163 	 * Do a TLB demap if needed, ie. the old pte was valid.
2164 	 *
2165 	 * Note that a stale TLB writeback to the PTE here either can't happen
2166 	 * or doesn't matter. The PFN can only change for NOSYNC|NOCONSIST
2167 	 * mappings, but they were created with REF and MOD already set, so
2168 	 * no stale writeback will happen.
2169 	 *
2170 	 * Segmap is the only place where remaps happen on the same pfn and for
2171 	 * that we want to preserve the stale REF/MOD bits.
2172 	 */
2173 	if (old & PT_REF)
2174 		hat_tlb_inval(hat, addr);
2175 
2176 done:
2177 	if (ptr == NULL)
2178 		x86pte_release_pagetable(ht);
2179 	return (old);
2180 }
2181 
2182 /*
2183  * Atomic compare and swap of a page table entry. No TLB invalidates are done.
2184  * This is used for links between pagetables of different levels.
2185  * Note we always create these links with dirty/access set, so they should
2186  * never change.
2187  */
2188 x86pte_t
2189 x86pte_cas(htable_t *ht, uint_t entry, x86pte_t old, x86pte_t new)
2190 {
2191 	x86pte_t	pte;
2192 	x86pte_t	*ptep;
2193 #ifdef __xpv
2194 	/*
2195 	 * We can't use writable pagetables for upper level tables, so fake it.
2196 	 */
2197 	mmu_update_t t[2];
2198 	int cnt = 1;
2199 	int count;
2200 	maddr_t ma;
2201 
2202 	if (!IN_XPV_PANIC()) {
2203 		ASSERT(!(ht->ht_flags & HTABLE_COPIED));
2204 		ma = pa_to_ma(PT_INDEX_PHYSADDR(pfn_to_pa(ht->ht_pfn), entry));
2205 		t[0].ptr = ma | MMU_NORMAL_PT_UPDATE;
2206 		t[0].val = new;
2207 
2208 #if defined(__amd64)
2209 		/*
2210 		 * On the 64-bit hypervisor we need to maintain the user mode
2211 		 * top page table too.
2212 		 */
2213 		if (ht->ht_level == mmu.max_level && ht->ht_hat != kas.a_hat) {
2214 			ma = pa_to_ma(PT_INDEX_PHYSADDR(pfn_to_pa(
2215 			    ht->ht_hat->hat_user_ptable), entry));
2216 			t[1].ptr = ma | MMU_NORMAL_PT_UPDATE;
2217 			t[1].val = new;
2218 			++cnt;
2219 		}
2220 #endif	/* __amd64 */
2221 
2222 		if (HYPERVISOR_mmu_update(t, cnt, &count, DOMID_SELF))
2223 			panic("HYPERVISOR_mmu_update() failed");
2224 		ASSERT(count == cnt);
2225 		return (old);
2226 	}
2227 #endif
2228 	ptep = x86pte_access_pagetable(ht, entry);
2229 	XPV_ALLOW_PAGETABLE_UPDATES();
2230 	pte = CAS_PTE(ptep, old, new);
2231 	XPV_DISALLOW_PAGETABLE_UPDATES();
2232 	x86pte_release_pagetable(ht);
2233 	return (pte);
2234 }
2235 
2236 /*
2237  * Invalidate a page table entry as long as it currently maps something that
2238  * matches the value determined by expect.
2239  *
2240  * If tlb is set, also invalidates any TLB entries.
2241  *
2242  * Returns the previous value of the PTE.
2243  */
2244 x86pte_t
2245 x86pte_inval(
2246 	htable_t *ht,
2247 	uint_t entry,
2248 	x86pte_t expect,
2249 	x86pte_t *pte_ptr,
2250 	boolean_t tlb)
2251 {
2252 	x86pte_t	*ptep;
2253 	x86pte_t	oldpte;
2254 	x86pte_t	found;
2255 
2256 	ASSERT(!(ht->ht_flags & HTABLE_SHARED_PFN));
2257 	ASSERT(ht->ht_level <= mmu.max_page_level);
2258 
2259 	if (pte_ptr != NULL)
2260 		ptep = pte_ptr;
2261 	else
2262 		ptep = x86pte_access_pagetable(ht, entry);
2263 
2264 #if defined(__xpv)
2265 	/*
2266 	 * If exit()ing just use HYPERVISOR_mmu_update(), as we can't be racing
2267 	 * with anything else.
2268 	 */
2269 	if ((ht->ht_hat->hat_flags & HAT_FREEING) && !IN_XPV_PANIC()) {
2270 		int count;
2271 		mmu_update_t t[1];
2272 		maddr_t ma;
2273 
2274 		oldpte = GET_PTE(ptep);
2275 		if (expect != 0 && (oldpte & PT_PADDR) != (expect & PT_PADDR))
2276 			goto done;
2277 		ma = pa_to_ma(PT_INDEX_PHYSADDR(pfn_to_pa(ht->ht_pfn), entry));
2278 		t[0].ptr = ma | MMU_NORMAL_PT_UPDATE;
2279 		t[0].val = 0;
2280 		if (HYPERVISOR_mmu_update(t, 1, &count, DOMID_SELF))
2281 			panic("HYPERVISOR_mmu_update() failed");
2282 		ASSERT(count == 1);
2283 		goto done;
2284 	}
2285 #endif /* __xpv */
2286 
2287 	/*
2288 	 * Note that the loop is needed to handle changes due to h/w updating
2289 	 * of PT_MOD/PT_REF.
2290 	 */
2291 	do {
2292 		oldpte = GET_PTE(ptep);
2293 		if (expect != 0 && (oldpte & PT_PADDR) != (expect & PT_PADDR))
2294 			goto done;
2295 		XPV_ALLOW_PAGETABLE_UPDATES();
2296 		found = CAS_PTE(ptep, oldpte, 0);
2297 		XPV_DISALLOW_PAGETABLE_UPDATES();
2298 	} while (found != oldpte);
2299 	if (tlb && (oldpte & (PT_REF | PT_MOD)))
2300 		hat_tlb_inval(ht->ht_hat, htable_e2va(ht, entry));
2301 
2302 done:
2303 	if (pte_ptr == NULL)
2304 		x86pte_release_pagetable(ht);
2305 	return (oldpte);
2306 }
2307 
2308 /*
2309  * Change a page table entry af it currently matches the value in expect.
2310  */
2311 x86pte_t
2312 x86pte_update(
2313 	htable_t *ht,
2314 	uint_t entry,
2315 	x86pte_t expect,
2316 	x86pte_t new)
2317 {
2318 	x86pte_t	*ptep;
2319 	x86pte_t	found;
2320 
2321 	ASSERT(new != 0);
2322 	ASSERT(!(ht->ht_flags & HTABLE_SHARED_PFN));
2323 	ASSERT(ht->ht_level <= mmu.max_page_level);
2324 
2325 	ptep = x86pte_access_pagetable(ht, entry);
2326 	XPV_ALLOW_PAGETABLE_UPDATES();
2327 	found = CAS_PTE(ptep, expect, new);
2328 	XPV_DISALLOW_PAGETABLE_UPDATES();
2329 	if (found == expect) {
2330 		hat_tlb_inval(ht->ht_hat, htable_e2va(ht, entry));
2331 
2332 		/*
2333 		 * When removing write permission *and* clearing the
2334 		 * MOD bit, check if a write happened via a stale
2335 		 * TLB entry before the TLB shootdown finished.
2336 		 *
2337 		 * If it did happen, simply re-enable write permission and
2338 		 * act like the original CAS failed.
2339 		 */
2340 		if ((expect & (PT_WRITABLE | PT_MOD)) == PT_WRITABLE &&
2341 		    (new & (PT_WRITABLE | PT_MOD)) == 0 &&
2342 		    (GET_PTE(ptep) & PT_MOD) != 0) {
2343 			do {
2344 				found = GET_PTE(ptep);
2345 				XPV_ALLOW_PAGETABLE_UPDATES();
2346 				found =
2347 				    CAS_PTE(ptep, found, found | PT_WRITABLE);
2348 				XPV_DISALLOW_PAGETABLE_UPDATES();
2349 			} while ((found & PT_WRITABLE) == 0);
2350 		}
2351 	}
2352 	x86pte_release_pagetable(ht);
2353 	return (found);
2354 }
2355 
2356 #ifndef __xpv
2357 /*
2358  * Copy page tables - this is just a little more complicated than the
2359  * previous routines. Note that it's also not atomic! It also is never
2360  * used for HTABLE_COPIED pagetables.
2361  */
2362 void
2363 x86pte_copy(htable_t *src, htable_t *dest, uint_t entry, uint_t count)
2364 {
2365 	caddr_t	src_va;
2366 	caddr_t dst_va;
2367 	size_t size;
2368 	x86pte_t *pteptr;
2369 	x86pte_t pte;
2370 
2371 	ASSERT(khat_running);
2372 	ASSERT(!(dest->ht_flags & HTABLE_COPIED));
2373 	ASSERT(!(src->ht_flags & HTABLE_COPIED));
2374 	ASSERT(!(src->ht_flags & HTABLE_SHARED_PFN));
2375 	ASSERT(!(dest->ht_flags & HTABLE_SHARED_PFN));
2376 
2377 	/*
2378 	 * Acquire access to the CPU pagetable windows for the dest and source.
2379 	 */
2380 	dst_va = (caddr_t)x86pte_access_pagetable(dest, entry);
2381 	if (kpm_vbase) {
2382 		src_va = (caddr_t)
2383 		    PT_INDEX_PTR(hat_kpm_pfn2va(src->ht_pfn), entry);
2384 	} else {
2385 		uint_t x = PWIN_SRC(CPU->cpu_id);
2386 
2387 		ASSERT(!(getcr4() & CR4_PCIDE));
2388 
2389 		/*
2390 		 * Finish defining the src pagetable mapping
2391 		 */
2392 		src_va = (caddr_t)PT_INDEX_PTR(PWIN_VA(x), entry);
2393 		pte = MAKEPTE(src->ht_pfn, 0) | mmu.pt_global | mmu.pt_nx;
2394 		pteptr = (x86pte_t *)PWIN_PTE_VA(x);
2395 		if (mmu.pae_hat)
2396 			*pteptr = pte;
2397 		else
2398 			*(x86pte32_t *)pteptr = pte;
2399 		mmu_flush_tlb_kpage((uintptr_t)PWIN_VA(x));
2400 	}
2401 
2402 	/*
2403 	 * now do the copy
2404 	 */
2405 	size = count << mmu.pte_size_shift;
2406 	bcopy(src_va, dst_va, size);
2407 
2408 	x86pte_release_pagetable(dest);
2409 }
2410 
2411 #else /* __xpv */
2412 
2413 /*
2414  * The hypervisor only supports writable pagetables at level 0, so we have
2415  * to install these 1 by 1 the slow way.
2416  */
2417 void
2418 x86pte_copy(htable_t *src, htable_t *dest, uint_t entry, uint_t count)
2419 {
2420 	caddr_t	src_va;
2421 	x86pte_t pte;
2422 
2423 	ASSERT(!IN_XPV_PANIC());
2424 	src_va = (caddr_t)x86pte_access_pagetable(src, entry);
2425 	while (count) {
2426 		if (mmu.pae_hat)
2427 			pte = *(x86pte_t *)src_va;
2428 		else
2429 			pte = *(x86pte32_t *)src_va;
2430 		if (pte != 0) {
2431 			set_pteval(pfn_to_pa(dest->ht_pfn), entry,
2432 			    dest->ht_level, pte);
2433 #ifdef __amd64
2434 			if (dest->ht_level == mmu.max_level &&
2435 			    htable_e2va(dest, entry) < HYPERVISOR_VIRT_END)
2436 				set_pteval(
2437 				    pfn_to_pa(dest->ht_hat->hat_user_ptable),
2438 				    entry, dest->ht_level, pte);
2439 #endif
2440 		}
2441 		--count;
2442 		++entry;
2443 		src_va += mmu.pte_size;
2444 	}
2445 	x86pte_release_pagetable(src);
2446 }
2447 #endif /* __xpv */
2448 
2449 /*
2450  * Zero page table entries - Note this doesn't use atomic stores!
2451  */
2452 static void
2453 x86pte_zero(htable_t *dest, uint_t entry, uint_t count)
2454 {
2455 	caddr_t dst_va;
2456 	size_t size;
2457 #ifdef __xpv
2458 	int x = 0;
2459 	x86pte_t newpte;
2460 #endif
2461 
2462 	/*
2463 	 * Map in the page table to be zeroed.
2464 	 */
2465 	ASSERT(!(dest->ht_flags & HTABLE_SHARED_PFN));
2466 	ASSERT(!(dest->ht_flags & HTABLE_COPIED));
2467 
2468 	/*
2469 	 * On the hypervisor we don't use x86pte_access_pagetable() since
2470 	 * in this case the page is not pinned yet.
2471 	 */
2472 #ifdef __xpv
2473 	if (kpm_vbase == NULL) {
2474 		kpreempt_disable();
2475 		ASSERT(CPU->cpu_hat_info != NULL);
2476 		mutex_enter(&CPU->cpu_hat_info->hci_mutex);
2477 		x = PWIN_TABLE(CPU->cpu_id);
2478 		newpte = MAKEPTE(dest->ht_pfn, 0) | PT_WRITABLE;
2479 		xen_map(newpte, PWIN_VA(x));
2480 		dst_va = (caddr_t)PT_INDEX_PTR(PWIN_VA(x), entry);
2481 	} else
2482 #endif
2483 		dst_va = (caddr_t)x86pte_access_pagetable(dest, entry);
2484 
2485 	size = count << mmu.pte_size_shift;
2486 	ASSERT(size > BLOCKZEROALIGN);
2487 #ifdef __i386
2488 	if (!is_x86_feature(x86_featureset, X86FSET_SSE2))
2489 		bzero(dst_va, size);
2490 	else
2491 #endif
2492 		block_zero_no_xmm(dst_va, size);
2493 
2494 #ifdef __xpv
2495 	if (kpm_vbase == NULL) {
2496 		xen_map(0, PWIN_VA(x));
2497 		mutex_exit(&CPU->cpu_hat_info->hci_mutex);
2498 		kpreempt_enable();
2499 	} else
2500 #endif
2501 		x86pte_release_pagetable(dest);
2502 }
2503 
2504 /*
2505  * Called to ensure that all pagetables are in the system dump
2506  */
2507 void
2508 hat_dump(void)
2509 {
2510 	hat_t *hat;
2511 	uint_t h;
2512 	htable_t *ht;
2513 
2514 	/*
2515 	 * Dump all page tables
2516 	 */
2517 	for (hat = kas.a_hat; hat != NULL; hat = hat->hat_next) {
2518 		for (h = 0; h < hat->hat_num_hash; ++h) {
2519 			for (ht = hat->hat_ht_hash[h]; ht; ht = ht->ht_next) {
2520 				if ((ht->ht_flags & HTABLE_COPIED) == 0)
2521 					dump_page(ht->ht_pfn);
2522 			}
2523 		}
2524 	}
2525 }
2526