subr_kmem.c revision 1.62.4.1 1 /* $NetBSD: subr_kmem.c,v 1.62.4.1 2017/04/21 16:54:02 bouyer 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 * 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 "kmem_guard" debugging feature compiled
91 * in. See the comment below for what kind of bugs it tries to detect. Even
92 * if compiled in, it's disabled by default because it's very expensive.
93 * 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.62.4.1 2017/04/21 16:54:02 bouyer Exp $");
104
105 #ifdef _KERNEL_OPT
106 #include "opt_kmem.h"
107 #endif
108
109 #include <sys/param.h>
110 #include <sys/callback.h>
111 #include <sys/kmem.h>
112 #include <sys/pool.h>
113 #include <sys/debug.h>
114 #include <sys/lockdebug.h>
115 #include <sys/cpu.h>
116
117 #include <uvm/uvm_extern.h>
118 #include <uvm/uvm_map.h>
119
120 #include <lib/libkern/libkern.h>
121
122 struct kmem_cache_info {
123 size_t kc_size;
124 const char * kc_name;
125 };
126
127 static const struct kmem_cache_info kmem_cache_sizes[] = {
128 { 8, "kmem-8" },
129 { 16, "kmem-16" },
130 { 24, "kmem-24" },
131 { 32, "kmem-32" },
132 { 40, "kmem-40" },
133 { 48, "kmem-48" },
134 { 56, "kmem-56" },
135 { 64, "kmem-64" },
136 { 80, "kmem-80" },
137 { 96, "kmem-96" },
138 { 112, "kmem-112" },
139 { 128, "kmem-128" },
140 { 160, "kmem-160" },
141 { 192, "kmem-192" },
142 { 224, "kmem-224" },
143 { 256, "kmem-256" },
144 { 320, "kmem-320" },
145 { 384, "kmem-384" },
146 { 448, "kmem-448" },
147 { 512, "kmem-512" },
148 { 768, "kmem-768" },
149 { 1024, "kmem-1024" },
150 { 0, NULL }
151 };
152
153 static const struct kmem_cache_info kmem_cache_big_sizes[] = {
154 { 2048, "kmem-2048" },
155 { 4096, "kmem-4096" },
156 { 8192, "kmem-8192" },
157 { 16384, "kmem-16384" },
158 { 0, NULL }
159 };
160
161 /*
162 * KMEM_ALIGN is the smallest guaranteed alignment and also the
163 * smallest allocateable quantum.
164 * Every cache size >= CACHE_LINE_SIZE gets CACHE_LINE_SIZE alignment.
165 */
166 #define KMEM_ALIGN 8
167 #define KMEM_SHIFT 3
168 #define KMEM_MAXSIZE 1024
169 #define KMEM_CACHE_COUNT (KMEM_MAXSIZE >> KMEM_SHIFT)
170
171 static pool_cache_t kmem_cache[KMEM_CACHE_COUNT] __cacheline_aligned;
172 static size_t kmem_cache_maxidx __read_mostly;
173
174 #define KMEM_BIG_ALIGN 2048
175 #define KMEM_BIG_SHIFT 11
176 #define KMEM_BIG_MAXSIZE 16384
177 #define KMEM_CACHE_BIG_COUNT (KMEM_BIG_MAXSIZE >> KMEM_BIG_SHIFT)
178
179 static pool_cache_t kmem_cache_big[KMEM_CACHE_BIG_COUNT] __cacheline_aligned;
180 static size_t kmem_cache_big_maxidx __read_mostly;
181
182 #if defined(DIAGNOSTIC) && defined(_HARDKERNEL)
183 #define KMEM_SIZE
184 #define KMEM_REDZONE
185 #endif /* defined(DIAGNOSTIC) */
186
187 #if defined(DEBUG) && defined(_HARDKERNEL)
188 #define KMEM_SIZE
189 #define KMEM_POISON
190 #define KMEM_GUARD
191 static void *kmem_freecheck;
192 #endif /* defined(DEBUG) */
193
194 #if defined(KMEM_POISON)
195 static int kmem_poison_ctor(void *, void *, int);
196 static void kmem_poison_fill(void *, size_t);
197 static void kmem_poison_check(void *, size_t);
198 #else /* defined(KMEM_POISON) */
199 #define kmem_poison_fill(p, sz) /* nothing */
200 #define kmem_poison_check(p, sz) /* nothing */
201 #endif /* defined(KMEM_POISON) */
202
203 #if defined(KMEM_REDZONE)
204 #define REDZONE_SIZE 2
205 static void kmem_redzone_fill(void *, size_t);
206 static void kmem_redzone_check(void *, size_t);
207 #else /* defined(KMEM_REDZONE) */
208 #define REDZONE_SIZE 0
209 #define kmem_redzone_fill(p, sz) /* nothing */
210 #define kmem_redzone_check(p, sz) /* nothing */
211 #endif /* defined(KMEM_REDZONE) */
212
213 #if defined(KMEM_SIZE)
214 struct kmem_header {
215 size_t size;
216 } __aligned(KMEM_ALIGN);
217 #define SIZE_SIZE sizeof(struct kmem_header)
218 static void kmem_size_set(void *, size_t);
219 static void kmem_size_check(void *, size_t);
220 #else
221 #define SIZE_SIZE 0
222 #define kmem_size_set(p, sz) /* nothing */
223 #define kmem_size_check(p, sz) /* nothing */
224 #endif
225
226 #if defined(KMEM_GUARD)
227 #ifndef KMEM_GUARD_DEPTH
228 #define KMEM_GUARD_DEPTH 0
229 #endif
230 struct kmem_guard {
231 u_int kg_depth;
232 intptr_t * kg_fifo;
233 u_int kg_rotor;
234 vmem_t * kg_vmem;
235 };
236
237 static bool kmem_guard_init(struct kmem_guard *, u_int, vmem_t *);
238 static void *kmem_guard_alloc(struct kmem_guard *, size_t, bool);
239 static void kmem_guard_free(struct kmem_guard *, size_t, void *);
240
241 int kmem_guard_depth = KMEM_GUARD_DEPTH;
242 static bool kmem_guard_enabled;
243 static struct kmem_guard kmem_guard;
244 #endif /* defined(KMEM_GUARD) */
245
246 CTASSERT(KM_SLEEP == PR_WAITOK);
247 CTASSERT(KM_NOSLEEP == PR_NOWAIT);
248
249 /*
250 * kmem_intr_alloc: allocate wired memory.
251 */
252
253 void *
254 kmem_intr_alloc(size_t requested_size, km_flag_t kmflags)
255 {
256 size_t allocsz, index;
257 size_t size;
258 pool_cache_t pc;
259 uint8_t *p;
260
261 KASSERT(requested_size > 0);
262
263 #ifdef KMEM_GUARD
264 if (kmem_guard_enabled) {
265 return kmem_guard_alloc(&kmem_guard, requested_size,
266 (kmflags & KM_SLEEP) != 0);
267 }
268 #endif
269 size = kmem_roundup_size(requested_size);
270 allocsz = size + SIZE_SIZE;
271
272 #ifdef KMEM_REDZONE
273 if (size - requested_size < REDZONE_SIZE) {
274 /* If there isn't enough space in the padding, allocate
275 * one more memory chunk for the red zone. */
276 allocsz += kmem_roundup_size(REDZONE_SIZE);
277 }
278 #endif
279
280 if ((index = ((allocsz -1) >> KMEM_SHIFT))
281 < kmem_cache_maxidx) {
282 pc = kmem_cache[index];
283 } else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
284 < kmem_cache_big_maxidx) {
285 pc = kmem_cache_big[index];
286 } else {
287 int ret = uvm_km_kmem_alloc(kmem_va_arena,
288 (vsize_t)round_page(size),
289 ((kmflags & KM_SLEEP) ? VM_SLEEP : VM_NOSLEEP)
290 | VM_INSTANTFIT, (vmem_addr_t *)&p);
291 if (ret) {
292 return NULL;
293 }
294 FREECHECK_OUT(&kmem_freecheck, p);
295 return p;
296 }
297
298 p = pool_cache_get(pc, kmflags);
299
300 if (__predict_true(p != NULL)) {
301 kmem_poison_check(p, allocsz);
302 FREECHECK_OUT(&kmem_freecheck, p);
303 kmem_size_set(p, requested_size);
304 kmem_redzone_fill(p, requested_size + SIZE_SIZE);
305
306 return p + SIZE_SIZE;
307 }
308 return p;
309 }
310
311 /*
312 * kmem_intr_zalloc: allocate zeroed wired memory.
313 */
314
315 void *
316 kmem_intr_zalloc(size_t size, km_flag_t kmflags)
317 {
318 void *p;
319
320 p = kmem_intr_alloc(size, kmflags);
321 if (p != NULL) {
322 memset(p, 0, size);
323 }
324 return p;
325 }
326
327 /*
328 * kmem_intr_free: free wired memory allocated by kmem_alloc.
329 */
330
331 void
332 kmem_intr_free(void *p, size_t requested_size)
333 {
334 size_t allocsz, index;
335 size_t size;
336 pool_cache_t pc;
337
338 KASSERT(p != NULL);
339 KASSERT(requested_size > 0);
340
341 #ifdef KMEM_GUARD
342 if (kmem_guard_enabled) {
343 kmem_guard_free(&kmem_guard, requested_size, p);
344 return;
345 }
346 #endif
347
348 size = kmem_roundup_size(requested_size);
349 allocsz = size + SIZE_SIZE;
350
351 #ifdef KMEM_REDZONE
352 if (size - requested_size < REDZONE_SIZE) {
353 allocsz += kmem_roundup_size(REDZONE_SIZE);
354 }
355 #endif
356
357 if ((index = ((allocsz -1) >> KMEM_SHIFT))
358 < kmem_cache_maxidx) {
359 pc = kmem_cache[index];
360 } else if ((index = ((allocsz - 1) >> KMEM_BIG_SHIFT))
361 < kmem_cache_big_maxidx) {
362 pc = kmem_cache_big[index];
363 } else {
364 FREECHECK_IN(&kmem_freecheck, p);
365 uvm_km_kmem_free(kmem_va_arena, (vaddr_t)p,
366 round_page(size));
367 return;
368 }
369
370 p = (uint8_t *)p - SIZE_SIZE;
371 kmem_size_check(p, requested_size);
372 kmem_redzone_check(p, requested_size + SIZE_SIZE);
373 FREECHECK_IN(&kmem_freecheck, p);
374 LOCKDEBUG_MEM_CHECK(p, size);
375 kmem_poison_fill(p, allocsz);
376
377 pool_cache_put(pc, p);
378 }
379
380 /* ---- kmem API */
381
382 /*
383 * kmem_alloc: allocate wired memory.
384 * => must not be called from interrupt context.
385 */
386
387 void *
388 kmem_alloc(size_t size, km_flag_t kmflags)
389 {
390 void *v;
391
392 KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
393 "kmem(9) should not be used from the interrupt context");
394 v = kmem_intr_alloc(size, kmflags);
395 KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
396 return v;
397 }
398
399 /*
400 * kmem_zalloc: allocate zeroed wired memory.
401 * => must not be called from interrupt context.
402 */
403
404 void *
405 kmem_zalloc(size_t size, km_flag_t kmflags)
406 {
407 void *v;
408
409 KASSERTMSG((!cpu_intr_p() && !cpu_softintr_p()),
410 "kmem(9) should not be used from the interrupt context");
411 v = kmem_intr_zalloc(size, kmflags);
412 KASSERT(v || (kmflags & KM_NOSLEEP) != 0);
413 return v;
414 }
415
416 /*
417 * kmem_free: free wired memory allocated by kmem_alloc.
418 * => must not be called from interrupt context.
419 */
420
421 void
422 kmem_free(void *p, size_t size)
423 {
424 KASSERT(!cpu_intr_p());
425 KASSERT(!cpu_softintr_p());
426 kmem_intr_free(p, size);
427 }
428
429 static size_t
430 kmem_create_caches(const struct kmem_cache_info *array,
431 pool_cache_t alloc_table[], size_t maxsize, int shift, int ipl)
432 {
433 size_t maxidx = 0;
434 size_t table_unit = (1 << shift);
435 size_t size = table_unit;
436 int i;
437
438 for (i = 0; array[i].kc_size != 0 ; i++) {
439 const char *name = array[i].kc_name;
440 size_t cache_size = array[i].kc_size;
441 struct pool_allocator *pa;
442 int flags = PR_NOALIGN;
443 pool_cache_t pc;
444 size_t align;
445
446 if ((cache_size & (CACHE_LINE_SIZE - 1)) == 0)
447 align = CACHE_LINE_SIZE;
448 else if ((cache_size & (PAGE_SIZE - 1)) == 0)
449 align = PAGE_SIZE;
450 else
451 align = KMEM_ALIGN;
452
453 if (cache_size < CACHE_LINE_SIZE)
454 flags |= PR_NOTOUCH;
455
456 /* check if we reached the requested size */
457 if (cache_size > maxsize || cache_size > PAGE_SIZE) {
458 break;
459 }
460 if ((cache_size >> shift) > maxidx) {
461 maxidx = cache_size >> shift;
462 }
463
464 if ((cache_size >> shift) > maxidx) {
465 maxidx = cache_size >> shift;
466 }
467
468 pa = &pool_allocator_kmem;
469 #if defined(KMEM_POISON)
470 pc = pool_cache_init(cache_size, align, 0, flags,
471 name, pa, ipl, kmem_poison_ctor,
472 NULL, (void *)cache_size);
473 #else /* defined(KMEM_POISON) */
474 pc = pool_cache_init(cache_size, align, 0, flags,
475 name, pa, ipl, NULL, NULL, NULL);
476 #endif /* defined(KMEM_POISON) */
477
478 while (size <= cache_size) {
479 alloc_table[(size - 1) >> shift] = pc;
480 size += table_unit;
481 }
482 }
483 return maxidx;
484 }
485
486 void
487 kmem_init(void)
488 {
489 #ifdef KMEM_GUARD
490 kmem_guard_enabled = kmem_guard_init(&kmem_guard, kmem_guard_depth,
491 kmem_va_arena);
492 #endif
493 kmem_cache_maxidx = kmem_create_caches(kmem_cache_sizes,
494 kmem_cache, KMEM_MAXSIZE, KMEM_SHIFT, IPL_VM);
495 kmem_cache_big_maxidx = kmem_create_caches(kmem_cache_big_sizes,
496 kmem_cache_big, PAGE_SIZE, KMEM_BIG_SHIFT, IPL_VM);
497 }
498
499 size_t
500 kmem_roundup_size(size_t size)
501 {
502 return (size + (KMEM_ALIGN - 1)) & ~(KMEM_ALIGN - 1);
503 }
504
505 /*
506 * Used to dynamically allocate string with kmem accordingly to format.
507 */
508 char *
509 kmem_asprintf(const char *fmt, ...)
510 {
511 int size __diagused, len;
512 va_list va;
513 char *str;
514
515 va_start(va, fmt);
516 len = vsnprintf(NULL, 0, fmt, va);
517 va_end(va);
518
519 str = kmem_alloc(len + 1, KM_SLEEP);
520
521 va_start(va, fmt);
522 size = vsnprintf(str, len + 1, fmt, va);
523 va_end(va);
524
525 KASSERT(size == len);
526
527 return str;
528 }
529
530 /* ------------------ DEBUG / DIAGNOSTIC ------------------ */
531
532 #if defined(KMEM_POISON) || defined(KMEM_REDZONE)
533 #if defined(_LP64)
534 #define PRIME 0x9e37fffffffc0000UL
535 #else /* defined(_LP64) */
536 #define PRIME 0x9e3779b1
537 #endif /* defined(_LP64) */
538
539 static inline uint8_t
540 kmem_pattern_generate(const void *p)
541 {
542 return (uint8_t)(((uintptr_t)p) * PRIME
543 >> ((sizeof(uintptr_t) - sizeof(uint8_t))) * CHAR_BIT);
544 }
545 #endif /* defined(KMEM_POISON) || defined(KMEM_REDZONE) */
546
547 #if defined(KMEM_POISON)
548 static int
549 kmem_poison_ctor(void *arg, void *obj, int flag)
550 {
551 size_t sz = (size_t)arg;
552
553 kmem_poison_fill(obj, sz);
554
555 return 0;
556 }
557
558 static void
559 kmem_poison_fill(void *p, size_t sz)
560 {
561 uint8_t *cp;
562 const uint8_t *ep;
563
564 cp = p;
565 ep = cp + sz;
566 while (cp < ep) {
567 *cp = kmem_pattern_generate(cp);
568 cp++;
569 }
570 }
571
572 static void
573 kmem_poison_check(void *p, size_t sz)
574 {
575 uint8_t *cp;
576 const uint8_t *ep;
577
578 cp = p;
579 ep = cp + sz;
580 while (cp < ep) {
581 const uint8_t expected = kmem_pattern_generate(cp);
582
583 if (*cp != expected) {
584 panic("%s: %p: 0x%02x != 0x%02x\n",
585 __func__, cp, *cp, expected);
586 }
587 cp++;
588 }
589 }
590 #endif /* defined(KMEM_POISON) */
591
592 #if defined(KMEM_SIZE)
593 static void
594 kmem_size_set(void *p, size_t sz)
595 {
596 struct kmem_header *hd;
597 hd = (struct kmem_header *)p;
598 hd->size = sz;
599 }
600
601 static void
602 kmem_size_check(void *p, size_t sz)
603 {
604 struct kmem_header *hd;
605 size_t hsz;
606
607 hd = (struct kmem_header *)p;
608 hsz = hd->size;
609
610 if (hsz != sz) {
611 panic("kmem_free(%p, %zu) != allocated size %zu",
612 (const uint8_t *)p + SIZE_SIZE, sz, hsz);
613 }
614 }
615 #endif /* defined(KMEM_SIZE) */
616
617 #if defined(KMEM_REDZONE)
618 #define STATIC_BYTE 0xFE
619 CTASSERT(REDZONE_SIZE > 1);
620 static void
621 kmem_redzone_fill(void *p, size_t sz)
622 {
623 uint8_t *cp, pat;
624 const uint8_t *ep;
625
626 cp = (uint8_t *)p + sz;
627 ep = cp + REDZONE_SIZE;
628
629 /*
630 * We really don't want the first byte of the red zone to be '\0';
631 * an off-by-one in a string may not be properly detected.
632 */
633 pat = kmem_pattern_generate(cp);
634 *cp = (pat == '\0') ? STATIC_BYTE: pat;
635 cp++;
636
637 while (cp < ep) {
638 *cp = kmem_pattern_generate(cp);
639 cp++;
640 }
641 }
642
643 static void
644 kmem_redzone_check(void *p, size_t sz)
645 {
646 uint8_t *cp, pat, expected;
647 const uint8_t *ep;
648
649 cp = (uint8_t *)p + sz;
650 ep = cp + REDZONE_SIZE;
651
652 pat = kmem_pattern_generate(cp);
653 expected = (pat == '\0') ? STATIC_BYTE: pat;
654 if (expected != *cp) {
655 panic("%s: %p: 0x%02x != 0x%02x\n",
656 __func__, cp, *cp, expected);
657 }
658 cp++;
659
660 while (cp < ep) {
661 expected = kmem_pattern_generate(cp);
662 if (*cp != expected) {
663 panic("%s: %p: 0x%02x != 0x%02x\n",
664 __func__, cp, *cp, expected);
665 }
666 cp++;
667 }
668 }
669 #endif /* defined(KMEM_REDZONE) */
670
671
672 #if defined(KMEM_GUARD)
673 /*
674 * The ultimate memory allocator for debugging, baby. It tries to catch:
675 *
676 * 1. Overflow, in realtime. A guard page sits immediately after the
677 * requested area; a read/write overflow therefore triggers a page
678 * fault.
679 * 2. Invalid pointer/size passed, at free. A kmem_header structure sits
680 * just before the requested area, and holds the allocated size. Any
681 * difference with what is given at free triggers a panic.
682 * 3. Underflow, at free. If an underflow occurs, the kmem header will be
683 * modified, and 2. will trigger a panic.
684 * 4. Use-after-free. When freeing, the memory is unmapped, and depending
685 * on the value of kmem_guard_depth, the kernel will more or less delay
686 * the recycling of that memory. Which means that any ulterior read/write
687 * access to the memory will trigger a page fault, given it hasn't been
688 * recycled yet.
689 */
690
691 #include <sys/atomic.h>
692 #include <uvm/uvm.h>
693
694 static bool
695 kmem_guard_init(struct kmem_guard *kg, u_int depth, vmem_t *vm)
696 {
697 vaddr_t va;
698
699 /* If not enabled, we have nothing to do. */
700 if (depth == 0) {
701 return false;
702 }
703 depth = roundup(depth, PAGE_SIZE / sizeof(void *));
704 KASSERT(depth != 0);
705
706 /*
707 * Allocate fifo.
708 */
709 va = uvm_km_alloc(kernel_map, depth * sizeof(void *), PAGE_SIZE,
710 UVM_KMF_WIRED | UVM_KMF_ZERO);
711 if (va == 0) {
712 return false;
713 }
714
715 /*
716 * Init object.
717 */
718 kg->kg_vmem = vm;
719 kg->kg_fifo = (void *)va;
720 kg->kg_depth = depth;
721 kg->kg_rotor = 0;
722
723 printf("kmem_guard(%p): depth %d\n", kg, depth);
724 return true;
725 }
726
727 static void *
728 kmem_guard_alloc(struct kmem_guard *kg, size_t requested_size, bool waitok)
729 {
730 struct vm_page *pg;
731 vm_flag_t flags;
732 vmem_addr_t va;
733 vaddr_t loopva;
734 vsize_t loopsize;
735 size_t size;
736 void **p;
737
738 /*
739 * Compute the size: take the kmem header into account, and add a guard
740 * page at the end.
741 */
742 size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE;
743
744 /* Allocate pages of kernel VA, but do not map anything in yet. */
745 flags = VM_BESTFIT | (waitok ? VM_SLEEP : VM_NOSLEEP);
746 if (vmem_alloc(kg->kg_vmem, size, flags, &va) != 0) {
747 return NULL;
748 }
749
750 loopva = va;
751 loopsize = size - PAGE_SIZE;
752
753 while (loopsize) {
754 pg = uvm_pagealloc(NULL, loopva, NULL, 0);
755 if (__predict_false(pg == NULL)) {
756 if (waitok) {
757 uvm_wait("kmem_guard");
758 continue;
759 } else {
760 uvm_km_pgremove_intrsafe(kernel_map, va,
761 va + size);
762 vmem_free(kg->kg_vmem, va, size);
763 return NULL;
764 }
765 }
766
767 pg->flags &= ~PG_BUSY; /* new page */
768 UVM_PAGE_OWN(pg, NULL);
769 pmap_kenter_pa(loopva, VM_PAGE_TO_PHYS(pg),
770 VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE);
771
772 loopva += PAGE_SIZE;
773 loopsize -= PAGE_SIZE;
774 }
775
776 pmap_update(pmap_kernel());
777
778 /*
779 * Offset the returned pointer so that the unmapped guard page sits
780 * immediately after the returned object.
781 */
782 p = (void **)((va + (size - PAGE_SIZE) - requested_size) & ~(uintptr_t)ALIGNBYTES);
783 kmem_size_set((uint8_t *)p - SIZE_SIZE, requested_size);
784 return (void *)p;
785 }
786
787 static void
788 kmem_guard_free(struct kmem_guard *kg, size_t requested_size, void *p)
789 {
790 vaddr_t va;
791 u_int rotor;
792 size_t size;
793 uint8_t *ptr;
794
795 ptr = (uint8_t *)p - SIZE_SIZE;
796 kmem_size_check(ptr, requested_size);
797 va = trunc_page((vaddr_t)ptr);
798 size = round_page(requested_size + SIZE_SIZE) + PAGE_SIZE;
799
800 KASSERT(pmap_extract(pmap_kernel(), va, NULL));
801 KASSERT(!pmap_extract(pmap_kernel(), va + (size - PAGE_SIZE), NULL));
802
803 /*
804 * Unmap and free the pages. The last one is never allocated.
805 */
806 uvm_km_pgremove_intrsafe(kernel_map, va, va + size);
807 pmap_update(pmap_kernel());
808
809 #if 0
810 /*
811 * XXX: Here, we need to atomically register the va and its size in the
812 * fifo.
813 */
814
815 /*
816 * Put the VA allocation into the list and swap an old one out to free.
817 * This behaves mostly like a fifo.
818 */
819 rotor = atomic_inc_uint_nv(&kg->kg_rotor) % kg->kg_depth;
820 va = (vaddr_t)atomic_swap_ptr(&kg->kg_fifo[rotor], (void *)va);
821 if (va != 0) {
822 vmem_free(kg->kg_vmem, va, size);
823 }
824 #else
825 (void)rotor;
826 vmem_free(kg->kg_vmem, va, size);
827 #endif
828 }
829
830 #endif /* defined(KMEM_GUARD) */
831