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