]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/uma_core.c
Add two new kernel options to control memory locality on NUMA hardware.
[FreeBSD/FreeBSD.git] / sys / vm / uma_core.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002-2005, 2009, 2013 Jeffrey Roberson <jeff@FreeBSD.org>
5  * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
6  * Copyright (c) 2004-2006 Robert N. M. Watson
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice unmodified, this list of conditions, and the following
14  *    disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 /*
32  * uma_core.c  Implementation of the Universal Memory allocator
33  *
34  * This allocator is intended to replace the multitude of similar object caches
35  * in the standard FreeBSD kernel.  The intent is to be flexible as well as
36  * efficient.  A primary design goal is to return unused memory to the rest of
37  * the system.  This will make the system as a whole more flexible due to the
38  * ability to move memory to subsystems which most need it instead of leaving
39  * pools of reserved memory unused.
40  *
41  * The basic ideas stem from similar slab/zone based allocators whose algorithms
42  * are well known.
43  *
44  */
45
46 /*
47  * TODO:
48  *      - Improve memory usage for large allocations
49  *      - Investigate cache size adjustments
50  */
51
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
54
55 #include "opt_ddb.h"
56 #include "opt_param.h"
57 #include "opt_vm.h"
58
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bitset.h>
62 #include <sys/domainset.h>
63 #include <sys/eventhandler.h>
64 #include <sys/kernel.h>
65 #include <sys/types.h>
66 #include <sys/limits.h>
67 #include <sys/queue.h>
68 #include <sys/malloc.h>
69 #include <sys/ktr.h>
70 #include <sys/lock.h>
71 #include <sys/sysctl.h>
72 #include <sys/mutex.h>
73 #include <sys/proc.h>
74 #include <sys/random.h>
75 #include <sys/rwlock.h>
76 #include <sys/sbuf.h>
77 #include <sys/sched.h>
78 #include <sys/smp.h>
79 #include <sys/taskqueue.h>
80 #include <sys/vmmeter.h>
81
82 #include <vm/vm.h>
83 #include <vm/vm_domainset.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pageout.h>
87 #include <vm/vm_param.h>
88 #include <vm/vm_phys.h>
89 #include <vm/vm_pagequeue.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
93 #include <vm/uma.h>
94 #include <vm/uma_int.h>
95 #include <vm/uma_dbg.h>
96
97 #include <ddb/ddb.h>
98
99 #ifdef DEBUG_MEMGUARD
100 #include <vm/memguard.h>
101 #endif
102
103 /*
104  * This is the zone and keg from which all zones are spawned.
105  */
106 static uma_zone_t kegs;
107 static uma_zone_t zones;
108
109 /* This is the zone from which all offpage uma_slab_ts are allocated. */
110 static uma_zone_t slabzone;
111
112 /*
113  * The initial hash tables come out of this zone so they can be allocated
114  * prior to malloc coming up.
115  */
116 static uma_zone_t hashzone;
117
118 /* The boot-time adjusted value for cache line alignment. */
119 int uma_align_cache = 64 - 1;
120
121 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
122
123 /*
124  * Are we allowed to allocate buckets?
125  */
126 static int bucketdisable = 1;
127
128 /* Linked list of all kegs in the system */
129 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
130
131 /* Linked list of all cache-only zones in the system */
132 static LIST_HEAD(,uma_zone) uma_cachezones =
133     LIST_HEAD_INITIALIZER(uma_cachezones);
134
135 /* This RW lock protects the keg list */
136 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
137
138 /*
139  * Pointer and counter to pool of pages, that is preallocated at
140  * startup to bootstrap UMA.
141  */
142 static char *bootmem;
143 static int boot_pages;
144
145 static struct sx uma_drain_lock;
146
147 /*
148  * kmem soft limit, initialized by uma_set_limit().  Ensure that early
149  * allocations don't trigger a wakeup of the reclaim thread.
150  */
151 static unsigned long uma_kmem_limit = LONG_MAX;
152 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_limit, CTLFLAG_RD, &uma_kmem_limit, 0,
153     "UMA kernel memory soft limit");
154 static unsigned long uma_kmem_total;
155 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_total, CTLFLAG_RD, &uma_kmem_total, 0,
156     "UMA kernel memory usage");
157
158 /* Is the VM done starting up? */
159 static enum { BOOT_COLD = 0, BOOT_STRAPPED, BOOT_PAGEALLOC, BOOT_BUCKETS,
160     BOOT_RUNNING } booted = BOOT_COLD;
161
162 /*
163  * This is the handle used to schedule events that need to happen
164  * outside of the allocation fast path.
165  */
166 static struct callout uma_callout;
167 #define UMA_TIMEOUT     20              /* Seconds for callout interval. */
168
169 /*
170  * This structure is passed as the zone ctor arg so that I don't have to create
171  * a special allocation function just for zones.
172  */
173 struct uma_zctor_args {
174         const char *name;
175         size_t size;
176         uma_ctor ctor;
177         uma_dtor dtor;
178         uma_init uminit;
179         uma_fini fini;
180         uma_import import;
181         uma_release release;
182         void *arg;
183         uma_keg_t keg;
184         int align;
185         uint32_t flags;
186 };
187
188 struct uma_kctor_args {
189         uma_zone_t zone;
190         size_t size;
191         uma_init uminit;
192         uma_fini fini;
193         int align;
194         uint32_t flags;
195 };
196
197 struct uma_bucket_zone {
198         uma_zone_t      ubz_zone;
199         char            *ubz_name;
200         int             ubz_entries;    /* Number of items it can hold. */
201         int             ubz_maxsize;    /* Maximum allocation size per-item. */
202 };
203
204 /*
205  * Compute the actual number of bucket entries to pack them in power
206  * of two sizes for more efficient space utilization.
207  */
208 #define BUCKET_SIZE(n)                                          \
209     (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
210
211 #define BUCKET_MAX      BUCKET_SIZE(256)
212
213 struct uma_bucket_zone bucket_zones[] = {
214         { NULL, "4 Bucket", BUCKET_SIZE(4), 4096 },
215         { NULL, "6 Bucket", BUCKET_SIZE(6), 3072 },
216         { NULL, "8 Bucket", BUCKET_SIZE(8), 2048 },
217         { NULL, "12 Bucket", BUCKET_SIZE(12), 1536 },
218         { NULL, "16 Bucket", BUCKET_SIZE(16), 1024 },
219         { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
220         { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
221         { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
222         { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
223         { NULL, NULL, 0}
224 };
225
226 /*
227  * Flags and enumerations to be passed to internal functions.
228  */
229 enum zfreeskip {
230         SKIP_NONE =     0,
231         SKIP_CNT =      0x00000001,
232         SKIP_DTOR =     0x00010000,
233         SKIP_FINI =     0x00020000,
234 };
235
236 #define UMA_ANYDOMAIN   -1      /* Special value for domain search. */
237
238 /* Prototypes.. */
239
240 int     uma_startup_count(int);
241 void    uma_startup(void *, int);
242 void    uma_startup1(void);
243 void    uma_startup2(void);
244
245 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
246 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
247 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
248 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
249 static void page_free(void *, vm_size_t, uint8_t);
250 static void pcpu_page_free(void *, vm_size_t, uint8_t);
251 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
252 static void cache_drain(uma_zone_t);
253 static void bucket_drain(uma_zone_t, uma_bucket_t);
254 static void bucket_cache_drain(uma_zone_t zone);
255 static int keg_ctor(void *, int, void *, int);
256 static void keg_dtor(void *, int, void *);
257 static int zone_ctor(void *, int, void *, int);
258 static void zone_dtor(void *, int, void *);
259 static int zero_init(void *, int, int);
260 static void keg_small_init(uma_keg_t keg);
261 static void keg_large_init(uma_keg_t keg);
262 static void zone_foreach(void (*zfunc)(uma_zone_t));
263 static void zone_timeout(uma_zone_t zone);
264 static int hash_alloc(struct uma_hash *, u_int);
265 static int hash_expand(struct uma_hash *, struct uma_hash *);
266 static void hash_free(struct uma_hash *hash);
267 static void uma_timeout(void *);
268 static void uma_startup3(void);
269 static void *zone_alloc_item(uma_zone_t, void *, int, int);
270 static void *zone_alloc_item_locked(uma_zone_t, void *, int, int);
271 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
272 static void bucket_enable(void);
273 static void bucket_init(void);
274 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
275 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
276 static void bucket_zone_drain(void);
277 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int, int);
278 static uma_slab_t zone_fetch_slab(uma_zone_t, uma_keg_t, int, int);
279 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
280 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
281 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
282     uma_fini fini, int align, uint32_t flags);
283 static int zone_import(uma_zone_t, void **, int, int, int);
284 static void zone_release(uma_zone_t, void **, int);
285 static void uma_zero_item(void *, uma_zone_t);
286
287 void uma_print_zone(uma_zone_t);
288 void uma_print_stats(void);
289 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
290 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
291
292 #ifdef INVARIANTS
293 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
294 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
295 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
296 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
297
298 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD, 0,
299     "Memory allocation debugging");
300
301 static u_int dbg_divisor = 1;
302 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
303     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
304     "Debug & thrash every this item in memory allocator");
305
306 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
307 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
308 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
309     &uma_dbg_cnt, "memory items debugged");
310 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
311     &uma_skip_cnt, "memory items skipped, not debugged");
312 #endif
313
314 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
315
316 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
317     0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
318
319 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
320     0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
321
322 static int zone_warnings = 1;
323 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
324     "Warn when UMA zones becomes full");
325
326 /* Adjust bytes under management by UMA. */
327 static inline void
328 uma_total_dec(unsigned long size)
329 {
330
331         atomic_subtract_long(&uma_kmem_total, size);
332 }
333
334 static inline void
335 uma_total_inc(unsigned long size)
336 {
337
338         if (atomic_fetchadd_long(&uma_kmem_total, size) > uma_kmem_limit)
339                 uma_reclaim_wakeup();
340 }
341
342 /*
343  * This routine checks to see whether or not it's safe to enable buckets.
344  */
345 static void
346 bucket_enable(void)
347 {
348         bucketdisable = vm_page_count_min();
349 }
350
351 /*
352  * Initialize bucket_zones, the array of zones of buckets of various sizes.
353  *
354  * For each zone, calculate the memory required for each bucket, consisting
355  * of the header and an array of pointers.
356  */
357 static void
358 bucket_init(void)
359 {
360         struct uma_bucket_zone *ubz;
361         int size;
362
363         for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
364                 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
365                 size += sizeof(void *) * ubz->ubz_entries;
366                 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
367                     NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
368                     UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET | UMA_ZONE_NUMA);
369         }
370 }
371
372 /*
373  * Given a desired number of entries for a bucket, return the zone from which
374  * to allocate the bucket.
375  */
376 static struct uma_bucket_zone *
377 bucket_zone_lookup(int entries)
378 {
379         struct uma_bucket_zone *ubz;
380
381         for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
382                 if (ubz->ubz_entries >= entries)
383                         return (ubz);
384         ubz--;
385         return (ubz);
386 }
387
388 static int
389 bucket_select(int size)
390 {
391         struct uma_bucket_zone *ubz;
392
393         ubz = &bucket_zones[0];
394         if (size > ubz->ubz_maxsize)
395                 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
396
397         for (; ubz->ubz_entries != 0; ubz++)
398                 if (ubz->ubz_maxsize < size)
399                         break;
400         ubz--;
401         return (ubz->ubz_entries);
402 }
403
404 static uma_bucket_t
405 bucket_alloc(uma_zone_t zone, void *udata, int flags)
406 {
407         struct uma_bucket_zone *ubz;
408         uma_bucket_t bucket;
409
410         /*
411          * This is to stop us from allocating per cpu buckets while we're
412          * running out of vm.boot_pages.  Otherwise, we would exhaust the
413          * boot pages.  This also prevents us from allocating buckets in
414          * low memory situations.
415          */
416         if (bucketdisable)
417                 return (NULL);
418         /*
419          * To limit bucket recursion we store the original zone flags
420          * in a cookie passed via zalloc_arg/zfree_arg.  This allows the
421          * NOVM flag to persist even through deep recursions.  We also
422          * store ZFLAG_BUCKET once we have recursed attempting to allocate
423          * a bucket for a bucket zone so we do not allow infinite bucket
424          * recursion.  This cookie will even persist to frees of unused
425          * buckets via the allocation path or bucket allocations in the
426          * free path.
427          */
428         if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
429                 udata = (void *)(uintptr_t)zone->uz_flags;
430         else {
431                 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
432                         return (NULL);
433                 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
434         }
435         if ((uintptr_t)udata & UMA_ZFLAG_CACHEONLY)
436                 flags |= M_NOVM;
437         ubz = bucket_zone_lookup(zone->uz_count);
438         if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
439                 ubz++;
440         bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
441         if (bucket) {
442 #ifdef INVARIANTS
443                 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
444 #endif
445                 bucket->ub_cnt = 0;
446                 bucket->ub_entries = ubz->ubz_entries;
447         }
448
449         return (bucket);
450 }
451
452 static void
453 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
454 {
455         struct uma_bucket_zone *ubz;
456
457         KASSERT(bucket->ub_cnt == 0,
458             ("bucket_free: Freeing a non free bucket."));
459         if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
460                 udata = (void *)(uintptr_t)zone->uz_flags;
461         ubz = bucket_zone_lookup(bucket->ub_entries);
462         uma_zfree_arg(ubz->ubz_zone, bucket, udata);
463 }
464
465 static void
466 bucket_zone_drain(void)
467 {
468         struct uma_bucket_zone *ubz;
469
470         for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
471                 zone_drain(ubz->ubz_zone);
472 }
473
474 static uma_bucket_t
475 zone_try_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, const bool ws)
476 {
477         uma_bucket_t bucket;
478
479         ZONE_LOCK_ASSERT(zone);
480
481         if ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
482                 MPASS(zdom->uzd_nitems >= bucket->ub_cnt);
483                 LIST_REMOVE(bucket, ub_link);
484                 zdom->uzd_nitems -= bucket->ub_cnt;
485                 if (ws && zdom->uzd_imin > zdom->uzd_nitems)
486                         zdom->uzd_imin = zdom->uzd_nitems;
487                 zone->uz_bkt_count -= bucket->ub_cnt;
488         }
489         return (bucket);
490 }
491
492 static void
493 zone_put_bucket(uma_zone_t zone, uma_zone_domain_t zdom, uma_bucket_t bucket,
494     const bool ws)
495 {
496
497         ZONE_LOCK_ASSERT(zone);
498         KASSERT(zone->uz_bkt_count < zone->uz_bkt_max, ("%s: zone %p overflow",
499             __func__, zone));
500
501         LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
502         zdom->uzd_nitems += bucket->ub_cnt;
503         if (ws && zdom->uzd_imax < zdom->uzd_nitems)
504                 zdom->uzd_imax = zdom->uzd_nitems;
505         zone->uz_bkt_count += bucket->ub_cnt;
506 }
507
508 static void
509 zone_log_warning(uma_zone_t zone)
510 {
511         static const struct timeval warninterval = { 300, 0 };
512
513         if (!zone_warnings || zone->uz_warning == NULL)
514                 return;
515
516         if (ratecheck(&zone->uz_ratecheck, &warninterval))
517                 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
518 }
519
520 static inline void
521 zone_maxaction(uma_zone_t zone)
522 {
523
524         if (zone->uz_maxaction.ta_func != NULL)
525                 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
526 }
527
528 /*
529  * Routine called by timeout which is used to fire off some time interval
530  * based calculations.  (stats, hash size, etc.)
531  *
532  * Arguments:
533  *      arg   Unused
534  *
535  * Returns:
536  *      Nothing
537  */
538 static void
539 uma_timeout(void *unused)
540 {
541         bucket_enable();
542         zone_foreach(zone_timeout);
543
544         /* Reschedule this event */
545         callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
546 }
547
548 /*
549  * Update the working set size estimate for the zone's bucket cache.
550  * The constants chosen here are somewhat arbitrary.  With an update period of
551  * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
552  * last 100s.
553  */
554 static void
555 zone_domain_update_wss(uma_zone_domain_t zdom)
556 {
557         long wss;
558
559         MPASS(zdom->uzd_imax >= zdom->uzd_imin);
560         wss = zdom->uzd_imax - zdom->uzd_imin;
561         zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
562         zdom->uzd_wss = (3 * wss + 2 * zdom->uzd_wss) / 5;
563 }
564
565 /*
566  * Routine to perform timeout driven calculations.  This expands the
567  * hashes and does per cpu statistics aggregation.
568  *
569  *  Returns nothing.
570  */
571 static void
572 zone_timeout(uma_zone_t zone)
573 {
574         uma_keg_t keg = zone->uz_keg;
575         u_int slabs;
576
577         KEG_LOCK(keg);
578         /*
579          * Expand the keg hash table.
580          *
581          * This is done if the number of slabs is larger than the hash size.
582          * What I'm trying to do here is completely reduce collisions.  This
583          * may be a little aggressive.  Should I allow for two collisions max?
584          */
585         if (keg->uk_flags & UMA_ZONE_HASH &&
586             (slabs = keg->uk_pages / keg->uk_ppera) >
587              keg->uk_hash.uh_hashsize) {
588                 struct uma_hash newhash;
589                 struct uma_hash oldhash;
590                 int ret;
591
592                 /*
593                  * This is so involved because allocating and freeing
594                  * while the keg lock is held will lead to deadlock.
595                  * I have to do everything in stages and check for
596                  * races.
597                  */
598                 KEG_UNLOCK(keg);
599                 ret = hash_alloc(&newhash, 1 << fls(slabs));
600                 KEG_LOCK(keg);
601                 if (ret) {
602                         if (hash_expand(&keg->uk_hash, &newhash)) {
603                                 oldhash = keg->uk_hash;
604                                 keg->uk_hash = newhash;
605                         } else
606                                 oldhash = newhash;
607
608                         KEG_UNLOCK(keg);
609                         hash_free(&oldhash);
610                         return;
611                 }
612         }
613
614         for (int i = 0; i < vm_ndomains; i++)
615                 zone_domain_update_wss(&zone->uz_domain[i]);
616
617         KEG_UNLOCK(keg);
618 }
619
620 /*
621  * Allocate and zero fill the next sized hash table from the appropriate
622  * backing store.
623  *
624  * Arguments:
625  *      hash  A new hash structure with the old hash size in uh_hashsize
626  *
627  * Returns:
628  *      1 on success and 0 on failure.
629  */
630 static int
631 hash_alloc(struct uma_hash *hash, u_int size)
632 {
633         size_t alloc;
634
635         KASSERT(powerof2(size), ("hash size must be power of 2"));
636         if (size > UMA_HASH_SIZE_INIT)  {
637                 hash->uh_hashsize = size;
638                 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
639                 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
640                     M_UMAHASH, M_NOWAIT);
641         } else {
642                 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
643                 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
644                     UMA_ANYDOMAIN, M_WAITOK);
645                 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
646         }
647         if (hash->uh_slab_hash) {
648                 bzero(hash->uh_slab_hash, alloc);
649                 hash->uh_hashmask = hash->uh_hashsize - 1;
650                 return (1);
651         }
652
653         return (0);
654 }
655
656 /*
657  * Expands the hash table for HASH zones.  This is done from zone_timeout
658  * to reduce collisions.  This must not be done in the regular allocation
659  * path, otherwise, we can recurse on the vm while allocating pages.
660  *
661  * Arguments:
662  *      oldhash  The hash you want to expand
663  *      newhash  The hash structure for the new table
664  *
665  * Returns:
666  *      Nothing
667  *
668  * Discussion:
669  */
670 static int
671 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
672 {
673         uma_slab_t slab;
674         u_int hval;
675         u_int idx;
676
677         if (!newhash->uh_slab_hash)
678                 return (0);
679
680         if (oldhash->uh_hashsize >= newhash->uh_hashsize)
681                 return (0);
682
683         /*
684          * I need to investigate hash algorithms for resizing without a
685          * full rehash.
686          */
687
688         for (idx = 0; idx < oldhash->uh_hashsize; idx++)
689                 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
690                         slab = SLIST_FIRST(&oldhash->uh_slab_hash[idx]);
691                         SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[idx], us_hlink);
692                         hval = UMA_HASH(newhash, slab->us_data);
693                         SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
694                             slab, us_hlink);
695                 }
696
697         return (1);
698 }
699
700 /*
701  * Free the hash bucket to the appropriate backing store.
702  *
703  * Arguments:
704  *      slab_hash  The hash bucket we're freeing
705  *      hashsize   The number of entries in that hash bucket
706  *
707  * Returns:
708  *      Nothing
709  */
710 static void
711 hash_free(struct uma_hash *hash)
712 {
713         if (hash->uh_slab_hash == NULL)
714                 return;
715         if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
716                 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
717         else
718                 free(hash->uh_slab_hash, M_UMAHASH);
719 }
720
721 /*
722  * Frees all outstanding items in a bucket
723  *
724  * Arguments:
725  *      zone   The zone to free to, must be unlocked.
726  *      bucket The free/alloc bucket with items, cpu queue must be locked.
727  *
728  * Returns:
729  *      Nothing
730  */
731
732 static void
733 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
734 {
735         int i;
736
737         if (bucket == NULL)
738                 return;
739
740         if (zone->uz_fini)
741                 for (i = 0; i < bucket->ub_cnt; i++) 
742                         zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
743         zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
744         if (zone->uz_max_items > 0) {
745                 ZONE_LOCK(zone);
746                 zone->uz_items -= bucket->ub_cnt;
747                 if (zone->uz_sleepers && zone->uz_items < zone->uz_max_items)
748                         wakeup_one(zone);
749                 ZONE_UNLOCK(zone);
750         }
751         bucket->ub_cnt = 0;
752 }
753
754 /*
755  * Drains the per cpu caches for a zone.
756  *
757  * NOTE: This may only be called while the zone is being turn down, and not
758  * during normal operation.  This is necessary in order that we do not have
759  * to migrate CPUs to drain the per-CPU caches.
760  *
761  * Arguments:
762  *      zone     The zone to drain, must be unlocked.
763  *
764  * Returns:
765  *      Nothing
766  */
767 static void
768 cache_drain(uma_zone_t zone)
769 {
770         uma_cache_t cache;
771         int cpu;
772
773         /*
774          * XXX: It is safe to not lock the per-CPU caches, because we're
775          * tearing down the zone anyway.  I.e., there will be no further use
776          * of the caches at this point.
777          *
778          * XXX: It would good to be able to assert that the zone is being
779          * torn down to prevent improper use of cache_drain().
780          *
781          * XXX: We lock the zone before passing into bucket_cache_drain() as
782          * it is used elsewhere.  Should the tear-down path be made special
783          * there in some form?
784          */
785         CPU_FOREACH(cpu) {
786                 cache = &zone->uz_cpu[cpu];
787                 bucket_drain(zone, cache->uc_allocbucket);
788                 if (cache->uc_allocbucket != NULL)
789                         bucket_free(zone, cache->uc_allocbucket, NULL);
790                 cache->uc_allocbucket = NULL;
791                 bucket_drain(zone, cache->uc_freebucket);
792                 if (cache->uc_freebucket != NULL)
793                         bucket_free(zone, cache->uc_freebucket, NULL);
794                 cache->uc_freebucket = NULL;
795                 bucket_drain(zone, cache->uc_crossbucket);
796                 if (cache->uc_crossbucket != NULL)
797                         bucket_free(zone, cache->uc_crossbucket, NULL);
798                 cache->uc_crossbucket = NULL;
799         }
800         ZONE_LOCK(zone);
801         bucket_cache_drain(zone);
802         ZONE_UNLOCK(zone);
803 }
804
805 static void
806 cache_shrink(uma_zone_t zone)
807 {
808
809         if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
810                 return;
811
812         ZONE_LOCK(zone);
813         zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
814         ZONE_UNLOCK(zone);
815 }
816
817 static void
818 cache_drain_safe_cpu(uma_zone_t zone)
819 {
820         uma_cache_t cache;
821         uma_bucket_t b1, b2, b3;
822         int domain;
823
824         if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
825                 return;
826
827         b1 = b2 = b3 = NULL;
828         ZONE_LOCK(zone);
829         critical_enter();
830         if (zone->uz_flags & UMA_ZONE_NUMA)
831                 domain = PCPU_GET(domain);
832         else
833                 domain = 0;
834         cache = &zone->uz_cpu[curcpu];
835         if (cache->uc_allocbucket) {
836                 if (cache->uc_allocbucket->ub_cnt != 0)
837                         zone_put_bucket(zone, &zone->uz_domain[domain],
838                             cache->uc_allocbucket, false);
839                 else
840                         b1 = cache->uc_allocbucket;
841                 cache->uc_allocbucket = NULL;
842         }
843         if (cache->uc_freebucket) {
844                 if (cache->uc_freebucket->ub_cnt != 0)
845                         zone_put_bucket(zone, &zone->uz_domain[domain],
846                             cache->uc_freebucket, false);
847                 else
848                         b2 = cache->uc_freebucket;
849                 cache->uc_freebucket = NULL;
850         }
851         b3 = cache->uc_crossbucket;
852         cache->uc_crossbucket = NULL;
853         critical_exit();
854         ZONE_UNLOCK(zone);
855         if (b1)
856                 bucket_free(zone, b1, NULL);
857         if (b2)
858                 bucket_free(zone, b2, NULL);
859         if (b3) {
860                 bucket_drain(zone, b3);
861                 bucket_free(zone, b3, NULL);
862         }
863 }
864
865 /*
866  * Safely drain per-CPU caches of a zone(s) to alloc bucket.
867  * This is an expensive call because it needs to bind to all CPUs
868  * one by one and enter a critical section on each of them in order
869  * to safely access their cache buckets.
870  * Zone lock must not be held on call this function.
871  */
872 static void
873 cache_drain_safe(uma_zone_t zone)
874 {
875         int cpu;
876
877         /*
878          * Polite bucket sizes shrinking was not enouth, shrink aggressively.
879          */
880         if (zone)
881                 cache_shrink(zone);
882         else
883                 zone_foreach(cache_shrink);
884
885         CPU_FOREACH(cpu) {
886                 thread_lock(curthread);
887                 sched_bind(curthread, cpu);
888                 thread_unlock(curthread);
889
890                 if (zone)
891                         cache_drain_safe_cpu(zone);
892                 else
893                         zone_foreach(cache_drain_safe_cpu);
894         }
895         thread_lock(curthread);
896         sched_unbind(curthread);
897         thread_unlock(curthread);
898 }
899
900 /*
901  * Drain the cached buckets from a zone.  Expects a locked zone on entry.
902  */
903 static void
904 bucket_cache_drain(uma_zone_t zone)
905 {
906         uma_zone_domain_t zdom;
907         uma_bucket_t bucket;
908         int i;
909
910         /*
911          * Drain the bucket queues and free the buckets.
912          */
913         for (i = 0; i < vm_ndomains; i++) {
914                 zdom = &zone->uz_domain[i];
915                 while ((bucket = zone_try_fetch_bucket(zone, zdom, false)) !=
916                     NULL) {
917                         ZONE_UNLOCK(zone);
918                         bucket_drain(zone, bucket);
919                         bucket_free(zone, bucket, NULL);
920                         ZONE_LOCK(zone);
921                 }
922         }
923
924         /*
925          * Shrink further bucket sizes.  Price of single zone lock collision
926          * is probably lower then price of global cache drain.
927          */
928         if (zone->uz_count > zone->uz_count_min)
929                 zone->uz_count--;
930 }
931
932 static void
933 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
934 {
935         uint8_t *mem;
936         int i;
937         uint8_t flags;
938
939         CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
940             keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
941
942         mem = slab->us_data;
943         flags = slab->us_flags;
944         i = start;
945         if (keg->uk_fini != NULL) {
946                 for (i--; i > -1; i--)
947 #ifdef INVARIANTS
948                 /*
949                  * trash_fini implies that dtor was trash_dtor. trash_fini
950                  * would check that memory hasn't been modified since free,
951                  * which executed trash_dtor.
952                  * That's why we need to run uma_dbg_kskip() check here,
953                  * albeit we don't make skip check for other init/fini
954                  * invocations.
955                  */
956                 if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
957                     keg->uk_fini != trash_fini)
958 #endif
959                         keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
960                             keg->uk_size);
961         }
962         if (keg->uk_flags & UMA_ZONE_OFFPAGE)
963                 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
964         keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
965         uma_total_dec(PAGE_SIZE * keg->uk_ppera);
966 }
967
968 /*
969  * Frees pages from a keg back to the system.  This is done on demand from
970  * the pageout daemon.
971  *
972  * Returns nothing.
973  */
974 static void
975 keg_drain(uma_keg_t keg)
976 {
977         struct slabhead freeslabs = { 0 };
978         uma_domain_t dom;
979         uma_slab_t slab, tmp;
980         int i;
981
982         /*
983          * We don't want to take pages from statically allocated kegs at this
984          * time
985          */
986         if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
987                 return;
988
989         CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
990             keg->uk_name, keg, keg->uk_free);
991         KEG_LOCK(keg);
992         if (keg->uk_free == 0)
993                 goto finished;
994
995         for (i = 0; i < vm_ndomains; i++) {
996                 dom = &keg->uk_domain[i];
997                 LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
998                         /* We have nowhere to free these to. */
999                         if (slab->us_flags & UMA_SLAB_BOOT)
1000                                 continue;
1001
1002                         LIST_REMOVE(slab, us_link);
1003                         keg->uk_pages -= keg->uk_ppera;
1004                         keg->uk_free -= keg->uk_ipers;
1005
1006                         if (keg->uk_flags & UMA_ZONE_HASH)
1007                                 UMA_HASH_REMOVE(&keg->uk_hash, slab,
1008                                     slab->us_data);
1009
1010                         SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
1011                 }
1012         }
1013
1014 finished:
1015         KEG_UNLOCK(keg);
1016
1017         while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
1018                 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
1019                 keg_free_slab(keg, slab, keg->uk_ipers);
1020         }
1021 }
1022
1023 static void
1024 zone_drain_wait(uma_zone_t zone, int waitok)
1025 {
1026
1027         /*
1028          * Set draining to interlock with zone_dtor() so we can release our
1029          * locks as we go.  Only dtor() should do a WAITOK call since it
1030          * is the only call that knows the structure will still be available
1031          * when it wakes up.
1032          */
1033         ZONE_LOCK(zone);
1034         while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
1035                 if (waitok == M_NOWAIT)
1036                         goto out;
1037                 msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
1038         }
1039         zone->uz_flags |= UMA_ZFLAG_DRAINING;
1040         bucket_cache_drain(zone);
1041         ZONE_UNLOCK(zone);
1042         /*
1043          * The DRAINING flag protects us from being freed while
1044          * we're running.  Normally the uma_rwlock would protect us but we
1045          * must be able to release and acquire the right lock for each keg.
1046          */
1047         keg_drain(zone->uz_keg);
1048         ZONE_LOCK(zone);
1049         zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
1050         wakeup(zone);
1051 out:
1052         ZONE_UNLOCK(zone);
1053 }
1054
1055 void
1056 zone_drain(uma_zone_t zone)
1057 {
1058
1059         zone_drain_wait(zone, M_NOWAIT);
1060 }
1061
1062 /*
1063  * Allocate a new slab for a keg.  This does not insert the slab onto a list.
1064  * If the allocation was successful, the keg lock will be held upon return,
1065  * otherwise the keg will be left unlocked.
1066  *
1067  * Arguments:
1068  *      flags   Wait flags for the item initialization routine
1069  *      aflags  Wait flags for the slab allocation
1070  *
1071  * Returns:
1072  *      The slab that was allocated or NULL if there is no memory and the
1073  *      caller specified M_NOWAIT.
1074  */
1075 static uma_slab_t
1076 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1077     int aflags)
1078 {
1079         uma_alloc allocf;
1080         uma_slab_t slab;
1081         unsigned long size;
1082         uint8_t *mem;
1083         uint8_t sflags;
1084         int i;
1085
1086         KASSERT(domain >= 0 && domain < vm_ndomains,
1087             ("keg_alloc_slab: domain %d out of range", domain));
1088         KEG_LOCK_ASSERT(keg);
1089         MPASS(zone->uz_lockptr == &keg->uk_lock);
1090
1091         allocf = keg->uk_allocf;
1092         KEG_UNLOCK(keg);
1093
1094         slab = NULL;
1095         mem = NULL;
1096         if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1097                 slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, aflags);
1098                 if (slab == NULL)
1099                         goto out;
1100         }
1101
1102         /*
1103          * This reproduces the old vm_zone behavior of zero filling pages the
1104          * first time they are added to a zone.
1105          *
1106          * Malloced items are zeroed in uma_zalloc.
1107          */
1108
1109         if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1110                 aflags |= M_ZERO;
1111         else
1112                 aflags &= ~M_ZERO;
1113
1114         if (keg->uk_flags & UMA_ZONE_NODUMP)
1115                 aflags |= M_NODUMP;
1116
1117         /* zone is passed for legacy reasons. */
1118         size = keg->uk_ppera * PAGE_SIZE;
1119         mem = allocf(zone, size, domain, &sflags, aflags);
1120         if (mem == NULL) {
1121                 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1122                         zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1123                 slab = NULL;
1124                 goto out;
1125         }
1126         uma_total_inc(size);
1127
1128         /* Point the slab into the allocated memory */
1129         if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1130                 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1131
1132         if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1133                 for (i = 0; i < keg->uk_ppera; i++)
1134                         vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1135
1136         slab->us_keg = keg;
1137         slab->us_data = mem;
1138         slab->us_freecount = keg->uk_ipers;
1139         slab->us_flags = sflags;
1140         slab->us_domain = domain;
1141         BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1142 #ifdef INVARIANTS
1143         BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1144 #endif
1145
1146         if (keg->uk_init != NULL) {
1147                 for (i = 0; i < keg->uk_ipers; i++)
1148                         if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1149                             keg->uk_size, flags) != 0)
1150                                 break;
1151                 if (i != keg->uk_ipers) {
1152                         keg_free_slab(keg, slab, i);
1153                         slab = NULL;
1154                         goto out;
1155                 }
1156         }
1157         KEG_LOCK(keg);
1158
1159         CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1160             slab, keg->uk_name, keg);
1161
1162         if (keg->uk_flags & UMA_ZONE_HASH)
1163                 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1164
1165         keg->uk_pages += keg->uk_ppera;
1166         keg->uk_free += keg->uk_ipers;
1167
1168 out:
1169         return (slab);
1170 }
1171
1172 /*
1173  * This function is intended to be used early on in place of page_alloc() so
1174  * that we may use the boot time page cache to satisfy allocations before
1175  * the VM is ready.
1176  */
1177 static void *
1178 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1179     int wait)
1180 {
1181         uma_keg_t keg;
1182         void *mem;
1183         int pages;
1184
1185         keg = zone->uz_keg;
1186         /*
1187          * If we are in BOOT_BUCKETS or higher, than switch to real
1188          * allocator.  Zones with page sized slabs switch at BOOT_PAGEALLOC.
1189          */
1190         switch (booted) {
1191                 case BOOT_COLD:
1192                 case BOOT_STRAPPED:
1193                         break;
1194                 case BOOT_PAGEALLOC:
1195                         if (keg->uk_ppera > 1)
1196                                 break;
1197                 case BOOT_BUCKETS:
1198                 case BOOT_RUNNING:
1199 #ifdef UMA_MD_SMALL_ALLOC
1200                         keg->uk_allocf = (keg->uk_ppera > 1) ?
1201                             page_alloc : uma_small_alloc;
1202 #else
1203                         keg->uk_allocf = page_alloc;
1204 #endif
1205                         return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1206         }
1207
1208         /*
1209          * Check our small startup cache to see if it has pages remaining.
1210          */
1211         pages = howmany(bytes, PAGE_SIZE);
1212         KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1213         if (pages > boot_pages)
1214                 panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1215 #ifdef DIAGNOSTIC
1216         printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1217             boot_pages);
1218 #endif
1219         mem = bootmem;
1220         boot_pages -= pages;
1221         bootmem += pages * PAGE_SIZE;
1222         *pflag = UMA_SLAB_BOOT;
1223
1224         return (mem);
1225 }
1226
1227 /*
1228  * Allocates a number of pages from the system
1229  *
1230  * Arguments:
1231  *      bytes  The number of bytes requested
1232  *      wait  Shall we wait?
1233  *
1234  * Returns:
1235  *      A pointer to the alloced memory or possibly
1236  *      NULL if M_NOWAIT is set.
1237  */
1238 static void *
1239 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1240     int wait)
1241 {
1242         void *p;        /* Returned page */
1243
1244         *pflag = UMA_SLAB_KERNEL;
1245         p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1246
1247         return (p);
1248 }
1249
1250 static void *
1251 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1252     int wait)
1253 {
1254         struct pglist alloctail;
1255         vm_offset_t addr, zkva;
1256         int cpu, flags;
1257         vm_page_t p, p_next;
1258 #ifdef NUMA
1259         struct pcpu *pc;
1260 #endif
1261
1262         MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1263
1264         TAILQ_INIT(&alloctail);
1265         flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1266             malloc2vm_flags(wait);
1267         *pflag = UMA_SLAB_KERNEL;
1268         for (cpu = 0; cpu <= mp_maxid; cpu++) {
1269                 if (CPU_ABSENT(cpu)) {
1270                         p = vm_page_alloc(NULL, 0, flags);
1271                 } else {
1272 #ifndef NUMA
1273                         p = vm_page_alloc(NULL, 0, flags);
1274 #else
1275                         pc = pcpu_find(cpu);
1276                         p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1277                         if (__predict_false(p == NULL))
1278                                 p = vm_page_alloc(NULL, 0, flags);
1279 #endif
1280                 }
1281                 if (__predict_false(p == NULL))
1282                         goto fail;
1283                 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1284         }
1285         if ((addr = kva_alloc(bytes)) == 0)
1286                 goto fail;
1287         zkva = addr;
1288         TAILQ_FOREACH(p, &alloctail, listq) {
1289                 pmap_qenter(zkva, &p, 1);
1290                 zkva += PAGE_SIZE;
1291         }
1292         return ((void*)addr);
1293 fail:
1294         TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1295                 vm_page_unwire_noq(p);
1296                 vm_page_free(p);
1297         }
1298         return (NULL);
1299 }
1300
1301 /*
1302  * Allocates a number of pages from within an object
1303  *
1304  * Arguments:
1305  *      bytes  The number of bytes requested
1306  *      wait   Shall we wait?
1307  *
1308  * Returns:
1309  *      A pointer to the alloced memory or possibly
1310  *      NULL if M_NOWAIT is set.
1311  */
1312 static void *
1313 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1314     int wait)
1315 {
1316         TAILQ_HEAD(, vm_page) alloctail;
1317         u_long npages;
1318         vm_offset_t retkva, zkva;
1319         vm_page_t p, p_next;
1320         uma_keg_t keg;
1321
1322         TAILQ_INIT(&alloctail);
1323         keg = zone->uz_keg;
1324
1325         npages = howmany(bytes, PAGE_SIZE);
1326         while (npages > 0) {
1327                 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1328                     VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1329                     ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1330                     VM_ALLOC_NOWAIT));
1331                 if (p != NULL) {
1332                         /*
1333                          * Since the page does not belong to an object, its
1334                          * listq is unused.
1335                          */
1336                         TAILQ_INSERT_TAIL(&alloctail, p, listq);
1337                         npages--;
1338                         continue;
1339                 }
1340                 /*
1341                  * Page allocation failed, free intermediate pages and
1342                  * exit.
1343                  */
1344                 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1345                         vm_page_unwire_noq(p);
1346                         vm_page_free(p); 
1347                 }
1348                 return (NULL);
1349         }
1350         *flags = UMA_SLAB_PRIV;
1351         zkva = keg->uk_kva +
1352             atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1353         retkva = zkva;
1354         TAILQ_FOREACH(p, &alloctail, listq) {
1355                 pmap_qenter(zkva, &p, 1);
1356                 zkva += PAGE_SIZE;
1357         }
1358
1359         return ((void *)retkva);
1360 }
1361
1362 /*
1363  * Frees a number of pages to the system
1364  *
1365  * Arguments:
1366  *      mem   A pointer to the memory to be freed
1367  *      size  The size of the memory being freed
1368  *      flags The original p->us_flags field
1369  *
1370  * Returns:
1371  *      Nothing
1372  */
1373 static void
1374 page_free(void *mem, vm_size_t size, uint8_t flags)
1375 {
1376
1377         if ((flags & UMA_SLAB_KERNEL) == 0)
1378                 panic("UMA: page_free used with invalid flags %x", flags);
1379
1380         kmem_free((vm_offset_t)mem, size);
1381 }
1382
1383 /*
1384  * Frees pcpu zone allocations
1385  *
1386  * Arguments:
1387  *      mem   A pointer to the memory to be freed
1388  *      size  The size of the memory being freed
1389  *      flags The original p->us_flags field
1390  *
1391  * Returns:
1392  *      Nothing
1393  */
1394 static void
1395 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1396 {
1397         vm_offset_t sva, curva;
1398         vm_paddr_t paddr;
1399         vm_page_t m;
1400
1401         MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1402         sva = (vm_offset_t)mem;
1403         for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1404                 paddr = pmap_kextract(curva);
1405                 m = PHYS_TO_VM_PAGE(paddr);
1406                 vm_page_unwire_noq(m);
1407                 vm_page_free(m);
1408         }
1409         pmap_qremove(sva, size >> PAGE_SHIFT);
1410         kva_free(sva, size);
1411 }
1412
1413
1414 /*
1415  * Zero fill initializer
1416  *
1417  * Arguments/Returns follow uma_init specifications
1418  */
1419 static int
1420 zero_init(void *mem, int size, int flags)
1421 {
1422         bzero(mem, size);
1423         return (0);
1424 }
1425
1426 /*
1427  * Finish creating a small uma keg.  This calculates ipers, and the keg size.
1428  *
1429  * Arguments
1430  *      keg  The zone we should initialize
1431  *
1432  * Returns
1433  *      Nothing
1434  */
1435 static void
1436 keg_small_init(uma_keg_t keg)
1437 {
1438         u_int rsize;
1439         u_int memused;
1440         u_int wastedspace;
1441         u_int shsize;
1442         u_int slabsize;
1443
1444         if (keg->uk_flags & UMA_ZONE_PCPU) {
1445                 u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1446
1447                 slabsize = UMA_PCPU_ALLOC_SIZE;
1448                 keg->uk_ppera = ncpus;
1449         } else {
1450                 slabsize = UMA_SLAB_SIZE;
1451                 keg->uk_ppera = 1;
1452         }
1453
1454         /*
1455          * Calculate the size of each allocation (rsize) according to
1456          * alignment.  If the requested size is smaller than we have
1457          * allocation bits for we round it up.
1458          */
1459         rsize = keg->uk_size;
1460         if (rsize < slabsize / SLAB_SETSIZE)
1461                 rsize = slabsize / SLAB_SETSIZE;
1462         if (rsize & keg->uk_align)
1463                 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1464         keg->uk_rsize = rsize;
1465
1466         KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1467             keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1468             ("%s: size %u too large", __func__, keg->uk_rsize));
1469
1470         if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1471                 shsize = 0;
1472         else 
1473                 shsize = SIZEOF_UMA_SLAB;
1474
1475         if (rsize <= slabsize - shsize)
1476                 keg->uk_ipers = (slabsize - shsize) / rsize;
1477         else {
1478                 /* Handle special case when we have 1 item per slab, so
1479                  * alignment requirement can be relaxed. */
1480                 KASSERT(keg->uk_size <= slabsize - shsize,
1481                     ("%s: size %u greater than slab", __func__, keg->uk_size));
1482                 keg->uk_ipers = 1;
1483         }
1484         KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1485             ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1486
1487         memused = keg->uk_ipers * rsize + shsize;
1488         wastedspace = slabsize - memused;
1489
1490         /*
1491          * We can't do OFFPAGE if we're internal or if we've been
1492          * asked to not go to the VM for buckets.  If we do this we
1493          * may end up going to the VM  for slabs which we do not
1494          * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1495          * of UMA_ZONE_VM, which clearly forbids it.
1496          */
1497         if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1498             (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1499                 return;
1500
1501         /*
1502          * See if using an OFFPAGE slab will limit our waste.  Only do
1503          * this if it permits more items per-slab.
1504          *
1505          * XXX We could try growing slabsize to limit max waste as well.
1506          * Historically this was not done because the VM could not
1507          * efficiently handle contiguous allocations.
1508          */
1509         if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1510             (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1511                 keg->uk_ipers = slabsize / keg->uk_rsize;
1512                 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1513                     ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1514                 CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1515                     "keg: %s(%p), calculated wastedspace = %d, "
1516                     "maximum wasted space allowed = %d, "
1517                     "calculated ipers = %d, "
1518                     "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1519                     slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1520                     slabsize - keg->uk_ipers * keg->uk_rsize);
1521                 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1522         }
1523
1524         if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1525             (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1526                 keg->uk_flags |= UMA_ZONE_HASH;
1527 }
1528
1529 /*
1530  * Finish creating a large (> UMA_SLAB_SIZE) uma kegs.  Just give in and do
1531  * OFFPAGE for now.  When I can allow for more dynamic slab sizes this will be
1532  * more complicated.
1533  *
1534  * Arguments
1535  *      keg  The keg we should initialize
1536  *
1537  * Returns
1538  *      Nothing
1539  */
1540 static void
1541 keg_large_init(uma_keg_t keg)
1542 {
1543
1544         KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1545         KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1546             ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1547
1548         keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1549         keg->uk_ipers = 1;
1550         keg->uk_rsize = keg->uk_size;
1551
1552         /* Check whether we have enough space to not do OFFPAGE. */
1553         if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0 &&
1554             PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < SIZEOF_UMA_SLAB) {
1555                 /*
1556                  * We can't do OFFPAGE if we're internal, in which case
1557                  * we need an extra page per allocation to contain the
1558                  * slab header.
1559                  */
1560                 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1561                         keg->uk_flags |= UMA_ZONE_OFFPAGE;
1562                 else
1563                         keg->uk_ppera++;
1564         }
1565
1566         if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1567             (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1568                 keg->uk_flags |= UMA_ZONE_HASH;
1569 }
1570
1571 static void
1572 keg_cachespread_init(uma_keg_t keg)
1573 {
1574         int alignsize;
1575         int trailer;
1576         int pages;
1577         int rsize;
1578
1579         KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1580             ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1581
1582         alignsize = keg->uk_align + 1;
1583         rsize = keg->uk_size;
1584         /*
1585          * We want one item to start on every align boundary in a page.  To
1586          * do this we will span pages.  We will also extend the item by the
1587          * size of align if it is an even multiple of align.  Otherwise, it
1588          * would fall on the same boundary every time.
1589          */
1590         if (rsize & keg->uk_align)
1591                 rsize = (rsize & ~keg->uk_align) + alignsize;
1592         if ((rsize & alignsize) == 0)
1593                 rsize += alignsize;
1594         trailer = rsize - keg->uk_size;
1595         pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1596         pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1597         keg->uk_rsize = rsize;
1598         keg->uk_ppera = pages;
1599         keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1600         keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1601         KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1602             ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1603             keg->uk_ipers));
1604 }
1605
1606 /*
1607  * Keg header ctor.  This initializes all fields, locks, etc.  And inserts
1608  * the keg onto the global keg list.
1609  *
1610  * Arguments/Returns follow uma_ctor specifications
1611  *      udata  Actually uma_kctor_args
1612  */
1613 static int
1614 keg_ctor(void *mem, int size, void *udata, int flags)
1615 {
1616         struct uma_kctor_args *arg = udata;
1617         uma_keg_t keg = mem;
1618         uma_zone_t zone;
1619
1620         bzero(keg, size);
1621         keg->uk_size = arg->size;
1622         keg->uk_init = arg->uminit;
1623         keg->uk_fini = arg->fini;
1624         keg->uk_align = arg->align;
1625         keg->uk_free = 0;
1626         keg->uk_reserve = 0;
1627         keg->uk_pages = 0;
1628         keg->uk_flags = arg->flags;
1629         keg->uk_slabzone = NULL;
1630
1631         /*
1632          * We use a global round-robin policy by default.  Zones with
1633          * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1634          * iterator is never run.
1635          */
1636         keg->uk_dr.dr_policy = DOMAINSET_RR();
1637         keg->uk_dr.dr_iter = 0;
1638
1639         /*
1640          * The master zone is passed to us at keg-creation time.
1641          */
1642         zone = arg->zone;
1643         keg->uk_name = zone->uz_name;
1644
1645         if (arg->flags & UMA_ZONE_VM)
1646                 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1647
1648         if (arg->flags & UMA_ZONE_ZINIT)
1649                 keg->uk_init = zero_init;
1650
1651         if (arg->flags & UMA_ZONE_MALLOC)
1652                 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1653
1654         if (arg->flags & UMA_ZONE_PCPU)
1655 #ifdef SMP
1656                 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1657 #else
1658                 keg->uk_flags &= ~UMA_ZONE_PCPU;
1659 #endif
1660
1661         if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1662                 keg_cachespread_init(keg);
1663         } else {
1664                 if (keg->uk_size > UMA_SLAB_SPACE)
1665                         keg_large_init(keg);
1666                 else
1667                         keg_small_init(keg);
1668         }
1669
1670         if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1671                 keg->uk_slabzone = slabzone;
1672
1673         /*
1674          * If we haven't booted yet we need allocations to go through the
1675          * startup cache until the vm is ready.
1676          */
1677         if (booted < BOOT_PAGEALLOC)
1678                 keg->uk_allocf = startup_alloc;
1679 #ifdef UMA_MD_SMALL_ALLOC
1680         else if (keg->uk_ppera == 1)
1681                 keg->uk_allocf = uma_small_alloc;
1682 #endif
1683         else if (keg->uk_flags & UMA_ZONE_PCPU)
1684                 keg->uk_allocf = pcpu_page_alloc;
1685         else
1686                 keg->uk_allocf = page_alloc;
1687 #ifdef UMA_MD_SMALL_ALLOC
1688         if (keg->uk_ppera == 1)
1689                 keg->uk_freef = uma_small_free;
1690         else
1691 #endif
1692         if (keg->uk_flags & UMA_ZONE_PCPU)
1693                 keg->uk_freef = pcpu_page_free;
1694         else
1695                 keg->uk_freef = page_free;
1696
1697         /*
1698          * Initialize keg's lock
1699          */
1700         KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1701
1702         /*
1703          * If we're putting the slab header in the actual page we need to
1704          * figure out where in each page it goes.  See SIZEOF_UMA_SLAB
1705          * macro definition.
1706          */
1707         if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1708                 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - SIZEOF_UMA_SLAB;
1709                 /*
1710                  * The only way the following is possible is if with our
1711                  * UMA_ALIGN_PTR adjustments we are now bigger than
1712                  * UMA_SLAB_SIZE.  I haven't checked whether this is
1713                  * mathematically possible for all cases, so we make
1714                  * sure here anyway.
1715                  */
1716                 KASSERT(keg->uk_pgoff + sizeof(struct uma_slab) <=
1717                     PAGE_SIZE * keg->uk_ppera,
1718                     ("zone %s ipers %d rsize %d size %d slab won't fit",
1719                     zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
1720         }
1721
1722         if (keg->uk_flags & UMA_ZONE_HASH)
1723                 hash_alloc(&keg->uk_hash, 0);
1724
1725         CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1726             keg, zone->uz_name, zone,
1727             (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1728             keg->uk_free);
1729
1730         LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1731
1732         rw_wlock(&uma_rwlock);
1733         LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1734         rw_wunlock(&uma_rwlock);
1735         return (0);
1736 }
1737
1738 static void
1739 zone_alloc_counters(uma_zone_t zone)
1740 {
1741
1742         zone->uz_allocs = counter_u64_alloc(M_WAITOK);
1743         zone->uz_frees = counter_u64_alloc(M_WAITOK);
1744         zone->uz_fails = counter_u64_alloc(M_WAITOK);
1745 }
1746
1747 /*
1748  * Zone header ctor.  This initializes all fields, locks, etc.
1749  *
1750  * Arguments/Returns follow uma_ctor specifications
1751  *      udata  Actually uma_zctor_args
1752  */
1753 static int
1754 zone_ctor(void *mem, int size, void *udata, int flags)
1755 {
1756         struct uma_zctor_args *arg = udata;
1757         uma_zone_t zone = mem;
1758         uma_zone_t z;
1759         uma_keg_t keg;
1760
1761         bzero(zone, size);
1762         zone->uz_name = arg->name;
1763         zone->uz_ctor = arg->ctor;
1764         zone->uz_dtor = arg->dtor;
1765         zone->uz_init = NULL;
1766         zone->uz_fini = NULL;
1767         zone->uz_sleeps = 0;
1768         zone->uz_xdomain = 0;
1769         zone->uz_count = 0;
1770         zone->uz_count_min = 0;
1771         zone->uz_count_max = BUCKET_MAX;
1772         zone->uz_flags = 0;
1773         zone->uz_warning = NULL;
1774         /* The domain structures follow the cpu structures. */
1775         zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1776         zone->uz_bkt_max = ULONG_MAX;
1777         timevalclear(&zone->uz_ratecheck);
1778
1779         if (__predict_true(booted == BOOT_RUNNING))
1780                 zone_alloc_counters(zone);
1781         else {
1782                 zone->uz_allocs = EARLY_COUNTER;
1783                 zone->uz_frees = EARLY_COUNTER;
1784                 zone->uz_fails = EARLY_COUNTER;
1785         }
1786
1787         /*
1788          * This is a pure cache zone, no kegs.
1789          */
1790         if (arg->import) {
1791                 if (arg->flags & UMA_ZONE_VM)
1792                         arg->flags |= UMA_ZFLAG_CACHEONLY;
1793                 zone->uz_flags = arg->flags;
1794                 zone->uz_size = arg->size;
1795                 zone->uz_import = arg->import;
1796                 zone->uz_release = arg->release;
1797                 zone->uz_arg = arg->arg;
1798                 zone->uz_lockptr = &zone->uz_lock;
1799                 ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1800                 rw_wlock(&uma_rwlock);
1801                 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1802                 rw_wunlock(&uma_rwlock);
1803                 goto out;
1804         }
1805
1806         /*
1807          * Use the regular zone/keg/slab allocator.
1808          */
1809         zone->uz_import = (uma_import)zone_import;
1810         zone->uz_release = (uma_release)zone_release;
1811         zone->uz_arg = zone; 
1812         keg = arg->keg;
1813
1814         if (arg->flags & UMA_ZONE_SECONDARY) {
1815                 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1816                 zone->uz_init = arg->uminit;
1817                 zone->uz_fini = arg->fini;
1818                 zone->uz_lockptr = &keg->uk_lock;
1819                 zone->uz_flags |= UMA_ZONE_SECONDARY;
1820                 rw_wlock(&uma_rwlock);
1821                 ZONE_LOCK(zone);
1822                 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1823                         if (LIST_NEXT(z, uz_link) == NULL) {
1824                                 LIST_INSERT_AFTER(z, zone, uz_link);
1825                                 break;
1826                         }
1827                 }
1828                 ZONE_UNLOCK(zone);
1829                 rw_wunlock(&uma_rwlock);
1830         } else if (keg == NULL) {
1831                 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1832                     arg->align, arg->flags)) == NULL)
1833                         return (ENOMEM);
1834         } else {
1835                 struct uma_kctor_args karg;
1836                 int error;
1837
1838                 /* We should only be here from uma_startup() */
1839                 karg.size = arg->size;
1840                 karg.uminit = arg->uminit;
1841                 karg.fini = arg->fini;
1842                 karg.align = arg->align;
1843                 karg.flags = arg->flags;
1844                 karg.zone = zone;
1845                 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1846                     flags);
1847                 if (error)
1848                         return (error);
1849         }
1850
1851         zone->uz_keg = keg;
1852         zone->uz_size = keg->uk_size;
1853         zone->uz_flags |= (keg->uk_flags &
1854             (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1855
1856         /*
1857          * Some internal zones don't have room allocated for the per cpu
1858          * caches.  If we're internal, bail out here.
1859          */
1860         if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1861                 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1862                     ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1863                 return (0);
1864         }
1865
1866 out:
1867         KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1868             (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1869             ("Invalid zone flag combination"));
1870         if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
1871                 zone->uz_count = BUCKET_MAX;
1872         else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1873                 zone->uz_count = 0;
1874         else
1875                 zone->uz_count = bucket_select(zone->uz_size);
1876         zone->uz_count_min = zone->uz_count;
1877
1878         return (0);
1879 }
1880
1881 /*
1882  * Keg header dtor.  This frees all data, destroys locks, frees the hash
1883  * table and removes the keg from the global list.
1884  *
1885  * Arguments/Returns follow uma_dtor specifications
1886  *      udata  unused
1887  */
1888 static void
1889 keg_dtor(void *arg, int size, void *udata)
1890 {
1891         uma_keg_t keg;
1892
1893         keg = (uma_keg_t)arg;
1894         KEG_LOCK(keg);
1895         if (keg->uk_free != 0) {
1896                 printf("Freed UMA keg (%s) was not empty (%d items). "
1897                     " Lost %d pages of memory.\n",
1898                     keg->uk_name ? keg->uk_name : "",
1899                     keg->uk_free, keg->uk_pages);
1900         }
1901         KEG_UNLOCK(keg);
1902
1903         hash_free(&keg->uk_hash);
1904
1905         KEG_LOCK_FINI(keg);
1906 }
1907
1908 /*
1909  * Zone header dtor.
1910  *
1911  * Arguments/Returns follow uma_dtor specifications
1912  *      udata  unused
1913  */
1914 static void
1915 zone_dtor(void *arg, int size, void *udata)
1916 {
1917         uma_zone_t zone;
1918         uma_keg_t keg;
1919
1920         zone = (uma_zone_t)arg;
1921
1922         if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1923                 cache_drain(zone);
1924
1925         rw_wlock(&uma_rwlock);
1926         LIST_REMOVE(zone, uz_link);
1927         rw_wunlock(&uma_rwlock);
1928         /*
1929          * XXX there are some races here where
1930          * the zone can be drained but zone lock
1931          * released and then refilled before we
1932          * remove it... we dont care for now
1933          */
1934         zone_drain_wait(zone, M_WAITOK);
1935         /*
1936          * We only destroy kegs from non secondary/non cache zones.
1937          */
1938         if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
1939                 keg = zone->uz_keg;
1940                 rw_wlock(&uma_rwlock);
1941                 LIST_REMOVE(keg, uk_link);
1942                 rw_wunlock(&uma_rwlock);
1943                 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1944         }
1945         counter_u64_free(zone->uz_allocs);
1946         counter_u64_free(zone->uz_frees);
1947         counter_u64_free(zone->uz_fails);
1948         if (zone->uz_lockptr == &zone->uz_lock)
1949                 ZONE_LOCK_FINI(zone);
1950 }
1951
1952 /*
1953  * Traverses every zone in the system and calls a callback
1954  *
1955  * Arguments:
1956  *      zfunc  A pointer to a function which accepts a zone
1957  *              as an argument.
1958  *
1959  * Returns:
1960  *      Nothing
1961  */
1962 static void
1963 zone_foreach(void (*zfunc)(uma_zone_t))
1964 {
1965         uma_keg_t keg;
1966         uma_zone_t zone;
1967
1968         /*
1969          * Before BOOT_RUNNING we are guaranteed to be single
1970          * threaded, so locking isn't needed. Startup functions
1971          * are allowed to use M_WAITOK.
1972          */
1973         if (__predict_true(booted == BOOT_RUNNING))
1974                 rw_rlock(&uma_rwlock);
1975         LIST_FOREACH(keg, &uma_kegs, uk_link) {
1976                 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1977                         zfunc(zone);
1978         }
1979         if (__predict_true(booted == BOOT_RUNNING))
1980                 rw_runlock(&uma_rwlock);
1981 }
1982
1983 /*
1984  * Count how many pages do we need to bootstrap.  VM supplies
1985  * its need in early zones in the argument, we add up our zones,
1986  * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
1987  * zone of zones and zone of kegs are accounted separately.
1988  */
1989 #define UMA_BOOT_ZONES  11
1990 /* Zone of zones and zone of kegs have arbitrary alignment. */
1991 #define UMA_BOOT_ALIGN  32
1992 static int zsize, ksize;
1993 int
1994 uma_startup_count(int vm_zones)
1995 {
1996         int zones, pages;
1997
1998         ksize = sizeof(struct uma_keg) +
1999             (sizeof(struct uma_domain) * vm_ndomains);
2000         zsize = sizeof(struct uma_zone) +
2001             (sizeof(struct uma_cache) * (mp_maxid + 1)) +
2002             (sizeof(struct uma_zone_domain) * vm_ndomains);
2003
2004         /*
2005          * Memory for the zone of kegs and its keg,
2006          * and for zone of zones.
2007          */
2008         pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
2009             roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
2010
2011 #ifdef  UMA_MD_SMALL_ALLOC
2012         zones = UMA_BOOT_ZONES;
2013 #else
2014         zones = UMA_BOOT_ZONES + vm_zones;
2015         vm_zones = 0;
2016 #endif
2017
2018         /* Memory for the rest of startup zones, UMA and VM, ... */
2019         if (zsize > UMA_SLAB_SPACE) {
2020                 /* See keg_large_init(). */
2021                 u_int ppera;
2022
2023                 ppera = howmany(roundup2(zsize, UMA_BOOT_ALIGN), PAGE_SIZE);
2024                 if (PAGE_SIZE * ppera - roundup2(zsize, UMA_BOOT_ALIGN) <
2025                     SIZEOF_UMA_SLAB)
2026                         ppera++;
2027                 pages += (zones + vm_zones) * ppera;
2028         } else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
2029                 /* See keg_small_init() special case for uk_ppera = 1. */
2030                 pages += zones;
2031         else
2032                 pages += howmany(zones,
2033                     UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
2034
2035         /* ... and their kegs. Note that zone of zones allocates a keg! */
2036         pages += howmany(zones + 1,
2037             UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
2038
2039         /*
2040          * Most of startup zones are not going to be offpages, that's
2041          * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
2042          * calculations.  Some large bucket zones will be offpage, and
2043          * thus will allocate hashes.  We take conservative approach
2044          * and assume that all zones may allocate hash.  This may give
2045          * us some positive inaccuracy, usually an extra single page.
2046          */
2047         pages += howmany(zones, UMA_SLAB_SPACE /
2048             (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
2049
2050         return (pages);
2051 }
2052
2053 void
2054 uma_startup(void *mem, int npages)
2055 {
2056         struct uma_zctor_args args;
2057         uma_keg_t masterkeg;
2058         uintptr_t m;
2059
2060 #ifdef DIAGNOSTIC
2061         printf("Entering %s with %d boot pages configured\n", __func__, npages);
2062 #endif
2063
2064         rw_init(&uma_rwlock, "UMA lock");
2065
2066         /* Use bootpages memory for the zone of zones and zone of kegs. */
2067         m = (uintptr_t)mem;
2068         zones = (uma_zone_t)m;
2069         m += roundup(zsize, CACHE_LINE_SIZE);
2070         kegs = (uma_zone_t)m;
2071         m += roundup(zsize, CACHE_LINE_SIZE);
2072         masterkeg = (uma_keg_t)m;
2073         m += roundup(ksize, CACHE_LINE_SIZE);
2074         m = roundup(m, PAGE_SIZE);
2075         npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2076         mem = (void *)m;
2077
2078         /* "manually" create the initial zone */
2079         memset(&args, 0, sizeof(args));
2080         args.name = "UMA Kegs";
2081         args.size = ksize;
2082         args.ctor = keg_ctor;
2083         args.dtor = keg_dtor;
2084         args.uminit = zero_init;
2085         args.fini = NULL;
2086         args.keg = masterkeg;
2087         args.align = UMA_BOOT_ALIGN - 1;
2088         args.flags = UMA_ZFLAG_INTERNAL;
2089         zone_ctor(kegs, zsize, &args, M_WAITOK);
2090
2091         bootmem = mem;
2092         boot_pages = npages;
2093
2094         args.name = "UMA Zones";
2095         args.size = zsize;
2096         args.ctor = zone_ctor;
2097         args.dtor = zone_dtor;
2098         args.uminit = zero_init;
2099         args.fini = NULL;
2100         args.keg = NULL;
2101         args.align = UMA_BOOT_ALIGN - 1;
2102         args.flags = UMA_ZFLAG_INTERNAL;
2103         zone_ctor(zones, zsize, &args, M_WAITOK);
2104
2105         /* Now make a zone for slab headers */
2106         slabzone = uma_zcreate("UMA Slabs",
2107                                 sizeof(struct uma_slab),
2108                                 NULL, NULL, NULL, NULL,
2109                                 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2110
2111         hashzone = uma_zcreate("UMA Hash",
2112             sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2113             NULL, NULL, NULL, NULL,
2114             UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2115
2116         bucket_init();
2117
2118         booted = BOOT_STRAPPED;
2119 }
2120
2121 void
2122 uma_startup1(void)
2123 {
2124
2125 #ifdef DIAGNOSTIC
2126         printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2127 #endif
2128         booted = BOOT_PAGEALLOC;
2129 }
2130
2131 void
2132 uma_startup2(void)
2133 {
2134
2135 #ifdef DIAGNOSTIC
2136         printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2137 #endif
2138         booted = BOOT_BUCKETS;
2139         sx_init(&uma_drain_lock, "umadrain");
2140         bucket_enable();
2141 }
2142
2143 /*
2144  * Initialize our callout handle
2145  *
2146  */
2147 static void
2148 uma_startup3(void)
2149 {
2150
2151 #ifdef INVARIANTS
2152         TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2153         uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2154         uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2155 #endif
2156         zone_foreach(zone_alloc_counters);
2157         callout_init(&uma_callout, 1);
2158         callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2159         booted = BOOT_RUNNING;
2160 }
2161
2162 static uma_keg_t
2163 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2164                 int align, uint32_t flags)
2165 {
2166         struct uma_kctor_args args;
2167
2168         args.size = size;
2169         args.uminit = uminit;
2170         args.fini = fini;
2171         args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2172         args.flags = flags;
2173         args.zone = zone;
2174         return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2175 }
2176
2177 /* Public functions */
2178 /* See uma.h */
2179 void
2180 uma_set_align(int align)
2181 {
2182
2183         if (align != UMA_ALIGN_CACHE)
2184                 uma_align_cache = align;
2185 }
2186
2187 /* See uma.h */
2188 uma_zone_t
2189 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2190                 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2191
2192 {
2193         struct uma_zctor_args args;
2194         uma_zone_t res;
2195         bool locked;
2196
2197         KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2198             align, name));
2199
2200         /* Sets all zones to a first-touch domain policy. */
2201 #ifdef UMA_FIRSTTOUCH
2202         flags |= UMA_ZONE_NUMA;
2203 #endif
2204
2205         /* This stuff is essential for the zone ctor */
2206         memset(&args, 0, sizeof(args));
2207         args.name = name;
2208         args.size = size;
2209         args.ctor = ctor;
2210         args.dtor = dtor;
2211         args.uminit = uminit;
2212         args.fini = fini;
2213 #ifdef  INVARIANTS
2214         /*
2215          * If a zone is being created with an empty constructor and
2216          * destructor, pass UMA constructor/destructor which checks for
2217          * memory use after free.
2218          */
2219         if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2220             ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2221                 args.ctor = trash_ctor;
2222                 args.dtor = trash_dtor;
2223                 args.uminit = trash_init;
2224                 args.fini = trash_fini;
2225         }
2226 #endif
2227         args.align = align;
2228         args.flags = flags;
2229         args.keg = NULL;
2230
2231         if (booted < BOOT_BUCKETS) {
2232                 locked = false;
2233         } else {
2234                 sx_slock(&uma_drain_lock);
2235                 locked = true;
2236         }
2237         res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2238         if (locked)
2239                 sx_sunlock(&uma_drain_lock);
2240         return (res);
2241 }
2242
2243 /* See uma.h */
2244 uma_zone_t
2245 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2246                     uma_init zinit, uma_fini zfini, uma_zone_t master)
2247 {
2248         struct uma_zctor_args args;
2249         uma_keg_t keg;
2250         uma_zone_t res;
2251         bool locked;
2252
2253         keg = master->uz_keg;
2254         memset(&args, 0, sizeof(args));
2255         args.name = name;
2256         args.size = keg->uk_size;
2257         args.ctor = ctor;
2258         args.dtor = dtor;
2259         args.uminit = zinit;
2260         args.fini = zfini;
2261         args.align = keg->uk_align;
2262         args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2263         args.keg = keg;
2264
2265         if (booted < BOOT_BUCKETS) {
2266                 locked = false;
2267         } else {
2268                 sx_slock(&uma_drain_lock);
2269                 locked = true;
2270         }
2271         /* XXX Attaches only one keg of potentially many. */
2272         res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2273         if (locked)
2274                 sx_sunlock(&uma_drain_lock);
2275         return (res);
2276 }
2277
2278 /* See uma.h */
2279 uma_zone_t
2280 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2281                     uma_init zinit, uma_fini zfini, uma_import zimport,
2282                     uma_release zrelease, void *arg, int flags)
2283 {
2284         struct uma_zctor_args args;
2285
2286         memset(&args, 0, sizeof(args));
2287         args.name = name;
2288         args.size = size;
2289         args.ctor = ctor;
2290         args.dtor = dtor;
2291         args.uminit = zinit;
2292         args.fini = zfini;
2293         args.import = zimport;
2294         args.release = zrelease;
2295         args.arg = arg;
2296         args.align = 0;
2297         args.flags = flags | UMA_ZFLAG_CACHE;
2298
2299         return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2300 }
2301
2302 /* See uma.h */
2303 void
2304 uma_zdestroy(uma_zone_t zone)
2305 {
2306
2307         sx_slock(&uma_drain_lock);
2308         zone_free_item(zones, zone, NULL, SKIP_NONE);
2309         sx_sunlock(&uma_drain_lock);
2310 }
2311
2312 void
2313 uma_zwait(uma_zone_t zone)
2314 {
2315         void *item;
2316
2317         item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2318         uma_zfree(zone, item);
2319 }
2320
2321 void *
2322 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2323 {
2324         void *item;
2325 #ifdef SMP
2326         int i;
2327
2328         MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2329 #endif
2330         item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2331         if (item != NULL && (flags & M_ZERO)) {
2332 #ifdef SMP
2333                 for (i = 0; i <= mp_maxid; i++)
2334                         bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2335 #else
2336                 bzero(item, zone->uz_size);
2337 #endif
2338         }
2339         return (item);
2340 }
2341
2342 /*
2343  * A stub while both regular and pcpu cases are identical.
2344  */
2345 void
2346 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2347 {
2348
2349 #ifdef SMP
2350         MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2351 #endif
2352         uma_zfree_arg(zone, item, udata);
2353 }
2354
2355 /* See uma.h */
2356 void *
2357 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2358 {
2359         uma_zone_domain_t zdom;
2360         uma_bucket_t bucket;
2361         uma_cache_t cache;
2362         void *item;
2363         int cpu, domain, lockfail, maxbucket;
2364 #ifdef INVARIANTS
2365         bool skipdbg;
2366 #endif
2367
2368         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2369         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2370
2371         /* This is the fast path allocation */
2372         CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2373             curthread, zone->uz_name, zone, flags);
2374
2375         if (flags & M_WAITOK) {
2376                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2377                     "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2378         }
2379         KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2380         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2381             ("uma_zalloc_arg: called with spinlock or critical section held"));
2382         if (zone->uz_flags & UMA_ZONE_PCPU)
2383                 KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2384                     "with M_ZERO passed"));
2385
2386 #ifdef DEBUG_MEMGUARD
2387         if (memguard_cmp_zone(zone)) {
2388                 item = memguard_alloc(zone->uz_size, flags);
2389                 if (item != NULL) {
2390                         if (zone->uz_init != NULL &&
2391                             zone->uz_init(item, zone->uz_size, flags) != 0)
2392                                 return (NULL);
2393                         if (zone->uz_ctor != NULL &&
2394                             zone->uz_ctor(item, zone->uz_size, udata,
2395                             flags) != 0) {
2396                                 zone->uz_fini(item, zone->uz_size);
2397                                 return (NULL);
2398                         }
2399                         return (item);
2400                 }
2401                 /* This is unfortunate but should not be fatal. */
2402         }
2403 #endif
2404         /*
2405          * If possible, allocate from the per-CPU cache.  There are two
2406          * requirements for safe access to the per-CPU cache: (1) the thread
2407          * accessing the cache must not be preempted or yield during access,
2408          * and (2) the thread must not migrate CPUs without switching which
2409          * cache it accesses.  We rely on a critical section to prevent
2410          * preemption and migration.  We release the critical section in
2411          * order to acquire the zone mutex if we are unable to allocate from
2412          * the current cache; when we re-acquire the critical section, we
2413          * must detect and handle migration if it has occurred.
2414          */
2415 zalloc_restart:
2416         critical_enter();
2417         cpu = curcpu;
2418         cache = &zone->uz_cpu[cpu];
2419
2420 zalloc_start:
2421         bucket = cache->uc_allocbucket;
2422         if (bucket != NULL && bucket->ub_cnt > 0) {
2423                 bucket->ub_cnt--;
2424                 item = bucket->ub_bucket[bucket->ub_cnt];
2425 #ifdef INVARIANTS
2426                 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2427 #endif
2428                 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2429                 cache->uc_allocs++;
2430                 critical_exit();
2431 #ifdef INVARIANTS
2432                 skipdbg = uma_dbg_zskip(zone, item);
2433 #endif
2434                 if (zone->uz_ctor != NULL &&
2435 #ifdef INVARIANTS
2436                     (!skipdbg || zone->uz_ctor != trash_ctor ||
2437                     zone->uz_dtor != trash_dtor) &&
2438 #endif
2439                     zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2440                         counter_u64_add(zone->uz_fails, 1);
2441                         zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2442                         return (NULL);
2443                 }
2444 #ifdef INVARIANTS
2445                 if (!skipdbg)
2446                         uma_dbg_alloc(zone, NULL, item);
2447 #endif
2448                 if (flags & M_ZERO)
2449                         uma_zero_item(item, zone);
2450                 return (item);
2451         }
2452
2453         /*
2454          * We have run out of items in our alloc bucket.
2455          * See if we can switch with our free bucket.
2456          */
2457         bucket = cache->uc_freebucket;
2458         if (bucket != NULL && bucket->ub_cnt > 0) {
2459                 CTR2(KTR_UMA,
2460                     "uma_zalloc: zone %s(%p) swapping empty with alloc",
2461                     zone->uz_name, zone);
2462                 cache->uc_freebucket = cache->uc_allocbucket;
2463                 cache->uc_allocbucket = bucket;
2464                 goto zalloc_start;
2465         }
2466
2467         /*
2468          * Discard any empty allocation bucket while we hold no locks.
2469          */
2470         bucket = cache->uc_allocbucket;
2471         cache->uc_allocbucket = NULL;
2472         critical_exit();
2473         if (bucket != NULL)
2474                 bucket_free(zone, bucket, udata);
2475
2476         /* Short-circuit for zones without buckets and low memory. */
2477         if (zone->uz_count == 0 || bucketdisable) {
2478                 ZONE_LOCK(zone);
2479                 if (zone->uz_flags & UMA_ZONE_NUMA)
2480                         domain = PCPU_GET(domain);
2481                 else
2482                         domain = UMA_ANYDOMAIN;
2483                 goto zalloc_item;
2484         }
2485
2486         /*
2487          * Attempt to retrieve the item from the per-CPU cache has failed, so
2488          * we must go back to the zone.  This requires the zone lock, so we
2489          * must drop the critical section, then re-acquire it when we go back
2490          * to the cache.  Since the critical section is released, we may be
2491          * preempted or migrate.  As such, make sure not to maintain any
2492          * thread-local state specific to the cache from prior to releasing
2493          * the critical section.
2494          */
2495         lockfail = 0;
2496         if (ZONE_TRYLOCK(zone) == 0) {
2497                 /* Record contention to size the buckets. */
2498                 ZONE_LOCK(zone);
2499                 lockfail = 1;
2500         }
2501         critical_enter();
2502         cpu = curcpu;
2503         cache = &zone->uz_cpu[cpu];
2504
2505         /* See if we lost the race to fill the cache. */
2506         if (cache->uc_allocbucket != NULL) {
2507                 ZONE_UNLOCK(zone);
2508                 goto zalloc_start;
2509         }
2510
2511         /*
2512          * Check the zone's cache of buckets.
2513          */
2514         if (zone->uz_flags & UMA_ZONE_NUMA) {
2515                 domain = PCPU_GET(domain);
2516                 zdom = &zone->uz_domain[domain];
2517         } else {
2518                 domain = UMA_ANYDOMAIN;
2519                 zdom = &zone->uz_domain[0];
2520         }
2521
2522         if ((bucket = zone_try_fetch_bucket(zone, zdom, true)) != NULL) {
2523                 KASSERT(bucket->ub_cnt != 0,
2524                     ("uma_zalloc_arg: Returning an empty bucket."));
2525                 cache->uc_allocbucket = bucket;
2526                 ZONE_UNLOCK(zone);
2527                 goto zalloc_start;
2528         }
2529         /* We are no longer associated with this CPU. */
2530         critical_exit();
2531
2532         /*
2533          * We bump the uz count when the cache size is insufficient to
2534          * handle the working set.
2535          */
2536         if (lockfail && zone->uz_count < zone->uz_count_max)
2537                 zone->uz_count++;
2538
2539         if (zone->uz_max_items > 0) {
2540                 if (zone->uz_items >= zone->uz_max_items)
2541                         goto zalloc_item;
2542                 maxbucket = MIN(zone->uz_count,
2543                     zone->uz_max_items - zone->uz_items);
2544                 zone->uz_items += maxbucket;
2545         } else
2546                 maxbucket = zone->uz_count;
2547         ZONE_UNLOCK(zone);
2548
2549         /*
2550          * Now lets just fill a bucket and put it on the free list.  If that
2551          * works we'll restart the allocation from the beginning and it
2552          * will use the just filled bucket.
2553          */
2554         bucket = zone_alloc_bucket(zone, udata, domain, flags, maxbucket);
2555         CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2556             zone->uz_name, zone, bucket);
2557         ZONE_LOCK(zone);
2558         if (bucket != NULL) {
2559                 if (zone->uz_max_items > 0 && bucket->ub_cnt < maxbucket) {
2560                         MPASS(zone->uz_items >= maxbucket - bucket->ub_cnt);
2561                         zone->uz_items -= maxbucket - bucket->ub_cnt;
2562                         if (zone->uz_sleepers > 0 &&
2563                             zone->uz_items < zone->uz_max_items)
2564                                 wakeup_one(zone);
2565                 }
2566                 critical_enter();
2567                 cpu = curcpu;
2568                 cache = &zone->uz_cpu[cpu];
2569
2570                 /*
2571                  * See if we lost the race or were migrated.  Cache the
2572                  * initialized bucket to make this less likely or claim
2573                  * the memory directly.
2574                  */
2575                 if (cache->uc_allocbucket == NULL &&
2576                     ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2577                     domain == PCPU_GET(domain))) {
2578                         cache->uc_allocbucket = bucket;
2579                         zdom->uzd_imax += bucket->ub_cnt;
2580                 } else if (zone->uz_bkt_count >= zone->uz_bkt_max) {
2581                         critical_exit();
2582                         ZONE_UNLOCK(zone);
2583                         bucket_drain(zone, bucket);
2584                         bucket_free(zone, bucket, udata);
2585                         goto zalloc_restart;
2586                 } else
2587                         zone_put_bucket(zone, zdom, bucket, false);
2588                 ZONE_UNLOCK(zone);
2589                 goto zalloc_start;
2590         } else if (zone->uz_max_items > 0) {
2591                 zone->uz_items -= maxbucket;
2592                 if (zone->uz_sleepers > 0 &&
2593                     zone->uz_items + 1 < zone->uz_max_items)
2594                         wakeup_one(zone);
2595         }
2596
2597         /*
2598          * We may not be able to get a bucket so return an actual item.
2599          */
2600 zalloc_item:
2601         item = zone_alloc_item_locked(zone, udata, domain, flags);
2602
2603         return (item);
2604 }
2605
2606 void *
2607 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2608 {
2609
2610         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2611         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2612
2613         /* This is the fast path allocation */
2614         CTR5(KTR_UMA,
2615             "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2616             curthread, zone->uz_name, zone, domain, flags);
2617
2618         if (flags & M_WAITOK) {
2619                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2620                     "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2621         }
2622         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2623             ("uma_zalloc_domain: called with spinlock or critical section held"));
2624
2625         return (zone_alloc_item(zone, udata, domain, flags));
2626 }
2627
2628 /*
2629  * Find a slab with some space.  Prefer slabs that are partially used over those
2630  * that are totally full.  This helps to reduce fragmentation.
2631  *
2632  * If 'rr' is 1, search all domains starting from 'domain'.  Otherwise check
2633  * only 'domain'.
2634  */
2635 static uma_slab_t
2636 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2637 {
2638         uma_domain_t dom;
2639         uma_slab_t slab;
2640         int start;
2641
2642         KASSERT(domain >= 0 && domain < vm_ndomains,
2643             ("keg_first_slab: domain %d out of range", domain));
2644         KEG_LOCK_ASSERT(keg);
2645
2646         slab = NULL;
2647         start = domain;
2648         do {
2649                 dom = &keg->uk_domain[domain];
2650                 if (!LIST_EMPTY(&dom->ud_part_slab))
2651                         return (LIST_FIRST(&dom->ud_part_slab));
2652                 if (!LIST_EMPTY(&dom->ud_free_slab)) {
2653                         slab = LIST_FIRST(&dom->ud_free_slab);
2654                         LIST_REMOVE(slab, us_link);
2655                         LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2656                         return (slab);
2657                 }
2658                 if (rr)
2659                         domain = (domain + 1) % vm_ndomains;
2660         } while (domain != start);
2661
2662         return (NULL);
2663 }
2664
2665 static uma_slab_t
2666 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2667 {
2668         uint32_t reserve;
2669
2670         KEG_LOCK_ASSERT(keg);
2671
2672         reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2673         if (keg->uk_free <= reserve)
2674                 return (NULL);
2675         return (keg_first_slab(keg, domain, rr));
2676 }
2677
2678 static uma_slab_t
2679 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2680 {
2681         struct vm_domainset_iter di;
2682         uma_domain_t dom;
2683         uma_slab_t slab;
2684         int aflags, domain;
2685         bool rr;
2686
2687 restart:
2688         KEG_LOCK_ASSERT(keg);
2689
2690         /*
2691          * Use the keg's policy if upper layers haven't already specified a
2692          * domain (as happens with first-touch zones).
2693          *
2694          * To avoid races we run the iterator with the keg lock held, but that
2695          * means that we cannot allow the vm_domainset layer to sleep.  Thus,
2696          * clear M_WAITOK and handle low memory conditions locally.
2697          */
2698         rr = rdomain == UMA_ANYDOMAIN;
2699         if (rr) {
2700                 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2701                 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2702                     &aflags);
2703         } else {
2704                 aflags = flags;
2705                 domain = rdomain;
2706         }
2707
2708         for (;;) {
2709                 slab = keg_fetch_free_slab(keg, domain, rr, flags);
2710                 if (slab != NULL) {
2711                         MPASS(slab->us_keg == keg);
2712                         return (slab);
2713                 }
2714
2715                 /*
2716                  * M_NOVM means don't ask at all!
2717                  */
2718                 if (flags & M_NOVM)
2719                         break;
2720
2721                 KASSERT(zone->uz_max_items == 0 ||
2722                     zone->uz_items <= zone->uz_max_items,
2723                     ("%s: zone %p overflow", __func__, zone));
2724
2725                 slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
2726                 /*
2727                  * If we got a slab here it's safe to mark it partially used
2728                  * and return.  We assume that the caller is going to remove
2729                  * at least one item.
2730                  */
2731                 if (slab) {
2732                         MPASS(slab->us_keg == keg);
2733                         dom = &keg->uk_domain[slab->us_domain];
2734                         LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2735                         return (slab);
2736                 }
2737                 KEG_LOCK(keg);
2738                 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2739                         if ((flags & M_WAITOK) != 0) {
2740                                 KEG_UNLOCK(keg);
2741                                 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2742                                 KEG_LOCK(keg);
2743                                 goto restart;
2744                         }
2745                         break;
2746                 }
2747         }
2748
2749         /*
2750          * We might not have been able to get a slab but another cpu
2751          * could have while we were unlocked.  Check again before we
2752          * fail.
2753          */
2754         if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2755                 MPASS(slab->us_keg == keg);
2756                 return (slab);
2757         }
2758         return (NULL);
2759 }
2760
2761 static uma_slab_t
2762 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2763 {
2764         uma_slab_t slab;
2765
2766         if (keg == NULL) {
2767                 keg = zone->uz_keg;
2768                 KEG_LOCK(keg);
2769         }
2770
2771         for (;;) {
2772                 slab = keg_fetch_slab(keg, zone, domain, flags);
2773                 if (slab)
2774                         return (slab);
2775                 if (flags & (M_NOWAIT | M_NOVM))
2776                         break;
2777         }
2778         KEG_UNLOCK(keg);
2779         return (NULL);
2780 }
2781
2782 static void *
2783 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2784 {
2785         uma_domain_t dom;
2786         void *item;
2787         uint8_t freei;
2788
2789         MPASS(keg == slab->us_keg);
2790         KEG_LOCK_ASSERT(keg);
2791
2792         freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2793         BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2794         item = slab->us_data + (keg->uk_rsize * freei);
2795         slab->us_freecount--;
2796         keg->uk_free--;
2797
2798         /* Move this slab to the full list */
2799         if (slab->us_freecount == 0) {
2800                 LIST_REMOVE(slab, us_link);
2801                 dom = &keg->uk_domain[slab->us_domain];
2802                 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2803         }
2804
2805         return (item);
2806 }
2807
2808 static int
2809 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2810 {
2811         uma_slab_t slab;
2812         uma_keg_t keg;
2813 #ifdef NUMA
2814         int stripe;
2815 #endif
2816         int i;
2817
2818         slab = NULL;
2819         keg = NULL;
2820         /* Try to keep the buckets totally full */
2821         for (i = 0; i < max; ) {
2822                 if ((slab = zone_fetch_slab(zone, keg, domain, flags)) == NULL)
2823                         break;
2824                 keg = slab->us_keg;
2825 #ifdef NUMA
2826                 stripe = howmany(max, vm_ndomains);
2827 #endif
2828                 while (slab->us_freecount && i < max) { 
2829                         bucket[i++] = slab_alloc_item(keg, slab);
2830                         if (keg->uk_free <= keg->uk_reserve)
2831                                 break;
2832 #ifdef NUMA
2833                         /*
2834                          * If the zone is striped we pick a new slab for every
2835                          * N allocations.  Eliminating this conditional will
2836                          * instead pick a new domain for each bucket rather
2837                          * than stripe within each bucket.  The current option
2838                          * produces more fragmentation and requires more cpu
2839                          * time but yields better distribution.
2840                          */
2841                         if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2842                             vm_ndomains > 1 && --stripe == 0)
2843                                 break;
2844 #endif
2845                 }
2846                 /* Don't block if we allocated any successfully. */
2847                 flags &= ~M_WAITOK;
2848                 flags |= M_NOWAIT;
2849         }
2850         if (slab != NULL)
2851                 KEG_UNLOCK(keg);
2852
2853         return i;
2854 }
2855
2856 static uma_bucket_t
2857 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags, int max)
2858 {
2859         uma_bucket_t bucket;
2860
2861         CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
2862
2863         /* Avoid allocs targeting empty domains. */
2864         if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
2865                 domain = UMA_ANYDOMAIN;
2866
2867         /* Don't wait for buckets, preserve caller's NOVM setting. */
2868         bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
2869         if (bucket == NULL)
2870                 return (NULL);
2871
2872         bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
2873             MIN(max, bucket->ub_entries), domain, flags);
2874
2875         /*
2876          * Initialize the memory if necessary.
2877          */
2878         if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
2879                 int i;
2880
2881                 for (i = 0; i < bucket->ub_cnt; i++)
2882                         if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2883                             flags) != 0)
2884                                 break;
2885                 /*
2886                  * If we couldn't initialize the whole bucket, put the
2887                  * rest back onto the freelist.
2888                  */
2889                 if (i != bucket->ub_cnt) {
2890                         zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
2891                             bucket->ub_cnt - i);
2892 #ifdef INVARIANTS
2893                         bzero(&bucket->ub_bucket[i],
2894                             sizeof(void *) * (bucket->ub_cnt - i));
2895 #endif
2896                         bucket->ub_cnt = i;
2897                 }
2898         }
2899
2900         if (bucket->ub_cnt == 0) {
2901                 bucket_free(zone, bucket, udata);
2902                 counter_u64_add(zone->uz_fails, 1);
2903                 return (NULL);
2904         }
2905
2906         return (bucket);
2907 }
2908
2909 /*
2910  * Allocates a single item from a zone.
2911  *
2912  * Arguments
2913  *      zone   The zone to alloc for.
2914  *      udata  The data to be passed to the constructor.
2915  *      domain The domain to allocate from or UMA_ANYDOMAIN.
2916  *      flags  M_WAITOK, M_NOWAIT, M_ZERO.
2917  *
2918  * Returns
2919  *      NULL if there is no memory and M_NOWAIT is set
2920  *      An item if successful
2921  */
2922
2923 static void *
2924 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
2925 {
2926
2927         ZONE_LOCK(zone);
2928         return (zone_alloc_item_locked(zone, udata, domain, flags));
2929 }
2930
2931 /*
2932  * Returns with zone unlocked.
2933  */
2934 static void *
2935 zone_alloc_item_locked(uma_zone_t zone, void *udata, int domain, int flags)
2936 {
2937         void *item;
2938 #ifdef INVARIANTS
2939         bool skipdbg;
2940 #endif
2941
2942         ZONE_LOCK_ASSERT(zone);
2943
2944         if (zone->uz_max_items > 0) {
2945                 if (zone->uz_items >= zone->uz_max_items) {
2946                         zone_log_warning(zone);
2947                         zone_maxaction(zone);
2948                         if (flags & M_NOWAIT) {
2949                                 ZONE_UNLOCK(zone);
2950                                 return (NULL);
2951                         }
2952                         zone->uz_sleeps++;
2953                         zone->uz_sleepers++;
2954                         while (zone->uz_items >= zone->uz_max_items)
2955                                 mtx_sleep(zone, zone->uz_lockptr, PVM,
2956                                     "zonelimit", 0);
2957                         zone->uz_sleepers--;
2958                         if (zone->uz_sleepers > 0 &&
2959                             zone->uz_items + 1 < zone->uz_max_items)
2960                                 wakeup_one(zone);
2961                 }
2962                 zone->uz_items++;
2963         }
2964         ZONE_UNLOCK(zone);
2965
2966         /* Avoid allocs targeting empty domains. */
2967         if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
2968                 domain = UMA_ANYDOMAIN;
2969
2970         if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
2971                 goto fail;
2972
2973 #ifdef INVARIANTS
2974         skipdbg = uma_dbg_zskip(zone, item);
2975 #endif
2976         /*
2977          * We have to call both the zone's init (not the keg's init)
2978          * and the zone's ctor.  This is because the item is going from
2979          * a keg slab directly to the user, and the user is expecting it
2980          * to be both zone-init'd as well as zone-ctor'd.
2981          */
2982         if (zone->uz_init != NULL) {
2983                 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
2984                         zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
2985                         goto fail;
2986                 }
2987         }
2988         if (zone->uz_ctor != NULL &&
2989 #ifdef INVARIANTS
2990             (!skipdbg || zone->uz_ctor != trash_ctor ||
2991             zone->uz_dtor != trash_dtor) &&
2992 #endif
2993             zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2994                 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2995                 goto fail;
2996         }
2997 #ifdef INVARIANTS
2998         if (!skipdbg)
2999                 uma_dbg_alloc(zone, NULL, item);
3000 #endif
3001         if (flags & M_ZERO)
3002                 uma_zero_item(item, zone);
3003
3004         counter_u64_add(zone->uz_allocs, 1);
3005         CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
3006             zone->uz_name, zone);
3007
3008         return (item);
3009
3010 fail:
3011         if (zone->uz_max_items > 0) {
3012                 ZONE_LOCK(zone);
3013                 zone->uz_items--;
3014                 ZONE_UNLOCK(zone);
3015         }
3016         counter_u64_add(zone->uz_fails, 1);
3017         CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
3018             zone->uz_name, zone);
3019         return (NULL);
3020 }
3021
3022 /* See uma.h */
3023 void
3024 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
3025 {
3026         uma_cache_t cache;
3027         uma_bucket_t bucket;
3028         uma_zone_domain_t zdom;
3029         int cpu, domain;
3030 #ifdef UMA_XDOMAIN
3031         int itemdomain;
3032 #endif
3033         bool lockfail;
3034 #ifdef INVARIANTS
3035         bool skipdbg;
3036 #endif
3037
3038         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3039         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3040
3041         CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
3042             zone->uz_name);
3043
3044         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3045             ("uma_zfree_arg: called with spinlock or critical section held"));
3046
3047         /* uma_zfree(..., NULL) does nothing, to match free(9). */
3048         if (item == NULL)
3049                 return;
3050 #ifdef DEBUG_MEMGUARD
3051         if (is_memguard_addr(item)) {
3052                 if (zone->uz_dtor != NULL)
3053                         zone->uz_dtor(item, zone->uz_size, udata);
3054                 if (zone->uz_fini != NULL)
3055                         zone->uz_fini(item, zone->uz_size);
3056                 memguard_free(item);
3057                 return;
3058         }
3059 #endif
3060 #ifdef INVARIANTS
3061         skipdbg = uma_dbg_zskip(zone, item);
3062         if (skipdbg == false) {
3063                 if (zone->uz_flags & UMA_ZONE_MALLOC)
3064                         uma_dbg_free(zone, udata, item);
3065                 else
3066                         uma_dbg_free(zone, NULL, item);
3067         }
3068         if (zone->uz_dtor != NULL && (!skipdbg ||
3069             zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3070 #else
3071         if (zone->uz_dtor != NULL)
3072 #endif
3073                 zone->uz_dtor(item, zone->uz_size, udata);
3074
3075         /*
3076          * The race here is acceptable.  If we miss it we'll just have to wait
3077          * a little longer for the limits to be reset.
3078          */
3079         if (zone->uz_sleepers > 0)
3080                 goto zfree_item;
3081
3082 #ifdef UMA_XDOMAIN
3083         if ((zone->uz_flags & UMA_ZONE_NUMA) != 0)
3084                 itemdomain = _vm_phys_domain(pmap_kextract((vm_offset_t)item));
3085 #endif
3086
3087         /*
3088          * If possible, free to the per-CPU cache.  There are two
3089          * requirements for safe access to the per-CPU cache: (1) the thread
3090          * accessing the cache must not be preempted or yield during access,
3091          * and (2) the thread must not migrate CPUs without switching which
3092          * cache it accesses.  We rely on a critical section to prevent
3093          * preemption and migration.  We release the critical section in
3094          * order to acquire the zone mutex if we are unable to free to the
3095          * current cache; when we re-acquire the critical section, we must
3096          * detect and handle migration if it has occurred.
3097          */
3098 zfree_restart:
3099         critical_enter();
3100         cpu = curcpu;
3101         cache = &zone->uz_cpu[cpu];
3102
3103 zfree_start:
3104         domain = PCPU_GET(domain);
3105 #ifdef UMA_XDOMAIN
3106         if ((zone->uz_flags & UMA_ZONE_NUMA) == 0)
3107                 itemdomain = domain;
3108 #endif
3109         /*
3110          * Try to free into the allocbucket first to give LIFO ordering
3111          * for cache-hot datastructures.  Spill over into the freebucket
3112          * if necessary.  Alloc will swap them if one runs dry.
3113          */
3114 #ifdef UMA_XDOMAIN
3115         if (domain != itemdomain) {
3116                 bucket = cache->uc_crossbucket;
3117         } else
3118 #endif
3119         {
3120                 bucket = cache->uc_allocbucket;
3121                 if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3122                         bucket = cache->uc_freebucket;
3123         }
3124         if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3125                 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3126                     ("uma_zfree: Freeing to non free bucket index."));
3127                 bucket->ub_bucket[bucket->ub_cnt] = item;
3128                 bucket->ub_cnt++;
3129                 cache->uc_frees++;
3130                 critical_exit();
3131                 return;
3132         }
3133
3134         /*
3135          * We must go back the zone, which requires acquiring the zone lock,
3136          * which in turn means we must release and re-acquire the critical
3137          * section.  Since the critical section is released, we may be
3138          * preempted or migrate.  As such, make sure not to maintain any
3139          * thread-local state specific to the cache from prior to releasing
3140          * the critical section.
3141          */
3142         critical_exit();
3143         if (zone->uz_count == 0 || bucketdisable)
3144                 goto zfree_item;
3145
3146         lockfail = false;
3147         if (ZONE_TRYLOCK(zone) == 0) {
3148                 /* Record contention to size the buckets. */
3149                 ZONE_LOCK(zone);
3150                 lockfail = true;
3151         }
3152         critical_enter();
3153         cpu = curcpu;
3154         domain = PCPU_GET(domain);
3155         cache = &zone->uz_cpu[cpu];
3156
3157 #ifdef UMA_XDOMAIN
3158         if (domain != itemdomain)
3159                 bucket = cache->uc_crossbucket;
3160         else
3161 #endif
3162                 bucket = cache->uc_freebucket;
3163         if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3164                 ZONE_UNLOCK(zone);
3165                 goto zfree_start;
3166         }
3167 #ifdef UMA_XDOMAIN
3168         if (domain != itemdomain)
3169                 cache->uc_crossbucket = NULL;
3170         else
3171 #endif
3172                 cache->uc_freebucket = NULL;
3173         /* We are no longer associated with this CPU. */
3174         critical_exit();
3175
3176 #ifdef UMA_XDOMAIN
3177         if (domain != itemdomain) {
3178                 if (bucket != NULL) {
3179                         zone->uz_xdomain += bucket->ub_cnt;
3180                         if (vm_ndomains > 2 ||
3181                             zone->uz_bkt_count >= zone->uz_bkt_max) {
3182                                 ZONE_UNLOCK(zone);
3183                                 bucket_drain(zone, bucket);
3184                                 bucket_free(zone, bucket, udata);
3185                         } else {
3186                                 zdom = &zone->uz_domain[itemdomain];
3187                                 zone_put_bucket(zone, zdom, bucket, true);
3188                                 ZONE_UNLOCK(zone);
3189                         }
3190                 } else
3191                         ZONE_UNLOCK(zone);
3192                 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3193                 if (bucket == NULL)
3194                         goto zfree_item;
3195                 critical_enter();
3196                 cpu = curcpu;
3197                 cache = &zone->uz_cpu[cpu];
3198                 if (cache->uc_crossbucket == NULL) {
3199                         cache->uc_crossbucket = bucket;
3200                         goto zfree_start;
3201                 }
3202                 critical_exit();
3203                 bucket_free(zone, bucket, udata);
3204                 goto zfree_restart;
3205         }
3206 #endif
3207
3208         if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3209                 zdom = &zone->uz_domain[domain];
3210         } else {
3211                 domain = 0;
3212                 zdom = &zone->uz_domain[0];
3213         }
3214
3215         /* Can we throw this on the zone full list? */
3216         if (bucket != NULL) {
3217                 CTR3(KTR_UMA,
3218                     "uma_zfree: zone %s(%p) putting bucket %p on free list",
3219                     zone->uz_name, zone, bucket);
3220                 /* ub_cnt is pointing to the last free item */
3221                 KASSERT(bucket->ub_cnt == bucket->ub_entries,
3222                     ("uma_zfree: Attempting to insert not full bucket onto the full list.\n"));
3223                 if (zone->uz_bkt_count >= zone->uz_bkt_max) {
3224                         ZONE_UNLOCK(zone);
3225                         bucket_drain(zone, bucket);
3226                         bucket_free(zone, bucket, udata);
3227                         goto zfree_restart;
3228                 } else
3229                         zone_put_bucket(zone, zdom, bucket, true);
3230         }
3231
3232         /*
3233          * We bump the uz count when the cache size is insufficient to
3234          * handle the working set.
3235          */
3236         if (lockfail && zone->uz_count < zone->uz_count_max)
3237                 zone->uz_count++;
3238         ZONE_UNLOCK(zone);
3239
3240         bucket = bucket_alloc(zone, udata, M_NOWAIT);
3241         CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3242             zone->uz_name, zone, bucket);
3243         if (bucket) {
3244                 critical_enter();
3245                 cpu = curcpu;
3246                 cache = &zone->uz_cpu[cpu];
3247                 if (cache->uc_freebucket == NULL &&
3248                     ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3249                     domain == PCPU_GET(domain))) {
3250                         cache->uc_freebucket = bucket;
3251                         goto zfree_start;
3252                 }
3253                 /*
3254                  * We lost the race, start over.  We have to drop our
3255                  * critical section to free the bucket.
3256                  */
3257                 critical_exit();
3258                 bucket_free(zone, bucket, udata);
3259                 goto zfree_restart;
3260         }
3261
3262         /*
3263          * If nothing else caught this, we'll just do an internal free.
3264          */
3265 zfree_item:
3266         zone_free_item(zone, item, udata, SKIP_DTOR);
3267 }
3268
3269 void
3270 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3271 {
3272
3273         /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3274         random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3275
3276         CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3277             zone->uz_name);
3278
3279         KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3280             ("uma_zfree_domain: called with spinlock or critical section held"));
3281
3282         /* uma_zfree(..., NULL) does nothing, to match free(9). */
3283         if (item == NULL)
3284                 return;
3285         zone_free_item(zone, item, udata, SKIP_NONE);
3286 }
3287
3288 static void
3289 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
3290 {
3291         uma_keg_t keg;
3292         uma_domain_t dom;
3293         uint8_t freei;
3294
3295         keg = zone->uz_keg;
3296         MPASS(zone->uz_lockptr == &keg->uk_lock);
3297         KEG_LOCK_ASSERT(keg);
3298         MPASS(keg == slab->us_keg);
3299
3300         dom = &keg->uk_domain[slab->us_domain];
3301
3302         /* Do we need to remove from any lists? */
3303         if (slab->us_freecount+1 == keg->uk_ipers) {
3304                 LIST_REMOVE(slab, us_link);
3305                 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3306         } else if (slab->us_freecount == 0) {
3307                 LIST_REMOVE(slab, us_link);
3308                 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3309         }
3310
3311         /* Slab management. */
3312         freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3313         BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3314         slab->us_freecount++;
3315
3316         /* Keg statistics. */
3317         keg->uk_free++;
3318 }
3319
3320 static void
3321 zone_release(uma_zone_t zone, void **bucket, int cnt)
3322 {
3323         void *item;
3324         uma_slab_t slab;
3325         uma_keg_t keg;
3326         uint8_t *mem;
3327         int i;
3328
3329         keg = zone->uz_keg;
3330         KEG_LOCK(keg);
3331         for (i = 0; i < cnt; i++) {
3332                 item = bucket[i];
3333                 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3334                         mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3335                         if (zone->uz_flags & UMA_ZONE_HASH) {
3336                                 slab = hash_sfind(&keg->uk_hash, mem);
3337                         } else {
3338                                 mem += keg->uk_pgoff;
3339                                 slab = (uma_slab_t)mem;
3340                         }
3341                 } else {
3342                         slab = vtoslab((vm_offset_t)item);
3343                         MPASS(slab->us_keg == keg);
3344                 }
3345                 slab_free_item(zone, slab, item);
3346         }
3347         KEG_UNLOCK(keg);
3348 }
3349
3350 /*
3351  * Frees a single item to any zone.
3352  *
3353  * Arguments:
3354  *      zone   The zone to free to
3355  *      item   The item we're freeing
3356  *      udata  User supplied data for the dtor
3357  *      skip   Skip dtors and finis
3358  */
3359 static void
3360 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3361 {
3362 #ifdef INVARIANTS
3363         bool skipdbg;
3364
3365         skipdbg = uma_dbg_zskip(zone, item);
3366         if (skip == SKIP_NONE && !skipdbg) {
3367                 if (zone->uz_flags & UMA_ZONE_MALLOC)
3368                         uma_dbg_free(zone, udata, item);
3369                 else
3370                         uma_dbg_free(zone, NULL, item);
3371         }
3372
3373         if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3374             (!skipdbg || zone->uz_dtor != trash_dtor ||
3375             zone->uz_ctor != trash_ctor))
3376 #else
3377         if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3378 #endif
3379                 zone->uz_dtor(item, zone->uz_size, udata);
3380
3381         if (skip < SKIP_FINI && zone->uz_fini)
3382                 zone->uz_fini(item, zone->uz_size);
3383
3384         zone->uz_release(zone->uz_arg, &item, 1);
3385
3386         if (skip & SKIP_CNT)
3387                 return;
3388
3389         counter_u64_add(zone->uz_frees, 1);
3390
3391         if (zone->uz_max_items > 0) {
3392                 ZONE_LOCK(zone);
3393                 zone->uz_items--;
3394                 if (zone->uz_sleepers > 0 &&
3395                     zone->uz_items < zone->uz_max_items)
3396                         wakeup_one(zone);
3397                 ZONE_UNLOCK(zone);
3398         }
3399 }
3400
3401 /* See uma.h */
3402 int
3403 uma_zone_set_max(uma_zone_t zone, int nitems)
3404 {
3405         struct uma_bucket_zone *ubz;
3406
3407         /*
3408          * If limit is very low we may need to limit how
3409          * much items are allowed in CPU caches.
3410          */
3411         ubz = &bucket_zones[0];
3412         for (; ubz->ubz_entries != 0; ubz++)
3413                 if (ubz->ubz_entries * 2 * mp_ncpus > nitems)
3414                         break;
3415         if (ubz == &bucket_zones[0])
3416                 nitems = ubz->ubz_entries * 2 * mp_ncpus;
3417         else
3418                 ubz--;
3419
3420         ZONE_LOCK(zone);
3421         zone->uz_count_max = zone->uz_count = ubz->ubz_entries;
3422         if (zone->uz_count_min > zone->uz_count_max)
3423                 zone->uz_count_min = zone->uz_count_max;
3424         zone->uz_max_items = nitems;
3425         ZONE_UNLOCK(zone);
3426
3427         return (nitems);
3428 }
3429
3430 /* See uma.h */
3431 int
3432 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
3433 {
3434
3435         ZONE_LOCK(zone);
3436         zone->uz_bkt_max = nitems;
3437         ZONE_UNLOCK(zone);
3438
3439         return (nitems);
3440 }
3441
3442 /* See uma.h */
3443 int
3444 uma_zone_get_max(uma_zone_t zone)
3445 {
3446         int nitems;
3447
3448         ZONE_LOCK(zone);
3449         nitems = zone->uz_max_items;
3450         ZONE_UNLOCK(zone);
3451
3452         return (nitems);
3453 }
3454
3455 /* See uma.h */
3456 void
3457 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3458 {
3459
3460         ZONE_LOCK(zone);
3461         zone->uz_warning = warning;
3462         ZONE_UNLOCK(zone);
3463 }
3464
3465 /* See uma.h */
3466 void
3467 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3468 {
3469
3470         ZONE_LOCK(zone);
3471         TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3472         ZONE_UNLOCK(zone);
3473 }
3474
3475 /* See uma.h */
3476 int
3477 uma_zone_get_cur(uma_zone_t zone)
3478 {
3479         int64_t nitems;
3480         u_int i;
3481
3482         ZONE_LOCK(zone);
3483         nitems = counter_u64_fetch(zone->uz_allocs) -
3484             counter_u64_fetch(zone->uz_frees);
3485         CPU_FOREACH(i) {
3486                 /*
3487                  * See the comment in uma_vm_zone_stats() regarding the
3488                  * safety of accessing the per-cpu caches. With the zone lock
3489                  * held, it is safe, but can potentially result in stale data.
3490                  */
3491                 nitems += zone->uz_cpu[i].uc_allocs -
3492                     zone->uz_cpu[i].uc_frees;
3493         }
3494         ZONE_UNLOCK(zone);
3495
3496         return (nitems < 0 ? 0 : nitems);
3497 }
3498
3499 /* See uma.h */
3500 void
3501 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3502 {
3503         uma_keg_t keg;
3504
3505         KEG_GET(zone, keg);
3506         KEG_LOCK(keg);
3507         KASSERT(keg->uk_pages == 0,
3508             ("uma_zone_set_init on non-empty keg"));
3509         keg->uk_init = uminit;
3510         KEG_UNLOCK(keg);
3511 }
3512
3513 /* See uma.h */
3514 void
3515 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3516 {
3517         uma_keg_t keg;
3518
3519         KEG_GET(zone, keg);
3520         KEG_LOCK(keg);
3521         KASSERT(keg->uk_pages == 0,
3522             ("uma_zone_set_fini on non-empty keg"));
3523         keg->uk_fini = fini;
3524         KEG_UNLOCK(keg);
3525 }
3526
3527 /* See uma.h */
3528 void
3529 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3530 {
3531
3532         ZONE_LOCK(zone);
3533         KASSERT(zone->uz_keg->uk_pages == 0,
3534             ("uma_zone_set_zinit on non-empty keg"));
3535         zone->uz_init = zinit;
3536         ZONE_UNLOCK(zone);
3537 }
3538
3539 /* See uma.h */
3540 void
3541 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3542 {
3543
3544         ZONE_LOCK(zone);
3545         KASSERT(zone->uz_keg->uk_pages == 0,
3546             ("uma_zone_set_zfini on non-empty keg"));
3547         zone->uz_fini = zfini;
3548         ZONE_UNLOCK(zone);
3549 }
3550
3551 /* See uma.h */
3552 /* XXX uk_freef is not actually used with the zone locked */
3553 void
3554 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3555 {
3556         uma_keg_t keg;
3557
3558         KEG_GET(zone, keg);
3559         KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3560         KEG_LOCK(keg);
3561         keg->uk_freef = freef;
3562         KEG_UNLOCK(keg);
3563 }
3564
3565 /* See uma.h */
3566 /* XXX uk_allocf is not actually used with the zone locked */
3567 void
3568 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3569 {
3570         uma_keg_t keg;
3571
3572         KEG_GET(zone, keg);
3573         KEG_LOCK(keg);
3574         keg->uk_allocf = allocf;
3575         KEG_UNLOCK(keg);
3576 }
3577
3578 /* See uma.h */
3579 void
3580 uma_zone_reserve(uma_zone_t zone, int items)
3581 {
3582         uma_keg_t keg;
3583
3584         KEG_GET(zone, keg);
3585         KEG_LOCK(keg);
3586         keg->uk_reserve = items;
3587         KEG_UNLOCK(keg);
3588 }
3589
3590 /* See uma.h */
3591 int
3592 uma_zone_reserve_kva(uma_zone_t zone, int count)
3593 {
3594         uma_keg_t keg;
3595         vm_offset_t kva;
3596         u_int pages;
3597
3598         KEG_GET(zone, keg);
3599
3600         pages = count / keg->uk_ipers;
3601         if (pages * keg->uk_ipers < count)
3602                 pages++;
3603         pages *= keg->uk_ppera;
3604
3605 #ifdef UMA_MD_SMALL_ALLOC
3606         if (keg->uk_ppera > 1) {
3607 #else
3608         if (1) {
3609 #endif
3610                 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3611                 if (kva == 0)
3612                         return (0);
3613         } else
3614                 kva = 0;
3615
3616         ZONE_LOCK(zone);
3617         MPASS(keg->uk_kva == 0);
3618         keg->uk_kva = kva;
3619         keg->uk_offset = 0;
3620         zone->uz_max_items = pages * keg->uk_ipers;
3621 #ifdef UMA_MD_SMALL_ALLOC
3622         keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3623 #else
3624         keg->uk_allocf = noobj_alloc;
3625 #endif
3626         keg->uk_flags |= UMA_ZONE_NOFREE;
3627         ZONE_UNLOCK(zone);
3628
3629         return (1);
3630 }
3631
3632 /* See uma.h */
3633 void
3634 uma_prealloc(uma_zone_t zone, int items)
3635 {
3636         struct vm_domainset_iter di;
3637         uma_domain_t dom;
3638         uma_slab_t slab;
3639         uma_keg_t keg;
3640         int aflags, domain, slabs;
3641
3642         KEG_GET(zone, keg);
3643         KEG_LOCK(keg);
3644         slabs = items / keg->uk_ipers;
3645         if (slabs * keg->uk_ipers < items)
3646                 slabs++;
3647         while (slabs-- > 0) {
3648                 aflags = M_NOWAIT;
3649                 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3650                     &aflags);
3651                 for (;;) {
3652                         slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
3653                             aflags);
3654                         if (slab != NULL) {
3655                                 MPASS(slab->us_keg == keg);
3656                                 dom = &keg->uk_domain[slab->us_domain];
3657                                 LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
3658                                     us_link);
3659                                 break;
3660                         }
3661                         KEG_LOCK(keg);
3662                         if (vm_domainset_iter_policy(&di, &domain) != 0) {
3663                                 KEG_UNLOCK(keg);
3664                                 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
3665                                 KEG_LOCK(keg);
3666                         }
3667                 }
3668         }
3669         KEG_UNLOCK(keg);
3670 }
3671
3672 /* See uma.h */
3673 static void
3674 uma_reclaim_locked(bool kmem_danger)
3675 {
3676
3677         CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3678         sx_assert(&uma_drain_lock, SA_XLOCKED);
3679         bucket_enable();
3680         zone_foreach(zone_drain);
3681         if (vm_page_count_min() || kmem_danger) {
3682                 cache_drain_safe(NULL);
3683                 zone_foreach(zone_drain);
3684         }
3685
3686         /*
3687          * Some slabs may have been freed but this zone will be visited early
3688          * we visit again so that we can free pages that are empty once other
3689          * zones are drained.  We have to do the same for buckets.
3690          */
3691         zone_drain(slabzone);
3692         bucket_zone_drain();
3693 }
3694
3695 void
3696 uma_reclaim(void)
3697 {
3698
3699         sx_xlock(&uma_drain_lock);
3700         uma_reclaim_locked(false);
3701         sx_xunlock(&uma_drain_lock);
3702 }
3703
3704 static volatile int uma_reclaim_needed;
3705
3706 void
3707 uma_reclaim_wakeup(void)
3708 {
3709
3710         if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3711                 wakeup(uma_reclaim);
3712 }
3713
3714 void
3715 uma_reclaim_worker(void *arg __unused)
3716 {
3717
3718         for (;;) {
3719                 sx_xlock(&uma_drain_lock);
3720                 while (atomic_load_int(&uma_reclaim_needed) == 0)
3721                         sx_sleep(uma_reclaim, &uma_drain_lock, PVM, "umarcl",
3722                             hz);
3723                 sx_xunlock(&uma_drain_lock);
3724                 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3725                 sx_xlock(&uma_drain_lock);
3726                 uma_reclaim_locked(true);
3727                 atomic_store_int(&uma_reclaim_needed, 0);
3728                 sx_xunlock(&uma_drain_lock);
3729                 /* Don't fire more than once per-second. */
3730                 pause("umarclslp", hz);
3731         }
3732 }
3733
3734 /* See uma.h */
3735 int
3736 uma_zone_exhausted(uma_zone_t zone)
3737 {
3738         int full;
3739
3740         ZONE_LOCK(zone);
3741         full = zone->uz_sleepers > 0;
3742         ZONE_UNLOCK(zone);
3743         return (full);  
3744 }
3745
3746 int
3747 uma_zone_exhausted_nolock(uma_zone_t zone)
3748 {
3749         return (zone->uz_sleepers > 0);
3750 }
3751
3752 void *
3753 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3754 {
3755         struct domainset *policy;
3756         vm_offset_t addr;
3757         uma_slab_t slab;
3758
3759         if (domain != UMA_ANYDOMAIN) {
3760                 /* avoid allocs targeting empty domains */
3761                 if (VM_DOMAIN_EMPTY(domain))
3762                         domain = UMA_ANYDOMAIN;
3763         }
3764         slab = zone_alloc_item(slabzone, NULL, domain, wait);
3765         if (slab == NULL)
3766                 return (NULL);
3767         policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3768             DOMAINSET_FIXED(domain);
3769         addr = kmem_malloc_domainset(policy, size, wait);
3770         if (addr != 0) {
3771                 vsetslab(addr, slab);
3772                 slab->us_data = (void *)addr;
3773                 slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3774                 slab->us_size = size;
3775                 slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3776                     pmap_kextract(addr)));
3777                 uma_total_inc(size);
3778         } else {
3779                 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3780         }
3781
3782         return ((void *)addr);
3783 }
3784
3785 void *
3786 uma_large_malloc(vm_size_t size, int wait)
3787 {
3788
3789         return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3790 }
3791
3792 void
3793 uma_large_free(uma_slab_t slab)
3794 {
3795
3796         KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3797             ("uma_large_free:  Memory not allocated with uma_large_malloc."));
3798         kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3799         uma_total_dec(slab->us_size);
3800         zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3801 }
3802
3803 static void
3804 uma_zero_item(void *item, uma_zone_t zone)
3805 {
3806
3807         bzero(item, zone->uz_size);
3808 }
3809
3810 unsigned long
3811 uma_limit(void)
3812 {
3813
3814         return (uma_kmem_limit);
3815 }
3816
3817 void
3818 uma_set_limit(unsigned long limit)
3819 {
3820
3821         uma_kmem_limit = limit;
3822 }
3823
3824 unsigned long
3825 uma_size(void)
3826 {
3827
3828         return (atomic_load_long(&uma_kmem_total));
3829 }
3830
3831 long
3832 uma_avail(void)
3833 {
3834
3835         return (uma_kmem_limit - uma_size());
3836 }
3837
3838 void
3839 uma_print_stats(void)
3840 {
3841         zone_foreach(uma_print_zone);
3842 }
3843
3844 static void
3845 slab_print(uma_slab_t slab)
3846 {
3847         printf("slab: keg %p, data %p, freecount %d\n",
3848                 slab->us_keg, slab->us_data, slab->us_freecount);
3849 }
3850
3851 static void
3852 cache_print(uma_cache_t cache)
3853 {
3854         printf("alloc: %p(%d), free: %p(%d), cross: %p(%d)j\n",
3855                 cache->uc_allocbucket,
3856                 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3857                 cache->uc_freebucket,
3858                 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0,
3859                 cache->uc_crossbucket,
3860                 cache->uc_crossbucket?cache->uc_crossbucket->ub_cnt:0);
3861 }
3862
3863 static void
3864 uma_print_keg(uma_keg_t keg)
3865 {
3866         uma_domain_t dom;
3867         uma_slab_t slab;
3868         int i;
3869
3870         printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3871             "out %d free %d\n",
3872             keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3873             keg->uk_ipers, keg->uk_ppera,
3874             (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3875             keg->uk_free);
3876         for (i = 0; i < vm_ndomains; i++) {
3877                 dom = &keg->uk_domain[i];
3878                 printf("Part slabs:\n");
3879                 LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3880                         slab_print(slab);
3881                 printf("Free slabs:\n");
3882                 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3883                         slab_print(slab);
3884                 printf("Full slabs:\n");
3885                 LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3886                         slab_print(slab);
3887         }
3888 }
3889
3890 void
3891 uma_print_zone(uma_zone_t zone)
3892 {
3893         uma_cache_t cache;
3894         int i;
3895
3896         printf("zone: %s(%p) size %d maxitems %ju flags %#x\n",
3897             zone->uz_name, zone, zone->uz_size, (uintmax_t)zone->uz_max_items,
3898             zone->uz_flags);
3899         if (zone->uz_lockptr != &zone->uz_lock)
3900                 uma_print_keg(zone->uz_keg);
3901         CPU_FOREACH(i) {
3902                 cache = &zone->uz_cpu[i];
3903                 printf("CPU %d Cache:\n", i);
3904                 cache_print(cache);
3905         }
3906 }
3907
3908 #ifdef DDB
3909 /*
3910  * Generate statistics across both the zone and its per-cpu cache's.  Return
3911  * desired statistics if the pointer is non-NULL for that statistic.
3912  *
3913  * Note: does not update the zone statistics, as it can't safely clear the
3914  * per-CPU cache statistic.
3915  *
3916  * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3917  * safe from off-CPU; we should modify the caches to track this information
3918  * directly so that we don't have to.
3919  */
3920 static void
3921 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
3922     uint64_t *freesp, uint64_t *sleepsp, uint64_t *xdomainp)
3923 {
3924         uma_cache_t cache;
3925         uint64_t allocs, frees, sleeps, xdomain;
3926         int cachefree, cpu;
3927
3928         allocs = frees = sleeps = xdomain = 0;
3929         cachefree = 0;
3930         CPU_FOREACH(cpu) {
3931                 cache = &z->uz_cpu[cpu];
3932                 if (cache->uc_allocbucket != NULL)
3933                         cachefree += cache->uc_allocbucket->ub_cnt;
3934                 if (cache->uc_freebucket != NULL)
3935                         cachefree += cache->uc_freebucket->ub_cnt;
3936                 if (cache->uc_crossbucket != NULL) {
3937                         xdomain += cache->uc_crossbucket->ub_cnt;
3938                         cachefree += cache->uc_crossbucket->ub_cnt;
3939                 }
3940                 allocs += cache->uc_allocs;
3941                 frees += cache->uc_frees;
3942         }
3943         allocs += counter_u64_fetch(z->uz_allocs);
3944         frees += counter_u64_fetch(z->uz_frees);
3945         sleeps += z->uz_sleeps;
3946         xdomain += z->uz_xdomain;
3947         if (cachefreep != NULL)
3948                 *cachefreep = cachefree;
3949         if (allocsp != NULL)
3950                 *allocsp = allocs;
3951         if (freesp != NULL)
3952                 *freesp = frees;
3953         if (sleepsp != NULL)
3954                 *sleepsp = sleeps;
3955         if (xdomainp != NULL)
3956                 *xdomainp = xdomain;
3957 }
3958 #endif /* DDB */
3959
3960 static int
3961 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3962 {
3963         uma_keg_t kz;
3964         uma_zone_t z;
3965         int count;
3966
3967         count = 0;
3968         rw_rlock(&uma_rwlock);
3969         LIST_FOREACH(kz, &uma_kegs, uk_link) {
3970                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3971                         count++;
3972         }
3973         LIST_FOREACH(z, &uma_cachezones, uz_link)
3974                 count++;
3975
3976         rw_runlock(&uma_rwlock);
3977         return (sysctl_handle_int(oidp, &count, 0, req));
3978 }
3979
3980 static void
3981 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
3982     struct uma_percpu_stat *ups, bool internal)
3983 {
3984         uma_zone_domain_t zdom;
3985         uma_cache_t cache;
3986         int i;
3987
3988
3989         for (i = 0; i < vm_ndomains; i++) {
3990                 zdom = &z->uz_domain[i];
3991                 uth->uth_zone_free += zdom->uzd_nitems;
3992         }
3993         uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
3994         uth->uth_frees = counter_u64_fetch(z->uz_frees);
3995         uth->uth_fails = counter_u64_fetch(z->uz_fails);
3996         uth->uth_sleeps = z->uz_sleeps;
3997         uth->uth_xdomain = z->uz_xdomain;
3998         /*
3999          * While it is not normally safe to access the cache
4000          * bucket pointers while not on the CPU that owns the
4001          * cache, we only allow the pointers to be exchanged
4002          * without the zone lock held, not invalidated, so
4003          * accept the possible race associated with bucket
4004          * exchange during monitoring.
4005          */
4006         for (i = 0; i < mp_maxid + 1; i++) {
4007                 bzero(&ups[i], sizeof(*ups));
4008                 if (internal || CPU_ABSENT(i))
4009                         continue;
4010                 cache = &z->uz_cpu[i];
4011                 if (cache->uc_allocbucket != NULL)
4012                         ups[i].ups_cache_free +=
4013                             cache->uc_allocbucket->ub_cnt;
4014                 if (cache->uc_freebucket != NULL)
4015                         ups[i].ups_cache_free +=
4016                             cache->uc_freebucket->ub_cnt;
4017                 if (cache->uc_crossbucket != NULL)
4018                         ups[i].ups_cache_free +=
4019                             cache->uc_crossbucket->ub_cnt;
4020                 ups[i].ups_allocs = cache->uc_allocs;
4021                 ups[i].ups_frees = cache->uc_frees;
4022         }
4023 }
4024
4025 static int
4026 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
4027 {
4028         struct uma_stream_header ush;
4029         struct uma_type_header uth;
4030         struct uma_percpu_stat *ups;
4031         struct sbuf sbuf;
4032         uma_keg_t kz;
4033         uma_zone_t z;
4034         int count, error, i;
4035
4036         error = sysctl_wire_old_buffer(req, 0);
4037         if (error != 0)
4038                 return (error);
4039         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
4040         sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
4041         ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
4042
4043         count = 0;
4044         rw_rlock(&uma_rwlock);
4045         LIST_FOREACH(kz, &uma_kegs, uk_link) {
4046                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
4047                         count++;
4048         }
4049
4050         LIST_FOREACH(z, &uma_cachezones, uz_link)
4051                 count++;
4052
4053         /*
4054          * Insert stream header.
4055          */
4056         bzero(&ush, sizeof(ush));
4057         ush.ush_version = UMA_STREAM_VERSION;
4058         ush.ush_maxcpus = (mp_maxid + 1);
4059         ush.ush_count = count;
4060         (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
4061
4062         LIST_FOREACH(kz, &uma_kegs, uk_link) {
4063                 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4064                         bzero(&uth, sizeof(uth));
4065                         ZONE_LOCK(z);
4066                         strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
4067                         uth.uth_align = kz->uk_align;
4068                         uth.uth_size = kz->uk_size;
4069                         uth.uth_rsize = kz->uk_rsize;
4070                         if (z->uz_max_items > 0)
4071                                 uth.uth_pages = (z->uz_items / kz->uk_ipers) *
4072                                         kz->uk_ppera;
4073                         else
4074                                 uth.uth_pages = kz->uk_pages;
4075                         uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
4076                             kz->uk_ppera;
4077                         uth.uth_limit = z->uz_max_items;
4078                         uth.uth_keg_free = z->uz_keg->uk_free;
4079
4080                         /*
4081                          * A zone is secondary is it is not the first entry
4082                          * on the keg's zone list.
4083                          */
4084                         if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
4085                             (LIST_FIRST(&kz->uk_zones) != z))
4086                                 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
4087                         uma_vm_zone_stats(&uth, z, &sbuf, ups,
4088                             kz->uk_flags & UMA_ZFLAG_INTERNAL);
4089                         ZONE_UNLOCK(z);
4090                         (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4091                         for (i = 0; i < mp_maxid + 1; i++)
4092                                 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4093                 }
4094         }
4095         LIST_FOREACH(z, &uma_cachezones, uz_link) {
4096                 bzero(&uth, sizeof(uth));
4097                 ZONE_LOCK(z);
4098                 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
4099                 uth.uth_size = z->uz_size;
4100                 uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
4101                 ZONE_UNLOCK(z);
4102                 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4103                 for (i = 0; i < mp_maxid + 1; i++)
4104                         (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4105         }
4106
4107         rw_runlock(&uma_rwlock);
4108         error = sbuf_finish(&sbuf);
4109         sbuf_delete(&sbuf);
4110         free(ups, M_TEMP);
4111         return (error);
4112 }
4113
4114 int
4115 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
4116 {
4117         uma_zone_t zone = *(uma_zone_t *)arg1;
4118         int error, max;
4119
4120         max = uma_zone_get_max(zone);
4121         error = sysctl_handle_int(oidp, &max, 0, req);
4122         if (error || !req->newptr)
4123                 return (error);
4124
4125         uma_zone_set_max(zone, max);
4126
4127         return (0);
4128 }
4129
4130 int
4131 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
4132 {
4133         uma_zone_t zone = *(uma_zone_t *)arg1;
4134         int cur;
4135
4136         cur = uma_zone_get_cur(zone);
4137         return (sysctl_handle_int(oidp, &cur, 0, req));
4138 }
4139
4140 #ifdef INVARIANTS
4141 static uma_slab_t
4142 uma_dbg_getslab(uma_zone_t zone, void *item)
4143 {
4144         uma_slab_t slab;
4145         uma_keg_t keg;
4146         uint8_t *mem;
4147
4148         mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4149         if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
4150                 slab = vtoslab((vm_offset_t)mem);
4151         } else {
4152                 /*
4153                  * It is safe to return the slab here even though the
4154                  * zone is unlocked because the item's allocation state
4155                  * essentially holds a reference.
4156                  */
4157                 if (zone->uz_lockptr == &zone->uz_lock)
4158                         return (NULL);
4159                 ZONE_LOCK(zone);
4160                 keg = zone->uz_keg;
4161                 if (keg->uk_flags & UMA_ZONE_HASH)
4162                         slab = hash_sfind(&keg->uk_hash, mem);
4163                 else
4164                         slab = (uma_slab_t)(mem + keg->uk_pgoff);
4165                 ZONE_UNLOCK(zone);
4166         }
4167
4168         return (slab);
4169 }
4170
4171 static bool
4172 uma_dbg_zskip(uma_zone_t zone, void *mem)
4173 {
4174
4175         if (zone->uz_lockptr == &zone->uz_lock)
4176                 return (true);
4177
4178         return (uma_dbg_kskip(zone->uz_keg, mem));
4179 }
4180
4181 static bool
4182 uma_dbg_kskip(uma_keg_t keg, void *mem)
4183 {
4184         uintptr_t idx;
4185
4186         if (dbg_divisor == 0)
4187                 return (true);
4188
4189         if (dbg_divisor == 1)
4190                 return (false);
4191
4192         idx = (uintptr_t)mem >> PAGE_SHIFT;
4193         if (keg->uk_ipers > 1) {
4194                 idx *= keg->uk_ipers;
4195                 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4196         }
4197
4198         if ((idx / dbg_divisor) * dbg_divisor != idx) {
4199                 counter_u64_add(uma_skip_cnt, 1);
4200                 return (true);
4201         }
4202         counter_u64_add(uma_dbg_cnt, 1);
4203
4204         return (false);
4205 }
4206
4207 /*
4208  * Set up the slab's freei data such that uma_dbg_free can function.
4209  *
4210  */
4211 static void
4212 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4213 {
4214         uma_keg_t keg;
4215         int freei;
4216
4217         if (slab == NULL) {
4218                 slab = uma_dbg_getslab(zone, item);
4219                 if (slab == NULL) 
4220                         panic("uma: item %p did not belong to zone %s\n",
4221                             item, zone->uz_name);
4222         }
4223         keg = slab->us_keg;
4224         freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4225
4226         if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4227                 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4228                     item, zone, zone->uz_name, slab, freei);
4229         BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4230
4231         return;
4232 }
4233
4234 /*
4235  * Verifies freed addresses.  Checks for alignment, valid slab membership
4236  * and duplicate frees.
4237  *
4238  */
4239 static void
4240 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4241 {
4242         uma_keg_t keg;
4243         int freei;
4244
4245         if (slab == NULL) {
4246                 slab = uma_dbg_getslab(zone, item);
4247                 if (slab == NULL) 
4248                         panic("uma: Freed item %p did not belong to zone %s\n",
4249                             item, zone->uz_name);
4250         }
4251         keg = slab->us_keg;
4252         freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4253
4254         if (freei >= keg->uk_ipers)
4255                 panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4256                     item, zone, zone->uz_name, slab, freei);
4257
4258         if (((freei * keg->uk_rsize) + slab->us_data) != item) 
4259                 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4260                     item, zone, zone->uz_name, slab, freei);
4261
4262         if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4263                 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4264                     item, zone, zone->uz_name, slab, freei);
4265
4266         BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4267 }
4268 #endif /* INVARIANTS */
4269
4270 #ifdef DDB
4271 DB_SHOW_COMMAND(uma, db_show_uma)
4272 {
4273         uma_keg_t kz;
4274         uma_zone_t z;
4275         uint64_t allocs, frees, sleeps, xdomain;
4276         long cachefree;
4277         int i;
4278
4279         db_printf("%18s %8s %8s %8s %12s %8s %8s %8s\n", "Zone", "Size", "Used",
4280             "Free", "Requests", "Sleeps", "Bucket", "XFree");
4281         LIST_FOREACH(kz, &uma_kegs, uk_link) {
4282                 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4283                         if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4284                                 allocs = counter_u64_fetch(z->uz_allocs);
4285                                 frees = counter_u64_fetch(z->uz_frees);
4286                                 sleeps = z->uz_sleeps;
4287                                 cachefree = 0;
4288                         } else
4289                                 uma_zone_sumstat(z, &cachefree, &allocs,
4290                                     &frees, &sleeps, &xdomain);
4291                         if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4292                             (LIST_FIRST(&kz->uk_zones) != z)))
4293                                 cachefree += kz->uk_free;
4294                         for (i = 0; i < vm_ndomains; i++)
4295                                 cachefree += z->uz_domain[i].uzd_nitems;
4296
4297                         db_printf("%18s %8ju %8jd %8ld %12ju %8ju %8u %8ju\n",
4298                             z->uz_name, (uintmax_t)kz->uk_size,
4299                             (intmax_t)(allocs - frees), cachefree,
4300                             (uintmax_t)allocs, sleeps, z->uz_count, xdomain);
4301                         if (db_pager_quit)
4302                                 return;
4303                 }
4304         }
4305 }
4306
4307 DB_SHOW_COMMAND(umacache, db_show_umacache)
4308 {
4309         uma_zone_t z;
4310         uint64_t allocs, frees;
4311         long cachefree;
4312         int i;
4313
4314         db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4315             "Requests", "Bucket");
4316         LIST_FOREACH(z, &uma_cachezones, uz_link) {
4317                 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL, NULL);
4318                 for (i = 0; i < vm_ndomains; i++)
4319                         cachefree += z->uz_domain[i].uzd_nitems;
4320                 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
4321                     z->uz_name, (uintmax_t)z->uz_size,
4322                     (intmax_t)(allocs - frees), cachefree,
4323                     (uintmax_t)allocs, z->uz_count);
4324                 if (db_pager_quit)
4325                         return;
4326         }
4327 }
4328 #endif  /* DDB */