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