Merge tag 'mmc-2021-2-19' of https://gitlab.denx.de/u-boot/custodians/u-boot-mmc
[pandora-u-boot.git] / common / dlmalloc.c
1 #include <common.h>
2 #include <log.h>
3 #include <asm/global_data.h>
4
5 #if CONFIG_IS_ENABLED(UNIT_TEST)
6 #define DEBUG
7 #endif
8
9 #include <malloc.h>
10 #include <asm/io.h>
11
12 #ifdef DEBUG
13 #if __STD_C
14 static void malloc_update_mallinfo (void);
15 void malloc_stats (void);
16 #else
17 static void malloc_update_mallinfo ();
18 void malloc_stats();
19 #endif
20 #endif  /* DEBUG */
21
22 DECLARE_GLOBAL_DATA_PTR;
23
24 /*
25   Emulation of sbrk for WIN32
26   All code within the ifdef WIN32 is untested by me.
27
28   Thanks to Martin Fong and others for supplying this.
29 */
30
31
32 #ifdef WIN32
33
34 #define AlignPage(add) (((add) + (malloc_getpagesize-1)) & \
35 ~(malloc_getpagesize-1))
36 #define AlignPage64K(add) (((add) + (0x10000 - 1)) & ~(0x10000 - 1))
37
38 /* resrve 64MB to insure large contiguous space */
39 #define RESERVED_SIZE (1024*1024*64)
40 #define NEXT_SIZE (2048*1024)
41 #define TOP_MEMORY ((unsigned long)2*1024*1024*1024)
42
43 struct GmListElement;
44 typedef struct GmListElement GmListElement;
45
46 struct GmListElement
47 {
48         GmListElement* next;
49         void* base;
50 };
51
52 static GmListElement* head = 0;
53 static unsigned int gNextAddress = 0;
54 static unsigned int gAddressBase = 0;
55 static unsigned int gAllocatedSize = 0;
56
57 static
58 GmListElement* makeGmListElement (void* bas)
59 {
60         GmListElement* this;
61         this = (GmListElement*)(void*)LocalAlloc (0, sizeof (GmListElement));
62         assert (this);
63         if (this)
64         {
65                 this->base = bas;
66                 this->next = head;
67                 head = this;
68         }
69         return this;
70 }
71
72 void gcleanup ()
73 {
74         BOOL rval;
75         assert ( (head == NULL) || (head->base == (void*)gAddressBase));
76         if (gAddressBase && (gNextAddress - gAddressBase))
77         {
78                 rval = VirtualFree ((void*)gAddressBase,
79                                                         gNextAddress - gAddressBase,
80                                                         MEM_DECOMMIT);
81         assert (rval);
82         }
83         while (head)
84         {
85                 GmListElement* next = head->next;
86                 rval = VirtualFree (head->base, 0, MEM_RELEASE);
87                 assert (rval);
88                 LocalFree (head);
89                 head = next;
90         }
91 }
92
93 static
94 void* findRegion (void* start_address, unsigned long size)
95 {
96         MEMORY_BASIC_INFORMATION info;
97         if (size >= TOP_MEMORY) return NULL;
98
99         while ((unsigned long)start_address + size < TOP_MEMORY)
100         {
101                 VirtualQuery (start_address, &info, sizeof (info));
102                 if ((info.State == MEM_FREE) && (info.RegionSize >= size))
103                         return start_address;
104                 else
105                 {
106                         /* Requested region is not available so see if the */
107                         /* next region is available.  Set 'start_address' */
108                         /* to the next region and call 'VirtualQuery()' */
109                         /* again. */
110
111                         start_address = (char*)info.BaseAddress + info.RegionSize;
112
113                         /* Make sure we start looking for the next region */
114                         /* on the *next* 64K boundary.  Otherwise, even if */
115                         /* the new region is free according to */
116                         /* 'VirtualQuery()', the subsequent call to */
117                         /* 'VirtualAlloc()' (which follows the call to */
118                         /* this routine in 'wsbrk()') will round *down* */
119                         /* the requested address to a 64K boundary which */
120                         /* we already know is an address in the */
121                         /* unavailable region.  Thus, the subsequent call */
122                         /* to 'VirtualAlloc()' will fail and bring us back */
123                         /* here, causing us to go into an infinite loop. */
124
125                         start_address =
126                                 (void *) AlignPage64K((unsigned long) start_address);
127                 }
128         }
129         return NULL;
130
131 }
132
133
134 void* wsbrk (long size)
135 {
136         void* tmp;
137         if (size > 0)
138         {
139                 if (gAddressBase == 0)
140                 {
141                         gAllocatedSize = max (RESERVED_SIZE, AlignPage (size));
142                         gNextAddress = gAddressBase =
143                                 (unsigned int)VirtualAlloc (NULL, gAllocatedSize,
144                                                                                         MEM_RESERVE, PAGE_NOACCESS);
145                 } else if (AlignPage (gNextAddress + size) > (gAddressBase +
146 gAllocatedSize))
147                 {
148                         long new_size = max (NEXT_SIZE, AlignPage (size));
149                         void* new_address = (void*)(gAddressBase+gAllocatedSize);
150                         do
151                         {
152                                 new_address = findRegion (new_address, new_size);
153
154                                 if (!new_address)
155                                         return (void*)-1;
156
157                                 gAddressBase = gNextAddress =
158                                         (unsigned int)VirtualAlloc (new_address, new_size,
159                                                                                                 MEM_RESERVE, PAGE_NOACCESS);
160                                 /* repeat in case of race condition */
161                                 /* The region that we found has been snagged */
162                                 /* by another thread */
163                         }
164                         while (gAddressBase == 0);
165
166                         assert (new_address == (void*)gAddressBase);
167
168                         gAllocatedSize = new_size;
169
170                         if (!makeGmListElement ((void*)gAddressBase))
171                                 return (void*)-1;
172                 }
173                 if ((size + gNextAddress) > AlignPage (gNextAddress))
174                 {
175                         void* res;
176                         res = VirtualAlloc ((void*)AlignPage (gNextAddress),
177                                                                 (size + gNextAddress -
178                                                                  AlignPage (gNextAddress)),
179                                                                 MEM_COMMIT, PAGE_READWRITE);
180                         if (!res)
181                                 return (void*)-1;
182                 }
183                 tmp = (void*)gNextAddress;
184                 gNextAddress = (unsigned int)tmp + size;
185                 return tmp;
186         }
187         else if (size < 0)
188         {
189                 unsigned int alignedGoal = AlignPage (gNextAddress + size);
190                 /* Trim by releasing the virtual memory */
191                 if (alignedGoal >= gAddressBase)
192                 {
193                         VirtualFree ((void*)alignedGoal, gNextAddress - alignedGoal,
194                                                  MEM_DECOMMIT);
195                         gNextAddress = gNextAddress + size;
196                         return (void*)gNextAddress;
197                 }
198                 else
199                 {
200                         VirtualFree ((void*)gAddressBase, gNextAddress - gAddressBase,
201                                                  MEM_DECOMMIT);
202                         gNextAddress = gAddressBase;
203                         return (void*)-1;
204                 }
205         }
206         else
207         {
208                 return (void*)gNextAddress;
209         }
210 }
211
212 #endif
213
214
215
216 /*
217   Type declarations
218 */
219
220
221 struct malloc_chunk
222 {
223   INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
224   INTERNAL_SIZE_T size;      /* Size in bytes, including overhead. */
225   struct malloc_chunk* fd;   /* double links -- used only if free. */
226   struct malloc_chunk* bk;
227 } __attribute__((__may_alias__)) ;
228
229 typedef struct malloc_chunk* mchunkptr;
230
231 /*
232
233    malloc_chunk details:
234
235     (The following includes lightly edited explanations by Colin Plumb.)
236
237     Chunks of memory are maintained using a `boundary tag' method as
238     described in e.g., Knuth or Standish.  (See the paper by Paul
239     Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
240     survey of such techniques.)  Sizes of free chunks are stored both
241     in the front of each chunk and at the end.  This makes
242     consolidating fragmented chunks into bigger chunks very fast.  The
243     size fields also hold bits representing whether chunks are free or
244     in use.
245
246     An allocated chunk looks like this:
247
248
249     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
250             |             Size of previous chunk, if allocated            | |
251             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
252             |             Size of chunk, in bytes                         |P|
253       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
254             |             User data starts here...                          .
255             .                                                               .
256             .             (malloc_usable_space() bytes)                     .
257             .                                                               |
258 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
259             |             Size of chunk                                     |
260             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
261
262
263     Where "chunk" is the front of the chunk for the purpose of most of
264     the malloc code, but "mem" is the pointer that is returned to the
265     user.  "Nextchunk" is the beginning of the next contiguous chunk.
266
267     Chunks always begin on even word boundries, so the mem portion
268     (which is returned to the user) is also on an even word boundary, and
269     thus double-word aligned.
270
271     Free chunks are stored in circular doubly-linked lists, and look like this:
272
273     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
274             |             Size of previous chunk                            |
275             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
276     `head:' |             Size of chunk, in bytes                         |P|
277       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
278             |             Forward pointer to next chunk in list             |
279             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
280             |             Back pointer to previous chunk in list            |
281             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
282             |             Unused space (may be 0 bytes long)                .
283             .                                                               .
284             .                                                               |
285
286 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
287     `foot:' |             Size of chunk, in bytes                           |
288             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
289
290     The P (PREV_INUSE) bit, stored in the unused low-order bit of the
291     chunk size (which is always a multiple of two words), is an in-use
292     bit for the *previous* chunk.  If that bit is *clear*, then the
293     word before the current chunk size contains the previous chunk
294     size, and can be used to find the front of the previous chunk.
295     (The very first chunk allocated always has this bit set,
296     preventing access to non-existent (or non-owned) memory.)
297
298     Note that the `foot' of the current chunk is actually represented
299     as the prev_size of the NEXT chunk. (This makes it easier to
300     deal with alignments etc).
301
302     The two exceptions to all this are
303
304      1. The special chunk `top', which doesn't bother using the
305         trailing size field since there is no
306         next contiguous chunk that would have to index off it. (After
307         initialization, `top' is forced to always exist.  If it would
308         become less than MINSIZE bytes long, it is replenished via
309         malloc_extend_top.)
310
311      2. Chunks allocated via mmap, which have the second-lowest-order
312         bit (IS_MMAPPED) set in their size fields.  Because they are
313         never merged or traversed from any other chunk, they have no
314         foot size or inuse information.
315
316     Available chunks are kept in any of several places (all declared below):
317
318     * `av': An array of chunks serving as bin headers for consolidated
319        chunks. Each bin is doubly linked.  The bins are approximately
320        proportionally (log) spaced.  There are a lot of these bins
321        (128). This may look excessive, but works very well in
322        practice.  All procedures maintain the invariant that no
323        consolidated chunk physically borders another one. Chunks in
324        bins are kept in size order, with ties going to the
325        approximately least recently used chunk.
326
327        The chunks in each bin are maintained in decreasing sorted order by
328        size.  This is irrelevant for the small bins, which all contain
329        the same-sized chunks, but facilitates best-fit allocation for
330        larger chunks. (These lists are just sequential. Keeping them in
331        order almost never requires enough traversal to warrant using
332        fancier ordered data structures.)  Chunks of the same size are
333        linked with the most recently freed at the front, and allocations
334        are taken from the back.  This results in LRU or FIFO allocation
335        order, which tends to give each chunk an equal opportunity to be
336        consolidated with adjacent freed chunks, resulting in larger free
337        chunks and less fragmentation.
338
339     * `top': The top-most available chunk (i.e., the one bordering the
340        end of available memory) is treated specially. It is never
341        included in any bin, is used only if no other chunk is
342        available, and is released back to the system if it is very
343        large (see M_TRIM_THRESHOLD).
344
345     * `last_remainder': A bin holding only the remainder of the
346        most recently split (non-top) chunk. This bin is checked
347        before other non-fitting chunks, so as to provide better
348        locality for runs of sequentially allocated chunks.
349
350     *  Implicitly, through the host system's memory mapping tables.
351        If supported, requests greater than a threshold are usually
352        serviced via calls to mmap, and then later released via munmap.
353
354 */
355
356 /*  sizes, alignments */
357
358 #define SIZE_SZ                (sizeof(INTERNAL_SIZE_T))
359 #define MALLOC_ALIGNMENT       (SIZE_SZ + SIZE_SZ)
360 #define MALLOC_ALIGN_MASK      (MALLOC_ALIGNMENT - 1)
361 #define MINSIZE                (sizeof(struct malloc_chunk))
362
363 /* conversion from malloc headers to user pointers, and back */
364
365 #define chunk2mem(p)   ((Void_t*)((char*)(p) + 2*SIZE_SZ))
366 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
367
368 /* pad request bytes into a usable size */
369
370 #define request2size(req) \
371  (((long)((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) < \
372   (long)(MINSIZE + MALLOC_ALIGN_MASK)) ? MINSIZE : \
373    (((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) & ~(MALLOC_ALIGN_MASK)))
374
375 /* Check if m has acceptable alignment */
376
377 #define aligned_OK(m)    (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
378
379
380
381
382 /*
383   Physical chunk operations
384 */
385
386
387 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
388
389 #define PREV_INUSE 0x1
390
391 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
392
393 #define IS_MMAPPED 0x2
394
395 /* Bits to mask off when extracting size */
396
397 #define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
398
399
400 /* Ptr to next physical malloc_chunk. */
401
402 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
403
404 /* Ptr to previous physical malloc_chunk */
405
406 #define prev_chunk(p)\
407    ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
408
409
410 /* Treat space at ptr + offset as a chunk */
411
412 #define chunk_at_offset(p, s)  ((mchunkptr)(((char*)(p)) + (s)))
413
414
415
416
417 /*
418   Dealing with use bits
419 */
420
421 /* extract p's inuse bit */
422
423 #define inuse(p)\
424 ((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
425
426 /* extract inuse bit of previous chunk */
427
428 #define prev_inuse(p)  ((p)->size & PREV_INUSE)
429
430 /* check for mmap()'ed chunk */
431
432 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
433
434 /* set/clear chunk as in use without otherwise disturbing */
435
436 #define set_inuse(p)\
437 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
438
439 #define clear_inuse(p)\
440 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
441
442 /* check/set/clear inuse bits in known places */
443
444 #define inuse_bit_at_offset(p, s)\
445  (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
446
447 #define set_inuse_bit_at_offset(p, s)\
448  (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
449
450 #define clear_inuse_bit_at_offset(p, s)\
451  (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
452
453
454
455
456 /*
457   Dealing with size fields
458 */
459
460 /* Get size, ignoring use bits */
461
462 #define chunksize(p)          ((p)->size & ~(SIZE_BITS))
463
464 /* Set size at head, without disturbing its use bit */
465
466 #define set_head_size(p, s)   ((p)->size = (((p)->size & PREV_INUSE) | (s)))
467
468 /* Set size/use ignoring previous bits in header */
469
470 #define set_head(p, s)        ((p)->size = (s))
471
472 /* Set size at footer (only when chunk is not in use) */
473
474 #define set_foot(p, s)   (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
475
476
477
478
479
480 /*
481    Bins
482
483     The bins, `av_' are an array of pairs of pointers serving as the
484     heads of (initially empty) doubly-linked lists of chunks, laid out
485     in a way so that each pair can be treated as if it were in a
486     malloc_chunk. (This way, the fd/bk offsets for linking bin heads
487     and chunks are the same).
488
489     Bins for sizes < 512 bytes contain chunks of all the same size, spaced
490     8 bytes apart. Larger bins are approximately logarithmically
491     spaced. (See the table below.) The `av_' array is never mentioned
492     directly in the code, but instead via bin access macros.
493
494     Bin layout:
495
496     64 bins of size       8
497     32 bins of size      64
498     16 bins of size     512
499      8 bins of size    4096
500      4 bins of size   32768
501      2 bins of size  262144
502      1 bin  of size what's left
503
504     There is actually a little bit of slop in the numbers in bin_index
505     for the sake of speed. This makes no difference elsewhere.
506
507     The special chunks `top' and `last_remainder' get their own bins,
508     (this is implemented via yet more trickery with the av_ array),
509     although `top' is never properly linked to its bin since it is
510     always handled specially.
511
512 */
513
514 #define NAV             128   /* number of bins */
515
516 typedef struct malloc_chunk* mbinptr;
517
518 /* access macros */
519
520 #define bin_at(i)      ((mbinptr)((char*)&(av_[2*(i) + 2]) - 2*SIZE_SZ))
521 #define next_bin(b)    ((mbinptr)((char*)(b) + 2 * sizeof(mbinptr)))
522 #define prev_bin(b)    ((mbinptr)((char*)(b) - 2 * sizeof(mbinptr)))
523
524 /*
525    The first 2 bins are never indexed. The corresponding av_ cells are instead
526    used for bookkeeping. This is not to save space, but to simplify
527    indexing, maintain locality, and avoid some initialization tests.
528 */
529
530 #define top            (av_[2])          /* The topmost chunk */
531 #define last_remainder (bin_at(1))       /* remainder from last split */
532
533
534 /*
535    Because top initially points to its own bin with initial
536    zero size, thus forcing extension on the first malloc request,
537    we avoid having any special code in malloc to check whether
538    it even exists yet. But we still need to in malloc_extend_top.
539 */
540
541 #define initial_top    ((mchunkptr)(bin_at(0)))
542
543 /* Helper macro to initialize bins */
544
545 #define IAV(i)  bin_at(i), bin_at(i)
546
547 static mbinptr av_[NAV * 2 + 2] = {
548  NULL, NULL,
549  IAV(0),   IAV(1),   IAV(2),   IAV(3),   IAV(4),   IAV(5),   IAV(6),   IAV(7),
550  IAV(8),   IAV(9),   IAV(10),  IAV(11),  IAV(12),  IAV(13),  IAV(14),  IAV(15),
551  IAV(16),  IAV(17),  IAV(18),  IAV(19),  IAV(20),  IAV(21),  IAV(22),  IAV(23),
552  IAV(24),  IAV(25),  IAV(26),  IAV(27),  IAV(28),  IAV(29),  IAV(30),  IAV(31),
553  IAV(32),  IAV(33),  IAV(34),  IAV(35),  IAV(36),  IAV(37),  IAV(38),  IAV(39),
554  IAV(40),  IAV(41),  IAV(42),  IAV(43),  IAV(44),  IAV(45),  IAV(46),  IAV(47),
555  IAV(48),  IAV(49),  IAV(50),  IAV(51),  IAV(52),  IAV(53),  IAV(54),  IAV(55),
556  IAV(56),  IAV(57),  IAV(58),  IAV(59),  IAV(60),  IAV(61),  IAV(62),  IAV(63),
557  IAV(64),  IAV(65),  IAV(66),  IAV(67),  IAV(68),  IAV(69),  IAV(70),  IAV(71),
558  IAV(72),  IAV(73),  IAV(74),  IAV(75),  IAV(76),  IAV(77),  IAV(78),  IAV(79),
559  IAV(80),  IAV(81),  IAV(82),  IAV(83),  IAV(84),  IAV(85),  IAV(86),  IAV(87),
560  IAV(88),  IAV(89),  IAV(90),  IAV(91),  IAV(92),  IAV(93),  IAV(94),  IAV(95),
561  IAV(96),  IAV(97),  IAV(98),  IAV(99),  IAV(100), IAV(101), IAV(102), IAV(103),
562  IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
563  IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
564  IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
565 };
566
567 #ifdef CONFIG_NEEDS_MANUAL_RELOC
568 static void malloc_bin_reloc(void)
569 {
570         mbinptr *p = &av_[2];
571         size_t i;
572
573         for (i = 2; i < ARRAY_SIZE(av_); ++i, ++p)
574                 *p = (mbinptr)((ulong)*p + gd->reloc_off);
575 }
576 #else
577 static inline void malloc_bin_reloc(void) {}
578 #endif
579
580 #ifdef CONFIG_SYS_MALLOC_DEFAULT_TO_INIT
581 static void malloc_init(void);
582 #endif
583
584 ulong mem_malloc_start = 0;
585 ulong mem_malloc_end = 0;
586 ulong mem_malloc_brk = 0;
587
588 void *sbrk(ptrdiff_t increment)
589 {
590         ulong old = mem_malloc_brk;
591         ulong new = old + increment;
592
593         /*
594          * if we are giving memory back make sure we clear it out since
595          * we set MORECORE_CLEARS to 1
596          */
597         if (increment < 0)
598                 memset((void *)new, 0, -increment);
599
600         if ((new < mem_malloc_start) || (new > mem_malloc_end))
601                 return (void *)MORECORE_FAILURE;
602
603         mem_malloc_brk = new;
604
605         return (void *)old;
606 }
607
608 void mem_malloc_init(ulong start, ulong size)
609 {
610         mem_malloc_start = start;
611         mem_malloc_end = start + size;
612         mem_malloc_brk = start;
613
614 #ifdef CONFIG_SYS_MALLOC_DEFAULT_TO_INIT
615         malloc_init();
616 #endif
617
618         debug("using memory %#lx-%#lx for malloc()\n", mem_malloc_start,
619               mem_malloc_end);
620 #ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
621         memset((void *)mem_malloc_start, 0x0, size);
622 #endif
623         malloc_bin_reloc();
624 }
625
626 /* field-extraction macros */
627
628 #define first(b) ((b)->fd)
629 #define last(b)  ((b)->bk)
630
631 /*
632   Indexing into bins
633 */
634
635 #define bin_index(sz)                                                          \
636 (((((unsigned long)(sz)) >> 9) ==    0) ?       (((unsigned long)(sz)) >>  3): \
637  ((((unsigned long)(sz)) >> 9) <=    4) ?  56 + (((unsigned long)(sz)) >>  6): \
638  ((((unsigned long)(sz)) >> 9) <=   20) ?  91 + (((unsigned long)(sz)) >>  9): \
639  ((((unsigned long)(sz)) >> 9) <=   84) ? 110 + (((unsigned long)(sz)) >> 12): \
640  ((((unsigned long)(sz)) >> 9) <=  340) ? 119 + (((unsigned long)(sz)) >> 15): \
641  ((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18): \
642                                           126)
643 /*
644   bins for chunks < 512 are all spaced 8 bytes apart, and hold
645   identically sized chunks. This is exploited in malloc.
646 */
647
648 #define MAX_SMALLBIN         63
649 #define MAX_SMALLBIN_SIZE   512
650 #define SMALLBIN_WIDTH        8
651
652 #define smallbin_index(sz)  (((unsigned long)(sz)) >> 3)
653
654 /*
655    Requests are `small' if both the corresponding and the next bin are small
656 */
657
658 #define is_small_request(nb) (nb < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
659
660
661
662 /*
663     To help compensate for the large number of bins, a one-level index
664     structure is used for bin-by-bin searching.  `binblocks' is a
665     one-word bitvector recording whether groups of BINBLOCKWIDTH bins
666     have any (possibly) non-empty bins, so they can be skipped over
667     all at once during during traversals. The bits are NOT always
668     cleared as soon as all bins in a block are empty, but instead only
669     when all are noticed to be empty during traversal in malloc.
670 */
671
672 #define BINBLOCKWIDTH     4   /* bins per block */
673
674 #define binblocks_r     ((INTERNAL_SIZE_T)av_[1]) /* bitvector of nonempty blocks */
675 #define binblocks_w     (av_[1])
676
677 /* bin<->block macros */
678
679 #define idx2binblock(ix)    ((unsigned)1 << (ix / BINBLOCKWIDTH))
680 #define mark_binblock(ii)   (binblocks_w = (mbinptr)(binblocks_r | idx2binblock(ii)))
681 #define clear_binblock(ii)  (binblocks_w = (mbinptr)(binblocks_r & ~(idx2binblock(ii))))
682
683
684
685
686
687 /*  Other static bookkeeping data */
688
689 /* variables holding tunable values */
690
691 static unsigned long trim_threshold   = DEFAULT_TRIM_THRESHOLD;
692 static unsigned long top_pad          = DEFAULT_TOP_PAD;
693 static unsigned int  n_mmaps_max      = DEFAULT_MMAP_MAX;
694 static unsigned long mmap_threshold   = DEFAULT_MMAP_THRESHOLD;
695
696 /* The first value returned from sbrk */
697 static char* sbrk_base = (char*)(-1);
698
699 /* The maximum memory obtained from system via sbrk */
700 static unsigned long max_sbrked_mem = 0;
701
702 /* The maximum via either sbrk or mmap */
703 static unsigned long max_total_mem = 0;
704
705 /* internal working copy of mallinfo */
706 static struct mallinfo current_mallinfo = {  0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
707
708 /* The total memory obtained from system via sbrk */
709 #define sbrked_mem  (current_mallinfo.arena)
710
711 /* Tracking mmaps */
712
713 #ifdef DEBUG
714 static unsigned int n_mmaps = 0;
715 #endif  /* DEBUG */
716 static unsigned long mmapped_mem = 0;
717 #if HAVE_MMAP
718 static unsigned int max_n_mmaps = 0;
719 static unsigned long max_mmapped_mem = 0;
720 #endif
721
722 #ifdef CONFIG_SYS_MALLOC_DEFAULT_TO_INIT
723 static void malloc_init(void)
724 {
725         int i, j;
726
727         debug("bins (av_ array) are at %p\n", (void *)av_);
728
729         av_[0] = NULL; av_[1] = NULL;
730         for (i = 2, j = 2; i < NAV * 2 + 2; i += 2, j++) {
731                 av_[i] = bin_at(j - 2);
732                 av_[i + 1] = bin_at(j - 2);
733
734                 /* Just print the first few bins so that
735                  * we can see there are alright.
736                  */
737                 if (i < 10)
738                         debug("av_[%d]=%lx av_[%d]=%lx\n",
739                               i, (ulong)av_[i],
740                               i + 1, (ulong)av_[i + 1]);
741         }
742
743         /* Init the static bookkeeping as well */
744         sbrk_base = (char *)(-1);
745         max_sbrked_mem = 0;
746         max_total_mem = 0;
747 #ifdef DEBUG
748         memset((void *)&current_mallinfo, 0, sizeof(struct mallinfo));
749 #endif
750 }
751 #endif
752
753 /*
754   Debugging support
755 */
756
757 #ifdef DEBUG
758
759
760 /*
761   These routines make a number of assertions about the states
762   of data structures that should be true at all times. If any
763   are not true, it's very likely that a user program has somehow
764   trashed memory. (It's also possible that there is a coding error
765   in malloc. In which case, please report it!)
766 */
767
768 #if __STD_C
769 static void do_check_chunk(mchunkptr p)
770 #else
771 static void do_check_chunk(p) mchunkptr p;
772 #endif
773 {
774   INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
775
776   /* No checkable chunk is mmapped */
777   assert(!chunk_is_mmapped(p));
778
779   /* Check for legal address ... */
780   assert((char*)p >= sbrk_base);
781   if (p != top)
782     assert((char*)p + sz <= (char*)top);
783   else
784     assert((char*)p + sz <= sbrk_base + sbrked_mem);
785
786 }
787
788
789 #if __STD_C
790 static void do_check_free_chunk(mchunkptr p)
791 #else
792 static void do_check_free_chunk(p) mchunkptr p;
793 #endif
794 {
795   INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
796   mchunkptr next = chunk_at_offset(p, sz);
797
798   do_check_chunk(p);
799
800   /* Check whether it claims to be free ... */
801   assert(!inuse(p));
802
803   /* Unless a special marker, must have OK fields */
804   if ((long)sz >= (long)MINSIZE)
805   {
806     assert((sz & MALLOC_ALIGN_MASK) == 0);
807     assert(aligned_OK(chunk2mem(p)));
808     /* ... matching footer field */
809     assert(next->prev_size == sz);
810     /* ... and is fully consolidated */
811     assert(prev_inuse(p));
812     assert (next == top || inuse(next));
813
814     /* ... and has minimally sane links */
815     assert(p->fd->bk == p);
816     assert(p->bk->fd == p);
817   }
818   else /* markers are always of size SIZE_SZ */
819     assert(sz == SIZE_SZ);
820 }
821
822 #if __STD_C
823 static void do_check_inuse_chunk(mchunkptr p)
824 #else
825 static void do_check_inuse_chunk(p) mchunkptr p;
826 #endif
827 {
828   mchunkptr next = next_chunk(p);
829   do_check_chunk(p);
830
831   /* Check whether it claims to be in use ... */
832   assert(inuse(p));
833
834   /* ... and is surrounded by OK chunks.
835     Since more things can be checked with free chunks than inuse ones,
836     if an inuse chunk borders them and debug is on, it's worth doing them.
837   */
838   if (!prev_inuse(p))
839   {
840     mchunkptr prv = prev_chunk(p);
841     assert(next_chunk(prv) == p);
842     do_check_free_chunk(prv);
843   }
844   if (next == top)
845   {
846     assert(prev_inuse(next));
847     assert(chunksize(next) >= MINSIZE);
848   }
849   else if (!inuse(next))
850     do_check_free_chunk(next);
851
852 }
853
854 #if __STD_C
855 static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)
856 #else
857 static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;
858 #endif
859 {
860   INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
861   long room = sz - s;
862
863   do_check_inuse_chunk(p);
864
865   /* Legal size ... */
866   assert((long)sz >= (long)MINSIZE);
867   assert((sz & MALLOC_ALIGN_MASK) == 0);
868   assert(room >= 0);
869   assert(room < (long)MINSIZE);
870
871   /* ... and alignment */
872   assert(aligned_OK(chunk2mem(p)));
873
874
875   /* ... and was allocated at front of an available chunk */
876   assert(prev_inuse(p));
877
878 }
879
880
881 #define check_free_chunk(P)  do_check_free_chunk(P)
882 #define check_inuse_chunk(P) do_check_inuse_chunk(P)
883 #define check_chunk(P) do_check_chunk(P)
884 #define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N)
885 #else
886 #define check_free_chunk(P)
887 #define check_inuse_chunk(P)
888 #define check_chunk(P)
889 #define check_malloced_chunk(P,N)
890 #endif
891
892
893
894 /*
895   Macro-based internal utilities
896 */
897
898
899 /*
900   Linking chunks in bin lists.
901   Call these only with variables, not arbitrary expressions, as arguments.
902 */
903
904 /*
905   Place chunk p of size s in its bin, in size order,
906   putting it ahead of others of same size.
907 */
908
909
910 #define frontlink(P, S, IDX, BK, FD)                                          \
911 {                                                                             \
912   if (S < MAX_SMALLBIN_SIZE)                                                  \
913   {                                                                           \
914     IDX = smallbin_index(S);                                                  \
915     mark_binblock(IDX);                                                       \
916     BK = bin_at(IDX);                                                         \
917     FD = BK->fd;                                                              \
918     P->bk = BK;                                                               \
919     P->fd = FD;                                                               \
920     FD->bk = BK->fd = P;                                                      \
921   }                                                                           \
922   else                                                                        \
923   {                                                                           \
924     IDX = bin_index(S);                                                       \
925     BK = bin_at(IDX);                                                         \
926     FD = BK->fd;                                                              \
927     if (FD == BK) mark_binblock(IDX);                                         \
928     else                                                                      \
929     {                                                                         \
930       while (FD != BK && S < chunksize(FD)) FD = FD->fd;                      \
931       BK = FD->bk;                                                            \
932     }                                                                         \
933     P->bk = BK;                                                               \
934     P->fd = FD;                                                               \
935     FD->bk = BK->fd = P;                                                      \
936   }                                                                           \
937 }
938
939
940 /* take a chunk off a list */
941
942 #define unlink(P, BK, FD)                                                     \
943 {                                                                             \
944   BK = P->bk;                                                                 \
945   FD = P->fd;                                                                 \
946   FD->bk = BK;                                                                \
947   BK->fd = FD;                                                                \
948 }                                                                             \
949
950 /* Place p as the last remainder */
951
952 #define link_last_remainder(P)                                                \
953 {                                                                             \
954   last_remainder->fd = last_remainder->bk =  P;                               \
955   P->fd = P->bk = last_remainder;                                             \
956 }
957
958 /* Clear the last_remainder bin */
959
960 #define clear_last_remainder \
961   (last_remainder->fd = last_remainder->bk = last_remainder)
962
963
964
965
966
967 /* Routines dealing with mmap(). */
968
969 #if HAVE_MMAP
970
971 #if __STD_C
972 static mchunkptr mmap_chunk(size_t size)
973 #else
974 static mchunkptr mmap_chunk(size) size_t size;
975 #endif
976 {
977   size_t page_mask = malloc_getpagesize - 1;
978   mchunkptr p;
979
980 #ifndef MAP_ANONYMOUS
981   static int fd = -1;
982 #endif
983
984   if(n_mmaps >= n_mmaps_max) return 0; /* too many regions */
985
986   /* For mmapped chunks, the overhead is one SIZE_SZ unit larger, because
987    * there is no following chunk whose prev_size field could be used.
988    */
989   size = (size + SIZE_SZ + page_mask) & ~page_mask;
990
991 #ifdef MAP_ANONYMOUS
992   p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE,
993                       MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
994 #else /* !MAP_ANONYMOUS */
995   if (fd < 0)
996   {
997     fd = open("/dev/zero", O_RDWR);
998     if(fd < 0) return 0;
999   }
1000   p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
1001 #endif
1002
1003   if(p == (mchunkptr)-1) return 0;
1004
1005   n_mmaps++;
1006   if (n_mmaps > max_n_mmaps) max_n_mmaps = n_mmaps;
1007
1008   /* We demand that eight bytes into a page must be 8-byte aligned. */
1009   assert(aligned_OK(chunk2mem(p)));
1010
1011   /* The offset to the start of the mmapped region is stored
1012    * in the prev_size field of the chunk; normally it is zero,
1013    * but that can be changed in memalign().
1014    */
1015   p->prev_size = 0;
1016   set_head(p, size|IS_MMAPPED);
1017
1018   mmapped_mem += size;
1019   if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
1020     max_mmapped_mem = mmapped_mem;
1021   if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1022     max_total_mem = mmapped_mem + sbrked_mem;
1023   return p;
1024 }
1025
1026 #if __STD_C
1027 static void munmap_chunk(mchunkptr p)
1028 #else
1029 static void munmap_chunk(p) mchunkptr p;
1030 #endif
1031 {
1032   INTERNAL_SIZE_T size = chunksize(p);
1033   int ret;
1034
1035   assert (chunk_is_mmapped(p));
1036   assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
1037   assert((n_mmaps > 0));
1038   assert(((p->prev_size + size) & (malloc_getpagesize-1)) == 0);
1039
1040   n_mmaps--;
1041   mmapped_mem -= (size + p->prev_size);
1042
1043   ret = munmap((char *)p - p->prev_size, size + p->prev_size);
1044
1045   /* munmap returns non-zero on failure */
1046   assert(ret == 0);
1047 }
1048
1049 #if HAVE_MREMAP
1050
1051 #if __STD_C
1052 static mchunkptr mremap_chunk(mchunkptr p, size_t new_size)
1053 #else
1054 static mchunkptr mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
1055 #endif
1056 {
1057   size_t page_mask = malloc_getpagesize - 1;
1058   INTERNAL_SIZE_T offset = p->prev_size;
1059   INTERNAL_SIZE_T size = chunksize(p);
1060   char *cp;
1061
1062   assert (chunk_is_mmapped(p));
1063   assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
1064   assert((n_mmaps > 0));
1065   assert(((size + offset) & (malloc_getpagesize-1)) == 0);
1066
1067   /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
1068   new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
1069
1070   cp = (char *)mremap((char *)p - offset, size + offset, new_size, 1);
1071
1072   if (cp == (char *)-1) return 0;
1073
1074   p = (mchunkptr)(cp + offset);
1075
1076   assert(aligned_OK(chunk2mem(p)));
1077
1078   assert((p->prev_size == offset));
1079   set_head(p, (new_size - offset)|IS_MMAPPED);
1080
1081   mmapped_mem -= size + offset;
1082   mmapped_mem += new_size;
1083   if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
1084     max_mmapped_mem = mmapped_mem;
1085   if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1086     max_total_mem = mmapped_mem + sbrked_mem;
1087   return p;
1088 }
1089
1090 #endif /* HAVE_MREMAP */
1091
1092 #endif /* HAVE_MMAP */
1093
1094 /*
1095   Extend the top-most chunk by obtaining memory from system.
1096   Main interface to sbrk (but see also malloc_trim).
1097 */
1098
1099 #if __STD_C
1100 static void malloc_extend_top(INTERNAL_SIZE_T nb)
1101 #else
1102 static void malloc_extend_top(nb) INTERNAL_SIZE_T nb;
1103 #endif
1104 {
1105   char*     brk;                  /* return value from sbrk */
1106   INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of sbrked space */
1107   INTERNAL_SIZE_T correction;     /* bytes for 2nd sbrk call */
1108   char*     new_brk;              /* return of 2nd sbrk call */
1109   INTERNAL_SIZE_T top_size;       /* new size of top chunk */
1110
1111   mchunkptr old_top     = top;  /* Record state of old top */
1112   INTERNAL_SIZE_T old_top_size = chunksize(old_top);
1113   char*     old_end      = (char*)(chunk_at_offset(old_top, old_top_size));
1114
1115   /* Pad request with top_pad plus minimal overhead */
1116
1117   INTERNAL_SIZE_T    sbrk_size     = nb + top_pad + MINSIZE;
1118   unsigned long pagesz    = malloc_getpagesize;
1119
1120   /* If not the first time through, round to preserve page boundary */
1121   /* Otherwise, we need to correct to a page size below anyway. */
1122   /* (We also correct below if an intervening foreign sbrk call.) */
1123
1124   if (sbrk_base != (char*)(-1))
1125     sbrk_size = (sbrk_size + (pagesz - 1)) & ~(pagesz - 1);
1126
1127   brk = (char*)(MORECORE (sbrk_size));
1128
1129   /* Fail if sbrk failed or if a foreign sbrk call killed our space */
1130   if (brk == (char*)(MORECORE_FAILURE) ||
1131       (brk < old_end && old_top != initial_top))
1132     return;
1133
1134   sbrked_mem += sbrk_size;
1135
1136   if (brk == old_end) /* can just add bytes to current top */
1137   {
1138     top_size = sbrk_size + old_top_size;
1139     set_head(top, top_size | PREV_INUSE);
1140   }
1141   else
1142   {
1143     if (sbrk_base == (char*)(-1))  /* First time through. Record base */
1144       sbrk_base = brk;
1145     else  /* Someone else called sbrk().  Count those bytes as sbrked_mem. */
1146       sbrked_mem += brk - (char*)old_end;
1147
1148     /* Guarantee alignment of first new chunk made from this space */
1149     front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
1150     if (front_misalign > 0)
1151     {
1152       correction = (MALLOC_ALIGNMENT) - front_misalign;
1153       brk += correction;
1154     }
1155     else
1156       correction = 0;
1157
1158     /* Guarantee the next brk will be at a page boundary */
1159
1160     correction += ((((unsigned long)(brk + sbrk_size))+(pagesz-1)) &
1161                    ~(pagesz - 1)) - ((unsigned long)(brk + sbrk_size));
1162
1163     /* Allocate correction */
1164     new_brk = (char*)(MORECORE (correction));
1165     if (new_brk == (char*)(MORECORE_FAILURE)) return;
1166
1167     sbrked_mem += correction;
1168
1169     top = (mchunkptr)brk;
1170     top_size = new_brk - brk + correction;
1171     set_head(top, top_size | PREV_INUSE);
1172
1173     if (old_top != initial_top)
1174     {
1175
1176       /* There must have been an intervening foreign sbrk call. */
1177       /* A double fencepost is necessary to prevent consolidation */
1178
1179       /* If not enough space to do this, then user did something very wrong */
1180       if (old_top_size < MINSIZE)
1181       {
1182         set_head(top, PREV_INUSE); /* will force null return from malloc */
1183         return;
1184       }
1185
1186       /* Also keep size a multiple of MALLOC_ALIGNMENT */
1187       old_top_size = (old_top_size - 3*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
1188       set_head_size(old_top, old_top_size);
1189       chunk_at_offset(old_top, old_top_size          )->size =
1190         SIZE_SZ|PREV_INUSE;
1191       chunk_at_offset(old_top, old_top_size + SIZE_SZ)->size =
1192         SIZE_SZ|PREV_INUSE;
1193       /* If possible, release the rest. */
1194       if (old_top_size >= MINSIZE)
1195         fREe(chunk2mem(old_top));
1196     }
1197   }
1198
1199   if ((unsigned long)sbrked_mem > (unsigned long)max_sbrked_mem)
1200     max_sbrked_mem = sbrked_mem;
1201   if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1202     max_total_mem = mmapped_mem + sbrked_mem;
1203
1204   /* We always land on a page boundary */
1205   assert(((unsigned long)((char*)top + top_size) & (pagesz - 1)) == 0);
1206 }
1207
1208
1209
1210
1211 /* Main public routines */
1212
1213
1214 /*
1215   Malloc Algorthim:
1216
1217     The requested size is first converted into a usable form, `nb'.
1218     This currently means to add 4 bytes overhead plus possibly more to
1219     obtain 8-byte alignment and/or to obtain a size of at least
1220     MINSIZE (currently 16 bytes), the smallest allocatable size.
1221     (All fits are considered `exact' if they are within MINSIZE bytes.)
1222
1223     From there, the first successful of the following steps is taken:
1224
1225       1. The bin corresponding to the request size is scanned, and if
1226          a chunk of exactly the right size is found, it is taken.
1227
1228       2. The most recently remaindered chunk is used if it is big
1229          enough.  This is a form of (roving) first fit, used only in
1230          the absence of exact fits. Runs of consecutive requests use
1231          the remainder of the chunk used for the previous such request
1232          whenever possible. This limited use of a first-fit style
1233          allocation strategy tends to give contiguous chunks
1234          coextensive lifetimes, which improves locality and can reduce
1235          fragmentation in the long run.
1236
1237       3. Other bins are scanned in increasing size order, using a
1238          chunk big enough to fulfill the request, and splitting off
1239          any remainder.  This search is strictly by best-fit; i.e.,
1240          the smallest (with ties going to approximately the least
1241          recently used) chunk that fits is selected.
1242
1243       4. If large enough, the chunk bordering the end of memory
1244          (`top') is split off. (This use of `top' is in accord with
1245          the best-fit search rule.  In effect, `top' is treated as
1246          larger (and thus less well fitting) than any other available
1247          chunk since it can be extended to be as large as necessary
1248          (up to system limitations).
1249
1250       5. If the request size meets the mmap threshold and the
1251          system supports mmap, and there are few enough currently
1252          allocated mmapped regions, and a call to mmap succeeds,
1253          the request is allocated via direct memory mapping.
1254
1255       6. Otherwise, the top of memory is extended by
1256          obtaining more space from the system (normally using sbrk,
1257          but definable to anything else via the MORECORE macro).
1258          Memory is gathered from the system (in system page-sized
1259          units) in a way that allows chunks obtained across different
1260          sbrk calls to be consolidated, but does not require
1261          contiguous memory. Thus, it should be safe to intersperse
1262          mallocs with other sbrk calls.
1263
1264
1265       All allocations are made from the the `lowest' part of any found
1266       chunk. (The implementation invariant is that prev_inuse is
1267       always true of any allocated chunk; i.e., that each allocated
1268       chunk borders either a previously allocated and still in-use chunk,
1269       or the base of its memory arena.)
1270
1271 */
1272
1273 #if __STD_C
1274 Void_t* mALLOc(size_t bytes)
1275 #else
1276 Void_t* mALLOc(bytes) size_t bytes;
1277 #endif
1278 {
1279   mchunkptr victim;                  /* inspected/selected chunk */
1280   INTERNAL_SIZE_T victim_size;       /* its size */
1281   int       idx;                     /* index for bin traversal */
1282   mbinptr   bin;                     /* associated bin */
1283   mchunkptr remainder;               /* remainder from a split */
1284   long      remainder_size;          /* its size */
1285   int       remainder_index;         /* its bin index */
1286   unsigned long block;               /* block traverser bit */
1287   int       startidx;                /* first bin of a traversed block */
1288   mchunkptr fwd;                     /* misc temp for linking */
1289   mchunkptr bck;                     /* misc temp for linking */
1290   mbinptr q;                         /* misc temp */
1291
1292   INTERNAL_SIZE_T nb;
1293
1294 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
1295         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT))
1296                 return malloc_simple(bytes);
1297 #endif
1298
1299   /* check if mem_malloc_init() was run */
1300   if ((mem_malloc_start == 0) && (mem_malloc_end == 0)) {
1301     /* not initialized yet */
1302     return NULL;
1303   }
1304
1305   if ((long)bytes < 0) return NULL;
1306
1307   nb = request2size(bytes);  /* padded request size; */
1308
1309   /* Check for exact match in a bin */
1310
1311   if (is_small_request(nb))  /* Faster version for small requests */
1312   {
1313     idx = smallbin_index(nb);
1314
1315     /* No traversal or size check necessary for small bins.  */
1316
1317     q = bin_at(idx);
1318     victim = last(q);
1319
1320     /* Also scan the next one, since it would have a remainder < MINSIZE */
1321     if (victim == q)
1322     {
1323       q = next_bin(q);
1324       victim = last(q);
1325     }
1326     if (victim != q)
1327     {
1328       victim_size = chunksize(victim);
1329       unlink(victim, bck, fwd);
1330       set_inuse_bit_at_offset(victim, victim_size);
1331       check_malloced_chunk(victim, nb);
1332       return chunk2mem(victim);
1333     }
1334
1335     idx += 2; /* Set for bin scan below. We've already scanned 2 bins. */
1336
1337   }
1338   else
1339   {
1340     idx = bin_index(nb);
1341     bin = bin_at(idx);
1342
1343     for (victim = last(bin); victim != bin; victim = victim->bk)
1344     {
1345       victim_size = chunksize(victim);
1346       remainder_size = victim_size - nb;
1347
1348       if (remainder_size >= (long)MINSIZE) /* too big */
1349       {
1350         --idx; /* adjust to rescan below after checking last remainder */
1351         break;
1352       }
1353
1354       else if (remainder_size >= 0) /* exact fit */
1355       {
1356         unlink(victim, bck, fwd);
1357         set_inuse_bit_at_offset(victim, victim_size);
1358         check_malloced_chunk(victim, nb);
1359         return chunk2mem(victim);
1360       }
1361     }
1362
1363     ++idx;
1364
1365   }
1366
1367   /* Try to use the last split-off remainder */
1368
1369   if ( (victim = last_remainder->fd) != last_remainder)
1370   {
1371     victim_size = chunksize(victim);
1372     remainder_size = victim_size - nb;
1373
1374     if (remainder_size >= (long)MINSIZE) /* re-split */
1375     {
1376       remainder = chunk_at_offset(victim, nb);
1377       set_head(victim, nb | PREV_INUSE);
1378       link_last_remainder(remainder);
1379       set_head(remainder, remainder_size | PREV_INUSE);
1380       set_foot(remainder, remainder_size);
1381       check_malloced_chunk(victim, nb);
1382       return chunk2mem(victim);
1383     }
1384
1385     clear_last_remainder;
1386
1387     if (remainder_size >= 0)  /* exhaust */
1388     {
1389       set_inuse_bit_at_offset(victim, victim_size);
1390       check_malloced_chunk(victim, nb);
1391       return chunk2mem(victim);
1392     }
1393
1394     /* Else place in bin */
1395
1396     frontlink(victim, victim_size, remainder_index, bck, fwd);
1397   }
1398
1399   /*
1400      If there are any possibly nonempty big-enough blocks,
1401      search for best fitting chunk by scanning bins in blockwidth units.
1402   */
1403
1404   if ( (block = idx2binblock(idx)) <= binblocks_r)
1405   {
1406
1407     /* Get to the first marked block */
1408
1409     if ( (block & binblocks_r) == 0)
1410     {
1411       /* force to an even block boundary */
1412       idx = (idx & ~(BINBLOCKWIDTH - 1)) + BINBLOCKWIDTH;
1413       block <<= 1;
1414       while ((block & binblocks_r) == 0)
1415       {
1416         idx += BINBLOCKWIDTH;
1417         block <<= 1;
1418       }
1419     }
1420
1421     /* For each possibly nonempty block ... */
1422     for (;;)
1423     {
1424       startidx = idx;          /* (track incomplete blocks) */
1425       q = bin = bin_at(idx);
1426
1427       /* For each bin in this block ... */
1428       do
1429       {
1430         /* Find and use first big enough chunk ... */
1431
1432         for (victim = last(bin); victim != bin; victim = victim->bk)
1433         {
1434           victim_size = chunksize(victim);
1435           remainder_size = victim_size - nb;
1436
1437           if (remainder_size >= (long)MINSIZE) /* split */
1438           {
1439             remainder = chunk_at_offset(victim, nb);
1440             set_head(victim, nb | PREV_INUSE);
1441             unlink(victim, bck, fwd);
1442             link_last_remainder(remainder);
1443             set_head(remainder, remainder_size | PREV_INUSE);
1444             set_foot(remainder, remainder_size);
1445             check_malloced_chunk(victim, nb);
1446             return chunk2mem(victim);
1447           }
1448
1449           else if (remainder_size >= 0)  /* take */
1450           {
1451             set_inuse_bit_at_offset(victim, victim_size);
1452             unlink(victim, bck, fwd);
1453             check_malloced_chunk(victim, nb);
1454             return chunk2mem(victim);
1455           }
1456
1457         }
1458
1459        bin = next_bin(bin);
1460
1461       } while ((++idx & (BINBLOCKWIDTH - 1)) != 0);
1462
1463       /* Clear out the block bit. */
1464
1465       do   /* Possibly backtrack to try to clear a partial block */
1466       {
1467         if ((startidx & (BINBLOCKWIDTH - 1)) == 0)
1468         {
1469           av_[1] = (mbinptr)(binblocks_r & ~block);
1470           break;
1471         }
1472         --startidx;
1473        q = prev_bin(q);
1474       } while (first(q) == q);
1475
1476       /* Get to the next possibly nonempty block */
1477
1478       if ( (block <<= 1) <= binblocks_r && (block != 0) )
1479       {
1480         while ((block & binblocks_r) == 0)
1481         {
1482           idx += BINBLOCKWIDTH;
1483           block <<= 1;
1484         }
1485       }
1486       else
1487         break;
1488     }
1489   }
1490
1491
1492   /* Try to use top chunk */
1493
1494   /* Require that there be a remainder, ensuring top always exists  */
1495   if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
1496   {
1497
1498 #if HAVE_MMAP
1499     /* If big and would otherwise need to extend, try to use mmap instead */
1500     if ((unsigned long)nb >= (unsigned long)mmap_threshold &&
1501         (victim = mmap_chunk(nb)))
1502       return chunk2mem(victim);
1503 #endif
1504
1505     /* Try to extend */
1506     malloc_extend_top(nb);
1507     if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
1508       return NULL; /* propagate failure */
1509   }
1510
1511   victim = top;
1512   set_head(victim, nb | PREV_INUSE);
1513   top = chunk_at_offset(victim, nb);
1514   set_head(top, remainder_size | PREV_INUSE);
1515   check_malloced_chunk(victim, nb);
1516   return chunk2mem(victim);
1517
1518 }
1519
1520
1521
1522
1523 /*
1524
1525   free() algorithm :
1526
1527     cases:
1528
1529        1. free(0) has no effect.
1530
1531        2. If the chunk was allocated via mmap, it is release via munmap().
1532
1533        3. If a returned chunk borders the current high end of memory,
1534           it is consolidated into the top, and if the total unused
1535           topmost memory exceeds the trim threshold, malloc_trim is
1536           called.
1537
1538        4. Other chunks are consolidated as they arrive, and
1539           placed in corresponding bins. (This includes the case of
1540           consolidating with the current `last_remainder').
1541
1542 */
1543
1544
1545 #if __STD_C
1546 void fREe(Void_t* mem)
1547 #else
1548 void fREe(mem) Void_t* mem;
1549 #endif
1550 {
1551   mchunkptr p;         /* chunk corresponding to mem */
1552   INTERNAL_SIZE_T hd;  /* its head field */
1553   INTERNAL_SIZE_T sz;  /* its size */
1554   int       idx;       /* its bin index */
1555   mchunkptr next;      /* next contiguous chunk */
1556   INTERNAL_SIZE_T nextsz; /* its size */
1557   INTERNAL_SIZE_T prevsz; /* size of previous contiguous chunk */
1558   mchunkptr bck;       /* misc temp for linking */
1559   mchunkptr fwd;       /* misc temp for linking */
1560   int       islr;      /* track whether merging with last_remainder */
1561
1562 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
1563         /* free() is a no-op - all the memory will be freed on relocation */
1564         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT))
1565                 return;
1566 #endif
1567
1568   if (mem == NULL)                              /* free(0) has no effect */
1569     return;
1570
1571   p = mem2chunk(mem);
1572   hd = p->size;
1573
1574 #if HAVE_MMAP
1575   if (hd & IS_MMAPPED)                       /* release mmapped memory. */
1576   {
1577     munmap_chunk(p);
1578     return;
1579   }
1580 #endif
1581
1582   check_inuse_chunk(p);
1583
1584   sz = hd & ~PREV_INUSE;
1585   next = chunk_at_offset(p, sz);
1586   nextsz = chunksize(next);
1587
1588   if (next == top)                            /* merge with top */
1589   {
1590     sz += nextsz;
1591
1592     if (!(hd & PREV_INUSE))                    /* consolidate backward */
1593     {
1594       prevsz = p->prev_size;
1595       p = chunk_at_offset(p, -((long) prevsz));
1596       sz += prevsz;
1597       unlink(p, bck, fwd);
1598     }
1599
1600     set_head(p, sz | PREV_INUSE);
1601     top = p;
1602     if ((unsigned long)(sz) >= (unsigned long)trim_threshold)
1603       malloc_trim(top_pad);
1604     return;
1605   }
1606
1607   set_head(next, nextsz);                    /* clear inuse bit */
1608
1609   islr = 0;
1610
1611   if (!(hd & PREV_INUSE))                    /* consolidate backward */
1612   {
1613     prevsz = p->prev_size;
1614     p = chunk_at_offset(p, -((long) prevsz));
1615     sz += prevsz;
1616
1617     if (p->fd == last_remainder)             /* keep as last_remainder */
1618       islr = 1;
1619     else
1620       unlink(p, bck, fwd);
1621   }
1622
1623   if (!(inuse_bit_at_offset(next, nextsz)))   /* consolidate forward */
1624   {
1625     sz += nextsz;
1626
1627     if (!islr && next->fd == last_remainder)  /* re-insert last_remainder */
1628     {
1629       islr = 1;
1630       link_last_remainder(p);
1631     }
1632     else
1633       unlink(next, bck, fwd);
1634   }
1635
1636
1637   set_head(p, sz | PREV_INUSE);
1638   set_foot(p, sz);
1639   if (!islr)
1640     frontlink(p, sz, idx, bck, fwd);
1641 }
1642
1643
1644
1645
1646
1647 /*
1648
1649   Realloc algorithm:
1650
1651     Chunks that were obtained via mmap cannot be extended or shrunk
1652     unless HAVE_MREMAP is defined, in which case mremap is used.
1653     Otherwise, if their reallocation is for additional space, they are
1654     copied.  If for less, they are just left alone.
1655
1656     Otherwise, if the reallocation is for additional space, and the
1657     chunk can be extended, it is, else a malloc-copy-free sequence is
1658     taken.  There are several different ways that a chunk could be
1659     extended. All are tried:
1660
1661        * Extending forward into following adjacent free chunk.
1662        * Shifting backwards, joining preceding adjacent space
1663        * Both shifting backwards and extending forward.
1664        * Extending into newly sbrked space
1665
1666     Unless the #define REALLOC_ZERO_BYTES_FREES is set, realloc with a
1667     size argument of zero (re)allocates a minimum-sized chunk.
1668
1669     If the reallocation is for less space, and the new request is for
1670     a `small' (<512 bytes) size, then the newly unused space is lopped
1671     off and freed.
1672
1673     The old unix realloc convention of allowing the last-free'd chunk
1674     to be used as an argument to realloc is no longer supported.
1675     I don't know of any programs still relying on this feature,
1676     and allowing it would also allow too many other incorrect
1677     usages of realloc to be sensible.
1678
1679
1680 */
1681
1682
1683 #if __STD_C
1684 Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
1685 #else
1686 Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
1687 #endif
1688 {
1689   INTERNAL_SIZE_T    nb;      /* padded request size */
1690
1691   mchunkptr oldp;             /* chunk corresponding to oldmem */
1692   INTERNAL_SIZE_T    oldsize; /* its size */
1693
1694   mchunkptr newp;             /* chunk to return */
1695   INTERNAL_SIZE_T    newsize; /* its size */
1696   Void_t*   newmem;           /* corresponding user mem */
1697
1698   mchunkptr next;             /* next contiguous chunk after oldp */
1699   INTERNAL_SIZE_T  nextsize;  /* its size */
1700
1701   mchunkptr prev;             /* previous contiguous chunk before oldp */
1702   INTERNAL_SIZE_T  prevsize;  /* its size */
1703
1704   mchunkptr remainder;        /* holds split off extra space from newp */
1705   INTERNAL_SIZE_T  remainder_size;   /* its size */
1706
1707   mchunkptr bck;              /* misc temp for linking */
1708   mchunkptr fwd;              /* misc temp for linking */
1709
1710 #ifdef REALLOC_ZERO_BYTES_FREES
1711   if (!bytes) {
1712         fREe(oldmem);
1713         return NULL;
1714   }
1715 #endif
1716
1717   if ((long)bytes < 0) return NULL;
1718
1719   /* realloc of null is supposed to be same as malloc */
1720   if (oldmem == NULL) return mALLOc(bytes);
1721
1722 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
1723         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
1724                 /* This is harder to support and should not be needed */
1725                 panic("pre-reloc realloc() is not supported");
1726         }
1727 #endif
1728
1729   newp    = oldp    = mem2chunk(oldmem);
1730   newsize = oldsize = chunksize(oldp);
1731
1732
1733   nb = request2size(bytes);
1734
1735 #if HAVE_MMAP
1736   if (chunk_is_mmapped(oldp))
1737   {
1738 #if HAVE_MREMAP
1739     newp = mremap_chunk(oldp, nb);
1740     if(newp) return chunk2mem(newp);
1741 #endif
1742     /* Note the extra SIZE_SZ overhead. */
1743     if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
1744     /* Must alloc, copy, free. */
1745     newmem = mALLOc(bytes);
1746     if (!newmem)
1747         return NULL; /* propagate failure */
1748     MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
1749     munmap_chunk(oldp);
1750     return newmem;
1751   }
1752 #endif
1753
1754   check_inuse_chunk(oldp);
1755
1756   if ((long)(oldsize) < (long)(nb))
1757   {
1758
1759     /* Try expanding forward */
1760
1761     next = chunk_at_offset(oldp, oldsize);
1762     if (next == top || !inuse(next))
1763     {
1764       nextsize = chunksize(next);
1765
1766       /* Forward into top only if a remainder */
1767       if (next == top)
1768       {
1769         if ((long)(nextsize + newsize) >= (long)(nb + MINSIZE))
1770         {
1771           newsize += nextsize;
1772           top = chunk_at_offset(oldp, nb);
1773           set_head(top, (newsize - nb) | PREV_INUSE);
1774           set_head_size(oldp, nb);
1775           return chunk2mem(oldp);
1776         }
1777       }
1778
1779       /* Forward into next chunk */
1780       else if (((long)(nextsize + newsize) >= (long)(nb)))
1781       {
1782         unlink(next, bck, fwd);
1783         newsize  += nextsize;
1784         goto split;
1785       }
1786     }
1787     else
1788     {
1789       next = NULL;
1790       nextsize = 0;
1791     }
1792
1793     /* Try shifting backwards. */
1794
1795     if (!prev_inuse(oldp))
1796     {
1797       prev = prev_chunk(oldp);
1798       prevsize = chunksize(prev);
1799
1800       /* try forward + backward first to save a later consolidation */
1801
1802       if (next != NULL)
1803       {
1804         /* into top */
1805         if (next == top)
1806         {
1807           if ((long)(nextsize + prevsize + newsize) >= (long)(nb + MINSIZE))
1808           {
1809             unlink(prev, bck, fwd);
1810             newp = prev;
1811             newsize += prevsize + nextsize;
1812             newmem = chunk2mem(newp);
1813             MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1814             top = chunk_at_offset(newp, nb);
1815             set_head(top, (newsize - nb) | PREV_INUSE);
1816             set_head_size(newp, nb);
1817             return newmem;
1818           }
1819         }
1820
1821         /* into next chunk */
1822         else if (((long)(nextsize + prevsize + newsize) >= (long)(nb)))
1823         {
1824           unlink(next, bck, fwd);
1825           unlink(prev, bck, fwd);
1826           newp = prev;
1827           newsize += nextsize + prevsize;
1828           newmem = chunk2mem(newp);
1829           MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1830           goto split;
1831         }
1832       }
1833
1834       /* backward only */
1835       if (prev != NULL && (long)(prevsize + newsize) >= (long)nb)
1836       {
1837         unlink(prev, bck, fwd);
1838         newp = prev;
1839         newsize += prevsize;
1840         newmem = chunk2mem(newp);
1841         MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1842         goto split;
1843       }
1844     }
1845
1846     /* Must allocate */
1847
1848     newmem = mALLOc (bytes);
1849
1850     if (newmem == NULL)  /* propagate failure */
1851       return NULL;
1852
1853     /* Avoid copy if newp is next chunk after oldp. */
1854     /* (This can only happen when new chunk is sbrk'ed.) */
1855
1856     if ( (newp = mem2chunk(newmem)) == next_chunk(oldp))
1857     {
1858       newsize += chunksize(newp);
1859       newp = oldp;
1860       goto split;
1861     }
1862
1863     /* Otherwise copy, free, and exit */
1864     MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1865     fREe(oldmem);
1866     return newmem;
1867   }
1868
1869
1870  split:  /* split off extra room in old or expanded chunk */
1871
1872   if (newsize - nb >= MINSIZE) /* split off remainder */
1873   {
1874     remainder = chunk_at_offset(newp, nb);
1875     remainder_size = newsize - nb;
1876     set_head_size(newp, nb);
1877     set_head(remainder, remainder_size | PREV_INUSE);
1878     set_inuse_bit_at_offset(remainder, remainder_size);
1879     fREe(chunk2mem(remainder)); /* let free() deal with it */
1880   }
1881   else
1882   {
1883     set_head_size(newp, newsize);
1884     set_inuse_bit_at_offset(newp, newsize);
1885   }
1886
1887   check_inuse_chunk(newp);
1888   return chunk2mem(newp);
1889 }
1890
1891
1892
1893
1894 /*
1895
1896   memalign algorithm:
1897
1898     memalign requests more than enough space from malloc, finds a spot
1899     within that chunk that meets the alignment request, and then
1900     possibly frees the leading and trailing space.
1901
1902     The alignment argument must be a power of two. This property is not
1903     checked by memalign, so misuse may result in random runtime errors.
1904
1905     8-byte alignment is guaranteed by normal malloc calls, so don't
1906     bother calling memalign with an argument of 8 or less.
1907
1908     Overreliance on memalign is a sure way to fragment space.
1909
1910 */
1911
1912
1913 #if __STD_C
1914 Void_t* mEMALIGn(size_t alignment, size_t bytes)
1915 #else
1916 Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
1917 #endif
1918 {
1919   INTERNAL_SIZE_T    nb;      /* padded  request size */
1920   char*     m;                /* memory returned by malloc call */
1921   mchunkptr p;                /* corresponding chunk */
1922   char*     brk;              /* alignment point within p */
1923   mchunkptr newp;             /* chunk to return */
1924   INTERNAL_SIZE_T  newsize;   /* its size */
1925   INTERNAL_SIZE_T  leadsize;  /* leading space befor alignment point */
1926   mchunkptr remainder;        /* spare room at end to split off */
1927   long      remainder_size;   /* its size */
1928
1929   if ((long)bytes < 0) return NULL;
1930
1931 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
1932         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
1933                 return memalign_simple(alignment, bytes);
1934         }
1935 #endif
1936
1937   /* If need less alignment than we give anyway, just relay to malloc */
1938
1939   if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
1940
1941   /* Otherwise, ensure that it is at least a minimum chunk size */
1942
1943   if (alignment <  MINSIZE) alignment = MINSIZE;
1944
1945   /* Call malloc with worst case padding to hit alignment. */
1946
1947   nb = request2size(bytes);
1948   m  = (char*)(mALLOc(nb + alignment + MINSIZE));
1949
1950   /*
1951   * The attempt to over-allocate (with a size large enough to guarantee the
1952   * ability to find an aligned region within allocated memory) failed.
1953   *
1954   * Try again, this time only allocating exactly the size the user wants. If
1955   * the allocation now succeeds and just happens to be aligned, we can still
1956   * fulfill the user's request.
1957   */
1958   if (m == NULL) {
1959     size_t extra, extra2;
1960     /*
1961      * Use bytes not nb, since mALLOc internally calls request2size too, and
1962      * each call increases the size to allocate, to account for the header.
1963      */
1964     m  = (char*)(mALLOc(bytes));
1965     /* Aligned -> return it */
1966     if ((((unsigned long)(m)) % alignment) == 0)
1967       return m;
1968     /*
1969      * Otherwise, try again, requesting enough extra space to be able to
1970      * acquire alignment.
1971      */
1972     fREe(m);
1973     /* Add in extra bytes to match misalignment of unexpanded allocation */
1974     extra = alignment - (((unsigned long)(m)) % alignment);
1975     m  = (char*)(mALLOc(bytes + extra));
1976     /*
1977      * m might not be the same as before. Validate that the previous value of
1978      * extra still works for the current value of m.
1979      * If (!m), extra2=alignment so 
1980      */
1981     if (m) {
1982       extra2 = alignment - (((unsigned long)(m)) % alignment);
1983       if (extra2 > extra) {
1984         fREe(m);
1985         m = NULL;
1986       }
1987     }
1988     /* Fall through to original NULL check and chunk splitting logic */
1989   }
1990
1991   if (m == NULL) return NULL; /* propagate failure */
1992
1993   p = mem2chunk(m);
1994
1995   if ((((unsigned long)(m)) % alignment) == 0) /* aligned */
1996   {
1997 #if HAVE_MMAP
1998     if(chunk_is_mmapped(p))
1999       return chunk2mem(p); /* nothing more to do */
2000 #endif
2001   }
2002   else /* misaligned */
2003   {
2004     /*
2005       Find an aligned spot inside chunk.
2006       Since we need to give back leading space in a chunk of at
2007       least MINSIZE, if the first calculation places us at
2008       a spot with less than MINSIZE leader, we can move to the
2009       next aligned spot -- we've allocated enough total room so that
2010       this is always possible.
2011     */
2012
2013     brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & -((signed) alignment));
2014     if ((long)(brk - (char*)(p)) < MINSIZE) brk = brk + alignment;
2015
2016     newp = (mchunkptr)brk;
2017     leadsize = brk - (char*)(p);
2018     newsize = chunksize(p) - leadsize;
2019
2020 #if HAVE_MMAP
2021     if(chunk_is_mmapped(p))
2022     {
2023       newp->prev_size = p->prev_size + leadsize;
2024       set_head(newp, newsize|IS_MMAPPED);
2025       return chunk2mem(newp);
2026     }
2027 #endif
2028
2029     /* give back leader, use the rest */
2030
2031     set_head(newp, newsize | PREV_INUSE);
2032     set_inuse_bit_at_offset(newp, newsize);
2033     set_head_size(p, leadsize);
2034     fREe(chunk2mem(p));
2035     p = newp;
2036
2037     assert (newsize >= nb && (((unsigned long)(chunk2mem(p))) % alignment) == 0);
2038   }
2039
2040   /* Also give back spare room at the end */
2041
2042   remainder_size = chunksize(p) - nb;
2043
2044   if (remainder_size >= (long)MINSIZE)
2045   {
2046     remainder = chunk_at_offset(p, nb);
2047     set_head(remainder, remainder_size | PREV_INUSE);
2048     set_head_size(p, nb);
2049     fREe(chunk2mem(remainder));
2050   }
2051
2052   check_inuse_chunk(p);
2053   return chunk2mem(p);
2054
2055 }
2056
2057
2058
2059
2060 /*
2061     valloc just invokes memalign with alignment argument equal
2062     to the page size of the system (or as near to this as can
2063     be figured out from all the includes/defines above.)
2064 */
2065
2066 #if __STD_C
2067 Void_t* vALLOc(size_t bytes)
2068 #else
2069 Void_t* vALLOc(bytes) size_t bytes;
2070 #endif
2071 {
2072   return mEMALIGn (malloc_getpagesize, bytes);
2073 }
2074
2075 /*
2076   pvalloc just invokes valloc for the nearest pagesize
2077   that will accommodate request
2078 */
2079
2080
2081 #if __STD_C
2082 Void_t* pvALLOc(size_t bytes)
2083 #else
2084 Void_t* pvALLOc(bytes) size_t bytes;
2085 #endif
2086 {
2087   size_t pagesize = malloc_getpagesize;
2088   return mEMALIGn (pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
2089 }
2090
2091 /*
2092
2093   calloc calls malloc, then zeroes out the allocated chunk.
2094
2095 */
2096
2097 #if __STD_C
2098 Void_t* cALLOc(size_t n, size_t elem_size)
2099 #else
2100 Void_t* cALLOc(n, elem_size) size_t n; size_t elem_size;
2101 #endif
2102 {
2103   mchunkptr p;
2104   INTERNAL_SIZE_T csz;
2105
2106   INTERNAL_SIZE_T sz = n * elem_size;
2107
2108
2109   /* check if expand_top called, in which case don't need to clear */
2110 #ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
2111 #if MORECORE_CLEARS
2112   mchunkptr oldtop = top;
2113   INTERNAL_SIZE_T oldtopsize = chunksize(top);
2114 #endif
2115 #endif
2116   Void_t* mem = mALLOc (sz);
2117
2118   if ((long)n < 0) return NULL;
2119
2120   if (mem == NULL)
2121     return NULL;
2122   else
2123   {
2124 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
2125         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
2126                 memset(mem, 0, sz);
2127                 return mem;
2128         }
2129 #endif
2130     p = mem2chunk(mem);
2131
2132     /* Two optional cases in which clearing not necessary */
2133
2134
2135 #if HAVE_MMAP
2136     if (chunk_is_mmapped(p)) return mem;
2137 #endif
2138
2139     csz = chunksize(p);
2140
2141 #ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
2142 #if MORECORE_CLEARS
2143     if (p == oldtop && csz > oldtopsize)
2144     {
2145       /* clear only the bytes from non-freshly-sbrked memory */
2146       csz = oldtopsize;
2147     }
2148 #endif
2149 #endif
2150
2151     MALLOC_ZERO(mem, csz - SIZE_SZ);
2152     return mem;
2153   }
2154 }
2155
2156 /*
2157
2158   cfree just calls free. It is needed/defined on some systems
2159   that pair it with calloc, presumably for odd historical reasons.
2160
2161 */
2162
2163 #if !defined(INTERNAL_LINUX_C_LIB) || !defined(__ELF__)
2164 #if __STD_C
2165 void cfree(Void_t *mem)
2166 #else
2167 void cfree(mem) Void_t *mem;
2168 #endif
2169 {
2170   fREe(mem);
2171 }
2172 #endif
2173
2174
2175
2176 /*
2177
2178     Malloc_trim gives memory back to the system (via negative
2179     arguments to sbrk) if there is unused memory at the `high' end of
2180     the malloc pool. You can call this after freeing large blocks of
2181     memory to potentially reduce the system-level memory requirements
2182     of a program. However, it cannot guarantee to reduce memory. Under
2183     some allocation patterns, some large free blocks of memory will be
2184     locked between two used chunks, so they cannot be given back to
2185     the system.
2186
2187     The `pad' argument to malloc_trim represents the amount of free
2188     trailing space to leave untrimmed. If this argument is zero,
2189     only the minimum amount of memory to maintain internal data
2190     structures will be left (one page or less). Non-zero arguments
2191     can be supplied to maintain enough trailing space to service
2192     future expected allocations without having to re-obtain memory
2193     from the system.
2194
2195     Malloc_trim returns 1 if it actually released any memory, else 0.
2196
2197 */
2198
2199 #if __STD_C
2200 int malloc_trim(size_t pad)
2201 #else
2202 int malloc_trim(pad) size_t pad;
2203 #endif
2204 {
2205   long  top_size;        /* Amount of top-most memory */
2206   long  extra;           /* Amount to release */
2207   char* current_brk;     /* address returned by pre-check sbrk call */
2208   char* new_brk;         /* address returned by negative sbrk call */
2209
2210   unsigned long pagesz = malloc_getpagesize;
2211
2212   top_size = chunksize(top);
2213   extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
2214
2215   if (extra < (long)pagesz)  /* Not enough memory to release */
2216     return 0;
2217
2218   else
2219   {
2220     /* Test to make sure no one else called sbrk */
2221     current_brk = (char*)(MORECORE (0));
2222     if (current_brk != (char*)(top) + top_size)
2223       return 0;     /* Apparently we don't own memory; must fail */
2224
2225     else
2226     {
2227       new_brk = (char*)(MORECORE (-extra));
2228
2229       if (new_brk == (char*)(MORECORE_FAILURE)) /* sbrk failed? */
2230       {
2231         /* Try to figure out what we have */
2232         current_brk = (char*)(MORECORE (0));
2233         top_size = current_brk - (char*)top;
2234         if (top_size >= (long)MINSIZE) /* if not, we are very very dead! */
2235         {
2236           sbrked_mem = current_brk - sbrk_base;
2237           set_head(top, top_size | PREV_INUSE);
2238         }
2239         check_chunk(top);
2240         return 0;
2241       }
2242
2243       else
2244       {
2245         /* Success. Adjust top accordingly. */
2246         set_head(top, (top_size - extra) | PREV_INUSE);
2247         sbrked_mem -= extra;
2248         check_chunk(top);
2249         return 1;
2250       }
2251     }
2252   }
2253 }
2254
2255
2256
2257 /*
2258   malloc_usable_size:
2259
2260     This routine tells you how many bytes you can actually use in an
2261     allocated chunk, which may be more than you requested (although
2262     often not). You can use this many bytes without worrying about
2263     overwriting other allocated objects. Not a particularly great
2264     programming practice, but still sometimes useful.
2265
2266 */
2267
2268 #if __STD_C
2269 size_t malloc_usable_size(Void_t* mem)
2270 #else
2271 size_t malloc_usable_size(mem) Void_t* mem;
2272 #endif
2273 {
2274   mchunkptr p;
2275   if (mem == NULL)
2276     return 0;
2277   else
2278   {
2279     p = mem2chunk(mem);
2280     if(!chunk_is_mmapped(p))
2281     {
2282       if (!inuse(p)) return 0;
2283       check_inuse_chunk(p);
2284       return chunksize(p) - SIZE_SZ;
2285     }
2286     return chunksize(p) - 2*SIZE_SZ;
2287   }
2288 }
2289
2290
2291
2292
2293 /* Utility to update current_mallinfo for malloc_stats and mallinfo() */
2294
2295 #ifdef DEBUG
2296 static void malloc_update_mallinfo()
2297 {
2298   int i;
2299   mbinptr b;
2300   mchunkptr p;
2301 #ifdef DEBUG
2302   mchunkptr q;
2303 #endif
2304
2305   INTERNAL_SIZE_T avail = chunksize(top);
2306   int   navail = ((long)(avail) >= (long)MINSIZE)? 1 : 0;
2307
2308   for (i = 1; i < NAV; ++i)
2309   {
2310     b = bin_at(i);
2311     for (p = last(b); p != b; p = p->bk)
2312     {
2313 #ifdef DEBUG
2314       check_free_chunk(p);
2315       for (q = next_chunk(p);
2316            q < top && inuse(q) && (long)(chunksize(q)) >= (long)MINSIZE;
2317            q = next_chunk(q))
2318         check_inuse_chunk(q);
2319 #endif
2320       avail += chunksize(p);
2321       navail++;
2322     }
2323   }
2324
2325   current_mallinfo.ordblks = navail;
2326   current_mallinfo.uordblks = sbrked_mem - avail;
2327   current_mallinfo.fordblks = avail;
2328   current_mallinfo.hblks = n_mmaps;
2329   current_mallinfo.hblkhd = mmapped_mem;
2330   current_mallinfo.keepcost = chunksize(top);
2331
2332 }
2333 #endif  /* DEBUG */
2334
2335
2336
2337 /*
2338
2339   malloc_stats:
2340
2341     Prints on the amount of space obtain from the system (both
2342     via sbrk and mmap), the maximum amount (which may be more than
2343     current if malloc_trim and/or munmap got called), the maximum
2344     number of simultaneous mmap regions used, and the current number
2345     of bytes allocated via malloc (or realloc, etc) but not yet
2346     freed. (Note that this is the number of bytes allocated, not the
2347     number requested. It will be larger than the number requested
2348     because of alignment and bookkeeping overhead.)
2349
2350 */
2351
2352 #ifdef DEBUG
2353 void malloc_stats()
2354 {
2355   malloc_update_mallinfo();
2356   printf("max system bytes = %10u\n",
2357           (unsigned int)(max_total_mem));
2358   printf("system bytes     = %10u\n",
2359           (unsigned int)(sbrked_mem + mmapped_mem));
2360   printf("in use bytes     = %10u\n",
2361           (unsigned int)(current_mallinfo.uordblks + mmapped_mem));
2362 #if HAVE_MMAP
2363   printf("max mmap regions = %10u\n",
2364           (unsigned int)max_n_mmaps);
2365 #endif
2366 }
2367 #endif  /* DEBUG */
2368
2369 /*
2370   mallinfo returns a copy of updated current mallinfo.
2371 */
2372
2373 #ifdef DEBUG
2374 struct mallinfo mALLINFo()
2375 {
2376   malloc_update_mallinfo();
2377   return current_mallinfo;
2378 }
2379 #endif  /* DEBUG */
2380
2381
2382
2383
2384 /*
2385   mallopt:
2386
2387     mallopt is the general SVID/XPG interface to tunable parameters.
2388     The format is to provide a (parameter-number, parameter-value) pair.
2389     mallopt then sets the corresponding parameter to the argument
2390     value if it can (i.e., so long as the value is meaningful),
2391     and returns 1 if successful else 0.
2392
2393     See descriptions of tunable parameters above.
2394
2395 */
2396
2397 #if __STD_C
2398 int mALLOPt(int param_number, int value)
2399 #else
2400 int mALLOPt(param_number, value) int param_number; int value;
2401 #endif
2402 {
2403   switch(param_number)
2404   {
2405     case M_TRIM_THRESHOLD:
2406       trim_threshold = value; return 1;
2407     case M_TOP_PAD:
2408       top_pad = value; return 1;
2409     case M_MMAP_THRESHOLD:
2410       mmap_threshold = value; return 1;
2411     case M_MMAP_MAX:
2412 #if HAVE_MMAP
2413       n_mmaps_max = value; return 1;
2414 #else
2415       if (value != 0) return 0; else  n_mmaps_max = value; return 1;
2416 #endif
2417
2418     default:
2419       return 0;
2420   }
2421 }
2422
2423 int initf_malloc(void)
2424 {
2425 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
2426         assert(gd->malloc_base);        /* Set up by crt0.S */
2427         gd->malloc_limit = CONFIG_VAL(SYS_MALLOC_F_LEN);
2428         gd->malloc_ptr = 0;
2429 #endif
2430
2431         return 0;
2432 }
2433
2434 /*
2435
2436 History:
2437
2438     V2.6.6 Sun Dec  5 07:42:19 1999  Doug Lea  (dl at gee)
2439       * return null for negative arguments
2440       * Added Several WIN32 cleanups from Martin C. Fong <mcfong@yahoo.com>
2441          * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
2442           (e.g. WIN32 platforms)
2443          * Cleanup up header file inclusion for WIN32 platforms
2444          * Cleanup code to avoid Microsoft Visual C++ compiler complaints
2445          * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
2446            memory allocation routines
2447          * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
2448          * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
2449            usage of 'assert' in non-WIN32 code
2450          * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
2451            avoid infinite loop
2452       * Always call 'fREe()' rather than 'free()'
2453
2454     V2.6.5 Wed Jun 17 15:57:31 1998  Doug Lea  (dl at gee)
2455       * Fixed ordering problem with boundary-stamping
2456
2457     V2.6.3 Sun May 19 08:17:58 1996  Doug Lea  (dl at gee)
2458       * Added pvalloc, as recommended by H.J. Liu
2459       * Added 64bit pointer support mainly from Wolfram Gloger
2460       * Added anonymously donated WIN32 sbrk emulation
2461       * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
2462       * malloc_extend_top: fix mask error that caused wastage after
2463         foreign sbrks
2464       * Add linux mremap support code from HJ Liu
2465
2466     V2.6.2 Tue Dec  5 06:52:55 1995  Doug Lea  (dl at gee)
2467       * Integrated most documentation with the code.
2468       * Add support for mmap, with help from
2469         Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
2470       * Use last_remainder in more cases.
2471       * Pack bins using idea from  colin@nyx10.cs.du.edu
2472       * Use ordered bins instead of best-fit threshhold
2473       * Eliminate block-local decls to simplify tracing and debugging.
2474       * Support another case of realloc via move into top
2475       * Fix error occuring when initial sbrk_base not word-aligned.
2476       * Rely on page size for units instead of SBRK_UNIT to
2477         avoid surprises about sbrk alignment conventions.
2478       * Add mallinfo, mallopt. Thanks to Raymond Nijssen
2479         (raymond@es.ele.tue.nl) for the suggestion.
2480       * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
2481       * More precautions for cases where other routines call sbrk,
2482         courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
2483       * Added macros etc., allowing use in linux libc from
2484         H.J. Lu (hjl@gnu.ai.mit.edu)
2485       * Inverted this history list
2486
2487     V2.6.1 Sat Dec  2 14:10:57 1995  Doug Lea  (dl at gee)
2488       * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
2489       * Removed all preallocation code since under current scheme
2490         the work required to undo bad preallocations exceeds
2491         the work saved in good cases for most test programs.
2492       * No longer use return list or unconsolidated bins since
2493         no scheme using them consistently outperforms those that don't
2494         given above changes.
2495       * Use best fit for very large chunks to prevent some worst-cases.
2496       * Added some support for debugging
2497
2498     V2.6.0 Sat Nov  4 07:05:23 1995  Doug Lea  (dl at gee)
2499       * Removed footers when chunks are in use. Thanks to
2500         Paul Wilson (wilson@cs.texas.edu) for the suggestion.
2501
2502     V2.5.4 Wed Nov  1 07:54:51 1995  Doug Lea  (dl at gee)
2503       * Added malloc_trim, with help from Wolfram Gloger
2504         (wmglo@Dent.MED.Uni-Muenchen.DE).
2505
2506     V2.5.3 Tue Apr 26 10:16:01 1994  Doug Lea  (dl at g)
2507
2508     V2.5.2 Tue Apr  5 16:20:40 1994  Doug Lea  (dl at g)
2509       * realloc: try to expand in both directions
2510       * malloc: swap order of clean-bin strategy;
2511       * realloc: only conditionally expand backwards
2512       * Try not to scavenge used bins
2513       * Use bin counts as a guide to preallocation
2514       * Occasionally bin return list chunks in first scan
2515       * Add a few optimizations from colin@nyx10.cs.du.edu
2516
2517     V2.5.1 Sat Aug 14 15:40:43 1993  Doug Lea  (dl at g)
2518       * faster bin computation & slightly different binning
2519       * merged all consolidations to one part of malloc proper
2520          (eliminating old malloc_find_space & malloc_clean_bin)
2521       * Scan 2 returns chunks (not just 1)
2522       * Propagate failure in realloc if malloc returns 0
2523       * Add stuff to allow compilation on non-ANSI compilers
2524           from kpv@research.att.com
2525
2526     V2.5 Sat Aug  7 07:41:59 1993  Doug Lea  (dl at g.oswego.edu)
2527       * removed potential for odd address access in prev_chunk
2528       * removed dependency on getpagesize.h
2529       * misc cosmetics and a bit more internal documentation
2530       * anticosmetics: mangled names in macros to evade debugger strangeness
2531       * tested on sparc, hp-700, dec-mips, rs6000
2532           with gcc & native cc (hp, dec only) allowing
2533           Detlefs & Zorn comparison study (in SIGPLAN Notices.)
2534
2535     Trial version Fri Aug 28 13:14:29 1992  Doug Lea  (dl at g.oswego.edu)
2536       * Based loosely on libg++-1.2X malloc. (It retains some of the overall
2537          structure of old version,  but most details differ.)
2538
2539 */