2 * KERN_SLABALLOC.C - Kernel SLAB memory allocator (MP SAFE)
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.33 2005/06/20 20:49:14 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>
106 #include <vm/vm_param.h>
107 #include <vm/vm_kern.h>
108 #include <vm/vm_extern.h>
109 #include <vm/vm_object.h>
111 #include <vm/vm_map.h>
112 #include <vm/vm_page.h>
113 #include <vm/vm_pageout.h>
115 #include <machine/cpu.h>
117 #include <sys/thread2.h>
119 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
122 * Fixed globals (not per-cpu)
125 static int ZoneLimit;
126 static int ZonePageCount;
128 static struct malloc_type *kmemstatistics;
129 static struct kmemusage *kmemusage;
130 static int32_t weirdary[16];
132 static void *kmem_slab_alloc(vm_size_t bytes, vm_offset_t align, int flags);
133 static void kmem_slab_free(void *ptr, vm_size_t bytes);
134 #if defined(INVARIANTS)
135 static void chunk_mark_allocated(SLZone *z, void *chunk);
136 static void chunk_mark_free(SLZone *z, void *chunk);
140 * Misc constants. Note that allocations that are exact multiples of
141 * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
142 * IN_SAME_PAGE_MASK is used to sanity-check the per-page free lists.
144 #define MIN_CHUNK_SIZE 8 /* in bytes */
145 #define MIN_CHUNK_MASK (MIN_CHUNK_SIZE - 1)
146 #define ZONE_RELS_THRESH 2 /* threshold number of zones */
147 #define IN_SAME_PAGE_MASK (~(intptr_t)PAGE_MASK | MIN_CHUNK_MASK)
150 * The WEIRD_ADDR is used as known text to copy into free objects to
151 * try to create deterministic failure cases if the data is accessed after
154 #define WEIRD_ADDR 0xdeadc0de
155 #define MAX_COPY sizeof(weirdary)
156 #define ZERO_LENGTH_PTR ((void *)-8)
159 * Misc global malloc buckets
162 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
163 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
164 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
166 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
167 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
170 * Initialize the slab memory allocator. We have to choose a zone size based
171 * on available physical memory. We choose a zone side which is approximately
172 * 1/1024th of our memory, so if we have 128MB of ram we have a zone size of
173 * 128K. The zone size is limited to the bounds set in slaballoc.h
174 * (typically 32K min, 128K max).
176 static void kmeminit(void *dummy);
178 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
182 * If enabled any memory allocated without M_ZERO is initialized to -1.
184 static int use_malloc_pattern;
185 SYSCTL_INT(_debug, OID_AUTO, use_malloc_pattern, CTLFLAG_RW,
186 &use_malloc_pattern, 0, "");
190 kmeminit(void *dummy)
197 limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
198 if (limsize > VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS)
199 limsize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
201 usesize = (int)(limsize / 1024); /* convert to KB */
203 ZoneSize = ZALLOC_MIN_ZONE_SIZE;
204 while (ZoneSize < ZALLOC_MAX_ZONE_SIZE && (ZoneSize << 1) < usesize)
206 ZoneLimit = ZoneSize / 4;
207 if (ZoneLimit > ZALLOC_ZONE_LIMIT)
208 ZoneLimit = ZALLOC_ZONE_LIMIT;
209 ZoneMask = ZoneSize - 1;
210 ZonePageCount = ZoneSize / PAGE_SIZE;
212 npg = (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) / PAGE_SIZE;
213 kmemusage = kmem_slab_alloc(npg * sizeof(struct kmemusage), PAGE_SIZE, M_WAITOK|M_ZERO);
215 for (i = 0; i < arysize(weirdary); ++i)
216 weirdary[i] = WEIRD_ADDR;
219 printf("Slab ZoneSize set to %dKB\n", ZoneSize / 1024);
223 * Initialize a malloc type tracking structure.
226 malloc_init(void *data)
228 struct malloc_type *type = data;
231 if (type->ks_magic != M_MAGIC)
232 panic("malloc type lacks magic");
234 if (type->ks_limit != 0)
237 if (vmstats.v_page_count == 0)
238 panic("malloc_init not allowed before vm init");
240 limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
241 if (limsize > VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS)
242 limsize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
243 type->ks_limit = limsize / 10;
245 type->ks_next = kmemstatistics;
246 kmemstatistics = type;
250 malloc_uninit(void *data)
252 struct malloc_type *type = data;
253 struct malloc_type *t;
259 if (type->ks_magic != M_MAGIC)
260 panic("malloc type lacks magic");
262 if (vmstats.v_page_count == 0)
263 panic("malloc_uninit not allowed before vm init");
265 if (type->ks_limit == 0)
266 panic("malloc_uninit on uninitialized type");
270 * memuse is only correct in aggregation. Due to memory being allocated
271 * on one cpu and freed on another individual array entries may be
272 * negative or positive (canceling each other out).
274 for (i = ttl = 0; i < ncpus; ++i)
275 ttl += type->ks_memuse[i];
277 printf("malloc_uninit: %ld bytes of '%s' still allocated on cpu %d\n",
278 ttl, type->ks_shortdesc, i);
281 if (type == kmemstatistics) {
282 kmemstatistics = type->ks_next;
284 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
285 if (t->ks_next == type) {
286 t->ks_next = type->ks_next;
291 type->ks_next = NULL;
296 * Calculate the zone index for the allocation request size and set the
297 * allocation request size to that particular zone's chunk size.
300 zoneindex(unsigned long *bytes)
302 unsigned int n = (unsigned int)*bytes; /* unsigned for shift opt */
304 *bytes = n = (n + 7) & ~7;
305 return(n / 8 - 1); /* 8 byte chunks, 16 zones */
308 *bytes = n = (n + 15) & ~15;
313 *bytes = n = (n + 31) & ~31;
317 *bytes = n = (n + 63) & ~63;
321 *bytes = n = (n + 127) & ~127;
322 return(n / 128 + 31);
325 *bytes = n = (n + 255) & ~255;
326 return(n / 256 + 39);
328 *bytes = n = (n + 511) & ~511;
329 return(n / 512 + 47);
331 #if ZALLOC_ZONE_LIMIT > 8192
333 *bytes = n = (n + 1023) & ~1023;
334 return(n / 1024 + 55);
337 #if ZALLOC_ZONE_LIMIT > 16384
339 *bytes = n = (n + 2047) & ~2047;
340 return(n / 2048 + 63);
343 panic("Unexpected byte count %d", n);
348 * malloc() (SLAB ALLOCATOR) (MP SAFE)
350 * Allocate memory via the slab allocator. If the request is too large,
351 * or if it page-aligned beyond a certain size, we fall back to the
352 * KMEM subsystem. A SLAB tracking descriptor must be specified, use
353 * &SlabMisc if you don't care.
355 * M_RNOWAIT - don't block.
356 * M_NULLOK - return NULL instead of blocking.
357 * M_ZERO - zero the returned memory.
358 * M_USE_RESERVE - allow greater drawdown of the free list
359 * M_USE_INTERRUPT_RESERVE - allow the freelist to be exhausted
362 malloc(unsigned long size, struct malloc_type *type, int flags)
367 struct globaldata *gd;
377 * XXX silly to have this in the critical path.
379 if (type->ks_limit == 0) {
381 if (type->ks_limit == 0)
388 * Handle the case where the limit is reached. Panic if we can't return
389 * NULL. The original malloc code looped, but this tended to
390 * simply deadlock the computer.
392 * ks_loosememuse is an up-only limit that is NOT MP-synchronized, used
393 * to determine if a more complete limit check should be done. The
394 * actual memory use is tracked via ks_memuse[cpu].
396 while (type->ks_loosememuse >= type->ks_limit) {
400 for (i = ttl = 0; i < ncpus; ++i)
401 ttl += type->ks_memuse[i];
402 type->ks_loosememuse = ttl; /* not MP synchronized */
403 if (ttl >= type->ks_limit) {
404 if (flags & M_NULLOK)
406 panic("%s: malloc limit exceeded", type->ks_shortdesc);
411 * Handle the degenerate size == 0 case. Yes, this does happen.
412 * Return a special pointer. This is to maintain compatibility with
413 * the original malloc implementation. Certain devices, such as the
414 * adaptec driver, not only allocate 0 bytes, they check for NULL and
415 * also realloc() later on. Joy.
418 return(ZERO_LENGTH_PTR);
421 * Handle hysteresis from prior frees here in malloc(). We cannot
422 * safely manipulate the kernel_map in free() due to free() possibly
423 * being called via an IPI message or from sensitive interrupt code.
425 while (slgd->NFreeZones > ZONE_RELS_THRESH && (flags & M_RNOWAIT) == 0) {
427 if (slgd->NFreeZones > ZONE_RELS_THRESH) { /* crit sect race */
429 slgd->FreeZones = z->z_Next;
431 kmem_slab_free(z, ZoneSize); /* may block */
436 * XXX handle oversized frees that were queued from free().
438 while (slgd->FreeOvZones && (flags & M_RNOWAIT) == 0) {
440 if ((z = slgd->FreeOvZones) != NULL) {
441 KKASSERT(z->z_Magic == ZALLOC_OVSZ_MAGIC);
442 slgd->FreeOvZones = z->z_Next;
443 kmem_slab_free(z, z->z_ChunkSize); /* may block */
449 * Handle large allocations directly. There should not be very many of
450 * these so performance is not a big issue.
452 * Guarentee page alignment for allocations in multiples of PAGE_SIZE
454 if (size >= ZoneLimit || (size & PAGE_MASK) == 0) {
455 struct kmemusage *kup;
457 size = round_page(size);
458 chunk = kmem_slab_alloc(size, PAGE_SIZE, flags);
461 flags &= ~M_ZERO; /* result already zero'd if M_ZERO was set */
462 flags |= M_PASSIVE_ZERO;
464 kup->ku_pagecnt = size / PAGE_SIZE;
465 kup->ku_cpu = gd->gd_cpuid;
471 * Attempt to allocate out of an existing zone. First try the free list,
472 * then allocate out of unallocated space. If we find a good zone move
473 * it to the head of the list so later allocations find it quickly
474 * (we might have thousands of zones in the list).
476 * Note: zoneindex() will panic of size is too large.
478 zi = zoneindex(&size);
479 KKASSERT(zi < NZONES);
481 if ((z = slgd->ZoneAry[zi]) != NULL) {
482 KKASSERT(z->z_NFree > 0);
485 * Remove us from the ZoneAry[] when we become empty
487 if (--z->z_NFree == 0) {
488 slgd->ZoneAry[zi] = z->z_Next;
493 * Locate a chunk in a free page. This attempts to localize
494 * reallocations into earlier pages without us having to sort
495 * the chunk list. A chunk may still overlap a page boundary.
497 while (z->z_FirstFreePg < ZonePageCount) {
498 if ((chunk = z->z_PageAry[z->z_FirstFreePg]) != NULL) {
501 * Diagnostic: c_Next is not total garbage.
503 KKASSERT(chunk->c_Next == NULL ||
504 ((intptr_t)chunk->c_Next & IN_SAME_PAGE_MASK) ==
505 ((intptr_t)chunk & IN_SAME_PAGE_MASK));
508 if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
509 panic("chunk %p FFPG %d/%d", chunk, z->z_FirstFreePg, ZonePageCount);
510 if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
511 panic("chunkNEXT %p %p FFPG %d/%d", chunk, chunk->c_Next, z->z_FirstFreePg, ZonePageCount);
512 chunk_mark_allocated(z, chunk);
514 z->z_PageAry[z->z_FirstFreePg] = chunk->c_Next;
521 * No chunks are available but NFree said we had some memory, so
522 * it must be available in the never-before-used-memory area
523 * governed by UIndex. The consequences are very serious if our zone
524 * got corrupted so we use an explicit panic rather then a KASSERT.
526 if (z->z_UIndex + 1 != z->z_NMax)
527 z->z_UIndex = z->z_UIndex + 1;
530 if (z->z_UIndex == z->z_UEndIndex)
531 panic("slaballoc: corrupted zone");
532 chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
533 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
535 flags |= M_PASSIVE_ZERO;
537 #if defined(INVARIANTS)
538 chunk_mark_allocated(z, chunk);
544 * If all zones are exhausted we need to allocate a new zone for this
545 * index. Use M_ZERO to take advantage of pre-zerod pages. Also see
546 * UAlloc use above in regards to M_ZERO. Note that when we are reusing
547 * a zone from the FreeZones list UAlloc'd data will not be zero'd, and
548 * we do not pre-zero it because we do not want to mess up the L1 cache.
550 * At least one subsystem, the tty code (see CROUND) expects power-of-2
551 * allocations to be power-of-2 aligned. We maintain compatibility by
552 * adjusting the base offset below.
557 if ((z = slgd->FreeZones) != NULL) {
558 slgd->FreeZones = z->z_Next;
560 bzero(z, sizeof(SLZone));
561 z->z_Flags |= SLZF_UNOTZEROD;
563 z = kmem_slab_alloc(ZoneSize, ZoneSize, flags|M_ZERO);
569 * How big is the base structure?
571 #if defined(INVARIANTS)
573 * Make room for z_Bitmap. An exact calculation is somewhat more
574 * complicated so don't make an exact calculation.
576 off = offsetof(SLZone, z_Bitmap[(ZoneSize / size + 31) / 32]);
577 bzero(z->z_Bitmap, (ZoneSize / size + 31) / 8);
579 off = sizeof(SLZone);
583 * Guarentee power-of-2 alignment for power-of-2-sized chunks.
584 * Otherwise just 8-byte align the data.
586 if ((size | (size - 1)) + 1 == (size << 1))
587 off = (off + size - 1) & ~(size - 1);
589 off = (off + MIN_CHUNK_MASK) & ~MIN_CHUNK_MASK;
590 z->z_Magic = ZALLOC_SLAB_MAGIC;
592 z->z_NMax = (ZoneSize - off) / size;
593 z->z_NFree = z->z_NMax - 1;
594 z->z_BasePtr = (char *)z + off;
595 z->z_UIndex = z->z_UEndIndex = slgd->JunkIndex % z->z_NMax;
596 z->z_ChunkSize = size;
597 z->z_FirstFreePg = ZonePageCount;
599 z->z_Cpu = gd->gd_cpuid;
600 chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
601 z->z_Next = slgd->ZoneAry[zi];
602 slgd->ZoneAry[zi] = z;
603 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
604 flags &= ~M_ZERO; /* already zero'd */
605 flags |= M_PASSIVE_ZERO;
607 #if defined(INVARIANTS)
608 chunk_mark_allocated(z, chunk);
612 * Slide the base index for initial allocations out of the next
613 * zone we create so we do not over-weight the lower part of the
616 slgd->JunkIndex = (slgd->JunkIndex + ZALLOC_SLAB_SLIDE)
617 & (ZALLOC_MAX_ZONE_SIZE - 1);
620 ++type->ks_inuse[gd->gd_cpuid];
621 type->ks_memuse[gd->gd_cpuid] += size;
622 type->ks_loosememuse += size; /* not MP synchronized */
627 else if ((flags & (M_ZERO|M_PASSIVE_ZERO)) == 0) {
628 if (use_malloc_pattern) {
629 for (i = 0; i < size; i += sizeof(int)) {
630 *(int *)((char *)chunk + i) = -1;
633 chunk->c_Next = (void *)-1; /* avoid accidental double-free check */
643 * kernel realloc. (SLAB ALLOCATOR) (MP SAFE)
645 * Generally speaking this routine is not called very often and we do
646 * not attempt to optimize it beyond reusing the same pointer if the
647 * new size fits within the chunking of the old pointer's zone.
650 realloc(void *ptr, unsigned long size, struct malloc_type *type, int flags)
656 KKASSERT((flags & M_ZERO) == 0); /* not supported */
658 if (ptr == NULL || ptr == ZERO_LENGTH_PTR)
659 return(malloc(size, type, flags));
666 * Handle oversized allocations. XXX we really should require that a
667 * size be passed to free() instead of this nonsense.
670 struct kmemusage *kup;
673 if (kup->ku_pagecnt) {
674 osize = kup->ku_pagecnt << PAGE_SHIFT;
675 if (osize == round_page(size))
677 if ((nptr = malloc(size, type, flags)) == NULL)
679 bcopy(ptr, nptr, min(size, osize));
686 * Get the original allocation's zone. If the new request winds up
687 * using the same chunk size we do not have to do anything.
689 z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
690 KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
693 if (z->z_ChunkSize == size)
697 * Allocate memory for the new request size. Note that zoneindex has
698 * already adjusted the request size to the appropriate chunk size, which
699 * should optimize our bcopy(). Then copy and return the new pointer.
701 if ((nptr = malloc(size, type, flags)) == NULL)
703 bcopy(ptr, nptr, min(size, z->z_ChunkSize));
709 * Allocate a copy of the specified string.
711 * (MP SAFE) (MAY BLOCK)
714 strdup(const char *str, struct malloc_type *type)
716 int zlen; /* length inclusive of terminating NUL */
721 zlen = strlen(str) + 1;
722 nstr = malloc(zlen, type, M_WAITOK);
723 bcopy(str, nstr, zlen);
729 * free() (SLAB ALLOCATOR)
731 * Free the specified chunk of memory.
735 free_remote(void *ptr)
737 free(ptr, *(struct malloc_type **)ptr);
743 * free (SLAB ALLOCATOR) (MP SAFE)
745 * Free a memory block previously allocated by malloc. Note that we do not
746 * attempt to uplodate ks_loosememuse as MP races could prevent us from
747 * checking memory limits in malloc.
750 free(void *ptr, struct malloc_type *type)
755 struct globaldata *gd;
762 panic("trying to free NULL pointer");
765 * Handle special 0-byte allocations
767 if (ptr == ZERO_LENGTH_PTR)
771 * Handle oversized allocations. XXX we really should require that a
772 * size be passed to free() instead of this nonsense.
774 * This code is never called via an ipi.
777 struct kmemusage *kup;
781 if (kup->ku_pagecnt) {
782 size = kup->ku_pagecnt << PAGE_SHIFT;
785 KKASSERT(sizeof(weirdary) <= size);
786 bcopy(weirdary, ptr, sizeof(weirdary));
789 * note: we always adjust our cpu's slot, not the originating
790 * cpu (kup->ku_cpuid). The statistics are in aggregate.
792 * note: XXX we have still inherited the interrupts-can't-block
793 * assumption. An interrupt thread does not bump
794 * gd_intr_nesting_level so check TDF_INTTHREAD. This is
795 * primarily until we can fix softupdate's assumptions about free().
798 --type->ks_inuse[gd->gd_cpuid];
799 type->ks_memuse[gd->gd_cpuid] -= size;
800 if (mycpu->gd_intr_nesting_level || (gd->gd_curthread->td_flags & TDF_INTTHREAD)) {
802 z->z_Magic = ZALLOC_OVSZ_MAGIC;
803 z->z_Next = slgd->FreeOvZones;
804 z->z_ChunkSize = size;
805 slgd->FreeOvZones = z;
809 kmem_slab_free(ptr, size); /* may block */
816 * Zone case. Figure out the zone based on the fact that it is
819 z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
820 KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
823 * If we do not own the zone then forward the request to the
824 * cpu that does. Since the timing is non-critical, a passive
827 if (z->z_CpuGd != gd) {
828 *(struct malloc_type **)ptr = type;
830 lwkt_send_ipiq_passive(z->z_CpuGd, free_remote, ptr);
832 panic("Corrupt SLZone");
837 if (type->ks_magic != M_MAGIC)
838 panic("free: malloc type lacks magic");
841 pgno = ((char *)ptr - (char *)z) >> PAGE_SHIFT;
846 * Attempt to detect a double-free. To reduce overhead we only check
847 * if there appears to be link pointer at the base of the data.
849 if (((intptr_t)chunk->c_Next - (intptr_t)z) >> PAGE_SHIFT == pgno) {
851 for (scan = z->z_PageAry[pgno]; scan; scan = scan->c_Next) {
853 panic("Double free at %p", chunk);
856 chunk_mark_free(z, chunk);
860 * Put weird data into the memory to detect modifications after freeing,
861 * illegal pointer use after freeing (we should fault on the odd address),
862 * and so forth. XXX needs more work, see the old malloc code.
865 if (z->z_ChunkSize < sizeof(weirdary))
866 bcopy(weirdary, chunk, z->z_ChunkSize);
868 bcopy(weirdary, chunk, sizeof(weirdary));
872 * Add this free non-zero'd chunk to a linked list for reuse, adjust
876 if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
877 panic("BADFREE %p", chunk);
879 chunk->c_Next = z->z_PageAry[pgno];
880 z->z_PageAry[pgno] = chunk;
882 if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
885 if (z->z_FirstFreePg > pgno)
886 z->z_FirstFreePg = pgno;
889 * Bump the number of free chunks. If it becomes non-zero the zone
890 * must be added back onto the appropriate list.
892 if (z->z_NFree++ == 0) {
893 z->z_Next = slgd->ZoneAry[z->z_ZoneIndex];
894 slgd->ZoneAry[z->z_ZoneIndex] = z;
897 --type->ks_inuse[z->z_Cpu];
898 type->ks_memuse[z->z_Cpu] -= z->z_ChunkSize;
901 * If the zone becomes totally free, and there are other zones we
902 * can allocate from, move this zone to the FreeZones list. Since
903 * this code can be called from an IPI callback, do *NOT* try to mess
904 * with kernel_map here. Hysteresis will be performed at malloc() time.
906 if (z->z_NFree == z->z_NMax &&
907 (z->z_Next || slgd->ZoneAry[z->z_ZoneIndex] != z)
911 for (pz = &slgd->ZoneAry[z->z_ZoneIndex]; z != *pz; pz = &(*pz)->z_Next)
915 z->z_Next = slgd->FreeZones;
922 #if defined(INVARIANTS)
924 * Helper routines for sanity checks
928 chunk_mark_allocated(SLZone *z, void *chunk)
930 int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
933 KASSERT(bitdex >= 0 && bitdex < z->z_NMax, ("memory chunk %p bit index %d is illegal", chunk, bitdex));
934 bitptr = &z->z_Bitmap[bitdex >> 5];
936 KASSERT((*bitptr & (1 << bitdex)) == 0, ("memory chunk %p is already allocated!", chunk));
937 *bitptr |= 1 << bitdex;
942 chunk_mark_free(SLZone *z, void *chunk)
944 int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
947 KASSERT(bitdex >= 0 && bitdex < z->z_NMax, ("memory chunk %p bit index %d is illegal!", chunk, bitdex));
948 bitptr = &z->z_Bitmap[bitdex >> 5];
950 KASSERT((*bitptr & (1 << bitdex)) != 0, ("memory chunk %p is already free!", chunk));
951 *bitptr &= ~(1 << bitdex);
957 * kmem_slab_alloc() (MP SAFE) (GETS BGL)
959 * Directly allocate and wire kernel memory in PAGE_SIZE chunks with the
960 * specified alignment. M_* flags are expected in the flags field.
962 * Alignment must be a multiple of PAGE_SIZE.
964 * NOTE! XXX For the moment we use vm_map_entry_reserve/release(),
965 * but when we move zalloc() over to use this function as its backend
966 * we will have to switch to kreserve/krelease and call reserve(0)
967 * after the new space is made available.
969 * Interrupt code which has preempted other code is not allowed to
970 * use PQ_CACHE pages. However, if an interrupt thread is run
971 * non-preemptively or blocks and then runs non-preemptively, then
972 * it is free to use PQ_CACHE pages.
974 * This routine will currently obtain the BGL.
977 kmem_slab_alloc(vm_size_t size, vm_offset_t align, int flags)
982 int count, vmflags, base_vmflags;
984 vm_map_t map = kernel_map;
986 size = round_page(size);
987 addr = vm_map_min(map);
990 * Reserve properly aligned space from kernel_map. RNOWAIT allocations
993 if (flags & M_RNOWAIT) {
994 if (try_mplock() == 0)
999 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1002 if (vm_map_findspace(map, vm_map_min(map), size, align, &addr)) {
1004 if ((flags & M_NULLOK) == 0)
1005 panic("kmem_slab_alloc(): kernel_map ran out of space!");
1007 vm_map_entry_release(count);
1011 offset = addr - VM_MIN_KERNEL_ADDRESS;
1012 vm_object_reference(kernel_object);
1013 vm_map_insert(map, &count,
1014 kernel_object, offset, addr, addr + size,
1015 VM_PROT_ALL, VM_PROT_ALL, 0);
1021 base_vmflags |= VM_ALLOC_ZERO;
1022 if (flags & M_USE_RESERVE)
1023 base_vmflags |= VM_ALLOC_SYSTEM;
1024 if (flags & M_USE_INTERRUPT_RESERVE)
1025 base_vmflags |= VM_ALLOC_INTERRUPT;
1026 if ((flags & (M_RNOWAIT|M_WAITOK)) == 0)
1027 panic("kmem_slab_alloc: bad flags %08x (%p)", flags, ((int **)&size)[-1]);
1031 * Allocate the pages. Do not mess with the PG_ZERO flag yet.
1033 for (i = 0; i < size; i += PAGE_SIZE) {
1035 vm_pindex_t idx = OFF_TO_IDX(offset + i);
1038 * VM_ALLOC_NORMAL can only be set if we are not preempting.
1040 * VM_ALLOC_SYSTEM is automatically set if we are preempting and
1041 * M_WAITOK was specified as an alternative (i.e. M_USE_RESERVE is
1042 * implied in this case), though I'm sure if we really need to do
1045 vmflags = base_vmflags;
1046 if (flags & M_WAITOK) {
1047 if (td->td_preempted)
1048 vmflags |= VM_ALLOC_SYSTEM;
1050 vmflags |= VM_ALLOC_NORMAL;
1053 m = vm_page_alloc(kernel_object, idx, vmflags);
1056 * If the allocation failed we either return NULL or we retry.
1058 * If M_WAITOK is specified we wait for more memory and retry.
1059 * If M_WAITOK is specified from a preemption we yield instead of
1060 * wait. Livelock will not occur because the interrupt thread
1061 * will not be preempting anyone the second time around after the
1065 if (flags & M_WAITOK) {
1066 if (td->td_preempted) {
1075 i -= PAGE_SIZE; /* retry */
1080 * We were unable to recover, cleanup and return NULL
1084 m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
1087 vm_map_delete(map, addr, addr + size, &count);
1090 vm_map_entry_release(count);
1099 * Mark the map entry as non-pageable using a routine that allows us to
1100 * populate the underlying pages.
1102 vm_map_set_wired_quick(map, addr, size, &count);
1106 * Enter the pages into the pmap and deal with PG_ZERO and M_ZERO.
1108 for (i = 0; i < size; i += PAGE_SIZE) {
1111 m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
1112 m->valid = VM_PAGE_BITS_ALL;
1115 pmap_enter(kernel_pmap, addr + i, m, VM_PROT_ALL, 1);
1116 if ((m->flags & PG_ZERO) == 0 && (flags & M_ZERO))
1117 bzero((char *)addr + i, PAGE_SIZE);
1118 vm_page_flag_clear(m, PG_ZERO);
1119 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE | PG_REFERENCED);
1122 vm_map_entry_release(count);
1124 return((void *)addr);
1128 * kmem_slab_free() (MP SAFE) (GETS BGL)
1131 kmem_slab_free(void *ptr, vm_size_t size)
1135 vm_map_remove(kernel_map, (vm_offset_t)ptr, (vm_offset_t)ptr + size);