2 * KERN_SLABALLOC.C - Kernel SLAB memory allocator
4 * Copyright (c) 2003,2004 The DragonFly Project. All rights reserved.
6 * This code is derived from software contributed to The DragonFly Project
7 * by Matthew Dillon <dillon@backplane.com>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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
17 * the documentation and/or other materials provided with the
19 * 3. Neither the name of The DragonFly Project nor the names of its
20 * contributors may be used to endorse or promote products derived
21 * from this software without specific, prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
31 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * $DragonFly: src/sys/kern/kern_slaballoc.c,v 1.55 2008/10/22 01:42:17 dillon Exp $
38 * This module implements a slab allocator drop-in replacement for the
41 * A slab allocator reserves a ZONE for each chunk size, then lays the
42 * chunks out in an array within the zone. Allocation and deallocation
43 * is nearly instantanious, and fragmentation/overhead losses are limited
44 * to a fixed worst-case amount.
46 * The downside of this slab implementation is in the chunk size
47 * multiplied by the number of zones. ~80 zones * 128K = 10MB of VM per cpu.
48 * In a kernel implementation all this memory will be physical so
49 * the zone size is adjusted downward on machines with less physical
50 * memory. The upside is that overhead is bounded... this is the *worst*
53 * Slab management is done on a per-cpu basis and no locking or mutexes
54 * are required, only a critical section. When one cpu frees memory
55 * belonging to another cpu's slab manager an asynchronous IPI message
56 * will be queued to execute the operation. In addition, both the
57 * high level slab allocator and the low level zone allocator optimize
58 * M_ZERO requests, and the slab allocator does not have to pre initialize
59 * the linked list of chunks.
61 * XXX Balancing is needed between cpus. Balance will be handled through
62 * asynchronous IPIs primarily by reassigning the z_Cpu ownership of chunks.
64 * XXX If we have to allocate a new zone and M_USE_RESERVE is set, use of
65 * the new zone should be restricted to M_USE_RESERVE requests only.
67 * Alloc Size Chunking Number of zones
77 * (if PAGE_SIZE is 4K the maximum zone allocation is 16383)
79 * Allocations >= ZoneLimit go directly to kmem.
81 * API REQUIREMENTS AND SIDE EFFECTS
83 * To operate as a drop-in replacement to the FreeBSD-4.x malloc() we
84 * have remained compatible with the following API requirements:
86 * + small power-of-2 sized allocations are power-of-2 aligned (kern_tty)
87 * + all power-of-2 sized allocations are power-of-2 aligned (twe)
88 * + malloc(0) is allowed and returns non-NULL (ahc driver)
89 * + ability to allocate arbitrarily large chunks of memory
94 #include <sys/param.h>
95 #include <sys/systm.h>
96 #include <sys/kernel.h>
97 #include <sys/slaballoc.h>
99 #include <sys/vmmeter.h>
100 #include <sys/lock.h>
101 #include <sys/thread.h>
102 #include <sys/globaldata.h>
103 #include <sys/sysctl.h>
107 #include <vm/vm_param.h>
108 #include <vm/vm_kern.h>
109 #include <vm/vm_extern.h>
110 #include <vm/vm_object.h>
112 #include <vm/vm_map.h>
113 #include <vm/vm_page.h>
114 #include <vm/vm_pageout.h>
116 #include <machine/cpu.h>
118 #include <sys/thread2.h>
119 #include <sys/mplock2.h>
121 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
123 #define MEMORY_STRING "ptr=%p type=%p size=%d flags=%04x"
124 #define MEMORY_ARG_SIZE (sizeof(void *) * 2 + sizeof(unsigned long) + \
127 #if !defined(KTR_MEMORY)
128 #define KTR_MEMORY KTR_ALL
130 KTR_INFO_MASTER(memory
);
131 KTR_INFO(KTR_MEMORY
, memory
, malloc
, 0, MEMORY_STRING
, MEMORY_ARG_SIZE
);
132 KTR_INFO(KTR_MEMORY
, memory
, free_zero
, 1, MEMORY_STRING
, MEMORY_ARG_SIZE
);
133 KTR_INFO(KTR_MEMORY
, memory
, free_ovsz
, 2, MEMORY_STRING
, MEMORY_ARG_SIZE
);
134 KTR_INFO(KTR_MEMORY
, memory
, free_ovsz_delayed
, 3, MEMORY_STRING
, MEMORY_ARG_SIZE
);
135 KTR_INFO(KTR_MEMORY
, memory
, free_chunk
, 4, MEMORY_STRING
, MEMORY_ARG_SIZE
);
137 KTR_INFO(KTR_MEMORY
, memory
, free_request
, 5, MEMORY_STRING
, MEMORY_ARG_SIZE
);
138 KTR_INFO(KTR_MEMORY
, memory
, free_remote
, 6, MEMORY_STRING
, MEMORY_ARG_SIZE
);
140 KTR_INFO(KTR_MEMORY
, memory
, malloc_beg
, 0, "malloc begin", 0);
141 KTR_INFO(KTR_MEMORY
, memory
, free_beg
, 0, "free begin", 0);
142 KTR_INFO(KTR_MEMORY
, memory
, free_end
, 0, "free end", 0);
144 #define logmemory(name, ptr, type, size, flags) \
145 KTR_LOG(memory_ ## name, ptr, type, size, flags)
146 #define logmemory_quick(name) \
147 KTR_LOG(memory_ ## name)
150 * Fixed globals (not per-cpu)
153 static int ZoneLimit
;
154 static int ZonePageCount
;
156 struct malloc_type
*kmemstatistics
; /* exported to vmstat */
157 static struct kmemusage
*kmemusage
;
158 static int32_t weirdary
[16];
160 static void *kmem_slab_alloc(vm_size_t bytes
, vm_offset_t align
, int flags
);
161 static void kmem_slab_free(void *ptr
, vm_size_t bytes
);
162 #if defined(INVARIANTS)
163 static void chunk_mark_allocated(SLZone
*z
, void *chunk
);
164 static void chunk_mark_free(SLZone
*z
, void *chunk
);
168 * Misc constants. Note that allocations that are exact multiples of
169 * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
170 * IN_SAME_PAGE_MASK is used to sanity-check the per-page free lists.
172 #define MIN_CHUNK_SIZE 8 /* in bytes */
173 #define MIN_CHUNK_MASK (MIN_CHUNK_SIZE - 1)
174 #define ZONE_RELS_THRESH 2 /* threshold number of zones */
175 #define IN_SAME_PAGE_MASK (~(intptr_t)PAGE_MASK | MIN_CHUNK_MASK)
178 * The WEIRD_ADDR is used as known text to copy into free objects to
179 * try to create deterministic failure cases if the data is accessed after
182 #define WEIRD_ADDR 0xdeadc0de
183 #define MAX_COPY sizeof(weirdary)
184 #define ZERO_LENGTH_PTR ((void *)-8)
187 * Misc global malloc buckets
190 MALLOC_DEFINE(M_CACHE
, "cache", "Various Dynamically allocated caches");
191 MALLOC_DEFINE(M_DEVBUF
, "devbuf", "device driver memory");
192 MALLOC_DEFINE(M_TEMP
, "temp", "misc temporary data buffers");
194 MALLOC_DEFINE(M_IP6OPT
, "ip6opt", "IPv6 options");
195 MALLOC_DEFINE(M_IP6NDP
, "ip6ndp", "IPv6 Neighbor Discovery");
198 * Initialize the slab memory allocator. We have to choose a zone size based
199 * on available physical memory. We choose a zone side which is approximately
200 * 1/1024th of our memory, so if we have 128MB of ram we have a zone size of
201 * 128K. The zone size is limited to the bounds set in slaballoc.h
202 * (typically 32K min, 128K max).
204 static void kmeminit(void *dummy
);
208 SYSINIT(kmem
, SI_BOOT1_ALLOCATOR
, SI_ORDER_FIRST
, kmeminit
, NULL
)
212 * If enabled any memory allocated without M_ZERO is initialized to -1.
214 static int use_malloc_pattern
;
215 SYSCTL_INT(_debug
, OID_AUTO
, use_malloc_pattern
, CTLFLAG_RW
,
216 &use_malloc_pattern
, 0, "");
220 kmeminit(void *dummy
)
227 limsize
= (vm_poff_t
)vmstats
.v_page_count
* PAGE_SIZE
;
228 if (limsize
> KvaSize
)
231 usesize
= (int)(limsize
/ 1024); /* convert to KB */
233 ZoneSize
= ZALLOC_MIN_ZONE_SIZE
;
234 while (ZoneSize
< ZALLOC_MAX_ZONE_SIZE
&& (ZoneSize
<< 1) < usesize
)
236 ZoneLimit
= ZoneSize
/ 4;
237 if (ZoneLimit
> ZALLOC_ZONE_LIMIT
)
238 ZoneLimit
= ZALLOC_ZONE_LIMIT
;
239 ZoneMask
= ZoneSize
- 1;
240 ZonePageCount
= ZoneSize
/ PAGE_SIZE
;
242 npg
= KvaSize
/ PAGE_SIZE
;
243 kmemusage
= kmem_slab_alloc(npg
* sizeof(struct kmemusage
),
244 PAGE_SIZE
, M_WAITOK
|M_ZERO
);
246 for (i
= 0; i
< arysize(weirdary
); ++i
)
247 weirdary
[i
] = WEIRD_ADDR
;
249 ZeroPage
= kmem_slab_alloc(PAGE_SIZE
, PAGE_SIZE
, M_WAITOK
|M_ZERO
);
252 kprintf("Slab ZoneSize set to %dKB\n", ZoneSize
/ 1024);
256 * Initialize a malloc type tracking structure.
259 malloc_init(void *data
)
261 struct malloc_type
*type
= data
;
264 if (type
->ks_magic
!= M_MAGIC
)
265 panic("malloc type lacks magic");
267 if (type
->ks_limit
!= 0)
270 if (vmstats
.v_page_count
== 0)
271 panic("malloc_init not allowed before vm init");
273 limsize
= (vm_poff_t
)vmstats
.v_page_count
* PAGE_SIZE
;
274 if (limsize
> KvaSize
)
276 type
->ks_limit
= limsize
/ 10;
278 type
->ks_next
= kmemstatistics
;
279 kmemstatistics
= type
;
283 malloc_uninit(void *data
)
285 struct malloc_type
*type
= data
;
286 struct malloc_type
*t
;
292 if (type
->ks_magic
!= M_MAGIC
)
293 panic("malloc type lacks magic");
295 if (vmstats
.v_page_count
== 0)
296 panic("malloc_uninit not allowed before vm init");
298 if (type
->ks_limit
== 0)
299 panic("malloc_uninit on uninitialized type");
302 /* Make sure that all pending kfree()s are finished. */
303 lwkt_synchronize_ipiqs("muninit");
308 * memuse is only correct in aggregation. Due to memory being allocated
309 * on one cpu and freed on another individual array entries may be
310 * negative or positive (canceling each other out).
312 for (i
= ttl
= 0; i
< ncpus
; ++i
)
313 ttl
+= type
->ks_memuse
[i
];
315 kprintf("malloc_uninit: %ld bytes of '%s' still allocated on cpu %d\n",
316 ttl
, type
->ks_shortdesc
, i
);
319 if (type
== kmemstatistics
) {
320 kmemstatistics
= type
->ks_next
;
322 for (t
= kmemstatistics
; t
->ks_next
!= NULL
; t
= t
->ks_next
) {
323 if (t
->ks_next
== type
) {
324 t
->ks_next
= type
->ks_next
;
329 type
->ks_next
= NULL
;
334 * Increase the kmalloc pool limit for the specified pool. No changes
335 * are the made if the pool would shrink.
338 kmalloc_raise_limit(struct malloc_type
*type
, size_t bytes
)
340 if (type
->ks_limit
== 0)
342 if (type
->ks_limit
< bytes
)
343 type
->ks_limit
= bytes
;
347 * Dynamically create a malloc pool. This function is a NOP if *typep is
351 kmalloc_create(struct malloc_type
**typep
, const char *descr
)
353 struct malloc_type
*type
;
355 if (*typep
== NULL
) {
356 type
= kmalloc(sizeof(*type
), M_TEMP
, M_WAITOK
| M_ZERO
);
357 type
->ks_magic
= M_MAGIC
;
358 type
->ks_shortdesc
= descr
;
365 * Destroy a dynamically created malloc pool. This function is a NOP if
366 * the pool has already been destroyed.
369 kmalloc_destroy(struct malloc_type
**typep
)
371 if (*typep
!= NULL
) {
372 malloc_uninit(*typep
);
373 kfree(*typep
, M_TEMP
);
379 * Calculate the zone index for the allocation request size and set the
380 * allocation request size to that particular zone's chunk size.
383 zoneindex(unsigned long *bytes
)
385 unsigned int n
= (unsigned int)*bytes
; /* unsigned for shift opt */
387 *bytes
= n
= (n
+ 7) & ~7;
388 return(n
/ 8 - 1); /* 8 byte chunks, 16 zones */
391 *bytes
= n
= (n
+ 15) & ~15;
396 *bytes
= n
= (n
+ 31) & ~31;
400 *bytes
= n
= (n
+ 63) & ~63;
404 *bytes
= n
= (n
+ 127) & ~127;
405 return(n
/ 128 + 31);
408 *bytes
= n
= (n
+ 255) & ~255;
409 return(n
/ 256 + 39);
411 *bytes
= n
= (n
+ 511) & ~511;
412 return(n
/ 512 + 47);
414 #if ZALLOC_ZONE_LIMIT > 8192
416 *bytes
= n
= (n
+ 1023) & ~1023;
417 return(n
/ 1024 + 55);
420 #if ZALLOC_ZONE_LIMIT > 16384
422 *bytes
= n
= (n
+ 2047) & ~2047;
423 return(n
/ 2048 + 63);
426 panic("Unexpected byte count %d", n
);
431 * malloc() (SLAB ALLOCATOR)
433 * Allocate memory via the slab allocator. If the request is too large,
434 * or if it page-aligned beyond a certain size, we fall back to the
435 * KMEM subsystem. A SLAB tracking descriptor must be specified, use
436 * &SlabMisc if you don't care.
438 * M_RNOWAIT - don't block.
439 * M_NULLOK - return NULL instead of blocking.
440 * M_ZERO - zero the returned memory.
441 * M_USE_RESERVE - allow greater drawdown of the free list
442 * M_USE_INTERRUPT_RESERVE - allow the freelist to be exhausted
448 kmalloc(unsigned long size
, struct malloc_type
*type
, int flags
)
453 struct globaldata
*gd
;
459 logmemory_quick(malloc_beg
);
464 * XXX silly to have this in the critical path.
466 if (type
->ks_limit
== 0) {
468 if (type
->ks_limit
== 0)
475 * Handle the case where the limit is reached. Panic if we can't return
476 * NULL. The original malloc code looped, but this tended to
477 * simply deadlock the computer.
479 * ks_loosememuse is an up-only limit that is NOT MP-synchronized, used
480 * to determine if a more complete limit check should be done. The
481 * actual memory use is tracked via ks_memuse[cpu].
483 while (type
->ks_loosememuse
>= type
->ks_limit
) {
487 for (i
= ttl
= 0; i
< ncpus
; ++i
)
488 ttl
+= type
->ks_memuse
[i
];
489 type
->ks_loosememuse
= ttl
; /* not MP synchronized */
490 if (ttl
>= type
->ks_limit
) {
491 if (flags
& M_NULLOK
) {
492 logmemory(malloc
, NULL
, type
, size
, flags
);
495 panic("%s: malloc limit exceeded", type
->ks_shortdesc
);
500 * Handle the degenerate size == 0 case. Yes, this does happen.
501 * Return a special pointer. This is to maintain compatibility with
502 * the original malloc implementation. Certain devices, such as the
503 * adaptec driver, not only allocate 0 bytes, they check for NULL and
504 * also realloc() later on. Joy.
507 logmemory(malloc
, ZERO_LENGTH_PTR
, type
, size
, flags
);
508 return(ZERO_LENGTH_PTR
);
512 * Handle hysteresis from prior frees here in malloc(). We cannot
513 * safely manipulate the kernel_map in free() due to free() possibly
514 * being called via an IPI message or from sensitive interrupt code.
516 while (slgd
->NFreeZones
> ZONE_RELS_THRESH
&& (flags
& M_RNOWAIT
) == 0) {
518 if (slgd
->NFreeZones
> ZONE_RELS_THRESH
) { /* crit sect race */
520 slgd
->FreeZones
= z
->z_Next
;
522 kmem_slab_free(z
, ZoneSize
); /* may block */
527 * XXX handle oversized frees that were queued from free().
529 while (slgd
->FreeOvZones
&& (flags
& M_RNOWAIT
) == 0) {
531 if ((z
= slgd
->FreeOvZones
) != NULL
) {
532 KKASSERT(z
->z_Magic
== ZALLOC_OVSZ_MAGIC
);
533 slgd
->FreeOvZones
= z
->z_Next
;
534 kmem_slab_free(z
, z
->z_ChunkSize
); /* may block */
540 * Handle large allocations directly. There should not be very many of
541 * these so performance is not a big issue.
543 * The backend allocator is pretty nasty on a SMP system. Use the
544 * slab allocator for one and two page-sized chunks even though we lose
545 * some efficiency. XXX maybe fix mmio and the elf loader instead.
547 if (size
>= ZoneLimit
|| ((size
& PAGE_MASK
) == 0 && size
> PAGE_SIZE
*2)) {
548 struct kmemusage
*kup
;
550 size
= round_page(size
);
551 chunk
= kmem_slab_alloc(size
, PAGE_SIZE
, flags
);
553 logmemory(malloc
, NULL
, type
, size
, flags
);
556 flags
&= ~M_ZERO
; /* result already zero'd if M_ZERO was set */
557 flags
|= M_PASSIVE_ZERO
;
559 kup
->ku_pagecnt
= size
/ PAGE_SIZE
;
560 kup
->ku_cpu
= gd
->gd_cpuid
;
566 * Attempt to allocate out of an existing zone. First try the free list,
567 * then allocate out of unallocated space. If we find a good zone move
568 * it to the head of the list so later allocations find it quickly
569 * (we might have thousands of zones in the list).
571 * Note: zoneindex() will panic of size is too large.
573 zi
= zoneindex(&size
);
574 KKASSERT(zi
< NZONES
);
576 if ((z
= slgd
->ZoneAry
[zi
]) != NULL
) {
577 KKASSERT(z
->z_NFree
> 0);
580 * Remove us from the ZoneAry[] when we become empty
582 if (--z
->z_NFree
== 0) {
583 slgd
->ZoneAry
[zi
] = z
->z_Next
;
588 * Locate a chunk in a free page. This attempts to localize
589 * reallocations into earlier pages without us having to sort
590 * the chunk list. A chunk may still overlap a page boundary.
592 while (z
->z_FirstFreePg
< ZonePageCount
) {
593 if ((chunk
= z
->z_PageAry
[z
->z_FirstFreePg
]) != NULL
) {
596 * Diagnostic: c_Next is not total garbage.
598 KKASSERT(chunk
->c_Next
== NULL
||
599 ((intptr_t)chunk
->c_Next
& IN_SAME_PAGE_MASK
) ==
600 ((intptr_t)chunk
& IN_SAME_PAGE_MASK
));
603 if ((vm_offset_t
)chunk
< KvaStart
|| (vm_offset_t
)chunk
>= KvaEnd
)
604 panic("chunk %p FFPG %d/%d", chunk
, z
->z_FirstFreePg
, ZonePageCount
);
605 if (chunk
->c_Next
&& (vm_offset_t
)chunk
->c_Next
< KvaStart
)
606 panic("chunkNEXT %p %p FFPG %d/%d", chunk
, chunk
->c_Next
, z
->z_FirstFreePg
, ZonePageCount
);
607 chunk_mark_allocated(z
, chunk
);
609 z
->z_PageAry
[z
->z_FirstFreePg
] = chunk
->c_Next
;
616 * No chunks are available but NFree said we had some memory, so
617 * it must be available in the never-before-used-memory area
618 * governed by UIndex. The consequences are very serious if our zone
619 * got corrupted so we use an explicit panic rather then a KASSERT.
621 if (z
->z_UIndex
+ 1 != z
->z_NMax
)
622 z
->z_UIndex
= z
->z_UIndex
+ 1;
625 if (z
->z_UIndex
== z
->z_UEndIndex
)
626 panic("slaballoc: corrupted zone");
627 chunk
= (SLChunk
*)(z
->z_BasePtr
+ z
->z_UIndex
* size
);
628 if ((z
->z_Flags
& SLZF_UNOTZEROD
) == 0) {
630 flags
|= M_PASSIVE_ZERO
;
632 #if defined(INVARIANTS)
633 chunk_mark_allocated(z
, chunk
);
639 * If all zones are exhausted we need to allocate a new zone for this
640 * index. Use M_ZERO to take advantage of pre-zerod pages. Also see
641 * UAlloc use above in regards to M_ZERO. Note that when we are reusing
642 * a zone from the FreeZones list UAlloc'd data will not be zero'd, and
643 * we do not pre-zero it because we do not want to mess up the L1 cache.
645 * At least one subsystem, the tty code (see CROUND) expects power-of-2
646 * allocations to be power-of-2 aligned. We maintain compatibility by
647 * adjusting the base offset below.
652 if ((z
= slgd
->FreeZones
) != NULL
) {
653 slgd
->FreeZones
= z
->z_Next
;
655 bzero(z
, sizeof(SLZone
));
656 z
->z_Flags
|= SLZF_UNOTZEROD
;
658 z
= kmem_slab_alloc(ZoneSize
, ZoneSize
, flags
|M_ZERO
);
664 * How big is the base structure?
666 #if defined(INVARIANTS)
668 * Make room for z_Bitmap. An exact calculation is somewhat more
669 * complicated so don't make an exact calculation.
671 off
= offsetof(SLZone
, z_Bitmap
[(ZoneSize
/ size
+ 31) / 32]);
672 bzero(z
->z_Bitmap
, (ZoneSize
/ size
+ 31) / 8);
674 off
= sizeof(SLZone
);
678 * Guarentee power-of-2 alignment for power-of-2-sized chunks.
679 * Otherwise just 8-byte align the data.
681 if ((size
| (size
- 1)) + 1 == (size
<< 1))
682 off
= (off
+ size
- 1) & ~(size
- 1);
684 off
= (off
+ MIN_CHUNK_MASK
) & ~MIN_CHUNK_MASK
;
685 z
->z_Magic
= ZALLOC_SLAB_MAGIC
;
687 z
->z_NMax
= (ZoneSize
- off
) / size
;
688 z
->z_NFree
= z
->z_NMax
- 1;
689 z
->z_BasePtr
= (char *)z
+ off
;
690 z
->z_UIndex
= z
->z_UEndIndex
= slgd
->JunkIndex
% z
->z_NMax
;
691 z
->z_ChunkSize
= size
;
692 z
->z_FirstFreePg
= ZonePageCount
;
694 z
->z_Cpu
= gd
->gd_cpuid
;
695 chunk
= (SLChunk
*)(z
->z_BasePtr
+ z
->z_UIndex
* size
);
696 z
->z_Next
= slgd
->ZoneAry
[zi
];
697 slgd
->ZoneAry
[zi
] = z
;
698 if ((z
->z_Flags
& SLZF_UNOTZEROD
) == 0) {
699 flags
&= ~M_ZERO
; /* already zero'd */
700 flags
|= M_PASSIVE_ZERO
;
702 #if defined(INVARIANTS)
703 chunk_mark_allocated(z
, chunk
);
707 * Slide the base index for initial allocations out of the next
708 * zone we create so we do not over-weight the lower part of the
711 slgd
->JunkIndex
= (slgd
->JunkIndex
+ ZALLOC_SLAB_SLIDE
)
712 & (ZALLOC_MAX_ZONE_SIZE
- 1);
715 ++type
->ks_inuse
[gd
->gd_cpuid
];
716 type
->ks_memuse
[gd
->gd_cpuid
] += size
;
717 type
->ks_loosememuse
+= size
; /* not MP synchronized */
722 else if ((flags
& (M_ZERO
|M_PASSIVE_ZERO
)) == 0) {
723 if (use_malloc_pattern
) {
724 for (i
= 0; i
< size
; i
+= sizeof(int)) {
725 *(int *)((char *)chunk
+ i
) = -1;
728 chunk
->c_Next
= (void *)-1; /* avoid accidental double-free check */
731 logmemory(malloc
, chunk
, type
, size
, flags
);
735 logmemory(malloc
, NULL
, type
, size
, flags
);
740 * kernel realloc. (SLAB ALLOCATOR) (MP SAFE)
742 * Generally speaking this routine is not called very often and we do
743 * not attempt to optimize it beyond reusing the same pointer if the
744 * new size fits within the chunking of the old pointer's zone.
747 krealloc(void *ptr
, unsigned long size
, struct malloc_type
*type
, int flags
)
753 KKASSERT((flags
& M_ZERO
) == 0); /* not supported */
755 if (ptr
== NULL
|| ptr
== ZERO_LENGTH_PTR
)
756 return(kmalloc(size
, type
, flags
));
763 * Handle oversized allocations. XXX we really should require that a
764 * size be passed to free() instead of this nonsense.
767 struct kmemusage
*kup
;
770 if (kup
->ku_pagecnt
) {
771 osize
= kup
->ku_pagecnt
<< PAGE_SHIFT
;
772 if (osize
== round_page(size
))
774 if ((nptr
= kmalloc(size
, type
, flags
)) == NULL
)
776 bcopy(ptr
, nptr
, min(size
, osize
));
783 * Get the original allocation's zone. If the new request winds up
784 * using the same chunk size we do not have to do anything.
786 z
= (SLZone
*)((uintptr_t)ptr
& ~(uintptr_t)ZoneMask
);
787 KKASSERT(z
->z_Magic
== ZALLOC_SLAB_MAGIC
);
790 * Allocate memory for the new request size. Note that zoneindex has
791 * already adjusted the request size to the appropriate chunk size, which
792 * should optimize our bcopy(). Then copy and return the new pointer.
794 * Resizing a non-power-of-2 allocation to a power-of-2 size does not
795 * necessary align the result.
797 * We can only zoneindex (to align size to the chunk size) if the new
798 * size is not too large.
800 if (size
< ZoneLimit
) {
802 if (z
->z_ChunkSize
== size
)
805 if ((nptr
= kmalloc(size
, type
, flags
)) == NULL
)
807 bcopy(ptr
, nptr
, min(size
, z
->z_ChunkSize
));
813 * Return the kmalloc limit for this type, in bytes.
816 kmalloc_limit(struct malloc_type
*type
)
818 if (type
->ks_limit
== 0) {
820 if (type
->ks_limit
== 0)
824 return(type
->ks_limit
);
828 * Allocate a copy of the specified string.
830 * (MP SAFE) (MAY BLOCK)
833 kstrdup(const char *str
, struct malloc_type
*type
)
835 int zlen
; /* length inclusive of terminating NUL */
840 zlen
= strlen(str
) + 1;
841 nstr
= kmalloc(zlen
, type
, M_WAITOK
);
842 bcopy(str
, nstr
, zlen
);
848 * free() (SLAB ALLOCATOR)
850 * Free the specified chunk of memory.
854 free_remote(void *ptr
)
856 logmemory(free_remote
, ptr
, *(struct malloc_type
**)ptr
, -1, 0);
857 kfree(ptr
, *(struct malloc_type
**)ptr
);
863 * free (SLAB ALLOCATOR)
865 * Free a memory block previously allocated by malloc. Note that we do not
866 * attempt to uplodate ks_loosememuse as MP races could prevent us from
867 * checking memory limits in malloc.
872 kfree(void *ptr
, struct malloc_type
*type
)
877 struct globaldata
*gd
;
880 logmemory_quick(free_beg
);
885 panic("trying to free NULL pointer");
888 * Handle special 0-byte allocations
890 if (ptr
== ZERO_LENGTH_PTR
) {
891 logmemory(free_zero
, ptr
, type
, -1, 0);
892 logmemory_quick(free_end
);
897 * Handle oversized allocations. XXX we really should require that a
898 * size be passed to free() instead of this nonsense.
900 * This code is never called via an ipi.
903 struct kmemusage
*kup
;
907 if (kup
->ku_pagecnt
) {
908 size
= kup
->ku_pagecnt
<< PAGE_SHIFT
;
911 KKASSERT(sizeof(weirdary
) <= size
);
912 bcopy(weirdary
, ptr
, sizeof(weirdary
));
915 * note: we always adjust our cpu's slot, not the originating
916 * cpu (kup->ku_cpuid). The statistics are in aggregate.
918 * note: XXX we have still inherited the interrupts-can't-block
919 * assumption. An interrupt thread does not bump
920 * gd_intr_nesting_level so check TDF_INTTHREAD. This is
921 * primarily until we can fix softupdate's assumptions about free().
924 --type
->ks_inuse
[gd
->gd_cpuid
];
925 type
->ks_memuse
[gd
->gd_cpuid
] -= size
;
926 if (mycpu
->gd_intr_nesting_level
|| (gd
->gd_curthread
->td_flags
& TDF_INTTHREAD
)) {
927 logmemory(free_ovsz_delayed
, ptr
, type
, size
, 0);
929 z
->z_Magic
= ZALLOC_OVSZ_MAGIC
;
930 z
->z_Next
= slgd
->FreeOvZones
;
931 z
->z_ChunkSize
= size
;
932 slgd
->FreeOvZones
= z
;
936 logmemory(free_ovsz
, ptr
, type
, size
, 0);
937 kmem_slab_free(ptr
, size
); /* may block */
939 logmemory_quick(free_end
);
945 * Zone case. Figure out the zone based on the fact that it is
948 z
= (SLZone
*)((uintptr_t)ptr
& ~(uintptr_t)ZoneMask
);
949 KKASSERT(z
->z_Magic
== ZALLOC_SLAB_MAGIC
);
952 * If we do not own the zone then forward the request to the
953 * cpu that does. Since the timing is non-critical, a passive
956 if (z
->z_CpuGd
!= gd
) {
957 *(struct malloc_type
**)ptr
= type
;
959 logmemory(free_request
, ptr
, type
, z
->z_ChunkSize
, 0);
960 lwkt_send_ipiq_passive(z
->z_CpuGd
, free_remote
, ptr
);
962 panic("Corrupt SLZone");
964 logmemory_quick(free_end
);
968 logmemory(free_chunk
, ptr
, type
, z
->z_ChunkSize
, 0);
970 if (type
->ks_magic
!= M_MAGIC
)
971 panic("free: malloc type lacks magic");
974 pgno
= ((char *)ptr
- (char *)z
) >> PAGE_SHIFT
;
979 * Attempt to detect a double-free. To reduce overhead we only check
980 * if there appears to be link pointer at the base of the data.
982 if (((intptr_t)chunk
->c_Next
- (intptr_t)z
) >> PAGE_SHIFT
== pgno
) {
984 for (scan
= z
->z_PageAry
[pgno
]; scan
; scan
= scan
->c_Next
) {
986 panic("Double free at %p", chunk
);
989 chunk_mark_free(z
, chunk
);
993 * Put weird data into the memory to detect modifications after freeing,
994 * illegal pointer use after freeing (we should fault on the odd address),
995 * and so forth. XXX needs more work, see the old malloc code.
998 if (z
->z_ChunkSize
< sizeof(weirdary
))
999 bcopy(weirdary
, chunk
, z
->z_ChunkSize
);
1001 bcopy(weirdary
, chunk
, sizeof(weirdary
));
1005 * Add this free non-zero'd chunk to a linked list for reuse, adjust
1009 if ((vm_offset_t
)chunk
< KvaStart
|| (vm_offset_t
)chunk
>= KvaEnd
)
1010 panic("BADFREE %p", chunk
);
1012 chunk
->c_Next
= z
->z_PageAry
[pgno
];
1013 z
->z_PageAry
[pgno
] = chunk
;
1015 if (chunk
->c_Next
&& (vm_offset_t
)chunk
->c_Next
< KvaStart
)
1018 if (z
->z_FirstFreePg
> pgno
)
1019 z
->z_FirstFreePg
= pgno
;
1022 * Bump the number of free chunks. If it becomes non-zero the zone
1023 * must be added back onto the appropriate list.
1025 if (z
->z_NFree
++ == 0) {
1026 z
->z_Next
= slgd
->ZoneAry
[z
->z_ZoneIndex
];
1027 slgd
->ZoneAry
[z
->z_ZoneIndex
] = z
;
1030 --type
->ks_inuse
[z
->z_Cpu
];
1031 type
->ks_memuse
[z
->z_Cpu
] -= z
->z_ChunkSize
;
1034 * If the zone becomes totally free, and there are other zones we
1035 * can allocate from, move this zone to the FreeZones list. Since
1036 * this code can be called from an IPI callback, do *NOT* try to mess
1037 * with kernel_map here. Hysteresis will be performed at malloc() time.
1039 if (z
->z_NFree
== z
->z_NMax
&&
1040 (z
->z_Next
|| slgd
->ZoneAry
[z
->z_ZoneIndex
] != z
)
1044 for (pz
= &slgd
->ZoneAry
[z
->z_ZoneIndex
]; z
!= *pz
; pz
= &(*pz
)->z_Next
)
1048 z
->z_Next
= slgd
->FreeZones
;
1049 slgd
->FreeZones
= z
;
1052 logmemory_quick(free_end
);
1056 #if defined(INVARIANTS)
1058 * Helper routines for sanity checks
1062 chunk_mark_allocated(SLZone
*z
, void *chunk
)
1064 int bitdex
= ((char *)chunk
- (char *)z
->z_BasePtr
) / z
->z_ChunkSize
;
1067 KASSERT(bitdex
>= 0 && bitdex
< z
->z_NMax
, ("memory chunk %p bit index %d is illegal", chunk
, bitdex
));
1068 bitptr
= &z
->z_Bitmap
[bitdex
>> 5];
1070 KASSERT((*bitptr
& (1 << bitdex
)) == 0, ("memory chunk %p is already allocated!", chunk
));
1071 *bitptr
|= 1 << bitdex
;
1076 chunk_mark_free(SLZone
*z
, void *chunk
)
1078 int bitdex
= ((char *)chunk
- (char *)z
->z_BasePtr
) / z
->z_ChunkSize
;
1081 KASSERT(bitdex
>= 0 && bitdex
< z
->z_NMax
, ("memory chunk %p bit index %d is illegal!", chunk
, bitdex
));
1082 bitptr
= &z
->z_Bitmap
[bitdex
>> 5];
1084 KASSERT((*bitptr
& (1 << bitdex
)) != 0, ("memory chunk %p is already free!", chunk
));
1085 *bitptr
&= ~(1 << bitdex
);
1093 * Directly allocate and wire kernel memory in PAGE_SIZE chunks with the
1094 * specified alignment. M_* flags are expected in the flags field.
1096 * Alignment must be a multiple of PAGE_SIZE.
1098 * NOTE! XXX For the moment we use vm_map_entry_reserve/release(),
1099 * but when we move zalloc() over to use this function as its backend
1100 * we will have to switch to kreserve/krelease and call reserve(0)
1101 * after the new space is made available.
1103 * Interrupt code which has preempted other code is not allowed to
1104 * use PQ_CACHE pages. However, if an interrupt thread is run
1105 * non-preemptively or blocks and then runs non-preemptively, then
1106 * it is free to use PQ_CACHE pages.
1108 * This routine will currently obtain the BGL.
1110 * MPALMOSTSAFE - acquires mplock
1113 kmem_slab_alloc(vm_size_t size
, vm_offset_t align
, int flags
)
1117 int count
, vmflags
, base_vmflags
;
1120 size
= round_page(size
);
1121 addr
= vm_map_min(&kernel_map
);
1124 * Reserve properly aligned space from kernel_map. RNOWAIT allocations
1127 if (flags
& M_RNOWAIT
) {
1128 if (try_mplock() == 0)
1133 count
= vm_map_entry_reserve(MAP_RESERVE_COUNT
);
1135 vm_map_lock(&kernel_map
);
1136 if (vm_map_findspace(&kernel_map
, addr
, size
, align
, 0, &addr
)) {
1137 vm_map_unlock(&kernel_map
);
1138 if ((flags
& M_NULLOK
) == 0)
1139 panic("kmem_slab_alloc(): kernel_map ran out of space!");
1141 vm_map_entry_release(count
);
1147 * kernel_object maps 1:1 to kernel_map.
1149 vm_object_reference(&kernel_object
);
1150 vm_map_insert(&kernel_map
, &count
,
1151 &kernel_object
, addr
, addr
, addr
+ size
,
1153 VM_PROT_ALL
, VM_PROT_ALL
,
1160 base_vmflags
|= VM_ALLOC_ZERO
;
1161 if (flags
& M_USE_RESERVE
)
1162 base_vmflags
|= VM_ALLOC_SYSTEM
;
1163 if (flags
& M_USE_INTERRUPT_RESERVE
)
1164 base_vmflags
|= VM_ALLOC_INTERRUPT
;
1165 if ((flags
& (M_RNOWAIT
|M_WAITOK
)) == 0)
1166 panic("kmem_slab_alloc: bad flags %08x (%p)", flags
, ((int **)&size
)[-1]);
1170 * Allocate the pages. Do not mess with the PG_ZERO flag yet.
1172 for (i
= 0; i
< size
; i
+= PAGE_SIZE
) {
1176 * VM_ALLOC_NORMAL can only be set if we are not preempting.
1178 * VM_ALLOC_SYSTEM is automatically set if we are preempting and
1179 * M_WAITOK was specified as an alternative (i.e. M_USE_RESERVE is
1180 * implied in this case), though I'm not sure if we really need to
1183 vmflags
= base_vmflags
;
1184 if (flags
& M_WAITOK
) {
1185 if (td
->td_preempted
)
1186 vmflags
|= VM_ALLOC_SYSTEM
;
1188 vmflags
|= VM_ALLOC_NORMAL
;
1191 m
= vm_page_alloc(&kernel_object
, OFF_TO_IDX(addr
+ i
), vmflags
);
1194 * If the allocation failed we either return NULL or we retry.
1196 * If M_WAITOK is specified we wait for more memory and retry.
1197 * If M_WAITOK is specified from a preemption we yield instead of
1198 * wait. Livelock will not occur because the interrupt thread
1199 * will not be preempting anyone the second time around after the
1203 if (flags
& M_WAITOK
) {
1204 if (td
->td_preempted
) {
1205 vm_map_unlock(&kernel_map
);
1207 vm_map_lock(&kernel_map
);
1209 vm_map_unlock(&kernel_map
);
1211 vm_map_lock(&kernel_map
);
1213 i
-= PAGE_SIZE
; /* retry */
1218 * We were unable to recover, cleanup and return NULL
1222 m
= vm_page_lookup(&kernel_object
, OFF_TO_IDX(addr
+ i
));
1223 /* page should already be busy */
1226 vm_map_delete(&kernel_map
, addr
, addr
+ size
, &count
);
1227 vm_map_unlock(&kernel_map
);
1229 vm_map_entry_release(count
);
1238 * Mark the map entry as non-pageable using a routine that allows us to
1239 * populate the underlying pages.
1241 * The pages were busied by the allocations above.
1243 vm_map_set_wired_quick(&kernel_map
, addr
, size
, &count
);
1247 * Enter the pages into the pmap and deal with PG_ZERO and M_ZERO.
1249 for (i
= 0; i
< size
; i
+= PAGE_SIZE
) {
1252 m
= vm_page_lookup(&kernel_object
, OFF_TO_IDX(addr
+ i
));
1253 m
->valid
= VM_PAGE_BITS_ALL
;
1254 /* page should already be busy */
1257 pmap_enter(&kernel_pmap
, addr
+ i
, m
, VM_PROT_ALL
, 1);
1258 if ((m
->flags
& PG_ZERO
) == 0 && (flags
& M_ZERO
))
1259 bzero((char *)addr
+ i
, PAGE_SIZE
);
1260 vm_page_flag_clear(m
, PG_ZERO
);
1261 KKASSERT(m
->flags
& (PG_WRITEABLE
| PG_MAPPED
));
1262 vm_page_flag_set(m
, PG_REFERENCED
);
1264 vm_map_unlock(&kernel_map
);
1265 vm_map_entry_release(count
);
1267 return((void *)addr
);
1273 * MPALMOSTSAFE - acquires mplock
1276 kmem_slab_free(void *ptr
, vm_size_t size
)
1280 vm_map_remove(&kernel_map
, (vm_offset_t
)ptr
, (vm_offset_t
)ptr
+ size
);