]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/vm/uma_core.c
MFC r363988:
[FreeBSD/stable/9.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                 msleep(zone, zone->uz_lock, PVM, "zonedrain", 1);
765         }
766         zone->uz_flags |= UMA_ZFLAG_DRAINING;
767         bucket_cache_drain(zone);
768         ZONE_UNLOCK(zone);
769         /*
770          * The DRAINING flag protects us from being freed while
771          * we're running.  Normally the uma_mtx would protect us but we
772          * must be able to release and acquire the right lock for each keg.
773          */
774         zone_foreach_keg(zone, &keg_drain);
775         ZONE_LOCK(zone);
776         zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
777         wakeup(zone);
778 out:
779         ZONE_UNLOCK(zone);
780 }
781
782 void
783 zone_drain(uma_zone_t zone)
784 {
785
786         zone_drain_wait(zone, M_NOWAIT);
787 }
788
789 /*
790  * Allocate a new slab for a keg.  This does not insert the slab onto a list.
791  *
792  * Arguments:
793  *      wait  Shall we wait?
794  *
795  * Returns:
796  *      The slab that was allocated or NULL if there is no memory and the
797  *      caller specified M_NOWAIT.
798  */
799 static uma_slab_t
800 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int wait)
801 {
802         uma_slabrefcnt_t slabref;
803         uma_alloc allocf;
804         uma_slab_t slab;
805         u_int8_t *mem;
806         u_int8_t flags;
807         int i;
808
809         mtx_assert(&keg->uk_lock, MA_OWNED);
810         slab = NULL;
811
812 #ifdef UMA_DEBUG
813         printf("slab_zalloc:  Allocating a new slab for %s\n", keg->uk_name);
814 #endif
815         allocf = keg->uk_allocf;
816         KEG_UNLOCK(keg);
817
818         if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
819                 slab = zone_alloc_item(keg->uk_slabzone, NULL, wait);
820                 if (slab == NULL) {
821                         KEG_LOCK(keg);
822                         return NULL;
823                 }
824         }
825
826         /*
827          * This reproduces the old vm_zone behavior of zero filling pages the
828          * first time they are added to a zone.
829          *
830          * Malloced items are zeroed in uma_zalloc.
831          */
832
833         if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
834                 wait |= M_ZERO;
835         else
836                 wait &= ~M_ZERO;
837
838         if (keg->uk_flags & UMA_ZONE_NODUMP)
839                 wait |= M_NODUMP;
840
841         /* zone is passed for legacy reasons. */
842         mem = allocf(zone, keg->uk_ppera * UMA_SLAB_SIZE, &flags, wait);
843         if (mem == NULL) {
844                 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
845                         zone_free_item(keg->uk_slabzone, slab, NULL,
846                             SKIP_NONE, ZFREE_STATFREE);
847                 KEG_LOCK(keg);
848                 return (NULL);
849         }
850
851         /* Point the slab into the allocated memory */
852         if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
853                 slab = (uma_slab_t )(mem + keg->uk_pgoff);
854
855         if (keg->uk_flags & UMA_ZONE_VTOSLAB)
856                 for (i = 0; i < keg->uk_ppera; i++)
857                         vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
858
859         slab->us_keg = keg;
860         slab->us_data = mem;
861         slab->us_freecount = keg->uk_ipers;
862         slab->us_firstfree = 0;
863         slab->us_flags = flags;
864
865         if (keg->uk_flags & UMA_ZONE_REFCNT) {
866                 slabref = (uma_slabrefcnt_t)slab;
867                 for (i = 0; i < keg->uk_ipers; i++) {
868                         slabref->us_freelist[i].us_refcnt = 0;
869                         slabref->us_freelist[i].us_item = i+1;
870                 }
871         } else {
872                 for (i = 0; i < keg->uk_ipers; i++)
873                         slab->us_freelist[i].us_item = i+1;
874         }
875
876         if (keg->uk_init != NULL) {
877                 for (i = 0; i < keg->uk_ipers; i++)
878                         if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
879                             keg->uk_size, wait) != 0)
880                                 break;
881                 if (i != keg->uk_ipers) {
882                         if (keg->uk_fini != NULL) {
883                                 for (i--; i > -1; i--)
884                                         keg->uk_fini(slab->us_data +
885                                             (keg->uk_rsize * i),
886                                             keg->uk_size);
887                         }
888                         if (keg->uk_flags & UMA_ZONE_VTOSLAB) {
889                                 vm_object_t obj;
890
891                                 if (flags & UMA_SLAB_KMEM)
892                                         obj = kmem_object;
893                                 else if (flags & UMA_SLAB_KERNEL)
894                                         obj = kernel_object;
895                                 else
896                                         obj = NULL;
897                                 for (i = 0; i < keg->uk_ppera; i++)
898                                         vsetobj((vm_offset_t)mem +
899                                             (i * PAGE_SIZE), obj);
900                         }
901                         if (keg->uk_flags & UMA_ZONE_OFFPAGE)
902                                 zone_free_item(keg->uk_slabzone, slab,
903                                     NULL, SKIP_NONE, ZFREE_STATFREE);
904                         keg->uk_freef(mem, UMA_SLAB_SIZE * keg->uk_ppera,
905                             flags);
906                         KEG_LOCK(keg);
907                         return (NULL);
908                 }
909         }
910         KEG_LOCK(keg);
911
912         if (keg->uk_flags & UMA_ZONE_HASH)
913                 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
914
915         keg->uk_pages += keg->uk_ppera;
916         keg->uk_free += keg->uk_ipers;
917
918         return (slab);
919 }
920
921 /*
922  * This function is intended to be used early on in place of page_alloc() so
923  * that we may use the boot time page cache to satisfy allocations before
924  * the VM is ready.
925  */
926 static void *
927 startup_alloc(uma_zone_t zone, int bytes, u_int8_t *pflag, int wait)
928 {
929         uma_keg_t keg;
930         uma_slab_t tmps;
931         int pages, check_pages;
932
933         keg = zone_first_keg(zone);
934         pages = howmany(bytes, PAGE_SIZE);
935         check_pages = pages - 1;
936         KASSERT(pages > 0, ("startup_alloc can't reserve 0 pages\n"));
937
938         /*
939          * Check our small startup cache to see if it has pages remaining.
940          */
941         mtx_lock(&uma_boot_pages_mtx);
942
943         /* First check if we have enough room. */
944         tmps = LIST_FIRST(&uma_boot_pages);
945         while (tmps != NULL && check_pages-- > 0)
946                 tmps = LIST_NEXT(tmps, us_link);
947         if (tmps != NULL) {
948                 /*
949                  * It's ok to lose tmps references.  The last one will
950                  * have tmps->us_data pointing to the start address of
951                  * "pages" contiguous pages of memory.
952                  */
953                 while (pages-- > 0) {
954                         tmps = LIST_FIRST(&uma_boot_pages);
955                         LIST_REMOVE(tmps, us_link);
956                 }
957                 mtx_unlock(&uma_boot_pages_mtx);
958                 *pflag = tmps->us_flags;
959                 return (tmps->us_data);
960         }
961         mtx_unlock(&uma_boot_pages_mtx);
962         if (booted < UMA_STARTUP2)
963                 panic("UMA: Increase vm.boot_pages");
964         /*
965          * Now that we've booted reset these users to their real allocator.
966          */
967 #ifdef UMA_MD_SMALL_ALLOC
968         keg->uk_allocf = (keg->uk_ppera > 1) ? page_alloc : uma_small_alloc;
969 #else
970         keg->uk_allocf = page_alloc;
971 #endif
972         return keg->uk_allocf(zone, bytes, pflag, wait);
973 }
974
975 /*
976  * Allocates a number of pages from the system
977  *
978  * Arguments:
979  *      bytes  The number of bytes requested
980  *      wait  Shall we wait?
981  *
982  * Returns:
983  *      A pointer to the alloced memory or possibly
984  *      NULL if M_NOWAIT is set.
985  */
986 static void *
987 page_alloc(uma_zone_t zone, int bytes, u_int8_t *pflag, int wait)
988 {
989         void *p;        /* Returned page */
990
991         *pflag = UMA_SLAB_KMEM;
992         p = (void *) kmem_malloc(kmem_map, bytes, wait);
993
994         return (p);
995 }
996
997 /*
998  * Allocates a number of pages from within an object
999  *
1000  * Arguments:
1001  *      bytes  The number of bytes requested
1002  *      wait   Shall we wait?
1003  *
1004  * Returns:
1005  *      A pointer to the alloced memory or possibly
1006  *      NULL if M_NOWAIT is set.
1007  */
1008 static void *
1009 obj_alloc(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
1010 {
1011         vm_object_t object;
1012         vm_offset_t retkva, zkva;
1013         vm_page_t p;
1014         int pages, startpages;
1015         uma_keg_t keg;
1016
1017         keg = zone_first_keg(zone);
1018         object = keg->uk_obj;
1019         retkva = 0;
1020
1021         /*
1022          * This looks a little weird since we're getting one page at a time.
1023          */
1024         VM_OBJECT_LOCK(object);
1025         p = TAILQ_LAST(&object->memq, pglist);
1026         pages = p != NULL ? p->pindex + 1 : 0;
1027         startpages = pages;
1028         zkva = keg->uk_kva + pages * PAGE_SIZE;
1029         for (; bytes > 0; bytes -= PAGE_SIZE) {
1030                 p = vm_page_alloc(object, pages,
1031                     VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED);
1032                 if (p == NULL) {
1033                         if (pages != startpages)
1034                                 pmap_qremove(retkva, pages - startpages);
1035                         while (pages != startpages) {
1036                                 pages--;
1037                                 p = TAILQ_LAST(&object->memq, pglist);
1038                                 vm_page_unwire(p, 0);
1039                                 vm_page_free(p);
1040                         }
1041                         retkva = 0;
1042                         goto done;
1043                 }
1044                 pmap_qenter(zkva, &p, 1);
1045                 if (retkva == 0)
1046                         retkva = zkva;
1047                 zkva += PAGE_SIZE;
1048                 pages += 1;
1049         }
1050 done:
1051         VM_OBJECT_UNLOCK(object);
1052         *flags = UMA_SLAB_PRIV;
1053
1054         return ((void *)retkva);
1055 }
1056
1057 /*
1058  * Frees a number of pages to the system
1059  *
1060  * Arguments:
1061  *      mem   A pointer to the memory to be freed
1062  *      size  The size of the memory being freed
1063  *      flags The original p->us_flags field
1064  *
1065  * Returns:
1066  *      Nothing
1067  */
1068 static void
1069 page_free(void *mem, int size, u_int8_t flags)
1070 {
1071         vm_map_t map;
1072
1073         if (flags & UMA_SLAB_KMEM)
1074                 map = kmem_map;
1075         else if (flags & UMA_SLAB_KERNEL)
1076                 map = kernel_map;
1077         else
1078                 panic("UMA: page_free used with invalid flags %d", flags);
1079
1080         kmem_free(map, (vm_offset_t)mem, size);
1081 }
1082
1083 /*
1084  * Zero fill initializer
1085  *
1086  * Arguments/Returns follow uma_init specifications
1087  */
1088 static int
1089 zero_init(void *mem, int size, int flags)
1090 {
1091         bzero(mem, size);
1092         return (0);
1093 }
1094
1095 /*
1096  * Finish creating a small uma keg.  This calculates ipers, and the keg size.
1097  *
1098  * Arguments
1099  *      keg  The zone we should initialize
1100  *
1101  * Returns
1102  *      Nothing
1103  */
1104 static void
1105 keg_small_init(uma_keg_t keg)
1106 {
1107         u_int rsize;
1108         u_int memused;
1109         u_int wastedspace;
1110         u_int shsize;
1111
1112         KASSERT(keg != NULL, ("Keg is null in keg_small_init"));
1113         rsize = keg->uk_size;
1114
1115         if (rsize < UMA_SMALLEST_UNIT)
1116                 rsize = UMA_SMALLEST_UNIT;
1117         if (rsize & keg->uk_align)
1118                 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1119
1120         keg->uk_rsize = rsize;
1121         keg->uk_ppera = 1;
1122
1123         if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1124                 shsize = 0;
1125         } else if (keg->uk_flags & UMA_ZONE_REFCNT) {
1126                 rsize += UMA_FRITMREF_SZ;       /* linkage & refcnt */
1127                 shsize = sizeof(struct uma_slab_refcnt);
1128         } else {
1129                 rsize += UMA_FRITM_SZ;  /* Account for linkage */
1130                 shsize = sizeof(struct uma_slab);
1131         }
1132
1133         keg->uk_ipers = (UMA_SLAB_SIZE - shsize) / rsize;
1134         KASSERT(keg->uk_ipers != 0, ("keg_small_init: ipers is 0"));
1135         memused = keg->uk_ipers * rsize + shsize;
1136         wastedspace = UMA_SLAB_SIZE - memused;
1137
1138         /*
1139          * We can't do OFFPAGE if we're internal or if we've been
1140          * asked to not go to the VM for buckets.  If we do this we
1141          * may end up going to the VM (kmem_map) for slabs which we
1142          * do not want to do if we're UMA_ZFLAG_CACHEONLY as a
1143          * result of UMA_ZONE_VM, which clearly forbids it.
1144          */
1145         if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1146             (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1147                 return;
1148
1149         if ((wastedspace >= UMA_MAX_WASTE) &&
1150             (keg->uk_ipers < (UMA_SLAB_SIZE / keg->uk_rsize))) {
1151                 keg->uk_ipers = UMA_SLAB_SIZE / keg->uk_rsize;
1152                 KASSERT(keg->uk_ipers <= 255,
1153                     ("keg_small_init: keg->uk_ipers too high!"));
1154 #ifdef UMA_DEBUG
1155                 printf("UMA decided we need offpage slab headers for "
1156                     "keg: %s, calculated wastedspace = %d, "
1157                     "maximum wasted space allowed = %d, "
1158                     "calculated ipers = %d, "
1159                     "new wasted space = %d\n", keg->uk_name, wastedspace,
1160                     UMA_MAX_WASTE, keg->uk_ipers,
1161                     UMA_SLAB_SIZE - keg->uk_ipers * keg->uk_rsize);
1162 #endif
1163                 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1164                 if ((keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1165                         keg->uk_flags |= UMA_ZONE_HASH;
1166         }
1167 }
1168
1169 /*
1170  * Finish creating a large (> UMA_SLAB_SIZE) uma kegs.  Just give in and do
1171  * OFFPAGE for now.  When I can allow for more dynamic slab sizes this will be
1172  * more complicated.
1173  *
1174  * Arguments
1175  *      keg  The keg we should initialize
1176  *
1177  * Returns
1178  *      Nothing
1179  */
1180 static void
1181 keg_large_init(uma_keg_t keg)
1182 {
1183         int pages;
1184
1185         KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1186         KASSERT((keg->uk_flags & UMA_ZFLAG_CACHEONLY) == 0,
1187             ("keg_large_init: Cannot large-init a UMA_ZFLAG_CACHEONLY keg"));
1188
1189         pages = keg->uk_size / UMA_SLAB_SIZE;
1190
1191         /* Account for remainder */
1192         if ((pages * UMA_SLAB_SIZE) < keg->uk_size)
1193                 pages++;
1194
1195         keg->uk_ppera = pages;
1196         keg->uk_ipers = 1;
1197         keg->uk_rsize = keg->uk_size;
1198
1199         /* We can't do OFFPAGE if we're internal, bail out here. */
1200         if (keg->uk_flags & UMA_ZFLAG_INTERNAL)
1201                 return;
1202
1203         keg->uk_flags |= UMA_ZONE_OFFPAGE;
1204         if ((keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1205                 keg->uk_flags |= UMA_ZONE_HASH;
1206 }
1207
1208 static void
1209 keg_cachespread_init(uma_keg_t keg)
1210 {
1211         int alignsize;
1212         int trailer;
1213         int pages;
1214         int rsize;
1215
1216         alignsize = keg->uk_align + 1;
1217         rsize = keg->uk_size;
1218         /*
1219          * We want one item to start on every align boundary in a page.  To
1220          * do this we will span pages.  We will also extend the item by the
1221          * size of align if it is an even multiple of align.  Otherwise, it
1222          * would fall on the same boundary every time.
1223          */
1224         if (rsize & keg->uk_align)
1225                 rsize = (rsize & ~keg->uk_align) + alignsize;
1226         if ((rsize & alignsize) == 0)
1227                 rsize += alignsize;
1228         trailer = rsize - keg->uk_size;
1229         pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1230         pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1231         keg->uk_rsize = rsize;
1232         keg->uk_ppera = pages;
1233         keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1234         keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1235         KASSERT(keg->uk_ipers <= uma_max_ipers,
1236             ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1237             keg->uk_ipers));
1238 }
1239
1240 /*
1241  * Keg header ctor.  This initializes all fields, locks, etc.  And inserts
1242  * the keg onto the global keg list.
1243  *
1244  * Arguments/Returns follow uma_ctor specifications
1245  *      udata  Actually uma_kctor_args
1246  */
1247 static int
1248 keg_ctor(void *mem, int size, void *udata, int flags)
1249 {
1250         struct uma_kctor_args *arg = udata;
1251         uma_keg_t keg = mem;
1252         uma_zone_t zone;
1253
1254         bzero(keg, size);
1255         keg->uk_size = arg->size;
1256         keg->uk_init = arg->uminit;
1257         keg->uk_fini = arg->fini;
1258         keg->uk_align = arg->align;
1259         keg->uk_free = 0;
1260         keg->uk_pages = 0;
1261         keg->uk_flags = arg->flags;
1262         keg->uk_allocf = page_alloc;
1263         keg->uk_freef = page_free;
1264         keg->uk_recurse = 0;
1265         keg->uk_slabzone = NULL;
1266
1267         /*
1268          * The master zone is passed to us at keg-creation time.
1269          */
1270         zone = arg->zone;
1271         keg->uk_name = zone->uz_name;
1272
1273         if (arg->flags & UMA_ZONE_VM)
1274                 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1275
1276         if (arg->flags & UMA_ZONE_ZINIT)
1277                 keg->uk_init = zero_init;
1278
1279         if (arg->flags & UMA_ZONE_REFCNT || arg->flags & UMA_ZONE_MALLOC)
1280                 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1281
1282         /*
1283          * The +UMA_FRITM_SZ added to uk_size is to account for the
1284          * linkage that is added to the size in keg_small_init().  If
1285          * we don't account for this here then we may end up in
1286          * keg_small_init() with a calculated 'ipers' of 0.
1287          */
1288         if (keg->uk_flags & UMA_ZONE_REFCNT) {
1289                 if (keg->uk_flags & UMA_ZONE_CACHESPREAD)
1290                         keg_cachespread_init(keg);
1291                 else if ((keg->uk_size+UMA_FRITMREF_SZ) >
1292                     (UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt)))
1293                         keg_large_init(keg);
1294                 else
1295                         keg_small_init(keg);
1296         } else {
1297                 if (keg->uk_flags & UMA_ZONE_CACHESPREAD)
1298                         keg_cachespread_init(keg);
1299                 else if ((keg->uk_size+UMA_FRITM_SZ) >
1300                     (UMA_SLAB_SIZE - sizeof(struct uma_slab)))
1301                         keg_large_init(keg);
1302                 else
1303                         keg_small_init(keg);
1304         }
1305
1306         if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1307                 if (keg->uk_flags & UMA_ZONE_REFCNT)
1308                         keg->uk_slabzone = slabrefzone;
1309                 else
1310                         keg->uk_slabzone = slabzone;
1311         }
1312
1313         /*
1314          * If we haven't booted yet we need allocations to go through the
1315          * startup cache until the vm is ready.
1316          */
1317         if (keg->uk_ppera == 1) {
1318 #ifdef UMA_MD_SMALL_ALLOC
1319                 keg->uk_allocf = uma_small_alloc;
1320                 keg->uk_freef = uma_small_free;
1321
1322                 if (booted < UMA_STARTUP)
1323                         keg->uk_allocf = startup_alloc;
1324 #else
1325                 if (booted < UMA_STARTUP2)
1326                         keg->uk_allocf = startup_alloc;
1327 #endif
1328         } else if (booted < UMA_STARTUP2 &&
1329             (keg->uk_flags & UMA_ZFLAG_INTERNAL))
1330                 keg->uk_allocf = startup_alloc;
1331
1332         /*
1333          * Initialize keg's lock (shared among zones).
1334          */
1335         if (arg->flags & UMA_ZONE_MTXCLASS)
1336                 KEG_LOCK_INIT(keg, 1);
1337         else
1338                 KEG_LOCK_INIT(keg, 0);
1339
1340         /*
1341          * If we're putting the slab header in the actual page we need to
1342          * figure out where in each page it goes.  This calculates a right
1343          * justified offset into the memory on an ALIGN_PTR boundary.
1344          */
1345         if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1346                 u_int totsize;
1347
1348                 /* Size of the slab struct and free list */
1349                 if (keg->uk_flags & UMA_ZONE_REFCNT)
1350                         totsize = sizeof(struct uma_slab_refcnt) +
1351                             keg->uk_ipers * UMA_FRITMREF_SZ;
1352                 else
1353                         totsize = sizeof(struct uma_slab) +
1354                             keg->uk_ipers * UMA_FRITM_SZ;
1355
1356                 if (totsize & UMA_ALIGN_PTR)
1357                         totsize = (totsize & ~UMA_ALIGN_PTR) +
1358                             (UMA_ALIGN_PTR + 1);
1359                 keg->uk_pgoff = (UMA_SLAB_SIZE * keg->uk_ppera) - totsize;
1360
1361                 if (keg->uk_flags & UMA_ZONE_REFCNT)
1362                         totsize = keg->uk_pgoff + sizeof(struct uma_slab_refcnt)
1363                             + keg->uk_ipers * UMA_FRITMREF_SZ;
1364                 else
1365                         totsize = keg->uk_pgoff + sizeof(struct uma_slab)
1366                             + keg->uk_ipers * UMA_FRITM_SZ;
1367
1368                 /*
1369                  * The only way the following is possible is if with our
1370                  * UMA_ALIGN_PTR adjustments we are now bigger than
1371                  * UMA_SLAB_SIZE.  I haven't checked whether this is
1372                  * mathematically possible for all cases, so we make
1373                  * sure here anyway.
1374                  */
1375                 if (totsize > UMA_SLAB_SIZE * keg->uk_ppera) {
1376                         printf("zone %s ipers %d rsize %d size %d\n",
1377                             zone->uz_name, keg->uk_ipers, keg->uk_rsize,
1378                             keg->uk_size);
1379                         panic("UMA slab won't fit.");
1380                 }
1381         }
1382
1383         if (keg->uk_flags & UMA_ZONE_HASH)
1384                 hash_alloc(&keg->uk_hash);
1385
1386 #ifdef UMA_DEBUG
1387         printf("UMA: %s(%p) size %d(%d) flags %#x ipers %d ppera %d out %d free %d\n",
1388             zone->uz_name, zone, keg->uk_size, keg->uk_rsize, keg->uk_flags,
1389             keg->uk_ipers, keg->uk_ppera,
1390             (keg->uk_ipers * keg->uk_pages) - keg->uk_free, keg->uk_free);
1391 #endif
1392
1393         LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1394
1395         mtx_lock(&uma_mtx);
1396         LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1397         mtx_unlock(&uma_mtx);
1398         return (0);
1399 }
1400
1401 /*
1402  * Zone header ctor.  This initializes all fields, locks, etc.
1403  *
1404  * Arguments/Returns follow uma_ctor specifications
1405  *      udata  Actually uma_zctor_args
1406  */
1407 static int
1408 zone_ctor(void *mem, int size, void *udata, int flags)
1409 {
1410         struct uma_zctor_args *arg = udata;
1411         uma_zone_t zone = mem;
1412         uma_zone_t z;
1413         uma_keg_t keg;
1414
1415         bzero(zone, size);
1416         zone->uz_name = arg->name;
1417         zone->uz_ctor = arg->ctor;
1418         zone->uz_dtor = arg->dtor;
1419         zone->uz_slab = zone_fetch_slab;
1420         zone->uz_init = NULL;
1421         zone->uz_fini = NULL;
1422         zone->uz_allocs = 0;
1423         zone->uz_frees = 0;
1424         zone->uz_fails = 0;
1425         zone->uz_sleeps = 0;
1426         zone->uz_fills = zone->uz_count = 0;
1427         zone->uz_flags = 0;
1428         keg = arg->keg;
1429
1430         if (arg->flags & UMA_ZONE_SECONDARY) {
1431                 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1432                 zone->uz_init = arg->uminit;
1433                 zone->uz_fini = arg->fini;
1434                 zone->uz_lock = &keg->uk_lock;
1435                 zone->uz_flags |= UMA_ZONE_SECONDARY;
1436                 mtx_lock(&uma_mtx);
1437                 ZONE_LOCK(zone);
1438                 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1439                         if (LIST_NEXT(z, uz_link) == NULL) {
1440                                 LIST_INSERT_AFTER(z, zone, uz_link);
1441                                 break;
1442                         }
1443                 }
1444                 ZONE_UNLOCK(zone);
1445                 mtx_unlock(&uma_mtx);
1446         } else if (keg == NULL) {
1447                 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1448                     arg->align, arg->flags)) == NULL)
1449                         return (ENOMEM);
1450         } else {
1451                 struct uma_kctor_args karg;
1452                 int error;
1453
1454                 /* We should only be here from uma_startup() */
1455                 karg.size = arg->size;
1456                 karg.uminit = arg->uminit;
1457                 karg.fini = arg->fini;
1458                 karg.align = arg->align;
1459                 karg.flags = arg->flags;
1460                 karg.zone = zone;
1461                 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1462                     flags);
1463                 if (error)
1464                         return (error);
1465         }
1466         /*
1467          * Link in the first keg.
1468          */
1469         zone->uz_klink.kl_keg = keg;
1470         LIST_INSERT_HEAD(&zone->uz_kegs, &zone->uz_klink, kl_link);
1471         zone->uz_lock = &keg->uk_lock;
1472         zone->uz_size = keg->uk_size;
1473         zone->uz_flags |= (keg->uk_flags &
1474             (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1475
1476         /*
1477          * Some internal zones don't have room allocated for the per cpu
1478          * caches.  If we're internal, bail out here.
1479          */
1480         if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1481                 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1482                     ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1483                 return (0);
1484         }
1485
1486         if (keg->uk_flags & UMA_ZONE_MAXBUCKET)
1487                 zone->uz_count = BUCKET_MAX;
1488         else if (keg->uk_ipers <= BUCKET_MAX)
1489                 zone->uz_count = keg->uk_ipers;
1490         else
1491                 zone->uz_count = BUCKET_MAX;
1492         return (0);
1493 }
1494
1495 /*
1496  * Keg header dtor.  This frees all data, destroys locks, frees the hash
1497  * table and removes the keg from the global list.
1498  *
1499  * Arguments/Returns follow uma_dtor specifications
1500  *      udata  unused
1501  */
1502 static void
1503 keg_dtor(void *arg, int size, void *udata)
1504 {
1505         uma_keg_t keg;
1506
1507         keg = (uma_keg_t)arg;
1508         KEG_LOCK(keg);
1509         if (keg->uk_free != 0) {
1510                 printf("Freed UMA keg (%s) was not empty (%d items). "
1511                     " Lost %d pages of memory.\n",
1512                     keg->uk_name ? keg->uk_name : "",
1513                     keg->uk_free, keg->uk_pages);
1514         }
1515         KEG_UNLOCK(keg);
1516
1517         hash_free(&keg->uk_hash);
1518
1519         KEG_LOCK_FINI(keg);
1520 }
1521
1522 /*
1523  * Zone header dtor.
1524  *
1525  * Arguments/Returns follow uma_dtor specifications
1526  *      udata  unused
1527  */
1528 static void
1529 zone_dtor(void *arg, int size, void *udata)
1530 {
1531         uma_klink_t klink;
1532         uma_zone_t zone;
1533         uma_keg_t keg;
1534
1535         zone = (uma_zone_t)arg;
1536         keg = zone_first_keg(zone);
1537
1538         if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1539                 cache_drain(zone);
1540
1541         mtx_lock(&uma_mtx);
1542         LIST_REMOVE(zone, uz_link);
1543         mtx_unlock(&uma_mtx);
1544         /*
1545          * XXX there are some races here where
1546          * the zone can be drained but zone lock
1547          * released and then refilled before we
1548          * remove it... we dont care for now
1549          */
1550         zone_drain_wait(zone, M_WAITOK);
1551         /*
1552          * Unlink all of our kegs.
1553          */
1554         while ((klink = LIST_FIRST(&zone->uz_kegs)) != NULL) {
1555                 klink->kl_keg = NULL;
1556                 LIST_REMOVE(klink, kl_link);
1557                 if (klink == &zone->uz_klink)
1558                         continue;
1559                 free(klink, M_TEMP);
1560         }
1561         /*
1562          * We only destroy kegs from non secondary zones.
1563          */
1564         if ((zone->uz_flags & UMA_ZONE_SECONDARY) == 0)  {
1565                 mtx_lock(&uma_mtx);
1566                 LIST_REMOVE(keg, uk_link);
1567                 mtx_unlock(&uma_mtx);
1568                 zone_free_item(kegs, keg, NULL, SKIP_NONE,
1569                     ZFREE_STATFREE);
1570         }
1571 }
1572
1573 /*
1574  * Traverses every zone in the system and calls a callback
1575  *
1576  * Arguments:
1577  *      zfunc  A pointer to a function which accepts a zone
1578  *              as an argument.
1579  *
1580  * Returns:
1581  *      Nothing
1582  */
1583 static void
1584 zone_foreach(void (*zfunc)(uma_zone_t))
1585 {
1586         uma_keg_t keg;
1587         uma_zone_t zone;
1588
1589         mtx_lock(&uma_mtx);
1590         LIST_FOREACH(keg, &uma_kegs, uk_link) {
1591                 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1592                         zfunc(zone);
1593         }
1594         mtx_unlock(&uma_mtx);
1595 }
1596
1597 /* Public functions */
1598 /* See uma.h */
1599 void
1600 uma_startup(void *bootmem, int boot_pages)
1601 {
1602         struct uma_zctor_args args;
1603         uma_slab_t slab;
1604         u_int slabsize;
1605         u_int objsize, totsize, wsize;
1606         int i;
1607
1608 #ifdef UMA_DEBUG
1609         printf("Creating uma keg headers zone and keg.\n");
1610 #endif
1611         mtx_init(&uma_mtx, "UMA lock", NULL, MTX_DEF);
1612
1613         /*
1614          * Figure out the maximum number of items-per-slab we'll have if
1615          * we're using the OFFPAGE slab header to track free items, given
1616          * all possible object sizes and the maximum desired wastage
1617          * (UMA_MAX_WASTE).
1618          *
1619          * We iterate until we find an object size for
1620          * which the calculated wastage in keg_small_init() will be
1621          * enough to warrant OFFPAGE.  Since wastedspace versus objsize
1622          * is an overall increasing see-saw function, we find the smallest
1623          * objsize such that the wastage is always acceptable for objects
1624          * with that objsize or smaller.  Since a smaller objsize always
1625          * generates a larger possible uma_max_ipers, we use this computed
1626          * objsize to calculate the largest ipers possible.  Since the
1627          * ipers calculated for OFFPAGE slab headers is always larger than
1628          * the ipers initially calculated in keg_small_init(), we use
1629          * the former's equation (UMA_SLAB_SIZE / keg->uk_rsize) to
1630          * obtain the maximum ipers possible for offpage slab headers.
1631          *
1632          * It should be noted that ipers versus objsize is an inversly
1633          * proportional function which drops off rather quickly so as
1634          * long as our UMA_MAX_WASTE is such that the objsize we calculate
1635          * falls into the portion of the inverse relation AFTER the steep
1636          * falloff, then uma_max_ipers shouldn't be too high (~10 on i386).
1637          *
1638          * Note that we have 8-bits (1 byte) to use as a freelist index
1639          * inside the actual slab header itself and this is enough to
1640          * accomodate us.  In the worst case, a UMA_SMALLEST_UNIT sized
1641          * object with offpage slab header would have ipers =
1642          * UMA_SLAB_SIZE / UMA_SMALLEST_UNIT (currently = 256), which is
1643          * 1 greater than what our byte-integer freelist index can
1644          * accomodate, but we know that this situation never occurs as
1645          * for UMA_SMALLEST_UNIT-sized objects, we will never calculate
1646          * that we need to go to offpage slab headers.  Or, if we do,
1647          * then we trap that condition below and panic in the INVARIANTS case.
1648          */
1649         wsize = UMA_SLAB_SIZE - sizeof(struct uma_slab) - UMA_MAX_WASTE;
1650         totsize = wsize;
1651         objsize = UMA_SMALLEST_UNIT;
1652         while (totsize >= wsize) {
1653                 totsize = (UMA_SLAB_SIZE - sizeof(struct uma_slab)) /
1654                     (objsize + UMA_FRITM_SZ);
1655                 totsize *= (UMA_FRITM_SZ + objsize);
1656                 objsize++;
1657         }
1658         if (objsize > UMA_SMALLEST_UNIT)
1659                 objsize--;
1660         uma_max_ipers = MAX(UMA_SLAB_SIZE / objsize, 64);
1661
1662         wsize = UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt) - UMA_MAX_WASTE;
1663         totsize = wsize;
1664         objsize = UMA_SMALLEST_UNIT;
1665         while (totsize >= wsize) {
1666                 totsize = (UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt)) /
1667                     (objsize + UMA_FRITMREF_SZ);
1668                 totsize *= (UMA_FRITMREF_SZ + objsize);
1669                 objsize++;
1670         }
1671         if (objsize > UMA_SMALLEST_UNIT)
1672                 objsize--;
1673         uma_max_ipers_ref = MAX(UMA_SLAB_SIZE / objsize, 64);
1674
1675         KASSERT((uma_max_ipers_ref <= 255) && (uma_max_ipers <= 255),
1676             ("uma_startup: calculated uma_max_ipers values too large!"));
1677
1678 #ifdef UMA_DEBUG
1679         printf("Calculated uma_max_ipers (for OFFPAGE) is %d\n", uma_max_ipers);
1680         printf("Calculated uma_max_ipers_ref (for OFFPAGE) is %d\n",
1681             uma_max_ipers_ref);
1682 #endif
1683
1684         /* "manually" create the initial zone */
1685         args.name = "UMA Kegs";
1686         args.size = sizeof(struct uma_keg);
1687         args.ctor = keg_ctor;
1688         args.dtor = keg_dtor;
1689         args.uminit = zero_init;
1690         args.fini = NULL;
1691         args.keg = &masterkeg;
1692         args.align = 32 - 1;
1693         args.flags = UMA_ZFLAG_INTERNAL;
1694         /* The initial zone has no Per cpu queues so it's smaller */
1695         zone_ctor(kegs, sizeof(struct uma_zone), &args, M_WAITOK);
1696
1697 #ifdef UMA_DEBUG
1698         printf("Filling boot free list.\n");
1699 #endif
1700         for (i = 0; i < boot_pages; i++) {
1701                 slab = (uma_slab_t)((u_int8_t *)bootmem + (i * UMA_SLAB_SIZE));
1702                 slab->us_data = (u_int8_t *)slab;
1703                 slab->us_flags = UMA_SLAB_BOOT;
1704                 LIST_INSERT_HEAD(&uma_boot_pages, slab, us_link);
1705         }
1706         mtx_init(&uma_boot_pages_mtx, "UMA boot pages", NULL, MTX_DEF);
1707
1708 #ifdef UMA_DEBUG
1709         printf("Creating uma zone headers zone and keg.\n");
1710 #endif
1711         args.name = "UMA Zones";
1712         args.size = sizeof(struct uma_zone) +
1713             (sizeof(struct uma_cache) * (mp_maxid + 1));
1714         args.ctor = zone_ctor;
1715         args.dtor = zone_dtor;
1716         args.uminit = zero_init;
1717         args.fini = NULL;
1718         args.keg = NULL;
1719         args.align = 32 - 1;
1720         args.flags = UMA_ZFLAG_INTERNAL;
1721         /* The initial zone has no Per cpu queues so it's smaller */
1722         zone_ctor(zones, sizeof(struct uma_zone), &args, M_WAITOK);
1723
1724 #ifdef UMA_DEBUG
1725         printf("Initializing pcpu cache locks.\n");
1726 #endif
1727 #ifdef UMA_DEBUG
1728         printf("Creating slab and hash zones.\n");
1729 #endif
1730
1731         /*
1732          * This is the max number of free list items we'll have with
1733          * offpage slabs.
1734          */
1735         slabsize = uma_max_ipers * UMA_FRITM_SZ;
1736         slabsize += sizeof(struct uma_slab);
1737
1738         /* Now make a zone for slab headers */
1739         slabzone = uma_zcreate("UMA Slabs",
1740                                 slabsize,
1741                                 NULL, NULL, NULL, NULL,
1742                                 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1743
1744         /*
1745          * We also create a zone for the bigger slabs with reference
1746          * counts in them, to accomodate UMA_ZONE_REFCNT zones.
1747          */
1748         slabsize = uma_max_ipers_ref * UMA_FRITMREF_SZ;
1749         slabsize += sizeof(struct uma_slab_refcnt);
1750         slabrefzone = uma_zcreate("UMA RCntSlabs",
1751                                   slabsize,
1752                                   NULL, NULL, NULL, NULL,
1753                                   UMA_ALIGN_PTR,
1754                                   UMA_ZFLAG_INTERNAL);
1755
1756         hashzone = uma_zcreate("UMA Hash",
1757             sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
1758             NULL, NULL, NULL, NULL,
1759             UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1760
1761         bucket_init();
1762
1763         booted = UMA_STARTUP;
1764
1765 #ifdef UMA_DEBUG
1766         printf("UMA startup complete.\n");
1767 #endif
1768 }
1769
1770 /* see uma.h */
1771 void
1772 uma_startup2(void)
1773 {
1774         booted = UMA_STARTUP2;
1775         bucket_enable();
1776 #ifdef UMA_DEBUG
1777         printf("UMA startup2 complete.\n");
1778 #endif
1779 }
1780
1781 /*
1782  * Initialize our callout handle
1783  *
1784  */
1785
1786 static void
1787 uma_startup3(void)
1788 {
1789 #ifdef UMA_DEBUG
1790         printf("Starting callout.\n");
1791 #endif
1792         callout_init(&uma_callout, CALLOUT_MPSAFE);
1793         callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
1794 #ifdef UMA_DEBUG
1795         printf("UMA startup3 complete.\n");
1796 #endif
1797 }
1798
1799 static uma_keg_t
1800 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
1801                 int align, u_int32_t flags)
1802 {
1803         struct uma_kctor_args args;
1804
1805         args.size = size;
1806         args.uminit = uminit;
1807         args.fini = fini;
1808         args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
1809         args.flags = flags;
1810         args.zone = zone;
1811         return (zone_alloc_item(kegs, &args, M_WAITOK));
1812 }
1813
1814 /* See uma.h */
1815 void
1816 uma_set_align(int align)
1817 {
1818
1819         if (align != UMA_ALIGN_CACHE)
1820                 uma_align_cache = align;
1821 }
1822
1823 /* See uma.h */
1824 uma_zone_t
1825 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
1826                 uma_init uminit, uma_fini fini, int align, u_int32_t flags)
1827
1828 {
1829         struct uma_zctor_args args;
1830
1831         /* This stuff is essential for the zone ctor */
1832         args.name = name;
1833         args.size = size;
1834         args.ctor = ctor;
1835         args.dtor = dtor;
1836         args.uminit = uminit;
1837         args.fini = fini;
1838         args.align = align;
1839         args.flags = flags;
1840         args.keg = NULL;
1841
1842         return (zone_alloc_item(zones, &args, M_WAITOK));
1843 }
1844
1845 /* See uma.h */
1846 uma_zone_t
1847 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
1848                     uma_init zinit, uma_fini zfini, uma_zone_t master)
1849 {
1850         struct uma_zctor_args args;
1851         uma_keg_t keg;
1852
1853         keg = zone_first_keg(master);
1854         args.name = name;
1855         args.size = keg->uk_size;
1856         args.ctor = ctor;
1857         args.dtor = dtor;
1858         args.uminit = zinit;
1859         args.fini = zfini;
1860         args.align = keg->uk_align;
1861         args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
1862         args.keg = keg;
1863
1864         /* XXX Attaches only one keg of potentially many. */
1865         return (zone_alloc_item(zones, &args, M_WAITOK));
1866 }
1867
1868 static void
1869 zone_lock_pair(uma_zone_t a, uma_zone_t b)
1870 {
1871         if (a < b) {
1872                 ZONE_LOCK(a);
1873                 mtx_lock_flags(b->uz_lock, MTX_DUPOK);
1874         } else {
1875                 ZONE_LOCK(b);
1876                 mtx_lock_flags(a->uz_lock, MTX_DUPOK);
1877         }
1878 }
1879
1880 static void
1881 zone_unlock_pair(uma_zone_t a, uma_zone_t b)
1882 {
1883
1884         ZONE_UNLOCK(a);
1885         ZONE_UNLOCK(b);
1886 }
1887
1888 int
1889 uma_zsecond_add(uma_zone_t zone, uma_zone_t master)
1890 {
1891         uma_klink_t klink;
1892         uma_klink_t kl;
1893         int error;
1894
1895         error = 0;
1896         klink = malloc(sizeof(*klink), M_TEMP, M_WAITOK | M_ZERO);
1897
1898         zone_lock_pair(zone, master);
1899         /*
1900          * zone must use vtoslab() to resolve objects and must already be
1901          * a secondary.
1902          */
1903         if ((zone->uz_flags & (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY))
1904             != (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY)) {
1905                 error = EINVAL;
1906                 goto out;
1907         }
1908         /*
1909          * The new master must also use vtoslab().
1910          */
1911         if ((zone->uz_flags & UMA_ZONE_VTOSLAB) != UMA_ZONE_VTOSLAB) {
1912                 error = EINVAL;
1913                 goto out;
1914         }
1915         /*
1916          * Both must either be refcnt, or not be refcnt.
1917          */
1918         if ((zone->uz_flags & UMA_ZONE_REFCNT) !=
1919             (master->uz_flags & UMA_ZONE_REFCNT)) {
1920                 error = EINVAL;
1921                 goto out;
1922         }
1923         /*
1924          * The underlying object must be the same size.  rsize
1925          * may be different.
1926          */
1927         if (master->uz_size != zone->uz_size) {
1928                 error = E2BIG;
1929                 goto out;
1930         }
1931         /*
1932          * Put it at the end of the list.
1933          */
1934         klink->kl_keg = zone_first_keg(master);
1935         LIST_FOREACH(kl, &zone->uz_kegs, kl_link) {
1936                 if (LIST_NEXT(kl, kl_link) == NULL) {
1937                         LIST_INSERT_AFTER(kl, klink, kl_link);
1938                         break;
1939                 }
1940         }
1941         klink = NULL;
1942         zone->uz_flags |= UMA_ZFLAG_MULTI;
1943         zone->uz_slab = zone_fetch_slab_multi;
1944
1945 out:
1946         zone_unlock_pair(zone, master);
1947         if (klink != NULL)
1948                 free(klink, M_TEMP);
1949
1950         return (error);
1951 }
1952
1953
1954 /* See uma.h */
1955 void
1956 uma_zdestroy(uma_zone_t zone)
1957 {
1958
1959         zone_free_item(zones, zone, NULL, SKIP_NONE, ZFREE_STATFREE);
1960 }
1961
1962 /* See uma.h */
1963 void *
1964 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
1965 {
1966         void *item;
1967         uma_cache_t cache;
1968         uma_bucket_t bucket;
1969         int cpu;
1970
1971         /* This is the fast path allocation */
1972 #ifdef UMA_DEBUG_ALLOC_1
1973         printf("Allocating one item from %s(%p)\n", zone->uz_name, zone);
1974 #endif
1975         CTR3(KTR_UMA, "uma_zalloc_arg thread %x zone %s flags %d", curthread,
1976             zone->uz_name, flags);
1977
1978         if (flags & M_WAITOK) {
1979                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1980                     "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
1981         }
1982
1983         /*
1984          * If possible, allocate from the per-CPU cache.  There are two
1985          * requirements for safe access to the per-CPU cache: (1) the thread
1986          * accessing the cache must not be preempted or yield during access,
1987          * and (2) the thread must not migrate CPUs without switching which
1988          * cache it accesses.  We rely on a critical section to prevent
1989          * preemption and migration.  We release the critical section in
1990          * order to acquire the zone mutex if we are unable to allocate from
1991          * the current cache; when we re-acquire the critical section, we
1992          * must detect and handle migration if it has occurred.
1993          */
1994 zalloc_restart:
1995         critical_enter();
1996         cpu = curcpu;
1997         cache = &zone->uz_cpu[cpu];
1998
1999 zalloc_start:
2000         bucket = cache->uc_allocbucket;
2001
2002         if (bucket) {
2003                 if (bucket->ub_cnt > 0) {
2004                         bucket->ub_cnt--;
2005                         item = bucket->ub_bucket[bucket->ub_cnt];
2006 #ifdef INVARIANTS
2007                         bucket->ub_bucket[bucket->ub_cnt] = NULL;
2008 #endif
2009                         KASSERT(item != NULL,
2010                             ("uma_zalloc: Bucket pointer mangled."));
2011                         cache->uc_allocs++;
2012                         critical_exit();
2013 #ifdef INVARIANTS
2014                         ZONE_LOCK(zone);
2015                         uma_dbg_alloc(zone, NULL, item);
2016                         ZONE_UNLOCK(zone);
2017 #endif
2018                         if (zone->uz_ctor != NULL) {
2019                                 if (zone->uz_ctor(item, zone->uz_size,
2020                                     udata, flags) != 0) {
2021                                         zone_free_item(zone, item, udata,
2022                                             SKIP_DTOR, ZFREE_STATFAIL |
2023                                             ZFREE_STATFREE);
2024                                         return (NULL);
2025                                 }
2026                         }
2027                         if (flags & M_ZERO)
2028                                 bzero(item, zone->uz_size);
2029                         return (item);
2030                 } else if (cache->uc_freebucket) {
2031                         /*
2032                          * We have run out of items in our allocbucket.
2033                          * See if we can switch with our free bucket.
2034                          */
2035                         if (cache->uc_freebucket->ub_cnt > 0) {
2036 #ifdef UMA_DEBUG_ALLOC
2037                                 printf("uma_zalloc: Swapping empty with"
2038                                     " alloc.\n");
2039 #endif
2040                                 bucket = cache->uc_freebucket;
2041                                 cache->uc_freebucket = cache->uc_allocbucket;
2042                                 cache->uc_allocbucket = bucket;
2043
2044                                 goto zalloc_start;
2045                         }
2046                 }
2047         }
2048         /*
2049          * Attempt to retrieve the item from the per-CPU cache has failed, so
2050          * we must go back to the zone.  This requires the zone lock, so we
2051          * must drop the critical section, then re-acquire it when we go back
2052          * to the cache.  Since the critical section is released, we may be
2053          * preempted or migrate.  As such, make sure not to maintain any
2054          * thread-local state specific to the cache from prior to releasing
2055          * the critical section.
2056          */
2057         critical_exit();
2058         ZONE_LOCK(zone);
2059         critical_enter();
2060         cpu = curcpu;
2061         cache = &zone->uz_cpu[cpu];
2062         bucket = cache->uc_allocbucket;
2063         if (bucket != NULL) {
2064                 if (bucket->ub_cnt > 0) {
2065                         ZONE_UNLOCK(zone);
2066                         goto zalloc_start;
2067                 }
2068                 bucket = cache->uc_freebucket;
2069                 if (bucket != NULL && bucket->ub_cnt > 0) {
2070                         ZONE_UNLOCK(zone);
2071                         goto zalloc_start;
2072                 }
2073         }
2074
2075         /* Since we have locked the zone we may as well send back our stats */
2076         zone->uz_allocs += cache->uc_allocs;
2077         cache->uc_allocs = 0;
2078         zone->uz_frees += cache->uc_frees;
2079         cache->uc_frees = 0;
2080
2081         /* Our old one is now a free bucket */
2082         if (cache->uc_allocbucket) {
2083                 KASSERT(cache->uc_allocbucket->ub_cnt == 0,
2084                     ("uma_zalloc_arg: Freeing a non free bucket."));
2085                 LIST_INSERT_HEAD(&zone->uz_free_bucket,
2086                     cache->uc_allocbucket, ub_link);
2087                 cache->uc_allocbucket = NULL;
2088         }
2089
2090         /* Check the free list for a new alloc bucket */
2091         if ((bucket = LIST_FIRST(&zone->uz_full_bucket)) != NULL) {
2092                 KASSERT(bucket->ub_cnt != 0,
2093                     ("uma_zalloc_arg: Returning an empty bucket."));
2094
2095                 LIST_REMOVE(bucket, ub_link);
2096                 cache->uc_allocbucket = bucket;
2097                 ZONE_UNLOCK(zone);
2098                 goto zalloc_start;
2099         }
2100         /* We are no longer associated with this CPU. */
2101         critical_exit();
2102
2103         /* Bump up our uz_count so we get here less */
2104         if (zone->uz_count < BUCKET_MAX)
2105                 zone->uz_count++;
2106
2107         /*
2108          * Now lets just fill a bucket and put it on the free list.  If that
2109          * works we'll restart the allocation from the begining.
2110          */
2111         if (zone_alloc_bucket(zone, flags)) {
2112                 ZONE_UNLOCK(zone);
2113                 goto zalloc_restart;
2114         }
2115         ZONE_UNLOCK(zone);
2116         /*
2117          * We may not be able to get a bucket so return an actual item.
2118          */
2119 #ifdef UMA_DEBUG
2120         printf("uma_zalloc_arg: Bucketzone returned NULL\n");
2121 #endif
2122
2123         item = zone_alloc_item(zone, udata, flags);
2124         return (item);
2125 }
2126
2127 static uma_slab_t
2128 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int flags)
2129 {
2130         uma_slab_t slab;
2131
2132         mtx_assert(&keg->uk_lock, MA_OWNED);
2133         slab = NULL;
2134
2135         for (;;) {
2136                 /*
2137                  * Find a slab with some space.  Prefer slabs that are partially
2138                  * used over those that are totally full.  This helps to reduce
2139                  * fragmentation.
2140                  */
2141                 if (keg->uk_free != 0) {
2142                         if (!LIST_EMPTY(&keg->uk_part_slab)) {
2143                                 slab = LIST_FIRST(&keg->uk_part_slab);
2144                         } else {
2145                                 slab = LIST_FIRST(&keg->uk_free_slab);
2146                                 LIST_REMOVE(slab, us_link);
2147                                 LIST_INSERT_HEAD(&keg->uk_part_slab, slab,
2148                                     us_link);
2149                         }
2150                         MPASS(slab->us_keg == keg);
2151                         return (slab);
2152                 }
2153
2154                 /*
2155                  * M_NOVM means don't ask at all!
2156                  */
2157                 if (flags & M_NOVM)
2158                         break;
2159
2160                 if (keg->uk_maxpages && keg->uk_pages >= keg->uk_maxpages) {
2161                         keg->uk_flags |= UMA_ZFLAG_FULL;
2162                         /*
2163                          * If this is not a multi-zone, set the FULL bit.
2164                          * Otherwise slab_multi() takes care of it.
2165                          */
2166                         if ((zone->uz_flags & UMA_ZFLAG_MULTI) == 0)
2167                                 zone->uz_flags |= UMA_ZFLAG_FULL;
2168                         if (flags & M_NOWAIT)
2169                                 break;
2170                         zone->uz_sleeps++;
2171                         msleep(keg, &keg->uk_lock, PVM, "keglimit", 0);
2172                         continue;
2173                 }
2174                 keg->uk_recurse++;
2175                 slab = keg_alloc_slab(keg, zone, flags);
2176                 keg->uk_recurse--;
2177                 /*
2178                  * If we got a slab here it's safe to mark it partially used
2179                  * and return.  We assume that the caller is going to remove
2180                  * at least one item.
2181                  */
2182                 if (slab) {
2183                         MPASS(slab->us_keg == keg);
2184                         LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
2185                         return (slab);
2186                 }
2187                 /*
2188                  * We might not have been able to get a slab but another cpu
2189                  * could have while we were unlocked.  Check again before we
2190                  * fail.
2191                  */
2192                 flags |= M_NOVM;
2193         }
2194         return (slab);
2195 }
2196
2197 static inline void
2198 zone_relock(uma_zone_t zone, uma_keg_t keg)
2199 {
2200         if (zone->uz_lock != &keg->uk_lock) {
2201                 KEG_UNLOCK(keg);
2202                 ZONE_LOCK(zone);
2203         }
2204 }
2205
2206 static inline void
2207 keg_relock(uma_keg_t keg, uma_zone_t zone)
2208 {
2209         if (zone->uz_lock != &keg->uk_lock) {
2210                 ZONE_UNLOCK(zone);
2211                 KEG_LOCK(keg);
2212         }
2213 }
2214
2215 static uma_slab_t
2216 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int flags)
2217 {
2218         uma_slab_t slab;
2219
2220         if (keg == NULL)
2221                 keg = zone_first_keg(zone);
2222         /*
2223          * This is to prevent us from recursively trying to allocate
2224          * buckets.  The problem is that if an allocation forces us to
2225          * grab a new bucket we will call page_alloc, which will go off
2226          * and cause the vm to allocate vm_map_entries.  If we need new
2227          * buckets there too we will recurse in kmem_alloc and bad
2228          * things happen.  So instead we return a NULL bucket, and make
2229          * the code that allocates buckets smart enough to deal with it
2230          */
2231         if (keg->uk_flags & UMA_ZFLAG_BUCKET && keg->uk_recurse != 0)
2232                 return (NULL);
2233
2234         for (;;) {
2235                 slab = keg_fetch_slab(keg, zone, flags);
2236                 if (slab)
2237                         return (slab);
2238                 if (flags & (M_NOWAIT | M_NOVM))
2239                         break;
2240         }
2241         return (NULL);
2242 }
2243
2244 /*
2245  * uma_zone_fetch_slab_multi:  Fetches a slab from one available keg.  Returns
2246  * with the keg locked.  Caller must call zone_relock() afterwards if the
2247  * zone lock is required.  On NULL the zone lock is held.
2248  *
2249  * The last pointer is used to seed the search.  It is not required.
2250  */
2251 static uma_slab_t
2252 zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int rflags)
2253 {
2254         uma_klink_t klink;
2255         uma_slab_t slab;
2256         uma_keg_t keg;
2257         int flags;
2258         int empty;
2259         int full;
2260
2261         /*
2262          * Don't wait on the first pass.  This will skip limit tests
2263          * as well.  We don't want to block if we can find a provider
2264          * without blocking.
2265          */
2266         flags = (rflags & ~M_WAITOK) | M_NOWAIT;
2267         /*
2268          * Use the last slab allocated as a hint for where to start
2269          * the search.
2270          */
2271         if (last) {
2272                 slab = keg_fetch_slab(last, zone, flags);
2273                 if (slab)
2274                         return (slab);
2275                 zone_relock(zone, last);
2276                 last = NULL;
2277         }
2278         /*
2279          * Loop until we have a slab incase of transient failures
2280          * while M_WAITOK is specified.  I'm not sure this is 100%
2281          * required but we've done it for so long now.
2282          */
2283         for (;;) {
2284                 empty = 0;
2285                 full = 0;
2286                 /*
2287                  * Search the available kegs for slabs.  Be careful to hold the
2288                  * correct lock while calling into the keg layer.
2289                  */
2290                 LIST_FOREACH(klink, &zone->uz_kegs, kl_link) {
2291                         keg = klink->kl_keg;
2292                         keg_relock(keg, zone);
2293                         if ((keg->uk_flags & UMA_ZFLAG_FULL) == 0) {
2294                                 slab = keg_fetch_slab(keg, zone, flags);
2295                                 if (slab)
2296                                         return (slab);
2297                         }
2298                         if (keg->uk_flags & UMA_ZFLAG_FULL)
2299                                 full++;
2300                         else
2301                                 empty++;
2302                         zone_relock(zone, keg);
2303                 }
2304                 if (rflags & (M_NOWAIT | M_NOVM))
2305                         break;
2306                 flags = rflags;
2307                 /*
2308                  * All kegs are full.  XXX We can't atomically check all kegs
2309                  * and sleep so just sleep for a short period and retry.
2310                  */
2311                 if (full && !empty) {
2312                         zone->uz_flags |= UMA_ZFLAG_FULL;
2313                         zone->uz_sleeps++;
2314                         msleep(zone, zone->uz_lock, PVM, "zonelimit", hz/100);
2315                         zone->uz_flags &= ~UMA_ZFLAG_FULL;
2316                         continue;
2317                 }
2318         }
2319         return (NULL);
2320 }
2321
2322 static void *
2323 slab_alloc_item(uma_zone_t zone, uma_slab_t slab)
2324 {
2325         uma_keg_t keg;
2326         uma_slabrefcnt_t slabref;
2327         void *item;
2328         u_int8_t freei;
2329
2330         keg = slab->us_keg;
2331         mtx_assert(&keg->uk_lock, MA_OWNED);
2332
2333         freei = slab->us_firstfree;
2334         if (keg->uk_flags & UMA_ZONE_REFCNT) {
2335                 slabref = (uma_slabrefcnt_t)slab;
2336                 slab->us_firstfree = slabref->us_freelist[freei].us_item;
2337         } else {
2338                 slab->us_firstfree = slab->us_freelist[freei].us_item;
2339         }
2340         item = slab->us_data + (keg->uk_rsize * freei);
2341
2342         slab->us_freecount--;
2343         keg->uk_free--;
2344 #ifdef INVARIANTS
2345         uma_dbg_alloc(zone, slab, item);
2346 #endif
2347         /* Move this slab to the full list */
2348         if (slab->us_freecount == 0) {
2349                 LIST_REMOVE(slab, us_link);
2350                 LIST_INSERT_HEAD(&keg->uk_full_slab, slab, us_link);
2351         }
2352
2353         return (item);
2354 }
2355
2356 static int
2357 zone_alloc_bucket(uma_zone_t zone, int flags)
2358 {
2359         uma_bucket_t bucket;
2360         uma_slab_t slab;
2361         uma_keg_t keg;
2362         int16_t saved;
2363         int max, origflags = flags;
2364
2365         /*
2366          * Try this zone's free list first so we don't allocate extra buckets.
2367          */
2368         if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
2369                 KASSERT(bucket->ub_cnt == 0,
2370                     ("zone_alloc_bucket: Bucket on free list is not empty."));
2371                 LIST_REMOVE(bucket, ub_link);
2372         } else {
2373                 int bflags;
2374
2375                 bflags = (flags & ~M_ZERO);
2376                 if (zone->uz_flags & UMA_ZFLAG_CACHEONLY)
2377                         bflags |= M_NOVM;
2378
2379                 ZONE_UNLOCK(zone);
2380                 bucket = bucket_alloc(zone->uz_count, bflags);
2381                 ZONE_LOCK(zone);
2382         }
2383
2384         if (bucket == NULL) {
2385                 return (0);
2386         }
2387
2388 #ifdef SMP
2389         /*
2390          * This code is here to limit the number of simultaneous bucket fills
2391          * for any given zone to the number of per cpu caches in this zone. This
2392          * is done so that we don't allocate more memory than we really need.
2393          */
2394         if (zone->uz_fills >= mp_ncpus)
2395                 goto done;
2396
2397 #endif
2398         zone->uz_fills++;
2399
2400         max = MIN(bucket->ub_entries, zone->uz_count);
2401         /* Try to keep the buckets totally full */
2402         saved = bucket->ub_cnt;
2403         slab = NULL;
2404         keg = NULL;
2405         while (bucket->ub_cnt < max &&
2406             (slab = zone->uz_slab(zone, keg, flags)) != NULL) {
2407                 keg = slab->us_keg;
2408                 while (slab->us_freecount && bucket->ub_cnt < max) {
2409                         bucket->ub_bucket[bucket->ub_cnt++] =
2410                             slab_alloc_item(zone, slab);
2411                 }
2412
2413                 /* Don't block on the next fill */
2414                 flags |= M_NOWAIT;
2415         }
2416         if (slab)
2417                 zone_relock(zone, keg);
2418
2419         /*
2420          * We unlock here because we need to call the zone's init.
2421          * It should be safe to unlock because the slab dealt with
2422          * above is already on the appropriate list within the keg
2423          * and the bucket we filled is not yet on any list, so we
2424          * own it.
2425          */
2426         if (zone->uz_init != NULL) {
2427                 int i;
2428
2429                 ZONE_UNLOCK(zone);
2430                 for (i = saved; i < bucket->ub_cnt; i++)
2431                         if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2432                             origflags) != 0)
2433                                 break;
2434                 /*
2435                  * If we couldn't initialize the whole bucket, put the
2436                  * rest back onto the freelist.
2437                  */
2438                 if (i != bucket->ub_cnt) {
2439                         int j;
2440
2441                         for (j = i; j < bucket->ub_cnt; j++) {
2442                                 zone_free_item(zone, bucket->ub_bucket[j],
2443                                     NULL, SKIP_FINI, 0);
2444 #ifdef INVARIANTS
2445                                 bucket->ub_bucket[j] = NULL;
2446 #endif
2447                         }
2448                         bucket->ub_cnt = i;
2449                 }
2450                 ZONE_LOCK(zone);
2451         }
2452
2453         zone->uz_fills--;
2454         if (bucket->ub_cnt != 0) {
2455                 LIST_INSERT_HEAD(&zone->uz_full_bucket,
2456                     bucket, ub_link);
2457                 return (1);
2458         }
2459 #ifdef SMP
2460 done:
2461 #endif
2462         bucket_free(bucket);
2463
2464         return (0);
2465 }
2466 /*
2467  * Allocates an item for an internal zone
2468  *
2469  * Arguments
2470  *      zone   The zone to alloc for.
2471  *      udata  The data to be passed to the constructor.
2472  *      flags  M_WAITOK, M_NOWAIT, M_ZERO.
2473  *
2474  * Returns
2475  *      NULL if there is no memory and M_NOWAIT is set
2476  *      An item if successful
2477  */
2478
2479 static void *
2480 zone_alloc_item(uma_zone_t zone, void *udata, int flags)
2481 {
2482         uma_slab_t slab;
2483         void *item;
2484
2485         item = NULL;
2486
2487 #ifdef UMA_DEBUG_ALLOC
2488         printf("INTERNAL: Allocating one item from %s(%p)\n", zone->uz_name, zone);
2489 #endif
2490         ZONE_LOCK(zone);
2491
2492         slab = zone->uz_slab(zone, NULL, flags);
2493         if (slab == NULL) {
2494                 zone->uz_fails++;
2495                 ZONE_UNLOCK(zone);
2496                 return (NULL);
2497         }
2498
2499         item = slab_alloc_item(zone, slab);
2500
2501         zone_relock(zone, slab->us_keg);
2502         zone->uz_allocs++;
2503         ZONE_UNLOCK(zone);
2504
2505         /*
2506          * We have to call both the zone's init (not the keg's init)
2507          * and the zone's ctor.  This is because the item is going from
2508          * a keg slab directly to the user, and the user is expecting it
2509          * to be both zone-init'd as well as zone-ctor'd.
2510          */
2511         if (zone->uz_init != NULL) {
2512                 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
2513                         zone_free_item(zone, item, udata, SKIP_FINI,
2514                             ZFREE_STATFAIL | ZFREE_STATFREE);
2515                         return (NULL);
2516                 }
2517         }
2518         if (zone->uz_ctor != NULL) {
2519                 if (zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2520                         zone_free_item(zone, item, udata, SKIP_DTOR,
2521                             ZFREE_STATFAIL | ZFREE_STATFREE);
2522                         return (NULL);
2523                 }
2524         }
2525         if (flags & M_ZERO)
2526                 bzero(item, zone->uz_size);
2527
2528         return (item);
2529 }
2530
2531 /* See uma.h */
2532 void
2533 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
2534 {
2535         uma_cache_t cache;
2536         uma_bucket_t bucket;
2537         int bflags;
2538         int cpu;
2539
2540 #ifdef UMA_DEBUG_ALLOC_1
2541         printf("Freeing item %p to %s(%p)\n", item, zone->uz_name, zone);
2542 #endif
2543         CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
2544             zone->uz_name);
2545
2546         /* uma_zfree(..., NULL) does nothing, to match free(9). */
2547         if (item == NULL)
2548                 return;
2549
2550         if (zone->uz_dtor)
2551                 zone->uz_dtor(item, zone->uz_size, udata);
2552
2553 #ifdef INVARIANTS
2554         ZONE_LOCK(zone);
2555         if (zone->uz_flags & UMA_ZONE_MALLOC)
2556                 uma_dbg_free(zone, udata, item);
2557         else
2558                 uma_dbg_free(zone, NULL, item);
2559         ZONE_UNLOCK(zone);
2560 #endif
2561         /*
2562          * The race here is acceptable.  If we miss it we'll just have to wait
2563          * a little longer for the limits to be reset.
2564          */
2565         if (zone->uz_flags & UMA_ZFLAG_FULL)
2566                 goto zfree_internal;
2567
2568         /*
2569          * If possible, free to the per-CPU cache.  There are two
2570          * requirements for safe access to the per-CPU cache: (1) the thread
2571          * accessing the cache must not be preempted or yield during access,
2572          * and (2) the thread must not migrate CPUs without switching which
2573          * cache it accesses.  We rely on a critical section to prevent
2574          * preemption and migration.  We release the critical section in
2575          * order to acquire the zone mutex if we are unable to free to the
2576          * current cache; when we re-acquire the critical section, we must
2577          * detect and handle migration if it has occurred.
2578          */
2579 zfree_restart:
2580         critical_enter();
2581         cpu = curcpu;
2582         cache = &zone->uz_cpu[cpu];
2583
2584 zfree_start:
2585         bucket = cache->uc_freebucket;
2586
2587         if (bucket) {
2588                 /*
2589                  * Do we have room in our bucket? It is OK for this uz count
2590                  * check to be slightly out of sync.
2591                  */
2592
2593                 if (bucket->ub_cnt < bucket->ub_entries) {
2594                         KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
2595                             ("uma_zfree: Freeing to non free bucket index."));
2596                         bucket->ub_bucket[bucket->ub_cnt] = item;
2597                         bucket->ub_cnt++;
2598                         cache->uc_frees++;
2599                         critical_exit();
2600                         return;
2601                 } else if (cache->uc_allocbucket) {
2602 #ifdef UMA_DEBUG_ALLOC
2603                         printf("uma_zfree: Swapping buckets.\n");
2604 #endif
2605                         /*
2606                          * We have run out of space in our freebucket.
2607                          * See if we can switch with our alloc bucket.
2608                          */
2609                         if (cache->uc_allocbucket->ub_cnt <
2610                             cache->uc_freebucket->ub_cnt) {
2611                                 bucket = cache->uc_freebucket;
2612                                 cache->uc_freebucket = cache->uc_allocbucket;
2613                                 cache->uc_allocbucket = bucket;
2614                                 goto zfree_start;
2615                         }
2616                 }
2617         }
2618         /*
2619          * We can get here for two reasons:
2620          *
2621          * 1) The buckets are NULL
2622          * 2) The alloc and free buckets are both somewhat full.
2623          *
2624          * We must go back the zone, which requires acquiring the zone lock,
2625          * which in turn means we must release and re-acquire the critical
2626          * section.  Since the critical section is released, we may be
2627          * preempted or migrate.  As such, make sure not to maintain any
2628          * thread-local state specific to the cache from prior to releasing
2629          * the critical section.
2630          */
2631         critical_exit();
2632         ZONE_LOCK(zone);
2633         critical_enter();
2634         cpu = curcpu;
2635         cache = &zone->uz_cpu[cpu];
2636         if (cache->uc_freebucket != NULL) {
2637                 if (cache->uc_freebucket->ub_cnt <
2638                     cache->uc_freebucket->ub_entries) {
2639                         ZONE_UNLOCK(zone);
2640                         goto zfree_start;
2641                 }
2642                 if (cache->uc_allocbucket != NULL &&
2643                     (cache->uc_allocbucket->ub_cnt <
2644                     cache->uc_freebucket->ub_cnt)) {
2645                         ZONE_UNLOCK(zone);
2646                         goto zfree_start;
2647                 }
2648         }
2649
2650         /* Since we have locked the zone we may as well send back our stats */
2651         zone->uz_allocs += cache->uc_allocs;
2652         cache->uc_allocs = 0;
2653         zone->uz_frees += cache->uc_frees;
2654         cache->uc_frees = 0;
2655
2656         bucket = cache->uc_freebucket;
2657         cache->uc_freebucket = NULL;
2658
2659         /* Can we throw this on the zone full list? */
2660         if (bucket != NULL) {
2661 #ifdef UMA_DEBUG_ALLOC
2662                 printf("uma_zfree: Putting old bucket on the free list.\n");
2663 #endif
2664                 /* ub_cnt is pointing to the last free item */
2665                 KASSERT(bucket->ub_cnt != 0,
2666                     ("uma_zfree: Attempting to insert an empty bucket onto the full list.\n"));
2667                 LIST_INSERT_HEAD(&zone->uz_full_bucket,
2668                     bucket, ub_link);
2669         }
2670         if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
2671                 LIST_REMOVE(bucket, ub_link);
2672                 ZONE_UNLOCK(zone);
2673                 cache->uc_freebucket = bucket;
2674                 goto zfree_start;
2675         }
2676         /* We are no longer associated with this CPU. */
2677         critical_exit();
2678
2679         /* And the zone.. */
2680         ZONE_UNLOCK(zone);
2681
2682 #ifdef UMA_DEBUG_ALLOC
2683         printf("uma_zfree: Allocating new free bucket.\n");
2684 #endif
2685         bflags = M_NOWAIT;
2686
2687         if (zone->uz_flags & UMA_ZFLAG_CACHEONLY)
2688                 bflags |= M_NOVM;
2689         bucket = bucket_alloc(zone->uz_count, bflags);
2690         if (bucket) {
2691                 ZONE_LOCK(zone);
2692                 LIST_INSERT_HEAD(&zone->uz_free_bucket,
2693                     bucket, ub_link);
2694                 ZONE_UNLOCK(zone);
2695                 goto zfree_restart;
2696         }
2697
2698         /*
2699          * If nothing else caught this, we'll just do an internal free.
2700          */
2701 zfree_internal:
2702         zone_free_item(zone, item, udata, SKIP_DTOR, ZFREE_STATFREE);
2703
2704         return;
2705 }
2706
2707 /*
2708  * Frees an item to an INTERNAL zone or allocates a free bucket
2709  *
2710  * Arguments:
2711  *      zone   The zone to free to
2712  *      item   The item we're freeing
2713  *      udata  User supplied data for the dtor
2714  *      skip   Skip dtors and finis
2715  */
2716 static void
2717 zone_free_item(uma_zone_t zone, void *item, void *udata,
2718     enum zfreeskip skip, int flags)
2719 {
2720         uma_slab_t slab;
2721         uma_slabrefcnt_t slabref;
2722         uma_keg_t keg;
2723         u_int8_t *mem;
2724         u_int8_t freei;
2725         int clearfull;
2726
2727         if (skip < SKIP_DTOR && zone->uz_dtor)
2728                 zone->uz_dtor(item, zone->uz_size, udata);
2729
2730         if (skip < SKIP_FINI && zone->uz_fini)
2731                 zone->uz_fini(item, zone->uz_size);
2732
2733         ZONE_LOCK(zone);
2734
2735         if (flags & ZFREE_STATFAIL)
2736                 zone->uz_fails++;
2737         if (flags & ZFREE_STATFREE)
2738                 zone->uz_frees++;
2739
2740         if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
2741                 mem = (u_int8_t *)((unsigned long)item & (~UMA_SLAB_MASK));
2742                 keg = zone_first_keg(zone); /* Must only be one. */
2743                 if (zone->uz_flags & UMA_ZONE_HASH) {
2744                         slab = hash_sfind(&keg->uk_hash, mem);
2745                 } else {
2746                         mem += keg->uk_pgoff;
2747                         slab = (uma_slab_t)mem;
2748                 }
2749         } else {
2750                 /* This prevents redundant lookups via free(). */
2751                 if ((zone->uz_flags & UMA_ZONE_MALLOC) && udata != NULL)
2752                         slab = (uma_slab_t)udata;
2753                 else
2754                         slab = vtoslab((vm_offset_t)item);
2755                 keg = slab->us_keg;
2756                 keg_relock(keg, zone);
2757         }
2758         MPASS(keg == slab->us_keg);
2759
2760         /* Do we need to remove from any lists? */
2761         if (slab->us_freecount+1 == keg->uk_ipers) {
2762                 LIST_REMOVE(slab, us_link);
2763                 LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
2764         } else if (slab->us_freecount == 0) {
2765                 LIST_REMOVE(slab, us_link);
2766                 LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
2767         }
2768
2769         /* Slab management stuff */
2770         freei = ((unsigned long)item - (unsigned long)slab->us_data)
2771                 / keg->uk_rsize;
2772
2773 #ifdef INVARIANTS
2774         if (!skip)
2775                 uma_dbg_free(zone, slab, item);
2776 #endif
2777
2778         if (keg->uk_flags & UMA_ZONE_REFCNT) {
2779                 slabref = (uma_slabrefcnt_t)slab;
2780                 slabref->us_freelist[freei].us_item = slab->us_firstfree;
2781         } else {
2782                 slab->us_freelist[freei].us_item = slab->us_firstfree;
2783         }
2784         slab->us_firstfree = freei;
2785         slab->us_freecount++;
2786
2787         /* Zone statistics */
2788         keg->uk_free++;
2789
2790         clearfull = 0;
2791         if (keg->uk_flags & UMA_ZFLAG_FULL) {
2792                 if (keg->uk_pages < keg->uk_maxpages) {
2793                         keg->uk_flags &= ~UMA_ZFLAG_FULL;
2794                         clearfull = 1;
2795                 }
2796
2797                 /* 
2798                  * We can handle one more allocation. Since we're clearing ZFLAG_FULL,
2799                  * wake up all procs blocked on pages. This should be uncommon, so 
2800                  * keeping this simple for now (rather than adding count of blocked 
2801                  * threads etc).
2802                  */
2803                 wakeup(keg);
2804         }
2805         if (clearfull) {
2806                 zone_relock(zone, keg);
2807                 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2808                 wakeup(zone);
2809                 ZONE_UNLOCK(zone);
2810         } else
2811                 KEG_UNLOCK(keg);
2812 }
2813
2814 /* See uma.h */
2815 int
2816 uma_zone_set_max(uma_zone_t zone, int nitems)
2817 {
2818         uma_keg_t keg;
2819
2820         ZONE_LOCK(zone);
2821         keg = zone_first_keg(zone);
2822         keg->uk_maxpages = (nitems / keg->uk_ipers) * keg->uk_ppera;
2823         if (keg->uk_maxpages * keg->uk_ipers < nitems)
2824                 keg->uk_maxpages += keg->uk_ppera;
2825         nitems = keg->uk_maxpages * keg->uk_ipers;
2826         ZONE_UNLOCK(zone);
2827
2828         return (nitems);
2829 }
2830
2831 /* See uma.h */
2832 int
2833 uma_zone_get_max(uma_zone_t zone)
2834 {
2835         int nitems;
2836         uma_keg_t keg;
2837
2838         ZONE_LOCK(zone);
2839         keg = zone_first_keg(zone);
2840         nitems = keg->uk_maxpages * keg->uk_ipers;
2841         ZONE_UNLOCK(zone);
2842
2843         return (nitems);
2844 }
2845
2846 /* See uma.h */
2847 int
2848 uma_zone_get_cur(uma_zone_t zone)
2849 {
2850         int64_t nitems;
2851         u_int i;
2852
2853         ZONE_LOCK(zone);
2854         nitems = zone->uz_allocs - zone->uz_frees;
2855         CPU_FOREACH(i) {
2856                 /*
2857                  * See the comment in sysctl_vm_zone_stats() regarding the
2858                  * safety of accessing the per-cpu caches. With the zone lock
2859                  * held, it is safe, but can potentially result in stale data.
2860                  */
2861                 nitems += zone->uz_cpu[i].uc_allocs -
2862                     zone->uz_cpu[i].uc_frees;
2863         }
2864         ZONE_UNLOCK(zone);
2865
2866         return (nitems < 0 ? 0 : nitems);
2867 }
2868
2869 /* See uma.h */
2870 void
2871 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
2872 {
2873         uma_keg_t keg;
2874
2875         ZONE_LOCK(zone);
2876         keg = zone_first_keg(zone);
2877         KASSERT(keg->uk_pages == 0,
2878             ("uma_zone_set_init on non-empty keg"));
2879         keg->uk_init = uminit;
2880         ZONE_UNLOCK(zone);
2881 }
2882
2883 /* See uma.h */
2884 void
2885 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
2886 {
2887         uma_keg_t keg;
2888
2889         ZONE_LOCK(zone);
2890         keg = zone_first_keg(zone);
2891         KASSERT(keg->uk_pages == 0,
2892             ("uma_zone_set_fini on non-empty keg"));
2893         keg->uk_fini = fini;
2894         ZONE_UNLOCK(zone);
2895 }
2896
2897 /* See uma.h */
2898 void
2899 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
2900 {
2901         ZONE_LOCK(zone);
2902         KASSERT(zone_first_keg(zone)->uk_pages == 0,
2903             ("uma_zone_set_zinit on non-empty keg"));
2904         zone->uz_init = zinit;
2905         ZONE_UNLOCK(zone);
2906 }
2907
2908 /* See uma.h */
2909 void
2910 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
2911 {
2912         ZONE_LOCK(zone);
2913         KASSERT(zone_first_keg(zone)->uk_pages == 0,
2914             ("uma_zone_set_zfini on non-empty keg"));
2915         zone->uz_fini = zfini;
2916         ZONE_UNLOCK(zone);
2917 }
2918
2919 /* See uma.h */
2920 /* XXX uk_freef is not actually used with the zone locked */
2921 void
2922 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
2923 {
2924
2925         ZONE_LOCK(zone);
2926         zone_first_keg(zone)->uk_freef = freef;
2927         ZONE_UNLOCK(zone);
2928 }
2929
2930 /* See uma.h */
2931 /* XXX uk_allocf is not actually used with the zone locked */
2932 void
2933 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
2934 {
2935         uma_keg_t keg;
2936
2937         ZONE_LOCK(zone);
2938         keg = zone_first_keg(zone);
2939         keg->uk_flags |= UMA_ZFLAG_PRIVALLOC;
2940         keg->uk_allocf = allocf;
2941         ZONE_UNLOCK(zone);
2942 }
2943
2944 /* See uma.h */
2945 int
2946 uma_zone_set_obj(uma_zone_t zone, struct vm_object *obj, int count)
2947 {
2948         uma_keg_t keg;
2949         vm_offset_t kva;
2950         int pages;
2951
2952         keg = zone_first_keg(zone);
2953         pages = count / keg->uk_ipers;
2954
2955         if (pages * keg->uk_ipers < count)
2956                 pages++;
2957
2958         kva = kmem_alloc_nofault(kernel_map, pages * UMA_SLAB_SIZE);
2959
2960         if (kva == 0)
2961                 return (0);
2962         if (obj == NULL)
2963                 obj = vm_object_allocate(OBJT_PHYS, pages);
2964         else {
2965                 VM_OBJECT_LOCK_INIT(obj, "uma object");
2966                 _vm_object_allocate(OBJT_PHYS, pages, obj);
2967         }
2968         ZONE_LOCK(zone);
2969         keg->uk_kva = kva;
2970         keg->uk_obj = obj;
2971         keg->uk_maxpages = pages;
2972         keg->uk_allocf = obj_alloc;
2973         keg->uk_flags |= UMA_ZONE_NOFREE | UMA_ZFLAG_PRIVALLOC;
2974         ZONE_UNLOCK(zone);
2975         return (1);
2976 }
2977
2978 /* See uma.h */
2979 void
2980 uma_prealloc(uma_zone_t zone, int items)
2981 {
2982         int slabs;
2983         uma_slab_t slab;
2984         uma_keg_t keg;
2985
2986         keg = zone_first_keg(zone);
2987         ZONE_LOCK(zone);
2988         slabs = items / keg->uk_ipers;
2989         if (slabs * keg->uk_ipers < items)
2990                 slabs++;
2991         while (slabs > 0) {
2992                 slab = keg_alloc_slab(keg, zone, M_WAITOK);
2993                 if (slab == NULL)
2994                         break;
2995                 MPASS(slab->us_keg == keg);
2996                 LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
2997                 slabs--;
2998         }
2999         ZONE_UNLOCK(zone);
3000 }
3001
3002 /* See uma.h */
3003 u_int32_t *
3004 uma_find_refcnt(uma_zone_t zone, void *item)
3005 {
3006         uma_slabrefcnt_t slabref;
3007         uma_keg_t keg;
3008         u_int32_t *refcnt;
3009         int idx;
3010
3011         slabref = (uma_slabrefcnt_t)vtoslab((vm_offset_t)item &
3012             (~UMA_SLAB_MASK));
3013         keg = slabref->us_keg;
3014         KASSERT(slabref != NULL && slabref->us_keg->uk_flags & UMA_ZONE_REFCNT,
3015             ("uma_find_refcnt(): zone possibly not UMA_ZONE_REFCNT"));
3016         idx = ((unsigned long)item - (unsigned long)slabref->us_data)
3017             / keg->uk_rsize;
3018         refcnt = &slabref->us_freelist[idx].us_refcnt;
3019         return refcnt;
3020 }
3021
3022 /* See uma.h */
3023 void
3024 uma_reclaim(void)
3025 {
3026 #ifdef UMA_DEBUG
3027         printf("UMA: vm asked us to release pages!\n");
3028 #endif
3029         bucket_enable();
3030         zone_foreach(zone_drain);
3031         /*
3032          * Some slabs may have been freed but this zone will be visited early
3033          * we visit again so that we can free pages that are empty once other
3034          * zones are drained.  We have to do the same for buckets.
3035          */
3036         zone_drain(slabzone);
3037         zone_drain(slabrefzone);
3038         bucket_zone_drain();
3039 }
3040
3041 /* See uma.h */
3042 int
3043 uma_zone_exhausted(uma_zone_t zone)
3044 {
3045         int full;
3046
3047         ZONE_LOCK(zone);
3048         full = (zone->uz_flags & UMA_ZFLAG_FULL);
3049         ZONE_UNLOCK(zone);
3050         return (full);  
3051 }
3052
3053 int
3054 uma_zone_exhausted_nolock(uma_zone_t zone)
3055 {
3056         return (zone->uz_flags & UMA_ZFLAG_FULL);
3057 }
3058
3059 void *
3060 uma_large_malloc(int size, int wait)
3061 {
3062         void *mem;
3063         uma_slab_t slab;
3064         u_int8_t flags;
3065
3066         slab = zone_alloc_item(slabzone, NULL, wait);
3067         if (slab == NULL)
3068                 return (NULL);
3069         mem = page_alloc(NULL, size, &flags, wait);
3070         if (mem) {
3071                 vsetslab((vm_offset_t)mem, slab);
3072                 slab->us_data = mem;
3073                 slab->us_flags = flags | UMA_SLAB_MALLOC;
3074                 slab->us_size = size;
3075         } else {
3076                 zone_free_item(slabzone, slab, NULL, SKIP_NONE,
3077                     ZFREE_STATFAIL | ZFREE_STATFREE);
3078         }
3079
3080         return (mem);
3081 }
3082
3083 void
3084 uma_large_free(uma_slab_t slab)
3085 {
3086         vsetobj((vm_offset_t)slab->us_data, kmem_object);
3087         page_free(slab->us_data, slab->us_size, slab->us_flags);
3088         zone_free_item(slabzone, slab, NULL, SKIP_NONE, ZFREE_STATFREE);
3089 }
3090
3091 void
3092 uma_print_stats(void)
3093 {
3094         zone_foreach(uma_print_zone);
3095 }
3096
3097 static void
3098 slab_print(uma_slab_t slab)
3099 {
3100         printf("slab: keg %p, data %p, freecount %d, firstfree %d\n",
3101                 slab->us_keg, slab->us_data, slab->us_freecount,
3102                 slab->us_firstfree);
3103 }
3104
3105 static void
3106 cache_print(uma_cache_t cache)
3107 {
3108         printf("alloc: %p(%d), free: %p(%d)\n",
3109                 cache->uc_allocbucket,
3110                 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3111                 cache->uc_freebucket,
3112                 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3113 }
3114
3115 static void
3116 uma_print_keg(uma_keg_t keg)
3117 {
3118         uma_slab_t slab;
3119
3120         printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3121             "out %d free %d limit %d\n",
3122             keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3123             keg->uk_ipers, keg->uk_ppera,
3124             (keg->uk_ipers * keg->uk_pages) - keg->uk_free, keg->uk_free,
3125             (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers);
3126         printf("Part slabs:\n");
3127         LIST_FOREACH(slab, &keg->uk_part_slab, us_link)
3128                 slab_print(slab);
3129         printf("Free slabs:\n");
3130         LIST_FOREACH(slab, &keg->uk_free_slab, us_link)
3131                 slab_print(slab);
3132         printf("Full slabs:\n");
3133         LIST_FOREACH(slab, &keg->uk_full_slab, us_link)
3134                 slab_print(slab);
3135 }
3136
3137 void
3138 uma_print_zone(uma_zone_t zone)
3139 {
3140         uma_cache_t cache;
3141         uma_klink_t kl;
3142         int i;
3143
3144         printf("zone: %s(%p) size %d flags %#x\n",
3145             zone->uz_name, zone, zone->uz_size, zone->uz_flags);
3146         LIST_FOREACH(kl, &zone->uz_kegs, kl_link)
3147                 uma_print_keg(kl->kl_keg);
3148         CPU_FOREACH(i) {
3149                 cache = &zone->uz_cpu[i];
3150                 printf("CPU %d Cache:\n", i);
3151                 cache_print(cache);
3152         }
3153 }
3154
3155 #ifdef DDB
3156 /*
3157  * Generate statistics across both the zone and its per-cpu cache's.  Return
3158  * desired statistics if the pointer is non-NULL for that statistic.
3159  *
3160  * Note: does not update the zone statistics, as it can't safely clear the
3161  * per-CPU cache statistic.
3162  *
3163  * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3164  * safe from off-CPU; we should modify the caches to track this information
3165  * directly so that we don't have to.
3166  */
3167 static void
3168 uma_zone_sumstat(uma_zone_t z, int *cachefreep, u_int64_t *allocsp,
3169     u_int64_t *freesp, u_int64_t *sleepsp)
3170 {
3171         uma_cache_t cache;
3172         u_int64_t allocs, frees, sleeps;
3173         int cachefree, cpu;
3174
3175         allocs = frees = sleeps = 0;
3176         cachefree = 0;
3177         CPU_FOREACH(cpu) {
3178                 cache = &z->uz_cpu[cpu];
3179                 if (cache->uc_allocbucket != NULL)
3180                         cachefree += cache->uc_allocbucket->ub_cnt;
3181                 if (cache->uc_freebucket != NULL)
3182                         cachefree += cache->uc_freebucket->ub_cnt;
3183                 allocs += cache->uc_allocs;
3184                 frees += cache->uc_frees;
3185         }
3186         allocs += z->uz_allocs;
3187         frees += z->uz_frees;
3188         sleeps += z->uz_sleeps;
3189         if (cachefreep != NULL)
3190                 *cachefreep = cachefree;
3191         if (allocsp != NULL)
3192                 *allocsp = allocs;
3193         if (freesp != NULL)
3194                 *freesp = frees;
3195         if (sleepsp != NULL)
3196                 *sleepsp = sleeps;
3197 }
3198 #endif /* DDB */
3199
3200 static int
3201 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3202 {
3203         uma_keg_t kz;
3204         uma_zone_t z;
3205         int count;
3206
3207         count = 0;
3208         mtx_lock(&uma_mtx);
3209         LIST_FOREACH(kz, &uma_kegs, uk_link) {
3210                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3211                         count++;
3212         }
3213         mtx_unlock(&uma_mtx);
3214         return (sysctl_handle_int(oidp, &count, 0, req));
3215 }
3216
3217 static int
3218 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3219 {
3220         struct uma_stream_header ush;
3221         struct uma_type_header uth;
3222         struct uma_percpu_stat ups;
3223         uma_bucket_t bucket;
3224         struct sbuf sbuf;
3225         uma_cache_t cache;
3226         uma_klink_t kl;
3227         uma_keg_t kz;
3228         uma_zone_t z;
3229         uma_keg_t k;
3230         int count, error, i;
3231
3232         error = sysctl_wire_old_buffer(req, 0);
3233         if (error != 0)
3234                 return (error);
3235         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3236
3237         count = 0;
3238         mtx_lock(&uma_mtx);
3239         LIST_FOREACH(kz, &uma_kegs, uk_link) {
3240                 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3241                         count++;
3242         }
3243
3244         /*
3245          * Insert stream header.
3246          */
3247         bzero(&ush, sizeof(ush));
3248         ush.ush_version = UMA_STREAM_VERSION;
3249         ush.ush_maxcpus = (mp_maxid + 1);
3250         ush.ush_count = count;
3251         (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
3252
3253         LIST_FOREACH(kz, &uma_kegs, uk_link) {
3254                 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3255                         bzero(&uth, sizeof(uth));
3256                         ZONE_LOCK(z);
3257                         strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3258                         uth.uth_align = kz->uk_align;
3259                         uth.uth_size = kz->uk_size;
3260                         uth.uth_rsize = kz->uk_rsize;
3261                         LIST_FOREACH(kl, &z->uz_kegs, kl_link) {
3262                                 k = kl->kl_keg;
3263                                 uth.uth_maxpages += k->uk_maxpages;
3264                                 uth.uth_pages += k->uk_pages;
3265                                 uth.uth_keg_free += k->uk_free;
3266                                 uth.uth_limit = (k->uk_maxpages / k->uk_ppera)
3267                                     * k->uk_ipers;
3268                         }
3269
3270                         /*
3271                          * A zone is secondary is it is not the first entry
3272                          * on the keg's zone list.
3273                          */
3274                         if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
3275                             (LIST_FIRST(&kz->uk_zones) != z))
3276                                 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
3277
3278                         LIST_FOREACH(bucket, &z->uz_full_bucket, ub_link)
3279                                 uth.uth_zone_free += bucket->ub_cnt;
3280                         uth.uth_allocs = z->uz_allocs;
3281                         uth.uth_frees = z->uz_frees;
3282                         uth.uth_fails = z->uz_fails;
3283                         uth.uth_sleeps = z->uz_sleeps;
3284                         (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
3285                         /*
3286                          * While it is not normally safe to access the cache
3287                          * bucket pointers while not on the CPU that owns the
3288                          * cache, we only allow the pointers to be exchanged
3289                          * without the zone lock held, not invalidated, so
3290                          * accept the possible race associated with bucket
3291                          * exchange during monitoring.
3292                          */
3293                         for (i = 0; i < (mp_maxid + 1); i++) {
3294                                 bzero(&ups, sizeof(ups));
3295                                 if (kz->uk_flags & UMA_ZFLAG_INTERNAL)
3296                                         goto skip;
3297                                 if (CPU_ABSENT(i))
3298                                         goto skip;
3299                                 cache = &z->uz_cpu[i];
3300                                 if (cache->uc_allocbucket != NULL)
3301                                         ups.ups_cache_free +=
3302                                             cache->uc_allocbucket->ub_cnt;
3303                                 if (cache->uc_freebucket != NULL)
3304                                         ups.ups_cache_free +=
3305                                             cache->uc_freebucket->ub_cnt;
3306                                 ups.ups_allocs = cache->uc_allocs;
3307                                 ups.ups_frees = cache->uc_frees;
3308 skip:
3309                                 (void)sbuf_bcat(&sbuf, &ups, sizeof(ups));
3310                         }
3311                         ZONE_UNLOCK(z);
3312                 }
3313         }
3314         mtx_unlock(&uma_mtx);
3315         error = sbuf_finish(&sbuf);
3316         sbuf_delete(&sbuf);
3317         return (error);
3318 }
3319
3320 #ifdef DDB
3321 DB_SHOW_COMMAND(uma, db_show_uma)
3322 {
3323         u_int64_t allocs, frees, sleeps;
3324         uma_bucket_t bucket;
3325         uma_keg_t kz;
3326         uma_zone_t z;
3327         int cachefree;
3328
3329         db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
3330             "Requests", "Sleeps");
3331         LIST_FOREACH(kz, &uma_kegs, uk_link) {
3332                 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3333                         if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
3334                                 allocs = z->uz_allocs;
3335                                 frees = z->uz_frees;
3336                                 sleeps = z->uz_sleeps;
3337                                 cachefree = 0;
3338                         } else
3339                                 uma_zone_sumstat(z, &cachefree, &allocs,
3340                                     &frees, &sleeps);
3341                         if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
3342                             (LIST_FIRST(&kz->uk_zones) != z)))
3343                                 cachefree += kz->uk_free;
3344                         LIST_FOREACH(bucket, &z->uz_full_bucket, ub_link)
3345                                 cachefree += bucket->ub_cnt;
3346                         db_printf("%18s %8ju %8jd %8d %12ju %8ju\n", z->uz_name,
3347                             (uintmax_t)kz->uk_size,
3348                             (intmax_t)(allocs - frees), cachefree,
3349                             (uintmax_t)allocs, sleeps);
3350                         if (db_pager_quit)
3351                                 return;
3352                 }
3353         }
3354 }
3355 #endif