Rename:
[dragonfly.git] / sys / kern / kern_slaballoc.c
CommitLineData
a108bf71
MD
1/*
2 * KERN_SLABALLOC.C - Kernel SLAB memory allocator
3 *
4 * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 *
074dcfe8 28 * $DragonFly: src/sys/kern/kern_slaballoc.c,v 1.6 2003/09/26 19:23:31 dillon Exp $
a108bf71
MD
29 *
30 * This module implements a slab allocator drop-in replacement for the
31 * kernel malloc().
32 *
33 * A slab allocator reserves a ZONE for each chunk size, then lays the
34 * chunks out in an array within the zone. Allocation and deallocation
35 * is nearly instantanious, and fragmentation/overhead losses are limited
36 * to a fixed worst-case amount.
37 *
38 * The downside of this slab implementation is in the chunk size
39 * multiplied by the number of zones. ~80 zones * 128K = 10MB of VM per cpu.
40 * In a kernel implementation all this memory will be physical so
41 * the zone size is adjusted downward on machines with less physical
42 * memory. The upside is that overhead is bounded... this is the *worst*
43 * case overhead.
44 *
45 * Slab management is done on a per-cpu basis and no locking or mutexes
46 * are required, only a critical section. When one cpu frees memory
47 * belonging to another cpu's slab manager an asynchronous IPI message
48 * will be queued to execute the operation. In addition, both the
49 * high level slab allocator and the low level zone allocator optimize
50 * M_ZERO requests, and the slab allocator does not have to pre initialize
51 * the linked list of chunks.
52 *
53 * XXX Balancing is needed between cpus. Balance will be handled through
54 * asynchronous IPIs primarily by reassigning the z_Cpu ownership of chunks.
55 *
56 * XXX If we have to allocate a new zone and M_USE_RESERVE is set, use of
57 * the new zone should be restricted to M_USE_RESERVE requests only.
58 *
59 * Alloc Size Chunking Number of zones
60 * 0-127 8 16
61 * 128-255 16 8
62 * 256-511 32 8
63 * 512-1023 64 8
64 * 1024-2047 128 8
65 * 2048-4095 256 8
66 * 4096-8191 512 8
67 * 8192-16383 1024 8
68 * 16384-32767 2048 8
69 * (if PAGE_SIZE is 4K the maximum zone allocation is 16383)
70 *
71 * Allocations >= ZALLOC_ZONE_LIMIT go directly to kmem.
72 *
73 * API REQUIREMENTS AND SIDE EFFECTS
74 *
75 * To operate as a drop-in replacement to the FreeBSD-4.x malloc() we
76 * have remained compatible with the following API requirements:
77 *
78 * + small power-of-2 sized allocations are power-of-2 aligned (kern_tty)
3d177b31 79 * + all power-of-2 sized allocations are power-of-2 aligned (twe)
a108bf71
MD
80 * + malloc(0) is allowed and returns non-NULL (ahc driver)
81 * + ability to allocate arbitrarily large chunks of memory
82 */
83
84#include "opt_vm.h"
85
074dcfe8 86#if !defined(NO_SLAB_ALLOCATOR)
a108bf71 87
074dcfe8
MD
88#if defined(USE_KMEM_MAP)
89#error "If you define USE_KMEM_MAP you must also define NO_SLAB_ALLOCATOR"
a108bf71
MD
90#endif
91
92#include <sys/param.h>
93#include <sys/systm.h>
94#include <sys/kernel.h>
95#include <sys/slaballoc.h>
96#include <sys/mbuf.h>
97#include <sys/vmmeter.h>
98#include <sys/lock.h>
99#include <sys/thread.h>
100#include <sys/globaldata.h>
101
102#include <vm/vm.h>
103#include <vm/vm_param.h>
104#include <vm/vm_kern.h>
105#include <vm/vm_extern.h>
106#include <vm/vm_object.h>
107#include <vm/pmap.h>
108#include <vm/vm_map.h>
109#include <vm/vm_page.h>
110#include <vm/vm_pageout.h>
111
112#include <machine/cpu.h>
113
114#include <sys/thread2.h>
115
116#define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
117
118/*
119 * Fixed globals (not per-cpu)
120 */
121static int ZoneSize;
122static int ZonePageCount;
123static int ZonePageLimit;
124static int ZoneMask;
125static struct malloc_type *kmemstatistics;
126static struct kmemusage *kmemusage;
127static int32_t weirdary[16];
128
129static void *kmem_slab_alloc(vm_size_t bytes, vm_offset_t align, int flags);
130static void kmem_slab_free(void *ptr, vm_size_t bytes);
131
132/*
133 * Misc constants. Note that allocations that are exact multiples of
134 * PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
135 * IN_SAME_PAGE_MASK is used to sanity-check the per-page free lists.
136 */
137#define MIN_CHUNK_SIZE 8 /* in bytes */
138#define MIN_CHUNK_MASK (MIN_CHUNK_SIZE - 1)
139#define ZONE_RELS_THRESH 2 /* threshold number of zones */
140#define IN_SAME_PAGE_MASK (~(intptr_t)PAGE_MASK | MIN_CHUNK_MASK)
141
142/*
143 * The WEIRD_ADDR is used as known text to copy into free objects to
144 * try to create deterministic failure cases if the data is accessed after
145 * free.
146 */
147#define WEIRD_ADDR 0xdeadc0de
148#define MAX_COPY sizeof(weirdary)
149#define ZERO_LENGTH_PTR ((void *)-8)
150
151/*
152 * Misc global malloc buckets
153 */
154
155MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
156MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
157MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
158
159MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
160MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
161
162/*
163 * Initialize the slab memory allocator. We have to choose a zone size based
164 * on available physical memory. We choose a zone side which is approximately
165 * 1/1024th of our memory, so if we have 128MB of ram we have a zone size of
166 * 128K. The zone size is limited to the bounds set in slaballoc.h
167 * (typically 32K min, 128K max).
168 */
169static void kmeminit(void *dummy);
170
171SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
172
173static void
174kmeminit(void *dummy)
175{
176 vm_poff_t limsize;
177 int usesize;
178 int i;
179 vm_pindex_t npg;
180
181 limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
182 if (limsize > VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS)
183 limsize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
184
185 usesize = (int)(limsize / 1024); /* convert to KB */
186
187 ZoneSize = ZALLOC_MIN_ZONE_SIZE;
188 while (ZoneSize < ZALLOC_MAX_ZONE_SIZE && (ZoneSize << 1) < usesize)
189 ZoneSize <<= 1;
190 ZoneMask = ZoneSize - 1;
191 ZonePageLimit = PAGE_SIZE * 4;
192 ZonePageCount = ZoneSize / PAGE_SIZE;
193
194 npg = (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) / PAGE_SIZE;
195 kmemusage = kmem_slab_alloc(npg * sizeof(struct kmemusage), PAGE_SIZE, M_ZERO);
196
197 for (i = 0; i < arysize(weirdary); ++i)
198 weirdary[i] = WEIRD_ADDR;
199
200 if (bootverbose)
201 printf("Slab ZoneSize set to %dKB\n", ZoneSize / 1024);
202}
203
204/*
205 * Initialize a malloc type tracking structure. NOTE! counters and such
206 * need to be made per-cpu (maybe with a MAXCPU array).
207 */
208void
209malloc_init(void *data)
210{
211 struct malloc_type *type = data;
212 vm_poff_t limsize;
213
214 if (type->ks_magic != M_MAGIC)
215 panic("malloc type lacks magic");
216
217 if (type->ks_limit != 0)
218 return;
219
220 if (vmstats.v_page_count == 0)
221 panic("malloc_init not allowed before vm init");
222
223 limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
224 if (limsize > VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS)
225 limsize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
226 type->ks_limit = limsize / 10;
227
228 type->ks_next = kmemstatistics;
229 kmemstatistics = type;
230}
231
232void
233malloc_uninit(void *data)
234{
235 struct malloc_type *type = data;
236 struct malloc_type *t;
237
238 if (type->ks_magic != M_MAGIC)
239 panic("malloc type lacks magic");
240
241 if (vmstats.v_page_count == 0)
242 panic("malloc_uninit not allowed before vm init");
243
244 if (type->ks_limit == 0)
245 panic("malloc_uninit on uninitialized type");
246
247#ifdef INVARIANTS
248 if (type->ks_memuse != 0) {
249 printf("malloc_uninit: %ld bytes of '%s' still allocated\n",
250 type->ks_memuse, type->ks_shortdesc);
251 }
252#endif
253 if (type == kmemstatistics) {
254 kmemstatistics = type->ks_next;
255 } else {
256 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
257 if (t->ks_next == type) {
258 t->ks_next = type->ks_next;
259 break;
260 }
261 }
262 }
263 type->ks_next = NULL;
264 type->ks_limit = 0;
265}
266
267/*
268 * Calculate the zone index for the allocation request size and set the
269 * allocation request size to that particular zone's chunk size.
270 */
271static __inline int
272zoneindex(unsigned long *bytes)
273{
274 unsigned int n = (unsigned int)*bytes; /* unsigned for shift opt */
275 if (n < 128) {
276 *bytes = n = (n + 7) & ~7;
277 return(n / 8 - 1); /* 8 byte chunks, 16 zones */
278 }
279 if (n < 256) {
280 *bytes = n = (n + 15) & ~15;
281 return(n / 16 + 7);
282 }
283 if (n < 8192) {
284 if (n < 512) {
285 *bytes = n = (n + 31) & ~31;
286 return(n / 32 + 15);
287 }
288 if (n < 1024) {
289 *bytes = n = (n + 63) & ~63;
290 return(n / 64 + 23);
291 }
292 if (n < 2048) {
293 *bytes = n = (n + 127) & ~127;
294 return(n / 128 + 31);
295 }
296 if (n < 4096) {
297 *bytes = n = (n + 255) & ~255;
298 return(n / 256 + 39);
299 }
300 *bytes = n = (n + 511) & ~511;
301 return(n / 512 + 47);
302 }
303#if ZALLOC_ZONE_LIMIT > 8192
304 if (n < 16384) {
305 *bytes = n = (n + 1023) & ~1023;
306 return(n / 1024 + 55);
307 }
308#endif
309#if ZALLOC_ZONE_LIMIT > 16384
310 if (n < 32768) {
311 *bytes = n = (n + 2047) & ~2047;
312 return(n / 2048 + 63);
313 }
314#endif
315 panic("Unexpected byte count %d", n);
316 return(0);
317}
318
319/*
320 * malloc() (SLAB ALLOCATOR)
321 *
322 * Allocate memory via the slab allocator. If the request is too large,
323 * or if it page-aligned beyond a certain size, we fall back to the
324 * KMEM subsystem. A SLAB tracking descriptor must be specified, use
325 * &SlabMisc if you don't care.
326 *
327 * M_NOWAIT - return NULL instead of blocking.
328 * M_ZERO - zero the returned memory.
329 * M_USE_RESERVE - allocate out of the system reserve if necessary
330 */
331void *
332malloc(unsigned long size, struct malloc_type *type, int flags)
333{
334 SLZone *z;
335 SLChunk *chunk;
336 SLGlobalData *slgd;
337 int zi;
338
339 slgd = &mycpu->gd_slab;
340
341 /*
342 * XXX silly to have this in the critical path.
343 */
344 if (type->ks_limit == 0) {
345 crit_enter();
346 if (type->ks_limit == 0)
347 malloc_init(type);
348 crit_exit();
349 }
350 ++type->ks_calls;
351
352 /*
353 * Handle the case where the limit is reached. Panic if can't return
354 * NULL. XXX the original malloc code looped, but this tended to
355 * simply deadlock the computer.
356 */
357 while (type->ks_memuse >= type->ks_limit) {
358 if (flags & (M_NOWAIT|M_NULLOK))
359 return(NULL);
360 panic("%s: malloc limit exceeded", type->ks_shortdesc);
361 }
362
363 /*
364 * Handle the degenerate size == 0 case. Yes, this does happen.
365 * Return a special pointer. This is to maintain compatibility with
366 * the original malloc implementation. Certain devices, such as the
367 * adaptec driver, not only allocate 0 bytes, they check for NULL and
368 * also realloc() later on. Joy.
369 */
370 if (size == 0)
371 return(ZERO_LENGTH_PTR);
372
a7cf0021
MD
373 /*
374 * Handle hysteresis from prior frees here in malloc(). We cannot
375 * safely manipulate the kernel_map in free() due to free() possibly
376 * being called via an IPI message or from sensitive interrupt code.
377 */
378 while (slgd->NFreeZones > ZONE_RELS_THRESH && (flags & M_NOWAIT) == 0) {
379 crit_enter();
380 if (slgd->NFreeZones > ZONE_RELS_THRESH) { /* crit sect race */
381 z = slgd->FreeZones;
382 slgd->FreeZones = z->z_Next;
383 --slgd->NFreeZones;
384 kmem_slab_free(z, ZoneSize); /* may block */
385 }
386 crit_exit();
387 }
388
a108bf71
MD
389 /*
390 * Handle large allocations directly. There should not be very many of
391 * these so performance is not a big issue.
392 *
393 * Guarentee page alignment for allocations in multiples of PAGE_SIZE
394 */
395 if (size >= ZALLOC_ZONE_LIMIT || (size & PAGE_MASK) == 0) {
396 struct kmemusage *kup;
397
398 size = round_page(size);
399 chunk = kmem_slab_alloc(size, PAGE_SIZE, flags);
400 if (chunk == NULL)
401 return(NULL);
402 flags &= ~M_ZERO; /* result already zero'd if M_ZERO was set */
403 kup = btokup(chunk);
404 kup->ku_pagecnt = size / PAGE_SIZE;
405 crit_enter();
406 goto done;
407 }
408
409 /*
410 * Attempt to allocate out of an existing zone. First try the free list,
411 * then allocate out of unallocated space. If we find a good zone move
412 * it to the head of the list so later allocations find it quickly
413 * (we might have thousands of zones in the list).
414 *
415 * Note: zoneindex() will panic of size is too large.
416 */
417 zi = zoneindex(&size);
418 KKASSERT(zi < NZONES);
419 crit_enter();
420 if ((z = slgd->ZoneAry[zi]) != NULL) {
421 KKASSERT(z->z_NFree > 0);
422
423 /*
424 * Remove us from the ZoneAry[] when we become empty
425 */
426 if (--z->z_NFree == 0) {
427 slgd->ZoneAry[zi] = z->z_Next;
428 z->z_Next = NULL;
429 }
430
431 /*
432 * Locate a chunk in a free page. This attempts to localize
433 * reallocations into earlier pages without us having to sort
434 * the chunk list. A chunk may still overlap a page boundary.
435 */
436 while (z->z_FirstFreePg < ZonePageCount) {
437 if ((chunk = z->z_PageAry[z->z_FirstFreePg]) != NULL) {
438#ifdef DIAGNOSTIC
439 /*
440 * Diagnostic: c_Next is not total garbage.
441 */
442 KKASSERT(chunk->c_Next == NULL ||
443 ((intptr_t)chunk->c_Next & IN_SAME_PAGE_MASK) ==
444 ((intptr_t)chunk & IN_SAME_PAGE_MASK));
445#endif
6ab8e1da
MD
446#ifdef INVARIANTS
447 if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
a108bf71 448 panic("chunk %p FFPG %d/%d", chunk, z->z_FirstFreePg, ZonePageCount);
6ab8e1da 449 if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
a108bf71 450 panic("chunkNEXT %p %p FFPG %d/%d", chunk, chunk->c_Next, z->z_FirstFreePg, ZonePageCount);
6ab8e1da 451#endif
a108bf71
MD
452 z->z_PageAry[z->z_FirstFreePg] = chunk->c_Next;
453 goto done;
454 }
455 ++z->z_FirstFreePg;
456 }
457
458 /*
1c5ca4f3
MD
459 * No chunks are available but NFree said we had some memory, so
460 * it must be available in the never-before-used-memory area
461 * governed by UIndex. The consequences are very serious if our zone
462 * got corrupted so we use an explicit panic rather then a KASSERT.
a108bf71 463 */
1c5ca4f3
MD
464 if (z->z_UIndex + 1 != z->z_NMax)
465 z->z_UIndex = z->z_UIndex + 1;
466 else
467 z->z_UIndex = 0;
468 if (z->z_UIndex == z->z_UEndIndex)
469 panic("slaballoc: corrupted zone");
470 chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
6ab8e1da
MD
471 if ((z->z_Flags & SLZF_UNOTZEROD) == 0)
472 flags &= ~M_ZERO;
a108bf71
MD
473 goto done;
474 }
475
476 /*
477 * If all zones are exhausted we need to allocate a new zone for this
478 * index. Use M_ZERO to take advantage of pre-zerod pages. Also see
6ab8e1da
MD
479 * UAlloc use above in regards to M_ZERO. Note that when we are reusing
480 * a zone from the FreeZones list UAlloc'd data will not be zero'd, and
481 * we do not pre-zero it because we do not want to mess up the L1 cache.
a108bf71
MD
482 *
483 * At least one subsystem, the tty code (see CROUND) expects power-of-2
484 * allocations to be power-of-2 aligned. We maintain compatibility by
485 * adjusting the base offset below.
486 */
487 {
488 int off;
489
490 if ((z = slgd->FreeZones) != NULL) {
491 slgd->FreeZones = z->z_Next;
492 --slgd->NFreeZones;
493 bzero(z, sizeof(SLZone));
6ab8e1da 494 z->z_Flags |= SLZF_UNOTZEROD;
a108bf71
MD
495 } else {
496 z = kmem_slab_alloc(ZoneSize, ZoneSize, flags|M_ZERO);
497 if (z == NULL)
498 goto fail;
499 }
500
501 /*
502 * Guarentee power-of-2 alignment for power-of-2-sized chunks.
503 * Otherwise just 8-byte align the data.
504 */
505 if ((size | (size - 1)) + 1 == (size << 1))
506 off = (sizeof(SLZone) + size - 1) & ~(size - 1);
507 else
508 off = (sizeof(SLZone) + MIN_CHUNK_MASK) & ~MIN_CHUNK_MASK;
509 z->z_Magic = ZALLOC_SLAB_MAGIC;
510 z->z_ZoneIndex = zi;
511 z->z_NMax = (ZoneSize - off) / size;
512 z->z_NFree = z->z_NMax - 1;
1c5ca4f3
MD
513 z->z_BasePtr = (char *)z + off;
514 z->z_UIndex = z->z_UEndIndex = slgd->JunkIndex % z->z_NMax;
a108bf71
MD
515 z->z_ChunkSize = size;
516 z->z_FirstFreePg = ZonePageCount;
517 z->z_Cpu = mycpu->gd_cpuid;
1c5ca4f3 518 chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
a108bf71
MD
519 z->z_Next = slgd->ZoneAry[zi];
520 slgd->ZoneAry[zi] = z;
6ab8e1da
MD
521 if ((z->z_Flags & SLZF_UNOTZEROD) == 0)
522 flags &= ~M_ZERO; /* already zero'd */
1c5ca4f3
MD
523
524 /*
525 * Slide the base index for initial allocations out of the next
526 * zone we create so we do not over-weight the lower part of the
527 * cpu memory caches.
528 */
529 slgd->JunkIndex = (slgd->JunkIndex + ZALLOC_SLAB_SLIDE)
530 & (ZALLOC_MAX_ZONE_SIZE - 1);
a108bf71
MD
531 }
532done:
533 crit_exit();
534 if (flags & M_ZERO)
535 bzero(chunk, size);
536 ++type->ks_inuse;
537 type->ks_memuse += size;
538 return(chunk);
539fail:
540 crit_exit();
541 return(NULL);
542}
543
544void *
545realloc(void *ptr, unsigned long size, struct malloc_type *type, int flags)
546{
547 SLZone *z;
548 void *nptr;
549 unsigned long osize;
550
551 if (ptr == NULL || ptr == ZERO_LENGTH_PTR)
552 return(malloc(size, type, flags));
553 if (size == 0) {
554 free(ptr, type);
555 return(NULL);
556 }
557
558 /*
559 * Handle oversized allocations. XXX we really should require that a
560 * size be passed to free() instead of this nonsense.
561 */
562 {
563 struct kmemusage *kup;
564
565 kup = btokup(ptr);
566 if (kup->ku_pagecnt) {
567 osize = kup->ku_pagecnt << PAGE_SHIFT;
568 if (osize == round_page(size))
569 return(ptr);
570 if ((nptr = malloc(size, type, flags)) == NULL)
571 return(NULL);
572 bcopy(ptr, nptr, min(size, osize));
573 free(ptr, type);
574 return(nptr);
575 }
576 }
577
578 /*
579 * Get the original allocation's zone. If the new request winds up
580 * using the same chunk size we do not have to do anything.
581 */
582 z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
583 KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
584
585 zoneindex(&size);
586 if (z->z_ChunkSize == size)
587 return(ptr);
588
589 /*
590 * Allocate memory for the new request size. Note that zoneindex has
591 * already adjusted the request size to the appropriate chunk size, which
592 * should optimize our bcopy(). Then copy and return the new pointer.
593 */
594 if ((nptr = malloc(size, type, flags)) == NULL)
595 return(NULL);
596 bcopy(ptr, nptr, min(size, z->z_ChunkSize));
597 free(ptr, type);
598 return(nptr);
599}
600
601/*
602 * free() (SLAB ALLOCATOR)
603 *
604 * Free the specified chunk of memory. The byte count is not strictly
605 * required but if DIAGNOSTIC is set we use it as a sanity check.
606 */
607static
608void
609free_remote(void *ptr)
610{
611 free(ptr, *(struct malloc_type **)ptr);
612}
613
614void
615free(void *ptr, struct malloc_type *type)
616{
617 SLZone *z;
618 SLChunk *chunk;
619 SLGlobalData *slgd;
620 int pgno;
621
622 slgd = &mycpu->gd_slab;
623
624 /*
625 * Handle special 0-byte allocations
626 */
627 if (ptr == ZERO_LENGTH_PTR)
628 return;
629
630 /*
631 * Handle oversized allocations. XXX we really should require that a
632 * size be passed to free() instead of this nonsense.
633 */
634 {
635 struct kmemusage *kup;
636 unsigned long size;
637
638 kup = btokup(ptr);
639 if (kup->ku_pagecnt) {
640 size = kup->ku_pagecnt << PAGE_SHIFT;
641 kup->ku_pagecnt = 0;
642 --type->ks_inuse;
643 type->ks_memuse -= size;
644#ifdef INVARIANTS
645 KKASSERT(sizeof(weirdary) <= size);
646 bcopy(weirdary, ptr, sizeof(weirdary));
647#endif
648 kmem_slab_free(ptr, size); /* may block */
649 return;
650 }
651 }
652
653 /*
654 * Zone case. Figure out the zone based on the fact that it is
655 * ZoneSize aligned.
656 */
657 z = (SLZone *)((uintptr_t)ptr & ~(uintptr_t)ZoneMask);
658 KKASSERT(z->z_Magic == ZALLOC_SLAB_MAGIC);
659
660 /*
661 * If we do not own the zone then forward the request to the
662 * cpu that does. The freeing code does not need the byte count
663 * unless DIAGNOSTIC is set.
664 */
665 if (z->z_Cpu != mycpu->gd_cpuid) {
666 *(struct malloc_type **)ptr = type;
667 lwkt_send_ipiq(z->z_Cpu, free_remote, ptr);
668 return;
669 }
670
671 if (type->ks_magic != M_MAGIC)
672 panic("free: malloc type lacks magic");
673
674 crit_enter();
675 pgno = ((char *)ptr - (char *)z) >> PAGE_SHIFT;
676 chunk = ptr;
677
678#ifdef DIAGNOSTIC
679 /*
680 * Diagnostic: attempt to detect a double-free (not perfect).
681 */
682 if (((intptr_t)chunk->c_Next - (intptr_t)z) >> PAGE_SHIFT == pgno) {
683 SLChunk *scan;
684 for (scan = z->z_PageAry[pgno]; scan; scan = scan->c_Next) {
685 if (scan == chunk)
686 panic("Double free at %p", chunk);
687 }
688 }
689#endif
690
691 /*
692 * Put weird data into the memory to detect modifications after freeing,
693 * illegal pointer use after freeing (we should fault on the odd address),
694 * and so forth. XXX needs more work, see the old malloc code.
695 */
696#ifdef INVARIANTS
697 if (z->z_ChunkSize < sizeof(weirdary))
698 bcopy(weirdary, chunk, z->z_ChunkSize);
699 else
700 bcopy(weirdary, chunk, sizeof(weirdary));
701#endif
702
703 /*
704 * Add this free non-zero'd chunk to a linked list for reuse, adjust
705 * z_FirstFreePg.
706 */
6ab8e1da
MD
707#ifdef INVARIANTS
708 if ((uintptr_t)chunk < VM_MIN_KERNEL_ADDRESS)
a108bf71 709 panic("BADFREE %p\n", chunk);
a108bf71
MD
710#endif
711 chunk->c_Next = z->z_PageAry[pgno];
712 z->z_PageAry[pgno] = chunk;
6ab8e1da
MD
713#ifdef INVARIANTS
714 if (chunk->c_Next && (uintptr_t)chunk->c_Next < VM_MIN_KERNEL_ADDRESS)
a108bf71 715 panic("BADFREE2");
6ab8e1da 716#endif
a108bf71
MD
717 if (z->z_FirstFreePg > pgno)
718 z->z_FirstFreePg = pgno;
719
720 /*
721 * Bump the number of free chunks. If it becomes non-zero the zone
722 * must be added back onto the appropriate list.
723 */
724 if (z->z_NFree++ == 0) {
725 z->z_Next = slgd->ZoneAry[z->z_ZoneIndex];
726 slgd->ZoneAry[z->z_ZoneIndex] = z;
727 }
728
729 --type->ks_inuse;
730 type->ks_memuse -= z->z_ChunkSize;
731
732 /*
733 * If the zone becomes totally free, and there are other zones we
a7cf0021
MD
734 * can allocate from, move this zone to the FreeZones list. Since
735 * this code can be called from an IPI callback, do *NOT* try to mess
736 * with kernel_map here. Hysteresis will be performed at malloc() time.
a108bf71
MD
737 */
738 if (z->z_NFree == z->z_NMax &&
739 (z->z_Next || slgd->ZoneAry[z->z_ZoneIndex] != z)
740 ) {
741 SLZone **pz;
742
743 for (pz = &slgd->ZoneAry[z->z_ZoneIndex]; z != *pz; pz = &(*pz)->z_Next)
744 ;
745 *pz = z->z_Next;
746 z->z_Magic = -1;
a7cf0021
MD
747 z->z_Next = slgd->FreeZones;
748 slgd->FreeZones = z;
749 ++slgd->NFreeZones;
a108bf71
MD
750 }
751 crit_exit();
752}
753
754/*
755 * kmem_slab_alloc()
756 *
757 * Directly allocate and wire kernel memory in PAGE_SIZE chunks with the
758 * specified alignment. M_* flags are expected in the flags field.
759 *
760 * Alignment must be a multiple of PAGE_SIZE.
761 *
762 * NOTE! XXX For the moment we use vm_map_entry_reserve/release(),
763 * but when we move zalloc() over to use this function as its backend
764 * we will have to switch to kreserve/krelease and call reserve(0)
765 * after the new space is made available.
766 */
767static void *
768kmem_slab_alloc(vm_size_t size, vm_offset_t align, int flags)
769{
770 vm_size_t i;
771 vm_offset_t addr;
772 vm_offset_t offset;
773 int count;
774 vm_map_t map = kernel_map;
775
776 size = round_page(size);
777 addr = vm_map_min(map);
778
779 /*
780 * Reserve properly aligned space from kernel_map
781 */
782 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
783 crit_enter();
784 vm_map_lock(map);
785 if (vm_map_findspace(map, vm_map_min(map), size, align, &addr)) {
786 vm_map_unlock(map);
787 if ((flags & (M_NOWAIT|M_NULLOK)) == 0)
788 panic("kmem_slab_alloc(): kernel_map ran out of space!");
789 crit_exit();
790 vm_map_entry_release(count);
791 return(NULL);
792 }
793 offset = addr - VM_MIN_KERNEL_ADDRESS;
794 vm_object_reference(kernel_object);
795 vm_map_insert(map, &count,
796 kernel_object, offset, addr, addr + size,
797 VM_PROT_ALL, VM_PROT_ALL, 0);
798
799 /*
800 * Allocate the pages. Do not mess with the PG_ZERO flag yet.
801 */
802 for (i = 0; i < size; i += PAGE_SIZE) {
803 vm_page_t m;
804 vm_pindex_t idx = OFF_TO_IDX(offset + i);
805 int zero = (flags & M_ZERO) ? VM_ALLOC_ZERO : 0;
806
807 if ((flags & (M_NOWAIT|M_USE_RESERVE)) == M_NOWAIT)
808 m = vm_page_alloc(kernel_object, idx, VM_ALLOC_INTERRUPT|zero);
809 else
810 m = vm_page_alloc(kernel_object, idx, VM_ALLOC_SYSTEM|zero);
811 if (m == NULL) {
812 if ((flags & M_NOWAIT) == 0) {
813 vm_map_unlock(map);
814 vm_wait();
815 vm_map_lock(map);
816 i -= PAGE_SIZE; /* retry */
817 continue;
818 }
819 while (i != 0) {
820 i -= PAGE_SIZE;
821 m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
822 vm_page_free(m);
823 }
824 vm_map_delete(map, addr, addr + size, &count);
825 vm_map_unlock(map);
826 crit_exit();
827 vm_map_entry_release(count);
828 return(NULL);
829 }
830 }
831
832 /*
833 * Mark the map entry as non-pageable using a routine that allows us to
834 * populate the underlying pages.
835 */
836 vm_map_set_wired_quick(map, addr, size, &count);
837 crit_exit();
838
839 /*
840 * Enter the pages into the pmap and deal with PG_ZERO and M_ZERO.
841 */
842 for (i = 0; i < size; i += PAGE_SIZE) {
843 vm_page_t m;
844
845 m = vm_page_lookup(kernel_object, OFF_TO_IDX(offset + i));
846 m->valid = VM_PAGE_BITS_ALL;
847 vm_page_wire(m);
848 vm_page_wakeup(m);
849 pmap_enter(kernel_pmap, addr + i, m, VM_PROT_ALL, 1);
850 if ((m->flags & PG_ZERO) == 0 && (flags & M_ZERO))
851 bzero((char *)addr + i, PAGE_SIZE);
852 vm_page_flag_clear(m, PG_ZERO);
853 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE | PG_REFERENCED);
854 }
855 vm_map_unlock(map);
856 vm_map_entry_release(count);
857 return((void *)addr);
858}
859
860static void
861kmem_slab_free(void *ptr, vm_size_t size)
862{
863 crit_enter();
864 vm_map_remove(kernel_map, (vm_offset_t)ptr, (vm_offset_t)ptr + size);
865 crit_exit();
866}
867
868#endif