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