2 * Copyright (c) 2004 Poul-Henning Kamp
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * Unit number allocation functions.
31 * These functions implement a mixed run-length/bitmap management of unit
32 * number spaces in a very memory efficient manner.
34 * Allocation policy is always lowest free number first.
36 * A return value of -1 signals that no more unit numbers are available.
38 * There is no cost associated with the range of unitnumbers, so unless
39 * the resource really is finite, specify INT_MAX to new_unrhdr() and
40 * forget about checking the return value.
42 * If a mutex is not provided when the unit number space is created, a
43 * default global mutex is used. The advantage to passing a mutex in, is
44 * that the alloc_unrl() function can be called with the mutex already
45 * held (it will not be released by alloc_unrl()).
47 * The allocation function alloc_unr{l}() never sleeps (but it may block on
48 * the mutex of course).
50 * Freeing a unit number may require allocating memory, and can therefore
51 * sleep so the free_unr() function does not come in a pre-locked variant.
53 * A userland test program is included.
55 * Memory usage is a very complex function of the exact allocation
56 * pattern, but always very compact:
57 * * For the very typical case where a single unbroken run of unit
58 * numbers are allocated 44 bytes are used on i386.
59 * * For a unit number space of 1000 units and the random pattern
60 * in the usermode test program included, the worst case usage
61 * was 252 bytes on i386 for 500 allocated and 500 free units.
62 * * For a unit number space of 10000 units and the random pattern
63 * in the usermode test program included, the worst case usage
64 * was 798 bytes on i386 for 5000 allocated and 5000 free units.
65 * * The worst case is where every other unit number is allocated and
66 * the rest are free. In that case 44 + N/4 bytes are used where
67 * N is the number of the highest unit allocated.
70 #include <sys/param.h>
71 #include <sys/types.h>
72 #include <sys/_unrhdr.h>
76 #include <sys/bitstring.h>
77 #include <sys/malloc.h>
78 #include <sys/kernel.h>
79 #include <sys/systm.h>
80 #include <sys/limits.h>
82 #include <sys/mutex.h>
85 * In theory it would be smarter to allocate the individual blocks
86 * with the zone allocator, but at this time the expectation is that
87 * there will typically not even be enough allocations to fill a single
88 * page, so we stick with malloc for now.
90 static MALLOC_DEFINE(M_UNIT, "Unitno", "Unit number allocation");
92 #define Malloc(foo) malloc(foo, M_UNIT, M_WAITOK | M_ZERO)
93 #define Free(foo) free(foo, M_UNIT)
95 static struct mtx unitmtx;
97 MTX_SYSINIT(unit, &unitmtx, "unit# allocation", MTX_DEF);
99 #else /* ...USERLAND */
101 #include <bitstring.h>
110 #define KASSERT(cond, arg) \
119 #define Malloc(foo) _Malloc(foo, __LINE__)
121 _Malloc(size_t foo, int line)
124 KASSERT(no_alloc == 0, ("malloc in wrong place() line %d", line));
125 return (calloc(foo, 1));
127 #define Free(foo) free(foo)
137 mtx_lock(struct mtx *mp)
139 KASSERT(mp->state == 0, ("mutex already locked"));
144 mtx_unlock(struct mtx *mp)
146 KASSERT(mp->state == 1, ("mutex not locked"));
153 mtx_assert(struct mtx *mp, int flag)
155 if (flag == MA_OWNED) {
156 KASSERT(mp->state == 1, ("mtx_assert(MA_OWNED) not true"));
160 #define CTASSERT(foo)
161 #define WITNESS_WARN(flags, lock, fmt, ...) (void)0
163 #endif /* USERLAND */
166 * This is our basic building block.
168 * It can be used in three different ways depending on the value of the ptr
170 * If ptr is NULL, it represents a run of free items.
171 * If ptr points to the unrhdr it represents a run of allocated items.
172 * Otherwise it points to a bitstring of allocated items.
174 * For runs the len field is the length of the run.
175 * For bitmaps the len field represents the number of allocated items.
177 * The bitmap is the same size as struct unr to optimize memory management.
180 TAILQ_ENTRY(unr) list;
186 bitstr_t map[sizeof(struct unr) / sizeof(bitstr_t)];
189 CTASSERT((sizeof(struct unr) % sizeof(bitstr_t)) == 0);
191 /* Number of bits we can store in the bitmap */
192 #define NBITS (8 * sizeof(((struct unrb*)NULL)->map))
194 /* Is the unrb empty in at least the first len bits? */
196 ub_empty(struct unrb *ub, int len) {
199 bit_ffs(ub->map, len, &first_set);
200 return (first_set == -1);
203 /* Is the unrb full? That is, is the number of set elements equal to len? */
205 ub_full(struct unrb *ub, int len)
209 bit_ffc(ub->map, len, &first_clear);
210 return (first_clear == -1);
214 #if defined(DIAGNOSTIC) || !defined(_KERNEL)
216 * Consistency check function.
218 * Checks the internal consistency as well as we can.
220 * Called at all boundaries of this API.
223 check_unrhdr(struct unrhdr *uh, int line)
232 TAILQ_FOREACH(up, &uh->head, list) {
234 if (up->ptr != uh && up->ptr != NULL) {
236 KASSERT (up->len <= NBITS,
237 ("UNR inconsistency: len %u max %zd (line %d)\n",
238 up->len, NBITS, line));
241 bit_count(ub->map, 0, up->len, &w);
243 } else if (up->ptr != NULL)
246 KASSERT (y == uh->busy,
247 ("UNR inconsistency: items %u found %u (line %d)\n",
249 KASSERT (z == uh->alloc,
250 ("UNR inconsistency: chunks %u found %u (line %d)\n",
251 uh->alloc, z, line));
257 check_unrhdr(struct unrhdr *uh __unused, int line __unused)
266 * Userland memory management. Just use calloc and keep track of how
267 * many elements we have allocated for check_unrhdr().
270 static __inline void *
271 new_unr(struct unrhdr *uh, void **p1, void **p2)
276 KASSERT(*p1 != NULL || *p2 != NULL, ("Out of cached memory"));
289 delete_unr(struct unrhdr *uh, void *ptr)
295 TAILQ_INSERT_TAIL(&uh->ppfree, up, list);
299 clean_unrhdrl(struct unrhdr *uh)
303 mtx_assert(uh->mtx, MA_OWNED);
304 while ((up = TAILQ_FIRST(&uh->ppfree)) != NULL) {
305 TAILQ_REMOVE(&uh->ppfree, up, list);
314 clean_unrhdr(struct unrhdr *uh)
323 init_unrhdr(struct unrhdr *uh, int low, int high, struct mtx *mutex)
326 KASSERT(low >= 0 && low <= high,
327 ("UNR: use error: new_unrhdr(%d, %d)", low, high));
332 TAILQ_INIT(&uh->head);
333 TAILQ_INIT(&uh->ppfree);
337 uh->last = 1 + (high - low);
338 check_unrhdr(uh, __LINE__);
342 * Allocate a new unrheader set.
344 * Highest and lowest valid values given as parameters.
348 new_unrhdr(int low, int high, struct mtx *mutex)
352 uh = Malloc(sizeof *uh);
353 init_unrhdr(uh, low, high, mutex);
358 delete_unrhdr(struct unrhdr *uh)
361 check_unrhdr(uh, __LINE__);
362 KASSERT(uh->busy == 0, ("unrhdr has %u allocations", uh->busy));
363 KASSERT(uh->alloc == 0, ("UNR memory leak in delete_unrhdr"));
364 KASSERT(TAILQ_FIRST(&uh->ppfree) == NULL,
365 ("unrhdr has postponed item for free"));
370 is_bitmap(struct unrhdr *uh, struct unr *up)
372 return (up->ptr != uh && up->ptr != NULL);
376 * Look for sequence of items which can be combined into a bitmap, if
377 * multiple are present, take the one which saves most memory.
379 * Return (1) if a sequence was found to indicate that another call
380 * might be able to do more. Return (0) if we found no suitable sequence.
382 * NB: called from alloc_unr(), no new memory allocation allowed.
385 optimize_unr(struct unrhdr *uh)
387 struct unr *up, *uf, *us;
388 struct unrb *ub, *ubf;
392 * Look for the run of items (if any) which when collapsed into
393 * a bitmap would save most memory.
397 TAILQ_FOREACH(uf, &uh->head, list) {
398 if (uf->len >= NBITS)
401 if (is_bitmap(uh, uf))
406 up = TAILQ_NEXT(up, list);
409 if ((up->len + l) > NBITS)
412 if (is_bitmap(uh, up))
425 * If the first element is not a bitmap, make it one.
426 * Trying to do so without allocating more memory complicates things
429 if (!is_bitmap(uh, us)) {
430 uf = TAILQ_NEXT(us, list);
431 TAILQ_REMOVE(&uh->head, us, list);
433 l = us->ptr == uh ? 1 : 0;
435 bit_nclear(ub->map, 0, NBITS - 1);
437 bit_nset(ub->map, 0, a);
438 if (!is_bitmap(uh, uf)) {
440 bit_nclear(ub->map, a, a + uf->len - 1);
442 bit_nset(ub->map, a, a + uf->len - 1);
448 for (l = 0; l < uf->len; l++, a++) {
449 if (bit_test(ubf->map, l))
452 bit_clear(ub->map, a);
455 delete_unr(uh, uf->ptr);
462 uf = TAILQ_NEXT(us, list);
465 if (uf->len + us->len > NBITS)
467 if (uf->ptr == NULL) {
468 bit_nclear(ub->map, us->len, us->len + uf->len - 1);
470 TAILQ_REMOVE(&uh->head, uf, list);
472 } else if (uf->ptr == uh) {
473 bit_nset(ub->map, us->len, us->len + uf->len - 1);
475 TAILQ_REMOVE(&uh->head, uf, list);
479 for (l = 0; l < uf->len; l++, us->len++) {
480 if (bit_test(ubf->map, l))
481 bit_set(ub->map, us->len);
483 bit_clear(ub->map, us->len);
485 TAILQ_REMOVE(&uh->head, uf, list);
493 * See if a given unr should be collapsed with a neighbor.
495 * NB: called from alloc_unr(), no new memory allocation allowed.
498 collapse_unr(struct unrhdr *uh, struct unr *up)
503 /* If bitmap is all set or clear, change it to runlength */
504 if (is_bitmap(uh, up)) {
506 if (ub_full(ub, up->len)) {
507 delete_unr(uh, up->ptr);
509 } else if (ub_empty(ub, up->len)) {
510 delete_unr(uh, up->ptr);
515 /* If nothing left in runlength, delete it */
517 upp = TAILQ_PREV(up, unrhd, list);
519 upp = TAILQ_NEXT(up, list);
520 TAILQ_REMOVE(&uh->head, up, list);
525 /* If we have "hot-spot" still, merge with neighbor if possible */
527 upp = TAILQ_PREV(up, unrhd, list);
528 if (upp != NULL && up->ptr == upp->ptr) {
530 TAILQ_REMOVE(&uh->head, upp, list);
533 upp = TAILQ_NEXT(up, list);
534 if (upp != NULL && up->ptr == upp->ptr) {
536 TAILQ_REMOVE(&uh->head, upp, list);
541 /* Merge into ->first if possible */
542 upp = TAILQ_FIRST(&uh->head);
543 if (upp != NULL && upp->ptr == uh) {
544 uh->first += upp->len;
545 TAILQ_REMOVE(&uh->head, upp, list);
551 /* Merge into ->last if possible */
552 upp = TAILQ_LAST(&uh->head, unrhd);
553 if (upp != NULL && upp->ptr == NULL) {
554 uh->last += upp->len;
555 TAILQ_REMOVE(&uh->head, upp, list);
561 /* Try to make bitmaps */
562 while (optimize_unr(uh))
567 * Allocate a free unr.
570 alloc_unrl(struct unrhdr *uh)
577 mtx_assert(uh->mtx, MA_OWNED);
578 check_unrhdr(uh, __LINE__);
579 x = uh->low + uh->first;
581 up = TAILQ_FIRST(&uh->head);
584 * If we have an ideal split, just adjust the first+last
586 if (up == NULL && uh->last > 0) {
594 * We can always allocate from the first list element, so if we have
595 * nothing on the list, we must have run out of unit numbers.
600 KASSERT(up->ptr != uh, ("UNR first element is allocated"));
602 if (up->ptr == NULL) { /* free run */
605 } else { /* bitmap */
607 bit_ffc(ub->map, up->len, &y);
608 KASSERT(y != -1, ("UNR corruption: No clear bit in bitmap."));
613 collapse_unr(uh, up);
618 alloc_unr(struct unrhdr *uh)
630 alloc_unr_specificl(struct unrhdr *uh, u_int item, void **p1, void **p2)
632 struct unr *up, *upn;
636 mtx_assert(uh->mtx, MA_OWNED);
638 if (item < uh->low + uh->first || item > uh->high)
641 up = TAILQ_FIRST(&uh->head);
643 if (up == NULL && item - uh->low == uh->first) {
647 check_unrhdr(uh, __LINE__);
651 i = item - uh->low - uh->first;
654 up = new_unr(uh, p1, p2);
657 TAILQ_INSERT_TAIL(&uh->head, up, list);
658 up = new_unr(uh, p1, p2);
661 TAILQ_INSERT_TAIL(&uh->head, up, list);
662 uh->last = uh->high - uh->low - i;
664 check_unrhdr(uh, __LINE__);
667 /* Find the item which contains the unit we want to allocate. */
668 TAILQ_FOREACH(up, &uh->head, list) {
677 up = new_unr(uh, p1, p2);
680 TAILQ_INSERT_TAIL(&uh->head, up, list);
682 up = new_unr(uh, p1, p2);
685 TAILQ_INSERT_TAIL(&uh->head, up, list);
689 if (is_bitmap(uh, up)) {
691 if (bit_test(ub->map, i) == 0) {
696 } else if (up->ptr == uh)
699 KASSERT(up->ptr == NULL,
700 ("alloc_unr_specificl: up->ptr != NULL (up=%p)", up));
702 /* Split off the tail end, if any. */
703 tl = up->len - (1 + i);
705 upn = new_unr(uh, p1, p2);
708 TAILQ_INSERT_AFTER(&uh->head, up, upn, list);
711 /* Split off head end, if any */
713 upn = new_unr(uh, p1, p2);
716 TAILQ_INSERT_BEFORE(up, upn, list);
722 last = uh->high - uh->low - (item - uh->low);
726 collapse_unr(uh, up);
727 check_unrhdr(uh, __LINE__);
732 alloc_unr_specific(struct unrhdr *uh, u_int item)
737 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "alloc_unr_specific");
739 p1 = Malloc(sizeof(struct unr));
740 p2 = Malloc(sizeof(struct unr));
743 i = alloc_unr_specificl(uh, item, &p1, &p2);
757 * If we can save unrs by using a bitmap, do so.
760 free_unrl(struct unrhdr *uh, u_int item, void **p1, void **p2)
762 struct unr *up, *upp, *upn;
766 KASSERT(item >= uh->low && item <= uh->high,
767 ("UNR: free_unr(%u) out of range [%u...%u]",
768 item, uh->low, uh->high));
769 check_unrhdr(uh, __LINE__);
771 upp = TAILQ_FIRST(&uh->head);
773 * Freeing in the ideal split case
775 if (item + 1 == uh->first && upp == NULL) {
779 check_unrhdr(uh, __LINE__);
783 * Freeing in the ->first section. Create a run starting at the
784 * freed item. The code below will subdivide it.
786 if (item < uh->first) {
787 up = new_unr(uh, p1, p2);
789 up->len = uh->first - item;
790 TAILQ_INSERT_HEAD(&uh->head, up, list);
791 uh->first -= up->len;
796 /* Find the item which contains the unit we want to free */
797 TAILQ_FOREACH(up, &uh->head, list) {
803 /* Handle bitmap items */
804 if (is_bitmap(uh, up)) {
807 KASSERT(bit_test(ub->map, item) != 0,
808 ("UNR: Freeing free item %d (bitmap)\n", item));
809 bit_clear(ub->map, item);
811 collapse_unr(uh, up);
815 KASSERT(up->ptr == uh, ("UNR Freeing free item %d (run))\n", item));
817 /* Just this one left, reap it */
821 collapse_unr(uh, up);
825 /* Check if we can shift the item into the previous 'free' run */
826 upp = TAILQ_PREV(up, unrhd, list);
827 if (item == 0 && upp != NULL && upp->ptr == NULL) {
831 collapse_unr(uh, up);
835 /* Check if we can shift the item to the next 'free' run */
836 upn = TAILQ_NEXT(up, list);
837 if (item == up->len - 1 && upn != NULL && upn->ptr == NULL) {
841 collapse_unr(uh, up);
845 /* Split off the tail end, if any. */
846 pl = up->len - (1 + item);
848 upp = new_unr(uh, p1, p2);
851 TAILQ_INSERT_AFTER(&uh->head, up, upp, list);
854 /* Split off head end, if any */
856 upp = new_unr(uh, p1, p2);
859 TAILQ_INSERT_BEFORE(up, upp, list);
864 collapse_unr(uh, up);
868 free_unr(struct unrhdr *uh, u_int item)
872 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "free_unr");
873 p1 = Malloc(sizeof(struct unr));
874 p2 = Malloc(sizeof(struct unr));
876 free_unrl(uh, item, &p1, &p2);
885 #ifndef _KERNEL /* USERLAND test driver */
888 * Simple stochastic test driver for the above functions. The code resides
889 * here so that it can access static functions and structures.
893 #define VPRINTF(...) {if (verbose) printf(__VA_ARGS__);}
896 print_unr(struct unrhdr *uh, struct unr *up)
901 printf(" %p len = %5u ", up, up->len);
904 else if (up->ptr == uh)
909 for (x = 0; x < up->len; x++) {
910 if (bit_test(ub->map, x))
920 print_unrhdr(struct unrhdr *uh)
926 "%p low = %u high = %u first = %u last = %u busy %u chunks = %u\n",
927 uh, uh->low, uh->high, uh->first, uh->last, uh->busy, uh->alloc);
928 x = uh->low + uh->first;
929 TAILQ_FOREACH(up, &uh->head, list) {
930 printf(" from = %5u", x);
932 if (up->ptr == NULL || up->ptr == uh)
940 test_alloc_unr(struct unrhdr *uh, u_int i, char a[])
945 VPRINTF("F %u\n", i);
953 VPRINTF("A %d\n", j);
960 test_alloc_unr_specific(struct unrhdr *uh, u_int i, char a[])
964 j = alloc_unr_specific(uh, i);
966 VPRINTF("F %u\n", i);
971 VPRINTF("A %d\n", j);
978 printf("%s [-h] [-r REPETITIONS] [-v]\n", argv[0]);
982 main(int argc, char **argv)
986 long count = 10000; /* Number of unrs to test */
993 while ((ch = getopt(argc, argv, "hr:v")) != -1) {
997 reps = strtol(optarg, NULL, 0);
998 if (errno == ERANGE || errno == EINVAL) {
1016 setbuf(stdout, NULL);
1017 uh = new_unrhdr(0, count - 1, NULL);
1020 a = calloc(count, sizeof(char));
1022 err(1, "calloc failed");
1025 printf("sizeof(struct unr) %zu\n", sizeof(struct unr));
1026 printf("sizeof(struct unrb) %zu\n", sizeof(struct unrb));
1027 printf("sizeof(struct unrhdr) %zu\n", sizeof(struct unrhdr));
1028 printf("NBITS %lu\n", (unsigned long)NBITS);
1030 for (m = 0; m < count * reps; m++) {
1032 i = (j >> 1) % count;
1034 if (a[i] && (j & 1))
1037 if ((random() & 1) != 0)
1038 test_alloc_unr(uh, i, a);
1040 test_alloc_unr_specific(uh, i, a);
1044 check_unrhdr(uh, __LINE__);
1046 for (i = 0; i < (u_int)count; i++) {
1049 printf("C %u\n", i);