xref: /freebsd/sys/vm/vm_glue.c (revision e9ac41698b2f322d55ccf9da50a3596edb2c1800)
1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *
35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36  * All rights reserved.
37  *
38  * Permission to use, copy, modify and distribute this software and
39  * its documentation is hereby granted, provided that both the copyright
40  * notice and this permission notice appear in all copies of the
41  * software, derivative works or modified versions, and any portions
42  * thereof, and that both notices appear in supporting documentation.
43  *
44  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
45  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
46  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
47  *
48  * Carnegie Mellon requests users of this software to return to
49  *
50  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
51  *  School of Computer Science
52  *  Carnegie Mellon University
53  *  Pittsburgh PA 15213-3890
54  *
55  * any improvements or extensions that they make and grant Carnegie the
56  * rights to redistribute these changes.
57  */
58 
59 #include <sys/cdefs.h>
60 #include "opt_vm.h"
61 #include "opt_kstack_pages.h"
62 #include "opt_kstack_max_pages.h"
63 #include "opt_kstack_usage_prof.h"
64 
65 #include <sys/param.h>
66 #include <sys/systm.h>
67 #include <sys/asan.h>
68 #include <sys/domainset.h>
69 #include <sys/limits.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/msan.h>
73 #include <sys/mutex.h>
74 #include <sys/proc.h>
75 #include <sys/racct.h>
76 #include <sys/refcount.h>
77 #include <sys/resourcevar.h>
78 #include <sys/rwlock.h>
79 #include <sys/sched.h>
80 #include <sys/sf_buf.h>
81 #include <sys/shm.h>
82 #include <sys/smp.h>
83 #include <sys/vmmeter.h>
84 #include <sys/vmem.h>
85 #include <sys/sx.h>
86 #include <sys/sysctl.h>
87 #include <sys/kernel.h>
88 #include <sys/ktr.h>
89 #include <sys/unistd.h>
90 
91 #include <vm/uma.h>
92 #include <vm/vm.h>
93 #include <vm/vm_param.h>
94 #include <vm/pmap.h>
95 #include <vm/vm_domainset.h>
96 #include <vm/vm_map.h>
97 #include <vm/vm_page.h>
98 #include <vm/vm_pageout.h>
99 #include <vm/vm_pagequeue.h>
100 #include <vm/vm_object.h>
101 #include <vm/vm_kern.h>
102 #include <vm/vm_extern.h>
103 #include <vm/vm_pager.h>
104 #include <vm/swap_pager.h>
105 #include <vm/vm_phys.h>
106 
107 #include <machine/cpu.h>
108 
109 #if VM_NRESERVLEVEL > 1
110 #define KVA_KSTACK_QUANTUM_SHIFT (VM_LEVEL_1_ORDER + VM_LEVEL_0_ORDER + \
111     PAGE_SHIFT)
112 #elif VM_NRESERVLEVEL > 0
113 #define KVA_KSTACK_QUANTUM_SHIFT (VM_LEVEL_0_ORDER + PAGE_SHIFT)
114 #else
115 #define KVA_KSTACK_QUANTUM_SHIFT (8 + PAGE_SHIFT)
116 #endif
117 #define KVA_KSTACK_QUANTUM (1ul << KVA_KSTACK_QUANTUM_SHIFT)
118 
119 /*
120  * MPSAFE
121  *
122  * WARNING!  This code calls vm_map_check_protection() which only checks
123  * the associated vm_map_entry range.  It does not determine whether the
124  * contents of the memory is actually readable or writable.  In most cases
125  * just checking the vm_map_entry is sufficient within the kernel's address
126  * space.
127  */
128 bool
129 kernacc(void *addr, int len, int rw)
130 {
131 	boolean_t rv;
132 	vm_offset_t saddr, eaddr;
133 	vm_prot_t prot;
134 
135 	KASSERT((rw & ~VM_PROT_ALL) == 0,
136 	    ("illegal ``rw'' argument to kernacc (%x)\n", rw));
137 
138 	if ((vm_offset_t)addr + len > vm_map_max(kernel_map) ||
139 	    (vm_offset_t)addr + len < (vm_offset_t)addr)
140 		return (false);
141 
142 	prot = rw;
143 	saddr = trunc_page((vm_offset_t)addr);
144 	eaddr = round_page((vm_offset_t)addr + len);
145 	vm_map_lock_read(kernel_map);
146 	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
147 	vm_map_unlock_read(kernel_map);
148 	return (rv == TRUE);
149 }
150 
151 /*
152  * MPSAFE
153  *
154  * WARNING!  This code calls vm_map_check_protection() which only checks
155  * the associated vm_map_entry range.  It does not determine whether the
156  * contents of the memory is actually readable or writable.  vmapbuf(),
157  * vm_fault_quick(), or copyin()/copout()/su*()/fu*() functions should be
158  * used in conjunction with this call.
159  */
160 bool
161 useracc(void *addr, int len, int rw)
162 {
163 	boolean_t rv;
164 	vm_prot_t prot;
165 	vm_map_t map;
166 
167 	KASSERT((rw & ~VM_PROT_ALL) == 0,
168 	    ("illegal ``rw'' argument to useracc (%x)\n", rw));
169 	prot = rw;
170 	map = &curproc->p_vmspace->vm_map;
171 	if ((vm_offset_t)addr + len > vm_map_max(map) ||
172 	    (vm_offset_t)addr + len < (vm_offset_t)addr) {
173 		return (false);
174 	}
175 	vm_map_lock_read(map);
176 	rv = vm_map_check_protection(map, trunc_page((vm_offset_t)addr),
177 	    round_page((vm_offset_t)addr + len), prot);
178 	vm_map_unlock_read(map);
179 	return (rv == TRUE);
180 }
181 
182 int
183 vslock(void *addr, size_t len)
184 {
185 	vm_offset_t end, last, start;
186 	vm_size_t npages;
187 	int error;
188 
189 	last = (vm_offset_t)addr + len;
190 	start = trunc_page((vm_offset_t)addr);
191 	end = round_page(last);
192 	if (last < (vm_offset_t)addr || end < (vm_offset_t)addr)
193 		return (EINVAL);
194 	npages = atop(end - start);
195 	if (npages > vm_page_max_user_wired)
196 		return (ENOMEM);
197 	error = vm_map_wire(&curproc->p_vmspace->vm_map, start, end,
198 	    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
199 	if (error == KERN_SUCCESS) {
200 		curthread->td_vslock_sz += len;
201 		return (0);
202 	}
203 
204 	/*
205 	 * Return EFAULT on error to match copy{in,out}() behaviour
206 	 * rather than returning ENOMEM like mlock() would.
207 	 */
208 	return (EFAULT);
209 }
210 
211 void
212 vsunlock(void *addr, size_t len)
213 {
214 
215 	/* Rely on the parameter sanity checks performed by vslock(). */
216 	MPASS(curthread->td_vslock_sz >= len);
217 	curthread->td_vslock_sz -= len;
218 	(void)vm_map_unwire(&curproc->p_vmspace->vm_map,
219 	    trunc_page((vm_offset_t)addr), round_page((vm_offset_t)addr + len),
220 	    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
221 }
222 
223 /*
224  * Pin the page contained within the given object at the given offset.  If the
225  * page is not resident, allocate and load it using the given object's pager.
226  * Return the pinned page if successful; otherwise, return NULL.
227  */
228 static vm_page_t
229 vm_imgact_hold_page(vm_object_t object, vm_ooffset_t offset)
230 {
231 	vm_page_t m;
232 	vm_pindex_t pindex;
233 
234 	pindex = OFF_TO_IDX(offset);
235 	(void)vm_page_grab_valid_unlocked(&m, object, pindex,
236 	    VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
237 	return (m);
238 }
239 
240 /*
241  * Return a CPU private mapping to the page at the given offset within the
242  * given object.  The page is pinned before it is mapped.
243  */
244 struct sf_buf *
245 vm_imgact_map_page(vm_object_t object, vm_ooffset_t offset)
246 {
247 	vm_page_t m;
248 
249 	m = vm_imgact_hold_page(object, offset);
250 	if (m == NULL)
251 		return (NULL);
252 	sched_pin();
253 	return (sf_buf_alloc(m, SFB_CPUPRIVATE));
254 }
255 
256 /*
257  * Destroy the given CPU private mapping and unpin the page that it mapped.
258  */
259 void
260 vm_imgact_unmap_page(struct sf_buf *sf)
261 {
262 	vm_page_t m;
263 
264 	m = sf_buf_page(sf);
265 	sf_buf_free(sf);
266 	sched_unpin();
267 	vm_page_unwire(m, PQ_ACTIVE);
268 }
269 
270 void
271 vm_sync_icache(vm_map_t map, vm_offset_t va, vm_offset_t sz)
272 {
273 
274 	pmap_sync_icache(map->pmap, va, sz);
275 }
276 
277 static vm_object_t kstack_object;
278 static vm_object_t kstack_alt_object;
279 static uma_zone_t kstack_cache;
280 static int kstack_cache_size;
281 static vmem_t *vmd_kstack_arena[MAXMEMDOM];
282 
283 static int
284 sysctl_kstack_cache_size(SYSCTL_HANDLER_ARGS)
285 {
286 	int error, oldsize;
287 
288 	oldsize = kstack_cache_size;
289 	error = sysctl_handle_int(oidp, arg1, arg2, req);
290 	if (error == 0 && req->newptr && oldsize != kstack_cache_size)
291 		uma_zone_set_maxcache(kstack_cache, kstack_cache_size);
292 	return (error);
293 }
294 SYSCTL_PROC(_vm, OID_AUTO, kstack_cache_size,
295     CTLTYPE_INT|CTLFLAG_MPSAFE|CTLFLAG_RW, &kstack_cache_size, 0,
296     sysctl_kstack_cache_size, "IU", "Maximum number of cached kernel stacks");
297 
298 /*
299  *	Allocate a virtual address range from a domain kstack arena, following
300  *	the specified NUMA policy.
301  */
302 static vm_offset_t
303 vm_thread_alloc_kstack_kva(vm_size_t size, int domain)
304 {
305 #ifndef __ILP32__
306 	int rv;
307 	vmem_t *arena;
308 	vm_offset_t addr = 0;
309 
310 	size = round_page(size);
311 	/* Allocate from the kernel arena for non-standard kstack sizes. */
312 	if (size != ptoa(kstack_pages + KSTACK_GUARD_PAGES)) {
313 		arena = vm_dom[domain].vmd_kernel_arena;
314 	} else {
315 		arena = vmd_kstack_arena[domain];
316 	}
317 	rv = vmem_alloc(arena, size, M_BESTFIT | M_NOWAIT, &addr);
318 	if (rv == ENOMEM)
319 		return (0);
320 	KASSERT(atop(addr - VM_MIN_KERNEL_ADDRESS) %
321 	    (kstack_pages + KSTACK_GUARD_PAGES) == 0,
322 	    ("%s: allocated kstack KVA not aligned to multiple of kstack size",
323 	    __func__));
324 
325 	return (addr);
326 #else
327 	return (kva_alloc(size));
328 #endif
329 }
330 
331 /*
332  *	Release a region of kernel virtual memory
333  *	allocated from the kstack arena.
334  */
335 static __noinline void
336 vm_thread_free_kstack_kva(vm_offset_t addr, vm_size_t size, int domain)
337 {
338 	vmem_t *arena;
339 
340 	size = round_page(size);
341 #ifdef __ILP32__
342 	arena = kernel_arena;
343 #else
344 	arena = vmd_kstack_arena[domain];
345 	if (size != ptoa(kstack_pages + KSTACK_GUARD_PAGES)) {
346 		arena = vm_dom[domain].vmd_kernel_arena;
347 	}
348 #endif
349 	vmem_free(arena, addr, size);
350 }
351 
352 static vmem_size_t
353 vm_thread_kstack_import_quantum(void)
354 {
355 #ifndef __ILP32__
356 	/*
357 	 * The kstack_quantum is larger than KVA_QUANTUM to account
358 	 * for holes induced by guard pages.
359 	 */
360 	return (KVA_KSTACK_QUANTUM * (kstack_pages + KSTACK_GUARD_PAGES));
361 #else
362 	return (KVA_KSTACK_QUANTUM);
363 #endif
364 }
365 
366 /*
367  * Import KVA from a parent arena into the kstack arena. Imports must be
368  * a multiple of kernel stack pages + guard pages in size.
369  *
370  * Kstack VA allocations need to be aligned so that the linear KVA pindex
371  * is divisible by the total number of kstack VA pages. This is necessary to
372  * make vm_kstack_pindex work properly.
373  *
374  * We import a multiple of KVA_KSTACK_QUANTUM-sized region from the parent
375  * arena. The actual size used by the kstack arena is one kstack smaller to
376  * allow for the necessary alignment adjustments to be made.
377  */
378 static int
379 vm_thread_kstack_arena_import(void *arena, vmem_size_t size, int flags,
380     vmem_addr_t *addrp)
381 {
382 	int error, rem;
383 	size_t kpages = kstack_pages + KSTACK_GUARD_PAGES;
384 
385 	KASSERT(atop(size) % kpages == 0,
386 	    ("%s: Size %jd is not a multiple of kstack pages (%d)", __func__,
387 	    (intmax_t)size, (int)kpages));
388 
389 	error = vmem_xalloc(arena, vm_thread_kstack_import_quantum(),
390 	    KVA_KSTACK_QUANTUM, 0, 0, VMEM_ADDR_MIN, VMEM_ADDR_MAX, flags,
391 	    addrp);
392 	if (error) {
393 		return (error);
394 	}
395 
396 	rem = atop(*addrp - VM_MIN_KERNEL_ADDRESS) % kpages;
397 	if (rem != 0) {
398 		/* Bump addr to next aligned address */
399 		*addrp = *addrp + (kpages - rem) * PAGE_SIZE;
400 	}
401 
402 	return (0);
403 }
404 
405 /*
406  * Release KVA from a parent arena into the kstack arena. Released imports must
407  * be a multiple of kernel stack pages + guard pages in size.
408  */
409 static void
410 vm_thread_kstack_arena_release(void *arena, vmem_addr_t addr, vmem_size_t size)
411 {
412 	int rem;
413 	size_t kpages __diagused = kstack_pages + KSTACK_GUARD_PAGES;
414 
415 	KASSERT(size % kpages == 0,
416 	    ("%s: Size %jd is not a multiple of kstack pages (%d)", __func__,
417 	    (intmax_t)size, (int)kpages));
418 
419 	KASSERT((addr - VM_MIN_KERNEL_ADDRESS) % kpages == 0,
420 	    ("%s: Address %p is not properly aligned (%p)", __func__,
421 		(void *)addr, (void *)VM_MIN_KERNEL_ADDRESS));
422 	/*
423 	 * If the address is not KVA_KSTACK_QUANTUM-aligned we have to decrement
424 	 * it to account for the shift in kva_import_kstack.
425 	 */
426 	rem = addr % KVA_KSTACK_QUANTUM;
427 	if (rem) {
428 		KASSERT(rem <= ptoa(kpages),
429 		    ("%s: rem > kpages (%d), (%d)", __func__, rem,
430 			(int)kpages));
431 		addr -= rem;
432 	}
433 	vmem_xfree(arena, addr, vm_thread_kstack_import_quantum());
434 }
435 
436 /*
437  * Create the kernel stack for a new thread.
438  */
439 static vm_offset_t
440 vm_thread_stack_create(struct domainset *ds, int pages)
441 {
442 	vm_page_t ma[KSTACK_MAX_PAGES];
443 	struct vm_domainset_iter di;
444 	int req = VM_ALLOC_NORMAL;
445 	vm_object_t obj;
446 	vm_offset_t ks;
447 	int domain, i;
448 
449 	obj = vm_thread_kstack_size_to_obj(pages);
450 	if (vm_ndomains > 1)
451 		obj->domain.dr_policy = ds;
452 	vm_domainset_iter_page_init(&di, obj, 0, &domain, &req);
453 	do {
454 		/*
455 		 * Get a kernel virtual address for this thread's kstack.
456 		 */
457 		ks = vm_thread_alloc_kstack_kva(ptoa(pages + KSTACK_GUARD_PAGES),
458 		    domain);
459 		if (ks == 0)
460 			continue;
461 		ks += ptoa(KSTACK_GUARD_PAGES);
462 
463 		/*
464 		 * Allocate physical pages to back the stack.
465 		 */
466 		if (vm_thread_stack_back(ks, ma, pages, req, domain) != 0) {
467 			vm_thread_free_kstack_kva(ks - ptoa(KSTACK_GUARD_PAGES),
468 			    ptoa(pages + KSTACK_GUARD_PAGES), domain);
469 			continue;
470 		}
471 		if (KSTACK_GUARD_PAGES != 0) {
472 			pmap_qremove(ks - ptoa(KSTACK_GUARD_PAGES),
473 			    KSTACK_GUARD_PAGES);
474 		}
475 		for (i = 0; i < pages; i++)
476 			vm_page_valid(ma[i]);
477 		pmap_qenter(ks, ma, pages);
478 		return (ks);
479 	} while (vm_domainset_iter_page(&di, obj, &domain) == 0);
480 
481 	return (0);
482 }
483 
484 static __noinline void
485 vm_thread_stack_dispose(vm_offset_t ks, int pages)
486 {
487 	vm_page_t m;
488 	vm_pindex_t pindex;
489 	int i, domain;
490 	vm_object_t obj = vm_thread_kstack_size_to_obj(pages);
491 
492 	pindex = vm_kstack_pindex(ks, pages);
493 	domain = vm_phys_domain(vtophys(ks));
494 	pmap_qremove(ks, pages);
495 	VM_OBJECT_WLOCK(obj);
496 	for (i = 0; i < pages; i++) {
497 		m = vm_page_lookup(obj, pindex + i);
498 		if (m == NULL)
499 			panic("%s: kstack already missing?", __func__);
500 		KASSERT(vm_page_domain(m) == domain,
501 		    ("%s: page %p domain mismatch, expected %d got %d",
502 		    __func__, m, domain, vm_page_domain(m)));
503 		vm_page_xbusy_claim(m);
504 		vm_page_unwire_noq(m);
505 		vm_page_free(m);
506 	}
507 	VM_OBJECT_WUNLOCK(obj);
508 	kasan_mark((void *)ks, ptoa(pages), ptoa(pages), 0);
509 	vm_thread_free_kstack_kva(ks - (KSTACK_GUARD_PAGES * PAGE_SIZE),
510 	    ptoa(pages + KSTACK_GUARD_PAGES), domain);
511 }
512 
513 /*
514  * Allocate the kernel stack for a new thread.
515  */
516 int
517 vm_thread_new(struct thread *td, int pages)
518 {
519 	vm_offset_t ks;
520 	u_short ks_domain;
521 
522 	/* Bounds check */
523 	if (pages <= 1)
524 		pages = kstack_pages;
525 	else if (pages > KSTACK_MAX_PAGES)
526 		pages = KSTACK_MAX_PAGES;
527 
528 	ks = 0;
529 	if (pages == kstack_pages && kstack_cache != NULL)
530 		ks = (vm_offset_t)uma_zalloc(kstack_cache, M_NOWAIT);
531 
532 	/*
533 	 * Ensure that kstack objects can draw pages from any memory
534 	 * domain.  Otherwise a local memory shortage can block a process
535 	 * swap-in.
536 	 */
537 	if (ks == 0)
538 		ks = vm_thread_stack_create(DOMAINSET_PREF(PCPU_GET(domain)),
539 		    pages);
540 	if (ks == 0)
541 		return (0);
542 
543 	ks_domain = vm_phys_domain(vtophys(ks));
544 	KASSERT(ks_domain >= 0 && ks_domain < vm_ndomains,
545 	    ("%s: invalid domain for kstack %p", __func__, (void *)ks));
546 	td->td_kstack = ks;
547 	td->td_kstack_pages = pages;
548 	td->td_kstack_domain = ks_domain;
549 	return (1);
550 }
551 
552 /*
553  * Dispose of a thread's kernel stack.
554  */
555 void
556 vm_thread_dispose(struct thread *td)
557 {
558 	vm_offset_t ks;
559 	int pages;
560 
561 	pages = td->td_kstack_pages;
562 	ks = td->td_kstack;
563 	td->td_kstack = 0;
564 	td->td_kstack_pages = 0;
565 	td->td_kstack_domain = MAXMEMDOM;
566 	if (pages == kstack_pages) {
567 		kasan_mark((void *)ks, 0, ptoa(pages), KASAN_KSTACK_FREED);
568 		uma_zfree(kstack_cache, (void *)ks);
569 	} else {
570 		vm_thread_stack_dispose(ks, pages);
571 	}
572 }
573 
574 /*
575  * Calculate kstack pindex.
576  *
577  * Uses a non-identity mapping if guard pages are
578  * active to avoid pindex holes in the kstack object.
579  */
580 vm_pindex_t
581 vm_kstack_pindex(vm_offset_t ks, int kpages)
582 {
583 	vm_pindex_t pindex = atop(ks - VM_MIN_KERNEL_ADDRESS);
584 
585 #ifdef __ILP32__
586 	return (pindex);
587 #else
588 	/*
589 	 * Return the linear pindex if guard pages aren't active or if we are
590 	 * allocating a non-standard kstack size.
591 	 */
592 	if (KSTACK_GUARD_PAGES == 0 || kpages != kstack_pages) {
593 		return (pindex);
594 	}
595 	KASSERT(pindex % (kpages + KSTACK_GUARD_PAGES) >= KSTACK_GUARD_PAGES,
596 	    ("%s: Attempting to calculate kstack guard page pindex", __func__));
597 
598 	return (pindex -
599 	    (pindex / (kpages + KSTACK_GUARD_PAGES) + 1) * KSTACK_GUARD_PAGES);
600 #endif
601 }
602 
603 /*
604  * Allocate physical pages, following the specified NUMA policy, to back a
605  * kernel stack.
606  */
607 int
608 vm_thread_stack_back(vm_offset_t ks, vm_page_t ma[], int npages, int req_class,
609     int domain)
610 {
611 	vm_object_t obj = vm_thread_kstack_size_to_obj(npages);
612 	vm_pindex_t pindex;
613 	vm_page_t m;
614 	int n;
615 
616 	pindex = vm_kstack_pindex(ks, npages);
617 
618 	VM_OBJECT_WLOCK(obj);
619 	for (n = 0; n < npages;) {
620 		m = vm_page_grab(obj, pindex + n,
621 		    VM_ALLOC_NOCREAT | VM_ALLOC_WIRED);
622 		if (m == NULL) {
623 			m = vm_page_alloc_domain(obj, pindex + n, domain,
624 			    req_class | VM_ALLOC_WIRED);
625 		}
626 		if (m == NULL)
627 			break;
628 		ma[n++] = m;
629 	}
630 	if (n < npages)
631 		goto cleanup;
632 	VM_OBJECT_WUNLOCK(obj);
633 
634 	return (0);
635 cleanup:
636 	for (int i = 0; i < n; i++) {
637 		m = ma[i];
638 		(void)vm_page_unwire_noq(m);
639 		vm_page_free(m);
640 	}
641 	VM_OBJECT_WUNLOCK(obj);
642 
643 	return (ENOMEM);
644 }
645 
646 vm_object_t
647 vm_thread_kstack_size_to_obj(int npages)
648 {
649 	return (npages == kstack_pages ? kstack_object : kstack_alt_object);
650 }
651 
652 static int
653 kstack_import(void *arg, void **store, int cnt, int domain, int flags)
654 {
655 	struct domainset *ds;
656 	int i;
657 
658 	if (domain == UMA_ANYDOMAIN)
659 		ds = DOMAINSET_RR();
660 	else
661 		ds = DOMAINSET_PREF(domain);
662 
663 	for (i = 0; i < cnt; i++) {
664 		store[i] = (void *)vm_thread_stack_create(ds, kstack_pages);
665 		if (store[i] == NULL)
666 			break;
667 	}
668 	return (i);
669 }
670 
671 static void
672 kstack_release(void *arg, void **store, int cnt)
673 {
674 	vm_offset_t ks;
675 	int i;
676 
677 	for (i = 0; i < cnt; i++) {
678 		ks = (vm_offset_t)store[i];
679 		vm_thread_stack_dispose(ks, kstack_pages);
680 	}
681 }
682 
683 static void
684 kstack_cache_init(void *null)
685 {
686 	vm_size_t kstack_quantum;
687 	int domain;
688 
689 	kstack_object = vm_object_allocate(OBJT_SWAP,
690 	    atop(VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS));
691 	kstack_cache = uma_zcache_create("kstack_cache",
692 	    kstack_pages * PAGE_SIZE, NULL, NULL, NULL, NULL,
693 	    kstack_import, kstack_release, NULL,
694 	    UMA_ZONE_FIRSTTOUCH);
695 	kstack_cache_size = imax(128, mp_ncpus * 4);
696 	uma_zone_set_maxcache(kstack_cache, kstack_cache_size);
697 
698 	kstack_alt_object = vm_object_allocate(OBJT_SWAP,
699 	    atop(VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS));
700 
701 	kstack_quantum = vm_thread_kstack_import_quantum();
702 	/*
703 	 * Reduce size used by the kstack arena to allow for
704 	 * alignment adjustments in vm_thread_kstack_arena_import.
705 	 */
706 	kstack_quantum -= (kstack_pages + KSTACK_GUARD_PAGES) * PAGE_SIZE;
707 	/*
708 	 * Create the kstack_arena for each domain and set kernel_arena as
709 	 * parent.
710 	 */
711 	for (domain = 0; domain < vm_ndomains; domain++) {
712 		vmd_kstack_arena[domain] = vmem_create("kstack arena", 0, 0,
713 		    PAGE_SIZE, 0, M_WAITOK);
714 		KASSERT(vmd_kstack_arena[domain] != NULL,
715 		    ("%s: failed to create domain %d kstack_arena", __func__,
716 		    domain));
717 		vmem_set_import(vmd_kstack_arena[domain],
718 		    vm_thread_kstack_arena_import,
719 		    vm_thread_kstack_arena_release,
720 		    vm_dom[domain].vmd_kernel_arena, kstack_quantum);
721 	}
722 }
723 SYSINIT(vm_kstacks, SI_SUB_KMEM, SI_ORDER_ANY, kstack_cache_init, NULL);
724 
725 #ifdef KSTACK_USAGE_PROF
726 /*
727  * Track maximum stack used by a thread in kernel.
728  */
729 static int max_kstack_used;
730 
731 SYSCTL_INT(_debug, OID_AUTO, max_kstack_used, CTLFLAG_RD,
732     &max_kstack_used, 0,
733     "Maximum stack depth used by a thread in kernel");
734 
735 void
736 intr_prof_stack_use(struct thread *td, struct trapframe *frame)
737 {
738 	vm_offset_t stack_top;
739 	vm_offset_t current;
740 	int used, prev_used;
741 
742 	/*
743 	 * Testing for interrupted kernel mode isn't strictly
744 	 * needed. It optimizes the execution, since interrupts from
745 	 * usermode will have only the trap frame on the stack.
746 	 */
747 	if (TRAPF_USERMODE(frame))
748 		return;
749 
750 	stack_top = td->td_kstack + td->td_kstack_pages * PAGE_SIZE;
751 	current = (vm_offset_t)(uintptr_t)&stack_top;
752 
753 	/*
754 	 * Try to detect if interrupt is using kernel thread stack.
755 	 * Hardware could use a dedicated stack for interrupt handling.
756 	 */
757 	if (stack_top <= current || current < td->td_kstack)
758 		return;
759 
760 	used = stack_top - current;
761 	for (;;) {
762 		prev_used = max_kstack_used;
763 		if (prev_used >= used)
764 			break;
765 		if (atomic_cmpset_int(&max_kstack_used, prev_used, used))
766 			break;
767 	}
768 }
769 #endif /* KSTACK_USAGE_PROF */
770 
771 /*
772  * Implement fork's actions on an address space.
773  * Here we arrange for the address space to be copied or referenced,
774  * allocate a user struct (pcb and kernel stack), then call the
775  * machine-dependent layer to fill those in and make the new process
776  * ready to run.  The new process is set up so that it returns directly
777  * to user mode to avoid stack copying and relocation problems.
778  */
779 int
780 vm_forkproc(struct thread *td, struct proc *p2, struct thread *td2,
781     struct vmspace *vm2, int flags)
782 {
783 	struct proc *p1 = td->td_proc;
784 	struct domainset *dset;
785 	int error;
786 
787 	if ((flags & RFPROC) == 0) {
788 		/*
789 		 * Divorce the memory, if it is shared, essentially
790 		 * this changes shared memory amongst threads, into
791 		 * COW locally.
792 		 */
793 		if ((flags & RFMEM) == 0) {
794 			error = vmspace_unshare(p1);
795 			if (error)
796 				return (error);
797 		}
798 		cpu_fork(td, p2, td2, flags);
799 		return (0);
800 	}
801 
802 	if (flags & RFMEM) {
803 		p2->p_vmspace = p1->p_vmspace;
804 		refcount_acquire(&p1->p_vmspace->vm_refcnt);
805 	}
806 	dset = td2->td_domain.dr_policy;
807 	while (vm_page_count_severe_set(&dset->ds_mask)) {
808 		vm_wait_doms(&dset->ds_mask, 0);
809 	}
810 
811 	if ((flags & RFMEM) == 0) {
812 		p2->p_vmspace = vm2;
813 		if (p1->p_vmspace->vm_shm)
814 			shmfork(p1, p2);
815 	}
816 
817 	/*
818 	 * cpu_fork will copy and update the pcb, set up the kernel stack,
819 	 * and make the child ready to run.
820 	 */
821 	cpu_fork(td, p2, td2, flags);
822 	return (0);
823 }
824 
825 /*
826  * Called after process has been wait(2)'ed upon and is being reaped.
827  * The idea is to reclaim resources that we could not reclaim while
828  * the process was still executing.
829  */
830 void
831 vm_waitproc(struct proc *p)
832 {
833 
834 	vmspace_exitfree(p);		/* and clean-out the vmspace */
835 }
836 
837 void
838 kick_proc0(void)
839 {
840 
841 	wakeup(&proc0);
842 }
843