AHCI - Fix minor bug. Also AHCI/SILI - use ATA_F_EXCLUSIVE for pass-thru
[dragonfly.git] / sys / kern / kern_slaballoc.c
... / ...
CommitLineData
1/*
2 * KERN_SLABALLOC.C - Kernel SLAB memory allocator
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 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
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
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
34 * SUCH DAMAGE.
35 *
36 * $DragonFly: src/sys/kern/kern_slaballoc.c,v 1.55 2008/10/22 01:42:17 dillon Exp $
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 *
79 * Allocations >= ZoneLimit go directly to kmem.
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)
87 * + all power-of-2 sized allocations are power-of-2 aligned (twe)
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
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>
103#include <sys/sysctl.h>
104#include <sys/ktr.h>
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>
119#include <sys/mplock2.h>
120
121#define arysize(ary) (sizeof(ary)/sizeof((ary)[0]))
122
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);
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);
136#ifdef SMP
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);
139#endif
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);
143
144#define logmemory(name, ptr, type, size, flags) \
145 KTR_LOG(memory_ ## name, ptr, type, size, flags)
146#define logmemory_quick(name) \
147 KTR_LOG(memory_ ## name)
148
149/*
150 * Fixed globals (not per-cpu)
151 */
152static int ZoneSize;
153static int ZoneLimit;
154static int ZonePageCount;
155static int ZoneMask;
156struct malloc_type *kmemstatistics; /* exported to vmstat */
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);
162#if defined(INVARIANTS)
163static void chunk_mark_allocated(SLZone *z, void *chunk);
164static void chunk_mark_free(SLZone *z, void *chunk);
165#endif
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
206char *ZeroPage;
207
208SYSINIT(kmem, SI_BOOT1_ALLOCATOR, SI_ORDER_FIRST, kmeminit, NULL)
209
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
219static void
220kmeminit(void *dummy)
221{
222 vm_poff_t limsize;
223 int usesize;
224 int i;
225 vm_offset_t npg;
226
227 limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
228 if (limsize > KvaSize)
229 limsize = KvaSize;
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;
236 ZoneLimit = ZoneSize / 4;
237 if (ZoneLimit > ZALLOC_ZONE_LIMIT)
238 ZoneLimit = ZALLOC_ZONE_LIMIT;
239 ZoneMask = ZoneSize - 1;
240 ZonePageCount = ZoneSize / PAGE_SIZE;
241
242 npg = KvaSize / PAGE_SIZE;
243 kmemusage = kmem_slab_alloc(npg * sizeof(struct kmemusage),
244 PAGE_SIZE, M_WAITOK|M_ZERO);
245
246 for (i = 0; i < arysize(weirdary); ++i)
247 weirdary[i] = WEIRD_ADDR;
248
249 ZeroPage = kmem_slab_alloc(PAGE_SIZE, PAGE_SIZE, M_WAITOK|M_ZERO);
250
251 if (bootverbose)
252 kprintf("Slab ZoneSize set to %dKB\n", ZoneSize / 1024);
253}
254
255/*
256 * Initialize a malloc type tracking structure.
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;
274 if (limsize > KvaSize)
275 limsize = KvaSize;
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;
287#ifdef INVARIANTS
288 int i;
289 long ttl;
290#endif
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
301#ifdef SMP
302 /* Make sure that all pending kfree()s are finished. */
303 lwkt_synchronize_ipiqs("muninit");
304#endif
305
306#ifdef INVARIANTS
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) {
315 kprintf("malloc_uninit: %ld bytes of '%s' still allocated on cpu %d\n",
316 ttl, type->ks_shortdesc, i);
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
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
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
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/*
431 * malloc() (SLAB ALLOCATOR)
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 *
438 * M_RNOWAIT - don't block.
439 * M_NULLOK - return NULL instead of blocking.
440 * M_ZERO - zero the returned memory.
441 * M_USE_RESERVE - allow greater drawdown of the free list
442 * M_USE_INTERRUPT_RESERVE - allow the freelist to be exhausted
443 *
444 * MPSAFE
445 */
446
447void *
448kmalloc(unsigned long size, struct malloc_type *type, int flags)
449{
450 SLZone *z;
451 SLChunk *chunk;
452 SLGlobalData *slgd;
453 struct globaldata *gd;
454 int zi;
455#ifdef INVARIANTS
456 int i;
457#endif
458
459 logmemory_quick(malloc_beg);
460 gd = mycpu;
461 slgd = &gd->gd_slab;
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 /*
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
477 * simply deadlock the computer.
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].
482 */
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];
489 type->ks_loosememuse = ttl; /* not MP synchronized */
490 if (ttl >= type->ks_limit) {
491 if (flags & M_NULLOK) {
492 logmemory(malloc, NULL, type, size, flags);
493 return(NULL);
494 }
495 panic("%s: malloc limit exceeded", type->ks_shortdesc);
496 }
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 */
506 if (size == 0) {
507 logmemory(malloc, ZERO_LENGTH_PTR, type, size, flags);
508 return(ZERO_LENGTH_PTR);
509 }
510
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 */
516 while (slgd->NFreeZones > ZONE_RELS_THRESH && (flags & M_RNOWAIT) == 0) {
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 */
529 while (slgd->FreeOvZones && (flags & M_RNOWAIT) == 0) {
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();
537 }
538
539 /*
540 * Handle large allocations directly. There should not be very many of
541 * these so performance is not a big issue.
542 *
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.
546 */
547 if (size >= ZoneLimit || ((size & PAGE_MASK) == 0 && size > PAGE_SIZE*2)) {
548 struct kmemusage *kup;
549
550 size = round_page(size);
551 chunk = kmem_slab_alloc(size, PAGE_SIZE, flags);
552 if (chunk == NULL) {
553 logmemory(malloc, NULL, type, size, flags);
554 return(NULL);
555 }
556 flags &= ~M_ZERO; /* result already zero'd if M_ZERO was set */
557 flags |= M_PASSIVE_ZERO;
558 kup = btokup(chunk);
559 kup->ku_pagecnt = size / PAGE_SIZE;
560 kup->ku_cpu = gd->gd_cpuid;
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
602#ifdef INVARIANTS
603 if ((vm_offset_t)chunk < KvaStart || (vm_offset_t)chunk >= KvaEnd)
604 panic("chunk %p FFPG %d/%d", chunk, z->z_FirstFreePg, ZonePageCount);
605 if (chunk->c_Next && (vm_offset_t)chunk->c_Next < KvaStart)
606 panic("chunkNEXT %p %p FFPG %d/%d", chunk, chunk->c_Next, z->z_FirstFreePg, ZonePageCount);
607 chunk_mark_allocated(z, chunk);
608#endif
609 z->z_PageAry[z->z_FirstFreePg] = chunk->c_Next;
610 goto done;
611 }
612 ++z->z_FirstFreePg;
613 }
614
615 /*
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.
620 */
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);
628 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
629 flags &= ~M_ZERO;
630 flags |= M_PASSIVE_ZERO;
631 }
632#if defined(INVARIANTS)
633 chunk_mark_allocated(z, chunk);
634#endif
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
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.
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));
656 z->z_Flags |= SLZF_UNOTZEROD;
657 } else {
658 z = kmem_slab_alloc(ZoneSize, ZoneSize, flags|M_ZERO);
659 if (z == NULL)
660 goto fail;
661 }
662
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
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))
682 off = (off + size - 1) & ~(size - 1);
683 else
684 off = (off + MIN_CHUNK_MASK) & ~MIN_CHUNK_MASK;
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;
689 z->z_BasePtr = (char *)z + off;
690 z->z_UIndex = z->z_UEndIndex = slgd->JunkIndex % z->z_NMax;
691 z->z_ChunkSize = size;
692 z->z_FirstFreePg = ZonePageCount;
693 z->z_CpuGd = gd;
694 z->z_Cpu = gd->gd_cpuid;
695 chunk = (SLChunk *)(z->z_BasePtr + z->z_UIndex * size);
696 z->z_Next = slgd->ZoneAry[zi];
697 slgd->ZoneAry[zi] = z;
698 if ((z->z_Flags & SLZF_UNOTZEROD) == 0) {
699 flags &= ~M_ZERO; /* already zero'd */
700 flags |= M_PASSIVE_ZERO;
701 }
702#if defined(INVARIANTS)
703 chunk_mark_allocated(z, chunk);
704#endif
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);
713 }
714done:
715 ++type->ks_inuse[gd->gd_cpuid];
716 type->ks_memuse[gd->gd_cpuid] += size;
717 type->ks_loosememuse += size; /* not MP synchronized */
718 crit_exit();
719 if (flags & M_ZERO)
720 bzero(chunk, size);
721#ifdef INVARIANTS
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 }
728 chunk->c_Next = (void *)-1; /* avoid accidental double-free check */
729 }
730#endif
731 logmemory(malloc, chunk, type, size, flags);
732 return(chunk);
733fail:
734 crit_exit();
735 logmemory(malloc, NULL, type, size, flags);
736 return(NULL);
737}
738
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 */
746void *
747krealloc(void *ptr, unsigned long size, struct malloc_type *type, int flags)
748{
749 SLZone *z;
750 void *nptr;
751 unsigned long osize;
752
753 KKASSERT((flags & M_ZERO) == 0); /* not supported */
754
755 if (ptr == NULL || ptr == ZERO_LENGTH_PTR)
756 return(kmalloc(size, type, flags));
757 if (size == 0) {
758 kfree(ptr, type);
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);
774 if ((nptr = kmalloc(size, type, flags)) == NULL)
775 return(NULL);
776 bcopy(ptr, nptr, min(size, osize));
777 kfree(ptr, type);
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
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.
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.
799 */
800 if (size < ZoneLimit) {
801 zoneindex(&size);
802 if (z->z_ChunkSize == size)
803 return(ptr);
804 }
805 if ((nptr = kmalloc(size, type, flags)) == NULL)
806 return(NULL);
807 bcopy(ptr, nptr, min(size, z->z_ChunkSize));
808 kfree(ptr, type);
809 return(nptr);
810}
811
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
827/*
828 * Allocate a copy of the specified string.
829 *
830 * (MP SAFE) (MAY BLOCK)
831 */
832char *
833kstrdup(const char *str, struct malloc_type *type)
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;
841 nstr = kmalloc(zlen, type, M_WAITOK);
842 bcopy(str, nstr, zlen);
843 return(nstr);
844}
845
846#ifdef SMP
847/*
848 * free() (SLAB ALLOCATOR)
849 *
850 * Free the specified chunk of memory.
851 */
852static
853void
854free_remote(void *ptr)
855{
856 logmemory(free_remote, ptr, *(struct malloc_type **)ptr, -1, 0);
857 kfree(ptr, *(struct malloc_type **)ptr);
858}
859
860#endif
861
862/*
863 * free (SLAB ALLOCATOR)
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.
868 *
869 * MPSAFE
870 */
871void
872kfree(void *ptr, struct malloc_type *type)
873{
874 SLZone *z;
875 SLChunk *chunk;
876 SLGlobalData *slgd;
877 struct globaldata *gd;
878 int pgno;
879
880 logmemory_quick(free_beg);
881 gd = mycpu;
882 slgd = &gd->gd_slab;
883
884 if (ptr == NULL)
885 panic("trying to free NULL pointer");
886
887 /*
888 * Handle special 0-byte allocations
889 */
890 if (ptr == ZERO_LENGTH_PTR) {
891 logmemory(free_zero, ptr, type, -1, 0);
892 logmemory_quick(free_end);
893 return;
894 }
895
896 /*
897 * Handle oversized allocations. XXX we really should require that a
898 * size be passed to free() instead of this nonsense.
899 *
900 * This code is never called via an ipi.
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;
910#ifdef INVARIANTS
911 KKASSERT(sizeof(weirdary) <= size);
912 bcopy(weirdary, ptr, sizeof(weirdary));
913#endif
914 /*
915 * note: we always adjust our cpu's slot, not the originating
916 * cpu (kup->ku_cpuid). The statistics are in aggregate.
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().
922 */
923 crit_enter();
924 --type->ks_inuse[gd->gd_cpuid];
925 type->ks_memuse[gd->gd_cpuid] -= size;
926 if (mycpu->gd_intr_nesting_level || (gd->gd_curthread->td_flags & TDF_INTTHREAD)) {
927 logmemory(free_ovsz_delayed, ptr, type, size, 0);
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 {
935 crit_exit();
936 logmemory(free_ovsz, ptr, type, size, 0);
937 kmem_slab_free(ptr, size); /* may block */
938 }
939 logmemory_quick(free_end);
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
953 * cpu that does. Since the timing is non-critical, a passive
954 * message is sent.
955 */
956 if (z->z_CpuGd != gd) {
957 *(struct malloc_type **)ptr = type;
958#ifdef SMP
959 logmemory(free_request, ptr, type, z->z_ChunkSize, 0);
960 lwkt_send_ipiq_passive(z->z_CpuGd, free_remote, ptr);
961#else
962 panic("Corrupt SLZone");
963#endif
964 logmemory_quick(free_end);
965 return;
966 }
967
968 logmemory(free_chunk, ptr, type, z->z_ChunkSize, 0);
969
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
977#ifdef INVARIANTS
978 /*
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.
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 }
989 chunk_mark_free(z, chunk);
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 */
1008#ifdef INVARIANTS
1009 if ((vm_offset_t)chunk < KvaStart || (vm_offset_t)chunk >= KvaEnd)
1010 panic("BADFREE %p", chunk);
1011#endif
1012 chunk->c_Next = z->z_PageAry[pgno];
1013 z->z_PageAry[pgno] = chunk;
1014#ifdef INVARIANTS
1015 if (chunk->c_Next && (vm_offset_t)chunk->c_Next < KvaStart)
1016 panic("BADFREE2");
1017#endif
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
1030 --type->ks_inuse[z->z_Cpu];
1031 type->ks_memuse[z->z_Cpu] -= z->z_ChunkSize;
1032
1033 /*
1034 * If the zone becomes totally free, and there are other zones we
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.
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;
1048 z->z_Next = slgd->FreeZones;
1049 slgd->FreeZones = z;
1050 ++slgd->NFreeZones;
1051 }
1052 logmemory_quick(free_end);
1053 crit_exit();
1054}
1055
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
1090/*
1091 * kmem_slab_alloc()
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.
1102 *
1103 * Interrupt code which has preempted other code is not allowed to
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.
1107 *
1108 * This routine will currently obtain the BGL.
1109 *
1110 * MPALMOSTSAFE - acquires mplock
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;
1117 int count, vmflags, base_vmflags;
1118 thread_t td;
1119
1120 size = round_page(size);
1121 addr = vm_map_min(&kernel_map);
1122
1123 /*
1124 * Reserve properly aligned space from kernel_map. RNOWAIT allocations
1125 * cannot block.
1126 */
1127 if (flags & M_RNOWAIT) {
1128 if (try_mplock() == 0)
1129 return(NULL);
1130 } else {
1131 get_mplock();
1132 }
1133 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1134 crit_enter();
1135 vm_map_lock(&kernel_map);
1136 if (vm_map_findspace(&kernel_map, addr, size, align, 0, &addr)) {
1137 vm_map_unlock(&kernel_map);
1138 if ((flags & M_NULLOK) == 0)
1139 panic("kmem_slab_alloc(): kernel_map ran out of space!");
1140 crit_exit();
1141 vm_map_entry_release(count);
1142 rel_mplock();
1143 return(NULL);
1144 }
1145
1146 /*
1147 * kernel_object maps 1:1 to kernel_map.
1148 */
1149 vm_object_reference(&kernel_object);
1150 vm_map_insert(&kernel_map, &count,
1151 &kernel_object, addr, addr, addr + size,
1152 VM_MAPTYPE_NORMAL,
1153 VM_PROT_ALL, VM_PROT_ALL,
1154 0);
1155
1156 td = curthread;
1157
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
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;
1174
1175 /*
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
1180 * implied in this case), though I'm not sure if we really need to
1181 * do that.
1182 */
1183 vmflags = base_vmflags;
1184 if (flags & M_WAITOK) {
1185 if (td->td_preempted)
1186 vmflags |= VM_ALLOC_SYSTEM;
1187 else
1188 vmflags |= VM_ALLOC_NORMAL;
1189 }
1190
1191 m = vm_page_alloc(&kernel_object, OFF_TO_IDX(addr + i), vmflags);
1192
1193 /*
1194 * If the allocation failed we either return NULL or we retry.
1195 *
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.
1201 */
1202 if (m == NULL) {
1203 if (flags & M_WAITOK) {
1204 if (td->td_preempted) {
1205 vm_map_unlock(&kernel_map);
1206 lwkt_yield();
1207 vm_map_lock(&kernel_map);
1208 } else {
1209 vm_map_unlock(&kernel_map);
1210 vm_wait(0);
1211 vm_map_lock(&kernel_map);
1212 }
1213 i -= PAGE_SIZE; /* retry */
1214 continue;
1215 }
1216
1217 /*
1218 * We were unable to recover, cleanup and return NULL
1219 */
1220 while (i != 0) {
1221 i -= PAGE_SIZE;
1222 m = vm_page_lookup(&kernel_object, OFF_TO_IDX(addr + i));
1223 /* page should already be busy */
1224 vm_page_free(m);
1225 }
1226 vm_map_delete(&kernel_map, addr, addr + size, &count);
1227 vm_map_unlock(&kernel_map);
1228 crit_exit();
1229 vm_map_entry_release(count);
1230 rel_mplock();
1231 return(NULL);
1232 }
1233 }
1234
1235 /*
1236 * Success!
1237 *
1238 * Mark the map entry as non-pageable using a routine that allows us to
1239 * populate the underlying pages.
1240 *
1241 * The pages were busied by the allocations above.
1242 */
1243 vm_map_set_wired_quick(&kernel_map, addr, size, &count);
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
1252 m = vm_page_lookup(&kernel_object, OFF_TO_IDX(addr + i));
1253 m->valid = VM_PAGE_BITS_ALL;
1254 /* page should already be busy */
1255 vm_page_wire(m);
1256 vm_page_wakeup(m);
1257 pmap_enter(&kernel_pmap, addr + i, m, VM_PROT_ALL, 1);
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);
1261 KKASSERT(m->flags & (PG_WRITEABLE | PG_MAPPED));
1262 vm_page_flag_set(m, PG_REFERENCED);
1263 }
1264 vm_map_unlock(&kernel_map);
1265 vm_map_entry_release(count);
1266 rel_mplock();
1267 return((void *)addr);
1268}
1269
1270/*
1271 * kmem_slab_free()
1272 *
1273 * MPALMOSTSAFE - acquires mplock
1274 */
1275static void
1276kmem_slab_free(void *ptr, vm_size_t size)
1277{
1278 get_mplock();
1279 crit_enter();
1280 vm_map_remove(&kernel_map, (vm_offset_t)ptr, (vm_offset_t)ptr + size);
1281 crit_exit();
1282 rel_mplock();
1283}
1284