Home | History | Annotate | Line # | Download | only in kern
subr_kmem.c revision 1.60.4.3
      1 /*	$NetBSD: subr_kmem.c,v 1.60.4.3 2017/08/28 17:53:07 skrll 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  * KMEM_REDZONE: detect overrun bugs.
     70  *	Add a 2-byte pattern (allocate one more memory chunk if needed) at the
     71  *	end of each allocated buffer. Check this pattern on kmem_free.
     72  *
     73  * These options are enabled on DIAGNOSTIC.
     74  *
     75  *  |CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|
     76  *  +-----+-----+-----+-----+-----+-----+-----+-----+-----+---+-+--+--+
     77  *  |/////|     |     |     |     |     |     |     |     |   |*|**|UU|
     78  *  |/HSZ/|     |     |     |     |     |     |     |     |   |*|**|UU|
     79  *  |/////|     |     |     |     |     |     |     |     |   |*|**|UU|
     80  *  +-----+-----+-----+-----+-----+-----+-----+-----+-----+---+-+--+--+
     81  *  |Size |    Buffer usable by the caller (requested size)   |RedZ|Unused\
     82  */
     83 
     84 /*
     85  * KMEM_POISON: detect modify-after-free bugs.
     86  *	Fill freed (in the sense of kmem_free) memory with a garbage pattern.
     87  *	Check the pattern on allocation.
     88  *
     89  * KMEM_GUARD
     90  *	A kernel with "option DEBUG" has "kmem_guard" debugging feature compiled
     91  *	in. See the comment below for what kind of bugs it tries to detect. Even
     92  *	if compiled in, it's disabled by default because it's very expensive.
     93  *	You can enable it on boot by:
     94  *		boot -d
     95  *		db> w kmem_guard_depth 0t30000
     96  *		db> c
     97  *
     98  *	The default value of kmem_guard_depth is 0, which means disabled.
     99  *	It can be changed by KMEM_GUARD_DEPTH kernel config option.
    100  */
    101 
    102 #include <sys/cdefs.h>
    103 __KERNEL_RCSID(0, "$NetBSD: subr_kmem.c,v 1.60.4.3 2017/08/28 17:53:07 skrll Exp $");
    104 #ifdef _KERNEL_OPT
    105 #include "opt_kmem.h"
    106 #endif
    107 
    108 #include <sys/param.h>
    109 #include <sys/callback.h>
    110 #include <sys/kmem.h>
    111 #include <sys/pool.h>
    112 #include <sys/debug.h>
    113 #include <sys/lockdebug.h>
    114 #include <sys/cpu.h>
    115 
    116 #include <uvm/uvm_extern.h>
    117 #include <uvm/uvm_map.h>
    118 
    119 #include <lib/libkern/libkern.h>
    120 
    121 struct kmem_cache_info {
    122 	size_t		kc_size;
    123 	const char *	kc_name;
    124 };
    125 
    126 static const struct kmem_cache_info kmem_cache_sizes[] = {
    127 	{  8, "kmem-8" },
    128 	{ 16, "kmem-16" },
    129 	{ 24, "kmem-24" },
    130 	{ 32, "kmem-32" },
    131 	{ 40, "kmem-40" },
    132 	{ 48, "kmem-48" },
    133 	{ 56, "kmem-56" },
    134 	{ 64, "kmem-64" },
    135 	{ 80, "kmem-80" },
    136 	{ 96, "kmem-96" },
    137 	{ 112, "kmem-112" },
    138 	{ 128, "kmem-128" },
    139 	{ 160, "kmem-160" },
    140 	{ 192, "kmem-192" },
    141 	{ 224, "kmem-224" },
    142 	{ 256, "kmem-256" },
    143 	{ 320, "kmem-320" },
    144 	{ 384, "kmem-384" },
    145 	{ 448, "kmem-448" },
    146 	{ 512, "kmem-512" },
    147 	{ 768, "kmem-768" },
    148 	{ 1024, "kmem-1024" },
    149 	{ 0, NULL }
    150 };
    151 
    152 static const struct kmem_cache_info kmem_cache_big_sizes[] = {
    153 	{ 2048, "kmem-2048" },
    154 	{ 4096, "kmem-4096" },
    155 	{ 8192, "kmem-8192" },
    156 	{ 16384, "kmem-16384" },
    157 	{ 0, NULL }
    158 };
    159 
    160 /*
    161  * KMEM_ALIGN is the smallest guaranteed alignment and also the
    162  * smallest allocateable quantum.
    163  * Every cache size >= CACHE_LINE_SIZE gets CACHE_LINE_SIZE alignment.
    164  */
    165 #define	KMEM_ALIGN		8
    166 #define	KMEM_SHIFT		3
    167 #define	KMEM_MAXSIZE		1024
    168 #define	KMEM_CACHE_COUNT	(KMEM_MAXSIZE >> KMEM_SHIFT)
    169 
    170 static pool_cache_t kmem_cache[KMEM_CACHE_COUNT] __cacheline_aligned;
    171 static size_t kmem_cache_maxidx __read_mostly;
    172 
    173 #define	KMEM_BIG_ALIGN		2048
    174 #define	KMEM_BIG_SHIFT		11
    175 #define	KMEM_BIG_MAXSIZE	16384
    176 #define	KMEM_CACHE_BIG_COUNT	(KMEM_BIG_MAXSIZE >> KMEM_BIG_SHIFT)
    177 
    178 static pool_cache_t kmem_cache_big[KMEM_CACHE_BIG_COUNT] __cacheline_aligned;
    179 static size_t kmem_cache_big_maxidx __read_mostly;
    180 
    181 #if defined(DIAGNOSTIC) && defined(_HARDKERNEL)
    182 #define	KMEM_SIZE
    183 #define	KMEM_REDZONE
    184 #endif /* defined(DIAGNOSTIC) */
    185 
    186 #if defined(DEBUG) && defined(_HARDKERNEL)
    187 #define	KMEM_SIZE
    188 #define	KMEM_POISON
    189 #define	KMEM_GUARD
    190 static void *kmem_freecheck;
    191 #endif /* defined(DEBUG) */
    192 
    193 #if defined(KMEM_POISON)
    194 static int kmem_poison_ctor(void *, void *, int);
    195 static void kmem_poison_fill(void *, size_t);
    196 static void kmem_poison_check(void *, size_t);
    197 #else /* defined(KMEM_POISON) */
    198 #define	kmem_poison_fill(p, sz)		/* nothing */
    199 #define	kmem_poison_check(p, sz)	/* nothing */
    200 #endif /* defined(KMEM_POISON) */
    201 
    202 #if defined(KMEM_REDZONE)
    203 #define	REDZONE_SIZE	2
    204 static void kmem_redzone_fill(void *, size_t);
    205 static void kmem_redzone_check(void *, size_t);
    206 #else /* defined(KMEM_REDZONE) */
    207 #define	REDZONE_SIZE	0
    208 #define	kmem_redzone_fill(p, sz)		/* nothing */
    209 #define	kmem_redzone_check(p, sz)	/* nothing */
    210 #endif /* defined(KMEM_REDZONE) */
    211 
    212 #if defined(KMEM_SIZE)
    213 struct kmem_header {
    214 	size_t		size;
    215 } __aligned(KMEM_ALIGN);
    216 #define	SIZE_SIZE	sizeof(struct kmem_header)
    217 static void kmem_size_set(void *, size_t);
    218 static void kmem_size_check(void *, size_t);
    219 #else
    220 #define	SIZE_SIZE	0
    221 #define	kmem_size_set(p, sz)	/* nothing */
    222 #define	kmem_size_check(p, sz)	/* nothing */
    223 #endif
    224 
    225 #if defined(KMEM_GUARD)
    226 #ifndef KMEM_GUARD_DEPTH
    227 #define KMEM_GUARD_DEPTH 0
    228 #endif
    229 struct kmem_guard {
    230 	u_int		kg_depth;
    231 	intptr_t *	kg_fifo;
    232 	u_int		kg_rotor;
    233 	vmem_t *	kg_vmem;
    234 };
    235 
    236 static bool	kmem_guard_init(struct kmem_guard *, u_int, vmem_t *);
    237 static void *kmem_guard_alloc(struct kmem_guard *, size_t, bool);
    238 static void kmem_guard_free(struct kmem_guard *, size_t, void *);
    239 
    240 int kmem_guard_depth = KMEM_GUARD_DEPTH;
    241 static bool kmem_guard_enabled;
    242 static struct kmem_guard kmem_guard;
    243 #endif /* defined(KMEM_GUARD) */
    244 
    245 CTASSERT(KM_SLEEP == PR_WAITOK);
    246 CTASSERT(KM_NOSLEEP == PR_NOWAIT);
    247 
    248 /*
    249  * kmem_intr_alloc: allocate wired memory.
    250  */
    251 
    252 void *
    253 kmem_intr_alloc(size_t requested_size, km_flag_t kmflags)
    254 {
    255 	size_t allocsz, index;
    256 	size_t size;
    257 	pool_cache_t pc;
    258 	uint8_t *p;
    259 
    260 	KASSERT(requested_size > 0);
    261 
    262 #ifdef KMEM_GUARD
    263 	if (kmem_guard_enabled) {
    264 		return kmem_guard_alloc(&kmem_guard, requested_size,
    265 		    (kmflags & KM_SLEEP) != 0);
    266 	}
    267 #endif
    268 	size = kmem_roundup_size(requested_size);
    269 	allocsz = size + SIZE_SIZE;
    270 
    271 #ifdef KMEM_REDZONE
    272 	if (size - requested_size < REDZONE_SIZE) {
    273 		/* If there isn't enough space in the padding, allocate
    274 		 * one more memory chunk for the red zone. */
    275 		allocsz += kmem_roundup_size(REDZONE_SIZE);
    276 	}
    277 #endif
    278 
    279 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
    280 	    < kmem_cache_maxidx) {
    281 		pc = kmem_cache[index];
    282 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
    283 	    < kmem_cache_big_maxidx) {
    284 		pc = kmem_cache_big[index];
    285 	} else {
    286 		int ret = uvm_km_kmem_alloc(kmem_va_arena,
    287 		    (vsize_t)round_page(size),
    288 		    ((kmflags & KM_SLEEP) ? VM_SLEEP : VM_NOSLEEP)
    289 		     | VM_INSTANTFIT, (vmem_addr_t *)&p);
    290 		if (ret) {
    291 			return NULL;
    292 		}
    293 		FREECHECK_OUT(&kmem_freecheck, p);
    294 		return p;
    295 	}
    296 
    297 	p = pool_cache_get(pc, kmflags);
    298 
    299 	if (__predict_true(p != NULL)) {
    300 		kmem_poison_check(p, allocsz);
    301 		FREECHECK_OUT(&kmem_freecheck, p);
    302 		kmem_size_set(p, requested_size);
    303 		kmem_redzone_fill(p, requested_size + SIZE_SIZE);
    304 
    305 		return p + SIZE_SIZE;
    306 	}
    307 	return p;
    308 }
    309 
    310 /*
    311  * kmem_intr_zalloc: allocate zeroed wired memory.
    312  */
    313 
    314 void *
    315 kmem_intr_zalloc(size_t size, km_flag_t kmflags)
    316 {
    317 	void *p;
    318 
    319 	p = kmem_intr_alloc(size, kmflags);
    320 	if (p != NULL) {
    321 		memset(p, 0, size);
    322 	}
    323 	return p;
    324 }
    325 
    326 /*
    327  * kmem_intr_free: free wired memory allocated by kmem_alloc.
    328  */
    329 
    330 void
    331 kmem_intr_free(void *p, size_t requested_size)
    332 {
    333 	size_t allocsz, index;
    334 	size_t size;
    335 	pool_cache_t pc;
    336 
    337 	KASSERT(p != NULL);
    338 	KASSERT(requested_size > 0);
    339 
    340 #ifdef KMEM_GUARD
    341 	if (kmem_guard_enabled) {
    342 		kmem_guard_free(&kmem_guard, requested_size, p);
    343 		return;
    344 	}
    345 #endif
    346 
    347 	size = kmem_roundup_size(requested_size);
    348 	allocsz = size + SIZE_SIZE;
    349 
    350 #ifdef KMEM_REDZONE
    351 	if (size - requested_size < REDZONE_SIZE) {
    352 		allocsz += kmem_roundup_size(REDZONE_SIZE);
    353 	}
    354 #endif
    355 
    356 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
    357 	    < kmem_cache_maxidx) {
    358 		pc = kmem_cache[index];
    359 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
    360 	    < kmem_cache_big_maxidx) {
    361 		pc = kmem_cache_big[index];
    362 	} else {
    363 		FREECHECK_IN(&kmem_freecheck, p);
    364 		uvm_km_kmem_free(kmem_va_arena, (vaddr_t)p,
    365 		    round_page(size));
    366 		return;
    367 	}
    368 
    369 	p = (uint8_t *)p - SIZE_SIZE;
    370 	kmem_size_check(p, requested_size);
    371 	kmem_redzone_check(p, requested_size + SIZE_SIZE);
    372 	FREECHECK_IN(&kmem_freecheck, p);
    373 	LOCKDEBUG_MEM_CHECK(p, size);
    374 	kmem_poison_fill(p, allocsz);
    375 
    376 	pool_cache_put(pc, p);
    377 }
    378 
    379 /* ---- kmem API */
    380 
    381 /*
    382  * kmem_alloc: allocate wired memory.
    383  * => must not be called from interrupt context.
    384  */
    385 
    386 void *
    387 kmem_alloc(size_t size, km_flag_t kmflags)
    388 {
    389 	void *v;
    390 
    391 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
    392 	    "kmem(9) should not be used from the interrupt context");
    393 	v = kmem_intr_alloc(size, kmflags);
    394 	KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
    395 	return v;
    396 }
    397 
    398 /*
    399  * kmem_zalloc: allocate zeroed wired memory.
    400  * => must not be called from interrupt context.
    401  */
    402 
    403 void *
    404 kmem_zalloc(size_t size, km_flag_t kmflags)
    405 {
    406 	void *v;
    407 
    408 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
    409 	    "kmem(9) should not be used from the interrupt context");
    410 	v = kmem_intr_zalloc(size, kmflags);
    411 	KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
    412 	return v;
    413 }
    414 
    415 /*
    416  * kmem_free: free wired memory allocated by kmem_alloc.
    417  * => must not be called from interrupt context.
    418  */
    419 
    420 void
    421 kmem_free(void *p, size_t size)
    422 {
    423 	KASSERT(!cpu_intr_p());
    424 	KASSERT(!cpu_softintr_p());
    425 	kmem_intr_free(p, size);
    426 }
    427 
    428 static size_t
    429 kmem_create_caches(const struct kmem_cache_info *array,
    430     pool_cache_t alloc_table[], size_t maxsize, int shift, int ipl)
    431 {
    432 	size_t maxidx = 0;
    433 	size_t table_unit = (1 << shift);
    434 	size_t size = table_unit;
    435 	int i;
    436 
    437 	for (i = 0; array[i].kc_size != 0 ; i++) {
    438 		const char *name = array[i].kc_name;
    439 		size_t cache_size = array[i].kc_size;
    440 		struct pool_allocator *pa;
    441 		int flags = PR_NOALIGN;
    442 		pool_cache_t pc;
    443 		size_t align;
    444 
    445 		if ((cache_size & (CACHE_LINE_SIZE - 1)) == 0)
    446 			align = CACHE_LINE_SIZE;
    447 		else if ((cache_size & (PAGE_SIZE - 1)) == 0)
    448 			align = PAGE_SIZE;
    449 		else
    450 			align = KMEM_ALIGN;
    451 
    452 		if (cache_size < CACHE_LINE_SIZE)
    453 			flags |= PR_NOTOUCH;
    454 
    455 		/* check if we reached the requested size */
    456 		if (cache_size > maxsize || cache_size > PAGE_SIZE) {
    457 			break;
    458 		}
    459 		if ((cache_size >> shift) > maxidx) {
    460 			maxidx = cache_size >> shift;
    461 		}
    462 
    463 		if ((cache_size >> shift) > maxidx) {
    464 			maxidx = cache_size >> shift;
    465 		}
    466 
    467 		pa = &pool_allocator_kmem;
    468 #if defined(KMEM_POISON)
    469 		pc = pool_cache_init(cache_size, align, 0, flags,
    470 		    name, pa, ipl, kmem_poison_ctor,
    471 		    NULL, (void *)cache_size);
    472 #else /* defined(KMEM_POISON) */
    473 		pc = pool_cache_init(cache_size, align, 0, flags,
    474 		    name, pa, ipl, NULL, NULL, NULL);
    475 #endif /* defined(KMEM_POISON) */
    476 
    477 		while (size <= cache_size) {
    478 			alloc_table[(size - 1) >> shift] = pc;
    479 			size += table_unit;
    480 		}
    481 	}
    482 	return maxidx;
    483 }
    484 
    485 void
    486 kmem_init(void)
    487 {
    488 #ifdef KMEM_GUARD
    489 	kmem_guard_enabled = kmem_guard_init(&kmem_guard, kmem_guard_depth,
    490 	    kmem_va_arena);
    491 #endif
    492 	kmem_cache_maxidx = kmem_create_caches(kmem_cache_sizes,
    493 	    kmem_cache, KMEM_MAXSIZE, KMEM_SHIFT, IPL_VM);
    494 	kmem_cache_big_maxidx = kmem_create_caches(kmem_cache_big_sizes,
    495 	    kmem_cache_big, PAGE_SIZE, KMEM_BIG_SHIFT, IPL_VM);
    496 }
    497 
    498 size_t
    499 kmem_roundup_size(size_t size)
    500 {
    501 	return (size + (KMEM_ALIGN - 1)) & ~(KMEM_ALIGN - 1);
    502 }
    503 
    504 /*
    505  * Used to dynamically allocate string with kmem accordingly to format.
    506  */
    507 char *
    508 kmem_asprintf(const char *fmt, ...)
    509 {
    510 	int size __diagused, len;
    511 	va_list va;
    512 	char *str;
    513 
    514 	va_start(va, fmt);
    515 	len = vsnprintf(NULL, 0, fmt, va);
    516 	va_end(va);
    517 
    518 	str = kmem_alloc(len + 1, KM_SLEEP);
    519 
    520 	va_start(va, fmt);
    521 	size = vsnprintf(str, len + 1, fmt, va);
    522 	va_end(va);
    523 
    524 	KASSERT(size == len);
    525 
    526 	return str;
    527 }
    528 
    529 /* ------------------ DEBUG / DIAGNOSTIC ------------------ */
    530 
    531 #if defined(KMEM_POISON) || defined(KMEM_REDZONE)
    532 #if defined(_LP64)
    533 #define PRIME 0x9e37fffffffc0000UL
    534 #else /* defined(_LP64) */
    535 #define PRIME 0x9e3779b1
    536 #endif /* defined(_LP64) */
    537 
    538 static inline uint8_t
    539 kmem_pattern_generate(const void *p)
    540 {
    541 	return (uint8_t)(((uintptr_t)p) * PRIME
    542 	   >> ((sizeof(uintptr_t) - sizeof(uint8_t))) * CHAR_BIT);
    543 }
    544 #endif /* defined(KMEM_POISON) || defined(KMEM_REDZONE) */
    545 
    546 #if defined(KMEM_POISON)
    547 static int
    548 kmem_poison_ctor(void *arg, void *obj, int flag)
    549 {
    550 	size_t sz = (size_t)arg;
    551 
    552 	kmem_poison_fill(obj, sz);
    553 
    554 	return 0;
    555 }
    556 
    557 static void
    558 kmem_poison_fill(void *p, size_t sz)
    559 {
    560 	uint8_t *cp;
    561 	const uint8_t *ep;
    562 
    563 	cp = p;
    564 	ep = cp + sz;
    565 	while (cp < ep) {
    566 		*cp = kmem_pattern_generate(cp);
    567 		cp++;
    568 	}
    569 }
    570 
    571 static void
    572 kmem_poison_check(void *p, size_t sz)
    573 {
    574 	uint8_t *cp;
    575 	const uint8_t *ep;
    576 
    577 	cp = p;
    578 	ep = cp + sz;
    579 	while (cp < ep) {
    580 		const uint8_t expected = kmem_pattern_generate(cp);
    581 
    582 		if (*cp != expected) {
    583 			panic("%s: %p: 0x%02x != 0x%02x\n",
    584 			   __func__, cp, *cp, expected);
    585 		}
    586 		cp++;
    587 	}
    588 }
    589 #endif /* defined(KMEM_POISON) */
    590 
    591 #if defined(KMEM_SIZE)
    592 static void
    593 kmem_size_set(void *p, size_t sz)
    594 {
    595 	struct kmem_header *hd;
    596 	hd = (struct kmem_header *)p;
    597 	hd->size = sz;
    598 }
    599 
    600 static void
    601 kmem_size_check(void *p, size_t sz)
    602 {
    603 	struct kmem_header *hd;
    604 	size_t hsz;
    605 
    606 	hd = (struct kmem_header *)p;
    607 	hsz = hd->size;
    608 
    609 	if (hsz != sz) {
    610 		panic("kmem_free(%p, %zu) != allocated size %zu",
    611 		    (const uint8_t *)p + SIZE_SIZE, sz, hsz);
    612 	}
    613 }
    614 #endif /* defined(KMEM_SIZE) */
    615 
    616 #if defined(KMEM_REDZONE)
    617 #define STATIC_BYTE	0xFE
    618 CTASSERT(REDZONE_SIZE > 1);
    619 static void
    620 kmem_redzone_fill(void *p, size_t sz)
    621 {
    622 	uint8_t *cp, pat;
    623 	const uint8_t *ep;
    624 
    625 	cp = (uint8_t *)p + sz;
    626 	ep = cp + REDZONE_SIZE;
    627 
    628 	/*
    629 	 * We really don't want the first byte of the red zone to be '\0';
    630 	 * an off-by-one in a string may not be properly detected.
    631 	 */
    632 	pat = kmem_pattern_generate(cp);
    633 	*cp = (pat == '\0') ? STATIC_BYTE: pat;
    634 	cp++;
    635 
    636 	while (cp < ep) {
    637 		*cp = kmem_pattern_generate(cp);
    638 		cp++;
    639 	}
    640 }
    641 
    642 static void
    643 kmem_redzone_check(void *p, size_t sz)
    644 {
    645 	uint8_t *cp, pat, expected;
    646 	const uint8_t *ep;
    647 
    648 	cp = (uint8_t *)p + sz;
    649 	ep = cp + REDZONE_SIZE;
    650 
    651 	pat = kmem_pattern_generate(cp);
    652 	expected = (pat == '\0') ? STATIC_BYTE: pat;
    653 	if (expected != *cp) {
    654 		panic("%s: %p: 0x%02x != 0x%02x\n",
    655 		   __func__, cp, *cp, expected);
    656 	}
    657 	cp++;
    658 
    659 	while (cp < ep) {
    660 		expected = kmem_pattern_generate(cp);
    661 		if (*cp != expected) {
    662 			panic("%s: %p: 0x%02x != 0x%02x\n",
    663 			   __func__, cp, *cp, expected);
    664 		}
    665 		cp++;
    666 	}
    667 }
    668 #endif /* defined(KMEM_REDZONE) */
    669 
    670 
    671 #if defined(KMEM_GUARD)
    672 /*
    673  * The ultimate memory allocator for debugging, baby.  It tries to catch:
    674  *
    675  * 1. Overflow, in realtime. A guard page sits immediately after the
    676  *    requested area; a read/write overflow therefore triggers a page
    677  *    fault.
    678  * 2. Invalid pointer/size passed, at free. A kmem_header structure sits
    679  *    just before the requested area, and holds the allocated size. Any
    680  *    difference with what is given at free triggers a panic.
    681  * 3. Underflow, at free. If an underflow occurs, the kmem header will be
    682  *    modified, and 2. will trigger a panic.
    683  * 4. Use-after-free. When freeing, the memory is unmapped, and depending
    684  *    on the value of kmem_guard_depth, the kernel will more or less delay
    685  *    the recycling of that memory. Which means that any ulterior read/write
    686  *    access to the memory will trigger a page fault, given it hasn't been
    687  *    recycled yet.
    688  */
    689 
    690 #include <sys/atomic.h>
    691 #include <uvm/uvm.h>
    692 
    693 static bool
    694 kmem_guard_init(struct kmem_guard *kg, u_int depth, vmem_t *vm)
    695 {
    696 	vaddr_t va;
    697 
    698 	/* If not enabled, we have nothing to do. */
    699 	if (depth == 0) {
    700 		return false;
    701 	}
    702 	depth = roundup(depth, PAGE_SIZE / sizeof(void *));
    703 	KASSERT(depth != 0);
    704 
    705 	/*
    706 	 * Allocate fifo.
    707 	 */
    708 	va = uvm_km_alloc(kernel_map, depth * sizeof(void *), PAGE_SIZE,
    709 	    UVM_KMF_WIRED | UVM_KMF_ZERO);
    710 	if (va == 0) {
    711 		return false;
    712 	}
    713 
    714 	/*
    715 	 * Init object.
    716 	 */
    717 	kg->kg_vmem = vm;
    718 	kg->kg_fifo = (void *)va;
    719 	kg->kg_depth = depth;
    720 	kg->kg_rotor = 0;
    721 
    722 	printf("kmem_guard(%p): depth %d\n", kg, depth);
    723 	return true;
    724 }
    725 
    726 static void *
    727 kmem_guard_alloc(struct kmem_guard *kg, size_t requested_size, bool waitok)
    728 {
    729 	struct vm_page *pg;
    730 	vm_flag_t flags;
    731 	vmem_addr_t va;
    732 	vaddr_t loopva;
    733 	vsize_t loopsize;
    734 	size_t size;
    735 	void **p;
    736 
    737 	/*
    738 	 * Compute the size: take the kmem header into account, and add a guard
    739 	 * page at the end.
    740 	 */
    741 	size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE;
    742 
    743 	/* Allocate pages of kernel VA, but do not map anything in yet. */
    744 	flags = VM_BESTFIT | (waitok ? VM_SLEEP : VM_NOSLEEP);
    745 	if (vmem_alloc(kg->kg_vmem, size, flags, &va) != 0) {
    746 		return NULL;
    747 	}
    748 
    749 	loopva = va;
    750 	loopsize = size - PAGE_SIZE;
    751 
    752 	while (loopsize) {
    753 		pg = uvm_pagealloc(NULL, loopva, NULL, 0);
    754 		if (__predict_false(pg == NULL)) {
    755 			if (waitok) {
    756 				uvm_wait("kmem_guard");
    757 				continue;
    758 			} else {
    759 				uvm_km_pgremove_intrsafe(kernel_map, va,
    760 				    va + size);
    761 				vmem_free(kg->kg_vmem, va, size);
    762 				return NULL;
    763 			}
    764 		}
    765 
    766 		pg->flags &= ~PG_BUSY;	/* new page */
    767 		UVM_PAGE_OWN(pg, NULL);
    768 		pmap_kenter_pa(loopva, VM_PAGE_TO_PHYS(pg),
    769 		    VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE);
    770 
    771 		loopva += PAGE_SIZE;
    772 		loopsize -= PAGE_SIZE;
    773 	}
    774 
    775 	pmap_update(pmap_kernel());
    776 
    777 	/*
    778 	 * Offset the returned pointer so that the unmapped guard page sits
    779 	 * immediately after the returned object.
    780 	 */
    781 	p = (void **)((va + (size - PAGE_SIZE) - requested_size) & ~(uintptr_t)ALIGNBYTES);
    782 	kmem_size_set((uint8_t *)p - SIZE_SIZE, requested_size);
    783 	return (void *)p;
    784 }
    785 
    786 static void
    787 kmem_guard_free(struct kmem_guard *kg, size_t requested_size, void *p)
    788 {
    789 	vaddr_t va;
    790 	u_int rotor;
    791 	size_t size;
    792 	uint8_t *ptr;
    793 
    794 	ptr = (uint8_t *)p - SIZE_SIZE;
    795 	kmem_size_check(ptr, requested_size);
    796 	va = trunc_page((vaddr_t)ptr);
    797 	size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE;
    798 
    799 	KASSERT(pmap_extract(pmap_kernel(), va, NULL));
    800 	KASSERT(!pmap_extract(pmap_kernel(), va + (size - PAGE_SIZE), NULL));
    801 
    802 	/*
    803 	 * Unmap and free the pages. The last one is never allocated.
    804 	 */
    805 	uvm_km_pgremove_intrsafe(kernel_map, va, va + size);
    806 	pmap_update(pmap_kernel());
    807 
    808 #if 0
    809 	/*
    810 	 * XXX: Here, we need to atomically register the va and its size in the
    811 	 * fifo.
    812 	 */
    813 
    814 	/*
    815 	 * Put the VA allocation into the list and swap an old one out to free.
    816 	 * This behaves mostly like a fifo.
    817 	 */
    818 	rotor = atomic_inc_uint_nv(&kg->kg_rotor) % kg->kg_depth;
    819 	va = (vaddr_t)atomic_swap_ptr(&kg->kg_fifo[rotor], (void *)va);
    820 	if (va != 0) {
    821 		vmem_free(kg->kg_vmem, va, size);
    822 	}
    823 #else
    824 	(void)rotor;
    825 	vmem_free(kg->kg_vmem, va, size);
    826 #endif
    827 }
    828 
    829 #endif /* defined(KMEM_GUARD) */
    830