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