alloc: remove unused variable
[ccan] / ccan / alloc / alloc.c
1 #include <unistd.h>
2 #include <stdint.h>
3 #include <string.h>
4 #include <limits.h>
5 #include <assert.h>
6 #include <stdlib.h>
7 #include "alloc.h"
8 #include "bitops.h"
9 #include "tiny.h"
10 #include <ccan/build_assert/build_assert.h>
11 #include <ccan/likely/likely.h>
12 #include <ccan/alignof/alignof.h>
13 #include <ccan/short_types/short_types.h>
14 #include <ccan/compiler/compiler.h>
15 #include "config.h"
16
17 /*
18    Inspired by (and parts taken from) Andrew Tridgell's alloc_mmap:
19    http://samba.org/~tridge/junkcode/alloc_mmap/
20
21    Copyright (C) Andrew Tridgell 2007
22    
23    This library is free software; you can redistribute it and/or
24    modify it under the terms of the GNU Lesser General Public
25    License as published by the Free Software Foundation; either
26    version 2 of the License, or (at your option) any later version.
27
28    This library is distributed in the hope that it will be useful,
29    but WITHOUT ANY WARRANTY; without even the implied warranty of
30    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
31    Lesser General Public License for more details.
32
33    You should have received a copy of the GNU Lesser General Public
34    License along with this library; if not, write to the Free Software
35    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
36  */
37
38 /* We divide the pool into this many large pages (nearest power of 2) */
39 #define MAX_LARGE_PAGES (256UL)
40
41 /* 32 small pages == 1 large page. */
42 #define BITS_FROM_SMALL_TO_LARGE_PAGE 5
43
44 #define MAX_SMALL_PAGES (MAX_LARGE_PAGES << BITS_FROM_SMALL_TO_LARGE_PAGE)
45
46 /* Smallest pool size for this scheme: 128-byte small pages.  That's
47  * 9/13% overhead for 32/64 bit. */
48 #define MIN_USEFUL_SIZE (MAX_SMALL_PAGES * 128)
49
50 /* Every 4 buckets, we jump up a power of 2. ...8 10 12 14 16 20 24 28 32... */
51 #define INTER_BUCKET_SPACE 4
52
53 #define SMALL_PAGES_PER_LARGE_PAGE (1 << BITS_FROM_SMALL_TO_LARGE_PAGE)
54
55 /* FIXME: Figure this out properly. */
56 #define MAX_SIZE (1 << 30)
57
58 /* How few object to fit in a page before using a larger one? (8) */
59 #define MAX_PAGE_OBJECT_ORDER   3
60
61 #define BITS_PER_LONG (sizeof(long) * CHAR_BIT)
62
63 struct bucket_state {
64         u32 elements_per_page;
65         u16 page_list;
66         u16 full_list;
67 };
68
69 struct header {
70         /* Bitmap of which pages are large. */
71         unsigned long pagesize[MAX_LARGE_PAGES / BITS_PER_LONG];
72
73         /* List of unused small/large pages. */
74         u16 small_free_list;
75         u16 large_free_list;
76
77         /* List of huge allocs. */
78         unsigned long huge;
79
80         /* This is less defined: we have two buckets for each power of 2 */
81         struct bucket_state bs[1];
82 };
83
84 struct huge_alloc {
85         unsigned long next, prev;
86         unsigned long off, len;
87 };
88
89 struct page_header {
90         u16 next, prev;
91         /* FIXME: We can just count all-0 and all-1 used[] elements. */
92         unsigned elements_used : 25;
93         unsigned bucket : 7;
94         unsigned long used[1]; /* One bit per element. */
95 };
96
97 /*
98  * Every 4 buckets, the size doubles.
99  * Between buckets, sizes increase linearly.
100  *
101  * eg. bucket 40 = 2^10                 = 1024
102  *     bucket 41 = 2^10 + 2^10*4        = 1024 + 256
103  *     bucket 42 = 2^10 + 2^10*4        = 1024 + 512
104  *     bucket 43 = 2^10 + 2^10*4        = 1024 + 768
105  *     bucket 45 = 2^11                 = 2048
106  *
107  * Care is taken to handle low numbered buckets, at cost of overflow.
108  */
109 static unsigned long bucket_to_size(unsigned int bucket)
110 {
111         unsigned long base = 1UL << (bucket / INTER_BUCKET_SPACE);
112         return base + ((bucket % INTER_BUCKET_SPACE)
113                        << (bucket / INTER_BUCKET_SPACE))
114                 / INTER_BUCKET_SPACE;
115 }
116
117 /*
118  * Say size is 10.
119  *   fls(size/2) == 3.  1 << 3 == 8, so we're 2 too large, out of a possible
120  * 8 too large.  That's 1/4 of the way to the next power of 2 == 1 bucket.
121  *
122  * We make sure we round up.  Note that this fails on 32 bit at size
123  * 1879048193 (around bucket 120).
124  */
125 static unsigned int size_to_bucket(unsigned long size)
126 {
127         unsigned int base = fls(size/2);
128         unsigned long overshoot;
129
130         overshoot = size - (1UL << base);
131         return base * INTER_BUCKET_SPACE
132                 + ((overshoot * INTER_BUCKET_SPACE + (1UL << base)-1) >> base);
133 }
134
135 static unsigned int small_page_bits(unsigned long poolsize)
136 {
137         return fls(poolsize / MAX_SMALL_PAGES - 1);
138 }
139
140 static struct page_header *from_pgnum(struct header *head,
141                                       unsigned long pgnum,
142                                       unsigned sp_bits)
143 {
144         return (struct page_header *)((char *)head + (pgnum << sp_bits));
145 }
146
147 static u16 to_pgnum(struct header *head, void *p, unsigned sp_bits)
148 {
149         return ((char *)p - (char *)head) >> sp_bits;
150 }
151
152 static size_t used_size(unsigned int num_elements)
153 {
154         return align_up(num_elements, BITS_PER_LONG) / CHAR_BIT;
155 }
156
157 /*
158  * We always align the first entry to the lower power of 2.
159  * eg. the 12-byte bucket gets 8-byte aligned.  The 4096-byte bucket
160  * gets 4096-byte aligned.
161  */
162 static unsigned long page_header_size(unsigned int align_bits,
163                                       unsigned long num_elements)
164 {
165         unsigned long size;
166
167         size = sizeof(struct page_header)
168                 - sizeof(((struct page_header *)0)->used)
169                 + used_size(num_elements);
170         return align_up(size, 1UL << align_bits);
171 }
172
173 static void add_to_list(struct header *head,
174                         u16 *list, struct page_header *ph, unsigned sp_bits)
175 {
176         unsigned long h = *list, offset = to_pgnum(head, ph, sp_bits);
177
178         ph->next = h;
179         if (h) {
180                 struct page_header *prev = from_pgnum(head, h, sp_bits);
181                 assert(prev->prev == 0);
182                 prev->prev = offset;
183         }
184         *list = offset;
185         ph->prev = 0;
186 }
187
188 static void del_from_list(struct header *head,
189                           u16 *list, struct page_header *ph, unsigned sp_bits)
190 {
191         /* Front of list? */
192         if (ph->prev == 0) {
193                 *list = ph->next;
194         } else {
195                 struct page_header *prev = from_pgnum(head, ph->prev, sp_bits);
196                 prev->next = ph->next;
197         }
198         if (ph->next != 0) {
199                 struct page_header *next = from_pgnum(head, ph->next, sp_bits);
200                 next->prev = ph->prev;
201         }
202 }
203
204 static u16 pop_from_list(struct header *head,
205                                    u16 *list,
206                                    unsigned int sp_bits)
207 {
208         u16 h = *list;
209         struct page_header *ph = from_pgnum(head, h, sp_bits);
210
211         if (likely(h)) {
212                 *list = ph->next;
213                 if (*list)
214                         from_pgnum(head, *list, sp_bits)->prev = 0;
215         }
216         return h;
217 }
218
219 static void add_to_huge_list(struct header *head, struct huge_alloc *ha)
220 {
221         unsigned long h = head->huge;
222         unsigned long offset = (char *)ha - (char *)head;
223
224         ha->next = h;
225         if (h) {
226                 struct huge_alloc *prev = (void *)((char *)head + h);
227                 assert(prev->prev == 0);
228                 prev->prev = offset;
229         }
230         head->huge = offset;
231         ha->prev = 0;
232 }
233
234 static void del_from_huge(struct header *head, struct huge_alloc *ha)
235 {
236         /* Front of list? */
237         if (ha->prev == 0) {
238                 head->huge = ha->next;
239         } else {
240                 struct huge_alloc *prev = (void *)((char *)head + ha->prev);
241                 prev->next = ha->next;
242         }
243         if (ha->next != 0) {
244                 struct huge_alloc *next = (void *)((char *)head + ha->next);
245                 next->prev = ha->prev;
246         }
247 }
248
249 static void add_small_page_to_freelist(struct header *head,
250                                        struct page_header *ph,
251                                        unsigned int sp_bits)
252 {
253         add_to_list(head, &head->small_free_list, ph, sp_bits);
254 }
255
256 static void add_large_page_to_freelist(struct header *head,
257                                        struct page_header *ph,
258                                        unsigned int sp_bits)
259 {
260         add_to_list(head, &head->large_free_list, ph, sp_bits);
261 }
262
263 static void add_to_bucket_list(struct header *head,
264                                struct bucket_state *bs,
265                                struct page_header *ph,
266                                unsigned int sp_bits)
267 {
268         add_to_list(head, &bs->page_list, ph, sp_bits);
269 }
270
271 static void del_from_bucket_list(struct header *head,
272                                  struct bucket_state *bs,
273                                  struct page_header *ph,
274                                  unsigned int sp_bits)
275 {
276         del_from_list(head, &bs->page_list, ph, sp_bits);
277 }
278
279 static void del_from_bucket_full_list(struct header *head,
280                                       struct bucket_state *bs,
281                                       struct page_header *ph,
282                                       unsigned int sp_bits)
283 {
284         del_from_list(head, &bs->full_list, ph, sp_bits);
285 }
286
287 static void add_to_bucket_full_list(struct header *head,
288                                     struct bucket_state *bs,
289                                     struct page_header *ph,
290                                     unsigned int sp_bits)
291 {
292         add_to_list(head, &bs->full_list, ph, sp_bits);
293 }
294
295 static void clear_bit(unsigned long bitmap[], unsigned int off)
296 {
297         bitmap[off / BITS_PER_LONG] &= ~(1UL << (off % BITS_PER_LONG));
298 }
299
300 static bool test_bit(const unsigned long bitmap[], unsigned int off)
301 {
302         return bitmap[off / BITS_PER_LONG] & (1UL << (off % BITS_PER_LONG));
303 }
304
305 static void set_bit(unsigned long bitmap[], unsigned int off)
306 {
307         bitmap[off / BITS_PER_LONG] |= (1UL << (off % BITS_PER_LONG));
308 }
309
310 /* There must be a bit to be found. */
311 static unsigned int find_free_bit(const unsigned long bitmap[])
312 {
313         unsigned int i;
314
315         for (i = 0; bitmap[i] == -1UL; i++);
316         return (i*BITS_PER_LONG) + ffsl(~bitmap[i]) - 1;
317 }
318
319 /* How many elements can we fit in a page? */
320 static unsigned long elements_per_page(unsigned long align_bits,
321                                        unsigned long esize,
322                                        unsigned long psize)
323 {
324         unsigned long num, overhead;
325
326         /* First approximation: no extra room for bitmap. */
327         overhead = align_up(sizeof(struct page_header), 1UL << align_bits);
328         num = (psize - overhead) / esize;
329
330         while (page_header_size(align_bits, num) + esize * num > psize)
331                 num--;
332         return num;
333 }
334
335 static bool large_page_bucket(unsigned int bucket, unsigned int sp_bits)
336 {
337         unsigned long max_smallsize;
338
339         /* Note: this doesn't take into account page header. */
340         max_smallsize = (1UL << sp_bits) >> MAX_PAGE_OBJECT_ORDER;
341
342         return bucket_to_size(bucket) > max_smallsize;
343 }
344
345 static unsigned int max_bucket(unsigned int lp_bits)
346 {
347         return (lp_bits - MAX_PAGE_OBJECT_ORDER) * INTER_BUCKET_SPACE;
348 }
349
350 void alloc_init(void *pool, unsigned long poolsize)
351 {
352         struct header *head = pool;
353         struct page_header *ph;
354         unsigned int lp_bits, sp_bits, num_buckets;
355         unsigned long header_size, i;
356
357         if (poolsize < MIN_USEFUL_SIZE) {
358                 tiny_alloc_init(pool, poolsize);
359                 return;
360         }
361
362         /* We rely on page numbers fitting in 16 bit. */
363         BUILD_ASSERT(MAX_SMALL_PAGES < 65536);
364         
365         sp_bits = small_page_bits(poolsize);
366         lp_bits = sp_bits + BITS_FROM_SMALL_TO_LARGE_PAGE;
367
368         num_buckets = max_bucket(lp_bits);
369
370         head = pool;
371         header_size = sizeof(*head) + sizeof(head->bs) * (num_buckets-1);
372
373         memset(head, 0, header_size);
374         for (i = 0; i < num_buckets; i++) {
375                 unsigned long pagesize;
376
377                 if (large_page_bucket(i, sp_bits))
378                         pagesize = 1UL << lp_bits;
379                 else
380                         pagesize = 1UL << sp_bits;
381
382                 head->bs[i].elements_per_page
383                         = elements_per_page(i / INTER_BUCKET_SPACE,
384                                             bucket_to_size(i),
385                                             pagesize);
386         }
387
388         /* They start as all large pages. */
389         memset(head->pagesize, 0xFF, sizeof(head->pagesize));
390         /* FIXME: small pages for last bit? */
391
392         /* Split first page into small pages. */
393         assert(header_size < (1UL << lp_bits));
394         clear_bit(head->pagesize, 0);
395
396         /* Skip over page(s) used by header, add rest to free list */
397         for (i = align_up(header_size, (1UL << sp_bits)) >> sp_bits;
398              i < SMALL_PAGES_PER_LARGE_PAGE;
399              i++) {
400                 ph = from_pgnum(head, i, sp_bits);
401                 ph->elements_used = 0;
402                 add_small_page_to_freelist(head, ph, sp_bits);
403         }
404
405         /* Add the rest of the pages as large pages. */
406         i = SMALL_PAGES_PER_LARGE_PAGE;
407         while ((i << sp_bits) + (1UL << lp_bits) <= poolsize) {
408                 assert(i < MAX_SMALL_PAGES);
409                 ph = from_pgnum(head, i, sp_bits);
410                 ph->elements_used = 0;
411                 add_large_page_to_freelist(head, ph, sp_bits);
412                 i += SMALL_PAGES_PER_LARGE_PAGE;
413         }
414 }
415
416 /* A large page worth of small pages are free: delete them from free list. */
417 static void del_large_from_small_free_list(struct header *head,
418                                            struct page_header *ph,
419                                            unsigned int sp_bits)
420 {
421         unsigned long i;
422
423         for (i = 0; i < SMALL_PAGES_PER_LARGE_PAGE; i++) {
424                 del_from_list(head, &head->small_free_list,
425                               (void *)ph + (i << sp_bits),
426                               sp_bits);
427         }
428 }
429
430 static bool all_empty(struct header *head,
431                       unsigned long pgnum,
432                       unsigned sp_bits)
433 {
434         unsigned long i;
435
436         for (i = 0; i < SMALL_PAGES_PER_LARGE_PAGE; i++) {
437                 struct page_header *ph = from_pgnum(head, pgnum + i, sp_bits);
438                 if (ph->elements_used)
439                         return false;
440         }
441         return true;
442 }
443
444 static void recombine_small_pages(struct header *head, unsigned long poolsize,
445                                   unsigned int sp_bits)
446 {
447         unsigned long i;
448         unsigned int lp_bits = sp_bits + BITS_FROM_SMALL_TO_LARGE_PAGE;
449
450         /* Look for small pages to coalesce, after first large page. */
451         for (i = SMALL_PAGES_PER_LARGE_PAGE;
452              i < (poolsize >> lp_bits) << BITS_FROM_SMALL_TO_LARGE_PAGE;
453              i += SMALL_PAGES_PER_LARGE_PAGE) {
454                 /* Already a large page? */
455                 if (test_bit(head->pagesize, i / SMALL_PAGES_PER_LARGE_PAGE))
456                         continue;
457                 if (all_empty(head, i, sp_bits)) {
458                         struct page_header *ph = from_pgnum(head, i, sp_bits);
459                         set_bit(head->pagesize,
460                                 i / SMALL_PAGES_PER_LARGE_PAGE);
461                         del_large_from_small_free_list(head, ph, sp_bits);
462                         add_large_page_to_freelist(head, ph, sp_bits);
463                 }
464         }
465 }
466
467 static u16 get_large_page(struct header *head, unsigned long poolsize,
468                           unsigned int sp_bits)
469 {
470         unsigned int page;
471
472         page = pop_from_list(head, &head->large_free_list, sp_bits);
473         if (likely(page))
474                 return page;
475
476         recombine_small_pages(head, poolsize, sp_bits);
477
478         return pop_from_list(head, &head->large_free_list, sp_bits);
479 }
480
481 /* Returns small page. */
482 static unsigned long break_up_large_page(struct header *head,
483                                          unsigned int sp_bits,
484                                          u16 lpage)
485 {
486         unsigned int i;
487
488         clear_bit(head->pagesize, lpage >> BITS_FROM_SMALL_TO_LARGE_PAGE);
489
490         for (i = 1; i < SMALL_PAGES_PER_LARGE_PAGE; i++) {
491                 struct page_header *ph = from_pgnum(head, lpage + i, sp_bits);
492                 /* Initialize this: huge_alloc reads it. */
493                 ph->elements_used = 0;
494                 add_small_page_to_freelist(head, ph, sp_bits);
495         }
496
497         return lpage;
498 }
499
500 static u16 get_small_page(struct header *head, unsigned long poolsize,
501                           unsigned int sp_bits)
502 {
503         u16 ret;
504
505         ret = pop_from_list(head, &head->small_free_list, sp_bits);
506         if (likely(ret))
507                 return ret;
508         ret = get_large_page(head, poolsize, sp_bits);
509         if (likely(ret))
510                 ret = break_up_large_page(head, sp_bits, ret);
511         return ret;
512 }
513
514 static bool huge_allocated(struct header *head, unsigned long offset)
515 {
516         unsigned long i;
517         struct huge_alloc *ha;
518
519         for (i = head->huge; i; i = ha->next) {
520                 ha = (void *)((char *)head + i);
521                 if (ha->off <= offset && ha->off + ha->len > offset)
522                         return true;
523         }
524         return false;
525 }
526
527 /* They want something really big.  Aim for contiguous pages (slow). */
528 static COLD void *huge_alloc(void *pool, unsigned long poolsize,
529                              unsigned long size, unsigned long align)
530 {
531         struct header *head = pool;
532         struct huge_alloc *ha;
533         unsigned long i, sp_bits, lp_bits, num, header_size;
534
535         sp_bits = small_page_bits(poolsize);
536         lp_bits = sp_bits + BITS_FROM_SMALL_TO_LARGE_PAGE;
537
538         /* Allocate tracking structure optimistically. */
539         ha = alloc_get(pool, poolsize, sizeof(*ha), ALIGNOF(*ha));
540         if (!ha)
541                 return NULL;
542
543         /* First search for contiguous small pages... */
544         header_size = sizeof(*head) + sizeof(head->bs) * (max_bucket(lp_bits)-1);
545
546         num = 0;
547         for (i = (header_size + (1UL << sp_bits) - 1) >> sp_bits;
548              i << sp_bits < poolsize;
549              i++) {
550                 struct page_header *pg;
551                 unsigned long off = (i << sp_bits);
552
553                 /* Skip over large pages. */
554                 if (test_bit(head->pagesize, i >> BITS_FROM_SMALL_TO_LARGE_PAGE)) {
555                         i += (1UL << BITS_FROM_SMALL_TO_LARGE_PAGE)-1;
556                         continue;
557                 }
558
559                 /* Does this page meet alignment requirements? */
560                 if (!num && off % align != 0)
561                         continue;
562
563                 /* FIXME: This makes us O(n^2). */
564                 if (huge_allocated(head, off)) {
565                         num = 0;
566                         continue;
567                 }
568
569                 pg = (struct page_header *)((char *)head + off);
570                 if (pg->elements_used) {
571                         num = 0;
572                         continue;
573                 }
574
575                 num++;
576                 if (num << sp_bits >= size) {
577                         unsigned long pgnum;
578
579                         /* Remove from free list. */
580                         for (pgnum = i; pgnum > i - num; pgnum--) {
581                                 pg = from_pgnum(head, pgnum, sp_bits);
582                                 del_from_list(head,
583                                               &head->small_free_list,
584                                               pg, sp_bits);
585                         }
586                         ha->off = (i - num + 1) << sp_bits;
587                         ha->len = num << sp_bits;
588                         goto done;
589                 }
590         }
591
592         /* Now search for large pages... */
593         recombine_small_pages(head, poolsize, sp_bits);
594
595         num = 0;
596         for (i = (header_size + (1UL << lp_bits) - 1) >> lp_bits;
597              (i << lp_bits) < poolsize; i++) {
598                 struct page_header *pg;
599                 unsigned long off = (i << lp_bits);
600
601                 /* Ignore small pages. */
602                 if (!test_bit(head->pagesize, i))
603                         continue;
604
605                 /* Does this page meet alignment requirements? */
606                 if (!num && off % align != 0)
607                         continue;
608
609                 /* FIXME: This makes us O(n^2). */
610                 if (huge_allocated(head, off)) {
611                         num = 0;
612                         continue;
613                 }
614
615                 pg = (struct page_header *)((char *)head + off);
616                 if (pg->elements_used) {
617                         num = 0;
618                         continue;
619                 }
620
621                 num++;
622                 if (num << lp_bits >= size) {
623                         unsigned long pgnum;
624
625                         /* Remove from free list. */
626                         for (pgnum = i; pgnum > i - num; pgnum--) {
627                                 pg = from_pgnum(head, pgnum, lp_bits);
628                                 del_from_list(head,
629                                               &head->large_free_list,
630                                               pg, sp_bits);
631                         }
632                         ha->off = (i - num + 1) << lp_bits;
633                         ha->len = num << lp_bits;
634                         goto done;
635                 }
636         }
637
638         /* Unable to satisfy: free huge alloc structure. */
639         alloc_free(pool, poolsize, ha);
640         return NULL;
641
642 done:
643         add_to_huge_list(pool, ha);
644         return (char *)pool + ha->off;
645 }
646
647 static COLD void
648 huge_free(struct header *head, unsigned long poolsize, void *free)
649 {
650         unsigned long i, off, pgnum, free_off = (char *)free - (char *)head;
651         unsigned int sp_bits, lp_bits;
652         struct huge_alloc *ha;
653
654         for (i = head->huge; i; i = ha->next) {
655                 ha = (void *)((char *)head + i);
656                 if (free_off == ha->off)
657                         break;
658         }
659         assert(i);
660
661         /* Free up all the pages, delete and free ha */
662         sp_bits = small_page_bits(poolsize);
663         lp_bits = sp_bits + BITS_FROM_SMALL_TO_LARGE_PAGE;
664         pgnum = free_off >> sp_bits;
665
666         if (test_bit(head->pagesize, pgnum >> BITS_FROM_SMALL_TO_LARGE_PAGE)) {
667                 for (off = ha->off;
668                      off < ha->off + ha->len;
669                      off += 1UL << lp_bits) {
670                         add_large_page_to_freelist(head,
671                                                    (void *)((char *)head + off),
672                                                    sp_bits);
673                 }
674         } else {
675                 for (off = ha->off;
676                      off < ha->off + ha->len;
677                      off += 1UL << sp_bits) {
678                         add_small_page_to_freelist(head,
679                                                    (void *)((char *)head + off),
680                                                    sp_bits);
681                 }
682         }
683         del_from_huge(head, ha);
684         alloc_free(head, poolsize, ha);
685 }
686
687 static COLD unsigned long huge_size(struct header *head, void *p)
688 {
689         unsigned long i, off = (char *)p - (char *)head;
690         struct huge_alloc *ha;
691
692         for (i = head->huge; i; i = ha->next) {
693                 ha = (void *)((char *)head + i);
694                 if (off == ha->off) {
695                         return ha->len;
696                 }
697         }
698         abort();
699 }
700
701 void *alloc_get(void *pool, unsigned long poolsize,
702                 unsigned long size, unsigned long align)
703 {
704         struct header *head = pool;
705         unsigned int bucket;
706         unsigned long i;
707         struct bucket_state *bs;
708         struct page_header *ph;
709         unsigned int sp_bits;
710
711         if (poolsize < MIN_USEFUL_SIZE) {
712                 return tiny_alloc_get(pool, poolsize, size, align);
713         }
714
715         size = align_up(size, align);
716         if (unlikely(!size))
717                 size = 1;
718         bucket = size_to_bucket(size);
719
720         sp_bits = small_page_bits(poolsize);
721
722         if (bucket >= max_bucket(sp_bits + BITS_FROM_SMALL_TO_LARGE_PAGE)) {
723                 return huge_alloc(pool, poolsize, size, align);
724         }
725
726         bs = &head->bs[bucket];
727
728         if (!bs->page_list) {
729                 struct page_header *ph;
730
731                 if (large_page_bucket(bucket, sp_bits))
732                         bs->page_list = get_large_page(head, poolsize,
733                                                        sp_bits);
734                 else
735                         bs->page_list = get_small_page(head, poolsize,
736                                                        sp_bits);
737                 /* FIXME: Try large-aligned alloc?  Header stuffing? */
738                 if (unlikely(!bs->page_list))
739                         return NULL;
740                 ph = from_pgnum(head, bs->page_list, sp_bits);
741                 ph->bucket = bucket;
742                 ph->elements_used = 0;
743                 ph->next = 0;
744                 memset(ph->used, 0, used_size(bs->elements_per_page));
745         }
746
747         ph = from_pgnum(head, bs->page_list, sp_bits);
748
749         i = find_free_bit(ph->used);
750         set_bit(ph->used, i);
751         ph->elements_used++;
752
753         /* check if this page is now full */
754         if (unlikely(ph->elements_used == bs->elements_per_page)) {
755                 del_from_bucket_list(head, bs, ph, sp_bits);
756                 add_to_bucket_full_list(head, bs, ph, sp_bits);
757         }
758
759         return (char *)ph + page_header_size(ph->bucket / INTER_BUCKET_SPACE,
760                                              bs->elements_per_page)
761                + i * bucket_to_size(bucket);
762 }
763
764 void alloc_free(void *pool, unsigned long poolsize, void *free)
765 {
766         struct header *head = pool;
767         struct bucket_state *bs;
768         unsigned int sp_bits;
769         unsigned long i, pgnum, pgoffset, offset = (char *)free - (char *)pool;
770         bool smallpage;
771         struct page_header *ph;
772
773         if (poolsize < MIN_USEFUL_SIZE) {
774                 return tiny_alloc_free(pool, poolsize, free);
775         }
776         
777         /* Get page header. */
778         sp_bits = small_page_bits(poolsize);
779         pgnum = offset >> sp_bits;
780
781         /* Big page? Round down further. */
782         if (test_bit(head->pagesize, pgnum >> BITS_FROM_SMALL_TO_LARGE_PAGE)) {
783                 smallpage = false;
784                 pgnum &= ~(SMALL_PAGES_PER_LARGE_PAGE - 1);
785         } else
786                 smallpage = true;
787
788         /* Step back to page header. */
789         ph = from_pgnum(head, pgnum, sp_bits);
790         if ((void *)ph == free) {
791                 huge_free(head, poolsize, free);
792                 return;
793         }
794
795         bs = &head->bs[ph->bucket];
796         pgoffset = offset - (pgnum << sp_bits)
797                 - page_header_size(ph->bucket / INTER_BUCKET_SPACE,
798                                    bs->elements_per_page);
799
800         if (unlikely(ph->elements_used == bs->elements_per_page)) {
801                 del_from_bucket_full_list(head, bs, ph, sp_bits);
802                 add_to_bucket_list(head, bs, ph, sp_bits);
803         }
804
805         /* Which element are we? */
806         i = pgoffset / bucket_to_size(ph->bucket);
807         clear_bit(ph->used, i);
808         ph->elements_used--;
809
810         if (unlikely(ph->elements_used == 0)) {
811                 bs = &head->bs[ph->bucket];
812                 del_from_bucket_list(head, bs, ph, sp_bits);
813                 if (smallpage)
814                         add_small_page_to_freelist(head, ph, sp_bits);
815                 else
816                         add_large_page_to_freelist(head, ph, sp_bits);
817         }
818 }
819
820 unsigned long alloc_size(void *pool, unsigned long poolsize, void *p)
821 {
822         struct header *head = pool;
823         unsigned int pgnum, sp_bits;
824         unsigned long offset = (char *)p - (char *)pool;
825         struct page_header *ph;
826
827         if (poolsize < MIN_USEFUL_SIZE)
828                 return tiny_alloc_size(pool, poolsize, p);
829
830         /* Get page header. */
831         sp_bits = small_page_bits(poolsize);
832         pgnum = offset >> sp_bits;
833
834         /* Big page? Round down further. */
835         if (test_bit(head->pagesize, pgnum >> BITS_FROM_SMALL_TO_LARGE_PAGE))
836                 pgnum &= ~(SMALL_PAGES_PER_LARGE_PAGE - 1);
837
838         /* Step back to page header. */
839         ph = from_pgnum(head, pgnum, sp_bits);
840         if ((void *)ph == p)
841                 return huge_size(head, p);
842
843         return bucket_to_size(ph->bucket);
844 }
845
846 /* Useful for gdb breakpoints. */
847 static bool check_fail(void)
848 {
849         return false;
850 }
851
852 static unsigned long count_bits(const unsigned long bitmap[],
853                                 unsigned long limit)
854 {
855         unsigned long i, count = 0;
856
857         while (limit >= BITS_PER_LONG) {
858                 count += popcount(bitmap[0]);
859                 bitmap++;
860                 limit -= BITS_PER_LONG;
861         }
862
863         for (i = 0; i < limit; i++)
864                 if (test_bit(bitmap, i))
865                         count++;
866         return count;
867 }
868
869 static bool out_of_bounds(unsigned long pgnum,
870                           unsigned int sp_bits,
871                           unsigned long pagesize,
872                           unsigned long poolsize)
873 {
874         if (((pgnum << sp_bits) >> sp_bits) != pgnum)
875                 return true;
876
877         if ((pgnum << sp_bits) > poolsize)
878                 return true;
879
880         return ((pgnum << sp_bits) + pagesize > poolsize);
881 }
882
883 static bool check_bucket(struct header *head,
884                          unsigned long poolsize,
885                          unsigned long pages[],
886                          struct bucket_state *bs,
887                          unsigned int bindex)
888 {
889         bool lp_bucket;
890         struct page_header *ph;
891         unsigned long taken, i, prev, pagesize, sp_bits, lp_bits;
892
893         sp_bits = small_page_bits(poolsize);
894         lp_bits = sp_bits + BITS_FROM_SMALL_TO_LARGE_PAGE;
895
896         lp_bucket = large_page_bucket(bindex, sp_bits);
897
898         pagesize = 1UL << (lp_bucket ? lp_bits : sp_bits);
899
900         /* This many elements fit? */
901         taken = page_header_size(bindex / INTER_BUCKET_SPACE,
902                                  bs->elements_per_page);
903         taken += bucket_to_size(bindex) * bs->elements_per_page;
904         if (taken > pagesize)
905                 return check_fail();
906
907         /* One more wouldn't fit? */
908         taken = page_header_size(bindex / INTER_BUCKET_SPACE,
909                                  bs->elements_per_page + 1);
910         taken += bucket_to_size(bindex) * (bs->elements_per_page + 1);
911         if (taken <= pagesize)
912                 return check_fail();
913
914         /* Walk used list. */
915         prev = 0;
916         for (i = bs->page_list; i; i = ph->next) {
917                 /* Bad pointer? */
918                 if (out_of_bounds(i, sp_bits, pagesize, poolsize))
919                         return check_fail();
920                 /* Wrong size page? */
921                 if (!!test_bit(head->pagesize, i >> BITS_FROM_SMALL_TO_LARGE_PAGE)
922                     != lp_bucket)
923                         return check_fail();
924                 /* Large page not on boundary? */
925                 if (lp_bucket && (i % SMALL_PAGES_PER_LARGE_PAGE) != 0)
926                         return check_fail();
927                 ph = from_pgnum(head, i, sp_bits);
928                 /* Linked list corrupt? */
929                 if (ph->prev != prev)
930                         return check_fail();
931                 /* Already seen this page? */
932                 if (test_bit(pages, i))
933                         return check_fail();
934                 set_bit(pages, i);
935                 /* Empty or full? */
936                 if (ph->elements_used == 0)
937                         return check_fail();
938                 if (ph->elements_used >= bs->elements_per_page)
939                         return check_fail();
940                 /* Used bits don't agree? */
941                 if (ph->elements_used != count_bits(ph->used,
942                                                     bs->elements_per_page))
943                         return check_fail();
944                 /* Wrong bucket? */
945                 if (ph->bucket != bindex)
946                         return check_fail();
947                 prev = i;
948         }
949
950         /* Walk full list. */
951         prev = 0;
952         for (i = bs->full_list; i; i = ph->next) {
953                 /* Bad pointer? */
954                 if (out_of_bounds(i, sp_bits, pagesize, poolsize))
955                         return check_fail();
956                 /* Wrong size page? */
957                 if (!!test_bit(head->pagesize, i >> BITS_FROM_SMALL_TO_LARGE_PAGE)
958                     != lp_bucket)
959                 /* Large page not on boundary? */
960                 if (lp_bucket && (i % SMALL_PAGES_PER_LARGE_PAGE) != 0)
961                         return check_fail();
962                 ph = from_pgnum(head, i, sp_bits);
963                 /* Linked list corrupt? */
964                 if (ph->prev != prev)
965                         return check_fail();
966                 /* Already seen this page? */
967                 if (test_bit(pages, i))
968                         return check_fail();
969                 set_bit(pages, i);
970                 /* Not full? */
971                 if (ph->elements_used != bs->elements_per_page)
972                         return check_fail();
973                 /* Used bits don't agree? */
974                 if (ph->elements_used != count_bits(ph->used,
975                                                     bs->elements_per_page))
976                         return check_fail();
977                 /* Wrong bucket? */
978                 if (ph->bucket != bindex)
979                         return check_fail();
980                 prev = i;
981         }
982         return true;
983 }
984
985 bool alloc_check(void *pool, unsigned long poolsize)
986 {
987         struct header *head = pool;
988         unsigned long prev, i, lp_bits, sp_bits, header_size, num_buckets;
989         struct page_header *ph;
990         struct huge_alloc *ha;
991         unsigned long pages[MAX_SMALL_PAGES / BITS_PER_LONG] = { 0 };
992
993         if (poolsize < MIN_USEFUL_SIZE)
994                 return tiny_alloc_check(pool, poolsize);
995
996         sp_bits = small_page_bits(poolsize);
997         lp_bits = sp_bits + BITS_FROM_SMALL_TO_LARGE_PAGE;
998
999         num_buckets = max_bucket(lp_bits);
1000
1001         header_size = sizeof(*head) + sizeof(head->bs) * (num_buckets-1);
1002
1003         /* First, set all bits taken by header. */
1004         for (i = 0; i < header_size; i += (1UL << sp_bits))
1005                 set_bit(pages, i >> sp_bits);
1006
1007         /* Check small page free list. */
1008         prev = 0;
1009         for (i = head->small_free_list; i; i = ph->next) {
1010                 /* Bad pointer? */
1011                 if (out_of_bounds(i, sp_bits, 1UL << sp_bits, poolsize))
1012                         return check_fail();
1013                 /* Large page? */
1014                 if (test_bit(head->pagesize, i >> BITS_FROM_SMALL_TO_LARGE_PAGE))
1015                         return check_fail();
1016                 ph = from_pgnum(head, i, sp_bits);
1017                 /* Linked list corrupt? */
1018                 if (ph->prev != prev)
1019                         return check_fail();
1020                 /* Already seen this page? */
1021                 if (test_bit(pages, i))
1022                         return check_fail();
1023                 set_bit(pages, i);
1024                 prev = i;
1025         }
1026
1027         /* Check large page free list. */
1028         prev = 0;
1029         for (i = head->large_free_list; i; i = ph->next) {
1030                 /* Bad pointer? */
1031                 if (out_of_bounds(i, sp_bits, 1UL << lp_bits, poolsize))
1032                         return check_fail();
1033                 /* Not large page? */
1034                 if (!test_bit(head->pagesize, i >> BITS_FROM_SMALL_TO_LARGE_PAGE))
1035                         return check_fail();
1036                 /* Not page boundary? */
1037                 if ((i % SMALL_PAGES_PER_LARGE_PAGE) != 0)
1038                         return check_fail();
1039                 ph = from_pgnum(head, i, sp_bits);
1040                 /* Linked list corrupt? */
1041                 if (ph->prev != prev)
1042                         return check_fail();
1043                 /* Already seen this page? */
1044                 if (test_bit(pages, i))
1045                         return check_fail();
1046                 set_bit(pages, i);
1047                 prev = i;
1048         }
1049
1050         /* Check the buckets. */
1051         for (i = 0; i < max_bucket(lp_bits); i++) {
1052                 struct bucket_state *bs = &head->bs[i];
1053
1054                 if (!check_bucket(head, poolsize, pages, bs, i))
1055                         return false;
1056         }
1057
1058         /* Check the huge alloc list. */
1059         prev = 0;
1060         for (i = head->huge; i; i = ha->next) {
1061                 unsigned long pgbits, j;
1062
1063                 /* Bad pointer? */
1064                 if (i >= poolsize || i + sizeof(*ha) > poolsize)
1065                         return check_fail();
1066                 ha = (void *)((char *)head + i);
1067
1068                 /* Check contents of ha. */
1069                 if (ha->off > poolsize || ha->off + ha->len > poolsize)
1070                         return check_fail();
1071
1072                 /* Large or small page? */
1073                 pgbits = test_bit(head->pagesize, ha->off >> lp_bits)
1074                         ? lp_bits : sp_bits;
1075
1076                 /* Not page boundary? */
1077                 if ((ha->off % (1UL << pgbits)) != 0)
1078                         return check_fail();
1079
1080                 /* Not page length? */
1081                 if ((ha->len % (1UL << pgbits)) != 0)
1082                         return check_fail();
1083
1084                 /* Linked list corrupt? */
1085                 if (ha->prev != prev)
1086                         return check_fail();
1087
1088                 for (j = ha->off; j < ha->off + ha->len; j += (1UL<<sp_bits)) {
1089                         /* Already seen this page? */
1090                         if (test_bit(pages, j >> sp_bits))
1091                                 return check_fail();
1092                         set_bit(pages, j >> sp_bits);
1093                 }
1094
1095                 prev = i;
1096         }
1097                 
1098         /* Make sure every page accounted for. */
1099         for (i = 0; i < poolsize >> sp_bits; i++) {
1100                 if (!test_bit(pages, i))
1101                         return check_fail();
1102                 if (test_bit(head->pagesize,
1103                              i >> BITS_FROM_SMALL_TO_LARGE_PAGE)) {
1104                         /* Large page, skip rest. */
1105                         i += SMALL_PAGES_PER_LARGE_PAGE - 1;
1106                 }
1107         }
1108
1109         return true;
1110 }
1111
1112 static unsigned long print_overhead(FILE *out, const char *desc,
1113                                     unsigned long bytes,
1114                                     unsigned long poolsize)
1115 {
1116         fprintf(out, "Overhead (%s): %lu bytes (%.3g%%)\n",
1117                 desc, bytes, 100.0 * bytes / poolsize);
1118         return bytes;
1119 }
1120
1121 static unsigned long count_list(struct header *head,
1122                                 u16 pgnum,
1123                                 unsigned int sp_bits,
1124                                 unsigned long *total_elems)
1125 {
1126         struct page_header *p;
1127         unsigned long ret = 0;
1128
1129         while (pgnum) {
1130                 p = from_pgnum(head, pgnum, sp_bits);
1131                 if (total_elems)
1132                         (*total_elems) += p->elements_used;
1133                 ret++;
1134                 pgnum = p->next;
1135         }
1136         return ret;
1137 }
1138
1139 static unsigned long visualize_bucket(FILE *out, struct header *head,
1140                                       unsigned int bucket,
1141                                       unsigned long poolsize,
1142                                       unsigned int sp_bits)
1143 {
1144         unsigned long num_full, num_partial, num_pages, page_size,
1145                 elems, hdr_min, hdr_size, elems_per_page, overhead = 0;
1146
1147         elems_per_page = head->bs[bucket].elements_per_page;
1148
1149         /* If we used byte-based bitmaps, we could get pg hdr to: */
1150         hdr_min = sizeof(struct page_header)
1151                 - sizeof(((struct page_header *)0)->used)
1152                 + align_up(elems_per_page, CHAR_BIT) / CHAR_BIT;
1153         hdr_size = page_header_size(bucket / INTER_BUCKET_SPACE,
1154                                     elems_per_page);
1155
1156         elems = 0;
1157         num_full = count_list(head, head->bs[bucket].full_list, sp_bits,
1158                               &elems);
1159         num_partial = count_list(head, head->bs[bucket].page_list, sp_bits,
1160                                  &elems);
1161         num_pages = num_full + num_partial;
1162         if (!num_pages)
1163                 return 0;
1164
1165         fprintf(out, "Bucket %u (%lu bytes):"
1166                 " %lu full, %lu partial = %lu elements\n",
1167                 bucket, bucket_to_size(bucket), num_full, num_partial, elems);
1168         /* Strict requirement of page header size. */
1169         overhead += print_overhead(out, "page headers",
1170                                    hdr_min * num_pages, poolsize);
1171         /* Gap between minimal page header and actual start. */
1172         overhead += print_overhead(out, "page post-header alignments",
1173                                    (hdr_size - hdr_min) * num_pages, poolsize);
1174         /* Between last element and end of page. */
1175         page_size = (1UL << sp_bits);
1176         if (large_page_bucket(bucket, sp_bits))
1177                 page_size <<= BITS_FROM_SMALL_TO_LARGE_PAGE;
1178
1179         overhead += print_overhead(out, "page tails",
1180                                    (page_size - (hdr_size
1181                                                  + (elems_per_page
1182                                                     * bucket_to_size(bucket))))
1183                                    * num_pages, poolsize);
1184         return overhead;
1185 }
1186
1187 void alloc_visualize(FILE *out, void *pool, unsigned long poolsize)
1188 {
1189         struct header *head = pool;
1190         unsigned long i, lp_bits, sp_bits, header_size, num_buckets, count,
1191                 overhead = 0;
1192
1193         fprintf(out, "Pool %p size %lu: (%s allocator)\n", pool, poolsize,
1194                 poolsize < MIN_USEFUL_SIZE ? "tiny" : "standard");
1195
1196         if (poolsize < MIN_USEFUL_SIZE) {
1197                 tiny_alloc_visualize(out, pool, poolsize);
1198                 return;
1199         }
1200         
1201         sp_bits = small_page_bits(poolsize);
1202         lp_bits = sp_bits + BITS_FROM_SMALL_TO_LARGE_PAGE;
1203
1204         num_buckets = max_bucket(lp_bits);
1205         header_size = sizeof(*head) + sizeof(head->bs) * (num_buckets-1);
1206
1207         fprintf(out, "Large page size %lu, small page size %lu.\n",
1208                 1UL << lp_bits, 1UL << sp_bits);
1209         overhead += print_overhead(out, "unused pool tail",
1210                                    poolsize % (1UL << lp_bits), poolsize);
1211         fprintf(out, "Main header %lu bytes (%lu small pages).\n",
1212                 header_size, align_up(header_size, 1UL << sp_bits) >> sp_bits);
1213         overhead += print_overhead(out, "partial header page",
1214                                    align_up(header_size, 1UL << sp_bits)
1215                                    - header_size, poolsize);
1216         /* Total large pages. */
1217         i = count_bits(head->pagesize, poolsize >> lp_bits);
1218         /* Used pages. */
1219         count = i - count_list(head, head->large_free_list, sp_bits, NULL);
1220         fprintf(out, "%lu/%lu large pages used (%.3g%%)\n",
1221                 count, i, count ? 100.0 * count / i : 0.0);
1222
1223         /* Total small pages. */
1224         i = ((poolsize >> lp_bits) - i) << BITS_FROM_SMALL_TO_LARGE_PAGE;
1225         /* Used pages */
1226         count = i - count_list(head, head->small_free_list, sp_bits, NULL);
1227         fprintf(out, "%lu/%lu small pages used (%.3g%%)\n",
1228                 count, i, count ? 100.0 * count / i : 0.0);
1229
1230         /* Summary of each bucket. */
1231         fprintf(out, "%lu buckets:\n", num_buckets);
1232         for (i = 0; i < num_buckets; i++)
1233                 overhead += visualize_bucket(out, head, i, poolsize, sp_bits);
1234
1235         print_overhead(out, "total", overhead, poolsize);
1236 }