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