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