xref: /dflybsd-src/sys/kern/kern_slaballoc.c (revision 2ac7d1050a3c50c16d77203ac6ed01a65757e5b0)
1 /*
2  * KERN_SLABALLOC.C	- Kernel SLAB memory allocator
3  *
4  * Copyright (c) 2003,2004,2010-2019 The DragonFly Project.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The DragonFly Project
8  * by Matthew Dillon <dillon@backplane.com>
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  * 3. Neither the name of The DragonFly Project nor the names of its
21  *    contributors may be used to endorse or promote products derived
22  *    from this software without specific, prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
28  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
30  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
32  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
34  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  * This module implements a slab allocator drop-in replacement for the
38  * kernel malloc().
39  *
40  * A slab allocator reserves a ZONE for each chunk size, then lays the
41  * chunks out in an array within the zone.  Allocation and deallocation
42  * is nearly instantanious, and fragmentation/overhead losses are limited
43  * to a fixed worst-case amount.
44  *
45  * The downside of this slab implementation is in the chunk size
46  * multiplied by the number of zones.  ~80 zones * 128K = 10MB of VM per cpu.
47  * In a kernel implementation all this memory will be physical so
48  * the zone size is adjusted downward on machines with less physical
49  * memory.  The upside is that overhead is bounded... this is the *worst*
50  * case overhead.
51  *
52  * Slab management is done on a per-cpu basis and no locking or mutexes
53  * are required, only a critical section.  When one cpu frees memory
54  * belonging to another cpu's slab manager an asynchronous IPI message
55  * will be queued to execute the operation.   In addition, both the
56  * high level slab allocator and the low level zone allocator optimize
57  * M_ZERO requests, and the slab allocator does not have to pre initialize
58  * the linked list of chunks.
59  *
60  * XXX Balancing is needed between cpus.  Balance will be handled through
61  * asynchronous IPIs primarily by reassigning the z_Cpu ownership of chunks.
62  *
63  * XXX If we have to allocate a new zone and M_USE_RESERVE is set, use of
64  * the new zone should be restricted to M_USE_RESERVE requests only.
65  *
66  *	Alloc Size	Chunking        Number of zones
67  *	0-127		8		16
68  *	128-255		16		8
69  *	256-511		32		8
70  *	512-1023	64		8
71  *	1024-2047	128		8
72  *	2048-4095	256		8
73  *	4096-8191	512		8
74  *	8192-16383	1024		8
75  *	16384-32767	2048		8
76  *	(if PAGE_SIZE is 4K the maximum zone allocation is 16383)
77  *
78  *	Allocations >= ZoneLimit go directly to kmem.
79  *	(n * PAGE_SIZE, n > 2) allocations go directly to kmem.
80  *
81  * Alignment properties:
82  * - All power-of-2 sized allocations are power-of-2 aligned.
83  * - Allocations with M_POWEROF2 are power-of-2 aligned on the nearest
84  *   power-of-2 round up of 'size'.
85  * - Non-power-of-2 sized allocations are zone chunk size aligned (see the
86  *   above table 'Chunking' column).
87  *
88  *			API REQUIREMENTS AND SIDE EFFECTS
89  *
90  *    To operate as a drop-in replacement to the FreeBSD-4.x malloc() we
91  *    have remained compatible with the following API requirements:
92  *
93  *    + malloc(0) is allowed and returns non-NULL (ahc driver)
94  *    + ability to allocate arbitrarily large chunks of memory
95  */
96 
97 #include "opt_vm.h"
98 
99 #include <sys/param.h>
100 #include <sys/systm.h>
101 #include <sys/kernel.h>
102 #include <sys/slaballoc.h>
103 #include <sys/mbuf.h>
104 #include <sys/vmmeter.h>
105 #include <sys/lock.h>
106 #include <sys/thread.h>
107 #include <sys/globaldata.h>
108 #include <sys/sysctl.h>
109 #include <sys/ktr.h>
110 #include <sys/malloc.h>
111 
112 #include <vm/vm.h>
113 #include <vm/vm_param.h>
114 #include <vm/vm_kern.h>
115 #include <vm/vm_extern.h>
116 #include <vm/vm_object.h>
117 #include <vm/pmap.h>
118 #include <vm/vm_map.h>
119 #include <vm/vm_page.h>
120 #include <vm/vm_pageout.h>
121 
122 #include <machine/cpu.h>
123 
124 #include <sys/thread2.h>
125 #include <vm/vm_page2.h>
126 
127 #if (__VM_CACHELINE_SIZE == 32)
128 #define CAN_CACHEALIGN(sz)	((sz) >= 256)
129 #elif (__VM_CACHELINE_SIZE == 64)
130 #define CAN_CACHEALIGN(sz)	((sz) >= 512)
131 #elif (__VM_CACHELINE_SIZE == 128)
132 #define CAN_CACHEALIGN(sz)	((sz) >= 1024)
133 #else
134 #error "unsupported cacheline size"
135 #endif
136 
137 #define btokup(z)	(&pmap_kvtom((vm_offset_t)(z))->ku_pagecnt)
138 
139 #define MEMORY_STRING	"ptr=%p type=%p size=%lu flags=%04x"
140 #define MEMORY_ARGS	void *ptr, void *type, unsigned long size, int flags
141 
142 #if !defined(KTR_MEMORY)
143 #define KTR_MEMORY	KTR_ALL
144 #endif
145 KTR_INFO_MASTER(memory);
146 KTR_INFO(KTR_MEMORY, memory, malloc_beg, 0, "malloc begin");
147 KTR_INFO(KTR_MEMORY, memory, malloc_end, 1, MEMORY_STRING, MEMORY_ARGS);
148 KTR_INFO(KTR_MEMORY, memory, free_zero, 2, MEMORY_STRING, MEMORY_ARGS);
149 KTR_INFO(KTR_MEMORY, memory, free_ovsz, 3, MEMORY_STRING, MEMORY_ARGS);
150 KTR_INFO(KTR_MEMORY, memory, free_ovsz_delayed, 4, MEMORY_STRING, MEMORY_ARGS);
151 KTR_INFO(KTR_MEMORY, memory, free_chunk, 5, MEMORY_STRING, MEMORY_ARGS);
152 KTR_INFO(KTR_MEMORY, memory, free_request, 6, MEMORY_STRING, MEMORY_ARGS);
153 KTR_INFO(KTR_MEMORY, memory, free_rem_beg, 7, MEMORY_STRING, MEMORY_ARGS);
154 KTR_INFO(KTR_MEMORY, memory, free_rem_end, 8, MEMORY_STRING, MEMORY_ARGS);
155 KTR_INFO(KTR_MEMORY, memory, free_beg, 9, "free begin");
156 KTR_INFO(KTR_MEMORY, memory, free_end, 10, "free end");
157 
158 #define logmemory(name, ptr, type, size, flags)				\
159 	KTR_LOG(memory_ ## name, ptr, type, size, flags)
160 #define logmemory_quick(name)						\
161 	KTR_LOG(memory_ ## name)
162 
163 /*
164  * Fixed globals (not per-cpu)
165  */
166 static int ZoneSize;
167 static int ZoneLimit;
168 static int ZonePageCount;
169 static uintptr_t ZoneMask;
170 static int ZoneBigAlloc;		/* in KB */
171 static int ZoneGenAlloc;		/* in KB */
172 struct malloc_type *kmemstatistics;	/* exported to vmstat */
173 #ifdef INVARIANTS
174 static int32_t weirdary[16];
175 #endif
176 
177 static void *kmem_slab_alloc(vm_size_t bytes, vm_offset_t align, int flags);
178 static void kmem_slab_free(void *ptr, vm_size_t bytes);
179 
180 #if defined(INVARIANTS)
181 static void chunk_mark_allocated(SLZone *z, void *chunk);
182 static void chunk_mark_free(SLZone *z, void *chunk);
183 #else
184 #define chunk_mark_allocated(z, chunk)
185 #define chunk_mark_free(z, chunk)
186 #endif
187 
188 /*
189  * Misc constants.  Note that allocations that are exact multiples of
190  * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
191  */
192 #define ZONE_RELS_THRESH	32		/* threshold number of zones */
193 
194 #ifdef INVARIANTS
195 /*
196  * The WEIRD_ADDR is used as known text to copy into free objects to
197  * try to create deterministic failure cases if the data is accessed after
198  * free.
199  */
200 #define WEIRD_ADDR      0xdeadc0de
201 #endif
202 #define ZERO_LENGTH_PTR	((void *)-8)
203 
204 /*
205  * Misc global malloc buckets
206  */
207 
208 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
209 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
210 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
211 MALLOC_DEFINE(M_DRM, "m_drm", "DRM memory allocations");
212 
213 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
214 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
215 
216 /*
217  * Initialize the slab memory allocator.  We have to choose a zone size based
218  * on available physical memory.  We choose a zone side which is approximately
219  * 1/1024th of our memory, so if we have 128MB of ram we have a zone size of
220  * 128K.  The zone size is limited to the bounds set in slaballoc.h
221  * (typically 32K min, 128K max).
222  */
223 static void kmeminit(void *dummy);
224 
225 char *ZeroPage;
226 
227 SYSINIT(kmem, SI_BOOT1_ALLOCATOR, SI_ORDER_FIRST, kmeminit, NULL);
228 
229 #ifdef INVARIANTS
230 /*
231  * If enabled any memory allocated without M_ZERO is initialized to -1.
232  */
233 static int  use_malloc_pattern;
234 SYSCTL_INT(_debug, OID_AUTO, use_malloc_pattern, CTLFLAG_RW,
235     &use_malloc_pattern, 0,
236     "Initialize memory to -1 if M_ZERO not specified");
237 #endif
238 
239 static int ZoneRelsThresh = ZONE_RELS_THRESH;
240 SYSCTL_INT(_kern, OID_AUTO, zone_big_alloc, CTLFLAG_RD, &ZoneBigAlloc, 0, "");
241 SYSCTL_INT(_kern, OID_AUTO, zone_gen_alloc, CTLFLAG_RD, &ZoneGenAlloc, 0, "");
242 SYSCTL_INT(_kern, OID_AUTO, zone_cache, CTLFLAG_RW, &ZoneRelsThresh, 0, "");
243 static long SlabsAllocated;
244 static long SlabsFreed;
245 SYSCTL_LONG(_kern, OID_AUTO, slabs_allocated, CTLFLAG_RD,
246 	    &SlabsAllocated, 0, "");
247 SYSCTL_LONG(_kern, OID_AUTO, slabs_freed, CTLFLAG_RD,
248 	    &SlabsFreed, 0, "");
249 static int SlabFreeToTail;
250 SYSCTL_INT(_kern, OID_AUTO, slab_freetotail, CTLFLAG_RW,
251 	    &SlabFreeToTail, 0, "");
252 
253 static struct spinlock kmemstat_spin =
254 			SPINLOCK_INITIALIZER(&kmemstat_spin, "malinit");
255 
256 /*
257  * Returns the kernel memory size limit for the purposes of initializing
258  * various subsystem caches.  The smaller of available memory and the KVM
259  * memory space is returned.
260  *
261  * The size in megabytes is returned.
262  */
263 size_t
264 kmem_lim_size(void)
265 {
266     size_t limsize;
267 
268     limsize = (size_t)vmstats.v_page_count * PAGE_SIZE;
269     if (limsize > KvaSize)
270 	limsize = KvaSize;
271     return (limsize / (1024 * 1024));
272 }
273 
274 static void
275 kmeminit(void *dummy)
276 {
277     size_t limsize;
278     int usesize;
279 #ifdef INVARIANTS
280     int i;
281 #endif
282 
283     limsize = kmem_lim_size();
284     usesize = (int)(limsize * 1024);	/* convert to KB */
285 
286     /*
287      * If the machine has a large KVM space and more than 8G of ram,
288      * double the zone release threshold to reduce SMP invalidations.
289      * If more than 16G of ram, do it again.
290      *
291      * The BIOS eats a little ram so add some slop.  We want 8G worth of
292      * memory sticks to trigger the first adjustment.
293      */
294     if (ZoneRelsThresh == ZONE_RELS_THRESH) {
295 	    if (limsize >= 7 * 1024)
296 		    ZoneRelsThresh *= 2;
297 	    if (limsize >= 15 * 1024)
298 		    ZoneRelsThresh *= 2;
299     }
300 
301     /*
302      * Calculate the zone size.  This typically calculates to
303      * ZALLOC_MAX_ZONE_SIZE
304      */
305     ZoneSize = ZALLOC_MIN_ZONE_SIZE;
306     while (ZoneSize < ZALLOC_MAX_ZONE_SIZE && (ZoneSize << 1) < usesize)
307 	ZoneSize <<= 1;
308     ZoneLimit = ZoneSize / 4;
309     if (ZoneLimit > ZALLOC_ZONE_LIMIT)
310 	ZoneLimit = ZALLOC_ZONE_LIMIT;
311     ZoneMask = ~(uintptr_t)(ZoneSize - 1);
312     ZonePageCount = ZoneSize / PAGE_SIZE;
313 
314 #ifdef INVARIANTS
315     for (i = 0; i < NELEM(weirdary); ++i)
316 	weirdary[i] = WEIRD_ADDR;
317 #endif
318 
319     ZeroPage = kmem_slab_alloc(PAGE_SIZE, PAGE_SIZE, M_WAITOK|M_ZERO);
320 
321     if (bootverbose)
322 	kprintf("Slab ZoneSize set to %dKB\n", ZoneSize / 1024);
323 }
324 
325 /*
326  * (low level) Initialize slab-related elements in the globaldata structure.
327  *
328  * Occurs after kmeminit().
329  */
330 void
331 slab_gdinit(globaldata_t gd)
332 {
333 	SLGlobalData *slgd;
334 	int i;
335 
336 	slgd = &gd->gd_slab;
337 	for (i = 0; i < NZONES; ++i)
338 		TAILQ_INIT(&slgd->ZoneAry[i]);
339 	TAILQ_INIT(&slgd->FreeZones);
340 	TAILQ_INIT(&slgd->FreeOvZones);
341 }
342 
343 /*
344  * Initialize a malloc type tracking structure.
345  */
346 void
347 malloc_init(void *data)
348 {
349     struct malloc_type *type = data;
350     size_t limsize;
351 
352     if (type->ks_magic != M_MAGIC)
353 	panic("malloc type lacks magic");
354 
355     if (type->ks_limit != 0)
356 	return;
357 
358     if (vmstats.v_page_count == 0)
359 	panic("malloc_init not allowed before vm init");
360 
361     limsize = kmem_lim_size() * (1024 * 1024);
362     type->ks_limit = limsize / 10;
363 
364     spin_lock(&kmemstat_spin);
365     type->ks_next = kmemstatistics;
366     kmemstatistics = type;
367     spin_unlock(&kmemstat_spin);
368 }
369 
370 void
371 malloc_uninit(void *data)
372 {
373     struct malloc_type *type = data;
374     struct malloc_type *t;
375 #ifdef INVARIANTS
376     int i;
377     long ttl;
378 #endif
379 
380     if (type->ks_magic != M_MAGIC)
381 	panic("malloc type lacks magic");
382 
383     if (vmstats.v_page_count == 0)
384 	panic("malloc_uninit not allowed before vm init");
385 
386     if (type->ks_limit == 0)
387 	panic("malloc_uninit on uninitialized type");
388 
389     /* Make sure that all pending kfree()s are finished. */
390     lwkt_synchronize_ipiqs("muninit");
391 
392 #ifdef INVARIANTS
393     /*
394      * memuse is only correct in aggregation.  Due to memory being allocated
395      * on one cpu and freed on another individual array entries may be
396      * negative or positive (canceling each other out).
397      */
398     for (i = ttl = 0; i < ncpus; ++i)
399 	ttl += type->ks_use[i].memuse;
400     if (ttl) {
401 	kprintf("malloc_uninit: %ld bytes of '%s' still allocated on cpu %d\n",
402 	    ttl, type->ks_shortdesc, i);
403     }
404 #endif
405     spin_lock(&kmemstat_spin);
406     if (type == kmemstatistics) {
407 	kmemstatistics = type->ks_next;
408     } else {
409 	for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
410 	    if (t->ks_next == type) {
411 		t->ks_next = type->ks_next;
412 		break;
413 	    }
414 	}
415     }
416     type->ks_next = NULL;
417     type->ks_limit = 0;
418     spin_unlock(&kmemstat_spin);
419 }
420 
421 /*
422  * Increase the kmalloc pool limit for the specified pool.  No changes
423  * are the made if the pool would shrink.
424  */
425 void
426 kmalloc_raise_limit(struct malloc_type *type, size_t bytes)
427 {
428     if (type->ks_limit == 0)
429 	malloc_init(type);
430     if (bytes == 0)
431 	bytes = KvaSize;
432     if (type->ks_limit < bytes)
433 	type->ks_limit = bytes;
434 }
435 
436 void
437 kmalloc_set_unlimited(struct malloc_type *type)
438 {
439     type->ks_limit = kmem_lim_size() * (1024 * 1024);
440 }
441 
442 /*
443  * Dynamically create a malloc pool.  This function is a NOP if *typep is
444  * already non-NULL.
445  */
446 void
447 kmalloc_create(struct malloc_type **typep, const char *descr)
448 {
449 	struct malloc_type *type;
450 
451 	if (*typep == NULL) {
452 		type = kmalloc(sizeof(*type), M_TEMP, M_WAITOK | M_ZERO);
453 		type->ks_magic = M_MAGIC;
454 		type->ks_shortdesc = descr;
455 		malloc_init(type);
456 		*typep = type;
457 	}
458 }
459 
460 /*
461  * Destroy a dynamically created malloc pool.  This function is a NOP if
462  * the pool has already been destroyed.
463  */
464 void
465 kmalloc_destroy(struct malloc_type **typep)
466 {
467 	if (*typep != NULL) {
468 		malloc_uninit(*typep);
469 		kfree(*typep, M_TEMP);
470 		*typep = NULL;
471 	}
472 }
473 
474 /*
475  * Calculate the zone index for the allocation request size and set the
476  * allocation request size to that particular zone's chunk size.
477  */
478 static __inline int
479 zoneindex(unsigned long *bytes, unsigned long *align)
480 {
481     unsigned int n = (unsigned int)*bytes;	/* unsigned for shift opt */
482 
483     if (n < 128) {
484 	*bytes = n = (n + 7) & ~7;
485 	*align = 8;
486 	return(n / 8 - 1);		/* 8 byte chunks, 16 zones */
487     }
488     if (n < 256) {
489 	*bytes = n = (n + 15) & ~15;
490 	*align = 16;
491 	return(n / 16 + 7);
492     }
493     if (n < 8192) {
494 	if (n < 512) {
495 	    *bytes = n = (n + 31) & ~31;
496 	    *align = 32;
497 	    return(n / 32 + 15);
498 	}
499 	if (n < 1024) {
500 	    *bytes = n = (n + 63) & ~63;
501 	    *align = 64;
502 	    return(n / 64 + 23);
503 	}
504 	if (n < 2048) {
505 	    *bytes = n = (n + 127) & ~127;
506 	    *align = 128;
507 	    return(n / 128 + 31);
508 	}
509 	if (n < 4096) {
510 	    *bytes = n = (n + 255) & ~255;
511 	    *align = 256;
512 	    return(n / 256 + 39);
513 	}
514 	*bytes = n = (n + 511) & ~511;
515 	*align = 512;
516 	return(n / 512 + 47);
517     }
518 #if ZALLOC_ZONE_LIMIT > 8192
519     if (n < 16384) {
520 	*bytes = n = (n + 1023) & ~1023;
521 	*align = 1024;
522 	return(n / 1024 + 55);
523     }
524 #endif
525 #if ZALLOC_ZONE_LIMIT > 16384
526     if (n < 32768) {
527 	*bytes = n = (n + 2047) & ~2047;
528 	*align = 2048;
529 	return(n / 2048 + 63);
530     }
531 #endif
532     panic("Unexpected byte count %d", n);
533     return(0);
534 }
535 
536 static __inline void
537 clean_zone_rchunks(SLZone *z)
538 {
539     SLChunk *bchunk;
540 
541     while ((bchunk = z->z_RChunks) != NULL) {
542 	cpu_ccfence();
543 	if (atomic_cmpset_ptr(&z->z_RChunks, bchunk, NULL)) {
544 	    *z->z_LChunksp = bchunk;
545 	    while (bchunk) {
546 		chunk_mark_free(z, bchunk);
547 		z->z_LChunksp = &bchunk->c_Next;
548 		bchunk = bchunk->c_Next;
549 		++z->z_NFree;
550 	    }
551 	    break;
552 	}
553 	/* retry */
554     }
555 }
556 
557 /*
558  * If the zone becomes totally free and is not the only zone listed for a
559  * chunk size we move it to the FreeZones list.  We always leave at least
560  * one zone per chunk size listed, even if it is freeable.
561  *
562  * Do not move the zone if there is an IPI in_flight (z_RCount != 0),
563  * otherwise MP races can result in our free_remote code accessing a
564  * destroyed zone.  The remote end interlocks z_RCount with z_RChunks
565  * so one has to test both z_NFree and z_RCount.
566  *
567  * Since this code can be called from an IPI callback, do *NOT* try to mess
568  * with kernel_map here.  Hysteresis will be performed at kmalloc() time.
569  */
570 static __inline SLZone *
571 check_zone_free(SLGlobalData *slgd, SLZone *z)
572 {
573     SLZone *znext;
574 
575     znext = TAILQ_NEXT(z, z_Entry);
576     if (z->z_NFree == z->z_NMax && z->z_RCount == 0 &&
577 	(TAILQ_FIRST(&slgd->ZoneAry[z->z_ZoneIndex]) != z || znext)) {
578 	int *kup;
579 
580 	TAILQ_REMOVE(&slgd->ZoneAry[z->z_ZoneIndex], z, z_Entry);
581 
582 	z->z_Magic = -1;
583 	TAILQ_INSERT_HEAD(&slgd->FreeZones, z, z_Entry);
584 	++slgd->NFreeZones;
585 	kup = btokup(z);
586 	*kup = 0;
587     }
588     return znext;
589 }
590 
591 #ifdef SLAB_DEBUG
592 /*
593  * Used to debug memory corruption issues.  Record up to (typically 32)
594  * allocation sources for this zone (for a particular chunk size).
595  */
596 
597 static void
598 slab_record_source(SLZone *z, const char *file, int line)
599 {
600     int i;
601     int b = line & (SLAB_DEBUG_ENTRIES - 1);
602 
603     i = b;
604     do {
605 	if (z->z_Sources[i].file == file && z->z_Sources[i].line == line)
606 		return;
607 	if (z->z_Sources[i].file == NULL)
608 		break;
609 	i = (i + 1) & (SLAB_DEBUG_ENTRIES - 1);
610     } while (i != b);
611     z->z_Sources[i].file = file;
612     z->z_Sources[i].line = line;
613 }
614 
615 #endif
616 
617 static __inline unsigned long
618 powerof2_size(unsigned long size)
619 {
620 	int i;
621 
622 	if (size == 0 || powerof2(size))
623 		return size;
624 
625 	i = flsl(size);
626 	return (1UL << i);
627 }
628 
629 /*
630  * kmalloc()	(SLAB ALLOCATOR)
631  *
632  *	Allocate memory via the slab allocator.  If the request is too large,
633  *	or if it page-aligned beyond a certain size, we fall back to the
634  *	KMEM subsystem.  A SLAB tracking descriptor must be specified, use
635  *	&SlabMisc if you don't care.
636  *
637  *	M_RNOWAIT	- don't block.
638  *	M_NULLOK	- return NULL instead of blocking.
639  *	M_ZERO		- zero the returned memory.
640  *	M_USE_RESERVE	- allow greater drawdown of the free list
641  *	M_USE_INTERRUPT_RESERVE - allow the freelist to be exhausted
642  *	M_POWEROF2	- roundup size to the nearest power of 2
643  *
644  * MPSAFE
645  */
646 
647 /* don't let kmalloc macro mess up function declaration */
648 #undef kmalloc
649 
650 #ifdef SLAB_DEBUG
651 void *
652 kmalloc_debug(unsigned long size, struct malloc_type *type, int flags,
653 	      const char *file, int line)
654 #else
655 void *
656 kmalloc(unsigned long size, struct malloc_type *type, int flags)
657 #endif
658 {
659     SLZone *z;
660     SLChunk *chunk;
661     SLGlobalData *slgd;
662     struct globaldata *gd;
663     unsigned long align;
664     int zi;
665 #ifdef INVARIANTS
666     int i;
667 #endif
668 
669     logmemory_quick(malloc_beg);
670     gd = mycpu;
671     slgd = &gd->gd_slab;
672 
673     /*
674      * XXX silly to have this in the critical path.
675      */
676     if (type->ks_limit == 0) {
677 	crit_enter();
678 	malloc_init(type);
679 	crit_exit();
680     }
681     ++type->ks_use[gd->gd_cpuid].calls;
682 
683     /*
684      * Flagged for cache-alignment
685      */
686     if (flags & M_CACHEALIGN) {
687 	if (size < __VM_CACHELINE_SIZE)
688 		size = __VM_CACHELINE_SIZE;
689 	else if (!CAN_CACHEALIGN(size))
690 		flags |= M_POWEROF2;
691     }
692 
693     /*
694      * Flagged to force nearest power-of-2 (higher or same)
695      */
696     if (flags & M_POWEROF2)
697 	size = powerof2_size(size);
698 
699     /*
700      * Handle the case where the limit is reached.  Panic if we can't return
701      * NULL.  The original malloc code looped, but this tended to
702      * simply deadlock the computer.
703      *
704      * ks_loosememuse is an up-only limit that is NOT MP-synchronized, used
705      * to determine if a more complete limit check should be done.  The
706      * actual memory use is tracked via ks_use[cpu].memuse.
707      */
708     while (type->ks_loosememuse >= type->ks_limit) {
709 	int i;
710 	long ttl;
711 
712 	for (i = ttl = 0; i < ncpus; ++i)
713 	    ttl += type->ks_use[i].memuse;
714 	type->ks_loosememuse = ttl;	/* not MP synchronized */
715 	if ((ssize_t)ttl < 0)		/* deal with occassional race */
716 		ttl = 0;
717 	if (ttl >= type->ks_limit) {
718 	    if (flags & M_NULLOK) {
719 		logmemory(malloc_end, NULL, type, size, flags);
720 		return(NULL);
721 	    }
722 	    panic("%s: malloc limit exceeded", type->ks_shortdesc);
723 	}
724     }
725 
726     /*
727      * Handle the degenerate size == 0 case.  Yes, this does happen.
728      * Return a special pointer.  This is to maintain compatibility with
729      * the original malloc implementation.  Certain devices, such as the
730      * adaptec driver, not only allocate 0 bytes, they check for NULL and
731      * also realloc() later on.  Joy.
732      */
733     if (size == 0) {
734 	logmemory(malloc_end, ZERO_LENGTH_PTR, type, size, flags);
735 	return(ZERO_LENGTH_PTR);
736     }
737 
738     /*
739      * Handle hysteresis from prior frees here in malloc().  We cannot
740      * safely manipulate the kernel_map in free() due to free() possibly
741      * being called via an IPI message or from sensitive interrupt code.
742      *
743      * NOTE: ku_pagecnt must be cleared before we free the slab or we
744      *	     might race another cpu allocating the kva and setting
745      *	     ku_pagecnt.
746      */
747     while (slgd->NFreeZones > ZoneRelsThresh && (flags & M_RNOWAIT) == 0) {
748 	crit_enter();
749 	if (slgd->NFreeZones > ZoneRelsThresh) {	/* crit sect race */
750 	    int *kup;
751 
752 	    z = TAILQ_LAST(&slgd->FreeZones, SLZoneList);
753 	    KKASSERT(z != NULL);
754 	    TAILQ_REMOVE(&slgd->FreeZones, z, z_Entry);
755 	    --slgd->NFreeZones;
756 	    kup = btokup(z);
757 	    *kup = 0;
758 	    kmem_slab_free(z, ZoneSize);	/* may block */
759 	    atomic_add_int(&ZoneGenAlloc, -ZoneSize / 1024);
760 	}
761 	crit_exit();
762     }
763 
764     /*
765      * XXX handle oversized frees that were queued from kfree().
766      */
767     while (TAILQ_FIRST(&slgd->FreeOvZones) && (flags & M_RNOWAIT) == 0) {
768 	crit_enter();
769 	if ((z = TAILQ_LAST(&slgd->FreeOvZones, SLZoneList)) != NULL) {
770 	    vm_size_t tsize;
771 
772 	    KKASSERT(z->z_Magic == ZALLOC_OVSZ_MAGIC);
773 	    TAILQ_REMOVE(&slgd->FreeOvZones, z, z_Entry);
774 	    tsize = z->z_ChunkSize;
775 	    kmem_slab_free(z, tsize);	/* may block */
776 	    atomic_add_int(&ZoneBigAlloc, -(int)tsize / 1024);
777 	}
778 	crit_exit();
779     }
780 
781     /*
782      * Handle large allocations directly.  There should not be very many of
783      * these so performance is not a big issue.
784      *
785      * The backend allocator is pretty nasty on a SMP system.   Use the
786      * slab allocator for one and two page-sized chunks even though we lose
787      * some efficiency.  XXX maybe fix mmio and the elf loader instead.
788      */
789     if (size >= ZoneLimit || ((size & PAGE_MASK) == 0 && size > PAGE_SIZE*2)) {
790 	int *kup;
791 
792 	size = round_page(size);
793 	chunk = kmem_slab_alloc(size, PAGE_SIZE, flags);
794 	if (chunk == NULL) {
795 	    logmemory(malloc_end, NULL, type, size, flags);
796 	    return(NULL);
797 	}
798 	atomic_add_int(&ZoneBigAlloc, (int)size / 1024);
799 	flags &= ~M_ZERO;	/* result already zero'd if M_ZERO was set */
800 	flags |= M_PASSIVE_ZERO;
801 	kup = btokup(chunk);
802 	*kup = size / PAGE_SIZE;
803 	crit_enter();
804 	goto done;
805     }
806 
807     /*
808      * Attempt to allocate out of an existing zone.  First try the free list,
809      * then allocate out of unallocated space.  If we find a good zone move
810      * it to the head of the list so later allocations find it quickly
811      * (we might have thousands of zones in the list).
812      *
813      * Note: zoneindex() will panic of size is too large.
814      */
815     zi = zoneindex(&size, &align);
816     KKASSERT(zi < NZONES);
817     crit_enter();
818 
819     if ((z = TAILQ_LAST(&slgd->ZoneAry[zi], SLZoneList)) != NULL) {
820 	/*
821 	 * Locate a chunk - we have to have at least one.  If this is the
822 	 * last chunk go ahead and do the work to retrieve chunks freed
823 	 * from remote cpus, and if the zone is still empty move it off
824 	 * the ZoneAry.
825 	 */
826 	if (--z->z_NFree <= 0) {
827 	    KKASSERT(z->z_NFree == 0);
828 
829 	    /*
830 	     * WARNING! This code competes with other cpus.  It is ok
831 	     * for us to not drain RChunks here but we might as well, and
832 	     * it is ok if more accumulate after we're done.
833 	     *
834 	     * Set RSignal before pulling rchunks off, indicating that we
835 	     * will be moving ourselves off of the ZoneAry.  Remote ends will
836 	     * read RSignal before putting rchunks on thus interlocking
837 	     * their IPI signaling.
838 	     */
839 	    if (z->z_RChunks == NULL)
840 		atomic_swap_int(&z->z_RSignal, 1);
841 
842 	    clean_zone_rchunks(z);
843 
844 	    /*
845 	     * Remove from the zone list if no free chunks remain.
846 	     * Clear RSignal
847 	     */
848 	    if (z->z_NFree == 0) {
849 		TAILQ_REMOVE(&slgd->ZoneAry[zi], z, z_Entry);
850 	    } else {
851 		z->z_RSignal = 0;
852 	    }
853 	}
854 
855 	/*
856 	 * Fast path, we have chunks available in z_LChunks.
857 	 */
858 	chunk = z->z_LChunks;
859 	if (chunk) {
860 		chunk_mark_allocated(z, chunk);
861 		z->z_LChunks = chunk->c_Next;
862 		if (z->z_LChunks == NULL)
863 			z->z_LChunksp = &z->z_LChunks;
864 #ifdef SLAB_DEBUG
865 		slab_record_source(z, file, line);
866 #endif
867 		goto done;
868 	}
869 
870 	/*
871 	 * No chunks are available in LChunks, the free chunk MUST be
872 	 * in the never-before-used memory area, controlled by UIndex.
873 	 *
874 	 * The consequences are very serious if our zone got corrupted so
875 	 * we use an explicit panic rather than a KASSERT.
876 	 */
877 	if (z->z_UIndex + 1 != z->z_NMax)
878 	    ++z->z_UIndex;
879 	else
880 	    z->z_UIndex = 0;
881 
882 	if (z->z_UIndex == z->z_UEndIndex)
883 	    panic("slaballoc: corrupted zone");
884 
885 	chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
886 	if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
887 	    flags &= ~M_ZERO;
888 	    flags |= M_PASSIVE_ZERO;
889 	}
890 	chunk_mark_allocated(z, chunk);
891 #ifdef SLAB_DEBUG
892 	slab_record_source(z, file, line);
893 #endif
894 	goto done;
895     }
896 
897     /*
898      * If all zones are exhausted we need to allocate a new zone for this
899      * index.  Use M_ZERO to take advantage of pre-zerod pages.  Also see
900      * UAlloc use above in regards to M_ZERO.  Note that when we are reusing
901      * a zone from the FreeZones list UAlloc'd data will not be zero'd, and
902      * we do not pre-zero it because we do not want to mess up the L1 cache.
903      *
904      * At least one subsystem, the tty code (see CROUND) expects power-of-2
905      * allocations to be power-of-2 aligned.  We maintain compatibility by
906      * adjusting the base offset below.
907      */
908     {
909 	int off;
910 	int *kup;
911 
912 	if ((z = TAILQ_FIRST(&slgd->FreeZones)) != NULL) {
913 	    TAILQ_REMOVE(&slgd->FreeZones, z, z_Entry);
914 	    --slgd->NFreeZones;
915 	    bzero(z, sizeof(SLZone));
916 	    z->z_Flags |= SLZF_UNOTZEROD;
917 	} else {
918 	    z = kmem_slab_alloc(ZoneSize, ZoneSize, flags|M_ZERO);
919 	    if (z == NULL)
920 		goto fail;
921 	    atomic_add_int(&ZoneGenAlloc, ZoneSize / 1024);
922 	}
923 
924 	/*
925 	 * How big is the base structure?
926 	 */
927 #if defined(INVARIANTS)
928 	/*
929 	 * Make room for z_Bitmap.  An exact calculation is somewhat more
930 	 * complicated so don't make an exact calculation.
931 	 */
932 	off = offsetof(SLZone, z_Bitmap[(ZoneSize / size + 31) / 32]);
933 	bzero(z->z_Bitmap, (ZoneSize / size + 31) / 8);
934 #else
935 	off = sizeof(SLZone);
936 #endif
937 
938 	/*
939 	 * Guarentee power-of-2 alignment for power-of-2-sized chunks.
940 	 * Otherwise properly align the data according to the chunk size.
941 	 */
942 	if (powerof2(size))
943 	    align = size;
944 	off = roundup2(off, align);
945 
946 	z->z_Magic = ZALLOC_SLAB_MAGIC;
947 	z->z_ZoneIndex = zi;
948 	z->z_NMax = (ZoneSize - off) / size;
949 	z->z_NFree = z->z_NMax - 1;
950 	z->z_BasePtr = (char *)z + off;
951 	z->z_UIndex = z->z_UEndIndex = slgd->JunkIndex % z->z_NMax;
952 	z->z_ChunkSize = size;
953 	z->z_CpuGd = gd;
954 	z->z_Cpu = gd->gd_cpuid;
955 	z->z_LChunksp = &z->z_LChunks;
956 #ifdef SLAB_DEBUG
957 	bcopy(z->z_Sources, z->z_AltSources, sizeof(z->z_Sources));
958 	bzero(z->z_Sources, sizeof(z->z_Sources));
959 #endif
960 	chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
961 	TAILQ_INSERT_HEAD(&slgd->ZoneAry[zi], z, z_Entry);
962 	if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
963 	    flags &= ~M_ZERO;	/* already zero'd */
964 	    flags |= M_PASSIVE_ZERO;
965 	}
966 	kup = btokup(z);
967 	*kup = -(z->z_Cpu + 1);	/* -1 to -(N+1) */
968 	chunk_mark_allocated(z, chunk);
969 #ifdef SLAB_DEBUG
970 	slab_record_source(z, file, line);
971 #endif
972 
973 	/*
974 	 * Slide the base index for initial allocations out of the next
975 	 * zone we create so we do not over-weight the lower part of the
976 	 * cpu memory caches.
977 	 */
978 	slgd->JunkIndex = (slgd->JunkIndex + ZALLOC_SLAB_SLIDE)
979 				& (ZALLOC_MAX_ZONE_SIZE - 1);
980     }
981 
982 done:
983     ++type->ks_use[gd->gd_cpuid].inuse;
984     type->ks_use[gd->gd_cpuid].memuse += size;
985     type->ks_use[gd->gd_cpuid].loosememuse += size;
986     if (type->ks_use[gd->gd_cpuid].loosememuse >= ZoneSize) {
987 	/* not MP synchronized */
988 	type->ks_loosememuse += type->ks_use[gd->gd_cpuid].loosememuse;
989 	type->ks_use[gd->gd_cpuid].loosememuse = 0;
990     }
991     crit_exit();
992 
993     if (flags & M_ZERO)
994 	bzero(chunk, size);
995 #ifdef INVARIANTS
996     else if ((flags & (M_ZERO|M_PASSIVE_ZERO)) == 0) {
997 	if (use_malloc_pattern) {
998 	    for (i = 0; i < size; i += sizeof(int)) {
999 		*(int *)((char *)chunk + i) = -1;
1000 	    }
1001 	}
1002 	chunk->c_Next = (void *)-1; /* avoid accidental double-free check */
1003     }
1004 #endif
1005     logmemory(malloc_end, chunk, type, size, flags);
1006     return(chunk);
1007 fail:
1008     crit_exit();
1009     logmemory(malloc_end, NULL, type, size, flags);
1010     return(NULL);
1011 }
1012 
1013 /*
1014  * kernel realloc.  (SLAB ALLOCATOR) (MP SAFE)
1015  *
1016  * Generally speaking this routine is not called very often and we do
1017  * not attempt to optimize it beyond reusing the same pointer if the
1018  * new size fits within the chunking of the old pointer's zone.
1019  */
1020 #ifdef SLAB_DEBUG
1021 void *
1022 krealloc_debug(void *ptr, unsigned long size,
1023 	       struct malloc_type *type, int flags,
1024 	       const char *file, int line)
1025 #else
1026 void *
1027 krealloc(void *ptr, unsigned long size, struct malloc_type *type, int flags)
1028 #endif
1029 {
1030     unsigned long osize;
1031     unsigned long align;
1032     SLZone *z;
1033     void *nptr;
1034     int *kup;
1035 
1036     KKASSERT((flags & M_ZERO) == 0);	/* not supported */
1037 
1038     if (ptr == NULL || ptr == ZERO_LENGTH_PTR)
1039 	return(kmalloc_debug(size, type, flags, file, line));
1040     if (size == 0) {
1041 	kfree(ptr, type);
1042 	return(NULL);
1043     }
1044 
1045     /*
1046      * Handle oversized allocations.  XXX we really should require that a
1047      * size be passed to free() instead of this nonsense.
1048      */
1049     kup = btokup(ptr);
1050     if (*kup > 0) {
1051 	osize = *kup << PAGE_SHIFT;
1052 	if (osize == round_page(size))
1053 	    return(ptr);
1054 	if ((nptr = kmalloc_debug(size, type, flags, file, line)) == NULL)
1055 	    return(NULL);
1056 	bcopy(ptr, nptr, min(size, osize));
1057 	kfree(ptr, type);
1058 	return(nptr);
1059     }
1060 
1061     /*
1062      * Get the original allocation's zone.  If the new request winds up
1063      * using the same chunk size we do not have to do anything.
1064      */
1065     z = (SLZone *)((uintptr_t)ptr & ZoneMask);
1066     kup = btokup(z);
1067     KKASSERT(*kup < 0);
1068     KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
1069 
1070     /*
1071      * Allocate memory for the new request size.  Note that zoneindex has
1072      * already adjusted the request size to the appropriate chunk size, which
1073      * should optimize our bcopy().  Then copy and return the new pointer.
1074      *
1075      * Resizing a non-power-of-2 allocation to a power-of-2 size does not
1076      * necessary align the result.
1077      *
1078      * We can only zoneindex (to align size to the chunk size) if the new
1079      * size is not too large.
1080      */
1081     if (size < ZoneLimit) {
1082 	zoneindex(&size, &align);
1083 	if (z->z_ChunkSize == size)
1084 	    return(ptr);
1085     }
1086     if ((nptr = kmalloc_debug(size, type, flags, file, line)) == NULL)
1087 	return(NULL);
1088     bcopy(ptr, nptr, min(size, z->z_ChunkSize));
1089     kfree(ptr, type);
1090     return(nptr);
1091 }
1092 
1093 /*
1094  * Return the kmalloc limit for this type, in bytes.
1095  */
1096 long
1097 kmalloc_limit(struct malloc_type *type)
1098 {
1099     if (type->ks_limit == 0) {
1100 	crit_enter();
1101 	if (type->ks_limit == 0)
1102 	    malloc_init(type);
1103 	crit_exit();
1104     }
1105     return(type->ks_limit);
1106 }
1107 
1108 /*
1109  * Allocate a copy of the specified string.
1110  *
1111  * (MP SAFE) (MAY BLOCK)
1112  */
1113 #ifdef SLAB_DEBUG
1114 char *
1115 kstrdup_debug(const char *str, struct malloc_type *type,
1116 	      const char *file, int line)
1117 #else
1118 char *
1119 kstrdup(const char *str, struct malloc_type *type)
1120 #endif
1121 {
1122     int zlen;	/* length inclusive of terminating NUL */
1123     char *nstr;
1124 
1125     if (str == NULL)
1126 	return(NULL);
1127     zlen = strlen(str) + 1;
1128     nstr = kmalloc_debug(zlen, type, M_WAITOK, file, line);
1129     bcopy(str, nstr, zlen);
1130     return(nstr);
1131 }
1132 
1133 #ifdef SLAB_DEBUG
1134 char *
1135 kstrndup_debug(const char *str, size_t maxlen, struct malloc_type *type,
1136 	      const char *file, int line)
1137 #else
1138 char *
1139 kstrndup(const char *str, size_t maxlen, struct malloc_type *type)
1140 #endif
1141 {
1142     int zlen;	/* length inclusive of terminating NUL */
1143     char *nstr;
1144 
1145     if (str == NULL)
1146 	return(NULL);
1147     zlen = strnlen(str, maxlen) + 1;
1148     nstr = kmalloc_debug(zlen, type, M_WAITOK, file, line);
1149     bcopy(str, nstr, zlen);
1150     nstr[zlen - 1] = '\0';
1151     return(nstr);
1152 }
1153 
1154 /*
1155  * Notify our cpu that a remote cpu has freed some chunks in a zone that
1156  * we own.  RCount will be bumped so the memory should be good, but validate
1157  * that it really is.
1158  */
1159 static void
1160 kfree_remote(void *ptr)
1161 {
1162     SLGlobalData *slgd;
1163     SLZone *z;
1164     int nfree;
1165     int *kup;
1166 
1167     slgd = &mycpu->gd_slab;
1168     z = ptr;
1169     kup = btokup(z);
1170     KKASSERT(*kup == -((int)mycpuid + 1));
1171     KKASSERT(z->z_RCount > 0);
1172     atomic_subtract_int(&z->z_RCount, 1);
1173 
1174     logmemory(free_rem_beg, z, NULL, 0L, 0);
1175     KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
1176     KKASSERT(z->z_Cpu  == mycpu->gd_cpuid);
1177     nfree = z->z_NFree;
1178 
1179     /*
1180      * Indicate that we will no longer be off of the ZoneAry by
1181      * clearing RSignal.
1182      */
1183     if (z->z_RChunks)
1184 	z->z_RSignal = 0;
1185 
1186     /*
1187      * Atomically extract the bchunks list and then process it back
1188      * into the lchunks list.  We want to append our bchunks to the
1189      * lchunks list and not prepend since we likely do not have
1190      * cache mastership of the related data (not that it helps since
1191      * we are using c_Next).
1192      */
1193     clean_zone_rchunks(z);
1194     if (z->z_NFree && nfree == 0) {
1195 	TAILQ_INSERT_HEAD(&slgd->ZoneAry[z->z_ZoneIndex], z, z_Entry);
1196     }
1197 
1198     check_zone_free(slgd, z);
1199     logmemory(free_rem_end, z, NULL, 0L, 0);
1200 }
1201 
1202 /*
1203  * free (SLAB ALLOCATOR)
1204  *
1205  * Free a memory block previously allocated by malloc.
1206  *
1207  * Note: We do not attempt to update ks_loosememuse as MP races could
1208  * prevent us from checking memory limits in malloc.   YYY we may
1209  * consider updating ks_cpu.loosememuse.
1210  *
1211  * MPSAFE
1212  */
1213 void
1214 kfree(void *ptr, struct malloc_type *type)
1215 {
1216     SLZone *z;
1217     SLChunk *chunk;
1218     SLGlobalData *slgd;
1219     struct globaldata *gd;
1220     int *kup;
1221     unsigned long size;
1222     SLChunk *bchunk;
1223     int rsignal;
1224 
1225     logmemory_quick(free_beg);
1226     gd = mycpu;
1227     slgd = &gd->gd_slab;
1228 
1229     if (ptr == NULL)
1230 	panic("trying to free NULL pointer");
1231 
1232     /*
1233      * Handle special 0-byte allocations
1234      */
1235     if (ptr == ZERO_LENGTH_PTR) {
1236 	logmemory(free_zero, ptr, type, -1UL, 0);
1237 	logmemory_quick(free_end);
1238 	return;
1239     }
1240 
1241     /*
1242      * Panic on bad malloc type
1243      */
1244     if (type->ks_magic != M_MAGIC)
1245 	panic("free: malloc type lacks magic");
1246 
1247     /*
1248      * Handle oversized allocations.  XXX we really should require that a
1249      * size be passed to free() instead of this nonsense.
1250      *
1251      * This code is never called via an ipi.
1252      */
1253     kup = btokup(ptr);
1254     if (*kup > 0) {
1255 	size = *kup << PAGE_SHIFT;
1256 	*kup = 0;
1257 #ifdef INVARIANTS
1258 	KKASSERT(sizeof(weirdary) <= size);
1259 	bcopy(weirdary, ptr, sizeof(weirdary));
1260 #endif
1261 	/*
1262 	 * NOTE: For oversized allocations we do not record the
1263 	 *	     originating cpu.  It gets freed on the cpu calling
1264 	 *	     kfree().  The statistics are in aggregate.
1265 	 *
1266 	 * note: XXX we have still inherited the interrupts-can't-block
1267 	 * assumption.  An interrupt thread does not bump
1268 	 * gd_intr_nesting_level so check TDF_INTTHREAD.  This is
1269 	 * primarily until we can fix softupdate's assumptions about free().
1270 	 */
1271 	crit_enter();
1272 	--type->ks_use[gd->gd_cpuid].inuse;
1273 	type->ks_use[gd->gd_cpuid].memuse -= size;
1274 	if (mycpu->gd_intr_nesting_level ||
1275 	    (gd->gd_curthread->td_flags & TDF_INTTHREAD)) {
1276 	    logmemory(free_ovsz_delayed, ptr, type, size, 0);
1277 	    z = (SLZone *)ptr;
1278 	    z->z_Magic = ZALLOC_OVSZ_MAGIC;
1279 	    z->z_ChunkSize = size;
1280 
1281 	    TAILQ_INSERT_HEAD(&slgd->FreeOvZones, z, z_Entry);
1282 	    crit_exit();
1283 	} else {
1284 	    crit_exit();
1285 	    logmemory(free_ovsz, ptr, type, size, 0);
1286 	    kmem_slab_free(ptr, size);	/* may block */
1287 	    atomic_add_int(&ZoneBigAlloc, -(int)size / 1024);
1288 	}
1289 	logmemory_quick(free_end);
1290 	return;
1291     }
1292 
1293     /*
1294      * Zone case.  Figure out the zone based on the fact that it is
1295      * ZoneSize aligned.
1296      */
1297     z = (SLZone *)((uintptr_t)ptr & ZoneMask);
1298     kup = btokup(z);
1299     KKASSERT(*kup < 0);
1300     KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
1301 
1302     /*
1303      * If we do not own the zone then use atomic ops to free to the
1304      * remote cpu linked list and notify the target zone using a
1305      * passive message.
1306      *
1307      * The target zone cannot be deallocated while we own a chunk of it,
1308      * so the zone header's storage is stable until the very moment
1309      * we adjust z_RChunks.  After that we cannot safely dereference (z).
1310      *
1311      * (no critical section needed)
1312      */
1313     if (z->z_CpuGd != gd) {
1314 	/*
1315 	 * Making these adjustments now allow us to avoid passing (type)
1316 	 * to the remote cpu.  Note that inuse/memuse is being
1317 	 * adjusted on OUR cpu, not the zone cpu, but it should all still
1318 	 * sum up properly and cancel out.
1319 	 */
1320 	crit_enter();
1321 	--type->ks_use[gd->gd_cpuid].inuse;
1322 	type->ks_use[gd->gd_cpuid].memuse -= z->z_ChunkSize;
1323 	crit_exit();
1324 
1325 	/*
1326 	 * WARNING! This code competes with other cpus.  Once we
1327 	 *	    successfully link the chunk to RChunks the remote
1328 	 *	    cpu can rip z's storage out from under us.
1329 	 *
1330 	 *	    Bumping RCount prevents z's storage from getting
1331 	 *	    ripped out.
1332 	 */
1333 	rsignal = z->z_RSignal;
1334 	cpu_lfence();
1335 	if (rsignal)
1336 		atomic_add_int(&z->z_RCount, 1);
1337 
1338 	chunk = ptr;
1339 	for (;;) {
1340 	    bchunk = z->z_RChunks;
1341 	    cpu_ccfence();
1342 	    chunk->c_Next = bchunk;
1343 	    cpu_sfence();
1344 
1345 	    if (atomic_cmpset_ptr(&z->z_RChunks, bchunk, chunk))
1346 		break;
1347 	}
1348 
1349 	/*
1350 	 * We have to signal the remote cpu if our actions will cause
1351 	 * the remote zone to be placed back on ZoneAry so it can
1352 	 * move the zone back on.
1353 	 *
1354 	 * We only need to deal with NULL->non-NULL RChunk transitions
1355 	 * and only if z_RSignal is set.  We interlock by reading rsignal
1356 	 * before adding our chunk to RChunks.  This should result in
1357 	 * virtually no IPI traffic.
1358 	 *
1359 	 * We can use a passive IPI to reduce overhead even further.
1360 	 */
1361 	if (bchunk == NULL && rsignal) {
1362 	    logmemory(free_request, ptr, type,
1363 		      (unsigned long)z->z_ChunkSize, 0);
1364 	    lwkt_send_ipiq_passive(z->z_CpuGd, kfree_remote, z);
1365 	    /* z can get ripped out from under us from this point on */
1366 	} else if (rsignal) {
1367 	    atomic_subtract_int(&z->z_RCount, 1);
1368 	    /* z can get ripped out from under us from this point on */
1369 	}
1370 	logmemory_quick(free_end);
1371 	return;
1372     }
1373 
1374     /*
1375      * kfree locally
1376      */
1377     logmemory(free_chunk, ptr, type, (unsigned long)z->z_ChunkSize, 0);
1378 
1379     crit_enter();
1380     chunk = ptr;
1381     chunk_mark_free(z, chunk);
1382 
1383     /*
1384      * Put weird data into the memory to detect modifications after freeing,
1385      * illegal pointer use after freeing (we should fault on the odd address),
1386      * and so forth.  XXX needs more work, see the old malloc code.
1387      */
1388 #ifdef INVARIANTS
1389     if (z->z_ChunkSize < sizeof(weirdary))
1390 	bcopy(weirdary, chunk, z->z_ChunkSize);
1391     else
1392 	bcopy(weirdary, chunk, sizeof(weirdary));
1393 #endif
1394 
1395     /*
1396      * Add this free non-zero'd chunk to a linked list for reuse.  Add
1397      * to the front of the linked list so it is more likely to be
1398      * reallocated, since it is already in our L1 cache.
1399      */
1400 #ifdef INVARIANTS
1401     if ((vm_offset_t)chunk < KvaStart || (vm_offset_t)chunk >= KvaEnd)
1402 	panic("BADFREE %p", chunk);
1403 #endif
1404     chunk->c_Next = z->z_LChunks;
1405     z->z_LChunks = chunk;
1406     if (chunk->c_Next == NULL)
1407 	z->z_LChunksp = &chunk->c_Next;
1408 
1409 #ifdef INVARIANTS
1410     if (chunk->c_Next && (vm_offset_t)chunk->c_Next < KvaStart)
1411 	panic("BADFREE2");
1412 #endif
1413 
1414     /*
1415      * Bump the number of free chunks.  If it becomes non-zero the zone
1416      * must be added back onto the appropriate list.  A fully allocated
1417      * zone that sees its first free is considered 'mature' and is placed
1418      * at the head, giving the system time to potentially free the remaining
1419      * entries even while other allocations are going on and making the zone
1420      * freeable.
1421      */
1422     if (z->z_NFree++ == 0) {
1423 	if (SlabFreeToTail)
1424 	    TAILQ_INSERT_TAIL(&slgd->ZoneAry[z->z_ZoneIndex], z, z_Entry);
1425 	else
1426 	    TAILQ_INSERT_HEAD(&slgd->ZoneAry[z->z_ZoneIndex], z, z_Entry);
1427     }
1428 
1429     --type->ks_use[gd->gd_cpuid].inuse;
1430     type->ks_use[gd->gd_cpuid].memuse -= z->z_ChunkSize;
1431 
1432     check_zone_free(slgd, z);
1433     logmemory_quick(free_end);
1434     crit_exit();
1435 }
1436 
1437 /*
1438  * Cleanup slabs which are hanging around due to RChunks or which are wholely
1439  * free and can be moved to the free list if not moved by other means.
1440  *
1441  * Called once every 10 seconds on all cpus.
1442  */
1443 void
1444 slab_cleanup(void)
1445 {
1446     SLGlobalData *slgd = &mycpu->gd_slab;
1447     SLZone *z;
1448     int i;
1449 
1450     crit_enter();
1451     for (i = 0; i < NZONES; ++i) {
1452 	if ((z = TAILQ_FIRST(&slgd->ZoneAry[i])) == NULL)
1453 		continue;
1454 
1455 	/*
1456 	 * Scan zones.
1457 	 */
1458 	while (z) {
1459 	    /*
1460 	     * Shift all RChunks to the end of the LChunks list.  This is
1461 	     * an O(1) operation.
1462 	     *
1463 	     * Then free the zone if possible.
1464 	     */
1465 	    clean_zone_rchunks(z);
1466 	    z = check_zone_free(slgd, z);
1467 	}
1468     }
1469     crit_exit();
1470 }
1471 
1472 #if defined(INVARIANTS)
1473 
1474 /*
1475  * Helper routines for sanity checks
1476  */
1477 static void
1478 chunk_mark_allocated(SLZone *z, void *chunk)
1479 {
1480     int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
1481     uint32_t *bitptr;
1482 
1483     KKASSERT((((intptr_t)chunk ^ (intptr_t)z) & ZoneMask) == 0);
1484     KASSERT(bitdex >= 0 && bitdex < z->z_NMax,
1485 	    ("memory chunk %p bit index %d is illegal", chunk, bitdex));
1486     bitptr = &z->z_Bitmap[bitdex >> 5];
1487     bitdex &= 31;
1488     KASSERT((*bitptr & (1 << bitdex)) == 0,
1489 	    ("memory chunk %p is already allocated!", chunk));
1490     *bitptr |= 1 << bitdex;
1491 }
1492 
1493 static void
1494 chunk_mark_free(SLZone *z, void *chunk)
1495 {
1496     int bitdex = ((char *)chunk - (char *)z->z_BasePtr) / z->z_ChunkSize;
1497     uint32_t *bitptr;
1498 
1499     KKASSERT((((intptr_t)chunk ^ (intptr_t)z) & ZoneMask) == 0);
1500     KASSERT(bitdex >= 0 && bitdex < z->z_NMax,
1501 	    ("memory chunk %p bit index %d is illegal!", chunk, bitdex));
1502     bitptr = &z->z_Bitmap[bitdex >> 5];
1503     bitdex &= 31;
1504     KASSERT((*bitptr & (1 << bitdex)) != 0,
1505 	    ("memory chunk %p is already free!", chunk));
1506     *bitptr &= ~(1 << bitdex);
1507 }
1508 
1509 #endif
1510 
1511 /*
1512  * kmem_slab_alloc()
1513  *
1514  *	Directly allocate and wire kernel memory in PAGE_SIZE chunks with the
1515  *	specified alignment.  M_* flags are expected in the flags field.
1516  *
1517  *	Alignment must be a multiple of PAGE_SIZE.
1518  *
1519  *	NOTE! XXX For the moment we use vm_map_entry_reserve/release(),
1520  *	but when we move zalloc() over to use this function as its backend
1521  *	we will have to switch to kreserve/krelease and call reserve(0)
1522  *	after the new space is made available.
1523  *
1524  *	Interrupt code which has preempted other code is not allowed to
1525  *	use PQ_CACHE pages.  However, if an interrupt thread is run
1526  *	non-preemptively or blocks and then runs non-preemptively, then
1527  *	it is free to use PQ_CACHE pages.  <--- may not apply any longer XXX
1528  */
1529 static void *
1530 kmem_slab_alloc(vm_size_t size, vm_offset_t align, int flags)
1531 {
1532     vm_size_t i;
1533     vm_offset_t addr;
1534     int count, vmflags, base_vmflags;
1535     vm_page_t mbase = NULL;
1536     vm_page_t m;
1537     thread_t td;
1538 
1539     size = round_page(size);
1540     addr = vm_map_min(&kernel_map);
1541 
1542     count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1543     crit_enter();
1544     vm_map_lock(&kernel_map);
1545     if (vm_map_findspace(&kernel_map, addr, size, align, 0, &addr)) {
1546 	vm_map_unlock(&kernel_map);
1547 	if ((flags & M_NULLOK) == 0)
1548 	    panic("kmem_slab_alloc(): kernel_map ran out of space!");
1549 	vm_map_entry_release(count);
1550 	crit_exit();
1551 	return(NULL);
1552     }
1553 
1554     /*
1555      * kernel_object maps 1:1 to kernel_map.
1556      */
1557     vm_object_hold(&kernel_object);
1558     vm_object_reference_locked(&kernel_object);
1559     vm_map_insert(&kernel_map, &count,
1560 		  &kernel_object, NULL,
1561 		  addr, NULL,
1562 		  addr, addr + size,
1563 		  VM_MAPTYPE_NORMAL,
1564 		  VM_SUBSYS_KMALLOC,
1565 		  VM_PROT_ALL, VM_PROT_ALL, 0);
1566     vm_object_drop(&kernel_object);
1567     vm_map_set_wired_quick(&kernel_map, addr, size, &count);
1568     vm_map_unlock(&kernel_map);
1569 
1570     td = curthread;
1571 
1572     base_vmflags = 0;
1573     if (flags & M_ZERO)
1574         base_vmflags |= VM_ALLOC_ZERO;
1575     if (flags & M_USE_RESERVE)
1576 	base_vmflags |= VM_ALLOC_SYSTEM;
1577     if (flags & M_USE_INTERRUPT_RESERVE)
1578         base_vmflags |= VM_ALLOC_INTERRUPT;
1579     if ((flags & (M_RNOWAIT|M_WAITOK)) == 0) {
1580 	panic("kmem_slab_alloc: bad flags %08x (%p)",
1581 	      flags, ((int **)&size)[-1]);
1582     }
1583 
1584     /*
1585      * Allocate the pages.  Do not map them yet.  VM_ALLOC_NORMAL can only
1586      * be set if we are not preempting.
1587      *
1588      * VM_ALLOC_SYSTEM is automatically set if we are preempting and
1589      * M_WAITOK was specified as an alternative (i.e. M_USE_RESERVE is
1590      * implied in this case), though I'm not sure if we really need to
1591      * do that.
1592      */
1593     vmflags = base_vmflags;
1594     if (flags & M_WAITOK) {
1595 	if (td->td_preempted)
1596 	    vmflags |= VM_ALLOC_SYSTEM;
1597 	else
1598 	    vmflags |= VM_ALLOC_NORMAL;
1599     }
1600 
1601     vm_object_hold(&kernel_object);
1602     for (i = 0; i < size; i += PAGE_SIZE) {
1603 	m = vm_page_alloc(&kernel_object, OFF_TO_IDX(addr + i), vmflags);
1604 	if (i == 0)
1605 		mbase = m;
1606 
1607 	/*
1608 	 * If the allocation failed we either return NULL or we retry.
1609 	 *
1610 	 * If M_WAITOK is specified we wait for more memory and retry.
1611 	 * If M_WAITOK is specified from a preemption we yield instead of
1612 	 * wait.  Livelock will not occur because the interrupt thread
1613 	 * will not be preempting anyone the second time around after the
1614 	 * yield.
1615 	 */
1616 	if (m == NULL) {
1617 	    if (flags & M_WAITOK) {
1618 		if (td->td_preempted) {
1619 		    lwkt_switch();
1620 		} else {
1621 		    vm_wait(0);
1622 		}
1623 		i -= PAGE_SIZE;	/* retry */
1624 		continue;
1625 	    }
1626 	    break;
1627 	}
1628     }
1629 
1630     /*
1631      * Check and deal with an allocation failure
1632      */
1633     if (i != size) {
1634 	while (i != 0) {
1635 	    i -= PAGE_SIZE;
1636 	    m = vm_page_lookup(&kernel_object, OFF_TO_IDX(addr + i));
1637 	    /* page should already be busy */
1638 	    vm_page_free(m);
1639 	}
1640 	vm_map_lock(&kernel_map);
1641 	vm_map_delete(&kernel_map, addr, addr + size, &count);
1642 	vm_map_unlock(&kernel_map);
1643 	vm_object_drop(&kernel_object);
1644 
1645 	vm_map_entry_release(count);
1646 	crit_exit();
1647 	return(NULL);
1648     }
1649 
1650     /*
1651      * Success!
1652      *
1653      * NOTE: The VM pages are still busied.  mbase points to the first one
1654      *	     but we have to iterate via vm_page_next()
1655      */
1656     vm_object_drop(&kernel_object);
1657     crit_exit();
1658 
1659     /*
1660      * Enter the pages into the pmap and deal with M_ZERO.
1661      */
1662     m = mbase;
1663     i = 0;
1664 
1665     while (i < size) {
1666 	/*
1667 	 * page should already be busy
1668 	 */
1669 	m->valid = VM_PAGE_BITS_ALL;
1670 	vm_page_wire(m);
1671 	pmap_enter(&kernel_pmap, addr + i, m,
1672 		   VM_PROT_ALL | VM_PROT_NOSYNC, 1, NULL);
1673 	if (flags & M_ZERO)
1674 		pagezero((char *)addr + i);
1675 	KKASSERT(m->flags & (PG_WRITEABLE | PG_MAPPED));
1676 	vm_page_flag_set(m, PG_REFERENCED);
1677 	vm_page_wakeup(m);
1678 
1679 	i += PAGE_SIZE;
1680 	vm_object_hold(&kernel_object);
1681 	m = vm_page_next(m);
1682 	vm_object_drop(&kernel_object);
1683     }
1684     smp_invltlb();
1685     vm_map_entry_release(count);
1686     atomic_add_long(&SlabsAllocated, 1);
1687     return((void *)addr);
1688 }
1689 
1690 /*
1691  * kmem_slab_free()
1692  */
1693 static void
1694 kmem_slab_free(void *ptr, vm_size_t size)
1695 {
1696     crit_enter();
1697     vm_map_remove(&kernel_map, (vm_offset_t)ptr, (vm_offset_t)ptr + size);
1698     atomic_add_long(&SlabsFreed, 1);
1699     crit_exit();
1700 }
1701