subr_kmem.c revision 1.60 1 /* $NetBSD: subr_kmem.c,v 1.60 2014/07/22 07:38:41 maxv Exp $ */
2
3 /*-
4 * Copyright (c) 2009 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.
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 "kmguard" debugging feature compiled
91 * in. See the comment in uvm/uvm_kmguard.c for what kind of bugs it tries
92 * to detect. Even if compiled in, it's disabled by default because it's
93 * very expensive. 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 2014/07/22 07:38:41 maxv Exp $");
104
105 #include <sys/param.h>
106 #include <sys/callback.h>
107 #include <sys/kmem.h>
108 #include <sys/pool.h>
109 #include <sys/debug.h>
110 #include <sys/lockdebug.h>
111 #include <sys/cpu.h>
112
113 #include <uvm/uvm_extern.h>
114 #include <uvm/uvm_map.h>
115 #include <uvm/uvm_kmguard.h>
116
117 #include <lib/libkern/libkern.h>
118
119 struct kmem_cache_info {
120 size_t kc_size;
121 const char * kc_name;
122 };
123
124 static const struct kmem_cache_info kmem_cache_sizes[] = {
125 { 8, "kmem-8" },
126 { 16, "kmem-16" },
127 { 24, "kmem-24" },
128 { 32, "kmem-32" },
129 { 40, "kmem-40" },
130 { 48, "kmem-48" },
131 { 56, "kmem-56" },
132 { 64, "kmem-64" },
133 { 80, "kmem-80" },
134 { 96, "kmem-96" },
135 { 112, "kmem-112" },
136 { 128, "kmem-128" },
137 { 160, "kmem-160" },
138 { 192, "kmem-192" },
139 { 224, "kmem-224" },
140 { 256, "kmem-256" },
141 { 320, "kmem-320" },
142 { 384, "kmem-384" },
143 { 448, "kmem-448" },
144 { 512, "kmem-512" },
145 { 768, "kmem-768" },
146 { 1024, "kmem-1024" },
147 { 0, NULL }
148 };
149
150 static const struct kmem_cache_info kmem_cache_big_sizes[] = {
151 { 2048, "kmem-2048" },
152 { 4096, "kmem-4096" },
153 { 8192, "kmem-8192" },
154 { 16384, "kmem-16384" },
155 { 0, NULL }
156 };
157
158 /*
159 * KMEM_ALIGN is the smallest guaranteed alignment and also the
160 * smallest allocateable quantum.
161 * Every cache size >= CACHE_LINE_SIZE gets CACHE_LINE_SIZE alignment.
162 */
163 #define KMEM_ALIGN 8
164 #define KMEM_SHIFT 3
165 #define KMEM_MAXSIZE 1024
166 #define KMEM_CACHE_COUNT (KMEM_MAXSIZE >> KMEM_SHIFT)
167
168 static pool_cache_t kmem_cache[KMEM_CACHE_COUNT] __cacheline_aligned;
169 static size_t kmem_cache_maxidx __read_mostly;
170
171 #define KMEM_BIG_ALIGN 2048
172 #define KMEM_BIG_SHIFT 11
173 #define KMEM_BIG_MAXSIZE 16384
174 #define KMEM_CACHE_BIG_COUNT (KMEM_BIG_MAXSIZE >> KMEM_BIG_SHIFT)
175
176 static pool_cache_t kmem_cache_big[KMEM_CACHE_BIG_COUNT] __cacheline_aligned;
177 static size_t kmem_cache_big_maxidx __read_mostly;
178
179 #if defined(DIAGNOSTIC) && defined(_HARDKERNEL)
180 #define KMEM_SIZE
181 #define KMEM_REDZONE
182 #endif /* defined(DIAGNOSTIC) */
183
184 #if defined(DEBUG) && defined(_HARDKERNEL)
185 #define KMEM_POISON
186 #define KMEM_GUARD
187 #endif /* defined(DEBUG) */
188
189 #if defined(KMEM_POISON)
190 static int kmem_poison_ctor(void *, void *, int);
191 static void kmem_poison_fill(void *, size_t);
192 static void kmem_poison_check(void *, size_t);
193 #else /* defined(KMEM_POISON) */
194 #define kmem_poison_fill(p, sz) /* nothing */
195 #define kmem_poison_check(p, sz) /* nothing */
196 #endif /* defined(KMEM_POISON) */
197
198 #if defined(KMEM_REDZONE)
199 #define REDZONE_SIZE 2
200 static void kmem_redzone_fill(void *, size_t);
201 static void kmem_redzone_check(void *, size_t);
202 #else /* defined(KMEM_REDZONE) */
203 #define REDZONE_SIZE 0
204 #define kmem_redzone_fill(p, sz) /* nothing */
205 #define kmem_redzone_check(p, sz) /* nothing */
206 #endif /* defined(KMEM_REDZONE) */
207
208 #if defined(KMEM_SIZE)
209 struct kmem_header {
210 size_t size;
211 } __aligned(KMEM_ALIGN);
212 #define SIZE_SIZE sizeof(struct kmem_header)
213 static void kmem_size_set(void *, size_t);
214 static void kmem_size_check(void *, size_t);
215 #else
216 #define SIZE_SIZE 0
217 #define kmem_size_set(p, sz) /* nothing */
218 #define kmem_size_check(p, sz) /* nothing */
219 #endif
220
221 #if defined(KMEM_GUARD)
222 #ifndef KMEM_GUARD_DEPTH
223 #define KMEM_GUARD_DEPTH 0
224 #endif
225 int kmem_guard_depth = KMEM_GUARD_DEPTH;
226 size_t kmem_guard_size;
227 static struct uvm_kmguard kmem_guard;
228 static void *kmem_freecheck;
229 #endif /* defined(KMEM_GUARD) */
230
231 CTASSERT(KM_SLEEP == PR_WAITOK);
232 CTASSERT(KM_NOSLEEP == PR_NOWAIT);
233
234 /*
235 * kmem_intr_alloc: allocate wired memory.
236 */
237
238 void *
239 kmem_intr_alloc(size_t requested_size, km_flag_t kmflags)
240 {
241 size_t allocsz, index;
242 size_t size;
243 pool_cache_t pc;
244 uint8_t *p;
245
246 KASSERT(requested_size > 0);
247
248 #ifdef KMEM_GUARD
249 if (requested_size <= kmem_guard_size) {
250 return uvm_kmguard_alloc(&kmem_guard, requested_size,
251 (kmflags & KM_SLEEP) != 0);
252 }
253 #endif
254 size = kmem_roundup_size(requested_size);
255 allocsz = size + SIZE_SIZE;
256
257 #ifdef KMEM_REDZONE
258 if (size - requested_size < REDZONE_SIZE) {
259 /* If there isn't enough space in the padding, allocate
260 * one more memory chunk for the red zone. */
261 allocsz += kmem_roundup_size(REDZONE_SIZE);
262 }
263 #endif
264
265 if ((index = ((allocsz -1) >> KMEM_SHIFT))
266 < kmem_cache_maxidx) {
267 pc = kmem_cache[index];
268 } else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
269 < kmem_cache_big_maxidx) {
270 pc = kmem_cache_big[index];
271 } else {
272 int ret = uvm_km_kmem_alloc(kmem_va_arena,
273 (vsize_t)round_page(size),
274 ((kmflags & KM_SLEEP) ? VM_SLEEP : VM_NOSLEEP)
275 | VM_INSTANTFIT, (vmem_addr_t *)&p);
276 if (ret) {
277 return NULL;
278 }
279 FREECHECK_OUT(&kmem_freecheck, p);
280 return p;
281 }
282
283 p = pool_cache_get(pc, kmflags);
284
285 if (__predict_true(p != NULL)) {
286 kmem_poison_check(p, allocsz);
287 FREECHECK_OUT(&kmem_freecheck, p);
288 kmem_size_set(p, requested_size);
289 kmem_redzone_fill(p, requested_size + SIZE_SIZE);
290
291 return p + SIZE_SIZE;
292 }
293 return p;
294 }
295
296 /*
297 * kmem_intr_zalloc: allocate zeroed wired memory.
298 */
299
300 void *
301 kmem_intr_zalloc(size_t size, km_flag_t kmflags)
302 {
303 void *p;
304
305 p = kmem_intr_alloc(size, kmflags);
306 if (p != NULL) {
307 memset(p, 0, size);
308 }
309 return p;
310 }
311
312 /*
313 * kmem_intr_free: free wired memory allocated by kmem_alloc.
314 */
315
316 void
317 kmem_intr_free(void *p, size_t requested_size)
318 {
319 size_t allocsz, index;
320 size_t size;
321 pool_cache_t pc;
322
323 KASSERT(p != NULL);
324 KASSERT(requested_size > 0);
325
326 #ifdef KMEM_GUARD
327 if (requested_size <= kmem_guard_size) {
328 uvm_kmguard_free(&kmem_guard, requested_size, p);
329 return;
330 }
331 #endif
332
333 size = kmem_roundup_size(requested_size);
334 allocsz = size + SIZE_SIZE;
335
336 #ifdef KMEM_REDZONE
337 if (size - requested_size < REDZONE_SIZE) {
338 allocsz += kmem_roundup_size(REDZONE_SIZE);
339 }
340 #endif
341
342 if ((index = ((allocsz -1) >> KMEM_SHIFT))
343 < kmem_cache_maxidx) {
344 pc = kmem_cache[index];
345 } else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
346 < kmem_cache_big_maxidx) {
347 pc = kmem_cache_big[index];
348 } else {
349 FREECHECK_IN(&kmem_freecheck, p);
350 uvm_km_kmem_free(kmem_va_arena, (vaddr_t)p,
351 round_page(size));
352 return;
353 }
354
355 p = (uint8_t *)p - SIZE_SIZE;
356 kmem_size_check(p, requested_size);
357 kmem_redzone_check(p, requested_size + SIZE_SIZE);
358 FREECHECK_IN(&kmem_freecheck, p);
359 LOCKDEBUG_MEM_CHECK(p, size);
360 kmem_poison_fill(p, allocsz);
361
362 pool_cache_put(pc, p);
363 }
364
365 /* ---- kmem API */
366
367 /*
368 * kmem_alloc: allocate wired memory.
369 * => must not be called from interrupt context.
370 */
371
372 void *
373 kmem_alloc(size_t size, km_flag_t kmflags)
374 {
375
376 KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
377 "kmem(9) should not be used from the interrupt context");
378 return kmem_intr_alloc(size, kmflags);
379 }
380
381 /*
382 * kmem_zalloc: allocate zeroed wired memory.
383 * => must not be called from interrupt context.
384 */
385
386 void *
387 kmem_zalloc(size_t size, km_flag_t kmflags)
388 {
389
390 KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
391 "kmem(9) should not be used from the interrupt context");
392 return kmem_intr_zalloc(size, kmflags);
393 }
394
395 /*
396 * kmem_free: free wired memory allocated by kmem_alloc.
397 * => must not be called from interrupt context.
398 */
399
400 void
401 kmem_free(void *p, size_t size)
402 {
403
404 KASSERT(!cpu_intr_p());
405 KASSERT(!cpu_softintr_p());
406 kmem_intr_free(p, size);
407 }
408
409 static size_t
410 kmem_create_caches(const struct kmem_cache_info *array,
411 pool_cache_t alloc_table[], size_t maxsize, int shift, int ipl)
412 {
413 size_t maxidx = 0;
414 size_t table_unit = (1 << shift);
415 size_t size = table_unit;
416 int i;
417
418 for (i = 0; array[i].kc_size != 0 ; i++) {
419 const char *name = array[i].kc_name;
420 size_t cache_size = array[i].kc_size;
421 struct pool_allocator *pa;
422 int flags = PR_NOALIGN;
423 pool_cache_t pc;
424 size_t align;
425
426 if ((cache_size & (CACHE_LINE_SIZE - 1)) == 0)
427 align = CACHE_LINE_SIZE;
428 else if ((cache_size & (PAGE_SIZE - 1)) == 0)
429 align = PAGE_SIZE;
430 else
431 align = KMEM_ALIGN;
432
433 if (cache_size < CACHE_LINE_SIZE)
434 flags |= PR_NOTOUCH;
435
436 /* check if we reached the requested size */
437 if (cache_size > maxsize || cache_size > PAGE_SIZE) {
438 break;
439 }
440 if ((cache_size >> shift) > maxidx) {
441 maxidx = cache_size >> shift;
442 }
443
444 if ((cache_size >> shift) > maxidx) {
445 maxidx = cache_size >> shift;
446 }
447
448 pa = &pool_allocator_kmem;
449 #if defined(KMEM_POISON)
450 pc = pool_cache_init(cache_size, align, 0, flags,
451 name, pa, ipl, kmem_poison_ctor,
452 NULL, (void *)cache_size);
453 #else /* defined(KMEM_POISON) */
454 pc = pool_cache_init(cache_size, align, 0, flags,
455 name, pa, ipl, NULL, NULL, NULL);
456 #endif /* defined(KMEM_POISON) */
457
458 while (size <= cache_size) {
459 alloc_table[(size - 1) >> shift] = pc;
460 size += table_unit;
461 }
462 }
463 return maxidx;
464 }
465
466 void
467 kmem_init(void)
468 {
469
470 #ifdef KMEM_GUARD
471 uvm_kmguard_init(&kmem_guard, &kmem_guard_depth, &kmem_guard_size,
472 kmem_va_arena);
473 #endif
474 kmem_cache_maxidx = kmem_create_caches(kmem_cache_sizes,
475 kmem_cache, KMEM_MAXSIZE, KMEM_SHIFT, IPL_VM);
476 kmem_cache_big_maxidx = kmem_create_caches(kmem_cache_big_sizes,
477 kmem_cache_big, PAGE_SIZE, KMEM_BIG_SHIFT, IPL_VM);
478 }
479
480 size_t
481 kmem_roundup_size(size_t size)
482 {
483
484 return (size + (KMEM_ALIGN - 1)) & ~(KMEM_ALIGN - 1);
485 }
486
487 /* ------------------ DEBUG / DIAGNOSTIC ------------------ */
488
489 #if defined(KMEM_POISON) || defined(KMEM_REDZONE)
490 #if defined(_LP64)
491 #define PRIME 0x9e37fffffffc0000UL
492 #else /* defined(_LP64) */
493 #define PRIME 0x9e3779b1
494 #endif /* defined(_LP64) */
495
496 static inline uint8_t
497 kmem_pattern_generate(const void *p)
498 {
499 return (uint8_t)(((uintptr_t)p) * PRIME
500 >> ((sizeof(uintptr_t) - sizeof(uint8_t))) * CHAR_BIT);
501 }
502 #endif /* defined(KMEM_POISON) || defined(KMEM_REDZONE) */
503
504 #if defined(KMEM_POISON)
505 static int
506 kmem_poison_ctor(void *arg, void *obj, int flag)
507 {
508 size_t sz = (size_t)arg;
509
510 kmem_poison_fill(obj, sz);
511
512 return 0;
513 }
514
515 static void
516 kmem_poison_fill(void *p, size_t sz)
517 {
518 uint8_t *cp;
519 const uint8_t *ep;
520
521 cp = p;
522 ep = cp + sz;
523 while (cp < ep) {
524 *cp = kmem_pattern_generate(cp);
525 cp++;
526 }
527 }
528
529 static void
530 kmem_poison_check(void *p, size_t sz)
531 {
532 uint8_t *cp;
533 const uint8_t *ep;
534
535 cp = p;
536 ep = cp + sz;
537 while (cp < ep) {
538 const uint8_t expected = kmem_pattern_generate(cp);
539
540 if (*cp != expected) {
541 panic("%s: %p: 0x%02x != 0x%02x\n",
542 __func__, cp, *cp, expected);
543 }
544 cp++;
545 }
546 }
547 #endif /* defined(KMEM_POISON) */
548
549 #if defined(KMEM_SIZE)
550 static void
551 kmem_size_set(void *p, size_t sz)
552 {
553 struct kmem_header *hd;
554 hd = (struct kmem_header *)p;
555 hd->size = sz;
556 }
557
558 static void
559 kmem_size_check(void *p, size_t sz)
560 {
561 struct kmem_header *hd;
562 size_t hsz;
563
564 hd = (struct kmem_header *)p;
565 hsz = hd->size;
566
567 if (hsz != sz) {
568 panic("kmem_free(%p, %zu) != allocated size %zu",
569 (const uint8_t *)p + SIZE_SIZE, sz, hsz);
570 }
571 }
572 #endif /* defined(KMEM_SIZE) */
573
574 #if defined(KMEM_REDZONE)
575 #define STATIC_BYTE 0xFE
576 CTASSERT(REDZONE_SIZE > 1);
577 static void
578 kmem_redzone_fill(void *p, size_t sz)
579 {
580 uint8_t *cp, pat;
581 const uint8_t *ep;
582
583 cp = (uint8_t *)p + sz;
584 ep = cp + REDZONE_SIZE;
585
586 /*
587 * We really don't want the first byte of the red zone to be '\0';
588 * an off-by-one in a string may not be properly detected.
589 */
590 pat = kmem_pattern_generate(cp);
591 *cp = (pat == '\0') ? STATIC_BYTE: pat;
592 cp++;
593
594 while (cp < ep) {
595 *cp = kmem_pattern_generate(cp);
596 cp++;
597 }
598 }
599
600 static void
601 kmem_redzone_check(void *p, size_t sz)
602 {
603 uint8_t *cp, pat, expected;
604 const uint8_t *ep;
605
606 cp = (uint8_t *)p + sz;
607 ep = cp + REDZONE_SIZE;
608
609 pat = kmem_pattern_generate(cp);
610 expected = (pat == '\0') ? STATIC_BYTE: pat;
611 if (expected != *cp) {
612 panic("%s: %p: 0x%02x != 0x%02x\n",
613 __func__, cp, *cp, expected);
614 }
615 cp++;
616
617 while (cp < ep) {
618 expected = kmem_pattern_generate(cp);
619 if (*cp != expected) {
620 panic("%s: %p: 0x%02x != 0x%02x\n",
621 __func__, cp, *cp, expected);
622 }
623 cp++;
624 }
625 }
626 #endif /* defined(KMEM_REDZONE) */
627
628
629 /*
630 * Used to dynamically allocate string with kmem accordingly to format.
631 */
632 char *
633 kmem_asprintf(const char *fmt, ...)
634 {
635 int size __diagused, len;
636 va_list va;
637 char *str;
638
639 va_start(va, fmt);
640 len = vsnprintf(NULL, 0, fmt, va);
641 va_end(va);
642
643 str = kmem_alloc(len + 1, KM_SLEEP);
644
645 va_start(va, fmt);
646 size = vsnprintf(str, len + 1, fmt, va);
647 va_end(va);
648
649 KASSERT(size == len);
650
651 return str;
652 }
653