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