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