]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/uma_core.c
uma: Avoid depleting keg reserves when filling a bucket
[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 /*
1419  * Frees pages from a keg back to the system.  This is done on demand from
1420  * the pageout daemon.
1421  *
1422  * Returns nothing.
1423  */
1424 static void
1425 keg_drain(uma_keg_t keg)
1426 {
1427         struct slabhead freeslabs;
1428         uma_domain_t dom;
1429         uma_slab_t slab, tmp;
1430         int i, n;
1431
1432         if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
1433                 return;
1434
1435         for (i = 0; i < vm_ndomains; i++) {
1436                 CTR4(KTR_UMA, "keg_drain %s(%p) domain %d free items: %u",
1437                     keg->uk_name, keg, i, dom->ud_free_items);
1438                 dom = &keg->uk_domain[i];
1439                 LIST_INIT(&freeslabs);
1440
1441                 KEG_LOCK(keg, i);
1442                 if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0) {
1443                         LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
1444                                 UMA_HASH_REMOVE(&keg->uk_hash, slab);
1445                 }
1446                 n = dom->ud_free_slabs;
1447                 LIST_SWAP(&freeslabs, &dom->ud_free_slab, uma_slab, us_link);
1448                 dom->ud_free_slabs = 0;
1449                 dom->ud_free_items -= n * keg->uk_ipers;
1450                 dom->ud_pages -= n * keg->uk_ppera;
1451                 KEG_UNLOCK(keg, i);
1452
1453                 LIST_FOREACH_SAFE(slab, &freeslabs, us_link, tmp)
1454                         keg_free_slab(keg, slab, keg->uk_ipers);
1455         }
1456 }
1457
1458 static void
1459 zone_reclaim(uma_zone_t zone, int waitok, bool drain)
1460 {
1461
1462         /*
1463          * Set draining to interlock with zone_dtor() so we can release our
1464          * locks as we go.  Only dtor() should do a WAITOK call since it
1465          * is the only call that knows the structure will still be available
1466          * when it wakes up.
1467          */
1468         ZONE_LOCK(zone);
1469         while (zone->uz_flags & UMA_ZFLAG_RECLAIMING) {
1470                 if (waitok == M_NOWAIT)
1471                         goto out;
1472                 msleep(zone, &ZDOM_GET(zone, 0)->uzd_lock, PVM, "zonedrain",
1473                     1);
1474         }
1475         zone->uz_flags |= UMA_ZFLAG_RECLAIMING;
1476         ZONE_UNLOCK(zone);
1477         bucket_cache_reclaim(zone, drain);
1478
1479         /*
1480          * The DRAINING flag protects us from being freed while
1481          * we're running.  Normally the uma_rwlock would protect us but we
1482          * must be able to release and acquire the right lock for each keg.
1483          */
1484         if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0)
1485                 keg_drain(zone->uz_keg);
1486         ZONE_LOCK(zone);
1487         zone->uz_flags &= ~UMA_ZFLAG_RECLAIMING;
1488         wakeup(zone);
1489 out:
1490         ZONE_UNLOCK(zone);
1491 }
1492
1493 static void
1494 zone_drain(uma_zone_t zone, void *unused)
1495 {
1496
1497         zone_reclaim(zone, M_NOWAIT, true);
1498 }
1499
1500 static void
1501 zone_trim(uma_zone_t zone, void *unused)
1502 {
1503
1504         zone_reclaim(zone, M_NOWAIT, false);
1505 }
1506
1507 /*
1508  * Allocate a new slab for a keg and inserts it into the partial slab list.
1509  * The keg should be unlocked on entry.  If the allocation succeeds it will
1510  * be locked on return.
1511  *
1512  * Arguments:
1513  *      flags   Wait flags for the item initialization routine
1514  *      aflags  Wait flags for the slab allocation
1515  *
1516  * Returns:
1517  *      The slab that was allocated or NULL if there is no memory and the
1518  *      caller specified M_NOWAIT.
1519  */
1520 static uma_slab_t
1521 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1522     int aflags)
1523 {
1524         uma_domain_t dom;
1525         uma_alloc allocf;
1526         uma_slab_t slab;
1527         unsigned long size;
1528         uint8_t *mem;
1529         uint8_t sflags;
1530         int i;
1531
1532         KASSERT(domain >= 0 && domain < vm_ndomains,
1533             ("keg_alloc_slab: domain %d out of range", domain));
1534
1535         allocf = keg->uk_allocf;
1536         slab = NULL;
1537         mem = NULL;
1538         if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
1539                 uma_hash_slab_t hslab;
1540                 hslab = zone_alloc_item(slabzone(keg->uk_ipers), NULL,
1541                     domain, aflags);
1542                 if (hslab == NULL)
1543                         goto fail;
1544                 slab = &hslab->uhs_slab;
1545         }
1546
1547         /*
1548          * This reproduces the old vm_zone behavior of zero filling pages the
1549          * first time they are added to a zone.
1550          *
1551          * Malloced items are zeroed in uma_zalloc.
1552          */
1553
1554         if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1555                 aflags |= M_ZERO;
1556         else
1557                 aflags &= ~M_ZERO;
1558
1559         if (keg->uk_flags & UMA_ZONE_NODUMP)
1560                 aflags |= M_NODUMP;
1561
1562         /* zone is passed for legacy reasons. */
1563         size = keg->uk_ppera * PAGE_SIZE;
1564         mem = allocf(zone, size, domain, &sflags, aflags);
1565         if (mem == NULL) {
1566                 if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
1567                         zone_free_item(slabzone(keg->uk_ipers),
1568                             slab_tohashslab(slab), NULL, SKIP_NONE);
1569                 goto fail;
1570         }
1571         uma_total_inc(size);
1572
1573         /* For HASH zones all pages go to the same uma_domain. */
1574         if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
1575                 domain = 0;
1576
1577         /* Point the slab into the allocated memory */
1578         if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE))
1579                 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1580         else
1581                 slab_tohashslab(slab)->uhs_data = mem;
1582
1583         if (keg->uk_flags & UMA_ZFLAG_VTOSLAB)
1584                 for (i = 0; i < keg->uk_ppera; i++)
1585                         vsetzoneslab((vm_offset_t)mem + (i * PAGE_SIZE),
1586                             zone, slab);
1587
1588         slab->us_freecount = keg->uk_ipers;
1589         slab->us_flags = sflags;
1590         slab->us_domain = domain;
1591
1592         BIT_FILL(keg->uk_ipers, &slab->us_free);
1593 #ifdef INVARIANTS
1594         BIT_ZERO(keg->uk_ipers, slab_dbg_bits(slab, keg));
1595 #endif
1596
1597         if (keg->uk_init != NULL) {
1598                 for (i = 0; i < keg->uk_ipers; i++)
1599                         if (keg->uk_init(slab_item(slab, keg, i),
1600                             keg->uk_size, flags) != 0)
1601                                 break;
1602                 if (i != keg->uk_ipers) {
1603                         keg_free_slab(keg, slab, i);
1604                         goto fail;
1605                 }
1606         }
1607         KEG_LOCK(keg, domain);
1608
1609         CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1610             slab, keg->uk_name, keg);
1611
1612         if (keg->uk_flags & UMA_ZFLAG_HASH)
1613                 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1614
1615         /*
1616          * If we got a slab here it's safe to mark it partially used
1617          * and return.  We assume that the caller is going to remove
1618          * at least one item.
1619          */
1620         dom = &keg->uk_domain[domain];
1621         LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
1622         dom->ud_pages += keg->uk_ppera;
1623         dom->ud_free_items += keg->uk_ipers;
1624
1625         return (slab);
1626
1627 fail:
1628         return (NULL);
1629 }
1630
1631 /*
1632  * This function is intended to be used early on in place of page_alloc() so
1633  * that we may use the boot time page cache to satisfy allocations before
1634  * the VM is ready.
1635  */
1636 static void *
1637 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1638     int wait)
1639 {
1640         vm_paddr_t pa;
1641         vm_page_t m;
1642         void *mem;
1643         int pages;
1644         int i;
1645
1646         pages = howmany(bytes, PAGE_SIZE);
1647         KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1648
1649         *pflag = UMA_SLAB_BOOT;
1650         m = vm_page_alloc_contig_domain(NULL, 0, domain,
1651             malloc2vm_flags(wait) | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED, pages, 
1652             (vm_paddr_t)0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT);
1653         if (m == NULL)
1654                 return (NULL);
1655
1656         pa = VM_PAGE_TO_PHYS(m);
1657         for (i = 0; i < pages; i++, pa += PAGE_SIZE) {
1658 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1659     defined(__riscv) || defined(__powerpc64__)
1660                 if ((wait & M_NODUMP) == 0)
1661                         dump_add_page(pa);
1662 #endif
1663         }
1664         /* Allocate KVA and indirectly advance bootmem. */
1665         mem = (void *)pmap_map(&bootmem, m->phys_addr,
1666             m->phys_addr + (pages * PAGE_SIZE), VM_PROT_READ | VM_PROT_WRITE);
1667         if ((wait & M_ZERO) != 0)
1668                 bzero(mem, pages * PAGE_SIZE);
1669
1670         return (mem);
1671 }
1672
1673 static void
1674 startup_free(void *mem, vm_size_t bytes)
1675 {
1676         vm_offset_t va;
1677         vm_page_t m;
1678
1679         va = (vm_offset_t)mem;
1680         m = PHYS_TO_VM_PAGE(pmap_kextract(va));
1681         pmap_remove(kernel_pmap, va, va + bytes);
1682         for (; bytes != 0; bytes -= PAGE_SIZE, m++) {
1683 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1684     defined(__riscv) || defined(__powerpc64__)
1685                 dump_drop_page(VM_PAGE_TO_PHYS(m));
1686 #endif
1687                 vm_page_unwire_noq(m);
1688                 vm_page_free(m);
1689         }
1690 }
1691
1692 /*
1693  * Allocates a number of pages from the system
1694  *
1695  * Arguments:
1696  *      bytes  The number of bytes requested
1697  *      wait  Shall we wait?
1698  *
1699  * Returns:
1700  *      A pointer to the alloced memory or possibly
1701  *      NULL if M_NOWAIT is set.
1702  */
1703 static void *
1704 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1705     int wait)
1706 {
1707         void *p;        /* Returned page */
1708
1709         *pflag = UMA_SLAB_KERNEL;
1710         p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1711
1712         return (p);
1713 }
1714
1715 static void *
1716 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1717     int wait)
1718 {
1719         struct pglist alloctail;
1720         vm_offset_t addr, zkva;
1721         int cpu, flags;
1722         vm_page_t p, p_next;
1723 #ifdef NUMA
1724         struct pcpu *pc;
1725 #endif
1726
1727         MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1728
1729         TAILQ_INIT(&alloctail);
1730         flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1731             malloc2vm_flags(wait);
1732         *pflag = UMA_SLAB_KERNEL;
1733         for (cpu = 0; cpu <= mp_maxid; cpu++) {
1734                 if (CPU_ABSENT(cpu)) {
1735                         p = vm_page_alloc(NULL, 0, flags);
1736                 } else {
1737 #ifndef NUMA
1738                         p = vm_page_alloc(NULL, 0, flags);
1739 #else
1740                         pc = pcpu_find(cpu);
1741                         if (__predict_false(VM_DOMAIN_EMPTY(pc->pc_domain)))
1742                                 p = NULL;
1743                         else
1744                                 p = vm_page_alloc_domain(NULL, 0,
1745                                     pc->pc_domain, flags);
1746                         if (__predict_false(p == NULL))
1747                                 p = vm_page_alloc(NULL, 0, flags);
1748 #endif
1749                 }
1750                 if (__predict_false(p == NULL))
1751                         goto fail;
1752                 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1753         }
1754         if ((addr = kva_alloc(bytes)) == 0)
1755                 goto fail;
1756         zkva = addr;
1757         TAILQ_FOREACH(p, &alloctail, listq) {
1758                 pmap_qenter(zkva, &p, 1);
1759                 zkva += PAGE_SIZE;
1760         }
1761         return ((void*)addr);
1762 fail:
1763         TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1764                 vm_page_unwire_noq(p);
1765                 vm_page_free(p);
1766         }
1767         return (NULL);
1768 }
1769
1770 /*
1771  * Allocates a number of pages from within an object
1772  *
1773  * Arguments:
1774  *      bytes  The number of bytes requested
1775  *      wait   Shall we wait?
1776  *
1777  * Returns:
1778  *      A pointer to the alloced memory or possibly
1779  *      NULL if M_NOWAIT is set.
1780  */
1781 static void *
1782 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1783     int wait)
1784 {
1785         TAILQ_HEAD(, vm_page) alloctail;
1786         u_long npages;
1787         vm_offset_t retkva, zkva;
1788         vm_page_t p, p_next;
1789         uma_keg_t keg;
1790
1791         TAILQ_INIT(&alloctail);
1792         keg = zone->uz_keg;
1793
1794         npages = howmany(bytes, PAGE_SIZE);
1795         while (npages > 0) {
1796                 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1797                     VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1798                     ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1799                     VM_ALLOC_NOWAIT));
1800                 if (p != NULL) {
1801                         /*
1802                          * Since the page does not belong to an object, its
1803                          * listq is unused.
1804                          */
1805                         TAILQ_INSERT_TAIL(&alloctail, p, listq);
1806                         npages--;
1807                         continue;
1808                 }
1809                 /*
1810                  * Page allocation failed, free intermediate pages and
1811                  * exit.
1812                  */
1813                 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1814                         vm_page_unwire_noq(p);
1815                         vm_page_free(p); 
1816                 }
1817                 return (NULL);
1818         }
1819         *flags = UMA_SLAB_PRIV;
1820         zkva = keg->uk_kva +
1821             atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1822         retkva = zkva;
1823         TAILQ_FOREACH(p, &alloctail, listq) {
1824                 pmap_qenter(zkva, &p, 1);
1825                 zkva += PAGE_SIZE;
1826         }
1827
1828         return ((void *)retkva);
1829 }
1830
1831 /*
1832  * Allocate physically contiguous pages.
1833  */
1834 static void *
1835 contig_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1836     int wait)
1837 {
1838
1839         *pflag = UMA_SLAB_KERNEL;
1840         return ((void *)kmem_alloc_contig_domainset(DOMAINSET_FIXED(domain),
1841             bytes, wait, 0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT));
1842 }
1843
1844 /*
1845  * Frees a number of pages to the system
1846  *
1847  * Arguments:
1848  *      mem   A pointer to the memory to be freed
1849  *      size  The size of the memory being freed
1850  *      flags The original p->us_flags field
1851  *
1852  * Returns:
1853  *      Nothing
1854  */
1855 static void
1856 page_free(void *mem, vm_size_t size, uint8_t flags)
1857 {
1858
1859         if ((flags & UMA_SLAB_BOOT) != 0) {
1860                 startup_free(mem, size);
1861                 return;
1862         }
1863
1864         KASSERT((flags & UMA_SLAB_KERNEL) != 0,
1865             ("UMA: page_free used with invalid flags %x", flags));
1866
1867         kmem_free((vm_offset_t)mem, size);
1868 }
1869
1870 /*
1871  * Frees pcpu zone allocations
1872  *
1873  * Arguments:
1874  *      mem   A pointer to the memory to be freed
1875  *      size  The size of the memory being freed
1876  *      flags The original p->us_flags field
1877  *
1878  * Returns:
1879  *      Nothing
1880  */
1881 static void
1882 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1883 {
1884         vm_offset_t sva, curva;
1885         vm_paddr_t paddr;
1886         vm_page_t m;
1887
1888         MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1889
1890         if ((flags & UMA_SLAB_BOOT) != 0) {
1891                 startup_free(mem, size);
1892                 return;
1893         }
1894
1895         sva = (vm_offset_t)mem;
1896         for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1897                 paddr = pmap_kextract(curva);
1898                 m = PHYS_TO_VM_PAGE(paddr);
1899                 vm_page_unwire_noq(m);
1900                 vm_page_free(m);
1901         }
1902         pmap_qremove(sva, size >> PAGE_SHIFT);
1903         kva_free(sva, size);
1904 }
1905
1906 /*
1907  * Zero fill initializer
1908  *
1909  * Arguments/Returns follow uma_init specifications
1910  */
1911 static int
1912 zero_init(void *mem, int size, int flags)
1913 {
1914         bzero(mem, size);
1915         return (0);
1916 }
1917
1918 #ifdef INVARIANTS
1919 static struct noslabbits *
1920 slab_dbg_bits(uma_slab_t slab, uma_keg_t keg)
1921 {
1922
1923         return ((void *)((char *)&slab->us_free + BITSET_SIZE(keg->uk_ipers)));
1924 }
1925 #endif
1926
1927 /*
1928  * Actual size of embedded struct slab (!OFFPAGE).
1929  */
1930 static size_t
1931 slab_sizeof(int nitems)
1932 {
1933         size_t s;
1934
1935         s = sizeof(struct uma_slab) + BITSET_SIZE(nitems) * SLAB_BITSETS;
1936         return (roundup(s, UMA_ALIGN_PTR + 1));
1937 }
1938
1939 #define UMA_FIXPT_SHIFT 31
1940 #define UMA_FRAC_FIXPT(n, d)                                            \
1941         ((uint32_t)(((uint64_t)(n) << UMA_FIXPT_SHIFT) / (d)))
1942 #define UMA_FIXPT_PCT(f)                                                \
1943         ((u_int)(((uint64_t)100 * (f)) >> UMA_FIXPT_SHIFT))
1944 #define UMA_PCT_FIXPT(pct)      UMA_FRAC_FIXPT((pct), 100)
1945 #define UMA_MIN_EFF     UMA_PCT_FIXPT(100 - UMA_MAX_WASTE)
1946
1947 /*
1948  * Compute the number of items that will fit in a slab.  If hdr is true, the
1949  * item count may be limited to provide space in the slab for an inline slab
1950  * header.  Otherwise, all slab space will be provided for item storage.
1951  */
1952 static u_int
1953 slab_ipers_hdr(u_int size, u_int rsize, u_int slabsize, bool hdr)
1954 {
1955         u_int ipers;
1956         u_int padpi;
1957
1958         /* The padding between items is not needed after the last item. */
1959         padpi = rsize - size;
1960
1961         if (hdr) {
1962                 /*
1963                  * Start with the maximum item count and remove items until
1964                  * the slab header first alongside the allocatable memory.
1965                  */
1966                 for (ipers = MIN(SLAB_MAX_SETSIZE,
1967                     (slabsize + padpi - slab_sizeof(1)) / rsize);
1968                     ipers > 0 &&
1969                     ipers * rsize - padpi + slab_sizeof(ipers) > slabsize;
1970                     ipers--)
1971                         continue;
1972         } else {
1973                 ipers = MIN((slabsize + padpi) / rsize, SLAB_MAX_SETSIZE);
1974         }
1975
1976         return (ipers);
1977 }
1978
1979 struct keg_layout_result {
1980         u_int format;
1981         u_int slabsize;
1982         u_int ipers;
1983         u_int eff;
1984 };
1985
1986 static void
1987 keg_layout_one(uma_keg_t keg, u_int rsize, u_int slabsize, u_int fmt,
1988     struct keg_layout_result *kl)
1989 {
1990         u_int total;
1991
1992         kl->format = fmt;
1993         kl->slabsize = slabsize;
1994
1995         /* Handle INTERNAL as inline with an extra page. */
1996         if ((fmt & UMA_ZFLAG_INTERNAL) != 0) {
1997                 kl->format &= ~UMA_ZFLAG_INTERNAL;
1998                 kl->slabsize += PAGE_SIZE;
1999         }
2000
2001         kl->ipers = slab_ipers_hdr(keg->uk_size, rsize, kl->slabsize,
2002             (fmt & UMA_ZFLAG_OFFPAGE) == 0);
2003
2004         /* Account for memory used by an offpage slab header. */
2005         total = kl->slabsize;
2006         if ((fmt & UMA_ZFLAG_OFFPAGE) != 0)
2007                 total += slabzone(kl->ipers)->uz_keg->uk_rsize;
2008
2009         kl->eff = UMA_FRAC_FIXPT(kl->ipers * rsize, total);
2010 }
2011
2012 /*
2013  * Determine the format of a uma keg.  This determines where the slab header
2014  * will be placed (inline or offpage) and calculates ipers, rsize, and ppera.
2015  *
2016  * Arguments
2017  *      keg  The zone we should initialize
2018  *
2019  * Returns
2020  *      Nothing
2021  */
2022 static void
2023 keg_layout(uma_keg_t keg)
2024 {
2025         struct keg_layout_result kl = {}, kl_tmp;
2026         u_int fmts[2];
2027         u_int alignsize;
2028         u_int nfmt;
2029         u_int pages;
2030         u_int rsize;
2031         u_int slabsize;
2032         u_int i, j;
2033
2034         KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
2035             (keg->uk_size <= UMA_PCPU_ALLOC_SIZE &&
2036              (keg->uk_flags & UMA_ZONE_CACHESPREAD) == 0),
2037             ("%s: cannot configure for PCPU: keg=%s, size=%u, flags=0x%b",
2038              __func__, keg->uk_name, keg->uk_size, keg->uk_flags,
2039              PRINT_UMA_ZFLAGS));
2040         KASSERT((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) == 0 ||
2041             (keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0,
2042             ("%s: incompatible flags 0x%b", __func__, keg->uk_flags,
2043              PRINT_UMA_ZFLAGS));
2044
2045         alignsize = keg->uk_align + 1;
2046
2047         /*
2048          * Calculate the size of each allocation (rsize) according to
2049          * alignment.  If the requested size is smaller than we have
2050          * allocation bits for we round it up.
2051          */
2052         rsize = MAX(keg->uk_size, UMA_SMALLEST_UNIT);
2053         rsize = roundup2(rsize, alignsize);
2054
2055         if ((keg->uk_flags & UMA_ZONE_CACHESPREAD) != 0) {
2056                 /*
2057                  * We want one item to start on every align boundary in a page.
2058                  * To do this we will span pages.  We will also extend the item
2059                  * by the size of align if it is an even multiple of align.
2060                  * Otherwise, it would fall on the same boundary every time.
2061                  */
2062                 if ((rsize & alignsize) == 0)
2063                         rsize += alignsize;
2064                 slabsize = rsize * (PAGE_SIZE / alignsize);
2065                 slabsize = MIN(slabsize, rsize * SLAB_MAX_SETSIZE);
2066                 slabsize = MIN(slabsize, UMA_CACHESPREAD_MAX_SIZE);
2067                 slabsize = round_page(slabsize);
2068         } else {
2069                 /*
2070                  * Start with a slab size of as many pages as it takes to
2071                  * represent a single item.  We will try to fit as many
2072                  * additional items into the slab as possible.
2073                  */
2074                 slabsize = round_page(keg->uk_size);
2075         }
2076
2077         /* Build a list of all of the available formats for this keg. */
2078         nfmt = 0;
2079
2080         /* Evaluate an inline slab layout. */
2081         if ((keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0)
2082                 fmts[nfmt++] = 0;
2083
2084         /* TODO: vm_page-embedded slab. */
2085
2086         /*
2087          * We can't do OFFPAGE if we're internal or if we've been
2088          * asked to not go to the VM for buckets.  If we do this we
2089          * may end up going to the VM for slabs which we do not want
2090          * to do if we're UMA_ZONE_VM, which clearly forbids it.
2091          * In those cases, evaluate a pseudo-format called INTERNAL
2092          * which has an inline slab header and one extra page to
2093          * guarantee that it fits.
2094          *
2095          * Otherwise, see if using an OFFPAGE slab will improve our
2096          * efficiency.
2097          */
2098         if ((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) != 0)
2099                 fmts[nfmt++] = UMA_ZFLAG_INTERNAL;
2100         else
2101                 fmts[nfmt++] = UMA_ZFLAG_OFFPAGE;
2102
2103         /*
2104          * Choose a slab size and format which satisfy the minimum efficiency.
2105          * Prefer the smallest slab size that meets the constraints.
2106          *
2107          * Start with a minimum slab size, to accommodate CACHESPREAD.  Then,
2108          * for small items (up to PAGE_SIZE), the iteration increment is one
2109          * page; and for large items, the increment is one item.
2110          */
2111         i = (slabsize + rsize - keg->uk_size) / MAX(PAGE_SIZE, rsize);
2112         KASSERT(i >= 1, ("keg %s(%p) flags=0x%b slabsize=%u, rsize=%u, i=%u",
2113             keg->uk_name, keg, keg->uk_flags, PRINT_UMA_ZFLAGS, slabsize,
2114             rsize, i));
2115         for ( ; ; i++) {
2116                 slabsize = (rsize <= PAGE_SIZE) ? ptoa(i) :
2117                     round_page(rsize * (i - 1) + keg->uk_size);
2118
2119                 for (j = 0; j < nfmt; j++) {
2120                         /* Only if we have no viable format yet. */
2121                         if ((fmts[j] & UMA_ZFLAG_INTERNAL) != 0 &&
2122                             kl.ipers > 0)
2123                                 continue;
2124
2125                         keg_layout_one(keg, rsize, slabsize, fmts[j], &kl_tmp);
2126                         if (kl_tmp.eff <= kl.eff)
2127                                 continue;
2128
2129                         kl = kl_tmp;
2130
2131                         CTR6(KTR_UMA, "keg %s layout: format %#x "
2132                             "(ipers %u * rsize %u) / slabsize %#x = %u%% eff",
2133                             keg->uk_name, kl.format, kl.ipers, rsize,
2134                             kl.slabsize, UMA_FIXPT_PCT(kl.eff));
2135
2136                         /* Stop when we reach the minimum efficiency. */
2137                         if (kl.eff >= UMA_MIN_EFF)
2138                                 break;
2139                 }
2140
2141                 if (kl.eff >= UMA_MIN_EFF || !multipage_slabs ||
2142                     slabsize >= SLAB_MAX_SETSIZE * rsize ||
2143                     (keg->uk_flags & (UMA_ZONE_PCPU | UMA_ZONE_CONTIG)) != 0)
2144                         break;
2145         }
2146
2147         pages = atop(kl.slabsize);
2148         if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
2149                 pages *= mp_maxid + 1;
2150
2151         keg->uk_rsize = rsize;
2152         keg->uk_ipers = kl.ipers;
2153         keg->uk_ppera = pages;
2154         keg->uk_flags |= kl.format;
2155
2156         /*
2157          * How do we find the slab header if it is offpage or if not all item
2158          * start addresses are in the same page?  We could solve the latter
2159          * case with vaddr alignment, but we don't.
2160          */
2161         if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0 ||
2162             (keg->uk_ipers - 1) * rsize >= PAGE_SIZE) {
2163                 if ((keg->uk_flags & UMA_ZONE_NOTPAGE) != 0)
2164                         keg->uk_flags |= UMA_ZFLAG_HASH;
2165                 else
2166                         keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2167         }
2168
2169         CTR6(KTR_UMA, "%s: keg=%s, flags=%#x, rsize=%u, ipers=%u, ppera=%u",
2170             __func__, keg->uk_name, keg->uk_flags, rsize, keg->uk_ipers,
2171             pages);
2172         KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_MAX_SETSIZE,
2173             ("%s: keg=%s, flags=0x%b, rsize=%u, ipers=%u, ppera=%u", __func__,
2174              keg->uk_name, keg->uk_flags, PRINT_UMA_ZFLAGS, rsize,
2175              keg->uk_ipers, pages));
2176 }
2177
2178 /*
2179  * Keg header ctor.  This initializes all fields, locks, etc.  And inserts
2180  * the keg onto the global keg list.
2181  *
2182  * Arguments/Returns follow uma_ctor specifications
2183  *      udata  Actually uma_kctor_args
2184  */
2185 static int
2186 keg_ctor(void *mem, int size, void *udata, int flags)
2187 {
2188         struct uma_kctor_args *arg = udata;
2189         uma_keg_t keg = mem;
2190         uma_zone_t zone;
2191         int i;
2192
2193         bzero(keg, size);
2194         keg->uk_size = arg->size;
2195         keg->uk_init = arg->uminit;
2196         keg->uk_fini = arg->fini;
2197         keg->uk_align = arg->align;
2198         keg->uk_reserve = 0;
2199         keg->uk_flags = arg->flags;
2200
2201         /*
2202          * We use a global round-robin policy by default.  Zones with
2203          * UMA_ZONE_FIRSTTOUCH set will use first-touch instead, in which
2204          * case the iterator is never run.
2205          */
2206         keg->uk_dr.dr_policy = DOMAINSET_RR();
2207         keg->uk_dr.dr_iter = 0;
2208
2209         /*
2210          * The primary zone is passed to us at keg-creation time.
2211          */
2212         zone = arg->zone;
2213         keg->uk_name = zone->uz_name;
2214
2215         if (arg->flags & UMA_ZONE_ZINIT)
2216                 keg->uk_init = zero_init;
2217
2218         if (arg->flags & UMA_ZONE_MALLOC)
2219                 keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2220
2221 #ifndef SMP
2222         keg->uk_flags &= ~UMA_ZONE_PCPU;
2223 #endif
2224
2225         keg_layout(keg);
2226
2227         /*
2228          * Use a first-touch NUMA policy for kegs that pmap_extract() will
2229          * work on.  Use round-robin for everything else.
2230          *
2231          * Zones may override the default by specifying either.
2232          */
2233 #ifdef NUMA
2234         if ((keg->uk_flags &
2235             (UMA_ZONE_ROUNDROBIN | UMA_ZFLAG_CACHE | UMA_ZONE_NOTPAGE)) == 0)
2236                 keg->uk_flags |= UMA_ZONE_FIRSTTOUCH;
2237         else if ((keg->uk_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2238                 keg->uk_flags |= UMA_ZONE_ROUNDROBIN;
2239 #endif
2240
2241         /*
2242          * If we haven't booted yet we need allocations to go through the
2243          * startup cache until the vm is ready.
2244          */
2245 #ifdef UMA_MD_SMALL_ALLOC
2246         if (keg->uk_ppera == 1)
2247                 keg->uk_allocf = uma_small_alloc;
2248         else
2249 #endif
2250         if (booted < BOOT_KVA)
2251                 keg->uk_allocf = startup_alloc;
2252         else if (keg->uk_flags & UMA_ZONE_PCPU)
2253                 keg->uk_allocf = pcpu_page_alloc;
2254         else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 && keg->uk_ppera > 1)
2255                 keg->uk_allocf = contig_alloc;
2256         else
2257                 keg->uk_allocf = page_alloc;
2258 #ifdef UMA_MD_SMALL_ALLOC
2259         if (keg->uk_ppera == 1)
2260                 keg->uk_freef = uma_small_free;
2261         else
2262 #endif
2263         if (keg->uk_flags & UMA_ZONE_PCPU)
2264                 keg->uk_freef = pcpu_page_free;
2265         else
2266                 keg->uk_freef = page_free;
2267
2268         /*
2269          * Initialize keg's locks.
2270          */
2271         for (i = 0; i < vm_ndomains; i++)
2272                 KEG_LOCK_INIT(keg, i, (arg->flags & UMA_ZONE_MTXCLASS));
2273
2274         /*
2275          * If we're putting the slab header in the actual page we need to
2276          * figure out where in each page it goes.  See slab_sizeof
2277          * definition.
2278          */
2279         if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE)) {
2280                 size_t shsize;
2281
2282                 shsize = slab_sizeof(keg->uk_ipers);
2283                 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - shsize;
2284                 /*
2285                  * The only way the following is possible is if with our
2286                  * UMA_ALIGN_PTR adjustments we are now bigger than
2287                  * UMA_SLAB_SIZE.  I haven't checked whether this is
2288                  * mathematically possible for all cases, so we make
2289                  * sure here anyway.
2290                  */
2291                 KASSERT(keg->uk_pgoff + shsize <= PAGE_SIZE * keg->uk_ppera,
2292                     ("zone %s ipers %d rsize %d size %d slab won't fit",
2293                     zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
2294         }
2295
2296         if (keg->uk_flags & UMA_ZFLAG_HASH)
2297                 hash_alloc(&keg->uk_hash, 0);
2298
2299         CTR3(KTR_UMA, "keg_ctor %p zone %s(%p)", keg, zone->uz_name, zone);
2300
2301         LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
2302
2303         rw_wlock(&uma_rwlock);
2304         LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
2305         rw_wunlock(&uma_rwlock);
2306         return (0);
2307 }
2308
2309 static void
2310 zone_kva_available(uma_zone_t zone, void *unused)
2311 {
2312         uma_keg_t keg;
2313
2314         if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
2315                 return;
2316         KEG_GET(zone, keg);
2317
2318         if (keg->uk_allocf == startup_alloc) {
2319                 /* Switch to the real allocator. */
2320                 if (keg->uk_flags & UMA_ZONE_PCPU)
2321                         keg->uk_allocf = pcpu_page_alloc;
2322                 else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 &&
2323                     keg->uk_ppera > 1)
2324                         keg->uk_allocf = contig_alloc;
2325                 else
2326                         keg->uk_allocf = page_alloc;
2327         }
2328 }
2329
2330 static void
2331 zone_alloc_counters(uma_zone_t zone, void *unused)
2332 {
2333
2334         zone->uz_allocs = counter_u64_alloc(M_WAITOK);
2335         zone->uz_frees = counter_u64_alloc(M_WAITOK);
2336         zone->uz_fails = counter_u64_alloc(M_WAITOK);
2337         zone->uz_xdomain = counter_u64_alloc(M_WAITOK);
2338 }
2339
2340 static void
2341 zone_alloc_sysctl(uma_zone_t zone, void *unused)
2342 {
2343         uma_zone_domain_t zdom;
2344         uma_domain_t dom;
2345         uma_keg_t keg;
2346         struct sysctl_oid *oid, *domainoid;
2347         int domains, i, cnt;
2348         static const char *nokeg = "cache zone";
2349         char *c;
2350
2351         /*
2352          * Make a sysctl safe copy of the zone name by removing
2353          * any special characters and handling dups by appending
2354          * an index.
2355          */
2356         if (zone->uz_namecnt != 0) {
2357                 /* Count the number of decimal digits and '_' separator. */
2358                 for (i = 1, cnt = zone->uz_namecnt; cnt != 0; i++)
2359                         cnt /= 10;
2360                 zone->uz_ctlname = malloc(strlen(zone->uz_name) + i + 1,
2361                     M_UMA, M_WAITOK);
2362                 sprintf(zone->uz_ctlname, "%s_%d", zone->uz_name,
2363                     zone->uz_namecnt);
2364         } else
2365                 zone->uz_ctlname = strdup(zone->uz_name, M_UMA);
2366         for (c = zone->uz_ctlname; *c != '\0'; c++)
2367                 if (strchr("./\\ -", *c) != NULL)
2368                         *c = '_';
2369
2370         /*
2371          * Basic parameters at the root.
2372          */
2373         zone->uz_oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_vm_uma),
2374             OID_AUTO, zone->uz_ctlname, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2375         oid = zone->uz_oid;
2376         SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2377             "size", CTLFLAG_RD, &zone->uz_size, 0, "Allocation size");
2378         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2379             "flags", CTLFLAG_RD | CTLTYPE_STRING | CTLFLAG_MPSAFE,
2380             zone, 0, sysctl_handle_uma_zone_flags, "A",
2381             "Allocator configuration flags");
2382         SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2383             "bucket_size", CTLFLAG_RD, &zone->uz_bucket_size, 0,
2384             "Desired per-cpu cache size");
2385         SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2386             "bucket_size_max", CTLFLAG_RD, &zone->uz_bucket_size_max, 0,
2387             "Maximum allowed per-cpu cache size");
2388
2389         /*
2390          * keg if present.
2391          */
2392         if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
2393                 domains = vm_ndomains;
2394         else
2395                 domains = 1;
2396         oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2397             "keg", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2398         keg = zone->uz_keg;
2399         if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0) {
2400                 SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2401                     "name", CTLFLAG_RD, keg->uk_name, "Keg name");
2402                 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2403                     "rsize", CTLFLAG_RD, &keg->uk_rsize, 0,
2404                     "Real object size with alignment");
2405                 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2406                     "ppera", CTLFLAG_RD, &keg->uk_ppera, 0,
2407                     "pages per-slab allocation");
2408                 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2409                     "ipers", CTLFLAG_RD, &keg->uk_ipers, 0,
2410                     "items available per-slab");
2411                 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2412                     "align", CTLFLAG_RD, &keg->uk_align, 0,
2413                     "item alignment mask");
2414                 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2415                     "efficiency", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2416                     keg, 0, sysctl_handle_uma_slab_efficiency, "I",
2417                     "Slab utilization (100 - internal fragmentation %)");
2418                 domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(oid),
2419                     OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2420                 for (i = 0; i < domains; i++) {
2421                         dom = &keg->uk_domain[i];
2422                         oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2423                             OID_AUTO, VM_DOMAIN(i)->vmd_name,
2424                             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2425                         SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2426                             "pages", CTLFLAG_RD, &dom->ud_pages, 0,
2427                             "Total pages currently allocated from VM");
2428                         SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2429                             "free_items", CTLFLAG_RD, &dom->ud_free_items, 0,
2430                             "items free in the slab layer");
2431                 }
2432         } else
2433                 SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2434                     "name", CTLFLAG_RD, nokeg, "Keg name");
2435
2436         /*
2437          * Information about zone limits.
2438          */
2439         oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2440             "limit", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2441         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2442             "items", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2443             zone, 0, sysctl_handle_uma_zone_items, "QU",
2444             "current number of allocated items if limit is set");
2445         SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2446             "max_items", CTLFLAG_RD, &zone->uz_max_items, 0,
2447             "Maximum number of cached items");
2448         SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2449             "sleepers", CTLFLAG_RD, &zone->uz_sleepers, 0,
2450             "Number of threads sleeping at limit");
2451         SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2452             "sleeps", CTLFLAG_RD, &zone->uz_sleeps, 0,
2453             "Total zone limit sleeps");
2454         SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2455             "bucket_max", CTLFLAG_RD, &zone->uz_bucket_max, 0,
2456             "Maximum number of items in each domain's bucket cache");
2457
2458         /*
2459          * Per-domain zone information.
2460          */
2461         domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid),
2462             OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2463         for (i = 0; i < domains; i++) {
2464                 zdom = ZDOM_GET(zone, i);
2465                 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2466                     OID_AUTO, VM_DOMAIN(i)->vmd_name,
2467                     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2468                 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2469                     "nitems", CTLFLAG_RD, &zdom->uzd_nitems,
2470                     "number of items in this domain");
2471                 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2472                     "imax", CTLFLAG_RD, &zdom->uzd_imax,
2473                     "maximum item count in this period");
2474                 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2475                     "imin", CTLFLAG_RD, &zdom->uzd_imin,
2476                     "minimum item count in this period");
2477                 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2478                     "wss", CTLFLAG_RD, &zdom->uzd_wss,
2479                     "Working set size");
2480         }
2481
2482         /*
2483          * General statistics.
2484          */
2485         oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2486             "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2487         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2488             "current", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2489             zone, 1, sysctl_handle_uma_zone_cur, "I",
2490             "Current number of allocated items");
2491         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2492             "allocs", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2493             zone, 0, sysctl_handle_uma_zone_allocs, "QU",
2494             "Total allocation calls");
2495         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2496             "frees", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2497             zone, 0, sysctl_handle_uma_zone_frees, "QU",
2498             "Total free calls");
2499         SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2500             "fails", CTLFLAG_RD, &zone->uz_fails,
2501             "Number of allocation failures");
2502         SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2503             "xdomain", CTLFLAG_RD, &zone->uz_xdomain,
2504             "Free calls from the wrong domain");
2505 }
2506
2507 struct uma_zone_count {
2508         const char      *name;
2509         int             count;
2510 };
2511
2512 static void
2513 zone_count(uma_zone_t zone, void *arg)
2514 {
2515         struct uma_zone_count *cnt;
2516
2517         cnt = arg;
2518         /*
2519          * Some zones are rapidly created with identical names and
2520          * destroyed out of order.  This can lead to gaps in the count.
2521          * Use one greater than the maximum observed for this name.
2522          */
2523         if (strcmp(zone->uz_name, cnt->name) == 0)
2524                 cnt->count = MAX(cnt->count,
2525                     zone->uz_namecnt + 1);
2526 }
2527
2528 static void
2529 zone_update_caches(uma_zone_t zone)
2530 {
2531         int i;
2532
2533         for (i = 0; i <= mp_maxid; i++) {
2534                 cache_set_uz_size(&zone->uz_cpu[i], zone->uz_size);
2535                 cache_set_uz_flags(&zone->uz_cpu[i], zone->uz_flags);
2536         }
2537 }
2538
2539 /*
2540  * Zone header ctor.  This initializes all fields, locks, etc.
2541  *
2542  * Arguments/Returns follow uma_ctor specifications
2543  *      udata  Actually uma_zctor_args
2544  */
2545 static int
2546 zone_ctor(void *mem, int size, void *udata, int flags)
2547 {
2548         struct uma_zone_count cnt;
2549         struct uma_zctor_args *arg = udata;
2550         uma_zone_domain_t zdom;
2551         uma_zone_t zone = mem;
2552         uma_zone_t z;
2553         uma_keg_t keg;
2554         int i;
2555
2556         bzero(zone, size);
2557         zone->uz_name = arg->name;
2558         zone->uz_ctor = arg->ctor;
2559         zone->uz_dtor = arg->dtor;
2560         zone->uz_init = NULL;
2561         zone->uz_fini = NULL;
2562         zone->uz_sleeps = 0;
2563         zone->uz_bucket_size = 0;
2564         zone->uz_bucket_size_min = 0;
2565         zone->uz_bucket_size_max = BUCKET_MAX;
2566         zone->uz_flags = (arg->flags & UMA_ZONE_SMR);
2567         zone->uz_warning = NULL;
2568         /* The domain structures follow the cpu structures. */
2569         zone->uz_bucket_max = ULONG_MAX;
2570         timevalclear(&zone->uz_ratecheck);
2571
2572         /* Count the number of duplicate names. */
2573         cnt.name = arg->name;
2574         cnt.count = 0;
2575         zone_foreach(zone_count, &cnt);
2576         zone->uz_namecnt = cnt.count;
2577         ZONE_CROSS_LOCK_INIT(zone);
2578
2579         for (i = 0; i < vm_ndomains; i++) {
2580                 zdom = ZDOM_GET(zone, i);
2581                 ZDOM_LOCK_INIT(zone, zdom, (arg->flags & UMA_ZONE_MTXCLASS));
2582                 STAILQ_INIT(&zdom->uzd_buckets);
2583         }
2584
2585 #ifdef INVARIANTS
2586         if (arg->uminit == trash_init && arg->fini == trash_fini)
2587                 zone->uz_flags |= UMA_ZFLAG_TRASH | UMA_ZFLAG_CTORDTOR;
2588 #endif
2589
2590         /*
2591          * This is a pure cache zone, no kegs.
2592          */
2593         if (arg->import) {
2594                 KASSERT((arg->flags & UMA_ZFLAG_CACHE) != 0,
2595                     ("zone_ctor: Import specified for non-cache zone."));
2596                 zone->uz_flags = arg->flags;
2597                 zone->uz_size = arg->size;
2598                 zone->uz_import = arg->import;
2599                 zone->uz_release = arg->release;
2600                 zone->uz_arg = arg->arg;
2601 #ifdef NUMA
2602                 /*
2603                  * Cache zones are round-robin unless a policy is
2604                  * specified because they may have incompatible
2605                  * constraints.
2606                  */
2607                 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2608                         zone->uz_flags |= UMA_ZONE_ROUNDROBIN;
2609 #endif
2610                 rw_wlock(&uma_rwlock);
2611                 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
2612                 rw_wunlock(&uma_rwlock);
2613                 goto out;
2614         }
2615
2616         /*
2617          * Use the regular zone/keg/slab allocator.
2618          */
2619         zone->uz_import = zone_import;
2620         zone->uz_release = zone_release;
2621         zone->uz_arg = zone; 
2622         keg = arg->keg;
2623
2624         if (arg->flags & UMA_ZONE_SECONDARY) {
2625                 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
2626                     ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
2627                 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
2628                 zone->uz_init = arg->uminit;
2629                 zone->uz_fini = arg->fini;
2630                 zone->uz_flags |= UMA_ZONE_SECONDARY;
2631                 rw_wlock(&uma_rwlock);
2632                 ZONE_LOCK(zone);
2633                 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
2634                         if (LIST_NEXT(z, uz_link) == NULL) {
2635                                 LIST_INSERT_AFTER(z, zone, uz_link);
2636                                 break;
2637                         }
2638                 }
2639                 ZONE_UNLOCK(zone);
2640                 rw_wunlock(&uma_rwlock);
2641         } else if (keg == NULL) {
2642                 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
2643                     arg->align, arg->flags)) == NULL)
2644                         return (ENOMEM);
2645         } else {
2646                 struct uma_kctor_args karg;
2647                 int error;
2648
2649                 /* We should only be here from uma_startup() */
2650                 karg.size = arg->size;
2651                 karg.uminit = arg->uminit;
2652                 karg.fini = arg->fini;
2653                 karg.align = arg->align;
2654                 karg.flags = (arg->flags & ~UMA_ZONE_SMR);
2655                 karg.zone = zone;
2656                 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
2657                     flags);
2658                 if (error)
2659                         return (error);
2660         }
2661
2662         /* Inherit properties from the keg. */
2663         zone->uz_keg = keg;
2664         zone->uz_size = keg->uk_size;
2665         zone->uz_flags |= (keg->uk_flags &
2666             (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
2667
2668 out:
2669         if (booted >= BOOT_PCPU) {
2670                 zone_alloc_counters(zone, NULL);
2671                 if (booted >= BOOT_RUNNING)
2672                         zone_alloc_sysctl(zone, NULL);
2673         } else {
2674                 zone->uz_allocs = EARLY_COUNTER;
2675                 zone->uz_frees = EARLY_COUNTER;
2676                 zone->uz_fails = EARLY_COUNTER;
2677         }
2678
2679         /* Caller requests a private SMR context. */
2680         if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
2681                 zone->uz_smr = smr_create(zone->uz_name, 0, 0);
2682
2683         KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
2684             (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
2685             ("Invalid zone flag combination"));
2686         if (arg->flags & UMA_ZFLAG_INTERNAL)
2687                 zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
2688         if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
2689                 zone->uz_bucket_size = BUCKET_MAX;
2690         else if ((arg->flags & UMA_ZONE_MINBUCKET) != 0)
2691                 zone->uz_bucket_size_max = zone->uz_bucket_size = BUCKET_MIN;
2692         else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
2693                 zone->uz_bucket_size = 0;
2694         else
2695                 zone->uz_bucket_size = bucket_select(zone->uz_size);
2696         zone->uz_bucket_size_min = zone->uz_bucket_size;
2697         if (zone->uz_dtor != NULL || zone->uz_ctor != NULL)
2698                 zone->uz_flags |= UMA_ZFLAG_CTORDTOR;
2699         zone_update_caches(zone);
2700
2701         return (0);
2702 }
2703
2704 /*
2705  * Keg header dtor.  This frees all data, destroys locks, frees the hash
2706  * table and removes the keg from the global list.
2707  *
2708  * Arguments/Returns follow uma_dtor specifications
2709  *      udata  unused
2710  */
2711 static void
2712 keg_dtor(void *arg, int size, void *udata)
2713 {
2714         uma_keg_t keg;
2715         uint32_t free, pages;
2716         int i;
2717
2718         keg = (uma_keg_t)arg;
2719         free = pages = 0;
2720         for (i = 0; i < vm_ndomains; i++) {
2721                 free += keg->uk_domain[i].ud_free_items;
2722                 pages += keg->uk_domain[i].ud_pages;
2723                 KEG_LOCK_FINI(keg, i);
2724         }
2725         if (pages != 0)
2726                 printf("Freed UMA keg (%s) was not empty (%u items). "
2727                     " Lost %u pages of memory.\n",
2728                     keg->uk_name ? keg->uk_name : "",
2729                     pages / keg->uk_ppera * keg->uk_ipers - free, pages);
2730
2731         hash_free(&keg->uk_hash);
2732 }
2733
2734 /*
2735  * Zone header dtor.
2736  *
2737  * Arguments/Returns follow uma_dtor specifications
2738  *      udata  unused
2739  */
2740 static void
2741 zone_dtor(void *arg, int size, void *udata)
2742 {
2743         uma_zone_t zone;
2744         uma_keg_t keg;
2745         int i;
2746
2747         zone = (uma_zone_t)arg;
2748
2749         sysctl_remove_oid(zone->uz_oid, 1, 1);
2750
2751         if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
2752                 cache_drain(zone);
2753
2754         rw_wlock(&uma_rwlock);
2755         LIST_REMOVE(zone, uz_link);
2756         rw_wunlock(&uma_rwlock);
2757         zone_reclaim(zone, M_WAITOK, true);
2758
2759         /*
2760          * We only destroy kegs from non secondary/non cache zones.
2761          */
2762         if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
2763                 keg = zone->uz_keg;
2764                 rw_wlock(&uma_rwlock);
2765                 LIST_REMOVE(keg, uk_link);
2766                 rw_wunlock(&uma_rwlock);
2767                 zone_free_item(kegs, keg, NULL, SKIP_NONE);
2768         }
2769         counter_u64_free(zone->uz_allocs);
2770         counter_u64_free(zone->uz_frees);
2771         counter_u64_free(zone->uz_fails);
2772         counter_u64_free(zone->uz_xdomain);
2773         free(zone->uz_ctlname, M_UMA);
2774         for (i = 0; i < vm_ndomains; i++)
2775                 ZDOM_LOCK_FINI(ZDOM_GET(zone, i));
2776         ZONE_CROSS_LOCK_FINI(zone);
2777 }
2778
2779 static void
2780 zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2781 {
2782         uma_keg_t keg;
2783         uma_zone_t zone;
2784
2785         LIST_FOREACH(keg, &uma_kegs, uk_link) {
2786                 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
2787                         zfunc(zone, arg);
2788         }
2789         LIST_FOREACH(zone, &uma_cachezones, uz_link)
2790                 zfunc(zone, arg);
2791 }
2792
2793 /*
2794  * Traverses every zone in the system and calls a callback
2795  *
2796  * Arguments:
2797  *      zfunc  A pointer to a function which accepts a zone
2798  *              as an argument.
2799  *
2800  * Returns:
2801  *      Nothing
2802  */
2803 static void
2804 zone_foreach(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2805 {
2806
2807         rw_rlock(&uma_rwlock);
2808         zone_foreach_unlocked(zfunc, arg);
2809         rw_runlock(&uma_rwlock);
2810 }
2811
2812 /*
2813  * Initialize the kernel memory allocator.  This is done after pages can be
2814  * allocated but before general KVA is available.
2815  */
2816 void
2817 uma_startup1(vm_offset_t virtual_avail)
2818 {
2819         struct uma_zctor_args args;
2820         size_t ksize, zsize, size;
2821         uma_keg_t primarykeg;
2822         uintptr_t m;
2823         int domain;
2824         uint8_t pflag;
2825
2826         bootstart = bootmem = virtual_avail;
2827
2828         rw_init(&uma_rwlock, "UMA lock");
2829         sx_init(&uma_reclaim_lock, "umareclaim");
2830
2831         ksize = sizeof(struct uma_keg) +
2832             (sizeof(struct uma_domain) * vm_ndomains);
2833         ksize = roundup(ksize, UMA_SUPER_ALIGN);
2834         zsize = sizeof(struct uma_zone) +
2835             (sizeof(struct uma_cache) * (mp_maxid + 1)) +
2836             (sizeof(struct uma_zone_domain) * vm_ndomains);
2837         zsize = roundup(zsize, UMA_SUPER_ALIGN);
2838
2839         /* Allocate the zone of zones, zone of kegs, and zone of zones keg. */
2840         size = (zsize * 2) + ksize;
2841         for (domain = 0; domain < vm_ndomains; domain++) {
2842                 m = (uintptr_t)startup_alloc(NULL, size, domain, &pflag,
2843                     M_NOWAIT | M_ZERO);
2844                 if (m != 0)
2845                         break;
2846         }
2847         zones = (uma_zone_t)m;
2848         m += zsize;
2849         kegs = (uma_zone_t)m;
2850         m += zsize;
2851         primarykeg = (uma_keg_t)m;
2852
2853         /* "manually" create the initial zone */
2854         memset(&args, 0, sizeof(args));
2855         args.name = "UMA Kegs";
2856         args.size = ksize;
2857         args.ctor = keg_ctor;
2858         args.dtor = keg_dtor;
2859         args.uminit = zero_init;
2860         args.fini = NULL;
2861         args.keg = primarykeg;
2862         args.align = UMA_SUPER_ALIGN - 1;
2863         args.flags = UMA_ZFLAG_INTERNAL;
2864         zone_ctor(kegs, zsize, &args, M_WAITOK);
2865
2866         args.name = "UMA Zones";
2867         args.size = zsize;
2868         args.ctor = zone_ctor;
2869         args.dtor = zone_dtor;
2870         args.uminit = zero_init;
2871         args.fini = NULL;
2872         args.keg = NULL;
2873         args.align = UMA_SUPER_ALIGN - 1;
2874         args.flags = UMA_ZFLAG_INTERNAL;
2875         zone_ctor(zones, zsize, &args, M_WAITOK);
2876
2877         /* Now make zones for slab headers */
2878         slabzones[0] = uma_zcreate("UMA Slabs 0", SLABZONE0_SIZE,
2879             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2880         slabzones[1] = uma_zcreate("UMA Slabs 1", SLABZONE1_SIZE,
2881             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2882
2883         hashzone = uma_zcreate("UMA Hash",
2884             sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2885             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2886
2887         bucket_init();
2888         smr_init();
2889 }
2890
2891 #ifndef UMA_MD_SMALL_ALLOC
2892 extern void vm_radix_reserve_kva(void);
2893 #endif
2894
2895 /*
2896  * Advertise the availability of normal kva allocations and switch to
2897  * the default back-end allocator.  Marks the KVA we consumed on startup
2898  * as used in the map.
2899  */
2900 void
2901 uma_startup2(void)
2902 {
2903
2904         if (bootstart != bootmem) {
2905                 vm_map_lock(kernel_map);
2906                 (void)vm_map_insert(kernel_map, NULL, 0, bootstart, bootmem,
2907                     VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
2908                 vm_map_unlock(kernel_map);
2909         }
2910
2911 #ifndef UMA_MD_SMALL_ALLOC
2912         /* Set up radix zone to use noobj_alloc. */
2913         vm_radix_reserve_kva();
2914 #endif
2915
2916         booted = BOOT_KVA;
2917         zone_foreach_unlocked(zone_kva_available, NULL);
2918         bucket_enable();
2919 }
2920
2921 /*
2922  * Allocate counters as early as possible so that boot-time allocations are
2923  * accounted more precisely.
2924  */
2925 static void
2926 uma_startup_pcpu(void *arg __unused)
2927 {
2928
2929         zone_foreach_unlocked(zone_alloc_counters, NULL);
2930         booted = BOOT_PCPU;
2931 }
2932 SYSINIT(uma_startup_pcpu, SI_SUB_COUNTER, SI_ORDER_ANY, uma_startup_pcpu, NULL);
2933
2934 /*
2935  * Finish our initialization steps.
2936  */
2937 static void
2938 uma_startup3(void *arg __unused)
2939 {
2940
2941 #ifdef INVARIANTS
2942         TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2943         uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2944         uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2945 #endif
2946         zone_foreach_unlocked(zone_alloc_sysctl, NULL);
2947         callout_init(&uma_callout, 1);
2948         callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2949         booted = BOOT_RUNNING;
2950
2951         EVENTHANDLER_REGISTER(shutdown_post_sync, uma_shutdown, NULL,
2952             EVENTHANDLER_PRI_FIRST);
2953 }
2954 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
2955
2956 static void
2957 uma_shutdown(void)
2958 {
2959
2960         booted = BOOT_SHUTDOWN;
2961 }
2962
2963 static uma_keg_t
2964 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2965                 int align, uint32_t flags)
2966 {
2967         struct uma_kctor_args args;
2968
2969         args.size = size;
2970         args.uminit = uminit;
2971         args.fini = fini;
2972         args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2973         args.flags = flags;
2974         args.zone = zone;
2975         return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2976 }
2977
2978 /* Public functions */
2979 /* See uma.h */
2980 void
2981 uma_set_align(int align)
2982 {
2983
2984         if (align != UMA_ALIGN_CACHE)
2985                 uma_align_cache = align;
2986 }
2987
2988 /* See uma.h */
2989 uma_zone_t
2990 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2991                 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2992
2993 {
2994         struct uma_zctor_args args;
2995         uma_zone_t res;
2996
2997         KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2998             align, name));
2999
3000         /* This stuff is essential for the zone ctor */
3001         memset(&args, 0, sizeof(args));
3002         args.name = name;
3003         args.size = size;
3004         args.ctor = ctor;
3005         args.dtor = dtor;
3006         args.uminit = uminit;
3007         args.fini = fini;
3008 #ifdef  INVARIANTS
3009         /*
3010          * Inject procedures which check for memory use after free if we are
3011          * allowed to scramble the memory while it is not allocated.  This
3012          * requires that: UMA is actually able to access the memory, no init
3013          * or fini procedures, no dependency on the initial value of the
3014          * memory, and no (legitimate) use of the memory after free.  Note,
3015          * the ctor and dtor do not need to be empty.
3016          */
3017         if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOTOUCH |
3018             UMA_ZONE_NOFREE))) && uminit == NULL && fini == NULL) {
3019                 args.uminit = trash_init;
3020                 args.fini = trash_fini;
3021         }
3022 #endif
3023         args.align = align;
3024         args.flags = flags;
3025         args.keg = NULL;
3026
3027         sx_slock(&uma_reclaim_lock);
3028         res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3029         sx_sunlock(&uma_reclaim_lock);
3030
3031         return (res);
3032 }
3033
3034 /* See uma.h */
3035 uma_zone_t
3036 uma_zsecond_create(const char *name, uma_ctor ctor, uma_dtor dtor,
3037     uma_init zinit, uma_fini zfini, uma_zone_t primary)
3038 {
3039         struct uma_zctor_args args;
3040         uma_keg_t keg;
3041         uma_zone_t res;
3042
3043         keg = primary->uz_keg;
3044         memset(&args, 0, sizeof(args));
3045         args.name = name;
3046         args.size = keg->uk_size;
3047         args.ctor = ctor;
3048         args.dtor = dtor;
3049         args.uminit = zinit;
3050         args.fini = zfini;
3051         args.align = keg->uk_align;
3052         args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
3053         args.keg = keg;
3054
3055         sx_slock(&uma_reclaim_lock);
3056         res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3057         sx_sunlock(&uma_reclaim_lock);
3058
3059         return (res);
3060 }
3061
3062 /* See uma.h */
3063 uma_zone_t
3064 uma_zcache_create(const char *name, int size, uma_ctor ctor, uma_dtor dtor,
3065     uma_init zinit, uma_fini zfini, uma_import zimport, uma_release zrelease,
3066     void *arg, int flags)
3067 {
3068         struct uma_zctor_args args;
3069
3070         memset(&args, 0, sizeof(args));
3071         args.name = name;
3072         args.size = size;
3073         args.ctor = ctor;
3074         args.dtor = dtor;
3075         args.uminit = zinit;
3076         args.fini = zfini;
3077         args.import = zimport;
3078         args.release = zrelease;
3079         args.arg = arg;
3080         args.align = 0;
3081         args.flags = flags | UMA_ZFLAG_CACHE;
3082
3083         return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
3084 }
3085
3086 /* See uma.h */
3087 void
3088 uma_zdestroy(uma_zone_t zone)
3089 {
3090
3091         /*
3092          * Large slabs are expensive to reclaim, so don't bother doing
3093          * unnecessary work if we're shutting down.
3094          */
3095         if (booted == BOOT_SHUTDOWN &&
3096             zone->uz_fini == NULL && zone->uz_release == zone_release)
3097                 return;
3098         sx_slock(&uma_reclaim_lock);
3099         zone_free_item(zones, zone, NULL, SKIP_NONE);
3100         sx_sunlock(&uma_reclaim_lock);
3101 }
3102
3103 void
3104 uma_zwait(uma_zone_t zone)
3105 {
3106
3107         if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
3108                 uma_zfree_smr(zone, uma_zalloc_smr(zone, M_WAITOK));
3109         else if ((zone->uz_flags & UMA_ZONE_PCPU) != 0)
3110                 uma_zfree_pcpu(zone, uma_zalloc_pcpu(zone, M_WAITOK));
3111         else
3112                 uma_zfree(zone, uma_zalloc(zone, M_WAITOK));
3113 }
3114
3115 void *
3116 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
3117 {
3118         void *item, *pcpu_item;
3119 #ifdef SMP
3120         int i;
3121
3122         MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3123 #endif
3124         item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
3125         if (item == NULL)
3126                 return (NULL);
3127         pcpu_item = zpcpu_base_to_offset(item);
3128         if (flags & M_ZERO) {
3129 #ifdef SMP
3130                 for (i = 0; i <= mp_maxid; i++)
3131                         bzero(zpcpu_get_cpu(pcpu_item, i), zone->uz_size);
3132 #else
3133                 bzero(item, zone->uz_size);
3134 #endif
3135         }
3136         return (pcpu_item);
3137 }
3138
3139 /*
3140  * A stub while both regular and pcpu cases are identical.
3141  */
3142 void
3143 uma_zfree_pcpu_arg(uma_zone_t zone, void *pcpu_item, void *udata)
3144 {
3145         void *item;
3146
3147 #ifdef SMP
3148         MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3149 #endif
3150         item = zpcpu_offset_to_base(pcpu_item);
3151         uma_zfree_arg(zone, item, udata);
3152 }
3153
3154 static inline void *
3155 item_ctor(uma_zone_t zone, int uz_flags, int size, void *udata, int flags,
3156     void *item)
3157 {
3158 #ifdef INVARIANTS
3159         bool skipdbg;
3160
3161         skipdbg = uma_dbg_zskip(zone, item);
3162         if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3163             zone->uz_ctor != trash_ctor)
3164                 trash_ctor(item, size, udata, flags);
3165 #endif
3166         /* Check flags before loading ctor pointer. */
3167         if (__predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0) &&
3168             __predict_false(zone->uz_ctor != NULL) &&
3169             zone->uz_ctor(item, size, udata, flags) != 0) {
3170                 counter_u64_add(zone->uz_fails, 1);
3171                 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
3172                 return (NULL);
3173         }
3174 #ifdef INVARIANTS
3175         if (!skipdbg)
3176                 uma_dbg_alloc(zone, NULL, item);
3177 #endif
3178         if (__predict_false(flags & M_ZERO))
3179                 return (memset(item, 0, size));
3180
3181         return (item);
3182 }
3183
3184 static inline void
3185 item_dtor(uma_zone_t zone, void *item, int size, void *udata,
3186     enum zfreeskip skip)
3187 {
3188 #ifdef INVARIANTS
3189         bool skipdbg;
3190
3191         skipdbg = uma_dbg_zskip(zone, item);
3192         if (skip == SKIP_NONE && !skipdbg) {
3193                 if ((zone->uz_flags & UMA_ZONE_MALLOC) != 0)
3194                         uma_dbg_free(zone, udata, item);
3195                 else
3196                         uma_dbg_free(zone, NULL, item);
3197         }
3198 #endif
3199         if (__predict_true(skip < SKIP_DTOR)) {
3200                 if (zone->uz_dtor != NULL)
3201                         zone->uz_dtor(item, size, udata);
3202 #ifdef INVARIANTS
3203                 if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3204                     zone->uz_dtor != trash_dtor)
3205                         trash_dtor(item, size, udata);
3206 #endif
3207         }
3208 }
3209
3210 #ifdef NUMA
3211 static int
3212 item_domain(void *item)
3213 {
3214         int domain;
3215
3216         domain = _vm_phys_domain(vtophys(item));
3217         KASSERT(domain >= 0 && domain < vm_ndomains,
3218             ("%s: unknown domain for item %p", __func__, item));
3219         return (domain);
3220 }
3221 #endif
3222
3223 #if defined(INVARIANTS) || defined(DEBUG_MEMGUARD) || defined(WITNESS)
3224 #define UMA_ZALLOC_DEBUG
3225 static int
3226 uma_zalloc_debug(uma_zone_t zone, void **itemp, void *udata, int flags)
3227 {
3228         int error;
3229
3230         error = 0;
3231 #ifdef WITNESS
3232         if (flags & M_WAITOK) {
3233                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3234                     "uma_zalloc_debug: zone \"%s\"", zone->uz_name);
3235         }
3236 #endif
3237
3238 #ifdef INVARIANTS
3239         KASSERT((flags & M_EXEC) == 0,
3240             ("uma_zalloc_debug: called with M_EXEC"));
3241         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3242             ("uma_zalloc_debug: called within spinlock or critical section"));
3243         KASSERT((zone->uz_flags & UMA_ZONE_PCPU) == 0 || (flags & M_ZERO) == 0,
3244             ("uma_zalloc_debug: allocating from a pcpu zone with M_ZERO"));
3245 #endif
3246
3247 #ifdef DEBUG_MEMGUARD
3248         if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && memguard_cmp_zone(zone)) {
3249                 void *item;
3250                 item = memguard_alloc(zone->uz_size, flags);
3251                 if (item != NULL) {
3252                         error = EJUSTRETURN;
3253                         if (zone->uz_init != NULL &&
3254                             zone->uz_init(item, zone->uz_size, flags) != 0) {
3255                                 *itemp = NULL;
3256                                 return (error);
3257                         }
3258                         if (zone->uz_ctor != NULL &&
3259                             zone->uz_ctor(item, zone->uz_size, udata,
3260                             flags) != 0) {
3261                                 counter_u64_add(zone->uz_fails, 1);
3262                                 zone->uz_fini(item, zone->uz_size);
3263                                 *itemp = NULL;
3264                                 return (error);
3265                         }
3266                         *itemp = item;
3267                         return (error);
3268                 }
3269                 /* This is unfortunate but should not be fatal. */
3270         }
3271 #endif
3272         return (error);
3273 }
3274
3275 static int
3276 uma_zfree_debug(uma_zone_t zone, void *item, void *udata)
3277 {
3278         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3279             ("uma_zfree_debug: called with spinlock or critical section held"));
3280
3281 #ifdef DEBUG_MEMGUARD
3282         if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && is_memguard_addr(item)) {
3283                 if (zone->uz_dtor != NULL)
3284                         zone->uz_dtor(item, zone->uz_size, udata);
3285                 if (zone->uz_fini != NULL)
3286                         zone->uz_fini(item, zone->uz_size);
3287                 memguard_free(item);
3288                 return (EJUSTRETURN);
3289         }
3290 #endif
3291         return (0);
3292 }
3293 #endif
3294
3295 static inline void *
3296 cache_alloc_item(uma_zone_t zone, uma_cache_t cache, uma_cache_bucket_t bucket,
3297     void *udata, int flags)
3298 {
3299         void *item;
3300         int size, uz_flags;
3301
3302         item = cache_bucket_pop(cache, bucket);
3303         size = cache_uz_size(cache);
3304         uz_flags = cache_uz_flags(cache);
3305         critical_exit();
3306         return (item_ctor(zone, uz_flags, size, udata, flags, item));
3307 }
3308
3309 static __noinline void *
3310 cache_alloc_retry(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3311 {
3312         uma_cache_bucket_t bucket;
3313         int domain;
3314
3315         while (cache_alloc(zone, cache, udata, flags)) {
3316                 cache = &zone->uz_cpu[curcpu];
3317                 bucket = &cache->uc_allocbucket;
3318                 if (__predict_false(bucket->ucb_cnt == 0))
3319                         continue;
3320                 return (cache_alloc_item(zone, cache, bucket, udata, flags));
3321         }
3322         critical_exit();
3323
3324         /*
3325          * We can not get a bucket so try to return a single item.
3326          */
3327         if (zone->uz_flags & UMA_ZONE_FIRSTTOUCH)
3328                 domain = PCPU_GET(domain);
3329         else
3330                 domain = UMA_ANYDOMAIN;
3331         return (zone_alloc_item(zone, udata, domain, flags));
3332 }
3333
3334 /* See uma.h */
3335 void *
3336 uma_zalloc_smr(uma_zone_t zone, int flags)
3337 {
3338         uma_cache_bucket_t bucket;
3339         uma_cache_t cache;
3340
3341 #ifdef UMA_ZALLOC_DEBUG
3342         void *item;
3343
3344         KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
3345             ("uma_zalloc_arg: called with non-SMR zone."));
3346         if (uma_zalloc_debug(zone, &item, NULL, flags) == EJUSTRETURN)
3347                 return (item);
3348 #endif
3349
3350         critical_enter();
3351         cache = &zone->uz_cpu[curcpu];
3352         bucket = &cache->uc_allocbucket;
3353         if (__predict_false(bucket->ucb_cnt == 0))
3354                 return (cache_alloc_retry(zone, cache, NULL, flags));
3355         return (cache_alloc_item(zone, cache, bucket, NULL, flags));
3356 }
3357
3358 /* See uma.h */
3359 void *
3360 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
3361 {
3362         uma_cache_bucket_t bucket;
3363         uma_cache_t cache;
3364
3365         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3366         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3367
3368         /* This is the fast path allocation */
3369         CTR3(KTR_UMA, "uma_zalloc_arg zone %s(%p) flags %d", zone->uz_name,
3370             zone, flags);
3371
3372 #ifdef UMA_ZALLOC_DEBUG
3373         void *item;
3374
3375         KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3376             ("uma_zalloc_arg: called with SMR zone."));
3377         if (uma_zalloc_debug(zone, &item, udata, flags) == EJUSTRETURN)
3378                 return (item);
3379 #endif
3380
3381         /*
3382          * If possible, allocate from the per-CPU cache.  There are two
3383          * requirements for safe access to the per-CPU cache: (1) the thread
3384          * accessing the cache must not be preempted or yield during access,
3385          * and (2) the thread must not migrate CPUs without switching which
3386          * cache it accesses.  We rely on a critical section to prevent
3387          * preemption and migration.  We release the critical section in
3388          * order to acquire the zone mutex if we are unable to allocate from
3389          * the current cache; when we re-acquire the critical section, we
3390          * must detect and handle migration if it has occurred.
3391          */
3392         critical_enter();
3393         cache = &zone->uz_cpu[curcpu];
3394         bucket = &cache->uc_allocbucket;
3395         if (__predict_false(bucket->ucb_cnt == 0))
3396                 return (cache_alloc_retry(zone, cache, udata, flags));
3397         return (cache_alloc_item(zone, cache, bucket, udata, flags));
3398 }
3399
3400 /*
3401  * Replenish an alloc bucket and possibly restore an old one.  Called in
3402  * a critical section.  Returns in a critical section.
3403  *
3404  * A false return value indicates an allocation failure.
3405  * A true return value indicates success and the caller should retry.
3406  */
3407 static __noinline bool
3408 cache_alloc(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3409 {
3410         uma_bucket_t bucket;
3411         int curdomain, domain;
3412         bool new;
3413
3414         CRITICAL_ASSERT(curthread);
3415
3416         /*
3417          * If we have run out of items in our alloc bucket see
3418          * if we can switch with the free bucket.
3419          *
3420          * SMR Zones can't re-use the free bucket until the sequence has
3421          * expired.
3422          */
3423         if ((cache_uz_flags(cache) & UMA_ZONE_SMR) == 0 &&
3424             cache->uc_freebucket.ucb_cnt != 0) {
3425                 cache_bucket_swap(&cache->uc_freebucket,
3426                     &cache->uc_allocbucket);
3427                 return (true);
3428         }
3429
3430         /*
3431          * Discard any empty allocation bucket while we hold no locks.
3432          */
3433         bucket = cache_bucket_unload_alloc(cache);
3434         critical_exit();
3435
3436         if (bucket != NULL) {
3437                 KASSERT(bucket->ub_cnt == 0,
3438                     ("cache_alloc: Entered with non-empty alloc bucket."));
3439                 bucket_free(zone, bucket, udata);
3440         }
3441
3442         /*
3443          * Attempt to retrieve the item from the per-CPU cache has failed, so
3444          * we must go back to the zone.  This requires the zdom lock, so we
3445          * must drop the critical section, then re-acquire it when we go back
3446          * to the cache.  Since the critical section is released, we may be
3447          * preempted or migrate.  As such, make sure not to maintain any
3448          * thread-local state specific to the cache from prior to releasing
3449          * the critical section.
3450          */
3451         domain = PCPU_GET(domain);
3452         if ((cache_uz_flags(cache) & UMA_ZONE_ROUNDROBIN) != 0 ||
3453             VM_DOMAIN_EMPTY(domain))
3454                 domain = zone_domain_highest(zone, domain);
3455         bucket = cache_fetch_bucket(zone, cache, domain);
3456         if (bucket == NULL && zone->uz_bucket_size != 0 && !bucketdisable) {
3457                 bucket = zone_alloc_bucket(zone, udata, domain, flags);
3458                 new = true;
3459         } else {
3460                 new = false;
3461         }
3462
3463         CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
3464             zone->uz_name, zone, bucket);
3465         if (bucket == NULL) {
3466                 critical_enter();
3467                 return (false);
3468         }
3469
3470         /*
3471          * See if we lost the race or were migrated.  Cache the
3472          * initialized bucket to make this less likely or claim
3473          * the memory directly.
3474          */
3475         critical_enter();
3476         cache = &zone->uz_cpu[curcpu];
3477         if (cache->uc_allocbucket.ucb_bucket == NULL &&
3478             ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) == 0 ||
3479             (curdomain = PCPU_GET(domain)) == domain ||
3480             VM_DOMAIN_EMPTY(curdomain))) {
3481                 if (new)
3482                         atomic_add_long(&ZDOM_GET(zone, domain)->uzd_imax,
3483                             bucket->ub_cnt);
3484                 cache_bucket_load_alloc(cache, bucket);
3485                 return (true);
3486         }
3487
3488         /*
3489          * We lost the race, release this bucket and start over.
3490          */
3491         critical_exit();
3492         zone_put_bucket(zone, domain, bucket, udata, false);
3493         critical_enter();
3494
3495         return (true);
3496 }
3497
3498 void *
3499 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
3500 {
3501 #ifdef NUMA
3502         uma_bucket_t bucket;
3503         uma_zone_domain_t zdom;
3504         void *item;
3505 #endif
3506
3507         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3508         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3509
3510         /* This is the fast path allocation */
3511         CTR4(KTR_UMA, "uma_zalloc_domain zone %s(%p) domain %d flags %d",
3512             zone->uz_name, zone, domain, flags);
3513
3514         if (flags & M_WAITOK) {
3515                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3516                     "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
3517         }
3518         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3519             ("uma_zalloc_domain: called with spinlock or critical section held"));
3520         KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3521             ("uma_zalloc_domain: called with SMR zone."));
3522 #ifdef NUMA
3523         KASSERT((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0,
3524             ("uma_zalloc_domain: called with non-FIRSTTOUCH zone."));
3525
3526         if (vm_ndomains == 1)
3527                 return (uma_zalloc_arg(zone, udata, flags));
3528
3529         /*
3530          * Try to allocate from the bucket cache before falling back to the keg.
3531          * We could try harder and attempt to allocate from per-CPU caches or
3532          * the per-domain cross-domain buckets, but the complexity is probably
3533          * not worth it.  It is more important that frees of previous
3534          * cross-domain allocations do not blow up the cache.
3535          */
3536         zdom = zone_domain_lock(zone, domain);
3537         if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL) {
3538                 item = bucket->ub_bucket[bucket->ub_cnt - 1];
3539 #ifdef INVARIANTS
3540                 bucket->ub_bucket[bucket->ub_cnt - 1] = NULL;
3541 #endif
3542                 bucket->ub_cnt--;
3543                 zone_put_bucket(zone, domain, bucket, udata, true);
3544                 item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata,
3545                     flags, item);
3546                 if (item != NULL) {
3547                         KASSERT(item_domain(item) == domain,
3548                             ("%s: bucket cache item %p from wrong domain",
3549                             __func__, item));
3550                         counter_u64_add(zone->uz_allocs, 1);
3551                 }
3552                 return (item);
3553         }
3554         ZDOM_UNLOCK(zdom);
3555         return (zone_alloc_item(zone, udata, domain, flags));
3556 #else
3557         return (uma_zalloc_arg(zone, udata, flags));
3558 #endif
3559 }
3560
3561 /*
3562  * Find a slab with some space.  Prefer slabs that are partially used over those
3563  * that are totally full.  This helps to reduce fragmentation.
3564  *
3565  * If 'rr' is 1, search all domains starting from 'domain'.  Otherwise check
3566  * only 'domain'.
3567  */
3568 static uma_slab_t
3569 keg_first_slab(uma_keg_t keg, int domain, bool rr)
3570 {
3571         uma_domain_t dom;
3572         uma_slab_t slab;
3573         int start;
3574
3575         KASSERT(domain >= 0 && domain < vm_ndomains,
3576             ("keg_first_slab: domain %d out of range", domain));
3577         KEG_LOCK_ASSERT(keg, domain);
3578
3579         slab = NULL;
3580         start = domain;
3581         do {
3582                 dom = &keg->uk_domain[domain];
3583                 if ((slab = LIST_FIRST(&dom->ud_part_slab)) != NULL)
3584                         return (slab);
3585                 if ((slab = LIST_FIRST(&dom->ud_free_slab)) != NULL) {
3586                         LIST_REMOVE(slab, us_link);
3587                         dom->ud_free_slabs--;
3588                         LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3589                         return (slab);
3590                 }
3591                 if (rr)
3592                         domain = (domain + 1) % vm_ndomains;
3593         } while (domain != start);
3594
3595         return (NULL);
3596 }
3597
3598 /*
3599  * Fetch an existing slab from a free or partial list.  Returns with the
3600  * keg domain lock held if a slab was found or unlocked if not.
3601  */
3602 static uma_slab_t
3603 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
3604 {
3605         uma_slab_t slab;
3606         uint32_t reserve;
3607
3608         /* HASH has a single free list. */
3609         if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
3610                 domain = 0;
3611
3612         KEG_LOCK(keg, domain);
3613         reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
3614         if (keg->uk_domain[domain].ud_free_items <= reserve ||
3615             (slab = keg_first_slab(keg, domain, rr)) == NULL) {
3616                 KEG_UNLOCK(keg, domain);
3617                 return (NULL);
3618         }
3619         return (slab);
3620 }
3621
3622 static uma_slab_t
3623 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
3624 {
3625         struct vm_domainset_iter di;
3626         uma_slab_t slab;
3627         int aflags, domain;
3628         bool rr;
3629
3630 restart:
3631         /*
3632          * Use the keg's policy if upper layers haven't already specified a
3633          * domain (as happens with first-touch zones).
3634          *
3635          * To avoid races we run the iterator with the keg lock held, but that
3636          * means that we cannot allow the vm_domainset layer to sleep.  Thus,
3637          * clear M_WAITOK and handle low memory conditions locally.
3638          */
3639         rr = rdomain == UMA_ANYDOMAIN;
3640         if (rr) {
3641                 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
3642                 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3643                     &aflags);
3644         } else {
3645                 aflags = flags;
3646                 domain = rdomain;
3647         }
3648
3649         for (;;) {
3650                 slab = keg_fetch_free_slab(keg, domain, rr, flags);
3651                 if (slab != NULL)
3652                         return (slab);
3653
3654                 /*
3655                  * M_NOVM means don't ask at all!
3656                  */
3657                 if (flags & M_NOVM)
3658                         break;
3659
3660                 slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
3661                 if (slab != NULL)
3662                         return (slab);
3663                 if (!rr && (flags & M_WAITOK) == 0)
3664                         break;
3665                 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
3666                         if ((flags & M_WAITOK) != 0) {
3667                                 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
3668                                 goto restart;
3669                         }
3670                         break;
3671                 }
3672         }
3673
3674         /*
3675          * We might not have been able to get a slab but another cpu
3676          * could have while we were unlocked.  Check again before we
3677          * fail.
3678          */
3679         if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL)
3680                 return (slab);
3681
3682         return (NULL);
3683 }
3684
3685 static void *
3686 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
3687 {
3688         uma_domain_t dom;
3689         void *item;
3690         int freei;
3691
3692         KEG_LOCK_ASSERT(keg, slab->us_domain);
3693
3694         dom = &keg->uk_domain[slab->us_domain];
3695         freei = BIT_FFS(keg->uk_ipers, &slab->us_free) - 1;
3696         BIT_CLR(keg->uk_ipers, freei, &slab->us_free);
3697         item = slab_item(slab, keg, freei);
3698         slab->us_freecount--;
3699         dom->ud_free_items--;
3700
3701         /*
3702          * Move this slab to the full list.  It must be on the partial list, so
3703          * we do not need to update the free slab count.  In particular,
3704          * keg_fetch_slab() always returns slabs on the partial list.
3705          */
3706         if (slab->us_freecount == 0) {
3707                 LIST_REMOVE(slab, us_link);
3708                 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
3709         }
3710
3711         return (item);
3712 }
3713
3714 static int
3715 zone_import(void *arg, void **bucket, int max, int domain, int flags)
3716 {
3717         uma_domain_t dom;
3718         uma_zone_t zone;
3719         uma_slab_t slab;
3720         uma_keg_t keg;
3721 #ifdef NUMA
3722         int stripe;
3723 #endif
3724         int i;
3725
3726         zone = arg;
3727         slab = NULL;
3728         keg = zone->uz_keg;
3729         /* Try to keep the buckets totally full */
3730         for (i = 0; i < max; ) {
3731                 if ((slab = keg_fetch_slab(keg, zone, domain, flags)) == NULL)
3732                         break;
3733 #ifdef NUMA
3734                 stripe = howmany(max, vm_ndomains);
3735 #endif
3736                 dom = &keg->uk_domain[slab->us_domain];
3737                 do {
3738                         bucket[i++] = slab_alloc_item(keg, slab);
3739                         if (dom->ud_free_items <= keg->uk_reserve) {
3740                                 /*
3741                                  * Avoid depleting the reserve after a
3742                                  * successful item allocation, even if
3743                                  * M_USE_RESERVE is specified.
3744                                  */
3745                                 KEG_UNLOCK(keg, slab->us_domain);
3746                                 goto out;
3747                         }
3748 #ifdef NUMA
3749                         /*
3750                          * If the zone is striped we pick a new slab for every
3751                          * N allocations.  Eliminating this conditional will
3752                          * instead pick a new domain for each bucket rather
3753                          * than stripe within each bucket.  The current option
3754                          * produces more fragmentation and requires more cpu
3755                          * time but yields better distribution.
3756                          */
3757                         if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0 &&
3758                             vm_ndomains > 1 && --stripe == 0)
3759                                 break;
3760 #endif
3761                 } while (slab->us_freecount != 0 && i < max);
3762                 KEG_UNLOCK(keg, slab->us_domain);
3763
3764                 /* Don't block if we allocated any successfully. */
3765                 flags &= ~M_WAITOK;
3766                 flags |= M_NOWAIT;
3767         }
3768 out:
3769         return i;
3770 }
3771
3772 static int
3773 zone_alloc_limit_hard(uma_zone_t zone, int count, int flags)
3774 {
3775         uint64_t old, new, total, max;
3776
3777         /*
3778          * The hard case.  We're going to sleep because there were existing
3779          * sleepers or because we ran out of items.  This routine enforces
3780          * fairness by keeping fifo order.
3781          *
3782          * First release our ill gotten gains and make some noise.
3783          */
3784         for (;;) {
3785                 zone_free_limit(zone, count);
3786                 zone_log_warning(zone);
3787                 zone_maxaction(zone);
3788                 if (flags & M_NOWAIT)
3789                         return (0);
3790
3791                 /*
3792                  * We need to allocate an item or set ourself as a sleeper
3793                  * while the sleepq lock is held to avoid wakeup races.  This
3794                  * is essentially a home rolled semaphore.
3795                  */
3796                 sleepq_lock(&zone->uz_max_items);
3797                 old = zone->uz_items;
3798                 do {
3799                         MPASS(UZ_ITEMS_SLEEPERS(old) < UZ_ITEMS_SLEEPERS_MAX);
3800                         /* Cache the max since we will evaluate twice. */
3801                         max = zone->uz_max_items;
3802                         if (UZ_ITEMS_SLEEPERS(old) != 0 ||
3803                             UZ_ITEMS_COUNT(old) >= max)
3804                                 new = old + UZ_ITEMS_SLEEPER;
3805                         else
3806                                 new = old + MIN(count, max - old);
3807                 } while (atomic_fcmpset_64(&zone->uz_items, &old, new) == 0);
3808
3809                 /* We may have successfully allocated under the sleepq lock. */
3810                 if (UZ_ITEMS_SLEEPERS(new) == 0) {
3811                         sleepq_release(&zone->uz_max_items);
3812                         return (new - old);
3813                 }
3814
3815                 /*
3816                  * This is in a different cacheline from uz_items so that we
3817                  * don't constantly invalidate the fastpath cacheline when we
3818                  * adjust item counts.  This could be limited to toggling on
3819                  * transitions.
3820                  */
3821                 atomic_add_32(&zone->uz_sleepers, 1);
3822                 atomic_add_64(&zone->uz_sleeps, 1);
3823
3824                 /*
3825                  * We have added ourselves as a sleeper.  The sleepq lock
3826                  * protects us from wakeup races.  Sleep now and then retry.
3827                  */
3828                 sleepq_add(&zone->uz_max_items, NULL, "zonelimit", 0, 0);
3829                 sleepq_wait(&zone->uz_max_items, PVM);
3830
3831                 /*
3832                  * After wakeup, remove ourselves as a sleeper and try
3833                  * again.  We no longer have the sleepq lock for protection.
3834                  *
3835                  * Subract ourselves as a sleeper while attempting to add
3836                  * our count.
3837                  */
3838                 atomic_subtract_32(&zone->uz_sleepers, 1);
3839                 old = atomic_fetchadd_64(&zone->uz_items,
3840                     -(UZ_ITEMS_SLEEPER - count));
3841                 /* We're no longer a sleeper. */
3842                 old -= UZ_ITEMS_SLEEPER;
3843
3844                 /*
3845                  * If we're still at the limit, restart.  Notably do not
3846                  * block on other sleepers.  Cache the max value to protect
3847                  * against changes via sysctl.
3848                  */
3849                 total = UZ_ITEMS_COUNT(old);
3850                 max = zone->uz_max_items;
3851                 if (total >= max)
3852                         continue;
3853                 /* Truncate if necessary, otherwise wake other sleepers. */
3854                 if (total + count > max) {
3855                         zone_free_limit(zone, total + count - max);
3856                         count = max - total;
3857                 } else if (total + count < max && UZ_ITEMS_SLEEPERS(old) != 0)
3858                         wakeup_one(&zone->uz_max_items);
3859
3860                 return (count);
3861         }
3862 }
3863
3864 /*
3865  * Allocate 'count' items from our max_items limit.  Returns the number
3866  * available.  If M_NOWAIT is not specified it will sleep until at least
3867  * one item can be allocated.
3868  */
3869 static int
3870 zone_alloc_limit(uma_zone_t zone, int count, int flags)
3871 {
3872         uint64_t old;
3873         uint64_t max;
3874
3875         max = zone->uz_max_items;
3876         MPASS(max > 0);
3877
3878         /*
3879          * We expect normal allocations to succeed with a simple
3880          * fetchadd.
3881          */
3882         old = atomic_fetchadd_64(&zone->uz_items, count);
3883         if (__predict_true(old + count <= max))
3884                 return (count);
3885
3886         /*
3887          * If we had some items and no sleepers just return the
3888          * truncated value.  We have to release the excess space
3889          * though because that may wake sleepers who weren't woken
3890          * because we were temporarily over the limit.
3891          */
3892         if (old < max) {
3893                 zone_free_limit(zone, (old + count) - max);
3894                 return (max - old);
3895         }
3896         return (zone_alloc_limit_hard(zone, count, flags));
3897 }
3898
3899 /*
3900  * Free a number of items back to the limit.
3901  */
3902 static void
3903 zone_free_limit(uma_zone_t zone, int count)
3904 {
3905         uint64_t old;
3906
3907         MPASS(count > 0);
3908
3909         /*
3910          * In the common case we either have no sleepers or
3911          * are still over the limit and can just return.
3912          */
3913         old = atomic_fetchadd_64(&zone->uz_items, -count);
3914         if (__predict_true(UZ_ITEMS_SLEEPERS(old) == 0 ||
3915            UZ_ITEMS_COUNT(old) - count >= zone->uz_max_items))
3916                 return;
3917
3918         /*
3919          * Moderate the rate of wakeups.  Sleepers will continue
3920          * to generate wakeups if necessary.
3921          */
3922         wakeup_one(&zone->uz_max_items);
3923 }
3924
3925 static uma_bucket_t
3926 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
3927 {
3928         uma_bucket_t bucket;
3929         int maxbucket, cnt;
3930
3931         CTR3(KTR_UMA, "zone_alloc_bucket zone %s(%p) domain %d", zone->uz_name,
3932             zone, domain);
3933
3934         /* Avoid allocs targeting empty domains. */
3935         if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
3936                 domain = UMA_ANYDOMAIN;
3937         else if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
3938                 domain = UMA_ANYDOMAIN;
3939
3940         if (zone->uz_max_items > 0)
3941                 maxbucket = zone_alloc_limit(zone, zone->uz_bucket_size,
3942                     M_NOWAIT);
3943         else
3944                 maxbucket = zone->uz_bucket_size;
3945         if (maxbucket == 0)
3946                 return (false);
3947
3948         /* Don't wait for buckets, preserve caller's NOVM setting. */
3949         bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
3950         if (bucket == NULL) {
3951                 cnt = 0;
3952                 goto out;
3953         }
3954
3955         bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
3956             MIN(maxbucket, bucket->ub_entries), domain, flags);
3957
3958         /*
3959          * Initialize the memory if necessary.
3960          */
3961         if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
3962                 int i;
3963
3964                 for (i = 0; i < bucket->ub_cnt; i++)
3965                         if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
3966                             flags) != 0)
3967                                 break;
3968                 /*
3969                  * If we couldn't initialize the whole bucket, put the
3970                  * rest back onto the freelist.
3971                  */
3972                 if (i != bucket->ub_cnt) {
3973                         zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
3974                             bucket->ub_cnt - i);
3975 #ifdef INVARIANTS
3976                         bzero(&bucket->ub_bucket[i],
3977                             sizeof(void *) * (bucket->ub_cnt - i));
3978 #endif
3979                         bucket->ub_cnt = i;
3980                 }
3981         }
3982
3983         cnt = bucket->ub_cnt;
3984         if (bucket->ub_cnt == 0) {
3985                 bucket_free(zone, bucket, udata);
3986                 counter_u64_add(zone->uz_fails, 1);
3987                 bucket = NULL;
3988         }
3989 out:
3990         if (zone->uz_max_items > 0 && cnt < maxbucket)
3991                 zone_free_limit(zone, maxbucket - cnt);
3992
3993         return (bucket);
3994 }
3995
3996 /*
3997  * Allocates a single item from a zone.
3998  *
3999  * Arguments
4000  *      zone   The zone to alloc for.
4001  *      udata  The data to be passed to the constructor.
4002  *      domain The domain to allocate from or UMA_ANYDOMAIN.
4003  *      flags  M_WAITOK, M_NOWAIT, M_ZERO.
4004  *
4005  * Returns
4006  *      NULL if there is no memory and M_NOWAIT is set
4007  *      An item if successful
4008  */
4009
4010 static void *
4011 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
4012 {
4013         void *item;
4014
4015         if (zone->uz_max_items > 0 && zone_alloc_limit(zone, 1, flags) == 0) {
4016                 counter_u64_add(zone->uz_fails, 1);
4017                 return (NULL);
4018         }
4019
4020         /* Avoid allocs targeting empty domains. */
4021         if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
4022                 domain = UMA_ANYDOMAIN;
4023
4024         if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
4025                 goto fail_cnt;
4026
4027         /*
4028          * We have to call both the zone's init (not the keg's init)
4029          * and the zone's ctor.  This is because the item is going from
4030          * a keg slab directly to the user, and the user is expecting it
4031          * to be both zone-init'd as well as zone-ctor'd.
4032          */
4033         if (zone->uz_init != NULL) {
4034                 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
4035                         zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
4036                         goto fail_cnt;
4037                 }
4038         }
4039         item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata, flags,
4040             item);
4041         if (item == NULL)
4042                 goto fail;
4043
4044         counter_u64_add(zone->uz_allocs, 1);
4045         CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
4046             zone->uz_name, zone);
4047
4048         return (item);
4049
4050 fail_cnt:
4051         counter_u64_add(zone->uz_fails, 1);
4052 fail:
4053         if (zone->uz_max_items > 0)
4054                 zone_free_limit(zone, 1);
4055         CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
4056             zone->uz_name, zone);
4057
4058         return (NULL);
4059 }
4060
4061 /* See uma.h */
4062 void
4063 uma_zfree_smr(uma_zone_t zone, void *item)
4064 {
4065         uma_cache_t cache;
4066         uma_cache_bucket_t bucket;
4067         int itemdomain, uz_flags;
4068
4069 #ifdef UMA_ZALLOC_DEBUG
4070         KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
4071             ("uma_zfree_smr: called with non-SMR zone."));
4072         KASSERT(item != NULL, ("uma_zfree_smr: Called with NULL pointer."));
4073         SMR_ASSERT_NOT_ENTERED(zone->uz_smr);
4074         if (uma_zfree_debug(zone, item, NULL) == EJUSTRETURN)
4075                 return;
4076 #endif
4077         cache = &zone->uz_cpu[curcpu];
4078         uz_flags = cache_uz_flags(cache);
4079         itemdomain = 0;
4080 #ifdef NUMA
4081         if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4082                 itemdomain = item_domain(item);
4083 #endif
4084         critical_enter();
4085         do {
4086                 cache = &zone->uz_cpu[curcpu];
4087                 /* SMR Zones must free to the free bucket. */
4088                 bucket = &cache->uc_freebucket;
4089 #ifdef NUMA
4090                 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4091                     PCPU_GET(domain) != itemdomain) {
4092                         bucket = &cache->uc_crossbucket;
4093                 }
4094 #endif
4095                 if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4096                         cache_bucket_push(cache, bucket, item);
4097                         critical_exit();
4098                         return;
4099                 }
4100         } while (cache_free(zone, cache, NULL, item, itemdomain));
4101         critical_exit();
4102
4103         /*
4104          * If nothing else caught this, we'll just do an internal free.
4105          */
4106         zone_free_item(zone, item, NULL, SKIP_NONE);
4107 }
4108
4109 /* See uma.h */
4110 void
4111 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
4112 {
4113         uma_cache_t cache;
4114         uma_cache_bucket_t bucket;
4115         int itemdomain, uz_flags;
4116
4117         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
4118         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
4119
4120         CTR2(KTR_UMA, "uma_zfree_arg zone %s(%p)", zone->uz_name, zone);
4121
4122 #ifdef UMA_ZALLOC_DEBUG
4123         KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4124             ("uma_zfree_arg: called with SMR zone."));
4125         if (uma_zfree_debug(zone, item, udata) == EJUSTRETURN)
4126                 return;
4127 #endif
4128         /* uma_zfree(..., NULL) does nothing, to match free(9). */
4129         if (item == NULL)
4130                 return;
4131
4132         /*
4133          * We are accessing the per-cpu cache without a critical section to
4134          * fetch size and flags.  This is acceptable, if we are preempted we
4135          * will simply read another cpu's line.
4136          */
4137         cache = &zone->uz_cpu[curcpu];
4138         uz_flags = cache_uz_flags(cache);
4139         if (UMA_ALWAYS_CTORDTOR ||
4140             __predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0))
4141                 item_dtor(zone, item, cache_uz_size(cache), udata, SKIP_NONE);
4142
4143         /*
4144          * The race here is acceptable.  If we miss it we'll just have to wait
4145          * a little longer for the limits to be reset.
4146          */
4147         if (__predict_false(uz_flags & UMA_ZFLAG_LIMIT)) {
4148                 if (zone->uz_sleepers > 0)
4149                         goto zfree_item;
4150         }
4151
4152         /*
4153          * If possible, free to the per-CPU cache.  There are two
4154          * requirements for safe access to the per-CPU cache: (1) the thread
4155          * accessing the cache must not be preempted or yield during access,
4156          * and (2) the thread must not migrate CPUs without switching which
4157          * cache it accesses.  We rely on a critical section to prevent
4158          * preemption and migration.  We release the critical section in
4159          * order to acquire the zone mutex if we are unable to free to the
4160          * current cache; when we re-acquire the critical section, we must
4161          * detect and handle migration if it has occurred.
4162          */
4163         itemdomain = 0;
4164 #ifdef NUMA
4165         if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4166                 itemdomain = item_domain(item);
4167 #endif
4168         critical_enter();
4169         do {
4170                 cache = &zone->uz_cpu[curcpu];
4171                 /*
4172                  * Try to free into the allocbucket first to give LIFO
4173                  * ordering for cache-hot datastructures.  Spill over
4174                  * into the freebucket if necessary.  Alloc will swap
4175                  * them if one runs dry.
4176                  */
4177                 bucket = &cache->uc_allocbucket;
4178 #ifdef NUMA
4179                 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4180                     PCPU_GET(domain) != itemdomain) {
4181                         bucket = &cache->uc_crossbucket;
4182                 } else
4183 #endif
4184                 if (bucket->ucb_cnt == bucket->ucb_entries &&
4185                    cache->uc_freebucket.ucb_cnt <
4186                    cache->uc_freebucket.ucb_entries)
4187                         cache_bucket_swap(&cache->uc_freebucket,
4188                             &cache->uc_allocbucket);
4189                 if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4190                         cache_bucket_push(cache, bucket, item);
4191                         critical_exit();
4192                         return;
4193                 }
4194         } while (cache_free(zone, cache, udata, item, itemdomain));
4195         critical_exit();
4196
4197         /*
4198          * If nothing else caught this, we'll just do an internal free.
4199          */
4200 zfree_item:
4201         zone_free_item(zone, item, udata, SKIP_DTOR);
4202 }
4203
4204 #ifdef NUMA
4205 /*
4206  * sort crossdomain free buckets to domain correct buckets and cache
4207  * them.
4208  */
4209 static void
4210 zone_free_cross(uma_zone_t zone, uma_bucket_t bucket, void *udata)
4211 {
4212         struct uma_bucketlist fullbuckets;
4213         uma_zone_domain_t zdom;
4214         uma_bucket_t b;
4215         smr_seq_t seq;
4216         void *item;
4217         int domain;
4218
4219         CTR3(KTR_UMA,
4220             "uma_zfree: zone %s(%p) draining cross bucket %p",
4221             zone->uz_name, zone, bucket);
4222
4223         /*
4224          * It is possible for buckets to arrive here out of order so we fetch
4225          * the current smr seq rather than accepting the bucket's.
4226          */
4227         seq = SMR_SEQ_INVALID;
4228         if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
4229                 seq = smr_advance(zone->uz_smr);
4230
4231         /*
4232          * To avoid having ndomain * ndomain buckets for sorting we have a
4233          * lock on the current crossfree bucket.  A full matrix with
4234          * per-domain locking could be used if necessary.
4235          */
4236         STAILQ_INIT(&fullbuckets);
4237         ZONE_CROSS_LOCK(zone);
4238         while (bucket->ub_cnt > 0) {
4239                 item = bucket->ub_bucket[bucket->ub_cnt - 1];
4240                 domain = item_domain(item);
4241                 zdom = ZDOM_GET(zone, domain);
4242                 if (zdom->uzd_cross == NULL) {
4243                         zdom->uzd_cross = bucket_alloc(zone, udata, M_NOWAIT);
4244                         if (zdom->uzd_cross == NULL)
4245                                 break;
4246                 }
4247                 b = zdom->uzd_cross;
4248                 b->ub_bucket[b->ub_cnt++] = item;
4249                 b->ub_seq = seq;
4250                 if (b->ub_cnt == b->ub_entries) {
4251                         STAILQ_INSERT_HEAD(&fullbuckets, b, ub_link);
4252                         zdom->uzd_cross = NULL;
4253                 }
4254                 bucket->ub_cnt--;
4255         }
4256         ZONE_CROSS_UNLOCK(zone);
4257         if (bucket->ub_cnt == 0)
4258                 bucket->ub_seq = SMR_SEQ_INVALID;
4259         bucket_free(zone, bucket, udata);
4260
4261         while ((b = STAILQ_FIRST(&fullbuckets)) != NULL) {
4262                 STAILQ_REMOVE_HEAD(&fullbuckets, ub_link);
4263                 domain = item_domain(b->ub_bucket[0]);
4264                 zone_put_bucket(zone, domain, b, udata, true);
4265         }
4266 }
4267 #endif
4268
4269 static void
4270 zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
4271     int itemdomain, bool ws)
4272 {
4273
4274 #ifdef NUMA
4275         /*
4276          * Buckets coming from the wrong domain will be entirely for the
4277          * only other domain on two domain systems.  In this case we can
4278          * simply cache them.  Otherwise we need to sort them back to
4279          * correct domains.
4280          */
4281         if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4282             vm_ndomains > 2 && PCPU_GET(domain) != itemdomain) {
4283                 zone_free_cross(zone, bucket, udata);
4284                 return;
4285         }
4286 #endif
4287
4288         /*
4289          * Attempt to save the bucket in the zone's domain bucket cache.
4290          */
4291         CTR3(KTR_UMA,
4292             "uma_zfree: zone %s(%p) putting bucket %p on free list",
4293             zone->uz_name, zone, bucket);
4294         /* ub_cnt is pointing to the last free item */
4295         if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
4296                 itemdomain = zone_domain_lowest(zone, itemdomain);
4297         zone_put_bucket(zone, itemdomain, bucket, udata, ws);
4298 }
4299
4300 /*
4301  * Populate a free or cross bucket for the current cpu cache.  Free any
4302  * existing full bucket either to the zone cache or back to the slab layer.
4303  *
4304  * Enters and returns in a critical section.  false return indicates that
4305  * we can not satisfy this free in the cache layer.  true indicates that
4306  * the caller should retry.
4307  */
4308 static __noinline bool
4309 cache_free(uma_zone_t zone, uma_cache_t cache, void *udata, void *item,
4310     int itemdomain)
4311 {
4312         uma_cache_bucket_t cbucket;
4313         uma_bucket_t newbucket, bucket;
4314
4315         CRITICAL_ASSERT(curthread);
4316
4317         if (zone->uz_bucket_size == 0)
4318                 return false;
4319
4320         cache = &zone->uz_cpu[curcpu];
4321         newbucket = NULL;
4322
4323         /*
4324          * FIRSTTOUCH domains need to free to the correct zdom.  When
4325          * enabled this is the zdom of the item.   The bucket is the
4326          * cross bucket if the current domain and itemdomain do not match.
4327          */
4328         cbucket = &cache->uc_freebucket;
4329 #ifdef NUMA
4330         if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4331                 if (PCPU_GET(domain) != itemdomain) {
4332                         cbucket = &cache->uc_crossbucket;
4333                         if (cbucket->ucb_cnt != 0)
4334                                 counter_u64_add(zone->uz_xdomain,
4335                                     cbucket->ucb_cnt);
4336                 }
4337         }
4338 #endif
4339         bucket = cache_bucket_unload(cbucket);
4340         KASSERT(bucket == NULL || bucket->ub_cnt == bucket->ub_entries,
4341             ("cache_free: Entered with non-full free bucket."));
4342
4343         /* We are no longer associated with this CPU. */
4344         critical_exit();
4345
4346         /*
4347          * Don't let SMR zones operate without a free bucket.  Force
4348          * a synchronize and re-use this one.  We will only degrade
4349          * to a synchronize every bucket_size items rather than every
4350          * item if we fail to allocate a bucket.
4351          */
4352         if ((zone->uz_flags & UMA_ZONE_SMR) != 0) {
4353                 if (bucket != NULL)
4354                         bucket->ub_seq = smr_advance(zone->uz_smr);
4355                 newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4356                 if (newbucket == NULL && bucket != NULL) {
4357                         bucket_drain(zone, bucket);
4358                         newbucket = bucket;
4359                         bucket = NULL;
4360                 }
4361         } else if (!bucketdisable)
4362                 newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4363
4364         if (bucket != NULL)
4365                 zone_free_bucket(zone, bucket, udata, itemdomain, true);
4366
4367         critical_enter();
4368         if ((bucket = newbucket) == NULL)
4369                 return (false);
4370         cache = &zone->uz_cpu[curcpu];
4371 #ifdef NUMA
4372         /*
4373          * Check to see if we should be populating the cross bucket.  If it
4374          * is already populated we will fall through and attempt to populate
4375          * the free bucket.
4376          */
4377         if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4378                 if (PCPU_GET(domain) != itemdomain &&
4379                     cache->uc_crossbucket.ucb_bucket == NULL) {
4380                         cache_bucket_load_cross(cache, bucket);
4381                         return (true);
4382                 }
4383         }
4384 #endif
4385         /*
4386          * We may have lost the race to fill the bucket or switched CPUs.
4387          */
4388         if (cache->uc_freebucket.ucb_bucket != NULL) {
4389                 critical_exit();
4390                 bucket_free(zone, bucket, udata);
4391                 critical_enter();
4392         } else
4393                 cache_bucket_load_free(cache, bucket);
4394
4395         return (true);
4396 }
4397
4398 static void
4399 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
4400 {
4401         uma_keg_t keg;
4402         uma_domain_t dom;
4403         int freei;
4404
4405         keg = zone->uz_keg;
4406         KEG_LOCK_ASSERT(keg, slab->us_domain);
4407
4408         /* Do we need to remove from any lists? */
4409         dom = &keg->uk_domain[slab->us_domain];
4410         if (slab->us_freecount + 1 == keg->uk_ipers) {
4411                 LIST_REMOVE(slab, us_link);
4412                 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
4413                 dom->ud_free_slabs++;
4414         } else if (slab->us_freecount == 0) {
4415                 LIST_REMOVE(slab, us_link);
4416                 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
4417         }
4418
4419         /* Slab management. */
4420         freei = slab_item_index(slab, keg, item);
4421         BIT_SET(keg->uk_ipers, freei, &slab->us_free);
4422         slab->us_freecount++;
4423
4424         /* Keg statistics. */
4425         dom->ud_free_items++;
4426 }
4427
4428 static void
4429 zone_release(void *arg, void **bucket, int cnt)
4430 {
4431         struct mtx *lock;
4432         uma_zone_t zone;
4433         uma_slab_t slab;
4434         uma_keg_t keg;
4435         uint8_t *mem;
4436         void *item;
4437         int i;
4438
4439         zone = arg;
4440         keg = zone->uz_keg;
4441         lock = NULL;
4442         if (__predict_false((zone->uz_flags & UMA_ZFLAG_HASH) != 0))
4443                 lock = KEG_LOCK(keg, 0);
4444         for (i = 0; i < cnt; i++) {
4445                 item = bucket[i];
4446                 if (__predict_true((zone->uz_flags & UMA_ZFLAG_VTOSLAB) != 0)) {
4447                         slab = vtoslab((vm_offset_t)item);
4448                 } else {
4449                         mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4450                         if ((zone->uz_flags & UMA_ZFLAG_HASH) != 0)
4451                                 slab = hash_sfind(&keg->uk_hash, mem);
4452                         else
4453                                 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4454                 }
4455                 if (lock != KEG_LOCKPTR(keg, slab->us_domain)) {
4456                         if (lock != NULL)
4457                                 mtx_unlock(lock);
4458                         lock = KEG_LOCK(keg, slab->us_domain);
4459                 }
4460                 slab_free_item(zone, slab, item);
4461         }
4462         if (lock != NULL)
4463                 mtx_unlock(lock);
4464 }
4465
4466 /*
4467  * Frees a single item to any zone.
4468  *
4469  * Arguments:
4470  *      zone   The zone to free to
4471  *      item   The item we're freeing
4472  *      udata  User supplied data for the dtor
4473  *      skip   Skip dtors and finis
4474  */
4475 static __noinline void
4476 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
4477 {
4478
4479         /*
4480          * If a free is sent directly to an SMR zone we have to
4481          * synchronize immediately because the item can instantly
4482          * be reallocated. This should only happen in degenerate
4483          * cases when no memory is available for per-cpu caches.
4484          */
4485         if ((zone->uz_flags & UMA_ZONE_SMR) != 0 && skip == SKIP_NONE)
4486                 smr_synchronize(zone->uz_smr);
4487
4488         item_dtor(zone, item, zone->uz_size, udata, skip);
4489
4490         if (skip < SKIP_FINI && zone->uz_fini)
4491                 zone->uz_fini(item, zone->uz_size);
4492
4493         zone->uz_release(zone->uz_arg, &item, 1);
4494
4495         if (skip & SKIP_CNT)
4496                 return;
4497
4498         counter_u64_add(zone->uz_frees, 1);
4499
4500         if (zone->uz_max_items > 0)
4501                 zone_free_limit(zone, 1);
4502 }
4503
4504 /* See uma.h */
4505 int
4506 uma_zone_set_max(uma_zone_t zone, int nitems)
4507 {
4508         struct uma_bucket_zone *ubz;
4509         int count;
4510
4511         /*
4512          * XXX This can misbehave if the zone has any allocations with
4513          * no limit and a limit is imposed.  There is currently no
4514          * way to clear a limit.
4515          */
4516         ZONE_LOCK(zone);
4517         ubz = bucket_zone_max(zone, nitems);
4518         count = ubz != NULL ? ubz->ubz_entries : 0;
4519         zone->uz_bucket_size_max = zone->uz_bucket_size = count;
4520         if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
4521                 zone->uz_bucket_size_min = zone->uz_bucket_size_max;
4522         zone->uz_max_items = nitems;
4523         zone->uz_flags |= UMA_ZFLAG_LIMIT;
4524         zone_update_caches(zone);
4525         /* We may need to wake waiters. */
4526         wakeup(&zone->uz_max_items);
4527         ZONE_UNLOCK(zone);
4528
4529         return (nitems);
4530 }
4531
4532 /* See uma.h */
4533 void
4534 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
4535 {
4536         struct uma_bucket_zone *ubz;
4537         int bpcpu;
4538
4539         ZONE_LOCK(zone);
4540         ubz = bucket_zone_max(zone, nitems);
4541         if (ubz != NULL) {
4542                 bpcpu = 2;
4543                 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4544                         /* Count the cross-domain bucket. */
4545                         bpcpu++;
4546                 nitems -= ubz->ubz_entries * bpcpu * mp_ncpus;
4547                 zone->uz_bucket_size_max = ubz->ubz_entries;
4548         } else {
4549                 zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
4550         }
4551         if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
4552                 zone->uz_bucket_size_min = zone->uz_bucket_size_max;
4553         zone->uz_bucket_max = nitems / vm_ndomains;
4554         ZONE_UNLOCK(zone);
4555 }
4556
4557 /* See uma.h */
4558 int
4559 uma_zone_get_max(uma_zone_t zone)
4560 {
4561         int nitems;
4562
4563         nitems = atomic_load_64(&zone->uz_max_items);
4564
4565         return (nitems);
4566 }
4567
4568 /* See uma.h */
4569 void
4570 uma_zone_set_warning(uma_zone_t zone, const char *warning)
4571 {
4572
4573         ZONE_ASSERT_COLD(zone);
4574         zone->uz_warning = warning;
4575 }
4576
4577 /* See uma.h */
4578 void
4579 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
4580 {
4581
4582         ZONE_ASSERT_COLD(zone);
4583         TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
4584 }
4585
4586 /* See uma.h */
4587 int
4588 uma_zone_get_cur(uma_zone_t zone)
4589 {
4590         int64_t nitems;
4591         u_int i;
4592
4593         nitems = 0;
4594         if (zone->uz_allocs != EARLY_COUNTER && zone->uz_frees != EARLY_COUNTER)
4595                 nitems = counter_u64_fetch(zone->uz_allocs) -
4596                     counter_u64_fetch(zone->uz_frees);
4597         CPU_FOREACH(i)
4598                 nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs) -
4599                     atomic_load_64(&zone->uz_cpu[i].uc_frees);
4600
4601         return (nitems < 0 ? 0 : nitems);
4602 }
4603
4604 static uint64_t
4605 uma_zone_get_allocs(uma_zone_t zone)
4606 {
4607         uint64_t nitems;
4608         u_int i;
4609
4610         nitems = 0;
4611         if (zone->uz_allocs != EARLY_COUNTER)
4612                 nitems = counter_u64_fetch(zone->uz_allocs);
4613         CPU_FOREACH(i)
4614                 nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs);
4615
4616         return (nitems);
4617 }
4618
4619 static uint64_t
4620 uma_zone_get_frees(uma_zone_t zone)
4621 {
4622         uint64_t nitems;
4623         u_int i;
4624
4625         nitems = 0;
4626         if (zone->uz_frees != EARLY_COUNTER)
4627                 nitems = counter_u64_fetch(zone->uz_frees);
4628         CPU_FOREACH(i)
4629                 nitems += atomic_load_64(&zone->uz_cpu[i].uc_frees);
4630
4631         return (nitems);
4632 }
4633
4634 #ifdef INVARIANTS
4635 /* Used only for KEG_ASSERT_COLD(). */
4636 static uint64_t
4637 uma_keg_get_allocs(uma_keg_t keg)
4638 {
4639         uma_zone_t z;
4640         uint64_t nitems;
4641
4642         nitems = 0;
4643         LIST_FOREACH(z, &keg->uk_zones, uz_link)
4644                 nitems += uma_zone_get_allocs(z);
4645
4646         return (nitems);
4647 }
4648 #endif
4649
4650 /* See uma.h */
4651 void
4652 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
4653 {
4654         uma_keg_t keg;
4655
4656         KEG_GET(zone, keg);
4657         KEG_ASSERT_COLD(keg);
4658         keg->uk_init = uminit;
4659 }
4660
4661 /* See uma.h */
4662 void
4663 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
4664 {
4665         uma_keg_t keg;
4666
4667         KEG_GET(zone, keg);
4668         KEG_ASSERT_COLD(keg);
4669         keg->uk_fini = fini;
4670 }
4671
4672 /* See uma.h */
4673 void
4674 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
4675 {
4676
4677         ZONE_ASSERT_COLD(zone);
4678         zone->uz_init = zinit;
4679 }
4680
4681 /* See uma.h */
4682 void
4683 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
4684 {
4685
4686         ZONE_ASSERT_COLD(zone);
4687         zone->uz_fini = zfini;
4688 }
4689
4690 /* See uma.h */
4691 void
4692 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
4693 {
4694         uma_keg_t keg;
4695
4696         KEG_GET(zone, keg);
4697         KEG_ASSERT_COLD(keg);
4698         keg->uk_freef = freef;
4699 }
4700
4701 /* See uma.h */
4702 void
4703 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
4704 {
4705         uma_keg_t keg;
4706
4707         KEG_GET(zone, keg);
4708         KEG_ASSERT_COLD(keg);
4709         keg->uk_allocf = allocf;
4710 }
4711
4712 /* See uma.h */
4713 void
4714 uma_zone_set_smr(uma_zone_t zone, smr_t smr)
4715 {
4716
4717         ZONE_ASSERT_COLD(zone);
4718
4719         KASSERT(smr != NULL, ("Got NULL smr"));
4720         KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4721             ("zone %p (%s) already uses SMR", zone, zone->uz_name));
4722         zone->uz_flags |= UMA_ZONE_SMR;
4723         zone->uz_smr = smr;
4724         zone_update_caches(zone);
4725 }
4726
4727 smr_t
4728 uma_zone_get_smr(uma_zone_t zone)
4729 {
4730
4731         return (zone->uz_smr);
4732 }
4733
4734 /* See uma.h */
4735 void
4736 uma_zone_reserve(uma_zone_t zone, int items)
4737 {
4738         uma_keg_t keg;
4739
4740         KEG_GET(zone, keg);
4741         KEG_ASSERT_COLD(keg);
4742         keg->uk_reserve = items;
4743 }
4744
4745 /* See uma.h */
4746 int
4747 uma_zone_reserve_kva(uma_zone_t zone, int count)
4748 {
4749         uma_keg_t keg;
4750         vm_offset_t kva;
4751         u_int pages;
4752
4753         KEG_GET(zone, keg);
4754         KEG_ASSERT_COLD(keg);
4755         ZONE_ASSERT_COLD(zone);
4756
4757         pages = howmany(count, keg->uk_ipers) * keg->uk_ppera;
4758
4759 #ifdef UMA_MD_SMALL_ALLOC
4760         if (keg->uk_ppera > 1) {
4761 #else
4762         if (1) {
4763 #endif
4764                 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
4765                 if (kva == 0)
4766                         return (0);
4767         } else
4768                 kva = 0;
4769
4770         MPASS(keg->uk_kva == 0);
4771         keg->uk_kva = kva;
4772         keg->uk_offset = 0;
4773         zone->uz_max_items = pages * keg->uk_ipers;
4774 #ifdef UMA_MD_SMALL_ALLOC
4775         keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
4776 #else
4777         keg->uk_allocf = noobj_alloc;
4778 #endif
4779         keg->uk_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4780         zone->uz_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4781         zone_update_caches(zone);
4782
4783         return (1);
4784 }
4785
4786 /* See uma.h */
4787 void
4788 uma_prealloc(uma_zone_t zone, int items)
4789 {
4790         struct vm_domainset_iter di;
4791         uma_domain_t dom;
4792         uma_slab_t slab;
4793         uma_keg_t keg;
4794         int aflags, domain, slabs;
4795
4796         KEG_GET(zone, keg);
4797         slabs = howmany(items, keg->uk_ipers);
4798         while (slabs-- > 0) {
4799                 aflags = M_NOWAIT;
4800                 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
4801                     &aflags);
4802                 for (;;) {
4803                         slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
4804                             aflags);
4805                         if (slab != NULL) {
4806                                 dom = &keg->uk_domain[slab->us_domain];
4807                                 /*
4808                                  * keg_alloc_slab() always returns a slab on the
4809                                  * partial list.
4810                                  */
4811                                 LIST_REMOVE(slab, us_link);
4812                                 LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
4813                                     us_link);
4814                                 dom->ud_free_slabs++;
4815                                 KEG_UNLOCK(keg, slab->us_domain);
4816                                 break;
4817                         }
4818                         if (vm_domainset_iter_policy(&di, &domain) != 0)
4819                                 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
4820                 }
4821         }
4822 }
4823
4824 /*
4825  * Returns a snapshot of memory consumption in bytes.
4826  */
4827 size_t
4828 uma_zone_memory(uma_zone_t zone)
4829 {
4830         size_t sz;
4831         int i;
4832
4833         sz = 0;
4834         if (zone->uz_flags & UMA_ZFLAG_CACHE) {
4835                 for (i = 0; i < vm_ndomains; i++)
4836                         sz += ZDOM_GET(zone, i)->uzd_nitems;
4837                 return (sz * zone->uz_size);
4838         }
4839         for (i = 0; i < vm_ndomains; i++)
4840                 sz += zone->uz_keg->uk_domain[i].ud_pages;
4841
4842         return (sz * PAGE_SIZE);
4843 }
4844
4845 /* See uma.h */
4846 void
4847 uma_reclaim(int req)
4848 {
4849
4850         CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
4851         sx_xlock(&uma_reclaim_lock);
4852         bucket_enable();
4853
4854         switch (req) {
4855         case UMA_RECLAIM_TRIM:
4856                 zone_foreach(zone_trim, NULL);
4857                 break;
4858         case UMA_RECLAIM_DRAIN:
4859         case UMA_RECLAIM_DRAIN_CPU:
4860                 zone_foreach(zone_drain, NULL);
4861                 if (req == UMA_RECLAIM_DRAIN_CPU) {
4862                         pcpu_cache_drain_safe(NULL);
4863                         zone_foreach(zone_drain, NULL);
4864                 }
4865                 break;
4866         default:
4867                 panic("unhandled reclamation request %d", req);
4868         }
4869
4870         /*
4871          * Some slabs may have been freed but this zone will be visited early
4872          * we visit again so that we can free pages that are empty once other
4873          * zones are drained.  We have to do the same for buckets.
4874          */
4875         zone_drain(slabzones[0], NULL);
4876         zone_drain(slabzones[1], NULL);
4877         bucket_zone_drain();
4878         sx_xunlock(&uma_reclaim_lock);
4879 }
4880
4881 static volatile int uma_reclaim_needed;
4882
4883 void
4884 uma_reclaim_wakeup(void)
4885 {
4886
4887         if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
4888                 wakeup(uma_reclaim);
4889 }
4890
4891 void
4892 uma_reclaim_worker(void *arg __unused)
4893 {
4894
4895         for (;;) {
4896                 sx_xlock(&uma_reclaim_lock);
4897                 while (atomic_load_int(&uma_reclaim_needed) == 0)
4898                         sx_sleep(uma_reclaim, &uma_reclaim_lock, PVM, "umarcl",
4899                             hz);
4900                 sx_xunlock(&uma_reclaim_lock);
4901                 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
4902                 uma_reclaim(UMA_RECLAIM_DRAIN_CPU);
4903                 atomic_store_int(&uma_reclaim_needed, 0);
4904                 /* Don't fire more than once per-second. */
4905                 pause("umarclslp", hz);
4906         }
4907 }
4908
4909 /* See uma.h */
4910 void
4911 uma_zone_reclaim(uma_zone_t zone, int req)
4912 {
4913
4914         switch (req) {
4915         case UMA_RECLAIM_TRIM:
4916                 zone_trim(zone, NULL);
4917                 break;
4918         case UMA_RECLAIM_DRAIN:
4919                 zone_drain(zone, NULL);
4920                 break;
4921         case UMA_RECLAIM_DRAIN_CPU:
4922                 pcpu_cache_drain_safe(zone);
4923                 zone_drain(zone, NULL);
4924                 break;
4925         default:
4926                 panic("unhandled reclamation request %d", req);
4927         }
4928 }
4929
4930 /* See uma.h */
4931 int
4932 uma_zone_exhausted(uma_zone_t zone)
4933 {
4934
4935         return (atomic_load_32(&zone->uz_sleepers) > 0);
4936 }
4937
4938 unsigned long
4939 uma_limit(void)
4940 {
4941
4942         return (uma_kmem_limit);
4943 }
4944
4945 void
4946 uma_set_limit(unsigned long limit)
4947 {
4948
4949         uma_kmem_limit = limit;
4950 }
4951
4952 unsigned long
4953 uma_size(void)
4954 {
4955
4956         return (atomic_load_long(&uma_kmem_total));
4957 }
4958
4959 long
4960 uma_avail(void)
4961 {
4962
4963         return (uma_kmem_limit - uma_size());
4964 }
4965
4966 #ifdef DDB
4967 /*
4968  * Generate statistics across both the zone and its per-cpu cache's.  Return
4969  * desired statistics if the pointer is non-NULL for that statistic.
4970  *
4971  * Note: does not update the zone statistics, as it can't safely clear the
4972  * per-CPU cache statistic.
4973  *
4974  */
4975 static void
4976 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
4977     uint64_t *freesp, uint64_t *sleepsp, uint64_t *xdomainp)
4978 {
4979         uma_cache_t cache;
4980         uint64_t allocs, frees, sleeps, xdomain;
4981         int cachefree, cpu;
4982
4983         allocs = frees = sleeps = xdomain = 0;
4984         cachefree = 0;
4985         CPU_FOREACH(cpu) {
4986                 cache = &z->uz_cpu[cpu];
4987                 cachefree += cache->uc_allocbucket.ucb_cnt;
4988                 cachefree += cache->uc_freebucket.ucb_cnt;
4989                 xdomain += cache->uc_crossbucket.ucb_cnt;
4990                 cachefree += cache->uc_crossbucket.ucb_cnt;
4991                 allocs += cache->uc_allocs;
4992                 frees += cache->uc_frees;
4993         }
4994         allocs += counter_u64_fetch(z->uz_allocs);
4995         frees += counter_u64_fetch(z->uz_frees);
4996         xdomain += counter_u64_fetch(z->uz_xdomain);
4997         sleeps += z->uz_sleeps;
4998         if (cachefreep != NULL)
4999                 *cachefreep = cachefree;
5000         if (allocsp != NULL)
5001                 *allocsp = allocs;
5002         if (freesp != NULL)
5003                 *freesp = frees;
5004         if (sleepsp != NULL)
5005                 *sleepsp = sleeps;
5006         if (xdomainp != NULL)
5007                 *xdomainp = xdomain;
5008 }
5009 #endif /* DDB */
5010
5011 static int
5012 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
5013 {
5014         uma_keg_t kz;
5015         uma_zone_t z;
5016         int count;
5017
5018         count = 0;
5019         rw_rlock(&uma_rwlock);
5020         LIST_FOREACH(kz, &uma_kegs, uk_link) {
5021                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
5022                         count++;
5023         }
5024         LIST_FOREACH(z, &uma_cachezones, uz_link)
5025                 count++;
5026
5027         rw_runlock(&uma_rwlock);
5028         return (sysctl_handle_int(oidp, &count, 0, req));
5029 }
5030
5031 static void
5032 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
5033     struct uma_percpu_stat *ups, bool internal)
5034 {
5035         uma_zone_domain_t zdom;
5036         uma_cache_t cache;
5037         int i;
5038
5039         for (i = 0; i < vm_ndomains; i++) {
5040                 zdom = ZDOM_GET(z, i);
5041                 uth->uth_zone_free += zdom->uzd_nitems;
5042         }
5043         uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
5044         uth->uth_frees = counter_u64_fetch(z->uz_frees);
5045         uth->uth_fails = counter_u64_fetch(z->uz_fails);
5046         uth->uth_xdomain = counter_u64_fetch(z->uz_xdomain);
5047         uth->uth_sleeps = z->uz_sleeps;
5048
5049         for (i = 0; i < mp_maxid + 1; i++) {
5050                 bzero(&ups[i], sizeof(*ups));
5051                 if (internal || CPU_ABSENT(i))
5052                         continue;
5053                 cache = &z->uz_cpu[i];
5054                 ups[i].ups_cache_free += cache->uc_allocbucket.ucb_cnt;
5055                 ups[i].ups_cache_free += cache->uc_freebucket.ucb_cnt;
5056                 ups[i].ups_cache_free += cache->uc_crossbucket.ucb_cnt;
5057                 ups[i].ups_allocs = cache->uc_allocs;
5058                 ups[i].ups_frees = cache->uc_frees;
5059         }
5060 }
5061
5062 static int
5063 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
5064 {
5065         struct uma_stream_header ush;
5066         struct uma_type_header uth;
5067         struct uma_percpu_stat *ups;
5068         struct sbuf sbuf;
5069         uma_keg_t kz;
5070         uma_zone_t z;
5071         uint64_t items;
5072         uint32_t kfree, pages;
5073         int count, error, i;
5074
5075         error = sysctl_wire_old_buffer(req, 0);
5076         if (error != 0)
5077                 return (error);
5078         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
5079         sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
5080         ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
5081
5082         count = 0;
5083         rw_rlock(&uma_rwlock);
5084         LIST_FOREACH(kz, &uma_kegs, uk_link) {
5085                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
5086                         count++;
5087         }
5088
5089         LIST_FOREACH(z, &uma_cachezones, uz_link)
5090                 count++;
5091
5092         /*
5093          * Insert stream header.
5094          */
5095         bzero(&ush, sizeof(ush));
5096         ush.ush_version = UMA_STREAM_VERSION;
5097         ush.ush_maxcpus = (mp_maxid + 1);
5098         ush.ush_count = count;
5099         (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
5100
5101         LIST_FOREACH(kz, &uma_kegs, uk_link) {
5102                 kfree = pages = 0;
5103                 for (i = 0; i < vm_ndomains; i++) {
5104                         kfree += kz->uk_domain[i].ud_free_items;
5105                         pages += kz->uk_domain[i].ud_pages;
5106                 }
5107                 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5108                         bzero(&uth, sizeof(uth));
5109                         strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5110                         uth.uth_align = kz->uk_align;
5111                         uth.uth_size = kz->uk_size;
5112                         uth.uth_rsize = kz->uk_rsize;
5113                         if (z->uz_max_items > 0) {
5114                                 items = UZ_ITEMS_COUNT(z->uz_items);
5115                                 uth.uth_pages = (items / kz->uk_ipers) *
5116                                         kz->uk_ppera;
5117                         } else
5118                                 uth.uth_pages = pages;
5119                         uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
5120                             kz->uk_ppera;
5121                         uth.uth_limit = z->uz_max_items;
5122                         uth.uth_keg_free = kfree;
5123
5124                         /*
5125                          * A zone is secondary is it is not the first entry
5126                          * on the keg's zone list.
5127                          */
5128                         if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
5129                             (LIST_FIRST(&kz->uk_zones) != z))
5130                                 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
5131                         uma_vm_zone_stats(&uth, z, &sbuf, ups,
5132                             kz->uk_flags & UMA_ZFLAG_INTERNAL);
5133                         (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5134                         for (i = 0; i < mp_maxid + 1; i++)
5135                                 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5136                 }
5137         }
5138         LIST_FOREACH(z, &uma_cachezones, uz_link) {
5139                 bzero(&uth, sizeof(uth));
5140                 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5141                 uth.uth_size = z->uz_size;
5142                 uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
5143                 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5144                 for (i = 0; i < mp_maxid + 1; i++)
5145                         (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5146         }
5147
5148         rw_runlock(&uma_rwlock);
5149         error = sbuf_finish(&sbuf);
5150         sbuf_delete(&sbuf);
5151         free(ups, M_TEMP);
5152         return (error);
5153 }
5154
5155 int
5156 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
5157 {
5158         uma_zone_t zone = *(uma_zone_t *)arg1;
5159         int error, max;
5160
5161         max = uma_zone_get_max(zone);
5162         error = sysctl_handle_int(oidp, &max, 0, req);
5163         if (error || !req->newptr)
5164                 return (error);
5165
5166         uma_zone_set_max(zone, max);
5167
5168         return (0);
5169 }
5170
5171 int
5172 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
5173 {
5174         uma_zone_t zone;
5175         int cur;
5176
5177         /*
5178          * Some callers want to add sysctls for global zones that
5179          * may not yet exist so they pass a pointer to a pointer.
5180          */
5181         if (arg2 == 0)
5182                 zone = *(uma_zone_t *)arg1;
5183         else
5184                 zone = arg1;
5185         cur = uma_zone_get_cur(zone);
5186         return (sysctl_handle_int(oidp, &cur, 0, req));
5187 }
5188
5189 static int
5190 sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS)
5191 {
5192         uma_zone_t zone = arg1;
5193         uint64_t cur;
5194
5195         cur = uma_zone_get_allocs(zone);
5196         return (sysctl_handle_64(oidp, &cur, 0, req));
5197 }
5198
5199 static int
5200 sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS)
5201 {
5202         uma_zone_t zone = arg1;
5203         uint64_t cur;
5204
5205         cur = uma_zone_get_frees(zone);
5206         return (sysctl_handle_64(oidp, &cur, 0, req));
5207 }
5208
5209 static int
5210 sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS)
5211 {
5212         struct sbuf sbuf;
5213         uma_zone_t zone = arg1;
5214         int error;
5215
5216         sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
5217         if (zone->uz_flags != 0)
5218                 sbuf_printf(&sbuf, "0x%b", zone->uz_flags, PRINT_UMA_ZFLAGS);
5219         else
5220                 sbuf_printf(&sbuf, "0");
5221         error = sbuf_finish(&sbuf);
5222         sbuf_delete(&sbuf);
5223
5224         return (error);
5225 }
5226
5227 static int
5228 sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS)
5229 {
5230         uma_keg_t keg = arg1;
5231         int avail, effpct, total;
5232
5233         total = keg->uk_ppera * PAGE_SIZE;
5234         if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
5235                 total += slabzone(keg->uk_ipers)->uz_keg->uk_rsize;
5236         /*
5237          * We consider the client's requested size and alignment here, not the
5238          * real size determination uk_rsize, because we also adjust the real
5239          * size for internal implementation reasons (max bitset size).
5240          */
5241         avail = keg->uk_ipers * roundup2(keg->uk_size, keg->uk_align + 1);
5242         if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
5243                 avail *= mp_maxid + 1;
5244         effpct = 100 * avail / total;
5245         return (sysctl_handle_int(oidp, &effpct, 0, req));
5246 }
5247
5248 static int
5249 sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS)
5250 {
5251         uma_zone_t zone = arg1;
5252         uint64_t cur;
5253
5254         cur = UZ_ITEMS_COUNT(atomic_load_64(&zone->uz_items));
5255         return (sysctl_handle_64(oidp, &cur, 0, req));
5256 }
5257
5258 #ifdef INVARIANTS
5259 static uma_slab_t
5260 uma_dbg_getslab(uma_zone_t zone, void *item)
5261 {
5262         uma_slab_t slab;
5263         uma_keg_t keg;
5264         uint8_t *mem;
5265
5266         /*
5267          * It is safe to return the slab here even though the
5268          * zone is unlocked because the item's allocation state
5269          * essentially holds a reference.
5270          */
5271         mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
5272         if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5273                 return (NULL);
5274         if (zone->uz_flags & UMA_ZFLAG_VTOSLAB)
5275                 return (vtoslab((vm_offset_t)mem));
5276         keg = zone->uz_keg;
5277         if ((keg->uk_flags & UMA_ZFLAG_HASH) == 0)
5278                 return ((uma_slab_t)(mem + keg->uk_pgoff));
5279         KEG_LOCK(keg, 0);
5280         slab = hash_sfind(&keg->uk_hash, mem);
5281         KEG_UNLOCK(keg, 0);
5282
5283         return (slab);
5284 }
5285
5286 static bool
5287 uma_dbg_zskip(uma_zone_t zone, void *mem)
5288 {
5289
5290         if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5291                 return (true);
5292
5293         return (uma_dbg_kskip(zone->uz_keg, mem));
5294 }
5295
5296 static bool
5297 uma_dbg_kskip(uma_keg_t keg, void *mem)
5298 {
5299         uintptr_t idx;
5300
5301         if (dbg_divisor == 0)
5302                 return (true);
5303
5304         if (dbg_divisor == 1)
5305                 return (false);
5306
5307         idx = (uintptr_t)mem >> PAGE_SHIFT;
5308         if (keg->uk_ipers > 1) {
5309                 idx *= keg->uk_ipers;
5310                 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
5311         }
5312
5313         if ((idx / dbg_divisor) * dbg_divisor != idx) {
5314                 counter_u64_add(uma_skip_cnt, 1);
5315                 return (true);
5316         }
5317         counter_u64_add(uma_dbg_cnt, 1);
5318
5319         return (false);
5320 }
5321
5322 /*
5323  * Set up the slab's freei data such that uma_dbg_free can function.
5324  *
5325  */
5326 static void
5327 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
5328 {
5329         uma_keg_t keg;
5330         int freei;
5331
5332         if (slab == NULL) {
5333                 slab = uma_dbg_getslab(zone, item);
5334                 if (slab == NULL) 
5335                         panic("uma: item %p did not belong to zone %s",
5336                             item, zone->uz_name);
5337         }
5338         keg = zone->uz_keg;
5339         freei = slab_item_index(slab, keg, item);
5340
5341         if (BIT_ISSET(keg->uk_ipers, freei, slab_dbg_bits(slab, keg)))
5342                 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)",
5343                     item, zone, zone->uz_name, slab, freei);
5344         BIT_SET_ATOMIC(keg->uk_ipers, freei, slab_dbg_bits(slab, keg));
5345 }
5346
5347 /*
5348  * Verifies freed addresses.  Checks for alignment, valid slab membership
5349  * and duplicate frees.
5350  *
5351  */
5352 static void
5353 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
5354 {
5355         uma_keg_t keg;
5356         int freei;
5357
5358         if (slab == NULL) {
5359                 slab = uma_dbg_getslab(zone, item);
5360                 if (slab == NULL) 
5361                         panic("uma: Freed item %p did not belong to zone %s",
5362                             item, zone->uz_name);
5363         }
5364         keg = zone->uz_keg;
5365         freei = slab_item_index(slab, keg, item);
5366
5367         if (freei >= keg->uk_ipers)
5368                 panic("Invalid free of %p from zone %p(%s) slab %p(%d)",
5369                     item, zone, zone->uz_name, slab, freei);
5370
5371         if (slab_item(slab, keg, freei) != item)
5372                 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)",
5373                     item, zone, zone->uz_name, slab, freei);
5374
5375         if (!BIT_ISSET(keg->uk_ipers, freei, slab_dbg_bits(slab, keg)))
5376                 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)",
5377                     item, zone, zone->uz_name, slab, freei);
5378
5379         BIT_CLR_ATOMIC(keg->uk_ipers, freei, slab_dbg_bits(slab, keg));
5380 }
5381 #endif /* INVARIANTS */
5382
5383 #ifdef DDB
5384 static int64_t
5385 get_uma_stats(uma_keg_t kz, uma_zone_t z, uint64_t *allocs, uint64_t *used,
5386     uint64_t *sleeps, long *cachefree, uint64_t *xdomain)
5387 {
5388         uint64_t frees;
5389         int i;
5390
5391         if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
5392                 *allocs = counter_u64_fetch(z->uz_allocs);
5393                 frees = counter_u64_fetch(z->uz_frees);
5394                 *sleeps = z->uz_sleeps;
5395                 *cachefree = 0;
5396                 *xdomain = 0;
5397         } else
5398                 uma_zone_sumstat(z, cachefree, allocs, &frees, sleeps,
5399                     xdomain);
5400         for (i = 0; i < vm_ndomains; i++) {
5401                 *cachefree += ZDOM_GET(z, i)->uzd_nitems;
5402                 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
5403                     (LIST_FIRST(&kz->uk_zones) != z)))
5404                         *cachefree += kz->uk_domain[i].ud_free_items;
5405         }
5406         *used = *allocs - frees;
5407         return (((int64_t)*used + *cachefree) * kz->uk_size);
5408 }
5409
5410 DB_SHOW_COMMAND(uma, db_show_uma)
5411 {
5412         const char *fmt_hdr, *fmt_entry;
5413         uma_keg_t kz;
5414         uma_zone_t z;
5415         uint64_t allocs, used, sleeps, xdomain;
5416         long cachefree;
5417         /* variables for sorting */
5418         uma_keg_t cur_keg;
5419         uma_zone_t cur_zone, last_zone;
5420         int64_t cur_size, last_size, size;
5421         int ties;
5422
5423         /* /i option produces machine-parseable CSV output */
5424         if (modif[0] == 'i') {
5425                 fmt_hdr = "%s,%s,%s,%s,%s,%s,%s,%s,%s\n";
5426                 fmt_entry = "\"%s\",%ju,%jd,%ld,%ju,%ju,%u,%jd,%ju\n";
5427         } else {
5428                 fmt_hdr = "%18s %6s %7s %7s %11s %7s %7s %10s %8s\n";
5429                 fmt_entry = "%18s %6ju %7jd %7ld %11ju %7ju %7u %10jd %8ju\n";
5430         }
5431
5432         db_printf(fmt_hdr, "Zone", "Size", "Used", "Free", "Requests",
5433             "Sleeps", "Bucket", "Total Mem", "XFree");
5434
5435         /* Sort the zones with largest size first. */
5436         last_zone = NULL;
5437         last_size = INT64_MAX;
5438         for (;;) {
5439                 cur_zone = NULL;
5440                 cur_size = -1;
5441                 ties = 0;
5442                 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5443                         LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5444                                 /*
5445                                  * In the case of size ties, print out zones
5446                                  * in the order they are encountered.  That is,
5447                                  * when we encounter the most recently output
5448                                  * zone, we have already printed all preceding
5449                                  * ties, and we must print all following ties.
5450                                  */
5451                                 if (z == last_zone) {
5452                                         ties = 1;
5453                                         continue;
5454                                 }
5455                                 size = get_uma_stats(kz, z, &allocs, &used,
5456                                     &sleeps, &cachefree, &xdomain);
5457                                 if (size > cur_size && size < last_size + ties)
5458                                 {
5459                                         cur_size = size;
5460                                         cur_zone = z;
5461                                         cur_keg = kz;
5462                                 }
5463                         }
5464                 }
5465                 if (cur_zone == NULL)
5466                         break;
5467
5468                 size = get_uma_stats(cur_keg, cur_zone, &allocs, &used,
5469                     &sleeps, &cachefree, &xdomain);
5470                 db_printf(fmt_entry, cur_zone->uz_name,
5471                     (uintmax_t)cur_keg->uk_size, (intmax_t)used, cachefree,
5472                     (uintmax_t)allocs, (uintmax_t)sleeps,
5473                     (unsigned)cur_zone->uz_bucket_size, (intmax_t)size,
5474                     xdomain);
5475
5476                 if (db_pager_quit)
5477                         return;
5478                 last_zone = cur_zone;
5479                 last_size = cur_size;
5480         }
5481 }
5482
5483 DB_SHOW_COMMAND(umacache, db_show_umacache)
5484 {
5485         uma_zone_t z;
5486         uint64_t allocs, frees;
5487         long cachefree;
5488         int i;
5489
5490         db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
5491             "Requests", "Bucket");
5492         LIST_FOREACH(z, &uma_cachezones, uz_link) {
5493                 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL, NULL);
5494                 for (i = 0; i < vm_ndomains; i++)
5495                         cachefree += ZDOM_GET(z, i)->uzd_nitems;
5496                 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
5497                     z->uz_name, (uintmax_t)z->uz_size,
5498                     (intmax_t)(allocs - frees), cachefree,
5499                     (uintmax_t)allocs, z->uz_bucket_size);
5500                 if (db_pager_quit)
5501                         return;
5502         }
5503 }
5504 #endif  /* DDB */