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