2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2004 Poul-Henning Kamp
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * Unit number allocation functions.
33 * These functions implement a mixed run-length/bitmap management of unit
34 * number spaces in a very memory efficient manner.
36 * Allocation policy is always lowest free number first.
38 * A return value of -1 signals that no more unit numbers are available.
40 * There is no cost associated with the range of unitnumbers, so unless
41 * the resource really is finite, specify INT_MAX to new_unrhdr() and
42 * forget about checking the return value.
44 * If a mutex is not provided when the unit number space is created, a
45 * default global mutex is used. The advantage to passing a mutex in, is
46 * that the alloc_unrl() function can be called with the mutex already
47 * held (it will not be released by alloc_unrl()).
49 * The allocation function alloc_unr{l}() never sleeps (but it may block on
50 * the mutex of course).
52 * Freeing a unit number may require allocating memory, and can therefore
53 * sleep so the free_unr() function does not come in a pre-locked variant.
55 * A userland test program is included.
57 * Memory usage is a very complex function of the exact allocation
58 * pattern, but always very compact:
59 * * For the very typical case where a single unbroken run of unit
60 * numbers are allocated 44 bytes are used on i386.
61 * * For a unit number space of 1000 units and the random pattern
62 * in the usermode test program included, the worst case usage
63 * was 252 bytes on i386 for 500 allocated and 500 free units.
64 * * For a unit number space of 10000 units and the random pattern
65 * in the usermode test program included, the worst case usage
66 * was 798 bytes on i386 for 5000 allocated and 5000 free units.
67 * * The worst case is where every other unit number is allocated and
68 * the rest are free. In that case 44 + N/4 bytes are used where
69 * N is the number of the highest unit allocated.
72 #include <sys/param.h>
73 #include <sys/types.h>
74 #include <sys/_unrhdr.h>
78 #include <sys/bitstring.h>
79 #include <sys/malloc.h>
80 #include <sys/kernel.h>
81 #include <sys/systm.h>
82 #include <sys/limits.h>
84 #include <sys/mutex.h>
87 * In theory it would be smarter to allocate the individual blocks
88 * with the zone allocator, but at this time the expectation is that
89 * there will typically not even be enough allocations to fill a single
90 * page, so we stick with malloc for now.
92 static MALLOC_DEFINE(M_UNIT, "Unitno", "Unit number allocation");
94 #define Malloc(foo) malloc(foo, M_UNIT, M_WAITOK | M_ZERO)
95 #define Free(foo) free(foo, M_UNIT)
97 static struct mtx unitmtx;
99 MTX_SYSINIT(unit, &unitmtx, "unit# allocation", MTX_DEF);
101 #else /* ...USERLAND */
103 #include <bitstring.h>
112 #define KASSERT(cond, arg) \
121 #define Malloc(foo) _Malloc(foo, __LINE__)
123 _Malloc(size_t foo, int line)
126 KASSERT(no_alloc == 0, ("malloc in wrong place() line %d", line));
127 return (calloc(foo, 1));
129 #define Free(foo) free(foo)
139 mtx_lock(struct mtx *mp)
141 KASSERT(mp->state == 0, ("mutex already locked"));
146 mtx_unlock(struct mtx *mp)
148 KASSERT(mp->state == 1, ("mutex not locked"));
155 mtx_assert(struct mtx *mp, int flag)
157 if (flag == MA_OWNED) {
158 KASSERT(mp->state == 1, ("mtx_assert(MA_OWNED) not true"));
162 #define CTASSERT(foo)
163 #define WITNESS_WARN(flags, lock, fmt, ...) (void)0
165 #endif /* USERLAND */
168 * This is our basic building block.
170 * It can be used in three different ways depending on the value of the ptr
172 * If ptr is NULL, it represents a run of free items.
173 * If ptr points to the unrhdr it represents a run of allocated items.
174 * Otherwise it points to a bitstring of allocated items.
176 * For runs the len field is the length of the run.
177 * For bitmaps the len field represents the number of allocated items.
179 * The bitmap is the same size as struct unr to optimize memory management.
182 TAILQ_ENTRY(unr) list;
188 bitstr_t map[sizeof(struct unr) / sizeof(bitstr_t)];
191 CTASSERT((sizeof(struct unr) % sizeof(bitstr_t)) == 0);
193 /* Number of bits we can store in the bitmap */
194 #define NBITS (8 * sizeof(((struct unrb*)NULL)->map))
196 /* Is the unrb empty in at least the first len bits? */
198 ub_empty(struct unrb *ub, int len) {
201 bit_ffs(ub->map, len, &first_set);
202 return (first_set == -1);
205 /* Is the unrb full? That is, is the number of set elements equal to len? */
207 ub_full(struct unrb *ub, int len)
211 bit_ffc(ub->map, len, &first_clear);
212 return (first_clear == -1);
216 #if defined(DIAGNOSTIC) || !defined(_KERNEL)
218 * Consistency check function.
220 * Checks the internal consistency as well as we can.
222 * Called at all boundaries of this API.
225 check_unrhdr(struct unrhdr *uh, int line)
234 TAILQ_FOREACH(up, &uh->head, list) {
236 if (up->ptr != uh && up->ptr != NULL) {
238 KASSERT (up->len <= NBITS,
239 ("UNR inconsistency: len %u max %zd (line %d)\n",
240 up->len, NBITS, line));
243 bit_count(ub->map, 0, up->len, &w);
245 } else if (up->ptr != NULL)
248 KASSERT (y == uh->busy,
249 ("UNR inconsistency: items %u found %u (line %d)\n",
251 KASSERT (z == uh->alloc,
252 ("UNR inconsistency: chunks %u found %u (line %d)\n",
253 uh->alloc, z, line));
259 check_unrhdr(struct unrhdr *uh __unused, int line __unused)
268 * Userland memory management. Just use calloc and keep track of how
269 * many elements we have allocated for check_unrhdr().
272 static __inline void *
273 new_unr(struct unrhdr *uh, void **p1, void **p2)
278 KASSERT(*p1 != NULL || *p2 != NULL, ("Out of cached memory"));
291 delete_unr(struct unrhdr *uh, void *ptr)
297 TAILQ_INSERT_TAIL(&uh->ppfree, up, list);
301 clean_unrhdrl(struct unrhdr *uh)
305 mtx_assert(uh->mtx, MA_OWNED);
306 while ((up = TAILQ_FIRST(&uh->ppfree)) != NULL) {
307 TAILQ_REMOVE(&uh->ppfree, up, list);
316 clean_unrhdr(struct unrhdr *uh)
325 init_unrhdr(struct unrhdr *uh, int low, int high, struct mtx *mutex)
328 KASSERT(low >= 0 && low <= high,
329 ("UNR: use error: new_unrhdr(%d, %d)", low, high));
334 TAILQ_INIT(&uh->head);
335 TAILQ_INIT(&uh->ppfree);
339 uh->last = 1 + (high - low);
340 check_unrhdr(uh, __LINE__);
344 * Allocate a new unrheader set.
346 * Highest and lowest valid values given as parameters.
350 new_unrhdr(int low, int high, struct mtx *mutex)
354 uh = Malloc(sizeof *uh);
355 init_unrhdr(uh, low, high, mutex);
360 delete_unrhdr(struct unrhdr *uh)
363 check_unrhdr(uh, __LINE__);
364 KASSERT(uh->busy == 0, ("unrhdr has %u allocations", uh->busy));
365 KASSERT(uh->alloc == 0, ("UNR memory leak in delete_unrhdr"));
366 KASSERT(TAILQ_FIRST(&uh->ppfree) == NULL,
367 ("unrhdr has postponed item for free"));
372 clear_unrhdr(struct unrhdr *uh)
376 KASSERT(TAILQ_EMPTY(&uh->ppfree),
377 ("unrhdr has postponed item for free"));
378 TAILQ_FOREACH_SAFE(up, &uh->head, list, uq) {
386 init_unrhdr(uh, uh->low, uh->high, uh->mtx);
388 check_unrhdr(uh, __LINE__);
392 is_bitmap(struct unrhdr *uh, struct unr *up)
394 return (up->ptr != uh && up->ptr != NULL);
398 * Look for sequence of items which can be combined into a bitmap, if
399 * multiple are present, take the one which saves most memory.
401 * Return (1) if a sequence was found to indicate that another call
402 * might be able to do more. Return (0) if we found no suitable sequence.
404 * NB: called from alloc_unr(), no new memory allocation allowed.
407 optimize_unr(struct unrhdr *uh)
409 struct unr *up, *uf, *us;
410 struct unrb *ub, *ubf;
414 * Look for the run of items (if any) which when collapsed into
415 * a bitmap would save most memory.
419 TAILQ_FOREACH(uf, &uh->head, list) {
420 if (uf->len >= NBITS)
423 if (is_bitmap(uh, uf))
428 up = TAILQ_NEXT(up, list);
431 if ((up->len + l) > NBITS)
434 if (is_bitmap(uh, up))
447 * If the first element is not a bitmap, make it one.
448 * Trying to do so without allocating more memory complicates things
451 if (!is_bitmap(uh, us)) {
452 uf = TAILQ_NEXT(us, list);
453 TAILQ_REMOVE(&uh->head, us, list);
455 l = us->ptr == uh ? 1 : 0;
457 bit_nclear(ub->map, 0, NBITS - 1);
459 bit_nset(ub->map, 0, a);
460 if (!is_bitmap(uh, uf)) {
462 bit_nclear(ub->map, a, a + uf->len - 1);
464 bit_nset(ub->map, a, a + uf->len - 1);
470 for (l = 0; l < uf->len; l++, a++) {
471 if (bit_test(ubf->map, l))
474 bit_clear(ub->map, a);
477 delete_unr(uh, uf->ptr);
484 uf = TAILQ_NEXT(us, list);
487 if (uf->len + us->len > NBITS)
489 if (uf->ptr == NULL) {
490 bit_nclear(ub->map, us->len, us->len + uf->len - 1);
492 TAILQ_REMOVE(&uh->head, uf, list);
494 } else if (uf->ptr == uh) {
495 bit_nset(ub->map, us->len, us->len + uf->len - 1);
497 TAILQ_REMOVE(&uh->head, uf, list);
501 for (l = 0; l < uf->len; l++, us->len++) {
502 if (bit_test(ubf->map, l))
503 bit_set(ub->map, us->len);
505 bit_clear(ub->map, us->len);
507 TAILQ_REMOVE(&uh->head, uf, list);
515 * See if a given unr should be collapsed with a neighbor.
517 * NB: called from alloc_unr(), no new memory allocation allowed.
520 collapse_unr(struct unrhdr *uh, struct unr *up)
525 /* If bitmap is all set or clear, change it to runlength */
526 if (is_bitmap(uh, up)) {
528 if (ub_full(ub, up->len)) {
529 delete_unr(uh, up->ptr);
531 } else if (ub_empty(ub, up->len)) {
532 delete_unr(uh, up->ptr);
537 /* If nothing left in runlength, delete it */
539 upp = TAILQ_PREV(up, unrhd, list);
541 upp = TAILQ_NEXT(up, list);
542 TAILQ_REMOVE(&uh->head, up, list);
547 /* If we have "hot-spot" still, merge with neighbor if possible */
549 upp = TAILQ_PREV(up, unrhd, list);
550 if (upp != NULL && up->ptr == upp->ptr) {
552 TAILQ_REMOVE(&uh->head, upp, list);
555 upp = TAILQ_NEXT(up, list);
556 if (upp != NULL && up->ptr == upp->ptr) {
558 TAILQ_REMOVE(&uh->head, upp, list);
563 /* Merge into ->first if possible */
564 upp = TAILQ_FIRST(&uh->head);
565 if (upp != NULL && upp->ptr == uh) {
566 uh->first += upp->len;
567 TAILQ_REMOVE(&uh->head, upp, list);
573 /* Merge into ->last if possible */
574 upp = TAILQ_LAST(&uh->head, unrhd);
575 if (upp != NULL && upp->ptr == NULL) {
576 uh->last += upp->len;
577 TAILQ_REMOVE(&uh->head, upp, list);
583 /* Try to make bitmaps */
584 while (optimize_unr(uh))
589 * Allocate a free unr.
592 alloc_unrl(struct unrhdr *uh)
599 mtx_assert(uh->mtx, MA_OWNED);
600 check_unrhdr(uh, __LINE__);
601 x = uh->low + uh->first;
603 up = TAILQ_FIRST(&uh->head);
606 * If we have an ideal split, just adjust the first+last
608 if (up == NULL && uh->last > 0) {
616 * We can always allocate from the first list element, so if we have
617 * nothing on the list, we must have run out of unit numbers.
622 KASSERT(up->ptr != uh, ("UNR first element is allocated"));
624 if (up->ptr == NULL) { /* free run */
627 } else { /* bitmap */
629 bit_ffc(ub->map, up->len, &y);
630 KASSERT(y != -1, ("UNR corruption: No clear bit in bitmap."));
635 collapse_unr(uh, up);
640 alloc_unr(struct unrhdr *uh)
652 alloc_unr_specificl(struct unrhdr *uh, u_int item, void **p1, void **p2)
654 struct unr *up, *upn;
658 mtx_assert(uh->mtx, MA_OWNED);
660 if (item < uh->low + uh->first || item > uh->high)
663 up = TAILQ_FIRST(&uh->head);
665 if (up == NULL && item - uh->low == uh->first) {
669 check_unrhdr(uh, __LINE__);
673 i = item - uh->low - uh->first;
676 up = new_unr(uh, p1, p2);
679 TAILQ_INSERT_TAIL(&uh->head, up, list);
680 up = new_unr(uh, p1, p2);
683 TAILQ_INSERT_TAIL(&uh->head, up, list);
684 uh->last = uh->high - uh->low - i;
686 check_unrhdr(uh, __LINE__);
689 /* Find the item which contains the unit we want to allocate. */
690 TAILQ_FOREACH(up, &uh->head, list) {
699 up = new_unr(uh, p1, p2);
702 TAILQ_INSERT_TAIL(&uh->head, up, list);
704 up = new_unr(uh, p1, p2);
707 TAILQ_INSERT_TAIL(&uh->head, up, list);
711 if (is_bitmap(uh, up)) {
713 if (bit_test(ub->map, i) == 0) {
718 } else if (up->ptr == uh)
721 KASSERT(up->ptr == NULL,
722 ("alloc_unr_specificl: up->ptr != NULL (up=%p)", up));
724 /* Split off the tail end, if any. */
725 tl = up->len - (1 + i);
727 upn = new_unr(uh, p1, p2);
730 TAILQ_INSERT_AFTER(&uh->head, up, upn, list);
733 /* Split off head end, if any */
735 upn = new_unr(uh, p1, p2);
738 TAILQ_INSERT_BEFORE(up, upn, list);
744 last = uh->high - uh->low - (item - uh->low);
748 collapse_unr(uh, up);
749 check_unrhdr(uh, __LINE__);
754 alloc_unr_specific(struct unrhdr *uh, u_int item)
759 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "alloc_unr_specific");
761 p1 = Malloc(sizeof(struct unr));
762 p2 = Malloc(sizeof(struct unr));
765 i = alloc_unr_specificl(uh, item, &p1, &p2);
779 * If we can save unrs by using a bitmap, do so.
782 free_unrl(struct unrhdr *uh, u_int item, void **p1, void **p2)
784 struct unr *up, *upp, *upn;
788 KASSERT(item >= uh->low && item <= uh->high,
789 ("UNR: free_unr(%u) out of range [%u...%u]",
790 item, uh->low, uh->high));
791 check_unrhdr(uh, __LINE__);
793 upp = TAILQ_FIRST(&uh->head);
795 * Freeing in the ideal split case
797 if (item + 1 == uh->first && upp == NULL) {
801 check_unrhdr(uh, __LINE__);
805 * Freeing in the ->first section. Create a run starting at the
806 * freed item. The code below will subdivide it.
808 if (item < uh->first) {
809 up = new_unr(uh, p1, p2);
811 up->len = uh->first - item;
812 TAILQ_INSERT_HEAD(&uh->head, up, list);
813 uh->first -= up->len;
818 /* Find the item which contains the unit we want to free */
819 TAILQ_FOREACH(up, &uh->head, list) {
825 /* Handle bitmap items */
826 if (is_bitmap(uh, up)) {
829 KASSERT(bit_test(ub->map, item) != 0,
830 ("UNR: Freeing free item %d (bitmap)\n", item));
831 bit_clear(ub->map, item);
833 collapse_unr(uh, up);
837 KASSERT(up->ptr == uh, ("UNR Freeing free item %d (run))\n", item));
839 /* Just this one left, reap it */
843 collapse_unr(uh, up);
847 /* Check if we can shift the item into the previous 'free' run */
848 upp = TAILQ_PREV(up, unrhd, list);
849 if (item == 0 && upp != NULL && upp->ptr == NULL) {
853 collapse_unr(uh, up);
857 /* Check if we can shift the item to the next 'free' run */
858 upn = TAILQ_NEXT(up, list);
859 if (item == up->len - 1 && upn != NULL && upn->ptr == NULL) {
863 collapse_unr(uh, up);
867 /* Split off the tail end, if any. */
868 pl = up->len - (1 + item);
870 upp = new_unr(uh, p1, p2);
873 TAILQ_INSERT_AFTER(&uh->head, up, upp, list);
876 /* Split off head end, if any */
878 upp = new_unr(uh, p1, p2);
881 TAILQ_INSERT_BEFORE(up, upp, list);
886 collapse_unr(uh, up);
890 free_unr(struct unrhdr *uh, u_int item)
894 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "free_unr");
895 p1 = Malloc(sizeof(struct unr));
896 p2 = Malloc(sizeof(struct unr));
898 free_unrl(uh, item, &p1, &p2);
907 #ifndef _KERNEL /* USERLAND test driver */
910 * Simple stochastic test driver for the above functions. The code resides
911 * here so that it can access static functions and structures.
915 #define VPRINTF(...) {if (verbose) printf(__VA_ARGS__);}
918 print_unr(struct unrhdr *uh, struct unr *up)
923 printf(" %p len = %5u ", up, up->len);
926 else if (up->ptr == uh)
931 for (x = 0; x < up->len; x++) {
932 if (bit_test(ub->map, x))
942 print_unrhdr(struct unrhdr *uh)
948 "%p low = %u high = %u first = %u last = %u busy %u chunks = %u\n",
949 uh, uh->low, uh->high, uh->first, uh->last, uh->busy, uh->alloc);
950 x = uh->low + uh->first;
951 TAILQ_FOREACH(up, &uh->head, list) {
952 printf(" from = %5u", x);
954 if (up->ptr == NULL || up->ptr == uh)
962 test_alloc_unr(struct unrhdr *uh, u_int i, char a[])
967 VPRINTF("F %u\n", i);
975 VPRINTF("A %d\n", j);
982 test_alloc_unr_specific(struct unrhdr *uh, u_int i, char a[])
986 j = alloc_unr_specific(uh, i);
988 VPRINTF("F %u\n", i);
993 VPRINTF("A %d\n", j);
1000 printf("%s [-h] [-r REPETITIONS] [-v]\n", argv[0]);
1004 main(int argc, char **argv)
1008 long count = 10000; /* Number of unrs to test */
1015 while ((ch = getopt(argc, argv, "hr:v")) != -1) {
1019 reps = strtol(optarg, NULL, 0);
1020 if (errno == ERANGE || errno == EINVAL) {
1038 setbuf(stdout, NULL);
1039 uh = new_unrhdr(0, count - 1, NULL);
1042 a = calloc(count, sizeof(char));
1044 err(1, "calloc failed");
1047 printf("sizeof(struct unr) %zu\n", sizeof(struct unr));
1048 printf("sizeof(struct unrb) %zu\n", sizeof(struct unrb));
1049 printf("sizeof(struct unrhdr) %zu\n", sizeof(struct unrhdr));
1050 printf("NBITS %lu\n", (unsigned long)NBITS);
1051 for (m = 0; m < count * reps; m++) {
1053 i = (j >> 1) % count;
1055 if (a[i] && (j & 1))
1058 if ((random() & 1) != 0)
1059 test_alloc_unr(uh, i, a);
1061 test_alloc_unr_specific(uh, i, a);
1065 check_unrhdr(uh, __LINE__);
1067 for (i = 0; i < (u_int)count; i++) {
1070 printf("C %u\n", i);