4 * KERN_SLABALLOC.C - Kernel SLAB memory allocator
6 * Copyright (c) 2003,2004,2010 The DragonFly Project. All rights reserved.
8 * This code is derived from software contributed to The DragonFly Project
9 * by Matthew Dillon <dillon@backplane.com>
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in
19 * the documentation and/or other materials provided with the
21 * 3. Neither the name of The DragonFly Project nor the names of its
22 * contributors may be used to endorse or promote products derived
23 * from this software without specific, prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
31 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
33 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
34 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
35 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * $DragonFly: src/sys/kern/kern_slaballoc.c,v 1.55 2008/10/22 01:42:17 dillon Exp $
40 * This module implements a slab allocator drop-in replacement for the
43 * A slab allocator reserves a ZONE for each chunk size, then lays the
44 * chunks out in an array within the zone. Allocation and deallocation
45 * is nearly instantanious, and fragmentation/overhead losses are limited
46 * to a fixed worst-case amount.
48 * The downside of this slab implementation is in the chunk size
49 * multiplied by the number of zones. ~80 zones * 128K = 10MB of VM per cpu.
50 * In a kernel implementation all this memory will be physical so
51 * the zone size is adjusted downward on machines with less physical
52 * memory. The upside is that overhead is bounded... this is the *worst*
55 * Slab management is done on a per-cpu basis and no locking or mutexes
56 * are required, only a critical section. When one cpu frees memory
57 * belonging to another cpu's slab manager an asynchronous IPI message
58 * will be queued to execute the operation. In addition, both the
59 * high level slab allocator and the low level zone allocator optimize
60 * M_ZERO requests, and the slab allocator does not have to pre initialize
61 * the linked list of chunks.
63 * XXX Balancing is needed between cpus. Balance will be handled through
64 * asynchronous IPIs primarily by reassigning the z_Cpu ownership of chunks.
66 * XXX If we have to allocate a new zone and M_USE_RESERVE is set, use of
67 * the new zone should be restricted to M_USE_RESERVE requests only.
69 * Alloc Size Chunking Number of zones
79 * (if PAGE_SIZE is 4K the maximum zone allocation is 16383)
81 * Allocations >= ZoneLimit go directly to kmem.
83 * API REQUIREMENTS AND SIDE EFFECTS
85 * To operate as a drop-in replacement to the FreeBSD-4.x malloc() we
86 * have remained compatible with the following API requirements:
88 * + small power-of-2 sized allocations are power-of-2 aligned (kern_tty)
89 * + all power-of-2 sized allocations are power-of-2 aligned (twe)
90 * + malloc(0) is allowed and returns non-NULL (ahc driver)
91 * + ability to allocate arbitrarily large chunks of memory
96 #include <sys/param.h>
97 #include <sys/systm.h>
98 #include <sys/kernel.h>
99 #include <sys/slaballoc.h>
100 #include <sys/mbuf.h>
101 #include <sys/vmmeter.h>
102 #include <sys/lock.h>
103 #include <sys/thread.h>
104 #include <sys/globaldata.h>
105 #include <sys/sysctl.h>
109 #include <vm/vm_param.h>
110 #include <vm/vm_kern.h>
111 #include <vm/vm_extern.h>
112 #include <vm/vm_object.h>
114 #include <vm/vm_map.h>
115 #include <vm/vm_page.h>
116 #include <vm/vm_pageout.h>
118 #include <machine/cpu.h>
120 #include <sys/thread2.h>
122 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
124 #define MEMORY_STRING "ptr=%p type=%p size=%d flags=%04x"
125 #define MEMORY_ARG_SIZE (sizeof(void *) * 2 + sizeof(unsigned long) + \
128 #if !defined(KTR_MEMORY)
129 #define KTR_MEMORY KTR_ALL
131 KTR_INFO_MASTER(memory);
132 KTR_INFO(KTR_MEMORY, memory, malloc, 0, MEMORY_STRING, MEMORY_ARG_SIZE);
133 KTR_INFO(KTR_MEMORY, memory, free_zero, 1, MEMORY_STRING, MEMORY_ARG_SIZE);
134 KTR_INFO(KTR_MEMORY, memory, free_ovsz, 2, MEMORY_STRING, MEMORY_ARG_SIZE);
135 KTR_INFO(KTR_MEMORY, memory, free_ovsz_delayed, 3, MEMORY_STRING, MEMORY_ARG_SIZE);
136 KTR_INFO(KTR_MEMORY, memory, free_chunk, 4, MEMORY_STRING, MEMORY_ARG_SIZE);
138 KTR_INFO(KTR_MEMORY, memory, free_request, 5, MEMORY_STRING, MEMORY_ARG_SIZE);
139 KTR_INFO(KTR_MEMORY, memory, free_remote, 6, MEMORY_STRING, MEMORY_ARG_SIZE);
141 KTR_INFO(KTR_MEMORY, memory, malloc_beg, 0, "malloc begin", 0);
142 KTR_INFO(KTR_MEMORY, memory, free_beg, 0, "free begin", 0);
143 KTR_INFO(KTR_MEMORY, memory, free_end, 0, "free end", 0);
145 #define logmemory(name, ptr, type, size, flags) \
146 KTR_LOG(memory_ ## name, ptr, type, size, flags)
147 #define logmemory_quick(name) \
148 KTR_LOG(memory_ ## name)
151 * Fixed globals (not per-cpu)
154 static int ZoneLimit;
155 static int ZonePageCount;
157 static int ZoneBigAlloc; /* in KB */
158 static int ZoneGenAlloc; /* in KB */
159 struct malloc_type *kmemstatistics; /* exported to vmstat */
160 static struct kmemusage *kmemusage;
161 static int32_t weirdary[16];
163 static void *kmem_slab_alloc(vm_size_t bytes, vm_offset_t align, int flags);
164 static void kmem_slab_free(void *ptr, vm_size_t bytes);
165 #if defined(INVARIANTS)
166 static void chunk_mark_allocated(SLZone *z, void *chunk);
167 static void chunk_mark_free(SLZone *z, void *chunk);
171 * Misc constants. Note that allocations that are exact multiples of
172 * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
173 * IN_SAME_PAGE_MASK is used to sanity-check the per-page free lists.
175 #define MIN_CHUNK_SIZE 8 /* in bytes */
176 #define MIN_CHUNK_MASK (MIN_CHUNK_SIZE - 1)
177 #define ZONE_RELS_THRESH 2 /* threshold number of zones */
178 #define IN_SAME_PAGE_MASK (~(intptr_t)PAGE_MASK | MIN_CHUNK_MASK)
181 * The WEIRD_ADDR is used as known text to copy into free objects to
182 * try to create deterministic failure cases if the data is accessed after
185 #define WEIRD_ADDR 0xdeadc0de
186 #define MAX_COPY sizeof(weirdary)
187 #define ZERO_LENGTH_PTR ((void *)-8)
190 * Misc global malloc buckets
193 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
194 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
195 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
197 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
198 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
201 * Initialize the slab memory allocator. We have to choose a zone size based
202 * on available physical memory. We choose a zone side which is approximately
203 * 1/1024th of our memory, so if we have 128MB of ram we have a zone size of
204 * 128K. The zone size is limited to the bounds set in slaballoc.h
205 * (typically 32K min, 128K max).
207 static void kmeminit(void *dummy);
211 SYSINIT(kmem, SI_BOOT1_ALLOCATOR, SI_ORDER_FIRST, kmeminit, NULL)
215 * If enabled any memory allocated without M_ZERO is initialized to -1.
217 static int use_malloc_pattern;
218 SYSCTL_INT(_debug, OID_AUTO, use_malloc_pattern, CTLFLAG_RW,
219 &use_malloc_pattern, 0, "");
222 SYSCTL_INT(_kern, OID_AUTO, zone_big_alloc, CTLFLAG_RD, &ZoneBigAlloc, 0, "");
223 SYSCTL_INT(_kern, OID_AUTO, zone_gen_alloc, CTLFLAG_RD, &ZoneGenAlloc, 0, "");
226 kmeminit(void *dummy)
233 limsize = (size_t)vmstats.v_page_count * PAGE_SIZE;
234 if (limsize > KvaSize)
237 usesize = (int)(limsize / 1024); /* convert to KB */
239 ZoneSize = ZALLOC_MIN_ZONE_SIZE;
240 while (ZoneSize < ZALLOC_MAX_ZONE_SIZE && (ZoneSize << 1) < usesize)
242 ZoneLimit = ZoneSize / 4;
243 if (ZoneLimit > ZALLOC_ZONE_LIMIT)
244 ZoneLimit = ZALLOC_ZONE_LIMIT;
245 ZoneMask = ZoneSize - 1;
246 ZonePageCount = ZoneSize / PAGE_SIZE;
248 npg = KvaSize / PAGE_SIZE;
249 kmemusage = kmem_slab_alloc(npg * sizeof(struct kmemusage),
250 PAGE_SIZE, M_WAITOK|M_ZERO);
252 for (i = 0; i < arysize(weirdary); ++i)
253 weirdary[i] = WEIRD_ADDR;
255 ZeroPage = kmem_slab_alloc(PAGE_SIZE, PAGE_SIZE, M_WAITOK|M_ZERO);
258 kprintf("Slab ZoneSize set to %dKB\n", ZoneSize / 1024);
262 * Initialize a malloc type tracking structure.
265 malloc_init(void *data)
267 struct malloc_type *type = data;
270 if (type->ks_magic != M_MAGIC)
271 panic("malloc type lacks magic");
273 if (type->ks_limit != 0)
276 if (vmstats.v_page_count == 0)
277 panic("malloc_init not allowed before vm init");
279 limsize = (size_t)vmstats.v_page_count * PAGE_SIZE;
280 if (limsize > KvaSize)
282 type->ks_limit = limsize / 10;
284 type->ks_next = kmemstatistics;
285 kmemstatistics = type;
289 malloc_uninit(void *data)
291 struct malloc_type *type = data;
292 struct malloc_type *t;
298 if (type->ks_magic != M_MAGIC)
299 panic("malloc type lacks magic");
301 if (vmstats.v_page_count == 0)
302 panic("malloc_uninit not allowed before vm init");
304 if (type->ks_limit == 0)
305 panic("malloc_uninit on uninitialized type");
308 /* Make sure that all pending kfree()s are finished. */
309 lwkt_synchronize_ipiqs("muninit");
314 * memuse is only correct in aggregation. Due to memory being allocated
315 * on one cpu and freed on another individual array entries may be
316 * negative or positive (canceling each other out).
318 for (i = ttl = 0; i < ncpus; ++i)
319 ttl += type->ks_memuse[i];
321 kprintf("malloc_uninit: %ld bytes of '%s' still allocated on cpu %d\n",
322 ttl, type->ks_shortdesc, i);
325 if (type == kmemstatistics) {
326 kmemstatistics = type->ks_next;
328 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
329 if (t->ks_next == type) {
330 t->ks_next = type->ks_next;
335 type->ks_next = NULL;
340 * Increase the kmalloc pool limit for the specified pool. No changes
341 * are the made if the pool would shrink.
344 kmalloc_raise_limit(struct malloc_type *type, size_t bytes)
346 if (type->ks_limit == 0)
350 if (type->ks_limit < bytes)
351 type->ks_limit = bytes;
355 * Dynamically create a malloc pool. This function is a NOP if *typep is
359 kmalloc_create(struct malloc_type **typep, const char *descr)
361 struct malloc_type *type;
363 if (*typep == NULL) {
364 type = kmalloc(sizeof(*type), M_TEMP, M_WAITOK | M_ZERO);
365 type->ks_magic = M_MAGIC;
366 type->ks_shortdesc = descr;
373 * Destroy a dynamically created malloc pool. This function is a NOP if
374 * the pool has already been destroyed.
377 kmalloc_destroy(struct malloc_type **typep)
379 if (*typep != NULL) {
380 malloc_uninit(*typep);
381 kfree(*typep, M_TEMP);
387 * Calculate the zone index for the allocation request size and set the
388 * allocation request size to that particular zone's chunk size.
391 zoneindex(unsigned long *bytes)
393 unsigned int n = (unsigned int)*bytes; /* unsigned for shift opt */
395 *bytes = n = (n + 7) & ~7;
396 return(n / 8 - 1); /* 8 byte chunks, 16 zones */
399 *bytes = n = (n + 15) & ~15;
404 *bytes = n = (n + 31) & ~31;
408 *bytes = n = (n + 63) & ~63;
412 *bytes = n = (n + 127) & ~127;
413 return(n / 128 + 31);
416 *bytes = n = (n + 255) & ~255;
417 return(n / 256 + 39);
419 *bytes = n = (n + 511) & ~511;
420 return(n / 512 + 47);
422 #if ZALLOC_ZONE_LIMIT > 8192
424 *bytes = n = (n + 1023) & ~1023;
425 return(n / 1024 + 55);
428 #if ZALLOC_ZONE_LIMIT > 16384
430 *bytes = n = (n + 2047) & ~2047;
431 return(n / 2048 + 63);
434 panic("Unexpected byte count %d", n);
439 * malloc() (SLAB ALLOCATOR)
441 * Allocate memory via the slab allocator. If the request is too large,
442 * or if it page-aligned beyond a certain size, we fall back to the
443 * KMEM subsystem. A SLAB tracking descriptor must be specified, use
444 * &SlabMisc if you don't care.
446 * M_RNOWAIT - don't block.
447 * M_NULLOK - return NULL instead of blocking.
448 * M_ZERO - zero the returned memory.
449 * M_USE_RESERVE - allow greater drawdown of the free list
450 * M_USE_INTERRUPT_RESERVE - allow the freelist to be exhausted
456 kmalloc(unsigned long size, struct malloc_type *type, int flags)
461 struct globaldata *gd;
467 logmemory_quick(malloc_beg);
472 * XXX silly to have this in the critical path.
474 if (type->ks_limit == 0) {
476 if (type->ks_limit == 0)
483 * Handle the case where the limit is reached. Panic if we can't return
484 * NULL. The original malloc code looped, but this tended to
485 * simply deadlock the computer.
487 * ks_loosememuse is an up-only limit that is NOT MP-synchronized, used
488 * to determine if a more complete limit check should be done. The
489 * actual memory use is tracked via ks_memuse[cpu].
491 while (type->ks_loosememuse >= type->ks_limit) {
495 for (i = ttl = 0; i < ncpus; ++i)
496 ttl += type->ks_memuse[i];
497 type->ks_loosememuse = ttl; /* not MP synchronized */
498 if (ttl >= type->ks_limit) {
499 if (flags & M_NULLOK) {
500 logmemory(malloc, NULL, type, size, flags);
503 panic("%s: malloc limit exceeded", type->ks_shortdesc);
508 * Handle the degenerate size == 0 case. Yes, this does happen.
509 * Return a special pointer. This is to maintain compatibility with
510 * the original malloc implementation. Certain devices, such as the
511 * adaptec driver, not only allocate 0 bytes, they check for NULL and
512 * also realloc() later on. Joy.
515 logmemory(malloc, ZERO_LENGTH_PTR, type, size, flags);
516 return(ZERO_LENGTH_PTR);
520 * Handle hysteresis from prior frees here in malloc(). We cannot
521 * safely manipulate the kernel_map in free() due to free() possibly
522 * being called via an IPI message or from sensitive interrupt code.
524 while (slgd->NFreeZones > ZONE_RELS_THRESH && (flags & M_RNOWAIT) == 0) {
526 if (slgd->NFreeZones > ZONE_RELS_THRESH) { /* crit sect race */
528 slgd->FreeZones = z->z_Next;
530 kmem_slab_free(z, ZoneSize); /* may block */
531 atomic_add_int(&ZoneGenAlloc, -(int)ZoneSize / 1024);
536 * XXX handle oversized frees that were queued from free().
538 while (slgd->FreeOvZones && (flags & M_RNOWAIT) == 0) {
540 if ((z = slgd->FreeOvZones) != NULL) {
543 KKASSERT(z->z_Magic == ZALLOC_OVSZ_MAGIC);
544 slgd->FreeOvZones = z->z_Next;
545 tsize = z->z_ChunkSize;
546 kmem_slab_free(z, tsize); /* may block */
547 atomic_add_int(&ZoneBigAlloc, -(int)tsize / 1024);
553 * Handle large allocations directly. There should not be very many of
554 * these so performance is not a big issue.
556 * The backend allocator is pretty nasty on a SMP system. Use the
557 * slab allocator for one and two page-sized chunks even though we lose
558 * some efficiency. XXX maybe fix mmio and the elf loader instead.
560 if (size >= ZoneLimit || ((size & PAGE_MASK) == 0 && size > PAGE_SIZE*2)) {
561 struct kmemusage *kup;
563 size = round_page(size);
564 chunk = kmem_slab_alloc(size, PAGE_SIZE, flags);
566 logmemory(malloc, NULL, type, size, flags);
569 atomic_add_int(&ZoneBigAlloc, (int)size / 1024);
570 flags &= ~M_ZERO; /* result already zero'd if M_ZERO was set */
571 flags |= M_PASSIVE_ZERO;
573 kup->ku_pagecnt = size / PAGE_SIZE;
579 * Attempt to allocate out of an existing zone. First try the free list,
580 * then allocate out of unallocated space. If we find a good zone move
581 * it to the head of the list so later allocations find it quickly
582 * (we might have thousands of zones in the list).
584 * Note: zoneindex() will panic of size is too large.
586 zi = zoneindex(&size);
587 KKASSERT(zi < NZONES);
589 if ((z = slgd->ZoneAry[zi]) != NULL) {
590 KKASSERT(z->z_NFree > 0);
593 * Remove us from the ZoneAry[] when we become empty
595 if (--z->z_NFree == 0) {
596 slgd->ZoneAry[zi] = z->z_Next;
601 * Locate a chunk in a free page. This attempts to localize
602 * reallocations into earlier pages without us having to sort
603 * the chunk list. A chunk may still overlap a page boundary.
605 while (z->z_FirstFreePg < ZonePageCount) {
606 if ((chunk = z->z_PageAry[z->z_FirstFreePg]) != NULL) {
609 * Diagnostic: c_Next is not total garbage.
611 KKASSERT(chunk->c_Next == NULL ||
612 ((intptr_t)chunk->c_Next & IN_SAME_PAGE_MASK) ==
613 ((intptr_t)chunk & IN_SAME_PAGE_MASK));
616 if ((vm_offset_t)chunk < KvaStart || (vm_offset_t)chunk >= KvaEnd)
617 panic("chunk %p FFPG %d/%d", chunk, z->z_FirstFreePg, ZonePageCount);
618 if (chunk->c_Next && (vm_offset_t)chunk->c_Next < KvaStart)
619 panic("chunkNEXT %p %p FFPG %d/%d", chunk, chunk->c_Next, z->z_FirstFreePg, ZonePageCount);
620 chunk_mark_allocated(z, chunk);
622 z->z_PageAry[z->z_FirstFreePg] = chunk->c_Next;
629 * No chunks are available but NFree said we had some memory, so
630 * it must be available in the never-before-used-memory area
631 * governed by UIndex. The consequences are very serious if our zone
632 * got corrupted so we use an explicit panic rather then a KASSERT.
634 if (z->z_UIndex + 1 != z->z_NMax)
635 z->z_UIndex = z->z_UIndex + 1;
638 if (z->z_UIndex == z->z_UEndIndex)
639 panic("slaballoc: corrupted zone");
640 chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
641 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
643 flags |= M_PASSIVE_ZERO;
645 #if defined(INVARIANTS)
646 chunk_mark_allocated(z, chunk);
652 * If all zones are exhausted we need to allocate a new zone for this
653 * index. Use M_ZERO to take advantage of pre-zerod pages. Also see
654 * UAlloc use above in regards to M_ZERO. Note that when we are reusing
655 * a zone from the FreeZones list UAlloc'd data will not be zero'd, and
656 * we do not pre-zero it because we do not want to mess up the L1 cache.
658 * At least one subsystem, the tty code (see CROUND) expects power-of-2
659 * allocations to be power-of-2 aligned. We maintain compatibility by
660 * adjusting the base offset below.
665 if ((z = slgd->FreeZones) != NULL) {
666 slgd->FreeZones = z->z_Next;
668 bzero(z, sizeof(SLZone));
669 z->z_Flags |= SLZF_UNOTZEROD;
671 z = kmem_slab_alloc(ZoneSize, ZoneSize, flags|M_ZERO);
674 atomic_add_int(&ZoneGenAlloc, (int)ZoneSize / 1024);
678 * How big is the base structure?
680 #if defined(INVARIANTS)
682 * Make room for z_Bitmap. An exact calculation is somewhat more
683 * complicated so don't make an exact calculation.
685 off = offsetof(SLZone, z_Bitmap[(ZoneSize / size + 31) / 32]);
686 bzero(z->z_Bitmap, (ZoneSize / size + 31) / 8);
688 off = sizeof(SLZone);
692 * Guarentee power-of-2 alignment for power-of-2-sized chunks.
693 * Otherwise just 8-byte align the data.
695 if ((size | (size - 1)) + 1 == (size << 1))
696 off = (off + size - 1) & ~(size - 1);
698 off = (off + MIN_CHUNK_MASK) & ~MIN_CHUNK_MASK;
699 z->z_Magic = ZALLOC_SLAB_MAGIC;
701 z->z_NMax = (ZoneSize - off) / size;
702 z->z_NFree = z->z_NMax - 1;
703 z->z_BasePtr = (char *)z + off;
704 z->z_UIndex = z->z_UEndIndex = slgd->JunkIndex % z->z_NMax;
705 z->z_ChunkSize = size;
706 z->z_FirstFreePg = ZonePageCount;
708 z->z_Cpu = gd->gd_cpuid;
709 chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
710 z->z_Next = slgd->ZoneAry[zi];
711 slgd->ZoneAry[zi] = z;
712 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
713 flags &= ~M_ZERO; /* already zero'd */
714 flags |= M_PASSIVE_ZERO;
716 #if defined(INVARIANTS)
717 chunk_mark_allocated(z, chunk);
721 * Slide the base index for initial allocations out of the next
722 * zone we create so we do not over-weight the lower part of the
725 slgd->JunkIndex = (slgd->JunkIndex + ZALLOC_SLAB_SLIDE)
726 & (ZALLOC_MAX_ZONE_SIZE - 1);
729 ++type->ks_inuse[gd->gd_cpuid];
730 type->ks_memuse[gd->gd_cpuid] += size;
731 type->ks_loosememuse += size; /* not MP synchronized */
736 else if ((flags & (M_ZERO|M_PASSIVE_ZERO)) == 0) {
737 if (use_malloc_pattern) {
738 for (i = 0; i < size; i += sizeof(int)) {
739 *(int *)((char *)chunk + i) = -1;
742 chunk->c_Next = (void *)-1; /* avoid accidental double-free check */
745 logmemory(malloc, chunk, type, size, flags);
749 logmemory(malloc, NULL, type, size, flags);
754 * kernel realloc. (SLAB ALLOCATOR) (MP SAFE)
756 * Generally speaking this routine is not called very often and we do
757 * not attempt to optimize it beyond reusing the same pointer if the
758 * new size fits within the chunking of the old pointer's zone.
761 krealloc(void *ptr, unsigned long size, struct malloc_type *type, int flags)
767 KKASSERT((flags & M_ZERO) == 0); /* not supported */
769 if (ptr == NULL || ptr == ZERO_LENGTH_PTR)
770 return(kmalloc(size, type, flags));
777 * Handle oversized allocations. XXX we really should require that a
778 * size be passed to free() instead of this nonsense.
781 struct kmemusage *kup;
784 if (kup->ku_pagecnt) {
785 osize = kup->ku_pagecnt << PAGE_SHIFT;
786 if (osize == round_page(size))
788 if ((nptr = kmalloc(size, type, flags)) == NULL)
790 bcopy(ptr, nptr, min(size, osize));
797 * Get the original allocation's zone. If the new request winds up
798 * using the same chunk size we do not have to do anything.
800 z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
801 KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
804 * Allocate memory for the new request size. Note that zoneindex has
805 * already adjusted the request size to the appropriate chunk size, which
806 * should optimize our bcopy(). Then copy and return the new pointer.
808 * Resizing a non-power-of-2 allocation to a power-of-2 size does not
809 * necessary align the result.
811 * We can only zoneindex (to align size to the chunk size) if the new
812 * size is not too large.
814 if (size < ZoneLimit) {
816 if (z->z_ChunkSize == size)
819 if ((nptr = kmalloc(size, type, flags)) == NULL)
821 bcopy(ptr, nptr, min(size, z->z_ChunkSize));
827 * Return the kmalloc limit for this type, in bytes.
830 kmalloc_limit(struct malloc_type *type)
832 if (type->ks_limit == 0) {
834 if (type->ks_limit == 0)
838 return(type->ks_limit);
842 * Allocate a copy of the specified string.
844 * (MP SAFE) (MAY BLOCK)
847 kstrdup(const char *str, struct malloc_type *type)
849 int zlen; /* length inclusive of terminating NUL */
854 zlen = strlen(str) + 1;
855 nstr = kmalloc(zlen, type, M_WAITOK);
856 bcopy(str, nstr, zlen);
862 * free() (SLAB ALLOCATOR)
864 * Free the specified chunk of memory.
868 free_remote(void *ptr)
870 logmemory(free_remote, ptr, *(struct malloc_type **)ptr, -1, 0);
871 kfree(ptr, *(struct malloc_type **)ptr);
877 * free (SLAB ALLOCATOR)
879 * Free a memory block previously allocated by malloc. Note that we do not
880 * attempt to uplodate ks_loosememuse as MP races could prevent us from
881 * checking memory limits in malloc.
886 kfree(void *ptr, struct malloc_type *type)
891 struct globaldata *gd;
894 logmemory_quick(free_beg);
899 panic("trying to free NULL pointer");
902 * Handle special 0-byte allocations
904 if (ptr == ZERO_LENGTH_PTR) {
905 logmemory(free_zero, ptr, type, -1, 0);
906 logmemory_quick(free_end);
911 * Handle oversized allocations. XXX we really should require that a
912 * size be passed to free() instead of this nonsense.
914 * This code is never called via an ipi.
917 struct kmemusage *kup;
921 if (kup->ku_pagecnt) {
922 size = kup->ku_pagecnt << PAGE_SHIFT;
925 KKASSERT(sizeof(weirdary) <= size);
926 bcopy(weirdary, ptr, sizeof(weirdary));
929 * NOTE: For oversized allocations we do not record the
930 * originating cpu. It gets freed on the cpu calling
931 * kfree(). The statistics are in aggregate.
933 * note: XXX we have still inherited the interrupts-can't-block
934 * assumption. An interrupt thread does not bump
935 * gd_intr_nesting_level so check TDF_INTTHREAD. This is
936 * primarily until we can fix softupdate's assumptions about free().
939 --type->ks_inuse[gd->gd_cpuid];
940 type->ks_memuse[gd->gd_cpuid] -= size;
941 if (mycpu->gd_intr_nesting_level ||
942 (gd->gd_curthread->td_flags & TDF_INTTHREAD))
944 logmemory(free_ovsz_delayed, ptr, type, size, 0);
946 z->z_Magic = ZALLOC_OVSZ_MAGIC;
947 z->z_Next = slgd->FreeOvZones;
948 z->z_ChunkSize = size;
949 slgd->FreeOvZones = z;
953 logmemory(free_ovsz, ptr, type, size, 0);
954 kmem_slab_free(ptr, size); /* may block */
955 atomic_add_int(&ZoneBigAlloc, -(int)size / 1024);
957 logmemory_quick(free_end);
963 * Zone case. Figure out the zone based on the fact that it is
966 z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
967 KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
970 * If we do not own the zone then forward the request to the
971 * cpu that does. Since the timing is non-critical, a passive
974 if (z->z_CpuGd != gd) {
975 *(struct malloc_type **)ptr = type;
977 logmemory(free_request, ptr, type, z->z_ChunkSize, 0);
978 lwkt_send_ipiq_passive(z->z_CpuGd, free_remote, ptr);
980 panic("Corrupt SLZone");
982 logmemory_quick(free_end);
986 logmemory(free_chunk, ptr, type, z->z_ChunkSize, 0);
988 if (type->ks_magic != M_MAGIC)
989 panic("free: malloc type lacks magic");
992 pgno = ((char *)ptr - (char *)z) >> PAGE_SHIFT;
997 * Attempt to detect a double-free. To reduce overhead we only check
998 * if there appears to be link pointer at the base of the data.
1000 if (((intptr_t)chunk->c_Next - (intptr_t)z) >> PAGE_SHIFT == pgno) {
1002 for (scan = z->z_PageAry[pgno]; scan; scan = scan->c_Next) {
1004 panic("Double free at %p", chunk);
1007 chunk_mark_free(z, chunk);
1011 * Put weird data into the memory to detect modifications after freeing,
1012 * illegal pointer use after freeing (we should fault on the odd address),
1013 * and so forth. XXX needs more work, see the old malloc code.
1016 if (z->z_ChunkSize < sizeof(weirdary))
1017 bcopy(weirdary, chunk, z->z_ChunkSize);
1019 bcopy(weirdary, chunk, sizeof(weirdary));
1023 * Add this free non-zero'd chunk to a linked list for reuse, adjust
1027 if ((vm_offset_t)chunk < KvaStart || (vm_offset_t)chunk >= KvaEnd)
1028 panic("BADFREE %p", chunk);
1030 chunk->c_Next = z->z_PageAry[pgno];
1031 z->z_PageAry[pgno] = chunk;
1033 if (chunk->c_Next && (vm_offset_t)chunk->c_Next < KvaStart)
1036 if (z->z_FirstFreePg > pgno)
1037 z->z_FirstFreePg = pgno;
1040 * Bump the number of free chunks. If it becomes non-zero the zone
1041 * must be added back onto the appropriate list.
1043 if (z->z_NFree++ == 0) {
1044 z->z_Next = slgd->ZoneAry[z->z_ZoneIndex];
1045 slgd->ZoneAry[z->z_ZoneIndex] = z;
1048 --type->ks_inuse[z->z_Cpu];
1049 type->ks_memuse[z->z_Cpu] -= z->z_ChunkSize;
1052 * If the zone becomes totally free, and there are other zones we
1053 * can allocate from, move this zone to the FreeZones list. Since
1054 * this code can be called from an IPI callback, do *NOT* try to mess
1055 * with kernel_map here. Hysteresis will be performed at malloc() time.
1057 if (z->z_NFree == z->z_NMax &&
1058 (z->z_Next || slgd->ZoneAry[z->z_ZoneIndex] != z)
1062 for (pz = &slgd->ZoneAry[z->z_ZoneIndex]; z != *pz; pz = &(*pz)->z_Next)
1066 z->z_Next = slgd->FreeZones;
1067 slgd->FreeZones = z;
1070 logmemory_quick(free_end);
1074 #if defined(INVARIANTS)
1076 * Helper routines for sanity checks
1080 chunk_mark_allocated(SLZone *z, void *chunk)
1082 int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
1085 KASSERT(bitdex >= 0 && bitdex < z->z_NMax, ("memory chunk %p bit index %d is illegal", chunk, bitdex));
1086 bitptr = &z->z_Bitmap[bitdex >> 5];
1088 KASSERT((*bitptr & (1 << bitdex)) == 0, ("memory chunk %p is already allocated!", chunk));
1089 *bitptr |= 1 << bitdex;
1094 chunk_mark_free(SLZone *z, void *chunk)
1096 int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
1099 KASSERT(bitdex >= 0 && bitdex < z->z_NMax, ("memory chunk %p bit index %d is illegal!", chunk, bitdex));
1100 bitptr = &z->z_Bitmap[bitdex >> 5];
1102 KASSERT((*bitptr & (1 << bitdex)) != 0, ("memory chunk %p is already free!", chunk));
1103 *bitptr &= ~(1 << bitdex);
1111 * Directly allocate and wire kernel memory in PAGE_SIZE chunks with the
1112 * specified alignment. M_* flags are expected in the flags field.
1114 * Alignment must be a multiple of PAGE_SIZE.
1116 * NOTE! XXX For the moment we use vm_map_entry_reserve/release(),
1117 * but when we move zalloc() over to use this function as its backend
1118 * we will have to switch to kreserve/krelease and call reserve(0)
1119 * after the new space is made available.
1121 * Interrupt code which has preempted other code is not allowed to
1122 * use PQ_CACHE pages. However, if an interrupt thread is run
1123 * non-preemptively or blocks and then runs non-preemptively, then
1124 * it is free to use PQ_CACHE pages.
1127 kmem_slab_alloc(vm_size_t size, vm_offset_t align, int flags)
1131 int count, vmflags, base_vmflags;
1134 size = round_page(size);
1135 addr = vm_map_min(&kernel_map);
1138 * Reserve properly aligned space from kernel_map. RNOWAIT allocations
1141 if (flags & M_RNOWAIT) {
1142 if (lwkt_trytoken(&vm_token) == 0)
1145 lwkt_gettoken(&vm_token);
1147 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1149 vm_map_lock(&kernel_map);
1150 if (vm_map_findspace(&kernel_map, addr, size, align, 0, &addr)) {
1151 vm_map_unlock(&kernel_map);
1152 if ((flags & M_NULLOK) == 0)
1153 panic("kmem_slab_alloc(): kernel_map ran out of space!");
1154 vm_map_entry_release(count);
1156 lwkt_reltoken(&vm_token);
1161 * kernel_object maps 1:1 to kernel_map.
1163 vm_object_reference(&kernel_object);
1164 vm_map_insert(&kernel_map, &count,
1165 &kernel_object, addr, addr, addr + size,
1167 VM_PROT_ALL, VM_PROT_ALL,
1174 base_vmflags |= VM_ALLOC_ZERO;
1175 if (flags & M_USE_RESERVE)
1176 base_vmflags |= VM_ALLOC_SYSTEM;
1177 if (flags & M_USE_INTERRUPT_RESERVE)
1178 base_vmflags |= VM_ALLOC_INTERRUPT;
1179 if ((flags & (M_RNOWAIT|M_WAITOK)) == 0) {
1180 panic("kmem_slab_alloc: bad flags %08x (%p)",
1181 flags, ((int **)&size)[-1]);
1186 * Allocate the pages. Do not mess with the PG_ZERO flag yet.
1188 for (i = 0; i < size; i += PAGE_SIZE) {
1192 * VM_ALLOC_NORMAL can only be set if we are not preempting.
1194 * VM_ALLOC_SYSTEM is automatically set if we are preempting and
1195 * M_WAITOK was specified as an alternative (i.e. M_USE_RESERVE is
1196 * implied in this case), though I'm not sure if we really need to
1199 vmflags = base_vmflags;
1200 if (flags & M_WAITOK) {
1201 if (td->td_preempted)
1202 vmflags |= VM_ALLOC_SYSTEM;
1204 vmflags |= VM_ALLOC_NORMAL;
1207 m = vm_page_alloc(&kernel_object, OFF_TO_IDX(addr + i), vmflags);
1210 * If the allocation failed we either return NULL or we retry.
1212 * If M_WAITOK is specified we wait for more memory and retry.
1213 * If M_WAITOK is specified from a preemption we yield instead of
1214 * wait. Livelock will not occur because the interrupt thread
1215 * will not be preempting anyone the second time around after the
1219 if (flags & M_WAITOK) {
1220 if (td->td_preempted) {
1221 vm_map_unlock(&kernel_map);
1223 vm_map_lock(&kernel_map);
1225 vm_map_unlock(&kernel_map);
1227 vm_map_lock(&kernel_map);
1229 i -= PAGE_SIZE; /* retry */
1234 * We were unable to recover, cleanup and return NULL
1236 * (vm_token already held)
1240 m = vm_page_lookup(&kernel_object, OFF_TO_IDX(addr + i));
1241 /* page should already be busy */
1244 vm_map_delete(&kernel_map, addr, addr + size, &count);
1245 vm_map_unlock(&kernel_map);
1246 vm_map_entry_release(count);
1248 lwkt_reltoken(&vm_token);
1256 * Mark the map entry as non-pageable using a routine that allows us to
1257 * populate the underlying pages.
1259 * The pages were busied by the allocations above.
1261 vm_map_set_wired_quick(&kernel_map, addr, size, &count);
1265 * Enter the pages into the pmap and deal with PG_ZERO and M_ZERO.
1267 lwkt_gettoken(&vm_token);
1268 for (i = 0; i < size; i += PAGE_SIZE) {
1271 m = vm_page_lookup(&kernel_object, OFF_TO_IDX(addr + i));
1272 m->valid = VM_PAGE_BITS_ALL;
1273 /* page should already be busy */
1276 pmap_enter(&kernel_pmap, addr + i, m, VM_PROT_ALL, 1);
1277 if ((m->flags & PG_ZERO) == 0 && (flags & M_ZERO))
1278 bzero((char *)addr + i, PAGE_SIZE);
1279 vm_page_flag_clear(m, PG_ZERO);
1280 KKASSERT(m->flags & (PG_WRITEABLE | PG_MAPPED));
1281 vm_page_flag_set(m, PG_REFERENCED);
1283 lwkt_reltoken(&vm_token);
1284 vm_map_unlock(&kernel_map);
1285 vm_map_entry_release(count);
1286 lwkt_reltoken(&vm_token);
1287 return((void *)addr);
1294 kmem_slab_free(void *ptr, vm_size_t size)
1297 lwkt_gettoken(&vm_token);
1298 vm_map_remove(&kernel_map, (vm_offset_t)ptr, (vm_offset_t)ptr + size);
1299 lwkt_reltoken(&vm_token);