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