xref: /illumos-gate/usr/src/uts/sun4v/vm/mach_vm_dep.c (revision 2038334ab26baaa43c9083f35def041511c3cc1f)
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/vm.h>
41 #include <sys/exec.h>
42 #include <sys/cmn_err.h>
43 #include <sys/cpu_module.h>
44 #include <sys/cpu.h>
45 #include <sys/elf_SPARC.h>
46 #include <sys/archsystm.h>
47 #include <vm/hat_sfmmu.h>
48 #include <sys/memnode.h>
49 #include <sys/mem_cage.h>
50 #include <vm/vm_dep.h>
51 #include <sys/error.h>
52 #include <sys/machsystm.h>
53 #include <vm/seg_kmem.h>
54 #include <sys/stack.h>
55 #include <sys/atomic.h>
56 
57 uint_t page_colors = 0;
58 uint_t page_colors_mask = 0;
59 uint_t page_coloring_shift = 0;
60 int consistent_coloring;
61 int update_proc_pgcolorbase_after_fork = 1;
62 
63 uint_t mmu_page_sizes = MMU_PAGE_SIZES;
64 uint_t max_mmu_page_sizes = MMU_PAGE_SIZES;
65 uint_t mmu_hashcnt = MAX_HASHCNT;
66 uint_t max_mmu_hashcnt = MAX_HASHCNT;
67 size_t mmu_ism_pagesize = DEFAULT_ISM_PAGESIZE;
68 
69 /*
70  * A bitmask of the page sizes supported by hardware based upon szc.
71  * The base pagesize (p_szc == 0) must always be supported by the hardware.
72  */
73 int mmu_exported_pagesize_mask;
74 uint_t mmu_exported_page_sizes;
75 
76 uint_t szc_2_userszc[MMU_PAGE_SIZES];
77 uint_t userszc_2_szc[MMU_PAGE_SIZES];
78 
79 extern uint_t vac_colors_mask;
80 extern int vac_shift;
81 
82 hw_pagesize_t hw_page_array[] = {
83 	{MMU_PAGESIZE, MMU_PAGESHIFT, 0, MMU_PAGESIZE >> MMU_PAGESHIFT},
84 	{MMU_PAGESIZE64K, MMU_PAGESHIFT64K, 0,
85 	    MMU_PAGESIZE64K >> MMU_PAGESHIFT},
86 	{MMU_PAGESIZE512K, MMU_PAGESHIFT512K, 0,
87 	    MMU_PAGESIZE512K >> MMU_PAGESHIFT},
88 	{MMU_PAGESIZE4M, MMU_PAGESHIFT4M, 0, MMU_PAGESIZE4M >> MMU_PAGESHIFT},
89 	{MMU_PAGESIZE32M, MMU_PAGESHIFT32M, 0,
90 	    MMU_PAGESIZE32M >> MMU_PAGESHIFT},
91 	{MMU_PAGESIZE256M, MMU_PAGESHIFT256M, 0,
92 	    MMU_PAGESIZE256M >> MMU_PAGESHIFT},
93 	{0, 0, 0, 0}
94 };
95 
96 /*
97  * Maximum page size used to map 64-bit memory segment kmem64_base..kmem64_end
98  */
99 int	max_bootlp_tteszc = TTE256M;
100 
101 /*
102  * Maximum and default segment size tunables for user heap, stack, private
103  * and shared anonymous memory, and user text and initialized data.
104  */
105 size_t max_uheap_lpsize = MMU_PAGESIZE64K;
106 size_t default_uheap_lpsize = MMU_PAGESIZE64K;
107 size_t max_ustack_lpsize = MMU_PAGESIZE64K;
108 size_t default_ustack_lpsize = MMU_PAGESIZE64K;
109 size_t max_privmap_lpsize = MMU_PAGESIZE64K;
110 size_t max_uidata_lpsize = MMU_PAGESIZE64K;
111 size_t max_utext_lpsize = MMU_PAGESIZE4M;
112 size_t max_shm_lpsize = MMU_PAGESIZE4M;
113 
114 /*
115  * Contiguous memory allocator data structures and variables.
116  *
117  * The sun4v kernel must provide a means to allocate physically
118  * contiguous, non-relocatable memory. The contig_mem_arena
119  * and contig_mem_slab_arena exist for this purpose. Allocations
120  * that require physically contiguous non-relocatable memory should
121  * be made using contig_mem_alloc() or contig_mem_alloc_align()
122  * which return memory from contig_mem_arena or contig_mem_reloc_arena.
123  * These arenas import memory from the contig_mem_slab_arena one
124  * contiguous chunk at a time.
125  *
126  * When importing slabs, an attempt is made to allocate a large page
127  * to use as backing. As a result of the non-relocatable requirement,
128  * slabs are allocated from the kernel cage freelists. If the cage does
129  * not contain any free contiguous chunks large enough to satisfy the
130  * slab allocation, the slab size will be downsized and the operation
131  * retried. Large slab sizes are tried first to minimize cage
132  * fragmentation. If the slab allocation is unsuccessful still, the slab
133  * is allocated from outside the kernel cage. This is undesirable because,
134  * until slabs are freed, it results in non-relocatable chunks scattered
135  * throughout physical memory.
136  *
137  * Allocations from the contig_mem_arena are backed by slabs from the
138  * cage. Allocations from the contig_mem_reloc_arena are backed by
139  * slabs allocated outside the cage. Slabs are left share locked while
140  * in use to prevent non-cage slabs from being relocated.
141  *
142  * Since there is no guarantee that large pages will be available in
143  * the kernel cage, contiguous memory is reserved and added to the
144  * contig_mem_arena at boot time, making it available for later
145  * contiguous memory allocations. This reserve will be used to satisfy
146  * contig_mem allocations first and it is only when the reserve is
147  * completely allocated that new slabs will need to be imported.
148  */
149 static	vmem_t		*contig_mem_slab_arena;
150 static	vmem_t		*contig_mem_arena;
151 static	vmem_t		*contig_mem_reloc_arena;
152 static	kmutex_t	contig_mem_lock;
153 #define	CONTIG_MEM_ARENA_QUANTUM	64
154 #define	CONTIG_MEM_SLAB_ARENA_QUANTUM	MMU_PAGESIZE64K
155 
156 /* contig_mem_arena import slab sizes, in decreasing size order */
157 static size_t contig_mem_import_sizes[] = {
158 	MMU_PAGESIZE4M,
159 	MMU_PAGESIZE512K,
160 	MMU_PAGESIZE64K
161 };
162 #define	NUM_IMPORT_SIZES	\
163 	(sizeof (contig_mem_import_sizes) / sizeof (size_t))
164 static size_t contig_mem_import_size_max	= MMU_PAGESIZE4M;
165 size_t contig_mem_slab_size			= MMU_PAGESIZE4M;
166 
167 /* Boot-time allocated buffer to pre-populate the contig_mem_arena */
168 static size_t prealloc_size;
169 static void *prealloc_buf;
170 
171 /*
172  * map_addr_proc() is the routine called when the system is to
173  * choose an address for the user.  We will pick an address
174  * range which is just below the current stack limit.  The
175  * algorithm used for cache consistency on machines with virtual
176  * address caches is such that offset 0 in the vnode is always
177  * on a shm_alignment'ed aligned address.  Unfortunately, this
178  * means that vnodes which are demand paged will not be mapped
179  * cache consistently with the executable images.  When the
180  * cache alignment for a given object is inconsistent, the
181  * lower level code must manage the translations so that this
182  * is not seen here (at the cost of efficiency, of course).
183  *
184  * addrp is a value/result parameter.
185  *	On input it is a hint from the user to be used in a completely
186  *	machine dependent fashion.  For MAP_ALIGN, addrp contains the
187  *	minimal alignment.
188  *
189  *	On output it is NULL if no address can be found in the current
190  *	processes address space or else an address that is currently
191  *	not mapped for len bytes with a page of red zone on either side.
192  *	If vacalign is true, then the selected address will obey the alignment
193  *	constraints of a vac machine based on the given off value.
194  */
195 /*ARGSUSED3*/
196 void
197 map_addr_proc(caddr_t *addrp, size_t len, offset_t off, int vacalign,
198     caddr_t userlimit, struct proc *p, uint_t flags)
199 {
200 	struct as *as = p->p_as;
201 	caddr_t addr;
202 	caddr_t base;
203 	size_t slen;
204 	uintptr_t align_amount;
205 	int allow_largepage_alignment = 1;
206 
207 	base = p->p_brkbase;
208 	if (userlimit < as->a_userlimit) {
209 		/*
210 		 * This happens when a program wants to map something in
211 		 * a range that's accessible to a program in a smaller
212 		 * address space.  For example, a 64-bit program might
213 		 * be calling mmap32(2) to guarantee that the returned
214 		 * address is below 4Gbytes.
215 		 */
216 		ASSERT(userlimit > base);
217 		slen = userlimit - base;
218 	} else {
219 		slen = p->p_usrstack - base - (((size_t)rctl_enforced_value(
220 		    rctlproc_legacy[RLIMIT_STACK], p->p_rctls, p) + PAGEOFFSET)
221 		    & PAGEMASK);
222 	}
223 	len = (len + PAGEOFFSET) & PAGEMASK;
224 
225 	/*
226 	 * Redzone for each side of the request. This is done to leave
227 	 * one page unmapped between segments. This is not required, but
228 	 * it's useful for the user because if their program strays across
229 	 * a segment boundary, it will catch a fault immediately making
230 	 * debugging a little easier.
231 	 */
232 	len += (2 * PAGESIZE);
233 
234 	/*
235 	 *  If the request is larger than the size of a particular
236 	 *  mmu level, then we use that level to map the request.
237 	 *  But this requires that both the virtual and the physical
238 	 *  addresses be aligned with respect to that level, so we
239 	 *  do the virtual bit of nastiness here.
240 	 *
241 	 *  For 32-bit processes, only those which have specified
242 	 *  MAP_ALIGN or an addr will be aligned on a page size > 4MB. Otherwise
243 	 *  we can potentially waste up to 256MB of the 4G process address
244 	 *  space just for alignment.
245 	 *
246 	 * XXXQ Should iterate trough hw_page_array here to catch
247 	 * all supported pagesizes
248 	 */
249 	if (p->p_model == DATAMODEL_ILP32 && ((flags & MAP_ALIGN) == 0 ||
250 	    ((uintptr_t)*addrp) != 0)) {
251 		allow_largepage_alignment = 0;
252 	}
253 	if ((mmu_page_sizes == max_mmu_page_sizes) &&
254 	    allow_largepage_alignment &&
255 		(len >= MMU_PAGESIZE256M)) {	/* 256MB mappings */
256 		align_amount = MMU_PAGESIZE256M;
257 	} else if ((mmu_page_sizes == max_mmu_page_sizes) &&
258 	    allow_largepage_alignment &&
259 		(len >= MMU_PAGESIZE32M)) {	/* 32MB mappings */
260 		align_amount = MMU_PAGESIZE32M;
261 	} else if (len >= MMU_PAGESIZE4M) {  /* 4MB mappings */
262 		align_amount = MMU_PAGESIZE4M;
263 	} else if (len >= MMU_PAGESIZE512K) { /* 512KB mappings */
264 		align_amount = MMU_PAGESIZE512K;
265 	} else if (len >= MMU_PAGESIZE64K) { /* 64KB mappings */
266 		align_amount = MMU_PAGESIZE64K;
267 	} else  {
268 		/*
269 		 * Align virtual addresses on a 64K boundary to ensure
270 		 * that ELF shared libraries are mapped with the appropriate
271 		 * alignment constraints by the run-time linker.
272 		 */
273 		align_amount = ELF_SPARC_MAXPGSZ;
274 		if ((flags & MAP_ALIGN) && ((uintptr_t)*addrp != 0) &&
275 			((uintptr_t)*addrp < align_amount))
276 			align_amount = (uintptr_t)*addrp;
277 	}
278 
279 	/*
280 	 * 64-bit processes require 1024K alignment of ELF shared libraries.
281 	 */
282 	if (p->p_model == DATAMODEL_LP64)
283 		align_amount = MAX(align_amount, ELF_SPARCV9_MAXPGSZ);
284 #ifdef VAC
285 	if (vac && vacalign && (align_amount < shm_alignment))
286 		align_amount = shm_alignment;
287 #endif
288 
289 	if ((flags & MAP_ALIGN) && ((uintptr_t)*addrp > align_amount)) {
290 		align_amount = (uintptr_t)*addrp;
291 	}
292 	len += align_amount;
293 
294 	/*
295 	 * Look for a large enough hole starting below the stack limit.
296 	 * After finding it, use the upper part.  Addition of PAGESIZE is
297 	 * for the redzone as described above.
298 	 */
299 	as_purge(as);
300 	if (as_gap(as, len, &base, &slen, AH_HI, NULL) == 0) {
301 		caddr_t as_addr;
302 
303 		addr = base + slen - len + PAGESIZE;
304 		as_addr = addr;
305 		/*
306 		 * Round address DOWN to the alignment amount,
307 		 * add the offset, and if this address is less
308 		 * than the original address, add alignment amount.
309 		 */
310 		addr = (caddr_t)((uintptr_t)addr & (~(align_amount - 1l)));
311 		addr += (long)(off & (align_amount - 1l));
312 		if (addr < as_addr) {
313 			addr += align_amount;
314 		}
315 
316 		ASSERT(addr <= (as_addr + align_amount));
317 		ASSERT(((uintptr_t)addr & (align_amount - 1l)) ==
318 		    ((uintptr_t)(off & (align_amount - 1l))));
319 		*addrp = addr;
320 
321 	} else {
322 		*addrp = NULL;	/* no more virtual space */
323 	}
324 }
325 
326 /*
327  * Platform-dependent page scrub call.
328  * We call hypervisor to scrub the page.
329  */
330 void
331 pagescrub(page_t *pp, uint_t off, uint_t len)
332 {
333 	uint64_t pa, length;
334 
335 	pa = (uint64_t)(pp->p_pagenum << MMU_PAGESHIFT + off);
336 	length = (uint64_t)len;
337 
338 	(void) mem_scrub(pa, length);
339 }
340 
341 void
342 sync_data_memory(caddr_t va, size_t len)
343 {
344 	/* Call memory sync function */
345 	(void) mem_sync(va, len);
346 }
347 
348 size_t
349 mmu_get_kernel_lpsize(size_t lpsize)
350 {
351 	extern int mmu_exported_pagesize_mask;
352 	uint_t tte;
353 
354 	if (lpsize == 0) {
355 		/* no setting for segkmem_lpsize in /etc/system: use default */
356 		if (mmu_exported_pagesize_mask & (1 << TTE256M)) {
357 			lpsize = MMU_PAGESIZE256M;
358 		} else if (mmu_exported_pagesize_mask & (1 << TTE4M)) {
359 			lpsize = MMU_PAGESIZE4M;
360 		} else if (mmu_exported_pagesize_mask & (1 << TTE64K)) {
361 			lpsize = MMU_PAGESIZE64K;
362 		} else {
363 			lpsize = MMU_PAGESIZE;
364 		}
365 
366 		return (lpsize);
367 	}
368 
369 	for (tte = TTE8K; tte <= TTE256M; tte++) {
370 
371 		if ((mmu_exported_pagesize_mask & (1 << tte)) == 0)
372 			continue;
373 
374 		if (lpsize == TTEBYTES(tte))
375 			return (lpsize);
376 	}
377 
378 	lpsize = TTEBYTES(TTE8K);
379 	return (lpsize);
380 }
381 
382 void
383 mmu_init_kcontext()
384 {
385 }
386 
387 /*ARGSUSED*/
388 void
389 mmu_init_kernel_pgsz(struct hat *hat)
390 {
391 }
392 
393 static void *
394 contig_mem_span_alloc(vmem_t *vmp, size_t size, int vmflag)
395 {
396 	page_t *ppl;
397 	page_t *rootpp;
398 	caddr_t addr = NULL;
399 	pgcnt_t npages = btopr(size);
400 	page_t **ppa;
401 	int pgflags;
402 	spgcnt_t i = 0;
403 
404 
405 	ASSERT(size <= contig_mem_import_size_max);
406 	ASSERT((size & (size - 1)) == 0);
407 
408 	if ((addr = vmem_xalloc(vmp, size, size, 0, 0,
409 	    NULL, NULL, vmflag)) == NULL) {
410 		return (NULL);
411 	}
412 
413 	/* The address should be slab-size aligned. */
414 	ASSERT(((uintptr_t)addr & (size - 1)) == 0);
415 
416 	if (page_resv(npages, vmflag & VM_KMFLAGS) == 0) {
417 		vmem_xfree(vmp, addr, size);
418 		return (NULL);
419 	}
420 
421 	pgflags = PG_EXCL;
422 	if (vmflag & VM_NORELOC)
423 		pgflags |= PG_NORELOC;
424 
425 	ppl = page_create_va_large(&kvp, (u_offset_t)(uintptr_t)addr, size,
426 	    pgflags, &kvseg, addr, NULL);
427 
428 	if (ppl == NULL) {
429 		vmem_xfree(vmp, addr, size);
430 		page_unresv(npages);
431 		return (NULL);
432 	}
433 
434 	rootpp = ppl;
435 	ppa = kmem_zalloc(npages * sizeof (page_t *), KM_SLEEP);
436 	while (ppl != NULL) {
437 		page_t *pp = ppl;
438 		ppa[i++] = pp;
439 		page_sub(&ppl, pp);
440 		ASSERT(page_iolock_assert(pp));
441 		ASSERT(PAGE_EXCL(pp));
442 		page_io_unlock(pp);
443 	}
444 
445 	/*
446 	 * Load the locked entry.  It's OK to preload the entry into
447 	 * the TSB since we now support large mappings in the kernel TSB.
448 	 */
449 	hat_memload_array(kas.a_hat, (caddr_t)rootpp->p_offset, size,
450 	    ppa, (PROT_ALL & ~PROT_USER) | HAT_NOSYNC, HAT_LOAD_LOCK);
451 
452 	ASSERT(i == page_get_pagecnt(ppa[0]->p_szc));
453 	for (--i; i >= 0; --i) {
454 		ASSERT(ppa[i]->p_szc == ppa[0]->p_szc);
455 		ASSERT(page_pptonum(ppa[i]) == page_pptonum(ppa[0]) + i);
456 		(void) page_pp_lock(ppa[i], 0, 1);
457 		/*
458 		 * Leave the page share locked. For non-cage pages,
459 		 * this would prevent memory DR if it were supported
460 		 * on sun4v.
461 		 */
462 		page_downgrade(ppa[i]);
463 	}
464 
465 	kmem_free(ppa, npages * sizeof (page_t *));
466 	return (addr);
467 }
468 
469 /*
470  * Allocates a slab by first trying to use the largest slab size
471  * in contig_mem_import_sizes and then falling back to smaller slab
472  * sizes still large enough for the allocation. The sizep argument
473  * is a pointer to the requested size. When a slab is successfully
474  * allocated, the slab size, which must be >= *sizep and <=
475  * contig_mem_import_size_max, is returned in the *sizep argument.
476  * Returns the virtual address of the new slab.
477  */
478 static void *
479 span_alloc_downsize(vmem_t *vmp, size_t *sizep, size_t align, int vmflag)
480 {
481 	int i;
482 
483 	ASSERT(*sizep <= contig_mem_import_size_max);
484 
485 	for (i = 0; i < NUM_IMPORT_SIZES; i++) {
486 		size_t page_size = contig_mem_import_sizes[i];
487 
488 		/*
489 		 * Check that the alignment is also less than the
490 		 * import (large page) size. In the case where the
491 		 * alignment is larger than the size, a large page
492 		 * large enough for the allocation is not necessarily
493 		 * physical-address aligned to satisfy the requested
494 		 * alignment. Since alignment is required to be a
495 		 * power-of-2, any large page >= size && >= align will
496 		 * suffice.
497 		 */
498 		if (*sizep <= page_size && align <= page_size) {
499 			void *addr;
500 			addr = contig_mem_span_alloc(vmp, page_size, vmflag);
501 			if (addr == NULL)
502 				continue;
503 			*sizep = page_size;
504 			return (addr);
505 		}
506 		return (NULL);
507 	}
508 
509 	return (NULL);
510 }
511 
512 static void *
513 contig_mem_span_xalloc(vmem_t *vmp, size_t *sizep, size_t align, int vmflag)
514 {
515 	return (span_alloc_downsize(vmp, sizep, align, vmflag | VM_NORELOC));
516 }
517 
518 static void *
519 contig_mem_reloc_span_xalloc(vmem_t *vmp, size_t *sizep, size_t align,
520     int vmflag)
521 {
522 	ASSERT((vmflag & VM_NORELOC) == 0);
523 	return (span_alloc_downsize(vmp, sizep, align, vmflag));
524 }
525 
526 /*
527  * Free a span, which is always exactly one large page.
528  */
529 static void
530 contig_mem_span_free(vmem_t *vmp, void *inaddr, size_t size)
531 {
532 	page_t *pp;
533 	caddr_t addr = inaddr;
534 	caddr_t eaddr;
535 	pgcnt_t npages = btopr(size);
536 	page_t *rootpp = NULL;
537 
538 	ASSERT(size <= contig_mem_import_size_max);
539 	/* All slabs should be size aligned */
540 	ASSERT(((uintptr_t)addr & (size - 1)) == 0);
541 
542 	hat_unload(kas.a_hat, addr, size, HAT_UNLOAD_UNLOCK);
543 
544 	for (eaddr = addr + size; addr < eaddr; addr += PAGESIZE) {
545 		pp = page_find(&kvp, (u_offset_t)(uintptr_t)addr);
546 		if (pp == NULL) {
547 			panic("contig_mem_span_free: page not found");
548 		}
549 		if (!page_tryupgrade(pp)) {
550 			page_unlock(pp);
551 			pp = page_lookup(&kvp,
552 			    (u_offset_t)(uintptr_t)addr, SE_EXCL);
553 			if (pp == NULL)
554 				panic("contig_mem_span_free: page not found");
555 		}
556 
557 		ASSERT(PAGE_EXCL(pp));
558 		ASSERT(size == page_get_pagesize(pp->p_szc));
559 		ASSERT(rootpp == NULL || rootpp->p_szc == pp->p_szc);
560 		ASSERT(rootpp == NULL || (page_pptonum(rootpp) +
561 		    (pgcnt_t)btop(addr - (caddr_t)inaddr) == page_pptonum(pp)));
562 
563 		page_pp_unlock(pp, 0, 1);
564 
565 		if (rootpp == NULL)
566 			rootpp = pp;
567 	}
568 	page_destroy_pages(rootpp);
569 	page_unresv(npages);
570 
571 	if (vmp != NULL)
572 		vmem_xfree(vmp, inaddr, size);
573 }
574 
575 static void *
576 contig_vmem_xalloc_aligned_wrapper(vmem_t *vmp, size_t *sizep, size_t align,
577     int vmflag)
578 {
579 	ASSERT((align & (align - 1)) == 0);
580 	return (vmem_xalloc(vmp, *sizep, align, 0, 0, NULL, NULL, vmflag));
581 }
582 
583 /*
584  * contig_mem_alloc, contig_mem_alloc_align
585  *
586  * Caution: contig_mem_alloc and contig_mem_alloc_align should be
587  * used only when physically contiguous non-relocatable memory is
588  * required. Furthermore, use of these allocation routines should be
589  * minimized as well as should the allocation size. As described in the
590  * contig_mem_arena comment block above, slab allocations fall back to
591  * being outside of the cage. Therefore, overuse of these allocation
592  * routines can lead to non-relocatable large pages being allocated
593  * outside the cage. Such pages prevent the allocation of a larger page
594  * occupying overlapping pages. This can impact performance for
595  * applications that utilize e.g. 256M large pages.
596  */
597 
598 /*
599  * Allocates size aligned contiguous memory up to contig_mem_import_size_max.
600  * Size must be a power of 2.
601  */
602 void *
603 contig_mem_alloc(size_t size)
604 {
605 	ASSERT((size & (size - 1)) == 0);
606 	return (contig_mem_alloc_align(size, size));
607 }
608 
609 /*
610  * contig_mem_alloc_align allocates real contiguous memory with the specified
611  * alignment up to contig_mem_import_size_max. The alignment must be a
612  * power of 2 and no greater than contig_mem_import_size_max. We assert
613  * the aligment is a power of 2. For non-debug, vmem_xalloc will panic
614  * for non power of 2 alignments.
615  */
616 void *
617 contig_mem_alloc_align(size_t size, size_t align)
618 {
619 	void *buf;
620 
621 	ASSERT(size <= contig_mem_import_size_max);
622 	ASSERT(align <= contig_mem_import_size_max);
623 	ASSERT((align & (align - 1)) == 0);
624 
625 	if (align < CONTIG_MEM_ARENA_QUANTUM)
626 		align = CONTIG_MEM_ARENA_QUANTUM;
627 
628 	/*
629 	 * We take the lock here to serialize span allocations.
630 	 * We do not lose concurrency for the common case, since
631 	 * allocations that don't require new span allocations
632 	 * are serialized by vmem_xalloc. Serializing span
633 	 * allocations also prevents us from trying to allocate
634 	 * more spans that necessary.
635 	 */
636 	mutex_enter(&contig_mem_lock);
637 
638 	buf = vmem_xalloc(contig_mem_arena, size, align, 0, 0,
639 	    NULL, NULL, VM_NOSLEEP | VM_NORELOC);
640 
641 	if ((buf == NULL) && (size <= MMU_PAGESIZE)) {
642 		mutex_exit(&contig_mem_lock);
643 		return (vmem_xalloc(static_alloc_arena, size, align, 0, 0,
644 		    NULL, NULL, VM_NOSLEEP));
645 	}
646 
647 	if (buf == NULL) {
648 		buf = vmem_xalloc(contig_mem_reloc_arena, size, align, 0, 0,
649 		    NULL, NULL, VM_NOSLEEP);
650 	}
651 
652 	mutex_exit(&contig_mem_lock);
653 
654 	return (buf);
655 }
656 
657 void
658 contig_mem_free(void *vaddr, size_t size)
659 {
660 	if (vmem_contains(contig_mem_arena, vaddr, size)) {
661 		vmem_xfree(contig_mem_arena, vaddr, size);
662 	} else if (size > MMU_PAGESIZE) {
663 		vmem_xfree(contig_mem_reloc_arena, vaddr, size);
664 	} else {
665 		vmem_xfree(static_alloc_arena, vaddr, size);
666 	}
667 }
668 
669 /*
670  * We create a set of stacked vmem arenas to enable us to
671  * allocate large >PAGESIZE chucks of contiguous Real Address space.
672  * The vmem_xcreate interface is used to create the contig_mem_arena
673  * allowing the import routine to downsize the requested slab size
674  * and return a smaller slab.
675  */
676 void
677 contig_mem_init(void)
678 {
679 	mutex_init(&contig_mem_lock, NULL, MUTEX_DEFAULT, NULL);
680 
681 	contig_mem_slab_arena = vmem_xcreate("contig_mem_slab_arena", NULL, 0,
682 	    CONTIG_MEM_SLAB_ARENA_QUANTUM, contig_vmem_xalloc_aligned_wrapper,
683 	    vmem_xfree, heap_arena, 0, VM_SLEEP | VMC_XALIGN);
684 
685 	contig_mem_arena = vmem_xcreate("contig_mem_arena", NULL, 0,
686 	    CONTIG_MEM_ARENA_QUANTUM, contig_mem_span_xalloc,
687 	    contig_mem_span_free, contig_mem_slab_arena, 0,
688 	    VM_SLEEP | VM_BESTFIT | VMC_XALIGN);
689 
690 	contig_mem_reloc_arena = vmem_xcreate("contig_mem_reloc_arena", NULL, 0,
691 	    CONTIG_MEM_ARENA_QUANTUM, contig_mem_reloc_span_xalloc,
692 	    contig_mem_span_free, contig_mem_slab_arena, 0,
693 	    VM_SLEEP | VM_BESTFIT | VMC_XALIGN);
694 
695 	if (vmem_add(contig_mem_arena, prealloc_buf, prealloc_size,
696 	    VM_SLEEP) == NULL)
697 		cmn_err(CE_PANIC, "Failed to pre-populate contig_mem_arena");
698 }
699 
700 /*
701  * In calculating how much memory to pre-allocate, we include a small
702  * amount per-CPU to account for per-CPU buffers in line with measured
703  * values for different size systems. contig_mem_prealloc_base is the
704  * base fixed amount to be preallocated before considering per-CPU
705  * requirements and memory size. We take the minimum of
706  * contig_mem_prealloc_base and a small percentage of physical memory
707  * to prevent allocating too much on smaller systems.
708  */
709 #define	PREALLOC_PER_CPU	(256 * 1024)		/* 256K */
710 #define	PREALLOC_PERCENT	(4)			/* 4% */
711 #define	PREALLOC_MIN		(16 * 1024 * 1024)	/* 16M */
712 size_t contig_mem_prealloc_base = 0;
713 
714 /*
715  * Called at boot-time allowing pre-allocation of contiguous memory.
716  * The argument 'alloc_base' is the requested base address for the
717  * allocation and originates in startup_memlist.
718  */
719 caddr_t
720 contig_mem_prealloc(caddr_t alloc_base, pgcnt_t npages)
721 {
722 	prealloc_size = MIN((PREALLOC_PER_CPU * ncpu_guest_max) +
723 	    contig_mem_prealloc_base, (ptob(npages) * PREALLOC_PERCENT) / 100);
724 	prealloc_size = MAX(prealloc_size, PREALLOC_MIN);
725 	prealloc_size = P2ROUNDUP(prealloc_size, MMU_PAGESIZE4M);
726 
727 	alloc_base = (caddr_t)roundup((uintptr_t)alloc_base, MMU_PAGESIZE4M);
728 	prealloc_buf = alloc_base;
729 	alloc_base += prealloc_size;
730 
731 	return (alloc_base);
732 }
733 
734 static uint_t sp_color_stride = 16;
735 static uint_t sp_color_mask = 0x1f;
736 static uint_t sp_current_color = (uint_t)-1;
737 
738 size_t
739 exec_get_spslew(void)
740 {
741 	uint_t spcolor = atomic_inc_32_nv(&sp_current_color);
742 	return ((size_t)((spcolor & sp_color_mask) * SA(sp_color_stride)));
743 }
744