Home | History | Annotate | Line # | Download | only in kern
subr_kmem.c revision 1.67
      1 /*	$NetBSD: subr_kmem.c,v 1.67 2018/08/20 11:35:28 maxv 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.67 2018/08/20 11:35:28 maxv 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 
    109 #include <uvm/uvm_extern.h>
    110 #include <uvm/uvm_map.h>
    111 
    112 #include <lib/libkern/libkern.h>
    113 
    114 struct kmem_cache_info {
    115 	size_t		kc_size;
    116 	const char *	kc_name;
    117 };
    118 
    119 static const struct kmem_cache_info kmem_cache_sizes[] = {
    120 	{  8, "kmem-8" },
    121 	{ 16, "kmem-16" },
    122 	{ 24, "kmem-24" },
    123 	{ 32, "kmem-32" },
    124 	{ 40, "kmem-40" },
    125 	{ 48, "kmem-48" },
    126 	{ 56, "kmem-56" },
    127 	{ 64, "kmem-64" },
    128 	{ 80, "kmem-80" },
    129 	{ 96, "kmem-96" },
    130 	{ 112, "kmem-112" },
    131 	{ 128, "kmem-128" },
    132 	{ 160, "kmem-160" },
    133 	{ 192, "kmem-192" },
    134 	{ 224, "kmem-224" },
    135 	{ 256, "kmem-256" },
    136 	{ 320, "kmem-320" },
    137 	{ 384, "kmem-384" },
    138 	{ 448, "kmem-448" },
    139 	{ 512, "kmem-512" },
    140 	{ 768, "kmem-768" },
    141 	{ 1024, "kmem-1024" },
    142 	{ 0, NULL }
    143 };
    144 
    145 static const struct kmem_cache_info kmem_cache_big_sizes[] = {
    146 	{ 2048, "kmem-2048" },
    147 	{ 4096, "kmem-4096" },
    148 	{ 8192, "kmem-8192" },
    149 	{ 16384, "kmem-16384" },
    150 	{ 0, NULL }
    151 };
    152 
    153 /*
    154  * KMEM_ALIGN is the smallest guaranteed alignment and also the
    155  * smallest allocateable quantum.
    156  * Every cache size >= CACHE_LINE_SIZE gets CACHE_LINE_SIZE alignment.
    157  */
    158 #define	KMEM_ALIGN		8
    159 #define	KMEM_SHIFT		3
    160 #define	KMEM_MAXSIZE		1024
    161 #define	KMEM_CACHE_COUNT	(KMEM_MAXSIZE >> KMEM_SHIFT)
    162 
    163 static pool_cache_t kmem_cache[KMEM_CACHE_COUNT] __cacheline_aligned;
    164 static size_t kmem_cache_maxidx __read_mostly;
    165 
    166 #define	KMEM_BIG_ALIGN		2048
    167 #define	KMEM_BIG_SHIFT		11
    168 #define	KMEM_BIG_MAXSIZE	16384
    169 #define	KMEM_CACHE_BIG_COUNT	(KMEM_BIG_MAXSIZE >> KMEM_BIG_SHIFT)
    170 
    171 static pool_cache_t kmem_cache_big[KMEM_CACHE_BIG_COUNT] __cacheline_aligned;
    172 static size_t kmem_cache_big_maxidx __read_mostly;
    173 
    174 #if defined(DIAGNOSTIC) && defined(_HARDKERNEL)
    175 #define	KMEM_SIZE
    176 #endif
    177 
    178 #if defined(DEBUG) && defined(_HARDKERNEL)
    179 #define	KMEM_SIZE
    180 #define	KMEM_GUARD
    181 static void *kmem_freecheck;
    182 #endif
    183 
    184 #if defined(KMEM_SIZE)
    185 struct kmem_header {
    186 	size_t		size;
    187 } __aligned(KMEM_ALIGN);
    188 #define	SIZE_SIZE	sizeof(struct kmem_header)
    189 static void kmem_size_set(void *, size_t);
    190 static void kmem_size_check(void *, size_t);
    191 #else
    192 #define	SIZE_SIZE	0
    193 #define	kmem_size_set(p, sz)	/* nothing */
    194 #define	kmem_size_check(p, sz)	/* nothing */
    195 #endif
    196 
    197 #if defined(KMEM_GUARD)
    198 #ifndef KMEM_GUARD_DEPTH
    199 #define KMEM_GUARD_DEPTH 0
    200 #endif
    201 struct kmem_guard {
    202 	u_int		kg_depth;
    203 	intptr_t *	kg_fifo;
    204 	u_int		kg_rotor;
    205 	vmem_t *	kg_vmem;
    206 };
    207 static bool kmem_guard_init(struct kmem_guard *, u_int, vmem_t *);
    208 static void *kmem_guard_alloc(struct kmem_guard *, size_t, bool);
    209 static void kmem_guard_free(struct kmem_guard *, size_t, void *);
    210 int kmem_guard_depth = KMEM_GUARD_DEPTH;
    211 static bool kmem_guard_enabled;
    212 static struct kmem_guard kmem_guard;
    213 #endif /* defined(KMEM_GUARD) */
    214 
    215 CTASSERT(KM_SLEEP == PR_WAITOK);
    216 CTASSERT(KM_NOSLEEP == PR_NOWAIT);
    217 
    218 /*
    219  * kmem_intr_alloc: allocate wired memory.
    220  */
    221 
    222 void *
    223 kmem_intr_alloc(size_t requested_size, km_flag_t kmflags)
    224 {
    225 	size_t allocsz, index;
    226 	size_t size;
    227 	pool_cache_t pc;
    228 	uint8_t *p;
    229 
    230 	KASSERT(requested_size > 0);
    231 
    232 	KASSERT((kmflags & KM_SLEEP) || (kmflags & KM_NOSLEEP));
    233 	KASSERT(!(kmflags & KM_SLEEP) || !(kmflags & KM_NOSLEEP));
    234 
    235 #ifdef KMEM_GUARD
    236 	if (kmem_guard_enabled) {
    237 		return kmem_guard_alloc(&kmem_guard, requested_size,
    238 		    (kmflags & KM_SLEEP) != 0);
    239 	}
    240 #endif
    241 
    242 	size = kmem_roundup_size(requested_size);
    243 	allocsz = size + SIZE_SIZE;
    244 
    245 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
    246 	    < kmem_cache_maxidx) {
    247 		pc = kmem_cache[index];
    248 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
    249 	    < kmem_cache_big_maxidx) {
    250 		pc = kmem_cache_big[index];
    251 	} else {
    252 		int ret = uvm_km_kmem_alloc(kmem_va_arena,
    253 		    (vsize_t)round_page(size),
    254 		    ((kmflags & KM_SLEEP) ? VM_SLEEP : VM_NOSLEEP)
    255 		     | VM_INSTANTFIT, (vmem_addr_t *)&p);
    256 		if (ret) {
    257 			return NULL;
    258 		}
    259 		FREECHECK_OUT(&kmem_freecheck, p);
    260 		return p;
    261 	}
    262 
    263 	p = pool_cache_get(pc, kmflags);
    264 
    265 	if (__predict_true(p != NULL)) {
    266 		FREECHECK_OUT(&kmem_freecheck, p);
    267 		kmem_size_set(p, requested_size);
    268 
    269 		return p + SIZE_SIZE;
    270 	}
    271 	return p;
    272 }
    273 
    274 /*
    275  * kmem_intr_zalloc: allocate zeroed wired memory.
    276  */
    277 
    278 void *
    279 kmem_intr_zalloc(size_t size, km_flag_t kmflags)
    280 {
    281 	void *p;
    282 
    283 	p = kmem_intr_alloc(size, kmflags);
    284 	if (p != NULL) {
    285 		memset(p, 0, size);
    286 	}
    287 	return p;
    288 }
    289 
    290 /*
    291  * kmem_intr_free: free wired memory allocated by kmem_alloc.
    292  */
    293 
    294 void
    295 kmem_intr_free(void *p, size_t requested_size)
    296 {
    297 	size_t allocsz, index;
    298 	size_t size;
    299 	pool_cache_t pc;
    300 
    301 	KASSERT(p != NULL);
    302 	KASSERT(requested_size > 0);
    303 
    304 #ifdef KMEM_GUARD
    305 	if (kmem_guard_enabled) {
    306 		kmem_guard_free(&kmem_guard, requested_size, p);
    307 		return;
    308 	}
    309 #endif
    310 
    311 	size = kmem_roundup_size(requested_size);
    312 	allocsz = size + SIZE_SIZE;
    313 
    314 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
    315 	    < kmem_cache_maxidx) {
    316 		pc = kmem_cache[index];
    317 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
    318 	    < kmem_cache_big_maxidx) {
    319 		pc = kmem_cache_big[index];
    320 	} else {
    321 		FREECHECK_IN(&kmem_freecheck, p);
    322 		uvm_km_kmem_free(kmem_va_arena, (vaddr_t)p,
    323 		    round_page(size));
    324 		return;
    325 	}
    326 
    327 	p = (uint8_t *)p - SIZE_SIZE;
    328 	kmem_size_check(p, requested_size);
    329 	FREECHECK_IN(&kmem_freecheck, p);
    330 	LOCKDEBUG_MEM_CHECK(p, size);
    331 
    332 	pool_cache_put(pc, p);
    333 }
    334 
    335 /* ---- kmem API */
    336 
    337 /*
    338  * kmem_alloc: allocate wired memory.
    339  * => must not be called from interrupt context.
    340  */
    341 
    342 void *
    343 kmem_alloc(size_t size, km_flag_t kmflags)
    344 {
    345 	void *v;
    346 
    347 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
    348 	    "kmem(9) should not be used from the interrupt context");
    349 	v = kmem_intr_alloc(size, kmflags);
    350 	KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
    351 	return v;
    352 }
    353 
    354 /*
    355  * kmem_zalloc: allocate zeroed wired memory.
    356  * => must not be called from interrupt context.
    357  */
    358 
    359 void *
    360 kmem_zalloc(size_t size, km_flag_t kmflags)
    361 {
    362 	void *v;
    363 
    364 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
    365 	    "kmem(9) should not be used from the interrupt context");
    366 	v = kmem_intr_zalloc(size, kmflags);
    367 	KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
    368 	return v;
    369 }
    370 
    371 /*
    372  * kmem_free: free wired memory allocated by kmem_alloc.
    373  * => must not be called from interrupt context.
    374  */
    375 
    376 void
    377 kmem_free(void *p, size_t size)
    378 {
    379 	KASSERT(!cpu_intr_p());
    380 	KASSERT(!cpu_softintr_p());
    381 	kmem_intr_free(p, size);
    382 }
    383 
    384 static size_t
    385 kmem_create_caches(const struct kmem_cache_info *array,
    386     pool_cache_t alloc_table[], size_t maxsize, int shift, int ipl)
    387 {
    388 	size_t maxidx = 0;
    389 	size_t table_unit = (1 << shift);
    390 	size_t size = table_unit;
    391 	int i;
    392 
    393 	for (i = 0; array[i].kc_size != 0 ; i++) {
    394 		const char *name = array[i].kc_name;
    395 		size_t cache_size = array[i].kc_size;
    396 		struct pool_allocator *pa;
    397 		int flags = PR_NOALIGN;
    398 		pool_cache_t pc;
    399 		size_t align;
    400 
    401 		if ((cache_size & (CACHE_LINE_SIZE - 1)) == 0)
    402 			align = CACHE_LINE_SIZE;
    403 		else if ((cache_size & (PAGE_SIZE - 1)) == 0)
    404 			align = PAGE_SIZE;
    405 		else
    406 			align = KMEM_ALIGN;
    407 
    408 		if (cache_size < CACHE_LINE_SIZE)
    409 			flags |= PR_NOTOUCH;
    410 
    411 		/* check if we reached the requested size */
    412 		if (cache_size > maxsize || cache_size > PAGE_SIZE) {
    413 			break;
    414 		}
    415 		if ((cache_size >> shift) > maxidx) {
    416 			maxidx = cache_size >> shift;
    417 		}
    418 
    419 		if ((cache_size >> shift) > maxidx) {
    420 			maxidx = cache_size >> shift;
    421 		}
    422 
    423 		pa = &pool_allocator_kmem;
    424 		pc = pool_cache_init(cache_size, align, 0, flags,
    425 		    name, pa, ipl, NULL, NULL, NULL);
    426 
    427 		while (size <= cache_size) {
    428 			alloc_table[(size - 1) >> shift] = pc;
    429 			size += table_unit;
    430 		}
    431 	}
    432 	return maxidx;
    433 }
    434 
    435 void
    436 kmem_init(void)
    437 {
    438 #ifdef KMEM_GUARD
    439 	kmem_guard_enabled = kmem_guard_init(&kmem_guard, kmem_guard_depth,
    440 	    kmem_va_arena);
    441 #endif
    442 	kmem_cache_maxidx = kmem_create_caches(kmem_cache_sizes,
    443 	    kmem_cache, KMEM_MAXSIZE, KMEM_SHIFT, IPL_VM);
    444 	kmem_cache_big_maxidx = kmem_create_caches(kmem_cache_big_sizes,
    445 	    kmem_cache_big, PAGE_SIZE, KMEM_BIG_SHIFT, IPL_VM);
    446 }
    447 
    448 size_t
    449 kmem_roundup_size(size_t size)
    450 {
    451 	return (size + (KMEM_ALIGN - 1)) & ~(KMEM_ALIGN - 1);
    452 }
    453 
    454 /*
    455  * Used to dynamically allocate string with kmem accordingly to format.
    456  */
    457 char *
    458 kmem_asprintf(const char *fmt, ...)
    459 {
    460 	int size __diagused, len;
    461 	va_list va;
    462 	char *str;
    463 
    464 	va_start(va, fmt);
    465 	len = vsnprintf(NULL, 0, fmt, va);
    466 	va_end(va);
    467 
    468 	str = kmem_alloc(len + 1, KM_SLEEP);
    469 
    470 	va_start(va, fmt);
    471 	size = vsnprintf(str, len + 1, fmt, va);
    472 	va_end(va);
    473 
    474 	KASSERT(size == len);
    475 
    476 	return str;
    477 }
    478 
    479 char *
    480 kmem_strdupsize(const char *str, size_t *lenp, km_flag_t flags)
    481 {
    482 	size_t len = strlen(str) + 1;
    483 	char *ptr = kmem_alloc(len, flags);
    484 	if (ptr == NULL)
    485 		return NULL;
    486 
    487 	if (lenp)
    488 		*lenp = len;
    489 	memcpy(ptr, str, len);
    490 	return ptr;
    491 }
    492 
    493 char *
    494 kmem_strndup(const char *str, size_t maxlen, km_flag_t flags)
    495 {
    496 	KASSERT(str != NULL);
    497 	KASSERT(maxlen != 0);
    498 
    499 	size_t len = strnlen(str, maxlen);
    500 	char *ptr = kmem_alloc(len + 1, flags);
    501 	if (ptr == NULL)
    502 		return NULL;
    503 
    504 	memcpy(ptr, str, len);
    505 	ptr[len] = '\0';
    506 
    507 	return ptr;
    508 }
    509 
    510 void
    511 kmem_strfree(char *str)
    512 {
    513 	if (str == NULL)
    514 		return;
    515 
    516 	kmem_free(str, strlen(str) + 1);
    517 }
    518 
    519 /* ------------------ DEBUG / DIAGNOSTIC ------------------ */
    520 
    521 #if defined(KMEM_SIZE)
    522 static void
    523 kmem_size_set(void *p, size_t sz)
    524 {
    525 	struct kmem_header *hd;
    526 	hd = (struct kmem_header *)p;
    527 	hd->size = sz;
    528 }
    529 
    530 static void
    531 kmem_size_check(void *p, size_t sz)
    532 {
    533 	struct kmem_header *hd;
    534 	size_t hsz;
    535 
    536 	hd = (struct kmem_header *)p;
    537 	hsz = hd->size;
    538 
    539 	if (hsz != sz) {
    540 		panic("kmem_free(%p, %zu) != allocated size %zu",
    541 		    (const uint8_t *)p + SIZE_SIZE, sz, hsz);
    542 	}
    543 }
    544 #endif /* defined(KMEM_SIZE) */
    545 
    546 #if defined(KMEM_GUARD)
    547 /*
    548  * The ultimate memory allocator for debugging, baby.  It tries to catch:
    549  *
    550  * 1. Overflow, in realtime. A guard page sits immediately after the
    551  *    requested area; a read/write overflow therefore triggers a page
    552  *    fault.
    553  * 2. Invalid pointer/size passed, at free. A kmem_header structure sits
    554  *    just before the requested area, and holds the allocated size. Any
    555  *    difference with what is given at free triggers a panic.
    556  * 3. Underflow, at free. If an underflow occurs, the kmem header will be
    557  *    modified, and 2. will trigger a panic.
    558  * 4. Use-after-free. When freeing, the memory is unmapped, and depending
    559  *    on the value of kmem_guard_depth, the kernel will more or less delay
    560  *    the recycling of that memory. Which means that any ulterior read/write
    561  *    access to the memory will trigger a page fault, given it hasn't been
    562  *    recycled yet.
    563  */
    564 
    565 #include <sys/atomic.h>
    566 #include <uvm/uvm.h>
    567 
    568 static bool
    569 kmem_guard_init(struct kmem_guard *kg, u_int depth, vmem_t *vm)
    570 {
    571 	vaddr_t va;
    572 
    573 	/* If not enabled, we have nothing to do. */
    574 	if (depth == 0) {
    575 		return false;
    576 	}
    577 	depth = roundup(depth, PAGE_SIZE / sizeof(void *));
    578 	KASSERT(depth != 0);
    579 
    580 	/*
    581 	 * Allocate fifo.
    582 	 */
    583 	va = uvm_km_alloc(kernel_map, depth * sizeof(void *), PAGE_SIZE,
    584 	    UVM_KMF_WIRED | UVM_KMF_ZERO);
    585 	if (va == 0) {
    586 		return false;
    587 	}
    588 
    589 	/*
    590 	 * Init object.
    591 	 */
    592 	kg->kg_vmem = vm;
    593 	kg->kg_fifo = (void *)va;
    594 	kg->kg_depth = depth;
    595 	kg->kg_rotor = 0;
    596 
    597 	printf("kmem_guard(%p): depth %d\n", kg, depth);
    598 	return true;
    599 }
    600 
    601 static void *
    602 kmem_guard_alloc(struct kmem_guard *kg, size_t requested_size, bool waitok)
    603 {
    604 	struct vm_page *pg;
    605 	vm_flag_t flags;
    606 	vmem_addr_t va;
    607 	vaddr_t loopva;
    608 	vsize_t loopsize;
    609 	size_t size;
    610 	void **p;
    611 
    612 	/*
    613 	 * Compute the size: take the kmem header into account, and add a guard
    614 	 * page at the end.
    615 	 */
    616 	size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE;
    617 
    618 	/* Allocate pages of kernel VA, but do not map anything in yet. */
    619 	flags = VM_BESTFIT | (waitok ? VM_SLEEP : VM_NOSLEEP);
    620 	if (vmem_alloc(kg->kg_vmem, size, flags, &va) != 0) {
    621 		return NULL;
    622 	}
    623 
    624 	loopva = va;
    625 	loopsize = size - PAGE_SIZE;
    626 
    627 	while (loopsize) {
    628 		pg = uvm_pagealloc(NULL, loopva, NULL, 0);
    629 		if (__predict_false(pg == NULL)) {
    630 			if (waitok) {
    631 				uvm_wait("kmem_guard");
    632 				continue;
    633 			} else {
    634 				uvm_km_pgremove_intrsafe(kernel_map, va,
    635 				    va + size);
    636 				vmem_free(kg->kg_vmem, va, size);
    637 				return NULL;
    638 			}
    639 		}
    640 
    641 		pg->flags &= ~PG_BUSY;	/* new page */
    642 		UVM_PAGE_OWN(pg, NULL);
    643 		pmap_kenter_pa(loopva, VM_PAGE_TO_PHYS(pg),
    644 		    VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE);
    645 
    646 		loopva += PAGE_SIZE;
    647 		loopsize -= PAGE_SIZE;
    648 	}
    649 
    650 	pmap_update(pmap_kernel());
    651 
    652 	/*
    653 	 * Offset the returned pointer so that the unmapped guard page sits
    654 	 * immediately after the returned object.
    655 	 */
    656 	p = (void **)((va + (size - PAGE_SIZE) - requested_size) & ~(uintptr_t)ALIGNBYTES);
    657 	kmem_size_set((uint8_t *)p - SIZE_SIZE, requested_size);
    658 	return (void *)p;
    659 }
    660 
    661 static void
    662 kmem_guard_free(struct kmem_guard *kg, size_t requested_size, void *p)
    663 {
    664 	vaddr_t va;
    665 	u_int rotor;
    666 	size_t size;
    667 	uint8_t *ptr;
    668 
    669 	ptr = (uint8_t *)p - SIZE_SIZE;
    670 	kmem_size_check(ptr, requested_size);
    671 	va = trunc_page((vaddr_t)ptr);
    672 	size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE;
    673 
    674 	KASSERT(pmap_extract(pmap_kernel(), va, NULL));
    675 	KASSERT(!pmap_extract(pmap_kernel(), va + (size - PAGE_SIZE), NULL));
    676 
    677 	/*
    678 	 * Unmap and free the pages. The last one is never allocated.
    679 	 */
    680 	uvm_km_pgremove_intrsafe(kernel_map, va, va + size);
    681 	pmap_update(pmap_kernel());
    682 
    683 #if 0
    684 	/*
    685 	 * XXX: Here, we need to atomically register the va and its size in the
    686 	 * fifo.
    687 	 */
    688 
    689 	/*
    690 	 * Put the VA allocation into the list and swap an old one out to free.
    691 	 * This behaves mostly like a fifo.
    692 	 */
    693 	rotor = atomic_inc_uint_nv(&kg->kg_rotor) % kg->kg_depth;
    694 	va = (vaddr_t)atomic_swap_ptr(&kg->kg_fifo[rotor], (void *)va);
    695 	if (va != 0) {
    696 		vmem_free(kg->kg_vmem, va, size);
    697 	}
    698 #else
    699 	(void)rotor;
    700 	vmem_free(kg->kg_vmem, va, size);
    701 #endif
    702 }
    703 
    704 #endif /* defined(KMEM_GUARD) */
    705