Home | History | Annotate | Line # | Download | only in kern
subr_kmem.c revision 1.66.4.2
      1 /*	$NetBSD: subr_kmem.c,v 1.66.4.2 2020/04/13 08:05:04 martin Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2009-2020 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  *	Append to each allocation a fixed-sized footer and record the exact
     66  *	user-requested allocation size in it.  When freeing, compare it with
     67  *	kmem_free's "size" argument.
     68  *
     69  * This option is enabled on DIAGNOSTIC.
     70  *
     71  *  |CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK|CHUNK| |
     72  *  +-----+-----+-----+-----+-----+-----+-----+-----+-----+-+
     73  *  |     |     |     |     |     |     |     |     |/////|U|
     74  *  |     |     |     |     |     |     |     |     |/HSZ/|U|
     75  *  |     |     |     |     |     |     |     |     |/////|U|
     76  *  +-----+-----+-----+-----+-----+-----+-----+-----+-----+-+
     77  *  | Buffer usable by the caller (requested size)  |Size |Unused
     78  */
     79 
     80 #include <sys/cdefs.h>
     81 __KERNEL_RCSID(0, "$NetBSD: subr_kmem.c,v 1.66.4.2 2020/04/13 08:05:04 martin Exp $");
     82 
     83 #ifdef _KERNEL_OPT
     84 #include "opt_kmem.h"
     85 #endif
     86 
     87 #include <sys/param.h>
     88 #include <sys/callback.h>
     89 #include <sys/kmem.h>
     90 #include <sys/pool.h>
     91 #include <sys/debug.h>
     92 #include <sys/lockdebug.h>
     93 #include <sys/cpu.h>
     94 #include <sys/asan.h>
     95 #include <sys/msan.h>
     96 
     97 #include <uvm/uvm_extern.h>
     98 #include <uvm/uvm_map.h>
     99 
    100 #include <lib/libkern/libkern.h>
    101 
    102 struct kmem_cache_info {
    103 	size_t		kc_size;
    104 	const char *	kc_name;
    105 };
    106 
    107 static const struct kmem_cache_info kmem_cache_sizes[] = {
    108 	{  8, "kmem-00008" },
    109 	{ 16, "kmem-00016" },
    110 	{ 24, "kmem-00024" },
    111 	{ 32, "kmem-00032" },
    112 	{ 40, "kmem-00040" },
    113 	{ 48, "kmem-00048" },
    114 	{ 56, "kmem-00056" },
    115 	{ 64, "kmem-00064" },
    116 	{ 80, "kmem-00080" },
    117 	{ 96, "kmem-00096" },
    118 	{ 112, "kmem-00112" },
    119 	{ 128, "kmem-00128" },
    120 	{ 160, "kmem-00160" },
    121 	{ 192, "kmem-00192" },
    122 	{ 224, "kmem-00224" },
    123 	{ 256, "kmem-00256" },
    124 	{ 320, "kmem-00320" },
    125 	{ 384, "kmem-00384" },
    126 	{ 448, "kmem-00448" },
    127 	{ 512, "kmem-00512" },
    128 	{ 768, "kmem-00768" },
    129 	{ 1024, "kmem-01024" },
    130 	{ 0, NULL }
    131 };
    132 
    133 static const struct kmem_cache_info kmem_cache_big_sizes[] = {
    134 	{ 2048, "kmem-02048" },
    135 	{ 4096, "kmem-04096" },
    136 	{ 8192, "kmem-08192" },
    137 	{ 16384, "kmem-16384" },
    138 	{ 0, NULL }
    139 };
    140 
    141 /*
    142  * KMEM_ALIGN is the smallest guaranteed alignment and also the
    143  * smallest allocateable quantum.
    144  * Every cache size >= CACHE_LINE_SIZE gets CACHE_LINE_SIZE alignment.
    145  */
    146 #define	KMEM_ALIGN		8
    147 #define	KMEM_SHIFT		3
    148 #define	KMEM_MAXSIZE		1024
    149 #define	KMEM_CACHE_COUNT	(KMEM_MAXSIZE >> KMEM_SHIFT)
    150 
    151 static pool_cache_t kmem_cache[KMEM_CACHE_COUNT] __cacheline_aligned;
    152 static size_t kmem_cache_maxidx __read_mostly;
    153 
    154 #define	KMEM_BIG_ALIGN		2048
    155 #define	KMEM_BIG_SHIFT		11
    156 #define	KMEM_BIG_MAXSIZE	16384
    157 #define	KMEM_CACHE_BIG_COUNT	(KMEM_BIG_MAXSIZE >> KMEM_BIG_SHIFT)
    158 
    159 static pool_cache_t kmem_cache_big[KMEM_CACHE_BIG_COUNT] __cacheline_aligned;
    160 static size_t kmem_cache_big_maxidx __read_mostly;
    161 
    162 #if defined(DIAGNOSTIC) && defined(_HARDKERNEL)
    163 #define	KMEM_SIZE
    164 #endif
    165 
    166 #if defined(DEBUG) && defined(_HARDKERNEL)
    167 static void *kmem_freecheck;
    168 #endif
    169 
    170 #if defined(KMEM_SIZE)
    171 #define	SIZE_SIZE	sizeof(size_t)
    172 static void kmem_size_set(void *, size_t);
    173 static void kmem_size_check(void *, size_t);
    174 #else
    175 #define	SIZE_SIZE	0
    176 #define	kmem_size_set(p, sz)	/* nothing */
    177 #define	kmem_size_check(p, sz)	/* nothing */
    178 #endif
    179 
    180 CTASSERT(KM_SLEEP == PR_WAITOK);
    181 CTASSERT(KM_NOSLEEP == PR_NOWAIT);
    182 
    183 /*
    184  * kmem_intr_alloc: allocate wired memory.
    185  */
    186 void *
    187 kmem_intr_alloc(size_t requested_size, km_flag_t kmflags)
    188 {
    189 #ifdef KASAN
    190 	const size_t origsize = requested_size;
    191 #endif
    192 	size_t allocsz, index;
    193 	size_t size;
    194 	pool_cache_t pc;
    195 	uint8_t *p;
    196 
    197 	KASSERT(requested_size > 0);
    198 
    199 	KASSERT((kmflags & KM_SLEEP) || (kmflags & KM_NOSLEEP));
    200 	KASSERT(!(kmflags & KM_SLEEP) || !(kmflags & KM_NOSLEEP));
    201 
    202 	kasan_add_redzone(&requested_size);
    203 	size = kmem_roundup_size(requested_size);
    204 	allocsz = size + SIZE_SIZE;
    205 
    206 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
    207 	    < kmem_cache_maxidx) {
    208 		pc = kmem_cache[index];
    209 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
    210 	    < kmem_cache_big_maxidx) {
    211 		pc = kmem_cache_big[index];
    212 	} else {
    213 		int ret = uvm_km_kmem_alloc(kmem_va_arena,
    214 		    (vsize_t)round_page(size),
    215 		    ((kmflags & KM_SLEEP) ? VM_SLEEP : VM_NOSLEEP)
    216 		     | VM_INSTANTFIT, (vmem_addr_t *)&p);
    217 		if (ret) {
    218 			return NULL;
    219 		}
    220 		FREECHECK_OUT(&kmem_freecheck, p);
    221 		return p;
    222 	}
    223 
    224 	p = pool_cache_get(pc, kmflags);
    225 
    226 	if (__predict_true(p != NULL)) {
    227 		FREECHECK_OUT(&kmem_freecheck, p);
    228 		kmem_size_set(p, requested_size);
    229 		kasan_mark(p, origsize, size, KASAN_KMEM_REDZONE);
    230 		return p;
    231 	}
    232 	return p;
    233 }
    234 
    235 /*
    236  * kmem_intr_zalloc: allocate zeroed wired memory.
    237  */
    238 void *
    239 kmem_intr_zalloc(size_t size, km_flag_t kmflags)
    240 {
    241 	void *p;
    242 
    243 	p = kmem_intr_alloc(size, kmflags);
    244 	if (p != NULL) {
    245 		memset(p, 0, size);
    246 	}
    247 	return p;
    248 }
    249 
    250 /*
    251  * kmem_intr_free: free wired memory allocated by kmem_alloc.
    252  */
    253 void
    254 kmem_intr_free(void *p, size_t requested_size)
    255 {
    256 	size_t allocsz, index;
    257 	size_t size;
    258 	pool_cache_t pc;
    259 
    260 	KASSERT(p != NULL);
    261 	KASSERT(requested_size > 0);
    262 
    263 	kasan_add_redzone(&requested_size);
    264 	size = kmem_roundup_size(requested_size);
    265 	allocsz = size + SIZE_SIZE;
    266 
    267 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
    268 	    < kmem_cache_maxidx) {
    269 		pc = kmem_cache[index];
    270 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
    271 	    < kmem_cache_big_maxidx) {
    272 		pc = kmem_cache_big[index];
    273 	} else {
    274 		FREECHECK_IN(&kmem_freecheck, p);
    275 		uvm_km_kmem_free(kmem_va_arena, (vaddr_t)p,
    276 		    round_page(size));
    277 		return;
    278 	}
    279 
    280 	kasan_mark(p, size, size, 0);
    281 
    282 	kmem_size_check(p, requested_size);
    283 	FREECHECK_IN(&kmem_freecheck, p);
    284 	LOCKDEBUG_MEM_CHECK(p, size);
    285 
    286 	pool_cache_put(pc, p);
    287 }
    288 
    289 /* -------------------------------- Kmem API -------------------------------- */
    290 
    291 /*
    292  * kmem_alloc: allocate wired memory.
    293  * => must not be called from interrupt context.
    294  */
    295 void *
    296 kmem_alloc(size_t size, km_flag_t kmflags)
    297 {
    298 	void *v;
    299 
    300 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
    301 	    "kmem(9) should not be used from the interrupt context");
    302 	v = kmem_intr_alloc(size, kmflags);
    303 	if (__predict_true(v != NULL)) {
    304 		kmsan_mark(v, size, KMSAN_STATE_UNINIT);
    305 		kmsan_orig(v, size, KMSAN_TYPE_KMEM, __RET_ADDR);
    306 	}
    307 	KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
    308 	return v;
    309 }
    310 
    311 /*
    312  * kmem_zalloc: allocate zeroed wired memory.
    313  * => must not be called from interrupt context.
    314  */
    315 void *
    316 kmem_zalloc(size_t size, km_flag_t kmflags)
    317 {
    318 	void *v;
    319 
    320 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
    321 	    "kmem(9) should not be used from the interrupt context");
    322 	v = kmem_intr_zalloc(size, kmflags);
    323 	KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
    324 	return v;
    325 }
    326 
    327 /*
    328  * kmem_free: free wired memory allocated by kmem_alloc.
    329  * => must not be called from interrupt context.
    330  */
    331 void
    332 kmem_free(void *p, size_t size)
    333 {
    334 	KASSERT(!cpu_intr_p());
    335 	KASSERT(!cpu_softintr_p());
    336 	kmem_intr_free(p, size);
    337 	kmsan_mark(p, size, KMSAN_STATE_INITED);
    338 }
    339 
    340 static size_t
    341 kmem_create_caches(const struct kmem_cache_info *array,
    342     pool_cache_t alloc_table[], size_t maxsize, int shift, int ipl)
    343 {
    344 	size_t maxidx = 0;
    345 	size_t table_unit = (1 << shift);
    346 	size_t size = table_unit;
    347 	int i;
    348 
    349 	for (i = 0; array[i].kc_size != 0 ; i++) {
    350 		const char *name = array[i].kc_name;
    351 		size_t cache_size = array[i].kc_size;
    352 		struct pool_allocator *pa;
    353 		int flags = 0;
    354 		pool_cache_t pc;
    355 		size_t align;
    356 
    357 		/* check if we reached the requested size */
    358 		if (cache_size > maxsize || cache_size > PAGE_SIZE) {
    359 			break;
    360 		}
    361 
    362 		/*
    363 		 * Exclude caches with size not a factor or multiple of the
    364 		 * coherency unit.
    365 		 */
    366 		if (cache_size < COHERENCY_UNIT) {
    367 			if (COHERENCY_UNIT % cache_size > 0) {
    368 			    	continue;
    369 			}
    370 			flags |= PR_NOTOUCH;
    371 			align = KMEM_ALIGN;
    372 		} else if ((cache_size & (PAGE_SIZE - 1)) == 0) {
    373 			align = PAGE_SIZE;
    374 		} else {
    375 			if ((cache_size % COHERENCY_UNIT) > 0) {
    376 				continue;
    377 			}
    378 			align = COHERENCY_UNIT;
    379 		}
    380 
    381 		if ((cache_size >> shift) > maxidx) {
    382 			maxidx = cache_size >> shift;
    383 		}
    384 
    385 		pa = &pool_allocator_kmem;
    386 		pc = pool_cache_init(cache_size, align, 0, flags,
    387 		    name, pa, ipl, NULL, NULL, NULL);
    388 
    389 		while (size <= cache_size) {
    390 			alloc_table[(size - 1) >> shift] = pc;
    391 			size += table_unit;
    392 		}
    393 	}
    394 	return maxidx;
    395 }
    396 
    397 void
    398 kmem_init(void)
    399 {
    400 	kmem_cache_maxidx = kmem_create_caches(kmem_cache_sizes,
    401 	    kmem_cache, KMEM_MAXSIZE, KMEM_SHIFT, IPL_VM);
    402 	kmem_cache_big_maxidx = kmem_create_caches(kmem_cache_big_sizes,
    403 	    kmem_cache_big, PAGE_SIZE, KMEM_BIG_SHIFT, IPL_VM);
    404 }
    405 
    406 size_t
    407 kmem_roundup_size(size_t size)
    408 {
    409 	return (size + (KMEM_ALIGN - 1)) & ~(KMEM_ALIGN - 1);
    410 }
    411 
    412 /*
    413  * Used to dynamically allocate string with kmem accordingly to format.
    414  */
    415 char *
    416 kmem_asprintf(const char *fmt, ...)
    417 {
    418 	int size __diagused, len;
    419 	va_list va;
    420 	char *str;
    421 
    422 	va_start(va, fmt);
    423 	len = vsnprintf(NULL, 0, fmt, va);
    424 	va_end(va);
    425 
    426 	str = kmem_alloc(len + 1, KM_SLEEP);
    427 
    428 	va_start(va, fmt);
    429 	size = vsnprintf(str, len + 1, fmt, va);
    430 	va_end(va);
    431 
    432 	KASSERT(size == len);
    433 
    434 	return str;
    435 }
    436 
    437 char *
    438 kmem_strdupsize(const char *str, size_t *lenp, km_flag_t flags)
    439 {
    440 	size_t len = strlen(str) + 1;
    441 	char *ptr = kmem_alloc(len, flags);
    442 	if (ptr == NULL)
    443 		return NULL;
    444 
    445 	if (lenp)
    446 		*lenp = len;
    447 	memcpy(ptr, str, len);
    448 	return ptr;
    449 }
    450 
    451 char *
    452 kmem_strndup(const char *str, size_t maxlen, km_flag_t flags)
    453 {
    454 	KASSERT(str != NULL);
    455 	KASSERT(maxlen != 0);
    456 
    457 	size_t len = strnlen(str, maxlen);
    458 	char *ptr = kmem_alloc(len + 1, flags);
    459 	if (ptr == NULL)
    460 		return NULL;
    461 
    462 	memcpy(ptr, str, len);
    463 	ptr[len] = '\0';
    464 
    465 	return ptr;
    466 }
    467 
    468 void
    469 kmem_strfree(char *str)
    470 {
    471 	if (str == NULL)
    472 		return;
    473 
    474 	kmem_free(str, strlen(str) + 1);
    475 }
    476 
    477 /* --------------------------- DEBUG / DIAGNOSTIC --------------------------- */
    478 
    479 #if defined(KMEM_SIZE)
    480 static void
    481 kmem_size_set(void *p, size_t sz)
    482 {
    483 	memcpy((size_t *)((uintptr_t)p + sz), &sz, sizeof(size_t));
    484 }
    485 
    486 static void
    487 kmem_size_check(void *p, size_t sz)
    488 {
    489 	size_t hsz;
    490 
    491 	memcpy(&hsz, (size_t *)((uintptr_t)p + sz), sizeof(size_t));
    492 
    493 	if (hsz != sz) {
    494 		panic("kmem_free(%p, %zu) != allocated size %zu; overwrote?",
    495 		    p, sz, hsz);
    496 	}
    497 
    498 	memset((size_t *)((uintptr_t)p + sz), 0xff, sizeof(size_t));
    499 }
    500 #endif /* defined(KMEM_SIZE) */
    501