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