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