kern_malloc.c revision 1.109 1 /* $NetBSD: kern_malloc.c,v 1.109 2007/03/12 16:42:14 ad Exp $ */
2
3 /*
4 * Copyright (c) 1987, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 * @(#)kern_malloc.c 8.4 (Berkeley) 5/20/95
32 */
33
34 /*
35 * Copyright (c) 1996 Christopher G. Demetriou. All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
45 * 3. All advertising materials mentioning features or use of this software
46 * must display the following acknowledgement:
47 * This product includes software developed by the University of
48 * California, Berkeley and its contributors.
49 * 4. Neither the name of the University nor the names of its contributors
50 * may be used to endorse or promote products derived from this software
51 * without specific prior written permission.
52 *
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 * SUCH DAMAGE.
64 *
65 * @(#)kern_malloc.c 8.4 (Berkeley) 5/20/95
66 */
67
68 #include <sys/cdefs.h>
69 __KERNEL_RCSID(0, "$NetBSD: kern_malloc.c,v 1.109 2007/03/12 16:42:14 ad Exp $");
70
71 #include "opt_lockdebug.h"
72
73 #include <sys/param.h>
74 #include <sys/proc.h>
75 #include <sys/kernel.h>
76 #include <sys/malloc.h>
77 #include <sys/systm.h>
78 #include <sys/debug.h>
79 #include <sys/mutex.h>
80
81 #include <uvm/uvm_extern.h>
82
83 static struct vm_map_kernel kmem_map_store;
84 struct vm_map *kmem_map = NULL;
85
86 #include "opt_kmempages.h"
87
88 #ifdef NKMEMCLUSTERS
89 #error NKMEMCLUSTERS is obsolete; remove it from your kernel config file and use NKMEMPAGES instead or let the kernel auto-size
90 #endif
91
92 /*
93 * Default number of pages in kmem_map. We attempt to calculate this
94 * at run-time, but allow it to be either patched or set in the kernel
95 * config file.
96 */
97 #ifndef NKMEMPAGES
98 #define NKMEMPAGES 0
99 #endif
100 int nkmempages = NKMEMPAGES;
101
102 /*
103 * Defaults for lower- and upper-bounds for the kmem_map page count.
104 * Can be overridden by kernel config options.
105 */
106 #ifndef NKMEMPAGES_MIN
107 #define NKMEMPAGES_MIN NKMEMPAGES_MIN_DEFAULT
108 #endif
109
110 #ifndef NKMEMPAGES_MAX
111 #define NKMEMPAGES_MAX NKMEMPAGES_MAX_DEFAULT
112 #endif
113
114 #include "opt_kmemstats.h"
115 #include "opt_malloclog.h"
116 #include "opt_malloc_debug.h"
117
118 #define MINALLOCSIZE (1 << MINBUCKET)
119 #define BUCKETINDX(size) \
120 ((size) <= (MINALLOCSIZE * 128) \
121 ? (size) <= (MINALLOCSIZE * 8) \
122 ? (size) <= (MINALLOCSIZE * 2) \
123 ? (size) <= (MINALLOCSIZE * 1) \
124 ? (MINBUCKET + 0) \
125 : (MINBUCKET + 1) \
126 : (size) <= (MINALLOCSIZE * 4) \
127 ? (MINBUCKET + 2) \
128 : (MINBUCKET + 3) \
129 : (size) <= (MINALLOCSIZE* 32) \
130 ? (size) <= (MINALLOCSIZE * 16) \
131 ? (MINBUCKET + 4) \
132 : (MINBUCKET + 5) \
133 : (size) <= (MINALLOCSIZE * 64) \
134 ? (MINBUCKET + 6) \
135 : (MINBUCKET + 7) \
136 : (size) <= (MINALLOCSIZE * 2048) \
137 ? (size) <= (MINALLOCSIZE * 512) \
138 ? (size) <= (MINALLOCSIZE * 256) \
139 ? (MINBUCKET + 8) \
140 : (MINBUCKET + 9) \
141 : (size) <= (MINALLOCSIZE * 1024) \
142 ? (MINBUCKET + 10) \
143 : (MINBUCKET + 11) \
144 : (size) <= (MINALLOCSIZE * 8192) \
145 ? (size) <= (MINALLOCSIZE * 4096) \
146 ? (MINBUCKET + 12) \
147 : (MINBUCKET + 13) \
148 : (size) <= (MINALLOCSIZE * 16384) \
149 ? (MINBUCKET + 14) \
150 : (MINBUCKET + 15))
151
152 /*
153 * Array of descriptors that describe the contents of each page
154 */
155 struct kmemusage {
156 short ku_indx; /* bucket index */
157 union {
158 u_short freecnt;/* for small allocations, free pieces in page */
159 u_short pagecnt;/* for large allocations, pages alloced */
160 } ku_un;
161 };
162 #define ku_freecnt ku_un.freecnt
163 #define ku_pagecnt ku_un.pagecnt
164
165 struct kmembuckets kmembuckets[MINBUCKET + 16];
166 struct kmemusage *kmemusage;
167 char *kmembase, *kmemlimit;
168
169 #ifdef DEBUG
170 static void *malloc_freecheck;
171 #endif
172
173 /*
174 * Turn virtual addresses into kmem map indicies
175 */
176 #define btokup(addr) (&kmemusage[((char *)(addr) - kmembase) >> PGSHIFT])
177
178 struct malloc_type *kmemstatistics;
179
180 #ifdef MALLOCLOG
181 #ifndef MALLOCLOGSIZE
182 #define MALLOCLOGSIZE 100000
183 #endif
184
185 struct malloclog {
186 void *addr;
187 long size;
188 struct malloc_type *type;
189 int action;
190 const char *file;
191 long line;
192 } malloclog[MALLOCLOGSIZE];
193
194 long malloclogptr;
195
196 static void
197 domlog(void *a, long size, struct malloc_type *type, int action,
198 const char *file, long line)
199 {
200
201 malloclog[malloclogptr].addr = a;
202 malloclog[malloclogptr].size = size;
203 malloclog[malloclogptr].type = type;
204 malloclog[malloclogptr].action = action;
205 malloclog[malloclogptr].file = file;
206 malloclog[malloclogptr].line = line;
207 malloclogptr++;
208 if (malloclogptr >= MALLOCLOGSIZE)
209 malloclogptr = 0;
210 }
211
212 static void
213 hitmlog(void *a)
214 {
215 struct malloclog *lp;
216 long l;
217
218 #define PRT do { \
219 lp = &malloclog[l]; \
220 if (lp->addr == a && lp->action) { \
221 printf("malloc log entry %ld:\n", l); \
222 printf("\taddr = %p\n", lp->addr); \
223 printf("\tsize = %ld\n", lp->size); \
224 printf("\ttype = %s\n", lp->type->ks_shortdesc); \
225 printf("\taction = %s\n", lp->action == 1 ? "alloc" : "free"); \
226 printf("\tfile = %s\n", lp->file); \
227 printf("\tline = %ld\n", lp->line); \
228 } \
229 } while (/* CONSTCOND */0)
230
231 for (l = malloclogptr; l < MALLOCLOGSIZE; l++)
232 PRT;
233
234 for (l = 0; l < malloclogptr; l++)
235 PRT;
236 #undef PRT
237 }
238 #endif /* MALLOCLOG */
239
240 #ifdef DIAGNOSTIC
241 /*
242 * This structure provides a set of masks to catch unaligned frees.
243 */
244 const long addrmask[] = { 0,
245 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
246 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
247 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
248 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
249 };
250
251 /*
252 * The WEIRD_ADDR is used as known text to copy into free objects so
253 * that modifications after frees can be detected.
254 */
255 #define WEIRD_ADDR ((uint32_t) 0xdeadbeef)
256 #ifdef DEBUG
257 #define MAX_COPY PAGE_SIZE
258 #else
259 #define MAX_COPY 32
260 #endif
261
262 /*
263 * Normally the freelist structure is used only to hold the list pointer
264 * for free objects. However, when running with diagnostics, the first
265 * 8/16 bytes of the structure is unused except for diagnostic information,
266 * and the free list pointer is at offset 8/16 in the structure. Since the
267 * first 8 bytes is the portion of the structure most often modified, this
268 * helps to detect memory reuse problems and avoid free list corruption.
269 */
270 struct freelist {
271 uint32_t spare0;
272 #ifdef _LP64
273 uint32_t spare1; /* explicit padding */
274 #endif
275 struct malloc_type *type;
276 void * next;
277 };
278 #else /* !DIAGNOSTIC */
279 struct freelist {
280 void * next;
281 };
282 #endif /* DIAGNOSTIC */
283
284 /*
285 * The following are standard, built-in malloc types and are not
286 * specific to any subsystem.
287 */
288 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
289 MALLOC_DEFINE(M_DMAMAP, "DMA map", "bus_dma(9) structures");
290 MALLOC_DEFINE(M_FREE, "free", "should be on free list");
291 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
292 MALLOC_DEFINE(M_SOFTINTR, "softintr", "Softinterrupt structures");
293 MALLOC_DEFINE(M_TEMP, "temp", "misc. temporary data buffers");
294
295 /* XXX These should all be elsewhere. */
296 MALLOC_DEFINE(M_RTABLE, "routetbl", "routing tables");
297 MALLOC_DEFINE(M_FTABLE, "fragtbl", "fragment reassembly header");
298 MALLOC_DEFINE(M_UFSMNT, "UFS mount", "UFS mount structure");
299 MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
300 MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
301 MALLOC_DEFINE(M_IPMADDR, "in_multi", "internet multicast address");
302 MALLOC_DEFINE(M_MRTABLE, "mrt", "multicast routing tables");
303 MALLOC_DEFINE(M_BWMETER, "bwmeter", "multicast upcall bw meters");
304 MALLOC_DEFINE(M_1394DATA, "1394data", "IEEE 1394 data buffers");
305
306 kmutex_t malloc_lock;
307
308 /*
309 * Allocate a block of memory
310 */
311 #ifdef MALLOCLOG
312 void *
313 _malloc(unsigned long size, struct malloc_type *ksp, int flags,
314 const char *file, long line)
315 #else
316 void *
317 malloc(unsigned long size, struct malloc_type *ksp, int flags)
318 #endif /* MALLOCLOG */
319 {
320 struct kmembuckets *kbp;
321 struct kmemusage *kup;
322 struct freelist *freep;
323 long indx, npg, allocsize;
324 char *va, *cp, *savedlist;
325 #ifdef DIAGNOSTIC
326 uint32_t *end, *lp;
327 int copysize;
328 #endif
329
330 #ifdef LOCKDEBUG
331 if ((flags & M_NOWAIT) == 0)
332 ASSERT_SLEEPABLE(NULL, "malloc");
333 #endif
334 #ifdef MALLOC_DEBUG
335 if (debug_malloc(size, ksp, flags, (void *) &va)) {
336 if (va != 0)
337 FREECHECK_OUT(&malloc_freecheck, (void *)va);
338 return ((void *) va);
339 }
340 #endif
341 indx = BUCKETINDX(size);
342 kbp = &kmembuckets[indx];
343 mutex_enter(&malloc_lock);
344 #ifdef KMEMSTATS
345 while (ksp->ks_memuse >= ksp->ks_limit) {
346 if (flags & M_NOWAIT) {
347 mutex_exit(&malloc_lock);
348 return ((void *) NULL);
349 }
350 if (ksp->ks_limblocks < 65535)
351 ksp->ks_limblocks++;
352 mtsleep((void *)ksp, PSWP+2, ksp->ks_shortdesc, 0,
353 &malloc_lock);
354 }
355 ksp->ks_size |= 1 << indx;
356 #endif
357 #ifdef DIAGNOSTIC
358 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
359 #endif
360 if (kbp->kb_next == NULL) {
361 kbp->kb_last = NULL;
362 if (size > MAXALLOCSAVE)
363 allocsize = round_page(size);
364 else
365 allocsize = 1 << indx;
366 npg = btoc(allocsize);
367 mutex_exit(&malloc_lock);
368 va = (void *) uvm_km_alloc(kmem_map,
369 (vsize_t)ctob(npg), 0,
370 ((flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0) |
371 ((flags & M_CANFAIL) ? UVM_KMF_CANFAIL : 0) |
372 UVM_KMF_WIRED);
373 if (__predict_false(va == NULL)) {
374 /*
375 * Kmem_malloc() can return NULL, even if it can
376 * wait, if there is no map space available, because
377 * it can't fix that problem. Neither can we,
378 * right now. (We should release pages which
379 * are completely free and which are in kmembuckets
380 * with too many free elements.)
381 */
382 if ((flags & (M_NOWAIT|M_CANFAIL)) == 0)
383 panic("malloc: out of space in kmem_map");
384 return (NULL);
385 }
386 mutex_enter(&malloc_lock);
387 #ifdef KMEMSTATS
388 kbp->kb_total += kbp->kb_elmpercl;
389 #endif
390 kup = btokup(va);
391 kup->ku_indx = indx;
392 if (allocsize > MAXALLOCSAVE) {
393 if (npg > 65535)
394 panic("malloc: allocation too large");
395 kup->ku_pagecnt = npg;
396 #ifdef KMEMSTATS
397 ksp->ks_memuse += allocsize;
398 #endif
399 goto out;
400 }
401 #ifdef KMEMSTATS
402 kup->ku_freecnt = kbp->kb_elmpercl;
403 kbp->kb_totalfree += kbp->kb_elmpercl;
404 #endif
405 /*
406 * Just in case we blocked while allocating memory,
407 * and someone else also allocated memory for this
408 * kmembucket, don't assume the list is still empty.
409 */
410 savedlist = kbp->kb_next;
411 kbp->kb_next = cp = va + (npg << PAGE_SHIFT) - allocsize;
412 for (;;) {
413 freep = (struct freelist *)cp;
414 #ifdef DIAGNOSTIC
415 /*
416 * Copy in known text to detect modification
417 * after freeing.
418 */
419 end = (uint32_t *)&cp[copysize];
420 for (lp = (uint32_t *)cp; lp < end; lp++)
421 *lp = WEIRD_ADDR;
422 freep->type = M_FREE;
423 #endif /* DIAGNOSTIC */
424 if (cp <= va)
425 break;
426 cp -= allocsize;
427 freep->next = cp;
428 }
429 freep->next = savedlist;
430 if (kbp->kb_last == NULL)
431 kbp->kb_last = (void *)freep;
432 }
433 va = kbp->kb_next;
434 kbp->kb_next = ((struct freelist *)va)->next;
435 #ifdef DIAGNOSTIC
436 freep = (struct freelist *)va;
437 /* XXX potential to get garbage pointer here. */
438 if (kbp->kb_next) {
439 int rv;
440 vaddr_t addr = (vaddr_t)kbp->kb_next;
441
442 vm_map_lock(kmem_map);
443 rv = uvm_map_checkprot(kmem_map, addr,
444 addr + sizeof(struct freelist), VM_PROT_WRITE);
445 vm_map_unlock(kmem_map);
446
447 if (__predict_false(rv == 0)) {
448 printf("Data modified on freelist: "
449 "word %ld of object %p size %ld previous type %s "
450 "(invalid addr %p)\n",
451 (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
452 va, size, "foo", kbp->kb_next);
453 #ifdef MALLOCLOG
454 hitmlog(va);
455 #endif
456 kbp->kb_next = NULL;
457 }
458 }
459
460 /* Fill the fields that we've used with WEIRD_ADDR */
461 #ifdef _LP64
462 freep->type = (struct malloc_type *)
463 (WEIRD_ADDR | (((u_long) WEIRD_ADDR) << 32));
464 #else
465 freep->type = (struct malloc_type *) WEIRD_ADDR;
466 #endif
467 end = (uint32_t *)&freep->next +
468 (sizeof(freep->next) / sizeof(int32_t));
469 for (lp = (uint32_t *)&freep->next; lp < end; lp++)
470 *lp = WEIRD_ADDR;
471
472 /* and check that the data hasn't been modified. */
473 end = (uint32_t *)&va[copysize];
474 for (lp = (uint32_t *)va; lp < end; lp++) {
475 if (__predict_true(*lp == WEIRD_ADDR))
476 continue;
477 printf("Data modified on freelist: "
478 "word %ld of object %p size %ld previous type %s "
479 "(0x%x != 0x%x)\n",
480 (long)(lp - (uint32_t *)va), va, size,
481 "bar", *lp, WEIRD_ADDR);
482 #ifdef MALLOCLOG
483 hitmlog(va);
484 #endif
485 break;
486 }
487
488 freep->spare0 = 0;
489 #endif /* DIAGNOSTIC */
490 #ifdef KMEMSTATS
491 kup = btokup(va);
492 if (kup->ku_indx != indx)
493 panic("malloc: wrong bucket");
494 if (kup->ku_freecnt == 0)
495 panic("malloc: lost data");
496 kup->ku_freecnt--;
497 kbp->kb_totalfree--;
498 ksp->ks_memuse += 1 << indx;
499 out:
500 kbp->kb_calls++;
501 ksp->ks_inuse++;
502 ksp->ks_calls++;
503 if (ksp->ks_memuse > ksp->ks_maxused)
504 ksp->ks_maxused = ksp->ks_memuse;
505 #else
506 out:
507 #endif
508 #ifdef MALLOCLOG
509 domlog(va, size, ksp, 1, file, line);
510 #endif
511 mutex_exit(&malloc_lock);
512 if ((flags & M_ZERO) != 0)
513 memset(va, 0, size);
514 FREECHECK_OUT(&malloc_freecheck, (void *)va);
515 return ((void *) va);
516 }
517
518 /*
519 * Free a block of memory allocated by malloc.
520 */
521 #ifdef MALLOCLOG
522 void
523 _free(void *addr, struct malloc_type *ksp, const char *file, long line)
524 #else
525 void
526 free(void *addr, struct malloc_type *ksp)
527 #endif /* MALLOCLOG */
528 {
529 struct kmembuckets *kbp;
530 struct kmemusage *kup;
531 struct freelist *freep;
532 long size;
533 #ifdef DIAGNOSTIC
534 void *cp;
535 int32_t *end, *lp;
536 long alloc, copysize;
537 #endif
538
539 FREECHECK_IN(&malloc_freecheck, addr);
540
541 #ifdef MALLOC_DEBUG
542 if (debug_free(addr, ksp))
543 return;
544 #endif
545
546 #ifdef DIAGNOSTIC
547 /*
548 * Ensure that we're free'ing something that we could
549 * have allocated in the first place. That is, check
550 * to see that the address is within kmem_map.
551 */
552 if (__predict_false((vaddr_t)addr < vm_map_min(kmem_map) ||
553 (vaddr_t)addr >= vm_map_max(kmem_map)))
554 panic("free: addr %p not within kmem_map", addr);
555 #endif
556
557 kup = btokup(addr);
558 size = 1 << kup->ku_indx;
559 kbp = &kmembuckets[kup->ku_indx];
560 mutex_enter(&malloc_lock);
561 #ifdef MALLOCLOG
562 domlog(addr, 0, ksp, 2, file, line);
563 #endif
564 #ifdef DIAGNOSTIC
565 /*
566 * Check for returns of data that do not point to the
567 * beginning of the allocation.
568 */
569 if (size > PAGE_SIZE)
570 alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
571 else
572 alloc = addrmask[kup->ku_indx];
573 if (((u_long)addr & alloc) != 0)
574 panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
575 addr, size, ksp->ks_shortdesc, alloc);
576 #endif /* DIAGNOSTIC */
577 if (size > MAXALLOCSAVE) {
578 uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt),
579 UVM_KMF_WIRED);
580 #ifdef KMEMSTATS
581 size = kup->ku_pagecnt << PGSHIFT;
582 ksp->ks_memuse -= size;
583 kup->ku_indx = 0;
584 kup->ku_pagecnt = 0;
585 if (ksp->ks_memuse + size >= ksp->ks_limit &&
586 ksp->ks_memuse < ksp->ks_limit)
587 wakeup((void *)ksp);
588 #ifdef DIAGNOSTIC
589 if (ksp->ks_inuse == 0)
590 panic("free 1: inuse 0, probable double free");
591 #endif
592 ksp->ks_inuse--;
593 kbp->kb_total -= 1;
594 #endif
595 mutex_exit(&malloc_lock);
596 return;
597 }
598 freep = (struct freelist *)addr;
599 #ifdef DIAGNOSTIC
600 /*
601 * Check for multiple frees. Use a quick check to see if
602 * it looks free before laboriously searching the freelist.
603 */
604 if (__predict_false(freep->spare0 == WEIRD_ADDR)) {
605 for (cp = kbp->kb_next; cp;
606 cp = ((struct freelist *)cp)->next) {
607 if (addr != cp)
608 continue;
609 printf("multiply freed item %p\n", addr);
610 #ifdef MALLOCLOG
611 hitmlog(addr);
612 #endif
613 panic("free: duplicated free");
614 }
615 }
616 #ifdef LOCKDEBUG
617 /*
618 * Check if we're freeing a locked simple lock.
619 */
620 simple_lock_freecheck(addr, (char *)addr + size);
621 #endif
622 /*
623 * Copy in known text to detect modification after freeing
624 * and to make it look free. Also, save the type being freed
625 * so we can list likely culprit if modification is detected
626 * when the object is reallocated.
627 */
628 copysize = size < MAX_COPY ? size : MAX_COPY;
629 end = (int32_t *)&((char *)addr)[copysize];
630 for (lp = (int32_t *)addr; lp < end; lp++)
631 *lp = WEIRD_ADDR;
632 freep->type = ksp;
633 #endif /* DIAGNOSTIC */
634 #ifdef KMEMSTATS
635 kup->ku_freecnt++;
636 if (kup->ku_freecnt >= kbp->kb_elmpercl) {
637 if (kup->ku_freecnt > kbp->kb_elmpercl)
638 panic("free: multiple frees");
639 else if (kbp->kb_totalfree > kbp->kb_highwat)
640 kbp->kb_couldfree++;
641 }
642 kbp->kb_totalfree++;
643 ksp->ks_memuse -= size;
644 if (ksp->ks_memuse + size >= ksp->ks_limit &&
645 ksp->ks_memuse < ksp->ks_limit)
646 wakeup((void *)ksp);
647 #ifdef DIAGNOSTIC
648 if (ksp->ks_inuse == 0)
649 panic("free 2: inuse 0, probable double free");
650 #endif
651 ksp->ks_inuse--;
652 #endif
653 if (kbp->kb_next == NULL)
654 kbp->kb_next = addr;
655 else
656 ((struct freelist *)kbp->kb_last)->next = addr;
657 freep->next = NULL;
658 kbp->kb_last = addr;
659 mutex_exit(&malloc_lock);
660 }
661
662 /*
663 * Change the size of a block of memory.
664 */
665 void *
666 realloc(void *curaddr, unsigned long newsize, struct malloc_type *ksp,
667 int flags)
668 {
669 struct kmemusage *kup;
670 unsigned long cursize;
671 void *newaddr;
672 #ifdef DIAGNOSTIC
673 long alloc;
674 #endif
675
676 /*
677 * realloc() with a NULL pointer is the same as malloc().
678 */
679 if (curaddr == NULL)
680 return (malloc(newsize, ksp, flags));
681
682 /*
683 * realloc() with zero size is the same as free().
684 */
685 if (newsize == 0) {
686 free(curaddr, ksp);
687 return (NULL);
688 }
689
690 #ifdef LOCKDEBUG
691 if ((flags & M_NOWAIT) == 0)
692 ASSERT_SLEEPABLE(NULL, "realloc");
693 #endif
694
695 /*
696 * Find out how large the old allocation was (and do some
697 * sanity checking).
698 */
699 kup = btokup(curaddr);
700 cursize = 1 << kup->ku_indx;
701
702 #ifdef DIAGNOSTIC
703 /*
704 * Check for returns of data that do not point to the
705 * beginning of the allocation.
706 */
707 if (cursize > PAGE_SIZE)
708 alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
709 else
710 alloc = addrmask[kup->ku_indx];
711 if (((u_long)curaddr & alloc) != 0)
712 panic("realloc: "
713 "unaligned addr %p, size %ld, type %s, mask %ld\n",
714 curaddr, cursize, ksp->ks_shortdesc, alloc);
715 #endif /* DIAGNOSTIC */
716
717 if (cursize > MAXALLOCSAVE)
718 cursize = ctob(kup->ku_pagecnt);
719
720 /*
721 * If we already actually have as much as they want, we're done.
722 */
723 if (newsize <= cursize)
724 return (curaddr);
725
726 /*
727 * Can't satisfy the allocation with the existing block.
728 * Allocate a new one and copy the data.
729 */
730 newaddr = malloc(newsize, ksp, flags);
731 if (__predict_false(newaddr == NULL)) {
732 /*
733 * malloc() failed, because flags included M_NOWAIT.
734 * Return NULL to indicate that failure. The old
735 * pointer is still valid.
736 */
737 return (NULL);
738 }
739 memcpy(newaddr, curaddr, cursize);
740
741 /*
742 * We were successful: free the old allocation and return
743 * the new one.
744 */
745 free(curaddr, ksp);
746 return (newaddr);
747 }
748
749 /*
750 * Roundup size to the actual allocation size.
751 */
752 unsigned long
753 malloc_roundup(unsigned long size)
754 {
755
756 if (size > MAXALLOCSAVE)
757 return (roundup(size, PAGE_SIZE));
758 else
759 return (1 << BUCKETINDX(size));
760 }
761
762 /*
763 * Add a malloc type to the system.
764 */
765 void
766 malloc_type_attach(struct malloc_type *type)
767 {
768
769 if (nkmempages == 0)
770 panic("malloc_type_attach: nkmempages == 0");
771
772 if (type->ks_magic != M_MAGIC)
773 panic("malloc_type_attach: bad magic");
774
775 #ifdef DIAGNOSTIC
776 {
777 struct malloc_type *ksp;
778 for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
779 if (ksp == type)
780 panic("malloc_type_attach: already on list");
781 }
782 }
783 #endif
784
785 #ifdef KMEMSTATS
786 if (type->ks_limit == 0)
787 type->ks_limit = ((u_long)nkmempages << PAGE_SHIFT) * 6U / 10U;
788 #else
789 type->ks_limit = 0;
790 #endif
791
792 type->ks_next = kmemstatistics;
793 kmemstatistics = type;
794 }
795
796 /*
797 * Remove a malloc type from the system..
798 */
799 void
800 malloc_type_detach(struct malloc_type *type)
801 {
802 struct malloc_type *ksp;
803
804 #ifdef DIAGNOSTIC
805 if (type->ks_magic != M_MAGIC)
806 panic("malloc_type_detach: bad magic");
807 #endif
808
809 if (type == kmemstatistics)
810 kmemstatistics = type->ks_next;
811 else {
812 for (ksp = kmemstatistics; ksp->ks_next != NULL;
813 ksp = ksp->ks_next) {
814 if (ksp->ks_next == type) {
815 ksp->ks_next = type->ks_next;
816 break;
817 }
818 }
819 #ifdef DIAGNOSTIC
820 if (ksp->ks_next == NULL)
821 panic("malloc_type_detach: not on list");
822 #endif
823 }
824 type->ks_next = NULL;
825 }
826
827 /*
828 * Set the limit on a malloc type.
829 */
830 void
831 malloc_type_setlimit(struct malloc_type *type, u_long limit)
832 {
833 #ifdef KMEMSTATS
834 mutex_enter(&malloc_lock);
835 type->ks_limit = limit;
836 mutex_exit(&malloc_lock);
837 #endif
838 }
839
840 /*
841 * Compute the number of pages that kmem_map will map, that is,
842 * the size of the kernel malloc arena.
843 */
844 void
845 kmeminit_nkmempages(void)
846 {
847 int npages;
848
849 if (nkmempages != 0) {
850 /*
851 * It's already been set (by us being here before, or
852 * by patching or kernel config options), bail out now.
853 */
854 return;
855 }
856
857 npages = physmem;
858
859 if (npages > NKMEMPAGES_MAX)
860 npages = NKMEMPAGES_MAX;
861
862 if (npages < NKMEMPAGES_MIN)
863 npages = NKMEMPAGES_MIN;
864
865 nkmempages = npages;
866 }
867
868 /*
869 * Initialize the kernel memory allocator
870 */
871 void
872 kmeminit(void)
873 {
874 __link_set_decl(malloc_types, struct malloc_type);
875 struct malloc_type * const *ksp;
876 vaddr_t kmb, kml;
877 #ifdef KMEMSTATS
878 long indx;
879 #endif
880
881 #if ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
882 ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
883 #endif
884 #if (MAXALLOCSAVE > MINALLOCSIZE * 32768)
885 ERROR!_kmeminit:_MAXALLOCSAVE_too_big
886 #endif
887 #if (MAXALLOCSAVE < NBPG)
888 ERROR!_kmeminit:_MAXALLOCSAVE_too_small
889 #endif
890
891 if (sizeof(struct freelist) > (1 << MINBUCKET))
892 panic("minbucket too small/struct freelist too big");
893
894 mutex_init(&malloc_lock, MUTEX_DRIVER, IPL_VM);
895
896 /*
897 * Compute the number of kmem_map pages, if we have not
898 * done so already.
899 */
900 kmeminit_nkmempages();
901
902 kmemusage = (struct kmemusage *) uvm_km_alloc(kernel_map,
903 (vsize_t)(nkmempages * sizeof(struct kmemusage)), 0,
904 UVM_KMF_WIRED|UVM_KMF_ZERO);
905 kmb = 0;
906 kmem_map = uvm_km_suballoc(kernel_map, &kmb,
907 &kml, ((vsize_t)nkmempages << PAGE_SHIFT),
908 VM_MAP_INTRSAFE, false, &kmem_map_store);
909 uvm_km_vacache_init(kmem_map, "kvakmem", 0);
910 kmembase = (char *)kmb;
911 kmemlimit = (char *)kml;
912 #ifdef KMEMSTATS
913 for (indx = 0; indx < MINBUCKET + 16; indx++) {
914 if (1 << indx >= PAGE_SIZE)
915 kmembuckets[indx].kb_elmpercl = 1;
916 else
917 kmembuckets[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
918 kmembuckets[indx].kb_highwat =
919 5 * kmembuckets[indx].kb_elmpercl;
920 }
921 #endif
922
923 /* Attach all of the statically-linked malloc types. */
924 __link_set_foreach(ksp, malloc_types)
925 malloc_type_attach(*ksp);
926
927 #ifdef MALLOC_DEBUG
928 debug_malloc_init();
929 #endif
930 }
931
932 #ifdef DDB
933 #include <ddb/db_output.h>
934
935 /*
936 * Dump kmem statistics from ddb.
937 *
938 * usage: call dump_kmemstats
939 */
940 void dump_kmemstats(void);
941
942 void
943 dump_kmemstats(void)
944 {
945 #ifdef KMEMSTATS
946 struct malloc_type *ksp;
947
948 for (ksp = kmemstatistics; ksp != NULL; ksp = ksp->ks_next) {
949 if (ksp->ks_memuse == 0)
950 continue;
951 db_printf("%s%.*s %ld\n", ksp->ks_shortdesc,
952 (int)(20 - strlen(ksp->ks_shortdesc)),
953 " ",
954 ksp->ks_memuse);
955 }
956 #else
957 db_printf("Kmem stats are not being collected.\n");
958 #endif /* KMEMSTATS */
959 }
960 #endif /* DDB */
961
962
963 #if 0
964 /*
965 * Diagnostic messages about "Data modified on
966 * freelist" indicate a memory corruption, but
967 * they do not help tracking it down.
968 * This function can be called at various places
969 * to sanity check malloc's freelist and discover
970 * where does the corruption take place.
971 */
972 int
973 freelist_sanitycheck(void) {
974 int i,j;
975 struct kmembuckets *kbp;
976 struct freelist *freep;
977 int rv = 0;
978
979 for (i = MINBUCKET; i <= MINBUCKET + 15; i++) {
980 kbp = &kmembuckets[i];
981 freep = (struct freelist *)kbp->kb_next;
982 j = 0;
983 while(freep) {
984 vm_map_lock(kmem_map);
985 rv = uvm_map_checkprot(kmem_map, (vaddr_t)freep,
986 (vaddr_t)freep + sizeof(struct freelist),
987 VM_PROT_WRITE);
988 vm_map_unlock(kmem_map);
989
990 if ((rv == 0) || (*(int *)freep != WEIRD_ADDR)) {
991 printf("bucket %i, chunck %d at %p modified\n",
992 i, j, freep);
993 return 1;
994 }
995 freep = (struct freelist *)freep->next;
996 j++;
997 }
998 }
999
1000 return 0;
1001 }
1002 #endif
1003