Include a bitmap of allocated entries when built with INVARIANTS. I
[dragonfly.git] / sys / kern / kern_slaballoc.c
1 /*
2  * KERN_SLABALLOC.C     - Kernel SLAB memory allocator (MP SAFE)
3  * 
4  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
5  * 
6  * This code is derived from software contributed to The DragonFly Project
7  * by Matthew Dillon <dillon@backplane.com>
8  * 
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  * 3. Neither the name of The DragonFly Project nor the names of its
20  *    contributors may be used to endorse or promote products derived
21  *    from this software without specific, prior written permission.
22  * 
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
27  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
31  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  * 
36  * $DragonFly: src/sys/kern/kern_slaballoc.c,v 1.33 2005/06/20 20:49:14 dillon Exp $
37  *
38  * This module implements a slab allocator drop-in replacement for the
39  * kernel malloc().
40  *
41  * A slab allocator reserves a ZONE for each chunk size, then lays the
42  * chunks out in an array within the zone.  Allocation and deallocation
43  * is nearly instantanious, and fragmentation/overhead losses are limited
44  * to a fixed worst-case amount.
45  *
46  * The downside of this slab implementation is in the chunk size
47  * multiplied by the number of zones.  ~80 zones * 128K = 10MB of VM per cpu.
48  * In a kernel implementation all this memory will be physical so
49  * the zone size is adjusted downward on machines with less physical
50  * memory.  The upside is that overhead is bounded... this is the *worst*
51  * case overhead.
52  *
53  * Slab management is done on a per-cpu basis and no locking or mutexes
54  * are required, only a critical section.  When one cpu frees memory
55  * belonging to another cpu's slab manager an asynchronous IPI message
56  * will be queued to execute the operation.   In addition, both the
57  * high level slab allocator and the low level zone allocator optimize
58  * M_ZERO requests, and the slab allocator does not have to pre initialize
59  * the linked list of chunks.
60  *
61  * XXX Balancing is needed between cpus.  Balance will be handled through
62  * asynchronous IPIs primarily by reassigning the z_Cpu ownership of chunks.
63  *
64  * XXX If we have to allocate a new zone and M_USE_RESERVE is set, use of
65  * the new zone should be restricted to M_USE_RESERVE requests only.
66  *
67  *      Alloc Size      Chunking        Number of zones
68  *      0-127           8               16
69  *      128-255         16              8
70  *      256-511         32              8
71  *      512-1023        64              8
72  *      1024-2047       128             8
73  *      2048-4095       256             8
74  *      4096-8191       512             8
75  *      8192-16383      1024            8
76  *      16384-32767     2048            8
77  *      (if PAGE_SIZE is 4K the maximum zone allocation is 16383)
78  *
79  *      Allocations >= ZoneLimit go directly to kmem.
80  *
81  *                      API REQUIREMENTS AND SIDE EFFECTS
82  *
83  *    To operate as a drop-in replacement to the FreeBSD-4.x malloc() we
84  *    have remained compatible with the following API requirements:
85  *
86  *    + small power-of-2 sized allocations are power-of-2 aligned (kern_tty)
87  *    + all power-of-2 sized allocations are power-of-2 aligned (twe)
88  *    + malloc(0) is allowed and returns non-NULL (ahc driver)
89  *    + ability to allocate arbitrarily large chunks of memory
90  */
91
92 #include "opt_vm.h"
93
94 #include <sys/param.h>
95 #include <sys/systm.h>
96 #include <sys/kernel.h>
97 #include <sys/slaballoc.h>
98 #include <sys/mbuf.h>
99 #include <sys/vmmeter.h>
100 #include <sys/lock.h>
101 #include <sys/thread.h>
102 #include <sys/globaldata.h>
103 #include <sys/sysctl.h>
104
105 #include <vm/vm.h>
106 #include <vm/vm_param.h>
107 #include <vm/vm_kern.h>
108 #include <vm/vm_extern.h>
109 #include <vm/vm_object.h>
110 #include <vm/pmap.h>
111 #include <vm/vm_map.h>
112 #include <vm/vm_page.h>
113 #include <vm/vm_pageout.h>
114
115 #include <machine/cpu.h>
116
117 #include <sys/thread2.h>
118
119 #define arysize(ary)    (sizeof(ary)/sizeof((ary)[0]))
120
121 /*
122  * Fixed globals (not per-cpu)
123  */
124 static int ZoneSize;
125 static int ZoneLimit;
126 static int ZonePageCount;
127 static int ZoneMask;
128 static struct malloc_type *kmemstatistics;
129 static struct kmemusage *kmemusage;
130 static int32_t weirdary[16];
131
132 static void *kmem_slab_alloc(vm_size_t bytes, vm_offset_t align, int flags);
133 static void kmem_slab_free(void *ptr, vm_size_t bytes);
134 #if defined(INVARIANTS)
135 static void chunk_mark_allocated(SLZone *z, void *chunk);
136 static void chunk_mark_free(SLZone *z, void *chunk);
137 #endif
138
139 /*
140  * Misc constants.  Note that allocations that are exact multiples of 
141  * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
142  * IN_SAME_PAGE_MASK is used to sanity-check the per-page free lists.
143  */
144 #define MIN_CHUNK_SIZE          8               /* in bytes */
145 #define MIN_CHUNK_MASK          (MIN_CHUNK_SIZE - 1)
146 #define ZONE_RELS_THRESH        2               /* threshold number of zones */
147 #define IN_SAME_PAGE_MASK       (~(intptr_t)PAGE_MASK | MIN_CHUNK_MASK)
148
149 /*
150  * The WEIRD_ADDR is used as known text to copy into free objects to
151  * try to create deterministic failure cases if the data is accessed after
152  * free.
153  */    
154 #define WEIRD_ADDR      0xdeadc0de
155 #define MAX_COPY        sizeof(weirdary)
156 #define ZERO_LENGTH_PTR ((void *)-8)
157
158 /*
159  * Misc global malloc buckets
160  */
161
162 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
163 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
164 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
165  
166 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
167 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
168
169 /*
170  * Initialize the slab memory allocator.  We have to choose a zone size based
171  * on available physical memory.  We choose a zone side which is approximately
172  * 1/1024th of our memory, so if we have 128MB of ram we have a zone size of
173  * 128K.  The zone size is limited to the bounds set in slaballoc.h
174  * (typically 32K min, 128K max). 
175  */
176 static void kmeminit(void *dummy);
177
178 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
179
180 #ifdef INVARIANTS
181 /*
182  * If enabled any memory allocated without M_ZERO is initialized to -1.
183  */
184 static int  use_malloc_pattern;
185 SYSCTL_INT(_debug, OID_AUTO, use_malloc_pattern, CTLFLAG_RW,
186                 &use_malloc_pattern, 0, "");
187 #endif
188
189 static void
190 kmeminit(void *dummy)
191 {
192     vm_poff_t limsize;
193     int usesize;
194     int i;
195     vm_pindex_t npg;
196
197     limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
198     if (limsize > VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS)
199         limsize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
200
201     usesize = (int)(limsize / 1024);    /* convert to KB */
202
203     ZoneSize = ZALLOC_MIN_ZONE_SIZE;
204     while (ZoneSize < ZALLOC_MAX_ZONE_SIZE && (ZoneSize << 1) < usesize)
205         ZoneSize <<= 1;
206     ZoneLimit = ZoneSize / 4;
207     if (ZoneLimit > ZALLOC_ZONE_LIMIT)
208         ZoneLimit = ZALLOC_ZONE_LIMIT;
209     ZoneMask = ZoneSize - 1;
210     ZonePageCount = ZoneSize / PAGE_SIZE;
211
212     npg = (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) / PAGE_SIZE;
213     kmemusage = kmem_slab_alloc(npg * sizeof(struct kmemusage), PAGE_SIZE, M_WAITOK|M_ZERO);
214
215     for (i = 0; i < arysize(weirdary); ++i)
216         weirdary[i] = WEIRD_ADDR;
217
218     if (bootverbose)
219         printf("Slab ZoneSize set to %dKB\n", ZoneSize / 1024);
220 }
221
222 /*
223  * Initialize a malloc type tracking structure.
224  */
225 void
226 malloc_init(void *data)
227 {
228     struct malloc_type *type = data;
229     vm_poff_t limsize;
230
231     if (type->ks_magic != M_MAGIC)
232         panic("malloc type lacks magic");
233                                            
234     if (type->ks_limit != 0)
235         return;
236
237     if (vmstats.v_page_count == 0)
238         panic("malloc_init not allowed before vm init");
239
240     limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
241     if (limsize > VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS)
242         limsize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
243     type->ks_limit = limsize / 10;
244
245     type->ks_next = kmemstatistics;
246     kmemstatistics = type;
247 }
248
249 void
250 malloc_uninit(void *data)
251 {
252     struct malloc_type *type = data;
253     struct malloc_type *t;
254 #ifdef INVARIANTS
255     int i;
256     long ttl;
257 #endif
258
259     if (type->ks_magic != M_MAGIC)
260         panic("malloc type lacks magic");
261
262     if (vmstats.v_page_count == 0)
263         panic("malloc_uninit not allowed before vm init");
264
265     if (type->ks_limit == 0)
266         panic("malloc_uninit on uninitialized type");
267
268 #ifdef INVARIANTS
269     /*
270      * memuse is only correct in aggregation.  Due to memory being allocated
271      * on one cpu and freed on another individual array entries may be 
272      * negative or positive (canceling each other out).
273      */
274     for (i = ttl = 0; i < ncpus; ++i)
275         ttl += type->ks_memuse[i];
276     if (ttl) {
277         printf("malloc_uninit: %ld bytes of '%s' still allocated on cpu %d\n",
278             ttl, type->ks_shortdesc, i);
279     }
280 #endif
281     if (type == kmemstatistics) {
282         kmemstatistics = type->ks_next;
283     } else {
284         for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
285             if (t->ks_next == type) {
286                 t->ks_next = type->ks_next;
287                 break;
288             }
289         }
290     }
291     type->ks_next = NULL;
292     type->ks_limit = 0;
293 }
294
295 /*
296  * Calculate the zone index for the allocation request size and set the
297  * allocation request size to that particular zone's chunk size.
298  */
299 static __inline int
300 zoneindex(unsigned long *bytes)
301 {
302     unsigned int n = (unsigned int)*bytes;      /* unsigned for shift opt */
303     if (n < 128) {
304         *bytes = n = (n + 7) & ~7;
305         return(n / 8 - 1);              /* 8 byte chunks, 16 zones */
306     }
307     if (n < 256) {
308         *bytes = n = (n + 15) & ~15;
309         return(n / 16 + 7);
310     }
311     if (n < 8192) {
312         if (n < 512) {
313             *bytes = n = (n + 31) & ~31;
314             return(n / 32 + 15);
315         }
316         if (n < 1024) {
317             *bytes = n = (n + 63) & ~63;
318             return(n / 64 + 23);
319         } 
320         if (n < 2048) {
321             *bytes = n = (n + 127) & ~127;
322             return(n / 128 + 31);
323         }
324         if (n < 4096) {
325             *bytes = n = (n + 255) & ~255;
326             return(n / 256 + 39);
327         }
328         *bytes = n = (n + 511) & ~511;
329         return(n / 512 + 47);
330     }
331 #if ZALLOC_ZONE_LIMIT > 8192
332     if (n < 16384) {
333         *bytes = n = (n + 1023) & ~1023;
334         return(n / 1024 + 55);
335     }
336 #endif
337 #if ZALLOC_ZONE_LIMIT > 16384
338     if (n < 32768) {
339         *bytes = n = (n + 2047) & ~2047;
340         return(n / 2048 + 63);
341     }
342 #endif
343     panic("Unexpected byte count %d", n);
344     return(0);
345 }
346
347 /*
348  * malloc()     (SLAB ALLOCATOR) (MP SAFE)
349  *
350  *      Allocate memory via the slab allocator.  If the request is too large,
351  *      or if it page-aligned beyond a certain size, we fall back to the
352  *      KMEM subsystem.  A SLAB tracking descriptor must be specified, use
353  *      &SlabMisc if you don't care.
354  *
355  *      M_RNOWAIT       - don't block.
356  *      M_NULLOK        - return NULL instead of blocking.
357  *      M_ZERO          - zero the returned memory.
358  *      M_USE_RESERVE   - allow greater drawdown of the free list
359  *      M_USE_INTERRUPT_RESERVE - allow the freelist to be exhausted
360  */
361 void *
362 malloc(unsigned long size, struct malloc_type *type, int flags)
363 {
364     SLZone *z;
365     SLChunk *chunk;
366     SLGlobalData *slgd;
367     struct globaldata *gd;
368     int zi;
369 #ifdef INVARIANTS
370     int i;
371 #endif
372
373     gd = mycpu;
374     slgd = &gd->gd_slab;
375
376     /*
377      * XXX silly to have this in the critical path.
378      */
379     if (type->ks_limit == 0) {
380         crit_enter();
381         if (type->ks_limit == 0)
382             malloc_init(type);
383         crit_exit();
384     }
385     ++type->ks_calls;
386
387     /*
388      * Handle the case where the limit is reached.  Panic if we can't return
389      * NULL.  The original malloc code looped, but this tended to
390      * simply deadlock the computer.
391      *
392      * ks_loosememuse is an up-only limit that is NOT MP-synchronized, used
393      * to determine if a more complete limit check should be done.  The
394      * actual memory use is tracked via ks_memuse[cpu].
395      */
396     while (type->ks_loosememuse >= type->ks_limit) {
397         int i;
398         long ttl;
399
400         for (i = ttl = 0; i < ncpus; ++i)
401             ttl += type->ks_memuse[i];
402         type->ks_loosememuse = ttl;     /* not MP synchronized */
403         if (ttl >= type->ks_limit) {
404             if (flags & M_NULLOK)
405                 return(NULL);
406             panic("%s: malloc limit exceeded", type->ks_shortdesc);
407         }
408     }
409
410     /*
411      * Handle the degenerate size == 0 case.  Yes, this does happen.
412      * Return a special pointer.  This is to maintain compatibility with
413      * the original malloc implementation.  Certain devices, such as the
414      * adaptec driver, not only allocate 0 bytes, they check for NULL and
415      * also realloc() later on.  Joy.
416      */
417     if (size == 0)
418         return(ZERO_LENGTH_PTR);
419
420     /*
421      * Handle hysteresis from prior frees here in malloc().  We cannot
422      * safely manipulate the kernel_map in free() due to free() possibly
423      * being called via an IPI message or from sensitive interrupt code.
424      */
425     while (slgd->NFreeZones > ZONE_RELS_THRESH && (flags & M_RNOWAIT) == 0) {
426         crit_enter();
427         if (slgd->NFreeZones > ZONE_RELS_THRESH) {      /* crit sect race */
428             z = slgd->FreeZones;
429             slgd->FreeZones = z->z_Next;
430             --slgd->NFreeZones;
431             kmem_slab_free(z, ZoneSize);        /* may block */
432         }
433         crit_exit();
434     }
435     /*
436      * XXX handle oversized frees that were queued from free().
437      */
438     while (slgd->FreeOvZones && (flags & M_RNOWAIT) == 0) {
439         crit_enter();
440         if ((z = slgd->FreeOvZones) != NULL) {
441             KKASSERT(z->z_Magic == ZALLOC_OVSZ_MAGIC);
442             slgd->FreeOvZones = z->z_Next;
443             kmem_slab_free(z, z->z_ChunkSize);  /* may block */
444         }
445         crit_exit();
446     }
447
448     /*
449      * Handle large allocations directly.  There should not be very many of
450      * these so performance is not a big issue.
451      *
452      * Guarentee page alignment for allocations in multiples of PAGE_SIZE
453      */
454     if (size >= ZoneLimit || (size & PAGE_MASK) == 0) {
455         struct kmemusage *kup;
456
457         size = round_page(size);
458         chunk = kmem_slab_alloc(size, PAGE_SIZE, flags);
459         if (chunk == NULL)
460             return(NULL);
461         flags &= ~M_ZERO;       /* result already zero'd if M_ZERO was set */
462         flags |= M_PASSIVE_ZERO;
463         kup = btokup(chunk);
464         kup->ku_pagecnt = size / PAGE_SIZE;
465         kup->ku_cpu = gd->gd_cpuid;
466         crit_enter();
467         goto done;
468     }
469
470     /*
471      * Attempt to allocate out of an existing zone.  First try the free list,
472      * then allocate out of unallocated space.  If we find a good zone move
473      * it to the head of the list so later allocations find it quickly
474      * (we might have thousands of zones in the list).
475      *
476      * Note: zoneindex() will panic of size is too large.
477      */
478     zi = zoneindex(&size);
479     KKASSERT(zi < NZONES);
480     crit_enter();
481     if ((z = slgd->ZoneAry[zi]) != NULL) {
482         KKASSERT(z->z_NFree > 0);
483
484         /*
485          * Remove us from the ZoneAry[] when we become empty
486          */
487         if (--z->z_NFree == 0) {
488             slgd->ZoneAry[zi] = z->z_Next;
489             z->z_Next = NULL;
490         }
491
492         /*
493          * Locate a chunk in a free page.  This attempts to localize
494          * reallocations into earlier pages without us having to sort
495          * the chunk list.  A chunk may still overlap a page boundary.
496          */
497         while (z->z_FirstFreePg < ZonePageCount) {
498             if ((chunk = z->z_PageAry[z->z_FirstFreePg]) != NULL) {
499 #ifdef DIAGNOSTIC
500                 /*
501                  * Diagnostic: c_Next is not total garbage.
502                  */
503                 KKASSERT(chunk->c_Next == NULL ||
504                         ((intptr_t)chunk->c_Next & IN_SAME_PAGE_MASK) ==
505                         ((intptr_t)chunk & IN_SAME_PAGE_MASK));
506 #endif
507 #ifdef INVARIANTS
508                 if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
509                         panic("chunk %p FFPG %d/%d", chunk, z->z_FirstFreePg, ZonePageCount);
510                 if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
511                         panic("chunkNEXT %p %p FFPG %d/%d", chunk, chunk->c_Next, z->z_FirstFreePg, ZonePageCount);
512                 chunk_mark_allocated(z, chunk);
513 #endif
514                 z->z_PageAry[z->z_FirstFreePg] = chunk->c_Next;
515                 goto done;
516             }
517             ++z->z_FirstFreePg;
518         }
519
520         /*
521          * No chunks are available but NFree said we had some memory, so
522          * it must be available in the never-before-used-memory area
523          * governed by UIndex.  The consequences are very serious if our zone
524          * got corrupted so we use an explicit panic rather then a KASSERT.
525          */
526         if (z->z_UIndex + 1 != z->z_NMax)
527             z->z_UIndex = z->z_UIndex + 1;
528         else
529             z->z_UIndex = 0;
530         if (z->z_UIndex == z->z_UEndIndex)
531             panic("slaballoc: corrupted zone");
532         chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
533         if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
534             flags &= ~M_ZERO;
535             flags |= M_PASSIVE_ZERO;
536         }
537 #if defined(INVARIANTS)
538         chunk_mark_allocated(z, chunk);
539 #endif
540         goto done;
541     }
542
543     /*
544      * If all zones are exhausted we need to allocate a new zone for this
545      * index.  Use M_ZERO to take advantage of pre-zerod pages.  Also see
546      * UAlloc use above in regards to M_ZERO.  Note that when we are reusing
547      * a zone from the FreeZones list UAlloc'd data will not be zero'd, and
548      * we do not pre-zero it because we do not want to mess up the L1 cache.
549      *
550      * At least one subsystem, the tty code (see CROUND) expects power-of-2
551      * allocations to be power-of-2 aligned.  We maintain compatibility by
552      * adjusting the base offset below.
553      */
554     {
555         int off;
556
557         if ((z = slgd->FreeZones) != NULL) {
558             slgd->FreeZones = z->z_Next;
559             --slgd->NFreeZones;
560             bzero(z, sizeof(SLZone));
561             z->z_Flags |= SLZF_UNOTZEROD;
562         } else {
563             z = kmem_slab_alloc(ZoneSize, ZoneSize, flags|M_ZERO);
564             if (z == NULL)
565                 goto fail;
566         }
567
568         /*
569          * How big is the base structure?
570          */
571 #if defined(INVARIANTS)
572         /*
573          * Make room for z_Bitmap.  An exact calculation is somewhat more
574          * complicated so don't make an exact calculation.
575          */
576         off = offsetof(SLZone, z_Bitmap[(ZoneSize / size + 31) / 32]);
577         bzero(z->z_Bitmap, (ZoneSize / size + 31) / 8);
578 #else
579         off = sizeof(SLZone);
580 #endif
581
582         /*
583          * Guarentee power-of-2 alignment for power-of-2-sized chunks.
584          * Otherwise just 8-byte align the data.
585          */
586         if ((size | (size - 1)) + 1 == (size << 1))
587             off = (off + size - 1) & ~(size - 1);
588         else
589             off = (off + MIN_CHUNK_MASK) & ~MIN_CHUNK_MASK;
590         z->z_Magic = ZALLOC_SLAB_MAGIC;
591         z->z_ZoneIndex = zi;
592         z->z_NMax = (ZoneSize - off) / size;
593         z->z_NFree = z->z_NMax - 1;
594         z->z_BasePtr = (char *)z + off;
595         z->z_UIndex = z->z_UEndIndex = slgd->JunkIndex % z->z_NMax;
596         z->z_ChunkSize = size;
597         z->z_FirstFreePg = ZonePageCount;
598         z->z_CpuGd = gd;
599         z->z_Cpu = gd->gd_cpuid;
600         chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
601         z->z_Next = slgd->ZoneAry[zi];
602         slgd->ZoneAry[zi] = z;
603         if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
604             flags &= ~M_ZERO;   /* already zero'd */
605             flags |= M_PASSIVE_ZERO;
606         }
607 #if defined(INVARIANTS)
608         chunk_mark_allocated(z, chunk);
609 #endif
610
611         /*
612          * Slide the base index for initial allocations out of the next
613          * zone we create so we do not over-weight the lower part of the
614          * cpu memory caches.
615          */
616         slgd->JunkIndex = (slgd->JunkIndex + ZALLOC_SLAB_SLIDE)
617                                 & (ZALLOC_MAX_ZONE_SIZE - 1);
618     }
619 done:
620     ++type->ks_inuse[gd->gd_cpuid];
621     type->ks_memuse[gd->gd_cpuid] += size;
622     type->ks_loosememuse += size;       /* not MP synchronized */
623     crit_exit();
624     if (flags & M_ZERO)
625         bzero(chunk, size);
626 #ifdef INVARIANTS
627     else if ((flags & (M_ZERO|M_PASSIVE_ZERO)) == 0) {
628         if (use_malloc_pattern) {
629             for (i = 0; i < size; i += sizeof(int)) {
630                 *(int *)((char *)chunk + i) = -1;
631             }
632         }
633         chunk->c_Next = (void *)-1; /* avoid accidental double-free check */
634     }
635 #endif
636     return(chunk);
637 fail:
638     crit_exit();
639     return(NULL);
640 }
641
642 /*
643  * kernel realloc.  (SLAB ALLOCATOR) (MP SAFE)
644  *
645  * Generally speaking this routine is not called very often and we do
646  * not attempt to optimize it beyond reusing the same pointer if the
647  * new size fits within the chunking of the old pointer's zone.
648  */
649 void *
650 realloc(void *ptr, unsigned long size, struct malloc_type *type, int flags)
651 {
652     SLZone *z;
653     void *nptr;
654     unsigned long osize;
655
656     KKASSERT((flags & M_ZERO) == 0);    /* not supported */
657
658     if (ptr == NULL || ptr == ZERO_LENGTH_PTR)
659         return(malloc(size, type, flags));
660     if (size == 0) {
661         free(ptr, type);
662         return(NULL);
663     }
664
665     /*
666      * Handle oversized allocations.  XXX we really should require that a
667      * size be passed to free() instead of this nonsense.
668      */
669     {
670         struct kmemusage *kup;
671
672         kup = btokup(ptr);
673         if (kup->ku_pagecnt) {
674             osize = kup->ku_pagecnt << PAGE_SHIFT;
675             if (osize == round_page(size))
676                 return(ptr);
677             if ((nptr = malloc(size, type, flags)) == NULL)
678                 return(NULL);
679             bcopy(ptr, nptr, min(size, osize));
680             free(ptr, type);
681             return(nptr);
682         }
683     }
684
685     /*
686      * Get the original allocation's zone.  If the new request winds up
687      * using the same chunk size we do not have to do anything.
688      */
689     z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
690     KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
691
692     zoneindex(&size);
693     if (z->z_ChunkSize == size)
694         return(ptr);
695
696     /*
697      * Allocate memory for the new request size.  Note that zoneindex has
698      * already adjusted the request size to the appropriate chunk size, which
699      * should optimize our bcopy().  Then copy and return the new pointer.
700      */
701     if ((nptr = malloc(size, type, flags)) == NULL)
702         return(NULL);
703     bcopy(ptr, nptr, min(size, z->z_ChunkSize));
704     free(ptr, type);
705     return(nptr);
706 }
707
708 /*
709  * Allocate a copy of the specified string.
710  *
711  * (MP SAFE) (MAY BLOCK)
712  */
713 char *
714 strdup(const char *str, struct malloc_type *type)
715 {
716     int zlen;   /* length inclusive of terminating NUL */
717     char *nstr;
718
719     if (str == NULL)
720         return(NULL);
721     zlen = strlen(str) + 1;
722     nstr = malloc(zlen, type, M_WAITOK);
723     bcopy(str, nstr, zlen);
724     return(nstr);
725 }
726
727 #ifdef SMP
728 /*
729  * free()       (SLAB ALLOCATOR)
730  *
731  *      Free the specified chunk of memory.
732  */
733 static
734 void
735 free_remote(void *ptr)
736 {
737     free(ptr, *(struct malloc_type **)ptr);
738 }
739
740 #endif
741
742 /*
743  * free (SLAB ALLOCATOR) (MP SAFE)
744  *
745  * Free a memory block previously allocated by malloc.  Note that we do not
746  * attempt to uplodate ks_loosememuse as MP races could prevent us from
747  * checking memory limits in malloc.
748  */
749 void
750 free(void *ptr, struct malloc_type *type)
751 {
752     SLZone *z;
753     SLChunk *chunk;
754     SLGlobalData *slgd;
755     struct globaldata *gd;
756     int pgno;
757
758     gd = mycpu;
759     slgd = &gd->gd_slab;
760
761     if (ptr == NULL)
762         panic("trying to free NULL pointer");
763
764     /*
765      * Handle special 0-byte allocations
766      */
767     if (ptr == ZERO_LENGTH_PTR)
768         return;
769
770     /*
771      * Handle oversized allocations.  XXX we really should require that a
772      * size be passed to free() instead of this nonsense.
773      *
774      * This code is never called via an ipi.
775      */
776     {
777         struct kmemusage *kup;
778         unsigned long size;
779
780         kup = btokup(ptr);
781         if (kup->ku_pagecnt) {
782             size = kup->ku_pagecnt << PAGE_SHIFT;
783             kup->ku_pagecnt = 0;
784 #ifdef INVARIANTS
785             KKASSERT(sizeof(weirdary) <= size);
786             bcopy(weirdary, ptr, sizeof(weirdary));
787 #endif
788             /*
789              * note: we always adjust our cpu's slot, not the originating
790              * cpu (kup->ku_cpuid).  The statistics are in aggregate.
791              *
792              * note: XXX we have still inherited the interrupts-can't-block
793              * assumption.  An interrupt thread does not bump
794              * gd_intr_nesting_level so check TDF_INTTHREAD.  This is
795              * primarily until we can fix softupdate's assumptions about free().
796              */
797             crit_enter();
798             --type->ks_inuse[gd->gd_cpuid];
799             type->ks_memuse[gd->gd_cpuid] -= size;
800             if (mycpu->gd_intr_nesting_level || (gd->gd_curthread->td_flags & TDF_INTTHREAD)) {
801                 z = (SLZone *)ptr;
802                 z->z_Magic = ZALLOC_OVSZ_MAGIC;
803                 z->z_Next = slgd->FreeOvZones;
804                 z->z_ChunkSize = size;
805                 slgd->FreeOvZones = z;
806                 crit_exit();
807             } else {
808                 crit_exit();
809                 kmem_slab_free(ptr, size);      /* may block */
810             }
811             return;
812         }
813     }
814
815     /*
816      * Zone case.  Figure out the zone based on the fact that it is
817      * ZoneSize aligned. 
818      */
819     z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
820     KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
821
822     /*
823      * If we do not own the zone then forward the request to the
824      * cpu that does.  Since the timing is non-critical, a passive
825      * message is sent.
826      */
827     if (z->z_CpuGd != gd) {
828         *(struct malloc_type **)ptr = type;
829 #ifdef SMP
830         lwkt_send_ipiq_passive(z->z_CpuGd, free_remote, ptr);
831 #else
832         panic("Corrupt SLZone");
833 #endif
834         return;
835     }
836
837     if (type->ks_magic != M_MAGIC)
838         panic("free: malloc type lacks magic");
839
840     crit_enter();
841     pgno = ((char *)ptr - (char *)z) >> PAGE_SHIFT;
842     chunk = ptr;
843
844 #ifdef INVARIANTS
845     /*
846      * Attempt to detect a double-free.  To reduce overhead we only check
847      * if there appears to be link pointer at the base of the data.
848      */
849     if (((intptr_t)chunk->c_Next - (intptr_t)z) >> PAGE_SHIFT == pgno) {
850         SLChunk *scan;
851         for (scan = z->z_PageAry[pgno]; scan; scan = scan->c_Next) {
852             if (scan == chunk)
853                 panic("Double free at %p", chunk);
854         }
855     }
856     chunk_mark_free(z, chunk);
857 #endif
858
859     /*
860      * Put weird data into the memory to detect modifications after freeing,
861      * illegal pointer use after freeing (we should fault on the odd address),
862      * and so forth.  XXX needs more work, see the old malloc code.
863      */
864 #ifdef INVARIANTS
865     if (z->z_ChunkSize < sizeof(weirdary))
866         bcopy(weirdary, chunk, z->z_ChunkSize);
867     else
868         bcopy(weirdary, chunk, sizeof(weirdary));
869 #endif
870
871     /*
872      * Add this free non-zero'd chunk to a linked list for reuse, adjust
873      * z_FirstFreePg.
874      */
875 #ifdef INVARIANTS
876     if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
877         panic("BADFREE %p", chunk);
878 #endif
879     chunk->c_Next = z->z_PageAry[pgno];
880     z->z_PageAry[pgno] = chunk;
881 #ifdef INVARIANTS
882     if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
883         panic("BADFREE2");
884 #endif
885     if (z->z_FirstFreePg > pgno)
886         z->z_FirstFreePg = pgno;
887
888     /*
889      * Bump the number of free chunks.  If it becomes non-zero the zone
890      * must be added back onto the appropriate list.
891      */
892     if (z->z_NFree++ == 0) {
893         z->z_Next = slgd->ZoneAry[z->z_ZoneIndex];
894         slgd->ZoneAry[z->z_ZoneIndex] = z;
895     }
896
897     --type->ks_inuse[z->z_Cpu];
898     type->ks_memuse[z->z_Cpu] -= z->z_ChunkSize;
899
900     /*
901      * If the zone becomes totally free, and there are other zones we
902      * can allocate from, move this zone to the FreeZones list.  Since
903      * this code can be called from an IPI callback, do *NOT* try to mess
904      * with kernel_map here.  Hysteresis will be performed at malloc() time.
905      */
906     if (z->z_NFree == z->z_NMax && 
907         (z->z_Next || slgd->ZoneAry[z->z_ZoneIndex] != z)
908     ) {
909         SLZone **pz;
910
911         for (pz = &slgd->ZoneAry[z->z_ZoneIndex]; z != *pz; pz = &(*pz)->z_Next)
912             ;
913         *pz = z->z_Next;
914         z->z_Magic = -1;
915         z->z_Next = slgd->FreeZones;
916         slgd->FreeZones = z;
917         ++slgd->NFreeZones;
918     }
919     crit_exit();
920 }
921
922 #if defined(INVARIANTS)
923 /*
924  * Helper routines for sanity checks
925  */
926 static
927 void
928 chunk_mark_allocated(SLZone *z, void *chunk)
929 {
930     int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
931     __uint32_t *bitptr;
932
933     KASSERT(bitdex >= 0 && bitdex < z->z_NMax, ("memory chunk %p bit index %d is illegal", chunk, bitdex));
934     bitptr = &z->z_Bitmap[bitdex >> 5];
935     bitdex &= 31;
936     KASSERT((*bitptr & (1 << bitdex)) == 0, ("memory chunk %p is already allocated!", chunk));
937     *bitptr |= 1 << bitdex;
938 }
939
940 static
941 void
942 chunk_mark_free(SLZone *z, void *chunk)
943 {
944     int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
945     __uint32_t *bitptr;
946
947     KASSERT(bitdex >= 0 && bitdex < z->z_NMax, ("memory chunk %p bit index %d is illegal!", chunk, bitdex));
948     bitptr = &z->z_Bitmap[bitdex >> 5];
949     bitdex &= 31;
950     KASSERT((*bitptr & (1 << bitdex)) != 0, ("memory chunk %p is already free!", chunk));
951     *bitptr &= ~(1 << bitdex);
952 }
953
954 #endif
955
956 /*
957  * kmem_slab_alloc()    (MP SAFE) (GETS BGL)
958  *
959  *      Directly allocate and wire kernel memory in PAGE_SIZE chunks with the
960  *      specified alignment.  M_* flags are expected in the flags field.
961  *
962  *      Alignment must be a multiple of PAGE_SIZE.
963  *
964  *      NOTE! XXX For the moment we use vm_map_entry_reserve/release(),
965  *      but when we move zalloc() over to use this function as its backend
966  *      we will have to switch to kreserve/krelease and call reserve(0)
967  *      after the new space is made available.
968  *
969  *      Interrupt code which has preempted other code is not allowed to
970  *      use PQ_CACHE pages.  However, if an interrupt thread is run
971  *      non-preemptively or blocks and then runs non-preemptively, then
972  *      it is free to use PQ_CACHE pages.
973  *
974  *      This routine will currently obtain the BGL.
975  */
976 static void *
977 kmem_slab_alloc(vm_size_t size, vm_offset_t align, int flags)
978 {
979     vm_size_t i;
980     vm_offset_t addr;
981     vm_offset_t offset;
982     int count, vmflags, base_vmflags;
983     thread_t td;
984     vm_map_t map = kernel_map;
985
986     size = round_page(size);
987     addr = vm_map_min(map);
988
989     /*
990      * Reserve properly aligned space from kernel_map.  RNOWAIT allocations
991      * cannot block.
992      */
993     if (flags & M_RNOWAIT) {
994         if (try_mplock() == 0)
995             return(NULL);
996     } else {
997         get_mplock();
998     }
999     count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1000     crit_enter();
1001     vm_map_lock(map);
1002     if (vm_map_findspace(map, vm_map_min(map), size, align, &addr)) {
1003         vm_map_unlock(map);
1004         if ((flags & M_NULLOK) == 0)
1005             panic("kmem_slab_alloc(): kernel_map ran out of space!");
1006         crit_exit();
1007         vm_map_entry_release(count);
1008         rel_mplock();
1009         return(NULL);
1010     }
1011     offset = addr - VM_MIN_KERNEL_ADDRESS;
1012     vm_object_reference(kernel_object);
1013     vm_map_insert(map, &count, 
1014                     kernel_object, offset, addr, addr + size,
1015                     VM_PROT_ALL, VM_PROT_ALL, 0);
1016
1017     td = curthread;
1018
1019     base_vmflags = 0;
1020     if (flags & M_ZERO)
1021         base_vmflags |= VM_ALLOC_ZERO;
1022     if (flags & M_USE_RESERVE)
1023         base_vmflags |= VM_ALLOC_SYSTEM;
1024     if (flags & M_USE_INTERRUPT_RESERVE)
1025         base_vmflags |= VM_ALLOC_INTERRUPT;
1026     if ((flags & (M_RNOWAIT|M_WAITOK)) == 0)
1027         panic("kmem_slab_alloc: bad flags %08x (%p)", flags, ((int **)&size)[-1]);
1028
1029
1030     /*
1031      * Allocate the pages.  Do not mess with the PG_ZERO flag yet.
1032      */
1033     for (i = 0; i < size; i += PAGE_SIZE) {
1034         vm_page_t m;
1035         vm_pindex_t idx = OFF_TO_IDX(offset + i);
1036
1037         /*
1038          * VM_ALLOC_NORMAL can only be set if we are not preempting.
1039          *
1040          * VM_ALLOC_SYSTEM is automatically set if we are preempting and
1041          * M_WAITOK was specified as an alternative (i.e. M_USE_RESERVE is
1042          * implied in this case), though I'm sure if we really need to do
1043          * that.
1044          */
1045         vmflags = base_vmflags;
1046         if (flags & M_WAITOK) {
1047             if (td->td_preempted)
1048                 vmflags |= VM_ALLOC_SYSTEM;
1049             else
1050                 vmflags |= VM_ALLOC_NORMAL;
1051         }
1052
1053         m = vm_page_alloc(kernel_object, idx, vmflags);
1054
1055         /*
1056          * If the allocation failed we either return NULL or we retry.
1057          *
1058          * If M_WAITOK is specified we wait for more memory and retry.
1059          * If M_WAITOK is specified from a preemption we yield instead of
1060          * wait.  Livelock will not occur because the interrupt thread
1061          * will not be preempting anyone the second time around after the
1062          * yield.
1063          */
1064         if (m == NULL) {
1065             if (flags & M_WAITOK) {
1066                 if (td->td_preempted) {
1067                     vm_map_unlock(map);
1068                     lwkt_yield();
1069                     vm_map_lock(map);
1070                 } else {
1071                     vm_map_unlock(map);
1072                     vm_wait();
1073                     vm_map_lock(map);
1074                 }
1075                 i -= PAGE_SIZE; /* retry */
1076                 continue;
1077             }
1078
1079             /*
1080              * We were unable to recover, cleanup and return NULL
1081              */
1082             while (i != 0) {
1083                 i -= PAGE_SIZE;
1084                 m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
1085                 vm_page_free(m);
1086             }
1087             vm_map_delete(map, addr, addr + size, &count);
1088             vm_map_unlock(map);
1089             crit_exit();
1090             vm_map_entry_release(count);
1091             rel_mplock();
1092             return(NULL);
1093         }
1094     }
1095
1096     /*
1097      * Success!
1098      *
1099      * Mark the map entry as non-pageable using a routine that allows us to
1100      * populate the underlying pages.
1101      */
1102     vm_map_set_wired_quick(map, addr, size, &count);
1103     crit_exit();
1104
1105     /*
1106      * Enter the pages into the pmap and deal with PG_ZERO and M_ZERO.
1107      */
1108     for (i = 0; i < size; i += PAGE_SIZE) {
1109         vm_page_t m;
1110
1111         m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
1112         m->valid = VM_PAGE_BITS_ALL;
1113         vm_page_wire(m);
1114         vm_page_wakeup(m);
1115         pmap_enter(kernel_pmap, addr + i, m, VM_PROT_ALL, 1);
1116         if ((m->flags & PG_ZERO) == 0 && (flags & M_ZERO))
1117             bzero((char *)addr + i, PAGE_SIZE);
1118         vm_page_flag_clear(m, PG_ZERO);
1119         vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE | PG_REFERENCED);
1120     }
1121     vm_map_unlock(map);
1122     vm_map_entry_release(count);
1123     rel_mplock();
1124     return((void *)addr);
1125 }
1126
1127 /*
1128  * kmem_slab_free()     (MP SAFE) (GETS BGL)
1129  */
1130 static void
1131 kmem_slab_free(void *ptr, vm_size_t size)
1132 {
1133     get_mplock();
1134     crit_enter();
1135     vm_map_remove(kernel_map, (vm_offset_t)ptr, (vm_offset_t)ptr + size);
1136     crit_exit();
1137     rel_mplock();
1138 }
1139