]> CyberLeo.Net >> Repos - FreeBSD/releng/9.3.git/blob - sys/vm/uma_core.c
Prefix SA-14:16.file with 'FreeBSD-' for consistency with other SA
[FreeBSD/releng/9.3.git] / sys / vm / uma_core.c
1 /*-
2  * Copyright (c) 2002-2005, 2009 Jeffrey Roberson <jeff@FreeBSD.org>
3  * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
4  * Copyright (c) 2004-2006 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 /*
30  * uma_core.c  Implementation of the Universal Memory allocator
31  *
32  * This allocator is intended to replace the multitude of similar object caches
33  * in the standard FreeBSD kernel.  The intent is to be flexible as well as
34  * effecient.  A primary design goal is to return unused memory to the rest of
35  * the system.  This will make the system as a whole more flexible due to the
36  * ability to move memory to subsystems which most need it instead of leaving
37  * pools of reserved memory unused.
38  *
39  * The basic ideas stem from similar slab/zone based allocators whose algorithms
40  * are well known.
41  *
42  */
43
44 /*
45  * TODO:
46  *      - Improve memory usage for large allocations
47  *      - Investigate cache size adjustments
48  */
49
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
52
53 /* I should really use ktr.. */
54 /*
55 #define UMA_DEBUG 1
56 #define UMA_DEBUG_ALLOC 1
57 #define UMA_DEBUG_ALLOC_1 1
58 */
59
60 #include "opt_ddb.h"
61 #include "opt_param.h"
62
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/kernel.h>
66 #include <sys/types.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/sbuf.h>
75 #include <sys/smp.h>
76 #include <sys/vmmeter.h>
77
78 #include <vm/vm.h>
79 #include <vm/vm_object.h>
80 #include <vm/vm_page.h>
81 #include <vm/vm_param.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_kern.h>
84 #include <vm/vm_extern.h>
85 #include <vm/uma.h>
86 #include <vm/uma_int.h>
87 #include <vm/uma_dbg.h>
88
89 #include <ddb/ddb.h>
90
91 /*
92  * This is the zone and keg from which all zones are spawned.  The idea is that
93  * even the zone & keg heads are allocated from the allocator, so we use the
94  * bss section to bootstrap us.
95  */
96 static struct uma_keg masterkeg;
97 static struct uma_zone masterzone_k;
98 static struct uma_zone masterzone_z;
99 static uma_zone_t kegs = &masterzone_k;
100 static uma_zone_t zones = &masterzone_z;
101
102 /* This is the zone from which all of uma_slab_t's are allocated. */
103 static uma_zone_t slabzone;
104 static uma_zone_t slabrefzone;  /* With refcounters (for UMA_ZONE_REFCNT) */
105
106 /*
107  * The initial hash tables come out of this zone so they can be allocated
108  * prior to malloc coming up.
109  */
110 static uma_zone_t hashzone;
111
112 /* The boot-time adjusted value for cache line alignment. */
113 int uma_align_cache = 64 - 1;
114
115 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
116
117 /*
118  * Are we allowed to allocate buckets?
119  */
120 static int bucketdisable = 1;
121
122 /* Linked list of all kegs in the system */
123 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
124
125 /* This mutex protects the keg list */
126 static struct mtx uma_mtx;
127
128 /* Linked list of boot time pages */
129 static LIST_HEAD(,uma_slab) uma_boot_pages =
130     LIST_HEAD_INITIALIZER(uma_boot_pages);
131
132 /* This mutex protects the boot time pages list */
133 static struct mtx uma_boot_pages_mtx;
134
135 /* Is the VM done starting up? */
136 static int booted = 0;
137 #define UMA_STARTUP     1
138 #define UMA_STARTUP2    2
139
140 /* Maximum number of allowed items-per-slab if the slab header is OFFPAGE */
141 static u_int uma_max_ipers;
142 static u_int uma_max_ipers_ref;
143
144 /*
145  * This is the handle used to schedule events that need to happen
146  * outside of the allocation fast path.
147  */
148 static struct callout uma_callout;
149 #define UMA_TIMEOUT     20              /* Seconds for callout interval. */
150
151 /*
152  * This structure is passed as the zone ctor arg so that I don't have to create
153  * a special allocation function just for zones.
154  */
155 struct uma_zctor_args {
156         const char *name;
157         size_t size;
158         uma_ctor ctor;
159         uma_dtor dtor;
160         uma_init uminit;
161         uma_fini fini;
162         uma_keg_t keg;
163         int align;
164         u_int32_t flags;
165 };
166
167 struct uma_kctor_args {
168         uma_zone_t zone;
169         size_t size;
170         uma_init uminit;
171         uma_fini fini;
172         int align;
173         u_int32_t flags;
174 };
175
176 struct uma_bucket_zone {
177         uma_zone_t      ubz_zone;
178         char            *ubz_name;
179         int             ubz_entries;
180 };
181
182 #define BUCKET_MAX      128
183
184 struct uma_bucket_zone bucket_zones[] = {
185         { NULL, "16 Bucket", 16 },
186         { NULL, "32 Bucket", 32 },
187         { NULL, "64 Bucket", 64 },
188         { NULL, "128 Bucket", 128 },
189         { NULL, NULL, 0}
190 };
191
192 #define BUCKET_SHIFT    4
193 #define BUCKET_ZONES    ((BUCKET_MAX >> BUCKET_SHIFT) + 1)
194
195 /*
196  * bucket_size[] maps requested bucket sizes to zones that allocate a bucket
197  * of approximately the right size.
198  */
199 static uint8_t bucket_size[BUCKET_ZONES];
200
201 /*
202  * Flags and enumerations to be passed to internal functions.
203  */
204 enum zfreeskip { SKIP_NONE, SKIP_DTOR, SKIP_FINI };
205
206 #define ZFREE_STATFAIL  0x00000001      /* Update zone failure statistic. */
207 #define ZFREE_STATFREE  0x00000002      /* Update zone free statistic. */
208
209 /* Prototypes.. */
210
211 static void *obj_alloc(uma_zone_t, int, u_int8_t *, int);
212 static void *page_alloc(uma_zone_t, int, u_int8_t *, int);
213 static void *startup_alloc(uma_zone_t, int, u_int8_t *, int);
214 static void page_free(void *, int, u_int8_t);
215 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int);
216 static void cache_drain(uma_zone_t);
217 static void bucket_drain(uma_zone_t, uma_bucket_t);
218 static void bucket_cache_drain(uma_zone_t zone);
219 static int keg_ctor(void *, int, void *, int);
220 static void keg_dtor(void *, int, void *);
221 static int zone_ctor(void *, int, void *, int);
222 static void zone_dtor(void *, int, void *);
223 static int zero_init(void *, int, int);
224 static void keg_small_init(uma_keg_t keg);
225 static void keg_large_init(uma_keg_t keg);
226 static void zone_foreach(void (*zfunc)(uma_zone_t));
227 static void zone_timeout(uma_zone_t zone);
228 static int hash_alloc(struct uma_hash *);
229 static int hash_expand(struct uma_hash *, struct uma_hash *);
230 static void hash_free(struct uma_hash *hash);
231 static void uma_timeout(void *);
232 static void uma_startup3(void);
233 static void *zone_alloc_item(uma_zone_t, void *, int);
234 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip,
235     int);
236 static void bucket_enable(void);
237 static void bucket_init(void);
238 static uma_bucket_t bucket_alloc(int, int);
239 static void bucket_free(uma_bucket_t);
240 static void bucket_zone_drain(void);
241 static int zone_alloc_bucket(uma_zone_t zone, int flags);
242 static uma_slab_t zone_fetch_slab(uma_zone_t zone, uma_keg_t last, int flags);
243 static uma_slab_t zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int flags);
244 static void *slab_alloc_item(uma_zone_t zone, uma_slab_t slab);
245 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
246     uma_fini fini, int align, u_int32_t flags);
247 static inline void zone_relock(uma_zone_t zone, uma_keg_t keg);
248 static inline void keg_relock(uma_keg_t keg, uma_zone_t zone);
249
250 void uma_print_zone(uma_zone_t);
251 void uma_print_stats(void);
252 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
253 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
254
255 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
256
257 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
258     0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
259
260 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
261     0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
262
263 /*
264  * This routine checks to see whether or not it's safe to enable buckets.
265  */
266
267 static void
268 bucket_enable(void)
269 {
270         bucketdisable = vm_page_count_min();
271 }
272
273 /*
274  * Initialize bucket_zones, the array of zones of buckets of various sizes.
275  *
276  * For each zone, calculate the memory required for each bucket, consisting
277  * of the header and an array of pointers.  Initialize bucket_size[] to point
278  * the range of appropriate bucket sizes at the zone.
279  */
280 static void
281 bucket_init(void)
282 {
283         struct uma_bucket_zone *ubz;
284         int i;
285         int j;
286
287         for (i = 0, j = 0; bucket_zones[j].ubz_entries != 0; j++) {
288                 int size;
289
290                 ubz = &bucket_zones[j];
291                 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
292                 size += sizeof(void *) * ubz->ubz_entries;
293                 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
294                     NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
295                     UMA_ZFLAG_INTERNAL | UMA_ZFLAG_BUCKET);
296                 for (; i <= ubz->ubz_entries; i += (1 << BUCKET_SHIFT))
297                         bucket_size[i >> BUCKET_SHIFT] = j;
298         }
299 }
300
301 /*
302  * Given a desired number of entries for a bucket, return the zone from which
303  * to allocate the bucket.
304  */
305 static struct uma_bucket_zone *
306 bucket_zone_lookup(int entries)
307 {
308         int idx;
309
310         idx = howmany(entries, 1 << BUCKET_SHIFT);
311         return (&bucket_zones[bucket_size[idx]]);
312 }
313
314 static uma_bucket_t
315 bucket_alloc(int entries, int bflags)
316 {
317         struct uma_bucket_zone *ubz;
318         uma_bucket_t bucket;
319
320         /*
321          * This is to stop us from allocating per cpu buckets while we're
322          * running out of vm.boot_pages.  Otherwise, we would exhaust the
323          * boot pages.  This also prevents us from allocating buckets in
324          * low memory situations.
325          */
326         if (bucketdisable)
327                 return (NULL);
328
329         ubz = bucket_zone_lookup(entries);
330         bucket = zone_alloc_item(ubz->ubz_zone, NULL, bflags);
331         if (bucket) {
332 #ifdef INVARIANTS
333                 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
334 #endif
335                 bucket->ub_cnt = 0;
336                 bucket->ub_entries = ubz->ubz_entries;
337         }
338
339         return (bucket);
340 }
341
342 static void
343 bucket_free(uma_bucket_t bucket)
344 {
345         struct uma_bucket_zone *ubz;
346
347         ubz = bucket_zone_lookup(bucket->ub_entries);
348         zone_free_item(ubz->ubz_zone, bucket, NULL, SKIP_NONE,
349             ZFREE_STATFREE);
350 }
351
352 static void
353 bucket_zone_drain(void)
354 {
355         struct uma_bucket_zone *ubz;
356
357         for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
358                 zone_drain(ubz->ubz_zone);
359 }
360
361 static inline uma_keg_t
362 zone_first_keg(uma_zone_t zone)
363 {
364
365         return (LIST_FIRST(&zone->uz_kegs)->kl_keg);
366 }
367
368 static void
369 zone_foreach_keg(uma_zone_t zone, void (*kegfn)(uma_keg_t))
370 {
371         uma_klink_t klink;
372
373         LIST_FOREACH(klink, &zone->uz_kegs, kl_link)
374                 kegfn(klink->kl_keg);
375 }
376
377 /*
378  * Routine called by timeout which is used to fire off some time interval
379  * based calculations.  (stats, hash size, etc.)
380  *
381  * Arguments:
382  *      arg   Unused
383  *
384  * Returns:
385  *      Nothing
386  */
387 static void
388 uma_timeout(void *unused)
389 {
390         bucket_enable();
391         zone_foreach(zone_timeout);
392
393         /* Reschedule this event */
394         callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
395 }
396
397 /*
398  * Routine to perform timeout driven calculations.  This expands the
399  * hashes and does per cpu statistics aggregation.
400  *
401  *  Returns nothing.
402  */
403 static void
404 keg_timeout(uma_keg_t keg)
405 {
406
407         KEG_LOCK(keg);
408         /*
409          * Expand the keg hash table.
410          *
411          * This is done if the number of slabs is larger than the hash size.
412          * What I'm trying to do here is completely reduce collisions.  This
413          * may be a little aggressive.  Should I allow for two collisions max?
414          */
415         if (keg->uk_flags & UMA_ZONE_HASH &&
416             keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
417                 struct uma_hash newhash;
418                 struct uma_hash oldhash;
419                 int ret;
420
421                 /*
422                  * This is so involved because allocating and freeing
423                  * while the keg lock is held will lead to deadlock.
424                  * I have to do everything in stages and check for
425                  * races.
426                  */
427                 newhash = keg->uk_hash;
428                 KEG_UNLOCK(keg);
429                 ret = hash_alloc(&newhash);
430                 KEG_LOCK(keg);
431                 if (ret) {
432                         if (hash_expand(&keg->uk_hash, &newhash)) {
433                                 oldhash = keg->uk_hash;
434                                 keg->uk_hash = newhash;
435                         } else
436                                 oldhash = newhash;
437
438                         KEG_UNLOCK(keg);
439                         hash_free(&oldhash);
440                         KEG_LOCK(keg);
441                 }
442         }
443         KEG_UNLOCK(keg);
444 }
445
446 static void
447 zone_timeout(uma_zone_t zone)
448 {
449
450         zone_foreach_keg(zone, &keg_timeout);
451 }
452
453 /*
454  * Allocate and zero fill the next sized hash table from the appropriate
455  * backing store.
456  *
457  * Arguments:
458  *      hash  A new hash structure with the old hash size in uh_hashsize
459  *
460  * Returns:
461  *      1 on sucess and 0 on failure.
462  */
463 static int
464 hash_alloc(struct uma_hash *hash)
465 {
466         int oldsize;
467         int alloc;
468
469         oldsize = hash->uh_hashsize;
470
471         /* We're just going to go to a power of two greater */
472         if (oldsize)  {
473                 hash->uh_hashsize = oldsize * 2;
474                 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
475                 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
476                     M_UMAHASH, M_NOWAIT);
477         } else {
478                 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
479                 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
480                     M_WAITOK);
481                 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
482         }
483         if (hash->uh_slab_hash) {
484                 bzero(hash->uh_slab_hash, alloc);
485                 hash->uh_hashmask = hash->uh_hashsize - 1;
486                 return (1);
487         }
488
489         return (0);
490 }
491
492 /*
493  * Expands the hash table for HASH zones.  This is done from zone_timeout
494  * to reduce collisions.  This must not be done in the regular allocation
495  * path, otherwise, we can recurse on the vm while allocating pages.
496  *
497  * Arguments:
498  *      oldhash  The hash you want to expand
499  *      newhash  The hash structure for the new table
500  *
501  * Returns:
502  *      Nothing
503  *
504  * Discussion:
505  */
506 static int
507 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
508 {
509         uma_slab_t slab;
510         int hval;
511         int i;
512
513         if (!newhash->uh_slab_hash)
514                 return (0);
515
516         if (oldhash->uh_hashsize >= newhash->uh_hashsize)
517                 return (0);
518
519         /*
520          * I need to investigate hash algorithms for resizing without a
521          * full rehash.
522          */
523
524         for (i = 0; i < oldhash->uh_hashsize; i++)
525                 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[i])) {
526                         slab = SLIST_FIRST(&oldhash->uh_slab_hash[i]);
527                         SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[i], us_hlink);
528                         hval = UMA_HASH(newhash, slab->us_data);
529                         SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
530                             slab, us_hlink);
531                 }
532
533         return (1);
534 }
535
536 /*
537  * Free the hash bucket to the appropriate backing store.
538  *
539  * Arguments:
540  *      slab_hash  The hash bucket we're freeing
541  *      hashsize   The number of entries in that hash bucket
542  *
543  * Returns:
544  *      Nothing
545  */
546 static void
547 hash_free(struct uma_hash *hash)
548 {
549         if (hash->uh_slab_hash == NULL)
550                 return;
551         if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
552                 zone_free_item(hashzone,
553                     hash->uh_slab_hash, NULL, SKIP_NONE, ZFREE_STATFREE);
554         else
555                 free(hash->uh_slab_hash, M_UMAHASH);
556 }
557
558 /*
559  * Frees all outstanding items in a bucket
560  *
561  * Arguments:
562  *      zone   The zone to free to, must be unlocked.
563  *      bucket The free/alloc bucket with items, cpu queue must be locked.
564  *
565  * Returns:
566  *      Nothing
567  */
568
569 static void
570 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
571 {
572         void *item;
573
574         if (bucket == NULL)
575                 return;
576
577         while (bucket->ub_cnt > 0)  {
578                 bucket->ub_cnt--;
579                 item = bucket->ub_bucket[bucket->ub_cnt];
580 #ifdef INVARIANTS
581                 bucket->ub_bucket[bucket->ub_cnt] = NULL;
582                 KASSERT(item != NULL,
583                     ("bucket_drain: botched ptr, item is NULL"));
584 #endif
585                 zone_free_item(zone, item, NULL, SKIP_DTOR, 0);
586         }
587 }
588
589 /*
590  * Drains the per cpu caches for a zone.
591  *
592  * NOTE: This may only be called while the zone is being turn down, and not
593  * during normal operation.  This is necessary in order that we do not have
594  * to migrate CPUs to drain the per-CPU caches.
595  *
596  * Arguments:
597  *      zone     The zone to drain, must be unlocked.
598  *
599  * Returns:
600  *      Nothing
601  */
602 static void
603 cache_drain(uma_zone_t zone)
604 {
605         uma_cache_t cache;
606         int cpu;
607
608         /*
609          * XXX: It is safe to not lock the per-CPU caches, because we're
610          * tearing down the zone anyway.  I.e., there will be no further use
611          * of the caches at this point.
612          *
613          * XXX: It would good to be able to assert that the zone is being
614          * torn down to prevent improper use of cache_drain().
615          *
616          * XXX: We lock the zone before passing into bucket_cache_drain() as
617          * it is used elsewhere.  Should the tear-down path be made special
618          * there in some form?
619          */
620         CPU_FOREACH(cpu) {
621                 cache = &zone->uz_cpu[cpu];
622                 bucket_drain(zone, cache->uc_allocbucket);
623                 bucket_drain(zone, cache->uc_freebucket);
624                 if (cache->uc_allocbucket != NULL)
625                         bucket_free(cache->uc_allocbucket);
626                 if (cache->uc_freebucket != NULL)
627                         bucket_free(cache->uc_freebucket);
628                 cache->uc_allocbucket = cache->uc_freebucket = NULL;
629         }
630         ZONE_LOCK(zone);
631         bucket_cache_drain(zone);
632         ZONE_UNLOCK(zone);
633 }
634
635 /*
636  * Drain the cached buckets from a zone.  Expects a locked zone on entry.
637  */
638 static void
639 bucket_cache_drain(uma_zone_t zone)
640 {
641         uma_bucket_t bucket;
642
643         /*
644          * Drain the bucket queues and free the buckets, we just keep two per
645          * cpu (alloc/free).
646          */
647         while ((bucket = LIST_FIRST(&zone->uz_full_bucket)) != NULL) {
648                 LIST_REMOVE(bucket, ub_link);
649                 ZONE_UNLOCK(zone);
650                 bucket_drain(zone, bucket);
651                 bucket_free(bucket);
652                 ZONE_LOCK(zone);
653         }
654
655         /* Now we do the free queue.. */
656         while ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
657                 LIST_REMOVE(bucket, ub_link);
658                 bucket_free(bucket);
659         }
660 }
661
662 /*
663  * Frees pages from a keg back to the system.  This is done on demand from
664  * the pageout daemon.
665  *
666  * Returns nothing.
667  */
668 static void
669 keg_drain(uma_keg_t keg)
670 {
671         struct slabhead freeslabs = { 0 };
672         uma_slab_t slab;
673         uma_slab_t n;
674         u_int8_t flags;
675         u_int8_t *mem;
676         int i;
677
678         /*
679          * We don't want to take pages from statically allocated kegs at this
680          * time
681          */
682         if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
683                 return;
684
685 #ifdef UMA_DEBUG
686         printf("%s free items: %u\n", keg->uk_name, keg->uk_free);
687 #endif
688         KEG_LOCK(keg);
689         if (keg->uk_free == 0)
690                 goto finished;
691
692         slab = LIST_FIRST(&keg->uk_free_slab);
693         while (slab) {
694                 n = LIST_NEXT(slab, us_link);
695
696                 /* We have no where to free these to */
697                 if (slab->us_flags & UMA_SLAB_BOOT) {
698                         slab = n;
699                         continue;
700                 }
701
702                 LIST_REMOVE(slab, us_link);
703                 keg->uk_pages -= keg->uk_ppera;
704                 keg->uk_free -= keg->uk_ipers;
705
706                 if (keg->uk_flags & UMA_ZONE_HASH)
707                         UMA_HASH_REMOVE(&keg->uk_hash, slab, slab->us_data);
708
709                 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
710
711                 slab = n;
712         }
713 finished:
714         KEG_UNLOCK(keg);
715
716         while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
717                 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
718                 if (keg->uk_fini)
719                         for (i = 0; i < keg->uk_ipers; i++)
720                                 keg->uk_fini(
721                                     slab->us_data + (keg->uk_rsize * i),
722                                     keg->uk_size);
723                 flags = slab->us_flags;
724                 mem = slab->us_data;
725
726                 if (keg->uk_flags & UMA_ZONE_VTOSLAB) {
727                         vm_object_t obj;
728
729                         if (flags & UMA_SLAB_KMEM)
730                                 obj = kmem_object;
731                         else if (flags & UMA_SLAB_KERNEL)
732                                 obj = kernel_object;
733                         else
734                                 obj = NULL;
735                         for (i = 0; i < keg->uk_ppera; i++)
736                                 vsetobj((vm_offset_t)mem + (i * PAGE_SIZE),
737                                     obj);
738                 }
739                 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
740                         zone_free_item(keg->uk_slabzone, slab, NULL,
741                             SKIP_NONE, ZFREE_STATFREE);
742 #ifdef UMA_DEBUG
743                 printf("%s: Returning %d bytes.\n",
744                     keg->uk_name, UMA_SLAB_SIZE * keg->uk_ppera);
745 #endif
746                 keg->uk_freef(mem, UMA_SLAB_SIZE * keg->uk_ppera, flags);
747         }
748 }
749
750 static void
751 zone_drain_wait(uma_zone_t zone, int waitok)
752 {
753
754         /*
755          * Set draining to interlock with zone_dtor() so we can release our
756          * locks as we go.  Only dtor() should do a WAITOK call since it
757          * is the only call that knows the structure will still be available
758          * when it wakes up.
759          */
760         ZONE_LOCK(zone);
761         while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
762                 if (waitok == M_NOWAIT)
763                         goto out;
764                 mtx_unlock(&uma_mtx);
765                 msleep(zone, zone->uz_lock, PVM, "zonedrain", 1);
766                 mtx_lock(&uma_mtx);
767         }
768         zone->uz_flags |= UMA_ZFLAG_DRAINING;
769         bucket_cache_drain(zone);
770         ZONE_UNLOCK(zone);
771         /*
772          * The DRAINING flag protects us from being freed while
773          * we're running.  Normally the uma_mtx would protect us but we
774          * must be able to release and acquire the right lock for each keg.
775          */
776         zone_foreach_keg(zone, &keg_drain);
777         ZONE_LOCK(zone);
778         zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
779         wakeup(zone);
780 out:
781         ZONE_UNLOCK(zone);
782 }
783
784 void
785 zone_drain(uma_zone_t zone)
786 {
787
788         zone_drain_wait(zone, M_NOWAIT);
789 }
790
791 /*
792  * Allocate a new slab for a keg.  This does not insert the slab onto a list.
793  *
794  * Arguments:
795  *      wait  Shall we wait?
796  *
797  * Returns:
798  *      The slab that was allocated or NULL if there is no memory and the
799  *      caller specified M_NOWAIT.
800  */
801 static uma_slab_t
802 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int wait)
803 {
804         uma_slabrefcnt_t slabref;
805         uma_alloc allocf;
806         uma_slab_t slab;
807         u_int8_t *mem;
808         u_int8_t flags;
809         int i;
810
811         mtx_assert(&keg->uk_lock, MA_OWNED);
812         slab = NULL;
813
814 #ifdef UMA_DEBUG
815         printf("slab_zalloc:  Allocating a new slab for %s\n", keg->uk_name);
816 #endif
817         allocf = keg->uk_allocf;
818         KEG_UNLOCK(keg);
819
820         if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
821                 slab = zone_alloc_item(keg->uk_slabzone, NULL, wait);
822                 if (slab == NULL) {
823                         KEG_LOCK(keg);
824                         return NULL;
825                 }
826         }
827
828         /*
829          * This reproduces the old vm_zone behavior of zero filling pages the
830          * first time they are added to a zone.
831          *
832          * Malloced items are zeroed in uma_zalloc.
833          */
834
835         if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
836                 wait |= M_ZERO;
837         else
838                 wait &= ~M_ZERO;
839
840         if (keg->uk_flags & UMA_ZONE_NODUMP)
841                 wait |= M_NODUMP;
842
843         /* zone is passed for legacy reasons. */
844         mem = allocf(zone, keg->uk_ppera * UMA_SLAB_SIZE, &flags, wait);
845         if (mem == NULL) {
846                 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
847                         zone_free_item(keg->uk_slabzone, slab, NULL,
848                             SKIP_NONE, ZFREE_STATFREE);
849                 KEG_LOCK(keg);
850                 return (NULL);
851         }
852
853         /* Point the slab into the allocated memory */
854         if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
855                 slab = (uma_slab_t )(mem + keg->uk_pgoff);
856
857         if (keg->uk_flags & UMA_ZONE_VTOSLAB)
858                 for (i = 0; i < keg->uk_ppera; i++)
859                         vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
860
861         slab->us_keg = keg;
862         slab->us_data = mem;
863         slab->us_freecount = keg->uk_ipers;
864         slab->us_firstfree = 0;
865         slab->us_flags = flags;
866
867         if (keg->uk_flags & UMA_ZONE_REFCNT) {
868                 slabref = (uma_slabrefcnt_t)slab;
869                 for (i = 0; i < keg->uk_ipers; i++) {
870                         slabref->us_freelist[i].us_refcnt = 0;
871                         slabref->us_freelist[i].us_item = i+1;
872                 }
873         } else {
874                 for (i = 0; i < keg->uk_ipers; i++)
875                         slab->us_freelist[i].us_item = i+1;
876         }
877
878         if (keg->uk_init != NULL) {
879                 for (i = 0; i < keg->uk_ipers; i++)
880                         if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
881                             keg->uk_size, wait) != 0)
882                                 break;
883                 if (i != keg->uk_ipers) {
884                         if (keg->uk_fini != NULL) {
885                                 for (i--; i > -1; i--)
886                                         keg->uk_fini(slab->us_data +
887                                             (keg->uk_rsize * i),
888                                             keg->uk_size);
889                         }
890                         if (keg->uk_flags & UMA_ZONE_VTOSLAB) {
891                                 vm_object_t obj;
892
893                                 if (flags & UMA_SLAB_KMEM)
894                                         obj = kmem_object;
895                                 else if (flags & UMA_SLAB_KERNEL)
896                                         obj = kernel_object;
897                                 else
898                                         obj = NULL;
899                                 for (i = 0; i < keg->uk_ppera; i++)
900                                         vsetobj((vm_offset_t)mem +
901                                             (i * PAGE_SIZE), obj);
902                         }
903                         if (keg->uk_flags & UMA_ZONE_OFFPAGE)
904                                 zone_free_item(keg->uk_slabzone, slab,
905                                     NULL, SKIP_NONE, ZFREE_STATFREE);
906                         keg->uk_freef(mem, UMA_SLAB_SIZE * keg->uk_ppera,
907                             flags);
908                         KEG_LOCK(keg);
909                         return (NULL);
910                 }
911         }
912         KEG_LOCK(keg);
913
914         if (keg->uk_flags & UMA_ZONE_HASH)
915                 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
916
917         keg->uk_pages += keg->uk_ppera;
918         keg->uk_free += keg->uk_ipers;
919
920         return (slab);
921 }
922
923 /*
924  * This function is intended to be used early on in place of page_alloc() so
925  * that we may use the boot time page cache to satisfy allocations before
926  * the VM is ready.
927  */
928 static void *
929 startup_alloc(uma_zone_t zone, int bytes, u_int8_t *pflag, int wait)
930 {
931         uma_keg_t keg;
932         uma_slab_t tmps;
933         int pages, check_pages;
934
935         keg = zone_first_keg(zone);
936         pages = howmany(bytes, PAGE_SIZE);
937         check_pages = pages - 1;
938         KASSERT(pages > 0, ("startup_alloc can't reserve 0 pages\n"));
939
940         /*
941          * Check our small startup cache to see if it has pages remaining.
942          */
943         mtx_lock(&uma_boot_pages_mtx);
944
945         /* First check if we have enough room. */
946         tmps = LIST_FIRST(&uma_boot_pages);
947         while (tmps != NULL && check_pages-- > 0)
948                 tmps = LIST_NEXT(tmps, us_link);
949         if (tmps != NULL) {
950                 /*
951                  * It's ok to lose tmps references.  The last one will
952                  * have tmps->us_data pointing to the start address of
953                  * "pages" contiguous pages of memory.
954                  */
955                 while (pages-- > 0) {
956                         tmps = LIST_FIRST(&uma_boot_pages);
957                         LIST_REMOVE(tmps, us_link);
958                 }
959                 mtx_unlock(&uma_boot_pages_mtx);
960                 *pflag = tmps->us_flags;
961                 return (tmps->us_data);
962         }
963         mtx_unlock(&uma_boot_pages_mtx);
964         if (booted < UMA_STARTUP2)
965                 panic("UMA: Increase vm.boot_pages");
966         /*
967          * Now that we've booted reset these users to their real allocator.
968          */
969 #ifdef UMA_MD_SMALL_ALLOC
970         keg->uk_allocf = (keg->uk_ppera > 1) ? page_alloc : uma_small_alloc;
971 #else
972         keg->uk_allocf = page_alloc;
973 #endif
974         return keg->uk_allocf(zone, bytes, pflag, wait);
975 }
976
977 /*
978  * Allocates a number of pages from the system
979  *
980  * Arguments:
981  *      bytes  The number of bytes requested
982  *      wait  Shall we wait?
983  *
984  * Returns:
985  *      A pointer to the alloced memory or possibly
986  *      NULL if M_NOWAIT is set.
987  */
988 static void *
989 page_alloc(uma_zone_t zone, int bytes, u_int8_t *pflag, int wait)
990 {
991         void *p;        /* Returned page */
992
993         *pflag = UMA_SLAB_KMEM;
994         p = (void *) kmem_malloc(kmem_map, bytes, wait);
995
996         return (p);
997 }
998
999 /*
1000  * Allocates a number of pages from within an object
1001  *
1002  * Arguments:
1003  *      bytes  The number of bytes requested
1004  *      wait   Shall we wait?
1005  *
1006  * Returns:
1007  *      A pointer to the alloced memory or possibly
1008  *      NULL if M_NOWAIT is set.
1009  */
1010 static void *
1011 obj_alloc(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
1012 {
1013         vm_object_t object;
1014         vm_offset_t retkva, zkva;
1015         vm_page_t p;
1016         int pages, startpages;
1017         uma_keg_t keg;
1018
1019         keg = zone_first_keg(zone);
1020         object = keg->uk_obj;
1021         retkva = 0;
1022
1023         /*
1024          * This looks a little weird since we're getting one page at a time.
1025          */
1026         VM_OBJECT_LOCK(object);
1027         p = TAILQ_LAST(&object->memq, pglist);
1028         pages = p != NULL ? p->pindex + 1 : 0;
1029         startpages = pages;
1030         zkva = keg->uk_kva + pages * PAGE_SIZE;
1031         for (; bytes > 0; bytes -= PAGE_SIZE) {
1032                 p = vm_page_alloc(object, pages,
1033                     VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED);
1034                 if (p == NULL) {
1035                         if (pages != startpages)
1036                                 pmap_qremove(retkva, pages - startpages);
1037                         while (pages != startpages) {
1038                                 pages--;
1039                                 p = TAILQ_LAST(&object->memq, pglist);
1040                                 vm_page_unwire(p, 0);
1041                                 vm_page_free(p);
1042                         }
1043                         retkva = 0;
1044                         goto done;
1045                 }
1046                 pmap_qenter(zkva, &p, 1);
1047                 if (retkva == 0)
1048                         retkva = zkva;
1049                 zkva += PAGE_SIZE;
1050                 pages += 1;
1051         }
1052 done:
1053         VM_OBJECT_UNLOCK(object);
1054         *flags = UMA_SLAB_PRIV;
1055
1056         return ((void *)retkva);
1057 }
1058
1059 /*
1060  * Frees a number of pages to the system
1061  *
1062  * Arguments:
1063  *      mem   A pointer to the memory to be freed
1064  *      size  The size of the memory being freed
1065  *      flags The original p->us_flags field
1066  *
1067  * Returns:
1068  *      Nothing
1069  */
1070 static void
1071 page_free(void *mem, int size, u_int8_t flags)
1072 {
1073         vm_map_t map;
1074
1075         if (flags & UMA_SLAB_KMEM)
1076                 map = kmem_map;
1077         else if (flags & UMA_SLAB_KERNEL)
1078                 map = kernel_map;
1079         else
1080                 panic("UMA: page_free used with invalid flags %d", flags);
1081
1082         kmem_free(map, (vm_offset_t)mem, size);
1083 }
1084
1085 /*
1086  * Zero fill initializer
1087  *
1088  * Arguments/Returns follow uma_init specifications
1089  */
1090 static int
1091 zero_init(void *mem, int size, int flags)
1092 {
1093         bzero(mem, size);
1094         return (0);
1095 }
1096
1097 /*
1098  * Finish creating a small uma keg.  This calculates ipers, and the keg size.
1099  *
1100  * Arguments
1101  *      keg  The zone we should initialize
1102  *
1103  * Returns
1104  *      Nothing
1105  */
1106 static void
1107 keg_small_init(uma_keg_t keg)
1108 {
1109         u_int rsize;
1110         u_int memused;
1111         u_int wastedspace;
1112         u_int shsize;
1113
1114         KASSERT(keg != NULL, ("Keg is null in keg_small_init"));
1115         rsize = keg->uk_size;
1116
1117         if (rsize < UMA_SMALLEST_UNIT)
1118                 rsize = UMA_SMALLEST_UNIT;
1119         if (rsize & keg->uk_align)
1120                 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1121
1122         keg->uk_rsize = rsize;
1123         keg->uk_ppera = 1;
1124
1125         if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1126                 shsize = 0;
1127         } else if (keg->uk_flags & UMA_ZONE_REFCNT) {
1128                 rsize += UMA_FRITMREF_SZ;       /* linkage & refcnt */
1129                 shsize = sizeof(struct uma_slab_refcnt);
1130         } else {
1131                 rsize += UMA_FRITM_SZ;  /* Account for linkage */
1132                 shsize = sizeof(struct uma_slab);
1133         }
1134
1135         keg->uk_ipers = (UMA_SLAB_SIZE - shsize) / rsize;
1136         KASSERT(keg->uk_ipers != 0, ("keg_small_init: ipers is 0"));
1137         memused = keg->uk_ipers * rsize + shsize;
1138         wastedspace = UMA_SLAB_SIZE - memused;
1139
1140         /*
1141          * We can't do OFFPAGE if we're internal or if we've been
1142          * asked to not go to the VM for buckets.  If we do this we
1143          * may end up going to the VM (kmem_map) for slabs which we
1144          * do not want to do if we're UMA_ZFLAG_CACHEONLY as a
1145          * result of UMA_ZONE_VM, which clearly forbids it.
1146          */
1147         if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1148             (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1149                 return;
1150
1151         if ((wastedspace >= UMA_MAX_WASTE) &&
1152             (keg->uk_ipers < (UMA_SLAB_SIZE / keg->uk_rsize))) {
1153                 keg->uk_ipers = UMA_SLAB_SIZE / keg->uk_rsize;
1154                 KASSERT(keg->uk_ipers <= 255,
1155                     ("keg_small_init: keg->uk_ipers too high!"));
1156 #ifdef UMA_DEBUG
1157                 printf("UMA decided we need offpage slab headers for "
1158                     "keg: %s, calculated wastedspace = %d, "
1159                     "maximum wasted space allowed = %d, "
1160                     "calculated ipers = %d, "
1161                     "new wasted space = %d\n", keg->uk_name, wastedspace,
1162                     UMA_MAX_WASTE, keg->uk_ipers,
1163                     UMA_SLAB_SIZE - keg->uk_ipers * keg->uk_rsize);
1164 #endif
1165                 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1166                 if ((keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1167                         keg->uk_flags |= UMA_ZONE_HASH;
1168         }
1169 }
1170
1171 /*
1172  * Finish creating a large (> UMA_SLAB_SIZE) uma kegs.  Just give in and do
1173  * OFFPAGE for now.  When I can allow for more dynamic slab sizes this will be
1174  * more complicated.
1175  *
1176  * Arguments
1177  *      keg  The keg we should initialize
1178  *
1179  * Returns
1180  *      Nothing
1181  */
1182 static void
1183 keg_large_init(uma_keg_t keg)
1184 {
1185         int pages;
1186
1187         KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1188         KASSERT((keg->uk_flags & UMA_ZFLAG_CACHEONLY) == 0,
1189             ("keg_large_init: Cannot large-init a UMA_ZFLAG_CACHEONLY keg"));
1190
1191         pages = keg->uk_size / UMA_SLAB_SIZE;
1192
1193         /* Account for remainder */
1194         if ((pages * UMA_SLAB_SIZE) < keg->uk_size)
1195                 pages++;
1196
1197         keg->uk_ppera = pages;
1198         keg->uk_ipers = 1;
1199         keg->uk_rsize = keg->uk_size;
1200
1201         /* We can't do OFFPAGE if we're internal, bail out here. */
1202         if (keg->uk_flags & UMA_ZFLAG_INTERNAL)
1203                 return;
1204
1205         keg->uk_flags |= UMA_ZONE_OFFPAGE;
1206         if ((keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1207                 keg->uk_flags |= UMA_ZONE_HASH;
1208 }
1209
1210 static void
1211 keg_cachespread_init(uma_keg_t keg)
1212 {
1213         int alignsize;
1214         int trailer;
1215         int pages;
1216         int rsize;
1217
1218         alignsize = keg->uk_align + 1;
1219         rsize = keg->uk_size;
1220         /*
1221          * We want one item to start on every align boundary in a page.  To
1222          * do this we will span pages.  We will also extend the item by the
1223          * size of align if it is an even multiple of align.  Otherwise, it
1224          * would fall on the same boundary every time.
1225          */
1226         if (rsize & keg->uk_align)
1227                 rsize = (rsize & ~keg->uk_align) + alignsize;
1228         if ((rsize & alignsize) == 0)
1229                 rsize += alignsize;
1230         trailer = rsize - keg->uk_size;
1231         pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1232         pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1233         keg->uk_rsize = rsize;
1234         keg->uk_ppera = pages;
1235         keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1236         keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1237         KASSERT(keg->uk_ipers <= uma_max_ipers,
1238             ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1239             keg->uk_ipers));
1240 }
1241
1242 /*
1243  * Keg header ctor.  This initializes all fields, locks, etc.  And inserts
1244  * the keg onto the global keg list.
1245  *
1246  * Arguments/Returns follow uma_ctor specifications
1247  *      udata  Actually uma_kctor_args
1248  */
1249 static int
1250 keg_ctor(void *mem, int size, void *udata, int flags)
1251 {
1252         struct uma_kctor_args *arg = udata;
1253         uma_keg_t keg = mem;
1254         uma_zone_t zone;
1255
1256         bzero(keg, size);
1257         keg->uk_size = arg->size;
1258         keg->uk_init = arg->uminit;
1259         keg->uk_fini = arg->fini;
1260         keg->uk_align = arg->align;
1261         keg->uk_free = 0;
1262         keg->uk_pages = 0;
1263         keg->uk_flags = arg->flags;
1264         keg->uk_allocf = page_alloc;
1265         keg->uk_freef = page_free;
1266         keg->uk_recurse = 0;
1267         keg->uk_slabzone = NULL;
1268
1269         /*
1270          * The master zone is passed to us at keg-creation time.
1271          */
1272         zone = arg->zone;
1273         keg->uk_name = zone->uz_name;
1274
1275         if (arg->flags & UMA_ZONE_VM)
1276                 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1277
1278         if (arg->flags & UMA_ZONE_ZINIT)
1279                 keg->uk_init = zero_init;
1280
1281         if (arg->flags & UMA_ZONE_REFCNT || arg->flags & UMA_ZONE_MALLOC)
1282                 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1283
1284         /*
1285          * The +UMA_FRITM_SZ added to uk_size is to account for the
1286          * linkage that is added to the size in keg_small_init().  If
1287          * we don't account for this here then we may end up in
1288          * keg_small_init() with a calculated 'ipers' of 0.
1289          */
1290         if (keg->uk_flags & UMA_ZONE_REFCNT) {
1291                 if (keg->uk_flags & UMA_ZONE_CACHESPREAD)
1292                         keg_cachespread_init(keg);
1293                 else if ((keg->uk_size+UMA_FRITMREF_SZ) >
1294                     (UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt)))
1295                         keg_large_init(keg);
1296                 else
1297                         keg_small_init(keg);
1298         } else {
1299                 if (keg->uk_flags & UMA_ZONE_CACHESPREAD)
1300                         keg_cachespread_init(keg);
1301                 else if ((keg->uk_size+UMA_FRITM_SZ) >
1302                     (UMA_SLAB_SIZE - sizeof(struct uma_slab)))
1303                         keg_large_init(keg);
1304                 else
1305                         keg_small_init(keg);
1306         }
1307
1308         if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1309                 if (keg->uk_flags & UMA_ZONE_REFCNT)
1310                         keg->uk_slabzone = slabrefzone;
1311                 else
1312                         keg->uk_slabzone = slabzone;
1313         }
1314
1315         /*
1316          * If we haven't booted yet we need allocations to go through the
1317          * startup cache until the vm is ready.
1318          */
1319         if (keg->uk_ppera == 1) {
1320 #ifdef UMA_MD_SMALL_ALLOC
1321                 keg->uk_allocf = uma_small_alloc;
1322                 keg->uk_freef = uma_small_free;
1323
1324                 if (booted < UMA_STARTUP)
1325                         keg->uk_allocf = startup_alloc;
1326 #else
1327                 if (booted < UMA_STARTUP2)
1328                         keg->uk_allocf = startup_alloc;
1329 #endif
1330         } else if (booted < UMA_STARTUP2 &&
1331             (keg->uk_flags & UMA_ZFLAG_INTERNAL))
1332                 keg->uk_allocf = startup_alloc;
1333
1334         /*
1335          * Initialize keg's lock (shared among zones).
1336          */
1337         if (arg->flags & UMA_ZONE_MTXCLASS)
1338                 KEG_LOCK_INIT(keg, 1);
1339         else
1340                 KEG_LOCK_INIT(keg, 0);
1341
1342         /*
1343          * If we're putting the slab header in the actual page we need to
1344          * figure out where in each page it goes.  This calculates a right
1345          * justified offset into the memory on an ALIGN_PTR boundary.
1346          */
1347         if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1348                 u_int totsize;
1349
1350                 /* Size of the slab struct and free list */
1351                 if (keg->uk_flags & UMA_ZONE_REFCNT)
1352                         totsize = sizeof(struct uma_slab_refcnt) +
1353                             keg->uk_ipers * UMA_FRITMREF_SZ;
1354                 else
1355                         totsize = sizeof(struct uma_slab) +
1356                             keg->uk_ipers * UMA_FRITM_SZ;
1357
1358                 if (totsize & UMA_ALIGN_PTR)
1359                         totsize = (totsize & ~UMA_ALIGN_PTR) +
1360                             (UMA_ALIGN_PTR + 1);
1361                 keg->uk_pgoff = (UMA_SLAB_SIZE * keg->uk_ppera) - totsize;
1362
1363                 if (keg->uk_flags & UMA_ZONE_REFCNT)
1364                         totsize = keg->uk_pgoff + sizeof(struct uma_slab_refcnt)
1365                             + keg->uk_ipers * UMA_FRITMREF_SZ;
1366                 else
1367                         totsize = keg->uk_pgoff + sizeof(struct uma_slab)
1368                             + keg->uk_ipers * UMA_FRITM_SZ;
1369
1370                 /*
1371                  * The only way the following is possible is if with our
1372                  * UMA_ALIGN_PTR adjustments we are now bigger than
1373                  * UMA_SLAB_SIZE.  I haven't checked whether this is
1374                  * mathematically possible for all cases, so we make
1375                  * sure here anyway.
1376                  */
1377                 if (totsize > UMA_SLAB_SIZE * keg->uk_ppera) {
1378                         printf("zone %s ipers %d rsize %d size %d\n",
1379                             zone->uz_name, keg->uk_ipers, keg->uk_rsize,
1380                             keg->uk_size);
1381                         panic("UMA slab won't fit.");
1382                 }
1383         }
1384
1385         if (keg->uk_flags & UMA_ZONE_HASH)
1386                 hash_alloc(&keg->uk_hash);
1387
1388 #ifdef UMA_DEBUG
1389         printf("UMA: %s(%p) size %d(%d) flags %#x ipers %d ppera %d out %d free %d\n",
1390             zone->uz_name, zone, keg->uk_size, keg->uk_rsize, keg->uk_flags,
1391             keg->uk_ipers, keg->uk_ppera,
1392             (keg->uk_ipers * keg->uk_pages) - keg->uk_free, keg->uk_free);
1393 #endif
1394
1395         LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1396
1397         mtx_lock(&uma_mtx);
1398         LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1399         mtx_unlock(&uma_mtx);
1400         return (0);
1401 }
1402
1403 /*
1404  * Zone header ctor.  This initializes all fields, locks, etc.
1405  *
1406  * Arguments/Returns follow uma_ctor specifications
1407  *      udata  Actually uma_zctor_args
1408  */
1409 static int
1410 zone_ctor(void *mem, int size, void *udata, int flags)
1411 {
1412         struct uma_zctor_args *arg = udata;
1413         uma_zone_t zone = mem;
1414         uma_zone_t z;
1415         uma_keg_t keg;
1416
1417         bzero(zone, size);
1418         zone->uz_name = arg->name;
1419         zone->uz_ctor = arg->ctor;
1420         zone->uz_dtor = arg->dtor;
1421         zone->uz_slab = zone_fetch_slab;
1422         zone->uz_init = NULL;
1423         zone->uz_fini = NULL;
1424         zone->uz_allocs = 0;
1425         zone->uz_frees = 0;
1426         zone->uz_fails = 0;
1427         zone->uz_sleeps = 0;
1428         zone->uz_fills = zone->uz_count = 0;
1429         zone->uz_flags = 0;
1430         keg = arg->keg;
1431
1432         if (arg->flags & UMA_ZONE_SECONDARY) {
1433                 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1434                 zone->uz_init = arg->uminit;
1435                 zone->uz_fini = arg->fini;
1436                 zone->uz_lock = &keg->uk_lock;
1437                 zone->uz_flags |= UMA_ZONE_SECONDARY;
1438                 mtx_lock(&uma_mtx);
1439                 ZONE_LOCK(zone);
1440                 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1441                         if (LIST_NEXT(z, uz_link) == NULL) {
1442                                 LIST_INSERT_AFTER(z, zone, uz_link);
1443                                 break;
1444                         }
1445                 }
1446                 ZONE_UNLOCK(zone);
1447                 mtx_unlock(&uma_mtx);
1448         } else if (keg == NULL) {
1449                 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1450                     arg->align, arg->flags)) == NULL)
1451                         return (ENOMEM);
1452         } else {
1453                 struct uma_kctor_args karg;
1454                 int error;
1455
1456                 /* We should only be here from uma_startup() */
1457                 karg.size = arg->size;
1458                 karg.uminit = arg->uminit;
1459                 karg.fini = arg->fini;
1460                 karg.align = arg->align;
1461                 karg.flags = arg->flags;
1462                 karg.zone = zone;
1463                 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1464                     flags);
1465                 if (error)
1466                         return (error);
1467         }
1468         /*
1469          * Link in the first keg.
1470          */
1471         zone->uz_klink.kl_keg = keg;
1472         LIST_INSERT_HEAD(&zone->uz_kegs, &zone->uz_klink, kl_link);
1473         zone->uz_lock = &keg->uk_lock;
1474         zone->uz_size = keg->uk_size;
1475         zone->uz_flags |= (keg->uk_flags &
1476             (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1477
1478         /*
1479          * Some internal zones don't have room allocated for the per cpu
1480          * caches.  If we're internal, bail out here.
1481          */
1482         if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1483                 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1484                     ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1485                 return (0);
1486         }
1487
1488         if (keg->uk_flags & UMA_ZONE_MAXBUCKET)
1489                 zone->uz_count = BUCKET_MAX;
1490         else if (keg->uk_ipers <= BUCKET_MAX)
1491                 zone->uz_count = keg->uk_ipers;
1492         else
1493                 zone->uz_count = BUCKET_MAX;
1494         return (0);
1495 }
1496
1497 /*
1498  * Keg header dtor.  This frees all data, destroys locks, frees the hash
1499  * table and removes the keg from the global list.
1500  *
1501  * Arguments/Returns follow uma_dtor specifications
1502  *      udata  unused
1503  */
1504 static void
1505 keg_dtor(void *arg, int size, void *udata)
1506 {
1507         uma_keg_t keg;
1508
1509         keg = (uma_keg_t)arg;
1510         KEG_LOCK(keg);
1511         if (keg->uk_free != 0) {
1512                 printf("Freed UMA keg (%s) was not empty (%d items). "
1513                     " Lost %d pages of memory.\n",
1514                     keg->uk_name ? keg->uk_name : "",
1515                     keg->uk_free, keg->uk_pages);
1516         }
1517         KEG_UNLOCK(keg);
1518
1519         hash_free(&keg->uk_hash);
1520
1521         KEG_LOCK_FINI(keg);
1522 }
1523
1524 /*
1525  * Zone header dtor.
1526  *
1527  * Arguments/Returns follow uma_dtor specifications
1528  *      udata  unused
1529  */
1530 static void
1531 zone_dtor(void *arg, int size, void *udata)
1532 {
1533         uma_klink_t klink;
1534         uma_zone_t zone;
1535         uma_keg_t keg;
1536
1537         zone = (uma_zone_t)arg;
1538         keg = zone_first_keg(zone);
1539
1540         if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1541                 cache_drain(zone);
1542
1543         mtx_lock(&uma_mtx);
1544         LIST_REMOVE(zone, uz_link);
1545         mtx_unlock(&uma_mtx);
1546         /*
1547          * XXX there are some races here where
1548          * the zone can be drained but zone lock
1549          * released and then refilled before we
1550          * remove it... we dont care for now
1551          */
1552         zone_drain_wait(zone, M_WAITOK);
1553         /*
1554          * Unlink all of our kegs.
1555          */
1556         while ((klink = LIST_FIRST(&zone->uz_kegs)) != NULL) {
1557                 klink->kl_keg = NULL;
1558                 LIST_REMOVE(klink, kl_link);
1559                 if (klink == &zone->uz_klink)
1560                         continue;
1561                 free(klink, M_TEMP);
1562         }
1563         /*
1564          * We only destroy kegs from non secondary zones.
1565          */
1566         if ((zone->uz_flags & UMA_ZONE_SECONDARY) == 0)  {
1567                 mtx_lock(&uma_mtx);
1568                 LIST_REMOVE(keg, uk_link);
1569                 mtx_unlock(&uma_mtx);
1570                 zone_free_item(kegs, keg, NULL, SKIP_NONE,
1571                     ZFREE_STATFREE);
1572         }
1573 }
1574
1575 /*
1576  * Traverses every zone in the system and calls a callback
1577  *
1578  * Arguments:
1579  *      zfunc  A pointer to a function which accepts a zone
1580  *              as an argument.
1581  *
1582  * Returns:
1583  *      Nothing
1584  */
1585 static void
1586 zone_foreach(void (*zfunc)(uma_zone_t))
1587 {
1588         uma_keg_t keg;
1589         uma_zone_t zone;
1590
1591         mtx_lock(&uma_mtx);
1592         LIST_FOREACH(keg, &uma_kegs, uk_link) {
1593                 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1594                         zfunc(zone);
1595         }
1596         mtx_unlock(&uma_mtx);
1597 }
1598
1599 /* Public functions */
1600 /* See uma.h */
1601 void
1602 uma_startup(void *bootmem, int boot_pages)
1603 {
1604         struct uma_zctor_args args;
1605         uma_slab_t slab;
1606         u_int slabsize;
1607         u_int objsize, totsize, wsize;
1608         int i;
1609
1610 #ifdef UMA_DEBUG
1611         printf("Creating uma keg headers zone and keg.\n");
1612 #endif
1613         mtx_init(&uma_mtx, "UMA lock", NULL, MTX_DEF);
1614
1615         /*
1616          * Figure out the maximum number of items-per-slab we'll have if
1617          * we're using the OFFPAGE slab header to track free items, given
1618          * all possible object sizes and the maximum desired wastage
1619          * (UMA_MAX_WASTE).
1620          *
1621          * We iterate until we find an object size for
1622          * which the calculated wastage in keg_small_init() will be
1623          * enough to warrant OFFPAGE.  Since wastedspace versus objsize
1624          * is an overall increasing see-saw function, we find the smallest
1625          * objsize such that the wastage is always acceptable for objects
1626          * with that objsize or smaller.  Since a smaller objsize always
1627          * generates a larger possible uma_max_ipers, we use this computed
1628          * objsize to calculate the largest ipers possible.  Since the
1629          * ipers calculated for OFFPAGE slab headers is always larger than
1630          * the ipers initially calculated in keg_small_init(), we use
1631          * the former's equation (UMA_SLAB_SIZE / keg->uk_rsize) to
1632          * obtain the maximum ipers possible for offpage slab headers.
1633          *
1634          * It should be noted that ipers versus objsize is an inversly
1635          * proportional function which drops off rather quickly so as
1636          * long as our UMA_MAX_WASTE is such that the objsize we calculate
1637          * falls into the portion of the inverse relation AFTER the steep
1638          * falloff, then uma_max_ipers shouldn't be too high (~10 on i386).
1639          *
1640          * Note that we have 8-bits (1 byte) to use as a freelist index
1641          * inside the actual slab header itself and this is enough to
1642          * accomodate us.  In the worst case, a UMA_SMALLEST_UNIT sized
1643          * object with offpage slab header would have ipers =
1644          * UMA_SLAB_SIZE / UMA_SMALLEST_UNIT (currently = 256), which is
1645          * 1 greater than what our byte-integer freelist index can
1646          * accomodate, but we know that this situation never occurs as
1647          * for UMA_SMALLEST_UNIT-sized objects, we will never calculate
1648          * that we need to go to offpage slab headers.  Or, if we do,
1649          * then we trap that condition below and panic in the INVARIANTS case.
1650          */
1651         wsize = UMA_SLAB_SIZE - sizeof(struct uma_slab) - UMA_MAX_WASTE;
1652         totsize = wsize;
1653         objsize = UMA_SMALLEST_UNIT;
1654         while (totsize >= wsize) {
1655                 totsize = (UMA_SLAB_SIZE - sizeof(struct uma_slab)) /
1656                     (objsize + UMA_FRITM_SZ);
1657                 totsize *= (UMA_FRITM_SZ + objsize);
1658                 objsize++;
1659         }
1660         if (objsize > UMA_SMALLEST_UNIT)
1661                 objsize--;
1662         uma_max_ipers = MAX(UMA_SLAB_SIZE / objsize, 64);
1663
1664         wsize = UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt) - UMA_MAX_WASTE;
1665         totsize = wsize;
1666         objsize = UMA_SMALLEST_UNIT;
1667         while (totsize >= wsize) {
1668                 totsize = (UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt)) /
1669                     (objsize + UMA_FRITMREF_SZ);
1670                 totsize *= (UMA_FRITMREF_SZ + objsize);
1671                 objsize++;
1672         }
1673         if (objsize > UMA_SMALLEST_UNIT)
1674                 objsize--;
1675         uma_max_ipers_ref = MAX(UMA_SLAB_SIZE / objsize, 64);
1676
1677         KASSERT((uma_max_ipers_ref <= 255) && (uma_max_ipers <= 255),
1678             ("uma_startup: calculated uma_max_ipers values too large!"));
1679
1680 #ifdef UMA_DEBUG
1681         printf("Calculated uma_max_ipers (for OFFPAGE) is %d\n", uma_max_ipers);
1682         printf("Calculated uma_max_ipers_ref (for OFFPAGE) is %d\n",
1683             uma_max_ipers_ref);
1684 #endif
1685
1686         /* "manually" create the initial zone */
1687         args.name = "UMA Kegs";
1688         args.size = sizeof(struct uma_keg);
1689         args.ctor = keg_ctor;
1690         args.dtor = keg_dtor;
1691         args.uminit = zero_init;
1692         args.fini = NULL;
1693         args.keg = &masterkeg;
1694         args.align = 32 - 1;
1695         args.flags = UMA_ZFLAG_INTERNAL;
1696         /* The initial zone has no Per cpu queues so it's smaller */
1697         zone_ctor(kegs, sizeof(struct uma_zone), &args, M_WAITOK);
1698
1699 #ifdef UMA_DEBUG
1700         printf("Filling boot free list.\n");
1701 #endif
1702         for (i = 0; i < boot_pages; i++) {
1703                 slab = (uma_slab_t)((u_int8_t *)bootmem + (i * UMA_SLAB_SIZE));
1704                 slab->us_data = (u_int8_t *)slab;
1705                 slab->us_flags = UMA_SLAB_BOOT;
1706                 LIST_INSERT_HEAD(&uma_boot_pages, slab, us_link);
1707         }
1708         mtx_init(&uma_boot_pages_mtx, "UMA boot pages", NULL, MTX_DEF);
1709
1710 #ifdef UMA_DEBUG
1711         printf("Creating uma zone headers zone and keg.\n");
1712 #endif
1713         args.name = "UMA Zones";
1714         args.size = sizeof(struct uma_zone) +
1715             (sizeof(struct uma_cache) * (mp_maxid + 1));
1716         args.ctor = zone_ctor;
1717         args.dtor = zone_dtor;
1718         args.uminit = zero_init;
1719         args.fini = NULL;
1720         args.keg = NULL;
1721         args.align = 32 - 1;
1722         args.flags = UMA_ZFLAG_INTERNAL;
1723         /* The initial zone has no Per cpu queues so it's smaller */
1724         zone_ctor(zones, sizeof(struct uma_zone), &args, M_WAITOK);
1725
1726 #ifdef UMA_DEBUG
1727         printf("Initializing pcpu cache locks.\n");
1728 #endif
1729 #ifdef UMA_DEBUG
1730         printf("Creating slab and hash zones.\n");
1731 #endif
1732
1733         /*
1734          * This is the max number of free list items we'll have with
1735          * offpage slabs.
1736          */
1737         slabsize = uma_max_ipers * UMA_FRITM_SZ;
1738         slabsize += sizeof(struct uma_slab);
1739
1740         /* Now make a zone for slab headers */
1741         slabzone = uma_zcreate("UMA Slabs",
1742                                 slabsize,
1743                                 NULL, NULL, NULL, NULL,
1744                                 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1745
1746         /*
1747          * We also create a zone for the bigger slabs with reference
1748          * counts in them, to accomodate UMA_ZONE_REFCNT zones.
1749          */
1750         slabsize = uma_max_ipers_ref * UMA_FRITMREF_SZ;
1751         slabsize += sizeof(struct uma_slab_refcnt);
1752         slabrefzone = uma_zcreate("UMA RCntSlabs",
1753                                   slabsize,
1754                                   NULL, NULL, NULL, NULL,
1755                                   UMA_ALIGN_PTR,
1756                                   UMA_ZFLAG_INTERNAL);
1757
1758         hashzone = uma_zcreate("UMA Hash",
1759             sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
1760             NULL, NULL, NULL, NULL,
1761             UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1762
1763         bucket_init();
1764
1765         booted = UMA_STARTUP;
1766
1767 #ifdef UMA_DEBUG
1768         printf("UMA startup complete.\n");
1769 #endif
1770 }
1771
1772 /* see uma.h */
1773 void
1774 uma_startup2(void)
1775 {
1776         booted = UMA_STARTUP2;
1777         bucket_enable();
1778 #ifdef UMA_DEBUG
1779         printf("UMA startup2 complete.\n");
1780 #endif
1781 }
1782
1783 /*
1784  * Initialize our callout handle
1785  *
1786  */
1787
1788 static void
1789 uma_startup3(void)
1790 {
1791 #ifdef UMA_DEBUG
1792         printf("Starting callout.\n");
1793 #endif
1794         callout_init(&uma_callout, CALLOUT_MPSAFE);
1795         callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
1796 #ifdef UMA_DEBUG
1797         printf("UMA startup3 complete.\n");
1798 #endif
1799 }
1800
1801 static uma_keg_t
1802 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
1803                 int align, u_int32_t flags)
1804 {
1805         struct uma_kctor_args args;
1806
1807         args.size = size;
1808         args.uminit = uminit;
1809         args.fini = fini;
1810         args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
1811         args.flags = flags;
1812         args.zone = zone;
1813         return (zone_alloc_item(kegs, &args, M_WAITOK));
1814 }
1815
1816 /* See uma.h */
1817 void
1818 uma_set_align(int align)
1819 {
1820
1821         if (align != UMA_ALIGN_CACHE)
1822                 uma_align_cache = align;
1823 }
1824
1825 /* See uma.h */
1826 uma_zone_t
1827 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
1828                 uma_init uminit, uma_fini fini, int align, u_int32_t flags)
1829
1830 {
1831         struct uma_zctor_args args;
1832
1833         /* This stuff is essential for the zone ctor */
1834         args.name = name;
1835         args.size = size;
1836         args.ctor = ctor;
1837         args.dtor = dtor;
1838         args.uminit = uminit;
1839         args.fini = fini;
1840         args.align = align;
1841         args.flags = flags;
1842         args.keg = NULL;
1843
1844         return (zone_alloc_item(zones, &args, M_WAITOK));
1845 }
1846
1847 /* See uma.h */
1848 uma_zone_t
1849 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
1850                     uma_init zinit, uma_fini zfini, uma_zone_t master)
1851 {
1852         struct uma_zctor_args args;
1853         uma_keg_t keg;
1854
1855         keg = zone_first_keg(master);
1856         args.name = name;
1857         args.size = keg->uk_size;
1858         args.ctor = ctor;
1859         args.dtor = dtor;
1860         args.uminit = zinit;
1861         args.fini = zfini;
1862         args.align = keg->uk_align;
1863         args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
1864         args.keg = keg;
1865
1866         /* XXX Attaches only one keg of potentially many. */
1867         return (zone_alloc_item(zones, &args, M_WAITOK));
1868 }
1869
1870 static void
1871 zone_lock_pair(uma_zone_t a, uma_zone_t b)
1872 {
1873         if (a < b) {
1874                 ZONE_LOCK(a);
1875                 mtx_lock_flags(b->uz_lock, MTX_DUPOK);
1876         } else {
1877                 ZONE_LOCK(b);
1878                 mtx_lock_flags(a->uz_lock, MTX_DUPOK);
1879         }
1880 }
1881
1882 static void
1883 zone_unlock_pair(uma_zone_t a, uma_zone_t b)
1884 {
1885
1886         ZONE_UNLOCK(a);
1887         ZONE_UNLOCK(b);
1888 }
1889
1890 int
1891 uma_zsecond_add(uma_zone_t zone, uma_zone_t master)
1892 {
1893         uma_klink_t klink;
1894         uma_klink_t kl;
1895         int error;
1896
1897         error = 0;
1898         klink = malloc(sizeof(*klink), M_TEMP, M_WAITOK | M_ZERO);
1899
1900         zone_lock_pair(zone, master);
1901         /*
1902          * zone must use vtoslab() to resolve objects and must already be
1903          * a secondary.
1904          */
1905         if ((zone->uz_flags & (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY))
1906             != (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY)) {
1907                 error = EINVAL;
1908                 goto out;
1909         }
1910         /*
1911          * The new master must also use vtoslab().
1912          */
1913         if ((zone->uz_flags & UMA_ZONE_VTOSLAB) != UMA_ZONE_VTOSLAB) {
1914                 error = EINVAL;
1915                 goto out;
1916         }
1917         /*
1918          * Both must either be refcnt, or not be refcnt.
1919          */
1920         if ((zone->uz_flags & UMA_ZONE_REFCNT) !=
1921             (master->uz_flags & UMA_ZONE_REFCNT)) {
1922                 error = EINVAL;
1923                 goto out;
1924         }
1925         /*
1926          * The underlying object must be the same size.  rsize
1927          * may be different.
1928          */
1929         if (master->uz_size != zone->uz_size) {
1930                 error = E2BIG;
1931                 goto out;
1932         }
1933         /*
1934          * Put it at the end of the list.
1935          */
1936         klink->kl_keg = zone_first_keg(master);
1937         LIST_FOREACH(kl, &zone->uz_kegs, kl_link) {
1938                 if (LIST_NEXT(kl, kl_link) == NULL) {
1939                         LIST_INSERT_AFTER(kl, klink, kl_link);
1940                         break;
1941                 }
1942         }
1943         klink = NULL;
1944         zone->uz_flags |= UMA_ZFLAG_MULTI;
1945         zone->uz_slab = zone_fetch_slab_multi;
1946
1947 out:
1948         zone_unlock_pair(zone, master);
1949         if (klink != NULL)
1950                 free(klink, M_TEMP);
1951
1952         return (error);
1953 }
1954
1955
1956 /* See uma.h */
1957 void
1958 uma_zdestroy(uma_zone_t zone)
1959 {
1960
1961         zone_free_item(zones, zone, NULL, SKIP_NONE, ZFREE_STATFREE);
1962 }
1963
1964 /* See uma.h */
1965 void *
1966 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
1967 {
1968         void *item;
1969         uma_cache_t cache;
1970         uma_bucket_t bucket;
1971         int cpu;
1972
1973         /* This is the fast path allocation */
1974 #ifdef UMA_DEBUG_ALLOC_1
1975         printf("Allocating one item from %s(%p)\n", zone->uz_name, zone);
1976 #endif
1977         CTR3(KTR_UMA, "uma_zalloc_arg thread %x zone %s flags %d", curthread,
1978             zone->uz_name, flags);
1979
1980         if (flags & M_WAITOK) {
1981                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1982                     "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
1983         }
1984
1985         /*
1986          * If possible, allocate from the per-CPU cache.  There are two
1987          * requirements for safe access to the per-CPU cache: (1) the thread
1988          * accessing the cache must not be preempted or yield during access,
1989          * and (2) the thread must not migrate CPUs without switching which
1990          * cache it accesses.  We rely on a critical section to prevent
1991          * preemption and migration.  We release the critical section in
1992          * order to acquire the zone mutex if we are unable to allocate from
1993          * the current cache; when we re-acquire the critical section, we
1994          * must detect and handle migration if it has occurred.
1995          */
1996 zalloc_restart:
1997         critical_enter();
1998         cpu = curcpu;
1999         cache = &zone->uz_cpu[cpu];
2000
2001 zalloc_start:
2002         bucket = cache->uc_allocbucket;
2003
2004         if (bucket) {
2005                 if (bucket->ub_cnt > 0) {
2006                         bucket->ub_cnt--;
2007                         item = bucket->ub_bucket[bucket->ub_cnt];
2008 #ifdef INVARIANTS
2009                         bucket->ub_bucket[bucket->ub_cnt] = NULL;
2010 #endif
2011                         KASSERT(item != NULL,
2012                             ("uma_zalloc: Bucket pointer mangled."));
2013                         cache->uc_allocs++;
2014                         critical_exit();
2015 #ifdef INVARIANTS
2016                         ZONE_LOCK(zone);
2017                         uma_dbg_alloc(zone, NULL, item);
2018                         ZONE_UNLOCK(zone);
2019 #endif
2020                         if (zone->uz_ctor != NULL) {
2021                                 if (zone->uz_ctor(item, zone->uz_size,
2022                                     udata, flags) != 0) {
2023                                         zone_free_item(zone, item, udata,
2024                                             SKIP_DTOR, ZFREE_STATFAIL |
2025                                             ZFREE_STATFREE);
2026                                         return (NULL);
2027                                 }
2028                         }
2029                         if (flags & M_ZERO)
2030                                 bzero(item, zone->uz_size);
2031                         return (item);
2032                 } else if (cache->uc_freebucket) {
2033                         /*
2034                          * We have run out of items in our allocbucket.
2035                          * See if we can switch with our free bucket.
2036                          */
2037                         if (cache->uc_freebucket->ub_cnt > 0) {
2038 #ifdef UMA_DEBUG_ALLOC
2039                                 printf("uma_zalloc: Swapping empty with"
2040                                     " alloc.\n");
2041 #endif
2042                                 bucket = cache->uc_freebucket;
2043                                 cache->uc_freebucket = cache->uc_allocbucket;
2044                                 cache->uc_allocbucket = bucket;
2045
2046                                 goto zalloc_start;
2047                         }
2048                 }
2049         }
2050         /*
2051          * Attempt to retrieve the item from the per-CPU cache has failed, so
2052          * we must go back to the zone.  This requires the zone lock, so we
2053          * must drop the critical section, then re-acquire it when we go back
2054          * to the cache.  Since the critical section is released, we may be
2055          * preempted or migrate.  As such, make sure not to maintain any
2056          * thread-local state specific to the cache from prior to releasing
2057          * the critical section.
2058          */
2059         critical_exit();
2060         ZONE_LOCK(zone);
2061         critical_enter();
2062         cpu = curcpu;
2063         cache = &zone->uz_cpu[cpu];
2064         bucket = cache->uc_allocbucket;
2065         if (bucket != NULL) {
2066                 if (bucket->ub_cnt > 0) {
2067                         ZONE_UNLOCK(zone);
2068                         goto zalloc_start;
2069                 }
2070                 bucket = cache->uc_freebucket;
2071                 if (bucket != NULL && bucket->ub_cnt > 0) {
2072                         ZONE_UNLOCK(zone);
2073                         goto zalloc_start;
2074                 }
2075         }
2076
2077         /* Since we have locked the zone we may as well send back our stats */
2078         zone->uz_allocs += cache->uc_allocs;
2079         cache->uc_allocs = 0;
2080         zone->uz_frees += cache->uc_frees;
2081         cache->uc_frees = 0;
2082
2083         /* Our old one is now a free bucket */
2084         if (cache->uc_allocbucket) {
2085                 KASSERT(cache->uc_allocbucket->ub_cnt == 0,
2086                     ("uma_zalloc_arg: Freeing a non free bucket."));
2087                 LIST_INSERT_HEAD(&zone->uz_free_bucket,
2088                     cache->uc_allocbucket, ub_link);
2089                 cache->uc_allocbucket = NULL;
2090         }
2091
2092         /* Check the free list for a new alloc bucket */
2093         if ((bucket = LIST_FIRST(&zone->uz_full_bucket)) != NULL) {
2094                 KASSERT(bucket->ub_cnt != 0,
2095                     ("uma_zalloc_arg: Returning an empty bucket."));
2096
2097                 LIST_REMOVE(bucket, ub_link);
2098                 cache->uc_allocbucket = bucket;
2099                 ZONE_UNLOCK(zone);
2100                 goto zalloc_start;
2101         }
2102         /* We are no longer associated with this CPU. */
2103         critical_exit();
2104
2105         /* Bump up our uz_count so we get here less */
2106         if (zone->uz_count < BUCKET_MAX)
2107                 zone->uz_count++;
2108
2109         /*
2110          * Now lets just fill a bucket and put it on the free list.  If that
2111          * works we'll restart the allocation from the begining.
2112          */
2113         if (zone_alloc_bucket(zone, flags)) {
2114                 ZONE_UNLOCK(zone);
2115                 goto zalloc_restart;
2116         }
2117         ZONE_UNLOCK(zone);
2118         /*
2119          * We may not be able to get a bucket so return an actual item.
2120          */
2121 #ifdef UMA_DEBUG
2122         printf("uma_zalloc_arg: Bucketzone returned NULL\n");
2123 #endif
2124
2125         item = zone_alloc_item(zone, udata, flags);
2126         return (item);
2127 }
2128
2129 static uma_slab_t
2130 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int flags)
2131 {
2132         uma_slab_t slab;
2133
2134         mtx_assert(&keg->uk_lock, MA_OWNED);
2135         slab = NULL;
2136
2137         for (;;) {
2138                 /*
2139                  * Find a slab with some space.  Prefer slabs that are partially
2140                  * used over those that are totally full.  This helps to reduce
2141                  * fragmentation.
2142                  */
2143                 if (keg->uk_free != 0) {
2144                         if (!LIST_EMPTY(&keg->uk_part_slab)) {
2145                                 slab = LIST_FIRST(&keg->uk_part_slab);
2146                         } else {
2147                                 slab = LIST_FIRST(&keg->uk_free_slab);
2148                                 LIST_REMOVE(slab, us_link);
2149                                 LIST_INSERT_HEAD(&keg->uk_part_slab, slab,
2150                                     us_link);
2151                         }
2152                         MPASS(slab->us_keg == keg);
2153                         return (slab);
2154                 }
2155
2156                 /*
2157                  * M_NOVM means don't ask at all!
2158                  */
2159                 if (flags & M_NOVM)
2160                         break;
2161
2162                 if (keg->uk_maxpages && keg->uk_pages >= keg->uk_maxpages) {
2163                         keg->uk_flags |= UMA_ZFLAG_FULL;
2164                         /*
2165                          * If this is not a multi-zone, set the FULL bit.
2166                          * Otherwise slab_multi() takes care of it.
2167                          */
2168                         if ((zone->uz_flags & UMA_ZFLAG_MULTI) == 0)
2169                                 zone->uz_flags |= UMA_ZFLAG_FULL;
2170                         if (flags & M_NOWAIT)
2171                                 break;
2172                         zone->uz_sleeps++;
2173                         msleep(keg, &keg->uk_lock, PVM, "keglimit", 0);
2174                         continue;
2175                 }
2176                 keg->uk_recurse++;
2177                 slab = keg_alloc_slab(keg, zone, flags);
2178                 keg->uk_recurse--;
2179                 /*
2180                  * If we got a slab here it's safe to mark it partially used
2181                  * and return.  We assume that the caller is going to remove
2182                  * at least one item.
2183                  */
2184                 if (slab) {
2185                         MPASS(slab->us_keg == keg);
2186                         LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
2187                         return (slab);
2188                 }
2189                 /*
2190                  * We might not have been able to get a slab but another cpu
2191                  * could have while we were unlocked.  Check again before we
2192                  * fail.
2193                  */
2194                 flags |= M_NOVM;
2195         }
2196         return (slab);
2197 }
2198
2199 static inline void
2200 zone_relock(uma_zone_t zone, uma_keg_t keg)
2201 {
2202         if (zone->uz_lock != &keg->uk_lock) {
2203                 KEG_UNLOCK(keg);
2204                 ZONE_LOCK(zone);
2205         }
2206 }
2207
2208 static inline void
2209 keg_relock(uma_keg_t keg, uma_zone_t zone)
2210 {
2211         if (zone->uz_lock != &keg->uk_lock) {
2212                 ZONE_UNLOCK(zone);
2213                 KEG_LOCK(keg);
2214         }
2215 }
2216
2217 static uma_slab_t
2218 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int flags)
2219 {
2220         uma_slab_t slab;
2221
2222         if (keg == NULL)
2223                 keg = zone_first_keg(zone);
2224         /*
2225          * This is to prevent us from recursively trying to allocate
2226          * buckets.  The problem is that if an allocation forces us to
2227          * grab a new bucket we will call page_alloc, which will go off
2228          * and cause the vm to allocate vm_map_entries.  If we need new
2229          * buckets there too we will recurse in kmem_alloc and bad
2230          * things happen.  So instead we return a NULL bucket, and make
2231          * the code that allocates buckets smart enough to deal with it
2232          */
2233         if (keg->uk_flags & UMA_ZFLAG_BUCKET && keg->uk_recurse != 0)
2234                 return (NULL);
2235
2236         for (;;) {
2237                 slab = keg_fetch_slab(keg, zone, flags);
2238                 if (slab)
2239                         return (slab);
2240                 if (flags & (M_NOWAIT | M_NOVM))
2241                         break;
2242         }
2243         return (NULL);
2244 }
2245
2246 /*
2247  * uma_zone_fetch_slab_multi:  Fetches a slab from one available keg.  Returns
2248  * with the keg locked.  Caller must call zone_relock() afterwards if the
2249  * zone lock is required.  On NULL the zone lock is held.
2250  *
2251  * The last pointer is used to seed the search.  It is not required.
2252  */
2253 static uma_slab_t
2254 zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int rflags)
2255 {
2256         uma_klink_t klink;
2257         uma_slab_t slab;
2258         uma_keg_t keg;
2259         int flags;
2260         int empty;
2261         int full;
2262
2263         /*
2264          * Don't wait on the first pass.  This will skip limit tests
2265          * as well.  We don't want to block if we can find a provider
2266          * without blocking.
2267          */
2268         flags = (rflags & ~M_WAITOK) | M_NOWAIT;
2269         /*
2270          * Use the last slab allocated as a hint for where to start
2271          * the search.
2272          */
2273         if (last) {
2274                 slab = keg_fetch_slab(last, zone, flags);
2275                 if (slab)
2276                         return (slab);
2277                 zone_relock(zone, last);
2278                 last = NULL;
2279         }
2280         /*
2281          * Loop until we have a slab incase of transient failures
2282          * while M_WAITOK is specified.  I'm not sure this is 100%
2283          * required but we've done it for so long now.
2284          */
2285         for (;;) {
2286                 empty = 0;
2287                 full = 0;
2288                 /*
2289                  * Search the available kegs for slabs.  Be careful to hold the
2290                  * correct lock while calling into the keg layer.
2291                  */
2292                 LIST_FOREACH(klink, &zone->uz_kegs, kl_link) {
2293                         keg = klink->kl_keg;
2294                         keg_relock(keg, zone);
2295                         if ((keg->uk_flags & UMA_ZFLAG_FULL) == 0) {
2296                                 slab = keg_fetch_slab(keg, zone, flags);
2297                                 if (slab)
2298                                         return (slab);
2299                         }
2300                         if (keg->uk_flags & UMA_ZFLAG_FULL)
2301                                 full++;
2302                         else
2303                                 empty++;
2304                         zone_relock(zone, keg);
2305                 }
2306                 if (rflags & (M_NOWAIT | M_NOVM))
2307                         break;
2308                 flags = rflags;
2309                 /*
2310                  * All kegs are full.  XXX We can't atomically check all kegs
2311                  * and sleep so just sleep for a short period and retry.
2312                  */
2313                 if (full && !empty) {
2314                         zone->uz_flags |= UMA_ZFLAG_FULL;
2315                         zone->uz_sleeps++;
2316                         msleep(zone, zone->uz_lock, PVM, "zonelimit", hz/100);
2317                         zone->uz_flags &= ~UMA_ZFLAG_FULL;
2318                         continue;
2319                 }
2320         }
2321         return (NULL);
2322 }
2323
2324 static void *
2325 slab_alloc_item(uma_zone_t zone, uma_slab_t slab)
2326 {
2327         uma_keg_t keg;
2328         uma_slabrefcnt_t slabref;
2329         void *item;
2330         u_int8_t freei;
2331
2332         keg = slab->us_keg;
2333         mtx_assert(&keg->uk_lock, MA_OWNED);
2334
2335         freei = slab->us_firstfree;
2336         if (keg->uk_flags & UMA_ZONE_REFCNT) {
2337                 slabref = (uma_slabrefcnt_t)slab;
2338                 slab->us_firstfree = slabref->us_freelist[freei].us_item;
2339         } else {
2340                 slab->us_firstfree = slab->us_freelist[freei].us_item;
2341         }
2342         item = slab->us_data + (keg->uk_rsize * freei);
2343
2344         slab->us_freecount--;
2345         keg->uk_free--;
2346 #ifdef INVARIANTS
2347         uma_dbg_alloc(zone, slab, item);
2348 #endif
2349         /* Move this slab to the full list */
2350         if (slab->us_freecount == 0) {
2351                 LIST_REMOVE(slab, us_link);
2352                 LIST_INSERT_HEAD(&keg->uk_full_slab, slab, us_link);
2353         }
2354
2355         return (item);
2356 }
2357
2358 static int
2359 zone_alloc_bucket(uma_zone_t zone, int flags)
2360 {
2361         uma_bucket_t bucket;
2362         uma_slab_t slab;
2363         uma_keg_t keg;
2364         int16_t saved;
2365         int max, origflags = flags;
2366
2367         /*
2368          * Try this zone's free list first so we don't allocate extra buckets.
2369          */
2370         if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
2371                 KASSERT(bucket->ub_cnt == 0,
2372                     ("zone_alloc_bucket: Bucket on free list is not empty."));
2373                 LIST_REMOVE(bucket, ub_link);
2374         } else {
2375                 int bflags;
2376
2377                 bflags = (flags & ~M_ZERO);
2378                 if (zone->uz_flags & UMA_ZFLAG_CACHEONLY)
2379                         bflags |= M_NOVM;
2380
2381                 ZONE_UNLOCK(zone);
2382                 bucket = bucket_alloc(zone->uz_count, bflags);
2383                 ZONE_LOCK(zone);
2384         }
2385
2386         if (bucket == NULL) {
2387                 return (0);
2388         }
2389
2390 #ifdef SMP
2391         /*
2392          * This code is here to limit the number of simultaneous bucket fills
2393          * for any given zone to the number of per cpu caches in this zone. This
2394          * is done so that we don't allocate more memory than we really need.
2395          */
2396         if (zone->uz_fills >= mp_ncpus)
2397                 goto done;
2398
2399 #endif
2400         zone->uz_fills++;
2401
2402         max = MIN(bucket->ub_entries, zone->uz_count);
2403         /* Try to keep the buckets totally full */
2404         saved = bucket->ub_cnt;
2405         slab = NULL;
2406         keg = NULL;
2407         while (bucket->ub_cnt < max &&
2408             (slab = zone->uz_slab(zone, keg, flags)) != NULL) {
2409                 keg = slab->us_keg;
2410                 while (slab->us_freecount && bucket->ub_cnt < max) {
2411                         bucket->ub_bucket[bucket->ub_cnt++] =
2412                             slab_alloc_item(zone, slab);
2413                 }
2414
2415                 /* Don't block on the next fill */
2416                 flags |= M_NOWAIT;
2417         }
2418         if (slab)
2419                 zone_relock(zone, keg);
2420
2421         /*
2422          * We unlock here because we need to call the zone's init.
2423          * It should be safe to unlock because the slab dealt with
2424          * above is already on the appropriate list within the keg
2425          * and the bucket we filled is not yet on any list, so we
2426          * own it.
2427          */
2428         if (zone->uz_init != NULL) {
2429                 int i;
2430
2431                 ZONE_UNLOCK(zone);
2432                 for (i = saved; i < bucket->ub_cnt; i++)
2433                         if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2434                             origflags) != 0)
2435                                 break;
2436                 /*
2437                  * If we couldn't initialize the whole bucket, put the
2438                  * rest back onto the freelist.
2439                  */
2440                 if (i != bucket->ub_cnt) {
2441                         int j;
2442
2443                         for (j = i; j < bucket->ub_cnt; j++) {
2444                                 zone_free_item(zone, bucket->ub_bucket[j],
2445                                     NULL, SKIP_FINI, 0);
2446 #ifdef INVARIANTS
2447                                 bucket->ub_bucket[j] = NULL;
2448 #endif
2449                         }
2450                         bucket->ub_cnt = i;
2451                 }
2452                 ZONE_LOCK(zone);
2453         }
2454
2455         zone->uz_fills--;
2456         if (bucket->ub_cnt != 0) {
2457                 LIST_INSERT_HEAD(&zone->uz_full_bucket,
2458                     bucket, ub_link);
2459                 return (1);
2460         }
2461 #ifdef SMP
2462 done:
2463 #endif
2464         bucket_free(bucket);
2465
2466         return (0);
2467 }
2468 /*
2469  * Allocates an item for an internal zone
2470  *
2471  * Arguments
2472  *      zone   The zone to alloc for.
2473  *      udata  The data to be passed to the constructor.
2474  *      flags  M_WAITOK, M_NOWAIT, M_ZERO.
2475  *
2476  * Returns
2477  *      NULL if there is no memory and M_NOWAIT is set
2478  *      An item if successful
2479  */
2480
2481 static void *
2482 zone_alloc_item(uma_zone_t zone, void *udata, int flags)
2483 {
2484         uma_slab_t slab;
2485         void *item;
2486
2487         item = NULL;
2488
2489 #ifdef UMA_DEBUG_ALLOC
2490         printf("INTERNAL: Allocating one item from %s(%p)\n", zone->uz_name, zone);
2491 #endif
2492         ZONE_LOCK(zone);
2493
2494         slab = zone->uz_slab(zone, NULL, flags);
2495         if (slab == NULL) {
2496                 zone->uz_fails++;
2497                 ZONE_UNLOCK(zone);
2498                 return (NULL);
2499         }
2500
2501         item = slab_alloc_item(zone, slab);
2502
2503         zone_relock(zone, slab->us_keg);
2504         zone->uz_allocs++;
2505         ZONE_UNLOCK(zone);
2506
2507         /*
2508          * We have to call both the zone's init (not the keg's init)
2509          * and the zone's ctor.  This is because the item is going from
2510          * a keg slab directly to the user, and the user is expecting it
2511          * to be both zone-init'd as well as zone-ctor'd.
2512          */
2513         if (zone->uz_init != NULL) {
2514                 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
2515                         zone_free_item(zone, item, udata, SKIP_FINI,
2516                             ZFREE_STATFAIL | ZFREE_STATFREE);
2517                         return (NULL);
2518                 }
2519         }
2520         if (zone->uz_ctor != NULL) {
2521                 if (zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2522                         zone_free_item(zone, item, udata, SKIP_DTOR,
2523                             ZFREE_STATFAIL | ZFREE_STATFREE);
2524                         return (NULL);
2525                 }
2526         }
2527         if (flags & M_ZERO)
2528                 bzero(item, zone->uz_size);
2529
2530         return (item);
2531 }
2532
2533 /* See uma.h */
2534 void
2535 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
2536 {
2537         uma_cache_t cache;
2538         uma_bucket_t bucket;
2539         int bflags;
2540         int cpu;
2541
2542 #ifdef UMA_DEBUG_ALLOC_1
2543         printf("Freeing item %p to %s(%p)\n", item, zone->uz_name, zone);
2544 #endif
2545         CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
2546             zone->uz_name);
2547
2548         /* uma_zfree(..., NULL) does nothing, to match free(9). */
2549         if (item == NULL)
2550                 return;
2551
2552         if (zone->uz_dtor)
2553                 zone->uz_dtor(item, zone->uz_size, udata);
2554
2555 #ifdef INVARIANTS
2556         ZONE_LOCK(zone);
2557         if (zone->uz_flags & UMA_ZONE_MALLOC)
2558                 uma_dbg_free(zone, udata, item);
2559         else
2560                 uma_dbg_free(zone, NULL, item);
2561         ZONE_UNLOCK(zone);
2562 #endif
2563         /*
2564          * The race here is acceptable.  If we miss it we'll just have to wait
2565          * a little longer for the limits to be reset.
2566          */
2567         if (zone->uz_flags & UMA_ZFLAG_FULL)
2568                 goto zfree_internal;
2569
2570         /*
2571          * If possible, free to the per-CPU cache.  There are two
2572          * requirements for safe access to the per-CPU cache: (1) the thread
2573          * accessing the cache must not be preempted or yield during access,
2574          * and (2) the thread must not migrate CPUs without switching which
2575          * cache it accesses.  We rely on a critical section to prevent
2576          * preemption and migration.  We release the critical section in
2577          * order to acquire the zone mutex if we are unable to free to the
2578          * current cache; when we re-acquire the critical section, we must
2579          * detect and handle migration if it has occurred.
2580          */
2581 zfree_restart:
2582         critical_enter();
2583         cpu = curcpu;
2584         cache = &zone->uz_cpu[cpu];
2585
2586 zfree_start:
2587         bucket = cache->uc_freebucket;
2588
2589         if (bucket) {
2590                 /*
2591                  * Do we have room in our bucket? It is OK for this uz count
2592                  * check to be slightly out of sync.
2593                  */
2594
2595                 if (bucket->ub_cnt < bucket->ub_entries) {
2596                         KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
2597                             ("uma_zfree: Freeing to non free bucket index."));
2598                         bucket->ub_bucket[bucket->ub_cnt] = item;
2599                         bucket->ub_cnt++;
2600                         cache->uc_frees++;
2601                         critical_exit();
2602                         return;
2603                 } else if (cache->uc_allocbucket) {
2604 #ifdef UMA_DEBUG_ALLOC
2605                         printf("uma_zfree: Swapping buckets.\n");
2606 #endif
2607                         /*
2608                          * We have run out of space in our freebucket.
2609                          * See if we can switch with our alloc bucket.
2610                          */
2611                         if (cache->uc_allocbucket->ub_cnt <
2612                             cache->uc_freebucket->ub_cnt) {
2613                                 bucket = cache->uc_freebucket;
2614                                 cache->uc_freebucket = cache->uc_allocbucket;
2615                                 cache->uc_allocbucket = bucket;
2616                                 goto zfree_start;
2617                         }
2618                 }
2619         }
2620         /*
2621          * We can get here for two reasons:
2622          *
2623          * 1) The buckets are NULL
2624          * 2) The alloc and free buckets are both somewhat full.
2625          *
2626          * We must go back the zone, which requires acquiring the zone lock,
2627          * which in turn means we must release and re-acquire the critical
2628          * section.  Since the critical section is released, we may be
2629          * preempted or migrate.  As such, make sure not to maintain any
2630          * thread-local state specific to the cache from prior to releasing
2631          * the critical section.
2632          */
2633         critical_exit();
2634         ZONE_LOCK(zone);
2635         critical_enter();
2636         cpu = curcpu;
2637         cache = &zone->uz_cpu[cpu];
2638         if (cache->uc_freebucket != NULL) {
2639                 if (cache->uc_freebucket->ub_cnt <
2640                     cache->uc_freebucket->ub_entries) {
2641                         ZONE_UNLOCK(zone);
2642                         goto zfree_start;
2643                 }
2644                 if (cache->uc_allocbucket != NULL &&
2645                     (cache->uc_allocbucket->ub_cnt <
2646                     cache->uc_freebucket->ub_cnt)) {
2647                         ZONE_UNLOCK(zone);
2648                         goto zfree_start;
2649                 }
2650         }
2651
2652         /* Since we have locked the zone we may as well send back our stats */
2653         zone->uz_allocs += cache->uc_allocs;
2654         cache->uc_allocs = 0;
2655         zone->uz_frees += cache->uc_frees;
2656         cache->uc_frees = 0;
2657
2658         bucket = cache->uc_freebucket;
2659         cache->uc_freebucket = NULL;
2660
2661         /* Can we throw this on the zone full list? */
2662         if (bucket != NULL) {
2663 #ifdef UMA_DEBUG_ALLOC
2664                 printf("uma_zfree: Putting old bucket on the free list.\n");
2665 #endif
2666                 /* ub_cnt is pointing to the last free item */
2667                 KASSERT(bucket->ub_cnt != 0,
2668                     ("uma_zfree: Attempting to insert an empty bucket onto the full list.\n"));
2669                 LIST_INSERT_HEAD(&zone->uz_full_bucket,
2670                     bucket, ub_link);
2671         }
2672         if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
2673                 LIST_REMOVE(bucket, ub_link);
2674                 ZONE_UNLOCK(zone);
2675                 cache->uc_freebucket = bucket;
2676                 goto zfree_start;
2677         }
2678         /* We are no longer associated with this CPU. */
2679         critical_exit();
2680
2681         /* And the zone.. */
2682         ZONE_UNLOCK(zone);
2683
2684 #ifdef UMA_DEBUG_ALLOC
2685         printf("uma_zfree: Allocating new free bucket.\n");
2686 #endif
2687         bflags = M_NOWAIT;
2688
2689         if (zone->uz_flags & UMA_ZFLAG_CACHEONLY)
2690                 bflags |= M_NOVM;
2691         bucket = bucket_alloc(zone->uz_count, bflags);
2692         if (bucket) {
2693                 ZONE_LOCK(zone);
2694                 LIST_INSERT_HEAD(&zone->uz_free_bucket,
2695                     bucket, ub_link);
2696                 ZONE_UNLOCK(zone);
2697                 goto zfree_restart;
2698         }
2699
2700         /*
2701          * If nothing else caught this, we'll just do an internal free.
2702          */
2703 zfree_internal:
2704         zone_free_item(zone, item, udata, SKIP_DTOR, ZFREE_STATFREE);
2705
2706         return;
2707 }
2708
2709 /*
2710  * Frees an item to an INTERNAL zone or allocates a free bucket
2711  *
2712  * Arguments:
2713  *      zone   The zone to free to
2714  *      item   The item we're freeing
2715  *      udata  User supplied data for the dtor
2716  *      skip   Skip dtors and finis
2717  */
2718 static void
2719 zone_free_item(uma_zone_t zone, void *item, void *udata,
2720     enum zfreeskip skip, int flags)
2721 {
2722         uma_slab_t slab;
2723         uma_slabrefcnt_t slabref;
2724         uma_keg_t keg;
2725         u_int8_t *mem;
2726         u_int8_t freei;
2727         int clearfull;
2728
2729         if (skip < SKIP_DTOR && zone->uz_dtor)
2730                 zone->uz_dtor(item, zone->uz_size, udata);
2731
2732         if (skip < SKIP_FINI && zone->uz_fini)
2733                 zone->uz_fini(item, zone->uz_size);
2734
2735         ZONE_LOCK(zone);
2736
2737         if (flags & ZFREE_STATFAIL)
2738                 zone->uz_fails++;
2739         if (flags & ZFREE_STATFREE)
2740                 zone->uz_frees++;
2741
2742         if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
2743                 mem = (u_int8_t *)((unsigned long)item & (~UMA_SLAB_MASK));
2744                 keg = zone_first_keg(zone); /* Must only be one. */
2745                 if (zone->uz_flags & UMA_ZONE_HASH) {
2746                         slab = hash_sfind(&keg->uk_hash, mem);
2747                 } else {
2748                         mem += keg->uk_pgoff;
2749                         slab = (uma_slab_t)mem;
2750                 }
2751         } else {
2752                 /* This prevents redundant lookups via free(). */
2753                 if ((zone->uz_flags & UMA_ZONE_MALLOC) && udata != NULL)
2754                         slab = (uma_slab_t)udata;
2755                 else
2756                         slab = vtoslab((vm_offset_t)item);
2757                 keg = slab->us_keg;
2758                 keg_relock(keg, zone);
2759         }
2760         MPASS(keg == slab->us_keg);
2761
2762         /* Do we need to remove from any lists? */
2763         if (slab->us_freecount+1 == keg->uk_ipers) {
2764                 LIST_REMOVE(slab, us_link);
2765                 LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
2766         } else if (slab->us_freecount == 0) {
2767                 LIST_REMOVE(slab, us_link);
2768                 LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
2769         }
2770
2771         /* Slab management stuff */
2772         freei = ((unsigned long)item - (unsigned long)slab->us_data)
2773                 / keg->uk_rsize;
2774
2775 #ifdef INVARIANTS
2776         if (!skip)
2777                 uma_dbg_free(zone, slab, item);
2778 #endif
2779
2780         if (keg->uk_flags & UMA_ZONE_REFCNT) {
2781                 slabref = (uma_slabrefcnt_t)slab;
2782                 slabref->us_freelist[freei].us_item = slab->us_firstfree;
2783         } else {
2784                 slab->us_freelist[freei].us_item = slab->us_firstfree;
2785         }
2786         slab->us_firstfree = freei;
2787         slab->us_freecount++;
2788
2789         /* Zone statistics */
2790         keg->uk_free++;
2791
2792         clearfull = 0;
2793         if (keg->uk_flags & UMA_ZFLAG_FULL) {
2794                 if (keg->uk_pages < keg->uk_maxpages) {
2795                         keg->uk_flags &= ~UMA_ZFLAG_FULL;
2796                         clearfull = 1;
2797                 }
2798
2799                 /* 
2800                  * We can handle one more allocation. Since we're clearing ZFLAG_FULL,
2801                  * wake up all procs blocked on pages. This should be uncommon, so 
2802                  * keeping this simple for now (rather than adding count of blocked 
2803                  * threads etc).
2804                  */
2805                 wakeup(keg);
2806         }
2807         if (clearfull) {
2808                 zone_relock(zone, keg);
2809                 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2810                 wakeup(zone);
2811                 ZONE_UNLOCK(zone);
2812         } else
2813                 KEG_UNLOCK(keg);
2814 }
2815
2816 /* See uma.h */
2817 int
2818 uma_zone_set_max(uma_zone_t zone, int nitems)
2819 {
2820         uma_keg_t keg;
2821
2822         ZONE_LOCK(zone);
2823         keg = zone_first_keg(zone);
2824         keg->uk_maxpages = (nitems / keg->uk_ipers) * keg->uk_ppera;
2825         if (keg->uk_maxpages * keg->uk_ipers < nitems)
2826                 keg->uk_maxpages += keg->uk_ppera;
2827         nitems = keg->uk_maxpages * keg->uk_ipers;
2828         ZONE_UNLOCK(zone);
2829
2830         return (nitems);
2831 }
2832
2833 /* See uma.h */
2834 int
2835 uma_zone_get_max(uma_zone_t zone)
2836 {
2837         int nitems;
2838         uma_keg_t keg;
2839
2840         ZONE_LOCK(zone);
2841         keg = zone_first_keg(zone);
2842         nitems = keg->uk_maxpages * keg->uk_ipers;
2843         ZONE_UNLOCK(zone);
2844
2845         return (nitems);
2846 }
2847
2848 /* See uma.h */
2849 int
2850 uma_zone_get_cur(uma_zone_t zone)
2851 {
2852         int64_t nitems;
2853         u_int i;
2854
2855         ZONE_LOCK(zone);
2856         nitems = zone->uz_allocs - zone->uz_frees;
2857         CPU_FOREACH(i) {
2858                 /*
2859                  * See the comment in sysctl_vm_zone_stats() regarding the
2860                  * safety of accessing the per-cpu caches. With the zone lock
2861                  * held, it is safe, but can potentially result in stale data.
2862                  */
2863                 nitems += zone->uz_cpu[i].uc_allocs -
2864                     zone->uz_cpu[i].uc_frees;
2865         }
2866         ZONE_UNLOCK(zone);
2867
2868         return (nitems < 0 ? 0 : nitems);
2869 }
2870
2871 /* See uma.h */
2872 void
2873 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
2874 {
2875         uma_keg_t keg;
2876
2877         ZONE_LOCK(zone);
2878         keg = zone_first_keg(zone);
2879         KASSERT(keg->uk_pages == 0,
2880             ("uma_zone_set_init on non-empty keg"));
2881         keg->uk_init = uminit;
2882         ZONE_UNLOCK(zone);
2883 }
2884
2885 /* See uma.h */
2886 void
2887 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
2888 {
2889         uma_keg_t keg;
2890
2891         ZONE_LOCK(zone);
2892         keg = zone_first_keg(zone);
2893         KASSERT(keg->uk_pages == 0,
2894             ("uma_zone_set_fini on non-empty keg"));
2895         keg->uk_fini = fini;
2896         ZONE_UNLOCK(zone);
2897 }
2898
2899 /* See uma.h */
2900 void
2901 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
2902 {
2903         ZONE_LOCK(zone);
2904         KASSERT(zone_first_keg(zone)->uk_pages == 0,
2905             ("uma_zone_set_zinit on non-empty keg"));
2906         zone->uz_init = zinit;
2907         ZONE_UNLOCK(zone);
2908 }
2909
2910 /* See uma.h */
2911 void
2912 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
2913 {
2914         ZONE_LOCK(zone);
2915         KASSERT(zone_first_keg(zone)->uk_pages == 0,
2916             ("uma_zone_set_zfini on non-empty keg"));
2917         zone->uz_fini = zfini;
2918         ZONE_UNLOCK(zone);
2919 }
2920
2921 /* See uma.h */
2922 /* XXX uk_freef is not actually used with the zone locked */
2923 void
2924 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
2925 {
2926
2927         ZONE_LOCK(zone);
2928         zone_first_keg(zone)->uk_freef = freef;
2929         ZONE_UNLOCK(zone);
2930 }
2931
2932 /* See uma.h */
2933 /* XXX uk_allocf is not actually used with the zone locked */
2934 void
2935 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
2936 {
2937         uma_keg_t keg;
2938
2939         ZONE_LOCK(zone);
2940         keg = zone_first_keg(zone);
2941         keg->uk_flags |= UMA_ZFLAG_PRIVALLOC;
2942         keg->uk_allocf = allocf;
2943         ZONE_UNLOCK(zone);
2944 }
2945
2946 /* See uma.h */
2947 int
2948 uma_zone_set_obj(uma_zone_t zone, struct vm_object *obj, int count)
2949 {
2950         uma_keg_t keg;
2951         vm_offset_t kva;
2952         int pages;
2953
2954         keg = zone_first_keg(zone);
2955         pages = count / keg->uk_ipers;
2956
2957         if (pages * keg->uk_ipers < count)
2958                 pages++;
2959
2960         kva = kmem_alloc_nofault(kernel_map, pages * UMA_SLAB_SIZE);
2961
2962         if (kva == 0)
2963                 return (0);
2964         if (obj == NULL)
2965                 obj = vm_object_allocate(OBJT_PHYS, pages);
2966         else {
2967                 VM_OBJECT_LOCK_INIT(obj, "uma object");
2968                 _vm_object_allocate(OBJT_PHYS, pages, obj);
2969         }
2970         ZONE_LOCK(zone);
2971         keg->uk_kva = kva;
2972         keg->uk_obj = obj;
2973         keg->uk_maxpages = pages;
2974         keg->uk_allocf = obj_alloc;
2975         keg->uk_flags |= UMA_ZONE_NOFREE | UMA_ZFLAG_PRIVALLOC;
2976         ZONE_UNLOCK(zone);
2977         return (1);
2978 }
2979
2980 /* See uma.h */
2981 void
2982 uma_prealloc(uma_zone_t zone, int items)
2983 {
2984         int slabs;
2985         uma_slab_t slab;
2986         uma_keg_t keg;
2987
2988         keg = zone_first_keg(zone);
2989         ZONE_LOCK(zone);
2990         slabs = items / keg->uk_ipers;
2991         if (slabs * keg->uk_ipers < items)
2992                 slabs++;
2993         while (slabs > 0) {
2994                 slab = keg_alloc_slab(keg, zone, M_WAITOK);
2995                 if (slab == NULL)
2996                         break;
2997                 MPASS(slab->us_keg == keg);
2998                 LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
2999                 slabs--;
3000         }
3001         ZONE_UNLOCK(zone);
3002 }
3003
3004 /* See uma.h */
3005 u_int32_t *
3006 uma_find_refcnt(uma_zone_t zone, void *item)
3007 {
3008         uma_slabrefcnt_t slabref;
3009         uma_keg_t keg;
3010         u_int32_t *refcnt;
3011         int idx;
3012
3013         slabref = (uma_slabrefcnt_t)vtoslab((vm_offset_t)item &
3014             (~UMA_SLAB_MASK));
3015         keg = slabref->us_keg;
3016         KASSERT(slabref != NULL && slabref->us_keg->uk_flags & UMA_ZONE_REFCNT,
3017             ("uma_find_refcnt(): zone possibly not UMA_ZONE_REFCNT"));
3018         idx = ((unsigned long)item - (unsigned long)slabref->us_data)
3019             / keg->uk_rsize;
3020         refcnt = &slabref->us_freelist[idx].us_refcnt;
3021         return refcnt;
3022 }
3023
3024 /* See uma.h */
3025 void
3026 uma_reclaim(void)
3027 {
3028 #ifdef UMA_DEBUG
3029         printf("UMA: vm asked us to release pages!\n");
3030 #endif
3031         bucket_enable();
3032         zone_foreach(zone_drain);
3033         /*
3034          * Some slabs may have been freed but this zone will be visited early
3035          * we visit again so that we can free pages that are empty once other
3036          * zones are drained.  We have to do the same for buckets.
3037          */
3038         zone_drain(slabzone);
3039         zone_drain(slabrefzone);
3040         bucket_zone_drain();
3041 }
3042
3043 /* See uma.h */
3044 int
3045 uma_zone_exhausted(uma_zone_t zone)
3046 {
3047         int full;
3048
3049         ZONE_LOCK(zone);
3050         full = (zone->uz_flags & UMA_ZFLAG_FULL);
3051         ZONE_UNLOCK(zone);
3052         return (full);  
3053 }
3054
3055 int
3056 uma_zone_exhausted_nolock(uma_zone_t zone)
3057 {
3058         return (zone->uz_flags & UMA_ZFLAG_FULL);
3059 }
3060
3061 void *
3062 uma_large_malloc(int size, int wait)
3063 {
3064         void *mem;
3065         uma_slab_t slab;
3066         u_int8_t flags;
3067
3068         slab = zone_alloc_item(slabzone, NULL, wait);
3069         if (slab == NULL)
3070                 return (NULL);
3071         mem = page_alloc(NULL, size, &flags, wait);
3072         if (mem) {
3073                 vsetslab((vm_offset_t)mem, slab);
3074                 slab->us_data = mem;
3075                 slab->us_flags = flags | UMA_SLAB_MALLOC;
3076                 slab->us_size = size;
3077         } else {
3078                 zone_free_item(slabzone, slab, NULL, SKIP_NONE,
3079                     ZFREE_STATFAIL | ZFREE_STATFREE);
3080         }
3081
3082         return (mem);
3083 }
3084
3085 void
3086 uma_large_free(uma_slab_t slab)
3087 {
3088         vsetobj((vm_offset_t)slab->us_data, kmem_object);
3089         page_free(slab->us_data, slab->us_size, slab->us_flags);
3090         zone_free_item(slabzone, slab, NULL, SKIP_NONE, ZFREE_STATFREE);
3091 }
3092
3093 void
3094 uma_print_stats(void)
3095 {
3096         zone_foreach(uma_print_zone);
3097 }
3098
3099 static void
3100 slab_print(uma_slab_t slab)
3101 {
3102         printf("slab: keg %p, data %p, freecount %d, firstfree %d\n",
3103                 slab->us_keg, slab->us_data, slab->us_freecount,
3104                 slab->us_firstfree);
3105 }
3106
3107 static void
3108 cache_print(uma_cache_t cache)
3109 {
3110         printf("alloc: %p(%d), free: %p(%d)\n",
3111                 cache->uc_allocbucket,
3112                 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3113                 cache->uc_freebucket,
3114                 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3115 }
3116
3117 static void
3118 uma_print_keg(uma_keg_t keg)
3119 {
3120         uma_slab_t slab;
3121
3122         printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3123             "out %d free %d limit %d\n",
3124             keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3125             keg->uk_ipers, keg->uk_ppera,
3126             (keg->uk_ipers * keg->uk_pages) - keg->uk_free, keg->uk_free,
3127             (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers);
3128         printf("Part slabs:\n");
3129         LIST_FOREACH(slab, &keg->uk_part_slab, us_link)
3130                 slab_print(slab);
3131         printf("Free slabs:\n");
3132         LIST_FOREACH(slab, &keg->uk_free_slab, us_link)
3133                 slab_print(slab);
3134         printf("Full slabs:\n");
3135         LIST_FOREACH(slab, &keg->uk_full_slab, us_link)
3136                 slab_print(slab);
3137 }
3138
3139 void
3140 uma_print_zone(uma_zone_t zone)
3141 {
3142         uma_cache_t cache;
3143         uma_klink_t kl;
3144         int i;
3145
3146         printf("zone: %s(%p) size %d flags %#x\n",
3147             zone->uz_name, zone, zone->uz_size, zone->uz_flags);
3148         LIST_FOREACH(kl, &zone->uz_kegs, kl_link)
3149                 uma_print_keg(kl->kl_keg);
3150         CPU_FOREACH(i) {
3151                 cache = &zone->uz_cpu[i];
3152                 printf("CPU %d Cache:\n", i);
3153                 cache_print(cache);
3154         }
3155 }
3156
3157 #ifdef DDB
3158 /*
3159  * Generate statistics across both the zone and its per-cpu cache's.  Return
3160  * desired statistics if the pointer is non-NULL for that statistic.
3161  *
3162  * Note: does not update the zone statistics, as it can't safely clear the
3163  * per-CPU cache statistic.
3164  *
3165  * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3166  * safe from off-CPU; we should modify the caches to track this information
3167  * directly so that we don't have to.
3168  */
3169 static void
3170 uma_zone_sumstat(uma_zone_t z, int *cachefreep, u_int64_t *allocsp,
3171     u_int64_t *freesp, u_int64_t *sleepsp)
3172 {
3173         uma_cache_t cache;
3174         u_int64_t allocs, frees, sleeps;
3175         int cachefree, cpu;
3176
3177         allocs = frees = sleeps = 0;
3178         cachefree = 0;
3179         CPU_FOREACH(cpu) {
3180                 cache = &z->uz_cpu[cpu];
3181                 if (cache->uc_allocbucket != NULL)
3182                         cachefree += cache->uc_allocbucket->ub_cnt;
3183                 if (cache->uc_freebucket != NULL)
3184                         cachefree += cache->uc_freebucket->ub_cnt;
3185                 allocs += cache->uc_allocs;
3186                 frees += cache->uc_frees;
3187         }
3188         allocs += z->uz_allocs;
3189         frees += z->uz_frees;
3190         sleeps += z->uz_sleeps;
3191         if (cachefreep != NULL)
3192                 *cachefreep = cachefree;
3193         if (allocsp != NULL)
3194                 *allocsp = allocs;
3195         if (freesp != NULL)
3196                 *freesp = frees;
3197         if (sleepsp != NULL)
3198                 *sleepsp = sleeps;
3199 }
3200 #endif /* DDB */
3201
3202 static int
3203 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3204 {
3205         uma_keg_t kz;
3206         uma_zone_t z;
3207         int count;
3208
3209         count = 0;
3210         mtx_lock(&uma_mtx);
3211         LIST_FOREACH(kz, &uma_kegs, uk_link) {
3212                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3213                         count++;
3214         }
3215         mtx_unlock(&uma_mtx);
3216         return (sysctl_handle_int(oidp, &count, 0, req));
3217 }
3218
3219 static int
3220 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3221 {
3222         struct uma_stream_header ush;
3223         struct uma_type_header uth;
3224         struct uma_percpu_stat ups;
3225         uma_bucket_t bucket;
3226         struct sbuf sbuf;
3227         uma_cache_t cache;
3228         uma_klink_t kl;
3229         uma_keg_t kz;
3230         uma_zone_t z;
3231         uma_keg_t k;
3232         int count, error, i;
3233
3234         error = sysctl_wire_old_buffer(req, 0);
3235         if (error != 0)
3236                 return (error);
3237         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3238
3239         count = 0;
3240         mtx_lock(&uma_mtx);
3241         LIST_FOREACH(kz, &uma_kegs, uk_link) {
3242                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3243                         count++;
3244         }
3245
3246         /*
3247          * Insert stream header.
3248          */
3249         bzero(&ush, sizeof(ush));
3250         ush.ush_version = UMA_STREAM_VERSION;
3251         ush.ush_maxcpus = (mp_maxid + 1);
3252         ush.ush_count = count;
3253         (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
3254
3255         LIST_FOREACH(kz, &uma_kegs, uk_link) {
3256                 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3257                         bzero(&uth, sizeof(uth));
3258                         ZONE_LOCK(z);
3259                         strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3260                         uth.uth_align = kz->uk_align;
3261                         uth.uth_size = kz->uk_size;
3262                         uth.uth_rsize = kz->uk_rsize;
3263                         LIST_FOREACH(kl, &z->uz_kegs, kl_link) {
3264                                 k = kl->kl_keg;
3265                                 uth.uth_maxpages += k->uk_maxpages;
3266                                 uth.uth_pages += k->uk_pages;
3267                                 uth.uth_keg_free += k->uk_free;
3268                                 uth.uth_limit = (k->uk_maxpages / k->uk_ppera)
3269                                     * k->uk_ipers;
3270                         }
3271
3272                         /*
3273                          * A zone is secondary is it is not the first entry
3274                          * on the keg's zone list.
3275                          */
3276                         if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
3277                             (LIST_FIRST(&kz->uk_zones) != z))
3278                                 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
3279
3280                         LIST_FOREACH(bucket, &z->uz_full_bucket, ub_link)
3281                                 uth.uth_zone_free += bucket->ub_cnt;
3282                         uth.uth_allocs = z->uz_allocs;
3283                         uth.uth_frees = z->uz_frees;
3284                         uth.uth_fails = z->uz_fails;
3285                         uth.uth_sleeps = z->uz_sleeps;
3286                         (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
3287                         /*
3288                          * While it is not normally safe to access the cache
3289                          * bucket pointers while not on the CPU that owns the
3290                          * cache, we only allow the pointers to be exchanged
3291                          * without the zone lock held, not invalidated, so
3292                          * accept the possible race associated with bucket
3293                          * exchange during monitoring.
3294                          */
3295                         for (i = 0; i < (mp_maxid + 1); i++) {
3296                                 bzero(&ups, sizeof(ups));
3297                                 if (kz->uk_flags & UMA_ZFLAG_INTERNAL)
3298                                         goto skip;
3299                                 if (CPU_ABSENT(i))
3300                                         goto skip;
3301                                 cache = &z->uz_cpu[i];
3302                                 if (cache->uc_allocbucket != NULL)
3303                                         ups.ups_cache_free +=
3304                                             cache->uc_allocbucket->ub_cnt;
3305                                 if (cache->uc_freebucket != NULL)
3306                                         ups.ups_cache_free +=
3307                                             cache->uc_freebucket->ub_cnt;
3308                                 ups.ups_allocs = cache->uc_allocs;
3309                                 ups.ups_frees = cache->uc_frees;
3310 skip:
3311                                 (void)sbuf_bcat(&sbuf, &ups, sizeof(ups));
3312                         }
3313                         ZONE_UNLOCK(z);
3314                 }
3315         }
3316         mtx_unlock(&uma_mtx);
3317         error = sbuf_finish(&sbuf);
3318         sbuf_delete(&sbuf);
3319         return (error);
3320 }
3321
3322 #ifdef DDB
3323 DB_SHOW_COMMAND(uma, db_show_uma)
3324 {
3325         u_int64_t allocs, frees, sleeps;
3326         uma_bucket_t bucket;
3327         uma_keg_t kz;
3328         uma_zone_t z;
3329         int cachefree;
3330
3331         db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
3332             "Requests", "Sleeps");
3333         LIST_FOREACH(kz, &uma_kegs, uk_link) {
3334                 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3335                         if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
3336                                 allocs = z->uz_allocs;
3337                                 frees = z->uz_frees;
3338                                 sleeps = z->uz_sleeps;
3339                                 cachefree = 0;
3340                         } else
3341                                 uma_zone_sumstat(z, &cachefree, &allocs,
3342                                     &frees, &sleeps);
3343                         if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
3344                             (LIST_FIRST(&kz->uk_zones) != z)))
3345                                 cachefree += kz->uk_free;
3346                         LIST_FOREACH(bucket, &z->uz_full_bucket, ub_link)
3347                                 cachefree += bucket->ub_cnt;
3348                         db_printf("%18s %8ju %8jd %8d %12ju %8ju\n", z->uz_name,
3349                             (uintmax_t)kz->uk_size,
3350                             (intmax_t)(allocs - frees), cachefree,
3351                             (uintmax_t)allocs, sleeps);
3352                         if (db_pager_quit)
3353                                 return;
3354                 }
3355         }
3356 }
3357 #endif