2 * Copyright (c) 2002-2005, 2009, 2013 Jeffrey Roberson <jeff@FreeBSD.org>
3 * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
4 * Copyright (c) 2004-2006 Robert N. M. Watson
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice unmodified, this list of conditions, and the following
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * uma_core.c Implementation of the Universal Memory allocator
32 * This allocator is intended to replace the multitude of similar object caches
33 * in the standard FreeBSD kernel. The intent is to be flexible as well as
34 * effecient. A primary design goal is to return unused memory to the rest of
35 * the system. This will make the system as a whole more flexible due to the
36 * ability to move memory to subsystems which most need it instead of leaving
37 * pools of reserved memory unused.
39 * The basic ideas stem from similar slab/zone based allocators whose algorithms
46 * - Improve memory usage for large allocations
47 * - Investigate cache size adjustments
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
53 /* I should really use ktr.. */
56 #define UMA_DEBUG_ALLOC 1
57 #define UMA_DEBUG_ALLOC_1 1
61 #include "opt_param.h"
64 #include <sys/param.h>
65 #include <sys/systm.h>
66 #include <sys/bitset.h>
67 #include <sys/kernel.h>
68 #include <sys/types.h>
69 #include <sys/queue.h>
70 #include <sys/malloc.h>
73 #include <sys/sysctl.h>
74 #include <sys/mutex.h>
76 #include <sys/rwlock.h>
79 #include <sys/vmmeter.h>
82 #include <vm/vm_object.h>
83 #include <vm/vm_page.h>
84 #include <vm/vm_pageout.h>
85 #include <vm/vm_param.h>
86 #include <vm/vm_map.h>
87 #include <vm/vm_kern.h>
88 #include <vm/vm_extern.h>
90 #include <vm/uma_int.h>
91 #include <vm/uma_dbg.h>
96 #include <vm/memguard.h>
100 * This is the zone and keg from which all zones are spawned. The idea is that
101 * even the zone & keg heads are allocated from the allocator, so we use the
102 * bss section to bootstrap us.
104 static struct uma_keg masterkeg;
105 static struct uma_zone masterzone_k;
106 static struct uma_zone masterzone_z;
107 static uma_zone_t kegs = &masterzone_k;
108 static uma_zone_t zones = &masterzone_z;
110 /* This is the zone from which all of uma_slab_t's are allocated. */
111 static uma_zone_t slabzone;
112 static uma_zone_t slabrefzone; /* With refcounters (for UMA_ZONE_REFCNT) */
115 * The initial hash tables come out of this zone so they can be allocated
116 * prior to malloc coming up.
118 static uma_zone_t hashzone;
120 /* The boot-time adjusted value for cache line alignment. */
121 int uma_align_cache = 64 - 1;
123 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
126 * Are we allowed to allocate buckets?
128 static int bucketdisable = 1;
130 /* Linked list of all kegs in the system */
131 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
133 /* This mutex protects the keg list */
134 static struct mtx_padalign uma_mtx;
136 /* Linked list of boot time pages */
137 static LIST_HEAD(,uma_slab) uma_boot_pages =
138 LIST_HEAD_INITIALIZER(uma_boot_pages);
140 /* This mutex protects the boot time pages list */
141 static struct mtx_padalign uma_boot_pages_mtx;
143 /* Is the VM done starting up? */
144 static int booted = 0;
145 #define UMA_STARTUP 1
146 #define UMA_STARTUP2 2
148 /* Maximum number of allowed items-per-slab if the slab header is OFFPAGE */
149 static const u_int uma_max_ipers = SLAB_SETSIZE;
152 * Only mbuf clusters use ref zones. Just provide enough references
153 * to support the one user. New code should not use the ref facility.
155 static const u_int uma_max_ipers_ref = PAGE_SIZE / MCLBYTES;
158 * This is the handle used to schedule events that need to happen
159 * outside of the allocation fast path.
161 static struct callout uma_callout;
162 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
165 * This structure is passed as the zone ctor arg so that I don't have to create
166 * a special allocation function just for zones.
168 struct uma_zctor_args {
183 struct uma_kctor_args {
192 struct uma_bucket_zone {
198 #define BUCKET_MAX 128
200 struct uma_bucket_zone bucket_zones[] = {
201 { NULL, "16 Bucket", 16 },
202 { NULL, "32 Bucket", 32 },
203 { NULL, "64 Bucket", 64 },
204 { NULL, "128 Bucket", 128 },
208 #define BUCKET_SHIFT 4
209 #define BUCKET_ZONES ((BUCKET_MAX >> BUCKET_SHIFT) + 1)
212 * bucket_size[] maps requested bucket sizes to zones that allocate a bucket
213 * of approximately the right size.
215 static uint8_t bucket_size[BUCKET_ZONES];
218 * Flags and enumerations to be passed to internal functions.
220 enum zfreeskip { SKIP_NONE = 0, SKIP_DTOR, SKIP_FINI };
224 static void *noobj_alloc(uma_zone_t, int, uint8_t *, int);
225 static void *page_alloc(uma_zone_t, int, uint8_t *, int);
226 static void *startup_alloc(uma_zone_t, int, uint8_t *, int);
227 static void page_free(void *, int, uint8_t);
228 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int);
229 static void cache_drain(uma_zone_t);
230 static void bucket_drain(uma_zone_t, uma_bucket_t);
231 static void bucket_cache_drain(uma_zone_t zone);
232 static int keg_ctor(void *, int, void *, int);
233 static void keg_dtor(void *, int, void *);
234 static int zone_ctor(void *, int, void *, int);
235 static void zone_dtor(void *, int, void *);
236 static int zero_init(void *, int, int);
237 static void keg_small_init(uma_keg_t keg);
238 static void keg_large_init(uma_keg_t keg);
239 static void zone_foreach(void (*zfunc)(uma_zone_t));
240 static void zone_timeout(uma_zone_t zone);
241 static int hash_alloc(struct uma_hash *);
242 static int hash_expand(struct uma_hash *, struct uma_hash *);
243 static void hash_free(struct uma_hash *hash);
244 static void uma_timeout(void *);
245 static void uma_startup3(void);
246 static void *zone_alloc_item(uma_zone_t, void *, int);
247 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
248 static void bucket_enable(void);
249 static void bucket_init(void);
250 static uma_bucket_t bucket_alloc(int, int);
251 static void bucket_free(uma_bucket_t);
252 static void bucket_zone_drain(void);
253 static int zone_alloc_bucket(uma_zone_t zone, int flags);
254 static uma_slab_t zone_fetch_slab(uma_zone_t zone, uma_keg_t last, int flags);
255 static uma_slab_t zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int flags);
256 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
257 static void slab_free_item(uma_keg_t keg, uma_slab_t slab, void *item);
258 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
259 uma_fini fini, int align, uint32_t flags);
260 static inline void zone_relock(uma_zone_t zone, uma_keg_t keg);
261 static inline void keg_relock(uma_keg_t keg, uma_zone_t zone);
262 static int zone_import(uma_zone_t zone, void **bucket, int max, int flags);
263 static void zone_release(uma_zone_t zone, void **bucket, int cnt);
265 void uma_print_zone(uma_zone_t);
266 void uma_print_stats(void);
267 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
268 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
270 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
272 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
273 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
275 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
276 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
278 static int zone_warnings = 1;
279 TUNABLE_INT("vm.zone_warnings", &zone_warnings);
280 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RW, &zone_warnings, 0,
281 "Warn when UMA zones becomes full");
284 * This routine checks to see whether or not it's safe to enable buckets.
290 bucketdisable = vm_page_count_min();
294 * Initialize bucket_zones, the array of zones of buckets of various sizes.
296 * For each zone, calculate the memory required for each bucket, consisting
297 * of the header and an array of pointers. Initialize bucket_size[] to point
298 * the range of appropriate bucket sizes at the zone.
303 struct uma_bucket_zone *ubz;
307 for (i = 0, j = 0; bucket_zones[j].ubz_entries != 0; j++) {
310 ubz = &bucket_zones[j];
311 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
312 size += sizeof(void *) * ubz->ubz_entries;
313 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
314 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
315 UMA_ZFLAG_INTERNAL | UMA_ZFLAG_BUCKET);
316 for (; i <= ubz->ubz_entries; i += (1 << BUCKET_SHIFT))
317 bucket_size[i >> BUCKET_SHIFT] = j;
322 * Given a desired number of entries for a bucket, return the zone from which
323 * to allocate the bucket.
325 static struct uma_bucket_zone *
326 bucket_zone_lookup(int entries)
330 idx = howmany(entries, 1 << BUCKET_SHIFT);
331 return (&bucket_zones[bucket_size[idx]]);
335 bucket_alloc(int entries, int bflags)
337 struct uma_bucket_zone *ubz;
341 * This is to stop us from allocating per cpu buckets while we're
342 * running out of vm.boot_pages. Otherwise, we would exhaust the
343 * boot pages. This also prevents us from allocating buckets in
344 * low memory situations.
349 ubz = bucket_zone_lookup(entries);
350 bucket = zone_alloc_item(ubz->ubz_zone, NULL, bflags);
353 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
356 bucket->ub_entries = ubz->ubz_entries;
363 bucket_free(uma_bucket_t bucket)
365 struct uma_bucket_zone *ubz;
367 ubz = bucket_zone_lookup(bucket->ub_entries);
368 zone_free_item(ubz->ubz_zone, bucket, NULL, SKIP_NONE);
372 bucket_zone_drain(void)
374 struct uma_bucket_zone *ubz;
376 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
377 zone_drain(ubz->ubz_zone);
381 zone_log_warning(uma_zone_t zone)
383 static const struct timeval warninterval = { 300, 0 };
385 if (!zone_warnings || zone->uz_warning == NULL)
388 if (ratecheck(&zone->uz_ratecheck, &warninterval))
389 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
393 zone_foreach_keg(uma_zone_t zone, void (*kegfn)(uma_keg_t))
397 LIST_FOREACH(klink, &zone->uz_kegs, kl_link)
398 kegfn(klink->kl_keg);
402 * Routine called by timeout which is used to fire off some time interval
403 * based calculations. (stats, hash size, etc.)
412 uma_timeout(void *unused)
415 zone_foreach(zone_timeout);
417 /* Reschedule this event */
418 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
422 * Routine to perform timeout driven calculations. This expands the
423 * hashes and does per cpu statistics aggregation.
428 keg_timeout(uma_keg_t keg)
433 * Expand the keg hash table.
435 * This is done if the number of slabs is larger than the hash size.
436 * What I'm trying to do here is completely reduce collisions. This
437 * may be a little aggressive. Should I allow for two collisions max?
439 if (keg->uk_flags & UMA_ZONE_HASH &&
440 keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
441 struct uma_hash newhash;
442 struct uma_hash oldhash;
446 * This is so involved because allocating and freeing
447 * while the keg lock is held will lead to deadlock.
448 * I have to do everything in stages and check for
451 newhash = keg->uk_hash;
453 ret = hash_alloc(&newhash);
456 if (hash_expand(&keg->uk_hash, &newhash)) {
457 oldhash = keg->uk_hash;
458 keg->uk_hash = newhash;
471 zone_timeout(uma_zone_t zone)
474 zone_foreach_keg(zone, &keg_timeout);
478 * Allocate and zero fill the next sized hash table from the appropriate
482 * hash A new hash structure with the old hash size in uh_hashsize
485 * 1 on sucess and 0 on failure.
488 hash_alloc(struct uma_hash *hash)
493 oldsize = hash->uh_hashsize;
495 /* We're just going to go to a power of two greater */
497 hash->uh_hashsize = oldsize * 2;
498 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
499 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
500 M_UMAHASH, M_NOWAIT);
502 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
503 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
505 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
507 if (hash->uh_slab_hash) {
508 bzero(hash->uh_slab_hash, alloc);
509 hash->uh_hashmask = hash->uh_hashsize - 1;
517 * Expands the hash table for HASH zones. This is done from zone_timeout
518 * to reduce collisions. This must not be done in the regular allocation
519 * path, otherwise, we can recurse on the vm while allocating pages.
522 * oldhash The hash you want to expand
523 * newhash The hash structure for the new table
531 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
537 if (!newhash->uh_slab_hash)
540 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
544 * I need to investigate hash algorithms for resizing without a
548 for (i = 0; i < oldhash->uh_hashsize; i++)
549 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[i])) {
550 slab = SLIST_FIRST(&oldhash->uh_slab_hash[i]);
551 SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[i], us_hlink);
552 hval = UMA_HASH(newhash, slab->us_data);
553 SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
561 * Free the hash bucket to the appropriate backing store.
564 * slab_hash The hash bucket we're freeing
565 * hashsize The number of entries in that hash bucket
571 hash_free(struct uma_hash *hash)
573 if (hash->uh_slab_hash == NULL)
575 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
576 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
578 free(hash->uh_slab_hash, M_UMAHASH);
582 * Frees all outstanding items in a bucket
585 * zone The zone to free to, must be unlocked.
586 * bucket The free/alloc bucket with items, cpu queue must be locked.
593 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
601 for (i = 0; i < bucket->ub_cnt; i++)
602 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
603 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
608 * Drains the per cpu caches for a zone.
610 * NOTE: This may only be called while the zone is being turn down, and not
611 * during normal operation. This is necessary in order that we do not have
612 * to migrate CPUs to drain the per-CPU caches.
615 * zone The zone to drain, must be unlocked.
621 cache_drain(uma_zone_t zone)
627 * XXX: It is safe to not lock the per-CPU caches, because we're
628 * tearing down the zone anyway. I.e., there will be no further use
629 * of the caches at this point.
631 * XXX: It would good to be able to assert that the zone is being
632 * torn down to prevent improper use of cache_drain().
634 * XXX: We lock the zone before passing into bucket_cache_drain() as
635 * it is used elsewhere. Should the tear-down path be made special
636 * there in some form?
639 cache = &zone->uz_cpu[cpu];
640 bucket_drain(zone, cache->uc_allocbucket);
641 bucket_drain(zone, cache->uc_freebucket);
642 if (cache->uc_allocbucket != NULL)
643 bucket_free(cache->uc_allocbucket);
644 if (cache->uc_freebucket != NULL)
645 bucket_free(cache->uc_freebucket);
646 cache->uc_allocbucket = cache->uc_freebucket = NULL;
649 bucket_cache_drain(zone);
654 * Drain the cached buckets from a zone. Expects a locked zone on entry.
657 bucket_cache_drain(uma_zone_t zone)
662 * Drain the bucket queues and free the buckets, we just keep two per
665 while ((bucket = LIST_FIRST(&zone->uz_full_bucket)) != NULL) {
666 LIST_REMOVE(bucket, ub_link);
668 bucket_drain(zone, bucket);
673 /* Now we do the free queue.. */
674 while ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
675 LIST_REMOVE(bucket, ub_link);
681 * Frees pages from a keg back to the system. This is done on demand from
682 * the pageout daemon.
687 keg_drain(uma_keg_t keg)
689 struct slabhead freeslabs = { 0 };
697 * We don't want to take pages from statically allocated kegs at this
700 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
704 printf("%s free items: %u\n", keg->uk_name, keg->uk_free);
707 if (keg->uk_free == 0)
710 slab = LIST_FIRST(&keg->uk_free_slab);
712 n = LIST_NEXT(slab, us_link);
714 /* We have no where to free these to */
715 if (slab->us_flags & UMA_SLAB_BOOT) {
720 LIST_REMOVE(slab, us_link);
721 keg->uk_pages -= keg->uk_ppera;
722 keg->uk_free -= keg->uk_ipers;
724 if (keg->uk_flags & UMA_ZONE_HASH)
725 UMA_HASH_REMOVE(&keg->uk_hash, slab, slab->us_data);
727 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
734 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
735 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
737 for (i = 0; i < keg->uk_ipers; i++)
739 slab->us_data + (keg->uk_rsize * i),
741 flags = slab->us_flags;
744 if (keg->uk_flags & UMA_ZONE_VTOSLAB) {
747 if (flags & UMA_SLAB_KMEM)
749 else if (flags & UMA_SLAB_KERNEL)
753 for (i = 0; i < keg->uk_ppera; i++)
754 vsetobj((vm_offset_t)mem + (i * PAGE_SIZE),
757 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
758 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
760 printf("%s: Returning %d bytes.\n",
761 keg->uk_name, PAGE_SIZE * keg->uk_ppera);
763 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
768 zone_drain_wait(uma_zone_t zone, int waitok)
772 * Set draining to interlock with zone_dtor() so we can release our
773 * locks as we go. Only dtor() should do a WAITOK call since it
774 * is the only call that knows the structure will still be available
778 while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
779 if (waitok == M_NOWAIT)
781 mtx_unlock(&uma_mtx);
782 msleep(zone, zone->uz_lock, PVM, "zonedrain", 1);
785 zone->uz_flags |= UMA_ZFLAG_DRAINING;
786 bucket_cache_drain(zone);
789 * The DRAINING flag protects us from being freed while
790 * we're running. Normally the uma_mtx would protect us but we
791 * must be able to release and acquire the right lock for each keg.
793 zone_foreach_keg(zone, &keg_drain);
795 zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
802 zone_drain(uma_zone_t zone)
805 zone_drain_wait(zone, M_NOWAIT);
809 * Allocate a new slab for a keg. This does not insert the slab onto a list.
812 * wait Shall we wait?
815 * The slab that was allocated or NULL if there is no memory and the
816 * caller specified M_NOWAIT.
819 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int wait)
821 uma_slabrefcnt_t slabref;
828 mtx_assert(&keg->uk_lock, MA_OWNED);
832 printf("alloc_slab: Allocating a new slab for %s\n", keg->uk_name);
834 allocf = keg->uk_allocf;
837 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
838 slab = zone_alloc_item(keg->uk_slabzone, NULL, wait);
846 * This reproduces the old vm_zone behavior of zero filling pages the
847 * first time they are added to a zone.
849 * Malloced items are zeroed in uma_zalloc.
852 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
857 if (keg->uk_flags & UMA_ZONE_NODUMP)
860 /* zone is passed for legacy reasons. */
861 mem = allocf(zone, keg->uk_ppera * PAGE_SIZE, &flags, wait);
863 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
864 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
869 /* Point the slab into the allocated memory */
870 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
871 slab = (uma_slab_t )(mem + keg->uk_pgoff);
873 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
874 for (i = 0; i < keg->uk_ppera; i++)
875 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
879 slab->us_freecount = keg->uk_ipers;
880 slab->us_flags = flags;
881 BIT_FILL(SLAB_SETSIZE, &slab->us_free);
883 BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
885 if (keg->uk_flags & UMA_ZONE_REFCNT) {
886 slabref = (uma_slabrefcnt_t)slab;
887 for (i = 0; i < keg->uk_ipers; i++)
888 slabref->us_refcnt[i] = 0;
891 if (keg->uk_init != NULL) {
892 for (i = 0; i < keg->uk_ipers; i++)
893 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
894 keg->uk_size, wait) != 0)
896 if (i != keg->uk_ipers) {
897 if (keg->uk_fini != NULL) {
898 for (i--; i > -1; i--)
899 keg->uk_fini(slab->us_data +
903 if (keg->uk_flags & UMA_ZONE_VTOSLAB) {
906 if (flags & UMA_SLAB_KMEM)
908 else if (flags & UMA_SLAB_KERNEL)
912 for (i = 0; i < keg->uk_ppera; i++)
913 vsetobj((vm_offset_t)mem +
914 (i * PAGE_SIZE), obj);
916 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
917 zone_free_item(keg->uk_slabzone, slab,
919 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera,
927 if (keg->uk_flags & UMA_ZONE_HASH)
928 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
930 keg->uk_pages += keg->uk_ppera;
931 keg->uk_free += keg->uk_ipers;
937 * This function is intended to be used early on in place of page_alloc() so
938 * that we may use the boot time page cache to satisfy allocations before
942 startup_alloc(uma_zone_t zone, int bytes, uint8_t *pflag, int wait)
946 int pages, check_pages;
948 keg = zone_first_keg(zone);
949 pages = howmany(bytes, PAGE_SIZE);
950 check_pages = pages - 1;
951 KASSERT(pages > 0, ("startup_alloc can't reserve 0 pages\n"));
954 * Check our small startup cache to see if it has pages remaining.
956 mtx_lock(&uma_boot_pages_mtx);
958 /* First check if we have enough room. */
959 tmps = LIST_FIRST(&uma_boot_pages);
960 while (tmps != NULL && check_pages-- > 0)
961 tmps = LIST_NEXT(tmps, us_link);
964 * It's ok to lose tmps references. The last one will
965 * have tmps->us_data pointing to the start address of
966 * "pages" contiguous pages of memory.
968 while (pages-- > 0) {
969 tmps = LIST_FIRST(&uma_boot_pages);
970 LIST_REMOVE(tmps, us_link);
972 mtx_unlock(&uma_boot_pages_mtx);
973 *pflag = tmps->us_flags;
974 return (tmps->us_data);
976 mtx_unlock(&uma_boot_pages_mtx);
977 if (booted < UMA_STARTUP2)
978 panic("UMA: Increase vm.boot_pages");
980 * Now that we've booted reset these users to their real allocator.
982 #ifdef UMA_MD_SMALL_ALLOC
983 keg->uk_allocf = (keg->uk_ppera > 1) ? page_alloc : uma_small_alloc;
985 keg->uk_allocf = page_alloc;
987 return keg->uk_allocf(zone, bytes, pflag, wait);
991 * Allocates a number of pages from the system
994 * bytes The number of bytes requested
995 * wait Shall we wait?
998 * A pointer to the alloced memory or possibly
999 * NULL if M_NOWAIT is set.
1002 page_alloc(uma_zone_t zone, int bytes, uint8_t *pflag, int wait)
1004 void *p; /* Returned page */
1006 *pflag = UMA_SLAB_KMEM;
1007 p = (void *) kmem_malloc(kmem_map, bytes, wait);
1013 * Allocates a number of pages from within an object
1016 * bytes The number of bytes requested
1017 * wait Shall we wait?
1020 * A pointer to the alloced memory or possibly
1021 * NULL if M_NOWAIT is set.
1024 noobj_alloc(uma_zone_t zone, int bytes, uint8_t *flags, int wait)
1026 TAILQ_HEAD(, vm_page) alloctail;
1028 vm_offset_t retkva, zkva;
1029 vm_page_t p, p_next;
1032 TAILQ_INIT(&alloctail);
1033 keg = zone_first_keg(zone);
1035 npages = howmany(bytes, PAGE_SIZE);
1036 while (npages > 0) {
1037 p = vm_page_alloc(NULL, 0, VM_ALLOC_INTERRUPT |
1038 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ);
1041 * Since the page does not belong to an object, its
1044 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1048 if (wait & M_WAITOK) {
1054 * Page allocation failed, free intermediate pages and
1057 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1058 vm_page_unwire(p, 0);
1063 *flags = UMA_SLAB_PRIV;
1064 zkva = keg->uk_kva +
1065 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1067 TAILQ_FOREACH(p, &alloctail, listq) {
1068 pmap_qenter(zkva, &p, 1);
1072 return ((void *)retkva);
1076 * Frees a number of pages to the system
1079 * mem A pointer to the memory to be freed
1080 * size The size of the memory being freed
1081 * flags The original p->us_flags field
1087 page_free(void *mem, int size, uint8_t flags)
1091 if (flags & UMA_SLAB_KMEM)
1093 else if (flags & UMA_SLAB_KERNEL)
1096 panic("UMA: page_free used with invalid flags %d", flags);
1098 kmem_free(map, (vm_offset_t)mem, size);
1102 * Zero fill initializer
1104 * Arguments/Returns follow uma_init specifications
1107 zero_init(void *mem, int size, int flags)
1114 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1117 * keg The zone we should initialize
1123 keg_small_init(uma_keg_t keg)
1130 if (keg->uk_flags & UMA_ZONE_PCPU) {
1131 KASSERT(mp_ncpus > 0, ("%s: ncpus %d\n", __func__, mp_ncpus));
1132 keg->uk_slabsize = sizeof(struct pcpu);
1133 keg->uk_ppera = howmany(mp_ncpus * sizeof(struct pcpu),
1136 keg->uk_slabsize = UMA_SLAB_SIZE;
1141 * Calculate the size of each allocation (rsize) according to
1142 * alignment. If the requested size is smaller than we have
1143 * allocation bits for we round it up.
1145 rsize = keg->uk_size;
1146 if (rsize < keg->uk_slabsize / SLAB_SETSIZE)
1147 rsize = keg->uk_slabsize / SLAB_SETSIZE;
1148 if (rsize & keg->uk_align)
1149 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1150 keg->uk_rsize = rsize;
1152 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1153 keg->uk_rsize < sizeof(struct pcpu),
1154 ("%s: size %u too large", __func__, keg->uk_rsize));
1156 if (keg->uk_flags & UMA_ZONE_REFCNT)
1157 rsize += sizeof(uint32_t);
1159 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1162 shsize = sizeof(struct uma_slab);
1164 keg->uk_ipers = (keg->uk_slabsize - shsize) / rsize;
1165 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1166 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1168 memused = keg->uk_ipers * rsize + shsize;
1169 wastedspace = keg->uk_slabsize - memused;
1172 * We can't do OFFPAGE if we're internal or if we've been
1173 * asked to not go to the VM for buckets. If we do this we
1174 * may end up going to the VM (kmem_map) for slabs which we
1175 * do not want to do if we're UMA_ZFLAG_CACHEONLY as a
1176 * result of UMA_ZONE_VM, which clearly forbids it.
1178 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1179 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1183 * See if using an OFFPAGE slab will limit our waste. Only do
1184 * this if it permits more items per-slab.
1186 * XXX We could try growing slabsize to limit max waste as well.
1187 * Historically this was not done because the VM could not
1188 * efficiently handle contiguous allocations.
1190 if ((wastedspace >= keg->uk_slabsize / UMA_MAX_WASTE) &&
1191 (keg->uk_ipers < (keg->uk_slabsize / keg->uk_rsize))) {
1192 keg->uk_ipers = keg->uk_slabsize / keg->uk_rsize;
1193 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1194 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1196 printf("UMA decided we need offpage slab headers for "
1197 "keg: %s, calculated wastedspace = %d, "
1198 "maximum wasted space allowed = %d, "
1199 "calculated ipers = %d, "
1200 "new wasted space = %d\n", keg->uk_name, wastedspace,
1201 keg->uk_slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1202 keg->uk_slabsize - keg->uk_ipers * keg->uk_rsize);
1204 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1207 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1208 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1209 keg->uk_flags |= UMA_ZONE_HASH;
1213 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1214 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1218 * keg The keg we should initialize
1224 keg_large_init(uma_keg_t keg)
1227 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1228 KASSERT((keg->uk_flags & UMA_ZFLAG_CACHEONLY) == 0,
1229 ("keg_large_init: Cannot large-init a UMA_ZFLAG_CACHEONLY keg"));
1230 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1231 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1233 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1234 keg->uk_slabsize = keg->uk_ppera * PAGE_SIZE;
1236 keg->uk_rsize = keg->uk_size;
1238 /* We can't do OFFPAGE if we're internal, bail out here. */
1239 if (keg->uk_flags & UMA_ZFLAG_INTERNAL)
1242 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1243 if ((keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1244 keg->uk_flags |= UMA_ZONE_HASH;
1248 keg_cachespread_init(uma_keg_t keg)
1255 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1256 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1258 alignsize = keg->uk_align + 1;
1259 rsize = keg->uk_size;
1261 * We want one item to start on every align boundary in a page. To
1262 * do this we will span pages. We will also extend the item by the
1263 * size of align if it is an even multiple of align. Otherwise, it
1264 * would fall on the same boundary every time.
1266 if (rsize & keg->uk_align)
1267 rsize = (rsize & ~keg->uk_align) + alignsize;
1268 if ((rsize & alignsize) == 0)
1270 trailer = rsize - keg->uk_size;
1271 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1272 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1273 keg->uk_rsize = rsize;
1274 keg->uk_ppera = pages;
1275 keg->uk_slabsize = UMA_SLAB_SIZE;
1276 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1277 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1278 KASSERT(keg->uk_ipers <= uma_max_ipers,
1279 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1284 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1285 * the keg onto the global keg list.
1287 * Arguments/Returns follow uma_ctor specifications
1288 * udata Actually uma_kctor_args
1291 keg_ctor(void *mem, int size, void *udata, int flags)
1293 struct uma_kctor_args *arg = udata;
1294 uma_keg_t keg = mem;
1298 keg->uk_size = arg->size;
1299 keg->uk_init = arg->uminit;
1300 keg->uk_fini = arg->fini;
1301 keg->uk_align = arg->align;
1304 keg->uk_flags = arg->flags;
1305 keg->uk_allocf = page_alloc;
1306 keg->uk_freef = page_free;
1307 keg->uk_recurse = 0;
1308 keg->uk_slabzone = NULL;
1311 * The master zone is passed to us at keg-creation time.
1314 keg->uk_name = zone->uz_name;
1316 if (arg->flags & UMA_ZONE_VM)
1317 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1319 if (arg->flags & UMA_ZONE_ZINIT)
1320 keg->uk_init = zero_init;
1322 if (arg->flags & UMA_ZONE_REFCNT || arg->flags & UMA_ZONE_MALLOC)
1323 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1325 if (arg->flags & UMA_ZONE_PCPU)
1327 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1329 keg->uk_flags &= ~UMA_ZONE_PCPU;
1332 if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1333 keg_cachespread_init(keg);
1334 } else if (keg->uk_flags & UMA_ZONE_REFCNT) {
1336 (UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt) -
1338 keg_large_init(keg);
1340 keg_small_init(keg);
1342 if (keg->uk_size > (UMA_SLAB_SIZE - sizeof(struct uma_slab)))
1343 keg_large_init(keg);
1345 keg_small_init(keg);
1348 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1349 if (keg->uk_flags & UMA_ZONE_REFCNT) {
1350 if (keg->uk_ipers > uma_max_ipers_ref)
1351 panic("Too many ref items per zone: %d > %d\n",
1352 keg->uk_ipers, uma_max_ipers_ref);
1353 keg->uk_slabzone = slabrefzone;
1355 keg->uk_slabzone = slabzone;
1359 * If we haven't booted yet we need allocations to go through the
1360 * startup cache until the vm is ready.
1362 if (keg->uk_ppera == 1) {
1363 #ifdef UMA_MD_SMALL_ALLOC
1364 keg->uk_allocf = uma_small_alloc;
1365 keg->uk_freef = uma_small_free;
1367 if (booted < UMA_STARTUP)
1368 keg->uk_allocf = startup_alloc;
1370 if (booted < UMA_STARTUP2)
1371 keg->uk_allocf = startup_alloc;
1373 } else if (booted < UMA_STARTUP2 &&
1374 (keg->uk_flags & UMA_ZFLAG_INTERNAL))
1375 keg->uk_allocf = startup_alloc;
1378 * Initialize keg's lock (shared among zones).
1380 if (arg->flags & UMA_ZONE_MTXCLASS)
1381 KEG_LOCK_INIT(keg, 1);
1383 KEG_LOCK_INIT(keg, 0);
1386 * If we're putting the slab header in the actual page we need to
1387 * figure out where in each page it goes. This calculates a right
1388 * justified offset into the memory on an ALIGN_PTR boundary.
1390 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1393 /* Size of the slab struct and free list */
1394 totsize = sizeof(struct uma_slab);
1396 /* Size of the reference counts. */
1397 if (keg->uk_flags & UMA_ZONE_REFCNT)
1398 totsize += keg->uk_ipers * sizeof(uint32_t);
1400 if (totsize & UMA_ALIGN_PTR)
1401 totsize = (totsize & ~UMA_ALIGN_PTR) +
1402 (UMA_ALIGN_PTR + 1);
1403 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - totsize;
1406 * The only way the following is possible is if with our
1407 * UMA_ALIGN_PTR adjustments we are now bigger than
1408 * UMA_SLAB_SIZE. I haven't checked whether this is
1409 * mathematically possible for all cases, so we make
1412 totsize = keg->uk_pgoff + sizeof(struct uma_slab);
1413 if (keg->uk_flags & UMA_ZONE_REFCNT)
1414 totsize += keg->uk_ipers * sizeof(uint32_t);
1415 if (totsize > PAGE_SIZE * keg->uk_ppera) {
1416 printf("zone %s ipers %d rsize %d size %d\n",
1417 zone->uz_name, keg->uk_ipers, keg->uk_rsize,
1419 panic("UMA slab won't fit.");
1423 if (keg->uk_flags & UMA_ZONE_HASH)
1424 hash_alloc(&keg->uk_hash);
1427 printf("UMA: %s(%p) size %d(%d) flags %#x ipers %d ppera %d out %d free %d\n",
1428 zone->uz_name, zone, keg->uk_size, keg->uk_rsize, keg->uk_flags,
1429 keg->uk_ipers, keg->uk_ppera,
1430 (keg->uk_ipers * keg->uk_pages) - keg->uk_free, keg->uk_free);
1433 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1436 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1437 mtx_unlock(&uma_mtx);
1442 * Zone header ctor. This initializes all fields, locks, etc.
1444 * Arguments/Returns follow uma_ctor specifications
1445 * udata Actually uma_zctor_args
1448 zone_ctor(void *mem, int size, void *udata, int flags)
1450 struct uma_zctor_args *arg = udata;
1451 uma_zone_t zone = mem;
1456 zone->uz_name = arg->name;
1457 zone->uz_ctor = arg->ctor;
1458 zone->uz_dtor = arg->dtor;
1459 zone->uz_slab = zone_fetch_slab;
1460 zone->uz_init = NULL;
1461 zone->uz_fini = NULL;
1462 zone->uz_allocs = 0;
1465 zone->uz_sleeps = 0;
1466 zone->uz_fills = zone->uz_count = 0;
1468 zone->uz_warning = NULL;
1469 timevalclear(&zone->uz_ratecheck);
1473 * This is a pure cache zone, no kegs.
1476 zone->uz_import = arg->import;
1477 zone->uz_release = arg->release;
1478 zone->uz_arg = arg->arg;
1479 zone->uz_count = BUCKET_MAX;
1484 * Use the regular zone/keg/slab allocator.
1486 zone->uz_import = (uma_import)zone_import;
1487 zone->uz_release = (uma_release)zone_release;
1488 zone->uz_arg = zone;
1490 if (arg->flags & UMA_ZONE_SECONDARY) {
1491 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1492 zone->uz_init = arg->uminit;
1493 zone->uz_fini = arg->fini;
1494 zone->uz_lock = &keg->uk_lock;
1495 zone->uz_flags |= UMA_ZONE_SECONDARY;
1498 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1499 if (LIST_NEXT(z, uz_link) == NULL) {
1500 LIST_INSERT_AFTER(z, zone, uz_link);
1505 mtx_unlock(&uma_mtx);
1506 } else if (keg == NULL) {
1507 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1508 arg->align, arg->flags)) == NULL)
1511 struct uma_kctor_args karg;
1514 /* We should only be here from uma_startup() */
1515 karg.size = arg->size;
1516 karg.uminit = arg->uminit;
1517 karg.fini = arg->fini;
1518 karg.align = arg->align;
1519 karg.flags = arg->flags;
1521 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1528 * Link in the first keg.
1530 zone->uz_klink.kl_keg = keg;
1531 LIST_INSERT_HEAD(&zone->uz_kegs, &zone->uz_klink, kl_link);
1532 zone->uz_lock = &keg->uk_lock;
1533 zone->uz_size = keg->uk_size;
1534 zone->uz_flags |= (keg->uk_flags &
1535 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1538 * Some internal zones don't have room allocated for the per cpu
1539 * caches. If we're internal, bail out here.
1541 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1542 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1543 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1547 if (keg->uk_flags & UMA_ZONE_MAXBUCKET)
1548 zone->uz_count = BUCKET_MAX;
1549 else if (keg->uk_ipers <= BUCKET_MAX)
1550 zone->uz_count = keg->uk_ipers;
1552 zone->uz_count = BUCKET_MAX;
1557 * Keg header dtor. This frees all data, destroys locks, frees the hash
1558 * table and removes the keg from the global list.
1560 * Arguments/Returns follow uma_dtor specifications
1564 keg_dtor(void *arg, int size, void *udata)
1568 keg = (uma_keg_t)arg;
1570 if (keg->uk_free != 0) {
1571 printf("Freed UMA keg was not empty (%d items). "
1572 " Lost %d pages of memory.\n",
1573 keg->uk_free, keg->uk_pages);
1577 hash_free(&keg->uk_hash);
1585 * Arguments/Returns follow uma_dtor specifications
1589 zone_dtor(void *arg, int size, void *udata)
1595 zone = (uma_zone_t)arg;
1596 keg = zone_first_keg(zone);
1598 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1602 LIST_REMOVE(zone, uz_link);
1603 mtx_unlock(&uma_mtx);
1605 * XXX there are some races here where
1606 * the zone can be drained but zone lock
1607 * released and then refilled before we
1608 * remove it... we dont care for now
1610 zone_drain_wait(zone, M_WAITOK);
1612 * Unlink all of our kegs.
1614 while ((klink = LIST_FIRST(&zone->uz_kegs)) != NULL) {
1615 klink->kl_keg = NULL;
1616 LIST_REMOVE(klink, kl_link);
1617 if (klink == &zone->uz_klink)
1619 free(klink, M_TEMP);
1622 * We only destroy kegs from non secondary zones.
1624 if (keg != NULL && (zone->uz_flags & UMA_ZONE_SECONDARY) == 0) {
1626 LIST_REMOVE(keg, uk_link);
1627 mtx_unlock(&uma_mtx);
1628 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1633 * Traverses every zone in the system and calls a callback
1636 * zfunc A pointer to a function which accepts a zone
1643 zone_foreach(void (*zfunc)(uma_zone_t))
1649 LIST_FOREACH(keg, &uma_kegs, uk_link) {
1650 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1653 mtx_unlock(&uma_mtx);
1656 /* Public functions */
1659 uma_startup(void *bootmem, int boot_pages)
1661 struct uma_zctor_args args;
1667 printf("Creating uma keg headers zone and keg.\n");
1669 mtx_init(&uma_mtx, "UMA lock", NULL, MTX_DEF);
1671 /* "manually" create the initial zone */
1672 memset(&args, 0, sizeof(args));
1673 args.name = "UMA Kegs";
1674 args.size = sizeof(struct uma_keg);
1675 args.ctor = keg_ctor;
1676 args.dtor = keg_dtor;
1677 args.uminit = zero_init;
1679 args.keg = &masterkeg;
1680 args.align = 32 - 1;
1681 args.flags = UMA_ZFLAG_INTERNAL;
1682 /* The initial zone has no Per cpu queues so it's smaller */
1683 zone_ctor(kegs, sizeof(struct uma_zone), &args, M_WAITOK);
1686 printf("Filling boot free list.\n");
1688 for (i = 0; i < boot_pages; i++) {
1689 slab = (uma_slab_t)((uint8_t *)bootmem + (i * UMA_SLAB_SIZE));
1690 slab->us_data = (uint8_t *)slab;
1691 slab->us_flags = UMA_SLAB_BOOT;
1692 LIST_INSERT_HEAD(&uma_boot_pages, slab, us_link);
1694 mtx_init(&uma_boot_pages_mtx, "UMA boot pages", NULL, MTX_DEF);
1697 printf("Creating uma zone headers zone and keg.\n");
1699 args.name = "UMA Zones";
1700 args.size = sizeof(struct uma_zone) +
1701 (sizeof(struct uma_cache) * (mp_maxid + 1));
1702 args.ctor = zone_ctor;
1703 args.dtor = zone_dtor;
1704 args.uminit = zero_init;
1707 args.align = 32 - 1;
1708 args.flags = UMA_ZFLAG_INTERNAL;
1709 /* The initial zone has no Per cpu queues so it's smaller */
1710 zone_ctor(zones, sizeof(struct uma_zone), &args, M_WAITOK);
1713 printf("Initializing pcpu cache locks.\n");
1716 printf("Creating slab and hash zones.\n");
1719 /* Now make a zone for slab headers */
1720 slabzone = uma_zcreate("UMA Slabs",
1721 sizeof(struct uma_slab),
1722 NULL, NULL, NULL, NULL,
1723 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1726 * We also create a zone for the bigger slabs with reference
1727 * counts in them, to accomodate UMA_ZONE_REFCNT zones.
1729 slabsize = sizeof(struct uma_slab_refcnt);
1730 slabsize += uma_max_ipers_ref * sizeof(uint32_t);
1731 slabrefzone = uma_zcreate("UMA RCntSlabs",
1733 NULL, NULL, NULL, NULL,
1735 UMA_ZFLAG_INTERNAL);
1737 hashzone = uma_zcreate("UMA Hash",
1738 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
1739 NULL, NULL, NULL, NULL,
1740 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1744 booted = UMA_STARTUP;
1747 printf("UMA startup complete.\n");
1755 booted = UMA_STARTUP2;
1758 printf("UMA startup2 complete.\n");
1763 * Initialize our callout handle
1771 printf("Starting callout.\n");
1773 callout_init(&uma_callout, CALLOUT_MPSAFE);
1774 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
1776 printf("UMA startup3 complete.\n");
1781 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
1782 int align, uint32_t flags)
1784 struct uma_kctor_args args;
1787 args.uminit = uminit;
1789 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
1792 return (zone_alloc_item(kegs, &args, M_WAITOK));
1797 uma_set_align(int align)
1800 if (align != UMA_ALIGN_CACHE)
1801 uma_align_cache = align;
1806 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
1807 uma_init uminit, uma_fini fini, int align, uint32_t flags)
1810 struct uma_zctor_args args;
1812 /* This stuff is essential for the zone ctor */
1813 memset(&args, 0, sizeof(args));
1818 args.uminit = uminit;
1824 return (zone_alloc_item(zones, &args, M_WAITOK));
1829 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
1830 uma_init zinit, uma_fini zfini, uma_zone_t master)
1832 struct uma_zctor_args args;
1835 keg = zone_first_keg(master);
1836 memset(&args, 0, sizeof(args));
1838 args.size = keg->uk_size;
1841 args.uminit = zinit;
1843 args.align = keg->uk_align;
1844 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
1847 /* XXX Attaches only one keg of potentially many. */
1848 return (zone_alloc_item(zones, &args, M_WAITOK));
1853 uma_zcache_create(char *name, uma_ctor ctor, uma_dtor dtor, uma_init zinit,
1854 uma_fini zfini, uma_import zimport, uma_release zrelease,
1855 void *arg, int flags)
1857 struct uma_zctor_args args;
1859 memset(&args, 0, sizeof(args));
1864 args.uminit = zinit;
1866 args.import = zimport;
1867 args.release = zrelease;
1872 return (zone_alloc_item(zones, &args, M_WAITOK));
1876 zone_lock_pair(uma_zone_t a, uma_zone_t b)
1880 mtx_lock_flags(b->uz_lock, MTX_DUPOK);
1883 mtx_lock_flags(a->uz_lock, MTX_DUPOK);
1888 zone_unlock_pair(uma_zone_t a, uma_zone_t b)
1896 uma_zsecond_add(uma_zone_t zone, uma_zone_t master)
1903 klink = malloc(sizeof(*klink), M_TEMP, M_WAITOK | M_ZERO);
1905 zone_lock_pair(zone, master);
1907 * zone must use vtoslab() to resolve objects and must already be
1910 if ((zone->uz_flags & (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY))
1911 != (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY)) {
1916 * The new master must also use vtoslab().
1918 if ((zone->uz_flags & UMA_ZONE_VTOSLAB) != UMA_ZONE_VTOSLAB) {
1923 * Both must either be refcnt, or not be refcnt.
1925 if ((zone->uz_flags & UMA_ZONE_REFCNT) !=
1926 (master->uz_flags & UMA_ZONE_REFCNT)) {
1931 * The underlying object must be the same size. rsize
1934 if (master->uz_size != zone->uz_size) {
1939 * Put it at the end of the list.
1941 klink->kl_keg = zone_first_keg(master);
1942 LIST_FOREACH(kl, &zone->uz_kegs, kl_link) {
1943 if (LIST_NEXT(kl, kl_link) == NULL) {
1944 LIST_INSERT_AFTER(kl, klink, kl_link);
1949 zone->uz_flags |= UMA_ZFLAG_MULTI;
1950 zone->uz_slab = zone_fetch_slab_multi;
1953 zone_unlock_pair(zone, master);
1955 free(klink, M_TEMP);
1963 uma_zdestroy(uma_zone_t zone)
1966 zone_free_item(zones, zone, NULL, SKIP_NONE);
1971 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
1975 uma_bucket_t bucket;
1978 /* This is the fast path allocation */
1979 #ifdef UMA_DEBUG_ALLOC_1
1980 printf("Allocating one item from %s(%p)\n", zone->uz_name, zone);
1982 CTR3(KTR_UMA, "uma_zalloc_arg thread %x zone %s flags %d", curthread,
1983 zone->uz_name, flags);
1985 if (flags & M_WAITOK) {
1986 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1987 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
1989 #ifdef DEBUG_MEMGUARD
1990 if (memguard_cmp_zone(zone)) {
1991 item = memguard_alloc(zone->uz_size, flags);
1994 * Avoid conflict with the use-after-free
1995 * protecting infrastructure from INVARIANTS.
1997 if (zone->uz_init != NULL &&
1998 zone->uz_init != mtrash_init &&
1999 zone->uz_init(item, zone->uz_size, flags) != 0)
2001 if (zone->uz_ctor != NULL &&
2002 zone->uz_ctor != mtrash_ctor &&
2003 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2004 zone->uz_fini(item, zone->uz_size);
2009 /* This is unfortunate but should not be fatal. */
2013 * If possible, allocate from the per-CPU cache. There are two
2014 * requirements for safe access to the per-CPU cache: (1) the thread
2015 * accessing the cache must not be preempted or yield during access,
2016 * and (2) the thread must not migrate CPUs without switching which
2017 * cache it accesses. We rely on a critical section to prevent
2018 * preemption and migration. We release the critical section in
2019 * order to acquire the zone mutex if we are unable to allocate from
2020 * the current cache; when we re-acquire the critical section, we
2021 * must detect and handle migration if it has occurred.
2026 cache = &zone->uz_cpu[cpu];
2029 bucket = cache->uc_allocbucket;
2032 if (bucket->ub_cnt > 0) {
2034 item = bucket->ub_bucket[bucket->ub_cnt];
2036 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2038 KASSERT(item != NULL,
2039 ("uma_zalloc: Bucket pointer mangled."));
2042 if (zone->uz_ctor != NULL) {
2043 if (zone->uz_ctor(item, zone->uz_size,
2044 udata, flags) != 0) {
2045 atomic_add_long(&zone->uz_fails, 1);
2046 zone_free_item(zone, item, udata,
2052 uma_dbg_alloc(zone, NULL, item);
2055 bzero(item, zone->uz_size);
2057 } else if (cache->uc_freebucket) {
2059 * We have run out of items in our allocbucket.
2060 * See if we can switch with our free bucket.
2062 if (cache->uc_freebucket->ub_cnt > 0) {
2063 #ifdef UMA_DEBUG_ALLOC
2064 printf("uma_zalloc: Swapping empty with"
2067 bucket = cache->uc_freebucket;
2068 cache->uc_freebucket = cache->uc_allocbucket;
2069 cache->uc_allocbucket = bucket;
2076 * Attempt to retrieve the item from the per-CPU cache has failed, so
2077 * we must go back to the zone. This requires the zone lock, so we
2078 * must drop the critical section, then re-acquire it when we go back
2079 * to the cache. Since the critical section is released, we may be
2080 * preempted or migrate. As such, make sure not to maintain any
2081 * thread-local state specific to the cache from prior to releasing
2082 * the critical section.
2088 cache = &zone->uz_cpu[cpu];
2089 bucket = cache->uc_allocbucket;
2090 if (bucket != NULL) {
2091 if (bucket->ub_cnt > 0) {
2095 bucket = cache->uc_freebucket;
2096 if (bucket != NULL && bucket->ub_cnt > 0) {
2102 /* Since we have locked the zone we may as well send back our stats */
2103 atomic_add_long(&zone->uz_allocs, cache->uc_allocs);
2104 atomic_add_long(&zone->uz_frees, cache->uc_frees);
2105 cache->uc_allocs = 0;
2106 cache->uc_frees = 0;
2108 /* Our old one is now a free bucket */
2109 if (cache->uc_allocbucket) {
2110 KASSERT(cache->uc_allocbucket->ub_cnt == 0,
2111 ("uma_zalloc_arg: Freeing a non free bucket."));
2112 LIST_INSERT_HEAD(&zone->uz_free_bucket,
2113 cache->uc_allocbucket, ub_link);
2114 cache->uc_allocbucket = NULL;
2117 /* Check the free list for a new alloc bucket */
2118 if ((bucket = LIST_FIRST(&zone->uz_full_bucket)) != NULL) {
2119 KASSERT(bucket->ub_cnt != 0,
2120 ("uma_zalloc_arg: Returning an empty bucket."));
2122 LIST_REMOVE(bucket, ub_link);
2123 cache->uc_allocbucket = bucket;
2127 /* We are no longer associated with this CPU. */
2130 /* Bump up our uz_count so we get here less */
2131 if (zone->uz_count < BUCKET_MAX)
2135 * Now lets just fill a bucket and put it on the free list. If that
2136 * works we'll restart the allocation from the begining.
2138 if (zone_alloc_bucket(zone, flags)) {
2140 goto zalloc_restart;
2144 * We may not be able to get a bucket so return an actual item.
2147 printf("uma_zalloc_arg: Bucketzone returned NULL\n");
2150 item = zone_alloc_item(zone, udata, flags);
2155 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int flags)
2159 mtx_assert(&keg->uk_lock, MA_OWNED);
2164 * Find a slab with some space. Prefer slabs that are partially
2165 * used over those that are totally full. This helps to reduce
2168 if (keg->uk_free != 0) {
2169 if (!LIST_EMPTY(&keg->uk_part_slab)) {
2170 slab = LIST_FIRST(&keg->uk_part_slab);
2172 slab = LIST_FIRST(&keg->uk_free_slab);
2173 LIST_REMOVE(slab, us_link);
2174 LIST_INSERT_HEAD(&keg->uk_part_slab, slab,
2177 MPASS(slab->us_keg == keg);
2182 * M_NOVM means don't ask at all!
2187 if (keg->uk_maxpages && keg->uk_pages >= keg->uk_maxpages) {
2188 keg->uk_flags |= UMA_ZFLAG_FULL;
2190 * If this is not a multi-zone, set the FULL bit.
2191 * Otherwise slab_multi() takes care of it.
2193 if ((zone->uz_flags & UMA_ZFLAG_MULTI) == 0) {
2194 zone->uz_flags |= UMA_ZFLAG_FULL;
2195 zone_log_warning(zone);
2197 if (flags & M_NOWAIT)
2200 msleep(keg, &keg->uk_lock, PVM, "keglimit", 0);
2204 slab = keg_alloc_slab(keg, zone, flags);
2207 * If we got a slab here it's safe to mark it partially used
2208 * and return. We assume that the caller is going to remove
2209 * at least one item.
2212 MPASS(slab->us_keg == keg);
2213 LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
2217 * We might not have been able to get a slab but another cpu
2218 * could have while we were unlocked. Check again before we
2227 zone_relock(uma_zone_t zone, uma_keg_t keg)
2229 if (zone->uz_lock != &keg->uk_lock) {
2236 keg_relock(uma_keg_t keg, uma_zone_t zone)
2238 if (zone->uz_lock != &keg->uk_lock) {
2245 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int flags)
2250 keg = zone_first_keg(zone);
2252 * This is to prevent us from recursively trying to allocate
2253 * buckets. The problem is that if an allocation forces us to
2254 * grab a new bucket we will call page_alloc, which will go off
2255 * and cause the vm to allocate vm_map_entries. If we need new
2256 * buckets there too we will recurse in kmem_alloc and bad
2257 * things happen. So instead we return a NULL bucket, and make
2258 * the code that allocates buckets smart enough to deal with it
2260 if (keg->uk_flags & UMA_ZFLAG_BUCKET && keg->uk_recurse != 0)
2264 slab = keg_fetch_slab(keg, zone, flags);
2267 if (flags & (M_NOWAIT | M_NOVM))
2274 * uma_zone_fetch_slab_multi: Fetches a slab from one available keg. Returns
2275 * with the keg locked. Caller must call zone_relock() afterwards if the
2276 * zone lock is required. On NULL the zone lock is held.
2278 * The last pointer is used to seed the search. It is not required.
2281 zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int rflags)
2291 * Don't wait on the first pass. This will skip limit tests
2292 * as well. We don't want to block if we can find a provider
2295 flags = (rflags & ~M_WAITOK) | M_NOWAIT;
2297 * Use the last slab allocated as a hint for where to start
2301 slab = keg_fetch_slab(last, zone, flags);
2304 zone_relock(zone, last);
2308 * Loop until we have a slab incase of transient failures
2309 * while M_WAITOK is specified. I'm not sure this is 100%
2310 * required but we've done it for so long now.
2316 * Search the available kegs for slabs. Be careful to hold the
2317 * correct lock while calling into the keg layer.
2319 LIST_FOREACH(klink, &zone->uz_kegs, kl_link) {
2320 keg = klink->kl_keg;
2321 keg_relock(keg, zone);
2322 if ((keg->uk_flags & UMA_ZFLAG_FULL) == 0) {
2323 slab = keg_fetch_slab(keg, zone, flags);
2327 if (keg->uk_flags & UMA_ZFLAG_FULL)
2331 zone_relock(zone, keg);
2333 if (rflags & (M_NOWAIT | M_NOVM))
2337 * All kegs are full. XXX We can't atomically check all kegs
2338 * and sleep so just sleep for a short period and retry.
2340 if (full && !empty) {
2341 zone->uz_flags |= UMA_ZFLAG_FULL;
2343 zone_log_warning(zone);
2344 msleep(zone, zone->uz_lock, PVM, "zonelimit", hz/100);
2345 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2353 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2358 MPASS(keg == slab->us_keg);
2359 mtx_assert(&keg->uk_lock, MA_OWNED);
2361 freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2362 BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2363 item = slab->us_data + (keg->uk_rsize * freei);
2364 slab->us_freecount--;
2367 /* Move this slab to the full list */
2368 if (slab->us_freecount == 0) {
2369 LIST_REMOVE(slab, us_link);
2370 LIST_INSERT_HEAD(&keg->uk_full_slab, slab, us_link);
2377 zone_import(uma_zone_t zone, void **bucket, int max, int flags)
2384 /* Try to keep the buckets totally full */
2387 for (i = 0; i < max; ) {
2388 if ((slab = zone->uz_slab(zone, keg, flags)) == NULL)
2391 while (slab->us_freecount && i < max)
2392 bucket[i++] = slab_alloc_item(keg, slab);
2394 /* Don't block on the next fill */
2407 zone_alloc_bucket(uma_zone_t zone, int flags)
2409 uma_bucket_t bucket;
2415 * This code is here to limit the number of simultaneous bucket fills
2416 * for any given zone to the number of per cpu caches in this zone. This
2417 * is done so that we don't allocate more memory than we really need.
2419 if (zone->uz_fills >= mp_ncpus)
2424 max = zone->uz_count;
2427 * Try this zone's free list first so we don't allocate extra buckets.
2429 if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
2430 KASSERT(bucket->ub_cnt == 0,
2431 ("zone_alloc_bucket: Bucket on free list is not empty."));
2432 LIST_REMOVE(bucket, ub_link);
2435 bflags = (flags & ~M_ZERO);
2436 if (zone->uz_flags & UMA_ZFLAG_CACHEONLY)
2439 bucket = bucket_alloc(zone->uz_count, bflags);
2444 max = MIN(bucket->ub_entries, max);
2445 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
2449 * Initialize the memory if necessary.
2451 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
2454 for (i = 0; i < bucket->ub_cnt; i++)
2455 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2459 * If we couldn't initialize the whole bucket, put the
2460 * rest back onto the freelist.
2462 if (i != bucket->ub_cnt) {
2463 zone->uz_release(zone->uz_arg, bucket->ub_bucket[i],
2464 bucket->ub_cnt - i);
2466 bzero(&bucket->ub_bucket[i],
2467 sizeof(void *) * (bucket->ub_cnt - i));
2476 if (bucket != NULL && bucket->ub_cnt != 0) {
2477 LIST_INSERT_HEAD(&zone->uz_full_bucket,
2481 atomic_add_long(&zone->uz_fails, 1);
2483 bucket_free(bucket);
2488 * Allocates a single item from a zone.
2491 * zone The zone to alloc for.
2492 * udata The data to be passed to the constructor.
2493 * flags M_WAITOK, M_NOWAIT, M_ZERO.
2496 * NULL if there is no memory and M_NOWAIT is set
2497 * An item if successful
2501 zone_alloc_item(uma_zone_t zone, void *udata, int flags)
2507 #ifdef UMA_DEBUG_ALLOC
2508 printf("INTERNAL: Allocating one item from %s(%p)\n", zone->uz_name, zone);
2510 if (zone->uz_import(zone->uz_arg, &item, 1, flags) != 1)
2512 atomic_add_long(&zone->uz_allocs, 1);
2515 * We have to call both the zone's init (not the keg's init)
2516 * and the zone's ctor. This is because the item is going from
2517 * a keg slab directly to the user, and the user is expecting it
2518 * to be both zone-init'd as well as zone-ctor'd.
2520 if (zone->uz_init != NULL) {
2521 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
2522 zone_free_item(zone, item, udata, SKIP_FINI);
2526 if (zone->uz_ctor != NULL) {
2527 if (zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2528 zone_free_item(zone, item, udata, SKIP_DTOR);
2533 uma_dbg_alloc(zone, NULL, item);
2536 bzero(item, zone->uz_size);
2541 atomic_add_long(&zone->uz_fails, 1);
2547 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
2550 uma_bucket_t bucket;
2554 #ifdef UMA_DEBUG_ALLOC_1
2555 printf("Freeing item %p to %s(%p)\n", item, zone->uz_name, zone);
2557 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
2560 /* uma_zfree(..., NULL) does nothing, to match free(9). */
2563 #ifdef DEBUG_MEMGUARD
2564 if (is_memguard_addr(item)) {
2565 if (zone->uz_dtor != NULL && zone->uz_dtor != mtrash_dtor)
2566 zone->uz_dtor(item, zone->uz_size, udata);
2567 if (zone->uz_fini != NULL && zone->uz_fini != mtrash_fini)
2568 zone->uz_fini(item, zone->uz_size);
2569 memguard_free(item);
2574 if (zone->uz_flags & UMA_ZONE_MALLOC)
2575 uma_dbg_free(zone, udata, item);
2577 uma_dbg_free(zone, NULL, item);
2580 zone->uz_dtor(item, zone->uz_size, udata);
2583 * The race here is acceptable. If we miss it we'll just have to wait
2584 * a little longer for the limits to be reset.
2586 if (zone->uz_flags & UMA_ZFLAG_FULL)
2587 goto zfree_internal;
2590 * If possible, free to the per-CPU cache. There are two
2591 * requirements for safe access to the per-CPU cache: (1) the thread
2592 * accessing the cache must not be preempted or yield during access,
2593 * and (2) the thread must not migrate CPUs without switching which
2594 * cache it accesses. We rely on a critical section to prevent
2595 * preemption and migration. We release the critical section in
2596 * order to acquire the zone mutex if we are unable to free to the
2597 * current cache; when we re-acquire the critical section, we must
2598 * detect and handle migration if it has occurred.
2603 cache = &zone->uz_cpu[cpu];
2606 bucket = cache->uc_freebucket;
2610 * Do we have room in our bucket? It is OK for this uz count
2611 * check to be slightly out of sync.
2614 if (bucket->ub_cnt < bucket->ub_entries) {
2615 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
2616 ("uma_zfree: Freeing to non free bucket index."));
2617 bucket->ub_bucket[bucket->ub_cnt] = item;
2622 } else if (cache->uc_allocbucket) {
2623 #ifdef UMA_DEBUG_ALLOC
2624 printf("uma_zfree: Swapping buckets.\n");
2627 * We have run out of space in our freebucket.
2628 * See if we can switch with our alloc bucket.
2630 if (cache->uc_allocbucket->ub_cnt <
2631 cache->uc_freebucket->ub_cnt) {
2632 bucket = cache->uc_freebucket;
2633 cache->uc_freebucket = cache->uc_allocbucket;
2634 cache->uc_allocbucket = bucket;
2640 * We can get here for two reasons:
2642 * 1) The buckets are NULL
2643 * 2) The alloc and free buckets are both somewhat full.
2645 * We must go back the zone, which requires acquiring the zone lock,
2646 * which in turn means we must release and re-acquire the critical
2647 * section. Since the critical section is released, we may be
2648 * preempted or migrate. As such, make sure not to maintain any
2649 * thread-local state specific to the cache from prior to releasing
2650 * the critical section.
2656 cache = &zone->uz_cpu[cpu];
2657 if (cache->uc_freebucket != NULL) {
2658 if (cache->uc_freebucket->ub_cnt <
2659 cache->uc_freebucket->ub_entries) {
2663 if (cache->uc_allocbucket != NULL &&
2664 (cache->uc_allocbucket->ub_cnt <
2665 cache->uc_freebucket->ub_cnt)) {
2671 /* Since we have locked the zone we may as well send back our stats */
2672 atomic_add_long(&zone->uz_allocs, cache->uc_allocs);
2673 atomic_add_long(&zone->uz_frees, cache->uc_frees);
2674 cache->uc_allocs = 0;
2675 cache->uc_frees = 0;
2677 bucket = cache->uc_freebucket;
2678 cache->uc_freebucket = NULL;
2680 /* Can we throw this on the zone full list? */
2681 if (bucket != NULL) {
2682 #ifdef UMA_DEBUG_ALLOC
2683 printf("uma_zfree: Putting old bucket on the free list.\n");
2685 /* ub_cnt is pointing to the last free item */
2686 KASSERT(bucket->ub_cnt != 0,
2687 ("uma_zfree: Attempting to insert an empty bucket onto the full list.\n"));
2688 LIST_INSERT_HEAD(&zone->uz_full_bucket,
2691 if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
2692 LIST_REMOVE(bucket, ub_link);
2694 cache->uc_freebucket = bucket;
2697 /* We are no longer associated with this CPU. */
2700 /* And the zone.. */
2703 #ifdef UMA_DEBUG_ALLOC
2704 printf("uma_zfree: Allocating new free bucket.\n");
2708 if (zone->uz_flags & UMA_ZFLAG_CACHEONLY)
2710 bucket = bucket_alloc(zone->uz_count, bflags);
2713 LIST_INSERT_HEAD(&zone->uz_free_bucket,
2720 * If nothing else caught this, we'll just do an internal free.
2723 zone_free_item(zone, item, udata, SKIP_DTOR);
2729 slab_free_item(uma_keg_t keg, uma_slab_t slab, void *item)
2733 mtx_assert(&keg->uk_lock, MA_OWNED);
2734 MPASS(keg == slab->us_keg);
2736 /* Do we need to remove from any lists? */
2737 if (slab->us_freecount+1 == keg->uk_ipers) {
2738 LIST_REMOVE(slab, us_link);
2739 LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
2740 } else if (slab->us_freecount == 0) {
2741 LIST_REMOVE(slab, us_link);
2742 LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
2745 /* Slab management. */
2746 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
2747 BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
2748 slab->us_freecount++;
2750 /* Keg statistics. */
2755 zone_release(uma_zone_t zone, void **bucket, int cnt)
2766 keg = zone_first_keg(zone);
2767 for (i = 0; i < cnt; i++) {
2769 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
2770 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
2771 if (zone->uz_flags & UMA_ZONE_HASH) {
2772 slab = hash_sfind(&keg->uk_hash, mem);
2774 mem += keg->uk_pgoff;
2775 slab = (uma_slab_t)mem;
2778 slab = vtoslab((vm_offset_t)item);
2779 if (slab->us_keg != keg) {
2785 slab_free_item(keg, slab, item);
2786 if (keg->uk_flags & UMA_ZFLAG_FULL) {
2787 if (keg->uk_pages < keg->uk_maxpages) {
2788 keg->uk_flags &= ~UMA_ZFLAG_FULL;
2793 * We can handle one more allocation. Since we're
2794 * clearing ZFLAG_FULL, wake up all procs blocked
2795 * on pages. This should be uncommon, so keeping this
2796 * simple for now (rather than adding count of blocked
2802 zone_relock(zone, keg);
2804 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2812 * Frees a single item to any zone.
2815 * zone The zone to free to
2816 * item The item we're freeing
2817 * udata User supplied data for the dtor
2818 * skip Skip dtors and finis
2821 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
2825 if (skip == SKIP_NONE) {
2826 if (zone->uz_flags & UMA_ZONE_MALLOC)
2827 uma_dbg_free(zone, udata, item);
2829 uma_dbg_free(zone, NULL, item);
2832 if (skip < SKIP_DTOR && zone->uz_dtor)
2833 zone->uz_dtor(item, zone->uz_size, udata);
2835 if (skip < SKIP_FINI && zone->uz_fini)
2836 zone->uz_fini(item, zone->uz_size);
2838 atomic_add_long(&zone->uz_frees, 1);
2839 zone->uz_release(zone->uz_arg, &item, 1);
2844 uma_zone_set_max(uma_zone_t zone, int nitems)
2848 keg = zone_first_keg(zone);
2852 keg->uk_maxpages = (nitems / keg->uk_ipers) * keg->uk_ppera;
2853 if (keg->uk_maxpages * keg->uk_ipers < nitems)
2854 keg->uk_maxpages += keg->uk_ppera;
2855 nitems = keg->uk_maxpages * keg->uk_ipers;
2863 uma_zone_get_max(uma_zone_t zone)
2868 keg = zone_first_keg(zone);
2872 nitems = keg->uk_maxpages * keg->uk_ipers;
2880 uma_zone_set_warning(uma_zone_t zone, const char *warning)
2884 zone->uz_warning = warning;
2890 uma_zone_get_cur(uma_zone_t zone)
2896 nitems = zone->uz_allocs - zone->uz_frees;
2899 * See the comment in sysctl_vm_zone_stats() regarding the
2900 * safety of accessing the per-cpu caches. With the zone lock
2901 * held, it is safe, but can potentially result in stale data.
2903 nitems += zone->uz_cpu[i].uc_allocs -
2904 zone->uz_cpu[i].uc_frees;
2908 return (nitems < 0 ? 0 : nitems);
2913 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
2918 keg = zone_first_keg(zone);
2919 KASSERT(keg != NULL, ("uma_zone_set_init: Invalid zone type"));
2920 KASSERT(keg->uk_pages == 0,
2921 ("uma_zone_set_init on non-empty keg"));
2922 keg->uk_init = uminit;
2928 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
2933 keg = zone_first_keg(zone);
2934 KASSERT(keg != NULL, ("uma_zone_set_init: Invalid zone type"));
2935 KASSERT(keg->uk_pages == 0,
2936 ("uma_zone_set_fini on non-empty keg"));
2937 keg->uk_fini = fini;
2943 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
2946 KASSERT(zone_first_keg(zone)->uk_pages == 0,
2947 ("uma_zone_set_zinit on non-empty keg"));
2948 zone->uz_init = zinit;
2954 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
2957 KASSERT(zone_first_keg(zone)->uk_pages == 0,
2958 ("uma_zone_set_zfini on non-empty keg"));
2959 zone->uz_fini = zfini;
2964 /* XXX uk_freef is not actually used with the zone locked */
2966 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
2971 keg = zone_first_keg(zone);
2972 KASSERT(keg != NULL, ("uma_zone_set_init: Invalid zone type"));
2973 keg->uk_freef = freef;
2978 /* XXX uk_allocf is not actually used with the zone locked */
2980 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
2985 keg = zone_first_keg(zone);
2986 keg->uk_flags |= UMA_ZFLAG_PRIVALLOC;
2987 keg->uk_allocf = allocf;
2993 uma_zone_reserve_kva(uma_zone_t zone, int count)
2999 keg = zone_first_keg(zone);
3002 pages = count / keg->uk_ipers;
3004 if (pages * keg->uk_ipers < count)
3007 #ifdef UMA_MD_SMALL_ALLOC
3008 if (keg->uk_ppera > 1) {
3012 kva = kmem_alloc_nofault(kernel_map, pages * UMA_SLAB_SIZE);
3020 keg->uk_maxpages = pages;
3021 #ifdef UMA_MD_SMALL_ALLOC
3022 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3024 keg->uk_allocf = noobj_alloc;
3026 keg->uk_flags |= UMA_ZONE_NOFREE | UMA_ZFLAG_PRIVALLOC;
3033 uma_prealloc(uma_zone_t zone, int items)
3039 keg = zone_first_keg(zone);
3043 slabs = items / keg->uk_ipers;
3044 if (slabs * keg->uk_ipers < items)
3047 slab = keg_alloc_slab(keg, zone, M_WAITOK);
3050 MPASS(slab->us_keg == keg);
3051 LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
3059 uma_find_refcnt(uma_zone_t zone, void *item)
3061 uma_slabrefcnt_t slabref;
3067 slab = vtoslab((vm_offset_t)item & (~UMA_SLAB_MASK));
3068 slabref = (uma_slabrefcnt_t)slab;
3070 KASSERT(keg->uk_flags & UMA_ZONE_REFCNT,
3071 ("uma_find_refcnt(): zone possibly not UMA_ZONE_REFCNT"));
3072 idx = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3073 refcnt = &slabref->us_refcnt[idx];
3082 printf("UMA: vm asked us to release pages!\n");
3085 zone_foreach(zone_drain);
3087 * Some slabs may have been freed but this zone will be visited early
3088 * we visit again so that we can free pages that are empty once other
3089 * zones are drained. We have to do the same for buckets.
3091 zone_drain(slabzone);
3092 zone_drain(slabrefzone);
3093 bucket_zone_drain();
3098 uma_zone_exhausted(uma_zone_t zone)
3103 full = (zone->uz_flags & UMA_ZFLAG_FULL);
3109 uma_zone_exhausted_nolock(uma_zone_t zone)
3111 return (zone->uz_flags & UMA_ZFLAG_FULL);
3115 uma_large_malloc(int size, int wait)
3121 slab = zone_alloc_item(slabzone, NULL, wait);
3124 mem = page_alloc(NULL, size, &flags, wait);
3126 vsetslab((vm_offset_t)mem, slab);
3127 slab->us_data = mem;
3128 slab->us_flags = flags | UMA_SLAB_MALLOC;
3129 slab->us_size = size;
3131 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3138 uma_large_free(uma_slab_t slab)
3140 vsetobj((vm_offset_t)slab->us_data, kmem_object);
3141 page_free(slab->us_data, slab->us_size, slab->us_flags);
3142 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3146 uma_print_stats(void)
3148 zone_foreach(uma_print_zone);
3152 slab_print(uma_slab_t slab)
3154 printf("slab: keg %p, data %p, freecount %d\n",
3155 slab->us_keg, slab->us_data, slab->us_freecount);
3159 cache_print(uma_cache_t cache)
3161 printf("alloc: %p(%d), free: %p(%d)\n",
3162 cache->uc_allocbucket,
3163 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3164 cache->uc_freebucket,
3165 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3169 uma_print_keg(uma_keg_t keg)
3173 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3174 "out %d free %d limit %d\n",
3175 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3176 keg->uk_ipers, keg->uk_ppera,
3177 (keg->uk_ipers * keg->uk_pages) - keg->uk_free, keg->uk_free,
3178 (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers);
3179 printf("Part slabs:\n");
3180 LIST_FOREACH(slab, &keg->uk_part_slab, us_link)
3182 printf("Free slabs:\n");
3183 LIST_FOREACH(slab, &keg->uk_free_slab, us_link)
3185 printf("Full slabs:\n");
3186 LIST_FOREACH(slab, &keg->uk_full_slab, us_link)
3191 uma_print_zone(uma_zone_t zone)
3197 printf("zone: %s(%p) size %d flags %#x\n",
3198 zone->uz_name, zone, zone->uz_size, zone->uz_flags);
3199 LIST_FOREACH(kl, &zone->uz_kegs, kl_link)
3200 uma_print_keg(kl->kl_keg);
3202 cache = &zone->uz_cpu[i];
3203 printf("CPU %d Cache:\n", i);
3210 * Generate statistics across both the zone and its per-cpu cache's. Return
3211 * desired statistics if the pointer is non-NULL for that statistic.
3213 * Note: does not update the zone statistics, as it can't safely clear the
3214 * per-CPU cache statistic.
3216 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3217 * safe from off-CPU; we should modify the caches to track this information
3218 * directly so that we don't have to.
3221 uma_zone_sumstat(uma_zone_t z, int *cachefreep, uint64_t *allocsp,
3222 uint64_t *freesp, uint64_t *sleepsp)
3225 uint64_t allocs, frees, sleeps;
3228 allocs = frees = sleeps = 0;
3231 cache = &z->uz_cpu[cpu];
3232 if (cache->uc_allocbucket != NULL)
3233 cachefree += cache->uc_allocbucket->ub_cnt;
3234 if (cache->uc_freebucket != NULL)
3235 cachefree += cache->uc_freebucket->ub_cnt;
3236 allocs += cache->uc_allocs;
3237 frees += cache->uc_frees;
3239 allocs += z->uz_allocs;
3240 frees += z->uz_frees;
3241 sleeps += z->uz_sleeps;
3242 if (cachefreep != NULL)
3243 *cachefreep = cachefree;
3244 if (allocsp != NULL)
3248 if (sleepsp != NULL)
3254 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3262 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3263 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3266 mtx_unlock(&uma_mtx);
3267 return (sysctl_handle_int(oidp, &count, 0, req));
3271 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3273 struct uma_stream_header ush;
3274 struct uma_type_header uth;
3275 struct uma_percpu_stat ups;
3276 uma_bucket_t bucket;
3283 int count, error, i;
3285 error = sysctl_wire_old_buffer(req, 0);
3288 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3292 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3293 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3298 * Insert stream header.
3300 bzero(&ush, sizeof(ush));
3301 ush.ush_version = UMA_STREAM_VERSION;
3302 ush.ush_maxcpus = (mp_maxid + 1);
3303 ush.ush_count = count;
3304 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
3306 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3307 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3308 bzero(&uth, sizeof(uth));
3310 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3311 uth.uth_align = kz->uk_align;
3312 uth.uth_size = kz->uk_size;
3313 uth.uth_rsize = kz->uk_rsize;
3314 LIST_FOREACH(kl, &z->uz_kegs, kl_link) {
3316 uth.uth_maxpages += k->uk_maxpages;
3317 uth.uth_pages += k->uk_pages;
3318 uth.uth_keg_free += k->uk_free;
3319 uth.uth_limit = (k->uk_maxpages / k->uk_ppera)
3324 * A zone is secondary is it is not the first entry
3325 * on the keg's zone list.
3327 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
3328 (LIST_FIRST(&kz->uk_zones) != z))
3329 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
3331 LIST_FOREACH(bucket, &z->uz_full_bucket, ub_link)
3332 uth.uth_zone_free += bucket->ub_cnt;
3333 uth.uth_allocs = z->uz_allocs;
3334 uth.uth_frees = z->uz_frees;
3335 uth.uth_fails = z->uz_fails;
3336 uth.uth_sleeps = z->uz_sleeps;
3337 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
3339 * While it is not normally safe to access the cache
3340 * bucket pointers while not on the CPU that owns the
3341 * cache, we only allow the pointers to be exchanged
3342 * without the zone lock held, not invalidated, so
3343 * accept the possible race associated with bucket
3344 * exchange during monitoring.
3346 for (i = 0; i < (mp_maxid + 1); i++) {
3347 bzero(&ups, sizeof(ups));
3348 if (kz->uk_flags & UMA_ZFLAG_INTERNAL)
3352 cache = &z->uz_cpu[i];
3353 if (cache->uc_allocbucket != NULL)
3354 ups.ups_cache_free +=
3355 cache->uc_allocbucket->ub_cnt;
3356 if (cache->uc_freebucket != NULL)
3357 ups.ups_cache_free +=
3358 cache->uc_freebucket->ub_cnt;
3359 ups.ups_allocs = cache->uc_allocs;
3360 ups.ups_frees = cache->uc_frees;
3362 (void)sbuf_bcat(&sbuf, &ups, sizeof(ups));
3367 mtx_unlock(&uma_mtx);
3368 error = sbuf_finish(&sbuf);
3374 DB_SHOW_COMMAND(uma, db_show_uma)
3376 uint64_t allocs, frees, sleeps;
3377 uma_bucket_t bucket;
3382 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
3383 "Requests", "Sleeps");
3384 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3385 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3386 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
3387 allocs = z->uz_allocs;
3388 frees = z->uz_frees;
3389 sleeps = z->uz_sleeps;
3392 uma_zone_sumstat(z, &cachefree, &allocs,
3394 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
3395 (LIST_FIRST(&kz->uk_zones) != z)))
3396 cachefree += kz->uk_free;
3397 LIST_FOREACH(bucket, &z->uz_full_bucket, ub_link)
3398 cachefree += bucket->ub_cnt;
3399 db_printf("%18s %8ju %8jd %8d %12ju %8ju\n", z->uz_name,
3400 (uintmax_t)kz->uk_size,
3401 (intmax_t)(allocs - frees), cachefree,
3402 (uintmax_t)allocs, sleeps);