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