2 * Copyright (c) 2002-2005, 2009 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/kernel.h>
67 #include <sys/types.h>
68 #include <sys/queue.h>
69 #include <sys/malloc.h>
72 #include <sys/sysctl.h>
73 #include <sys/mutex.h>
75 #include <sys/rwlock.h>
78 #include <sys/vmmeter.h>
81 #include <vm/vm_object.h>
82 #include <vm/vm_page.h>
83 #include <vm/vm_pageout.h>
84 #include <vm/vm_param.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_kern.h>
87 #include <vm/vm_extern.h>
89 #include <vm/uma_int.h>
90 #include <vm/uma_dbg.h>
95 #include <vm/memguard.h>
99 * This is the zone and keg from which all zones are spawned. The idea is that
100 * even the zone & keg heads are allocated from the allocator, so we use the
101 * bss section to bootstrap us.
103 static struct uma_keg masterkeg;
104 static struct uma_zone masterzone_k;
105 static struct uma_zone masterzone_z;
106 static uma_zone_t kegs = &masterzone_k;
107 static uma_zone_t zones = &masterzone_z;
109 /* This is the zone from which all of uma_slab_t's are allocated. */
110 static uma_zone_t slabzone;
111 static uma_zone_t slabrefzone; /* With refcounters (for UMA_ZONE_REFCNT) */
114 * The initial hash tables come out of this zone so they can be allocated
115 * prior to malloc coming up.
117 static uma_zone_t hashzone;
119 /* The boot-time adjusted value for cache line alignment. */
120 int uma_align_cache = 64 - 1;
122 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
125 * Are we allowed to allocate buckets?
127 static int bucketdisable = 1;
129 /* Linked list of all kegs in the system */
130 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
132 /* This mutex protects the keg list */
133 static struct mtx uma_mtx;
135 /* Linked list of boot time pages */
136 static LIST_HEAD(,uma_slab) uma_boot_pages =
137 LIST_HEAD_INITIALIZER(uma_boot_pages);
139 /* This mutex protects the boot time pages list */
140 static struct mtx uma_boot_pages_mtx;
142 /* Is the VM done starting up? */
143 static int booted = 0;
144 #define UMA_STARTUP 1
145 #define UMA_STARTUP2 2
147 /* Maximum number of allowed items-per-slab if the slab header is OFFPAGE */
148 static u_int uma_max_ipers;
149 static u_int uma_max_ipers_ref;
152 * This is the handle used to schedule events that need to happen
153 * outside of the allocation fast path.
155 static struct callout uma_callout;
156 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
159 * This structure is passed as the zone ctor arg so that I don't have to create
160 * a special allocation function just for zones.
162 struct uma_zctor_args {
174 struct uma_kctor_args {
183 struct uma_bucket_zone {
189 #define BUCKET_MAX 128
191 struct uma_bucket_zone bucket_zones[] = {
192 { NULL, "16 Bucket", 16 },
193 { NULL, "32 Bucket", 32 },
194 { NULL, "64 Bucket", 64 },
195 { NULL, "128 Bucket", 128 },
199 #define BUCKET_SHIFT 4
200 #define BUCKET_ZONES ((BUCKET_MAX >> BUCKET_SHIFT) + 1)
203 * bucket_size[] maps requested bucket sizes to zones that allocate a bucket
204 * of approximately the right size.
206 static uint8_t bucket_size[BUCKET_ZONES];
209 * Flags and enumerations to be passed to internal functions.
211 enum zfreeskip { SKIP_NONE, SKIP_DTOR, SKIP_FINI };
213 #define ZFREE_STATFAIL 0x00000001 /* Update zone failure statistic. */
214 #define ZFREE_STATFREE 0x00000002 /* Update zone free statistic. */
218 static void *noobj_alloc(uma_zone_t, int, uint8_t *, int);
219 static void *page_alloc(uma_zone_t, int, uint8_t *, int);
220 static void *startup_alloc(uma_zone_t, int, uint8_t *, int);
221 static void page_free(void *, int, uint8_t);
222 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int);
223 static void cache_drain(uma_zone_t);
224 static void bucket_drain(uma_zone_t, uma_bucket_t);
225 static void bucket_cache_drain(uma_zone_t zone);
226 static int keg_ctor(void *, int, void *, int);
227 static void keg_dtor(void *, int, void *);
228 static int zone_ctor(void *, int, void *, int);
229 static void zone_dtor(void *, int, void *);
230 static int zero_init(void *, int, int);
231 static void keg_small_init(uma_keg_t keg);
232 static void keg_large_init(uma_keg_t keg);
233 static void zone_foreach(void (*zfunc)(uma_zone_t));
234 static void zone_timeout(uma_zone_t zone);
235 static int hash_alloc(struct uma_hash *);
236 static int hash_expand(struct uma_hash *, struct uma_hash *);
237 static void hash_free(struct uma_hash *hash);
238 static void uma_timeout(void *);
239 static void uma_startup3(void);
240 static void *zone_alloc_item(uma_zone_t, void *, int);
241 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip,
243 static void bucket_enable(void);
244 static void bucket_init(void);
245 static uma_bucket_t bucket_alloc(int, int);
246 static void bucket_free(uma_bucket_t);
247 static void bucket_zone_drain(void);
248 static int zone_alloc_bucket(uma_zone_t zone, int flags);
249 static uma_slab_t zone_fetch_slab(uma_zone_t zone, uma_keg_t last, int flags);
250 static uma_slab_t zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int flags);
251 static void *slab_alloc_item(uma_zone_t zone, uma_slab_t slab);
252 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
253 uma_fini fini, int align, uint32_t flags);
254 static inline void zone_relock(uma_zone_t zone, uma_keg_t keg);
255 static inline void keg_relock(uma_keg_t keg, uma_zone_t zone);
257 void uma_print_zone(uma_zone_t);
258 void uma_print_stats(void);
259 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
260 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
262 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
264 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
265 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
267 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
268 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
270 static int zone_warnings = 1;
271 TUNABLE_INT("vm.zone_warnings", &zone_warnings);
272 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RW, &zone_warnings, 0,
273 "Warn when UMA zones becomes full");
276 * This routine checks to see whether or not it's safe to enable buckets.
282 bucketdisable = vm_page_count_min();
286 * Initialize bucket_zones, the array of zones of buckets of various sizes.
288 * For each zone, calculate the memory required for each bucket, consisting
289 * of the header and an array of pointers. Initialize bucket_size[] to point
290 * the range of appropriate bucket sizes at the zone.
295 struct uma_bucket_zone *ubz;
299 for (i = 0, j = 0; bucket_zones[j].ubz_entries != 0; j++) {
302 ubz = &bucket_zones[j];
303 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
304 size += sizeof(void *) * ubz->ubz_entries;
305 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
306 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
307 UMA_ZFLAG_INTERNAL | UMA_ZFLAG_BUCKET);
308 for (; i <= ubz->ubz_entries; i += (1 << BUCKET_SHIFT))
309 bucket_size[i >> BUCKET_SHIFT] = j;
314 * Given a desired number of entries for a bucket, return the zone from which
315 * to allocate the bucket.
317 static struct uma_bucket_zone *
318 bucket_zone_lookup(int entries)
322 idx = howmany(entries, 1 << BUCKET_SHIFT);
323 return (&bucket_zones[bucket_size[idx]]);
327 bucket_alloc(int entries, int bflags)
329 struct uma_bucket_zone *ubz;
333 * This is to stop us from allocating per cpu buckets while we're
334 * running out of vm.boot_pages. Otherwise, we would exhaust the
335 * boot pages. This also prevents us from allocating buckets in
336 * low memory situations.
341 ubz = bucket_zone_lookup(entries);
342 bucket = zone_alloc_item(ubz->ubz_zone, NULL, bflags);
345 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
348 bucket->ub_entries = ubz->ubz_entries;
355 bucket_free(uma_bucket_t bucket)
357 struct uma_bucket_zone *ubz;
359 ubz = bucket_zone_lookup(bucket->ub_entries);
360 zone_free_item(ubz->ubz_zone, bucket, NULL, SKIP_NONE,
365 bucket_zone_drain(void)
367 struct uma_bucket_zone *ubz;
369 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
370 zone_drain(ubz->ubz_zone);
374 zone_log_warning(uma_zone_t zone)
376 static const struct timeval warninterval = { 300, 0 };
378 if (!zone_warnings || zone->uz_warning == NULL)
381 if (ratecheck(&zone->uz_ratecheck, &warninterval))
382 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
385 static inline uma_keg_t
386 zone_first_keg(uma_zone_t zone)
389 return (LIST_FIRST(&zone->uz_kegs)->kl_keg);
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,
577 hash->uh_slab_hash, NULL, SKIP_NONE, ZFREE_STATFREE);
579 free(hash->uh_slab_hash, M_UMAHASH);
583 * Frees all outstanding items in a bucket
586 * zone The zone to free to, must be unlocked.
587 * bucket The free/alloc bucket with items, cpu queue must be locked.
594 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
601 while (bucket->ub_cnt > 0) {
603 item = bucket->ub_bucket[bucket->ub_cnt];
605 bucket->ub_bucket[bucket->ub_cnt] = NULL;
606 KASSERT(item != NULL,
607 ("bucket_drain: botched ptr, item is NULL"));
609 zone_free_item(zone, item, NULL, SKIP_DTOR, 0);
614 * Drains the per cpu caches for a zone.
616 * NOTE: This may only be called while the zone is being turn down, and not
617 * during normal operation. This is necessary in order that we do not have
618 * to migrate CPUs to drain the per-CPU caches.
621 * zone The zone to drain, must be unlocked.
627 cache_drain(uma_zone_t zone)
633 * XXX: It is safe to not lock the per-CPU caches, because we're
634 * tearing down the zone anyway. I.e., there will be no further use
635 * of the caches at this point.
637 * XXX: It would good to be able to assert that the zone is being
638 * torn down to prevent improper use of cache_drain().
640 * XXX: We lock the zone before passing into bucket_cache_drain() as
641 * it is used elsewhere. Should the tear-down path be made special
642 * there in some form?
645 cache = &zone->uz_cpu[cpu];
646 bucket_drain(zone, cache->uc_allocbucket);
647 bucket_drain(zone, cache->uc_freebucket);
648 if (cache->uc_allocbucket != NULL)
649 bucket_free(cache->uc_allocbucket);
650 if (cache->uc_freebucket != NULL)
651 bucket_free(cache->uc_freebucket);
652 cache->uc_allocbucket = cache->uc_freebucket = NULL;
655 bucket_cache_drain(zone);
660 * Drain the cached buckets from a zone. Expects a locked zone on entry.
663 bucket_cache_drain(uma_zone_t zone)
668 * Drain the bucket queues and free the buckets, we just keep two per
671 while ((bucket = LIST_FIRST(&zone->uz_full_bucket)) != NULL) {
672 LIST_REMOVE(bucket, ub_link);
674 bucket_drain(zone, bucket);
679 /* Now we do the free queue.. */
680 while ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
681 LIST_REMOVE(bucket, ub_link);
687 * Frees pages from a keg back to the system. This is done on demand from
688 * the pageout daemon.
693 keg_drain(uma_keg_t keg)
695 struct slabhead freeslabs = { 0 };
703 * We don't want to take pages from statically allocated kegs at this
706 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
710 printf("%s free items: %u\n", keg->uk_name, keg->uk_free);
713 if (keg->uk_free == 0)
716 slab = LIST_FIRST(&keg->uk_free_slab);
718 n = LIST_NEXT(slab, us_link);
720 /* We have no where to free these to */
721 if (slab->us_flags & UMA_SLAB_BOOT) {
726 LIST_REMOVE(slab, us_link);
727 keg->uk_pages -= keg->uk_ppera;
728 keg->uk_free -= keg->uk_ipers;
730 if (keg->uk_flags & UMA_ZONE_HASH)
731 UMA_HASH_REMOVE(&keg->uk_hash, slab, slab->us_data);
733 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
740 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
741 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
743 for (i = 0; i < keg->uk_ipers; i++)
745 slab->us_data + (keg->uk_rsize * i),
747 flags = slab->us_flags;
750 if (keg->uk_flags & UMA_ZONE_VTOSLAB) {
753 if (flags & UMA_SLAB_KMEM)
755 else if (flags & UMA_SLAB_KERNEL)
759 for (i = 0; i < keg->uk_ppera; i++)
760 vsetobj((vm_offset_t)mem + (i * PAGE_SIZE),
763 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
764 zone_free_item(keg->uk_slabzone, slab, NULL,
765 SKIP_NONE, ZFREE_STATFREE);
767 printf("%s: Returning %d bytes.\n",
768 keg->uk_name, PAGE_SIZE * keg->uk_ppera);
770 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
775 zone_drain_wait(uma_zone_t zone, int waitok)
779 * Set draining to interlock with zone_dtor() so we can release our
780 * locks as we go. Only dtor() should do a WAITOK call since it
781 * is the only call that knows the structure will still be available
785 while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
786 if (waitok == M_NOWAIT)
788 mtx_unlock(&uma_mtx);
789 msleep(zone, zone->uz_lock, PVM, "zonedrain", 1);
792 zone->uz_flags |= UMA_ZFLAG_DRAINING;
793 bucket_cache_drain(zone);
796 * The DRAINING flag protects us from being freed while
797 * we're running. Normally the uma_mtx would protect us but we
798 * must be able to release and acquire the right lock for each keg.
800 zone_foreach_keg(zone, &keg_drain);
802 zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
809 zone_drain(uma_zone_t zone)
812 zone_drain_wait(zone, M_NOWAIT);
816 * Allocate a new slab for a keg. This does not insert the slab onto a list.
819 * wait Shall we wait?
822 * The slab that was allocated or NULL if there is no memory and the
823 * caller specified M_NOWAIT.
826 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int wait)
828 uma_slabrefcnt_t slabref;
835 mtx_assert(&keg->uk_lock, MA_OWNED);
839 printf("slab_zalloc: Allocating a new slab for %s\n", keg->uk_name);
841 allocf = keg->uk_allocf;
844 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
845 slab = zone_alloc_item(keg->uk_slabzone, NULL, wait);
853 * This reproduces the old vm_zone behavior of zero filling pages the
854 * first time they are added to a zone.
856 * Malloced items are zeroed in uma_zalloc.
859 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
864 if (keg->uk_flags & UMA_ZONE_NODUMP)
867 /* zone is passed for legacy reasons. */
868 mem = allocf(zone, keg->uk_ppera * PAGE_SIZE, &flags, wait);
870 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
871 zone_free_item(keg->uk_slabzone, slab, NULL,
872 SKIP_NONE, ZFREE_STATFREE);
877 /* Point the slab into the allocated memory */
878 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
879 slab = (uma_slab_t )(mem + keg->uk_pgoff);
881 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
882 for (i = 0; i < keg->uk_ppera; i++)
883 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
887 slab->us_freecount = keg->uk_ipers;
888 slab->us_firstfree = 0;
889 slab->us_flags = flags;
891 if (keg->uk_flags & UMA_ZONE_REFCNT) {
892 slabref = (uma_slabrefcnt_t)slab;
893 for (i = 0; i < keg->uk_ipers; i++) {
894 slabref->us_freelist[i].us_refcnt = 0;
895 slabref->us_freelist[i].us_item = i+1;
898 for (i = 0; i < keg->uk_ipers; i++)
899 slab->us_freelist[i].us_item = i+1;
902 if (keg->uk_init != NULL) {
903 for (i = 0; i < keg->uk_ipers; i++)
904 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
905 keg->uk_size, wait) != 0)
907 if (i != keg->uk_ipers) {
908 if (keg->uk_fini != NULL) {
909 for (i--; i > -1; i--)
910 keg->uk_fini(slab->us_data +
914 if (keg->uk_flags & UMA_ZONE_VTOSLAB) {
917 if (flags & UMA_SLAB_KMEM)
919 else if (flags & UMA_SLAB_KERNEL)
923 for (i = 0; i < keg->uk_ppera; i++)
924 vsetobj((vm_offset_t)mem +
925 (i * PAGE_SIZE), obj);
927 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
928 zone_free_item(keg->uk_slabzone, slab,
929 NULL, SKIP_NONE, ZFREE_STATFREE);
930 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera,
938 if (keg->uk_flags & UMA_ZONE_HASH)
939 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
941 keg->uk_pages += keg->uk_ppera;
942 keg->uk_free += keg->uk_ipers;
948 * This function is intended to be used early on in place of page_alloc() so
949 * that we may use the boot time page cache to satisfy allocations before
953 startup_alloc(uma_zone_t zone, int bytes, uint8_t *pflag, int wait)
957 int pages, check_pages;
959 keg = zone_first_keg(zone);
960 pages = howmany(bytes, PAGE_SIZE);
961 check_pages = pages - 1;
962 KASSERT(pages > 0, ("startup_alloc can't reserve 0 pages\n"));
965 * Check our small startup cache to see if it has pages remaining.
967 mtx_lock(&uma_boot_pages_mtx);
969 /* First check if we have enough room. */
970 tmps = LIST_FIRST(&uma_boot_pages);
971 while (tmps != NULL && check_pages-- > 0)
972 tmps = LIST_NEXT(tmps, us_link);
975 * It's ok to lose tmps references. The last one will
976 * have tmps->us_data pointing to the start address of
977 * "pages" contiguous pages of memory.
979 while (pages-- > 0) {
980 tmps = LIST_FIRST(&uma_boot_pages);
981 LIST_REMOVE(tmps, us_link);
983 mtx_unlock(&uma_boot_pages_mtx);
984 *pflag = tmps->us_flags;
985 return (tmps->us_data);
987 mtx_unlock(&uma_boot_pages_mtx);
988 if (booted < UMA_STARTUP2)
989 panic("UMA: Increase vm.boot_pages");
991 * Now that we've booted reset these users to their real allocator.
993 #ifdef UMA_MD_SMALL_ALLOC
994 keg->uk_allocf = (keg->uk_ppera > 1) ? page_alloc : uma_small_alloc;
996 keg->uk_allocf = page_alloc;
998 return keg->uk_allocf(zone, bytes, pflag, wait);
1002 * Allocates a number of pages from the system
1005 * bytes The number of bytes requested
1006 * wait Shall we wait?
1009 * A pointer to the alloced memory or possibly
1010 * NULL if M_NOWAIT is set.
1013 page_alloc(uma_zone_t zone, int bytes, uint8_t *pflag, int wait)
1015 void *p; /* Returned page */
1017 *pflag = UMA_SLAB_KMEM;
1018 p = (void *) kmem_malloc(kmem_map, bytes, wait);
1024 * Allocates a number of pages from within an object
1027 * bytes The number of bytes requested
1028 * wait Shall we wait?
1031 * A pointer to the alloced memory or possibly
1032 * NULL if M_NOWAIT is set.
1035 noobj_alloc(uma_zone_t zone, int bytes, uint8_t *flags, int wait)
1037 TAILQ_HEAD(, vm_page) alloctail;
1039 vm_offset_t retkva, zkva;
1040 vm_page_t p, p_next;
1043 TAILQ_INIT(&alloctail);
1044 keg = zone_first_keg(zone);
1046 npages = howmany(bytes, PAGE_SIZE);
1047 while (npages > 0) {
1048 p = vm_page_alloc(NULL, 0, VM_ALLOC_INTERRUPT |
1049 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ);
1052 * Since the page does not belong to an object, its
1055 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1059 if (wait & M_WAITOK) {
1065 * Page allocation failed, free intermediate pages and
1068 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1069 vm_page_unwire(p, 0);
1074 *flags = UMA_SLAB_PRIV;
1075 zkva = keg->uk_kva +
1076 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1078 TAILQ_FOREACH(p, &alloctail, listq) {
1079 pmap_qenter(zkva, &p, 1);
1083 return ((void *)retkva);
1087 * Frees a number of pages to the system
1090 * mem A pointer to the memory to be freed
1091 * size The size of the memory being freed
1092 * flags The original p->us_flags field
1098 page_free(void *mem, int size, uint8_t flags)
1102 if (flags & UMA_SLAB_KMEM)
1104 else if (flags & UMA_SLAB_KERNEL)
1107 panic("UMA: page_free used with invalid flags %d", flags);
1109 kmem_free(map, (vm_offset_t)mem, size);
1113 * Zero fill initializer
1115 * Arguments/Returns follow uma_init specifications
1118 zero_init(void *mem, int size, int flags)
1125 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1128 * keg The zone we should initialize
1134 keg_small_init(uma_keg_t keg)
1141 if (keg->uk_flags & UMA_ZONE_PCPU) {
1142 KASSERT(mp_ncpus > 0, ("%s: ncpus %d\n", __func__, mp_ncpus));
1143 keg->uk_slabsize = sizeof(struct pcpu);
1144 keg->uk_ppera = howmany(mp_ncpus * sizeof(struct pcpu),
1147 keg->uk_slabsize = UMA_SLAB_SIZE;
1151 rsize = keg->uk_size;
1153 if (rsize & keg->uk_align)
1154 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1155 if (rsize < keg->uk_slabsize / 256)
1156 rsize = keg->uk_slabsize / 256;
1158 keg->uk_rsize = rsize;
1160 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1161 keg->uk_rsize < sizeof(struct pcpu),
1162 ("%s: size %u too large", __func__, keg->uk_rsize));
1164 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1166 } else if (keg->uk_flags & UMA_ZONE_REFCNT) {
1167 rsize += UMA_FRITMREF_SZ; /* linkage & refcnt */
1168 shsize = sizeof(struct uma_slab_refcnt);
1170 rsize += UMA_FRITM_SZ; /* Account for linkage */
1171 shsize = sizeof(struct uma_slab);
1174 keg->uk_ipers = (keg->uk_slabsize - shsize) / rsize;
1175 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= 256,
1176 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1178 memused = keg->uk_ipers * rsize + shsize;
1179 wastedspace = keg->uk_slabsize - memused;
1182 * We can't do OFFPAGE if we're internal or if we've been
1183 * asked to not go to the VM for buckets. If we do this we
1184 * may end up going to the VM (kmem_map) for slabs which we
1185 * do not want to do if we're UMA_ZFLAG_CACHEONLY as a
1186 * result of UMA_ZONE_VM, which clearly forbids it.
1188 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1189 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1192 if ((wastedspace >= keg->uk_slabsize / UMA_MAX_WASTE) &&
1193 (keg->uk_ipers < (keg->uk_slabsize / keg->uk_rsize))) {
1194 keg->uk_ipers = keg->uk_slabsize / keg->uk_rsize;
1195 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= 256,
1196 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1198 printf("UMA decided we need offpage slab headers for "
1199 "keg: %s, calculated wastedspace = %d, "
1200 "maximum wasted space allowed = %d, "
1201 "calculated ipers = %d, "
1202 "new wasted space = %d\n", keg->uk_name, wastedspace,
1203 keg->uk_slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1204 keg->uk_slabsize - keg->uk_ipers * keg->uk_rsize);
1206 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1209 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1210 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1211 keg->uk_flags |= UMA_ZONE_HASH;
1215 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1216 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1220 * keg The keg we should initialize
1226 keg_large_init(uma_keg_t keg)
1229 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1230 KASSERT((keg->uk_flags & UMA_ZFLAG_CACHEONLY) == 0,
1231 ("keg_large_init: Cannot large-init a UMA_ZFLAG_CACHEONLY keg"));
1232 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1233 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1235 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1236 keg->uk_slabsize = keg->uk_ppera * PAGE_SIZE;
1238 keg->uk_rsize = keg->uk_size;
1240 /* We can't do OFFPAGE if we're internal, bail out here. */
1241 if (keg->uk_flags & UMA_ZFLAG_INTERNAL)
1244 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1245 if ((keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1246 keg->uk_flags |= UMA_ZONE_HASH;
1250 keg_cachespread_init(uma_keg_t keg)
1257 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1258 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1260 alignsize = keg->uk_align + 1;
1261 rsize = keg->uk_size;
1263 * We want one item to start on every align boundary in a page. To
1264 * do this we will span pages. We will also extend the item by the
1265 * size of align if it is an even multiple of align. Otherwise, it
1266 * would fall on the same boundary every time.
1268 if (rsize & keg->uk_align)
1269 rsize = (rsize & ~keg->uk_align) + alignsize;
1270 if ((rsize & alignsize) == 0)
1272 trailer = rsize - keg->uk_size;
1273 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1274 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1275 keg->uk_rsize = rsize;
1276 keg->uk_ppera = pages;
1277 keg->uk_slabsize = UMA_SLAB_SIZE;
1278 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1279 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1280 KASSERT(keg->uk_ipers <= uma_max_ipers,
1281 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1286 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1287 * the keg onto the global keg list.
1289 * Arguments/Returns follow uma_ctor specifications
1290 * udata Actually uma_kctor_args
1293 keg_ctor(void *mem, int size, void *udata, int flags)
1295 struct uma_kctor_args *arg = udata;
1296 uma_keg_t keg = mem;
1300 keg->uk_size = arg->size;
1301 keg->uk_init = arg->uminit;
1302 keg->uk_fini = arg->fini;
1303 keg->uk_align = arg->align;
1306 keg->uk_flags = arg->flags;
1307 keg->uk_allocf = page_alloc;
1308 keg->uk_freef = page_free;
1309 keg->uk_recurse = 0;
1310 keg->uk_slabzone = NULL;
1313 * The master zone is passed to us at keg-creation time.
1316 keg->uk_name = zone->uz_name;
1318 if (arg->flags & UMA_ZONE_VM)
1319 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1321 if (arg->flags & UMA_ZONE_ZINIT)
1322 keg->uk_init = zero_init;
1324 if (arg->flags & UMA_ZONE_REFCNT || arg->flags & UMA_ZONE_MALLOC)
1325 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1327 if (arg->flags & UMA_ZONE_PCPU)
1329 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1331 keg->uk_flags &= ~UMA_ZONE_PCPU;
1335 * The +UMA_FRITM_SZ added to uk_size is to account for the
1336 * linkage that is added to the size in keg_small_init(). If
1337 * we don't account for this here then we may end up in
1338 * keg_small_init() with a calculated 'ipers' of 0.
1340 if (keg->uk_flags & UMA_ZONE_REFCNT) {
1341 if (keg->uk_flags & UMA_ZONE_CACHESPREAD)
1342 keg_cachespread_init(keg);
1343 else if ((keg->uk_size+UMA_FRITMREF_SZ) >
1344 (UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt)))
1345 keg_large_init(keg);
1347 keg_small_init(keg);
1349 if (keg->uk_flags & UMA_ZONE_CACHESPREAD)
1350 keg_cachespread_init(keg);
1351 else if ((keg->uk_size+UMA_FRITM_SZ) >
1352 (UMA_SLAB_SIZE - sizeof(struct uma_slab)))
1353 keg_large_init(keg);
1355 keg_small_init(keg);
1358 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1359 if (keg->uk_flags & UMA_ZONE_REFCNT)
1360 keg->uk_slabzone = slabrefzone;
1362 keg->uk_slabzone = slabzone;
1366 * If we haven't booted yet we need allocations to go through the
1367 * startup cache until the vm is ready.
1369 if (keg->uk_ppera == 1) {
1370 #ifdef UMA_MD_SMALL_ALLOC
1371 keg->uk_allocf = uma_small_alloc;
1372 keg->uk_freef = uma_small_free;
1374 if (booted < UMA_STARTUP)
1375 keg->uk_allocf = startup_alloc;
1377 if (booted < UMA_STARTUP2)
1378 keg->uk_allocf = startup_alloc;
1380 } else if (booted < UMA_STARTUP2 &&
1381 (keg->uk_flags & UMA_ZFLAG_INTERNAL))
1382 keg->uk_allocf = startup_alloc;
1385 * Initialize keg's lock (shared among zones).
1387 if (arg->flags & UMA_ZONE_MTXCLASS)
1388 KEG_LOCK_INIT(keg, 1);
1390 KEG_LOCK_INIT(keg, 0);
1393 * If we're putting the slab header in the actual page we need to
1394 * figure out where in each page it goes. This calculates a right
1395 * justified offset into the memory on an ALIGN_PTR boundary.
1397 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1400 /* Size of the slab struct and free list */
1401 if (keg->uk_flags & UMA_ZONE_REFCNT)
1402 totsize = sizeof(struct uma_slab_refcnt) +
1403 keg->uk_ipers * UMA_FRITMREF_SZ;
1405 totsize = sizeof(struct uma_slab) +
1406 keg->uk_ipers * UMA_FRITM_SZ;
1408 if (totsize & UMA_ALIGN_PTR)
1409 totsize = (totsize & ~UMA_ALIGN_PTR) +
1410 (UMA_ALIGN_PTR + 1);
1411 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - totsize;
1413 if (keg->uk_flags & UMA_ZONE_REFCNT)
1414 totsize = keg->uk_pgoff + sizeof(struct uma_slab_refcnt)
1415 + keg->uk_ipers * UMA_FRITMREF_SZ;
1417 totsize = keg->uk_pgoff + sizeof(struct uma_slab)
1418 + keg->uk_ipers * UMA_FRITM_SZ;
1421 * The only way the following is possible is if with our
1422 * UMA_ALIGN_PTR adjustments we are now bigger than
1423 * UMA_SLAB_SIZE. I haven't checked whether this is
1424 * mathematically possible for all cases, so we make
1427 if (totsize > PAGE_SIZE * keg->uk_ppera) {
1428 printf("zone %s ipers %d rsize %d size %d\n",
1429 zone->uz_name, keg->uk_ipers, keg->uk_rsize,
1431 panic("UMA slab won't fit.");
1435 if (keg->uk_flags & UMA_ZONE_HASH)
1436 hash_alloc(&keg->uk_hash);
1439 printf("UMA: %s(%p) size %d(%d) flags %#x ipers %d ppera %d out %d free %d\n",
1440 zone->uz_name, zone, keg->uk_size, keg->uk_rsize, keg->uk_flags,
1441 keg->uk_ipers, keg->uk_ppera,
1442 (keg->uk_ipers * keg->uk_pages) - keg->uk_free, keg->uk_free);
1445 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1448 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1449 mtx_unlock(&uma_mtx);
1454 * Zone header ctor. This initializes all fields, locks, etc.
1456 * Arguments/Returns follow uma_ctor specifications
1457 * udata Actually uma_zctor_args
1460 zone_ctor(void *mem, int size, void *udata, int flags)
1462 struct uma_zctor_args *arg = udata;
1463 uma_zone_t zone = mem;
1468 zone->uz_name = arg->name;
1469 zone->uz_ctor = arg->ctor;
1470 zone->uz_dtor = arg->dtor;
1471 zone->uz_slab = zone_fetch_slab;
1472 zone->uz_init = NULL;
1473 zone->uz_fini = NULL;
1474 zone->uz_allocs = 0;
1477 zone->uz_sleeps = 0;
1478 zone->uz_fills = zone->uz_count = 0;
1480 zone->uz_warning = NULL;
1481 timevalclear(&zone->uz_ratecheck);
1484 if (arg->flags & UMA_ZONE_SECONDARY) {
1485 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1486 zone->uz_init = arg->uminit;
1487 zone->uz_fini = arg->fini;
1488 zone->uz_lock = &keg->uk_lock;
1489 zone->uz_flags |= UMA_ZONE_SECONDARY;
1492 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1493 if (LIST_NEXT(z, uz_link) == NULL) {
1494 LIST_INSERT_AFTER(z, zone, uz_link);
1499 mtx_unlock(&uma_mtx);
1500 } else if (keg == NULL) {
1501 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1502 arg->align, arg->flags)) == NULL)
1505 struct uma_kctor_args karg;
1508 /* We should only be here from uma_startup() */
1509 karg.size = arg->size;
1510 karg.uminit = arg->uminit;
1511 karg.fini = arg->fini;
1512 karg.align = arg->align;
1513 karg.flags = arg->flags;
1515 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1521 * Link in the first keg.
1523 zone->uz_klink.kl_keg = keg;
1524 LIST_INSERT_HEAD(&zone->uz_kegs, &zone->uz_klink, kl_link);
1525 zone->uz_lock = &keg->uk_lock;
1526 zone->uz_size = keg->uk_size;
1527 zone->uz_flags |= (keg->uk_flags &
1528 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1531 * Some internal zones don't have room allocated for the per cpu
1532 * caches. If we're internal, bail out here.
1534 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1535 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1536 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1540 if (keg->uk_flags & UMA_ZONE_MAXBUCKET)
1541 zone->uz_count = BUCKET_MAX;
1542 else if (keg->uk_ipers <= BUCKET_MAX)
1543 zone->uz_count = keg->uk_ipers;
1545 zone->uz_count = BUCKET_MAX;
1550 * Keg header dtor. This frees all data, destroys locks, frees the hash
1551 * table and removes the keg from the global list.
1553 * Arguments/Returns follow uma_dtor specifications
1557 keg_dtor(void *arg, int size, void *udata)
1561 keg = (uma_keg_t)arg;
1563 if (keg->uk_free != 0) {
1564 printf("Freed UMA keg was not empty (%d items). "
1565 " Lost %d pages of memory.\n",
1566 keg->uk_free, keg->uk_pages);
1570 hash_free(&keg->uk_hash);
1578 * Arguments/Returns follow uma_dtor specifications
1582 zone_dtor(void *arg, int size, void *udata)
1588 zone = (uma_zone_t)arg;
1589 keg = zone_first_keg(zone);
1591 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1595 LIST_REMOVE(zone, uz_link);
1596 mtx_unlock(&uma_mtx);
1598 * XXX there are some races here where
1599 * the zone can be drained but zone lock
1600 * released and then refilled before we
1601 * remove it... we dont care for now
1603 zone_drain_wait(zone, M_WAITOK);
1605 * Unlink all of our kegs.
1607 while ((klink = LIST_FIRST(&zone->uz_kegs)) != NULL) {
1608 klink->kl_keg = NULL;
1609 LIST_REMOVE(klink, kl_link);
1610 if (klink == &zone->uz_klink)
1612 free(klink, M_TEMP);
1615 * We only destroy kegs from non secondary zones.
1617 if ((zone->uz_flags & UMA_ZONE_SECONDARY) == 0) {
1619 LIST_REMOVE(keg, uk_link);
1620 mtx_unlock(&uma_mtx);
1621 zone_free_item(kegs, keg, NULL, SKIP_NONE,
1627 * Traverses every zone in the system and calls a callback
1630 * zfunc A pointer to a function which accepts a zone
1637 zone_foreach(void (*zfunc)(uma_zone_t))
1643 LIST_FOREACH(keg, &uma_kegs, uk_link) {
1644 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1647 mtx_unlock(&uma_mtx);
1650 /* Public functions */
1653 uma_startup(void *bootmem, int boot_pages)
1655 struct uma_zctor_args args;
1658 u_int objsize, totsize, wsize;
1662 printf("Creating uma keg headers zone and keg.\n");
1664 mtx_init(&uma_mtx, "UMA lock", NULL, MTX_DEF);
1667 * Figure out the maximum number of items-per-slab we'll have if
1668 * we're using the OFFPAGE slab header to track free items, given
1669 * all possible object sizes and the maximum desired wastage
1672 * We iterate until we find an object size for
1673 * which the calculated wastage in keg_small_init() will be
1674 * enough to warrant OFFPAGE. Since wastedspace versus objsize
1675 * is an overall increasing see-saw function, we find the smallest
1676 * objsize such that the wastage is always acceptable for objects
1677 * with that objsize or smaller. Since a smaller objsize always
1678 * generates a larger possible uma_max_ipers, we use this computed
1679 * objsize to calculate the largest ipers possible. Since the
1680 * ipers calculated for OFFPAGE slab headers is always larger than
1681 * the ipers initially calculated in keg_small_init(), we use
1682 * the former's equation (UMA_SLAB_SIZE / keg->uk_rsize) to
1683 * obtain the maximum ipers possible for offpage slab headers.
1685 * It should be noted that ipers versus objsize is an inversly
1686 * proportional function which drops off rather quickly so as
1687 * long as our UMA_MAX_WASTE is such that the objsize we calculate
1688 * falls into the portion of the inverse relation AFTER the steep
1689 * falloff, then uma_max_ipers shouldn't be too high (~10 on i386).
1691 * Note that we have 8-bits (1 byte) to use as a freelist index
1692 * inside the actual slab header itself and this is enough to
1693 * accomodate us. In the worst case, a UMA_SMALLEST_UNIT sized
1694 * object with offpage slab header would have ipers =
1695 * UMA_SLAB_SIZE / UMA_SMALLEST_UNIT (currently = 256), which is
1696 * 1 greater than what our byte-integer freelist index can
1697 * accomodate, but we know that this situation never occurs as
1698 * for UMA_SMALLEST_UNIT-sized objects, we will never calculate
1699 * that we need to go to offpage slab headers. Or, if we do,
1700 * then we trap that condition below and panic in the INVARIANTS case.
1702 wsize = UMA_SLAB_SIZE - sizeof(struct uma_slab) -
1703 (UMA_SLAB_SIZE / UMA_MAX_WASTE);
1705 objsize = UMA_SMALLEST_UNIT;
1706 while (totsize >= wsize) {
1707 totsize = (UMA_SLAB_SIZE - sizeof(struct uma_slab)) /
1708 (objsize + UMA_FRITM_SZ);
1709 totsize *= (UMA_FRITM_SZ + objsize);
1712 if (objsize > UMA_SMALLEST_UNIT)
1714 uma_max_ipers = MAX(UMA_SLAB_SIZE / objsize, 64);
1716 wsize = UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt) -
1717 (UMA_SLAB_SIZE / UMA_MAX_WASTE);
1719 objsize = UMA_SMALLEST_UNIT;
1720 while (totsize >= wsize) {
1721 totsize = (UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt)) /
1722 (objsize + UMA_FRITMREF_SZ);
1723 totsize *= (UMA_FRITMREF_SZ + objsize);
1726 if (objsize > UMA_SMALLEST_UNIT)
1728 uma_max_ipers_ref = MAX(UMA_SLAB_SIZE / objsize, 64);
1730 KASSERT((uma_max_ipers_ref <= 256) && (uma_max_ipers <= 256),
1731 ("uma_startup: calculated uma_max_ipers values too large!"));
1734 printf("Calculated uma_max_ipers (for OFFPAGE) is %d\n", uma_max_ipers);
1735 printf("Calculated uma_max_ipers_ref (for OFFPAGE) is %d\n",
1739 /* "manually" create the initial zone */
1740 args.name = "UMA Kegs";
1741 args.size = sizeof(struct uma_keg);
1742 args.ctor = keg_ctor;
1743 args.dtor = keg_dtor;
1744 args.uminit = zero_init;
1746 args.keg = &masterkeg;
1747 args.align = 32 - 1;
1748 args.flags = UMA_ZFLAG_INTERNAL;
1749 /* The initial zone has no Per cpu queues so it's smaller */
1750 zone_ctor(kegs, sizeof(struct uma_zone), &args, M_WAITOK);
1753 printf("Filling boot free list.\n");
1755 for (i = 0; i < boot_pages; i++) {
1756 slab = (uma_slab_t)((uint8_t *)bootmem + (i * UMA_SLAB_SIZE));
1757 slab->us_data = (uint8_t *)slab;
1758 slab->us_flags = UMA_SLAB_BOOT;
1759 LIST_INSERT_HEAD(&uma_boot_pages, slab, us_link);
1761 mtx_init(&uma_boot_pages_mtx, "UMA boot pages", NULL, MTX_DEF);
1764 printf("Creating uma zone headers zone and keg.\n");
1766 args.name = "UMA Zones";
1767 args.size = sizeof(struct uma_zone) +
1768 (sizeof(struct uma_cache) * (mp_maxid + 1));
1769 args.ctor = zone_ctor;
1770 args.dtor = zone_dtor;
1771 args.uminit = zero_init;
1774 args.align = 32 - 1;
1775 args.flags = UMA_ZFLAG_INTERNAL;
1776 /* The initial zone has no Per cpu queues so it's smaller */
1777 zone_ctor(zones, sizeof(struct uma_zone), &args, M_WAITOK);
1780 printf("Initializing pcpu cache locks.\n");
1783 printf("Creating slab and hash zones.\n");
1787 * This is the max number of free list items we'll have with
1790 slabsize = uma_max_ipers * UMA_FRITM_SZ;
1791 slabsize += sizeof(struct uma_slab);
1793 /* Now make a zone for slab headers */
1794 slabzone = uma_zcreate("UMA Slabs",
1796 NULL, NULL, NULL, NULL,
1797 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1800 * We also create a zone for the bigger slabs with reference
1801 * counts in them, to accomodate UMA_ZONE_REFCNT zones.
1803 slabsize = uma_max_ipers_ref * UMA_FRITMREF_SZ;
1804 slabsize += sizeof(struct uma_slab_refcnt);
1805 slabrefzone = uma_zcreate("UMA RCntSlabs",
1807 NULL, NULL, NULL, NULL,
1809 UMA_ZFLAG_INTERNAL);
1811 hashzone = uma_zcreate("UMA Hash",
1812 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
1813 NULL, NULL, NULL, NULL,
1814 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1818 booted = UMA_STARTUP;
1821 printf("UMA startup complete.\n");
1829 booted = UMA_STARTUP2;
1832 printf("UMA startup2 complete.\n");
1837 * Initialize our callout handle
1845 printf("Starting callout.\n");
1847 callout_init(&uma_callout, CALLOUT_MPSAFE);
1848 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
1850 printf("UMA startup3 complete.\n");
1855 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
1856 int align, uint32_t flags)
1858 struct uma_kctor_args args;
1861 args.uminit = uminit;
1863 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
1866 return (zone_alloc_item(kegs, &args, M_WAITOK));
1871 uma_set_align(int align)
1874 if (align != UMA_ALIGN_CACHE)
1875 uma_align_cache = align;
1880 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
1881 uma_init uminit, uma_fini fini, int align, uint32_t flags)
1884 struct uma_zctor_args args;
1886 /* This stuff is essential for the zone ctor */
1891 args.uminit = uminit;
1897 return (zone_alloc_item(zones, &args, M_WAITOK));
1902 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
1903 uma_init zinit, uma_fini zfini, uma_zone_t master)
1905 struct uma_zctor_args args;
1908 keg = zone_first_keg(master);
1910 args.size = keg->uk_size;
1913 args.uminit = zinit;
1915 args.align = keg->uk_align;
1916 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
1919 /* XXX Attaches only one keg of potentially many. */
1920 return (zone_alloc_item(zones, &args, M_WAITOK));
1924 zone_lock_pair(uma_zone_t a, uma_zone_t b)
1928 mtx_lock_flags(b->uz_lock, MTX_DUPOK);
1931 mtx_lock_flags(a->uz_lock, MTX_DUPOK);
1936 zone_unlock_pair(uma_zone_t a, uma_zone_t b)
1944 uma_zsecond_add(uma_zone_t zone, uma_zone_t master)
1951 klink = malloc(sizeof(*klink), M_TEMP, M_WAITOK | M_ZERO);
1953 zone_lock_pair(zone, master);
1955 * zone must use vtoslab() to resolve objects and must already be
1958 if ((zone->uz_flags & (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY))
1959 != (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY)) {
1964 * The new master must also use vtoslab().
1966 if ((zone->uz_flags & UMA_ZONE_VTOSLAB) != UMA_ZONE_VTOSLAB) {
1971 * Both must either be refcnt, or not be refcnt.
1973 if ((zone->uz_flags & UMA_ZONE_REFCNT) !=
1974 (master->uz_flags & UMA_ZONE_REFCNT)) {
1979 * The underlying object must be the same size. rsize
1982 if (master->uz_size != zone->uz_size) {
1987 * Put it at the end of the list.
1989 klink->kl_keg = zone_first_keg(master);
1990 LIST_FOREACH(kl, &zone->uz_kegs, kl_link) {
1991 if (LIST_NEXT(kl, kl_link) == NULL) {
1992 LIST_INSERT_AFTER(kl, klink, kl_link);
1997 zone->uz_flags |= UMA_ZFLAG_MULTI;
1998 zone->uz_slab = zone_fetch_slab_multi;
2001 zone_unlock_pair(zone, master);
2003 free(klink, M_TEMP);
2011 uma_zdestroy(uma_zone_t zone)
2014 zone_free_item(zones, zone, NULL, SKIP_NONE, ZFREE_STATFREE);
2019 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2023 uma_bucket_t bucket;
2026 /* This is the fast path allocation */
2027 #ifdef UMA_DEBUG_ALLOC_1
2028 printf("Allocating one item from %s(%p)\n", zone->uz_name, zone);
2030 CTR3(KTR_UMA, "uma_zalloc_arg thread %x zone %s flags %d", curthread,
2031 zone->uz_name, flags);
2033 if (flags & M_WAITOK) {
2034 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2035 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2037 #ifdef DEBUG_MEMGUARD
2038 if (memguard_cmp_zone(zone)) {
2039 item = memguard_alloc(zone->uz_size, flags);
2042 * Avoid conflict with the use-after-free
2043 * protecting infrastructure from INVARIANTS.
2045 if (zone->uz_init != NULL &&
2046 zone->uz_init != mtrash_init &&
2047 zone->uz_init(item, zone->uz_size, flags) != 0)
2049 if (zone->uz_ctor != NULL &&
2050 zone->uz_ctor != mtrash_ctor &&
2051 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2052 zone->uz_fini(item, zone->uz_size);
2057 /* This is unfortunate but should not be fatal. */
2061 * If possible, allocate from the per-CPU cache. There are two
2062 * requirements for safe access to the per-CPU cache: (1) the thread
2063 * accessing the cache must not be preempted or yield during access,
2064 * and (2) the thread must not migrate CPUs without switching which
2065 * cache it accesses. We rely on a critical section to prevent
2066 * preemption and migration. We release the critical section in
2067 * order to acquire the zone mutex if we are unable to allocate from
2068 * the current cache; when we re-acquire the critical section, we
2069 * must detect and handle migration if it has occurred.
2074 cache = &zone->uz_cpu[cpu];
2077 bucket = cache->uc_allocbucket;
2080 if (bucket->ub_cnt > 0) {
2082 item = bucket->ub_bucket[bucket->ub_cnt];
2084 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2086 KASSERT(item != NULL,
2087 ("uma_zalloc: Bucket pointer mangled."));
2092 uma_dbg_alloc(zone, NULL, item);
2095 if (zone->uz_ctor != NULL) {
2096 if (zone->uz_ctor(item, zone->uz_size,
2097 udata, flags) != 0) {
2098 zone_free_item(zone, item, udata,
2099 SKIP_DTOR, ZFREE_STATFAIL |
2105 bzero(item, zone->uz_size);
2107 } else if (cache->uc_freebucket) {
2109 * We have run out of items in our allocbucket.
2110 * See if we can switch with our free bucket.
2112 if (cache->uc_freebucket->ub_cnt > 0) {
2113 #ifdef UMA_DEBUG_ALLOC
2114 printf("uma_zalloc: Swapping empty with"
2117 bucket = cache->uc_freebucket;
2118 cache->uc_freebucket = cache->uc_allocbucket;
2119 cache->uc_allocbucket = bucket;
2126 * Attempt to retrieve the item from the per-CPU cache has failed, so
2127 * we must go back to the zone. This requires the zone lock, so we
2128 * must drop the critical section, then re-acquire it when we go back
2129 * to the cache. Since the critical section is released, we may be
2130 * preempted or migrate. As such, make sure not to maintain any
2131 * thread-local state specific to the cache from prior to releasing
2132 * the critical section.
2138 cache = &zone->uz_cpu[cpu];
2139 bucket = cache->uc_allocbucket;
2140 if (bucket != NULL) {
2141 if (bucket->ub_cnt > 0) {
2145 bucket = cache->uc_freebucket;
2146 if (bucket != NULL && bucket->ub_cnt > 0) {
2152 /* Since we have locked the zone we may as well send back our stats */
2153 zone->uz_allocs += cache->uc_allocs;
2154 cache->uc_allocs = 0;
2155 zone->uz_frees += cache->uc_frees;
2156 cache->uc_frees = 0;
2158 /* Our old one is now a free bucket */
2159 if (cache->uc_allocbucket) {
2160 KASSERT(cache->uc_allocbucket->ub_cnt == 0,
2161 ("uma_zalloc_arg: Freeing a non free bucket."));
2162 LIST_INSERT_HEAD(&zone->uz_free_bucket,
2163 cache->uc_allocbucket, ub_link);
2164 cache->uc_allocbucket = NULL;
2167 /* Check the free list for a new alloc bucket */
2168 if ((bucket = LIST_FIRST(&zone->uz_full_bucket)) != NULL) {
2169 KASSERT(bucket->ub_cnt != 0,
2170 ("uma_zalloc_arg: Returning an empty bucket."));
2172 LIST_REMOVE(bucket, ub_link);
2173 cache->uc_allocbucket = bucket;
2177 /* We are no longer associated with this CPU. */
2180 /* Bump up our uz_count so we get here less */
2181 if (zone->uz_count < BUCKET_MAX)
2185 * Now lets just fill a bucket and put it on the free list. If that
2186 * works we'll restart the allocation from the begining.
2188 if (zone_alloc_bucket(zone, flags)) {
2190 goto zalloc_restart;
2194 * We may not be able to get a bucket so return an actual item.
2197 printf("uma_zalloc_arg: Bucketzone returned NULL\n");
2200 item = zone_alloc_item(zone, udata, flags);
2205 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int flags)
2209 mtx_assert(&keg->uk_lock, MA_OWNED);
2214 * Find a slab with some space. Prefer slabs that are partially
2215 * used over those that are totally full. This helps to reduce
2218 if (keg->uk_free != 0) {
2219 if (!LIST_EMPTY(&keg->uk_part_slab)) {
2220 slab = LIST_FIRST(&keg->uk_part_slab);
2222 slab = LIST_FIRST(&keg->uk_free_slab);
2223 LIST_REMOVE(slab, us_link);
2224 LIST_INSERT_HEAD(&keg->uk_part_slab, slab,
2227 MPASS(slab->us_keg == keg);
2232 * M_NOVM means don't ask at all!
2237 if (keg->uk_maxpages && keg->uk_pages >= keg->uk_maxpages) {
2238 keg->uk_flags |= UMA_ZFLAG_FULL;
2240 * If this is not a multi-zone, set the FULL bit.
2241 * Otherwise slab_multi() takes care of it.
2243 if ((zone->uz_flags & UMA_ZFLAG_MULTI) == 0) {
2244 zone->uz_flags |= UMA_ZFLAG_FULL;
2245 zone_log_warning(zone);
2247 if (flags & M_NOWAIT)
2250 msleep(keg, &keg->uk_lock, PVM, "keglimit", 0);
2254 slab = keg_alloc_slab(keg, zone, flags);
2257 * If we got a slab here it's safe to mark it partially used
2258 * and return. We assume that the caller is going to remove
2259 * at least one item.
2262 MPASS(slab->us_keg == keg);
2263 LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
2267 * We might not have been able to get a slab but another cpu
2268 * could have while we were unlocked. Check again before we
2277 zone_relock(uma_zone_t zone, uma_keg_t keg)
2279 if (zone->uz_lock != &keg->uk_lock) {
2286 keg_relock(uma_keg_t keg, uma_zone_t zone)
2288 if (zone->uz_lock != &keg->uk_lock) {
2295 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int flags)
2300 keg = zone_first_keg(zone);
2302 * This is to prevent us from recursively trying to allocate
2303 * buckets. The problem is that if an allocation forces us to
2304 * grab a new bucket we will call page_alloc, which will go off
2305 * and cause the vm to allocate vm_map_entries. If we need new
2306 * buckets there too we will recurse in kmem_alloc and bad
2307 * things happen. So instead we return a NULL bucket, and make
2308 * the code that allocates buckets smart enough to deal with it
2310 if (keg->uk_flags & UMA_ZFLAG_BUCKET && keg->uk_recurse != 0)
2314 slab = keg_fetch_slab(keg, zone, flags);
2317 if (flags & (M_NOWAIT | M_NOVM))
2324 * uma_zone_fetch_slab_multi: Fetches a slab from one available keg. Returns
2325 * with the keg locked. Caller must call zone_relock() afterwards if the
2326 * zone lock is required. On NULL the zone lock is held.
2328 * The last pointer is used to seed the search. It is not required.
2331 zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int rflags)
2341 * Don't wait on the first pass. This will skip limit tests
2342 * as well. We don't want to block if we can find a provider
2345 flags = (rflags & ~M_WAITOK) | M_NOWAIT;
2347 * Use the last slab allocated as a hint for where to start
2351 slab = keg_fetch_slab(last, zone, flags);
2354 zone_relock(zone, last);
2358 * Loop until we have a slab incase of transient failures
2359 * while M_WAITOK is specified. I'm not sure this is 100%
2360 * required but we've done it for so long now.
2366 * Search the available kegs for slabs. Be careful to hold the
2367 * correct lock while calling into the keg layer.
2369 LIST_FOREACH(klink, &zone->uz_kegs, kl_link) {
2370 keg = klink->kl_keg;
2371 keg_relock(keg, zone);
2372 if ((keg->uk_flags & UMA_ZFLAG_FULL) == 0) {
2373 slab = keg_fetch_slab(keg, zone, flags);
2377 if (keg->uk_flags & UMA_ZFLAG_FULL)
2381 zone_relock(zone, keg);
2383 if (rflags & (M_NOWAIT | M_NOVM))
2387 * All kegs are full. XXX We can't atomically check all kegs
2388 * and sleep so just sleep for a short period and retry.
2390 if (full && !empty) {
2391 zone->uz_flags |= UMA_ZFLAG_FULL;
2393 zone_log_warning(zone);
2394 msleep(zone, zone->uz_lock, PVM, "zonelimit", hz/100);
2395 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2403 slab_alloc_item(uma_zone_t zone, uma_slab_t slab)
2406 uma_slabrefcnt_t slabref;
2411 mtx_assert(&keg->uk_lock, MA_OWNED);
2413 freei = slab->us_firstfree;
2414 if (keg->uk_flags & UMA_ZONE_REFCNT) {
2415 slabref = (uma_slabrefcnt_t)slab;
2416 slab->us_firstfree = slabref->us_freelist[freei].us_item;
2418 slab->us_firstfree = slab->us_freelist[freei].us_item;
2420 item = slab->us_data + (keg->uk_rsize * freei);
2422 slab->us_freecount--;
2425 uma_dbg_alloc(zone, slab, item);
2427 /* Move this slab to the full list */
2428 if (slab->us_freecount == 0) {
2429 LIST_REMOVE(slab, us_link);
2430 LIST_INSERT_HEAD(&keg->uk_full_slab, slab, us_link);
2437 zone_alloc_bucket(uma_zone_t zone, int flags)
2439 uma_bucket_t bucket;
2443 int max, origflags = flags;
2446 * Try this zone's free list first so we don't allocate extra buckets.
2448 if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
2449 KASSERT(bucket->ub_cnt == 0,
2450 ("zone_alloc_bucket: Bucket on free list is not empty."));
2451 LIST_REMOVE(bucket, ub_link);
2455 bflags = (flags & ~M_ZERO);
2456 if (zone->uz_flags & UMA_ZFLAG_CACHEONLY)
2460 bucket = bucket_alloc(zone->uz_count, bflags);
2464 if (bucket == NULL) {
2470 * This code is here to limit the number of simultaneous bucket fills
2471 * for any given zone to the number of per cpu caches in this zone. This
2472 * is done so that we don't allocate more memory than we really need.
2474 if (zone->uz_fills >= mp_ncpus)
2480 max = MIN(bucket->ub_entries, zone->uz_count);
2481 /* Try to keep the buckets totally full */
2482 saved = bucket->ub_cnt;
2485 while (bucket->ub_cnt < max &&
2486 (slab = zone->uz_slab(zone, keg, flags)) != NULL) {
2488 while (slab->us_freecount && bucket->ub_cnt < max) {
2489 bucket->ub_bucket[bucket->ub_cnt++] =
2490 slab_alloc_item(zone, slab);
2493 /* Don't block on the next fill */
2497 zone_relock(zone, keg);
2500 * We unlock here because we need to call the zone's init.
2501 * It should be safe to unlock because the slab dealt with
2502 * above is already on the appropriate list within the keg
2503 * and the bucket we filled is not yet on any list, so we
2506 if (zone->uz_init != NULL) {
2510 for (i = saved; i < bucket->ub_cnt; i++)
2511 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2515 * If we couldn't initialize the whole bucket, put the
2516 * rest back onto the freelist.
2518 if (i != bucket->ub_cnt) {
2521 for (j = i; j < bucket->ub_cnt; j++) {
2522 zone_free_item(zone, bucket->ub_bucket[j],
2523 NULL, SKIP_FINI, 0);
2525 bucket->ub_bucket[j] = NULL;
2534 if (bucket->ub_cnt != 0) {
2535 LIST_INSERT_HEAD(&zone->uz_full_bucket,
2542 bucket_free(bucket);
2547 * Allocates an item for an internal zone
2550 * zone The zone to alloc for.
2551 * udata The data to be passed to the constructor.
2552 * flags M_WAITOK, M_NOWAIT, M_ZERO.
2555 * NULL if there is no memory and M_NOWAIT is set
2556 * An item if successful
2560 zone_alloc_item(uma_zone_t zone, void *udata, int flags)
2567 #ifdef UMA_DEBUG_ALLOC
2568 printf("INTERNAL: Allocating one item from %s(%p)\n", zone->uz_name, zone);
2572 slab = zone->uz_slab(zone, NULL, flags);
2579 item = slab_alloc_item(zone, slab);
2581 zone_relock(zone, slab->us_keg);
2586 * We have to call both the zone's init (not the keg's init)
2587 * and the zone's ctor. This is because the item is going from
2588 * a keg slab directly to the user, and the user is expecting it
2589 * to be both zone-init'd as well as zone-ctor'd.
2591 if (zone->uz_init != NULL) {
2592 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
2593 zone_free_item(zone, item, udata, SKIP_FINI,
2594 ZFREE_STATFAIL | ZFREE_STATFREE);
2598 if (zone->uz_ctor != NULL) {
2599 if (zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2600 zone_free_item(zone, item, udata, SKIP_DTOR,
2601 ZFREE_STATFAIL | ZFREE_STATFREE);
2606 bzero(item, zone->uz_size);
2613 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
2616 uma_bucket_t bucket;
2620 #ifdef UMA_DEBUG_ALLOC_1
2621 printf("Freeing item %p to %s(%p)\n", item, zone->uz_name, zone);
2623 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
2626 /* uma_zfree(..., NULL) does nothing, to match free(9). */
2629 #ifdef DEBUG_MEMGUARD
2630 if (is_memguard_addr(item)) {
2631 if (zone->uz_dtor != NULL && zone->uz_dtor != mtrash_dtor)
2632 zone->uz_dtor(item, zone->uz_size, udata);
2633 if (zone->uz_fini != NULL && zone->uz_fini != mtrash_fini)
2634 zone->uz_fini(item, zone->uz_size);
2635 memguard_free(item);
2640 zone->uz_dtor(item, zone->uz_size, udata);
2644 if (zone->uz_flags & UMA_ZONE_MALLOC)
2645 uma_dbg_free(zone, udata, item);
2647 uma_dbg_free(zone, NULL, item);
2651 * The race here is acceptable. If we miss it we'll just have to wait
2652 * a little longer for the limits to be reset.
2654 if (zone->uz_flags & UMA_ZFLAG_FULL)
2655 goto zfree_internal;
2658 * If possible, free to the per-CPU cache. There are two
2659 * requirements for safe access to the per-CPU cache: (1) the thread
2660 * accessing the cache must not be preempted or yield during access,
2661 * and (2) the thread must not migrate CPUs without switching which
2662 * cache it accesses. We rely on a critical section to prevent
2663 * preemption and migration. We release the critical section in
2664 * order to acquire the zone mutex if we are unable to free to the
2665 * current cache; when we re-acquire the critical section, we must
2666 * detect and handle migration if it has occurred.
2671 cache = &zone->uz_cpu[cpu];
2674 bucket = cache->uc_freebucket;
2678 * Do we have room in our bucket? It is OK for this uz count
2679 * check to be slightly out of sync.
2682 if (bucket->ub_cnt < bucket->ub_entries) {
2683 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
2684 ("uma_zfree: Freeing to non free bucket index."));
2685 bucket->ub_bucket[bucket->ub_cnt] = item;
2690 } else if (cache->uc_allocbucket) {
2691 #ifdef UMA_DEBUG_ALLOC
2692 printf("uma_zfree: Swapping buckets.\n");
2695 * We have run out of space in our freebucket.
2696 * See if we can switch with our alloc bucket.
2698 if (cache->uc_allocbucket->ub_cnt <
2699 cache->uc_freebucket->ub_cnt) {
2700 bucket = cache->uc_freebucket;
2701 cache->uc_freebucket = cache->uc_allocbucket;
2702 cache->uc_allocbucket = bucket;
2708 * We can get here for two reasons:
2710 * 1) The buckets are NULL
2711 * 2) The alloc and free buckets are both somewhat full.
2713 * We must go back the zone, which requires acquiring the zone lock,
2714 * which in turn means we must release and re-acquire the critical
2715 * section. Since the critical section is released, we may be
2716 * preempted or migrate. As such, make sure not to maintain any
2717 * thread-local state specific to the cache from prior to releasing
2718 * the critical section.
2724 cache = &zone->uz_cpu[cpu];
2725 if (cache->uc_freebucket != NULL) {
2726 if (cache->uc_freebucket->ub_cnt <
2727 cache->uc_freebucket->ub_entries) {
2731 if (cache->uc_allocbucket != NULL &&
2732 (cache->uc_allocbucket->ub_cnt <
2733 cache->uc_freebucket->ub_cnt)) {
2739 /* Since we have locked the zone we may as well send back our stats */
2740 zone->uz_allocs += cache->uc_allocs;
2741 cache->uc_allocs = 0;
2742 zone->uz_frees += cache->uc_frees;
2743 cache->uc_frees = 0;
2745 bucket = cache->uc_freebucket;
2746 cache->uc_freebucket = NULL;
2748 /* Can we throw this on the zone full list? */
2749 if (bucket != NULL) {
2750 #ifdef UMA_DEBUG_ALLOC
2751 printf("uma_zfree: Putting old bucket on the free list.\n");
2753 /* ub_cnt is pointing to the last free item */
2754 KASSERT(bucket->ub_cnt != 0,
2755 ("uma_zfree: Attempting to insert an empty bucket onto the full list.\n"));
2756 LIST_INSERT_HEAD(&zone->uz_full_bucket,
2759 if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
2760 LIST_REMOVE(bucket, ub_link);
2762 cache->uc_freebucket = bucket;
2765 /* We are no longer associated with this CPU. */
2768 /* And the zone.. */
2771 #ifdef UMA_DEBUG_ALLOC
2772 printf("uma_zfree: Allocating new free bucket.\n");
2776 if (zone->uz_flags & UMA_ZFLAG_CACHEONLY)
2778 bucket = bucket_alloc(zone->uz_count, bflags);
2781 LIST_INSERT_HEAD(&zone->uz_free_bucket,
2788 * If nothing else caught this, we'll just do an internal free.
2791 zone_free_item(zone, item, udata, SKIP_DTOR, ZFREE_STATFREE);
2797 * Frees an item to an INTERNAL zone or allocates a free bucket
2800 * zone The zone to free to
2801 * item The item we're freeing
2802 * udata User supplied data for the dtor
2803 * skip Skip dtors and finis
2806 zone_free_item(uma_zone_t zone, void *item, void *udata,
2807 enum zfreeskip skip, int flags)
2810 uma_slabrefcnt_t slabref;
2816 if (skip < SKIP_DTOR && zone->uz_dtor)
2817 zone->uz_dtor(item, zone->uz_size, udata);
2819 if (skip < SKIP_FINI && zone->uz_fini)
2820 zone->uz_fini(item, zone->uz_size);
2824 if (flags & ZFREE_STATFAIL)
2826 if (flags & ZFREE_STATFREE)
2829 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
2830 mem = (uint8_t *)((unsigned long)item & (~UMA_SLAB_MASK));
2831 keg = zone_first_keg(zone); /* Must only be one. */
2832 if (zone->uz_flags & UMA_ZONE_HASH) {
2833 slab = hash_sfind(&keg->uk_hash, mem);
2835 mem += keg->uk_pgoff;
2836 slab = (uma_slab_t)mem;
2839 /* This prevents redundant lookups via free(). */
2840 if ((zone->uz_flags & UMA_ZONE_MALLOC) && udata != NULL)
2841 slab = (uma_slab_t)udata;
2843 slab = vtoslab((vm_offset_t)item);
2845 keg_relock(keg, zone);
2847 MPASS(keg == slab->us_keg);
2849 /* Do we need to remove from any lists? */
2850 if (slab->us_freecount+1 == keg->uk_ipers) {
2851 LIST_REMOVE(slab, us_link);
2852 LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
2853 } else if (slab->us_freecount == 0) {
2854 LIST_REMOVE(slab, us_link);
2855 LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
2858 /* Slab management stuff */
2859 freei = ((unsigned long)item - (unsigned long)slab->us_data)
2864 uma_dbg_free(zone, slab, item);
2867 if (keg->uk_flags & UMA_ZONE_REFCNT) {
2868 slabref = (uma_slabrefcnt_t)slab;
2869 slabref->us_freelist[freei].us_item = slab->us_firstfree;
2871 slab->us_freelist[freei].us_item = slab->us_firstfree;
2873 slab->us_firstfree = freei;
2874 slab->us_freecount++;
2876 /* Zone statistics */
2880 if (keg->uk_flags & UMA_ZFLAG_FULL) {
2881 if (keg->uk_pages < keg->uk_maxpages) {
2882 keg->uk_flags &= ~UMA_ZFLAG_FULL;
2887 * We can handle one more allocation. Since we're clearing ZFLAG_FULL,
2888 * wake up all procs blocked on pages. This should be uncommon, so
2889 * keeping this simple for now (rather than adding count of blocked
2895 zone_relock(zone, keg);
2896 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2905 uma_zone_set_max(uma_zone_t zone, int nitems)
2910 keg = zone_first_keg(zone);
2911 keg->uk_maxpages = (nitems / keg->uk_ipers) * keg->uk_ppera;
2912 if (keg->uk_maxpages * keg->uk_ipers < nitems)
2913 keg->uk_maxpages += keg->uk_ppera;
2914 nitems = keg->uk_maxpages * keg->uk_ipers;
2922 uma_zone_get_max(uma_zone_t zone)
2928 keg = zone_first_keg(zone);
2929 nitems = keg->uk_maxpages * keg->uk_ipers;
2937 uma_zone_set_warning(uma_zone_t zone, const char *warning)
2941 zone->uz_warning = warning;
2947 uma_zone_get_cur(uma_zone_t zone)
2953 nitems = zone->uz_allocs - zone->uz_frees;
2956 * See the comment in sysctl_vm_zone_stats() regarding the
2957 * safety of accessing the per-cpu caches. With the zone lock
2958 * held, it is safe, but can potentially result in stale data.
2960 nitems += zone->uz_cpu[i].uc_allocs -
2961 zone->uz_cpu[i].uc_frees;
2965 return (nitems < 0 ? 0 : nitems);
2970 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
2975 keg = zone_first_keg(zone);
2976 KASSERT(keg->uk_pages == 0,
2977 ("uma_zone_set_init on non-empty keg"));
2978 keg->uk_init = uminit;
2984 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
2989 keg = zone_first_keg(zone);
2990 KASSERT(keg->uk_pages == 0,
2991 ("uma_zone_set_fini on non-empty keg"));
2992 keg->uk_fini = fini;
2998 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3001 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3002 ("uma_zone_set_zinit on non-empty keg"));
3003 zone->uz_init = zinit;
3009 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3012 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3013 ("uma_zone_set_zfini on non-empty keg"));
3014 zone->uz_fini = zfini;
3019 /* XXX uk_freef is not actually used with the zone locked */
3021 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3025 zone_first_keg(zone)->uk_freef = freef;
3030 /* XXX uk_allocf is not actually used with the zone locked */
3032 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3037 keg = zone_first_keg(zone);
3038 keg->uk_flags |= UMA_ZFLAG_PRIVALLOC;
3039 keg->uk_allocf = allocf;
3045 uma_zone_reserve_kva(uma_zone_t zone, int count)
3051 keg = zone_first_keg(zone);
3052 pages = count / keg->uk_ipers;
3054 if (pages * keg->uk_ipers < count)
3057 #ifdef UMA_MD_SMALL_ALLOC
3058 if (keg->uk_ppera > 1) {
3062 kva = kmem_alloc_nofault(kernel_map, pages * UMA_SLAB_SIZE);
3070 keg->uk_maxpages = pages;
3071 #ifdef UMA_MD_SMALL_ALLOC
3072 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3074 keg->uk_allocf = noobj_alloc;
3076 keg->uk_flags |= UMA_ZONE_NOFREE | UMA_ZFLAG_PRIVALLOC;
3083 uma_prealloc(uma_zone_t zone, int items)
3089 keg = zone_first_keg(zone);
3091 slabs = items / keg->uk_ipers;
3092 if (slabs * keg->uk_ipers < items)
3095 slab = keg_alloc_slab(keg, zone, M_WAITOK);
3098 MPASS(slab->us_keg == keg);
3099 LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
3107 uma_find_refcnt(uma_zone_t zone, void *item)
3109 uma_slabrefcnt_t slabref;
3114 slabref = (uma_slabrefcnt_t)vtoslab((vm_offset_t)item &
3116 keg = slabref->us_keg;
3117 KASSERT(slabref != NULL && slabref->us_keg->uk_flags & UMA_ZONE_REFCNT,
3118 ("uma_find_refcnt(): zone possibly not UMA_ZONE_REFCNT"));
3119 idx = ((unsigned long)item - (unsigned long)slabref->us_data)
3121 refcnt = &slabref->us_freelist[idx].us_refcnt;
3130 printf("UMA: vm asked us to release pages!\n");
3133 zone_foreach(zone_drain);
3135 * Some slabs may have been freed but this zone will be visited early
3136 * we visit again so that we can free pages that are empty once other
3137 * zones are drained. We have to do the same for buckets.
3139 zone_drain(slabzone);
3140 zone_drain(slabrefzone);
3141 bucket_zone_drain();
3146 uma_zone_exhausted(uma_zone_t zone)
3151 full = (zone->uz_flags & UMA_ZFLAG_FULL);
3157 uma_zone_exhausted_nolock(uma_zone_t zone)
3159 return (zone->uz_flags & UMA_ZFLAG_FULL);
3163 uma_large_malloc(int size, int wait)
3169 slab = zone_alloc_item(slabzone, NULL, wait);
3172 mem = page_alloc(NULL, size, &flags, wait);
3174 vsetslab((vm_offset_t)mem, slab);
3175 slab->us_data = mem;
3176 slab->us_flags = flags | UMA_SLAB_MALLOC;
3177 slab->us_size = size;
3179 zone_free_item(slabzone, slab, NULL, SKIP_NONE,
3180 ZFREE_STATFAIL | ZFREE_STATFREE);
3187 uma_large_free(uma_slab_t slab)
3189 vsetobj((vm_offset_t)slab->us_data, kmem_object);
3190 page_free(slab->us_data, slab->us_size, slab->us_flags);
3191 zone_free_item(slabzone, slab, NULL, SKIP_NONE, ZFREE_STATFREE);
3195 uma_print_stats(void)
3197 zone_foreach(uma_print_zone);
3201 slab_print(uma_slab_t slab)
3203 printf("slab: keg %p, data %p, freecount %d, firstfree %d\n",
3204 slab->us_keg, slab->us_data, slab->us_freecount,
3205 slab->us_firstfree);
3209 cache_print(uma_cache_t cache)
3211 printf("alloc: %p(%d), free: %p(%d)\n",
3212 cache->uc_allocbucket,
3213 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3214 cache->uc_freebucket,
3215 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3219 uma_print_keg(uma_keg_t keg)
3223 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3224 "out %d free %d limit %d\n",
3225 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3226 keg->uk_ipers, keg->uk_ppera,
3227 (keg->uk_ipers * keg->uk_pages) - keg->uk_free, keg->uk_free,
3228 (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers);
3229 printf("Part slabs:\n");
3230 LIST_FOREACH(slab, &keg->uk_part_slab, us_link)
3232 printf("Free slabs:\n");
3233 LIST_FOREACH(slab, &keg->uk_free_slab, us_link)
3235 printf("Full slabs:\n");
3236 LIST_FOREACH(slab, &keg->uk_full_slab, us_link)
3241 uma_print_zone(uma_zone_t zone)
3247 printf("zone: %s(%p) size %d flags %#x\n",
3248 zone->uz_name, zone, zone->uz_size, zone->uz_flags);
3249 LIST_FOREACH(kl, &zone->uz_kegs, kl_link)
3250 uma_print_keg(kl->kl_keg);
3252 cache = &zone->uz_cpu[i];
3253 printf("CPU %d Cache:\n", i);
3260 * Generate statistics across both the zone and its per-cpu cache's. Return
3261 * desired statistics if the pointer is non-NULL for that statistic.
3263 * Note: does not update the zone statistics, as it can't safely clear the
3264 * per-CPU cache statistic.
3266 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3267 * safe from off-CPU; we should modify the caches to track this information
3268 * directly so that we don't have to.
3271 uma_zone_sumstat(uma_zone_t z, int *cachefreep, uint64_t *allocsp,
3272 uint64_t *freesp, uint64_t *sleepsp)
3275 uint64_t allocs, frees, sleeps;
3278 allocs = frees = sleeps = 0;
3281 cache = &z->uz_cpu[cpu];
3282 if (cache->uc_allocbucket != NULL)
3283 cachefree += cache->uc_allocbucket->ub_cnt;
3284 if (cache->uc_freebucket != NULL)
3285 cachefree += cache->uc_freebucket->ub_cnt;
3286 allocs += cache->uc_allocs;
3287 frees += cache->uc_frees;
3289 allocs += z->uz_allocs;
3290 frees += z->uz_frees;
3291 sleeps += z->uz_sleeps;
3292 if (cachefreep != NULL)
3293 *cachefreep = cachefree;
3294 if (allocsp != NULL)
3298 if (sleepsp != NULL)
3304 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3312 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3313 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3316 mtx_unlock(&uma_mtx);
3317 return (sysctl_handle_int(oidp, &count, 0, req));
3321 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3323 struct uma_stream_header ush;
3324 struct uma_type_header uth;
3325 struct uma_percpu_stat ups;
3326 uma_bucket_t bucket;
3333 int count, error, i;
3335 error = sysctl_wire_old_buffer(req, 0);
3338 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3342 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3343 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3348 * Insert stream header.
3350 bzero(&ush, sizeof(ush));
3351 ush.ush_version = UMA_STREAM_VERSION;
3352 ush.ush_maxcpus = (mp_maxid + 1);
3353 ush.ush_count = count;
3354 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
3356 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3357 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3358 bzero(&uth, sizeof(uth));
3360 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3361 uth.uth_align = kz->uk_align;
3362 uth.uth_size = kz->uk_size;
3363 uth.uth_rsize = kz->uk_rsize;
3364 LIST_FOREACH(kl, &z->uz_kegs, kl_link) {
3366 uth.uth_maxpages += k->uk_maxpages;
3367 uth.uth_pages += k->uk_pages;
3368 uth.uth_keg_free += k->uk_free;
3369 uth.uth_limit = (k->uk_maxpages / k->uk_ppera)
3374 * A zone is secondary is it is not the first entry
3375 * on the keg's zone list.
3377 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
3378 (LIST_FIRST(&kz->uk_zones) != z))
3379 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
3381 LIST_FOREACH(bucket, &z->uz_full_bucket, ub_link)
3382 uth.uth_zone_free += bucket->ub_cnt;
3383 uth.uth_allocs = z->uz_allocs;
3384 uth.uth_frees = z->uz_frees;
3385 uth.uth_fails = z->uz_fails;
3386 uth.uth_sleeps = z->uz_sleeps;
3387 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
3389 * While it is not normally safe to access the cache
3390 * bucket pointers while not on the CPU that owns the
3391 * cache, we only allow the pointers to be exchanged
3392 * without the zone lock held, not invalidated, so
3393 * accept the possible race associated with bucket
3394 * exchange during monitoring.
3396 for (i = 0; i < (mp_maxid + 1); i++) {
3397 bzero(&ups, sizeof(ups));
3398 if (kz->uk_flags & UMA_ZFLAG_INTERNAL)
3402 cache = &z->uz_cpu[i];
3403 if (cache->uc_allocbucket != NULL)
3404 ups.ups_cache_free +=
3405 cache->uc_allocbucket->ub_cnt;
3406 if (cache->uc_freebucket != NULL)
3407 ups.ups_cache_free +=
3408 cache->uc_freebucket->ub_cnt;
3409 ups.ups_allocs = cache->uc_allocs;
3410 ups.ups_frees = cache->uc_frees;
3412 (void)sbuf_bcat(&sbuf, &ups, sizeof(ups));
3417 mtx_unlock(&uma_mtx);
3418 error = sbuf_finish(&sbuf);
3424 DB_SHOW_COMMAND(uma, db_show_uma)
3426 uint64_t allocs, frees, sleeps;
3427 uma_bucket_t bucket;
3432 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
3433 "Requests", "Sleeps");
3434 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3435 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3436 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
3437 allocs = z->uz_allocs;
3438 frees = z->uz_frees;
3439 sleeps = z->uz_sleeps;
3442 uma_zone_sumstat(z, &cachefree, &allocs,
3444 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
3445 (LIST_FIRST(&kz->uk_zones) != z)))
3446 cachefree += kz->uk_free;
3447 LIST_FOREACH(bucket, &z->uz_full_bucket, ub_link)
3448 cachefree += bucket->ub_cnt;
3449 db_printf("%18s %8ju %8jd %8d %12ju %8ju\n", z->uz_name,
3450 (uintmax_t)kz->uk_size,
3451 (intmax_t)(allocs - frees), cachefree,
3452 (uintmax_t)allocs, sleeps);