xref: /illumos-gate/usr/src/uts/i86pc/vm/vm_machdep.c (revision f045d8d6fec1759551cc2bce1d26628931f14fce)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 /*
25  * Copyright (c) 2010, Intel Corporation.
26  * All rights reserved.
27  */
28 
29 /* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */
30 /*	All Rights Reserved   */
31 
32 /*
33  * Portions of this source code were derived from Berkeley 4.3 BSD
34  * under license from the Regents of the University of California.
35  */
36 
37 /*
38  * UNIX machine dependent virtual memory support.
39  */
40 
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/user.h>
45 #include <sys/proc.h>
46 #include <sys/kmem.h>
47 #include <sys/vmem.h>
48 #include <sys/buf.h>
49 #include <sys/cpuvar.h>
50 #include <sys/lgrp.h>
51 #include <sys/disp.h>
52 #include <sys/vm.h>
53 #include <sys/mman.h>
54 #include <sys/vnode.h>
55 #include <sys/cred.h>
56 #include <sys/exec.h>
57 #include <sys/exechdr.h>
58 #include <sys/debug.h>
59 #include <sys/vmsystm.h>
60 #include <sys/swap.h>
61 
62 #include <vm/hat.h>
63 #include <vm/as.h>
64 #include <vm/seg.h>
65 #include <vm/seg_kp.h>
66 #include <vm/seg_vn.h>
67 #include <vm/page.h>
68 #include <vm/seg_kmem.h>
69 #include <vm/seg_kpm.h>
70 #include <vm/vm_dep.h>
71 
72 #include <sys/cpu.h>
73 #include <sys/vm_machparam.h>
74 #include <sys/memlist.h>
75 #include <sys/bootconf.h> /* XXX the memlist stuff belongs in memlist_plat.h */
76 #include <vm/hat_i86.h>
77 #include <sys/x86_archext.h>
78 #include <sys/elf_386.h>
79 #include <sys/cmn_err.h>
80 #include <sys/archsystm.h>
81 #include <sys/machsystm.h>
82 
83 #include <sys/vtrace.h>
84 #include <sys/ddidmareq.h>
85 #include <sys/promif.h>
86 #include <sys/memnode.h>
87 #include <sys/stack.h>
88 #include <util/qsort.h>
89 #include <sys/taskq.h>
90 #include <sys/kflt_mem.h>
91 
92 #ifdef __xpv
93 
94 #include <sys/hypervisor.h>
95 #include <sys/xen_mmu.h>
96 #include <sys/balloon_impl.h>
97 
98 /*
99  * domain 0 pages usable for DMA are kept pre-allocated and kept in
100  * distinct lists, ordered by increasing mfn.
101  */
102 static kmutex_t io_pool_lock;
103 static kmutex_t contig_list_lock;
104 static page_t *io_pool_4g;	/* pool for 32 bit dma limited devices */
105 static page_t *io_pool_16m;	/* pool for 24 bit dma limited legacy devices */
106 static long io_pool_cnt;
107 static long io_pool_cnt_max = 0;
108 #define	DEFAULT_IO_POOL_MIN	128
109 static long io_pool_cnt_min = DEFAULT_IO_POOL_MIN;
110 static long io_pool_cnt_lowater = 0;
111 static long io_pool_shrink_attempts; /* how many times did we try to shrink */
112 static long io_pool_shrinks;	/* how many times did we really shrink */
113 static long io_pool_grows;	/* how many times did we grow */
114 static mfn_t start_mfn = 1;
115 static caddr_t io_pool_kva;	/* use to alloc pages when needed */
116 
117 static int create_contig_pfnlist(uint_t);
118 
119 /*
120  * percentage of phys mem to hold in the i/o pool
121  */
122 #define	DEFAULT_IO_POOL_PCT	2
123 static long io_pool_physmem_pct = DEFAULT_IO_POOL_PCT;
124 static void page_io_pool_sub(page_t **, page_t *, page_t *);
125 int ioalloc_dbg = 0;
126 
127 #endif /* __xpv */
128 
129 uint_t vac_colors = 1;
130 
131 int largepagesupport = 0;
132 extern uint_t page_create_new;
133 extern uint_t page_create_exists;
134 extern uint_t page_create_putbacks;
135 /*
136  * Allow users to disable the kernel's use of SSE.
137  */
138 extern int use_sse_pagecopy, use_sse_pagezero;
139 
140 /*
141  * As the PC architecture evolved memory up was clumped into several
142  * ranges for various historical I/O devices to do DMA.
143  * < 16Meg - ISA bus
144  * < 2Gig - ???
145  * < 4Gig - PCI bus or drivers that don't understand PAE mode
146  *
147  * These are listed in reverse order, so that we can skip over unused
148  * ranges on machines with small memories.
149  *
150  * For now under the Hypervisor, we'll only ever have one memrange.
151  */
152 #define	PFN_4GIG	0x100000
153 #define	PFN_16MEG	0x1000
154 /* Indices into the memory range (arch_memranges) array. */
155 #define	MRI_4G		0
156 #define	MRI_2G		1
157 #define	MRI_16M		2
158 #define	MRI_0		3
159 static pfn_t arch_memranges[NUM_MEM_RANGES] = {
160     PFN_4GIG,	/* pfn range for 4G and above */
161     0x80000,	/* pfn range for 2G-4G */
162     PFN_16MEG,	/* pfn range for 16M-2G */
163     0x00000,	/* pfn range for 0-16M */
164 };
165 pfn_t *memranges = &arch_memranges[0];
166 int nranges = NUM_MEM_RANGES;
167 
168 /*
169  * This combines mem_node_config and memranges into one data
170  * structure to be used for page list management.
171  */
172 mnoderange_t	*mnoderanges;
173 int		mnoderangecnt;
174 int		mtype4g;
175 int		mtype16m;
176 int		mtypetop;	/* index of highest pfn'ed mnoderange */
177 
178 /*
179  * 4g memory management variables for systems with more than 4g of memory:
180  *
181  * physical memory below 4g is required for 32bit dma devices and, currently,
182  * for kmem memory. On systems with more than 4g of memory, the pool of memory
183  * below 4g can be depleted without any paging activity given that there is
184  * likely to be sufficient memory above 4g.
185  *
186  * physmax4g is set true if the largest pfn is over 4g. The rest of the
187  * 4g memory management code is enabled only when physmax4g is true.
188  *
189  * maxmem4g is the count of the maximum number of pages on the page lists
190  * with physical addresses below 4g. It can be a lot less then 4g given that
191  * BIOS may reserve large chunks of space below 4g for hot plug pci devices,
192  * agp aperture etc.
193  *
194  * freemem4g maintains the count of the number of available pages on the
195  * page lists with physical addresses below 4g.
196  *
197  * DESFREE4G specifies the desired amount of below 4g memory. It defaults to
198  * 6% (desfree4gshift = 4) of maxmem4g.
199  *
200  * RESTRICT4G_ALLOC returns true if freemem4g falls below DESFREE4G
201  * and the amount of physical memory above 4g is greater than freemem4g.
202  * In this case, page_get_* routines will restrict below 4g allocations
203  * for requests that don't specifically require it.
204  */
205 
206 #define	DESFREE4G	(maxmem4g >> desfree4gshift)
207 
208 #define	RESTRICT4G_ALLOC					\
209 	(physmax4g && (freemem4g < DESFREE4G) && ((freemem4g << 1) < freemem))
210 
211 static pgcnt_t	maxmem4g;
212 static pgcnt_t	freemem4g;
213 static int	physmax4g;
214 static int	desfree4gshift = 4;	/* maxmem4g shift to derive DESFREE4G */
215 
216 /*
217  * 16m memory management:
218  *
219  * reserve some amount of physical memory below 16m for legacy devices.
220  *
221  * RESTRICT16M_ALLOC returns true if an there are sufficient free pages above
222  * 16m or if the 16m pool drops below DESFREE16M.
223  *
224  * In this case, general page allocations via page_get_{free,cache}list
225  * routines will be restricted from allocating from the 16m pool. Allocations
226  * that require specific pfn ranges (page_get_anylist) and PG_PANIC allocations
227  * are not restricted.
228  */
229 
230 #define	FREEMEM16M	MTYPE_FREEMEM(mtype16m)
231 #define	DESFREE16M	desfree16m
232 #define	RESTRICT16M_ALLOC(freemem, pgcnt, flags)		\
233 	((freemem != 0) && ((flags & PG_PANIC) == 0) &&		\
234 	    ((freemem >= (FREEMEM16M)) ||			\
235 	    (FREEMEM16M  < (DESFREE16M + pgcnt))))
236 
237 static pgcnt_t	desfree16m = 0x380;
238 
239 /*
240  * This can be patched via /etc/system to allow old non-PAE aware device
241  * drivers to use kmem_alloc'd memory on 32 bit systems with > 4Gig RAM.
242  */
243 int restricted_kmemalloc = 0;
244 
245 #ifdef VM_STATS
246 struct {
247 	ulong_t	pga_alloc;
248 	ulong_t	pga_notfullrange;
249 	ulong_t	pga_nulldmaattr;
250 	ulong_t	pga_allocok;
251 	ulong_t	pga_allocfailed;
252 	ulong_t	pgma_alloc;
253 	ulong_t	pgma_allocok;
254 	ulong_t	pgma_allocfailed;
255 	ulong_t	pgma_allocempty;
256 } pga_vmstats;
257 #endif
258 
259 uint_t mmu_page_sizes;
260 
261 /* How many page sizes the users can see */
262 uint_t mmu_exported_page_sizes;
263 
264 /* page sizes that legacy applications can see */
265 uint_t mmu_legacy_page_sizes;
266 
267 /*
268  * Number of pages in 1 GB.  Don't enable automatic large pages if we have
269  * fewer than this many pages.
270  */
271 pgcnt_t shm_lpg_min_physmem = 1 << (30 - MMU_PAGESHIFT);
272 pgcnt_t privm_lpg_min_physmem = 1 << (30 - MMU_PAGESHIFT);
273 
274 /*
275  * Maximum and default segment size tunables for user private
276  * and shared anon memory, and user text and initialized data.
277  * These can be patched via /etc/system to allow large pages
278  * to be used for mapping application private and shared anon memory.
279  */
280 size_t mcntl0_lpsize = MMU_PAGESIZE;
281 size_t max_uheap_lpsize = MMU_PAGESIZE;
282 size_t default_uheap_lpsize = MMU_PAGESIZE;
283 size_t max_ustack_lpsize = MMU_PAGESIZE;
284 size_t default_ustack_lpsize = MMU_PAGESIZE;
285 size_t max_privmap_lpsize = MMU_PAGESIZE;
286 size_t max_uidata_lpsize = MMU_PAGESIZE;
287 size_t max_utext_lpsize = MMU_PAGESIZE;
288 size_t max_shm_lpsize = MMU_PAGESIZE;
289 
290 
291 /*
292  * initialized by page_coloring_init().
293  */
294 uint_t	page_colors;
295 uint_t	page_colors_mask;
296 uint_t	page_coloring_shift;
297 int	cpu_page_colors;
298 static uint_t	l2_colors;
299 
300 /*
301  * Page freelists and cachelists are dynamically allocated once mnoderangecnt
302  * and page_colors are calculated from the l2 cache n-way set size.  Within a
303  * mnode range, the page freelist and cachelist are hashed into bins based on
304  * color. This makes it easier to search for a page within a specific memory
305  * range.
306  */
307 #define	PAGE_COLORS_MIN	16
308 
309 page_t ****page_freelists;
310 page_t ***page_cachelists;
311 
312 
313 /*
314  * Used by page layer to know about page sizes
315  */
316 hw_pagesize_t hw_page_array[MAX_NUM_LEVEL + 1];
317 
318 kmutex_t	*fpc_mutex[NPC_MUTEX];	/* user page freelist mutexes */
319 kmutex_t	*kfpc_mutex[NPC_MUTEX];	/* kernel page freelist mutexes */
320 kmutex_t	*cpc_mutex[NPC_MUTEX];	/* page cachelist mutexes */
321 
322 /* Lock to protect mnoderanges array for memory DR operations. */
323 static kmutex_t mnoderange_lock;
324 
325 /*
326  * Only let one thread at a time try to coalesce large pages, to
327  * prevent them from working against each other.
328  */
329 static kmutex_t	contig_lock;
330 #define	CONTIG_LOCK()	mutex_enter(&contig_lock);
331 #define	CONTIG_UNLOCK()	mutex_exit(&contig_lock);
332 
333 #define	PFN_16M		(mmu_btop((uint64_t)0x1000000))
334 
335 /*
336  * Return the optimum page size for a given mapping
337  */
338 /*ARGSUSED*/
339 size_t
340 map_pgsz(int maptype, struct proc *p, caddr_t addr, size_t len, int memcntl)
341 {
342 	level_t l = 0;
343 	size_t pgsz = MMU_PAGESIZE;
344 	size_t max_lpsize;
345 	uint_t mszc;
346 
347 	ASSERT(maptype != MAPPGSZ_VA);
348 
349 	if (maptype != MAPPGSZ_ISM && physmem < privm_lpg_min_physmem) {
350 		return (MMU_PAGESIZE);
351 	}
352 
353 	switch (maptype) {
354 	case MAPPGSZ_HEAP:
355 	case MAPPGSZ_STK:
356 		max_lpsize = memcntl ? mcntl0_lpsize : (maptype ==
357 		    MAPPGSZ_HEAP ? max_uheap_lpsize : max_ustack_lpsize);
358 		if (max_lpsize == MMU_PAGESIZE) {
359 			return (MMU_PAGESIZE);
360 		}
361 		if (len == 0) {
362 			len = (maptype == MAPPGSZ_HEAP) ? p->p_brkbase +
363 			    p->p_brksize - p->p_bssbase : p->p_stksize;
364 		}
365 		len = (maptype == MAPPGSZ_HEAP) ? MAX(len,
366 		    default_uheap_lpsize) : MAX(len, default_ustack_lpsize);
367 
368 		/*
369 		 * use the pages size that best fits len
370 		 */
371 		for (l = mmu.umax_page_level; l > 0; --l) {
372 			if (LEVEL_SIZE(l) > max_lpsize || len < LEVEL_SIZE(l)) {
373 				continue;
374 			} else {
375 				pgsz = LEVEL_SIZE(l);
376 			}
377 			break;
378 		}
379 
380 		mszc = (maptype == MAPPGSZ_HEAP ? p->p_brkpageszc :
381 		    p->p_stkpageszc);
382 		if (addr == 0 && (pgsz < hw_page_array[mszc].hp_size)) {
383 			pgsz = hw_page_array[mszc].hp_size;
384 		}
385 		return (pgsz);
386 
387 	case MAPPGSZ_ISM:
388 		for (l = mmu.umax_page_level; l > 0; --l) {
389 			if (len >= LEVEL_SIZE(l))
390 				return (LEVEL_SIZE(l));
391 		}
392 		return (LEVEL_SIZE(0));
393 	}
394 	return (pgsz);
395 }
396 
397 static uint_t
398 map_szcvec(caddr_t addr, size_t size, uintptr_t off, size_t max_lpsize,
399     size_t min_physmem)
400 {
401 	caddr_t eaddr = addr + size;
402 	uint_t szcvec = 0;
403 	caddr_t raddr;
404 	caddr_t readdr;
405 	size_t	pgsz;
406 	int i;
407 
408 	if (physmem < min_physmem || max_lpsize <= MMU_PAGESIZE) {
409 		return (0);
410 	}
411 
412 	for (i = mmu_exported_page_sizes - 1; i > 0; i--) {
413 		pgsz = page_get_pagesize(i);
414 		if (pgsz > max_lpsize) {
415 			continue;
416 		}
417 		raddr = (caddr_t)P2ROUNDUP((uintptr_t)addr, pgsz);
418 		readdr = (caddr_t)P2ALIGN((uintptr_t)eaddr, pgsz);
419 		if (raddr < addr || raddr >= readdr) {
420 			continue;
421 		}
422 		if (P2PHASE((uintptr_t)addr ^ off, pgsz)) {
423 			continue;
424 		}
425 		/*
426 		 * Set szcvec to the remaining page sizes.
427 		 */
428 		szcvec = ((1 << (i + 1)) - 1) & ~1;
429 		break;
430 	}
431 	return (szcvec);
432 }
433 
434 /*
435  * Return a bit vector of large page size codes that
436  * can be used to map [addr, addr + len) region.
437  */
438 /*ARGSUSED*/
439 uint_t
440 map_pgszcvec(caddr_t addr, size_t size, uintptr_t off, int flags, int type,
441     int memcntl)
442 {
443 	size_t max_lpsize = mcntl0_lpsize;
444 
445 	if (mmu.max_page_level == 0)
446 		return (0);
447 
448 	if (flags & MAP_TEXT) {
449 		if (!memcntl)
450 			max_lpsize = max_utext_lpsize;
451 		return (map_szcvec(addr, size, off, max_lpsize,
452 		    shm_lpg_min_physmem));
453 
454 	} else if (flags & MAP_INITDATA) {
455 		if (!memcntl)
456 			max_lpsize = max_uidata_lpsize;
457 		return (map_szcvec(addr, size, off, max_lpsize,
458 		    privm_lpg_min_physmem));
459 
460 	} else if (type == MAPPGSZC_SHM) {
461 		if (!memcntl)
462 			max_lpsize = max_shm_lpsize;
463 		return (map_szcvec(addr, size, off, max_lpsize,
464 		    shm_lpg_min_physmem));
465 
466 	} else if (type == MAPPGSZC_HEAP) {
467 		if (!memcntl)
468 			max_lpsize = max_uheap_lpsize;
469 		return (map_szcvec(addr, size, off, max_lpsize,
470 		    privm_lpg_min_physmem));
471 
472 	} else if (type == MAPPGSZC_STACK) {
473 		if (!memcntl)
474 			max_lpsize = max_ustack_lpsize;
475 		return (map_szcvec(addr, size, off, max_lpsize,
476 		    privm_lpg_min_physmem));
477 
478 	} else {
479 		if (!memcntl)
480 			max_lpsize = max_privmap_lpsize;
481 		return (map_szcvec(addr, size, off, max_lpsize,
482 		    privm_lpg_min_physmem));
483 	}
484 }
485 
486 /*
487  * Handle a pagefault.
488  */
489 faultcode_t
490 pagefault(
491 	caddr_t addr,
492 	enum fault_type type,
493 	enum seg_rw rw,
494 	int iskernel)
495 {
496 	struct as *as;
497 	struct hat *hat;
498 	struct proc *p;
499 	kthread_t *t;
500 	faultcode_t res;
501 	caddr_t base;
502 	size_t len;
503 	int err;
504 	int mapped_red;
505 	uintptr_t ea;
506 
507 	ASSERT_STACK_ALIGNED();
508 
509 	if (INVALID_VADDR(addr))
510 		return (FC_NOMAP);
511 
512 	mapped_red = segkp_map_red();
513 
514 	if (iskernel) {
515 		as = &kas;
516 		hat = as->a_hat;
517 	} else {
518 		t = curthread;
519 		p = ttoproc(t);
520 		as = p->p_as;
521 		hat = as->a_hat;
522 	}
523 
524 	/*
525 	 * Dispatch pagefault.
526 	 */
527 	res = as_fault(hat, as, addr, 1, type, rw);
528 
529 	/*
530 	 * If this isn't a potential unmapped hole in the user's
531 	 * UNIX data or stack segments, just return status info.
532 	 */
533 	if (res != FC_NOMAP || iskernel)
534 		goto out;
535 
536 	/*
537 	 * Check to see if we happened to faulted on a currently unmapped
538 	 * part of the UNIX data or stack segments.  If so, create a zfod
539 	 * mapping there and then try calling the fault routine again.
540 	 */
541 	base = p->p_brkbase;
542 	len = p->p_brksize;
543 
544 	if (addr < base || addr >= base + len) {		/* data seg? */
545 		base = (caddr_t)p->p_usrstack - p->p_stksize;
546 		len = p->p_stksize;
547 		if (addr < base || addr >= p->p_usrstack) {	/* stack seg? */
548 			/* not in either UNIX data or stack segments */
549 			res = FC_NOMAP;
550 			goto out;
551 		}
552 	}
553 
554 	/*
555 	 * the rest of this function implements a 3.X 4.X 5.X compatibility
556 	 * This code is probably not needed anymore
557 	 */
558 	if (p->p_model == DATAMODEL_ILP32) {
559 
560 		/* expand the gap to the page boundaries on each side */
561 		ea = P2ROUNDUP((uintptr_t)base + len, MMU_PAGESIZE);
562 		base = (caddr_t)P2ALIGN((uintptr_t)base, MMU_PAGESIZE);
563 		len = ea - (uintptr_t)base;
564 
565 		as_rangelock(as);
566 		if (as_gap(as, MMU_PAGESIZE, &base, &len, AH_CONTAIN, addr) ==
567 		    0) {
568 			err = as_map(as, base, len, segvn_create, zfod_argsp);
569 			as_rangeunlock(as);
570 			if (err) {
571 				res = FC_MAKE_ERR(err);
572 				goto out;
573 			}
574 		} else {
575 			/*
576 			 * This page is already mapped by another thread after
577 			 * we returned from as_fault() above.  We just fall
578 			 * through as_fault() below.
579 			 */
580 			as_rangeunlock(as);
581 		}
582 
583 		res = as_fault(hat, as, addr, 1, F_INVAL, rw);
584 	}
585 
586 out:
587 	if (mapped_red)
588 		segkp_unmap_red();
589 
590 	return (res);
591 }
592 
593 void
594 map_addr(caddr_t *addrp, size_t len, offset_t off, int vacalign, uint_t flags)
595 {
596 	struct proc *p = curproc;
597 	caddr_t userlimit = (flags & _MAP_LOW32) ?
598 	    (caddr_t)_userlimit32 : p->p_as->a_userlimit;
599 
600 	map_addr_proc(addrp, len, off, vacalign, userlimit, curproc, flags);
601 }
602 
603 /*ARGSUSED*/
604 int
605 map_addr_vacalign_check(caddr_t addr, u_offset_t off)
606 {
607 	return (0);
608 }
609 
610 /*
611  * map_addr_proc() is the routine called when the system is to
612  * choose an address for the user.  We will pick an address
613  * range which is the highest available below userlimit.
614  *
615  * Every mapping will have a redzone of a single page on either side of
616  * the request. This is done to leave one page unmapped between segments.
617  * This is not required, but it's useful for the user because if their
618  * program strays across a segment boundary, it will catch a fault
619  * immediately making debugging a little easier.  Currently the redzone
620  * is mandatory.
621  *
622  * addrp is a value/result parameter.
623  *	On input it is a hint from the user to be used in a completely
624  *	machine dependent fashion.  We decide to completely ignore this hint.
625  *	If MAP_ALIGN was specified, addrp contains the minimal alignment, which
626  *	must be some "power of two" multiple of pagesize.
627  *
628  *	On output it is NULL if no address can be found in the current
629  *	processes address space or else an address that is currently
630  *	not mapped for len bytes with a page of red zone on either side.
631  *
632  *	vacalign is not needed on x86 (it's for viturally addressed caches)
633  */
634 /*ARGSUSED*/
635 void
636 map_addr_proc(
637 	caddr_t *addrp,
638 	size_t len,
639 	offset_t off,
640 	int vacalign,
641 	caddr_t userlimit,
642 	struct proc *p,
643 	uint_t flags)
644 {
645 	struct as *as = p->p_as;
646 	caddr_t addr;
647 	caddr_t base;
648 	size_t slen;
649 	size_t align_amount;
650 
651 	ASSERT32(userlimit == as->a_userlimit);
652 
653 	base = p->p_brkbase;
654 #if defined(__amd64)
655 	/*
656 	 * XX64 Yes, this needs more work.
657 	 */
658 	if (p->p_model == DATAMODEL_NATIVE) {
659 		if (userlimit < as->a_userlimit) {
660 			/*
661 			 * This happens when a program wants to map
662 			 * something in a range that's accessible to a
663 			 * program in a smaller address space.  For example,
664 			 * a 64-bit program calling mmap32(2) to guarantee
665 			 * that the returned address is below 4Gbytes.
666 			 */
667 			ASSERT((uintptr_t)userlimit < ADDRESS_C(0xffffffff));
668 
669 			if (userlimit > base)
670 				slen = userlimit - base;
671 			else {
672 				*addrp = NULL;
673 				return;
674 			}
675 		} else {
676 			/*
677 			 * XX64 This layout is probably wrong .. but in
678 			 * the event we make the amd64 address space look
679 			 * like sparcv9 i.e. with the stack -above- the
680 			 * heap, this bit of code might even be correct.
681 			 */
682 			slen = p->p_usrstack - base -
683 			    ((p->p_stk_ctl + PAGEOFFSET) & PAGEMASK);
684 		}
685 	} else
686 #endif
687 		slen = userlimit - base;
688 
689 	/* Make len be a multiple of PAGESIZE */
690 	len = (len + PAGEOFFSET) & PAGEMASK;
691 
692 	/*
693 	 * figure out what the alignment should be
694 	 *
695 	 * XX64 -- is there an ELF_AMD64_MAXPGSZ or is it the same????
696 	 */
697 	if (len <= ELF_386_MAXPGSZ) {
698 		/*
699 		 * Align virtual addresses to ensure that ELF shared libraries
700 		 * are mapped with the appropriate alignment constraints by
701 		 * the run-time linker.
702 		 */
703 		align_amount = ELF_386_MAXPGSZ;
704 	} else {
705 		/*
706 		 * For 32-bit processes, only those which have specified
707 		 * MAP_ALIGN and an addr will be aligned on a larger page size.
708 		 * Not doing so can potentially waste up to 1G of process
709 		 * address space.
710 		 */
711 		int lvl = (p->p_model == DATAMODEL_ILP32) ? 1 :
712 		    mmu.umax_page_level;
713 
714 		while (lvl && len < LEVEL_SIZE(lvl))
715 			--lvl;
716 
717 		align_amount = LEVEL_SIZE(lvl);
718 	}
719 	if ((flags & MAP_ALIGN) && ((uintptr_t)*addrp > align_amount))
720 		align_amount = (uintptr_t)*addrp;
721 
722 	ASSERT(ISP2(align_amount));
723 	ASSERT(align_amount == 0 || align_amount >= PAGESIZE);
724 
725 	off = off & (align_amount - 1);
726 	/*
727 	 * Look for a large enough hole starting below userlimit.
728 	 * After finding it, use the upper part.
729 	 */
730 	if (as_gap_aligned(as, len, &base, &slen, AH_HI, NULL, align_amount,
731 	    PAGESIZE, off) == 0) {
732 		caddr_t as_addr;
733 
734 		/*
735 		 * addr is the highest possible address to use since we have
736 		 * a PAGESIZE redzone at the beginning and end.
737 		 */
738 		addr = base + slen - (PAGESIZE + len);
739 		as_addr = addr;
740 		/*
741 		 * Round address DOWN to the alignment amount and
742 		 * add the offset in.
743 		 * If addr is greater than as_addr, len would not be large
744 		 * enough to include the redzone, so we must adjust down
745 		 * by the alignment amount.
746 		 */
747 		addr = (caddr_t)((uintptr_t)addr & (~(align_amount - 1)));
748 		addr += (uintptr_t)off;
749 		if (addr > as_addr) {
750 			addr -= align_amount;
751 		}
752 
753 		ASSERT(addr > base);
754 		ASSERT(addr + len < base + slen);
755 		ASSERT(((uintptr_t)addr & (align_amount - 1)) ==
756 		    ((uintptr_t)(off)));
757 		*addrp = addr;
758 	} else {
759 		*addrp = NULL;	/* no more virtual space */
760 	}
761 }
762 
763 int valid_va_range_aligned_wraparound;
764 
765 /*
766  * Determine whether [*basep, *basep + *lenp) contains a mappable range of
767  * addresses at least "minlen" long, where the base of the range is at "off"
768  * phase from an "align" boundary and there is space for a "redzone"-sized
769  * redzone on either side of the range.  On success, 1 is returned and *basep
770  * and *lenp are adjusted to describe the acceptable range (including
771  * the redzone).  On failure, 0 is returned.
772  */
773 /*ARGSUSED3*/
774 int
775 valid_va_range_aligned(caddr_t *basep, size_t *lenp, size_t minlen, int dir,
776     size_t align, size_t redzone, size_t off)
777 {
778 	uintptr_t hi, lo;
779 	size_t tot_len;
780 
781 	ASSERT(align == 0 ? off == 0 : off < align);
782 	ASSERT(ISP2(align));
783 	ASSERT(align == 0 || align >= PAGESIZE);
784 
785 	lo = (uintptr_t)*basep;
786 	hi = lo + *lenp;
787 	tot_len = minlen + 2 * redzone; /* need at least this much space */
788 
789 	/*
790 	 * If hi rolled over the top, try cutting back.
791 	 */
792 	if (hi < lo) {
793 		*lenp = 0UL - lo - 1UL;
794 		/* See if this really happens. If so, then we figure out why */
795 		valid_va_range_aligned_wraparound++;
796 		hi = lo + *lenp;
797 	}
798 	if (*lenp < tot_len) {
799 		return (0);
800 	}
801 
802 #if defined(__amd64)
803 	/*
804 	 * Deal with a possible hole in the address range between
805 	 * hole_start and hole_end that should never be mapped.
806 	 */
807 	if (lo < hole_start) {
808 		if (hi > hole_start) {
809 			if (hi < hole_end) {
810 				hi = hole_start;
811 			} else {
812 				/* lo < hole_start && hi >= hole_end */
813 				if (dir == AH_LO) {
814 					/*
815 					 * prefer lowest range
816 					 */
817 					if (hole_start - lo >= tot_len)
818 						hi = hole_start;
819 					else if (hi - hole_end >= tot_len)
820 						lo = hole_end;
821 					else
822 						return (0);
823 				} else {
824 					/*
825 					 * prefer highest range
826 					 */
827 					if (hi - hole_end >= tot_len)
828 						lo = hole_end;
829 					else if (hole_start - lo >= tot_len)
830 						hi = hole_start;
831 					else
832 						return (0);
833 				}
834 			}
835 		}
836 	} else {
837 		/* lo >= hole_start */
838 		if (hi < hole_end)
839 			return (0);
840 		if (lo < hole_end)
841 			lo = hole_end;
842 	}
843 #endif
844 
845 	if (hi - lo < tot_len)
846 		return (0);
847 
848 	if (align > 1) {
849 		uintptr_t tlo = lo + redzone;
850 		uintptr_t thi = hi - redzone;
851 		tlo = (uintptr_t)P2PHASEUP(tlo, align, off);
852 		if (tlo < lo + redzone) {
853 			return (0);
854 		}
855 		if (thi < tlo || thi - tlo < minlen) {
856 			return (0);
857 		}
858 	}
859 
860 	*basep = (caddr_t)lo;
861 	*lenp = hi - lo;
862 	return (1);
863 }
864 
865 /*
866  * Determine whether [*basep, *basep + *lenp) contains a mappable range of
867  * addresses at least "minlen" long.  On success, 1 is returned and *basep
868  * and *lenp are adjusted to describe the acceptable range.  On failure, 0
869  * is returned.
870  */
871 int
872 valid_va_range(caddr_t *basep, size_t *lenp, size_t minlen, int dir)
873 {
874 	return (valid_va_range_aligned(basep, lenp, minlen, dir, 0, 0, 0));
875 }
876 
877 /*
878  * Determine whether [addr, addr+len] are valid user addresses.
879  */
880 /*ARGSUSED*/
881 int
882 valid_usr_range(caddr_t addr, size_t len, uint_t prot, struct as *as,
883     caddr_t userlimit)
884 {
885 	caddr_t eaddr = addr + len;
886 
887 	if (eaddr <= addr || addr >= userlimit || eaddr > userlimit)
888 		return (RANGE_BADADDR);
889 
890 #if defined(__amd64)
891 	/*
892 	 * Check for the VA hole
893 	 */
894 	if (eaddr > (caddr_t)hole_start && addr < (caddr_t)hole_end)
895 		return (RANGE_BADADDR);
896 #endif
897 
898 	return (RANGE_OKAY);
899 }
900 
901 /*
902  * Return 1 if the page frame is onboard memory, else 0.
903  */
904 int
905 pf_is_memory(pfn_t pf)
906 {
907 	if (pfn_is_foreign(pf))
908 		return (0);
909 	return (address_in_memlist(phys_install, pfn_to_pa(pf), 1));
910 }
911 
912 /*
913  * return the memrange containing pfn
914  */
915 int
916 memrange_num(pfn_t pfn)
917 {
918 	int n;
919 
920 	for (n = 0; n < nranges - 1; ++n) {
921 		if (pfn >= memranges[n])
922 			break;
923 	}
924 	return (n);
925 }
926 
927 /*
928  * return the mnoderange containing pfn
929  */
930 /*ARGSUSED*/
931 int
932 pfn_2_mtype(pfn_t pfn)
933 {
934 #if defined(__xpv)
935 	return (0);
936 #else
937 	int	n;
938 
939 	/* Always start from highest pfn and work our way down */
940 	for (n = mtypetop; n != -1; n = mnoderanges[n].mnr_next) {
941 		if (pfn >= mnoderanges[n].mnr_pfnlo) {
942 			break;
943 		}
944 	}
945 	return (n);
946 #endif
947 }
948 
949 #if !defined(__xpv)
950 /*
951  * is_contigpage_free:
952  *	returns a page list of contiguous pages. It minimally has to return
953  *	minctg pages. Caller determines minctg based on the scatter-gather
954  *	list length.
955  *
956  *	pfnp is set to the next page frame to search on return.
957  */
958 static page_t *
959 is_contigpage_free(
960 	pfn_t *pfnp,
961 	pgcnt_t *pgcnt,
962 	pgcnt_t minctg,
963 	uint64_t pfnseg,
964 	int iolock)
965 {
966 	int	i = 0;
967 	pfn_t	pfn = *pfnp;
968 	page_t	*pp;
969 	page_t	*plist = NULL;
970 
971 	/*
972 	 * fail if pfn + minctg crosses a segment boundary.
973 	 * Adjust for next starting pfn to begin at segment boundary.
974 	 */
975 
976 	if (((*pfnp + minctg - 1) & pfnseg) < (*pfnp & pfnseg)) {
977 		*pfnp = roundup(*pfnp, pfnseg + 1);
978 		return (NULL);
979 	}
980 
981 	do {
982 retry:
983 		pp = page_numtopp_nolock(pfn + i);
984 		if ((pp == NULL) ||
985 		    (page_trylock(pp, SE_EXCL) == 0)) {
986 			(*pfnp)++;
987 			break;
988 		}
989 		if (page_pptonum(pp) != pfn + i) {
990 			page_unlock(pp);
991 			goto retry;
992 		}
993 
994 		if (!(PP_ISFREE(pp))) {
995 			page_unlock(pp);
996 			(*pfnp)++;
997 			break;
998 		}
999 
1000 		if (!PP_ISAGED(pp)) {
1001 			page_list_sub(pp, PG_CACHE_LIST);
1002 			page_hashout(pp, (kmutex_t *)NULL);
1003 		} else {
1004 			page_list_sub(pp, PG_FREE_LIST);
1005 		}
1006 
1007 		if (iolock)
1008 			page_io_lock(pp);
1009 		page_list_concat(&plist, &pp);
1010 
1011 		/*
1012 		 * exit loop when pgcnt satisfied or segment boundary reached.
1013 		 */
1014 
1015 	} while ((++i < *pgcnt) && ((pfn + i) & pfnseg));
1016 
1017 	*pfnp += i;		/* set to next pfn to search */
1018 
1019 	if (i >= minctg) {
1020 		*pgcnt -= i;
1021 		return (plist);
1022 	}
1023 
1024 	/*
1025 	 * failure: minctg not satisfied.
1026 	 *
1027 	 * if next request crosses segment boundary, set next pfn
1028 	 * to search from the segment boundary.
1029 	 */
1030 	if (((*pfnp + minctg - 1) & pfnseg) < (*pfnp & pfnseg))
1031 		*pfnp = roundup(*pfnp, pfnseg + 1);
1032 
1033 	/* clean up any pages already allocated */
1034 
1035 	while (plist) {
1036 		pp = plist;
1037 		page_sub(&plist, pp);
1038 		page_list_add(pp, PG_FREE_LIST | PG_LIST_TAIL);
1039 		if (iolock)
1040 			page_io_unlock(pp);
1041 		page_unlock(pp);
1042 	}
1043 
1044 	return (NULL);
1045 }
1046 #endif	/* !__xpv */
1047 
1048 /*
1049  * verify that pages being returned from allocator have correct DMA attribute
1050  */
1051 #ifndef DEBUG
1052 #define	check_dma(a, b, c) (void)(0)
1053 #else
1054 static void
1055 check_dma(ddi_dma_attr_t *dma_attr, page_t *pp, int cnt)
1056 {
1057 	if (dma_attr == NULL)
1058 		return;
1059 
1060 	while (cnt-- > 0) {
1061 		if (pa_to_ma(pfn_to_pa(pp->p_pagenum)) <
1062 		    dma_attr->dma_attr_addr_lo)
1063 			panic("PFN (pp=%p) below dma_attr_addr_lo", (void *)pp);
1064 		if (pa_to_ma(pfn_to_pa(pp->p_pagenum)) >=
1065 		    dma_attr->dma_attr_addr_hi)
1066 			panic("PFN (pp=%p) above dma_attr_addr_hi", (void *)pp);
1067 		pp = pp->p_next;
1068 	}
1069 }
1070 #endif
1071 
1072 #if !defined(__xpv)
1073 static page_t *
1074 page_get_contigpage(pgcnt_t *pgcnt, ddi_dma_attr_t *mattr, int iolock)
1075 {
1076 	pfn_t		pfn;
1077 	int		sgllen;
1078 	uint64_t	pfnseg;
1079 	pgcnt_t		minctg;
1080 	page_t		*pplist = NULL, *plist;
1081 	uint64_t	lo, hi;
1082 	pgcnt_t		pfnalign = 0;
1083 	static pfn_t	startpfn;
1084 	static pgcnt_t	lastctgcnt;
1085 	uintptr_t	align;
1086 
1087 	CONTIG_LOCK();
1088 
1089 	if (mattr) {
1090 		lo = mmu_btop((mattr->dma_attr_addr_lo + MMU_PAGEOFFSET));
1091 		hi = mmu_btop(mattr->dma_attr_addr_hi);
1092 		if (hi >= physmax)
1093 			hi = physmax - 1;
1094 		sgllen = mattr->dma_attr_sgllen;
1095 		pfnseg = mmu_btop(mattr->dma_attr_seg);
1096 
1097 		align = maxbit(mattr->dma_attr_align, mattr->dma_attr_minxfer);
1098 		if (align > MMU_PAGESIZE)
1099 			pfnalign = mmu_btop(align);
1100 
1101 		/*
1102 		 * in order to satisfy the request, must minimally
1103 		 * acquire minctg contiguous pages
1104 		 */
1105 		minctg = howmany(*pgcnt, sgllen);
1106 
1107 		ASSERT(hi >= lo);
1108 
1109 		/*
1110 		 * start from where last searched if the minctg >= lastctgcnt
1111 		 */
1112 		if (minctg < lastctgcnt || startpfn < lo || startpfn > hi)
1113 			startpfn = lo;
1114 	} else {
1115 		hi = physmax - 1;
1116 		lo = 0;
1117 		sgllen = 1;
1118 		pfnseg = mmu.highest_pfn;
1119 		minctg = *pgcnt;
1120 
1121 		if (minctg < lastctgcnt)
1122 			startpfn = lo;
1123 	}
1124 	lastctgcnt = minctg;
1125 
1126 	ASSERT(pfnseg + 1 >= (uint64_t)minctg);
1127 
1128 	/* conserve 16m memory - start search above 16m when possible */
1129 	if (hi > PFN_16M && startpfn < PFN_16M)
1130 		startpfn = PFN_16M;
1131 
1132 	pfn = startpfn;
1133 	if (pfnalign)
1134 		pfn = P2ROUNDUP(pfn, pfnalign);
1135 
1136 	while (pfn + minctg - 1 <= hi) {
1137 
1138 		plist = is_contigpage_free(&pfn, pgcnt, minctg, pfnseg, iolock);
1139 		if (plist) {
1140 			page_list_concat(&pplist, &plist);
1141 			sgllen--;
1142 			/*
1143 			 * return when contig pages no longer needed
1144 			 */
1145 			if (!*pgcnt || ((*pgcnt <= sgllen) && !pfnalign)) {
1146 				startpfn = pfn;
1147 				CONTIG_UNLOCK();
1148 #ifdef DEBUG
1149 				check_dma(mattr, pplist, *pgcnt);
1150 #endif
1151 				return (pplist);
1152 			}
1153 			minctg = howmany(*pgcnt, sgllen);
1154 		}
1155 		if (pfnalign)
1156 			pfn = P2ROUNDUP(pfn, pfnalign);
1157 	}
1158 
1159 	/* cannot find contig pages in specified range */
1160 	if (startpfn == lo) {
1161 		CONTIG_UNLOCK();
1162 		return (NULL);
1163 	}
1164 
1165 	/* did not start with lo previously */
1166 	pfn = lo;
1167 	if (pfnalign)
1168 		pfn = P2ROUNDUP(pfn, pfnalign);
1169 
1170 	/* allow search to go above startpfn */
1171 	while (pfn < startpfn) {
1172 
1173 		plist = is_contigpage_free(&pfn, pgcnt, minctg, pfnseg, iolock);
1174 		if (plist != NULL) {
1175 
1176 			page_list_concat(&pplist, &plist);
1177 			sgllen--;
1178 
1179 			/*
1180 			 * return when contig pages no longer needed
1181 			 */
1182 			if (!*pgcnt || ((*pgcnt <= sgllen) && !pfnalign)) {
1183 				startpfn = pfn;
1184 				CONTIG_UNLOCK();
1185 #ifdef DEBUG
1186 				check_dma(mattr, pplist, *pgcnt);
1187 #endif
1188 				return (pplist);
1189 			}
1190 			minctg = howmany(*pgcnt, sgllen);
1191 		}
1192 		if (pfnalign)
1193 			pfn = P2ROUNDUP(pfn, pfnalign);
1194 	}
1195 	CONTIG_UNLOCK();
1196 	return (NULL);
1197 }
1198 #endif	/* !__xpv */
1199 
1200 /*
1201  * mnode_range_cnt() calculates the number of memory ranges for mnode and
1202  * memranges[]. Used to determine the size of page lists and mnoderanges.
1203  */
1204 int
1205 mnode_range_cnt(int mnode)
1206 {
1207 #if defined(__xpv)
1208 	ASSERT(mnode == 0);
1209 	return (1);
1210 #else	/* __xpv */
1211 	int	mri;
1212 	int	mnrcnt = 0;
1213 
1214 	if (mem_node_config[mnode].exists != 0) {
1215 		mri = nranges - 1;
1216 
1217 		/* find the memranges index below contained in mnode range */
1218 
1219 		while (MEMRANGEHI(mri) < mem_node_config[mnode].physbase)
1220 			mri--;
1221 
1222 		/*
1223 		 * increment mnode range counter when memranges or mnode
1224 		 * boundary is reached.
1225 		 */
1226 		while (mri >= 0 &&
1227 		    mem_node_config[mnode].physmax >= MEMRANGELO(mri)) {
1228 			mnrcnt++;
1229 			if (mem_node_config[mnode].physmax > MEMRANGEHI(mri))
1230 				mri--;
1231 			else
1232 				break;
1233 		}
1234 	}
1235 	ASSERT(mnrcnt <= MAX_MNODE_MRANGES);
1236 	return (mnrcnt);
1237 #endif	/* __xpv */
1238 }
1239 
1240 /*
1241  * mnode_range_setup() initializes mnoderanges.
1242  */
1243 void
1244 mnode_range_setup(mnoderange_t *mnoderanges)
1245 {
1246 	mnoderange_t *mp = mnoderanges;
1247 	int	mnode, mri;
1248 	int	mindex = 0;	/* current index into mnoderanges array */
1249 	int	i, j;
1250 	pfn_t	hipfn;
1251 	int	last, hi;
1252 
1253 	for (mnode = 0; mnode < max_mem_nodes; mnode++) {
1254 		if (mem_node_config[mnode].exists == 0)
1255 			continue;
1256 
1257 		mri = nranges - 1;
1258 
1259 		while (MEMRANGEHI(mri) < mem_node_config[mnode].physbase)
1260 			mri--;
1261 
1262 		while (mri >= 0 && mem_node_config[mnode].physmax >=
1263 		    MEMRANGELO(mri)) {
1264 			mnoderanges->mnr_pfnlo = MAX(MEMRANGELO(mri),
1265 			    mem_node_config[mnode].physbase);
1266 			mnoderanges->mnr_pfnhi = MIN(MEMRANGEHI(mri),
1267 			    mem_node_config[mnode].physmax);
1268 			mnoderanges->mnr_mnode = mnode;
1269 			mnoderanges->mnr_memrange = mri;
1270 			mnoderanges->mnr_exists = 1;
1271 			mnoderanges++;
1272 			mindex++;
1273 			if (mem_node_config[mnode].physmax > MEMRANGEHI(mri))
1274 				mri--;
1275 			else
1276 				break;
1277 		}
1278 	}
1279 
1280 	/*
1281 	 * For now do a simple sort of the mnoderanges array to fill in
1282 	 * the mnr_next fields.  Since mindex is expected to be relatively
1283 	 * small, using a simple O(N^2) algorithm.
1284 	 */
1285 	for (i = 0; i < mindex; i++) {
1286 		if (mp[i].mnr_pfnlo == 0)	/* find lowest */
1287 			break;
1288 	}
1289 	ASSERT(i < mindex);
1290 	last = i;
1291 	mtype16m = last;
1292 	mp[last].mnr_next = -1;
1293 	for (i = 0; i < mindex - 1; i++) {
1294 		hipfn = (pfn_t)(-1);
1295 		hi = -1;
1296 		/* find next highest mnode range */
1297 		for (j = 0; j < mindex; j++) {
1298 			if (mp[j].mnr_pfnlo > mp[last].mnr_pfnlo &&
1299 			    mp[j].mnr_pfnlo < hipfn) {
1300 				hipfn = mp[j].mnr_pfnlo;
1301 				hi = j;
1302 			}
1303 		}
1304 		mp[hi].mnr_next = last;
1305 		last = hi;
1306 	}
1307 	mtypetop = last;
1308 }
1309 
1310 #ifndef	__xpv
1311 /*
1312  * Update mnoderanges for memory hot-add DR operations.
1313  */
1314 static void
1315 mnode_range_add(int mnode)
1316 {
1317 	int	*prev;
1318 	int	n, mri;
1319 	pfn_t	start, end;
1320 	extern	void membar_sync(void);
1321 
1322 	ASSERT(0 <= mnode && mnode < max_mem_nodes);
1323 	ASSERT(mem_node_config[mnode].exists);
1324 	start = mem_node_config[mnode].physbase;
1325 	end = mem_node_config[mnode].physmax;
1326 	ASSERT(start <= end);
1327 	mutex_enter(&mnoderange_lock);
1328 
1329 #ifdef	DEBUG
1330 	/* Check whether it interleaves with other memory nodes. */
1331 	for (n = mtypetop; n != -1; n = mnoderanges[n].mnr_next) {
1332 		ASSERT(mnoderanges[n].mnr_exists);
1333 		if (mnoderanges[n].mnr_mnode == mnode)
1334 			continue;
1335 		ASSERT(start > mnoderanges[n].mnr_pfnhi ||
1336 		    end < mnoderanges[n].mnr_pfnlo);
1337 	}
1338 #endif	/* DEBUG */
1339 
1340 	mri = nranges - 1;
1341 	while (MEMRANGEHI(mri) < mem_node_config[mnode].physbase)
1342 		mri--;
1343 	while (mri >= 0 && mem_node_config[mnode].physmax >= MEMRANGELO(mri)) {
1344 		/* Check whether mtype already exists. */
1345 		for (n = mtypetop; n != -1; n = mnoderanges[n].mnr_next) {
1346 			if (mnoderanges[n].mnr_mnode == mnode &&
1347 			    mnoderanges[n].mnr_memrange == mri) {
1348 				mnoderanges[n].mnr_pfnlo = MAX(MEMRANGELO(mri),
1349 				    start);
1350 				mnoderanges[n].mnr_pfnhi = MIN(MEMRANGEHI(mri),
1351 				    end);
1352 				break;
1353 			}
1354 		}
1355 
1356 		/* Add a new entry if it doesn't exist yet. */
1357 		if (n == -1) {
1358 			/* Try to find an unused entry in mnoderanges array. */
1359 			for (n = 0; n < mnoderangecnt; n++) {
1360 				if (mnoderanges[n].mnr_exists == 0)
1361 					break;
1362 			}
1363 			ASSERT(n < mnoderangecnt);
1364 			mnoderanges[n].mnr_pfnlo = MAX(MEMRANGELO(mri), start);
1365 			mnoderanges[n].mnr_pfnhi = MIN(MEMRANGEHI(mri), end);
1366 			mnoderanges[n].mnr_mnode = mnode;
1367 			mnoderanges[n].mnr_memrange = mri;
1368 			mnoderanges[n].mnr_exists = 1;
1369 			/* Page 0 should always be present. */
1370 			for (prev = &mtypetop;
1371 			    mnoderanges[*prev].mnr_pfnlo > start;
1372 			    prev = &mnoderanges[*prev].mnr_next) {
1373 				ASSERT(mnoderanges[*prev].mnr_next >= 0);
1374 				ASSERT(mnoderanges[*prev].mnr_pfnlo > end);
1375 			}
1376 			mnoderanges[n].mnr_next = *prev;
1377 			membar_sync();
1378 			*prev = n;
1379 		}
1380 
1381 		if (mem_node_config[mnode].physmax > MEMRANGEHI(mri))
1382 			mri--;
1383 		else
1384 			break;
1385 	}
1386 
1387 	mutex_exit(&mnoderange_lock);
1388 }
1389 
1390 /*
1391  * Update mnoderanges for memory hot-removal DR operations.
1392  */
1393 static void
1394 mnode_range_del(int mnode)
1395 {
1396 	_NOTE(ARGUNUSED(mnode));
1397 	ASSERT(0 <= mnode && mnode < max_mem_nodes);
1398 	/* TODO: support deletion operation. */
1399 	ASSERT(0);
1400 }
1401 
1402 void
1403 plat_slice_add(pfn_t start, pfn_t end)
1404 {
1405 	mem_node_add_slice(start, end);
1406 	if (plat_dr_enabled()) {
1407 		mnode_range_add(PFN_2_MEM_NODE(start));
1408 	}
1409 }
1410 
1411 void
1412 plat_slice_del(pfn_t start, pfn_t end)
1413 {
1414 	ASSERT(PFN_2_MEM_NODE(start) == PFN_2_MEM_NODE(end));
1415 	ASSERT(plat_dr_enabled());
1416 	mnode_range_del(PFN_2_MEM_NODE(start));
1417 	mem_node_del_slice(start, end);
1418 }
1419 #endif	/* __xpv */
1420 
1421 /*ARGSUSED*/
1422 int
1423 mtype_init(vnode_t *vp, caddr_t vaddr, uint_t *flags, size_t pgsz)
1424 {
1425 	int mtype = mtypetop;
1426 
1427 #if !defined(__xpv)
1428 #if defined(__i386)
1429 	/*
1430 	 * set the mtype range
1431 	 * - kmem requests need to be below 4g if restricted_kmemalloc is set.
1432 	 * - for non kmem requests, set range to above 4g if memory below 4g
1433 	 * runs low.
1434 	 */
1435 	if (restricted_kmemalloc && VN_ISKAS(vp) &&
1436 	    (caddr_t)(vaddr) >= kernelheap &&
1437 	    (caddr_t)(vaddr) < ekernelheap) {
1438 		ASSERT(physmax4g);
1439 		mtype = mtype4g;
1440 		if (RESTRICT16M_ALLOC(freemem4g - btop(pgsz),
1441 		    btop(pgsz), *flags)) {
1442 			*flags |= PGI_MT_RANGE16M;
1443 		} else {
1444 			VM_STAT_ADD(vmm_vmstats.unrestrict16mcnt);
1445 			VM_STAT_COND_ADD((*flags & PG_PANIC),
1446 			    vmm_vmstats.pgpanicalloc);
1447 			*flags |= PGI_MT_RANGE0;
1448 		}
1449 		return (mtype);
1450 	}
1451 #endif	/* __i386 */
1452 
1453 	if (RESTRICT4G_ALLOC) {
1454 		VM_STAT_ADD(vmm_vmstats.restrict4gcnt);
1455 		/* here only for > 4g systems */
1456 		*flags |= PGI_MT_RANGE4G;
1457 	} else if (RESTRICT16M_ALLOC(freemem, btop(pgsz), *flags)) {
1458 		*flags |= PGI_MT_RANGE16M;
1459 	} else {
1460 		VM_STAT_ADD(vmm_vmstats.unrestrict16mcnt);
1461 		VM_STAT_COND_ADD((*flags & PG_PANIC), vmm_vmstats.pgpanicalloc);
1462 		*flags |= PGI_MT_RANGE0;
1463 	}
1464 #endif /* !__xpv */
1465 	return (mtype);
1466 }
1467 
1468 
1469 /* mtype init for page_get_replacement_page */
1470 /*ARGSUSED*/
1471 int
1472 mtype_pgr_init(int *flags, page_t *pp, int mnode, pgcnt_t pgcnt)
1473 {
1474 	int mtype = mtypetop;
1475 #if !defined(__xpv)
1476 	if (RESTRICT16M_ALLOC(freemem, pgcnt, *flags)) {
1477 		*flags |= PGI_MT_RANGE16M;
1478 	} else {
1479 		VM_STAT_ADD(vmm_vmstats.unrestrict16mcnt);
1480 		*flags |= PGI_MT_RANGE0;
1481 	}
1482 #endif
1483 	return (mtype);
1484 }
1485 
1486 /*
1487  * Determine if the mnode range specified in mtype contains memory belonging
1488  * to memory node mnode.  If flags & PGI_MT_RANGE is set then mtype contains
1489  * the range from high pfn to 0, 16m or 4g.
1490  *
1491  * Return first mnode range type index found otherwise return -1 if none found.
1492  */
1493 int
1494 mtype_func(int mnode, int mtype, uint_t flags)
1495 {
1496 	if (flags & PGI_MT_RANGE) {
1497 		int	mnr_lim = MRI_0;
1498 
1499 		if (flags & PGI_MT_NEXT) {
1500 			mtype = mnoderanges[mtype].mnr_next;
1501 		}
1502 		if (flags & PGI_MT_RANGE4G)
1503 			mnr_lim = MRI_4G;	/* exclude 0-4g range */
1504 		else if (flags & PGI_MT_RANGE16M)
1505 			mnr_lim = MRI_16M;	/* exclude 0-16m range */
1506 		while (mtype != -1 &&
1507 		    mnoderanges[mtype].mnr_memrange <= mnr_lim) {
1508 			if (mnoderanges[mtype].mnr_mnode == mnode)
1509 				return (mtype);
1510 			mtype = mnoderanges[mtype].mnr_next;
1511 		}
1512 	} else if (mnoderanges[mtype].mnr_mnode == mnode) {
1513 		return (mtype);
1514 	}
1515 	return (-1);
1516 }
1517 
1518 /*
1519  * Update the page list max counts with the pfn range specified by the
1520  * input parameters.
1521  */
1522 void
1523 mtype_modify_max(pfn_t startpfn, long cnt)
1524 {
1525 	int		mtype;
1526 	pgcnt_t		inc;
1527 	spgcnt_t	scnt = (spgcnt_t)(cnt);
1528 	pgcnt_t		acnt = ABS(scnt);
1529 	pfn_t		endpfn = startpfn + acnt;
1530 	pfn_t		pfn, lo;
1531 
1532 	if (!physmax4g)
1533 		return;
1534 
1535 	mtype = mtypetop;
1536 	for (pfn = endpfn; pfn > startpfn; ) {
1537 		ASSERT(mtype != -1);
1538 		lo = mnoderanges[mtype].mnr_pfnlo;
1539 		if (pfn > lo) {
1540 			if (startpfn >= lo) {
1541 				inc = pfn - startpfn;
1542 			} else {
1543 				inc = pfn - lo;
1544 			}
1545 			if (mnoderanges[mtype].mnr_memrange != MRI_4G) {
1546 				if (scnt > 0)
1547 					maxmem4g += inc;
1548 				else
1549 					maxmem4g -= inc;
1550 			}
1551 			pfn -= inc;
1552 		}
1553 		mtype = mnoderanges[mtype].mnr_next;
1554 	}
1555 }
1556 
1557 int
1558 mtype_2_mrange(int mtype)
1559 {
1560 	return (mnoderanges[mtype].mnr_memrange);
1561 }
1562 
1563 void
1564 mnodetype_2_pfn(int mnode, int mtype, pfn_t *pfnlo, pfn_t *pfnhi)
1565 {
1566 	_NOTE(ARGUNUSED(mnode));
1567 	ASSERT(mnoderanges[mtype].mnr_mnode == mnode);
1568 	*pfnlo = mnoderanges[mtype].mnr_pfnlo;
1569 	*pfnhi = mnoderanges[mtype].mnr_pfnhi;
1570 }
1571 
1572 size_t
1573 plcnt_sz(size_t ctrs_sz)
1574 {
1575 #ifdef DEBUG
1576 	int	szc, colors;
1577 
1578 	ctrs_sz += mnoderangecnt * sizeof (struct mnr_mts) * mmu_page_sizes;
1579 	for (szc = 0; szc < mmu_page_sizes; szc++) {
1580 		colors = page_get_pagecolors(szc);
1581 		ctrs_sz += mnoderangecnt * sizeof (pgcnt_t) * colors;
1582 	}
1583 #endif
1584 	return (ctrs_sz);
1585 }
1586 
1587 caddr_t
1588 plcnt_init(caddr_t addr)
1589 {
1590 #ifdef DEBUG
1591 	int	mt, szc, colors;
1592 
1593 	for (mt = 0; mt < mnoderangecnt; mt++) {
1594 		mnoderanges[mt].mnr_mts = (struct mnr_mts *)addr;
1595 		addr += (sizeof (struct mnr_mts) * mmu_page_sizes);
1596 		for (szc = 0; szc < mmu_page_sizes; szc++) {
1597 			colors = page_get_pagecolors(szc);
1598 			mnoderanges[mt].mnr_mts[szc].mnr_mts_colors = colors;
1599 			mnoderanges[mt].mnr_mts[szc].mnr_mtsc_pgcnt =
1600 			    (pgcnt_t *)addr;
1601 			addr += (sizeof (pgcnt_t) * colors);
1602 		}
1603 	}
1604 #endif
1605 	return (addr);
1606 }
1607 
1608 void
1609 plcnt_inc_dec(page_t *pp, int mtype, int szc, long cnt, int flags)
1610 {
1611 	_NOTE(ARGUNUSED(pp));
1612 #ifdef DEBUG
1613 	int	bin = PP_2_BIN(pp);
1614 
1615 	atomic_add_long(&mnoderanges[mtype].mnr_mts[szc].mnr_mts_pgcnt, cnt);
1616 	atomic_add_long(&mnoderanges[mtype].mnr_mts[szc].mnr_mtsc_pgcnt[bin],
1617 	    cnt);
1618 #endif
1619 	ASSERT(mtype == PP_2_MTYPE(pp));
1620 	if (physmax4g && mnoderanges[mtype].mnr_memrange != MRI_4G)
1621 		atomic_add_long(&freemem4g, cnt);
1622 	if (flags & PG_CACHE_LIST)
1623 		atomic_add_long(&mnoderanges[mtype].mnr_mt_clpgcnt, cnt);
1624 	else
1625 		atomic_add_long(&mnoderanges[mtype].mnr_mt_flpgcnt[szc], cnt);
1626 	atomic_add_long(&mnoderanges[mtype].mnr_mt_totcnt, cnt);
1627 }
1628 
1629 /*
1630  * Returns the free page count for mnode
1631  */
1632 int
1633 mnode_pgcnt(int mnode)
1634 {
1635 	int	mtype = mtypetop;
1636 	int	flags = PGI_MT_RANGE0;
1637 	pgcnt_t	pgcnt = 0;
1638 
1639 	mtype = mtype_func(mnode, mtype, flags);
1640 
1641 	while (mtype != -1) {
1642 		pgcnt += MTYPE_FREEMEM(mtype);
1643 		mtype = mtype_func(mnode, mtype, flags | PGI_MT_NEXT);
1644 	}
1645 	return (pgcnt);
1646 }
1647 
1648 /*
1649  * Initialize page coloring variables based on the l2 cache parameters.
1650  * Calculate and return memory needed for page coloring data structures.
1651  */
1652 size_t
1653 page_coloring_init(uint_t l2_sz, int l2_linesz, int l2_assoc)
1654 {
1655 	_NOTE(ARGUNUSED(l2_linesz));
1656 	size_t	colorsz = 0;
1657 	int	i;
1658 	int	colors;
1659 
1660 #if defined(__xpv)
1661 	/*
1662 	 * Hypervisor domains currently don't have any concept of NUMA.
1663 	 * Hence we'll act like there is only 1 memrange.
1664 	 */
1665 	i = memrange_num(1);
1666 #else /* !__xpv */
1667 	/*
1668 	 * Reduce the memory ranges lists if we don't have large amounts
1669 	 * of memory. This avoids searching known empty free lists.
1670 	 * To support memory DR operations, we need to keep memory ranges
1671 	 * for possible memory hot-add operations.
1672 	 */
1673 	if (plat_dr_physmax > physmax)
1674 		i = memrange_num(plat_dr_physmax);
1675 	else
1676 		i = memrange_num(physmax);
1677 #if defined(__i386)
1678 	if (i > MRI_4G)
1679 		restricted_kmemalloc = 0;
1680 #endif
1681 	/* physmax greater than 4g */
1682 	if (i == MRI_4G)
1683 		physmax4g = 1;
1684 #endif /* !__xpv */
1685 	memranges += i;
1686 	nranges -= i;
1687 
1688 	ASSERT(mmu_page_sizes <= MMU_PAGE_SIZES);
1689 
1690 	ASSERT(ISP2(l2_linesz));
1691 	ASSERT(l2_sz > MMU_PAGESIZE);
1692 
1693 	/* l2_assoc is 0 for fully associative l2 cache */
1694 	if (l2_assoc)
1695 		l2_colors = MAX(1, l2_sz / (l2_assoc * MMU_PAGESIZE));
1696 	else
1697 		l2_colors = 1;
1698 
1699 	ASSERT(ISP2(l2_colors));
1700 
1701 	/* for scalability, configure at least PAGE_COLORS_MIN color bins */
1702 	page_colors = MAX(l2_colors, PAGE_COLORS_MIN);
1703 
1704 	/*
1705 	 * cpu_page_colors is non-zero when a page color may be spread across
1706 	 * multiple bins.
1707 	 */
1708 	if (l2_colors < page_colors)
1709 		cpu_page_colors = l2_colors;
1710 
1711 	ASSERT(ISP2(page_colors));
1712 
1713 	page_colors_mask = page_colors - 1;
1714 
1715 	ASSERT(ISP2(CPUSETSIZE()));
1716 	page_coloring_shift = lowbit(CPUSETSIZE());
1717 
1718 	/* initialize number of colors per page size */
1719 	for (i = 0; i <= mmu.max_page_level; i++) {
1720 		hw_page_array[i].hp_size = LEVEL_SIZE(i);
1721 		hw_page_array[i].hp_shift = LEVEL_SHIFT(i);
1722 		hw_page_array[i].hp_pgcnt = LEVEL_SIZE(i) >> LEVEL_SHIFT(0);
1723 		hw_page_array[i].hp_colors = (page_colors_mask >>
1724 		    (hw_page_array[i].hp_shift - hw_page_array[0].hp_shift))
1725 		    + 1;
1726 		colorequivszc[i] = 0;
1727 	}
1728 
1729 	/*
1730 	 * The value of cpu_page_colors determines if additional color bins
1731 	 * need to be checked for a particular color in the page_get routines.
1732 	 */
1733 	if (cpu_page_colors != 0) {
1734 
1735 		int a = lowbit(page_colors) - lowbit(cpu_page_colors);
1736 		ASSERT(a > 0);
1737 		ASSERT(a < 16);
1738 
1739 		for (i = 0; i <= mmu.max_page_level; i++) {
1740 			if ((colors = hw_page_array[i].hp_colors) <= 1) {
1741 				colorequivszc[i] = 0;
1742 				continue;
1743 			}
1744 			while ((colors >> a) == 0)
1745 				a--;
1746 			ASSERT(a >= 0);
1747 
1748 			/* higher 4 bits encodes color equiv mask */
1749 			colorequivszc[i] = (a << 4);
1750 		}
1751 	}
1752 
1753 	/* factor in colorequiv to check additional 'equivalent' bins. */
1754 	if (colorequiv > 1) {
1755 
1756 		int a = lowbit(colorequiv) - 1;
1757 		if (a > 15)
1758 			a = 15;
1759 
1760 		for (i = 0; i <= mmu.max_page_level; i++) {
1761 			if ((colors = hw_page_array[i].hp_colors) <= 1) {
1762 				continue;
1763 			}
1764 			while ((colors >> a) == 0)
1765 				a--;
1766 			if ((a << 4) > colorequivszc[i]) {
1767 				colorequivszc[i] = (a << 4);
1768 			}
1769 		}
1770 	}
1771 
1772 	/* size for mnoderanges */
1773 	for (mnoderangecnt = 0, i = 0; i < max_mem_nodes; i++)
1774 		mnoderangecnt += mnode_range_cnt(i);
1775 	if (plat_dr_support_memory()) {
1776 		/*
1777 		 * Reserve enough space for memory DR operations.
1778 		 * Two extra mnoderanges for possbile fragmentations,
1779 		 * one for the 2G boundary and the other for the 4G boundary.
1780 		 * We don't expect a memory board crossing the 16M boundary
1781 		 * for memory hot-add operations on x86 platforms.
1782 		 */
1783 		mnoderangecnt += 2 + max_mem_nodes - lgrp_plat_node_cnt;
1784 	}
1785 	colorsz = mnoderangecnt * sizeof (mnoderange_t);
1786 
1787 	if (!kflt_disable) {
1788 		/* size for kernel page freelists */
1789 		colorsz += mnoderangecnt * sizeof (page_t ***);
1790 		colorsz += (mnoderangecnt * KFLT_PAGE_COLORS *
1791 		    sizeof (page_t *));
1792 
1793 		/* size for kfpc_mutex */
1794 		colorsz += (max_mem_nodes * sizeof (kmutex_t) * NPC_MUTEX);
1795 	}
1796 	/* size for fpc_mutex and cpc_mutex */
1797 	colorsz += (2 * max_mem_nodes * sizeof (kmutex_t) * NPC_MUTEX);
1798 
1799 	/* size of page_freelists */
1800 	colorsz += mnoderangecnt * sizeof (page_t ***);
1801 	colorsz += mnoderangecnt * mmu_page_sizes * sizeof (page_t **);
1802 
1803 	for (i = 0; i < mmu_page_sizes; i++) {
1804 		colors = page_get_pagecolors(i);
1805 		colorsz += mnoderangecnt * colors * sizeof (page_t *);
1806 	}
1807 
1808 	/* size of page_cachelists */
1809 	colorsz += mnoderangecnt * sizeof (page_t **);
1810 	colorsz += mnoderangecnt * page_colors * sizeof (page_t *);
1811 
1812 	return (colorsz);
1813 }
1814 
1815 /*
1816  * Called once at startup to configure page_coloring data structures and
1817  * does the 1st page_free()/page_freelist_add().
1818  */
1819 void
1820 page_coloring_setup(caddr_t pcmemaddr)
1821 {
1822 	int	i;
1823 	int	j;
1824 	int	k;
1825 	caddr_t	addr;
1826 	int	colors;
1827 
1828 	/*
1829 	 * do page coloring setup
1830 	 */
1831 	addr = pcmemaddr;
1832 
1833 	mnoderanges = (mnoderange_t *)addr;
1834 	addr += (mnoderangecnt * sizeof (mnoderange_t));
1835 
1836 	mnode_range_setup(mnoderanges);
1837 
1838 	if (physmax4g)
1839 		mtype4g = pfn_2_mtype(0xfffff);
1840 
1841 	for (k = 0; k < NPC_MUTEX; k++) {
1842 		fpc_mutex[k] = (kmutex_t *)addr;
1843 		addr += (max_mem_nodes * sizeof (kmutex_t));
1844 	}
1845 	if (!kflt_disable) {
1846 		for (k = 0; k < NPC_MUTEX; k++) {
1847 			kfpc_mutex[k] = (kmutex_t *)addr;
1848 			addr += (max_mem_nodes * sizeof (kmutex_t));
1849 		}
1850 	}
1851 	for (k = 0; k < NPC_MUTEX; k++) {
1852 		cpc_mutex[k] = (kmutex_t *)addr;
1853 		addr += (max_mem_nodes * sizeof (kmutex_t));
1854 	}
1855 	ufltp->pflt_freelists = (page_t ****)addr;
1856 	addr += (mnoderangecnt * sizeof (page_t ***));
1857 
1858 	page_cachelists = (page_t ***)addr;
1859 	addr += (mnoderangecnt * sizeof (page_t **));
1860 
1861 	for (i = 0; i < mnoderangecnt; i++) {
1862 		ufltp->pflt_freelists[i] = (page_t ***)addr;
1863 		addr += (mmu_page_sizes * sizeof (page_t **));
1864 
1865 		for (j = 0; j < mmu_page_sizes; j++) {
1866 			colors = page_get_pagecolors(j);
1867 			ufltp->pflt_freelists[i][j] = (page_t **)addr;
1868 			addr += (colors * sizeof (page_t *));
1869 		}
1870 		page_cachelists[i] = (page_t **)addr;
1871 		addr += (page_colors * sizeof (page_t *));
1872 	}
1873 
1874 	if (!kflt_disable) {
1875 		kfltp->pflt_freelists = (page_t ****)addr;
1876 		addr += (mnoderangecnt * sizeof (page_t ***));
1877 		for (i = 0; i < mnoderangecnt; i++) {
1878 			kfltp->pflt_freelists[i] = (page_t ***)addr;
1879 			addr += (KFLT_PAGE_COLORS * sizeof (page_t *));
1880 		}
1881 	}
1882 	page_flt_init(ufltp, kfltp);
1883 }
1884 
1885 #if defined(__xpv)
1886 /*
1887  * Give back 10% of the io_pool pages to the free list.
1888  * Don't shrink the pool below some absolute minimum.
1889  */
1890 static void
1891 page_io_pool_shrink()
1892 {
1893 	int retcnt;
1894 	page_t *pp, *pp_first, *pp_last, **curpool;
1895 	mfn_t mfn;
1896 	int bothpools = 0;
1897 
1898 	mutex_enter(&io_pool_lock);
1899 	io_pool_shrink_attempts++;	/* should be a kstat? */
1900 	retcnt = io_pool_cnt / 10;
1901 	if (io_pool_cnt - retcnt < io_pool_cnt_min)
1902 		retcnt = io_pool_cnt - io_pool_cnt_min;
1903 	if (retcnt <= 0)
1904 		goto done;
1905 	io_pool_shrinks++;	/* should be a kstat? */
1906 	curpool = &io_pool_4g;
1907 domore:
1908 	/*
1909 	 * Loop through taking pages from the end of the list
1910 	 * (highest mfns) till amount to return reached.
1911 	 */
1912 	for (pp = *curpool; pp && retcnt > 0; ) {
1913 		pp_first = pp_last = pp->p_prev;
1914 		if (pp_first == *curpool)
1915 			break;
1916 		retcnt--;
1917 		io_pool_cnt--;
1918 		page_io_pool_sub(curpool, pp_first, pp_last);
1919 		if ((mfn = pfn_to_mfn(pp->p_pagenum)) < start_mfn)
1920 			start_mfn = mfn;
1921 		page_free(pp_first, 1);
1922 		pp = *curpool;
1923 	}
1924 	if (retcnt != 0 && !bothpools) {
1925 		/*
1926 		 * If not enough found in less constrained pool try the
1927 		 * more constrained one.
1928 		 */
1929 		curpool = &io_pool_16m;
1930 		bothpools = 1;
1931 		goto domore;
1932 	}
1933 done:
1934 	mutex_exit(&io_pool_lock);
1935 }
1936 
1937 #endif	/* __xpv */
1938 
1939 uint_t
1940 page_create_update_flags_x86(uint_t flags)
1941 {
1942 #if defined(__xpv)
1943 	/*
1944 	 * Check this is an urgent allocation and free pages are depleted.
1945 	 */
1946 	if (!(flags & PG_WAIT) && freemem < desfree)
1947 		page_io_pool_shrink();
1948 #else /* !__xpv */
1949 	/*
1950 	 * page_create_get_something may call this because 4g memory may be
1951 	 * depleted. Set flags to allow for relocation of base page below
1952 	 * 4g if necessary.
1953 	 */
1954 	if (physmax4g)
1955 		flags |= (PGI_PGCPSZC0 | PGI_PGCPHIPRI);
1956 #endif /* __xpv */
1957 	return (flags);
1958 }
1959 
1960 int
1961 kernel_page_update_flags_x86(uint_t *flags)
1962 {
1963 	/*
1964 	 * page_get_kflt() calls this after walking the kernel pagelists and
1965 	 * not finding a free page to allocate. If the PGI_MT_RANGE4G flag is
1966 	 * set then we only walk mnodes in the greater than 4g range, so if we
1967 	 * didn't find a page there must be free kernel memory below this range.
1968 	 *
1969 	 * kflt_expand() calls this before trying to allocate large pages for
1970 	 * kernel memory.
1971 	 */
1972 	if (physmax4g) {
1973 		if (*flags & PGI_MT_RANGE4G) {
1974 			*flags &= ~PGI_MT_RANGE4G;
1975 			*flags |= PGI_MT_RANGE0;
1976 			return (1);
1977 		} else {
1978 			return (0);
1979 		}
1980 	}
1981 	return (0);
1982 }
1983 
1984 /*ARGSUSED*/
1985 int
1986 bp_color(struct buf *bp)
1987 {
1988 	return (0);
1989 }
1990 
1991 #if defined(__xpv)
1992 
1993 /*
1994  * Take pages out of an io_pool
1995  */
1996 static void
1997 page_io_pool_sub(page_t **poolp, page_t *pp_first, page_t *pp_last)
1998 {
1999 	if (*poolp == pp_first) {
2000 		*poolp = pp_last->p_next;
2001 		if (*poolp == pp_first)
2002 			*poolp = NULL;
2003 	}
2004 	pp_first->p_prev->p_next = pp_last->p_next;
2005 	pp_last->p_next->p_prev = pp_first->p_prev;
2006 	pp_first->p_prev = pp_last;
2007 	pp_last->p_next = pp_first;
2008 }
2009 
2010 /*
2011  * Put a page on the io_pool list. The list is ordered by increasing MFN.
2012  */
2013 static void
2014 page_io_pool_add(page_t **poolp, page_t *pp)
2015 {
2016 	page_t	*look;
2017 	mfn_t	mfn = mfn_list[pp->p_pagenum];
2018 
2019 	if (*poolp == NULL) {
2020 		*poolp = pp;
2021 		pp->p_next = pp;
2022 		pp->p_prev = pp;
2023 		return;
2024 	}
2025 
2026 	/*
2027 	 * Since we try to take pages from the high end of the pool
2028 	 * chances are good that the pages to be put on the list will
2029 	 * go at or near the end of the list. so start at the end and
2030 	 * work backwards.
2031 	 */
2032 	look = (*poolp)->p_prev;
2033 	while (mfn < mfn_list[look->p_pagenum]) {
2034 		look = look->p_prev;
2035 		if (look == (*poolp)->p_prev)
2036 			break; /* backed all the way to front of list */
2037 	}
2038 
2039 	/* insert after look */
2040 	pp->p_prev = look;
2041 	pp->p_next = look->p_next;
2042 	pp->p_next->p_prev = pp;
2043 	look->p_next = pp;
2044 	if (mfn < mfn_list[(*poolp)->p_pagenum]) {
2045 		/*
2046 		 * we inserted a new first list element
2047 		 * adjust pool pointer to newly inserted element
2048 		 */
2049 		*poolp = pp;
2050 	}
2051 }
2052 
2053 /*
2054  * Add a page to the io_pool.  Setting the force flag will force the page
2055  * into the io_pool no matter what.
2056  */
2057 static void
2058 add_page_to_pool(page_t *pp, int force)
2059 {
2060 	page_t *highest;
2061 	page_t *freep = NULL;
2062 
2063 	mutex_enter(&io_pool_lock);
2064 	/*
2065 	 * Always keep the scarce low memory pages
2066 	 */
2067 	if (mfn_list[pp->p_pagenum] < PFN_16MEG) {
2068 		++io_pool_cnt;
2069 		page_io_pool_add(&io_pool_16m, pp);
2070 		goto done;
2071 	}
2072 	if (io_pool_cnt < io_pool_cnt_max || force || io_pool_4g == NULL) {
2073 		++io_pool_cnt;
2074 		page_io_pool_add(&io_pool_4g, pp);
2075 	} else {
2076 		highest = io_pool_4g->p_prev;
2077 		if (mfn_list[pp->p_pagenum] < mfn_list[highest->p_pagenum]) {
2078 			page_io_pool_sub(&io_pool_4g, highest, highest);
2079 			page_io_pool_add(&io_pool_4g, pp);
2080 			freep = highest;
2081 		} else {
2082 			freep = pp;
2083 		}
2084 	}
2085 done:
2086 	mutex_exit(&io_pool_lock);
2087 	if (freep)
2088 		page_free(freep, 1);
2089 }
2090 
2091 
2092 int contig_pfn_cnt;	/* no of pfns in the contig pfn list */
2093 int contig_pfn_max;	/* capacity of the contig pfn list */
2094 int next_alloc_pfn;	/* next position in list to start a contig search */
2095 int contig_pfnlist_updates;	/* pfn list update count */
2096 int contig_pfnlist_builds;	/* how many times have we (re)built list */
2097 int contig_pfnlist_buildfailed;	/* how many times has list build failed */
2098 int create_contig_pending;	/* nonzero means taskq creating contig list */
2099 pfn_t *contig_pfn_list = NULL;	/* list of contig pfns in ascending mfn order */
2100 
2101 /*
2102  * Function to use in sorting a list of pfns by their underlying mfns.
2103  */
2104 static int
2105 mfn_compare(const void *pfnp1, const void *pfnp2)
2106 {
2107 	mfn_t mfn1 = mfn_list[*(pfn_t *)pfnp1];
2108 	mfn_t mfn2 = mfn_list[*(pfn_t *)pfnp2];
2109 
2110 	if (mfn1 > mfn2)
2111 		return (1);
2112 	if (mfn1 < mfn2)
2113 		return (-1);
2114 	return (0);
2115 }
2116 
2117 /*
2118  * Compact the contig_pfn_list by tossing all the non-contiguous
2119  * elements from the list.
2120  */
2121 static void
2122 compact_contig_pfn_list(void)
2123 {
2124 	pfn_t pfn, lapfn, prev_lapfn;
2125 	mfn_t mfn;
2126 	int i, newcnt = 0;
2127 
2128 	prev_lapfn = 0;
2129 	for (i = 0; i < contig_pfn_cnt - 1; i++) {
2130 		pfn = contig_pfn_list[i];
2131 		lapfn = contig_pfn_list[i + 1];
2132 		mfn = mfn_list[pfn];
2133 		/*
2134 		 * See if next pfn is for a contig mfn
2135 		 */
2136 		if (mfn_list[lapfn] != mfn + 1)
2137 			continue;
2138 		/*
2139 		 * pfn and lookahead are both put in list
2140 		 * unless pfn is the previous lookahead.
2141 		 */
2142 		if (pfn != prev_lapfn)
2143 			contig_pfn_list[newcnt++] = pfn;
2144 		contig_pfn_list[newcnt++] = lapfn;
2145 		prev_lapfn = lapfn;
2146 	}
2147 	for (i = newcnt; i < contig_pfn_cnt; i++)
2148 		contig_pfn_list[i] = 0;
2149 	contig_pfn_cnt = newcnt;
2150 }
2151 
2152 /*ARGSUSED*/
2153 static void
2154 call_create_contiglist(void *arg)
2155 {
2156 	(void) create_contig_pfnlist(PG_WAIT);
2157 }
2158 
2159 /*
2160  * Create list of freelist pfns that have underlying
2161  * contiguous mfns.  The list is kept in ascending mfn order.
2162  * returns 1 if list created else 0.
2163  */
2164 static int
2165 create_contig_pfnlist(uint_t flags)
2166 {
2167 	pfn_t pfn;
2168 	page_t *pp;
2169 	int ret = 1;
2170 
2171 	mutex_enter(&contig_list_lock);
2172 	if (contig_pfn_list != NULL)
2173 		goto out;
2174 	contig_pfn_max = freemem + (freemem / 10);
2175 	contig_pfn_list = kmem_zalloc(contig_pfn_max * sizeof (pfn_t),
2176 	    (flags & PG_WAIT) ? KM_SLEEP : KM_NOSLEEP);
2177 	if (contig_pfn_list == NULL) {
2178 		/*
2179 		 * If we could not create the contig list (because
2180 		 * we could not sleep for memory).  Dispatch a taskq that can
2181 		 * sleep to get the memory.
2182 		 */
2183 		if (!create_contig_pending) {
2184 			if (taskq_dispatch(system_taskq, call_create_contiglist,
2185 			    NULL, TQ_NOSLEEP) != NULL)
2186 				create_contig_pending = 1;
2187 		}
2188 		contig_pfnlist_buildfailed++;	/* count list build failures */
2189 		ret = 0;
2190 		goto out;
2191 	}
2192 	create_contig_pending = 0;
2193 	ASSERT(contig_pfn_cnt == 0);
2194 	for (pfn = 0; pfn < mfn_count; pfn++) {
2195 		pp = page_numtopp_nolock(pfn);
2196 		if (pp == NULL || !PP_ISFREE(pp))
2197 			continue;
2198 		contig_pfn_list[contig_pfn_cnt] = pfn;
2199 		if (++contig_pfn_cnt == contig_pfn_max)
2200 			break;
2201 	}
2202 	/*
2203 	 * Sanity check the new list.
2204 	 */
2205 	if (contig_pfn_cnt < 2) { /* no contig pfns */
2206 		contig_pfn_cnt = 0;
2207 		contig_pfnlist_buildfailed++;
2208 		kmem_free(contig_pfn_list, contig_pfn_max * sizeof (pfn_t));
2209 		contig_pfn_list = NULL;
2210 		contig_pfn_max = 0;
2211 		ret = 0;
2212 		goto out;
2213 	}
2214 	qsort(contig_pfn_list, contig_pfn_cnt, sizeof (pfn_t), mfn_compare);
2215 	compact_contig_pfn_list();
2216 	/*
2217 	 * Make sure next search of the newly created contiguous pfn
2218 	 * list starts at the beginning of the list.
2219 	 */
2220 	next_alloc_pfn = 0;
2221 	contig_pfnlist_builds++;	/* count list builds */
2222 out:
2223 	mutex_exit(&contig_list_lock);
2224 	return (ret);
2225 }
2226 
2227 
2228 /*
2229  * Toss the current contig pfnlist.  Someone is about to do a massive
2230  * update to pfn<->mfn mappings.  So we have them destroy the list and lock
2231  * it till they are done with their update.
2232  */
2233 void
2234 clear_and_lock_contig_pfnlist()
2235 {
2236 	pfn_t *listp = NULL;
2237 	size_t listsize;
2238 
2239 	mutex_enter(&contig_list_lock);
2240 	if (contig_pfn_list != NULL) {
2241 		listp = contig_pfn_list;
2242 		listsize = contig_pfn_max * sizeof (pfn_t);
2243 		contig_pfn_list = NULL;
2244 		contig_pfn_max = contig_pfn_cnt = 0;
2245 	}
2246 	if (listp != NULL)
2247 		kmem_free(listp, listsize);
2248 }
2249 
2250 /*
2251  * Unlock the contig_pfn_list.  The next attempted use of it will cause
2252  * it to be re-created.
2253  */
2254 void
2255 unlock_contig_pfnlist()
2256 {
2257 	mutex_exit(&contig_list_lock);
2258 }
2259 
2260 /*
2261  * Update the contiguous pfn list in response to a pfn <-> mfn reassignment
2262  */
2263 void
2264 update_contig_pfnlist(pfn_t pfn, mfn_t oldmfn, mfn_t newmfn)
2265 {
2266 	int probe_hi, probe_lo, probe_pos, insert_after, insert_point;
2267 	pfn_t probe_pfn;
2268 	mfn_t probe_mfn;
2269 	int drop_lock = 0;
2270 
2271 	if (mutex_owner(&contig_list_lock) != curthread) {
2272 		drop_lock = 1;
2273 		mutex_enter(&contig_list_lock);
2274 	}
2275 	if (contig_pfn_list == NULL)
2276 		goto done;
2277 	contig_pfnlist_updates++;
2278 	/*
2279 	 * Find the pfn in the current list.  Use a binary chop to locate it.
2280 	 */
2281 	probe_hi = contig_pfn_cnt - 1;
2282 	probe_lo = 0;
2283 	probe_pos = (probe_hi + probe_lo) / 2;
2284 	while ((probe_pfn = contig_pfn_list[probe_pos]) != pfn) {
2285 		if (probe_pos == probe_lo) { /* pfn not in list */
2286 			probe_pos = -1;
2287 			break;
2288 		}
2289 		if (pfn_to_mfn(probe_pfn) <= oldmfn)
2290 			probe_lo = probe_pos;
2291 		else
2292 			probe_hi = probe_pos;
2293 		probe_pos = (probe_hi + probe_lo) / 2;
2294 	}
2295 	if (probe_pos >= 0) {
2296 		/*
2297 		 * Remove pfn from list and ensure next alloc
2298 		 * position stays in bounds.
2299 		 */
2300 		if (--contig_pfn_cnt <= next_alloc_pfn)
2301 			next_alloc_pfn = 0;
2302 		if (contig_pfn_cnt < 2) { /* no contig pfns */
2303 			contig_pfn_cnt = 0;
2304 			kmem_free(contig_pfn_list,
2305 			    contig_pfn_max * sizeof (pfn_t));
2306 			contig_pfn_list = NULL;
2307 			contig_pfn_max = 0;
2308 			goto done;
2309 		}
2310 		ovbcopy(&contig_pfn_list[probe_pos + 1],
2311 		    &contig_pfn_list[probe_pos],
2312 		    (contig_pfn_cnt - probe_pos) * sizeof (pfn_t));
2313 	}
2314 	if (newmfn == MFN_INVALID)
2315 		goto done;
2316 	/*
2317 	 * Check if new mfn has adjacent mfns in the list
2318 	 */
2319 	probe_hi = contig_pfn_cnt - 1;
2320 	probe_lo = 0;
2321 	insert_after = -2;
2322 	do {
2323 		probe_pos = (probe_hi + probe_lo) / 2;
2324 		probe_mfn = pfn_to_mfn(contig_pfn_list[probe_pos]);
2325 		if (newmfn == probe_mfn + 1)
2326 			insert_after = probe_pos;
2327 		else if (newmfn == probe_mfn - 1)
2328 			insert_after = probe_pos - 1;
2329 		if (probe_pos == probe_lo)
2330 			break;
2331 		if (probe_mfn <= newmfn)
2332 			probe_lo = probe_pos;
2333 		else
2334 			probe_hi = probe_pos;
2335 	} while (insert_after == -2);
2336 	/*
2337 	 * If there is space in the list and there are adjacent mfns
2338 	 * insert the pfn in to its proper place in the list.
2339 	 */
2340 	if (insert_after != -2 && contig_pfn_cnt + 1 <= contig_pfn_max) {
2341 		insert_point = insert_after + 1;
2342 		ovbcopy(&contig_pfn_list[insert_point],
2343 		    &contig_pfn_list[insert_point + 1],
2344 		    (contig_pfn_cnt - insert_point) * sizeof (pfn_t));
2345 		contig_pfn_list[insert_point] = pfn;
2346 		contig_pfn_cnt++;
2347 	}
2348 done:
2349 	if (drop_lock)
2350 		mutex_exit(&contig_list_lock);
2351 }
2352 
2353 /*
2354  * Called to (re-)populate the io_pool from the free page lists.
2355  */
2356 long
2357 populate_io_pool(void)
2358 {
2359 	pfn_t pfn;
2360 	mfn_t mfn, max_mfn;
2361 	page_t *pp;
2362 
2363 	/*
2364 	 * Figure out the bounds of the pool on first invocation.
2365 	 * We use a percentage of memory for the io pool size.
2366 	 * we allow that to shrink, but not to less than a fixed minimum
2367 	 */
2368 	if (io_pool_cnt_max == 0) {
2369 		io_pool_cnt_max = physmem / (100 / io_pool_physmem_pct);
2370 		io_pool_cnt_lowater = io_pool_cnt_max;
2371 		/*
2372 		 * This is the first time in populate_io_pool, grab a va to use
2373 		 * when we need to allocate pages.
2374 		 */
2375 		io_pool_kva = vmem_alloc(heap_arena, PAGESIZE, VM_SLEEP);
2376 	}
2377 	/*
2378 	 * If we are out of pages in the pool, then grow the size of the pool
2379 	 */
2380 	if (io_pool_cnt == 0) {
2381 		/*
2382 		 * Grow the max size of the io pool by 5%, but never more than
2383 		 * 25% of physical memory.
2384 		 */
2385 		if (io_pool_cnt_max < physmem / 4)
2386 			io_pool_cnt_max += io_pool_cnt_max / 20;
2387 	}
2388 	io_pool_grows++;	/* should be a kstat? */
2389 
2390 	/*
2391 	 * Get highest mfn on this platform, but limit to the 32 bit DMA max.
2392 	 */
2393 	(void) mfn_to_pfn(start_mfn);
2394 	max_mfn = MIN(cached_max_mfn, PFN_4GIG);
2395 	for (mfn = start_mfn; mfn < max_mfn; start_mfn = ++mfn) {
2396 		pfn = mfn_to_pfn(mfn);
2397 		if (pfn & PFN_IS_FOREIGN_MFN)
2398 			continue;
2399 		/*
2400 		 * try to allocate it from free pages
2401 		 */
2402 		pp = page_numtopp_alloc(pfn);
2403 		if (pp == NULL)
2404 			continue;
2405 		PP_CLRFREE(pp);
2406 		add_page_to_pool(pp, 1);
2407 		if (io_pool_cnt >= io_pool_cnt_max)
2408 			break;
2409 	}
2410 
2411 	return (io_pool_cnt);
2412 }
2413 
2414 /*
2415  * Destroy a page that was being used for DMA I/O. It may or
2416  * may not actually go back to the io_pool.
2417  */
2418 void
2419 page_destroy_io(page_t *pp)
2420 {
2421 	mfn_t mfn = mfn_list[pp->p_pagenum];
2422 
2423 	/*
2424 	 * When the page was alloc'd a reservation was made, release it now
2425 	 */
2426 	page_unresv(1);
2427 	/*
2428 	 * Unload translations, if any, then hash out the
2429 	 * page to erase its identity.
2430 	 */
2431 	(void) hat_pageunload(pp, HAT_FORCE_PGUNLOAD);
2432 	page_hashout(pp, NULL);
2433 
2434 	/*
2435 	 * If the page came from the free lists, just put it back to them.
2436 	 * DomU pages always go on the free lists as well.
2437 	 */
2438 	if (!DOMAIN_IS_INITDOMAIN(xen_info) || mfn >= PFN_4GIG) {
2439 		page_free(pp, 1);
2440 		return;
2441 	}
2442 
2443 	add_page_to_pool(pp, 0);
2444 }
2445 
2446 
2447 long contig_searches;		/* count of times contig pages requested */
2448 long contig_search_restarts;	/* count of contig ranges tried */
2449 long contig_search_failed;	/* count of contig alloc failures */
2450 
2451 /*
2452  * Free partial page list
2453  */
2454 static void
2455 free_partial_list(page_t **pplist)
2456 {
2457 	page_t *pp;
2458 
2459 	while (*pplist != NULL) {
2460 		pp = *pplist;
2461 		page_io_pool_sub(pplist, pp, pp);
2462 		page_free(pp, 1);
2463 	}
2464 }
2465 
2466 /*
2467  * Look thru the contiguous pfns that are not part of the io_pool for
2468  * contiguous free pages.  Return a list of the found pages or NULL.
2469  */
2470 page_t *
2471 find_contig_free(uint_t npages, uint_t flags, uint64_t pfnseg,
2472     pgcnt_t pfnalign)
2473 {
2474 	page_t *pp, *plist = NULL;
2475 	mfn_t mfn, prev_mfn, start_mfn;
2476 	pfn_t pfn;
2477 	int pages_needed, pages_requested;
2478 	int search_start;
2479 
2480 	/*
2481 	 * create the contig pfn list if not already done
2482 	 */
2483 retry:
2484 	mutex_enter(&contig_list_lock);
2485 	if (contig_pfn_list == NULL) {
2486 		mutex_exit(&contig_list_lock);
2487 		if (!create_contig_pfnlist(flags)) {
2488 			return (NULL);
2489 		}
2490 		goto retry;
2491 	}
2492 	contig_searches++;
2493 	/*
2494 	 * Search contiguous pfn list for physically contiguous pages not in
2495 	 * the io_pool.  Start the search where the last search left off.
2496 	 */
2497 	pages_requested = pages_needed = npages;
2498 	search_start = next_alloc_pfn;
2499 	start_mfn = prev_mfn = 0;
2500 	while (pages_needed) {
2501 		pfn = contig_pfn_list[next_alloc_pfn];
2502 		mfn = pfn_to_mfn(pfn);
2503 		/*
2504 		 * Check if mfn is first one or contig to previous one and
2505 		 * if page corresponding to mfn is free and that mfn
2506 		 * range is not crossing a segment boundary.
2507 		 */
2508 		if ((prev_mfn == 0 || mfn == prev_mfn + 1) &&
2509 		    (pp = page_numtopp_alloc(pfn)) != NULL &&
2510 		    !((mfn & pfnseg) < (start_mfn & pfnseg))) {
2511 			PP_CLRFREE(pp);
2512 			page_io_pool_add(&plist, pp);
2513 			pages_needed--;
2514 			if (prev_mfn == 0) {
2515 				if (pfnalign &&
2516 				    mfn != P2ROUNDUP(mfn, pfnalign)) {
2517 					/*
2518 					 * not properly aligned
2519 					 */
2520 					contig_search_restarts++;
2521 					free_partial_list(&plist);
2522 					pages_needed = pages_requested;
2523 					start_mfn = prev_mfn = 0;
2524 					goto skip;
2525 				}
2526 				start_mfn = mfn;
2527 			}
2528 			prev_mfn = mfn;
2529 		} else {
2530 			contig_search_restarts++;
2531 			free_partial_list(&plist);
2532 			pages_needed = pages_requested;
2533 			start_mfn = prev_mfn = 0;
2534 		}
2535 skip:
2536 		if (++next_alloc_pfn == contig_pfn_cnt)
2537 			next_alloc_pfn = 0;
2538 		if (next_alloc_pfn == search_start)
2539 			break; /* all pfns searched */
2540 	}
2541 	mutex_exit(&contig_list_lock);
2542 	if (pages_needed) {
2543 		contig_search_failed++;
2544 		/*
2545 		 * Failed to find enough contig pages.
2546 		 * free partial page list
2547 		 */
2548 		free_partial_list(&plist);
2549 	}
2550 	return (plist);
2551 }
2552 
2553 /*
2554  * Search the reserved io pool pages for a page range with the
2555  * desired characteristics.
2556  */
2557 page_t *
2558 page_io_pool_alloc(ddi_dma_attr_t *mattr, int contig, pgcnt_t minctg)
2559 {
2560 	page_t *pp_first, *pp_last;
2561 	page_t *pp, **poolp;
2562 	pgcnt_t nwanted, pfnalign;
2563 	uint64_t pfnseg;
2564 	mfn_t mfn, tmfn, hi_mfn, lo_mfn;
2565 	int align, attempt = 0;
2566 
2567 	if (minctg == 1)
2568 		contig = 0;
2569 	lo_mfn = mmu_btop(mattr->dma_attr_addr_lo);
2570 	hi_mfn = mmu_btop(mattr->dma_attr_addr_hi);
2571 	pfnseg = mmu_btop(mattr->dma_attr_seg);
2572 	align = maxbit(mattr->dma_attr_align, mattr->dma_attr_minxfer);
2573 	if (align > MMU_PAGESIZE)
2574 		pfnalign = mmu_btop(align);
2575 	else
2576 		pfnalign = 0;
2577 
2578 try_again:
2579 	/*
2580 	 * See if we want pages for a legacy device
2581 	 */
2582 	if (hi_mfn < PFN_16MEG)
2583 		poolp = &io_pool_16m;
2584 	else
2585 		poolp = &io_pool_4g;
2586 try_smaller:
2587 	/*
2588 	 * Take pages from I/O pool. We'll use pages from the highest
2589 	 * MFN range possible.
2590 	 */
2591 	pp_first = pp_last = NULL;
2592 	mutex_enter(&io_pool_lock);
2593 	nwanted = minctg;
2594 	for (pp = *poolp; pp && nwanted > 0; ) {
2595 		pp = pp->p_prev;
2596 
2597 		/*
2598 		 * skip pages above allowable range
2599 		 */
2600 		mfn = mfn_list[pp->p_pagenum];
2601 		if (hi_mfn < mfn)
2602 			goto skip;
2603 
2604 		/*
2605 		 * stop at pages below allowable range
2606 		 */
2607 		if (lo_mfn > mfn)
2608 			break;
2609 restart:
2610 		if (pp_last == NULL) {
2611 			/*
2612 			 * Check alignment
2613 			 */
2614 			tmfn = mfn - (minctg - 1);
2615 			if (pfnalign && tmfn != P2ROUNDUP(tmfn, pfnalign))
2616 				goto skip; /* not properly aligned */
2617 			/*
2618 			 * Check segment
2619 			 */
2620 			if ((mfn & pfnseg) < (tmfn & pfnseg))
2621 				goto skip; /* crosses seg boundary */
2622 			/*
2623 			 * Start building page list
2624 			 */
2625 			pp_first = pp_last = pp;
2626 			nwanted--;
2627 		} else {
2628 			/*
2629 			 * check physical contiguity if required
2630 			 */
2631 			if (contig &&
2632 			    mfn_list[pp_first->p_pagenum] != mfn + 1) {
2633 				/*
2634 				 * not a contiguous page, restart list.
2635 				 */
2636 				pp_last = NULL;
2637 				nwanted = minctg;
2638 				goto restart;
2639 			} else { /* add page to list */
2640 				pp_first = pp;
2641 				nwanted--;
2642 			}
2643 		}
2644 skip:
2645 		if (pp == *poolp)
2646 			break;
2647 	}
2648 
2649 	/*
2650 	 * If we didn't find memory. Try the more constrained pool, then
2651 	 * sweep free pages into the DMA pool and try again.
2652 	 */
2653 	if (nwanted != 0) {
2654 		mutex_exit(&io_pool_lock);
2655 		/*
2656 		 * If we were looking in the less constrained pool and
2657 		 * didn't find pages, try the more constrained pool.
2658 		 */
2659 		if (poolp == &io_pool_4g) {
2660 			poolp = &io_pool_16m;
2661 			goto try_smaller;
2662 		}
2663 		kmem_reap();
2664 		if (++attempt < 4) {
2665 			/*
2666 			 * Grab some more io_pool pages
2667 			 */
2668 			(void) populate_io_pool();
2669 			goto try_again; /* go around and retry */
2670 		}
2671 		return (NULL);
2672 	}
2673 	/*
2674 	 * Found the pages, now snip them from the list
2675 	 */
2676 	page_io_pool_sub(poolp, pp_first, pp_last);
2677 	io_pool_cnt -= minctg;
2678 	/*
2679 	 * reset low water mark
2680 	 */
2681 	if (io_pool_cnt < io_pool_cnt_lowater)
2682 		io_pool_cnt_lowater = io_pool_cnt;
2683 	mutex_exit(&io_pool_lock);
2684 	return (pp_first);
2685 }
2686 
2687 page_t *
2688 page_swap_with_hypervisor(struct vnode *vp, u_offset_t off, caddr_t vaddr,
2689     ddi_dma_attr_t *mattr, uint_t flags, pgcnt_t minctg)
2690 {
2691 	uint_t kflags;
2692 	int order, extra, extpages, i, contig, nbits, extents;
2693 	page_t *pp, *expp, *pp_first, **pplist = NULL;
2694 	mfn_t *mfnlist = NULL;
2695 
2696 	contig = flags & PG_PHYSCONTIG;
2697 	if (minctg == 1)
2698 		contig = 0;
2699 	flags &= ~PG_PHYSCONTIG;
2700 	kflags = flags & PG_WAIT ? KM_SLEEP : KM_NOSLEEP;
2701 	/*
2702 	 * Hypervisor will allocate extents, if we want contig
2703 	 * pages extent must be >= minctg
2704 	 */
2705 	if (contig) {
2706 		order = highbit(minctg) - 1;
2707 		if (minctg & ((1 << order) - 1))
2708 			order++;
2709 		extpages = 1 << order;
2710 	} else {
2711 		order = 0;
2712 		extpages = minctg;
2713 	}
2714 	if (extpages > minctg) {
2715 		extra = extpages - minctg;
2716 		if (!page_resv(extra, kflags))
2717 			return (NULL);
2718 	}
2719 	pp_first = NULL;
2720 	pplist = kmem_alloc(extpages * sizeof (page_t *), kflags);
2721 	if (pplist == NULL)
2722 		goto balloon_fail;
2723 	mfnlist = kmem_alloc(extpages * sizeof (mfn_t), kflags);
2724 	if (mfnlist == NULL)
2725 		goto balloon_fail;
2726 	pp = page_create_va(vp, off, minctg * PAGESIZE, flags, &kvseg, vaddr);
2727 	if (pp == NULL)
2728 		goto balloon_fail;
2729 	pp_first = pp;
2730 	if (extpages > minctg) {
2731 		/*
2732 		 * fill out the rest of extent pages to swap
2733 		 * with the hypervisor
2734 		 */
2735 		for (i = 0; i < extra; i++) {
2736 			expp = page_create_va(vp,
2737 			    (u_offset_t)(uintptr_t)io_pool_kva,
2738 			    PAGESIZE, flags, &kvseg, io_pool_kva);
2739 			if (expp == NULL)
2740 				goto balloon_fail;
2741 			(void) hat_pageunload(expp, HAT_FORCE_PGUNLOAD);
2742 			page_io_unlock(expp);
2743 			page_hashout(expp, NULL);
2744 			page_io_lock(expp);
2745 			/*
2746 			 * add page to end of list
2747 			 */
2748 			expp->p_prev = pp_first->p_prev;
2749 			expp->p_next = pp_first;
2750 			expp->p_prev->p_next = expp;
2751 			pp_first->p_prev = expp;
2752 		}
2753 
2754 	}
2755 	for (i = 0; i < extpages; i++) {
2756 		pplist[i] = pp;
2757 		pp = pp->p_next;
2758 	}
2759 	nbits = highbit(mattr->dma_attr_addr_hi);
2760 	extents = contig ? 1 : minctg;
2761 	if (balloon_replace_pages(extents, pplist, nbits, order,
2762 	    mfnlist) != extents) {
2763 		if (ioalloc_dbg)
2764 			cmn_err(CE_NOTE, "request to hypervisor"
2765 			    " for %d pages, maxaddr %" PRIx64 " failed",
2766 			    extpages, mattr->dma_attr_addr_hi);
2767 		goto balloon_fail;
2768 	}
2769 
2770 	kmem_free(pplist, extpages * sizeof (page_t *));
2771 	kmem_free(mfnlist, extpages * sizeof (mfn_t));
2772 	/*
2773 	 * Return any excess pages to free list
2774 	 */
2775 	if (extpages > minctg) {
2776 		for (i = 0; i < extra; i++) {
2777 			pp = pp_first->p_prev;
2778 			page_sub(&pp_first, pp);
2779 			page_io_unlock(pp);
2780 			page_unresv(1);
2781 			page_free(pp, 1);
2782 		}
2783 	}
2784 	return (pp_first);
2785 balloon_fail:
2786 	/*
2787 	 * Return pages to free list and return failure
2788 	 */
2789 	while (pp_first != NULL) {
2790 		pp = pp_first;
2791 		page_sub(&pp_first, pp);
2792 		page_io_unlock(pp);
2793 		if (pp->p_vnode != NULL)
2794 			page_hashout(pp, NULL);
2795 		page_free(pp, 1);
2796 	}
2797 	if (pplist)
2798 		kmem_free(pplist, extpages * sizeof (page_t *));
2799 	if (mfnlist)
2800 		kmem_free(mfnlist, extpages * sizeof (mfn_t));
2801 	page_unresv(extpages - minctg);
2802 	return (NULL);
2803 }
2804 
2805 static void
2806 return_partial_alloc(page_t *plist)
2807 {
2808 	page_t *pp;
2809 
2810 	while (plist != NULL) {
2811 		pp = plist;
2812 		page_sub(&plist, pp);
2813 		page_io_unlock(pp);
2814 		page_destroy_io(pp);
2815 	}
2816 }
2817 
2818 static page_t *
2819 page_get_contigpages(
2820 	struct vnode	*vp,
2821 	u_offset_t	off,
2822 	int		*npagesp,
2823 	uint_t		flags,
2824 	caddr_t		vaddr,
2825 	ddi_dma_attr_t	*mattr)
2826 {
2827 	mfn_t	max_mfn = HYPERVISOR_memory_op(XENMEM_maximum_ram_page, NULL);
2828 	page_t	*plist;	/* list to return */
2829 	page_t	*pp, *mcpl;
2830 	int	contig, anyaddr, npages, getone = 0;
2831 	mfn_t	lo_mfn;
2832 	mfn_t	hi_mfn;
2833 	pgcnt_t	pfnalign = 0;
2834 	int	align, sgllen;
2835 	uint64_t pfnseg;
2836 	pgcnt_t	minctg;
2837 
2838 	npages = *npagesp;
2839 	ASSERT(mattr != NULL);
2840 	lo_mfn = mmu_btop(mattr->dma_attr_addr_lo);
2841 	hi_mfn = mmu_btop(mattr->dma_attr_addr_hi);
2842 	sgllen = mattr->dma_attr_sgllen;
2843 	pfnseg = mmu_btop(mattr->dma_attr_seg);
2844 	align = maxbit(mattr->dma_attr_align, mattr->dma_attr_minxfer);
2845 	if (align > MMU_PAGESIZE)
2846 		pfnalign = mmu_btop(align);
2847 
2848 	contig = flags & PG_PHYSCONTIG;
2849 	if (npages == -1) {
2850 		npages = 1;
2851 		pfnalign = 0;
2852 	}
2853 	/*
2854 	 * Clear the contig flag if only one page is needed.
2855 	 */
2856 	if (npages == 1) {
2857 		getone = 1;
2858 		contig = 0;
2859 	}
2860 
2861 	/*
2862 	 * Check if any page in the system is fine.
2863 	 */
2864 	anyaddr = lo_mfn == 0 && hi_mfn >= max_mfn;
2865 	if (!contig && anyaddr && !pfnalign) {
2866 		flags &= ~PG_PHYSCONTIG;
2867 		plist = page_create_va(vp, off, npages * MMU_PAGESIZE,
2868 		    flags, &kvseg, vaddr);
2869 		if (plist != NULL) {
2870 			*npagesp = 0;
2871 			return (plist);
2872 		}
2873 	}
2874 	plist = NULL;
2875 	minctg = howmany(npages, sgllen);
2876 	while (npages > sgllen || getone) {
2877 		if (minctg > npages)
2878 			minctg = npages;
2879 		mcpl = NULL;
2880 		/*
2881 		 * We could want contig pages with no address range limits.
2882 		 */
2883 		if (anyaddr && contig) {
2884 			/*
2885 			 * Look for free contig pages to satisfy the request.
2886 			 */
2887 			mcpl = find_contig_free(minctg, flags, pfnseg,
2888 			    pfnalign);
2889 		}
2890 		/*
2891 		 * Try the reserved io pools next
2892 		 */
2893 		if (mcpl == NULL)
2894 			mcpl = page_io_pool_alloc(mattr, contig, minctg);
2895 		if (mcpl != NULL) {
2896 			pp = mcpl;
2897 			do {
2898 				if (!page_hashin(pp, vp, off, NULL)) {
2899 					panic("page_get_contigpages:"
2900 					    " hashin failed"
2901 					    " pp %p, vp %p, off %llx",
2902 					    (void *)pp, (void *)vp, off);
2903 				}
2904 				off += MMU_PAGESIZE;
2905 				PP_CLRFREE(pp);
2906 				PP_CLRAGED(pp);
2907 				page_set_props(pp, P_REF);
2908 				page_io_lock(pp);
2909 				pp = pp->p_next;
2910 			} while (pp != mcpl);
2911 		} else {
2912 			/*
2913 			 * Hypervisor exchange doesn't handle segment or
2914 			 * alignment constraints
2915 			 */
2916 			if (mattr->dma_attr_seg < mattr->dma_attr_addr_hi ||
2917 			    pfnalign)
2918 				goto fail;
2919 			/*
2920 			 * Try exchanging pages with the hypervisor
2921 			 */
2922 			mcpl = page_swap_with_hypervisor(vp, off, vaddr, mattr,
2923 			    flags, minctg);
2924 			if (mcpl == NULL)
2925 				goto fail;
2926 			off += minctg * MMU_PAGESIZE;
2927 		}
2928 #ifdef DEBUG
2929 		check_dma(mattr, mcpl, minctg);
2930 #endif
2931 		/*
2932 		 * Here with a minctg run of contiguous pages, add them to the
2933 		 * list we will return for this request.
2934 		 */
2935 		page_list_concat(&plist, &mcpl);
2936 		npages -= minctg;
2937 		*npagesp = npages;
2938 		sgllen--;
2939 		if (getone)
2940 			break;
2941 	}
2942 	return (plist);
2943 fail:
2944 	return_partial_alloc(plist);
2945 	return (NULL);
2946 }
2947 
2948 /*
2949  * Allocator for domain 0 I/O pages. We match the required
2950  * DMA attributes and contiguity constraints.
2951  */
2952 /*ARGSUSED*/
2953 page_t *
2954 page_create_io(
2955 	struct vnode	*vp,
2956 	u_offset_t	off,
2957 	uint_t		bytes,
2958 	uint_t		flags,
2959 	struct as	*as,
2960 	caddr_t		vaddr,
2961 	ddi_dma_attr_t	*mattr)
2962 {
2963 	page_t	*plist = NULL, *pp;
2964 	int	npages = 0, contig, anyaddr, pages_req;
2965 	mfn_t	lo_mfn;
2966 	mfn_t	hi_mfn;
2967 	pgcnt_t	pfnalign = 0;
2968 	int	align;
2969 	int	is_domu = 0;
2970 	int	dummy, bytes_got;
2971 	mfn_t	max_mfn = HYPERVISOR_memory_op(XENMEM_maximum_ram_page, NULL);
2972 
2973 	ASSERT(mattr != NULL);
2974 	lo_mfn = mmu_btop(mattr->dma_attr_addr_lo);
2975 	hi_mfn = mmu_btop(mattr->dma_attr_addr_hi);
2976 	align = maxbit(mattr->dma_attr_align, mattr->dma_attr_minxfer);
2977 	if (align > MMU_PAGESIZE)
2978 		pfnalign = mmu_btop(align);
2979 
2980 	/*
2981 	 * Clear the contig flag if only one page is needed or the scatter
2982 	 * gather list length is >= npages.
2983 	 */
2984 	pages_req = npages = mmu_btopr(bytes);
2985 	contig = (flags & PG_PHYSCONTIG);
2986 	bytes = P2ROUNDUP(bytes, MMU_PAGESIZE);
2987 	if (bytes == MMU_PAGESIZE || mattr->dma_attr_sgllen >= npages)
2988 		contig = 0;
2989 
2990 	/*
2991 	 * Check if any old page in the system is fine.
2992 	 * DomU should always go down this path.
2993 	 */
2994 	is_domu = !DOMAIN_IS_INITDOMAIN(xen_info);
2995 	anyaddr = lo_mfn == 0 && hi_mfn >= max_mfn && !pfnalign;
2996 	if ((!contig && anyaddr) || is_domu) {
2997 		flags &= ~PG_PHYSCONTIG;
2998 		plist = page_create_va(vp, off, bytes, flags, &kvseg, vaddr);
2999 		if (plist != NULL)
3000 			return (plist);
3001 		else if (is_domu)
3002 			return (NULL); /* no memory available */
3003 	}
3004 	/*
3005 	 * DomU should never reach here
3006 	 */
3007 	if (contig) {
3008 		plist = page_get_contigpages(vp, off, &npages, flags, vaddr,
3009 		    mattr);
3010 		if (plist == NULL)
3011 			goto fail;
3012 		bytes_got = (pages_req - npages) << MMU_PAGESHIFT;
3013 		vaddr += bytes_got;
3014 		off += bytes_got;
3015 		/*
3016 		 * We now have all the contiguous pages we need, but
3017 		 * we may still need additional non-contiguous pages.
3018 		 */
3019 	}
3020 	/*
3021 	 * now loop collecting the requested number of pages, these do
3022 	 * not have to be contiguous pages but we will use the contig
3023 	 * page alloc code to get the pages since it will honor any
3024 	 * other constraints the pages may have.
3025 	 */
3026 	while (npages--) {
3027 		dummy = -1;
3028 		pp = page_get_contigpages(vp, off, &dummy, flags, vaddr, mattr);
3029 		if (pp == NULL)
3030 			goto fail;
3031 		page_add(&plist, pp);
3032 		vaddr += MMU_PAGESIZE;
3033 		off += MMU_PAGESIZE;
3034 	}
3035 	return (plist);
3036 fail:
3037 	/*
3038 	 * Failed to get enough pages, return ones we did get
3039 	 */
3040 	return_partial_alloc(plist);
3041 	return (NULL);
3042 }
3043 
3044 /*
3045  * Lock and return the page with the highest mfn that we can find.  last_mfn
3046  * holds the last one found, so the next search can start from there.  We
3047  * also keep a counter so that we don't loop forever if the machine has no
3048  * free pages.
3049  *
3050  * This is called from the balloon thread to find pages to give away.  new_high
3051  * is used when new mfn's have been added to the system - we will reset our
3052  * search if the new mfn's are higher than our current search position.
3053  */
3054 page_t *
3055 page_get_high_mfn(mfn_t new_high)
3056 {
3057 	static mfn_t last_mfn = 0;
3058 	pfn_t pfn;
3059 	page_t *pp;
3060 	ulong_t loop_count = 0;
3061 
3062 	if (new_high > last_mfn)
3063 		last_mfn = new_high;
3064 
3065 	for (; loop_count < mfn_count; loop_count++, last_mfn--) {
3066 		if (last_mfn == 0) {
3067 			last_mfn = cached_max_mfn;
3068 		}
3069 
3070 		pfn = mfn_to_pfn(last_mfn);
3071 		if (pfn & PFN_IS_FOREIGN_MFN)
3072 			continue;
3073 
3074 		/* See if the page is free.  If so, lock it. */
3075 		pp = page_numtopp_alloc(pfn);
3076 		if (pp == NULL)
3077 			continue;
3078 		PP_CLRFREE(pp);
3079 
3080 		ASSERT(PAGE_EXCL(pp));
3081 		ASSERT(pp->p_vnode == NULL);
3082 		ASSERT(!hat_page_is_mapped(pp));
3083 		last_mfn--;
3084 		return (pp);
3085 	}
3086 	return (NULL);
3087 }
3088 
3089 #else /* !__xpv */
3090 
3091 /*
3092  * get a page from any list with the given mnode
3093  */
3094 static page_t *
3095 page_get_mnode_anylist(ulong_t origbin, uchar_t szc, uint_t flags,
3096     int mnode, int mtype, ddi_dma_attr_t *dma_attr)
3097 {
3098 	kmutex_t		*pcm;
3099 	int			i;
3100 	page_t			*pp;
3101 	page_t			*first_pp;
3102 	uint64_t		pgaddr;
3103 	ulong_t			bin;
3104 	int			mtypestart;
3105 	int			plw_initialized;
3106 	page_list_walker_t	plw;
3107 
3108 	VM_STAT_ADD(pga_vmstats.pgma_alloc);
3109 
3110 	ASSERT((flags & PG_MATCH_COLOR) == 0);
3111 	ASSERT(szc == 0);
3112 	ASSERT(dma_attr != NULL);
3113 
3114 	MTYPE_START(mnode, mtype, flags);
3115 	if (mtype < 0) {
3116 		VM_STAT_ADD(pga_vmstats.pgma_allocempty);
3117 		return (NULL);
3118 	}
3119 
3120 	mtypestart = mtype;
3121 
3122 	bin = origbin;
3123 
3124 	/*
3125 	 * check up to page_colors + 1 bins - origbin may be checked twice
3126 	 * because of BIN_STEP skip
3127 	 */
3128 	do {
3129 		plw_initialized = 0;
3130 
3131 		for (plw.plw_count = 0;
3132 		    plw.plw_count < page_colors; plw.plw_count++) {
3133 
3134 			if (PAGE_FREELISTS(PFLT_USER, mnode, szc, bin, mtype)
3135 			    == NULL)
3136 				goto nextfreebin;
3137 
3138 			pcm = PC_FREELIST_BIN_MUTEX(PFLT_USER, mnode, bin,
3139 			    PG_FREE_LIST);
3140 			mutex_enter(pcm);
3141 			pp = PAGE_FREELISTS(PFLT_USER, mnode, szc, bin, mtype);
3142 			first_pp = pp;
3143 			while (pp != NULL) {
3144 				if (page_trylock(pp, SE_EXCL) == 0) {
3145 					pp = pp->p_next;
3146 					if (pp == first_pp) {
3147 						pp = NULL;
3148 					}
3149 					continue;
3150 				}
3151 
3152 				ASSERT(PP_ISFREE(pp));
3153 				ASSERT(PP_ISAGED(pp));
3154 				ASSERT(pp->p_vnode == NULL);
3155 				ASSERT(pp->p_hash == NULL);
3156 				ASSERT(pp->p_offset == (u_offset_t)-1);
3157 				ASSERT(pp->p_szc == szc);
3158 				ASSERT(PFN_2_MEM_NODE(pp->p_pagenum) == mnode);
3159 				/* check if page within DMA attributes */
3160 				pgaddr = pa_to_ma(pfn_to_pa(pp->p_pagenum));
3161 				if ((pgaddr >= dma_attr->dma_attr_addr_lo) &&
3162 				    (pgaddr + MMU_PAGESIZE - 1 <=
3163 				    dma_attr->dma_attr_addr_hi)) {
3164 					break;
3165 				}
3166 
3167 				/* continue looking */
3168 				page_unlock(pp);
3169 				pp = pp->p_next;
3170 				if (pp == first_pp)
3171 					pp = NULL;
3172 
3173 			}
3174 			if (pp != NULL) {
3175 				ASSERT(mtype == PP_2_MTYPE(pp));
3176 				ASSERT(pp->p_szc == 0);
3177 
3178 				/* found a page with specified DMA attributes */
3179 				page_sub(PAGE_FREELISTP(PFLT_USER, mnode, szc,
3180 				    bin, mtype), pp);
3181 				page_ctr_sub(mnode, mtype, pp, PG_FREE_LIST);
3182 
3183 				if ((PP_ISFREE(pp) == 0) ||
3184 				    (PP_ISAGED(pp) == 0)) {
3185 					cmn_err(CE_PANIC, "page %p is not free",
3186 					    (void *)pp);
3187 				}
3188 
3189 				mutex_exit(pcm);
3190 #ifdef DEBUG
3191 				check_dma(dma_attr, pp, 1);
3192 #endif
3193 				VM_STAT_ADD(pga_vmstats.pgma_allocok);
3194 				return (pp);
3195 			}
3196 			mutex_exit(pcm);
3197 nextfreebin:
3198 			if (plw_initialized == 0) {
3199 				page_list_walk_init(szc, 0, bin, 1, 0, &plw);
3200 				ASSERT(plw.plw_ceq_dif == page_colors);
3201 				plw_initialized = 1;
3202 			}
3203 
3204 			if (plw.plw_do_split) {
3205 				pp = page_freelist_split(szc, bin, mnode,
3206 				    mtype,
3207 				    mmu_btop(dma_attr->dma_attr_addr_lo),
3208 				    mmu_btop(dma_attr->dma_attr_addr_hi + 1),
3209 				    &plw);
3210 				if (pp != NULL) {
3211 #ifdef DEBUG
3212 					check_dma(dma_attr, pp, 1);
3213 #endif
3214 					return (pp);
3215 				}
3216 			}
3217 
3218 			bin = page_list_walk_next_bin(szc, bin, &plw);
3219 		}
3220 
3221 		MTYPE_NEXT(mnode, mtype, flags);
3222 	} while (mtype >= 0);
3223 
3224 	/* failed to find a page in the freelist; try it in the cachelist */
3225 
3226 	/* reset mtype start for cachelist search */
3227 	mtype = mtypestart;
3228 	ASSERT(mtype >= 0);
3229 
3230 	/* start with the bin of matching color */
3231 	bin = origbin;
3232 
3233 	do {
3234 		for (i = 0; i <= page_colors; i++) {
3235 			if (PAGE_CACHELISTS(mnode, bin, mtype) == NULL)
3236 				goto nextcachebin;
3237 			pcm = PC_BIN_MUTEX(PFLT_USER, mnode, bin,
3238 			    PG_CACHE_LIST);
3239 			mutex_enter(pcm);
3240 			pp = PAGE_CACHELISTS(mnode, bin, mtype);
3241 			first_pp = pp;
3242 			while (pp != NULL) {
3243 				if (page_trylock(pp, SE_EXCL) == 0) {
3244 					pp = pp->p_next;
3245 					if (pp == first_pp)
3246 						pp = NULL;
3247 					continue;
3248 				}
3249 				ASSERT(pp->p_vnode);
3250 				ASSERT(PP_ISAGED(pp) == 0);
3251 				ASSERT(pp->p_szc == 0);
3252 				ASSERT(PFN_2_MEM_NODE(pp->p_pagenum) == mnode);
3253 
3254 				/* check if page within DMA attributes */
3255 
3256 				pgaddr = pa_to_ma(pfn_to_pa(pp->p_pagenum));
3257 				if ((pgaddr >= dma_attr->dma_attr_addr_lo) &&
3258 				    (pgaddr + MMU_PAGESIZE - 1 <=
3259 				    dma_attr->dma_attr_addr_hi)) {
3260 					break;
3261 				}
3262 
3263 				/* continue looking */
3264 				page_unlock(pp);
3265 				pp = pp->p_next;
3266 				if (pp == first_pp)
3267 					pp = NULL;
3268 			}
3269 
3270 			if (pp != NULL) {
3271 				ASSERT(mtype == PP_2_MTYPE(pp));
3272 				ASSERT(pp->p_szc == 0);
3273 
3274 				/* found a page with specified DMA attributes */
3275 				page_sub(&PAGE_CACHELISTS(mnode, bin,
3276 				    mtype), pp);
3277 				page_ctr_sub(mnode, mtype, pp, PG_CACHE_LIST);
3278 
3279 				mutex_exit(pcm);
3280 				ASSERT(pp->p_vnode);
3281 				ASSERT(PP_ISAGED(pp) == 0);
3282 #ifdef DEBUG
3283 				check_dma(dma_attr, pp, 1);
3284 #endif
3285 				VM_STAT_ADD(pga_vmstats.pgma_allocok);
3286 				return (pp);
3287 			}
3288 			mutex_exit(pcm);
3289 nextcachebin:
3290 			bin += (i == 0) ? BIN_STEP : 1;
3291 			bin &= page_colors_mask;
3292 		}
3293 		MTYPE_NEXT(mnode, mtype, flags);
3294 	} while (mtype >= 0);
3295 
3296 	VM_STAT_ADD(pga_vmstats.pgma_allocfailed);
3297 	return (NULL);
3298 }
3299 
3300 /*
3301  * This function is similar to page_get_freelist()/page_get_cachelist()
3302  * but it searches both the lists to find a page with the specified
3303  * color (or no color) and DMA attributes. The search is done in the
3304  * freelist first and then in the cache list within the highest memory
3305  * range (based on DMA attributes) before searching in the lower
3306  * memory ranges.
3307  *
3308  * Note: This function is called only by page_create_io().
3309  */
3310 /*ARGSUSED*/
3311 static page_t *
3312 page_get_anylist(struct vnode *vp, u_offset_t off, struct as *as, caddr_t vaddr,
3313     size_t size, uint_t flags, ddi_dma_attr_t *dma_attr, lgrp_t	*lgrp)
3314 {
3315 	uint_t		bin;
3316 	int		mtype;
3317 	page_t		*pp;
3318 	int		n;
3319 	int		m;
3320 	int		szc;
3321 	int		fullrange;
3322 	int		mnode;
3323 	int		local_failed_stat = 0;
3324 	lgrp_mnode_cookie_t	lgrp_cookie;
3325 
3326 	VM_STAT_ADD(pga_vmstats.pga_alloc);
3327 
3328 	/* only base pagesize currently supported */
3329 	if (size != MMU_PAGESIZE)
3330 		return (NULL);
3331 
3332 	/*
3333 	 * If we're passed a specific lgroup, we use it.  Otherwise,
3334 	 * assume first-touch placement is desired.
3335 	 */
3336 	if (!LGRP_EXISTS(lgrp))
3337 		lgrp = lgrp_home_lgrp();
3338 
3339 	/* LINTED */
3340 	AS_2_BIN(PFLT_USER, as, seg, vp, vaddr, bin, 0);
3341 
3342 	/*
3343 	 * Only hold one freelist or cachelist lock at a time, that way we
3344 	 * can start anywhere and not have to worry about lock
3345 	 * ordering.
3346 	 */
3347 	if (dma_attr == NULL) {
3348 		n = mtype16m;
3349 		m = mtypetop;
3350 		fullrange = 1;
3351 		VM_STAT_ADD(pga_vmstats.pga_nulldmaattr);
3352 	} else {
3353 		pfn_t pfnlo = mmu_btop(dma_attr->dma_attr_addr_lo);
3354 		pfn_t pfnhi = mmu_btop(dma_attr->dma_attr_addr_hi);
3355 
3356 		/*
3357 		 * We can guarantee alignment only for page boundary.
3358 		 */
3359 		if (dma_attr->dma_attr_align > MMU_PAGESIZE)
3360 			return (NULL);
3361 
3362 		/* Sanity check the dma_attr */
3363 		if (pfnlo > pfnhi)
3364 			return (NULL);
3365 
3366 		n = pfn_2_mtype(pfnlo);
3367 		m = pfn_2_mtype(pfnhi);
3368 
3369 		fullrange = ((pfnlo == mnoderanges[n].mnr_pfnlo) &&
3370 		    (pfnhi >= mnoderanges[m].mnr_pfnhi));
3371 	}
3372 	VM_STAT_COND_ADD(fullrange == 0, pga_vmstats.pga_notfullrange);
3373 
3374 	szc = 0;
3375 
3376 	/* cylcing thru mtype handled by RANGE0 if n == mtype16m */
3377 	if (n == mtype16m) {
3378 		flags |= PGI_MT_RANGE0;
3379 		n = m;
3380 	}
3381 
3382 	/*
3383 	 * Try local memory node first, but try remote if we can't
3384 	 * get a page of the right color.
3385 	 */
3386 	LGRP_MNODE_COOKIE_INIT(lgrp_cookie, lgrp, LGRP_SRCH_HIER);
3387 	while ((mnode = lgrp_memnode_choose(&lgrp_cookie)) >= 0) {
3388 		/*
3389 		 * allocate pages from high pfn to low.
3390 		 */
3391 		mtype = m;
3392 		do {
3393 			if (fullrange != 0) {
3394 				pp = page_get_mnode_freelist(ufltp, mnode,
3395 				    bin, mtype, szc, flags);
3396 				if (pp == NULL) {
3397 					pp = page_get_mnode_cachelist(
3398 					    bin, flags, mnode, mtype);
3399 				}
3400 			} else {
3401 				pp = page_get_mnode_anylist(bin, szc,
3402 				    flags, mnode, mtype, dma_attr);
3403 			}
3404 			if (pp != NULL) {
3405 				VM_STAT_ADD(pga_vmstats.pga_allocok);
3406 #ifdef DEBUG
3407 				check_dma(dma_attr, pp, 1);
3408 #endif
3409 				return (pp);
3410 			}
3411 		} while (mtype != n &&
3412 		    (mtype = mnoderanges[mtype].mnr_next) != -1);
3413 		if (!local_failed_stat) {
3414 			lgrp_stat_add(lgrp->lgrp_id, LGRP_NUM_ALLOC_FAIL, 1);
3415 			local_failed_stat = 1;
3416 		}
3417 	}
3418 	VM_STAT_ADD(pga_vmstats.pga_allocfailed);
3419 
3420 	return (NULL);
3421 }
3422 
3423 /*
3424  * page_create_io()
3425  *
3426  * This function is a copy of page_create_va() with an additional
3427  * argument 'mattr' that specifies DMA memory requirements to
3428  * the page list functions. This function is used by the segkmem
3429  * allocator so it is only to create new pages (i.e PG_EXCL is
3430  * set).
3431  *
3432  * Note: This interface is currently used by x86 PSM only and is
3433  *	 not fully specified so the commitment level is only for
3434  *	 private interface specific to x86. This interface uses PSM
3435  *	 specific page_get_anylist() interface.
3436  */
3437 
3438 #define	PAGE_HASH_SEARCH(index, pp, vp, off) { \
3439 	for ((pp) = page_hash[(index)]; (pp); (pp) = (pp)->p_hash) { \
3440 		if ((pp)->p_vnode == (vp) && (pp)->p_offset == (off)) \
3441 			break; \
3442 	} \
3443 }
3444 
3445 
3446 page_t *
3447 page_create_io(
3448 	struct vnode	*vp,
3449 	u_offset_t	off,
3450 	uint_t		bytes,
3451 	uint_t		flags,
3452 	struct as	*as,
3453 	caddr_t		vaddr,
3454 	ddi_dma_attr_t	*mattr)	/* DMA memory attributes if any */
3455 {
3456 	page_t		*plist = NULL;
3457 	uint_t		plist_len = 0;
3458 	pgcnt_t		npages;
3459 	page_t		*npp = NULL;
3460 	uint_t		pages_req;
3461 	page_t		*pp;
3462 	kmutex_t	*phm = NULL;
3463 	uint_t		index;
3464 
3465 	TRACE_4(TR_FAC_VM, TR_PAGE_CREATE_START,
3466 	    "page_create_start:vp %p off %llx bytes %u flags %x",
3467 	    vp, off, bytes, flags);
3468 
3469 	ASSERT((flags & ~(PG_EXCL | PG_WAIT | PG_PHYSCONTIG)) == 0);
3470 
3471 	pages_req = npages = mmu_btopr(bytes);
3472 
3473 	/*
3474 	 * Do the freemem and pcf accounting.
3475 	 */
3476 	if (!page_create_wait(npages, flags)) {
3477 		return (NULL);
3478 	}
3479 
3480 	TRACE_2(TR_FAC_VM, TR_PAGE_CREATE_SUCCESS,
3481 	    "page_create_success:vp %p off %llx", vp, off);
3482 
3483 	/*
3484 	 * If satisfying this request has left us with too little
3485 	 * memory, start the wheels turning to get some back.  The
3486 	 * first clause of the test prevents waking up the pageout
3487 	 * daemon in situations where it would decide that there's
3488 	 * nothing to do.
3489 	 */
3490 	if (nscan < desscan && freemem < minfree) {
3491 		TRACE_1(TR_FAC_VM, TR_PAGEOUT_CV_SIGNAL,
3492 		    "pageout_cv_signal:freemem %ld", freemem);
3493 		cv_signal(&proc_pageout->p_cv);
3494 	}
3495 
3496 	if (flags & PG_PHYSCONTIG) {
3497 
3498 		plist = page_get_contigpage(&npages, mattr, 1);
3499 		if (plist == NULL) {
3500 			page_create_putback(npages);
3501 			return (NULL);
3502 		}
3503 
3504 		pp = plist;
3505 
3506 		do {
3507 			if (!page_hashin(pp, vp, off, NULL)) {
3508 				panic("pg_creat_io: hashin failed %p %p %llx",
3509 				    (void *)pp, (void *)vp, off);
3510 			}
3511 			VM_STAT_ADD(page_create_new);
3512 			off += MMU_PAGESIZE;
3513 			PP_CLRFREE(pp);
3514 			PP_CLRAGED(pp);
3515 			page_set_props(pp, P_REF);
3516 			pp = pp->p_next;
3517 		} while (pp != plist);
3518 
3519 		if (!npages) {
3520 #ifdef DEBUG
3521 			check_dma(mattr, plist, pages_req);
3522 #endif
3523 			return (plist);
3524 		} else {
3525 			vaddr += (pages_req - npages) << MMU_PAGESHIFT;
3526 		}
3527 
3528 		/*
3529 		 * fall-thru:
3530 		 *
3531 		 * page_get_contigpage returns when npages <= sgllen.
3532 		 * Grab the rest of the non-contig pages below from anylist.
3533 		 */
3534 	}
3535 
3536 	/*
3537 	 * Loop around collecting the requested number of pages.
3538 	 * Most of the time, we have to `create' a new page. With
3539 	 * this in mind, pull the page off the free list before
3540 	 * getting the hash lock.  This will minimize the hash
3541 	 * lock hold time, nesting, and the like.  If it turns
3542 	 * out we don't need the page, we put it back at the end.
3543 	 */
3544 	while (npages--) {
3545 		phm = NULL;
3546 
3547 		index = PAGE_HASH_FUNC(vp, off);
3548 top:
3549 		ASSERT(phm == NULL);
3550 		ASSERT(index == PAGE_HASH_FUNC(vp, off));
3551 		ASSERT(MUTEX_NOT_HELD(page_vnode_mutex(vp)));
3552 
3553 		if (npp == NULL) {
3554 			/*
3555 			 * Try to get the page of any color either from
3556 			 * the freelist or from the cache list.
3557 			 */
3558 			npp = page_get_anylist(vp, off, as, vaddr, MMU_PAGESIZE,
3559 			    flags & ~PG_MATCH_COLOR, mattr, NULL);
3560 			if (npp == NULL) {
3561 				if (mattr == NULL) {
3562 					/*
3563 					 * Not looking for a special page;
3564 					 * panic!
3565 					 */
3566 					panic("no page found %d", (int)npages);
3567 				}
3568 				/*
3569 				 * No page found! This can happen
3570 				 * if we are looking for a page
3571 				 * within a specific memory range
3572 				 * for DMA purposes. If PG_WAIT is
3573 				 * specified then we wait for a
3574 				 * while and then try again. The
3575 				 * wait could be forever if we
3576 				 * don't get the page(s) we need.
3577 				 *
3578 				 * Note: XXX We really need a mechanism
3579 				 * to wait for pages in the desired
3580 				 * range. For now, we wait for any
3581 				 * pages and see if we can use it.
3582 				 */
3583 
3584 				if ((mattr != NULL) && (flags & PG_WAIT)) {
3585 					delay(10);
3586 					goto top;
3587 				}
3588 				goto fail; /* undo accounting stuff */
3589 			}
3590 
3591 			if (PP_ISAGED(npp) == 0) {
3592 				/*
3593 				 * Since this page came from the
3594 				 * cachelist, we must destroy the
3595 				 * old vnode association.
3596 				 */
3597 				page_hashout(npp, (kmutex_t *)NULL);
3598 			}
3599 		}
3600 
3601 		/*
3602 		 * We own this page!
3603 		 */
3604 		ASSERT(PAGE_EXCL(npp));
3605 		ASSERT(npp->p_vnode == NULL);
3606 		ASSERT(!hat_page_is_mapped(npp));
3607 		PP_CLRFREE(npp);
3608 		PP_CLRAGED(npp);
3609 
3610 		/*
3611 		 * Here we have a page in our hot little mits and are
3612 		 * just waiting to stuff it on the appropriate lists.
3613 		 * Get the mutex and check to see if it really does
3614 		 * not exist.
3615 		 */
3616 		phm = PAGE_HASH_MUTEX(index);
3617 		mutex_enter(phm);
3618 		PAGE_HASH_SEARCH(index, pp, vp, off);
3619 		if (pp == NULL) {
3620 			VM_STAT_ADD(page_create_new);
3621 			pp = npp;
3622 			npp = NULL;
3623 			if (!page_hashin(pp, vp, off, phm)) {
3624 				/*
3625 				 * Since we hold the page hash mutex and
3626 				 * just searched for this page, page_hashin
3627 				 * had better not fail.  If it does, that
3628 				 * means somethread did not follow the
3629 				 * page hash mutex rules.  Panic now and
3630 				 * get it over with.  As usual, go down
3631 				 * holding all the locks.
3632 				 */
3633 				ASSERT(MUTEX_HELD(phm));
3634 				panic("page_create: hashin fail %p %p %llx %p",
3635 				    (void *)pp, (void *)vp, off, (void *)phm);
3636 
3637 			}
3638 			ASSERT(MUTEX_HELD(phm));
3639 			mutex_exit(phm);
3640 			phm = NULL;
3641 
3642 			/*
3643 			 * Hat layer locking need not be done to set
3644 			 * the following bits since the page is not hashed
3645 			 * and was on the free list (i.e., had no mappings).
3646 			 *
3647 			 * Set the reference bit to protect
3648 			 * against immediate pageout
3649 			 *
3650 			 * XXXmh modify freelist code to set reference
3651 			 * bit so we don't have to do it here.
3652 			 */
3653 			page_set_props(pp, P_REF);
3654 		} else {
3655 			ASSERT(MUTEX_HELD(phm));
3656 			mutex_exit(phm);
3657 			phm = NULL;
3658 			/*
3659 			 * NOTE: This should not happen for pages associated
3660 			 *	 with kernel vnode 'kvp'.
3661 			 */
3662 			/* XX64 - to debug why this happens! */
3663 			ASSERT(!VN_ISKAS(vp));
3664 			if (VN_ISKAS(vp))
3665 				cmn_err(CE_NOTE,
3666 				    "page_create: page not expected "
3667 				    "in hash list for kernel vnode - pp 0x%p",
3668 				    (void *)pp);
3669 			VM_STAT_ADD(page_create_exists);
3670 			goto fail;
3671 		}
3672 
3673 		/*
3674 		 * Got a page!  It is locked.  Acquire the i/o
3675 		 * lock since we are going to use the p_next and
3676 		 * p_prev fields to link the requested pages together.
3677 		 */
3678 		page_io_lock(pp);
3679 		page_add(&plist, pp);
3680 		plist = plist->p_next;
3681 		off += MMU_PAGESIZE;
3682 		vaddr += MMU_PAGESIZE;
3683 	}
3684 
3685 #ifdef DEBUG
3686 	check_dma(mattr, plist, pages_req);
3687 #endif
3688 	return (plist);
3689 
3690 fail:
3691 	if (npp != NULL) {
3692 		/*
3693 		 * Did not need this page after all.
3694 		 * Put it back on the free list.
3695 		 */
3696 		VM_STAT_ADD(page_create_putbacks);
3697 		PP_SETFREE(npp);
3698 		PP_SETAGED(npp);
3699 		npp->p_offset = (u_offset_t)-1;
3700 		page_list_add(npp, PG_FREE_LIST | PG_LIST_TAIL);
3701 		page_unlock(npp);
3702 	}
3703 
3704 	/*
3705 	 * Give up the pages we already got.
3706 	 */
3707 	while (plist != NULL) {
3708 		pp = plist;
3709 		page_sub(&plist, pp);
3710 		page_io_unlock(pp);
3711 		plist_len++;
3712 		/*LINTED: constant in conditional ctx*/
3713 		VN_DISPOSE(pp, B_INVAL, 0, kcred);
3714 	}
3715 
3716 	/*
3717 	 * VN_DISPOSE does freemem accounting for the pages in plist
3718 	 * by calling page_free. So, we need to undo the pcf accounting
3719 	 * for only the remaining pages.
3720 	 */
3721 	VM_STAT_ADD(page_create_putbacks);
3722 	page_create_putback(pages_req - plist_len);
3723 
3724 	return (NULL);
3725 }
3726 #endif /* !__xpv */
3727 
3728 
3729 /*
3730  * Copy the data from the physical page represented by "frompp" to
3731  * that represented by "topp". ppcopy uses CPU->cpu_caddr1 and
3732  * CPU->cpu_caddr2.  It assumes that no one uses either map at interrupt
3733  * level and no one sleeps with an active mapping there.
3734  *
3735  * Note that the ref/mod bits in the page_t's are not affected by
3736  * this operation, hence it is up to the caller to update them appropriately.
3737  */
3738 int
3739 ppcopy(page_t *frompp, page_t *topp)
3740 {
3741 	caddr_t		pp_addr1;
3742 	caddr_t		pp_addr2;
3743 	hat_mempte_t	pte1;
3744 	hat_mempte_t	pte2;
3745 	kmutex_t	*ppaddr_mutex;
3746 	label_t		ljb;
3747 	int		ret = 1;
3748 
3749 	ASSERT_STACK_ALIGNED();
3750 	ASSERT(PAGE_LOCKED(frompp));
3751 	ASSERT(PAGE_LOCKED(topp));
3752 
3753 	if (kpm_enable) {
3754 		pp_addr1 = hat_kpm_page2va(frompp, 0);
3755 		pp_addr2 = hat_kpm_page2va(topp, 0);
3756 		kpreempt_disable();
3757 	} else {
3758 		/*
3759 		 * disable pre-emption so that CPU can't change
3760 		 */
3761 		kpreempt_disable();
3762 
3763 		pp_addr1 = CPU->cpu_caddr1;
3764 		pp_addr2 = CPU->cpu_caddr2;
3765 		pte1 = CPU->cpu_caddr1pte;
3766 		pte2 = CPU->cpu_caddr2pte;
3767 
3768 		ppaddr_mutex = &CPU->cpu_ppaddr_mutex;
3769 		mutex_enter(ppaddr_mutex);
3770 
3771 		hat_mempte_remap(page_pptonum(frompp), pp_addr1, pte1,
3772 		    PROT_READ | HAT_STORECACHING_OK, HAT_LOAD_NOCONSIST);
3773 		hat_mempte_remap(page_pptonum(topp), pp_addr2, pte2,
3774 		    PROT_READ | PROT_WRITE | HAT_STORECACHING_OK,
3775 		    HAT_LOAD_NOCONSIST);
3776 	}
3777 
3778 	if (on_fault(&ljb)) {
3779 		ret = 0;
3780 		goto faulted;
3781 	}
3782 	if (use_sse_pagecopy)
3783 #ifdef __xpv
3784 		page_copy_no_xmm(pp_addr2, pp_addr1);
3785 #else
3786 		hwblkpagecopy(pp_addr1, pp_addr2);
3787 #endif
3788 	else
3789 		bcopy(pp_addr1, pp_addr2, PAGESIZE);
3790 
3791 	no_fault();
3792 faulted:
3793 	if (!kpm_enable) {
3794 #ifdef __xpv
3795 		/*
3796 		 * We can't leave unused mappings laying about under the
3797 		 * hypervisor, so blow them away.
3798 		 */
3799 		if (HYPERVISOR_update_va_mapping((uintptr_t)pp_addr1, 0,
3800 		    UVMF_INVLPG | UVMF_LOCAL) < 0)
3801 			panic("HYPERVISOR_update_va_mapping() failed");
3802 		if (HYPERVISOR_update_va_mapping((uintptr_t)pp_addr2, 0,
3803 		    UVMF_INVLPG | UVMF_LOCAL) < 0)
3804 			panic("HYPERVISOR_update_va_mapping() failed");
3805 #endif
3806 		mutex_exit(ppaddr_mutex);
3807 	}
3808 	kpreempt_enable();
3809 	return (ret);
3810 }
3811 
3812 void
3813 pagezero(page_t *pp, uint_t off, uint_t len)
3814 {
3815 	ASSERT(PAGE_LOCKED(pp));
3816 	pfnzero(page_pptonum(pp), off, len);
3817 }
3818 
3819 /*
3820  * Zero the physical page from off to off + len given by pfn
3821  * without changing the reference and modified bits of page.
3822  *
3823  * We use this using CPU private page address #2, see ppcopy() for more info.
3824  * pfnzero() must not be called at interrupt level.
3825  */
3826 void
3827 pfnzero(pfn_t pfn, uint_t off, uint_t len)
3828 {
3829 	caddr_t		pp_addr2;
3830 	hat_mempte_t	pte2;
3831 	kmutex_t	*ppaddr_mutex = NULL;
3832 
3833 	ASSERT_STACK_ALIGNED();
3834 	ASSERT(len <= MMU_PAGESIZE);
3835 	ASSERT(off <= MMU_PAGESIZE);
3836 	ASSERT(off + len <= MMU_PAGESIZE);
3837 
3838 	if (kpm_enable && !pfn_is_foreign(pfn)) {
3839 		pp_addr2 = hat_kpm_pfn2va(pfn);
3840 		kpreempt_disable();
3841 	} else {
3842 		kpreempt_disable();
3843 
3844 		pp_addr2 = CPU->cpu_caddr2;
3845 		pte2 = CPU->cpu_caddr2pte;
3846 
3847 		ppaddr_mutex = &CPU->cpu_ppaddr_mutex;
3848 		mutex_enter(ppaddr_mutex);
3849 
3850 		hat_mempte_remap(pfn, pp_addr2, pte2,
3851 		    PROT_READ | PROT_WRITE | HAT_STORECACHING_OK,
3852 		    HAT_LOAD_NOCONSIST);
3853 	}
3854 
3855 	if (use_sse_pagezero) {
3856 #ifdef __xpv
3857 		uint_t rem;
3858 
3859 		/*
3860 		 * zero a byte at a time until properly aligned for
3861 		 * block_zero_no_xmm().
3862 		 */
3863 		while (!P2NPHASE(off, ((uint_t)BLOCKZEROALIGN)) && len-- > 0)
3864 			pp_addr2[off++] = 0;
3865 
3866 		/*
3867 		 * Now use faster block_zero_no_xmm() for any range
3868 		 * that is properly aligned and sized.
3869 		 */
3870 		rem = P2PHASE(len, ((uint_t)BLOCKZEROALIGN));
3871 		len -= rem;
3872 		if (len != 0) {
3873 			block_zero_no_xmm(pp_addr2 + off, len);
3874 			off += len;
3875 		}
3876 
3877 		/*
3878 		 * zero remainder with byte stores.
3879 		 */
3880 		while (rem-- > 0)
3881 			pp_addr2[off++] = 0;
3882 #else
3883 		hwblkclr(pp_addr2 + off, len);
3884 #endif
3885 	} else {
3886 		bzero(pp_addr2 + off, len);
3887 	}
3888 
3889 	if (!kpm_enable || pfn_is_foreign(pfn)) {
3890 #ifdef __xpv
3891 		/*
3892 		 * On the hypervisor this page might get used for a page
3893 		 * table before any intervening change to this mapping,
3894 		 * so blow it away.
3895 		 */
3896 		if (HYPERVISOR_update_va_mapping((uintptr_t)pp_addr2, 0,
3897 		    UVMF_INVLPG) < 0)
3898 			panic("HYPERVISOR_update_va_mapping() failed");
3899 #endif
3900 		mutex_exit(ppaddr_mutex);
3901 	}
3902 
3903 	kpreempt_enable();
3904 }
3905 
3906 /*
3907  * Platform-dependent page scrub call.
3908  */
3909 void
3910 pagescrub(page_t *pp, uint_t off, uint_t len)
3911 {
3912 	/*
3913 	 * For now, we rely on the fact that pagezero() will
3914 	 * always clear UEs.
3915 	 */
3916 	pagezero(pp, off, len);
3917 }
3918 
3919 /*
3920  * set up two private addresses for use on a given CPU for use in ppcopy()
3921  */
3922 void
3923 setup_vaddr_for_ppcopy(struct cpu *cpup)
3924 {
3925 	void *addr;
3926 	hat_mempte_t pte_pa;
3927 
3928 	addr = vmem_alloc(heap_arena, mmu_ptob(1), VM_SLEEP);
3929 	pte_pa = hat_mempte_setup(addr);
3930 	cpup->cpu_caddr1 = addr;
3931 	cpup->cpu_caddr1pte = pte_pa;
3932 
3933 	addr = vmem_alloc(heap_arena, mmu_ptob(1), VM_SLEEP);
3934 	pte_pa = hat_mempte_setup(addr);
3935 	cpup->cpu_caddr2 = addr;
3936 	cpup->cpu_caddr2pte = pte_pa;
3937 
3938 	mutex_init(&cpup->cpu_ppaddr_mutex, NULL, MUTEX_DEFAULT, NULL);
3939 }
3940 
3941 /*
3942  * Undo setup_vaddr_for_ppcopy
3943  */
3944 void
3945 teardown_vaddr_for_ppcopy(struct cpu *cpup)
3946 {
3947 	mutex_destroy(&cpup->cpu_ppaddr_mutex);
3948 
3949 	hat_mempte_release(cpup->cpu_caddr2, cpup->cpu_caddr2pte);
3950 	cpup->cpu_caddr2pte = 0;
3951 	vmem_free(heap_arena, cpup->cpu_caddr2, mmu_ptob(1));
3952 	cpup->cpu_caddr2 = 0;
3953 
3954 	hat_mempte_release(cpup->cpu_caddr1, cpup->cpu_caddr1pte);
3955 	cpup->cpu_caddr1pte = 0;
3956 	vmem_free(heap_arena, cpup->cpu_caddr1, mmu_ptob(1));
3957 	cpup->cpu_caddr1 = 0;
3958 }
3959 
3960 /*
3961  * Function for flushing D-cache when performing module relocations
3962  * to an alternate mapping.  Unnecessary on Intel / AMD platforms.
3963  */
3964 void
3965 dcache_flushall()
3966 {}
3967 
3968 size_t
3969 exec_get_spslew(void)
3970 {
3971 	return (0);
3972 }
3973 
3974 /*
3975  * Allocate a memory page.  The argument 'seed' can be any pseudo-random
3976  * number to vary where the pages come from.  This is quite a hacked up
3977  * method -- it works for now, but really needs to be fixed up a bit.
3978  *
3979  * We currently use page_create_va() on the kvp with fake offsets,
3980  * segments and virt address.  This is pretty bogus, but was copied from the
3981  * old hat_i86.c code.  A better approach would be to specify either mnode
3982  * random or mnode local and takes a page from whatever color has the MOST
3983  * available - this would have a minimal impact on page coloring.
3984  */
3985 page_t *
3986 page_get_physical(uintptr_t seed)
3987 {
3988 	page_t *pp;
3989 	u_offset_t offset;
3990 	static struct seg tmpseg;
3991 	static uintptr_t ctr = 0;
3992 
3993 	/*
3994 	 * This code is gross, we really need a simpler page allocator.
3995 	 *
3996 	 * We need to assign an offset for the page to call page_create_va()
3997 	 * To avoid conflicts with other pages, we get creative with the offset.
3998 	 * For 32 bits, we need an offset > 4Gig
3999 	 * For 64 bits, need an offset somewhere in the VA hole.
4000 	 */
4001 	offset = seed;
4002 	if (offset > kernelbase)
4003 		offset -= kernelbase;
4004 	offset <<= MMU_PAGESHIFT;
4005 #if defined(__amd64)
4006 	offset += mmu.hole_start;	/* something in VA hole */
4007 #else
4008 	offset += 1ULL << 40;	/* something > 4 Gig */
4009 #endif
4010 
4011 	if (page_resv(1, KM_NOSLEEP) == 0)
4012 		return (NULL);
4013 
4014 #ifdef	DEBUG
4015 	pp = page_exists(&kvp, offset);
4016 	if (pp != NULL)
4017 		panic("page already exists %p", (void *)pp);
4018 #endif
4019 
4020 	pp = page_create_va(&kvp, offset, MMU_PAGESIZE, PG_EXCL,
4021 	    &tmpseg, (caddr_t)(ctr += MMU_PAGESIZE));	/* changing VA usage */
4022 	if (pp != NULL) {
4023 		page_io_unlock(pp);
4024 		page_hashout(pp, NULL);
4025 		page_downgrade(pp);
4026 	}
4027 	return (pp);
4028 }
4029 
4030 /*
4031  * Initializes the user and kernel page freelist type structures.
4032  */
4033 /* ARGSUSED */
4034 void
4035 page_flt_init(page_freelist_type_t *ufp, page_freelist_type_t *kfp)
4036 {
4037 	ufp->pflt_type = PFLT_USER;
4038 	ufp->pflt_get_free = &page_get_uflt;
4039 	ufp->pflt_walk_init = page_list_walk_init;
4040 	ufp->pflt_walk_next = page_list_walk_next_bin;
4041 	ufp->pflt_policy[0] = page_get_mnode_freelist;
4042 	ufp->pflt_policy[1] = page_get_contig_pages;
4043 	ufp->pflt_num_policies = 2;
4044 #if defined(__amd64) && !defined(__xpv)
4045 	if (!kflt_disable) {
4046 		ufp->pflt_num_policies = 3;
4047 		ufp->pflt_policy[1] = page_user_alloc_kflt;
4048 		ufp->pflt_policy[2] = page_get_contig_pages;
4049 
4050 		kfp->pflt_type = PFLT_KMEM;
4051 		kfp->pflt_get_free = &page_get_kflt;
4052 		kfp->pflt_walk_init = page_kflt_walk_init;
4053 		kfp->pflt_walk_next = page_list_walk_next_bin;
4054 		kfp->pflt_num_policies = 1;
4055 		kfp->pflt_policy[0] = page_get_mnode_freelist;
4056 	}
4057 #endif /* __amd64 && !__xpv */
4058 }
4059