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