xref: /illumos-gate/usr/src/uts/i86pc/vm/htable.c (revision fff9db267fec9f40a5545420d9ce9f2893e2f6a6)
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 2007 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 #include <sys/types.h>
30 #include <sys/sysmacros.h>
31 #include <sys/kmem.h>
32 #include <sys/atomic.h>
33 #include <sys/bitmap.h>
34 #include <sys/machparam.h>
35 #include <sys/machsystm.h>
36 #include <sys/mman.h>
37 #include <sys/systm.h>
38 #include <sys/cpuvar.h>
39 #include <sys/thread.h>
40 #include <sys/proc.h>
41 #include <sys/cpu.h>
42 #include <sys/kmem.h>
43 #include <sys/disp.h>
44 #include <sys/vmem.h>
45 #include <sys/vmsystm.h>
46 #include <sys/promif.h>
47 #include <sys/var.h>
48 #include <sys/x86_archext.h>
49 #include <sys/archsystm.h>
50 #include <sys/bootconf.h>
51 #include <sys/dumphdr.h>
52 #include <vm/seg_kmem.h>
53 #include <vm/seg_kpm.h>
54 #include <vm/hat.h>
55 #include <vm/hat_i86.h>
56 #include <sys/cmn_err.h>
57 
58 #include <sys/bootinfo.h>
59 #include <vm/kboot_mmu.h>
60 
61 static void x86pte_zero(htable_t *dest, uint_t entry, uint_t count);
62 
63 kmem_cache_t *htable_cache;
64 
65 /*
66  * The variable htable_reserve_amount, rather than HTABLE_RESERVE_AMOUNT,
67  * is used in order to facilitate testing of the htable_steal() code.
68  * By resetting htable_reserve_amount to a lower value, we can force
69  * stealing to occur.  The reserve amount is a guess to get us through boot.
70  */
71 #define	HTABLE_RESERVE_AMOUNT	(200)
72 uint_t htable_reserve_amount = HTABLE_RESERVE_AMOUNT;
73 kmutex_t htable_reserve_mutex;
74 uint_t htable_reserve_cnt;
75 htable_t *htable_reserve_pool;
76 
77 /*
78  * Used to hand test htable_steal().
79  */
80 #ifdef DEBUG
81 ulong_t force_steal = 0;
82 ulong_t ptable_cnt = 0;
83 #endif
84 
85 /*
86  * This variable is so that we can tune this via /etc/system
87  * Any value works, but a power of two <= mmu.ptes_per_table is best.
88  */
89 uint_t htable_steal_passes = 8;
90 
91 /*
92  * mutex stuff for access to htable hash
93  */
94 #define	NUM_HTABLE_MUTEX 128
95 kmutex_t htable_mutex[NUM_HTABLE_MUTEX];
96 #define	HTABLE_MUTEX_HASH(h) ((h) & (NUM_HTABLE_MUTEX - 1))
97 
98 #define	HTABLE_ENTER(h)	mutex_enter(&htable_mutex[HTABLE_MUTEX_HASH(h)]);
99 #define	HTABLE_EXIT(h)	mutex_exit(&htable_mutex[HTABLE_MUTEX_HASH(h)]);
100 
101 /*
102  * forward declarations
103  */
104 static void link_ptp(htable_t *higher, htable_t *new, uintptr_t vaddr);
105 static void unlink_ptp(htable_t *higher, htable_t *old, uintptr_t vaddr);
106 static void htable_free(htable_t *ht);
107 static x86pte_t *x86pte_access_pagetable(htable_t *ht, uint_t index);
108 static void x86pte_release_pagetable(htable_t *ht);
109 static x86pte_t x86pte_cas(htable_t *ht, uint_t entry, x86pte_t old,
110 	x86pte_t new);
111 
112 /*
113  * A counter to track if we are stealing or reaping htables. When non-zero
114  * htable_free() will directly free htables (either to the reserve or kmem)
115  * instead of putting them in a hat's htable cache.
116  */
117 uint32_t htable_dont_cache = 0;
118 
119 /*
120  * Track the number of active pagetables, so we can know how many to reap
121  */
122 static uint32_t active_ptables = 0;
123 
124 /*
125  * Allocate a memory page for a hardware page table.
126  *
127  * A wrapper around page_get_physical(), with some extra checks.
128  */
129 static pfn_t
130 ptable_alloc(uintptr_t seed)
131 {
132 	pfn_t pfn;
133 	page_t *pp;
134 
135 	pfn = PFN_INVALID;
136 	atomic_add_32(&active_ptables, 1);
137 
138 	/*
139 	 * The first check is to see if there is memory in the system. If we
140 	 * drop to throttlefree, then fail the ptable_alloc() and let the
141 	 * stealing code kick in. Note that we have to do this test here,
142 	 * since the test in page_create_throttle() would let the NOSLEEP
143 	 * allocation go through and deplete the page reserves.
144 	 *
145 	 * The !NOMEMWAIT() lets pageout, fsflush, etc. skip this check.
146 	 */
147 	if (!NOMEMWAIT() && freemem <= throttlefree + 1)
148 		return (PFN_INVALID);
149 
150 #ifdef DEBUG
151 	/*
152 	 * This code makes htable_steal() easier to test. By setting
153 	 * force_steal we force pagetable allocations to fall
154 	 * into the stealing code. Roughly 1 in ever "force_steal"
155 	 * page table allocations will fail.
156 	 */
157 	if (proc_pageout != NULL && force_steal > 1 &&
158 	    ++ptable_cnt > force_steal) {
159 		ptable_cnt = 0;
160 		return (PFN_INVALID);
161 	}
162 #endif /* DEBUG */
163 
164 	pp = page_get_physical(seed);
165 	if (pp == NULL)
166 		return (PFN_INVALID);
167 	pfn = pp->p_pagenum;
168 	page_downgrade(pp);
169 	ASSERT(PAGE_SHARED(pp));
170 
171 	if (pfn == PFN_INVALID)
172 		panic("ptable_alloc(): Invalid PFN!!");
173 	HATSTAT_INC(hs_ptable_allocs);
174 	return (pfn);
175 }
176 
177 /*
178  * Free an htable's associated page table page.  See the comments
179  * for ptable_alloc().
180  */
181 static void
182 ptable_free(pfn_t pfn)
183 {
184 	page_t *pp = page_numtopp_nolock(pfn);
185 
186 	/*
187 	 * need to destroy the page used for the pagetable
188 	 */
189 	ASSERT(pfn != PFN_INVALID);
190 	HATSTAT_INC(hs_ptable_frees);
191 	atomic_add_32(&active_ptables, -1);
192 	if (pp == NULL)
193 		panic("ptable_free(): no page for pfn!");
194 	ASSERT(PAGE_SHARED(pp));
195 	ASSERT(pfn == pp->p_pagenum);
196 
197 	/*
198 	 * Get an exclusive lock, might have to wait for a kmem reader.
199 	 */
200 	if (!page_tryupgrade(pp)) {
201 		page_unlock(pp);
202 		/*
203 		 * RFE: we could change this to not loop forever
204 		 * George Cameron had some idea on how to do that.
205 		 * For now looping works - it's just like sfmmu.
206 		 */
207 		while (!page_lock(pp, SE_EXCL, (kmutex_t *)NULL, P_RECLAIM))
208 			continue;
209 	}
210 	page_free(pp, 1);
211 	page_unresv(1);
212 }
213 
214 /*
215  * Put one htable on the reserve list.
216  */
217 static void
218 htable_put_reserve(htable_t *ht)
219 {
220 	ht->ht_hat = NULL;		/* no longer tied to a hat */
221 	ASSERT(ht->ht_pfn == PFN_INVALID);
222 	HATSTAT_INC(hs_htable_rputs);
223 	mutex_enter(&htable_reserve_mutex);
224 	ht->ht_next = htable_reserve_pool;
225 	htable_reserve_pool = ht;
226 	++htable_reserve_cnt;
227 	mutex_exit(&htable_reserve_mutex);
228 }
229 
230 /*
231  * Take one htable from the reserve.
232  */
233 static htable_t *
234 htable_get_reserve(void)
235 {
236 	htable_t *ht = NULL;
237 
238 	mutex_enter(&htable_reserve_mutex);
239 	if (htable_reserve_cnt != 0) {
240 		ht = htable_reserve_pool;
241 		ASSERT(ht != NULL);
242 		ASSERT(ht->ht_pfn == PFN_INVALID);
243 		htable_reserve_pool = ht->ht_next;
244 		--htable_reserve_cnt;
245 		HATSTAT_INC(hs_htable_rgets);
246 	}
247 	mutex_exit(&htable_reserve_mutex);
248 	return (ht);
249 }
250 
251 /*
252  * Allocate initial htables and put them on the reserve list
253  */
254 void
255 htable_initial_reserve(uint_t count)
256 {
257 	htable_t *ht;
258 
259 	count += HTABLE_RESERVE_AMOUNT;
260 	while (count > 0) {
261 		ht = kmem_cache_alloc(htable_cache, KM_NOSLEEP);
262 		ASSERT(ht != NULL);
263 
264 		ASSERT(use_boot_reserve);
265 		ht->ht_pfn = PFN_INVALID;
266 		htable_put_reserve(ht);
267 		--count;
268 	}
269 }
270 
271 /*
272  * Readjust the reserves after a thread finishes using them.
273  */
274 void
275 htable_adjust_reserve()
276 {
277 	htable_t *ht;
278 
279 	/*
280 	 * Free any excess htables in the reserve list
281 	 */
282 	while (htable_reserve_cnt > htable_reserve_amount &&
283 	    !USE_HAT_RESERVES()) {
284 		ht = htable_get_reserve();
285 		if (ht == NULL)
286 			return;
287 		ASSERT(ht->ht_pfn == PFN_INVALID);
288 		kmem_cache_free(htable_cache, ht);
289 	}
290 }
291 
292 
293 /*
294  * This routine steals htables from user processes for htable_alloc() or
295  * for htable_reap().
296  */
297 static htable_t *
298 htable_steal(uint_t cnt)
299 {
300 	hat_t		*hat = kas.a_hat;	/* list starts with khat */
301 	htable_t	*list = NULL;
302 	htable_t	*ht;
303 	htable_t	*higher;
304 	uint_t		h;
305 	uint_t		h_start;
306 	static uint_t	h_seed = 0;
307 	uint_t		e;
308 	uintptr_t	va;
309 	x86pte_t	pte;
310 	uint_t		stolen = 0;
311 	uint_t		pass;
312 	uint_t		threshold;
313 
314 	/*
315 	 * Limit htable_steal_passes to something reasonable
316 	 */
317 	if (htable_steal_passes == 0)
318 		htable_steal_passes = 1;
319 	if (htable_steal_passes > mmu.ptes_per_table)
320 		htable_steal_passes = mmu.ptes_per_table;
321 
322 	/*
323 	 * Loop through all user hats. The 1st pass takes cached htables that
324 	 * aren't in use. The later passes steal by removing mappings, too.
325 	 */
326 	atomic_add_32(&htable_dont_cache, 1);
327 	for (pass = 0; pass <= htable_steal_passes && stolen < cnt; ++pass) {
328 		threshold = pass * mmu.ptes_per_table / htable_steal_passes;
329 		hat = kas.a_hat;
330 		for (;;) {
331 
332 			/*
333 			 * Clear the victim flag and move to next hat
334 			 */
335 			mutex_enter(&hat_list_lock);
336 			if (hat != kas.a_hat) {
337 				hat->hat_flags &= ~HAT_VICTIM;
338 				cv_broadcast(&hat_list_cv);
339 			}
340 			hat = hat->hat_next;
341 
342 			/*
343 			 * Skip any hat that is already being stolen from.
344 			 *
345 			 * We skip SHARED hats, as these are dummy
346 			 * hats that host ISM shared page tables.
347 			 *
348 			 * We also skip if HAT_FREEING because hat_pte_unmap()
349 			 * won't zero out the PTE's. That would lead to hitting
350 			 * stale PTEs either here or under hat_unload() when we
351 			 * steal and unload the same page table in competing
352 			 * threads.
353 			 */
354 			while (hat != NULL &&
355 			    (hat->hat_flags &
356 			    (HAT_VICTIM | HAT_SHARED | HAT_FREEING)) != 0)
357 				hat = hat->hat_next;
358 
359 			if (hat == NULL) {
360 				mutex_exit(&hat_list_lock);
361 				break;
362 			}
363 
364 			/*
365 			 * Are we finished?
366 			 */
367 			if (stolen == cnt) {
368 				/*
369 				 * Try to spread the pain of stealing,
370 				 * move victim HAT to the end of the HAT list.
371 				 */
372 				if (pass >= 1 && cnt == 1 &&
373 				    kas.a_hat->hat_prev != hat) {
374 
375 					/* unlink victim hat */
376 					if (hat->hat_prev)
377 						hat->hat_prev->hat_next =
378 						    hat->hat_next;
379 					else
380 						kas.a_hat->hat_next =
381 						    hat->hat_next;
382 					if (hat->hat_next)
383 						hat->hat_next->hat_prev =
384 						    hat->hat_prev;
385 					else
386 						kas.a_hat->hat_prev =
387 						    hat->hat_prev;
388 
389 
390 					/* relink at end of hat list */
391 					hat->hat_next = NULL;
392 					hat->hat_prev = kas.a_hat->hat_prev;
393 					if (hat->hat_prev)
394 						hat->hat_prev->hat_next = hat;
395 					else
396 						kas.a_hat->hat_next = hat;
397 					kas.a_hat->hat_prev = hat;
398 
399 				}
400 
401 				mutex_exit(&hat_list_lock);
402 				break;
403 			}
404 
405 			/*
406 			 * Mark the HAT as a stealing victim.
407 			 */
408 			hat->hat_flags |= HAT_VICTIM;
409 			mutex_exit(&hat_list_lock);
410 
411 			/*
412 			 * Take any htables from the hat's cached "free" list.
413 			 */
414 			hat_enter(hat);
415 			while ((ht = hat->hat_ht_cached) != NULL &&
416 			    stolen < cnt) {
417 				hat->hat_ht_cached = ht->ht_next;
418 				ht->ht_next = list;
419 				list = ht;
420 				++stolen;
421 			}
422 			hat_exit(hat);
423 
424 			/*
425 			 * Don't steal on first pass.
426 			 */
427 			if (pass == 0 || stolen == cnt)
428 				continue;
429 
430 			/*
431 			 * Search the active htables for one to steal.
432 			 * Start at a different hash bucket every time to
433 			 * help spread the pain of stealing.
434 			 */
435 			h = h_start = h_seed++ % hat->hat_num_hash;
436 			do {
437 				higher = NULL;
438 				HTABLE_ENTER(h);
439 				for (ht = hat->hat_ht_hash[h]; ht;
440 				    ht = ht->ht_next) {
441 
442 					/*
443 					 * Can we rule out reaping?
444 					 */
445 					if (ht->ht_busy != 0 ||
446 					    (ht->ht_flags & HTABLE_SHARED_PFN)||
447 					    ht->ht_level > 0 ||
448 					    ht->ht_valid_cnt > threshold ||
449 					    ht->ht_lock_cnt != 0)
450 						continue;
451 
452 					/*
453 					 * Increment busy so the htable can't
454 					 * disappear. We drop the htable mutex
455 					 * to avoid deadlocks with
456 					 * hat_pageunload() and the hment mutex
457 					 * while we call hat_pte_unmap()
458 					 */
459 					++ht->ht_busy;
460 					HTABLE_EXIT(h);
461 
462 					/*
463 					 * Try stealing.
464 					 * - unload and invalidate all PTEs
465 					 */
466 					for (e = 0, va = ht->ht_vaddr;
467 					    e < HTABLE_NUM_PTES(ht) &&
468 					    ht->ht_valid_cnt > 0 &&
469 					    ht->ht_busy == 1 &&
470 					    ht->ht_lock_cnt == 0;
471 					    ++e, va += MMU_PAGESIZE) {
472 						pte = x86pte_get(ht, e);
473 						if (!PTE_ISVALID(pte))
474 							continue;
475 						hat_pte_unmap(ht, e,
476 						    HAT_UNLOAD, pte, NULL);
477 					}
478 
479 					/*
480 					 * Reacquire htable lock. If we didn't
481 					 * remove all mappings in the table,
482 					 * or another thread added a new mapping
483 					 * behind us, give up on this table.
484 					 */
485 					HTABLE_ENTER(h);
486 					if (ht->ht_busy != 1 ||
487 					    ht->ht_valid_cnt != 0 ||
488 					    ht->ht_lock_cnt != 0) {
489 						--ht->ht_busy;
490 						continue;
491 					}
492 
493 					/*
494 					 * Steal it and unlink the page table.
495 					 */
496 					higher = ht->ht_parent;
497 					unlink_ptp(higher, ht, ht->ht_vaddr);
498 
499 					/*
500 					 * remove from the hash list
501 					 */
502 					if (ht->ht_next)
503 						ht->ht_next->ht_prev =
504 						    ht->ht_prev;
505 
506 					if (ht->ht_prev) {
507 						ht->ht_prev->ht_next =
508 						    ht->ht_next;
509 					} else {
510 						ASSERT(hat->hat_ht_hash[h] ==
511 						    ht);
512 						hat->hat_ht_hash[h] =
513 						    ht->ht_next;
514 					}
515 
516 					/*
517 					 * Break to outer loop to release the
518 					 * higher (ht_parent) pagetable. This
519 					 * spreads out the pain caused by
520 					 * pagefaults.
521 					 */
522 					ht->ht_next = list;
523 					list = ht;
524 					++stolen;
525 					break;
526 				}
527 				HTABLE_EXIT(h);
528 				if (higher != NULL)
529 					htable_release(higher);
530 				if (++h == hat->hat_num_hash)
531 					h = 0;
532 			} while (stolen < cnt && h != h_start);
533 		}
534 	}
535 	atomic_add_32(&htable_dont_cache, -1);
536 	return (list);
537 }
538 
539 
540 /*
541  * This is invoked from kmem when the system is low on memory.  We try
542  * to free hments, htables, and ptables to improve the memory situation.
543  */
544 /*ARGSUSED*/
545 static void
546 htable_reap(void *handle)
547 {
548 	uint_t		reap_cnt;
549 	htable_t	*list;
550 	htable_t	*ht;
551 
552 	HATSTAT_INC(hs_reap_attempts);
553 	if (!can_steal_post_boot)
554 		return;
555 
556 	/*
557 	 * Try to reap 5% of the page tables bounded by a maximum of
558 	 * 5% of physmem and a minimum of 10.
559 	 */
560 	reap_cnt = MIN(MAX(physmem / 20, active_ptables / 20), 10);
561 
562 	/*
563 	 * Let htable_steal() do the work, we just call htable_free()
564 	 */
565 	list = htable_steal(reap_cnt);
566 	while ((ht = list) != NULL) {
567 		list = ht->ht_next;
568 		HATSTAT_INC(hs_reaped);
569 		htable_free(ht);
570 	}
571 
572 	/*
573 	 * Free up excess reserves
574 	 */
575 	htable_adjust_reserve();
576 	hment_adjust_reserve();
577 }
578 
579 /*
580  * Allocate an htable, stealing one or using the reserve if necessary
581  */
582 static htable_t *
583 htable_alloc(
584 	hat_t		*hat,
585 	uintptr_t	vaddr,
586 	level_t		level,
587 	htable_t	*shared)
588 {
589 	htable_t	*ht = NULL;
590 	uint_t		is_vlp;
591 	uint_t		is_bare = 0;
592 	uint_t		need_to_zero = 1;
593 	int		kmflags = (can_steal_post_boot ? KM_NOSLEEP : KM_SLEEP);
594 
595 	if (level < 0 || level > TOP_LEVEL(hat))
596 		panic("htable_alloc(): level %d out of range\n", level);
597 
598 	is_vlp = (hat->hat_flags & HAT_VLP) && level == VLP_LEVEL;
599 	if (is_vlp || shared != NULL)
600 		is_bare = 1;
601 
602 	/*
603 	 * First reuse a cached htable from the hat_ht_cached field, this
604 	 * avoids unnecessary trips through kmem/page allocators.
605 	 */
606 	if (hat->hat_ht_cached != NULL && !is_bare) {
607 		hat_enter(hat);
608 		ht = hat->hat_ht_cached;
609 		if (ht != NULL) {
610 			hat->hat_ht_cached = ht->ht_next;
611 			need_to_zero = 0;
612 			/* XX64 ASSERT() they're all zero somehow */
613 			ASSERT(ht->ht_pfn != PFN_INVALID);
614 		}
615 		hat_exit(hat);
616 	}
617 
618 	if (ht == NULL) {
619 		/*
620 		 * Allocate an htable, possibly refilling the reserves.
621 		 */
622 		if (USE_HAT_RESERVES()) {
623 			ht = htable_get_reserve();
624 		} else {
625 			/*
626 			 * Donate successful htable allocations to the reserve.
627 			 */
628 			for (;;) {
629 				ht = kmem_cache_alloc(htable_cache, kmflags);
630 				if (ht == NULL)
631 					break;
632 				ht->ht_pfn = PFN_INVALID;
633 				if (USE_HAT_RESERVES() ||
634 				    htable_reserve_cnt >= htable_reserve_amount)
635 					break;
636 				htable_put_reserve(ht);
637 			}
638 		}
639 
640 		/*
641 		 * allocate a page for the hardware page table if needed
642 		 */
643 		if (ht != NULL && !is_bare) {
644 			ht->ht_hat = hat;
645 			ht->ht_pfn = ptable_alloc((uintptr_t)ht);
646 			if (ht->ht_pfn == PFN_INVALID) {
647 				if (USE_HAT_RESERVES())
648 					htable_put_reserve(ht);
649 				else
650 					kmem_cache_free(htable_cache, ht);
651 				ht = NULL;
652 			}
653 		}
654 	}
655 
656 	/*
657 	 * If allocations failed, kick off a kmem_reap() and resort to
658 	 * htable steal(). We may spin here if the system is very low on
659 	 * memory. If the kernel itself has consumed all memory and kmem_reap()
660 	 * can't free up anything, then we'll really get stuck here.
661 	 * That should only happen in a system where the administrator has
662 	 * misconfigured VM parameters via /etc/system.
663 	 */
664 	while (ht == NULL && can_steal_post_boot) {
665 		kmem_reap();
666 		ht = htable_steal(1);
667 		HATSTAT_INC(hs_steals);
668 
669 		/*
670 		 * If we stole for a bare htable, release the pagetable page.
671 		 */
672 		if (ht != NULL) {
673 			if (is_bare) {
674 				ptable_free(ht->ht_pfn);
675 				ht->ht_pfn = PFN_INVALID;
676 			}
677 		}
678 	}
679 
680 	/*
681 	 * All attempts to allocate or steal failed. This should only happen
682 	 * if we run out of memory during boot, due perhaps to a huge
683 	 * boot_archive. At this point there's no way to continue.
684 	 */
685 	if (ht == NULL)
686 		panic("htable_alloc(): couldn't steal\n");
687 
688 	/*
689 	 * Shared page tables have all entries locked and entries may not
690 	 * be added or deleted.
691 	 */
692 	ht->ht_flags = 0;
693 	if (shared != NULL) {
694 		ASSERT(shared->ht_valid_cnt > 0);
695 		ht->ht_flags |= HTABLE_SHARED_PFN;
696 		ht->ht_pfn = shared->ht_pfn;
697 		ht->ht_lock_cnt = 0;
698 		ht->ht_valid_cnt = 0;		/* updated in hat_share() */
699 		ht->ht_shares = shared;
700 		need_to_zero = 0;
701 	} else {
702 		ht->ht_shares = NULL;
703 		ht->ht_lock_cnt = 0;
704 		ht->ht_valid_cnt = 0;
705 	}
706 
707 	/*
708 	 * setup flags, etc. for VLP htables
709 	 */
710 	if (is_vlp) {
711 		ht->ht_flags |= HTABLE_VLP;
712 		ASSERT(ht->ht_pfn == PFN_INVALID);
713 		need_to_zero = 0;
714 	}
715 
716 	/*
717 	 * fill in the htable
718 	 */
719 	ht->ht_hat = hat;
720 	ht->ht_parent = NULL;
721 	ht->ht_vaddr = vaddr;
722 	ht->ht_level = level;
723 	ht->ht_busy = 1;
724 	ht->ht_next = NULL;
725 	ht->ht_prev = NULL;
726 
727 	/*
728 	 * Zero out any freshly allocated page table
729 	 */
730 	if (need_to_zero)
731 		x86pte_zero(ht, 0, mmu.ptes_per_table);
732 
733 	return (ht);
734 }
735 
736 /*
737  * Free up an htable, either to a hat's cached list, the reserves or
738  * back to kmem.
739  */
740 static void
741 htable_free(htable_t *ht)
742 {
743 	hat_t *hat = ht->ht_hat;
744 
745 	/*
746 	 * If the process isn't exiting, cache the free htable in the hat
747 	 * structure. We always do this for the boot reserve. We don't
748 	 * do this if the hat is exiting or we are stealing/reaping htables.
749 	 */
750 	if (hat != NULL &&
751 	    !(ht->ht_flags & HTABLE_SHARED_PFN) &&
752 	    (use_boot_reserve ||
753 	    (!(hat->hat_flags & HAT_FREEING) && !htable_dont_cache))) {
754 		ASSERT((ht->ht_flags & HTABLE_VLP) == 0);
755 		ASSERT(ht->ht_pfn != PFN_INVALID);
756 		hat_enter(hat);
757 		ht->ht_next = hat->hat_ht_cached;
758 		hat->hat_ht_cached = ht;
759 		hat_exit(hat);
760 		return;
761 	}
762 
763 	/*
764 	 * If we have a hardware page table, free it.
765 	 * We don't free page tables that are accessed by sharing.
766 	 */
767 	if (ht->ht_flags & HTABLE_SHARED_PFN) {
768 		ASSERT(ht->ht_pfn != PFN_INVALID);
769 	} else if (!(ht->ht_flags & HTABLE_VLP)) {
770 		ptable_free(ht->ht_pfn);
771 	}
772 	ht->ht_pfn = PFN_INVALID;
773 
774 	/*
775 	 * Free htables or put into reserves.
776 	 */
777 	if (USE_HAT_RESERVES() || htable_reserve_cnt < htable_reserve_amount) {
778 		htable_put_reserve(ht);
779 	} else {
780 		kmem_cache_free(htable_cache, ht);
781 		htable_adjust_reserve();
782 	}
783 }
784 
785 
786 /*
787  * This is called when a hat is being destroyed or swapped out. We reap all
788  * the remaining htables in the hat cache. If destroying all left over
789  * htables are also destroyed.
790  *
791  * We also don't need to invalidate any of the PTPs nor do any demapping.
792  */
793 void
794 htable_purge_hat(hat_t *hat)
795 {
796 	htable_t *ht;
797 	int h;
798 
799 	/*
800 	 * Purge the htable cache if just reaping.
801 	 */
802 	if (!(hat->hat_flags & HAT_FREEING)) {
803 		atomic_add_32(&htable_dont_cache, 1);
804 		for (;;) {
805 			hat_enter(hat);
806 			ht = hat->hat_ht_cached;
807 			if (ht == NULL) {
808 				hat_exit(hat);
809 				break;
810 			}
811 			hat->hat_ht_cached = ht->ht_next;
812 			hat_exit(hat);
813 			htable_free(ht);
814 		}
815 		atomic_add_32(&htable_dont_cache, -1);
816 		return;
817 	}
818 
819 	/*
820 	 * if freeing, no locking is needed
821 	 */
822 	while ((ht = hat->hat_ht_cached) != NULL) {
823 		hat->hat_ht_cached = ht->ht_next;
824 		htable_free(ht);
825 	}
826 
827 	/*
828 	 * walk thru the htable hash table and free all the htables in it.
829 	 */
830 	for (h = 0; h < hat->hat_num_hash; ++h) {
831 		while ((ht = hat->hat_ht_hash[h]) != NULL) {
832 			if (ht->ht_next)
833 				ht->ht_next->ht_prev = ht->ht_prev;
834 
835 			if (ht->ht_prev) {
836 				ht->ht_prev->ht_next = ht->ht_next;
837 			} else {
838 				ASSERT(hat->hat_ht_hash[h] == ht);
839 				hat->hat_ht_hash[h] = ht->ht_next;
840 			}
841 			htable_free(ht);
842 		}
843 	}
844 }
845 
846 /*
847  * Unlink an entry for a table at vaddr and level out of the existing table
848  * one level higher. We are always holding the HASH_ENTER() when doing this.
849  */
850 static void
851 unlink_ptp(htable_t *higher, htable_t *old, uintptr_t vaddr)
852 {
853 	uint_t		entry = htable_va2entry(vaddr, higher);
854 	x86pte_t	expect = MAKEPTP(old->ht_pfn, old->ht_level);
855 	x86pte_t	found;
856 	hat_t		*hat = old->ht_hat;
857 
858 	ASSERT(higher->ht_busy > 0);
859 	ASSERT(higher->ht_valid_cnt > 0);
860 	ASSERT(old->ht_valid_cnt == 0);
861 	found = x86pte_cas(higher, entry, expect, 0);
862 	if (found != expect)
863 		panic("Bad PTP found=" FMT_PTE ", expected=" FMT_PTE,
864 		    found, expect);
865 
866 	/*
867 	 * When a top level VLP page table entry changes, we must issue
868 	 * a reload of cr3 on all processors.
869 	 *
870 	 * If we don't need do do that, then we still have to INVLPG against
871 	 * an address covered by the inner page table, as the latest processors
872 	 * have TLB-like caches for non-leaf page table entries.
873 	 */
874 	if (!(hat->hat_flags & HAT_FREEING)) {
875 		hat_tlb_inval(hat, (higher->ht_flags & HTABLE_VLP) ?
876 		    DEMAP_ALL_ADDR : old->ht_vaddr);
877 	}
878 
879 	HTABLE_DEC(higher->ht_valid_cnt);
880 }
881 
882 /*
883  * Link an entry for a new table at vaddr and level into the existing table
884  * one level higher. We are always holding the HASH_ENTER() when doing this.
885  */
886 static void
887 link_ptp(htable_t *higher, htable_t *new, uintptr_t vaddr)
888 {
889 	uint_t		entry = htable_va2entry(vaddr, higher);
890 	x86pte_t	newptp = MAKEPTP(new->ht_pfn, new->ht_level);
891 	x86pte_t	found;
892 
893 	ASSERT(higher->ht_busy > 0);
894 
895 	ASSERT(new->ht_level != mmu.max_level);
896 
897 	HTABLE_INC(higher->ht_valid_cnt);
898 
899 	found = x86pte_cas(higher, entry, 0, newptp);
900 	if ((found & ~PT_REF) != 0)
901 		panic("HAT: ptp not 0, found=" FMT_PTE, found);
902 
903 	/*
904 	 * When any top level VLP page table entry changes, we must issue
905 	 * a reload of cr3 on all processors using it.
906 	 * We also need to do this for the kernel hat on PAE 32 bit kernel.
907 	 */
908 	if (
909 #ifdef __i386
910 	    (higher->ht_hat == kas.a_hat && higher->ht_level == VLP_LEVEL) ||
911 #endif
912 	    (higher->ht_flags & HTABLE_VLP))
913 		hat_tlb_inval(higher->ht_hat, DEMAP_ALL_ADDR);
914 }
915 
916 /*
917  * Release of hold on an htable. If this is the last use and the pagetable
918  * is empty we may want to free it, then recursively look at the pagetable
919  * above it. The recursion is handled by the outer while() loop.
920  */
921 void
922 htable_release(htable_t *ht)
923 {
924 	uint_t		hashval;
925 	htable_t	*shared;
926 	htable_t	*higher;
927 	hat_t		*hat;
928 	uintptr_t	va;
929 	level_t		level;
930 
931 	while (ht != NULL) {
932 		shared = NULL;
933 		for (;;) {
934 			hat = ht->ht_hat;
935 			va = ht->ht_vaddr;
936 			level = ht->ht_level;
937 			hashval = HTABLE_HASH(hat, va, level);
938 
939 			/*
940 			 * The common case is that this isn't the last use of
941 			 * an htable so we don't want to free the htable.
942 			 */
943 			HTABLE_ENTER(hashval);
944 			ASSERT(ht->ht_lock_cnt == 0 || ht->ht_valid_cnt > 0);
945 			ASSERT(ht->ht_valid_cnt >= 0);
946 			ASSERT(ht->ht_busy > 0);
947 			if (ht->ht_valid_cnt > 0)
948 				break;
949 			if (ht->ht_busy > 1)
950 				break;
951 
952 			/*
953 			 * we always release empty shared htables
954 			 */
955 			if (!(ht->ht_flags & HTABLE_SHARED_PFN)) {
956 
957 				/*
958 				 * don't release if in address space tear down
959 				 */
960 				if (hat->hat_flags & HAT_FREEING)
961 					break;
962 
963 				/*
964 				 * At and above max_page_level, free if it's for
965 				 * a boot-time kernel mapping below kernelbase.
966 				 */
967 				if (level >= mmu.max_page_level &&
968 				    (hat != kas.a_hat || va >= kernelbase))
969 					break;
970 			}
971 
972 			/*
973 			 * Remember if we destroy an htable that shares its PFN
974 			 * from elsewhere.
975 			 */
976 			if (ht->ht_flags & HTABLE_SHARED_PFN) {
977 				ASSERT(shared == NULL);
978 				shared = ht->ht_shares;
979 				HATSTAT_INC(hs_htable_unshared);
980 			}
981 
982 			/*
983 			 * Handle release of a table and freeing the htable_t.
984 			 * Unlink it from the table higher (ie. ht_parent).
985 			 */
986 			ASSERT(ht->ht_lock_cnt == 0);
987 			higher = ht->ht_parent;
988 			ASSERT(higher != NULL);
989 
990 			/*
991 			 * Unlink the pagetable.
992 			 */
993 			unlink_ptp(higher, ht, va);
994 
995 			/*
996 			 * remove this htable from its hash list
997 			 */
998 			if (ht->ht_next)
999 				ht->ht_next->ht_prev = ht->ht_prev;
1000 
1001 			if (ht->ht_prev) {
1002 				ht->ht_prev->ht_next = ht->ht_next;
1003 			} else {
1004 				ASSERT(hat->hat_ht_hash[hashval] == ht);
1005 				hat->hat_ht_hash[hashval] = ht->ht_next;
1006 			}
1007 			HTABLE_EXIT(hashval);
1008 			htable_free(ht);
1009 			ht = higher;
1010 		}
1011 
1012 		ASSERT(ht->ht_busy >= 1);
1013 		--ht->ht_busy;
1014 		HTABLE_EXIT(hashval);
1015 
1016 		/*
1017 		 * If we released a shared htable, do a release on the htable
1018 		 * from which it shared
1019 		 */
1020 		ht = shared;
1021 	}
1022 }
1023 
1024 /*
1025  * Find the htable for the pagetable at the given level for the given address.
1026  * If found acquires a hold that eventually needs to be htable_release()d
1027  */
1028 htable_t *
1029 htable_lookup(hat_t *hat, uintptr_t vaddr, level_t level)
1030 {
1031 	uintptr_t	base;
1032 	uint_t		hashval;
1033 	htable_t	*ht = NULL;
1034 
1035 	ASSERT(level >= 0);
1036 	ASSERT(level <= TOP_LEVEL(hat));
1037 
1038 	if (level == TOP_LEVEL(hat)) {
1039 #if defined(__amd64)
1040 		/*
1041 		 * 32 bit address spaces on 64 bit kernels need to check
1042 		 * for overflow of the 32 bit address space
1043 		 */
1044 		if ((hat->hat_flags & HAT_VLP) && vaddr >= ((uint64_t)1 << 32))
1045 			return (NULL);
1046 #endif
1047 		base = 0;
1048 	} else {
1049 		base = vaddr & LEVEL_MASK(level + 1);
1050 	}
1051 
1052 	hashval = HTABLE_HASH(hat, base, level);
1053 	HTABLE_ENTER(hashval);
1054 	for (ht = hat->hat_ht_hash[hashval]; ht; ht = ht->ht_next) {
1055 		if (ht->ht_hat == hat &&
1056 		    ht->ht_vaddr == base &&
1057 		    ht->ht_level == level)
1058 			break;
1059 	}
1060 	if (ht)
1061 		++ht->ht_busy;
1062 
1063 	HTABLE_EXIT(hashval);
1064 	return (ht);
1065 }
1066 
1067 /*
1068  * Acquires a hold on a known htable (from a locked hment entry).
1069  */
1070 void
1071 htable_acquire(htable_t *ht)
1072 {
1073 	hat_t		*hat = ht->ht_hat;
1074 	level_t		level = ht->ht_level;
1075 	uintptr_t	base = ht->ht_vaddr;
1076 	uint_t		hashval = HTABLE_HASH(hat, base, level);
1077 
1078 	HTABLE_ENTER(hashval);
1079 #ifdef DEBUG
1080 	/*
1081 	 * make sure the htable is there
1082 	 */
1083 	{
1084 		htable_t	*h;
1085 
1086 		for (h = hat->hat_ht_hash[hashval];
1087 		    h && h != ht;
1088 		    h = h->ht_next)
1089 			;
1090 		ASSERT(h == ht);
1091 	}
1092 #endif /* DEBUG */
1093 	++ht->ht_busy;
1094 	HTABLE_EXIT(hashval);
1095 }
1096 
1097 /*
1098  * Find the htable for the pagetable at the given level for the given address.
1099  * If found acquires a hold that eventually needs to be htable_release()d
1100  * If not found the table is created.
1101  *
1102  * Since we can't hold a hash table mutex during allocation, we have to
1103  * drop it and redo the search on a create. Then we may have to free the newly
1104  * allocated htable if another thread raced in and created it ahead of us.
1105  */
1106 htable_t *
1107 htable_create(
1108 	hat_t		*hat,
1109 	uintptr_t	vaddr,
1110 	level_t		level,
1111 	htable_t	*shared)
1112 {
1113 	uint_t		h;
1114 	level_t		l;
1115 	uintptr_t	base;
1116 	htable_t	*ht;
1117 	htable_t	*higher = NULL;
1118 	htable_t	*new = NULL;
1119 
1120 	if (level < 0 || level > TOP_LEVEL(hat))
1121 		panic("htable_create(): level %d out of range\n", level);
1122 
1123 	/*
1124 	 * Create the page tables in top down order.
1125 	 */
1126 	for (l = TOP_LEVEL(hat); l >= level; --l) {
1127 		new = NULL;
1128 		if (l == TOP_LEVEL(hat))
1129 			base = 0;
1130 		else
1131 			base = vaddr & LEVEL_MASK(l + 1);
1132 
1133 		h = HTABLE_HASH(hat, base, l);
1134 try_again:
1135 		/*
1136 		 * look up the htable at this level
1137 		 */
1138 		HTABLE_ENTER(h);
1139 		if (l == TOP_LEVEL(hat)) {
1140 			ht = hat->hat_htable;
1141 		} else {
1142 			for (ht = hat->hat_ht_hash[h]; ht; ht = ht->ht_next) {
1143 				ASSERT(ht->ht_hat == hat);
1144 				if (ht->ht_vaddr == base &&
1145 				    ht->ht_level == l)
1146 					break;
1147 			}
1148 		}
1149 
1150 		/*
1151 		 * if we found the htable, increment its busy cnt
1152 		 * and if we had allocated a new htable, free it.
1153 		 */
1154 		if (ht != NULL) {
1155 			/*
1156 			 * If we find a pre-existing shared table, it must
1157 			 * share from the same place.
1158 			 */
1159 			if (l == level && shared && ht->ht_shares &&
1160 			    ht->ht_shares != shared) {
1161 				panic("htable shared from wrong place "
1162 				    "found htable=%p shared=%p", ht, shared);
1163 			}
1164 			++ht->ht_busy;
1165 			HTABLE_EXIT(h);
1166 			if (new)
1167 				htable_free(new);
1168 			if (higher != NULL)
1169 				htable_release(higher);
1170 			higher = ht;
1171 
1172 		/*
1173 		 * if we didn't find it on the first search
1174 		 * allocate a new one and search again
1175 		 */
1176 		} else if (new == NULL) {
1177 			HTABLE_EXIT(h);
1178 			new = htable_alloc(hat, base, l,
1179 			    l == level ? shared : NULL);
1180 			goto try_again;
1181 
1182 		/*
1183 		 * 2nd search and still not there, use "new" table
1184 		 * Link new table into higher, when not at top level.
1185 		 */
1186 		} else {
1187 			ht = new;
1188 			if (higher != NULL) {
1189 				link_ptp(higher, ht, base);
1190 				ht->ht_parent = higher;
1191 			}
1192 			ht->ht_next = hat->hat_ht_hash[h];
1193 			ASSERT(ht->ht_prev == NULL);
1194 			if (hat->hat_ht_hash[h])
1195 				hat->hat_ht_hash[h]->ht_prev = ht;
1196 			hat->hat_ht_hash[h] = ht;
1197 			HTABLE_EXIT(h);
1198 
1199 			/*
1200 			 * Note we don't do htable_release(higher).
1201 			 * That happens recursively when "new" is removed by
1202 			 * htable_release() or htable_steal().
1203 			 */
1204 			higher = ht;
1205 
1206 			/*
1207 			 * If we just created a new shared page table we
1208 			 * increment the shared htable's busy count, so that
1209 			 * it can't be the victim of a steal even if it's empty.
1210 			 */
1211 			if (l == level && shared) {
1212 				(void) htable_lookup(shared->ht_hat,
1213 				    shared->ht_vaddr, shared->ht_level);
1214 				HATSTAT_INC(hs_htable_shared);
1215 			}
1216 		}
1217 	}
1218 
1219 	return (ht);
1220 }
1221 
1222 /*
1223  * Inherit initial pagetables from the boot program.
1224  */
1225 void
1226 htable_attach(
1227 	hat_t *hat,
1228 	uintptr_t base,
1229 	level_t level,
1230 	htable_t *parent,
1231 	pfn_t pfn)
1232 {
1233 	htable_t	*ht;
1234 	uint_t		h;
1235 	uint_t		i;
1236 	x86pte_t	pte;
1237 	x86pte_t	*ptep;
1238 	page_t		*pp;
1239 	extern page_t	*boot_claim_page(pfn_t);
1240 
1241 	ht = htable_get_reserve();
1242 	if (level == mmu.max_level)
1243 		kas.a_hat->hat_htable = ht;
1244 	ht->ht_hat = hat;
1245 	ht->ht_parent = parent;
1246 	ht->ht_vaddr = base;
1247 	ht->ht_level = level;
1248 	ht->ht_busy = 1;
1249 	ht->ht_next = NULL;
1250 	ht->ht_prev = NULL;
1251 	ht->ht_flags = 0;
1252 	ht->ht_pfn = pfn;
1253 	ht->ht_lock_cnt = 0;
1254 	ht->ht_valid_cnt = 0;
1255 	if (parent != NULL)
1256 		++parent->ht_busy;
1257 
1258 	h = HTABLE_HASH(hat, base, level);
1259 	HTABLE_ENTER(h);
1260 	ht->ht_next = hat->hat_ht_hash[h];
1261 	ASSERT(ht->ht_prev == NULL);
1262 	if (hat->hat_ht_hash[h])
1263 		hat->hat_ht_hash[h]->ht_prev = ht;
1264 	hat->hat_ht_hash[h] = ht;
1265 	HTABLE_EXIT(h);
1266 
1267 	/*
1268 	 * make sure the page table physical page is not FREE
1269 	 */
1270 	if (page_resv(1, KM_NOSLEEP) == 0)
1271 		panic("page_resv() failed in ptable alloc");
1272 
1273 	pp = boot_claim_page(pfn);
1274 	ASSERT(pp != NULL);
1275 	page_downgrade(pp);
1276 	/*
1277 	 * Record in the page_t that is a pagetable for segkpm setup.
1278 	 */
1279 	if (kpm_vbase)
1280 		pp->p_index = 1;
1281 
1282 	/*
1283 	 * Count valid mappings and recursively attach lower level pagetables.
1284 	 */
1285 	ptep = kbm_remap_window(pfn_to_pa(pfn), 0);
1286 	for (i = 0; i < HTABLE_NUM_PTES(ht); ++i) {
1287 		if (mmu.pae_hat)
1288 			pte = ptep[i];
1289 		else
1290 			pte = ((x86pte32_t *)ptep)[i];
1291 		if (!IN_HYPERVISOR_VA(base) && PTE_ISVALID(pte)) {
1292 			++ht->ht_valid_cnt;
1293 			if (!PTE_ISPAGE(pte, level)) {
1294 				htable_attach(hat, base, level - 1,
1295 				    ht, PTE2PFN(pte, level));
1296 				ptep = kbm_remap_window(pfn_to_pa(pfn), 0);
1297 			}
1298 		}
1299 		base += LEVEL_SIZE(level);
1300 		if (base == mmu.hole_start)
1301 			base = (mmu.hole_end + MMU_PAGEOFFSET) & MMU_PAGEMASK;
1302 	}
1303 
1304 	/*
1305 	 * As long as all the mappings we had were below kernel base
1306 	 * we can release the htable.
1307 	 */
1308 	if (base < kernelbase)
1309 		htable_release(ht);
1310 }
1311 
1312 /*
1313  * Walk through a given htable looking for the first valid entry.  This
1314  * routine takes both a starting and ending address.  The starting address
1315  * is required to be within the htable provided by the caller, but there is
1316  * no such restriction on the ending address.
1317  *
1318  * If the routine finds a valid entry in the htable (at or beyond the
1319  * starting address), the PTE (and its address) will be returned.
1320  * This PTE may correspond to either a page or a pagetable - it is the
1321  * caller's responsibility to determine which.  If no valid entry is
1322  * found, 0 (and invalid PTE) and the next unexamined address will be
1323  * returned.
1324  *
1325  * The loop has been carefully coded for optimization.
1326  */
1327 static x86pte_t
1328 htable_scan(htable_t *ht, uintptr_t *vap, uintptr_t eaddr)
1329 {
1330 	uint_t e;
1331 	x86pte_t found_pte = (x86pte_t)0;
1332 	caddr_t pte_ptr;
1333 	caddr_t end_pte_ptr;
1334 	int l = ht->ht_level;
1335 	uintptr_t va = *vap & LEVEL_MASK(l);
1336 	size_t pgsize = LEVEL_SIZE(l);
1337 
1338 	ASSERT(va >= ht->ht_vaddr);
1339 	ASSERT(va <= HTABLE_LAST_PAGE(ht));
1340 
1341 	/*
1342 	 * Compute the starting index and ending virtual address
1343 	 */
1344 	e = htable_va2entry(va, ht);
1345 
1346 	/*
1347 	 * The following page table scan code knows that the valid
1348 	 * bit of a PTE is in the lowest byte AND that x86 is little endian!!
1349 	 */
1350 	pte_ptr = (caddr_t)x86pte_access_pagetable(ht, 0);
1351 	end_pte_ptr = (caddr_t)PT_INDEX_PTR(pte_ptr, HTABLE_NUM_PTES(ht));
1352 	pte_ptr = (caddr_t)PT_INDEX_PTR((x86pte_t *)pte_ptr, e);
1353 	while (!PTE_ISVALID(*pte_ptr)) {
1354 		va += pgsize;
1355 		if (va >= eaddr)
1356 			break;
1357 		pte_ptr += mmu.pte_size;
1358 		ASSERT(pte_ptr <= end_pte_ptr);
1359 		if (pte_ptr == end_pte_ptr)
1360 			break;
1361 	}
1362 
1363 	/*
1364 	 * if we found a valid PTE, load the entire PTE
1365 	 */
1366 	if (va < eaddr && pte_ptr != end_pte_ptr)
1367 		found_pte = GET_PTE((x86pte_t *)pte_ptr);
1368 	x86pte_release_pagetable(ht);
1369 
1370 #if defined(__amd64)
1371 	/*
1372 	 * deal with VA hole on amd64
1373 	 */
1374 	if (l == mmu.max_level && va >= mmu.hole_start && va <= mmu.hole_end)
1375 		va = mmu.hole_end + va - mmu.hole_start;
1376 #endif /* __amd64 */
1377 
1378 	*vap = va;
1379 	return (found_pte);
1380 }
1381 
1382 /*
1383  * Find the address and htable for the first populated translation at or
1384  * above the given virtual address.  The caller may also specify an upper
1385  * limit to the address range to search.  Uses level information to quickly
1386  * skip unpopulated sections of virtual address spaces.
1387  *
1388  * If not found returns NULL. When found, returns the htable and virt addr
1389  * and has a hold on the htable.
1390  */
1391 x86pte_t
1392 htable_walk(
1393 	struct hat *hat,
1394 	htable_t **htp,
1395 	uintptr_t *vaddr,
1396 	uintptr_t eaddr)
1397 {
1398 	uintptr_t va = *vaddr;
1399 	htable_t *ht;
1400 	htable_t *prev = *htp;
1401 	level_t l;
1402 	level_t max_mapped_level;
1403 	x86pte_t pte;
1404 
1405 	ASSERT(eaddr > va);
1406 
1407 	/*
1408 	 * If this is a user address, then we know we need not look beyond
1409 	 * kernelbase.
1410 	 */
1411 	ASSERT(hat == kas.a_hat || eaddr <= kernelbase ||
1412 	    eaddr == HTABLE_WALK_TO_END);
1413 	if (hat != kas.a_hat && eaddr == HTABLE_WALK_TO_END)
1414 		eaddr = kernelbase;
1415 
1416 	/*
1417 	 * If we're coming in with a previous page table, search it first
1418 	 * without doing an htable_lookup(), this should be frequent.
1419 	 */
1420 	if (prev) {
1421 		ASSERT(prev->ht_busy > 0);
1422 		ASSERT(prev->ht_vaddr <= va);
1423 		l = prev->ht_level;
1424 		if (va <= HTABLE_LAST_PAGE(prev)) {
1425 			pte = htable_scan(prev, &va, eaddr);
1426 
1427 			if (PTE_ISPAGE(pte, l)) {
1428 				*vaddr = va;
1429 				*htp = prev;
1430 				return (pte);
1431 			}
1432 		}
1433 
1434 		/*
1435 		 * We found nothing in the htable provided by the caller,
1436 		 * so fall through and do the full search
1437 		 */
1438 		htable_release(prev);
1439 	}
1440 
1441 	/*
1442 	 * Find the level of the largest pagesize used by this HAT.
1443 	 */
1444 	if (hat->hat_ism_pgcnt > 0) {
1445 		max_mapped_level = mmu.max_page_level;
1446 	} else {
1447 		max_mapped_level = 0;
1448 		for (l = 1; l <= mmu.max_page_level; ++l)
1449 			if (hat->hat_pages_mapped[l] != 0)
1450 				max_mapped_level = l;
1451 	}
1452 
1453 	while (va < eaddr && va >= *vaddr) {
1454 		ASSERT(!IN_VA_HOLE(va));
1455 
1456 		/*
1457 		 *  Find lowest table with any entry for given address.
1458 		 */
1459 		for (l = 0; l <= TOP_LEVEL(hat); ++l) {
1460 			ht = htable_lookup(hat, va, l);
1461 			if (ht != NULL) {
1462 				pte = htable_scan(ht, &va, eaddr);
1463 				if (PTE_ISPAGE(pte, l)) {
1464 					*vaddr = va;
1465 					*htp = ht;
1466 					return (pte);
1467 				}
1468 				htable_release(ht);
1469 				break;
1470 			}
1471 
1472 			/*
1473 			 * No htable at this level for the address. If there
1474 			 * is no larger page size that could cover it, we can
1475 			 * skip right to the start of the next page table.
1476 			 */
1477 			ASSERT(l < TOP_LEVEL(hat));
1478 			if (l >= max_mapped_level) {
1479 				va = NEXT_ENTRY_VA(va, l + 1);
1480 				if (va >= eaddr)
1481 					break;
1482 			}
1483 		}
1484 	}
1485 
1486 	*vaddr = 0;
1487 	*htp = NULL;
1488 	return (0);
1489 }
1490 
1491 /*
1492  * Find the htable and page table entry index of the given virtual address
1493  * with pagesize at or below given level.
1494  * If not found returns NULL. When found, returns the htable, sets
1495  * entry, and has a hold on the htable.
1496  */
1497 htable_t *
1498 htable_getpte(
1499 	struct hat *hat,
1500 	uintptr_t vaddr,
1501 	uint_t *entry,
1502 	x86pte_t *pte,
1503 	level_t level)
1504 {
1505 	htable_t	*ht;
1506 	level_t		l;
1507 	uint_t		e;
1508 
1509 	ASSERT(level <= mmu.max_page_level);
1510 
1511 	for (l = 0; l <= level; ++l) {
1512 		ht = htable_lookup(hat, vaddr, l);
1513 		if (ht == NULL)
1514 			continue;
1515 		e = htable_va2entry(vaddr, ht);
1516 		if (entry != NULL)
1517 			*entry = e;
1518 		if (pte != NULL)
1519 			*pte = x86pte_get(ht, e);
1520 		return (ht);
1521 	}
1522 	return (NULL);
1523 }
1524 
1525 /*
1526  * Find the htable and page table entry index of the given virtual address.
1527  * There must be a valid page mapped at the given address.
1528  * If not found returns NULL. When found, returns the htable, sets
1529  * entry, and has a hold on the htable.
1530  */
1531 htable_t *
1532 htable_getpage(struct hat *hat, uintptr_t vaddr, uint_t *entry)
1533 {
1534 	htable_t	*ht;
1535 	uint_t		e;
1536 	x86pte_t	pte;
1537 
1538 	ht = htable_getpte(hat, vaddr, &e, &pte, mmu.max_page_level);
1539 	if (ht == NULL)
1540 		return (NULL);
1541 
1542 	if (entry)
1543 		*entry = e;
1544 
1545 	if (PTE_ISPAGE(pte, ht->ht_level))
1546 		return (ht);
1547 	htable_release(ht);
1548 	return (NULL);
1549 }
1550 
1551 
1552 void
1553 htable_init()
1554 {
1555 	/*
1556 	 * To save on kernel VA usage, we avoid debug information in 32 bit
1557 	 * kernels.
1558 	 */
1559 #if defined(__amd64)
1560 	int	kmem_flags = KMC_NOHASH;
1561 #elif defined(__i386)
1562 	int	kmem_flags = KMC_NOHASH | KMC_NODEBUG;
1563 #endif
1564 
1565 	/*
1566 	 * initialize kmem caches
1567 	 */
1568 	htable_cache = kmem_cache_create("htable_t",
1569 	    sizeof (htable_t), 0, NULL, NULL,
1570 	    htable_reap, NULL, hat_memload_arena, kmem_flags);
1571 }
1572 
1573 /*
1574  * get the pte index for the virtual address in the given htable's pagetable
1575  */
1576 uint_t
1577 htable_va2entry(uintptr_t va, htable_t *ht)
1578 {
1579 	level_t	l = ht->ht_level;
1580 
1581 	ASSERT(va >= ht->ht_vaddr);
1582 	ASSERT(va <= HTABLE_LAST_PAGE(ht));
1583 	return ((va >> LEVEL_SHIFT(l)) & (HTABLE_NUM_PTES(ht) - 1));
1584 }
1585 
1586 /*
1587  * Given an htable and the index of a pte in it, return the virtual address
1588  * of the page.
1589  */
1590 uintptr_t
1591 htable_e2va(htable_t *ht, uint_t entry)
1592 {
1593 	level_t	l = ht->ht_level;
1594 	uintptr_t va;
1595 
1596 	ASSERT(entry < HTABLE_NUM_PTES(ht));
1597 	va = ht->ht_vaddr + ((uintptr_t)entry << LEVEL_SHIFT(l));
1598 
1599 	/*
1600 	 * Need to skip over any VA hole in top level table
1601 	 */
1602 #if defined(__amd64)
1603 	if (ht->ht_level == mmu.max_level && va >= mmu.hole_start)
1604 		va += ((mmu.hole_end - mmu.hole_start) + 1);
1605 #endif
1606 
1607 	return (va);
1608 }
1609 
1610 /*
1611  * The code uses compare and swap instructions to read/write PTE's to
1612  * avoid atomicity problems, since PTEs can be 8 bytes on 32 bit systems.
1613  * will naturally be atomic.
1614  *
1615  * The combination of using kpreempt_disable()/_enable() and the hci_mutex
1616  * are used to ensure that an interrupt won't overwrite a temporary mapping
1617  * while it's in use. If an interrupt thread tries to access a PTE, it will
1618  * yield briefly back to the pinned thread which holds the cpu's hci_mutex.
1619  */
1620 void
1621 x86pte_cpu_init(cpu_t *cpu)
1622 {
1623 	struct hat_cpu_info *hci;
1624 
1625 	hci = kmem_zalloc(sizeof (*hci), KM_SLEEP);
1626 	mutex_init(&hci->hci_mutex, NULL, MUTEX_DEFAULT, NULL);
1627 	cpu->cpu_hat_info = hci;
1628 }
1629 
1630 void
1631 x86pte_cpu_fini(cpu_t *cpu)
1632 {
1633 	struct hat_cpu_info *hci = cpu->cpu_hat_info;
1634 
1635 	kmem_free(hci, sizeof (*hci));
1636 	cpu->cpu_hat_info = NULL;
1637 }
1638 
1639 #ifdef __i386
1640 /*
1641  * On 32 bit kernels, loading a 64 bit PTE is a little tricky
1642  */
1643 x86pte_t
1644 get_pte64(x86pte_t *ptr)
1645 {
1646 	volatile uint32_t *p = (uint32_t *)ptr;
1647 	x86pte_t t;
1648 
1649 	ASSERT(mmu.pae_hat != 0);
1650 	for (;;) {
1651 		t = p[0];
1652 		t |= (uint64_t)p[1] << 32;
1653 		if ((t & 0xffffffff) == p[0])
1654 			return (t);
1655 	}
1656 }
1657 #endif /* __i386 */
1658 
1659 /*
1660  * Disable preemption and establish a mapping to the pagetable with the
1661  * given pfn. This is optimized for there case where it's the same
1662  * pfn as we last used referenced from this CPU.
1663  */
1664 static x86pte_t *
1665 x86pte_access_pagetable(htable_t *ht, uint_t index)
1666 {
1667 	/*
1668 	 * VLP pagetables are contained in the hat_t
1669 	 */
1670 	if (ht->ht_flags & HTABLE_VLP)
1671 		return (PT_INDEX_PTR(ht->ht_hat->hat_vlp_ptes, index));
1672 	return (x86pte_mapin(ht->ht_pfn, index, ht));
1673 }
1674 
1675 /*
1676  * map the given pfn into the page table window.
1677  */
1678 /*ARGSUSED*/
1679 x86pte_t *
1680 x86pte_mapin(pfn_t pfn, uint_t index, htable_t *ht)
1681 {
1682 	x86pte_t *pteptr;
1683 	x86pte_t pte;
1684 	x86pte_t newpte;
1685 	int x;
1686 
1687 	ASSERT(pfn != PFN_INVALID);
1688 
1689 	if (!khat_running) {
1690 		caddr_t va = kbm_remap_window(pfn_to_pa(pfn), 1);
1691 		return (PT_INDEX_PTR(va, index));
1692 	}
1693 
1694 	/*
1695 	 * If kpm is available, use it.
1696 	 */
1697 	if (kpm_vbase)
1698 		return (PT_INDEX_PTR(hat_kpm_pfn2va(pfn), index));
1699 
1700 	/*
1701 	 * Disable preemption and grab the CPU's hci_mutex
1702 	 */
1703 	kpreempt_disable();
1704 	ASSERT(CPU->cpu_hat_info != NULL);
1705 	mutex_enter(&CPU->cpu_hat_info->hci_mutex);
1706 	x = PWIN_TABLE(CPU->cpu_id);
1707 	pteptr = (x86pte_t *)PWIN_PTE_VA(x);
1708 	if (mmu.pae_hat)
1709 		pte = *pteptr;
1710 	else
1711 		pte = *(x86pte32_t *)pteptr;
1712 
1713 	newpte = MAKEPTE(pfn, 0) | mmu.pt_global | mmu.pt_nx;
1714 	newpte |= PT_WRITABLE;
1715 
1716 	if (!PTE_EQUIV(newpte, pte)) {
1717 		if (mmu.pae_hat)
1718 			*pteptr = newpte;
1719 		else
1720 			*(x86pte32_t *)pteptr = newpte;
1721 		mmu_tlbflush_entry((caddr_t)(PWIN_VA(x)));
1722 	}
1723 	return (PT_INDEX_PTR(PWIN_VA(x), index));
1724 }
1725 
1726 /*
1727  * Release access to a page table.
1728  */
1729 static void
1730 x86pte_release_pagetable(htable_t *ht)
1731 {
1732 	/*
1733 	 * nothing to do for VLP htables
1734 	 */
1735 	if (ht->ht_flags & HTABLE_VLP)
1736 		return;
1737 
1738 	x86pte_mapout();
1739 }
1740 
1741 void
1742 x86pte_mapout(void)
1743 {
1744 	if (mmu.pwin_base == NULL || !khat_running)
1745 		return;
1746 
1747 	/*
1748 	 * Drop the CPU's hci_mutex and restore preemption.
1749 	 */
1750 	mutex_exit(&CPU->cpu_hat_info->hci_mutex);
1751 	kpreempt_enable();
1752 }
1753 
1754 /*
1755  * Atomic retrieval of a pagetable entry
1756  */
1757 x86pte_t
1758 x86pte_get(htable_t *ht, uint_t entry)
1759 {
1760 	x86pte_t	pte;
1761 	x86pte_t	*ptep;
1762 
1763 	/*
1764 	 * Be careful that loading PAE entries in 32 bit kernel is atomic.
1765 	 */
1766 	ASSERT(entry < mmu.ptes_per_table);
1767 	ptep = x86pte_access_pagetable(ht, entry);
1768 	pte = GET_PTE(ptep);
1769 	x86pte_release_pagetable(ht);
1770 	return (pte);
1771 }
1772 
1773 /*
1774  * Atomic unconditional set of a page table entry, it returns the previous
1775  * value. For pre-existing mappings if the PFN changes, then we don't care
1776  * about the old pte's REF / MOD bits. If the PFN remains the same, we leave
1777  * the MOD/REF bits unchanged.
1778  *
1779  * If asked to overwrite a link to a lower page table with a large page
1780  * mapping, this routine returns the special value of LPAGE_ERROR. This
1781  * allows the upper HAT layers to retry with a smaller mapping size.
1782  */
1783 x86pte_t
1784 x86pte_set(htable_t *ht, uint_t entry, x86pte_t new, void *ptr)
1785 {
1786 	x86pte_t	old;
1787 	x86pte_t	prev;
1788 	x86pte_t	*ptep;
1789 	level_t		l = ht->ht_level;
1790 	x86pte_t	pfn_mask = (l != 0) ? PT_PADDR_LGPG : PT_PADDR;
1791 	x86pte_t	n;
1792 	uintptr_t	addr = htable_e2va(ht, entry);
1793 	hat_t		*hat = ht->ht_hat;
1794 
1795 	ASSERT(new != 0); /* don't use to invalidate a PTE, see x86pte_update */
1796 	ASSERT(!(ht->ht_flags & HTABLE_SHARED_PFN));
1797 	if (ptr == NULL)
1798 		ptep = x86pte_access_pagetable(ht, entry);
1799 	else
1800 		ptep = ptr;
1801 
1802 	/*
1803 	 * Install the new PTE. If remapping the same PFN, then
1804 	 * copy existing REF/MOD bits to new mapping.
1805 	 */
1806 	do {
1807 		prev = GET_PTE(ptep);
1808 		n = new;
1809 		if (PTE_ISVALID(n) && (prev & pfn_mask) == (new & pfn_mask))
1810 			n |= prev & (PT_REF | PT_MOD);
1811 
1812 		/*
1813 		 * Another thread may have installed this mapping already,
1814 		 * flush the local TLB and be done.
1815 		 */
1816 		if (prev == n) {
1817 			old = new;
1818 			mmu_tlbflush_entry((caddr_t)addr);
1819 			goto done;
1820 		}
1821 
1822 		/*
1823 		 * Detect if we have a collision of installing a large
1824 		 * page mapping where there already is a lower page table.
1825 		 */
1826 		if (l > 0 && (prev & PT_VALID) && !(prev & PT_PAGESIZE)) {
1827 			old = LPAGE_ERROR;
1828 			goto done;
1829 		}
1830 
1831 		old = CAS_PTE(ptep, prev, n);
1832 	} while (old != prev);
1833 
1834 	/*
1835 	 * Do a TLB demap if needed, ie. the old pte was valid.
1836 	 *
1837 	 * Note that a stale TLB writeback to the PTE here either can't happen
1838 	 * or doesn't matter. The PFN can only change for NOSYNC|NOCONSIST
1839 	 * mappings, but they were created with REF and MOD already set, so
1840 	 * no stale writeback will happen.
1841 	 *
1842 	 * Segmap is the only place where remaps happen on the same pfn and for
1843 	 * that we want to preserve the stale REF/MOD bits.
1844 	 */
1845 	if (old & PT_REF)
1846 		hat_tlb_inval(hat, addr);
1847 
1848 done:
1849 	if (ptr == NULL)
1850 		x86pte_release_pagetable(ht);
1851 	return (old);
1852 }
1853 
1854 /*
1855  * Atomic compare and swap of a page table entry. No TLB invalidates are done.
1856  * This is used for links between pagetables of different levels.
1857  * Note we always create these links with dirty/access set, so they should
1858  * never change.
1859  */
1860 x86pte_t
1861 x86pte_cas(htable_t *ht, uint_t entry, x86pte_t old, x86pte_t new)
1862 {
1863 	x86pte_t	pte;
1864 	x86pte_t	*ptep;
1865 
1866 	ptep = x86pte_access_pagetable(ht, entry);
1867 	pte = CAS_PTE(ptep, old, new);
1868 	x86pte_release_pagetable(ht);
1869 	return (pte);
1870 }
1871 
1872 /*
1873  * Invalidate a page table entry as long as it currently maps something that
1874  * matches the value determined by expect.
1875  *
1876  * Also invalidates any TLB entries and returns the previous value of the PTE.
1877  */
1878 x86pte_t
1879 x86pte_inval(
1880 	htable_t *ht,
1881 	uint_t entry,
1882 	x86pte_t expect,
1883 	x86pte_t *pte_ptr)
1884 {
1885 	x86pte_t	*ptep;
1886 	x86pte_t	oldpte;
1887 	x86pte_t	found;
1888 
1889 	ASSERT(!(ht->ht_flags & HTABLE_SHARED_PFN));
1890 	ASSERT(ht->ht_level != VLP_LEVEL);
1891 
1892 	if (pte_ptr != NULL)
1893 		ptep = pte_ptr;
1894 	else
1895 		ptep = x86pte_access_pagetable(ht, entry);
1896 
1897 	/*
1898 	 * Note that the loop is needed to handle changes due to h/w updating
1899 	 * of PT_MOD/PT_REF.
1900 	 */
1901 	do {
1902 		oldpte = GET_PTE(ptep);
1903 		if (expect != 0 && (oldpte & PT_PADDR) != (expect & PT_PADDR))
1904 			goto done;
1905 		found = CAS_PTE(ptep, oldpte, 0);
1906 	} while (found != oldpte);
1907 	if (oldpte & (PT_REF | PT_MOD))
1908 		hat_tlb_inval(ht->ht_hat, htable_e2va(ht, entry));
1909 
1910 done:
1911 	if (pte_ptr == NULL)
1912 		x86pte_release_pagetable(ht);
1913 	return (oldpte);
1914 }
1915 
1916 /*
1917  * Change a page table entry af it currently matches the value in expect.
1918  */
1919 x86pte_t
1920 x86pte_update(
1921 	htable_t *ht,
1922 	uint_t entry,
1923 	x86pte_t expect,
1924 	x86pte_t new)
1925 {
1926 	x86pte_t	*ptep;
1927 	x86pte_t	found;
1928 
1929 	ASSERT(new != 0);
1930 	ASSERT(!(ht->ht_flags & HTABLE_SHARED_PFN));
1931 	ASSERT(ht->ht_level != VLP_LEVEL);
1932 
1933 	ptep = x86pte_access_pagetable(ht, entry);
1934 	found = CAS_PTE(ptep, expect, new);
1935 	if (found == expect) {
1936 		hat_tlb_inval(ht->ht_hat, htable_e2va(ht, entry));
1937 
1938 		/*
1939 		 * When removing write permission *and* clearing the
1940 		 * MOD bit, check if a write happened via a stale
1941 		 * TLB entry before the TLB shootdown finished.
1942 		 *
1943 		 * If it did happen, simply re-enable write permission and
1944 		 * act like the original CAS failed.
1945 		 */
1946 		if ((expect & (PT_WRITABLE | PT_MOD)) == PT_WRITABLE &&
1947 		    (new & (PT_WRITABLE | PT_MOD)) == 0 &&
1948 		    (GET_PTE(ptep) & PT_MOD) != 0) {
1949 			do {
1950 				found = GET_PTE(ptep);
1951 				found =
1952 				    CAS_PTE(ptep, found, found | PT_WRITABLE);
1953 			} while ((found & PT_WRITABLE) == 0);
1954 		}
1955 	}
1956 	x86pte_release_pagetable(ht);
1957 	return (found);
1958 }
1959 
1960 /*
1961  * Copy page tables - this is just a little more complicated than the
1962  * previous routines. Note that it's also not atomic! It also is never
1963  * used for VLP pagetables.
1964  */
1965 void
1966 x86pte_copy(htable_t *src, htable_t *dest, uint_t entry, uint_t count)
1967 {
1968 	caddr_t	src_va;
1969 	caddr_t dst_va;
1970 	size_t size;
1971 	x86pte_t *pteptr;
1972 	x86pte_t pte;
1973 
1974 	ASSERT(khat_running);
1975 	ASSERT(!(dest->ht_flags & HTABLE_VLP));
1976 	ASSERT(!(src->ht_flags & HTABLE_VLP));
1977 	ASSERT(!(src->ht_flags & HTABLE_SHARED_PFN));
1978 	ASSERT(!(dest->ht_flags & HTABLE_SHARED_PFN));
1979 
1980 	/*
1981 	 * Acquire access to the CPU pagetable windows for the dest and source.
1982 	 */
1983 	dst_va = (caddr_t)x86pte_access_pagetable(dest, entry);
1984 	if (kpm_vbase) {
1985 		src_va = (caddr_t)
1986 		    PT_INDEX_PTR(hat_kpm_pfn2va(src->ht_pfn), entry);
1987 	} else {
1988 		uint_t x = PWIN_SRC(CPU->cpu_id);
1989 
1990 		/*
1991 		 * Finish defining the src pagetable mapping
1992 		 */
1993 		src_va = (caddr_t)PT_INDEX_PTR(PWIN_VA(x), entry);
1994 		pte = MAKEPTE(src->ht_pfn, 0) | mmu.pt_global | mmu.pt_nx;
1995 		pteptr = (x86pte_t *)PWIN_PTE_VA(x);
1996 		if (mmu.pae_hat)
1997 			*pteptr = pte;
1998 		else
1999 			*(x86pte32_t *)pteptr = pte;
2000 		mmu_tlbflush_entry((caddr_t)(PWIN_VA(x)));
2001 	}
2002 
2003 	/*
2004 	 * now do the copy
2005 	 */
2006 	size = count << mmu.pte_size_shift;
2007 	bcopy(src_va, dst_va, size);
2008 
2009 	x86pte_release_pagetable(dest);
2010 }
2011 
2012 /*
2013  * Zero page table entries - Note this doesn't use atomic stores!
2014  */
2015 static void
2016 x86pte_zero(htable_t *dest, uint_t entry, uint_t count)
2017 {
2018 	caddr_t dst_va;
2019 	size_t size;
2020 
2021 	/*
2022 	 * Map in the page table to be zeroed.
2023 	 */
2024 	ASSERT(!(dest->ht_flags & HTABLE_SHARED_PFN));
2025 	ASSERT(!(dest->ht_flags & HTABLE_VLP));
2026 
2027 	dst_va = (caddr_t)x86pte_access_pagetable(dest, entry);
2028 
2029 	size = count << mmu.pte_size_shift;
2030 	ASSERT(size > BLOCKZEROALIGN);
2031 #ifdef __i386
2032 	if ((x86_feature & X86_SSE2) == 0)
2033 		bzero(dst_va, size);
2034 	else
2035 #endif
2036 		block_zero_no_xmm(dst_va, size);
2037 
2038 	x86pte_release_pagetable(dest);
2039 }
2040 
2041 /*
2042  * Called to ensure that all pagetables are in the system dump
2043  */
2044 void
2045 hat_dump(void)
2046 {
2047 	hat_t *hat;
2048 	uint_t h;
2049 	htable_t *ht;
2050 
2051 	/*
2052 	 * Dump all page tables
2053 	 */
2054 	for (hat = kas.a_hat; hat != NULL; hat = hat->hat_next) {
2055 		for (h = 0; h < hat->hat_num_hash; ++h) {
2056 			for (ht = hat->hat_ht_hash[h]; ht; ht = ht->ht_next) {
2057 				if ((ht->ht_flags & HTABLE_VLP) == 0)
2058 					dump_page(ht->ht_pfn);
2059 			}
2060 		}
2061 	}
2062 }
2063