Entirely remove the old kernel malloc and kmem_map code. The slab allocator
[dragonfly.git] / sys / kern / kern_slaballoc.c
1 /*
2  * KERN_SLABALLOC.C     - Kernel SLAB memory allocator
3  *
4  * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
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
26  * SUCH DAMAGE.
27  *
28  * $DragonFly: src/sys/kern/kern_slaballoc.c,v 1.11 2003/10/19 00:23:24 dillon Exp $
29  *
30  * This module implements a slab allocator drop-in replacement for the
31  * kernel malloc().
32  *
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.
37  *
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*
43  * case overhead.
44  *
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.
52  *
53  * XXX Balancing is needed between cpus.  Balance will be handled through
54  * asynchronous IPIs primarily by reassigning the z_Cpu ownership of chunks.
55  *
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.
58  *
59  *      Alloc Size      Chunking        Number of zones
60  *      0-127           8               16
61  *      128-255         16              8
62  *      256-511         32              8
63  *      512-1023        64              8
64  *      1024-2047       128             8
65  *      2048-4095       256             8
66  *      4096-8191       512             8
67  *      8192-16383      1024            8
68  *      16384-32767     2048            8
69  *      (if PAGE_SIZE is 4K the maximum zone allocation is 16383)
70  *
71  *      Allocations >= ZoneLimit go directly to kmem.
72  *
73  *                      API REQUIREMENTS AND SIDE EFFECTS
74  *
75  *    To operate as a drop-in replacement to the FreeBSD-4.x malloc() we
76  *    have remained compatible with the following API requirements:
77  *
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
82  */
83
84 #include "opt_vm.h"
85
86 #include <sys/param.h>
87 #include <sys/systm.h>
88 #include <sys/kernel.h>
89 #include <sys/slaballoc.h>
90 #include <sys/mbuf.h>
91 #include <sys/vmmeter.h>
92 #include <sys/lock.h>
93 #include <sys/thread.h>
94 #include <sys/globaldata.h>
95
96 #include <vm/vm.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>
101 #include <vm/pmap.h>
102 #include <vm/vm_map.h>
103 #include <vm/vm_page.h>
104 #include <vm/vm_pageout.h>
105
106 #include <machine/cpu.h>
107
108 #include <sys/thread2.h>
109
110 #define arysize(ary)    (sizeof(ary)/sizeof((ary)[0]))
111
112 /*
113  * Fixed globals (not per-cpu)
114  */
115 static int ZoneSize;
116 static int ZoneLimit;
117 static int ZonePageCount;
118 static int ZonePageLimit;
119 static int ZoneMask;
120 static struct malloc_type *kmemstatistics;
121 static struct kmemusage *kmemusage;
122 static int32_t weirdary[16];
123
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);
126
127 /*
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.
131  */
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)
136
137 /*
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
140  * free.
141  */    
142 #define WEIRD_ADDR      0xdeadc0de
143 #define MAX_COPY        sizeof(weirdary)
144 #define ZERO_LENGTH_PTR ((void *)-8)
145
146 /*
147  * Misc global malloc buckets
148  */
149
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");
153  
154 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
155 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
156
157 /*
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). 
163  */
164 static void kmeminit(void *dummy);
165
166 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
167
168 static void
169 kmeminit(void *dummy)
170 {
171     vm_poff_t limsize;
172     int usesize;
173     int i;
174     vm_pindex_t npg;
175
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;
179
180     usesize = (int)(limsize / 1024);    /* convert to KB */
181
182     ZoneSize = ZALLOC_MIN_ZONE_SIZE;
183     while (ZoneSize < ZALLOC_MAX_ZONE_SIZE && (ZoneSize << 1) < usesize)
184         ZoneSize <<= 1;
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;
191
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);
194
195     for (i = 0; i < arysize(weirdary); ++i)
196         weirdary[i] = WEIRD_ADDR;
197
198     if (bootverbose)
199         printf("Slab ZoneSize set to %dKB\n", ZoneSize / 1024);
200 }
201
202 /*
203  * Initialize a malloc type tracking structure.
204  */
205 void
206 malloc_init(void *data)
207 {
208     struct malloc_type *type = data;
209     vm_poff_t limsize;
210
211     if (type->ks_magic != M_MAGIC)
212         panic("malloc type lacks magic");
213                                            
214     if (type->ks_limit != 0)
215         return;
216
217     if (vmstats.v_page_count == 0)
218         panic("malloc_init not allowed before vm init");
219
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;
224
225     type->ks_next = kmemstatistics;
226     kmemstatistics = type;
227 }
228
229 void
230 malloc_uninit(void *data)
231 {
232     struct malloc_type *type = data;
233     struct malloc_type *t;
234 #ifdef INVARIANTS
235     int i;
236 #endif
237
238     if (type->ks_magic != M_MAGIC)
239         panic("malloc type lacks magic");
240
241     if (vmstats.v_page_count == 0)
242         panic("malloc_uninit not allowed before vm init");
243
244     if (type->ks_limit == 0)
245         panic("malloc_uninit on uninitialized type");
246
247 #ifdef INVARIANTS
248     for (i = 0; i < ncpus; ++i) {
249         if (type->ks_memuse[i] != 0) {
250             printf(
251                 "malloc_uninit: %ld bytes of '%s' still allocated on cpu %d\n",
252                 type->ks_memuse[i], type->ks_shortdesc, i);
253         }
254     }
255 #endif
256     if (type == kmemstatistics) {
257         kmemstatistics = type->ks_next;
258     } else {
259         for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
260             if (t->ks_next == type) {
261                 t->ks_next = type->ks_next;
262                 break;
263             }
264         }
265     }
266     type->ks_next = NULL;
267     type->ks_limit = 0;
268 }
269
270 /*
271  * Calculate the zone index for the allocation request size and set the
272  * allocation request size to that particular zone's chunk size.
273  */
274 static __inline int
275 zoneindex(unsigned long *bytes)
276 {
277     unsigned int n = (unsigned int)*bytes;      /* unsigned for shift opt */
278     if (n < 128) {
279         *bytes = n = (n + 7) & ~7;
280         return(n / 8 - 1);              /* 8 byte chunks, 16 zones */
281     }
282     if (n < 256) {
283         *bytes = n = (n + 15) & ~15;
284         return(n / 16 + 7);
285     }
286     if (n < 8192) {
287         if (n < 512) {
288             *bytes = n = (n + 31) & ~31;
289             return(n / 32 + 15);
290         }
291         if (n < 1024) {
292             *bytes = n = (n + 63) & ~63;
293             return(n / 64 + 23);
294         } 
295         if (n < 2048) {
296             *bytes = n = (n + 127) & ~127;
297             return(n / 128 + 31);
298         }
299         if (n < 4096) {
300             *bytes = n = (n + 255) & ~255;
301             return(n / 256 + 39);
302         }
303         *bytes = n = (n + 511) & ~511;
304         return(n / 512 + 47);
305     }
306 #if ZALLOC_ZONE_LIMIT > 8192
307     if (n < 16384) {
308         *bytes = n = (n + 1023) & ~1023;
309         return(n / 1024 + 55);
310     }
311 #endif
312 #if ZALLOC_ZONE_LIMIT > 16384
313     if (n < 32768) {
314         *bytes = n = (n + 2047) & ~2047;
315         return(n / 2048 + 63);
316     }
317 #endif
318     panic("Unexpected byte count %d", n);
319     return(0);
320 }
321
322 /*
323  * malloc()     (SLAB ALLOCATOR)
324  *
325  *      Allocate memory via the slab allocator.  If the request is too large,
326  *      or if it page-aligned beyond a certain size, we fall back to the
327  *      KMEM subsystem.  A SLAB tracking descriptor must be specified, use
328  *      &SlabMisc if you don't care.
329  *
330  *      M_NOWAIT        - return NULL instead of blocking.
331  *      M_ZERO          - zero the returned memory.
332  *      M_USE_RESERVE   - allocate out of the system reserve if necessary
333  */
334 void *
335 malloc(unsigned long size, struct malloc_type *type, int flags)
336 {
337     SLZone *z;
338     SLChunk *chunk;
339     SLGlobalData *slgd;
340     struct globaldata *gd;
341     int zi;
342
343     gd = mycpu;
344     slgd = &gd->gd_slab;
345
346     /*
347      * XXX silly to have this in the critical path.
348      */
349     if (type->ks_limit == 0) {
350         crit_enter();
351         if (type->ks_limit == 0)
352             malloc_init(type);
353         crit_exit();
354     }
355     ++type->ks_calls;
356
357     /*
358      * Handle the case where the limit is reached.  Panic if can't return
359      * NULL.  XXX the original malloc code looped, but this tended to
360      * simply deadlock the computer.
361      */
362     while (type->ks_loosememuse >= type->ks_limit) {
363         int i;
364         long ttl;
365
366         for (i = ttl = 0; i < ncpus; ++i)
367             ttl += type->ks_memuse[i];
368         type->ks_loosememuse = ttl;
369         if (ttl >= type->ks_limit) {
370             if (flags & (M_NOWAIT|M_NULLOK))
371                 return(NULL);
372             panic("%s: malloc limit exceeded", type->ks_shortdesc);
373         }
374     }
375
376     /*
377      * Handle the degenerate size == 0 case.  Yes, this does happen.
378      * Return a special pointer.  This is to maintain compatibility with
379      * the original malloc implementation.  Certain devices, such as the
380      * adaptec driver, not only allocate 0 bytes, they check for NULL and
381      * also realloc() later on.  Joy.
382      */
383     if (size == 0)
384         return(ZERO_LENGTH_PTR);
385
386     /*
387      * Handle hysteresis from prior frees here in malloc().  We cannot
388      * safely manipulate the kernel_map in free() due to free() possibly
389      * being called via an IPI message or from sensitive interrupt code.
390      */
391     while (slgd->NFreeZones > ZONE_RELS_THRESH && (flags & M_NOWAIT) == 0) {
392         crit_enter();
393         if (slgd->NFreeZones > ZONE_RELS_THRESH) {      /* crit sect race */
394             z = slgd->FreeZones;
395             slgd->FreeZones = z->z_Next;
396             --slgd->NFreeZones;
397             kmem_slab_free(z, ZoneSize);        /* may block */
398         }
399         crit_exit();
400     }
401     /*
402      * XXX handle oversized frees that were queued from free().
403      */
404     while (slgd->FreeOvZones && (flags & M_NOWAIT) == 0) {
405         crit_enter();
406         if ((z = slgd->FreeOvZones) != NULL) {
407             KKASSERT(z->z_Magic == ZALLOC_OVSZ_MAGIC);
408             slgd->FreeOvZones = z->z_Next;
409             kmem_slab_free(z, z->z_ChunkSize);  /* may block */
410         }
411         crit_exit();
412     }
413
414     /*
415      * Handle large allocations directly.  There should not be very many of
416      * these so performance is not a big issue.
417      *
418      * Guarentee page alignment for allocations in multiples of PAGE_SIZE
419      */
420     if (size >= ZoneLimit || (size & PAGE_MASK) == 0) {
421         struct kmemusage *kup;
422
423         size = round_page(size);
424         chunk = kmem_slab_alloc(size, PAGE_SIZE, flags);
425         if (chunk == NULL)
426             return(NULL);
427         flags &= ~M_ZERO;       /* result already zero'd if M_ZERO was set */
428         kup = btokup(chunk);
429         kup->ku_pagecnt = size / PAGE_SIZE;
430         kup->ku_cpu = gd->gd_cpuid;
431         crit_enter();
432         goto done;
433     }
434
435     /*
436      * Attempt to allocate out of an existing zone.  First try the free list,
437      * then allocate out of unallocated space.  If we find a good zone move
438      * it to the head of the list so later allocations find it quickly
439      * (we might have thousands of zones in the list).
440      *
441      * Note: zoneindex() will panic of size is too large.
442      */
443     zi = zoneindex(&size);
444     KKASSERT(zi < NZONES);
445     crit_enter();
446     if ((z = slgd->ZoneAry[zi]) != NULL) {
447         KKASSERT(z->z_NFree > 0);
448
449         /*
450          * Remove us from the ZoneAry[] when we become empty
451          */
452         if (--z->z_NFree == 0) {
453             slgd->ZoneAry[zi] = z->z_Next;
454             z->z_Next = NULL;
455         }
456
457         /*
458          * Locate a chunk in a free page.  This attempts to localize
459          * reallocations into earlier pages without us having to sort
460          * the chunk list.  A chunk may still overlap a page boundary.
461          */
462         while (z->z_FirstFreePg < ZonePageCount) {
463             if ((chunk = z->z_PageAry[z->z_FirstFreePg]) != NULL) {
464 #ifdef DIAGNOSTIC
465                 /*
466                  * Diagnostic: c_Next is not total garbage.
467                  */
468                 KKASSERT(chunk->c_Next == NULL ||
469                         ((intptr_t)chunk->c_Next & IN_SAME_PAGE_MASK) ==
470                         ((intptr_t)chunk & IN_SAME_PAGE_MASK));
471 #endif
472 #ifdef INVARIANTS
473                 if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
474                         panic("chunk %p FFPG %d/%d", chunk, z->z_FirstFreePg, ZonePageCount);
475                 if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
476                         panic("chunkNEXT %p %p FFPG %d/%d", chunk, chunk->c_Next, z->z_FirstFreePg, ZonePageCount);
477 #endif
478                 z->z_PageAry[z->z_FirstFreePg] = chunk->c_Next;
479                 goto done;
480             }
481             ++z->z_FirstFreePg;
482         }
483
484         /*
485          * No chunks are available but NFree said we had some memory, so
486          * it must be available in the never-before-used-memory area
487          * governed by UIndex.  The consequences are very serious if our zone
488          * got corrupted so we use an explicit panic rather then a KASSERT.
489          */
490         if (z->z_UIndex + 1 != z->z_NMax)
491             z->z_UIndex = z->z_UIndex + 1;
492         else
493             z->z_UIndex = 0;
494         if (z->z_UIndex == z->z_UEndIndex)
495             panic("slaballoc: corrupted zone");
496         chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
497         if ((z->z_Flags & SLZF_UNOTZEROD) == 0)
498             flags &= ~M_ZERO;
499         goto done;
500     }
501
502     /*
503      * If all zones are exhausted we need to allocate a new zone for this
504      * index.  Use M_ZERO to take advantage of pre-zerod pages.  Also see
505      * UAlloc use above in regards to M_ZERO.  Note that when we are reusing
506      * a zone from the FreeZones list UAlloc'd data will not be zero'd, and
507      * we do not pre-zero it because we do not want to mess up the L1 cache.
508      *
509      * At least one subsystem, the tty code (see CROUND) expects power-of-2
510      * allocations to be power-of-2 aligned.  We maintain compatibility by
511      * adjusting the base offset below.
512      */
513     {
514         int off;
515
516         if ((z = slgd->FreeZones) != NULL) {
517             slgd->FreeZones = z->z_Next;
518             --slgd->NFreeZones;
519             bzero(z, sizeof(SLZone));
520             z->z_Flags |= SLZF_UNOTZEROD;
521         } else {
522             z = kmem_slab_alloc(ZoneSize, ZoneSize, flags|M_ZERO);
523             if (z == NULL)
524                 goto fail;
525         }
526
527         /*
528          * Guarentee power-of-2 alignment for power-of-2-sized chunks.
529          * Otherwise just 8-byte align the data.
530          */
531         if ((size | (size - 1)) + 1 == (size << 1))
532             off = (sizeof(SLZone) + size - 1) & ~(size - 1);
533         else
534             off = (sizeof(SLZone) + MIN_CHUNK_MASK) & ~MIN_CHUNK_MASK;
535         z->z_Magic = ZALLOC_SLAB_MAGIC;
536         z->z_ZoneIndex = zi;
537         z->z_NMax = (ZoneSize - off) / size;
538         z->z_NFree = z->z_NMax - 1;
539         z->z_BasePtr = (char *)z + off;
540         z->z_UIndex = z->z_UEndIndex = slgd->JunkIndex % z->z_NMax;
541         z->z_ChunkSize = size;
542         z->z_FirstFreePg = ZonePageCount;
543         z->z_Cpu = gd->gd_cpuid;
544         chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
545         z->z_Next = slgd->ZoneAry[zi];
546         slgd->ZoneAry[zi] = z;
547         if ((z->z_Flags & SLZF_UNOTZEROD) == 0)
548             flags &= ~M_ZERO;   /* already zero'd */
549
550         /*
551          * Slide the base index for initial allocations out of the next
552          * zone we create so we do not over-weight the lower part of the
553          * cpu memory caches.
554          */
555         slgd->JunkIndex = (slgd->JunkIndex + ZALLOC_SLAB_SLIDE)
556                                 & (ZALLOC_MAX_ZONE_SIZE - 1);
557     }
558 done:
559     ++type->ks_inuse[gd->gd_cpuid];
560     type->ks_memuse[gd->gd_cpuid] += size;
561     type->ks_loosememuse += size;
562     crit_exit();
563     if (flags & M_ZERO)
564         bzero(chunk, size);
565 #ifdef INVARIANTS
566     else
567         chunk->c_Next = (void *)-1; /* avoid accidental double-free check */
568 #endif
569     return(chunk);
570 fail:
571     crit_exit();
572     return(NULL);
573 }
574
575 void *
576 realloc(void *ptr, unsigned long size, struct malloc_type *type, int flags)
577 {
578     SLZone *z;
579     void *nptr;
580     unsigned long osize;
581
582     if (ptr == NULL || ptr == ZERO_LENGTH_PTR)
583         return(malloc(size, type, flags));
584     if (size == 0) {
585         free(ptr, type);
586         return(NULL);
587     }
588
589     /*
590      * Handle oversized allocations.  XXX we really should require that a
591      * size be passed to free() instead of this nonsense.
592      */
593     {
594         struct kmemusage *kup;
595
596         kup = btokup(ptr);
597         if (kup->ku_pagecnt) {
598             osize = kup->ku_pagecnt << PAGE_SHIFT;
599             if (osize == round_page(size))
600                 return(ptr);
601             if ((nptr = malloc(size, type, flags)) == NULL)
602                 return(NULL);
603             bcopy(ptr, nptr, min(size, osize));
604             free(ptr, type);
605             return(nptr);
606         }
607     }
608
609     /*
610      * Get the original allocation's zone.  If the new request winds up
611      * using the same chunk size we do not have to do anything.
612      */
613     z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
614     KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
615
616     zoneindex(&size);
617     if (z->z_ChunkSize == size)
618         return(ptr);
619
620     /*
621      * Allocate memory for the new request size.  Note that zoneindex has
622      * already adjusted the request size to the appropriate chunk size, which
623      * should optimize our bcopy().  Then copy and return the new pointer.
624      */
625     if ((nptr = malloc(size, type, flags)) == NULL)
626         return(NULL);
627     bcopy(ptr, nptr, min(size, z->z_ChunkSize));
628     free(ptr, type);
629     return(nptr);
630 }
631
632 /*
633  * free()       (SLAB ALLOCATOR)
634  *
635  *      Free the specified chunk of memory.
636  */
637 static
638 void
639 free_remote(void *ptr)
640 {
641     free(ptr, *(struct malloc_type **)ptr);
642 }
643
644 void
645 free(void *ptr, struct malloc_type *type)
646 {
647     SLZone *z;
648     SLChunk *chunk;
649     SLGlobalData *slgd;
650     struct globaldata *gd;
651     int pgno;
652
653     gd = mycpu;
654     slgd = &gd->gd_slab;
655
656     /*
657      * Handle special 0-byte allocations
658      */
659     if (ptr == ZERO_LENGTH_PTR)
660         return;
661
662     /*
663      * Handle oversized allocations.  XXX we really should require that a
664      * size be passed to free() instead of this nonsense.
665      *
666      * This code is never called via an ipi.
667      */
668     {
669         struct kmemusage *kup;
670         unsigned long size;
671
672         kup = btokup(ptr);
673         if (kup->ku_pagecnt) {
674             size = kup->ku_pagecnt << PAGE_SHIFT;
675             kup->ku_pagecnt = 0;
676 #ifdef INVARIANTS
677             KKASSERT(sizeof(weirdary) <= size);
678             bcopy(weirdary, ptr, sizeof(weirdary));
679 #endif
680             /*
681              * note: we always adjust our cpu's slot, not the originating
682              * cpu (kup->ku_cpuid).  The statistics are in aggregate.
683              */
684             crit_enter();
685             --type->ks_inuse[gd->gd_cpuid];
686             type->ks_memuse[gd->gd_cpuid] -= size;
687             if (mycpu->gd_intr_nesting_level) {
688                 z = (SLZone *)ptr;
689                 z->z_Magic = ZALLOC_OVSZ_MAGIC;
690                 z->z_Next = slgd->FreeOvZones;
691                 z->z_ChunkSize = size;
692                 slgd->FreeOvZones = z;
693                 crit_exit();
694             } else {
695                 crit_exit();
696                 kmem_slab_free(ptr, size);      /* may block */
697             }
698             return;
699         }
700     }
701
702     /*
703      * Zone case.  Figure out the zone based on the fact that it is
704      * ZoneSize aligned. 
705      */
706     z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
707     KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
708
709     /*
710      * If we do not own the zone then forward the request to the
711      * cpu that does.  The freeing code does not need the byte count
712      * unless DIAGNOSTIC is set.
713      */
714     if (z->z_Cpu != gd->gd_cpuid) {
715         *(struct malloc_type **)ptr = type;
716 #ifdef SMP
717         lwkt_send_ipiq(z->z_Cpu, free_remote, ptr);
718 #else
719         panic("Corrupt SLZone");
720 #endif
721         return;
722     }
723
724     if (type->ks_magic != M_MAGIC)
725         panic("free: malloc type lacks magic");
726
727     crit_enter();
728     pgno = ((char *)ptr - (char *)z) >> PAGE_SHIFT;
729     chunk = ptr;
730
731 #ifdef INVARIANTS
732     /*
733      * Attempt to detect a double-free.  To reduce overhead we only check
734      * if there appears to be link pointer at the base of the data.
735      */
736     if (((intptr_t)chunk->c_Next - (intptr_t)z) >> PAGE_SHIFT == pgno) {
737         SLChunk *scan;
738         for (scan = z->z_PageAry[pgno]; scan; scan = scan->c_Next) {
739             if (scan == chunk)
740                 panic("Double free at %p", chunk);
741         }
742     }
743 #endif
744
745     /*
746      * Put weird data into the memory to detect modifications after freeing,
747      * illegal pointer use after freeing (we should fault on the odd address),
748      * and so forth.  XXX needs more work, see the old malloc code.
749      */
750 #ifdef INVARIANTS
751     if (z->z_ChunkSize < sizeof(weirdary))
752         bcopy(weirdary, chunk, z->z_ChunkSize);
753     else
754         bcopy(weirdary, chunk, sizeof(weirdary));
755 #endif
756
757     /*
758      * Add this free non-zero'd chunk to a linked list for reuse, adjust
759      * z_FirstFreePg.
760      */
761 #ifdef INVARIANTS
762     if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
763         panic("BADFREE %p\n", chunk);
764 #endif
765     chunk->c_Next = z->z_PageAry[pgno];
766     z->z_PageAry[pgno] = chunk;
767 #ifdef INVARIANTS
768     if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
769         panic("BADFREE2");
770 #endif
771     if (z->z_FirstFreePg > pgno)
772         z->z_FirstFreePg = pgno;
773
774     /*
775      * Bump the number of free chunks.  If it becomes non-zero the zone
776      * must be added back onto the appropriate list.
777      */
778     if (z->z_NFree++ == 0) {
779         z->z_Next = slgd->ZoneAry[z->z_ZoneIndex];
780         slgd->ZoneAry[z->z_ZoneIndex] = z;
781     }
782
783     --type->ks_inuse[z->z_Cpu];
784     type->ks_memuse[z->z_Cpu] -= z->z_ChunkSize;
785
786     /*
787      * If the zone becomes totally free, and there are other zones we
788      * can allocate from, move this zone to the FreeZones list.  Since
789      * this code can be called from an IPI callback, do *NOT* try to mess
790      * with kernel_map here.  Hysteresis will be performed at malloc() time.
791      */
792     if (z->z_NFree == z->z_NMax && 
793         (z->z_Next || slgd->ZoneAry[z->z_ZoneIndex] != z)
794     ) {
795         SLZone **pz;
796
797         for (pz = &slgd->ZoneAry[z->z_ZoneIndex]; z != *pz; pz = &(*pz)->z_Next)
798             ;
799         *pz = z->z_Next;
800         z->z_Magic = -1;
801         z->z_Next = slgd->FreeZones;
802         slgd->FreeZones = z;
803         ++slgd->NFreeZones;
804     }
805     crit_exit();
806 }
807
808 /*
809  * kmem_slab_alloc()
810  *
811  *      Directly allocate and wire kernel memory in PAGE_SIZE chunks with the
812  *      specified alignment.  M_* flags are expected in the flags field.
813  *
814  *      Alignment must be a multiple of PAGE_SIZE.
815  *
816  *      NOTE! XXX For the moment we use vm_map_entry_reserve/release(),
817  *      but when we move zalloc() over to use this function as its backend
818  *      we will have to switch to kreserve/krelease and call reserve(0)
819  *      after the new space is made available.
820  */
821 static void *
822 kmem_slab_alloc(vm_size_t size, vm_offset_t align, int flags)
823 {
824     vm_size_t i;
825     vm_offset_t addr;
826     vm_offset_t offset;
827     int count;
828     vm_map_t map = kernel_map;
829
830     size = round_page(size);
831     addr = vm_map_min(map);
832
833     /*
834      * Reserve properly aligned space from kernel_map
835      */
836     count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
837     crit_enter();
838     vm_map_lock(map);
839     if (vm_map_findspace(map, vm_map_min(map), size, align, &addr)) {
840         vm_map_unlock(map);
841         if ((flags & (M_NOWAIT|M_NULLOK)) == 0)
842             panic("kmem_slab_alloc(): kernel_map ran out of space!");
843         crit_exit();
844         vm_map_entry_release(count);
845         return(NULL);
846     }
847     offset = addr - VM_MIN_KERNEL_ADDRESS;
848     vm_object_reference(kernel_object);
849     vm_map_insert(map, &count, 
850                     kernel_object, offset, addr, addr + size,
851                     VM_PROT_ALL, VM_PROT_ALL, 0);
852
853     /*
854      * Allocate the pages.  Do not mess with the PG_ZERO flag yet.
855      */
856     for (i = 0; i < size; i += PAGE_SIZE) {
857         vm_page_t m;
858         vm_pindex_t idx = OFF_TO_IDX(offset + i);
859         int zero = (flags & M_ZERO) ? VM_ALLOC_ZERO : 0;
860
861         if ((flags & (M_NOWAIT|M_USE_RESERVE)) == M_NOWAIT)
862             m = vm_page_alloc(kernel_object, idx, VM_ALLOC_INTERRUPT|zero);
863         else
864             m = vm_page_alloc(kernel_object, idx, VM_ALLOC_SYSTEM|zero);
865         if (m == NULL) {
866             if ((flags & M_NOWAIT) == 0) {
867                 vm_map_unlock(map);
868                 vm_wait();
869                 vm_map_lock(map);
870                 i -= PAGE_SIZE; /* retry */
871                 continue;
872             }
873             while (i != 0) {
874                 i -= PAGE_SIZE;
875                 m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
876                 vm_page_free(m);
877             }
878             vm_map_delete(map, addr, addr + size, &count);
879             vm_map_unlock(map);
880             crit_exit();
881             vm_map_entry_release(count);
882             return(NULL);
883         }
884     }
885
886     /*
887      * Mark the map entry as non-pageable using a routine that allows us to
888      * populate the underlying pages.
889      */
890     vm_map_set_wired_quick(map, addr, size, &count);
891     crit_exit();
892
893     /*
894      * Enter the pages into the pmap and deal with PG_ZERO and M_ZERO.
895      */
896     for (i = 0; i < size; i += PAGE_SIZE) {
897         vm_page_t m;
898
899         m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
900         m->valid = VM_PAGE_BITS_ALL;
901         vm_page_wire(m);
902         vm_page_wakeup(m);
903         pmap_enter(kernel_pmap, addr + i, m, VM_PROT_ALL, 1);
904         if ((m->flags & PG_ZERO) == 0 && (flags & M_ZERO))
905             bzero((char *)addr + i, PAGE_SIZE);
906         vm_page_flag_clear(m, PG_ZERO);
907         vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE | PG_REFERENCED);
908     }
909     vm_map_unlock(map);
910     vm_map_entry_release(count);
911     return((void *)addr);
912 }
913
914 static void
915 kmem_slab_free(void *ptr, vm_size_t size)
916 {
917     crit_enter();
918     vm_map_remove(kernel_map, (vm_offset_t)ptr, (vm_offset_t)ptr + size);
919     crit_exit();
920 }
921