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