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);
103 alloc_unr64(struct unrhdr64 *unr64)
108 item = unr64->counter++;
109 mtx_unlock(&unitmtx);
114 #else /* ...USERLAND */
116 #include <bitstring.h>
125 #define KASSERT(cond, arg) \
134 #define Malloc(foo) _Malloc(foo, __LINE__)
136 _Malloc(size_t foo, int line)
139 KASSERT(no_alloc == 0, ("malloc in wrong place() line %d", line));
140 return (calloc(foo, 1));
142 #define Free(foo) free(foo)
151 mtx_lock(struct mtx *mp)
153 KASSERT(mp->state == 0, ("mutex already locked"));
158 mtx_unlock(struct mtx *mp)
160 KASSERT(mp->state == 1, ("mutex not locked"));
167 mtx_assert(struct mtx *mp, int flag)
169 if (flag == MA_OWNED) {
170 KASSERT(mp->state == 1, ("mtx_assert(MA_OWNED) not true"));
174 #define CTASSERT(foo)
175 #define WITNESS_WARN(flags, lock, fmt, ...) (void)0
177 #endif /* USERLAND */
180 * This is our basic building block.
182 * It can be used in three different ways depending on the value of the ptr
184 * If ptr is NULL, it represents a run of free items.
185 * If ptr points to the unrhdr it represents a run of allocated items.
186 * Otherwise it points to a bitstring of allocated items.
188 * For runs the len field is the length of the run.
189 * For bitmaps the len field represents the number of allocated items.
191 * The bitmap is the same size as struct unr to optimize memory management.
194 TAILQ_ENTRY(unr) list;
200 bitstr_t map[sizeof(struct unr) / sizeof(bitstr_t)];
203 CTASSERT((sizeof(struct unr) % sizeof(bitstr_t)) == 0);
205 /* Number of bits we can store in the bitmap */
206 #define NBITS (8 * sizeof(((struct unrb*)NULL)->map))
208 /* Is the unrb empty in at least the first len bits? */
210 ub_empty(struct unrb *ub, int len) {
213 bit_ffs(ub->map, len, &first_set);
214 return (first_set == -1);
217 /* Is the unrb full? That is, is the number of set elements equal to len? */
219 ub_full(struct unrb *ub, int len)
223 bit_ffc(ub->map, len, &first_clear);
224 return (first_clear == -1);
227 #if defined(DIAGNOSTIC) || !defined(_KERNEL)
229 * Consistency check function.
231 * Checks the internal consistency as well as we can.
233 * Called at all boundaries of this API.
236 check_unrhdr(struct unrhdr *uh, int line)
245 TAILQ_FOREACH(up, &uh->head, list) {
247 if (up->ptr != uh && up->ptr != NULL) {
249 KASSERT (up->len <= NBITS,
250 ("UNR inconsistency: len %u max %zd (line %d)\n",
251 up->len, NBITS, line));
254 bit_count(ub->map, 0, up->len, &w);
256 } else if (up->ptr != NULL)
259 KASSERT (y == uh->busy,
260 ("UNR inconsistency: items %u found %u (line %d)\n",
262 KASSERT (z == uh->alloc,
263 ("UNR inconsistency: chunks %u found %u (line %d)\n",
264 uh->alloc, z, line));
270 check_unrhdr(struct unrhdr *uh __unused, int line __unused)
278 * Userland memory management. Just use calloc and keep track of how
279 * many elements we have allocated for check_unrhdr().
282 static __inline void *
283 new_unr(struct unrhdr *uh, void **p1, void **p2)
288 KASSERT(*p1 != NULL || *p2 != NULL, ("Out of cached memory"));
301 delete_unr(struct unrhdr *uh, void *ptr)
307 TAILQ_INSERT_TAIL(&uh->ppfree, up, list);
311 clean_unrhdrl(struct unrhdr *uh)
315 mtx_assert(uh->mtx, MA_OWNED);
316 while ((up = TAILQ_FIRST(&uh->ppfree)) != NULL) {
317 TAILQ_REMOVE(&uh->ppfree, up, list);
326 clean_unrhdr(struct unrhdr *uh)
335 init_unrhdr(struct unrhdr *uh, int low, int high, struct mtx *mutex)
338 KASSERT(low >= 0 && low <= high,
339 ("UNR: use error: new_unrhdr(%d, %d)", low, high));
344 TAILQ_INIT(&uh->head);
345 TAILQ_INIT(&uh->ppfree);
349 uh->last = 1 + (high - low);
350 check_unrhdr(uh, __LINE__);
354 * Allocate a new unrheader set.
356 * Highest and lowest valid values given as parameters.
360 new_unrhdr(int low, int high, struct mtx *mutex)
364 uh = Malloc(sizeof *uh);
365 init_unrhdr(uh, low, high, mutex);
370 delete_unrhdr(struct unrhdr *uh)
373 check_unrhdr(uh, __LINE__);
374 KASSERT(uh->busy == 0, ("unrhdr has %u allocations", uh->busy));
375 KASSERT(uh->alloc == 0, ("UNR memory leak in delete_unrhdr"));
376 KASSERT(TAILQ_FIRST(&uh->ppfree) == NULL,
377 ("unrhdr has postponed item for free"));
382 clear_unrhdr(struct unrhdr *uh)
386 KASSERT(TAILQ_EMPTY(&uh->ppfree),
387 ("unrhdr has postponed item for free"));
388 TAILQ_FOREACH_SAFE(up, &uh->head, list, uq) {
396 init_unrhdr(uh, uh->low, uh->high, uh->mtx);
398 check_unrhdr(uh, __LINE__);
402 is_bitmap(struct unrhdr *uh, struct unr *up)
404 return (up->ptr != uh && up->ptr != NULL);
408 * Look for sequence of items which can be combined into a bitmap, if
409 * multiple are present, take the one which saves most memory.
411 * Return (1) if a sequence was found to indicate that another call
412 * might be able to do more. Return (0) if we found no suitable sequence.
414 * NB: called from alloc_unr(), no new memory allocation allowed.
417 optimize_unr(struct unrhdr *uh)
419 struct unr *up, *uf, *us;
420 struct unrb *ub, *ubf;
424 * Look for the run of items (if any) which when collapsed into
425 * a bitmap would save most memory.
429 TAILQ_FOREACH(uf, &uh->head, list) {
430 if (uf->len >= NBITS)
433 if (is_bitmap(uh, uf))
438 up = TAILQ_NEXT(up, list);
441 if ((up->len + l) > NBITS)
444 if (is_bitmap(uh, up))
457 * If the first element is not a bitmap, make it one.
458 * Trying to do so without allocating more memory complicates things
461 if (!is_bitmap(uh, us)) {
462 uf = TAILQ_NEXT(us, list);
463 TAILQ_REMOVE(&uh->head, us, list);
465 l = us->ptr == uh ? 1 : 0;
467 bit_nclear(ub->map, 0, NBITS - 1);
469 bit_nset(ub->map, 0, a);
470 if (!is_bitmap(uh, uf)) {
472 bit_nclear(ub->map, a, a + uf->len - 1);
474 bit_nset(ub->map, a, a + uf->len - 1);
480 for (l = 0; l < uf->len; l++, a++) {
481 if (bit_test(ubf->map, l))
484 bit_clear(ub->map, a);
487 delete_unr(uh, uf->ptr);
494 uf = TAILQ_NEXT(us, list);
497 if (uf->len + us->len > NBITS)
499 if (uf->ptr == NULL) {
500 bit_nclear(ub->map, us->len, us->len + uf->len - 1);
502 TAILQ_REMOVE(&uh->head, uf, list);
504 } else if (uf->ptr == uh) {
505 bit_nset(ub->map, us->len, us->len + uf->len - 1);
507 TAILQ_REMOVE(&uh->head, uf, list);
511 for (l = 0; l < uf->len; l++, us->len++) {
512 if (bit_test(ubf->map, l))
513 bit_set(ub->map, us->len);
515 bit_clear(ub->map, us->len);
517 TAILQ_REMOVE(&uh->head, uf, list);
525 * See if a given unr should be collapsed with a neighbor.
527 * NB: called from alloc_unr(), no new memory allocation allowed.
530 collapse_unr(struct unrhdr *uh, struct unr *up)
535 /* If bitmap is all set or clear, change it to runlength */
536 if (is_bitmap(uh, up)) {
538 if (ub_full(ub, up->len)) {
539 delete_unr(uh, up->ptr);
541 } else if (ub_empty(ub, up->len)) {
542 delete_unr(uh, up->ptr);
547 /* If nothing left in runlength, delete it */
549 upp = TAILQ_PREV(up, unrhd, list);
551 upp = TAILQ_NEXT(up, list);
552 TAILQ_REMOVE(&uh->head, up, list);
557 /* If we have "hot-spot" still, merge with neighbor if possible */
559 upp = TAILQ_PREV(up, unrhd, list);
560 if (upp != NULL && up->ptr == upp->ptr) {
562 TAILQ_REMOVE(&uh->head, upp, list);
565 upp = TAILQ_NEXT(up, list);
566 if (upp != NULL && up->ptr == upp->ptr) {
568 TAILQ_REMOVE(&uh->head, upp, list);
573 /* Merge into ->first if possible */
574 upp = TAILQ_FIRST(&uh->head);
575 if (upp != NULL && upp->ptr == uh) {
576 uh->first += upp->len;
577 TAILQ_REMOVE(&uh->head, upp, list);
583 /* Merge into ->last if possible */
584 upp = TAILQ_LAST(&uh->head, unrhd);
585 if (upp != NULL && upp->ptr == NULL) {
586 uh->last += upp->len;
587 TAILQ_REMOVE(&uh->head, upp, list);
593 /* Try to make bitmaps */
594 while (optimize_unr(uh))
599 * Allocate a free unr.
602 alloc_unrl(struct unrhdr *uh)
609 mtx_assert(uh->mtx, MA_OWNED);
610 check_unrhdr(uh, __LINE__);
611 x = uh->low + uh->first;
613 up = TAILQ_FIRST(&uh->head);
616 * If we have an ideal split, just adjust the first+last
618 if (up == NULL && uh->last > 0) {
626 * We can always allocate from the first list element, so if we have
627 * nothing on the list, we must have run out of unit numbers.
632 KASSERT(up->ptr != uh, ("UNR first element is allocated"));
634 if (up->ptr == NULL) { /* free run */
637 } else { /* bitmap */
639 bit_ffc(ub->map, up->len, &y);
640 KASSERT(y != -1, ("UNR corruption: No clear bit in bitmap."));
645 collapse_unr(uh, up);
650 alloc_unr(struct unrhdr *uh)
662 alloc_unr_specificl(struct unrhdr *uh, u_int item, void **p1, void **p2)
664 struct unr *up, *upn;
668 mtx_assert(uh->mtx, MA_OWNED);
670 if (item < uh->low + uh->first || item > uh->high)
673 up = TAILQ_FIRST(&uh->head);
675 if (up == NULL && item - uh->low == uh->first) {
679 check_unrhdr(uh, __LINE__);
683 i = item - uh->low - uh->first;
686 up = new_unr(uh, p1, p2);
689 TAILQ_INSERT_TAIL(&uh->head, up, list);
690 up = new_unr(uh, p1, p2);
693 TAILQ_INSERT_TAIL(&uh->head, up, list);
694 uh->last = uh->high - uh->low - i;
696 check_unrhdr(uh, __LINE__);
699 /* Find the item which contains the unit we want to allocate. */
700 TAILQ_FOREACH(up, &uh->head, list) {
709 up = new_unr(uh, p1, p2);
712 TAILQ_INSERT_TAIL(&uh->head, up, list);
714 up = new_unr(uh, p1, p2);
717 TAILQ_INSERT_TAIL(&uh->head, up, list);
721 if (is_bitmap(uh, up)) {
723 if (bit_test(ub->map, i) == 0) {
728 } else if (up->ptr == uh)
731 KASSERT(up->ptr == NULL,
732 ("alloc_unr_specificl: up->ptr != NULL (up=%p)", up));
734 /* Split off the tail end, if any. */
735 tl = up->len - (1 + i);
737 upn = new_unr(uh, p1, p2);
740 TAILQ_INSERT_AFTER(&uh->head, up, upn, list);
743 /* Split off head end, if any */
745 upn = new_unr(uh, p1, p2);
748 TAILQ_INSERT_BEFORE(up, upn, list);
754 last = uh->high - uh->low - (item - uh->low);
758 collapse_unr(uh, up);
759 check_unrhdr(uh, __LINE__);
764 alloc_unr_specific(struct unrhdr *uh, u_int item)
769 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "alloc_unr_specific");
771 p1 = Malloc(sizeof(struct unr));
772 p2 = Malloc(sizeof(struct unr));
775 i = alloc_unr_specificl(uh, item, &p1, &p2);
789 * If we can save unrs by using a bitmap, do so.
792 free_unrl(struct unrhdr *uh, u_int item, void **p1, void **p2)
794 struct unr *up, *upp, *upn;
798 KASSERT(item >= uh->low && item <= uh->high,
799 ("UNR: free_unr(%u) out of range [%u...%u]",
800 item, uh->low, uh->high));
801 check_unrhdr(uh, __LINE__);
803 upp = TAILQ_FIRST(&uh->head);
805 * Freeing in the ideal split case
807 if (item + 1 == uh->first && upp == NULL) {
811 check_unrhdr(uh, __LINE__);
815 * Freeing in the ->first section. Create a run starting at the
816 * freed item. The code below will subdivide it.
818 if (item < uh->first) {
819 up = new_unr(uh, p1, p2);
821 up->len = uh->first - item;
822 TAILQ_INSERT_HEAD(&uh->head, up, list);
823 uh->first -= up->len;
828 /* Find the item which contains the unit we want to free */
829 TAILQ_FOREACH(up, &uh->head, list) {
835 /* Handle bitmap items */
836 if (is_bitmap(uh, up)) {
839 KASSERT(bit_test(ub->map, item) != 0,
840 ("UNR: Freeing free item %d (bitmap)\n", item));
841 bit_clear(ub->map, item);
843 collapse_unr(uh, up);
847 KASSERT(up->ptr == uh, ("UNR Freeing free item %d (run))\n", item));
849 /* Just this one left, reap it */
853 collapse_unr(uh, up);
857 /* Check if we can shift the item into the previous 'free' run */
858 upp = TAILQ_PREV(up, unrhd, list);
859 if (item == 0 && upp != NULL && upp->ptr == NULL) {
863 collapse_unr(uh, up);
867 /* Check if we can shift the item to the next 'free' run */
868 upn = TAILQ_NEXT(up, list);
869 if (item == up->len - 1 && upn != NULL && upn->ptr == NULL) {
873 collapse_unr(uh, up);
877 /* Split off the tail end, if any. */
878 pl = up->len - (1 + item);
880 upp = new_unr(uh, p1, p2);
883 TAILQ_INSERT_AFTER(&uh->head, up, upp, list);
886 /* Split off head end, if any */
888 upp = new_unr(uh, p1, p2);
891 TAILQ_INSERT_BEFORE(up, upp, list);
896 collapse_unr(uh, up);
900 free_unr(struct unrhdr *uh, u_int item)
904 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, "free_unr");
905 p1 = Malloc(sizeof(struct unr));
906 p2 = Malloc(sizeof(struct unr));
908 free_unrl(uh, item, &p1, &p2);
917 #ifndef _KERNEL /* USERLAND test driver */
920 * Simple stochastic test driver for the above functions. The code resides
921 * here so that it can access static functions and structures.
925 #define VPRINTF(...) {if (verbose) printf(__VA_ARGS__);}
928 print_unr(struct unrhdr *uh, struct unr *up)
933 printf(" %p len = %5u ", up, up->len);
936 else if (up->ptr == uh)
941 for (x = 0; x < up->len; x++) {
942 if (bit_test(ub->map, x))
952 print_unrhdr(struct unrhdr *uh)
958 "%p low = %u high = %u first = %u last = %u busy %u chunks = %u\n",
959 uh, uh->low, uh->high, uh->first, uh->last, uh->busy, uh->alloc);
960 x = uh->low + uh->first;
961 TAILQ_FOREACH(up, &uh->head, list) {
962 printf(" from = %5u", x);
964 if (up->ptr == NULL || up->ptr == uh)
972 test_alloc_unr(struct unrhdr *uh, u_int i, char a[])
977 VPRINTF("F %u\n", i);
985 VPRINTF("A %d\n", j);
992 test_alloc_unr_specific(struct unrhdr *uh, u_int i, char a[])
996 j = alloc_unr_specific(uh, i);
998 VPRINTF("F %u\n", i);
1003 VPRINTF("A %d\n", j);
1010 printf("%s [-h] [-r REPETITIONS] [-v]\n", argv[0]);
1014 main(int argc, char **argv)
1018 long count = 10000; /* Number of unrs to test */
1025 while ((ch = getopt(argc, argv, "hr:v")) != -1) {
1029 reps = strtol(optarg, NULL, 0);
1030 if (errno == ERANGE || errno == EINVAL) {
1046 setbuf(stdout, NULL);
1047 uh = new_unrhdr(0, count - 1, NULL);
1050 a = calloc(count, sizeof(char));
1052 err(1, "calloc failed");
1054 printf("sizeof(struct unr) %zu\n", sizeof(struct unr));
1055 printf("sizeof(struct unrb) %zu\n", sizeof(struct unrb));
1056 printf("sizeof(struct unrhdr) %zu\n", sizeof(struct unrhdr));
1057 printf("NBITS %lu\n", (unsigned long)NBITS);
1058 for (m = 0; m < count * reps; m++) {
1059 i = arc4random_uniform(count);
1061 if (a[i] && (j & 1))
1064 if ((arc4random() & 1) != 0)
1065 test_alloc_unr(uh, i, a);
1067 test_alloc_unr_specific(uh, i, a);
1071 check_unrhdr(uh, __LINE__);
1073 for (i = 0; i < (u_int)count; i++) {
1076 printf("C %u\n", i);