Home | History | Annotate | Line # | Download | only in kern
subr_kmem.c revision 1.66.2.1
      1 /*	$NetBSD: subr_kmem.c,v 1.66.2.1 2018/09/06 06:56:42 pgoyette Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2009-2015 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Doran and Maxime Villard.
      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  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c)2006 YAMAMOTO Takashi,
     34  * All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  *
     45  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     55  * SUCH DAMAGE.
     56  */
     57 
     58 /*
     59  * Allocator of kernel wired memory. This allocator has some debug features
     60  * enabled with "option DIAGNOSTIC" and "option DEBUG".
     61  */
     62 
     63 /*
     64  * KMEM_SIZE: detect alloc/free size mismatch bugs.
     65  *	Prefix each allocations with a fixed-sized, aligned header and record
     66  *	the exact user-requested allocation size in it. When freeing, compare
     67  *	it with kmem_free's "size" argument.
     68  *
     69  * This option enabled on DIAGNOSTIC.
     70  *
     71  *  |CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|
     72  *  +-----+-----+-----+-----+-----+-----+-----+-----+-----+---+-+
     73  *  |/////|     |     |     |     |     |     |     |     |   |U|
     74  *  |/HSZ/|     |     |     |     |     |     |     |     |   |U|
     75  *  |/////|     |     |     |     |     |     |     |     |   |U|
     76  *  +-----+-----+-----+-----+-----+-----+-----+-----+-----+---+-+
     77  *  |Size |    Buffer usable by the caller (requested size)   |Unused\
     78  */
     79 
     80 /*
     81  * KMEM_GUARD
     82  *	A kernel with "option DEBUG" has "kmem_guard" debugging feature compiled
     83  *	in. See the comment below for what kind of bugs it tries to detect. Even
     84  *	if compiled in, it's disabled by default because it's very expensive.
     85  *	You can enable it on boot by:
     86  *		boot -d
     87  *		db> w kmem_guard_depth 0t30000
     88  *		db> c
     89  *
     90  *	The default value of kmem_guard_depth is 0, which means disabled.
     91  *	It can be changed by KMEM_GUARD_DEPTH kernel config option.
     92  */
     93 
     94 #include <sys/cdefs.h>
     95 __KERNEL_RCSID(0, "$NetBSD: subr_kmem.c,v 1.66.2.1 2018/09/06 06:56:42 pgoyette Exp $");
     96 
     97 #ifdef _KERNEL_OPT
     98 #include "opt_kmem.h"
     99 #endif
    100 
    101 #include <sys/param.h>
    102 #include <sys/callback.h>
    103 #include <sys/kmem.h>
    104 #include <sys/pool.h>
    105 #include <sys/debug.h>
    106 #include <sys/lockdebug.h>
    107 #include <sys/cpu.h>
    108 #include <sys/asan.h>
    109 
    110 #include <uvm/uvm_extern.h>
    111 #include <uvm/uvm_map.h>
    112 
    113 #include <lib/libkern/libkern.h>
    114 
    115 struct kmem_cache_info {
    116 	size_t		kc_size;
    117 	const char *	kc_name;
    118 };
    119 
    120 static const struct kmem_cache_info kmem_cache_sizes[] = {
    121 	{  8, "kmem-8" },
    122 	{ 16, "kmem-16" },
    123 	{ 24, "kmem-24" },
    124 	{ 32, "kmem-32" },
    125 	{ 40, "kmem-40" },
    126 	{ 48, "kmem-48" },
    127 	{ 56, "kmem-56" },
    128 	{ 64, "kmem-64" },
    129 	{ 80, "kmem-80" },
    130 	{ 96, "kmem-96" },
    131 	{ 112, "kmem-112" },
    132 	{ 128, "kmem-128" },
    133 	{ 160, "kmem-160" },
    134 	{ 192, "kmem-192" },
    135 	{ 224, "kmem-224" },
    136 	{ 256, "kmem-256" },
    137 	{ 320, "kmem-320" },
    138 	{ 384, "kmem-384" },
    139 	{ 448, "kmem-448" },
    140 	{ 512, "kmem-512" },
    141 	{ 768, "kmem-768" },
    142 	{ 1024, "kmem-1024" },
    143 	{ 0, NULL }
    144 };
    145 
    146 static const struct kmem_cache_info kmem_cache_big_sizes[] = {
    147 	{ 2048, "kmem-2048" },
    148 	{ 4096, "kmem-4096" },
    149 	{ 8192, "kmem-8192" },
    150 	{ 16384, "kmem-16384" },
    151 	{ 0, NULL }
    152 };
    153 
    154 /*
    155  * KMEM_ALIGN is the smallest guaranteed alignment and also the
    156  * smallest allocateable quantum.
    157  * Every cache size >= CACHE_LINE_SIZE gets CACHE_LINE_SIZE alignment.
    158  */
    159 #define	KMEM_ALIGN		8
    160 #define	KMEM_SHIFT		3
    161 #define	KMEM_MAXSIZE		1024
    162 #define	KMEM_CACHE_COUNT	(KMEM_MAXSIZE >> KMEM_SHIFT)
    163 
    164 static pool_cache_t kmem_cache[KMEM_CACHE_COUNT] __cacheline_aligned;
    165 static size_t kmem_cache_maxidx __read_mostly;
    166 
    167 #define	KMEM_BIG_ALIGN		2048
    168 #define	KMEM_BIG_SHIFT		11
    169 #define	KMEM_BIG_MAXSIZE	16384
    170 #define	KMEM_CACHE_BIG_COUNT	(KMEM_BIG_MAXSIZE >> KMEM_BIG_SHIFT)
    171 
    172 static pool_cache_t kmem_cache_big[KMEM_CACHE_BIG_COUNT] __cacheline_aligned;
    173 static size_t kmem_cache_big_maxidx __read_mostly;
    174 
    175 #if defined(DIAGNOSTIC) && defined(_HARDKERNEL)
    176 #define	KMEM_SIZE
    177 #endif
    178 
    179 #if defined(DEBUG) && defined(_HARDKERNEL)
    180 #define	KMEM_SIZE
    181 #define	KMEM_GUARD
    182 static void *kmem_freecheck;
    183 #endif
    184 
    185 #if defined(KMEM_SIZE)
    186 struct kmem_header {
    187 	size_t		size;
    188 } __aligned(KMEM_ALIGN);
    189 #define	SIZE_SIZE	sizeof(struct kmem_header)
    190 static void kmem_size_set(void *, size_t);
    191 static void kmem_size_check(void *, size_t);
    192 #else
    193 #define	SIZE_SIZE	0
    194 #define	kmem_size_set(p, sz)	/* nothing */
    195 #define	kmem_size_check(p, sz)	/* nothing */
    196 #endif
    197 
    198 #if defined(KMEM_GUARD)
    199 #ifndef KMEM_GUARD_DEPTH
    200 #define KMEM_GUARD_DEPTH 0
    201 #endif
    202 struct kmem_guard {
    203 	u_int		kg_depth;
    204 	intptr_t *	kg_fifo;
    205 	u_int		kg_rotor;
    206 	vmem_t *	kg_vmem;
    207 };
    208 static bool kmem_guard_init(struct kmem_guard *, u_int, vmem_t *);
    209 static void *kmem_guard_alloc(struct kmem_guard *, size_t, bool);
    210 static void kmem_guard_free(struct kmem_guard *, size_t, void *);
    211 int kmem_guard_depth = KMEM_GUARD_DEPTH;
    212 static bool kmem_guard_enabled;
    213 static struct kmem_guard kmem_guard;
    214 #endif /* defined(KMEM_GUARD) */
    215 
    216 CTASSERT(KM_SLEEP == PR_WAITOK);
    217 CTASSERT(KM_NOSLEEP == PR_NOWAIT);
    218 
    219 /*
    220  * kmem_intr_alloc: allocate wired memory.
    221  */
    222 
    223 void *
    224 kmem_intr_alloc(size_t requested_size, km_flag_t kmflags)
    225 {
    226 #ifdef KASAN
    227 	const size_t origsize = requested_size;
    228 #endif
    229 	size_t allocsz, index;
    230 	size_t size;
    231 	pool_cache_t pc;
    232 	uint8_t *p;
    233 
    234 	KASSERT(requested_size > 0);
    235 
    236 	KASSERT((kmflags & KM_SLEEP) || (kmflags & KM_NOSLEEP));
    237 	KASSERT(!(kmflags & KM_SLEEP) || !(kmflags & KM_NOSLEEP));
    238 
    239 #ifdef KMEM_GUARD
    240 	if (kmem_guard_enabled) {
    241 		return kmem_guard_alloc(&kmem_guard, requested_size,
    242 		    (kmflags & KM_SLEEP) != 0);
    243 	}
    244 #endif
    245 
    246 	kasan_add_redzone(&requested_size);
    247 	size = kmem_roundup_size(requested_size);
    248 	allocsz = size + SIZE_SIZE;
    249 
    250 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
    251 	    < kmem_cache_maxidx) {
    252 		pc = kmem_cache[index];
    253 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
    254 	    < kmem_cache_big_maxidx) {
    255 		pc = kmem_cache_big[index];
    256 	} else {
    257 		int ret = uvm_km_kmem_alloc(kmem_va_arena,
    258 		    (vsize_t)round_page(size),
    259 		    ((kmflags & KM_SLEEP) ? VM_SLEEP : VM_NOSLEEP)
    260 		     | VM_INSTANTFIT, (vmem_addr_t *)&p);
    261 		if (ret) {
    262 			return NULL;
    263 		}
    264 		FREECHECK_OUT(&kmem_freecheck, p);
    265 		return p;
    266 	}
    267 
    268 	p = pool_cache_get(pc, kmflags);
    269 
    270 	if (__predict_true(p != NULL)) {
    271 		FREECHECK_OUT(&kmem_freecheck, p);
    272 		kmem_size_set(p, requested_size);
    273 		p += SIZE_SIZE;
    274 		kasan_alloc(p, origsize, size);
    275 		return p;
    276 	}
    277 	return p;
    278 }
    279 
    280 /*
    281  * kmem_intr_zalloc: allocate zeroed wired memory.
    282  */
    283 
    284 void *
    285 kmem_intr_zalloc(size_t size, km_flag_t kmflags)
    286 {
    287 	void *p;
    288 
    289 	p = kmem_intr_alloc(size, kmflags);
    290 	if (p != NULL) {
    291 		memset(p, 0, size);
    292 	}
    293 	return p;
    294 }
    295 
    296 /*
    297  * kmem_intr_free: free wired memory allocated by kmem_alloc.
    298  */
    299 
    300 void
    301 kmem_intr_free(void *p, size_t requested_size)
    302 {
    303 	size_t allocsz, index;
    304 	size_t size;
    305 	pool_cache_t pc;
    306 
    307 	KASSERT(p != NULL);
    308 	KASSERT(requested_size > 0);
    309 
    310 #ifdef KMEM_GUARD
    311 	if (kmem_guard_enabled) {
    312 		kmem_guard_free(&kmem_guard, requested_size, p);
    313 		return;
    314 	}
    315 #endif
    316 
    317 	kasan_add_redzone(&requested_size);
    318 	size = kmem_roundup_size(requested_size);
    319 	allocsz = size + SIZE_SIZE;
    320 
    321 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
    322 	    < kmem_cache_maxidx) {
    323 		pc = kmem_cache[index];
    324 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
    325 	    < kmem_cache_big_maxidx) {
    326 		pc = kmem_cache_big[index];
    327 	} else {
    328 		FREECHECK_IN(&kmem_freecheck, p);
    329 		uvm_km_kmem_free(kmem_va_arena, (vaddr_t)p,
    330 		    round_page(size));
    331 		return;
    332 	}
    333 
    334 	kasan_free(p, size);
    335 
    336 	p = (uint8_t *)p - SIZE_SIZE;
    337 	kmem_size_check(p, requested_size);
    338 	FREECHECK_IN(&kmem_freecheck, p);
    339 	LOCKDEBUG_MEM_CHECK(p, size);
    340 
    341 	pool_cache_put(pc, p);
    342 }
    343 
    344 /* ---- kmem API */
    345 
    346 /*
    347  * kmem_alloc: allocate wired memory.
    348  * => must not be called from interrupt context.
    349  */
    350 
    351 void *
    352 kmem_alloc(size_t size, km_flag_t kmflags)
    353 {
    354 	void *v;
    355 
    356 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
    357 	    "kmem(9) should not be used from the interrupt context");
    358 	v = kmem_intr_alloc(size, kmflags);
    359 	KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
    360 	return v;
    361 }
    362 
    363 /*
    364  * kmem_zalloc: allocate zeroed wired memory.
    365  * => must not be called from interrupt context.
    366  */
    367 
    368 void *
    369 kmem_zalloc(size_t size, km_flag_t kmflags)
    370 {
    371 	void *v;
    372 
    373 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
    374 	    "kmem(9) should not be used from the interrupt context");
    375 	v = kmem_intr_zalloc(size, kmflags);
    376 	KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
    377 	return v;
    378 }
    379 
    380 /*
    381  * kmem_free: free wired memory allocated by kmem_alloc.
    382  * => must not be called from interrupt context.
    383  */
    384 
    385 void
    386 kmem_free(void *p, size_t size)
    387 {
    388 	KASSERT(!cpu_intr_p());
    389 	KASSERT(!cpu_softintr_p());
    390 	kmem_intr_free(p, size);
    391 }
    392 
    393 static size_t
    394 kmem_create_caches(const struct kmem_cache_info *array,
    395     pool_cache_t alloc_table[], size_t maxsize, int shift, int ipl)
    396 {
    397 	size_t maxidx = 0;
    398 	size_t table_unit = (1 << shift);
    399 	size_t size = table_unit;
    400 	int i;
    401 
    402 	for (i = 0; array[i].kc_size != 0 ; i++) {
    403 		const char *name = array[i].kc_name;
    404 		size_t cache_size = array[i].kc_size;
    405 		struct pool_allocator *pa;
    406 		int flags = PR_NOALIGN;
    407 		pool_cache_t pc;
    408 		size_t align;
    409 
    410 		if ((cache_size & (CACHE_LINE_SIZE - 1)) == 0)
    411 			align = CACHE_LINE_SIZE;
    412 		else if ((cache_size & (PAGE_SIZE - 1)) == 0)
    413 			align = PAGE_SIZE;
    414 		else
    415 			align = KMEM_ALIGN;
    416 
    417 		if (cache_size < CACHE_LINE_SIZE)
    418 			flags |= PR_NOTOUCH;
    419 
    420 		/* check if we reached the requested size */
    421 		if (cache_size > maxsize || cache_size > PAGE_SIZE) {
    422 			break;
    423 		}
    424 		if ((cache_size >> shift) > maxidx) {
    425 			maxidx = cache_size >> shift;
    426 		}
    427 
    428 		if ((cache_size >> shift) > maxidx) {
    429 			maxidx = cache_size >> shift;
    430 		}
    431 
    432 		pa = &pool_allocator_kmem;
    433 		pc = pool_cache_init(cache_size, align, 0, flags,
    434 		    name, pa, ipl, NULL, NULL, NULL);
    435 
    436 		while (size <= cache_size) {
    437 			alloc_table[(size - 1) >> shift] = pc;
    438 			size += table_unit;
    439 		}
    440 	}
    441 	return maxidx;
    442 }
    443 
    444 void
    445 kmem_init(void)
    446 {
    447 #ifdef KMEM_GUARD
    448 	kmem_guard_enabled = kmem_guard_init(&kmem_guard, kmem_guard_depth,
    449 	    kmem_va_arena);
    450 #endif
    451 	kmem_cache_maxidx = kmem_create_caches(kmem_cache_sizes,
    452 	    kmem_cache, KMEM_MAXSIZE, KMEM_SHIFT, IPL_VM);
    453 	kmem_cache_big_maxidx = kmem_create_caches(kmem_cache_big_sizes,
    454 	    kmem_cache_big, PAGE_SIZE, KMEM_BIG_SHIFT, IPL_VM);
    455 }
    456 
    457 size_t
    458 kmem_roundup_size(size_t size)
    459 {
    460 	return (size + (KMEM_ALIGN - 1)) & ~(KMEM_ALIGN - 1);
    461 }
    462 
    463 /*
    464  * Used to dynamically allocate string with kmem accordingly to format.
    465  */
    466 char *
    467 kmem_asprintf(const char *fmt, ...)
    468 {
    469 	int size __diagused, len;
    470 	va_list va;
    471 	char *str;
    472 
    473 	va_start(va, fmt);
    474 	len = vsnprintf(NULL, 0, fmt, va);
    475 	va_end(va);
    476 
    477 	str = kmem_alloc(len + 1, KM_SLEEP);
    478 
    479 	va_start(va, fmt);
    480 	size = vsnprintf(str, len + 1, fmt, va);
    481 	va_end(va);
    482 
    483 	KASSERT(size == len);
    484 
    485 	return str;
    486 }
    487 
    488 char *
    489 kmem_strdupsize(const char *str, size_t *lenp, km_flag_t flags)
    490 {
    491 	size_t len = strlen(str) + 1;
    492 	char *ptr = kmem_alloc(len, flags);
    493 	if (ptr == NULL)
    494 		return NULL;
    495 
    496 	if (lenp)
    497 		*lenp = len;
    498 	memcpy(ptr, str, len);
    499 	return ptr;
    500 }
    501 
    502 char *
    503 kmem_strndup(const char *str, size_t maxlen, km_flag_t flags)
    504 {
    505 	KASSERT(str != NULL);
    506 	KASSERT(maxlen != 0);
    507 
    508 	size_t len = strnlen(str, maxlen);
    509 	char *ptr = kmem_alloc(len + 1, flags);
    510 	if (ptr == NULL)
    511 		return NULL;
    512 
    513 	memcpy(ptr, str, len);
    514 	ptr[len] = '\0';
    515 
    516 	return ptr;
    517 }
    518 
    519 void
    520 kmem_strfree(char *str)
    521 {
    522 	if (str == NULL)
    523 		return;
    524 
    525 	kmem_free(str, strlen(str) + 1);
    526 }
    527 
    528 /* ------------------ DEBUG / DIAGNOSTIC ------------------ */
    529 
    530 #if defined(KMEM_SIZE)
    531 static void
    532 kmem_size_set(void *p, size_t sz)
    533 {
    534 	struct kmem_header *hd;
    535 	hd = (struct kmem_header *)p;
    536 	hd->size = sz;
    537 }
    538 
    539 static void
    540 kmem_size_check(void *p, size_t sz)
    541 {
    542 	struct kmem_header *hd;
    543 	size_t hsz;
    544 
    545 	hd = (struct kmem_header *)p;
    546 	hsz = hd->size;
    547 
    548 	if (hsz != sz) {
    549 		panic("kmem_free(%p, %zu) != allocated size %zu",
    550 		    (const uint8_t *)p + SIZE_SIZE, sz, hsz);
    551 	}
    552 }
    553 #endif /* defined(KMEM_SIZE) */
    554 
    555 #if defined(KMEM_GUARD)
    556 /*
    557  * The ultimate memory allocator for debugging, baby.  It tries to catch:
    558  *
    559  * 1. Overflow, in realtime. A guard page sits immediately after the
    560  *    requested area; a read/write overflow therefore triggers a page
    561  *    fault.
    562  * 2. Invalid pointer/size passed, at free. A kmem_header structure sits
    563  *    just before the requested area, and holds the allocated size. Any
    564  *    difference with what is given at free triggers a panic.
    565  * 3. Underflow, at free. If an underflow occurs, the kmem header will be
    566  *    modified, and 2. will trigger a panic.
    567  * 4. Use-after-free. When freeing, the memory is unmapped, and depending
    568  *    on the value of kmem_guard_depth, the kernel will more or less delay
    569  *    the recycling of that memory. Which means that any ulterior read/write
    570  *    access to the memory will trigger a page fault, given it hasn't been
    571  *    recycled yet.
    572  */
    573 
    574 #include <sys/atomic.h>
    575 #include <uvm/uvm.h>
    576 
    577 static bool
    578 kmem_guard_init(struct kmem_guard *kg, u_int depth, vmem_t *vm)
    579 {
    580 	vaddr_t va;
    581 
    582 	/* If not enabled, we have nothing to do. */
    583 	if (depth == 0) {
    584 		return false;
    585 	}
    586 	depth = roundup(depth, PAGE_SIZE / sizeof(void *));
    587 	KASSERT(depth != 0);
    588 
    589 	/*
    590 	 * Allocate fifo.
    591 	 */
    592 	va = uvm_km_alloc(kernel_map, depth * sizeof(void *), PAGE_SIZE,
    593 	    UVM_KMF_WIRED | UVM_KMF_ZERO);
    594 	if (va == 0) {
    595 		return false;
    596 	}
    597 
    598 	/*
    599 	 * Init object.
    600 	 */
    601 	kg->kg_vmem = vm;
    602 	kg->kg_fifo = (void *)va;
    603 	kg->kg_depth = depth;
    604 	kg->kg_rotor = 0;
    605 
    606 	printf("kmem_guard(%p): depth %d\n", kg, depth);
    607 	return true;
    608 }
    609 
    610 static void *
    611 kmem_guard_alloc(struct kmem_guard *kg, size_t requested_size, bool waitok)
    612 {
    613 	struct vm_page *pg;
    614 	vm_flag_t flags;
    615 	vmem_addr_t va;
    616 	vaddr_t loopva;
    617 	vsize_t loopsize;
    618 	size_t size;
    619 	void **p;
    620 
    621 	/*
    622 	 * Compute the size: take the kmem header into account, and add a guard
    623 	 * page at the end.
    624 	 */
    625 	size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE;
    626 
    627 	/* Allocate pages of kernel VA, but do not map anything in yet. */
    628 	flags = VM_BESTFIT | (waitok ? VM_SLEEP : VM_NOSLEEP);
    629 	if (vmem_alloc(kg->kg_vmem, size, flags, &va) != 0) {
    630 		return NULL;
    631 	}
    632 
    633 	loopva = va;
    634 	loopsize = size - PAGE_SIZE;
    635 
    636 	while (loopsize) {
    637 		pg = uvm_pagealloc(NULL, loopva, NULL, 0);
    638 		if (__predict_false(pg == NULL)) {
    639 			if (waitok) {
    640 				uvm_wait("kmem_guard");
    641 				continue;
    642 			} else {
    643 				uvm_km_pgremove_intrsafe(kernel_map, va,
    644 				    va + size);
    645 				vmem_free(kg->kg_vmem, va, size);
    646 				return NULL;
    647 			}
    648 		}
    649 
    650 		pg->flags &= ~PG_BUSY;	/* new page */
    651 		UVM_PAGE_OWN(pg, NULL);
    652 		pmap_kenter_pa(loopva, VM_PAGE_TO_PHYS(pg),
    653 		    VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE);
    654 
    655 		loopva += PAGE_SIZE;
    656 		loopsize -= PAGE_SIZE;
    657 	}
    658 
    659 	pmap_update(pmap_kernel());
    660 
    661 	/*
    662 	 * Offset the returned pointer so that the unmapped guard page sits
    663 	 * immediately after the returned object.
    664 	 */
    665 	p = (void **)((va + (size - PAGE_SIZE) - requested_size) & ~(uintptr_t)ALIGNBYTES);
    666 	kmem_size_set((uint8_t *)p - SIZE_SIZE, requested_size);
    667 	return (void *)p;
    668 }
    669 
    670 static void
    671 kmem_guard_free(struct kmem_guard *kg, size_t requested_size, void *p)
    672 {
    673 	vaddr_t va;
    674 	u_int rotor;
    675 	size_t size;
    676 	uint8_t *ptr;
    677 
    678 	ptr = (uint8_t *)p - SIZE_SIZE;
    679 	kmem_size_check(ptr, requested_size);
    680 	va = trunc_page((vaddr_t)ptr);
    681 	size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE;
    682 
    683 	KASSERT(pmap_extract(pmap_kernel(), va, NULL));
    684 	KASSERT(!pmap_extract(pmap_kernel(), va + (size - PAGE_SIZE), NULL));
    685 
    686 	/*
    687 	 * Unmap and free the pages. The last one is never allocated.
    688 	 */
    689 	uvm_km_pgremove_intrsafe(kernel_map, va, va + size);
    690 	pmap_update(pmap_kernel());
    691 
    692 #if 0
    693 	/*
    694 	 * XXX: Here, we need to atomically register the va and its size in the
    695 	 * fifo.
    696 	 */
    697 
    698 	/*
    699 	 * Put the VA allocation into the list and swap an old one out to free.
    700 	 * This behaves mostly like a fifo.
    701 	 */
    702 	rotor = atomic_inc_uint_nv(&kg->kg_rotor) % kg->kg_depth;
    703 	va = (vaddr_t)atomic_swap_ptr(&kg->kg_fifo[rotor], (void *)va);
    704 	if (va != 0) {
    705 		vmem_free(kg->kg_vmem, va, size);
    706 	}
    707 #else
    708 	(void)rotor;
    709 	vmem_free(kg->kg_vmem, va, size);
    710 #endif
    711 }
    712 
    713 #endif /* defined(KMEM_GUARD) */
    714