]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/uma_core.c
uma: fix KTR message after r366840
[FreeBSD/FreeBSD.git] / sys / vm / uma_core.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002-2019 Jeffrey Roberson <jeff@FreeBSD.org>
5  * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
6  * Copyright (c) 2004-2006 Robert N. M. Watson
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice unmodified, this list of conditions, and the following
14  *    disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 /*
32  * uma_core.c  Implementation of the Universal Memory allocator
33  *
34  * This allocator is intended to replace the multitude of similar object caches
35  * in the standard FreeBSD kernel.  The intent is to be flexible as well as
36  * efficient.  A primary design goal is to return unused memory to the rest of
37  * the system.  This will make the system as a whole more flexible due to the
38  * ability to move memory to subsystems which most need it instead of leaving
39  * pools of reserved memory unused.
40  *
41  * The basic ideas stem from similar slab/zone based allocators whose algorithms
42  * are well known.
43  *
44  */
45
46 /*
47  * TODO:
48  *      - Improve memory usage for large allocations
49  *      - Investigate cache size adjustments
50  */
51
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
54
55 #include "opt_ddb.h"
56 #include "opt_param.h"
57 #include "opt_vm.h"
58
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bitset.h>
62 #include <sys/domainset.h>
63 #include <sys/eventhandler.h>
64 #include <sys/kernel.h>
65 #include <sys/types.h>
66 #include <sys/limits.h>
67 #include <sys/queue.h>
68 #include <sys/malloc.h>
69 #include <sys/ktr.h>
70 #include <sys/lock.h>
71 #include <sys/sysctl.h>
72 #include <sys/mutex.h>
73 #include <sys/proc.h>
74 #include <sys/random.h>
75 #include <sys/rwlock.h>
76 #include <sys/sbuf.h>
77 #include <sys/sched.h>
78 #include <sys/sleepqueue.h>
79 #include <sys/smp.h>
80 #include <sys/smr.h>
81 #include <sys/taskqueue.h>
82 #include <sys/vmmeter.h>
83
84 #include <vm/vm.h>
85 #include <vm/vm_param.h>
86 #include <vm/vm_domainset.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_phys.h>
91 #include <vm/vm_pagequeue.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_kern.h>
94 #include <vm/vm_extern.h>
95 #include <vm/vm_dumpset.h>
96 #include <vm/uma.h>
97 #include <vm/uma_int.h>
98 #include <vm/uma_dbg.h>
99
100 #include <ddb/ddb.h>
101
102 #ifdef DEBUG_MEMGUARD
103 #include <vm/memguard.h>
104 #endif
105
106 #include <machine/md_var.h>
107
108 #ifdef INVARIANTS
109 #define UMA_ALWAYS_CTORDTOR     1
110 #else
111 #define UMA_ALWAYS_CTORDTOR     0
112 #endif
113
114 /*
115  * This is the zone and keg from which all zones are spawned.
116  */
117 static uma_zone_t kegs;
118 static uma_zone_t zones;
119
120 /*
121  * On INVARIANTS builds, the slab contains a second bitset of the same size,
122  * "dbg_bits", which is laid out immediately after us_free.
123  */
124 #ifdef INVARIANTS
125 #define SLAB_BITSETS    2
126 #else
127 #define SLAB_BITSETS    1
128 #endif
129
130 /*
131  * These are the two zones from which all offpage uma_slab_ts are allocated.
132  *
133  * One zone is for slab headers that can represent a larger number of items,
134  * making the slabs themselves more efficient, and the other zone is for
135  * headers that are smaller and represent fewer items, making the headers more
136  * efficient.
137  */
138 #define SLABZONE_SIZE(setsize)                                  \
139     (sizeof(struct uma_hash_slab) + BITSET_SIZE(setsize) * SLAB_BITSETS)
140 #define SLABZONE0_SETSIZE       (PAGE_SIZE / 16)
141 #define SLABZONE1_SETSIZE       SLAB_MAX_SETSIZE
142 #define SLABZONE0_SIZE  SLABZONE_SIZE(SLABZONE0_SETSIZE)
143 #define SLABZONE1_SIZE  SLABZONE_SIZE(SLABZONE1_SETSIZE)
144 static uma_zone_t slabzones[2];
145
146 /*
147  * The initial hash tables come out of this zone so they can be allocated
148  * prior to malloc coming up.
149  */
150 static uma_zone_t hashzone;
151
152 /* The boot-time adjusted value for cache line alignment. */
153 int uma_align_cache = 64 - 1;
154
155 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
156 static MALLOC_DEFINE(M_UMA, "UMA", "UMA Misc");
157
158 /*
159  * Are we allowed to allocate buckets?
160  */
161 static int bucketdisable = 1;
162
163 /* Linked list of all kegs in the system */
164 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
165
166 /* Linked list of all cache-only zones in the system */
167 static LIST_HEAD(,uma_zone) uma_cachezones =
168     LIST_HEAD_INITIALIZER(uma_cachezones);
169
170 /* This RW lock protects the keg list */
171 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
172
173 /*
174  * First available virual address for boot time allocations.
175  */
176 static vm_offset_t bootstart;
177 static vm_offset_t bootmem;
178
179 static struct sx uma_reclaim_lock;
180
181 /*
182  * kmem soft limit, initialized by uma_set_limit().  Ensure that early
183  * allocations don't trigger a wakeup of the reclaim thread.
184  */
185 unsigned long uma_kmem_limit = LONG_MAX;
186 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_limit, CTLFLAG_RD, &uma_kmem_limit, 0,
187     "UMA kernel memory soft limit");
188 unsigned long uma_kmem_total;
189 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_total, CTLFLAG_RD, &uma_kmem_total, 0,
190     "UMA kernel memory usage");
191
192 /* Is the VM done starting up? */
193 static enum {
194         BOOT_COLD,
195         BOOT_KVA,
196         BOOT_PCPU,
197         BOOT_RUNNING,
198         BOOT_SHUTDOWN,
199 } booted = BOOT_COLD;
200
201 /*
202  * This is the handle used to schedule events that need to happen
203  * outside of the allocation fast path.
204  */
205 static struct callout uma_callout;
206 #define UMA_TIMEOUT     20              /* Seconds for callout interval. */
207
208 /*
209  * This structure is passed as the zone ctor arg so that I don't have to create
210  * a special allocation function just for zones.
211  */
212 struct uma_zctor_args {
213         const char *name;
214         size_t size;
215         uma_ctor ctor;
216         uma_dtor dtor;
217         uma_init uminit;
218         uma_fini fini;
219         uma_import import;
220         uma_release release;
221         void *arg;
222         uma_keg_t keg;
223         int align;
224         uint32_t flags;
225 };
226
227 struct uma_kctor_args {
228         uma_zone_t zone;
229         size_t size;
230         uma_init uminit;
231         uma_fini fini;
232         int align;
233         uint32_t flags;
234 };
235
236 struct uma_bucket_zone {
237         uma_zone_t      ubz_zone;
238         const char      *ubz_name;
239         int             ubz_entries;    /* Number of items it can hold. */
240         int             ubz_maxsize;    /* Maximum allocation size per-item. */
241 };
242
243 /*
244  * Compute the actual number of bucket entries to pack them in power
245  * of two sizes for more efficient space utilization.
246  */
247 #define BUCKET_SIZE(n)                                          \
248     (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
249
250 #define BUCKET_MAX      BUCKET_SIZE(256)
251 #define BUCKET_MIN      2
252
253 struct uma_bucket_zone bucket_zones[] = {
254         /* Literal bucket sizes. */
255         { NULL, "2 Bucket", 2, 4096 },
256         { NULL, "4 Bucket", 4, 3072 },
257         { NULL, "8 Bucket", 8, 2048 },
258         { NULL, "16 Bucket", 16, 1024 },
259         /* Rounded down power of 2 sizes for efficiency. */
260         { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
261         { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
262         { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
263         { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
264         { NULL, NULL, 0}
265 };
266
267 /*
268  * Flags and enumerations to be passed to internal functions.
269  */
270 enum zfreeskip {
271         SKIP_NONE =     0,
272         SKIP_CNT =      0x00000001,
273         SKIP_DTOR =     0x00010000,
274         SKIP_FINI =     0x00020000,
275 };
276
277 /* Prototypes.. */
278
279 void    uma_startup1(vm_offset_t);
280 void    uma_startup2(void);
281
282 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
283 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
284 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
285 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
286 static void *contig_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
287 static void page_free(void *, vm_size_t, uint8_t);
288 static void pcpu_page_free(void *, vm_size_t, uint8_t);
289 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
290 static void cache_drain(uma_zone_t);
291 static void bucket_drain(uma_zone_t, uma_bucket_t);
292 static void bucket_cache_reclaim(uma_zone_t zone, bool);
293 static int keg_ctor(void *, int, void *, int);
294 static void keg_dtor(void *, int, void *);
295 static int zone_ctor(void *, int, void *, int);
296 static void zone_dtor(void *, int, void *);
297 static inline void item_dtor(uma_zone_t zone, void *item, int size,
298     void *udata, enum zfreeskip skip);
299 static int zero_init(void *, int, int);
300 static void zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
301     int itemdomain, bool ws);
302 static void zone_foreach(void (*zfunc)(uma_zone_t, void *), void *);
303 static void zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *), void *);
304 static void zone_timeout(uma_zone_t zone, void *);
305 static int hash_alloc(struct uma_hash *, u_int);
306 static int hash_expand(struct uma_hash *, struct uma_hash *);
307 static void hash_free(struct uma_hash *hash);
308 static void uma_timeout(void *);
309 static void uma_shutdown(void);
310 static void *zone_alloc_item(uma_zone_t, void *, int, int);
311 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
312 static int zone_alloc_limit(uma_zone_t zone, int count, int flags);
313 static void zone_free_limit(uma_zone_t zone, int count);
314 static void bucket_enable(void);
315 static void bucket_init(void);
316 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
317 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
318 static void bucket_zone_drain(void);
319 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int);
320 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
321 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
322 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
323     uma_fini fini, int align, uint32_t flags);
324 static int zone_import(void *, void **, int, int, int);
325 static void zone_release(void *, void **, int);
326 static bool cache_alloc(uma_zone_t, uma_cache_t, void *, int);
327 static bool cache_free(uma_zone_t, uma_cache_t, void *, void *, int);
328
329 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
330 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
331 static int sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS);
332 static int sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS);
333 static int sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS);
334 static int sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS);
335 static int sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS);
336
337 static uint64_t uma_zone_get_allocs(uma_zone_t zone);
338
339 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
340     "Memory allocation debugging");
341
342 #ifdef INVARIANTS
343 static uint64_t uma_keg_get_allocs(uma_keg_t zone);
344 static inline struct noslabbits *slab_dbg_bits(uma_slab_t slab, uma_keg_t keg);
345
346 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
347 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
348 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
349 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
350
351 static u_int dbg_divisor = 1;
352 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
353     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
354     "Debug & thrash every this item in memory allocator");
355
356 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
357 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
358 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
359     &uma_dbg_cnt, "memory items debugged");
360 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
361     &uma_skip_cnt, "memory items skipped, not debugged");
362 #endif
363
364 SYSCTL_NODE(_vm, OID_AUTO, uma, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
365     "Universal Memory Allocator");
366
367 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_INT,
368     0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
369
370 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_STRUCT,
371     0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
372
373 static int zone_warnings = 1;
374 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
375     "Warn when UMA zones becomes full");
376
377 static int multipage_slabs = 1;
378 TUNABLE_INT("vm.debug.uma_multipage_slabs", &multipage_slabs);
379 SYSCTL_INT(_vm_debug, OID_AUTO, uma_multipage_slabs,
380     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &multipage_slabs, 0,
381     "UMA may choose larger slab sizes for better efficiency");
382
383 /*
384  * Select the slab zone for an offpage slab with the given maximum item count.
385  */
386 static inline uma_zone_t
387 slabzone(int ipers)
388 {
389
390         return (slabzones[ipers > SLABZONE0_SETSIZE]);
391 }
392
393 /*
394  * This routine checks to see whether or not it's safe to enable buckets.
395  */
396 static void
397 bucket_enable(void)
398 {
399
400         KASSERT(booted >= BOOT_KVA, ("Bucket enable before init"));
401         bucketdisable = vm_page_count_min();
402 }
403
404 /*
405  * Initialize bucket_zones, the array of zones of buckets of various sizes.
406  *
407  * For each zone, calculate the memory required for each bucket, consisting
408  * of the header and an array of pointers.
409  */
410 static void
411 bucket_init(void)
412 {
413         struct uma_bucket_zone *ubz;
414         int size;
415
416         for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
417                 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
418                 size += sizeof(void *) * ubz->ubz_entries;
419                 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
420                     NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
421                     UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET |
422                     UMA_ZONE_FIRSTTOUCH);
423         }
424 }
425
426 /*
427  * Given a desired number of entries for a bucket, return the zone from which
428  * to allocate the bucket.
429  */
430 static struct uma_bucket_zone *
431 bucket_zone_lookup(int entries)
432 {
433         struct uma_bucket_zone *ubz;
434
435         for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
436                 if (ubz->ubz_entries >= entries)
437                         return (ubz);
438         ubz--;
439         return (ubz);
440 }
441
442 static struct uma_bucket_zone *
443 bucket_zone_max(uma_zone_t zone, int nitems)
444 {
445         struct uma_bucket_zone *ubz;
446         int bpcpu;
447
448         bpcpu = 2;
449         if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
450                 /* Count the cross-domain bucket. */
451                 bpcpu++;
452
453         for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
454                 if (ubz->ubz_entries * bpcpu * mp_ncpus > nitems)
455                         break;
456         if (ubz == &bucket_zones[0])
457                 ubz = NULL;
458         else
459                 ubz--;
460         return (ubz);
461 }
462
463 static int
464 bucket_select(int size)
465 {
466         struct uma_bucket_zone *ubz;
467
468         ubz = &bucket_zones[0];
469         if (size > ubz->ubz_maxsize)
470                 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
471
472         for (; ubz->ubz_entries != 0; ubz++)
473                 if (ubz->ubz_maxsize < size)
474                         break;
475         ubz--;
476         return (ubz->ubz_entries);
477 }
478
479 static uma_bucket_t
480 bucket_alloc(uma_zone_t zone, void *udata, int flags)
481 {
482         struct uma_bucket_zone *ubz;
483         uma_bucket_t bucket;
484
485         /*
486          * Don't allocate buckets early in boot.
487          */
488         if (__predict_false(booted < BOOT_KVA))
489                 return (NULL);
490
491         /*
492          * To limit bucket recursion we store the original zone flags
493          * in a cookie passed via zalloc_arg/zfree_arg.  This allows the
494          * NOVM flag to persist even through deep recursions.  We also
495          * store ZFLAG_BUCKET once we have recursed attempting to allocate
496          * a bucket for a bucket zone so we do not allow infinite bucket
497          * recursion.  This cookie will even persist to frees of unused
498          * buckets via the allocation path or bucket allocations in the
499          * free path.
500          */
501         if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
502                 udata = (void *)(uintptr_t)zone->uz_flags;
503         else {
504                 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
505                         return (NULL);
506                 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
507         }
508         if (((uintptr_t)udata & UMA_ZONE_VM) != 0)
509                 flags |= M_NOVM;
510         ubz = bucket_zone_lookup(zone->uz_bucket_size);
511         if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
512                 ubz++;
513         bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
514         if (bucket) {
515 #ifdef INVARIANTS
516                 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
517 #endif
518                 bucket->ub_cnt = 0;
519                 bucket->ub_entries = ubz->ubz_entries;
520                 bucket->ub_seq = SMR_SEQ_INVALID;
521                 CTR3(KTR_UMA, "bucket_alloc: zone %s(%p) allocated bucket %p",
522                     zone->uz_name, zone, bucket);
523         }
524
525         return (bucket);
526 }
527
528 static void
529 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
530 {
531         struct uma_bucket_zone *ubz;
532
533         if (bucket->ub_cnt != 0)
534                 bucket_drain(zone, bucket);
535
536         KASSERT(bucket->ub_cnt == 0,
537             ("bucket_free: Freeing a non free bucket."));
538         KASSERT(bucket->ub_seq == SMR_SEQ_INVALID,
539             ("bucket_free: Freeing an SMR bucket."));
540         if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
541                 udata = (void *)(uintptr_t)zone->uz_flags;
542         ubz = bucket_zone_lookup(bucket->ub_entries);
543         uma_zfree_arg(ubz->ubz_zone, bucket, udata);
544 }
545
546 static void
547 bucket_zone_drain(void)
548 {
549         struct uma_bucket_zone *ubz;
550
551         for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
552                 uma_zone_reclaim(ubz->ubz_zone, UMA_RECLAIM_DRAIN);
553 }
554
555 /*
556  * Acquire the domain lock and record contention.
557  */
558 static uma_zone_domain_t
559 zone_domain_lock(uma_zone_t zone, int domain)
560 {
561         uma_zone_domain_t zdom;
562         bool lockfail;
563
564         zdom = ZDOM_GET(zone, domain);
565         lockfail = false;
566         if (ZDOM_OWNED(zdom))
567                 lockfail = true;
568         ZDOM_LOCK(zdom);
569         /* This is unsynchronized.  The counter does not need to be precise. */
570         if (lockfail && zone->uz_bucket_size < zone->uz_bucket_size_max)
571                 zone->uz_bucket_size++;
572         return (zdom);
573 }
574
575 /*
576  * Search for the domain with the least cached items and return it if it
577  * is out of balance with the preferred domain.
578  */
579 static __noinline int
580 zone_domain_lowest(uma_zone_t zone, int pref)
581 {
582         long least, nitems, prefitems;
583         int domain;
584         int i;
585
586         prefitems = least = LONG_MAX;
587         domain = 0;
588         for (i = 0; i < vm_ndomains; i++) {
589                 nitems = ZDOM_GET(zone, i)->uzd_nitems;
590                 if (nitems < least) {
591                         domain = i;
592                         least = nitems;
593                 }
594                 if (domain == pref)
595                         prefitems = nitems;
596         }
597         if (prefitems < least * 2)
598                 return (pref);
599
600         return (domain);
601 }
602
603 /*
604  * Search for the domain with the most cached items and return it or the
605  * preferred domain if it has enough to proceed.
606  */
607 static __noinline int
608 zone_domain_highest(uma_zone_t zone, int pref)
609 {
610         long most, nitems;
611         int domain;
612         int i;
613
614         if (ZDOM_GET(zone, pref)->uzd_nitems > BUCKET_MAX)
615                 return (pref);
616
617         most = 0;
618         domain = 0;
619         for (i = 0; i < vm_ndomains; i++) {
620                 nitems = ZDOM_GET(zone, i)->uzd_nitems;
621                 if (nitems > most) {
622                         domain = i;
623                         most = nitems;
624                 }
625         }
626
627         return (domain);
628 }
629
630 /*
631  * Safely subtract cnt from imax.
632  */
633 static void
634 zone_domain_imax_sub(uma_zone_domain_t zdom, int cnt)
635 {
636         long new;
637         long old;
638
639         old = zdom->uzd_imax;
640         do {
641                 if (old <= cnt)
642                         new = 0;
643                 else
644                         new = old - cnt;
645         } while (atomic_fcmpset_long(&zdom->uzd_imax, &old, new) == 0);
646 }
647
648 /*
649  * Set the maximum imax value.
650  */
651 static void
652 zone_domain_imax_set(uma_zone_domain_t zdom, int nitems)
653 {
654         long old;
655
656         old = zdom->uzd_imax;
657         do {
658                 if (old >= nitems)
659                         break;
660         } while (atomic_fcmpset_long(&zdom->uzd_imax, &old, nitems) == 0);
661 }
662
663 /*
664  * Attempt to satisfy an allocation by retrieving a full bucket from one of the
665  * zone's caches.  If a bucket is found the zone is not locked on return.
666  */
667 static uma_bucket_t
668 zone_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, bool reclaim)
669 {
670         uma_bucket_t bucket;
671         int i;
672         bool dtor = false;
673
674         ZDOM_LOCK_ASSERT(zdom);
675
676         if ((bucket = STAILQ_FIRST(&zdom->uzd_buckets)) == NULL)
677                 return (NULL);
678
679         /* SMR Buckets can not be re-used until readers expire. */
680         if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
681             bucket->ub_seq != SMR_SEQ_INVALID) {
682                 if (!smr_poll(zone->uz_smr, bucket->ub_seq, false))
683                         return (NULL);
684                 bucket->ub_seq = SMR_SEQ_INVALID;
685                 dtor = (zone->uz_dtor != NULL) || UMA_ALWAYS_CTORDTOR;
686                 if (STAILQ_NEXT(bucket, ub_link) != NULL)
687                         zdom->uzd_seq = STAILQ_NEXT(bucket, ub_link)->ub_seq;
688         }
689         STAILQ_REMOVE_HEAD(&zdom->uzd_buckets, ub_link);
690
691         KASSERT(zdom->uzd_nitems >= bucket->ub_cnt,
692             ("%s: item count underflow (%ld, %d)",
693             __func__, zdom->uzd_nitems, bucket->ub_cnt));
694         KASSERT(bucket->ub_cnt > 0,
695             ("%s: empty bucket in bucket cache", __func__));
696         zdom->uzd_nitems -= bucket->ub_cnt;
697
698         /*
699          * Shift the bounds of the current WSS interval to avoid
700          * perturbing the estimate.
701          */
702         if (reclaim) {
703                 zdom->uzd_imin -= lmin(zdom->uzd_imin, bucket->ub_cnt);
704                 zone_domain_imax_sub(zdom, bucket->ub_cnt);
705         } else if (zdom->uzd_imin > zdom->uzd_nitems)
706                 zdom->uzd_imin = zdom->uzd_nitems;
707
708         ZDOM_UNLOCK(zdom);
709         if (dtor)
710                 for (i = 0; i < bucket->ub_cnt; i++)
711                         item_dtor(zone, bucket->ub_bucket[i], zone->uz_size,
712                             NULL, SKIP_NONE);
713
714         return (bucket);
715 }
716
717 /*
718  * Insert a full bucket into the specified cache.  The "ws" parameter indicates
719  * whether the bucket's contents should be counted as part of the zone's working
720  * set.  The bucket may be freed if it exceeds the bucket limit.
721  */
722 static void
723 zone_put_bucket(uma_zone_t zone, int domain, uma_bucket_t bucket, void *udata,
724     const bool ws)
725 {
726         uma_zone_domain_t zdom;
727
728         /* We don't cache empty buckets.  This can happen after a reclaim. */
729         if (bucket->ub_cnt == 0)
730                 goto out;
731         zdom = zone_domain_lock(zone, domain);
732
733         /*
734          * Conditionally set the maximum number of items.
735          */
736         zdom->uzd_nitems += bucket->ub_cnt;
737         if (__predict_true(zdom->uzd_nitems < zone->uz_bucket_max)) {
738                 if (ws)
739                         zone_domain_imax_set(zdom, zdom->uzd_nitems);
740                 if (STAILQ_EMPTY(&zdom->uzd_buckets))
741                         zdom->uzd_seq = bucket->ub_seq;
742
743                 /*
744                  * Try to promote reuse of recently used items.  For items
745                  * protected by SMR, try to defer reuse to minimize polling.
746                  */
747                 if (bucket->ub_seq == SMR_SEQ_INVALID)
748                         STAILQ_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
749                 else
750                         STAILQ_INSERT_TAIL(&zdom->uzd_buckets, bucket, ub_link);
751                 ZDOM_UNLOCK(zdom);
752                 return;
753         }
754         zdom->uzd_nitems -= bucket->ub_cnt;
755         ZDOM_UNLOCK(zdom);
756 out:
757         bucket_free(zone, bucket, udata);
758 }
759
760 /* Pops an item out of a per-cpu cache bucket. */
761 static inline void *
762 cache_bucket_pop(uma_cache_t cache, uma_cache_bucket_t bucket)
763 {
764         void *item;
765
766         CRITICAL_ASSERT(curthread);
767
768         bucket->ucb_cnt--;
769         item = bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt];
770 #ifdef INVARIANTS
771         bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = NULL;
772         KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
773 #endif
774         cache->uc_allocs++;
775
776         return (item);
777 }
778
779 /* Pushes an item into a per-cpu cache bucket. */
780 static inline void
781 cache_bucket_push(uma_cache_t cache, uma_cache_bucket_t bucket, void *item)
782 {
783
784         CRITICAL_ASSERT(curthread);
785         KASSERT(bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] == NULL,
786             ("uma_zfree: Freeing to non free bucket index."));
787
788         bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = item;
789         bucket->ucb_cnt++;
790         cache->uc_frees++;
791 }
792
793 /*
794  * Unload a UMA bucket from a per-cpu cache.
795  */
796 static inline uma_bucket_t
797 cache_bucket_unload(uma_cache_bucket_t bucket)
798 {
799         uma_bucket_t b;
800
801         b = bucket->ucb_bucket;
802         if (b != NULL) {
803                 MPASS(b->ub_entries == bucket->ucb_entries);
804                 b->ub_cnt = bucket->ucb_cnt;
805                 bucket->ucb_bucket = NULL;
806                 bucket->ucb_entries = bucket->ucb_cnt = 0;
807         }
808
809         return (b);
810 }
811
812 static inline uma_bucket_t
813 cache_bucket_unload_alloc(uma_cache_t cache)
814 {
815
816         return (cache_bucket_unload(&cache->uc_allocbucket));
817 }
818
819 static inline uma_bucket_t
820 cache_bucket_unload_free(uma_cache_t cache)
821 {
822
823         return (cache_bucket_unload(&cache->uc_freebucket));
824 }
825
826 static inline uma_bucket_t
827 cache_bucket_unload_cross(uma_cache_t cache)
828 {
829
830         return (cache_bucket_unload(&cache->uc_crossbucket));
831 }
832
833 /*
834  * Load a bucket into a per-cpu cache bucket.
835  */
836 static inline void
837 cache_bucket_load(uma_cache_bucket_t bucket, uma_bucket_t b)
838 {
839
840         CRITICAL_ASSERT(curthread);
841         MPASS(bucket->ucb_bucket == NULL);
842         MPASS(b->ub_seq == SMR_SEQ_INVALID);
843
844         bucket->ucb_bucket = b;
845         bucket->ucb_cnt = b->ub_cnt;
846         bucket->ucb_entries = b->ub_entries;
847 }
848
849 static inline void
850 cache_bucket_load_alloc(uma_cache_t cache, uma_bucket_t b)
851 {
852
853         cache_bucket_load(&cache->uc_allocbucket, b);
854 }
855
856 static inline void
857 cache_bucket_load_free(uma_cache_t cache, uma_bucket_t b)
858 {
859
860         cache_bucket_load(&cache->uc_freebucket, b);
861 }
862
863 #ifdef NUMA
864 static inline void 
865 cache_bucket_load_cross(uma_cache_t cache, uma_bucket_t b)
866 {
867
868         cache_bucket_load(&cache->uc_crossbucket, b);
869 }
870 #endif
871
872 /*
873  * Copy and preserve ucb_spare.
874  */
875 static inline void
876 cache_bucket_copy(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
877 {
878
879         b1->ucb_bucket = b2->ucb_bucket;
880         b1->ucb_entries = b2->ucb_entries;
881         b1->ucb_cnt = b2->ucb_cnt;
882 }
883
884 /*
885  * Swap two cache buckets.
886  */
887 static inline void
888 cache_bucket_swap(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
889 {
890         struct uma_cache_bucket b3;
891
892         CRITICAL_ASSERT(curthread);
893
894         cache_bucket_copy(&b3, b1);
895         cache_bucket_copy(b1, b2);
896         cache_bucket_copy(b2, &b3);
897 }
898
899 /*
900  * Attempt to fetch a bucket from a zone on behalf of the current cpu cache.
901  */
902 static uma_bucket_t
903 cache_fetch_bucket(uma_zone_t zone, uma_cache_t cache, int domain)
904 {
905         uma_zone_domain_t zdom;
906         uma_bucket_t bucket;
907
908         /*
909          * Avoid the lock if possible.
910          */
911         zdom = ZDOM_GET(zone, domain);
912         if (zdom->uzd_nitems == 0)
913                 return (NULL);
914
915         if ((cache_uz_flags(cache) & UMA_ZONE_SMR) != 0 &&
916             !smr_poll(zone->uz_smr, zdom->uzd_seq, false))
917                 return (NULL);
918
919         /*
920          * Check the zone's cache of buckets.
921          */
922         zdom = zone_domain_lock(zone, domain);
923         if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL)
924                 return (bucket);
925         ZDOM_UNLOCK(zdom);
926
927         return (NULL);
928 }
929
930 static void
931 zone_log_warning(uma_zone_t zone)
932 {
933         static const struct timeval warninterval = { 300, 0 };
934
935         if (!zone_warnings || zone->uz_warning == NULL)
936                 return;
937
938         if (ratecheck(&zone->uz_ratecheck, &warninterval))
939                 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
940 }
941
942 static inline void
943 zone_maxaction(uma_zone_t zone)
944 {
945
946         if (zone->uz_maxaction.ta_func != NULL)
947                 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
948 }
949
950 /*
951  * Routine called by timeout which is used to fire off some time interval
952  * based calculations.  (stats, hash size, etc.)
953  *
954  * Arguments:
955  *      arg   Unused
956  *
957  * Returns:
958  *      Nothing
959  */
960 static void
961 uma_timeout(void *unused)
962 {
963         bucket_enable();
964         zone_foreach(zone_timeout, NULL);
965
966         /* Reschedule this event */
967         callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
968 }
969
970 /*
971  * Update the working set size estimate for the zone's bucket cache.
972  * The constants chosen here are somewhat arbitrary.  With an update period of
973  * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
974  * last 100s.
975  */
976 static void
977 zone_domain_update_wss(uma_zone_domain_t zdom)
978 {
979         long wss;
980
981         ZDOM_LOCK(zdom);
982         MPASS(zdom->uzd_imax >= zdom->uzd_imin);
983         wss = zdom->uzd_imax - zdom->uzd_imin;
984         zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
985         zdom->uzd_wss = (4 * wss + zdom->uzd_wss) / 5;
986         ZDOM_UNLOCK(zdom);
987 }
988
989 /*
990  * Routine to perform timeout driven calculations.  This expands the
991  * hashes and does per cpu statistics aggregation.
992  *
993  *  Returns nothing.
994  */
995 static void
996 zone_timeout(uma_zone_t zone, void *unused)
997 {
998         uma_keg_t keg;
999         u_int slabs, pages;
1000
1001         if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
1002                 goto update_wss;
1003
1004         keg = zone->uz_keg;
1005
1006         /*
1007          * Hash zones are non-numa by definition so the first domain
1008          * is the only one present.
1009          */
1010         KEG_LOCK(keg, 0);
1011         pages = keg->uk_domain[0].ud_pages;
1012
1013         /*
1014          * Expand the keg hash table.
1015          *
1016          * This is done if the number of slabs is larger than the hash size.
1017          * What I'm trying to do here is completely reduce collisions.  This
1018          * may be a little aggressive.  Should I allow for two collisions max?
1019          */
1020         if ((slabs = pages / keg->uk_ppera) > keg->uk_hash.uh_hashsize) {
1021                 struct uma_hash newhash;
1022                 struct uma_hash oldhash;
1023                 int ret;
1024
1025                 /*
1026                  * This is so involved because allocating and freeing
1027                  * while the keg lock is held will lead to deadlock.
1028                  * I have to do everything in stages and check for
1029                  * races.
1030                  */
1031                 KEG_UNLOCK(keg, 0);
1032                 ret = hash_alloc(&newhash, 1 << fls(slabs));
1033                 KEG_LOCK(keg, 0);
1034                 if (ret) {
1035                         if (hash_expand(&keg->uk_hash, &newhash)) {
1036                                 oldhash = keg->uk_hash;
1037                                 keg->uk_hash = newhash;
1038                         } else
1039                                 oldhash = newhash;
1040
1041                         KEG_UNLOCK(keg, 0);
1042                         hash_free(&oldhash);
1043                         goto update_wss;
1044                 }
1045         }
1046         KEG_UNLOCK(keg, 0);
1047
1048 update_wss:
1049         for (int i = 0; i < vm_ndomains; i++)
1050                 zone_domain_update_wss(ZDOM_GET(zone, i));
1051 }
1052
1053 /*
1054  * Allocate and zero fill the next sized hash table from the appropriate
1055  * backing store.
1056  *
1057  * Arguments:
1058  *      hash  A new hash structure with the old hash size in uh_hashsize
1059  *
1060  * Returns:
1061  *      1 on success and 0 on failure.
1062  */
1063 static int
1064 hash_alloc(struct uma_hash *hash, u_int size)
1065 {
1066         size_t alloc;
1067
1068         KASSERT(powerof2(size), ("hash size must be power of 2"));
1069         if (size > UMA_HASH_SIZE_INIT)  {
1070                 hash->uh_hashsize = size;
1071                 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
1072                 hash->uh_slab_hash = malloc(alloc, M_UMAHASH, M_NOWAIT);
1073         } else {
1074                 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
1075                 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
1076                     UMA_ANYDOMAIN, M_WAITOK);
1077                 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
1078         }
1079         if (hash->uh_slab_hash) {
1080                 bzero(hash->uh_slab_hash, alloc);
1081                 hash->uh_hashmask = hash->uh_hashsize - 1;
1082                 return (1);
1083         }
1084
1085         return (0);
1086 }
1087
1088 /*
1089  * Expands the hash table for HASH zones.  This is done from zone_timeout
1090  * to reduce collisions.  This must not be done in the regular allocation
1091  * path, otherwise, we can recurse on the vm while allocating pages.
1092  *
1093  * Arguments:
1094  *      oldhash  The hash you want to expand
1095  *      newhash  The hash structure for the new table
1096  *
1097  * Returns:
1098  *      Nothing
1099  *
1100  * Discussion:
1101  */
1102 static int
1103 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
1104 {
1105         uma_hash_slab_t slab;
1106         u_int hval;
1107         u_int idx;
1108
1109         if (!newhash->uh_slab_hash)
1110                 return (0);
1111
1112         if (oldhash->uh_hashsize >= newhash->uh_hashsize)
1113                 return (0);
1114
1115         /*
1116          * I need to investigate hash algorithms for resizing without a
1117          * full rehash.
1118          */
1119
1120         for (idx = 0; idx < oldhash->uh_hashsize; idx++)
1121                 while (!LIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
1122                         slab = LIST_FIRST(&oldhash->uh_slab_hash[idx]);
1123                         LIST_REMOVE(slab, uhs_hlink);
1124                         hval = UMA_HASH(newhash, slab->uhs_data);
1125                         LIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
1126                             slab, uhs_hlink);
1127                 }
1128
1129         return (1);
1130 }
1131
1132 /*
1133  * Free the hash bucket to the appropriate backing store.
1134  *
1135  * Arguments:
1136  *      slab_hash  The hash bucket we're freeing
1137  *      hashsize   The number of entries in that hash bucket
1138  *
1139  * Returns:
1140  *      Nothing
1141  */
1142 static void
1143 hash_free(struct uma_hash *hash)
1144 {
1145         if (hash->uh_slab_hash == NULL)
1146                 return;
1147         if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
1148                 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
1149         else
1150                 free(hash->uh_slab_hash, M_UMAHASH);
1151 }
1152
1153 /*
1154  * Frees all outstanding items in a bucket
1155  *
1156  * Arguments:
1157  *      zone   The zone to free to, must be unlocked.
1158  *      bucket The free/alloc bucket with items.
1159  *
1160  * Returns:
1161  *      Nothing
1162  */
1163 static void
1164 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
1165 {
1166         int i;
1167
1168         if (bucket->ub_cnt == 0)
1169                 return;
1170
1171         if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
1172             bucket->ub_seq != SMR_SEQ_INVALID) {
1173                 smr_wait(zone->uz_smr, bucket->ub_seq);
1174                 bucket->ub_seq = SMR_SEQ_INVALID;
1175                 for (i = 0; i < bucket->ub_cnt; i++)
1176                         item_dtor(zone, bucket->ub_bucket[i],
1177                             zone->uz_size, NULL, SKIP_NONE);
1178         }
1179         if (zone->uz_fini)
1180                 for (i = 0; i < bucket->ub_cnt; i++) 
1181                         zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
1182         zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
1183         if (zone->uz_max_items > 0)
1184                 zone_free_limit(zone, bucket->ub_cnt);
1185 #ifdef INVARIANTS
1186         bzero(bucket->ub_bucket, sizeof(void *) * bucket->ub_cnt);
1187 #endif
1188         bucket->ub_cnt = 0;
1189 }
1190
1191 /*
1192  * Drains the per cpu caches for a zone.
1193  *
1194  * NOTE: This may only be called while the zone is being torn down, and not
1195  * during normal operation.  This is necessary in order that we do not have
1196  * to migrate CPUs to drain the per-CPU caches.
1197  *
1198  * Arguments:
1199  *      zone     The zone to drain, must be unlocked.
1200  *
1201  * Returns:
1202  *      Nothing
1203  */
1204 static void
1205 cache_drain(uma_zone_t zone)
1206 {
1207         uma_cache_t cache;
1208         uma_bucket_t bucket;
1209         smr_seq_t seq;
1210         int cpu;
1211
1212         /*
1213          * XXX: It is safe to not lock the per-CPU caches, because we're
1214          * tearing down the zone anyway.  I.e., there will be no further use
1215          * of the caches at this point.
1216          *
1217          * XXX: It would good to be able to assert that the zone is being
1218          * torn down to prevent improper use of cache_drain().
1219          */
1220         seq = SMR_SEQ_INVALID;
1221         if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
1222                 seq = smr_advance(zone->uz_smr);
1223         CPU_FOREACH(cpu) {
1224                 cache = &zone->uz_cpu[cpu];
1225                 bucket = cache_bucket_unload_alloc(cache);
1226                 if (bucket != NULL)
1227                         bucket_free(zone, bucket, NULL);
1228                 bucket = cache_bucket_unload_free(cache);
1229                 if (bucket != NULL) {
1230                         bucket->ub_seq = seq;
1231                         bucket_free(zone, bucket, NULL);
1232                 }
1233                 bucket = cache_bucket_unload_cross(cache);
1234                 if (bucket != NULL) {
1235                         bucket->ub_seq = seq;
1236                         bucket_free(zone, bucket, NULL);
1237                 }
1238         }
1239         bucket_cache_reclaim(zone, true);
1240 }
1241
1242 static void
1243 cache_shrink(uma_zone_t zone, void *unused)
1244 {
1245
1246         if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1247                 return;
1248
1249         zone->uz_bucket_size =
1250             (zone->uz_bucket_size_min + zone->uz_bucket_size) / 2;
1251 }
1252
1253 static void
1254 cache_drain_safe_cpu(uma_zone_t zone, void *unused)
1255 {
1256         uma_cache_t cache;
1257         uma_bucket_t b1, b2, b3;
1258         int domain;
1259
1260         if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1261                 return;
1262
1263         b1 = b2 = b3 = NULL;
1264         critical_enter();
1265         cache = &zone->uz_cpu[curcpu];
1266         domain = PCPU_GET(domain);
1267         b1 = cache_bucket_unload_alloc(cache);
1268
1269         /*
1270          * Don't flush SMR zone buckets.  This leaves the zone without a
1271          * bucket and forces every free to synchronize().
1272          */
1273         if ((zone->uz_flags & UMA_ZONE_SMR) == 0) {
1274                 b2 = cache_bucket_unload_free(cache);
1275                 b3 = cache_bucket_unload_cross(cache);
1276         }
1277         critical_exit();
1278
1279         if (b1 != NULL)
1280                 zone_free_bucket(zone, b1, NULL, domain, false);
1281         if (b2 != NULL)
1282                 zone_free_bucket(zone, b2, NULL, domain, false);
1283         if (b3 != NULL) {
1284                 /* Adjust the domain so it goes to zone_free_cross. */
1285                 domain = (domain + 1) % vm_ndomains;
1286                 zone_free_bucket(zone, b3, NULL, domain, false);
1287         }
1288 }
1289
1290 /*
1291  * Safely drain per-CPU caches of a zone(s) to alloc bucket.
1292  * This is an expensive call because it needs to bind to all CPUs
1293  * one by one and enter a critical section on each of them in order
1294  * to safely access their cache buckets.
1295  * Zone lock must not be held on call this function.
1296  */
1297 static void
1298 pcpu_cache_drain_safe(uma_zone_t zone)
1299 {
1300         int cpu;
1301
1302         /*
1303          * Polite bucket sizes shrinking was not enough, shrink aggressively.
1304          */
1305         if (zone)
1306                 cache_shrink(zone, NULL);
1307         else
1308                 zone_foreach(cache_shrink, NULL);
1309
1310         CPU_FOREACH(cpu) {
1311                 thread_lock(curthread);
1312                 sched_bind(curthread, cpu);
1313                 thread_unlock(curthread);
1314
1315                 if (zone)
1316                         cache_drain_safe_cpu(zone, NULL);
1317                 else
1318                         zone_foreach(cache_drain_safe_cpu, NULL);
1319         }
1320         thread_lock(curthread);
1321         sched_unbind(curthread);
1322         thread_unlock(curthread);
1323 }
1324
1325 /*
1326  * Reclaim cached buckets from a zone.  All buckets are reclaimed if the caller
1327  * requested a drain, otherwise the per-domain caches are trimmed to either
1328  * estimated working set size.
1329  */
1330 static void
1331 bucket_cache_reclaim(uma_zone_t zone, bool drain)
1332 {
1333         uma_zone_domain_t zdom;
1334         uma_bucket_t bucket;
1335         long target;
1336         int i;
1337
1338         /*
1339          * Shrink the zone bucket size to ensure that the per-CPU caches
1340          * don't grow too large.
1341          */
1342         if (zone->uz_bucket_size > zone->uz_bucket_size_min)
1343                 zone->uz_bucket_size--;
1344
1345         for (i = 0; i < vm_ndomains; i++) {
1346                 /*
1347                  * The cross bucket is partially filled and not part of
1348                  * the item count.  Reclaim it individually here.
1349                  */
1350                 zdom = ZDOM_GET(zone, i);
1351                 if ((zone->uz_flags & UMA_ZONE_SMR) == 0 || drain) {
1352                         ZONE_CROSS_LOCK(zone);
1353                         bucket = zdom->uzd_cross;
1354                         zdom->uzd_cross = NULL;
1355                         ZONE_CROSS_UNLOCK(zone);
1356                         if (bucket != NULL)
1357                                 bucket_free(zone, bucket, NULL);
1358                 }
1359
1360                 /*
1361                  * If we were asked to drain the zone, we are done only once
1362                  * this bucket cache is empty.  Otherwise, we reclaim items in
1363                  * excess of the zone's estimated working set size.  If the
1364                  * difference nitems - imin is larger than the WSS estimate,
1365                  * then the estimate will grow at the end of this interval and
1366                  * we ignore the historical average.
1367                  */
1368                 ZDOM_LOCK(zdom);
1369                 target = drain ? 0 : lmax(zdom->uzd_wss, zdom->uzd_nitems -
1370                     zdom->uzd_imin);
1371                 while (zdom->uzd_nitems > target) {
1372                         bucket = zone_fetch_bucket(zone, zdom, true);
1373                         if (bucket == NULL)
1374                                 break;
1375                         bucket_free(zone, bucket, NULL);
1376                         ZDOM_LOCK(zdom);
1377                 }
1378                 ZDOM_UNLOCK(zdom);
1379         }
1380 }
1381
1382 static void
1383 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
1384 {
1385         uint8_t *mem;
1386         int i;
1387         uint8_t flags;
1388
1389         CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
1390             keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
1391
1392         mem = slab_data(slab, keg);
1393         flags = slab->us_flags;
1394         i = start;
1395         if (keg->uk_fini != NULL) {
1396                 for (i--; i > -1; i--)
1397 #ifdef INVARIANTS
1398                 /*
1399                  * trash_fini implies that dtor was trash_dtor. trash_fini
1400                  * would check that memory hasn't been modified since free,
1401                  * which executed trash_dtor.
1402                  * That's why we need to run uma_dbg_kskip() check here,
1403                  * albeit we don't make skip check for other init/fini
1404                  * invocations.
1405                  */
1406                 if (!uma_dbg_kskip(keg, slab_item(slab, keg, i)) ||
1407                     keg->uk_fini != trash_fini)
1408 #endif
1409                         keg->uk_fini(slab_item(slab, keg, i), keg->uk_size);
1410         }
1411         if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
1412                 zone_free_item(slabzone(keg->uk_ipers), slab_tohashslab(slab),
1413                     NULL, SKIP_NONE);
1414         keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
1415         uma_total_dec(PAGE_SIZE * keg->uk_ppera);
1416 }
1417
1418 static void
1419 keg_drain_domain(uma_keg_t keg, int domain)
1420 {
1421         struct slabhead freeslabs;
1422         uma_domain_t dom;
1423         uma_slab_t slab, tmp;
1424         uint32_t i, stofree, stokeep, partial;
1425
1426         dom = &keg->uk_domain[domain];
1427         LIST_INIT(&freeslabs);
1428
1429         CTR4(KTR_UMA, "keg_drain %s(%p) domain %d free items: %u",
1430             keg->uk_name, keg, domain, dom->ud_free_items);
1431
1432         KEG_LOCK(keg, domain);
1433
1434         /*
1435          * Are the free items in partially allocated slabs sufficient to meet
1436          * the reserve? If not, compute the number of fully free slabs that must
1437          * be kept.
1438          */
1439         partial = dom->ud_free_items - dom->ud_free_slabs * keg->uk_ipers;
1440         if (partial < keg->uk_reserve) {
1441                 stokeep = min(dom->ud_free_slabs,
1442                     howmany(keg->uk_reserve - partial, keg->uk_ipers));
1443         } else {
1444                 stokeep = 0;
1445         }
1446         stofree = dom->ud_free_slabs - stokeep;
1447
1448         /*
1449          * Partition the free slabs into two sets: those that must be kept in
1450          * order to maintain the reserve, and those that may be released back to
1451          * the system.  Since one set may be much larger than the other,
1452          * populate the smaller of the two sets and swap them if necessary.
1453          */
1454         for (i = min(stofree, stokeep); i > 0; i--) {
1455                 slab = LIST_FIRST(&dom->ud_free_slab);
1456                 LIST_REMOVE(slab, us_link);
1457                 LIST_INSERT_HEAD(&freeslabs, slab, us_link);
1458         }
1459         if (stofree > stokeep)
1460                 LIST_SWAP(&freeslabs, &dom->ud_free_slab, uma_slab, us_link);
1461
1462         if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0) {
1463                 LIST_FOREACH(slab, &freeslabs, us_link)
1464                         UMA_HASH_REMOVE(&keg->uk_hash, slab);
1465         }
1466         dom->ud_free_items -= stofree * keg->uk_ipers;
1467         dom->ud_free_slabs -= stofree;
1468         dom->ud_pages -= stofree * keg->uk_ppera;
1469         KEG_UNLOCK(keg, domain);
1470
1471         LIST_FOREACH_SAFE(slab, &freeslabs, us_link, tmp)
1472                 keg_free_slab(keg, slab, keg->uk_ipers);
1473 }
1474
1475 /*
1476  * Frees pages from a keg back to the system.  This is done on demand from
1477  * the pageout daemon.
1478  *
1479  * Returns nothing.
1480  */
1481 static void
1482 keg_drain(uma_keg_t keg)
1483 {
1484         int i;
1485
1486         if ((keg->uk_flags & UMA_ZONE_NOFREE) != 0)
1487                 return;
1488         for (i = 0; i < vm_ndomains; i++)
1489                 keg_drain_domain(keg, i);
1490 }
1491
1492 static void
1493 zone_reclaim(uma_zone_t zone, int waitok, bool drain)
1494 {
1495
1496         /*
1497          * Set draining to interlock with zone_dtor() so we can release our
1498          * locks as we go.  Only dtor() should do a WAITOK call since it
1499          * is the only call that knows the structure will still be available
1500          * when it wakes up.
1501          */
1502         ZONE_LOCK(zone);
1503         while (zone->uz_flags & UMA_ZFLAG_RECLAIMING) {
1504                 if (waitok == M_NOWAIT)
1505                         goto out;
1506                 msleep(zone, &ZDOM_GET(zone, 0)->uzd_lock, PVM, "zonedrain",
1507                     1);
1508         }
1509         zone->uz_flags |= UMA_ZFLAG_RECLAIMING;
1510         ZONE_UNLOCK(zone);
1511         bucket_cache_reclaim(zone, drain);
1512
1513         /*
1514          * The DRAINING flag protects us from being freed while
1515          * we're running.  Normally the uma_rwlock would protect us but we
1516          * must be able to release and acquire the right lock for each keg.
1517          */
1518         if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0)
1519                 keg_drain(zone->uz_keg);
1520         ZONE_LOCK(zone);
1521         zone->uz_flags &= ~UMA_ZFLAG_RECLAIMING;
1522         wakeup(zone);
1523 out:
1524         ZONE_UNLOCK(zone);
1525 }
1526
1527 static void
1528 zone_drain(uma_zone_t zone, void *unused)
1529 {
1530
1531         zone_reclaim(zone, M_NOWAIT, true);
1532 }
1533
1534 static void
1535 zone_trim(uma_zone_t zone, void *unused)
1536 {
1537
1538         zone_reclaim(zone, M_NOWAIT, false);
1539 }
1540
1541 /*
1542  * Allocate a new slab for a keg and inserts it into the partial slab list.
1543  * The keg should be unlocked on entry.  If the allocation succeeds it will
1544  * be locked on return.
1545  *
1546  * Arguments:
1547  *      flags   Wait flags for the item initialization routine
1548  *      aflags  Wait flags for the slab allocation
1549  *
1550  * Returns:
1551  *      The slab that was allocated or NULL if there is no memory and the
1552  *      caller specified M_NOWAIT.
1553  */
1554 static uma_slab_t
1555 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1556     int aflags)
1557 {
1558         uma_domain_t dom;
1559         uma_alloc allocf;
1560         uma_slab_t slab;
1561         unsigned long size;
1562         uint8_t *mem;
1563         uint8_t sflags;
1564         int i;
1565
1566         KASSERT(domain >= 0 && domain < vm_ndomains,
1567             ("keg_alloc_slab: domain %d out of range", domain));
1568
1569         allocf = keg->uk_allocf;
1570         slab = NULL;
1571         mem = NULL;
1572         if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
1573                 uma_hash_slab_t hslab;
1574                 hslab = zone_alloc_item(slabzone(keg->uk_ipers), NULL,
1575                     domain, aflags);
1576                 if (hslab == NULL)
1577                         goto fail;
1578                 slab = &hslab->uhs_slab;
1579         }
1580
1581         /*
1582          * This reproduces the old vm_zone behavior of zero filling pages the
1583          * first time they are added to a zone.
1584          *
1585          * Malloced items are zeroed in uma_zalloc.
1586          */
1587
1588         if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1589                 aflags |= M_ZERO;
1590         else
1591                 aflags &= ~M_ZERO;
1592
1593         if (keg->uk_flags & UMA_ZONE_NODUMP)
1594                 aflags |= M_NODUMP;
1595
1596         /* zone is passed for legacy reasons. */
1597         size = keg->uk_ppera * PAGE_SIZE;
1598         mem = allocf(zone, size, domain, &sflags, aflags);
1599         if (mem == NULL) {
1600                 if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
1601                         zone_free_item(slabzone(keg->uk_ipers),
1602                             slab_tohashslab(slab), NULL, SKIP_NONE);
1603                 goto fail;
1604         }
1605         uma_total_inc(size);
1606
1607         /* For HASH zones all pages go to the same uma_domain. */
1608         if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
1609                 domain = 0;
1610
1611         /* Point the slab into the allocated memory */
1612         if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE))
1613                 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1614         else
1615                 slab_tohashslab(slab)->uhs_data = mem;
1616
1617         if (keg->uk_flags & UMA_ZFLAG_VTOSLAB)
1618                 for (i = 0; i < keg->uk_ppera; i++)
1619                         vsetzoneslab((vm_offset_t)mem + (i * PAGE_SIZE),
1620                             zone, slab);
1621
1622         slab->us_freecount = keg->uk_ipers;
1623         slab->us_flags = sflags;
1624         slab->us_domain = domain;
1625
1626         BIT_FILL(keg->uk_ipers, &slab->us_free);
1627 #ifdef INVARIANTS
1628         BIT_ZERO(keg->uk_ipers, slab_dbg_bits(slab, keg));
1629 #endif
1630
1631         if (keg->uk_init != NULL) {
1632                 for (i = 0; i < keg->uk_ipers; i++)
1633                         if (keg->uk_init(slab_item(slab, keg, i),
1634                             keg->uk_size, flags) != 0)
1635                                 break;
1636                 if (i != keg->uk_ipers) {
1637                         keg_free_slab(keg, slab, i);
1638                         goto fail;
1639                 }
1640         }
1641         KEG_LOCK(keg, domain);
1642
1643         CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1644             slab, keg->uk_name, keg);
1645
1646         if (keg->uk_flags & UMA_ZFLAG_HASH)
1647                 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1648
1649         /*
1650          * If we got a slab here it's safe to mark it partially used
1651          * and return.  We assume that the caller is going to remove
1652          * at least one item.
1653          */
1654         dom = &keg->uk_domain[domain];
1655         LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
1656         dom->ud_pages += keg->uk_ppera;
1657         dom->ud_free_items += keg->uk_ipers;
1658
1659         return (slab);
1660
1661 fail:
1662         return (NULL);
1663 }
1664
1665 /*
1666  * This function is intended to be used early on in place of page_alloc() so
1667  * that we may use the boot time page cache to satisfy allocations before
1668  * the VM is ready.
1669  */
1670 static void *
1671 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1672     int wait)
1673 {
1674         vm_paddr_t pa;
1675         vm_page_t m;
1676         void *mem;
1677         int pages;
1678         int i;
1679
1680         pages = howmany(bytes, PAGE_SIZE);
1681         KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1682
1683         *pflag = UMA_SLAB_BOOT;
1684         m = vm_page_alloc_contig_domain(NULL, 0, domain,
1685             malloc2vm_flags(wait) | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED, pages, 
1686             (vm_paddr_t)0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT);
1687         if (m == NULL)
1688                 return (NULL);
1689
1690         pa = VM_PAGE_TO_PHYS(m);
1691         for (i = 0; i < pages; i++, pa += PAGE_SIZE) {
1692 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1693     defined(__riscv) || defined(__powerpc64__)
1694                 if ((wait & M_NODUMP) == 0)
1695                         dump_add_page(pa);
1696 #endif
1697         }
1698         /* Allocate KVA and indirectly advance bootmem. */
1699         mem = (void *)pmap_map(&bootmem, m->phys_addr,
1700             m->phys_addr + (pages * PAGE_SIZE), VM_PROT_READ | VM_PROT_WRITE);
1701         if ((wait & M_ZERO) != 0)
1702                 bzero(mem, pages * PAGE_SIZE);
1703
1704         return (mem);
1705 }
1706
1707 static void
1708 startup_free(void *mem, vm_size_t bytes)
1709 {
1710         vm_offset_t va;
1711         vm_page_t m;
1712
1713         va = (vm_offset_t)mem;
1714         m = PHYS_TO_VM_PAGE(pmap_kextract(va));
1715         pmap_remove(kernel_pmap, va, va + bytes);
1716         for (; bytes != 0; bytes -= PAGE_SIZE, m++) {
1717 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1718     defined(__riscv) || defined(__powerpc64__)
1719                 dump_drop_page(VM_PAGE_TO_PHYS(m));
1720 #endif
1721                 vm_page_unwire_noq(m);
1722                 vm_page_free(m);
1723         }
1724 }
1725
1726 /*
1727  * Allocates a number of pages from the system
1728  *
1729  * Arguments:
1730  *      bytes  The number of bytes requested
1731  *      wait  Shall we wait?
1732  *
1733  * Returns:
1734  *      A pointer to the alloced memory or possibly
1735  *      NULL if M_NOWAIT is set.
1736  */
1737 static void *
1738 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1739     int wait)
1740 {
1741         void *p;        /* Returned page */
1742
1743         *pflag = UMA_SLAB_KERNEL;
1744         p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1745
1746         return (p);
1747 }
1748
1749 static void *
1750 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1751     int wait)
1752 {
1753         struct pglist alloctail;
1754         vm_offset_t addr, zkva;
1755         int cpu, flags;
1756         vm_page_t p, p_next;
1757 #ifdef NUMA
1758         struct pcpu *pc;
1759 #endif
1760
1761         MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1762
1763         TAILQ_INIT(&alloctail);
1764         flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1765             malloc2vm_flags(wait);
1766         *pflag = UMA_SLAB_KERNEL;
1767         for (cpu = 0; cpu <= mp_maxid; cpu++) {
1768                 if (CPU_ABSENT(cpu)) {
1769                         p = vm_page_alloc(NULL, 0, flags);
1770                 } else {
1771 #ifndef NUMA
1772                         p = vm_page_alloc(NULL, 0, flags);
1773 #else
1774                         pc = pcpu_find(cpu);
1775                         if (__predict_false(VM_DOMAIN_EMPTY(pc->pc_domain)))
1776                                 p = NULL;
1777                         else
1778                                 p = vm_page_alloc_domain(NULL, 0,
1779                                     pc->pc_domain, flags);
1780                         if (__predict_false(p == NULL))
1781                                 p = vm_page_alloc(NULL, 0, flags);
1782 #endif
1783                 }
1784                 if (__predict_false(p == NULL))
1785                         goto fail;
1786                 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1787         }
1788         if ((addr = kva_alloc(bytes)) == 0)
1789                 goto fail;
1790         zkva = addr;
1791         TAILQ_FOREACH(p, &alloctail, listq) {
1792                 pmap_qenter(zkva, &p, 1);
1793                 zkva += PAGE_SIZE;
1794         }
1795         return ((void*)addr);
1796 fail:
1797         TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1798                 vm_page_unwire_noq(p);
1799                 vm_page_free(p);
1800         }
1801         return (NULL);
1802 }
1803
1804 /*
1805  * Allocates a number of pages from within an object
1806  *
1807  * Arguments:
1808  *      bytes  The number of bytes requested
1809  *      wait   Shall we wait?
1810  *
1811  * Returns:
1812  *      A pointer to the alloced memory or possibly
1813  *      NULL if M_NOWAIT is set.
1814  */
1815 static void *
1816 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1817     int wait)
1818 {
1819         TAILQ_HEAD(, vm_page) alloctail;
1820         u_long npages;
1821         vm_offset_t retkva, zkva;
1822         vm_page_t p, p_next;
1823         uma_keg_t keg;
1824
1825         TAILQ_INIT(&alloctail);
1826         keg = zone->uz_keg;
1827
1828         npages = howmany(bytes, PAGE_SIZE);
1829         while (npages > 0) {
1830                 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1831                     VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1832                     ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1833                     VM_ALLOC_NOWAIT));
1834                 if (p != NULL) {
1835                         /*
1836                          * Since the page does not belong to an object, its
1837                          * listq is unused.
1838                          */
1839                         TAILQ_INSERT_TAIL(&alloctail, p, listq);
1840                         npages--;
1841                         continue;
1842                 }
1843                 /*
1844                  * Page allocation failed, free intermediate pages and
1845                  * exit.
1846                  */
1847                 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1848                         vm_page_unwire_noq(p);
1849                         vm_page_free(p); 
1850                 }
1851                 return (NULL);
1852         }
1853         *flags = UMA_SLAB_PRIV;
1854         zkva = keg->uk_kva +
1855             atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1856         retkva = zkva;
1857         TAILQ_FOREACH(p, &alloctail, listq) {
1858                 pmap_qenter(zkva, &p, 1);
1859                 zkva += PAGE_SIZE;
1860         }
1861
1862         return ((void *)retkva);
1863 }
1864
1865 /*
1866  * Allocate physically contiguous pages.
1867  */
1868 static void *
1869 contig_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1870     int wait)
1871 {
1872
1873         *pflag = UMA_SLAB_KERNEL;
1874         return ((void *)kmem_alloc_contig_domainset(DOMAINSET_FIXED(domain),
1875             bytes, wait, 0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT));
1876 }
1877
1878 /*
1879  * Frees a number of pages to the system
1880  *
1881  * Arguments:
1882  *      mem   A pointer to the memory to be freed
1883  *      size  The size of the memory being freed
1884  *      flags The original p->us_flags field
1885  *
1886  * Returns:
1887  *      Nothing
1888  */
1889 static void
1890 page_free(void *mem, vm_size_t size, uint8_t flags)
1891 {
1892
1893         if ((flags & UMA_SLAB_BOOT) != 0) {
1894                 startup_free(mem, size);
1895                 return;
1896         }
1897
1898         KASSERT((flags & UMA_SLAB_KERNEL) != 0,
1899             ("UMA: page_free used with invalid flags %x", flags));
1900
1901         kmem_free((vm_offset_t)mem, size);
1902 }
1903
1904 /*
1905  * Frees pcpu zone allocations
1906  *
1907  * Arguments:
1908  *      mem   A pointer to the memory to be freed
1909  *      size  The size of the memory being freed
1910  *      flags The original p->us_flags field
1911  *
1912  * Returns:
1913  *      Nothing
1914  */
1915 static void
1916 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1917 {
1918         vm_offset_t sva, curva;
1919         vm_paddr_t paddr;
1920         vm_page_t m;
1921
1922         MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1923
1924         if ((flags & UMA_SLAB_BOOT) != 0) {
1925                 startup_free(mem, size);
1926                 return;
1927         }
1928
1929         sva = (vm_offset_t)mem;
1930         for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1931                 paddr = pmap_kextract(curva);
1932                 m = PHYS_TO_VM_PAGE(paddr);
1933                 vm_page_unwire_noq(m);
1934                 vm_page_free(m);
1935         }
1936         pmap_qremove(sva, size >> PAGE_SHIFT);
1937         kva_free(sva, size);
1938 }
1939
1940 /*
1941  * Zero fill initializer
1942  *
1943  * Arguments/Returns follow uma_init specifications
1944  */
1945 static int
1946 zero_init(void *mem, int size, int flags)
1947 {
1948         bzero(mem, size);
1949         return (0);
1950 }
1951
1952 #ifdef INVARIANTS
1953 static struct noslabbits *
1954 slab_dbg_bits(uma_slab_t slab, uma_keg_t keg)
1955 {
1956
1957         return ((void *)((char *)&slab->us_free + BITSET_SIZE(keg->uk_ipers)));
1958 }
1959 #endif
1960
1961 /*
1962  * Actual size of embedded struct slab (!OFFPAGE).
1963  */
1964 static size_t
1965 slab_sizeof(int nitems)
1966 {
1967         size_t s;
1968
1969         s = sizeof(struct uma_slab) + BITSET_SIZE(nitems) * SLAB_BITSETS;
1970         return (roundup(s, UMA_ALIGN_PTR + 1));
1971 }
1972
1973 #define UMA_FIXPT_SHIFT 31
1974 #define UMA_FRAC_FIXPT(n, d)                                            \
1975         ((uint32_t)(((uint64_t)(n) << UMA_FIXPT_SHIFT) / (d)))
1976 #define UMA_FIXPT_PCT(f)                                                \
1977         ((u_int)(((uint64_t)100 * (f)) >> UMA_FIXPT_SHIFT))
1978 #define UMA_PCT_FIXPT(pct)      UMA_FRAC_FIXPT((pct), 100)
1979 #define UMA_MIN_EFF     UMA_PCT_FIXPT(100 - UMA_MAX_WASTE)
1980
1981 /*
1982  * Compute the number of items that will fit in a slab.  If hdr is true, the
1983  * item count may be limited to provide space in the slab for an inline slab
1984  * header.  Otherwise, all slab space will be provided for item storage.
1985  */
1986 static u_int
1987 slab_ipers_hdr(u_int size, u_int rsize, u_int slabsize, bool hdr)
1988 {
1989         u_int ipers;
1990         u_int padpi;
1991
1992         /* The padding between items is not needed after the last item. */
1993         padpi = rsize - size;
1994
1995         if (hdr) {
1996                 /*
1997                  * Start with the maximum item count and remove items until
1998                  * the slab header first alongside the allocatable memory.
1999                  */
2000                 for (ipers = MIN(SLAB_MAX_SETSIZE,
2001                     (slabsize + padpi - slab_sizeof(1)) / rsize);
2002                     ipers > 0 &&
2003                     ipers * rsize - padpi + slab_sizeof(ipers) > slabsize;
2004                     ipers--)
2005                         continue;
2006         } else {
2007                 ipers = MIN((slabsize + padpi) / rsize, SLAB_MAX_SETSIZE);
2008         }
2009
2010         return (ipers);
2011 }
2012
2013 struct keg_layout_result {
2014         u_int format;
2015         u_int slabsize;
2016         u_int ipers;
2017         u_int eff;
2018 };
2019
2020 static void
2021 keg_layout_one(uma_keg_t keg, u_int rsize, u_int slabsize, u_int fmt,
2022     struct keg_layout_result *kl)
2023 {
2024         u_int total;
2025
2026         kl->format = fmt;
2027         kl->slabsize = slabsize;
2028
2029         /* Handle INTERNAL as inline with an extra page. */
2030         if ((fmt & UMA_ZFLAG_INTERNAL) != 0) {
2031                 kl->format &= ~UMA_ZFLAG_INTERNAL;
2032                 kl->slabsize += PAGE_SIZE;
2033         }
2034
2035         kl->ipers = slab_ipers_hdr(keg->uk_size, rsize, kl->slabsize,
2036             (fmt & UMA_ZFLAG_OFFPAGE) == 0);
2037
2038         /* Account for memory used by an offpage slab header. */
2039         total = kl->slabsize;
2040         if ((fmt & UMA_ZFLAG_OFFPAGE) != 0)
2041                 total += slabzone(kl->ipers)->uz_keg->uk_rsize;
2042
2043         kl->eff = UMA_FRAC_FIXPT(kl->ipers * rsize, total);
2044 }
2045
2046 /*
2047  * Determine the format of a uma keg.  This determines where the slab header
2048  * will be placed (inline or offpage) and calculates ipers, rsize, and ppera.
2049  *
2050  * Arguments
2051  *      keg  The zone we should initialize
2052  *
2053  * Returns
2054  *      Nothing
2055  */
2056 static void
2057 keg_layout(uma_keg_t keg)
2058 {
2059         struct keg_layout_result kl = {}, kl_tmp;
2060         u_int fmts[2];
2061         u_int alignsize;
2062         u_int nfmt;
2063         u_int pages;
2064         u_int rsize;
2065         u_int slabsize;
2066         u_int i, j;
2067
2068         KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
2069             (keg->uk_size <= UMA_PCPU_ALLOC_SIZE &&
2070              (keg->uk_flags & UMA_ZONE_CACHESPREAD) == 0),
2071             ("%s: cannot configure for PCPU: keg=%s, size=%u, flags=0x%b",
2072              __func__, keg->uk_name, keg->uk_size, keg->uk_flags,
2073              PRINT_UMA_ZFLAGS));
2074         KASSERT((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) == 0 ||
2075             (keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0,
2076             ("%s: incompatible flags 0x%b", __func__, keg->uk_flags,
2077              PRINT_UMA_ZFLAGS));
2078
2079         alignsize = keg->uk_align + 1;
2080
2081         /*
2082          * Calculate the size of each allocation (rsize) according to
2083          * alignment.  If the requested size is smaller than we have
2084          * allocation bits for we round it up.
2085          */
2086         rsize = MAX(keg->uk_size, UMA_SMALLEST_UNIT);
2087         rsize = roundup2(rsize, alignsize);
2088
2089         if ((keg->uk_flags & UMA_ZONE_CACHESPREAD) != 0) {
2090                 /*
2091                  * We want one item to start on every align boundary in a page.
2092                  * To do this we will span pages.  We will also extend the item
2093                  * by the size of align if it is an even multiple of align.
2094                  * Otherwise, it would fall on the same boundary every time.
2095                  */
2096                 if ((rsize & alignsize) == 0)
2097                         rsize += alignsize;
2098                 slabsize = rsize * (PAGE_SIZE / alignsize);
2099                 slabsize = MIN(slabsize, rsize * SLAB_MAX_SETSIZE);
2100                 slabsize = MIN(slabsize, UMA_CACHESPREAD_MAX_SIZE);
2101                 slabsize = round_page(slabsize);
2102         } else {
2103                 /*
2104                  * Start with a slab size of as many pages as it takes to
2105                  * represent a single item.  We will try to fit as many
2106                  * additional items into the slab as possible.
2107                  */
2108                 slabsize = round_page(keg->uk_size);
2109         }
2110
2111         /* Build a list of all of the available formats for this keg. */
2112         nfmt = 0;
2113
2114         /* Evaluate an inline slab layout. */
2115         if ((keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0)
2116                 fmts[nfmt++] = 0;
2117
2118         /* TODO: vm_page-embedded slab. */
2119
2120         /*
2121          * We can't do OFFPAGE if we're internal or if we've been
2122          * asked to not go to the VM for buckets.  If we do this we
2123          * may end up going to the VM for slabs which we do not want
2124          * to do if we're UMA_ZONE_VM, which clearly forbids it.
2125          * In those cases, evaluate a pseudo-format called INTERNAL
2126          * which has an inline slab header and one extra page to
2127          * guarantee that it fits.
2128          *
2129          * Otherwise, see if using an OFFPAGE slab will improve our
2130          * efficiency.
2131          */
2132         if ((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) != 0)
2133                 fmts[nfmt++] = UMA_ZFLAG_INTERNAL;
2134         else
2135                 fmts[nfmt++] = UMA_ZFLAG_OFFPAGE;
2136
2137         /*
2138          * Choose a slab size and format which satisfy the minimum efficiency.
2139          * Prefer the smallest slab size that meets the constraints.
2140          *
2141          * Start with a minimum slab size, to accommodate CACHESPREAD.  Then,
2142          * for small items (up to PAGE_SIZE), the iteration increment is one
2143          * page; and for large items, the increment is one item.
2144          */
2145         i = (slabsize + rsize - keg->uk_size) / MAX(PAGE_SIZE, rsize);
2146         KASSERT(i >= 1, ("keg %s(%p) flags=0x%b slabsize=%u, rsize=%u, i=%u",
2147             keg->uk_name, keg, keg->uk_flags, PRINT_UMA_ZFLAGS, slabsize,
2148             rsize, i));
2149         for ( ; ; i++) {
2150                 slabsize = (rsize <= PAGE_SIZE) ? ptoa(i) :
2151                     round_page(rsize * (i - 1) + keg->uk_size);
2152
2153                 for (j = 0; j < nfmt; j++) {
2154                         /* Only if we have no viable format yet. */
2155                         if ((fmts[j] & UMA_ZFLAG_INTERNAL) != 0 &&
2156                             kl.ipers > 0)
2157                                 continue;
2158
2159                         keg_layout_one(keg, rsize, slabsize, fmts[j], &kl_tmp);
2160                         if (kl_tmp.eff <= kl.eff)
2161                                 continue;
2162
2163                         kl = kl_tmp;
2164
2165                         CTR6(KTR_UMA, "keg %s layout: format %#x "
2166                             "(ipers %u * rsize %u) / slabsize %#x = %u%% eff",
2167                             keg->uk_name, kl.format, kl.ipers, rsize,
2168                             kl.slabsize, UMA_FIXPT_PCT(kl.eff));
2169
2170                         /* Stop when we reach the minimum efficiency. */
2171                         if (kl.eff >= UMA_MIN_EFF)
2172                                 break;
2173                 }
2174
2175                 if (kl.eff >= UMA_MIN_EFF || !multipage_slabs ||
2176                     slabsize >= SLAB_MAX_SETSIZE * rsize ||
2177                     (keg->uk_flags & (UMA_ZONE_PCPU | UMA_ZONE_CONTIG)) != 0)
2178                         break;
2179         }
2180
2181         pages = atop(kl.slabsize);
2182         if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
2183                 pages *= mp_maxid + 1;
2184
2185         keg->uk_rsize = rsize;
2186         keg->uk_ipers = kl.ipers;
2187         keg->uk_ppera = pages;
2188         keg->uk_flags |= kl.format;
2189
2190         /*
2191          * How do we find the slab header if it is offpage or if not all item
2192          * start addresses are in the same page?  We could solve the latter
2193          * case with vaddr alignment, but we don't.
2194          */
2195         if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0 ||
2196             (keg->uk_ipers - 1) * rsize >= PAGE_SIZE) {
2197                 if ((keg->uk_flags & UMA_ZONE_NOTPAGE) != 0)
2198                         keg->uk_flags |= UMA_ZFLAG_HASH;
2199                 else
2200                         keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2201         }
2202
2203         CTR6(KTR_UMA, "%s: keg=%s, flags=%#x, rsize=%u, ipers=%u, ppera=%u",
2204             __func__, keg->uk_name, keg->uk_flags, rsize, keg->uk_ipers,
2205             pages);
2206         KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_MAX_SETSIZE,
2207             ("%s: keg=%s, flags=0x%b, rsize=%u, ipers=%u, ppera=%u", __func__,
2208              keg->uk_name, keg->uk_flags, PRINT_UMA_ZFLAGS, rsize,
2209              keg->uk_ipers, pages));
2210 }
2211
2212 /*
2213  * Keg header ctor.  This initializes all fields, locks, etc.  And inserts
2214  * the keg onto the global keg list.
2215  *
2216  * Arguments/Returns follow uma_ctor specifications
2217  *      udata  Actually uma_kctor_args
2218  */
2219 static int
2220 keg_ctor(void *mem, int size, void *udata, int flags)
2221 {
2222         struct uma_kctor_args *arg = udata;
2223         uma_keg_t keg = mem;
2224         uma_zone_t zone;
2225         int i;
2226
2227         bzero(keg, size);
2228         keg->uk_size = arg->size;
2229         keg->uk_init = arg->uminit;
2230         keg->uk_fini = arg->fini;
2231         keg->uk_align = arg->align;
2232         keg->uk_reserve = 0;
2233         keg->uk_flags = arg->flags;
2234
2235         /*
2236          * We use a global round-robin policy by default.  Zones with
2237          * UMA_ZONE_FIRSTTOUCH set will use first-touch instead, in which
2238          * case the iterator is never run.
2239          */
2240         keg->uk_dr.dr_policy = DOMAINSET_RR();
2241         keg->uk_dr.dr_iter = 0;
2242
2243         /*
2244          * The primary zone is passed to us at keg-creation time.
2245          */
2246         zone = arg->zone;
2247         keg->uk_name = zone->uz_name;
2248
2249         if (arg->flags & UMA_ZONE_ZINIT)
2250                 keg->uk_init = zero_init;
2251
2252         if (arg->flags & UMA_ZONE_MALLOC)
2253                 keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2254
2255 #ifndef SMP
2256         keg->uk_flags &= ~UMA_ZONE_PCPU;
2257 #endif
2258
2259         keg_layout(keg);
2260
2261         /*
2262          * Use a first-touch NUMA policy for kegs that pmap_extract() will
2263          * work on.  Use round-robin for everything else.
2264          *
2265          * Zones may override the default by specifying either.
2266          */
2267 #ifdef NUMA
2268         if ((keg->uk_flags &
2269             (UMA_ZONE_ROUNDROBIN | UMA_ZFLAG_CACHE | UMA_ZONE_NOTPAGE)) == 0)
2270                 keg->uk_flags |= UMA_ZONE_FIRSTTOUCH;
2271         else if ((keg->uk_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2272                 keg->uk_flags |= UMA_ZONE_ROUNDROBIN;
2273 #endif
2274
2275         /*
2276          * If we haven't booted yet we need allocations to go through the
2277          * startup cache until the vm is ready.
2278          */
2279 #ifdef UMA_MD_SMALL_ALLOC
2280         if (keg->uk_ppera == 1)
2281                 keg->uk_allocf = uma_small_alloc;
2282         else
2283 #endif
2284         if (booted < BOOT_KVA)
2285                 keg->uk_allocf = startup_alloc;
2286         else if (keg->uk_flags & UMA_ZONE_PCPU)
2287                 keg->uk_allocf = pcpu_page_alloc;
2288         else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 && keg->uk_ppera > 1)
2289                 keg->uk_allocf = contig_alloc;
2290         else
2291                 keg->uk_allocf = page_alloc;
2292 #ifdef UMA_MD_SMALL_ALLOC
2293         if (keg->uk_ppera == 1)
2294                 keg->uk_freef = uma_small_free;
2295         else
2296 #endif
2297         if (keg->uk_flags & UMA_ZONE_PCPU)
2298                 keg->uk_freef = pcpu_page_free;
2299         else
2300                 keg->uk_freef = page_free;
2301
2302         /*
2303          * Initialize keg's locks.
2304          */
2305         for (i = 0; i < vm_ndomains; i++)
2306                 KEG_LOCK_INIT(keg, i, (arg->flags & UMA_ZONE_MTXCLASS));
2307
2308         /*
2309          * If we're putting the slab header in the actual page we need to
2310          * figure out where in each page it goes.  See slab_sizeof
2311          * definition.
2312          */
2313         if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE)) {
2314                 size_t shsize;
2315
2316                 shsize = slab_sizeof(keg->uk_ipers);
2317                 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - shsize;
2318                 /*
2319                  * The only way the following is possible is if with our
2320                  * UMA_ALIGN_PTR adjustments we are now bigger than
2321                  * UMA_SLAB_SIZE.  I haven't checked whether this is
2322                  * mathematically possible for all cases, so we make
2323                  * sure here anyway.
2324                  */
2325                 KASSERT(keg->uk_pgoff + shsize <= PAGE_SIZE * keg->uk_ppera,
2326                     ("zone %s ipers %d rsize %d size %d slab won't fit",
2327                     zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
2328         }
2329
2330         if (keg->uk_flags & UMA_ZFLAG_HASH)
2331                 hash_alloc(&keg->uk_hash, 0);
2332
2333         CTR3(KTR_UMA, "keg_ctor %p zone %s(%p)", keg, zone->uz_name, zone);
2334
2335         LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
2336
2337         rw_wlock(&uma_rwlock);
2338         LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
2339         rw_wunlock(&uma_rwlock);
2340         return (0);
2341 }
2342
2343 static void
2344 zone_kva_available(uma_zone_t zone, void *unused)
2345 {
2346         uma_keg_t keg;
2347
2348         if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
2349                 return;
2350         KEG_GET(zone, keg);
2351
2352         if (keg->uk_allocf == startup_alloc) {
2353                 /* Switch to the real allocator. */
2354                 if (keg->uk_flags & UMA_ZONE_PCPU)
2355                         keg->uk_allocf = pcpu_page_alloc;
2356                 else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 &&
2357                     keg->uk_ppera > 1)
2358                         keg->uk_allocf = contig_alloc;
2359                 else
2360                         keg->uk_allocf = page_alloc;
2361         }
2362 }
2363
2364 static void
2365 zone_alloc_counters(uma_zone_t zone, void *unused)
2366 {
2367
2368         zone->uz_allocs = counter_u64_alloc(M_WAITOK);
2369         zone->uz_frees = counter_u64_alloc(M_WAITOK);
2370         zone->uz_fails = counter_u64_alloc(M_WAITOK);
2371         zone->uz_xdomain = counter_u64_alloc(M_WAITOK);
2372 }
2373
2374 static void
2375 zone_alloc_sysctl(uma_zone_t zone, void *unused)
2376 {
2377         uma_zone_domain_t zdom;
2378         uma_domain_t dom;
2379         uma_keg_t keg;
2380         struct sysctl_oid *oid, *domainoid;
2381         int domains, i, cnt;
2382         static const char *nokeg = "cache zone";
2383         char *c;
2384
2385         /*
2386          * Make a sysctl safe copy of the zone name by removing
2387          * any special characters and handling dups by appending
2388          * an index.
2389          */
2390         if (zone->uz_namecnt != 0) {
2391                 /* Count the number of decimal digits and '_' separator. */
2392                 for (i = 1, cnt = zone->uz_namecnt; cnt != 0; i++)
2393                         cnt /= 10;
2394                 zone->uz_ctlname = malloc(strlen(zone->uz_name) + i + 1,
2395                     M_UMA, M_WAITOK);
2396                 sprintf(zone->uz_ctlname, "%s_%d", zone->uz_name,
2397                     zone->uz_namecnt);
2398         } else
2399                 zone->uz_ctlname = strdup(zone->uz_name, M_UMA);
2400         for (c = zone->uz_ctlname; *c != '\0'; c++)
2401                 if (strchr("./\\ -", *c) != NULL)
2402                         *c = '_';
2403
2404         /*
2405          * Basic parameters at the root.
2406          */
2407         zone->uz_oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_vm_uma),
2408             OID_AUTO, zone->uz_ctlname, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2409         oid = zone->uz_oid;
2410         SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2411             "size", CTLFLAG_RD, &zone->uz_size, 0, "Allocation size");
2412         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2413             "flags", CTLFLAG_RD | CTLTYPE_STRING | CTLFLAG_MPSAFE,
2414             zone, 0, sysctl_handle_uma_zone_flags, "A",
2415             "Allocator configuration flags");
2416         SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2417             "bucket_size", CTLFLAG_RD, &zone->uz_bucket_size, 0,
2418             "Desired per-cpu cache size");
2419         SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2420             "bucket_size_max", CTLFLAG_RD, &zone->uz_bucket_size_max, 0,
2421             "Maximum allowed per-cpu cache size");
2422
2423         /*
2424          * keg if present.
2425          */
2426         if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
2427                 domains = vm_ndomains;
2428         else
2429                 domains = 1;
2430         oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2431             "keg", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2432         keg = zone->uz_keg;
2433         if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0) {
2434                 SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2435                     "name", CTLFLAG_RD, keg->uk_name, "Keg name");
2436                 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2437                     "rsize", CTLFLAG_RD, &keg->uk_rsize, 0,
2438                     "Real object size with alignment");
2439                 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2440                     "ppera", CTLFLAG_RD, &keg->uk_ppera, 0,
2441                     "pages per-slab allocation");
2442                 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2443                     "ipers", CTLFLAG_RD, &keg->uk_ipers, 0,
2444                     "items available per-slab");
2445                 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2446                     "align", CTLFLAG_RD, &keg->uk_align, 0,
2447                     "item alignment mask");
2448                 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2449                     "reserve", CTLFLAG_RD, &keg->uk_reserve, 0,
2450                     "number of reserved items");
2451                 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2452                     "efficiency", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2453                     keg, 0, sysctl_handle_uma_slab_efficiency, "I",
2454                     "Slab utilization (100 - internal fragmentation %)");
2455                 domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(oid),
2456                     OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2457                 for (i = 0; i < domains; i++) {
2458                         dom = &keg->uk_domain[i];
2459                         oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2460                             OID_AUTO, VM_DOMAIN(i)->vmd_name,
2461                             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2462                         SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2463                             "pages", CTLFLAG_RD, &dom->ud_pages, 0,
2464                             "Total pages currently allocated from VM");
2465                         SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2466                             "free_items", CTLFLAG_RD, &dom->ud_free_items, 0,
2467                             "items free in the slab layer");
2468                 }
2469         } else
2470                 SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2471                     "name", CTLFLAG_RD, nokeg, "Keg name");
2472
2473         /*
2474          * Information about zone limits.
2475          */
2476         oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2477             "limit", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2478         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2479             "items", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2480             zone, 0, sysctl_handle_uma_zone_items, "QU",
2481             "current number of allocated items if limit is set");
2482         SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2483             "max_items", CTLFLAG_RD, &zone->uz_max_items, 0,
2484             "Maximum number of cached items");
2485         SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2486             "sleepers", CTLFLAG_RD, &zone->uz_sleepers, 0,
2487             "Number of threads sleeping at limit");
2488         SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2489             "sleeps", CTLFLAG_RD, &zone->uz_sleeps, 0,
2490             "Total zone limit sleeps");
2491         SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2492             "bucket_max", CTLFLAG_RD, &zone->uz_bucket_max, 0,
2493             "Maximum number of items in each domain's bucket cache");
2494
2495         /*
2496          * Per-domain zone information.
2497          */
2498         domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid),
2499             OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2500         for (i = 0; i < domains; i++) {
2501                 zdom = ZDOM_GET(zone, i);
2502                 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2503                     OID_AUTO, VM_DOMAIN(i)->vmd_name,
2504                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2505                 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2506                     "nitems", CTLFLAG_RD, &zdom->uzd_nitems,
2507                     "number of items in this domain");
2508                 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2509                     "imax", CTLFLAG_RD, &zdom->uzd_imax,
2510                     "maximum item count in this period");
2511                 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2512                     "imin", CTLFLAG_RD, &zdom->uzd_imin,
2513                     "minimum item count in this period");
2514                 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2515                     "wss", CTLFLAG_RD, &zdom->uzd_wss,
2516                     "Working set size");
2517         }
2518
2519         /*
2520          * General statistics.
2521          */
2522         oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2523             "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2524         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2525             "current", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2526             zone, 1, sysctl_handle_uma_zone_cur, "I",
2527             "Current number of allocated items");
2528         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2529             "allocs", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2530             zone, 0, sysctl_handle_uma_zone_allocs, "QU",
2531             "Total allocation calls");
2532         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2533             "frees", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2534             zone, 0, sysctl_handle_uma_zone_frees, "QU",
2535             "Total free calls");
2536         SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2537             "fails", CTLFLAG_RD, &zone->uz_fails,
2538             "Number of allocation failures");
2539         SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2540             "xdomain", CTLFLAG_RD, &zone->uz_xdomain,
2541             "Free calls from the wrong domain");
2542 }
2543
2544 struct uma_zone_count {
2545         const char      *name;
2546         int             count;
2547 };
2548
2549 static void
2550 zone_count(uma_zone_t zone, void *arg)
2551 {
2552         struct uma_zone_count *cnt;
2553
2554         cnt = arg;
2555         /*
2556          * Some zones are rapidly created with identical names and
2557          * destroyed out of order.  This can lead to gaps in the count.
2558          * Use one greater than the maximum observed for this name.
2559          */
2560         if (strcmp(zone->uz_name, cnt->name) == 0)
2561                 cnt->count = MAX(cnt->count,
2562                     zone->uz_namecnt + 1);
2563 }
2564
2565 static void
2566 zone_update_caches(uma_zone_t zone)
2567 {
2568         int i;
2569
2570         for (i = 0; i <= mp_maxid; i++) {
2571                 cache_set_uz_size(&zone->uz_cpu[i], zone->uz_size);
2572                 cache_set_uz_flags(&zone->uz_cpu[i], zone->uz_flags);
2573         }
2574 }
2575
2576 /*
2577  * Zone header ctor.  This initializes all fields, locks, etc.
2578  *
2579  * Arguments/Returns follow uma_ctor specifications
2580  *      udata  Actually uma_zctor_args
2581  */
2582 static int
2583 zone_ctor(void *mem, int size, void *udata, int flags)
2584 {
2585         struct uma_zone_count cnt;
2586         struct uma_zctor_args *arg = udata;
2587         uma_zone_domain_t zdom;
2588         uma_zone_t zone = mem;
2589         uma_zone_t z;
2590         uma_keg_t keg;
2591         int i;
2592
2593         bzero(zone, size);
2594         zone->uz_name = arg->name;
2595         zone->uz_ctor = arg->ctor;
2596         zone->uz_dtor = arg->dtor;
2597         zone->uz_init = NULL;
2598         zone->uz_fini = NULL;
2599         zone->uz_sleeps = 0;
2600         zone->uz_bucket_size = 0;
2601         zone->uz_bucket_size_min = 0;
2602         zone->uz_bucket_size_max = BUCKET_MAX;
2603         zone->uz_flags = (arg->flags & UMA_ZONE_SMR);
2604         zone->uz_warning = NULL;
2605         /* The domain structures follow the cpu structures. */
2606         zone->uz_bucket_max = ULONG_MAX;
2607         timevalclear(&zone->uz_ratecheck);
2608
2609         /* Count the number of duplicate names. */
2610         cnt.name = arg->name;
2611         cnt.count = 0;
2612         zone_foreach(zone_count, &cnt);
2613         zone->uz_namecnt = cnt.count;
2614         ZONE_CROSS_LOCK_INIT(zone);
2615
2616         for (i = 0; i < vm_ndomains; i++) {
2617                 zdom = ZDOM_GET(zone, i);
2618                 ZDOM_LOCK_INIT(zone, zdom, (arg->flags & UMA_ZONE_MTXCLASS));
2619                 STAILQ_INIT(&zdom->uzd_buckets);
2620         }
2621
2622 #ifdef INVARIANTS
2623         if (arg->uminit == trash_init && arg->fini == trash_fini)
2624                 zone->uz_flags |= UMA_ZFLAG_TRASH | UMA_ZFLAG_CTORDTOR;
2625 #endif
2626
2627         /*
2628          * This is a pure cache zone, no kegs.
2629          */
2630         if (arg->import) {
2631                 KASSERT((arg->flags & UMA_ZFLAG_CACHE) != 0,
2632                     ("zone_ctor: Import specified for non-cache zone."));
2633                 zone->uz_flags = arg->flags;
2634                 zone->uz_size = arg->size;
2635                 zone->uz_import = arg->import;
2636                 zone->uz_release = arg->release;
2637                 zone->uz_arg = arg->arg;
2638 #ifdef NUMA
2639                 /*
2640                  * Cache zones are round-robin unless a policy is
2641                  * specified because they may have incompatible
2642                  * constraints.
2643                  */
2644                 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2645                         zone->uz_flags |= UMA_ZONE_ROUNDROBIN;
2646 #endif
2647                 rw_wlock(&uma_rwlock);
2648                 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
2649                 rw_wunlock(&uma_rwlock);
2650                 goto out;
2651         }
2652
2653         /*
2654          * Use the regular zone/keg/slab allocator.
2655          */
2656         zone->uz_import = zone_import;
2657         zone->uz_release = zone_release;
2658         zone->uz_arg = zone; 
2659         keg = arg->keg;
2660
2661         if (arg->flags & UMA_ZONE_SECONDARY) {
2662                 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
2663                     ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
2664                 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
2665                 zone->uz_init = arg->uminit;
2666                 zone->uz_fini = arg->fini;
2667                 zone->uz_flags |= UMA_ZONE_SECONDARY;
2668                 rw_wlock(&uma_rwlock);
2669                 ZONE_LOCK(zone);
2670                 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
2671                         if (LIST_NEXT(z, uz_link) == NULL) {
2672                                 LIST_INSERT_AFTER(z, zone, uz_link);
2673                                 break;
2674                         }
2675                 }
2676                 ZONE_UNLOCK(zone);
2677                 rw_wunlock(&uma_rwlock);
2678         } else if (keg == NULL) {
2679                 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
2680                     arg->align, arg->flags)) == NULL)
2681                         return (ENOMEM);
2682         } else {
2683                 struct uma_kctor_args karg;
2684                 int error;
2685
2686                 /* We should only be here from uma_startup() */
2687                 karg.size = arg->size;
2688                 karg.uminit = arg->uminit;
2689                 karg.fini = arg->fini;
2690                 karg.align = arg->align;
2691                 karg.flags = (arg->flags & ~UMA_ZONE_SMR);
2692                 karg.zone = zone;
2693                 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
2694                     flags);
2695                 if (error)
2696                         return (error);
2697         }
2698
2699         /* Inherit properties from the keg. */
2700         zone->uz_keg = keg;
2701         zone->uz_size = keg->uk_size;
2702         zone->uz_flags |= (keg->uk_flags &
2703             (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
2704
2705 out:
2706         if (booted >= BOOT_PCPU) {
2707                 zone_alloc_counters(zone, NULL);
2708                 if (booted >= BOOT_RUNNING)
2709                         zone_alloc_sysctl(zone, NULL);
2710         } else {
2711                 zone->uz_allocs = EARLY_COUNTER;
2712                 zone->uz_frees = EARLY_COUNTER;
2713                 zone->uz_fails = EARLY_COUNTER;
2714         }
2715
2716         /* Caller requests a private SMR context. */
2717         if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
2718                 zone->uz_smr = smr_create(zone->uz_name, 0, 0);
2719
2720         KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
2721             (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
2722             ("Invalid zone flag combination"));
2723         if (arg->flags & UMA_ZFLAG_INTERNAL)
2724                 zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
2725         if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
2726                 zone->uz_bucket_size = BUCKET_MAX;
2727         else if ((arg->flags & UMA_ZONE_MINBUCKET) != 0)
2728                 zone->uz_bucket_size_max = zone->uz_bucket_size = BUCKET_MIN;
2729         else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
2730                 zone->uz_bucket_size = 0;
2731         else
2732                 zone->uz_bucket_size = bucket_select(zone->uz_size);
2733         zone->uz_bucket_size_min = zone->uz_bucket_size;
2734         if (zone->uz_dtor != NULL || zone->uz_ctor != NULL)
2735                 zone->uz_flags |= UMA_ZFLAG_CTORDTOR;
2736         zone_update_caches(zone);
2737
2738         return (0);
2739 }
2740
2741 /*
2742  * Keg header dtor.  This frees all data, destroys locks, frees the hash
2743  * table and removes the keg from the global list.
2744  *
2745  * Arguments/Returns follow uma_dtor specifications
2746  *      udata  unused
2747  */
2748 static void
2749 keg_dtor(void *arg, int size, void *udata)
2750 {
2751         uma_keg_t keg;
2752         uint32_t free, pages;
2753         int i;
2754
2755         keg = (uma_keg_t)arg;
2756         free = pages = 0;
2757         for (i = 0; i < vm_ndomains; i++) {
2758                 free += keg->uk_domain[i].ud_free_items;
2759                 pages += keg->uk_domain[i].ud_pages;
2760                 KEG_LOCK_FINI(keg, i);
2761         }
2762         if (pages != 0)
2763                 printf("Freed UMA keg (%s) was not empty (%u items). "
2764                     " Lost %u pages of memory.\n",
2765                     keg->uk_name ? keg->uk_name : "",
2766                     pages / keg->uk_ppera * keg->uk_ipers - free, pages);
2767
2768         hash_free(&keg->uk_hash);
2769 }
2770
2771 /*
2772  * Zone header dtor.
2773  *
2774  * Arguments/Returns follow uma_dtor specifications
2775  *      udata  unused
2776  */
2777 static void
2778 zone_dtor(void *arg, int size, void *udata)
2779 {
2780         uma_zone_t zone;
2781         uma_keg_t keg;
2782         int i;
2783
2784         zone = (uma_zone_t)arg;
2785
2786         sysctl_remove_oid(zone->uz_oid, 1, 1);
2787
2788         if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
2789                 cache_drain(zone);
2790
2791         rw_wlock(&uma_rwlock);
2792         LIST_REMOVE(zone, uz_link);
2793         rw_wunlock(&uma_rwlock);
2794         zone_reclaim(zone, M_WAITOK, true);
2795
2796         /*
2797          * We only destroy kegs from non secondary/non cache zones.
2798          */
2799         if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
2800                 keg = zone->uz_keg;
2801                 rw_wlock(&uma_rwlock);
2802                 LIST_REMOVE(keg, uk_link);
2803                 rw_wunlock(&uma_rwlock);
2804                 zone_free_item(kegs, keg, NULL, SKIP_NONE);
2805         }
2806         counter_u64_free(zone->uz_allocs);
2807         counter_u64_free(zone->uz_frees);
2808         counter_u64_free(zone->uz_fails);
2809         counter_u64_free(zone->uz_xdomain);
2810         free(zone->uz_ctlname, M_UMA);
2811         for (i = 0; i < vm_ndomains; i++)
2812                 ZDOM_LOCK_FINI(ZDOM_GET(zone, i));
2813         ZONE_CROSS_LOCK_FINI(zone);
2814 }
2815
2816 static void
2817 zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2818 {
2819         uma_keg_t keg;
2820         uma_zone_t zone;
2821
2822         LIST_FOREACH(keg, &uma_kegs, uk_link) {
2823                 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
2824                         zfunc(zone, arg);
2825         }
2826         LIST_FOREACH(zone, &uma_cachezones, uz_link)
2827                 zfunc(zone, arg);
2828 }
2829
2830 /*
2831  * Traverses every zone in the system and calls a callback
2832  *
2833  * Arguments:
2834  *      zfunc  A pointer to a function which accepts a zone
2835  *              as an argument.
2836  *
2837  * Returns:
2838  *      Nothing
2839  */
2840 static void
2841 zone_foreach(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2842 {
2843
2844         rw_rlock(&uma_rwlock);
2845         zone_foreach_unlocked(zfunc, arg);
2846         rw_runlock(&uma_rwlock);
2847 }
2848
2849 /*
2850  * Initialize the kernel memory allocator.  This is done after pages can be
2851  * allocated but before general KVA is available.
2852  */
2853 void
2854 uma_startup1(vm_offset_t virtual_avail)
2855 {
2856         struct uma_zctor_args args;
2857         size_t ksize, zsize, size;
2858         uma_keg_t primarykeg;
2859         uintptr_t m;
2860         int domain;
2861         uint8_t pflag;
2862
2863         bootstart = bootmem = virtual_avail;
2864
2865         rw_init(&uma_rwlock, "UMA lock");
2866         sx_init(&uma_reclaim_lock, "umareclaim");
2867
2868         ksize = sizeof(struct uma_keg) +
2869             (sizeof(struct uma_domain) * vm_ndomains);
2870         ksize = roundup(ksize, UMA_SUPER_ALIGN);
2871         zsize = sizeof(struct uma_zone) +
2872             (sizeof(struct uma_cache) * (mp_maxid + 1)) +
2873             (sizeof(struct uma_zone_domain) * vm_ndomains);
2874         zsize = roundup(zsize, UMA_SUPER_ALIGN);
2875
2876         /* Allocate the zone of zones, zone of kegs, and zone of zones keg. */
2877         size = (zsize * 2) + ksize;
2878         for (domain = 0; domain < vm_ndomains; domain++) {
2879                 m = (uintptr_t)startup_alloc(NULL, size, domain, &pflag,
2880                     M_NOWAIT | M_ZERO);
2881                 if (m != 0)
2882                         break;
2883         }
2884         zones = (uma_zone_t)m;
2885         m += zsize;
2886         kegs = (uma_zone_t)m;
2887         m += zsize;
2888         primarykeg = (uma_keg_t)m;
2889
2890         /* "manually" create the initial zone */
2891         memset(&args, 0, sizeof(args));
2892         args.name = "UMA Kegs";
2893         args.size = ksize;
2894         args.ctor = keg_ctor;
2895         args.dtor = keg_dtor;
2896         args.uminit = zero_init;
2897         args.fini = NULL;
2898         args.keg = primarykeg;
2899         args.align = UMA_SUPER_ALIGN - 1;
2900         args.flags = UMA_ZFLAG_INTERNAL;
2901         zone_ctor(kegs, zsize, &args, M_WAITOK);
2902
2903         args.name = "UMA Zones";
2904         args.size = zsize;
2905         args.ctor = zone_ctor;
2906         args.dtor = zone_dtor;
2907         args.uminit = zero_init;
2908         args.fini = NULL;
2909         args.keg = NULL;
2910         args.align = UMA_SUPER_ALIGN - 1;
2911         args.flags = UMA_ZFLAG_INTERNAL;
2912         zone_ctor(zones, zsize, &args, M_WAITOK);
2913
2914         /* Now make zones for slab headers */
2915         slabzones[0] = uma_zcreate("UMA Slabs 0", SLABZONE0_SIZE,
2916             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2917         slabzones[1] = uma_zcreate("UMA Slabs 1", SLABZONE1_SIZE,
2918             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2919
2920         hashzone = uma_zcreate("UMA Hash",
2921             sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2922             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2923
2924         bucket_init();
2925         smr_init();
2926 }
2927
2928 #ifndef UMA_MD_SMALL_ALLOC
2929 extern void vm_radix_reserve_kva(void);
2930 #endif
2931
2932 /*
2933  * Advertise the availability of normal kva allocations and switch to
2934  * the default back-end allocator.  Marks the KVA we consumed on startup
2935  * as used in the map.
2936  */
2937 void
2938 uma_startup2(void)
2939 {
2940
2941         if (bootstart != bootmem) {
2942                 vm_map_lock(kernel_map);
2943                 (void)vm_map_insert(kernel_map, NULL, 0, bootstart, bootmem,
2944                     VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
2945                 vm_map_unlock(kernel_map);
2946         }
2947
2948 #ifndef UMA_MD_SMALL_ALLOC
2949         /* Set up radix zone to use noobj_alloc. */
2950         vm_radix_reserve_kva();
2951 #endif
2952
2953         booted = BOOT_KVA;
2954         zone_foreach_unlocked(zone_kva_available, NULL);
2955         bucket_enable();
2956 }
2957
2958 /*
2959  * Allocate counters as early as possible so that boot-time allocations are
2960  * accounted more precisely.
2961  */
2962 static void
2963 uma_startup_pcpu(void *arg __unused)
2964 {
2965
2966         zone_foreach_unlocked(zone_alloc_counters, NULL);
2967         booted = BOOT_PCPU;
2968 }
2969 SYSINIT(uma_startup_pcpu, SI_SUB_COUNTER, SI_ORDER_ANY, uma_startup_pcpu, NULL);
2970
2971 /*
2972  * Finish our initialization steps.
2973  */
2974 static void
2975 uma_startup3(void *arg __unused)
2976 {
2977
2978 #ifdef INVARIANTS
2979         TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2980         uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2981         uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2982 #endif
2983         zone_foreach_unlocked(zone_alloc_sysctl, NULL);
2984         callout_init(&uma_callout, 1);
2985         callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2986         booted = BOOT_RUNNING;
2987
2988         EVENTHANDLER_REGISTER(shutdown_post_sync, uma_shutdown, NULL,
2989             EVENTHANDLER_PRI_FIRST);
2990 }
2991 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
2992
2993 static void
2994 uma_shutdown(void)
2995 {
2996
2997         booted = BOOT_SHUTDOWN;
2998 }
2999
3000 static uma_keg_t
3001 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
3002                 int align, uint32_t flags)
3003 {
3004         struct uma_kctor_args args;
3005
3006         args.size = size;
3007         args.uminit = uminit;
3008         args.fini = fini;
3009         args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
3010         args.flags = flags;
3011         args.zone = zone;
3012         return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
3013 }
3014
3015 /* Public functions */
3016 /* See uma.h */
3017 void
3018 uma_set_align(int align)
3019 {
3020
3021         if (align != UMA_ALIGN_CACHE)
3022                 uma_align_cache = align;
3023 }
3024
3025 /* See uma.h */
3026 uma_zone_t
3027 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
3028                 uma_init uminit, uma_fini fini, int align, uint32_t flags)
3029
3030 {
3031         struct uma_zctor_args args;
3032         uma_zone_t res;
3033
3034         KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
3035             align, name));
3036
3037         /* This stuff is essential for the zone ctor */
3038         memset(&args, 0, sizeof(args));
3039         args.name = name;
3040         args.size = size;
3041         args.ctor = ctor;
3042         args.dtor = dtor;
3043         args.uminit = uminit;
3044         args.fini = fini;
3045 #ifdef  INVARIANTS
3046         /*
3047          * Inject procedures which check for memory use after free if we are
3048          * allowed to scramble the memory while it is not allocated.  This
3049          * requires that: UMA is actually able to access the memory, no init
3050          * or fini procedures, no dependency on the initial value of the
3051          * memory, and no (legitimate) use of the memory after free.  Note,
3052          * the ctor and dtor do not need to be empty.
3053          */
3054         if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOTOUCH |
3055             UMA_ZONE_NOFREE))) && uminit == NULL && fini == NULL) {
3056                 args.uminit = trash_init;
3057                 args.fini = trash_fini;
3058         }
3059 #endif
3060         args.align = align;
3061         args.flags = flags;
3062         args.keg = NULL;
3063
3064         sx_slock(&uma_reclaim_lock);
3065         res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3066         sx_sunlock(&uma_reclaim_lock);
3067
3068         return (res);
3069 }
3070
3071 /* See uma.h */
3072 uma_zone_t
3073 uma_zsecond_create(const char *name, uma_ctor ctor, uma_dtor dtor,
3074     uma_init zinit, uma_fini zfini, uma_zone_t primary)
3075 {
3076         struct uma_zctor_args args;
3077         uma_keg_t keg;
3078         uma_zone_t res;
3079
3080         keg = primary->uz_keg;
3081         memset(&args, 0, sizeof(args));
3082         args.name = name;
3083         args.size = keg->uk_size;
3084         args.ctor = ctor;
3085         args.dtor = dtor;
3086         args.uminit = zinit;
3087         args.fini = zfini;
3088         args.align = keg->uk_align;
3089         args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
3090         args.keg = keg;
3091
3092         sx_slock(&uma_reclaim_lock);
3093         res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3094         sx_sunlock(&uma_reclaim_lock);
3095
3096         return (res);
3097 }
3098
3099 /* See uma.h */
3100 uma_zone_t
3101 uma_zcache_create(const char *name, int size, uma_ctor ctor, uma_dtor dtor,
3102     uma_init zinit, uma_fini zfini, uma_import zimport, uma_release zrelease,
3103     void *arg, int flags)
3104 {
3105         struct uma_zctor_args args;
3106
3107         memset(&args, 0, sizeof(args));
3108         args.name = name;
3109         args.size = size;
3110         args.ctor = ctor;
3111         args.dtor = dtor;
3112         args.uminit = zinit;
3113         args.fini = zfini;
3114         args.import = zimport;
3115         args.release = zrelease;
3116         args.arg = arg;
3117         args.align = 0;
3118         args.flags = flags | UMA_ZFLAG_CACHE;
3119
3120         return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
3121 }
3122
3123 /* See uma.h */
3124 void
3125 uma_zdestroy(uma_zone_t zone)
3126 {
3127
3128         /*
3129          * Large slabs are expensive to reclaim, so don't bother doing
3130          * unnecessary work if we're shutting down.
3131          */
3132         if (booted == BOOT_SHUTDOWN &&
3133             zone->uz_fini == NULL && zone->uz_release == zone_release)
3134                 return;
3135         sx_slock(&uma_reclaim_lock);
3136         zone_free_item(zones, zone, NULL, SKIP_NONE);
3137         sx_sunlock(&uma_reclaim_lock);
3138 }
3139
3140 void
3141 uma_zwait(uma_zone_t zone)
3142 {
3143
3144         if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
3145                 uma_zfree_smr(zone, uma_zalloc_smr(zone, M_WAITOK));
3146         else if ((zone->uz_flags & UMA_ZONE_PCPU) != 0)
3147                 uma_zfree_pcpu(zone, uma_zalloc_pcpu(zone, M_WAITOK));
3148         else
3149                 uma_zfree(zone, uma_zalloc(zone, M_WAITOK));
3150 }
3151
3152 void *
3153 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
3154 {
3155         void *item, *pcpu_item;
3156 #ifdef SMP
3157         int i;
3158
3159         MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3160 #endif
3161         item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
3162         if (item == NULL)
3163                 return (NULL);
3164         pcpu_item = zpcpu_base_to_offset(item);
3165         if (flags & M_ZERO) {
3166 #ifdef SMP
3167                 for (i = 0; i <= mp_maxid; i++)
3168                         bzero(zpcpu_get_cpu(pcpu_item, i), zone->uz_size);
3169 #else
3170                 bzero(item, zone->uz_size);
3171 #endif
3172         }
3173         return (pcpu_item);
3174 }
3175
3176 /*
3177  * A stub while both regular and pcpu cases are identical.
3178  */
3179 void
3180 uma_zfree_pcpu_arg(uma_zone_t zone, void *pcpu_item, void *udata)
3181 {
3182         void *item;
3183
3184 #ifdef SMP
3185         MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3186 #endif
3187         item = zpcpu_offset_to_base(pcpu_item);
3188         uma_zfree_arg(zone, item, udata);
3189 }
3190
3191 static inline void *
3192 item_ctor(uma_zone_t zone, int uz_flags, int size, void *udata, int flags,
3193     void *item)
3194 {
3195 #ifdef INVARIANTS
3196         bool skipdbg;
3197
3198         skipdbg = uma_dbg_zskip(zone, item);
3199         if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3200             zone->uz_ctor != trash_ctor)
3201                 trash_ctor(item, size, udata, flags);
3202 #endif
3203         /* Check flags before loading ctor pointer. */
3204         if (__predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0) &&
3205             __predict_false(zone->uz_ctor != NULL) &&
3206             zone->uz_ctor(item, size, udata, flags) != 0) {
3207                 counter_u64_add(zone->uz_fails, 1);
3208                 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
3209                 return (NULL);
3210         }
3211 #ifdef INVARIANTS
3212         if (!skipdbg)
3213                 uma_dbg_alloc(zone, NULL, item);
3214 #endif
3215         if (__predict_false(flags & M_ZERO))
3216                 return (memset(item, 0, size));
3217
3218         return (item);
3219 }
3220
3221 static inline void
3222 item_dtor(uma_zone_t zone, void *item, int size, void *udata,
3223     enum zfreeskip skip)
3224 {
3225 #ifdef INVARIANTS
3226         bool skipdbg;
3227
3228         skipdbg = uma_dbg_zskip(zone, item);
3229         if (skip == SKIP_NONE && !skipdbg) {
3230                 if ((zone->uz_flags & UMA_ZONE_MALLOC) != 0)
3231                         uma_dbg_free(zone, udata, item);
3232                 else
3233                         uma_dbg_free(zone, NULL, item);
3234         }
3235 #endif
3236         if (__predict_true(skip < SKIP_DTOR)) {
3237                 if (zone->uz_dtor != NULL)
3238                         zone->uz_dtor(item, size, udata);
3239 #ifdef INVARIANTS
3240                 if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3241                     zone->uz_dtor != trash_dtor)
3242                         trash_dtor(item, size, udata);
3243 #endif
3244         }
3245 }
3246
3247 #ifdef NUMA
3248 static int
3249 item_domain(void *item)
3250 {
3251         int domain;
3252
3253         domain = _vm_phys_domain(vtophys(item));
3254         KASSERT(domain >= 0 && domain < vm_ndomains,
3255             ("%s: unknown domain for item %p", __func__, item));
3256         return (domain);
3257 }
3258 #endif
3259
3260 #if defined(INVARIANTS) || defined(DEBUG_MEMGUARD) || defined(WITNESS)
3261 #define UMA_ZALLOC_DEBUG
3262 static int
3263 uma_zalloc_debug(uma_zone_t zone, void **itemp, void *udata, int flags)
3264 {
3265         int error;
3266
3267         error = 0;
3268 #ifdef WITNESS
3269         if (flags & M_WAITOK) {
3270                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3271                     "uma_zalloc_debug: zone \"%s\"", zone->uz_name);
3272         }
3273 #endif
3274
3275 #ifdef INVARIANTS
3276         KASSERT((flags & M_EXEC) == 0,
3277             ("uma_zalloc_debug: called with M_EXEC"));
3278         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3279             ("uma_zalloc_debug: called within spinlock or critical section"));
3280         KASSERT((zone->uz_flags & UMA_ZONE_PCPU) == 0 || (flags & M_ZERO) == 0,
3281             ("uma_zalloc_debug: allocating from a pcpu zone with M_ZERO"));
3282 #endif
3283
3284 #ifdef DEBUG_MEMGUARD
3285         if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && memguard_cmp_zone(zone)) {
3286                 void *item;
3287                 item = memguard_alloc(zone->uz_size, flags);
3288                 if (item != NULL) {
3289                         error = EJUSTRETURN;
3290                         if (zone->uz_init != NULL &&
3291                             zone->uz_init(item, zone->uz_size, flags) != 0) {
3292                                 *itemp = NULL;
3293                                 return (error);
3294                         }
3295                         if (zone->uz_ctor != NULL &&
3296                             zone->uz_ctor(item, zone->uz_size, udata,
3297                             flags) != 0) {
3298                                 counter_u64_add(zone->uz_fails, 1);
3299                                 zone->uz_fini(item, zone->uz_size);
3300                                 *itemp = NULL;
3301                                 return (error);
3302                         }
3303                         *itemp = item;
3304                         return (error);
3305                 }
3306                 /* This is unfortunate but should not be fatal. */
3307         }
3308 #endif
3309         return (error);
3310 }
3311
3312 static int
3313 uma_zfree_debug(uma_zone_t zone, void *item, void *udata)
3314 {
3315         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3316             ("uma_zfree_debug: called with spinlock or critical section held"));
3317
3318 #ifdef DEBUG_MEMGUARD
3319         if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && is_memguard_addr(item)) {
3320                 if (zone->uz_dtor != NULL)
3321                         zone->uz_dtor(item, zone->uz_size, udata);
3322                 if (zone->uz_fini != NULL)
3323                         zone->uz_fini(item, zone->uz_size);
3324                 memguard_free(item);
3325                 return (EJUSTRETURN);
3326         }
3327 #endif
3328         return (0);
3329 }
3330 #endif
3331
3332 static inline void *
3333 cache_alloc_item(uma_zone_t zone, uma_cache_t cache, uma_cache_bucket_t bucket,
3334     void *udata, int flags)
3335 {
3336         void *item;
3337         int size, uz_flags;
3338
3339         item = cache_bucket_pop(cache, bucket);
3340         size = cache_uz_size(cache);
3341         uz_flags = cache_uz_flags(cache);
3342         critical_exit();
3343         return (item_ctor(zone, uz_flags, size, udata, flags, item));
3344 }
3345
3346 static __noinline void *
3347 cache_alloc_retry(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3348 {
3349         uma_cache_bucket_t bucket;
3350         int domain;
3351
3352         while (cache_alloc(zone, cache, udata, flags)) {
3353                 cache = &zone->uz_cpu[curcpu];
3354                 bucket = &cache->uc_allocbucket;
3355                 if (__predict_false(bucket->ucb_cnt == 0))
3356                         continue;
3357                 return (cache_alloc_item(zone, cache, bucket, udata, flags));
3358         }
3359         critical_exit();
3360
3361         /*
3362          * We can not get a bucket so try to return a single item.
3363          */
3364         if (zone->uz_flags & UMA_ZONE_FIRSTTOUCH)
3365                 domain = PCPU_GET(domain);
3366         else
3367                 domain = UMA_ANYDOMAIN;
3368         return (zone_alloc_item(zone, udata, domain, flags));
3369 }
3370
3371 /* See uma.h */
3372 void *
3373 uma_zalloc_smr(uma_zone_t zone, int flags)
3374 {
3375         uma_cache_bucket_t bucket;
3376         uma_cache_t cache;
3377
3378 #ifdef UMA_ZALLOC_DEBUG
3379         void *item;
3380
3381         KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
3382             ("uma_zalloc_arg: called with non-SMR zone."));
3383         if (uma_zalloc_debug(zone, &item, NULL, flags) == EJUSTRETURN)
3384                 return (item);
3385 #endif
3386
3387         critical_enter();
3388         cache = &zone->uz_cpu[curcpu];
3389         bucket = &cache->uc_allocbucket;
3390         if (__predict_false(bucket->ucb_cnt == 0))
3391                 return (cache_alloc_retry(zone, cache, NULL, flags));
3392         return (cache_alloc_item(zone, cache, bucket, NULL, flags));
3393 }
3394
3395 /* See uma.h */
3396 void *
3397 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
3398 {
3399         uma_cache_bucket_t bucket;
3400         uma_cache_t cache;
3401
3402         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3403         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3404
3405         /* This is the fast path allocation */
3406         CTR3(KTR_UMA, "uma_zalloc_arg zone %s(%p) flags %d", zone->uz_name,
3407             zone, flags);
3408
3409 #ifdef UMA_ZALLOC_DEBUG
3410         void *item;
3411
3412         KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3413             ("uma_zalloc_arg: called with SMR zone."));
3414         if (uma_zalloc_debug(zone, &item, udata, flags) == EJUSTRETURN)
3415                 return (item);
3416 #endif
3417
3418         /*
3419          * If possible, allocate from the per-CPU cache.  There are two
3420          * requirements for safe access to the per-CPU cache: (1) the thread
3421          * accessing the cache must not be preempted or yield during access,
3422          * and (2) the thread must not migrate CPUs without switching which
3423          * cache it accesses.  We rely on a critical section to prevent
3424          * preemption and migration.  We release the critical section in
3425          * order to acquire the zone mutex if we are unable to allocate from
3426          * the current cache; when we re-acquire the critical section, we
3427          * must detect and handle migration if it has occurred.
3428          */
3429         critical_enter();
3430         cache = &zone->uz_cpu[curcpu];
3431         bucket = &cache->uc_allocbucket;
3432         if (__predict_false(bucket->ucb_cnt == 0))
3433                 return (cache_alloc_retry(zone, cache, udata, flags));
3434         return (cache_alloc_item(zone, cache, bucket, udata, flags));
3435 }
3436
3437 /*
3438  * Replenish an alloc bucket and possibly restore an old one.  Called in
3439  * a critical section.  Returns in a critical section.
3440  *
3441  * A false return value indicates an allocation failure.
3442  * A true return value indicates success and the caller should retry.
3443  */
3444 static __noinline bool
3445 cache_alloc(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3446 {
3447         uma_bucket_t bucket;
3448         int curdomain, domain;
3449         bool new;
3450
3451         CRITICAL_ASSERT(curthread);
3452
3453         /*
3454          * If we have run out of items in our alloc bucket see
3455          * if we can switch with the free bucket.
3456          *
3457          * SMR Zones can't re-use the free bucket until the sequence has
3458          * expired.
3459          */
3460         if ((cache_uz_flags(cache) & UMA_ZONE_SMR) == 0 &&
3461             cache->uc_freebucket.ucb_cnt != 0) {
3462                 cache_bucket_swap(&cache->uc_freebucket,
3463                     &cache->uc_allocbucket);
3464                 return (true);
3465         }
3466
3467         /*
3468          * Discard any empty allocation bucket while we hold no locks.
3469          */
3470         bucket = cache_bucket_unload_alloc(cache);
3471         critical_exit();
3472
3473         if (bucket != NULL) {
3474                 KASSERT(bucket->ub_cnt == 0,
3475                     ("cache_alloc: Entered with non-empty alloc bucket."));
3476                 bucket_free(zone, bucket, udata);
3477         }
3478
3479         /*
3480          * Attempt to retrieve the item from the per-CPU cache has failed, so
3481          * we must go back to the zone.  This requires the zdom lock, so we
3482          * must drop the critical section, then re-acquire it when we go back
3483          * to the cache.  Since the critical section is released, we may be
3484          * preempted or migrate.  As such, make sure not to maintain any
3485          * thread-local state specific to the cache from prior to releasing
3486          * the critical section.
3487          */
3488         domain = PCPU_GET(domain);
3489         if ((cache_uz_flags(cache) & UMA_ZONE_ROUNDROBIN) != 0 ||
3490             VM_DOMAIN_EMPTY(domain))
3491                 domain = zone_domain_highest(zone, domain);
3492         bucket = cache_fetch_bucket(zone, cache, domain);
3493         if (bucket == NULL && zone->uz_bucket_size != 0 && !bucketdisable) {
3494                 bucket = zone_alloc_bucket(zone, udata, domain, flags);
3495                 new = true;
3496         } else {
3497                 new = false;
3498         }
3499
3500         CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
3501             zone->uz_name, zone, bucket);
3502         if (bucket == NULL) {
3503                 critical_enter();
3504                 return (false);
3505         }
3506
3507         /*
3508          * See if we lost the race or were migrated.  Cache the
3509          * initialized bucket to make this less likely or claim
3510          * the memory directly.
3511          */
3512         critical_enter();
3513         cache = &zone->uz_cpu[curcpu];
3514         if (cache->uc_allocbucket.ucb_bucket == NULL &&
3515             ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) == 0 ||
3516             (curdomain = PCPU_GET(domain)) == domain ||
3517             VM_DOMAIN_EMPTY(curdomain))) {
3518                 if (new)
3519                         atomic_add_long(&ZDOM_GET(zone, domain)->uzd_imax,
3520                             bucket->ub_cnt);
3521                 cache_bucket_load_alloc(cache, bucket);
3522                 return (true);
3523         }
3524
3525         /*
3526          * We lost the race, release this bucket and start over.
3527          */
3528         critical_exit();
3529         zone_put_bucket(zone, domain, bucket, udata, false);
3530         critical_enter();
3531
3532         return (true);
3533 }
3534
3535 void *
3536 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
3537 {
3538 #ifdef NUMA
3539         uma_bucket_t bucket;
3540         uma_zone_domain_t zdom;
3541         void *item;
3542 #endif
3543
3544         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3545         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3546
3547         /* This is the fast path allocation */
3548         CTR4(KTR_UMA, "uma_zalloc_domain zone %s(%p) domain %d flags %d",
3549             zone->uz_name, zone, domain, flags);
3550
3551         if (flags & M_WAITOK) {
3552                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3553                     "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
3554         }
3555         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3556             ("uma_zalloc_domain: called with spinlock or critical section held"));
3557         KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3558             ("uma_zalloc_domain: called with SMR zone."));
3559 #ifdef NUMA
3560         KASSERT((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0,
3561             ("uma_zalloc_domain: called with non-FIRSTTOUCH zone."));
3562
3563         if (vm_ndomains == 1)
3564                 return (uma_zalloc_arg(zone, udata, flags));
3565
3566         /*
3567          * Try to allocate from the bucket cache before falling back to the keg.
3568          * We could try harder and attempt to allocate from per-CPU caches or
3569          * the per-domain cross-domain buckets, but the complexity is probably
3570          * not worth it.  It is more important that frees of previous
3571          * cross-domain allocations do not blow up the cache.
3572          */
3573         zdom = zone_domain_lock(zone, domain);
3574         if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL) {
3575                 item = bucket->ub_bucket[bucket->ub_cnt - 1];
3576 #ifdef INVARIANTS
3577                 bucket->ub_bucket[bucket->ub_cnt - 1] = NULL;
3578 #endif
3579                 bucket->ub_cnt--;
3580                 zone_put_bucket(zone, domain, bucket, udata, true);
3581                 item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata,
3582                     flags, item);
3583                 if (item != NULL) {
3584                         KASSERT(item_domain(item) == domain,
3585                             ("%s: bucket cache item %p from wrong domain",
3586                             __func__, item));
3587                         counter_u64_add(zone->uz_allocs, 1);
3588                 }
3589                 return (item);
3590         }
3591         ZDOM_UNLOCK(zdom);
3592         return (zone_alloc_item(zone, udata, domain, flags));
3593 #else
3594         return (uma_zalloc_arg(zone, udata, flags));
3595 #endif
3596 }
3597
3598 /*
3599  * Find a slab with some space.  Prefer slabs that are partially used over those
3600  * that are totally full.  This helps to reduce fragmentation.
3601  *
3602  * If 'rr' is 1, search all domains starting from 'domain'.  Otherwise check
3603  * only 'domain'.
3604  */
3605 static uma_slab_t
3606 keg_first_slab(uma_keg_t keg, int domain, bool rr)
3607 {
3608         uma_domain_t dom;
3609         uma_slab_t slab;
3610         int start;
3611
3612         KASSERT(domain >= 0 && domain < vm_ndomains,
3613             ("keg_first_slab: domain %d out of range", domain));
3614         KEG_LOCK_ASSERT(keg, domain);
3615
3616         slab = NULL;
3617         start = domain;
3618         do {
3619                 dom = &keg->uk_domain[domain];
3620                 if ((slab = LIST_FIRST(&dom->ud_part_slab)) != NULL)
3621                         return (slab);
3622                 if ((slab = LIST_FIRST(&dom->ud_free_slab)) != NULL) {
3623                         LIST_REMOVE(slab, us_link);
3624                         dom->ud_free_slabs--;
3625                         LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3626                         return (slab);
3627                 }
3628                 if (rr)
3629                         domain = (domain + 1) % vm_ndomains;
3630         } while (domain != start);
3631
3632         return (NULL);
3633 }
3634
3635 /*
3636  * Fetch an existing slab from a free or partial list.  Returns with the
3637  * keg domain lock held if a slab was found or unlocked if not.
3638  */
3639 static uma_slab_t
3640 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
3641 {
3642         uma_slab_t slab;
3643         uint32_t reserve;
3644
3645         /* HASH has a single free list. */
3646         if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
3647                 domain = 0;
3648
3649         KEG_LOCK(keg, domain);
3650         reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
3651         if (keg->uk_domain[domain].ud_free_items <= reserve ||
3652             (slab = keg_first_slab(keg, domain, rr)) == NULL) {
3653                 KEG_UNLOCK(keg, domain);
3654                 return (NULL);
3655         }
3656         return (slab);
3657 }
3658
3659 static uma_slab_t
3660 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
3661 {
3662         struct vm_domainset_iter di;
3663         uma_slab_t slab;
3664         int aflags, domain;
3665         bool rr;
3666
3667 restart:
3668         /*
3669          * Use the keg's policy if upper layers haven't already specified a
3670          * domain (as happens with first-touch zones).
3671          *
3672          * To avoid races we run the iterator with the keg lock held, but that
3673          * means that we cannot allow the vm_domainset layer to sleep.  Thus,
3674          * clear M_WAITOK and handle low memory conditions locally.
3675          */
3676         rr = rdomain == UMA_ANYDOMAIN;
3677         if (rr) {
3678                 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
3679                 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3680                     &aflags);
3681         } else {
3682                 aflags = flags;
3683                 domain = rdomain;
3684         }
3685
3686         for (;;) {
3687                 slab = keg_fetch_free_slab(keg, domain, rr, flags);
3688                 if (slab != NULL)
3689                         return (slab);
3690
3691                 /*
3692                  * M_NOVM means don't ask at all!
3693                  */
3694                 if (flags & M_NOVM)
3695                         break;
3696
3697                 slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
3698                 if (slab != NULL)
3699                         return (slab);
3700                 if (!rr && (flags & M_WAITOK) == 0)
3701                         break;
3702                 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
3703                         if ((flags & M_WAITOK) != 0) {
3704                                 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
3705                                 goto restart;
3706                         }
3707                         break;
3708                 }
3709         }
3710
3711         /*
3712          * We might not have been able to get a slab but another cpu
3713          * could have while we were unlocked.  Check again before we
3714          * fail.
3715          */
3716         if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL)
3717                 return (slab);
3718
3719         return (NULL);
3720 }
3721
3722 static void *
3723 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
3724 {
3725         uma_domain_t dom;
3726         void *item;
3727         int freei;
3728
3729         KEG_LOCK_ASSERT(keg, slab->us_domain);
3730
3731         dom = &keg->uk_domain[slab->us_domain];
3732         freei = BIT_FFS(keg->uk_ipers, &slab->us_free) - 1;
3733         BIT_CLR(keg->uk_ipers, freei, &slab->us_free);
3734         item = slab_item(slab, keg, freei);
3735         slab->us_freecount--;
3736         dom->ud_free_items--;
3737
3738         /*
3739          * Move this slab to the full list.  It must be on the partial list, so
3740          * we do not need to update the free slab count.  In particular,
3741          * keg_fetch_slab() always returns slabs on the partial list.
3742          */
3743         if (slab->us_freecount == 0) {
3744                 LIST_REMOVE(slab, us_link);
3745                 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
3746         }
3747
3748         return (item);
3749 }
3750
3751 static int
3752 zone_import(void *arg, void **bucket, int max, int domain, int flags)
3753 {
3754         uma_domain_t dom;
3755         uma_zone_t zone;
3756         uma_slab_t slab;
3757         uma_keg_t keg;
3758 #ifdef NUMA
3759         int stripe;
3760 #endif
3761         int i;
3762
3763         zone = arg;
3764         slab = NULL;
3765         keg = zone->uz_keg;
3766         /* Try to keep the buckets totally full */
3767         for (i = 0; i < max; ) {
3768                 if ((slab = keg_fetch_slab(keg, zone, domain, flags)) == NULL)
3769                         break;
3770 #ifdef NUMA
3771                 stripe = howmany(max, vm_ndomains);
3772 #endif
3773                 dom = &keg->uk_domain[slab->us_domain];
3774                 do {
3775                         bucket[i++] = slab_alloc_item(keg, slab);
3776                         if (dom->ud_free_items <= keg->uk_reserve) {
3777                                 /*
3778                                  * Avoid depleting the reserve after a
3779                                  * successful item allocation, even if
3780                                  * M_USE_RESERVE is specified.
3781                                  */
3782                                 KEG_UNLOCK(keg, slab->us_domain);
3783                                 goto out;
3784                         }
3785 #ifdef NUMA
3786                         /*
3787                          * If the zone is striped we pick a new slab for every
3788                          * N allocations.  Eliminating this conditional will
3789                          * instead pick a new domain for each bucket rather
3790                          * than stripe within each bucket.  The current option
3791                          * produces more fragmentation and requires more cpu
3792                          * time but yields better distribution.
3793                          */
3794                         if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0 &&
3795                             vm_ndomains > 1 && --stripe == 0)
3796                                 break;
3797 #endif
3798                 } while (slab->us_freecount != 0 && i < max);
3799                 KEG_UNLOCK(keg, slab->us_domain);
3800
3801                 /* Don't block if we allocated any successfully. */
3802                 flags &= ~M_WAITOK;
3803                 flags |= M_NOWAIT;
3804         }
3805 out:
3806         return i;
3807 }
3808
3809 static int
3810 zone_alloc_limit_hard(uma_zone_t zone, int count, int flags)
3811 {
3812         uint64_t old, new, total, max;
3813
3814         /*
3815          * The hard case.  We're going to sleep because there were existing
3816          * sleepers or because we ran out of items.  This routine enforces
3817          * fairness by keeping fifo order.
3818          *
3819          * First release our ill gotten gains and make some noise.
3820          */
3821         for (;;) {
3822                 zone_free_limit(zone, count);
3823                 zone_log_warning(zone);
3824                 zone_maxaction(zone);
3825                 if (flags & M_NOWAIT)
3826                         return (0);
3827
3828                 /*
3829                  * We need to allocate an item or set ourself as a sleeper
3830                  * while the sleepq lock is held to avoid wakeup races.  This
3831                  * is essentially a home rolled semaphore.
3832                  */
3833                 sleepq_lock(&zone->uz_max_items);
3834                 old = zone->uz_items;
3835                 do {
3836                         MPASS(UZ_ITEMS_SLEEPERS(old) < UZ_ITEMS_SLEEPERS_MAX);
3837                         /* Cache the max since we will evaluate twice. */
3838                         max = zone->uz_max_items;
3839                         if (UZ_ITEMS_SLEEPERS(old) != 0 ||
3840                             UZ_ITEMS_COUNT(old) >= max)
3841                                 new = old + UZ_ITEMS_SLEEPER;
3842                         else
3843                                 new = old + MIN(count, max - old);
3844                 } while (atomic_fcmpset_64(&zone->uz_items, &old, new) == 0);
3845
3846                 /* We may have successfully allocated under the sleepq lock. */
3847                 if (UZ_ITEMS_SLEEPERS(new) == 0) {
3848                         sleepq_release(&zone->uz_max_items);
3849                         return (new - old);
3850                 }
3851
3852                 /*
3853                  * This is in a different cacheline from uz_items so that we
3854                  * don't constantly invalidate the fastpath cacheline when we
3855                  * adjust item counts.  This could be limited to toggling on
3856                  * transitions.
3857                  */
3858                 atomic_add_32(&zone->uz_sleepers, 1);
3859                 atomic_add_64(&zone->uz_sleeps, 1);
3860
3861                 /*
3862                  * We have added ourselves as a sleeper.  The sleepq lock
3863                  * protects us from wakeup races.  Sleep now and then retry.
3864                  */
3865                 sleepq_add(&zone->uz_max_items, NULL, "zonelimit", 0, 0);
3866                 sleepq_wait(&zone->uz_max_items, PVM);
3867
3868                 /*
3869                  * After wakeup, remove ourselves as a sleeper and try
3870                  * again.  We no longer have the sleepq lock for protection.
3871                  *
3872                  * Subract ourselves as a sleeper while attempting to add
3873                  * our count.
3874                  */
3875                 atomic_subtract_32(&zone->uz_sleepers, 1);
3876                 old = atomic_fetchadd_64(&zone->uz_items,
3877                     -(UZ_ITEMS_SLEEPER - count));
3878                 /* We're no longer a sleeper. */
3879                 old -= UZ_ITEMS_SLEEPER;
3880
3881                 /*
3882                  * If we're still at the limit, restart.  Notably do not
3883                  * block on other sleepers.  Cache the max value to protect
3884                  * against changes via sysctl.
3885                  */
3886                 total = UZ_ITEMS_COUNT(old);
3887                 max = zone->uz_max_items;
3888                 if (total >= max)
3889                         continue;
3890                 /* Truncate if necessary, otherwise wake other sleepers. */
3891                 if (total + count > max) {
3892                         zone_free_limit(zone, total + count - max);
3893                         count = max - total;
3894                 } else if (total + count < max && UZ_ITEMS_SLEEPERS(old) != 0)
3895                         wakeup_one(&zone->uz_max_items);
3896
3897                 return (count);
3898         }
3899 }
3900
3901 /*
3902  * Allocate 'count' items from our max_items limit.  Returns the number
3903  * available.  If M_NOWAIT is not specified it will sleep until at least
3904  * one item can be allocated.
3905  */
3906 static int
3907 zone_alloc_limit(uma_zone_t zone, int count, int flags)
3908 {
3909         uint64_t old;
3910         uint64_t max;
3911
3912         max = zone->uz_max_items;
3913         MPASS(max > 0);
3914
3915         /*
3916          * We expect normal allocations to succeed with a simple
3917          * fetchadd.
3918          */
3919         old = atomic_fetchadd_64(&zone->uz_items, count);
3920         if (__predict_true(old + count <= max))
3921                 return (count);
3922
3923         /*
3924          * If we had some items and no sleepers just return the
3925          * truncated value.  We have to release the excess space
3926          * though because that may wake sleepers who weren't woken
3927          * because we were temporarily over the limit.
3928          */
3929         if (old < max) {
3930                 zone_free_limit(zone, (old + count) - max);
3931                 return (max - old);
3932         }
3933         return (zone_alloc_limit_hard(zone, count, flags));
3934 }
3935
3936 /*
3937  * Free a number of items back to the limit.
3938  */
3939 static void
3940 zone_free_limit(uma_zone_t zone, int count)
3941 {
3942         uint64_t old;
3943
3944         MPASS(count > 0);
3945
3946         /*
3947          * In the common case we either have no sleepers or
3948          * are still over the limit and can just return.
3949          */
3950         old = atomic_fetchadd_64(&zone->uz_items, -count);
3951         if (__predict_true(UZ_ITEMS_SLEEPERS(old) == 0 ||
3952            UZ_ITEMS_COUNT(old) - count >= zone->uz_max_items))
3953                 return;
3954
3955         /*
3956          * Moderate the rate of wakeups.  Sleepers will continue
3957          * to generate wakeups if necessary.
3958          */
3959         wakeup_one(&zone->uz_max_items);
3960 }
3961
3962 static uma_bucket_t
3963 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
3964 {
3965         uma_bucket_t bucket;
3966         int maxbucket, cnt;
3967
3968         CTR3(KTR_UMA, "zone_alloc_bucket zone %s(%p) domain %d", zone->uz_name,
3969             zone, domain);
3970
3971         /* Avoid allocs targeting empty domains. */
3972         if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
3973                 domain = UMA_ANYDOMAIN;
3974         else if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
3975                 domain = UMA_ANYDOMAIN;
3976
3977         if (zone->uz_max_items > 0)
3978                 maxbucket = zone_alloc_limit(zone, zone->uz_bucket_size,
3979                     M_NOWAIT);
3980         else
3981                 maxbucket = zone->uz_bucket_size;
3982         if (maxbucket == 0)
3983                 return (false);
3984
3985         /* Don't wait for buckets, preserve caller's NOVM setting. */
3986         bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
3987         if (bucket == NULL) {
3988                 cnt = 0;
3989                 goto out;
3990         }
3991
3992         bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
3993             MIN(maxbucket, bucket->ub_entries), domain, flags);
3994
3995         /*
3996          * Initialize the memory if necessary.
3997          */
3998         if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
3999                 int i;
4000
4001                 for (i = 0; i < bucket->ub_cnt; i++)
4002                         if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
4003                             flags) != 0)
4004                                 break;
4005                 /*
4006                  * If we couldn't initialize the whole bucket, put the
4007                  * rest back onto the freelist.
4008                  */
4009                 if (i != bucket->ub_cnt) {
4010                         zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
4011                             bucket->ub_cnt - i);
4012 #ifdef INVARIANTS
4013                         bzero(&bucket->ub_bucket[i],
4014                             sizeof(void *) * (bucket->ub_cnt - i));
4015 #endif
4016                         bucket->ub_cnt = i;
4017                 }
4018         }
4019
4020         cnt = bucket->ub_cnt;
4021         if (bucket->ub_cnt == 0) {
4022                 bucket_free(zone, bucket, udata);
4023                 counter_u64_add(zone->uz_fails, 1);
4024                 bucket = NULL;
4025         }
4026 out:
4027         if (zone->uz_max_items > 0 && cnt < maxbucket)
4028                 zone_free_limit(zone, maxbucket - cnt);
4029
4030         return (bucket);
4031 }
4032
4033 /*
4034  * Allocates a single item from a zone.
4035  *
4036  * Arguments
4037  *      zone   The zone to alloc for.
4038  *      udata  The data to be passed to the constructor.
4039  *      domain The domain to allocate from or UMA_ANYDOMAIN.
4040  *      flags  M_WAITOK, M_NOWAIT, M_ZERO.
4041  *
4042  * Returns
4043  *      NULL if there is no memory and M_NOWAIT is set
4044  *      An item if successful
4045  */
4046
4047 static void *
4048 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
4049 {
4050         void *item;
4051
4052         if (zone->uz_max_items > 0 && zone_alloc_limit(zone, 1, flags) == 0) {
4053                 counter_u64_add(zone->uz_fails, 1);
4054                 return (NULL);
4055         }
4056
4057         /* Avoid allocs targeting empty domains. */
4058         if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
4059                 domain = UMA_ANYDOMAIN;
4060
4061         if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
4062                 goto fail_cnt;
4063
4064         /*
4065          * We have to call both the zone's init (not the keg's init)
4066          * and the zone's ctor.  This is because the item is going from
4067          * a keg slab directly to the user, and the user is expecting it
4068          * to be both zone-init'd as well as zone-ctor'd.
4069          */
4070         if (zone->uz_init != NULL) {
4071                 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
4072                         zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
4073                         goto fail_cnt;
4074                 }
4075         }
4076         item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata, flags,
4077             item);
4078         if (item == NULL)
4079                 goto fail;
4080
4081         counter_u64_add(zone->uz_allocs, 1);
4082         CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
4083             zone->uz_name, zone);
4084
4085         return (item);
4086
4087 fail_cnt:
4088         counter_u64_add(zone->uz_fails, 1);
4089 fail:
4090         if (zone->uz_max_items > 0)
4091                 zone_free_limit(zone, 1);
4092         CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
4093             zone->uz_name, zone);
4094
4095         return (NULL);
4096 }
4097
4098 /* See uma.h */
4099 void
4100 uma_zfree_smr(uma_zone_t zone, void *item)
4101 {
4102         uma_cache_t cache;
4103         uma_cache_bucket_t bucket;
4104         int itemdomain, uz_flags;
4105
4106 #ifdef UMA_ZALLOC_DEBUG
4107         KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
4108             ("uma_zfree_smr: called with non-SMR zone."));
4109         KASSERT(item != NULL, ("uma_zfree_smr: Called with NULL pointer."));
4110         SMR_ASSERT_NOT_ENTERED(zone->uz_smr);
4111         if (uma_zfree_debug(zone, item, NULL) == EJUSTRETURN)
4112                 return;
4113 #endif
4114         cache = &zone->uz_cpu[curcpu];
4115         uz_flags = cache_uz_flags(cache);
4116         itemdomain = 0;
4117 #ifdef NUMA
4118         if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4119                 itemdomain = item_domain(item);
4120 #endif
4121         critical_enter();
4122         do {
4123                 cache = &zone->uz_cpu[curcpu];
4124                 /* SMR Zones must free to the free bucket. */
4125                 bucket = &cache->uc_freebucket;
4126 #ifdef NUMA
4127                 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4128                     PCPU_GET(domain) != itemdomain) {
4129                         bucket = &cache->uc_crossbucket;
4130                 }
4131 #endif
4132                 if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4133                         cache_bucket_push(cache, bucket, item);
4134                         critical_exit();
4135                         return;
4136                 }
4137         } while (cache_free(zone, cache, NULL, item, itemdomain));
4138         critical_exit();
4139
4140         /*
4141          * If nothing else caught this, we'll just do an internal free.
4142          */
4143         zone_free_item(zone, item, NULL, SKIP_NONE);
4144 }
4145
4146 /* See uma.h */
4147 void
4148 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
4149 {
4150         uma_cache_t cache;
4151         uma_cache_bucket_t bucket;
4152         int itemdomain, uz_flags;
4153
4154         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
4155         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
4156
4157         CTR2(KTR_UMA, "uma_zfree_arg zone %s(%p)", zone->uz_name, zone);
4158
4159 #ifdef UMA_ZALLOC_DEBUG
4160         KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4161             ("uma_zfree_arg: called with SMR zone."));
4162         if (uma_zfree_debug(zone, item, udata) == EJUSTRETURN)
4163                 return;
4164 #endif
4165         /* uma_zfree(..., NULL) does nothing, to match free(9). */
4166         if (item == NULL)
4167                 return;
4168
4169         /*
4170          * We are accessing the per-cpu cache without a critical section to
4171          * fetch size and flags.  This is acceptable, if we are preempted we
4172          * will simply read another cpu's line.
4173          */
4174         cache = &zone->uz_cpu[curcpu];
4175         uz_flags = cache_uz_flags(cache);
4176         if (UMA_ALWAYS_CTORDTOR ||
4177             __predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0))
4178                 item_dtor(zone, item, cache_uz_size(cache), udata, SKIP_NONE);
4179
4180         /*
4181          * The race here is acceptable.  If we miss it we'll just have to wait
4182          * a little longer for the limits to be reset.
4183          */
4184         if (__predict_false(uz_flags & UMA_ZFLAG_LIMIT)) {
4185                 if (zone->uz_sleepers > 0)
4186                         goto zfree_item;
4187         }
4188
4189         /*
4190          * If possible, free to the per-CPU cache.  There are two
4191          * requirements for safe access to the per-CPU cache: (1) the thread
4192          * accessing the cache must not be preempted or yield during access,
4193          * and (2) the thread must not migrate CPUs without switching which
4194          * cache it accesses.  We rely on a critical section to prevent
4195          * preemption and migration.  We release the critical section in
4196          * order to acquire the zone mutex if we are unable to free to the
4197          * current cache; when we re-acquire the critical section, we must
4198          * detect and handle migration if it has occurred.
4199          */
4200         itemdomain = 0;
4201 #ifdef NUMA
4202         if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4203                 itemdomain = item_domain(item);
4204 #endif
4205         critical_enter();
4206         do {
4207                 cache = &zone->uz_cpu[curcpu];
4208                 /*
4209                  * Try to free into the allocbucket first to give LIFO
4210                  * ordering for cache-hot datastructures.  Spill over
4211                  * into the freebucket if necessary.  Alloc will swap
4212                  * them if one runs dry.
4213                  */
4214                 bucket = &cache->uc_allocbucket;
4215 #ifdef NUMA
4216                 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4217                     PCPU_GET(domain) != itemdomain) {
4218                         bucket = &cache->uc_crossbucket;
4219                 } else
4220 #endif
4221                 if (bucket->ucb_cnt == bucket->ucb_entries &&
4222                    cache->uc_freebucket.ucb_cnt <
4223                    cache->uc_freebucket.ucb_entries)
4224                         cache_bucket_swap(&cache->uc_freebucket,
4225                             &cache->uc_allocbucket);
4226                 if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4227                         cache_bucket_push(cache, bucket, item);
4228                         critical_exit();
4229                         return;
4230                 }
4231         } while (cache_free(zone, cache, udata, item, itemdomain));
4232         critical_exit();
4233
4234         /*
4235          * If nothing else caught this, we'll just do an internal free.
4236          */
4237 zfree_item:
4238         zone_free_item(zone, item, udata, SKIP_DTOR);
4239 }
4240
4241 #ifdef NUMA
4242 /*
4243  * sort crossdomain free buckets to domain correct buckets and cache
4244  * them.
4245  */
4246 static void
4247 zone_free_cross(uma_zone_t zone, uma_bucket_t bucket, void *udata)
4248 {
4249         struct uma_bucketlist fullbuckets;
4250         uma_zone_domain_t zdom;
4251         uma_bucket_t b;
4252         smr_seq_t seq;
4253         void *item;
4254         int domain;
4255
4256         CTR3(KTR_UMA,
4257             "uma_zfree: zone %s(%p) draining cross bucket %p",
4258             zone->uz_name, zone, bucket);
4259
4260         /*
4261          * It is possible for buckets to arrive here out of order so we fetch
4262          * the current smr seq rather than accepting the bucket's.
4263          */
4264         seq = SMR_SEQ_INVALID;
4265         if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
4266                 seq = smr_advance(zone->uz_smr);
4267
4268         /*
4269          * To avoid having ndomain * ndomain buckets for sorting we have a
4270          * lock on the current crossfree bucket.  A full matrix with
4271          * per-domain locking could be used if necessary.
4272          */
4273         STAILQ_INIT(&fullbuckets);
4274         ZONE_CROSS_LOCK(zone);
4275         while (bucket->ub_cnt > 0) {
4276                 item = bucket->ub_bucket[bucket->ub_cnt - 1];
4277                 domain = item_domain(item);
4278                 zdom = ZDOM_GET(zone, domain);
4279                 if (zdom->uzd_cross == NULL) {
4280                         zdom->uzd_cross = bucket_alloc(zone, udata, M_NOWAIT);
4281                         if (zdom->uzd_cross == NULL)
4282                                 break;
4283                 }
4284                 b = zdom->uzd_cross;
4285                 b->ub_bucket[b->ub_cnt++] = item;
4286                 b->ub_seq = seq;
4287                 if (b->ub_cnt == b->ub_entries) {
4288                         STAILQ_INSERT_HEAD(&fullbuckets, b, ub_link);
4289                         zdom->uzd_cross = NULL;
4290                 }
4291                 bucket->ub_cnt--;
4292         }
4293         ZONE_CROSS_UNLOCK(zone);
4294         if (bucket->ub_cnt == 0)
4295                 bucket->ub_seq = SMR_SEQ_INVALID;
4296         bucket_free(zone, bucket, udata);
4297
4298         while ((b = STAILQ_FIRST(&fullbuckets)) != NULL) {
4299                 STAILQ_REMOVE_HEAD(&fullbuckets, ub_link);
4300                 domain = item_domain(b->ub_bucket[0]);
4301                 zone_put_bucket(zone, domain, b, udata, true);
4302         }
4303 }
4304 #endif
4305
4306 static void
4307 zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
4308     int itemdomain, bool ws)
4309 {
4310
4311 #ifdef NUMA
4312         /*
4313          * Buckets coming from the wrong domain will be entirely for the
4314          * only other domain on two domain systems.  In this case we can
4315          * simply cache them.  Otherwise we need to sort them back to
4316          * correct domains.
4317          */
4318         if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4319             vm_ndomains > 2 && PCPU_GET(domain) != itemdomain) {
4320                 zone_free_cross(zone, bucket, udata);
4321                 return;
4322         }
4323 #endif
4324
4325         /*
4326          * Attempt to save the bucket in the zone's domain bucket cache.
4327          */
4328         CTR3(KTR_UMA,
4329             "uma_zfree: zone %s(%p) putting bucket %p on free list",
4330             zone->uz_name, zone, bucket);
4331         /* ub_cnt is pointing to the last free item */
4332         if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
4333                 itemdomain = zone_domain_lowest(zone, itemdomain);
4334         zone_put_bucket(zone, itemdomain, bucket, udata, ws);
4335 }
4336
4337 /*
4338  * Populate a free or cross bucket for the current cpu cache.  Free any
4339  * existing full bucket either to the zone cache or back to the slab layer.
4340  *
4341  * Enters and returns in a critical section.  false return indicates that
4342  * we can not satisfy this free in the cache layer.  true indicates that
4343  * the caller should retry.
4344  */
4345 static __noinline bool
4346 cache_free(uma_zone_t zone, uma_cache_t cache, void *udata, void *item,
4347     int itemdomain)
4348 {
4349         uma_cache_bucket_t cbucket;
4350         uma_bucket_t newbucket, bucket;
4351
4352         CRITICAL_ASSERT(curthread);
4353
4354         if (zone->uz_bucket_size == 0)
4355                 return false;
4356
4357         cache = &zone->uz_cpu[curcpu];
4358         newbucket = NULL;
4359
4360         /*
4361          * FIRSTTOUCH domains need to free to the correct zdom.  When
4362          * enabled this is the zdom of the item.   The bucket is the
4363          * cross bucket if the current domain and itemdomain do not match.
4364          */
4365         cbucket = &cache->uc_freebucket;
4366 #ifdef NUMA
4367         if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4368                 if (PCPU_GET(domain) != itemdomain) {
4369                         cbucket = &cache->uc_crossbucket;
4370                         if (cbucket->ucb_cnt != 0)
4371                                 counter_u64_add(zone->uz_xdomain,
4372                                     cbucket->ucb_cnt);
4373                 }
4374         }
4375 #endif
4376         bucket = cache_bucket_unload(cbucket);
4377         KASSERT(bucket == NULL || bucket->ub_cnt == bucket->ub_entries,
4378             ("cache_free: Entered with non-full free bucket."));
4379
4380         /* We are no longer associated with this CPU. */
4381         critical_exit();
4382
4383         /*
4384          * Don't let SMR zones operate without a free bucket.  Force
4385          * a synchronize and re-use this one.  We will only degrade
4386          * to a synchronize every bucket_size items rather than every
4387          * item if we fail to allocate a bucket.
4388          */
4389         if ((zone->uz_flags & UMA_ZONE_SMR) != 0) {
4390                 if (bucket != NULL)
4391                         bucket->ub_seq = smr_advance(zone->uz_smr);
4392                 newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4393                 if (newbucket == NULL && bucket != NULL) {
4394                         bucket_drain(zone, bucket);
4395                         newbucket = bucket;
4396                         bucket = NULL;
4397                 }
4398         } else if (!bucketdisable)
4399                 newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4400
4401         if (bucket != NULL)
4402                 zone_free_bucket(zone, bucket, udata, itemdomain, true);
4403
4404         critical_enter();
4405         if ((bucket = newbucket) == NULL)
4406                 return (false);
4407         cache = &zone->uz_cpu[curcpu];
4408 #ifdef NUMA
4409         /*
4410          * Check to see if we should be populating the cross bucket.  If it
4411          * is already populated we will fall through and attempt to populate
4412          * the free bucket.
4413          */
4414         if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4415                 if (PCPU_GET(domain) != itemdomain &&
4416                     cache->uc_crossbucket.ucb_bucket == NULL) {
4417                         cache_bucket_load_cross(cache, bucket);
4418                         return (true);
4419                 }
4420         }
4421 #endif
4422         /*
4423          * We may have lost the race to fill the bucket or switched CPUs.
4424          */
4425         if (cache->uc_freebucket.ucb_bucket != NULL) {
4426                 critical_exit();
4427                 bucket_free(zone, bucket, udata);
4428                 critical_enter();
4429         } else
4430                 cache_bucket_load_free(cache, bucket);
4431
4432         return (true);
4433 }
4434
4435 static void
4436 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
4437 {
4438         uma_keg_t keg;
4439         uma_domain_t dom;
4440         int freei;
4441
4442         keg = zone->uz_keg;
4443         KEG_LOCK_ASSERT(keg, slab->us_domain);
4444
4445         /* Do we need to remove from any lists? */
4446         dom = &keg->uk_domain[slab->us_domain];
4447         if (slab->us_freecount + 1 == keg->uk_ipers) {
4448                 LIST_REMOVE(slab, us_link);
4449                 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
4450                 dom->ud_free_slabs++;
4451         } else if (slab->us_freecount == 0) {
4452                 LIST_REMOVE(slab, us_link);
4453                 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
4454         }
4455
4456         /* Slab management. */
4457         freei = slab_item_index(slab, keg, item);
4458         BIT_SET(keg->uk_ipers, freei, &slab->us_free);
4459         slab->us_freecount++;
4460
4461         /* Keg statistics. */
4462         dom->ud_free_items++;
4463 }
4464
4465 static void
4466 zone_release(void *arg, void **bucket, int cnt)
4467 {
4468         struct mtx *lock;
4469         uma_zone_t zone;
4470         uma_slab_t slab;
4471         uma_keg_t keg;
4472         uint8_t *mem;
4473         void *item;
4474         int i;
4475
4476         zone = arg;
4477         keg = zone->uz_keg;
4478         lock = NULL;
4479         if (__predict_false((zone->uz_flags & UMA_ZFLAG_HASH) != 0))
4480                 lock = KEG_LOCK(keg, 0);
4481         for (i = 0; i < cnt; i++) {
4482                 item = bucket[i];
4483                 if (__predict_true((zone->uz_flags & UMA_ZFLAG_VTOSLAB) != 0)) {
4484                         slab = vtoslab((vm_offset_t)item);
4485                 } else {
4486                         mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4487                         if ((zone->uz_flags & UMA_ZFLAG_HASH) != 0)
4488                                 slab = hash_sfind(&keg->uk_hash, mem);
4489                         else
4490                                 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4491                 }
4492                 if (lock != KEG_LOCKPTR(keg, slab->us_domain)) {
4493                         if (lock != NULL)
4494                                 mtx_unlock(lock);
4495                         lock = KEG_LOCK(keg, slab->us_domain);
4496                 }
4497                 slab_free_item(zone, slab, item);
4498         }
4499         if (lock != NULL)
4500                 mtx_unlock(lock);
4501 }
4502
4503 /*
4504  * Frees a single item to any zone.
4505  *
4506  * Arguments:
4507  *      zone   The zone to free to
4508  *      item   The item we're freeing
4509  *      udata  User supplied data for the dtor
4510  *      skip   Skip dtors and finis
4511  */
4512 static __noinline void
4513 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
4514 {
4515
4516         /*
4517          * If a free is sent directly to an SMR zone we have to
4518          * synchronize immediately because the item can instantly
4519          * be reallocated. This should only happen in degenerate
4520          * cases when no memory is available for per-cpu caches.
4521          */
4522         if ((zone->uz_flags & UMA_ZONE_SMR) != 0 && skip == SKIP_NONE)
4523                 smr_synchronize(zone->uz_smr);
4524
4525         item_dtor(zone, item, zone->uz_size, udata, skip);
4526
4527         if (skip < SKIP_FINI && zone->uz_fini)
4528                 zone->uz_fini(item, zone->uz_size);
4529
4530         zone->uz_release(zone->uz_arg, &item, 1);
4531
4532         if (skip & SKIP_CNT)
4533                 return;
4534
4535         counter_u64_add(zone->uz_frees, 1);
4536
4537         if (zone->uz_max_items > 0)
4538                 zone_free_limit(zone, 1);
4539 }
4540
4541 /* See uma.h */
4542 int
4543 uma_zone_set_max(uma_zone_t zone, int nitems)
4544 {
4545         struct uma_bucket_zone *ubz;
4546         int count;
4547
4548         /*
4549          * XXX This can misbehave if the zone has any allocations with
4550          * no limit and a limit is imposed.  There is currently no
4551          * way to clear a limit.
4552          */
4553         ZONE_LOCK(zone);
4554         ubz = bucket_zone_max(zone, nitems);
4555         count = ubz != NULL ? ubz->ubz_entries : 0;
4556         zone->uz_bucket_size_max = zone->uz_bucket_size = count;
4557         if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
4558                 zone->uz_bucket_size_min = zone->uz_bucket_size_max;
4559         zone->uz_max_items = nitems;
4560         zone->uz_flags |= UMA_ZFLAG_LIMIT;
4561         zone_update_caches(zone);
4562         /* We may need to wake waiters. */
4563         wakeup(&zone->uz_max_items);
4564         ZONE_UNLOCK(zone);
4565
4566         return (nitems);
4567 }
4568
4569 /* See uma.h */
4570 void
4571 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
4572 {
4573         struct uma_bucket_zone *ubz;
4574         int bpcpu;
4575
4576         ZONE_LOCK(zone);
4577         ubz = bucket_zone_max(zone, nitems);
4578         if (ubz != NULL) {
4579                 bpcpu = 2;
4580                 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4581                         /* Count the cross-domain bucket. */
4582                         bpcpu++;
4583                 nitems -= ubz->ubz_entries * bpcpu * mp_ncpus;
4584                 zone->uz_bucket_size_max = ubz->ubz_entries;
4585         } else {
4586                 zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
4587         }
4588         if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
4589                 zone->uz_bucket_size_min = zone->uz_bucket_size_max;
4590         zone->uz_bucket_max = nitems / vm_ndomains;
4591         ZONE_UNLOCK(zone);
4592 }
4593
4594 /* See uma.h */
4595 int
4596 uma_zone_get_max(uma_zone_t zone)
4597 {
4598         int nitems;
4599
4600         nitems = atomic_load_64(&zone->uz_max_items);
4601
4602         return (nitems);
4603 }
4604
4605 /* See uma.h */
4606 void
4607 uma_zone_set_warning(uma_zone_t zone, const char *warning)
4608 {
4609
4610         ZONE_ASSERT_COLD(zone);
4611         zone->uz_warning = warning;
4612 }
4613
4614 /* See uma.h */
4615 void
4616 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
4617 {
4618
4619         ZONE_ASSERT_COLD(zone);
4620         TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
4621 }
4622
4623 /* See uma.h */
4624 int
4625 uma_zone_get_cur(uma_zone_t zone)
4626 {
4627         int64_t nitems;
4628         u_int i;
4629
4630         nitems = 0;
4631         if (zone->uz_allocs != EARLY_COUNTER && zone->uz_frees != EARLY_COUNTER)
4632                 nitems = counter_u64_fetch(zone->uz_allocs) -
4633                     counter_u64_fetch(zone->uz_frees);
4634         CPU_FOREACH(i)
4635                 nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs) -
4636                     atomic_load_64(&zone->uz_cpu[i].uc_frees);
4637
4638         return (nitems < 0 ? 0 : nitems);
4639 }
4640
4641 static uint64_t
4642 uma_zone_get_allocs(uma_zone_t zone)
4643 {
4644         uint64_t nitems;
4645         u_int i;
4646
4647         nitems = 0;
4648         if (zone->uz_allocs != EARLY_COUNTER)
4649                 nitems = counter_u64_fetch(zone->uz_allocs);
4650         CPU_FOREACH(i)
4651                 nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs);
4652
4653         return (nitems);
4654 }
4655
4656 static uint64_t
4657 uma_zone_get_frees(uma_zone_t zone)
4658 {
4659         uint64_t nitems;
4660         u_int i;
4661
4662         nitems = 0;
4663         if (zone->uz_frees != EARLY_COUNTER)
4664                 nitems = counter_u64_fetch(zone->uz_frees);
4665         CPU_FOREACH(i)
4666                 nitems += atomic_load_64(&zone->uz_cpu[i].uc_frees);
4667
4668         return (nitems);
4669 }
4670
4671 #ifdef INVARIANTS
4672 /* Used only for KEG_ASSERT_COLD(). */
4673 static uint64_t
4674 uma_keg_get_allocs(uma_keg_t keg)
4675 {
4676         uma_zone_t z;
4677         uint64_t nitems;
4678
4679         nitems = 0;
4680         LIST_FOREACH(z, &keg->uk_zones, uz_link)
4681                 nitems += uma_zone_get_allocs(z);
4682
4683         return (nitems);
4684 }
4685 #endif
4686
4687 /* See uma.h */
4688 void
4689 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
4690 {
4691         uma_keg_t keg;
4692
4693         KEG_GET(zone, keg);
4694         KEG_ASSERT_COLD(keg);
4695         keg->uk_init = uminit;
4696 }
4697
4698 /* See uma.h */
4699 void
4700 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
4701 {
4702         uma_keg_t keg;
4703
4704         KEG_GET(zone, keg);
4705         KEG_ASSERT_COLD(keg);
4706         keg->uk_fini = fini;
4707 }
4708
4709 /* See uma.h */
4710 void
4711 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
4712 {
4713
4714         ZONE_ASSERT_COLD(zone);
4715         zone->uz_init = zinit;
4716 }
4717
4718 /* See uma.h */
4719 void
4720 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
4721 {
4722
4723         ZONE_ASSERT_COLD(zone);
4724         zone->uz_fini = zfini;
4725 }
4726
4727 /* See uma.h */
4728 void
4729 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
4730 {
4731         uma_keg_t keg;
4732
4733         KEG_GET(zone, keg);
4734         KEG_ASSERT_COLD(keg);
4735         keg->uk_freef = freef;
4736 }
4737
4738 /* See uma.h */
4739 void
4740 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
4741 {
4742         uma_keg_t keg;
4743
4744         KEG_GET(zone, keg);
4745         KEG_ASSERT_COLD(keg);
4746         keg->uk_allocf = allocf;
4747 }
4748
4749 /* See uma.h */
4750 void
4751 uma_zone_set_smr(uma_zone_t zone, smr_t smr)
4752 {
4753
4754         ZONE_ASSERT_COLD(zone);
4755
4756         KASSERT(smr != NULL, ("Got NULL smr"));
4757         KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4758             ("zone %p (%s) already uses SMR", zone, zone->uz_name));
4759         zone->uz_flags |= UMA_ZONE_SMR;
4760         zone->uz_smr = smr;
4761         zone_update_caches(zone);
4762 }
4763
4764 smr_t
4765 uma_zone_get_smr(uma_zone_t zone)
4766 {
4767
4768         return (zone->uz_smr);
4769 }
4770
4771 /* See uma.h */
4772 void
4773 uma_zone_reserve(uma_zone_t zone, int items)
4774 {
4775         uma_keg_t keg;
4776
4777         KEG_GET(zone, keg);
4778         KEG_ASSERT_COLD(keg);
4779         keg->uk_reserve = items;
4780 }
4781
4782 /* See uma.h */
4783 int
4784 uma_zone_reserve_kva(uma_zone_t zone, int count)
4785 {
4786         uma_keg_t keg;
4787         vm_offset_t kva;
4788         u_int pages;
4789
4790         KEG_GET(zone, keg);
4791         KEG_ASSERT_COLD(keg);
4792         ZONE_ASSERT_COLD(zone);
4793
4794         pages = howmany(count, keg->uk_ipers) * keg->uk_ppera;
4795
4796 #ifdef UMA_MD_SMALL_ALLOC
4797         if (keg->uk_ppera > 1) {
4798 #else
4799         if (1) {
4800 #endif
4801                 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
4802                 if (kva == 0)
4803                         return (0);
4804         } else
4805                 kva = 0;
4806
4807         MPASS(keg->uk_kva == 0);
4808         keg->uk_kva = kva;
4809         keg->uk_offset = 0;
4810         zone->uz_max_items = pages * keg->uk_ipers;
4811 #ifdef UMA_MD_SMALL_ALLOC
4812         keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
4813 #else
4814         keg->uk_allocf = noobj_alloc;
4815 #endif
4816         keg->uk_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4817         zone->uz_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4818         zone_update_caches(zone);
4819
4820         return (1);
4821 }
4822
4823 /* See uma.h */
4824 void
4825 uma_prealloc(uma_zone_t zone, int items)
4826 {
4827         struct vm_domainset_iter di;
4828         uma_domain_t dom;
4829         uma_slab_t slab;
4830         uma_keg_t keg;
4831         int aflags, domain, slabs;
4832
4833         KEG_GET(zone, keg);
4834         slabs = howmany(items, keg->uk_ipers);
4835         while (slabs-- > 0) {
4836                 aflags = M_NOWAIT;
4837                 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
4838                     &aflags);
4839                 for (;;) {
4840                         slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
4841                             aflags);
4842                         if (slab != NULL) {
4843                                 dom = &keg->uk_domain[slab->us_domain];
4844                                 /*
4845                                  * keg_alloc_slab() always returns a slab on the
4846                                  * partial list.
4847                                  */
4848                                 LIST_REMOVE(slab, us_link);
4849                                 LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
4850                                     us_link);
4851                                 dom->ud_free_slabs++;
4852                                 KEG_UNLOCK(keg, slab->us_domain);
4853                                 break;
4854                         }
4855                         if (vm_domainset_iter_policy(&di, &domain) != 0)
4856                                 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
4857                 }
4858         }
4859 }
4860
4861 /*
4862  * Returns a snapshot of memory consumption in bytes.
4863  */
4864 size_t
4865 uma_zone_memory(uma_zone_t zone)
4866 {
4867         size_t sz;
4868         int i;
4869
4870         sz = 0;
4871         if (zone->uz_flags & UMA_ZFLAG_CACHE) {
4872                 for (i = 0; i < vm_ndomains; i++)
4873                         sz += ZDOM_GET(zone, i)->uzd_nitems;
4874                 return (sz * zone->uz_size);
4875         }
4876         for (i = 0; i < vm_ndomains; i++)
4877                 sz += zone->uz_keg->uk_domain[i].ud_pages;
4878
4879         return (sz * PAGE_SIZE);
4880 }
4881
4882 /* See uma.h */
4883 void
4884 uma_reclaim(int req)
4885 {
4886
4887         CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
4888         sx_xlock(&uma_reclaim_lock);
4889         bucket_enable();
4890
4891         switch (req) {
4892         case UMA_RECLAIM_TRIM:
4893                 zone_foreach(zone_trim, NULL);
4894                 break;
4895         case UMA_RECLAIM_DRAIN:
4896         case UMA_RECLAIM_DRAIN_CPU:
4897                 zone_foreach(zone_drain, NULL);
4898                 if (req == UMA_RECLAIM_DRAIN_CPU) {
4899                         pcpu_cache_drain_safe(NULL);
4900                         zone_foreach(zone_drain, NULL);
4901                 }
4902                 break;
4903         default:
4904                 panic("unhandled reclamation request %d", req);
4905         }
4906
4907         /*
4908          * Some slabs may have been freed but this zone will be visited early
4909          * we visit again so that we can free pages that are empty once other
4910          * zones are drained.  We have to do the same for buckets.
4911          */
4912         zone_drain(slabzones[0], NULL);
4913         zone_drain(slabzones[1], NULL);
4914         bucket_zone_drain();
4915         sx_xunlock(&uma_reclaim_lock);
4916 }
4917
4918 static volatile int uma_reclaim_needed;
4919
4920 void
4921 uma_reclaim_wakeup(void)
4922 {
4923
4924         if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
4925                 wakeup(uma_reclaim);
4926 }
4927
4928 void
4929 uma_reclaim_worker(void *arg __unused)
4930 {
4931
4932         for (;;) {
4933                 sx_xlock(&uma_reclaim_lock);
4934                 while (atomic_load_int(&uma_reclaim_needed) == 0)
4935                         sx_sleep(uma_reclaim, &uma_reclaim_lock, PVM, "umarcl",
4936                             hz);
4937                 sx_xunlock(&uma_reclaim_lock);
4938                 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
4939                 uma_reclaim(UMA_RECLAIM_DRAIN_CPU);
4940                 atomic_store_int(&uma_reclaim_needed, 0);
4941                 /* Don't fire more than once per-second. */
4942                 pause("umarclslp", hz);
4943         }
4944 }
4945
4946 /* See uma.h */
4947 void
4948 uma_zone_reclaim(uma_zone_t zone, int req)
4949 {
4950
4951         switch (req) {
4952         case UMA_RECLAIM_TRIM:
4953                 zone_trim(zone, NULL);
4954                 break;
4955         case UMA_RECLAIM_DRAIN:
4956                 zone_drain(zone, NULL);
4957                 break;
4958         case UMA_RECLAIM_DRAIN_CPU:
4959                 pcpu_cache_drain_safe(zone);
4960                 zone_drain(zone, NULL);
4961                 break;
4962         default:
4963                 panic("unhandled reclamation request %d", req);
4964         }
4965 }
4966
4967 /* See uma.h */
4968 int
4969 uma_zone_exhausted(uma_zone_t zone)
4970 {
4971
4972         return (atomic_load_32(&zone->uz_sleepers) > 0);
4973 }
4974
4975 unsigned long
4976 uma_limit(void)
4977 {
4978
4979         return (uma_kmem_limit);
4980 }
4981
4982 void
4983 uma_set_limit(unsigned long limit)
4984 {
4985
4986         uma_kmem_limit = limit;
4987 }
4988
4989 unsigned long
4990 uma_size(void)
4991 {
4992
4993         return (atomic_load_long(&uma_kmem_total));
4994 }
4995
4996 long
4997 uma_avail(void)
4998 {
4999
5000         return (uma_kmem_limit - uma_size());
5001 }
5002
5003 #ifdef DDB
5004 /*
5005  * Generate statistics across both the zone and its per-cpu cache's.  Return
5006  * desired statistics if the pointer is non-NULL for that statistic.
5007  *
5008  * Note: does not update the zone statistics, as it can't safely clear the
5009  * per-CPU cache statistic.
5010  *
5011  */
5012 static void
5013 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
5014     uint64_t *freesp, uint64_t *sleepsp, uint64_t *xdomainp)
5015 {
5016         uma_cache_t cache;
5017         uint64_t allocs, frees, sleeps, xdomain;
5018         int cachefree, cpu;
5019
5020         allocs = frees = sleeps = xdomain = 0;
5021         cachefree = 0;
5022         CPU_FOREACH(cpu) {
5023                 cache = &z->uz_cpu[cpu];
5024                 cachefree += cache->uc_allocbucket.ucb_cnt;
5025                 cachefree += cache->uc_freebucket.ucb_cnt;
5026                 xdomain += cache->uc_crossbucket.ucb_cnt;
5027                 cachefree += cache->uc_crossbucket.ucb_cnt;
5028                 allocs += cache->uc_allocs;
5029                 frees += cache->uc_frees;
5030         }
5031         allocs += counter_u64_fetch(z->uz_allocs);
5032         frees += counter_u64_fetch(z->uz_frees);
5033         xdomain += counter_u64_fetch(z->uz_xdomain);
5034         sleeps += z->uz_sleeps;
5035         if (cachefreep != NULL)
5036                 *cachefreep = cachefree;
5037         if (allocsp != NULL)
5038                 *allocsp = allocs;
5039         if (freesp != NULL)
5040                 *freesp = frees;
5041         if (sleepsp != NULL)
5042                 *sleepsp = sleeps;
5043         if (xdomainp != NULL)
5044                 *xdomainp = xdomain;
5045 }
5046 #endif /* DDB */
5047
5048 static int
5049 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
5050 {
5051         uma_keg_t kz;
5052         uma_zone_t z;
5053         int count;
5054
5055         count = 0;
5056         rw_rlock(&uma_rwlock);
5057         LIST_FOREACH(kz, &uma_kegs, uk_link) {
5058                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
5059                         count++;
5060         }
5061         LIST_FOREACH(z, &uma_cachezones, uz_link)
5062                 count++;
5063
5064         rw_runlock(&uma_rwlock);
5065         return (sysctl_handle_int(oidp, &count, 0, req));
5066 }
5067
5068 static void
5069 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
5070     struct uma_percpu_stat *ups, bool internal)
5071 {
5072         uma_zone_domain_t zdom;
5073         uma_cache_t cache;
5074         int i;
5075
5076         for (i = 0; i < vm_ndomains; i++) {
5077                 zdom = ZDOM_GET(z, i);
5078                 uth->uth_zone_free += zdom->uzd_nitems;
5079         }
5080         uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
5081         uth->uth_frees = counter_u64_fetch(z->uz_frees);
5082         uth->uth_fails = counter_u64_fetch(z->uz_fails);
5083         uth->uth_xdomain = counter_u64_fetch(z->uz_xdomain);
5084         uth->uth_sleeps = z->uz_sleeps;
5085
5086         for (i = 0; i < mp_maxid + 1; i++) {
5087                 bzero(&ups[i], sizeof(*ups));
5088                 if (internal || CPU_ABSENT(i))
5089                         continue;
5090                 cache = &z->uz_cpu[i];
5091                 ups[i].ups_cache_free += cache->uc_allocbucket.ucb_cnt;
5092                 ups[i].ups_cache_free += cache->uc_freebucket.ucb_cnt;
5093                 ups[i].ups_cache_free += cache->uc_crossbucket.ucb_cnt;
5094                 ups[i].ups_allocs = cache->uc_allocs;
5095                 ups[i].ups_frees = cache->uc_frees;
5096         }
5097 }
5098
5099 static int
5100 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
5101 {
5102         struct uma_stream_header ush;
5103         struct uma_type_header uth;
5104         struct uma_percpu_stat *ups;
5105         struct sbuf sbuf;
5106         uma_keg_t kz;
5107         uma_zone_t z;
5108         uint64_t items;
5109         uint32_t kfree, pages;
5110         int count, error, i;
5111
5112         error = sysctl_wire_old_buffer(req, 0);
5113         if (error != 0)
5114                 return (error);
5115         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
5116         sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
5117         ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
5118
5119         count = 0;
5120         rw_rlock(&uma_rwlock);
5121         LIST_FOREACH(kz, &uma_kegs, uk_link) {
5122                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
5123                         count++;
5124         }
5125
5126         LIST_FOREACH(z, &uma_cachezones, uz_link)
5127                 count++;
5128
5129         /*
5130          * Insert stream header.
5131          */
5132         bzero(&ush, sizeof(ush));
5133         ush.ush_version = UMA_STREAM_VERSION;
5134         ush.ush_maxcpus = (mp_maxid + 1);
5135         ush.ush_count = count;
5136         (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
5137
5138         LIST_FOREACH(kz, &uma_kegs, uk_link) {
5139                 kfree = pages = 0;
5140                 for (i = 0; i < vm_ndomains; i++) {
5141                         kfree += kz->uk_domain[i].ud_free_items;
5142                         pages += kz->uk_domain[i].ud_pages;
5143                 }
5144                 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5145                         bzero(&uth, sizeof(uth));
5146                         strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5147                         uth.uth_align = kz->uk_align;
5148                         uth.uth_size = kz->uk_size;
5149                         uth.uth_rsize = kz->uk_rsize;
5150                         if (z->uz_max_items > 0) {
5151                                 items = UZ_ITEMS_COUNT(z->uz_items);
5152                                 uth.uth_pages = (items / kz->uk_ipers) *
5153                                         kz->uk_ppera;
5154                         } else
5155                                 uth.uth_pages = pages;
5156                         uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
5157                             kz->uk_ppera;
5158                         uth.uth_limit = z->uz_max_items;
5159                         uth.uth_keg_free = kfree;
5160
5161                         /*
5162                          * A zone is secondary is it is not the first entry
5163                          * on the keg's zone list.
5164                          */
5165                         if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
5166                             (LIST_FIRST(&kz->uk_zones) != z))
5167                                 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
5168                         uma_vm_zone_stats(&uth, z, &sbuf, ups,
5169                             kz->uk_flags & UMA_ZFLAG_INTERNAL);
5170                         (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5171                         for (i = 0; i < mp_maxid + 1; i++)
5172                                 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5173                 }
5174         }
5175         LIST_FOREACH(z, &uma_cachezones, uz_link) {
5176                 bzero(&uth, sizeof(uth));
5177                 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5178                 uth.uth_size = z->uz_size;
5179                 uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
5180                 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5181                 for (i = 0; i < mp_maxid + 1; i++)
5182                         (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5183         }
5184
5185         rw_runlock(&uma_rwlock);
5186         error = sbuf_finish(&sbuf);
5187         sbuf_delete(&sbuf);
5188         free(ups, M_TEMP);
5189         return (error);
5190 }
5191
5192 int
5193 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
5194 {
5195         uma_zone_t zone = *(uma_zone_t *)arg1;
5196         int error, max;
5197
5198         max = uma_zone_get_max(zone);
5199         error = sysctl_handle_int(oidp, &max, 0, req);
5200         if (error || !req->newptr)
5201                 return (error);
5202
5203         uma_zone_set_max(zone, max);
5204
5205         return (0);
5206 }
5207
5208 int
5209 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
5210 {
5211         uma_zone_t zone;
5212         int cur;
5213
5214         /*
5215          * Some callers want to add sysctls for global zones that
5216          * may not yet exist so they pass a pointer to a pointer.
5217          */
5218         if (arg2 == 0)
5219                 zone = *(uma_zone_t *)arg1;
5220         else
5221                 zone = arg1;
5222         cur = uma_zone_get_cur(zone);
5223         return (sysctl_handle_int(oidp, &cur, 0, req));
5224 }
5225
5226 static int
5227 sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS)
5228 {
5229         uma_zone_t zone = arg1;
5230         uint64_t cur;
5231
5232         cur = uma_zone_get_allocs(zone);
5233         return (sysctl_handle_64(oidp, &cur, 0, req));
5234 }
5235
5236 static int
5237 sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS)
5238 {
5239         uma_zone_t zone = arg1;
5240         uint64_t cur;
5241
5242         cur = uma_zone_get_frees(zone);
5243         return (sysctl_handle_64(oidp, &cur, 0, req));
5244 }
5245
5246 static int
5247 sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS)
5248 {
5249         struct sbuf sbuf;
5250         uma_zone_t zone = arg1;
5251         int error;
5252
5253         sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
5254         if (zone->uz_flags != 0)
5255                 sbuf_printf(&sbuf, "0x%b", zone->uz_flags, PRINT_UMA_ZFLAGS);
5256         else
5257                 sbuf_printf(&sbuf, "0");
5258         error = sbuf_finish(&sbuf);
5259         sbuf_delete(&sbuf);
5260
5261         return (error);
5262 }
5263
5264 static int
5265 sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS)
5266 {
5267         uma_keg_t keg = arg1;
5268         int avail, effpct, total;
5269
5270         total = keg->uk_ppera * PAGE_SIZE;
5271         if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
5272                 total += slabzone(keg->uk_ipers)->uz_keg->uk_rsize;
5273         /*
5274          * We consider the client's requested size and alignment here, not the
5275          * real size determination uk_rsize, because we also adjust the real
5276          * size for internal implementation reasons (max bitset size).
5277          */
5278         avail = keg->uk_ipers * roundup2(keg->uk_size, keg->uk_align + 1);
5279         if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
5280                 avail *= mp_maxid + 1;
5281         effpct = 100 * avail / total;
5282         return (sysctl_handle_int(oidp, &effpct, 0, req));
5283 }
5284
5285 static int
5286 sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS)
5287 {
5288         uma_zone_t zone = arg1;
5289         uint64_t cur;
5290
5291         cur = UZ_ITEMS_COUNT(atomic_load_64(&zone->uz_items));
5292         return (sysctl_handle_64(oidp, &cur, 0, req));
5293 }
5294
5295 #ifdef INVARIANTS
5296 static uma_slab_t
5297 uma_dbg_getslab(uma_zone_t zone, void *item)
5298 {
5299         uma_slab_t slab;
5300         uma_keg_t keg;
5301         uint8_t *mem;
5302
5303         /*
5304          * It is safe to return the slab here even though the
5305          * zone is unlocked because the item's allocation state
5306          * essentially holds a reference.
5307          */
5308         mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
5309         if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5310                 return (NULL);
5311         if (zone->uz_flags & UMA_ZFLAG_VTOSLAB)
5312                 return (vtoslab((vm_offset_t)mem));
5313         keg = zone->uz_keg;
5314         if ((keg->uk_flags & UMA_ZFLAG_HASH) == 0)
5315                 return ((uma_slab_t)(mem + keg->uk_pgoff));
5316         KEG_LOCK(keg, 0);
5317         slab = hash_sfind(&keg->uk_hash, mem);
5318         KEG_UNLOCK(keg, 0);
5319
5320         return (slab);
5321 }
5322
5323 static bool
5324 uma_dbg_zskip(uma_zone_t zone, void *mem)
5325 {
5326
5327         if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5328                 return (true);
5329
5330         return (uma_dbg_kskip(zone->uz_keg, mem));
5331 }
5332
5333 static bool
5334 uma_dbg_kskip(uma_keg_t keg, void *mem)
5335 {
5336         uintptr_t idx;
5337
5338         if (dbg_divisor == 0)
5339                 return (true);
5340
5341         if (dbg_divisor == 1)
5342                 return (false);
5343
5344         idx = (uintptr_t)mem >> PAGE_SHIFT;
5345         if (keg->uk_ipers > 1) {
5346                 idx *= keg->uk_ipers;
5347                 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
5348         }
5349
5350         if ((idx / dbg_divisor) * dbg_divisor != idx) {
5351                 counter_u64_add(uma_skip_cnt, 1);
5352                 return (true);
5353         }
5354         counter_u64_add(uma_dbg_cnt, 1);
5355
5356         return (false);
5357 }
5358
5359 /*
5360  * Set up the slab's freei data such that uma_dbg_free can function.
5361  *
5362  */
5363 static void
5364 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
5365 {
5366         uma_keg_t keg;
5367         int freei;
5368
5369         if (slab == NULL) {
5370                 slab = uma_dbg_getslab(zone, item);
5371                 if (slab == NULL) 
5372                         panic("uma: item %p did not belong to zone %s",
5373                             item, zone->uz_name);
5374         }
5375         keg = zone->uz_keg;
5376         freei = slab_item_index(slab, keg, item);
5377
5378         if (BIT_ISSET(keg->uk_ipers, freei, slab_dbg_bits(slab, keg)))
5379                 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)",
5380                     item, zone, zone->uz_name, slab, freei);
5381         BIT_SET_ATOMIC(keg->uk_ipers, freei, slab_dbg_bits(slab, keg));
5382 }
5383
5384 /*
5385  * Verifies freed addresses.  Checks for alignment, valid slab membership
5386  * and duplicate frees.
5387  *
5388  */
5389 static void
5390 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
5391 {
5392         uma_keg_t keg;
5393         int freei;
5394
5395         if (slab == NULL) {
5396                 slab = uma_dbg_getslab(zone, item);
5397                 if (slab == NULL) 
5398                         panic("uma: Freed item %p did not belong to zone %s",
5399                             item, zone->uz_name);
5400         }
5401         keg = zone->uz_keg;
5402         freei = slab_item_index(slab, keg, item);
5403
5404         if (freei >= keg->uk_ipers)
5405                 panic("Invalid free of %p from zone %p(%s) slab %p(%d)",
5406                     item, zone, zone->uz_name, slab, freei);
5407
5408         if (slab_item(slab, keg, freei) != item)
5409                 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)",
5410                     item, zone, zone->uz_name, slab, freei);
5411
5412         if (!BIT_ISSET(keg->uk_ipers, freei, slab_dbg_bits(slab, keg)))
5413                 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)",
5414                     item, zone, zone->uz_name, slab, freei);
5415
5416         BIT_CLR_ATOMIC(keg->uk_ipers, freei, slab_dbg_bits(slab, keg));
5417 }
5418 #endif /* INVARIANTS */
5419
5420 #ifdef DDB
5421 static int64_t
5422 get_uma_stats(uma_keg_t kz, uma_zone_t z, uint64_t *allocs, uint64_t *used,
5423     uint64_t *sleeps, long *cachefree, uint64_t *xdomain)
5424 {
5425         uint64_t frees;
5426         int i;
5427
5428         if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
5429                 *allocs = counter_u64_fetch(z->uz_allocs);
5430                 frees = counter_u64_fetch(z->uz_frees);
5431                 *sleeps = z->uz_sleeps;
5432                 *cachefree = 0;
5433                 *xdomain = 0;
5434         } else
5435                 uma_zone_sumstat(z, cachefree, allocs, &frees, sleeps,
5436                     xdomain);
5437         for (i = 0; i < vm_ndomains; i++) {
5438                 *cachefree += ZDOM_GET(z, i)->uzd_nitems;
5439                 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
5440                     (LIST_FIRST(&kz->uk_zones) != z)))
5441                         *cachefree += kz->uk_domain[i].ud_free_items;
5442         }
5443         *used = *allocs - frees;
5444         return (((int64_t)*used + *cachefree) * kz->uk_size);
5445 }
5446
5447 DB_SHOW_COMMAND(uma, db_show_uma)
5448 {
5449         const char *fmt_hdr, *fmt_entry;
5450         uma_keg_t kz;
5451         uma_zone_t z;
5452         uint64_t allocs, used, sleeps, xdomain;
5453         long cachefree;
5454         /* variables for sorting */
5455         uma_keg_t cur_keg;
5456         uma_zone_t cur_zone, last_zone;
5457         int64_t cur_size, last_size, size;
5458         int ties;
5459
5460         /* /i option produces machine-parseable CSV output */
5461         if (modif[0] == 'i') {
5462                 fmt_hdr = "%s,%s,%s,%s,%s,%s,%s,%s,%s\n";
5463                 fmt_entry = "\"%s\",%ju,%jd,%ld,%ju,%ju,%u,%jd,%ju\n";
5464         } else {
5465                 fmt_hdr = "%18s %6s %7s %7s %11s %7s %7s %10s %8s\n";
5466                 fmt_entry = "%18s %6ju %7jd %7ld %11ju %7ju %7u %10jd %8ju\n";
5467         }
5468
5469         db_printf(fmt_hdr, "Zone", "Size", "Used", "Free", "Requests",
5470             "Sleeps", "Bucket", "Total Mem", "XFree");
5471
5472         /* Sort the zones with largest size first. */
5473         last_zone = NULL;
5474         last_size = INT64_MAX;
5475         for (;;) {
5476                 cur_zone = NULL;
5477                 cur_size = -1;
5478                 ties = 0;
5479                 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5480                         LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5481                                 /*
5482                                  * In the case of size ties, print out zones
5483                                  * in the order they are encountered.  That is,
5484                                  * when we encounter the most recently output
5485                                  * zone, we have already printed all preceding
5486                                  * ties, and we must print all following ties.
5487                                  */
5488                                 if (z == last_zone) {
5489                                         ties = 1;
5490                                         continue;
5491                                 }
5492                                 size = get_uma_stats(kz, z, &allocs, &used,
5493                                     &sleeps, &cachefree, &xdomain);
5494                                 if (size > cur_size && size < last_size + ties)
5495                                 {
5496                                         cur_size = size;
5497                                         cur_zone = z;
5498                                         cur_keg = kz;
5499                                 }
5500                         }
5501                 }
5502                 if (cur_zone == NULL)
5503                         break;
5504
5505                 size = get_uma_stats(cur_keg, cur_zone, &allocs, &used,
5506                     &sleeps, &cachefree, &xdomain);
5507                 db_printf(fmt_entry, cur_zone->uz_name,
5508                     (uintmax_t)cur_keg->uk_size, (intmax_t)used, cachefree,
5509                     (uintmax_t)allocs, (uintmax_t)sleeps,
5510                     (unsigned)cur_zone->uz_bucket_size, (intmax_t)size,
5511                     xdomain);
5512
5513                 if (db_pager_quit)
5514                         return;
5515                 last_zone = cur_zone;
5516                 last_size = cur_size;
5517         }
5518 }
5519
5520 DB_SHOW_COMMAND(umacache, db_show_umacache)
5521 {
5522         uma_zone_t z;
5523         uint64_t allocs, frees;
5524         long cachefree;
5525         int i;
5526
5527         db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
5528             "Requests", "Bucket");
5529         LIST_FOREACH(z, &uma_cachezones, uz_link) {
5530                 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL, NULL);
5531                 for (i = 0; i < vm_ndomains; i++)
5532                         cachefree += ZDOM_GET(z, i)->uzd_nitems;
5533                 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
5534                     z->uz_name, (uintmax_t)z->uz_size,
5535                     (intmax_t)(allocs - frees), cachefree,
5536                     (uintmax_t)allocs, z->uz_bucket_size);
5537                 if (db_pager_quit)
5538                         return;
5539         }
5540 }
5541 #endif  /* DDB */