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