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