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