2 * KERN_SLABALLOC.C - Kernel SLAB memory allocator
4 * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * $DragonFly: src/sys/kern/kern_slaballoc.c,v 1.12 2003/10/19 18:18:50 dillon Exp $
30 * This module implements a slab allocator drop-in replacement for the
33 * A slab allocator reserves a ZONE for each chunk size, then lays the
34 * chunks out in an array within the zone. Allocation and deallocation
35 * is nearly instantanious, and fragmentation/overhead losses are limited
36 * to a fixed worst-case amount.
38 * The downside of this slab implementation is in the chunk size
39 * multiplied by the number of zones. ~80 zones * 128K = 10MB of VM per cpu.
40 * In a kernel implementation all this memory will be physical so
41 * the zone size is adjusted downward on machines with less physical
42 * memory. The upside is that overhead is bounded... this is the *worst*
45 * Slab management is done on a per-cpu basis and no locking or mutexes
46 * are required, only a critical section. When one cpu frees memory
47 * belonging to another cpu's slab manager an asynchronous IPI message
48 * will be queued to execute the operation. In addition, both the
49 * high level slab allocator and the low level zone allocator optimize
50 * M_ZERO requests, and the slab allocator does not have to pre initialize
51 * the linked list of chunks.
53 * XXX Balancing is needed between cpus. Balance will be handled through
54 * asynchronous IPIs primarily by reassigning the z_Cpu ownership of chunks.
56 * XXX If we have to allocate a new zone and M_USE_RESERVE is set, use of
57 * the new zone should be restricted to M_USE_RESERVE requests only.
59 * Alloc Size Chunking Number of zones
69 * (if PAGE_SIZE is 4K the maximum zone allocation is 16383)
71 * Allocations >= ZoneLimit go directly to kmem.
73 * API REQUIREMENTS AND SIDE EFFECTS
75 * To operate as a drop-in replacement to the FreeBSD-4.x malloc() we
76 * have remained compatible with the following API requirements:
78 * + small power-of-2 sized allocations are power-of-2 aligned (kern_tty)
79 * + all power-of-2 sized allocations are power-of-2 aligned (twe)
80 * + malloc(0) is allowed and returns non-NULL (ahc driver)
81 * + ability to allocate arbitrarily large chunks of memory
86 #include <sys/param.h>
87 #include <sys/systm.h>
88 #include <sys/kernel.h>
89 #include <sys/slaballoc.h>
91 #include <sys/vmmeter.h>
93 #include <sys/thread.h>
94 #include <sys/globaldata.h>
97 #include <vm/vm_param.h>
98 #include <vm/vm_kern.h>
99 #include <vm/vm_extern.h>
100 #include <vm/vm_object.h>
102 #include <vm/vm_map.h>
103 #include <vm/vm_page.h>
104 #include <vm/vm_pageout.h>
106 #include <machine/cpu.h>
108 #include <sys/thread2.h>
110 #define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
113 * Fixed globals (not per-cpu)
116 static int ZoneLimit;
117 static int ZonePageCount;
118 static int ZonePageLimit;
120 static struct malloc_type *kmemstatistics;
121 static struct kmemusage *kmemusage;
122 static int32_t weirdary[16];
124 static void *kmem_slab_alloc(vm_size_t bytes, vm_offset_t align, int flags);
125 static void kmem_slab_free(void *ptr, vm_size_t bytes);
128 * Misc constants. Note that allocations that are exact multiples of
129 * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
130 * IN_SAME_PAGE_MASK is used to sanity-check the per-page free lists.
132 #define MIN_CHUNK_SIZE 8 /* in bytes */
133 #define MIN_CHUNK_MASK (MIN_CHUNK_SIZE - 1)
134 #define ZONE_RELS_THRESH 2 /* threshold number of zones */
135 #define IN_SAME_PAGE_MASK (~(intptr_t)PAGE_MASK | MIN_CHUNK_MASK)
138 * The WEIRD_ADDR is used as known text to copy into free objects to
139 * try to create deterministic failure cases if the data is accessed after
142 #define WEIRD_ADDR 0xdeadc0de
143 #define MAX_COPY sizeof(weirdary)
144 #define ZERO_LENGTH_PTR ((void *)-8)
147 * Misc global malloc buckets
150 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
151 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
152 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
154 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
155 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
158 * Initialize the slab memory allocator. We have to choose a zone size based
159 * on available physical memory. We choose a zone side which is approximately
160 * 1/1024th of our memory, so if we have 128MB of ram we have a zone size of
161 * 128K. The zone size is limited to the bounds set in slaballoc.h
162 * (typically 32K min, 128K max).
164 static void kmeminit(void *dummy);
166 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
169 kmeminit(void *dummy)
176 limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
177 if (limsize > VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS)
178 limsize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
180 usesize = (int)(limsize / 1024); /* convert to KB */
182 ZoneSize = ZALLOC_MIN_ZONE_SIZE;
183 while (ZoneSize < ZALLOC_MAX_ZONE_SIZE && (ZoneSize << 1) < usesize)
185 ZoneLimit = ZoneSize / 4;
186 if (ZoneLimit > ZALLOC_ZONE_LIMIT)
187 ZoneLimit = ZALLOC_ZONE_LIMIT;
188 ZoneMask = ZoneSize - 1;
189 ZonePageLimit = PAGE_SIZE * 4;
190 ZonePageCount = ZoneSize / PAGE_SIZE;
192 npg = (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) / PAGE_SIZE;
193 kmemusage = kmem_slab_alloc(npg * sizeof(struct kmemusage), PAGE_SIZE, M_ZERO);
195 for (i = 0; i < arysize(weirdary); ++i)
196 weirdary[i] = WEIRD_ADDR;
199 printf("Slab ZoneSize set to %dKB\n", ZoneSize / 1024);
203 * Initialize a malloc type tracking structure.
206 malloc_init(void *data)
208 struct malloc_type *type = data;
211 if (type->ks_magic != M_MAGIC)
212 panic("malloc type lacks magic");
214 if (type->ks_limit != 0)
217 if (vmstats.v_page_count == 0)
218 panic("malloc_init not allowed before vm init");
220 limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
221 if (limsize > VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS)
222 limsize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
223 type->ks_limit = limsize / 10;
225 type->ks_next = kmemstatistics;
226 kmemstatistics = type;
230 malloc_uninit(void *data)
232 struct malloc_type *type = data;
233 struct malloc_type *t;
239 if (type->ks_magic != M_MAGIC)
240 panic("malloc type lacks magic");
242 if (vmstats.v_page_count == 0)
243 panic("malloc_uninit not allowed before vm init");
245 if (type->ks_limit == 0)
246 panic("malloc_uninit on uninitialized type");
250 * memuse is only correct in aggregation. Due to memory being allocated
251 * on one cpu and freed on another individual array entries may be
252 * negative or positive (canceling each other out).
254 for (i = ttl = 0; i < ncpus; ++i)
255 ttl += type->ks_memuse[i];
257 printf("malloc_uninit: %ld bytes of '%s' still allocated on cpu %d\n",
258 ttl, type->ks_shortdesc, i);
261 if (type == kmemstatistics) {
262 kmemstatistics = type->ks_next;
264 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
265 if (t->ks_next == type) {
266 t->ks_next = type->ks_next;
271 type->ks_next = NULL;
276 * Calculate the zone index for the allocation request size and set the
277 * allocation request size to that particular zone's chunk size.
280 zoneindex(unsigned long *bytes)
282 unsigned int n = (unsigned int)*bytes; /* unsigned for shift opt */
284 *bytes = n = (n + 7) & ~7;
285 return(n / 8 - 1); /* 8 byte chunks, 16 zones */
288 *bytes = n = (n + 15) & ~15;
293 *bytes = n = (n + 31) & ~31;
297 *bytes = n = (n + 63) & ~63;
301 *bytes = n = (n + 127) & ~127;
302 return(n / 128 + 31);
305 *bytes = n = (n + 255) & ~255;
306 return(n / 256 + 39);
308 *bytes = n = (n + 511) & ~511;
309 return(n / 512 + 47);
311 #if ZALLOC_ZONE_LIMIT > 8192
313 *bytes = n = (n + 1023) & ~1023;
314 return(n / 1024 + 55);
317 #if ZALLOC_ZONE_LIMIT > 16384
319 *bytes = n = (n + 2047) & ~2047;
320 return(n / 2048 + 63);
323 panic("Unexpected byte count %d", n);
328 * malloc() (SLAB ALLOCATOR)
330 * Allocate memory via the slab allocator. If the request is too large,
331 * or if it page-aligned beyond a certain size, we fall back to the
332 * KMEM subsystem. A SLAB tracking descriptor must be specified, use
333 * &SlabMisc if you don't care.
335 * M_NOWAIT - return NULL instead of blocking.
336 * M_ZERO - zero the returned memory.
337 * M_USE_RESERVE - allocate out of the system reserve if necessary
340 malloc(unsigned long size, struct malloc_type *type, int flags)
345 struct globaldata *gd;
352 * XXX silly to have this in the critical path.
354 if (type->ks_limit == 0) {
356 if (type->ks_limit == 0)
363 * Handle the case where the limit is reached. Panic if can't return
364 * NULL. XXX the original malloc code looped, but this tended to
365 * simply deadlock the computer.
367 while (type->ks_loosememuse >= type->ks_limit) {
371 for (i = ttl = 0; i < ncpus; ++i)
372 ttl += type->ks_memuse[i];
373 type->ks_loosememuse = ttl;
374 if (ttl >= type->ks_limit) {
375 if (flags & (M_NOWAIT|M_NULLOK))
377 panic("%s: malloc limit exceeded", type->ks_shortdesc);
382 * Handle the degenerate size == 0 case. Yes, this does happen.
383 * Return a special pointer. This is to maintain compatibility with
384 * the original malloc implementation. Certain devices, such as the
385 * adaptec driver, not only allocate 0 bytes, they check for NULL and
386 * also realloc() later on. Joy.
389 return(ZERO_LENGTH_PTR);
392 * Handle hysteresis from prior frees here in malloc(). We cannot
393 * safely manipulate the kernel_map in free() due to free() possibly
394 * being called via an IPI message or from sensitive interrupt code.
396 while (slgd->NFreeZones > ZONE_RELS_THRESH && (flags & M_NOWAIT) == 0) {
398 if (slgd->NFreeZones > ZONE_RELS_THRESH) { /* crit sect race */
400 slgd->FreeZones = z->z_Next;
402 kmem_slab_free(z, ZoneSize); /* may block */
407 * XXX handle oversized frees that were queued from free().
409 while (slgd->FreeOvZones && (flags & M_NOWAIT) == 0) {
411 if ((z = slgd->FreeOvZones) != NULL) {
412 KKASSERT(z->z_Magic == ZALLOC_OVSZ_MAGIC);
413 slgd->FreeOvZones = z->z_Next;
414 kmem_slab_free(z, z->z_ChunkSize); /* may block */
420 * Handle large allocations directly. There should not be very many of
421 * these so performance is not a big issue.
423 * Guarentee page alignment for allocations in multiples of PAGE_SIZE
425 if (size >= ZoneLimit || (size & PAGE_MASK) == 0) {
426 struct kmemusage *kup;
428 size = round_page(size);
429 chunk = kmem_slab_alloc(size, PAGE_SIZE, flags);
432 flags &= ~M_ZERO; /* result already zero'd if M_ZERO was set */
434 kup->ku_pagecnt = size / PAGE_SIZE;
435 kup->ku_cpu = gd->gd_cpuid;
441 * Attempt to allocate out of an existing zone. First try the free list,
442 * then allocate out of unallocated space. If we find a good zone move
443 * it to the head of the list so later allocations find it quickly
444 * (we might have thousands of zones in the list).
446 * Note: zoneindex() will panic of size is too large.
448 zi = zoneindex(&size);
449 KKASSERT(zi < NZONES);
451 if ((z = slgd->ZoneAry[zi]) != NULL) {
452 KKASSERT(z->z_NFree > 0);
455 * Remove us from the ZoneAry[] when we become empty
457 if (--z->z_NFree == 0) {
458 slgd->ZoneAry[zi] = z->z_Next;
463 * Locate a chunk in a free page. This attempts to localize
464 * reallocations into earlier pages without us having to sort
465 * the chunk list. A chunk may still overlap a page boundary.
467 while (z->z_FirstFreePg < ZonePageCount) {
468 if ((chunk = z->z_PageAry[z->z_FirstFreePg]) != NULL) {
471 * Diagnostic: c_Next is not total garbage.
473 KKASSERT(chunk->c_Next == NULL ||
474 ((intptr_t)chunk->c_Next & IN_SAME_PAGE_MASK) ==
475 ((intptr_t)chunk & IN_SAME_PAGE_MASK));
478 if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
479 panic("chunk %p FFPG %d/%d", chunk, z->z_FirstFreePg, ZonePageCount);
480 if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
481 panic("chunkNEXT %p %p FFPG %d/%d", chunk, chunk->c_Next, z->z_FirstFreePg, ZonePageCount);
483 z->z_PageAry[z->z_FirstFreePg] = chunk->c_Next;
490 * No chunks are available but NFree said we had some memory, so
491 * it must be available in the never-before-used-memory area
492 * governed by UIndex. The consequences are very serious if our zone
493 * got corrupted so we use an explicit panic rather then a KASSERT.
495 if (z->z_UIndex + 1 != z->z_NMax)
496 z->z_UIndex = z->z_UIndex + 1;
499 if (z->z_UIndex == z->z_UEndIndex)
500 panic("slaballoc: corrupted zone");
501 chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
502 if ((z->z_Flags & SLZF_UNOTZEROD) == 0)
508 * If all zones are exhausted we need to allocate a new zone for this
509 * index. Use M_ZERO to take advantage of pre-zerod pages. Also see
510 * UAlloc use above in regards to M_ZERO. Note that when we are reusing
511 * a zone from the FreeZones list UAlloc'd data will not be zero'd, and
512 * we do not pre-zero it because we do not want to mess up the L1 cache.
514 * At least one subsystem, the tty code (see CROUND) expects power-of-2
515 * allocations to be power-of-2 aligned. We maintain compatibility by
516 * adjusting the base offset below.
521 if ((z = slgd->FreeZones) != NULL) {
522 slgd->FreeZones = z->z_Next;
524 bzero(z, sizeof(SLZone));
525 z->z_Flags |= SLZF_UNOTZEROD;
527 z = kmem_slab_alloc(ZoneSize, ZoneSize, flags|M_ZERO);
533 * Guarentee power-of-2 alignment for power-of-2-sized chunks.
534 * Otherwise just 8-byte align the data.
536 if ((size | (size - 1)) + 1 == (size << 1))
537 off = (sizeof(SLZone) + size - 1) & ~(size - 1);
539 off = (sizeof(SLZone) + MIN_CHUNK_MASK) & ~MIN_CHUNK_MASK;
540 z->z_Magic = ZALLOC_SLAB_MAGIC;
542 z->z_NMax = (ZoneSize - off) / size;
543 z->z_NFree = z->z_NMax - 1;
544 z->z_BasePtr = (char *)z + off;
545 z->z_UIndex = z->z_UEndIndex = slgd->JunkIndex % z->z_NMax;
546 z->z_ChunkSize = size;
547 z->z_FirstFreePg = ZonePageCount;
548 z->z_Cpu = gd->gd_cpuid;
549 chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
550 z->z_Next = slgd->ZoneAry[zi];
551 slgd->ZoneAry[zi] = z;
552 if ((z->z_Flags & SLZF_UNOTZEROD) == 0)
553 flags &= ~M_ZERO; /* already zero'd */
556 * Slide the base index for initial allocations out of the next
557 * zone we create so we do not over-weight the lower part of the
560 slgd->JunkIndex = (slgd->JunkIndex + ZALLOC_SLAB_SLIDE)
561 & (ZALLOC_MAX_ZONE_SIZE - 1);
564 ++type->ks_inuse[gd->gd_cpuid];
565 type->ks_memuse[gd->gd_cpuid] += size;
566 type->ks_loosememuse += size;
572 chunk->c_Next = (void *)-1; /* avoid accidental double-free check */
581 realloc(void *ptr, unsigned long size, struct malloc_type *type, int flags)
587 if (ptr == NULL || ptr == ZERO_LENGTH_PTR)
588 return(malloc(size, type, flags));
595 * Handle oversized allocations. XXX we really should require that a
596 * size be passed to free() instead of this nonsense.
599 struct kmemusage *kup;
602 if (kup->ku_pagecnt) {
603 osize = kup->ku_pagecnt << PAGE_SHIFT;
604 if (osize == round_page(size))
606 if ((nptr = malloc(size, type, flags)) == NULL)
608 bcopy(ptr, nptr, min(size, osize));
615 * Get the original allocation's zone. If the new request winds up
616 * using the same chunk size we do not have to do anything.
618 z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
619 KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
622 if (z->z_ChunkSize == size)
626 * Allocate memory for the new request size. Note that zoneindex has
627 * already adjusted the request size to the appropriate chunk size, which
628 * should optimize our bcopy(). Then copy and return the new pointer.
630 if ((nptr = malloc(size, type, flags)) == NULL)
632 bcopy(ptr, nptr, min(size, z->z_ChunkSize));
639 * free() (SLAB ALLOCATOR)
641 * Free the specified chunk of memory.
645 free_remote(void *ptr)
647 free(ptr, *(struct malloc_type **)ptr);
653 free(void *ptr, struct malloc_type *type)
658 struct globaldata *gd;
665 * Handle special 0-byte allocations
667 if (ptr == ZERO_LENGTH_PTR)
671 * Handle oversized allocations. XXX we really should require that a
672 * size be passed to free() instead of this nonsense.
674 * This code is never called via an ipi.
677 struct kmemusage *kup;
681 if (kup->ku_pagecnt) {
682 size = kup->ku_pagecnt << PAGE_SHIFT;
685 KKASSERT(sizeof(weirdary) <= size);
686 bcopy(weirdary, ptr, sizeof(weirdary));
689 * note: we always adjust our cpu's slot, not the originating
690 * cpu (kup->ku_cpuid). The statistics are in aggregate.
693 --type->ks_inuse[gd->gd_cpuid];
694 type->ks_memuse[gd->gd_cpuid] -= size;
695 if (mycpu->gd_intr_nesting_level) {
697 z->z_Magic = ZALLOC_OVSZ_MAGIC;
698 z->z_Next = slgd->FreeOvZones;
699 z->z_ChunkSize = size;
700 slgd->FreeOvZones = z;
704 kmem_slab_free(ptr, size); /* may block */
711 * Zone case. Figure out the zone based on the fact that it is
714 z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
715 KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
718 * If we do not own the zone then forward the request to the
719 * cpu that does. The freeing code does not need the byte count
720 * unless DIAGNOSTIC is set.
722 if (z->z_Cpu != gd->gd_cpuid) {
723 *(struct malloc_type **)ptr = type;
725 lwkt_send_ipiq(z->z_Cpu, free_remote, ptr);
727 panic("Corrupt SLZone");
732 if (type->ks_magic != M_MAGIC)
733 panic("free: malloc type lacks magic");
736 pgno = ((char *)ptr - (char *)z) >> PAGE_SHIFT;
741 * Attempt to detect a double-free. To reduce overhead we only check
742 * if there appears to be link pointer at the base of the data.
744 if (((intptr_t)chunk->c_Next - (intptr_t)z) >> PAGE_SHIFT == pgno) {
746 for (scan = z->z_PageAry[pgno]; scan; scan = scan->c_Next) {
748 panic("Double free at %p", chunk);
754 * Put weird data into the memory to detect modifications after freeing,
755 * illegal pointer use after freeing (we should fault on the odd address),
756 * and so forth. XXX needs more work, see the old malloc code.
759 if (z->z_ChunkSize < sizeof(weirdary))
760 bcopy(weirdary, chunk, z->z_ChunkSize);
762 bcopy(weirdary, chunk, sizeof(weirdary));
766 * Add this free non-zero'd chunk to a linked list for reuse, adjust
770 if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
771 panic("BADFREE %p\n", chunk);
773 chunk->c_Next = z->z_PageAry[pgno];
774 z->z_PageAry[pgno] = chunk;
776 if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
779 if (z->z_FirstFreePg > pgno)
780 z->z_FirstFreePg = pgno;
783 * Bump the number of free chunks. If it becomes non-zero the zone
784 * must be added back onto the appropriate list.
786 if (z->z_NFree++ == 0) {
787 z->z_Next = slgd->ZoneAry[z->z_ZoneIndex];
788 slgd->ZoneAry[z->z_ZoneIndex] = z;
791 --type->ks_inuse[z->z_Cpu];
792 type->ks_memuse[z->z_Cpu] -= z->z_ChunkSize;
795 * If the zone becomes totally free, and there are other zones we
796 * can allocate from, move this zone to the FreeZones list. Since
797 * this code can be called from an IPI callback, do *NOT* try to mess
798 * with kernel_map here. Hysteresis will be performed at malloc() time.
800 if (z->z_NFree == z->z_NMax &&
801 (z->z_Next || slgd->ZoneAry[z->z_ZoneIndex] != z)
805 for (pz = &slgd->ZoneAry[z->z_ZoneIndex]; z != *pz; pz = &(*pz)->z_Next)
809 z->z_Next = slgd->FreeZones;
819 * Directly allocate and wire kernel memory in PAGE_SIZE chunks with the
820 * specified alignment. M_* flags are expected in the flags field.
822 * Alignment must be a multiple of PAGE_SIZE.
824 * NOTE! XXX For the moment we use vm_map_entry_reserve/release(),
825 * but when we move zalloc() over to use this function as its backend
826 * we will have to switch to kreserve/krelease and call reserve(0)
827 * after the new space is made available.
830 kmem_slab_alloc(vm_size_t size, vm_offset_t align, int flags)
836 vm_map_t map = kernel_map;
838 size = round_page(size);
839 addr = vm_map_min(map);
842 * Reserve properly aligned space from kernel_map
844 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
847 if (vm_map_findspace(map, vm_map_min(map), size, align, &addr)) {
849 if ((flags & (M_NOWAIT|M_NULLOK)) == 0)
850 panic("kmem_slab_alloc(): kernel_map ran out of space!");
852 vm_map_entry_release(count);
855 offset = addr - VM_MIN_KERNEL_ADDRESS;
856 vm_object_reference(kernel_object);
857 vm_map_insert(map, &count,
858 kernel_object, offset, addr, addr + size,
859 VM_PROT_ALL, VM_PROT_ALL, 0);
862 * Allocate the pages. Do not mess with the PG_ZERO flag yet.
864 for (i = 0; i < size; i += PAGE_SIZE) {
866 vm_pindex_t idx = OFF_TO_IDX(offset + i);
867 int zero = (flags & M_ZERO) ? VM_ALLOC_ZERO : 0;
869 if ((flags & (M_NOWAIT|M_USE_RESERVE)) == M_NOWAIT)
870 m = vm_page_alloc(kernel_object, idx, VM_ALLOC_INTERRUPT|zero);
872 m = vm_page_alloc(kernel_object, idx, VM_ALLOC_SYSTEM|zero);
874 if ((flags & M_NOWAIT) == 0) {
878 i -= PAGE_SIZE; /* retry */
883 m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
886 vm_map_delete(map, addr, addr + size, &count);
889 vm_map_entry_release(count);
895 * Mark the map entry as non-pageable using a routine that allows us to
896 * populate the underlying pages.
898 vm_map_set_wired_quick(map, addr, size, &count);
902 * Enter the pages into the pmap and deal with PG_ZERO and M_ZERO.
904 for (i = 0; i < size; i += PAGE_SIZE) {
907 m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
908 m->valid = VM_PAGE_BITS_ALL;
911 pmap_enter(kernel_pmap, addr + i, m, VM_PROT_ALL, 1);
912 if ((m->flags & PG_ZERO) == 0 && (flags & M_ZERO))
913 bzero((char *)addr + i, PAGE_SIZE);
914 vm_page_flag_clear(m, PG_ZERO);
915 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE | PG_REFERENCED);
918 vm_map_entry_release(count);
919 return((void *)addr);
923 kmem_slab_free(void *ptr, vm_size_t size)
926 vm_map_remove(kernel_map, (vm_offset_t)ptr, (vm_offset_t)ptr + size);