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