xref: /netbsd-src/sys/kern/subr_kmem.c (revision 7330f729ccf0bd976a06f95fad452fe774fc7fd1)
1 /*	$NetBSD: subr_kmem.c,v 1.76 2019/08/15 12:06:42 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 is 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 #include <sys/cdefs.h>
81 __KERNEL_RCSID(0, "$NetBSD: subr_kmem.c,v 1.76 2019/08/15 12:06:42 maxv 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 
96 #include <uvm/uvm_extern.h>
97 #include <uvm/uvm_map.h>
98 
99 #include <lib/libkern/libkern.h>
100 
101 struct kmem_cache_info {
102 	size_t		kc_size;
103 	const char *	kc_name;
104 };
105 
106 static const struct kmem_cache_info kmem_cache_sizes[] = {
107 	{  8, "kmem-8" },
108 	{ 16, "kmem-16" },
109 	{ 24, "kmem-24" },
110 	{ 32, "kmem-32" },
111 	{ 40, "kmem-40" },
112 	{ 48, "kmem-48" },
113 	{ 56, "kmem-56" },
114 	{ 64, "kmem-64" },
115 	{ 80, "kmem-80" },
116 	{ 96, "kmem-96" },
117 	{ 112, "kmem-112" },
118 	{ 128, "kmem-128" },
119 	{ 160, "kmem-160" },
120 	{ 192, "kmem-192" },
121 	{ 224, "kmem-224" },
122 	{ 256, "kmem-256" },
123 	{ 320, "kmem-320" },
124 	{ 384, "kmem-384" },
125 	{ 448, "kmem-448" },
126 	{ 512, "kmem-512" },
127 	{ 768, "kmem-768" },
128 	{ 1024, "kmem-1024" },
129 	{ 0, NULL }
130 };
131 
132 static const struct kmem_cache_info kmem_cache_big_sizes[] = {
133 	{ 2048, "kmem-2048" },
134 	{ 4096, "kmem-4096" },
135 	{ 8192, "kmem-8192" },
136 	{ 16384, "kmem-16384" },
137 	{ 0, NULL }
138 };
139 
140 /*
141  * KMEM_ALIGN is the smallest guaranteed alignment and also the
142  * smallest allocateable quantum.
143  * Every cache size >= CACHE_LINE_SIZE gets CACHE_LINE_SIZE alignment.
144  */
145 #define	KMEM_ALIGN		8
146 #define	KMEM_SHIFT		3
147 #define	KMEM_MAXSIZE		1024
148 #define	KMEM_CACHE_COUNT	(KMEM_MAXSIZE >> KMEM_SHIFT)
149 
150 static pool_cache_t kmem_cache[KMEM_CACHE_COUNT] __cacheline_aligned;
151 static size_t kmem_cache_maxidx __read_mostly;
152 
153 #define	KMEM_BIG_ALIGN		2048
154 #define	KMEM_BIG_SHIFT		11
155 #define	KMEM_BIG_MAXSIZE	16384
156 #define	KMEM_CACHE_BIG_COUNT	(KMEM_BIG_MAXSIZE >> KMEM_BIG_SHIFT)
157 
158 static pool_cache_t kmem_cache_big[KMEM_CACHE_BIG_COUNT] __cacheline_aligned;
159 static size_t kmem_cache_big_maxidx __read_mostly;
160 
161 #if defined(DIAGNOSTIC) && defined(_HARDKERNEL)
162 #define	KMEM_SIZE
163 #endif
164 
165 #if defined(DEBUG) && defined(_HARDKERNEL)
166 static void *kmem_freecheck;
167 #endif
168 
169 #if defined(KMEM_SIZE)
170 struct kmem_header {
171 	size_t		size;
172 } __aligned(KMEM_ALIGN);
173 #define	SIZE_SIZE	sizeof(struct kmem_header)
174 static void kmem_size_set(void *, size_t);
175 static void kmem_size_check(void *, size_t);
176 #else
177 #define	SIZE_SIZE	0
178 #define	kmem_size_set(p, sz)	/* nothing */
179 #define	kmem_size_check(p, sz)	/* nothing */
180 #endif
181 
182 CTASSERT(KM_SLEEP == PR_WAITOK);
183 CTASSERT(KM_NOSLEEP == PR_NOWAIT);
184 
185 /*
186  * kmem_intr_alloc: allocate wired memory.
187  */
188 void *
189 kmem_intr_alloc(size_t requested_size, km_flag_t kmflags)
190 {
191 #ifdef KASAN
192 	const size_t origsize = requested_size;
193 #endif
194 	size_t allocsz, index;
195 	size_t size;
196 	pool_cache_t pc;
197 	uint8_t *p;
198 
199 	KASSERT(requested_size > 0);
200 
201 	KASSERT((kmflags & KM_SLEEP) || (kmflags & KM_NOSLEEP));
202 	KASSERT(!(kmflags & KM_SLEEP) || !(kmflags & KM_NOSLEEP));
203 
204 	kasan_add_redzone(&requested_size);
205 	size = kmem_roundup_size(requested_size);
206 	allocsz = size + SIZE_SIZE;
207 
208 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
209 	    < kmem_cache_maxidx) {
210 		pc = kmem_cache[index];
211 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
212 	    < kmem_cache_big_maxidx) {
213 		pc = kmem_cache_big[index];
214 	} else {
215 		int ret = uvm_km_kmem_alloc(kmem_va_arena,
216 		    (vsize_t)round_page(size),
217 		    ((kmflags & KM_SLEEP) ? VM_SLEEP : VM_NOSLEEP)
218 		     | VM_INSTANTFIT, (vmem_addr_t *)&p);
219 		if (ret) {
220 			return NULL;
221 		}
222 		FREECHECK_OUT(&kmem_freecheck, p);
223 		return p;
224 	}
225 
226 	p = pool_cache_get(pc, kmflags);
227 
228 	if (__predict_true(p != NULL)) {
229 		FREECHECK_OUT(&kmem_freecheck, p);
230 		kmem_size_set(p, requested_size);
231 		p += SIZE_SIZE;
232 		kasan_mark(p, origsize, size, KASAN_KMEM_REDZONE);
233 		return p;
234 	}
235 	return p;
236 }
237 
238 /*
239  * kmem_intr_zalloc: allocate zeroed wired memory.
240  */
241 void *
242 kmem_intr_zalloc(size_t size, km_flag_t kmflags)
243 {
244 	void *p;
245 
246 	p = kmem_intr_alloc(size, kmflags);
247 	if (p != NULL) {
248 		memset(p, 0, size);
249 	}
250 	return p;
251 }
252 
253 /*
254  * kmem_intr_free: free wired memory allocated by kmem_alloc.
255  */
256 void
257 kmem_intr_free(void *p, size_t requested_size)
258 {
259 	size_t allocsz, index;
260 	size_t size;
261 	pool_cache_t pc;
262 
263 	KASSERT(p != NULL);
264 	KASSERT(requested_size > 0);
265 
266 	kasan_add_redzone(&requested_size);
267 	size = kmem_roundup_size(requested_size);
268 	allocsz = size + SIZE_SIZE;
269 
270 	if ((index = ((allocsz -1) >> KMEM_SHIFT))
271 	    < kmem_cache_maxidx) {
272 		pc = kmem_cache[index];
273 	} else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
274 	    < kmem_cache_big_maxidx) {
275 		pc = kmem_cache_big[index];
276 	} else {
277 		FREECHECK_IN(&kmem_freecheck, p);
278 		uvm_km_kmem_free(kmem_va_arena, (vaddr_t)p,
279 		    round_page(size));
280 		return;
281 	}
282 
283 	kasan_mark(p, size, size, 0);
284 
285 	p = (uint8_t *)p - SIZE_SIZE;
286 	kmem_size_check(p, requested_size);
287 	FREECHECK_IN(&kmem_freecheck, p);
288 	LOCKDEBUG_MEM_CHECK(p, size);
289 
290 	pool_cache_put(pc, p);
291 }
292 
293 /* -------------------------------- Kmem API -------------------------------- */
294 
295 /*
296  * kmem_alloc: allocate wired memory.
297  * => must not be called from interrupt context.
298  */
299 void *
300 kmem_alloc(size_t size, km_flag_t kmflags)
301 {
302 	void *v;
303 
304 	KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
305 	    "kmem(9) should not be used from the interrupt context");
306 	v = kmem_intr_alloc(size, kmflags);
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 }
338 
339 static size_t
340 kmem_create_caches(const struct kmem_cache_info *array,
341     pool_cache_t alloc_table[], size_t maxsize, int shift, int ipl)
342 {
343 	size_t maxidx = 0;
344 	size_t table_unit = (1 << shift);
345 	size_t size = table_unit;
346 	int i;
347 
348 	for (i = 0; array[i].kc_size != 0 ; i++) {
349 		const char *name = array[i].kc_name;
350 		size_t cache_size = array[i].kc_size;
351 		struct pool_allocator *pa;
352 		int flags = 0;
353 		pool_cache_t pc;
354 		size_t align;
355 
356 		if ((cache_size & (CACHE_LINE_SIZE - 1)) == 0)
357 			align = CACHE_LINE_SIZE;
358 		else if ((cache_size & (PAGE_SIZE - 1)) == 0)
359 			align = PAGE_SIZE;
360 		else
361 			align = KMEM_ALIGN;
362 
363 		if (cache_size < CACHE_LINE_SIZE)
364 			flags |= PR_NOTOUCH;
365 
366 		/* check if we reached the requested size */
367 		if (cache_size > maxsize || cache_size > PAGE_SIZE) {
368 			break;
369 		}
370 		if ((cache_size >> shift) > maxidx) {
371 			maxidx = cache_size >> shift;
372 		}
373 
374 		if ((cache_size >> shift) > maxidx) {
375 			maxidx = cache_size >> shift;
376 		}
377 
378 		pa = &pool_allocator_kmem;
379 		pc = pool_cache_init(cache_size, align, 0, flags,
380 		    name, pa, ipl, NULL, NULL, NULL);
381 
382 		while (size <= cache_size) {
383 			alloc_table[(size - 1) >> shift] = pc;
384 			size += table_unit;
385 		}
386 	}
387 	return maxidx;
388 }
389 
390 void
391 kmem_init(void)
392 {
393 	kmem_cache_maxidx = kmem_create_caches(kmem_cache_sizes,
394 	    kmem_cache, KMEM_MAXSIZE, KMEM_SHIFT, IPL_VM);
395 	kmem_cache_big_maxidx = kmem_create_caches(kmem_cache_big_sizes,
396 	    kmem_cache_big, PAGE_SIZE, KMEM_BIG_SHIFT, IPL_VM);
397 }
398 
399 size_t
400 kmem_roundup_size(size_t size)
401 {
402 	return (size + (KMEM_ALIGN - 1)) & ~(KMEM_ALIGN - 1);
403 }
404 
405 /*
406  * Used to dynamically allocate string with kmem accordingly to format.
407  */
408 char *
409 kmem_asprintf(const char *fmt, ...)
410 {
411 	int size __diagused, len;
412 	va_list va;
413 	char *str;
414 
415 	va_start(va, fmt);
416 	len = vsnprintf(NULL, 0, fmt, va);
417 	va_end(va);
418 
419 	str = kmem_alloc(len + 1, KM_SLEEP);
420 
421 	va_start(va, fmt);
422 	size = vsnprintf(str, len + 1, fmt, va);
423 	va_end(va);
424 
425 	KASSERT(size == len);
426 
427 	return str;
428 }
429 
430 char *
431 kmem_strdupsize(const char *str, size_t *lenp, km_flag_t flags)
432 {
433 	size_t len = strlen(str) + 1;
434 	char *ptr = kmem_alloc(len, flags);
435 	if (ptr == NULL)
436 		return NULL;
437 
438 	if (lenp)
439 		*lenp = len;
440 	memcpy(ptr, str, len);
441 	return ptr;
442 }
443 
444 char *
445 kmem_strndup(const char *str, size_t maxlen, km_flag_t flags)
446 {
447 	KASSERT(str != NULL);
448 	KASSERT(maxlen != 0);
449 
450 	size_t len = strnlen(str, maxlen);
451 	char *ptr = kmem_alloc(len + 1, flags);
452 	if (ptr == NULL)
453 		return NULL;
454 
455 	memcpy(ptr, str, len);
456 	ptr[len] = '\0';
457 
458 	return ptr;
459 }
460 
461 void
462 kmem_strfree(char *str)
463 {
464 	if (str == NULL)
465 		return;
466 
467 	kmem_free(str, strlen(str) + 1);
468 }
469 
470 /* --------------------------- DEBUG / DIAGNOSTIC --------------------------- */
471 
472 #if defined(KMEM_SIZE)
473 static void
474 kmem_size_set(void *p, size_t sz)
475 {
476 	struct kmem_header *hd;
477 	hd = (struct kmem_header *)p;
478 	hd->size = sz;
479 }
480 
481 static void
482 kmem_size_check(void *p, size_t sz)
483 {
484 	struct kmem_header *hd;
485 	size_t hsz;
486 
487 	hd = (struct kmem_header *)p;
488 	hsz = hd->size;
489 
490 	if (hsz != sz) {
491 		panic("kmem_free(%p, %zu) != allocated size %zu",
492 		    (const uint8_t *)p + SIZE_SIZE, sz, hsz);
493 	}
494 
495 	hd->size = -1;
496 }
497 #endif /* defined(KMEM_SIZE) */
498