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