nand_base: We have to ignore the -EUCLEAN error
[barebox-mini2440.git] / common / dlmalloc.c
blobe524204730a70a03df089716b0fc2cf915623875
2 #include <malloc.h>
4 #include <config.h>
5 #include <stdio.h>
6 #include <module.h>
8 /*
9 Emulation of sbrk for WIN32
10 All code within the ifdef WIN32 is untested by me.
12 Thanks to Martin Fong and others for supplying this.
16 #ifdef WIN32
18 #define AlignPage(add) (((add) + (malloc_getpagesize-1)) & \
19 ~(malloc_getpagesize-1))
20 #define AlignPage64K(add) (((add) + (0x10000 - 1)) & ~(0x10000 - 1))
22 /* resrve 64MB to insure large contiguous space */
23 #define RESERVED_SIZE (1024*1024*64)
24 #define NEXT_SIZE (2048*1024)
25 #define TOP_MEMORY ((unsigned long)2*1024*1024*1024)
27 struct GmListElement;
28 typedef struct GmListElement GmListElement;
30 struct GmListElement
32 GmListElement* next;
33 void* base;
36 static GmListElement* head = 0;
37 static unsigned int gNextAddress = 0;
38 static unsigned int gAddressBase = 0;
39 static unsigned int gAllocatedSize = 0;
41 static
42 GmListElement* makeGmListElement (void* bas)
44 GmListElement* this;
45 this = (GmListElement*)(void*)LocalAlloc (0, sizeof (GmListElement));
46 assert (this);
47 if (this)
49 this->base = bas;
50 this->next = head;
51 head = this;
53 return this;
56 void gcleanup ()
58 BOOL rval;
59 assert ( (head == NULL) || (head->base == (void*)gAddressBase));
60 if (gAddressBase && (gNextAddress - gAddressBase))
62 rval = VirtualFree ((void*)gAddressBase,
63 gNextAddress - gAddressBase,
64 MEM_DECOMMIT);
65 assert (rval);
67 while (head)
69 GmListElement* next = head->next;
70 rval = VirtualFree (head->base, 0, MEM_RELEASE);
71 assert (rval);
72 LocalFree (head);
73 head = next;
77 static
78 void* findRegion (void* start_address, unsigned long size)
80 MEMORY_BASIC_INFORMATION info;
81 if (size >= TOP_MEMORY) return NULL;
83 while ((unsigned long)start_address + size < TOP_MEMORY)
85 VirtualQuery (start_address, &info, sizeof (info));
86 if ((info.State == MEM_FREE) && (info.RegionSize >= size))
87 return start_address;
88 else
90 /* Requested region is not available so see if the */
91 /* next region is available. Set 'start_address' */
92 /* to the next region and call 'VirtualQuery()' */
93 /* again. */
95 start_address = (char*)info.BaseAddress + info.RegionSize;
97 /* Make sure we start looking for the next region */
98 /* on the *next* 64K boundary. Otherwise, even if */
99 /* the new region is free according to */
100 /* 'VirtualQuery()', the subsequent call to */
101 /* 'VirtualAlloc()' (which follows the call to */
102 /* this routine in 'wsbrk()') will round *down* */
103 /* the requested address to a 64K boundary which */
104 /* we already know is an address in the */
105 /* unavailable region. Thus, the subsequent call */
106 /* to 'VirtualAlloc()' will fail and bring us back */
107 /* here, causing us to go into an infinite loop. */
109 start_address =
110 (void *) AlignPage64K((unsigned long) start_address);
113 return NULL;
118 void* wsbrk (long size)
120 void* tmp;
121 if (size > 0)
123 if (gAddressBase == 0)
125 gAllocatedSize = max (RESERVED_SIZE, AlignPage (size));
126 gNextAddress = gAddressBase =
127 (unsigned int)VirtualAlloc (NULL, gAllocatedSize,
128 MEM_RESERVE, PAGE_NOACCESS);
129 } else if (AlignPage (gNextAddress + size) > (gAddressBase +
130 gAllocatedSize))
132 long new_size = max (NEXT_SIZE, AlignPage (size));
133 void* new_address = (void*)(gAddressBase+gAllocatedSize);
136 new_address = findRegion (new_address, new_size);
138 if (new_address == 0)
139 return (void*)-1;
141 gAddressBase = gNextAddress =
142 (unsigned int)VirtualAlloc (new_address, new_size,
143 MEM_RESERVE, PAGE_NOACCESS);
144 /* repeat in case of race condition */
145 /* The region that we found has been snagged */
146 /* by another thread */
148 while (gAddressBase == 0);
150 assert (new_address == (void*)gAddressBase);
152 gAllocatedSize = new_size;
154 if (!makeGmListElement ((void*)gAddressBase))
155 return (void*)-1;
157 if ((size + gNextAddress) > AlignPage (gNextAddress))
159 void* res;
160 res = VirtualAlloc ((void*)AlignPage (gNextAddress),
161 (size + gNextAddress -
162 AlignPage (gNextAddress)),
163 MEM_COMMIT, PAGE_READWRITE);
164 if (res == 0)
165 return (void*)-1;
167 tmp = (void*)gNextAddress;
168 gNextAddress = (unsigned int)tmp + size;
169 return tmp;
171 else if (size < 0)
173 unsigned int alignedGoal = AlignPage (gNextAddress + size);
174 /* Trim by releasing the virtual memory */
175 if (alignedGoal >= gAddressBase)
177 VirtualFree ((void*)alignedGoal, gNextAddress - alignedGoal,
178 MEM_DECOMMIT);
179 gNextAddress = gNextAddress + size;
180 return (void*)gNextAddress;
182 else
184 VirtualFree ((void*)gAddressBase, gNextAddress - gAddressBase,
185 MEM_DECOMMIT);
186 gNextAddress = gAddressBase;
187 return (void*)-1;
190 else
192 return (void*)gNextAddress;
196 #endif
201 Type declarations
205 struct malloc_chunk
207 INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
208 INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
209 struct malloc_chunk* fd; /* double links -- used only if free. */
210 struct malloc_chunk* bk;
213 typedef struct malloc_chunk* mchunkptr;
217 malloc_chunk details:
219 (The following includes lightly edited explanations by Colin Plumb.)
221 Chunks of memory are maintained using a `boundary tag' method as
222 described in e.g., Knuth or Standish. (See the paper by Paul
223 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
224 survey of such techniques.) Sizes of free chunks are stored both
225 in the front of each chunk and at the end. This makes
226 consolidating fragmented chunks into bigger chunks very fast. The
227 size fields also hold bits representing whether chunks are free or
228 in use.
230 An allocated chunk looks like this:
233 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
234 | Size of previous chunk, if allocated | |
235 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
236 | Size of chunk, in bytes |P|
237 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
238 | User data starts here... .
240 . (malloc_usable_space() bytes) .
242 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
243 | Size of chunk |
244 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
247 Where "chunk" is the front of the chunk for the purpose of most of
248 the malloc code, but "mem" is the pointer that is returned to the
249 user. "Nextchunk" is the beginning of the next contiguous chunk.
251 Chunks always begin on even word boundries, so the mem portion
252 (which is returned to the user) is also on an even word boundary, and
253 thus double-word aligned.
255 Free chunks are stored in circular doubly-linked lists, and look like this:
257 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
258 | Size of previous chunk |
259 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
260 `head:' | Size of chunk, in bytes |P|
261 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
262 | Forward pointer to next chunk in list |
263 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
264 | Back pointer to previous chunk in list |
265 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
266 | Unused space (may be 0 bytes long) .
269 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
270 `foot:' | Size of chunk, in bytes |
271 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
273 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
274 chunk size (which is always a multiple of two words), is an in-use
275 bit for the *previous* chunk. If that bit is *clear*, then the
276 word before the current chunk size contains the previous chunk
277 size, and can be used to find the front of the previous chunk.
278 (The very first chunk allocated always has this bit set,
279 preventing access to non-existent (or non-owned) memory.)
281 Note that the `foot' of the current chunk is actually represented
282 as the prev_size of the NEXT chunk. (This makes it easier to
283 deal with alignments etc).
285 The two exceptions to all this are
287 1. The special chunk `top', which doesn't bother using the
288 trailing size field since there is no
289 next contiguous chunk that would have to index off it. (After
290 initialization, `top' is forced to always exist. If it would
291 become less than MINSIZE bytes long, it is replenished via
292 malloc_extend_top.)
294 2. Chunks allocated via mmap, which have the second-lowest-order
295 bit (IS_MMAPPED) set in their size fields. Because they are
296 never merged or traversed from any other chunk, they have no
297 foot size or inuse information.
299 Available chunks are kept in any of several places (all declared below):
301 * `av': An array of chunks serving as bin headers for consolidated
302 chunks. Each bin is doubly linked. The bins are approximately
303 proportionally (log) spaced. There are a lot of these bins
304 (128). This may look excessive, but works very well in
305 practice. All procedures maintain the invariant that no
306 consolidated chunk physically borders another one. Chunks in
307 bins are kept in size order, with ties going to the
308 approximately least recently used chunk.
310 The chunks in each bin are maintained in decreasing sorted order by
311 size. This is irrelevant for the small bins, which all contain
312 the same-sized chunks, but facilitates best-fit allocation for
313 larger chunks. (These lists are just sequential. Keeping them in
314 order almost never requires enough traversal to warrant using
315 fancier ordered data structures.) Chunks of the same size are
316 linked with the most recently freed at the front, and allocations
317 are taken from the back. This results in LRU or FIFO allocation
318 order, which tends to give each chunk an equal opportunity to be
319 consolidated with adjacent freed chunks, resulting in larger free
320 chunks and less fragmentation.
322 * `top': The top-most available chunk (i.e., the one bordering the
323 end of available memory) is treated specially. It is never
324 included in any bin, is used only if no other chunk is
325 available, and is released back to the system if it is very
326 large (see M_TRIM_THRESHOLD).
328 * `last_remainder': A bin holding only the remainder of the
329 most recently split (non-top) chunk. This bin is checked
330 before other non-fitting chunks, so as to provide better
331 locality for runs of sequentially allocated chunks.
333 * Implicitly, through the host system's memory mapping tables.
334 If supported, requests greater than a threshold are usually
335 serviced via calls to mmap, and then later released via munmap.
339 /* sizes, alignments */
341 #define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
342 #define MALLOC_ALIGNMENT (SIZE_SZ + SIZE_SZ)
343 #define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
344 #define MINSIZE (sizeof(struct malloc_chunk))
346 /* conversion from malloc headers to user pointers, and back */
348 #define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
349 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
351 /* pad request bytes into a usable size */
353 #define request2size(req) \
354 (((long)((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) < \
355 (long)(MINSIZE + MALLOC_ALIGN_MASK)) ? MINSIZE : \
356 (((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) & ~(MALLOC_ALIGN_MASK)))
358 /* Check if m has acceptable alignment */
360 #define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
366 Physical chunk operations
370 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
372 #define PREV_INUSE 0x1
374 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
376 #define IS_MMAPPED 0x2
378 /* Bits to mask off when extracting size */
380 #define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
383 /* Ptr to next physical malloc_chunk. */
385 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
387 /* Ptr to previous physical malloc_chunk */
389 #define prev_chunk(p)\
390 ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
393 /* Treat space at ptr + offset as a chunk */
395 #define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
401 Dealing with use bits
404 /* extract p's inuse bit */
406 #define inuse(p)\
407 ((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
409 /* extract inuse bit of previous chunk */
411 #define prev_inuse(p) ((p)->size & PREV_INUSE)
413 /* check for mmap()'ed chunk */
415 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
417 /* set/clear chunk as in use without otherwise disturbing */
419 #define set_inuse(p)\
420 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
422 #define clear_inuse(p)\
423 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
425 /* check/set/clear inuse bits in known places */
427 #define inuse_bit_at_offset(p, s)\
428 (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
430 #define set_inuse_bit_at_offset(p, s)\
431 (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
433 #define clear_inuse_bit_at_offset(p, s)\
434 (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
440 Dealing with size fields
443 /* Get size, ignoring use bits */
445 #define chunksize(p) ((p)->size & ~(SIZE_BITS))
447 /* Set size at head, without disturbing its use bit */
449 #define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
451 /* Set size/use ignoring previous bits in header */
453 #define set_head(p, s) ((p)->size = (s))
455 /* Set size at footer (only when chunk is not in use) */
457 #define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
464 Bins
466 The bins, `av_' are an array of pairs of pointers serving as the
467 heads of (initially empty) doubly-linked lists of chunks, laid out
468 in a way so that each pair can be treated as if it were in a
469 malloc_chunk. (This way, the fd/bk offsets for linking bin heads
470 and chunks are the same).
472 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
473 8 bytes apart. Larger bins are approximately logarithmically
474 spaced. (See the table below.) The `av_' array is never mentioned
475 directly in the code, but instead via bin access macros.
477 Bin layout:
479 64 bins of size 8
480 32 bins of size 64
481 16 bins of size 512
482 8 bins of size 4096
483 4 bins of size 32768
484 2 bins of size 262144
485 1 bin of size what's left
487 There is actually a little bit of slop in the numbers in bin_index
488 for the sake of speed. This makes no difference elsewhere.
490 The special chunks `top' and `last_remainder' get their own bins,
491 (this is implemented via yet more trickery with the av_ array),
492 although `top' is never properly linked to its bin since it is
493 always handled specially.
497 #define NAV 128 /* number of bins */
499 typedef struct malloc_chunk* mbinptr;
501 /* access macros */
503 #define bin_at(i) ((mbinptr)((char*)&(av_[2*(i) + 2]) - 2*SIZE_SZ))
504 #define next_bin(b) ((mbinptr)((char*)(b) + 2 * sizeof(mbinptr)))
505 #define prev_bin(b) ((mbinptr)((char*)(b) - 2 * sizeof(mbinptr)))
508 The first 2 bins are never indexed. The corresponding av_ cells are instead
509 used for bookkeeping. This is not to save space, but to simplify
510 indexing, maintain locality, and avoid some initialization tests.
513 #define top (bin_at(0)->fd) /* The topmost chunk */
514 #define last_remainder (bin_at(1)) /* remainder from last split */
518 Because top initially points to its own bin with initial
519 zero size, thus forcing extension on the first malloc request,
520 we avoid having any special code in malloc to check whether
521 it even exists yet. But we still need to in malloc_extend_top.
524 #define initial_top ((mchunkptr)(bin_at(0)))
526 /* Helper macro to initialize bins */
528 #define IAV(i) bin_at(i), bin_at(i)
530 static mbinptr av_[NAV * 2 + 2] = {
531 0, 0,
532 IAV(0), IAV(1), IAV(2), IAV(3), IAV(4), IAV(5), IAV(6), IAV(7),
533 IAV(8), IAV(9), IAV(10), IAV(11), IAV(12), IAV(13), IAV(14), IAV(15),
534 IAV(16), IAV(17), IAV(18), IAV(19), IAV(20), IAV(21), IAV(22), IAV(23),
535 IAV(24), IAV(25), IAV(26), IAV(27), IAV(28), IAV(29), IAV(30), IAV(31),
536 IAV(32), IAV(33), IAV(34), IAV(35), IAV(36), IAV(37), IAV(38), IAV(39),
537 IAV(40), IAV(41), IAV(42), IAV(43), IAV(44), IAV(45), IAV(46), IAV(47),
538 IAV(48), IAV(49), IAV(50), IAV(51), IAV(52), IAV(53), IAV(54), IAV(55),
539 IAV(56), IAV(57), IAV(58), IAV(59), IAV(60), IAV(61), IAV(62), IAV(63),
540 IAV(64), IAV(65), IAV(66), IAV(67), IAV(68), IAV(69), IAV(70), IAV(71),
541 IAV(72), IAV(73), IAV(74), IAV(75), IAV(76), IAV(77), IAV(78), IAV(79),
542 IAV(80), IAV(81), IAV(82), IAV(83), IAV(84), IAV(85), IAV(86), IAV(87),
543 IAV(88), IAV(89), IAV(90), IAV(91), IAV(92), IAV(93), IAV(94), IAV(95),
544 IAV(96), IAV(97), IAV(98), IAV(99), IAV(100), IAV(101), IAV(102), IAV(103),
545 IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
546 IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
547 IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
550 /* field-extraction macros */
552 #define first(b) ((b)->fd)
553 #define last(b) ((b)->bk)
556 Indexing into bins
559 #define bin_index(sz) \
560 (((((unsigned long)(sz)) >> 9) == 0) ? (((unsigned long)(sz)) >> 3): \
561 ((((unsigned long)(sz)) >> 9) <= 4) ? 56 + (((unsigned long)(sz)) >> 6): \
562 ((((unsigned long)(sz)) >> 9) <= 20) ? 91 + (((unsigned long)(sz)) >> 9): \
563 ((((unsigned long)(sz)) >> 9) <= 84) ? 110 + (((unsigned long)(sz)) >> 12): \
564 ((((unsigned long)(sz)) >> 9) <= 340) ? 119 + (((unsigned long)(sz)) >> 15): \
565 ((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18): \
566 126)
568 bins for chunks < 512 are all spaced 8 bytes apart, and hold
569 identically sized chunks. This is exploited in malloc.
572 #define MAX_SMALLBIN 63
573 #define MAX_SMALLBIN_SIZE 512
574 #define SMALLBIN_WIDTH 8
576 #define smallbin_index(sz) (((unsigned long)(sz)) >> 3)
579 Requests are `small' if both the corresponding and the next bin are small
582 #define is_small_request(nb) (nb < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
587 To help compensate for the large number of bins, a one-level index
588 structure is used for bin-by-bin searching. `binblocks' is a
589 one-word bitvector recording whether groups of BINBLOCKWIDTH bins
590 have any (possibly) non-empty bins, so they can be skipped over
591 all at once during during traversals. The bits are NOT always
592 cleared as soon as all bins in a block are empty, but instead only
593 when all are noticed to be empty during traversal in malloc.
596 #define BINBLOCKWIDTH 4 /* bins per block */
598 #define binblocks (bin_at(0)->size) /* bitvector of nonempty blocks */
600 /* bin<->block macros */
602 #define idx2binblock(ix) ((unsigned)1 << (ix / BINBLOCKWIDTH))
603 #define mark_binblock(ii) (binblocks |= idx2binblock(ii))
604 #define clear_binblock(ii) (binblocks &= ~(idx2binblock(ii)))
610 /* Other static bookkeeping data */
612 /* variables holding tunable values */
613 #ifndef __U_BOOT__
614 static unsigned long trim_threshold = DEFAULT_TRIM_THRESHOLD;
615 static unsigned int n_mmaps_max = DEFAULT_MMAP_MAX;
616 static unsigned long mmap_threshold = DEFAULT_MMAP_THRESHOLD;
617 #endif
618 static unsigned long top_pad = DEFAULT_TOP_PAD;
620 /* The first value returned from sbrk */
621 static char* sbrk_base = (char*)(-1);
623 /* The maximum memory obtained from system via sbrk */
624 static unsigned long max_sbrked_mem = 0;
626 /* The maximum via either sbrk or mmap */
627 static unsigned long max_total_mem = 0;
629 /* internal working copy of mallinfo */
630 static struct mallinfo current_mallinfo = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
632 /* The total memory obtained from system via sbrk */
633 #define sbrked_mem (current_mallinfo.arena)
635 /* Tracking mmaps */
637 static unsigned long mmapped_mem = 0;
642 Debugging support
645 #ifdef DEBUG
649 These routines make a number of assertions about the states
650 of data structures that should be true at all times. If any
651 are not true, it's very likely that a user program has somehow
652 trashed memory. (It's also possible that there is a coding error
653 in malloc. In which case, please report it!)
656 #if __STD_C
657 static void do_check_chunk(mchunkptr p)
658 #else
659 static void do_check_chunk(p) mchunkptr p;
660 #endif
663 /* No checkable chunk is mmapped */
664 assert(!chunk_is_mmapped(p));
666 /* Check for legal address ... */
667 assert((char*)p >= sbrk_base);
668 if (p != top)
669 assert((char*)p + sz <= (char*)top);
670 else
671 assert((char*)p + sz <= sbrk_base + sbrked_mem);
676 #if __STD_C
677 static void do_check_free_chunk(mchunkptr p)
678 #else
679 static void do_check_free_chunk(p) mchunkptr p;
680 #endif
682 INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
684 do_check_chunk(p);
686 /* Check whether it claims to be free ... */
687 assert(!inuse(p));
689 /* Unless a special marker, must have OK fields */
690 if ((long)sz >= (long)MINSIZE)
692 assert((sz & MALLOC_ALIGN_MASK) == 0);
693 assert(aligned_OK(chunk2mem(p)));
694 /* ... matching footer field */
695 assert(next->prev_size == sz);
696 /* ... and is fully consolidated */
697 assert(prev_inuse(p));
698 assert (next == top || inuse(next));
700 /* ... and has minimally sane links */
701 assert(p->fd->bk == p);
702 assert(p->bk->fd == p);
704 else /* markers are always of size SIZE_SZ */
705 assert(sz == SIZE_SZ);
708 #if __STD_C
709 static void do_check_inuse_chunk(mchunkptr p)
710 #else
711 static void do_check_inuse_chunk(p) mchunkptr p;
712 #endif
714 mchunkptr next = next_chunk(p);
715 do_check_chunk(p);
717 /* Check whether it claims to be in use ... */
718 assert(inuse(p));
720 /* ... and is surrounded by OK chunks.
721 Since more things can be checked with free chunks than inuse ones,
722 if an inuse chunk borders them and debug is on, it's worth doing them.
724 if (!prev_inuse(p))
726 mchunkptr prv = prev_chunk(p);
727 assert(next_chunk(prv) == p);
728 do_check_free_chunk(prv);
730 if (next == top)
732 assert(prev_inuse(next));
733 assert(chunksize(next) >= MINSIZE);
735 else if (!inuse(next))
736 do_check_free_chunk(next);
740 #if __STD_C
741 static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)
742 #else
743 static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;
744 #endif
747 do_check_inuse_chunk(p);
749 /* Legal size ... */
750 assert((long)sz >= (long)MINSIZE);
751 assert((sz & MALLOC_ALIGN_MASK) == 0);
752 assert(room >= 0);
753 assert(room < (long)MINSIZE);
755 /* ... and alignment */
756 assert(aligned_OK(chunk2mem(p)));
759 /* ... and was allocated at front of an available chunk */
760 assert(prev_inuse(p));
765 #define check_free_chunk(P) do_check_free_chunk(P)
766 #define check_inuse_chunk(P) do_check_inuse_chunk(P)
767 #define check_chunk(P) do_check_chunk(P)
768 #define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N)
769 #else
770 #define check_free_chunk(P)
771 #define check_inuse_chunk(P)
772 #define check_chunk(P)
773 #define check_malloced_chunk(P,N)
774 #endif
779 Macro-based internal utilities
784 Linking chunks in bin lists.
785 Call these only with variables, not arbitrary expressions, as arguments.
789 Place chunk p of size s in its bin, in size order,
790 putting it ahead of others of same size.
794 #define frontlink(P, S, IDX, BK, FD) \
796 if (S < MAX_SMALLBIN_SIZE) \
798 IDX = smallbin_index(S); \
799 mark_binblock(IDX); \
800 BK = bin_at(IDX); \
801 FD = BK->fd; \
802 P->bk = BK; \
803 P->fd = FD; \
804 FD->bk = BK->fd = P; \
806 else \
808 IDX = bin_index(S); \
809 BK = bin_at(IDX); \
810 FD = BK->fd; \
811 if (FD == BK) mark_binblock(IDX); \
812 else \
814 while (FD != BK && S < chunksize(FD)) FD = FD->fd; \
815 BK = FD->bk; \
817 P->bk = BK; \
818 P->fd = FD; \
819 FD->bk = BK->fd = P; \
824 /* take a chunk off a list */
826 #define unlink(P, BK, FD) \
828 BK = P->bk; \
829 FD = P->fd; \
830 FD->bk = BK; \
831 BK->fd = FD; \
834 /* Place p as the last remainder */
836 #define link_last_remainder(P) \
838 last_remainder->fd = last_remainder->bk = P; \
839 P->fd = P->bk = last_remainder; \
842 /* Clear the last_remainder bin */
844 #define clear_last_remainder \
845 (last_remainder->fd = last_remainder->bk = last_remainder)
851 /* Routines dealing with mmap(). */
858 Extend the top-most chunk by obtaining memory from system.
859 Main interface to sbrk (but see also malloc_trim).
862 #if __STD_C
863 static void malloc_extend_top(INTERNAL_SIZE_T nb)
864 #else
865 static void malloc_extend_top(nb) INTERNAL_SIZE_T nb;
866 #endif
868 char* brk; /* return value from sbrk */
869 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of sbrked space */
870 INTERNAL_SIZE_T correction; /* bytes for 2nd sbrk call */
871 char* new_brk; /* return of 2nd sbrk call */
872 INTERNAL_SIZE_T top_size; /* new size of top chunk */
874 mchunkptr old_top = top; /* Record state of old top */
875 INTERNAL_SIZE_T old_top_size = chunksize(old_top);
876 char* old_end = (char*)(chunk_at_offset(old_top, old_top_size));
878 /* Pad request with top_pad plus minimal overhead */
880 INTERNAL_SIZE_T sbrk_size = nb + top_pad + MINSIZE;
881 unsigned long pagesz = malloc_getpagesize;
883 /* If not the first time through, round to preserve page boundary */
884 /* Otherwise, we need to correct to a page size below anyway. */
885 /* (We also correct below if an intervening foreign sbrk call.) */
887 if (sbrk_base != (char*)(-1))
888 sbrk_size = (sbrk_size + (pagesz - 1)) & ~(pagesz - 1);
890 brk = (char*)(MORECORE (sbrk_size));
892 /* Fail if sbrk failed or if a foreign sbrk call killed our space */
893 if (brk == (char*)(MORECORE_FAILURE) ||
894 (brk < old_end && old_top != initial_top))
895 return;
897 sbrked_mem += sbrk_size;
899 if (brk == old_end) /* can just add bytes to current top */
901 top_size = sbrk_size + old_top_size;
902 set_head(top, top_size | PREV_INUSE);
904 else
906 if (sbrk_base == (char*)(-1)) /* First time through. Record base */
907 sbrk_base = brk;
908 else /* Someone else called sbrk(). Count those bytes as sbrked_mem. */
909 sbrked_mem += brk - (char*)old_end;
911 /* Guarantee alignment of first new chunk made from this space */
912 front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
913 if (front_misalign > 0)
915 correction = (MALLOC_ALIGNMENT) - front_misalign;
916 brk += correction;
918 else
919 correction = 0;
921 /* Guarantee the next brk will be at a page boundary */
923 correction += ((((unsigned long)(brk + sbrk_size))+(pagesz-1)) &
924 ~(pagesz - 1)) - ((unsigned long)(brk + sbrk_size));
926 /* Allocate correction */
927 new_brk = (char*)(MORECORE (correction));
928 if (new_brk == (char*)(MORECORE_FAILURE)) return;
930 sbrked_mem += correction;
932 top = (mchunkptr)brk;
933 top_size = new_brk - brk + correction;
934 set_head(top, top_size | PREV_INUSE);
936 if (old_top != initial_top)
939 /* There must have been an intervening foreign sbrk call. */
940 /* A double fencepost is necessary to prevent consolidation */
942 /* If not enough space to do this, then user did something very wrong */
943 if (old_top_size < MINSIZE)
945 set_head(top, PREV_INUSE); /* will force null return from malloc */
946 return;
949 /* Also keep size a multiple of MALLOC_ALIGNMENT */
950 old_top_size = (old_top_size - 3*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
951 set_head_size(old_top, old_top_size);
952 chunk_at_offset(old_top, old_top_size )->size =
953 SIZE_SZ|PREV_INUSE;
954 chunk_at_offset(old_top, old_top_size + SIZE_SZ)->size =
955 SIZE_SZ|PREV_INUSE;
956 /* If possible, release the rest. */
957 if (old_top_size >= MINSIZE)
958 fREe(chunk2mem(old_top));
962 if ((unsigned long)sbrked_mem > (unsigned long)max_sbrked_mem)
963 max_sbrked_mem = sbrked_mem;
964 if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
965 max_total_mem = mmapped_mem + sbrked_mem;
967 /* We always land on a page boundary */
968 assert(((unsigned long)((char*)top + top_size) & (pagesz - 1)) == 0);
974 /* Main public routines */
978 Malloc Algorthim:
980 The requested size is first converted into a usable form, `nb'.
981 This currently means to add 4 bytes overhead plus possibly more to
982 obtain 8-byte alignment and/or to obtain a size of at least
983 MINSIZE (currently 16 bytes), the smallest allocatable size.
984 (All fits are considered `exact' if they are within MINSIZE bytes.)
986 From there, the first successful of the following steps is taken:
988 1. The bin corresponding to the request size is scanned, and if
989 a chunk of exactly the right size is found, it is taken.
991 2. The most recently remaindered chunk is used if it is big
992 enough. This is a form of (roving) first fit, used only in
993 the absence of exact fits. Runs of consecutive requests use
994 the remainder of the chunk used for the previous such request
995 whenever possible. This limited use of a first-fit style
996 allocation strategy tends to give contiguous chunks
997 coextensive lifetimes, which improves locality and can reduce
998 fragmentation in the long run.
1000 3. Other bins are scanned in increasing size order, using a
1001 chunk big enough to fulfill the request, and splitting off
1002 any remainder. This search is strictly by best-fit; i.e.,
1003 the smallest (with ties going to approximately the least
1004 recently used) chunk that fits is selected.
1006 4. If large enough, the chunk bordering the end of memory
1007 (`top') is split off. (This use of `top' is in accord with
1008 the best-fit search rule. In effect, `top' is treated as
1009 larger (and thus less well fitting) than any other available
1010 chunk since it can be extended to be as large as necessary
1011 (up to system limitations).
1013 5. If the request size meets the mmap threshold and the
1014 system supports mmap, and there are few enough currently
1015 allocated mmapped regions, and a call to mmap succeeds,
1016 the request is allocated via direct memory mapping.
1018 6. Otherwise, the top of memory is extended by
1019 obtaining more space from the system (normally using sbrk,
1020 but definable to anything else via the MORECORE macro).
1021 Memory is gathered from the system (in system page-sized
1022 units) in a way that allows chunks obtained across different
1023 sbrk calls to be consolidated, but does not require
1024 contiguous memory. Thus, it should be safe to intersperse
1025 mallocs with other sbrk calls.
1028 All allocations are made from the the `lowest' part of any found
1029 chunk. (The implementation invariant is that prev_inuse is
1030 always true of any allocated chunk; i.e., that each allocated
1031 chunk borders either a previously allocated and still in-use chunk,
1032 or the base of its memory arena.)
1036 #if __STD_C
1037 Void_t* mALLOc(size_t bytes)
1038 #else
1039 Void_t* mALLOc(bytes) size_t bytes;
1040 #endif
1042 mchunkptr victim; /* inspected/selected chunk */
1043 INTERNAL_SIZE_T victim_size; /* its size */
1044 int idx; /* index for bin traversal */
1045 mbinptr bin; /* associated bin */
1046 mchunkptr remainder; /* remainder from a split */
1047 long remainder_size; /* its size */
1048 int remainder_index; /* its bin index */
1049 unsigned long block; /* block traverser bit */
1050 int startidx; /* first bin of a traversed block */
1051 mchunkptr fwd; /* misc temp for linking */
1052 mchunkptr bck; /* misc temp for linking */
1053 mbinptr q; /* misc temp */
1055 INTERNAL_SIZE_T nb;
1057 if ((long)bytes < 0) return 0;
1059 nb = request2size(bytes); /* padded request size; */
1061 /* Check for exact match in a bin */
1063 if (is_small_request(nb)) /* Faster version for small requests */
1065 idx = smallbin_index(nb);
1067 /* No traversal or size check necessary for small bins. */
1069 q = bin_at(idx);
1070 victim = last(q);
1072 /* Also scan the next one, since it would have a remainder < MINSIZE */
1073 if (victim == q)
1075 q = next_bin(q);
1076 victim = last(q);
1078 if (victim != q)
1080 victim_size = chunksize(victim);
1081 unlink(victim, bck, fwd);
1082 set_inuse_bit_at_offset(victim, victim_size);
1083 check_malloced_chunk(victim, nb);
1084 return chunk2mem(victim);
1087 idx += 2; /* Set for bin scan below. We've already scanned 2 bins. */
1090 else
1092 idx = bin_index(nb);
1093 bin = bin_at(idx);
1095 for (victim = last(bin); victim != bin; victim = victim->bk)
1097 victim_size = chunksize(victim);
1098 remainder_size = victim_size - nb;
1100 if (remainder_size >= (long)MINSIZE) /* too big */
1102 --idx; /* adjust to rescan below after checking last remainder */
1103 break;
1106 else if (remainder_size >= 0) /* exact fit */
1108 unlink(victim, bck, fwd);
1109 set_inuse_bit_at_offset(victim, victim_size);
1110 check_malloced_chunk(victim, nb);
1111 return chunk2mem(victim);
1115 ++idx;
1119 /* Try to use the last split-off remainder */
1121 if ( (victim = last_remainder->fd) != last_remainder)
1123 victim_size = chunksize(victim);
1124 remainder_size = victim_size - nb;
1126 if (remainder_size >= (long)MINSIZE) /* re-split */
1128 remainder = chunk_at_offset(victim, nb);
1129 set_head(victim, nb | PREV_INUSE);
1130 link_last_remainder(remainder);
1131 set_head(remainder, remainder_size | PREV_INUSE);
1132 set_foot(remainder, remainder_size);
1133 check_malloced_chunk(victim, nb);
1134 return chunk2mem(victim);
1137 clear_last_remainder;
1139 if (remainder_size >= 0) /* exhaust */
1141 set_inuse_bit_at_offset(victim, victim_size);
1142 check_malloced_chunk(victim, nb);
1143 return chunk2mem(victim);
1146 /* Else place in bin */
1148 frontlink(victim, victim_size, remainder_index, bck, fwd);
1152 If there are any possibly nonempty big-enough blocks,
1153 search for best fitting chunk by scanning bins in blockwidth units.
1156 if ( (block = idx2binblock(idx)) <= binblocks)
1159 /* Get to the first marked block */
1161 if ( (block & binblocks) == 0)
1163 /* force to an even block boundary */
1164 idx = (idx & ~(BINBLOCKWIDTH - 1)) + BINBLOCKWIDTH;
1165 block <<= 1;
1166 while ((block & binblocks) == 0)
1168 idx += BINBLOCKWIDTH;
1169 block <<= 1;
1173 /* For each possibly nonempty block ... */
1174 for (;;)
1176 startidx = idx; /* (track incomplete blocks) */
1177 q = bin = bin_at(idx);
1179 /* For each bin in this block ... */
1182 /* Find and use first big enough chunk ... */
1184 for (victim = last(bin); victim != bin; victim = victim->bk)
1186 victim_size = chunksize(victim);
1187 remainder_size = victim_size - nb;
1189 if (remainder_size >= (long)MINSIZE) /* split */
1191 remainder = chunk_at_offset(victim, nb);
1192 set_head(victim, nb | PREV_INUSE);
1193 unlink(victim, bck, fwd);
1194 link_last_remainder(remainder);
1195 set_head(remainder, remainder_size | PREV_INUSE);
1196 set_foot(remainder, remainder_size);
1197 check_malloced_chunk(victim, nb);
1198 return chunk2mem(victim);
1201 else if (remainder_size >= 0) /* take */
1203 set_inuse_bit_at_offset(victim, victim_size);
1204 unlink(victim, bck, fwd);
1205 check_malloced_chunk(victim, nb);
1206 return chunk2mem(victim);
1211 bin = next_bin(bin);
1213 } while ((++idx & (BINBLOCKWIDTH - 1)) != 0);
1215 /* Clear out the block bit. */
1217 do /* Possibly backtrack to try to clear a partial block */
1219 if ((startidx & (BINBLOCKWIDTH - 1)) == 0)
1221 binblocks &= ~block;
1222 break;
1224 --startidx;
1225 q = prev_bin(q);
1226 } while (first(q) == q);
1228 /* Get to the next possibly nonempty block */
1230 if ( (block <<= 1) <= binblocks && (block != 0) )
1232 while ((block & binblocks) == 0)
1234 idx += BINBLOCKWIDTH;
1235 block <<= 1;
1238 else
1239 break;
1244 /* Try to use top chunk */
1246 /* Require that there be a remainder, ensuring top always exists */
1247 if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
1251 /* Try to extend */
1252 malloc_extend_top(nb);
1253 if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
1254 return 0; /* propagate failure */
1257 victim = top;
1258 set_head(victim, nb | PREV_INUSE);
1259 top = chunk_at_offset(victim, nb);
1260 set_head(top, remainder_size | PREV_INUSE);
1261 check_malloced_chunk(victim, nb);
1262 return chunk2mem(victim);
1271 free() algorithm :
1273 cases:
1275 1. free(0) has no effect.
1277 2. If the chunk was allocated via mmap, it is release via munmap().
1279 3. If a returned chunk borders the current high end of memory,
1280 it is consolidated into the top, and if the total unused
1281 topmost memory exceeds the trim threshold, malloc_trim is
1282 called.
1284 4. Other chunks are consolidated as they arrive, and
1285 placed in corresponding bins. (This includes the case of
1286 consolidating with the current `last_remainder').
1291 #if __STD_C
1292 void fREe(Void_t* mem)
1293 #else
1294 void fREe(mem) Void_t* mem;
1295 #endif
1297 mchunkptr p; /* chunk corresponding to mem */
1298 INTERNAL_SIZE_T hd; /* its head field */
1299 INTERNAL_SIZE_T sz; /* its size */
1300 int idx; /* its bin index */
1301 mchunkptr next; /* next contiguous chunk */
1302 INTERNAL_SIZE_T nextsz; /* its size */
1303 INTERNAL_SIZE_T prevsz; /* size of previous contiguous chunk */
1304 mchunkptr bck; /* misc temp for linking */
1305 mchunkptr fwd; /* misc temp for linking */
1306 int islr; /* track whether merging with last_remainder */
1308 if (mem == 0) /* free(0) has no effect */
1309 return;
1311 p = mem2chunk(mem);
1312 hd = p->size;
1315 check_inuse_chunk(p);
1317 sz = hd & ~PREV_INUSE;
1318 next = chunk_at_offset(p, sz);
1319 nextsz = chunksize(next);
1321 if (next == top) /* merge with top */
1323 sz += nextsz;
1325 if (!(hd & PREV_INUSE)) /* consolidate backward */
1327 prevsz = p->prev_size;
1328 p = chunk_at_offset(p, -((long) prevsz));
1329 sz += prevsz;
1330 unlink(p, bck, fwd);
1333 set_head(p, sz | PREV_INUSE);
1334 top = p;
1335 #ifdef USE_MALLOC_TRIM
1336 if ((unsigned long)(sz) >= (unsigned long)trim_threshold)
1337 malloc_trim(top_pad);
1338 #endif
1339 return;
1342 set_head(next, nextsz); /* clear inuse bit */
1344 islr = 0;
1346 if (!(hd & PREV_INUSE)) /* consolidate backward */
1348 prevsz = p->prev_size;
1349 p = chunk_at_offset(p, -((long) prevsz));
1350 sz += prevsz;
1352 if (p->fd == last_remainder) /* keep as last_remainder */
1353 islr = 1;
1354 else
1355 unlink(p, bck, fwd);
1358 if (!(inuse_bit_at_offset(next, nextsz))) /* consolidate forward */
1360 sz += nextsz;
1362 if (!islr && next->fd == last_remainder) /* re-insert last_remainder */
1364 islr = 1;
1365 link_last_remainder(p);
1367 else
1368 unlink(next, bck, fwd);
1372 set_head(p, sz | PREV_INUSE);
1373 set_foot(p, sz);
1374 if (!islr)
1375 frontlink(p, sz, idx, bck, fwd);
1384 Realloc algorithm:
1386 Chunks that were obtained via mmap cannot be extended or shrunk
1387 unless HAVE_MREMAP is defined, in which case mremap is used.
1388 Otherwise, if their reallocation is for additional space, they are
1389 copied. If for less, they are just left alone.
1391 Otherwise, if the reallocation is for additional space, and the
1392 chunk can be extended, it is, else a malloc-copy-free sequence is
1393 taken. There are several different ways that a chunk could be
1394 extended. All are tried:
1396 * Extending forward into following adjacent free chunk.
1397 * Shifting backwards, joining preceding adjacent space
1398 * Both shifting backwards and extending forward.
1399 * Extending into newly sbrked space
1401 Unless the #define REALLOC_ZERO_BYTES_FREES is set, realloc with a
1402 size argument of zero (re)allocates a minimum-sized chunk.
1404 If the reallocation is for less space, and the new request is for
1405 a `small' (<512 bytes) size, then the newly unused space is lopped
1406 off and freed.
1408 The old unix realloc convention of allowing the last-free'd chunk
1409 to be used as an argument to realloc is no longer supported.
1410 I don't know of any programs still relying on this feature,
1411 and allowing it would also allow too many other incorrect
1412 usages of realloc to be sensible.
1418 #if __STD_C
1419 Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
1420 #else
1421 Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
1422 #endif
1424 INTERNAL_SIZE_T nb; /* padded request size */
1426 mchunkptr oldp; /* chunk corresponding to oldmem */
1427 INTERNAL_SIZE_T oldsize; /* its size */
1429 mchunkptr newp; /* chunk to return */
1430 INTERNAL_SIZE_T newsize; /* its size */
1431 Void_t* newmem; /* corresponding user mem */
1433 mchunkptr next; /* next contiguous chunk after oldp */
1434 INTERNAL_SIZE_T nextsize; /* its size */
1436 mchunkptr prev; /* previous contiguous chunk before oldp */
1437 INTERNAL_SIZE_T prevsize; /* its size */
1439 mchunkptr remainder; /* holds split off extra space from newp */
1440 INTERNAL_SIZE_T remainder_size; /* its size */
1442 mchunkptr bck; /* misc temp for linking */
1443 mchunkptr fwd; /* misc temp for linking */
1445 #ifdef REALLOC_ZERO_BYTES_FREES
1446 if (bytes == 0) { fREe(oldmem); return 0; }
1447 #endif
1449 if ((long)bytes < 0) return 0;
1451 /* realloc of null is supposed to be same as malloc */
1452 if (oldmem == 0) return mALLOc(bytes);
1454 newp = oldp = mem2chunk(oldmem);
1455 newsize = oldsize = chunksize(oldp);
1458 nb = request2size(bytes);
1461 check_inuse_chunk(oldp);
1463 if ((long)(oldsize) < (long)(nb))
1466 /* Try expanding forward */
1468 next = chunk_at_offset(oldp, oldsize);
1469 if (next == top || !inuse(next))
1471 nextsize = chunksize(next);
1473 /* Forward into top only if a remainder */
1474 if (next == top)
1476 if ((long)(nextsize + newsize) >= (long)(nb + MINSIZE))
1478 newsize += nextsize;
1479 top = chunk_at_offset(oldp, nb);
1480 set_head(top, (newsize - nb) | PREV_INUSE);
1481 set_head_size(oldp, nb);
1482 return chunk2mem(oldp);
1486 /* Forward into next chunk */
1487 else if (((long)(nextsize + newsize) >= (long)(nb)))
1489 unlink(next, bck, fwd);
1490 newsize += nextsize;
1491 goto split;
1494 else
1496 next = 0;
1497 nextsize = 0;
1500 /* Try shifting backwards. */
1502 if (!prev_inuse(oldp))
1504 prev = prev_chunk(oldp);
1505 prevsize = chunksize(prev);
1507 /* try forward + backward first to save a later consolidation */
1509 if (next != 0)
1511 /* into top */
1512 if (next == top)
1514 if ((long)(nextsize + prevsize + newsize) >= (long)(nb + MINSIZE))
1516 unlink(prev, bck, fwd);
1517 newp = prev;
1518 newsize += prevsize + nextsize;
1519 newmem = chunk2mem(newp);
1520 MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1521 top = chunk_at_offset(newp, nb);
1522 set_head(top, (newsize - nb) | PREV_INUSE);
1523 set_head_size(newp, nb);
1524 return newmem;
1528 /* into next chunk */
1529 else if (((long)(nextsize + prevsize + newsize) >= (long)(nb)))
1531 unlink(next, bck, fwd);
1532 unlink(prev, bck, fwd);
1533 newp = prev;
1534 newsize += nextsize + prevsize;
1535 newmem = chunk2mem(newp);
1536 MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1537 goto split;
1541 /* backward only */
1542 if (prev != 0 && (long)(prevsize + newsize) >= (long)nb)
1544 unlink(prev, bck, fwd);
1545 newp = prev;
1546 newsize += prevsize;
1547 newmem = chunk2mem(newp);
1548 MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1549 goto split;
1553 /* Must allocate */
1555 newmem = mALLOc (bytes);
1557 if (newmem == 0) /* propagate failure */
1558 return 0;
1560 /* Avoid copy if newp is next chunk after oldp. */
1561 /* (This can only happen when new chunk is sbrk'ed.) */
1563 if ( (newp = mem2chunk(newmem)) == next_chunk(oldp))
1565 newsize += chunksize(newp);
1566 newp = oldp;
1567 goto split;
1570 /* Otherwise copy, free, and exit */
1571 MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1572 fREe(oldmem);
1573 return newmem;
1577 split: /* split off extra room in old or expanded chunk */
1579 if (newsize - nb >= MINSIZE) /* split off remainder */
1581 remainder = chunk_at_offset(newp, nb);
1582 remainder_size = newsize - nb;
1583 set_head_size(newp, nb);
1584 set_head(remainder, remainder_size | PREV_INUSE);
1585 set_inuse_bit_at_offset(remainder, remainder_size);
1586 fREe(chunk2mem(remainder)); /* let free() deal with it */
1588 else
1590 set_head_size(newp, newsize);
1591 set_inuse_bit_at_offset(newp, newsize);
1594 check_inuse_chunk(newp);
1595 return chunk2mem(newp);
1603 memalign algorithm:
1605 memalign requests more than enough space from malloc, finds a spot
1606 within that chunk that meets the alignment request, and then
1607 possibly frees the leading and trailing space.
1609 The alignment argument must be a power of two. This property is not
1610 checked by memalign, so misuse may result in random runtime errors.
1612 8-byte alignment is guaranteed by normal malloc calls, so don't
1613 bother calling memalign with an argument of 8 or less.
1615 Overreliance on memalign is a sure way to fragment space.
1620 #if __STD_C
1621 Void_t* mEMALIGn(size_t alignment, size_t bytes)
1622 #else
1623 Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
1624 #endif
1626 INTERNAL_SIZE_T nb; /* padded request size */
1627 char* m; /* memory returned by malloc call */
1628 mchunkptr p; /* corresponding chunk */
1629 char* brk; /* alignment point within p */
1630 mchunkptr newp; /* chunk to return */
1631 INTERNAL_SIZE_T newsize; /* its size */
1632 INTERNAL_SIZE_T leadsize; /* leading space befor alignment point */
1633 mchunkptr remainder; /* spare room at end to split off */
1634 long remainder_size; /* its size */
1636 if ((long)bytes < 0) return 0;
1638 /* If need less alignment than we give anyway, just relay to malloc */
1640 if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
1642 /* Otherwise, ensure that it is at least a minimum chunk size */
1644 if (alignment < MINSIZE) alignment = MINSIZE;
1646 /* Call malloc with worst case padding to hit alignment. */
1648 nb = request2size(bytes);
1649 m = (char*)(mALLOc(nb + alignment + MINSIZE));
1651 if (m == 0) return 0; /* propagate failure */
1653 p = mem2chunk(m);
1655 if ((((unsigned long)(m)) % alignment) == 0) /* aligned */
1658 else /* misaligned */
1661 Find an aligned spot inside chunk.
1662 Since we need to give back leading space in a chunk of at
1663 least MINSIZE, if the first calculation places us at
1664 a spot with less than MINSIZE leader, we can move to the
1665 next aligned spot -- we've allocated enough total room so that
1666 this is always possible.
1669 brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & -((signed) alignment));
1670 if ((long)(brk - (char*)(p)) < MINSIZE) brk = brk + alignment;
1672 newp = (mchunkptr)brk;
1673 leadsize = brk - (char*)(p);
1674 newsize = chunksize(p) - leadsize;
1677 /* give back leader, use the rest */
1679 set_head(newp, newsize | PREV_INUSE);
1680 set_inuse_bit_at_offset(newp, newsize);
1681 set_head_size(p, leadsize);
1682 fREe(chunk2mem(p));
1683 p = newp;
1685 assert (newsize >= nb && (((unsigned long)(chunk2mem(p))) % alignment) == 0);
1688 /* Also give back spare room at the end */
1690 remainder_size = chunksize(p) - nb;
1692 if (remainder_size >= (long)MINSIZE)
1694 remainder = chunk_at_offset(p, nb);
1695 set_head(remainder, remainder_size | PREV_INUSE);
1696 set_head_size(p, nb);
1697 fREe(chunk2mem(remainder));
1700 check_inuse_chunk(p);
1701 return chunk2mem(p);
1709 valloc just invokes memalign with alignment argument equal
1710 to the page size of the system (or as near to this as can
1711 be figured out from all the includes/defines above.)
1714 #if __STD_C
1715 Void_t* vALLOc(size_t bytes)
1716 #else
1717 Void_t* vALLOc(bytes) size_t bytes;
1718 #endif
1720 return mEMALIGn (malloc_getpagesize, bytes);
1724 pvalloc just invokes valloc for the nearest pagesize
1725 that will accommodate request
1729 #if __STD_C
1730 Void_t* pvALLOc(size_t bytes)
1731 #else
1732 Void_t* pvALLOc(bytes) size_t bytes;
1733 #endif
1735 size_t pagesize = malloc_getpagesize;
1736 return mEMALIGn (pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
1741 calloc calls malloc, then zeroes out the allocated chunk.
1745 #if __STD_C
1746 Void_t* cALLOc(size_t n, size_t elem_size)
1747 #else
1748 Void_t* cALLOc(n, elem_size) size_t n; size_t elem_size;
1749 #endif
1751 mchunkptr p;
1752 INTERNAL_SIZE_T csz;
1754 INTERNAL_SIZE_T sz = n * elem_size;
1757 /* check if expand_top called, in which case don't need to clear */
1758 #if MORECORE_CLEARS
1759 mchunkptr oldtop = top;
1760 INTERNAL_SIZE_T oldtopsize = chunksize(top);
1761 #endif
1762 Void_t* mem = mALLOc (sz);
1764 if ((long)n < 0) return 0;
1766 if (mem == 0)
1767 return 0;
1768 else
1770 p = mem2chunk(mem);
1772 /* Two optional cases in which clearing not necessary */
1776 csz = chunksize(p);
1778 #if MORECORE_CLEARS
1779 if (p == oldtop && csz > oldtopsize)
1781 /* clear only the bytes from non-freshly-sbrked memory */
1782 csz = oldtopsize;
1784 #endif
1786 MALLOC_ZERO(mem, csz - SIZE_SZ);
1787 return mem;
1793 cfree just calls free. It is needed/defined on some systems
1794 that pair it with calloc, presumably for odd historical reasons.
1798 #if !defined(INTERNAL_LINUX_C_LIB) || !defined(__ELF__)
1799 #if __STD_C
1800 void cfree(Void_t *mem)
1801 #else
1802 void cfree(mem) Void_t *mem;
1803 #endif
1805 fREe(mem);
1807 #endif
1813 Malloc_trim gives memory back to the system (via negative
1814 arguments to sbrk) if there is unused memory at the `high' end of
1815 the malloc pool. You can call this after freeing large blocks of
1816 memory to potentially reduce the system-level memory requirements
1817 of a program. However, it cannot guarantee to reduce memory. Under
1818 some allocation patterns, some large free blocks of memory will be
1819 locked between two used chunks, so they cannot be given back to
1820 the system.
1822 The `pad' argument to malloc_trim represents the amount of free
1823 trailing space to leave untrimmed. If this argument is zero,
1824 only the minimum amount of memory to maintain internal data
1825 structures will be left (one page or less). Non-zero arguments
1826 can be supplied to maintain enough trailing space to service
1827 future expected allocations without having to re-obtain memory
1828 from the system.
1830 Malloc_trim returns 1 if it actually released any memory, else 0.
1833 #ifdef USE_MALLOC_TRIM
1834 #if __STD_C
1835 int malloc_trim(size_t pad)
1836 #else
1837 int malloc_trim(pad) size_t pad;
1838 #endif
1840 long top_size; /* Amount of top-most memory */
1841 long extra; /* Amount to release */
1842 char* current_brk; /* address returned by pre-check sbrk call */
1843 char* new_brk; /* address returned by negative sbrk call */
1845 unsigned long pagesz = malloc_getpagesize;
1847 top_size = chunksize(top);
1848 extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
1850 if (extra < (long)pagesz) /* Not enough memory to release */
1851 return 0;
1853 else
1855 /* Test to make sure no one else called sbrk */
1856 current_brk = (char*)(MORECORE (0));
1857 if (current_brk != (char*)(top) + top_size)
1858 return 0; /* Apparently we don't own memory; must fail */
1860 else
1862 new_brk = (char*)(MORECORE (-extra));
1864 if (new_brk == (char*)(MORECORE_FAILURE)) /* sbrk failed? */
1866 /* Try to figure out what we have */
1867 current_brk = (char*)(MORECORE (0));
1868 top_size = current_brk - (char*)top;
1869 if (top_size >= (long)MINSIZE) /* if not, we are very very dead! */
1871 sbrked_mem = current_brk - sbrk_base;
1872 set_head(top, top_size | PREV_INUSE);
1874 check_chunk(top);
1875 return 0;
1878 else
1880 /* Success. Adjust top accordingly. */
1881 set_head(top, (top_size - extra) | PREV_INUSE);
1882 sbrked_mem -= extra;
1883 check_chunk(top);
1884 return 1;
1889 #endif
1893 malloc_usable_size:
1895 This routine tells you how many bytes you can actually use in an
1896 allocated chunk, which may be more than you requested (although
1897 often not). You can use this many bytes without worrying about
1898 overwriting other allocated objects. Not a particularly great
1899 programming practice, but still sometimes useful.
1903 #if __STD_C
1904 size_t malloc_usable_size(Void_t* mem)
1905 #else
1906 size_t malloc_usable_size(mem) Void_t* mem;
1907 #endif
1909 mchunkptr p;
1910 if (mem == 0)
1911 return 0;
1912 else
1914 p = mem2chunk(mem);
1915 if(!chunk_is_mmapped(p))
1917 if (!inuse(p)) return 0;
1918 check_inuse_chunk(p);
1919 return chunksize(p) - SIZE_SZ;
1921 return chunksize(p) - 2*SIZE_SZ;
1928 /* Utility to update current_mallinfo for malloc_stats and mallinfo() */
1930 #ifdef CONFIG_CMD_MEMINFO
1931 static void malloc_update_mallinfo(void)
1933 int i;
1934 mbinptr b;
1935 mchunkptr p;
1936 #ifdef DEBUG
1937 mchunkptr q;
1938 #endif
1940 INTERNAL_SIZE_T avail = chunksize(top);
1941 int navail = ((long)(avail) >= (long)MINSIZE)? 1 : 0;
1943 for (i = 1; i < NAV; ++i)
1945 b = bin_at(i);
1946 for (p = last(b); p != b; p = p->bk)
1948 #ifdef DEBUG
1949 check_free_chunk(p);
1950 for (q = next_chunk(p);
1951 q < top && inuse(q) && (long)(chunksize(q)) >= (long)MINSIZE;
1952 q = next_chunk(q))
1953 check_inuse_chunk(q);
1954 #endif
1955 avail += chunksize(p);
1956 navail++;
1960 current_mallinfo.ordblks = navail;
1961 current_mallinfo.uordblks = sbrked_mem - avail;
1962 current_mallinfo.fordblks = avail;
1963 #if HAVE_MMAP
1964 current_mallinfo.hblks = n_mmaps;
1965 #endif
1966 current_mallinfo.hblkhd = mmapped_mem;
1967 current_mallinfo.keepcost = chunksize(top);
1975 malloc_stats:
1977 Prints on the amount of space obtain from the system (both
1978 via sbrk and mmap), the maximum amount (which may be more than
1979 current if malloc_trim and/or munmap got called), the maximum
1980 number of simultaneous mmap regions used, and the current number
1981 of bytes allocated via malloc (or realloc, etc) but not yet
1982 freed. (Note that this is the number of bytes allocated, not the
1983 number requested. It will be larger than the number requested
1984 because of alignment and bookkeeping overhead.)
1990 mallinfo returns a copy of updated current mallinfo.
1993 void malloc_stats()
1995 malloc_update_mallinfo();
1996 printf("max system bytes = %10u\n",
1997 (unsigned int)(max_total_mem));
1998 printf("system bytes = %10u\n",
1999 (unsigned int)(sbrked_mem + mmapped_mem));
2000 printf("in use bytes = %10u\n",
2001 (unsigned int)(current_mallinfo.uordblks + mmapped_mem));
2002 #if HAVE_MMAP
2003 fprintf(stderr, "max mmap regions = %10u\n",
2004 (unsigned int)max_n_mmaps);
2005 #endif
2008 #endif /* CONFIG_CMD_MEMINFO */
2013 mallopt:
2015 mallopt is the general SVID/XPG interface to tunable parameters.
2016 The format is to provide a (parameter-number, parameter-value) pair.
2017 mallopt then sets the corresponding parameter to the argument
2018 value if it can (i.e., so long as the value is meaningful),
2019 and returns 1 if successful else 0.
2021 See descriptions of tunable parameters above.
2024 #ifndef __U_BOOT__
2025 #if __STD_C
2026 int mALLOPt(int param_number, int value)
2027 #else
2028 int mALLOPt(param_number, value) int param_number; int value;
2029 #endif
2031 switch(param_number)
2033 case M_TRIM_THRESHOLD:
2034 trim_threshold = value; return 1;
2035 case M_TOP_PAD:
2036 top_pad = value; return 1;
2037 case M_MMAP_THRESHOLD:
2038 mmap_threshold = value; return 1;
2039 case M_MMAP_MAX:
2040 if (value != 0) return 0; else n_mmaps_max = value; return 1;
2042 default:
2043 return 0;
2046 #endif
2049 History:
2051 V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
2052 * return null for negative arguments
2053 * Added Several WIN32 cleanups from Martin C. Fong <mcfong@yahoo.com>
2054 * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
2055 (e.g. WIN32 platforms)
2056 * Cleanup up header file inclusion for WIN32 platforms
2057 * Cleanup code to avoid Microsoft Visual C++ compiler complaints
2058 * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
2059 memory allocation routines
2060 * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
2061 * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
2062 usage of 'assert' in non-WIN32 code
2063 * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
2064 avoid infinite loop
2065 * Always call 'fREe()' rather than 'free()'
2067 V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
2068 * Fixed ordering problem with boundary-stamping
2070 V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
2071 * Added pvalloc, as recommended by H.J. Liu
2072 * Added 64bit pointer support mainly from Wolfram Gloger
2073 * Added anonymously donated WIN32 sbrk emulation
2074 * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
2075 * malloc_extend_top: fix mask error that caused wastage after
2076 foreign sbrks
2077 * Add linux mremap support code from HJ Liu
2079 V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
2080 * Integrated most documentation with the code.
2081 * Add support for mmap, with help from
2082 Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
2083 * Use last_remainder in more cases.
2084 * Pack bins using idea from colin@nyx10.cs.du.edu
2085 * Use ordered bins instead of best-fit threshhold
2086 * Eliminate block-local decls to simplify tracing and debugging.
2087 * Support another case of realloc via move into top
2088 * Fix error occuring when initial sbrk_base not word-aligned.
2089 * Rely on page size for units instead of SBRK_UNIT to
2090 avoid surprises about sbrk alignment conventions.
2091 * Add mallinfo, mallopt. Thanks to Raymond Nijssen
2092 (raymond@es.ele.tue.nl) for the suggestion.
2093 * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
2094 * More precautions for cases where other routines call sbrk,
2095 courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
2096 * Added macros etc., allowing use in linux libc from
2097 H.J. Lu (hjl@gnu.ai.mit.edu)
2098 * Inverted this history list
2100 V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
2101 * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
2102 * Removed all preallocation code since under current scheme
2103 the work required to undo bad preallocations exceeds
2104 the work saved in good cases for most test programs.
2105 * No longer use return list or unconsolidated bins since
2106 no scheme using them consistently outperforms those that don't
2107 given above changes.
2108 * Use best fit for very large chunks to prevent some worst-cases.
2109 * Added some support for debugging
2111 V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
2112 * Removed footers when chunks are in use. Thanks to
2113 Paul Wilson (wilson@cs.texas.edu) for the suggestion.
2115 V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
2116 * Added malloc_trim, with help from Wolfram Gloger
2117 (wmglo@Dent.MED.Uni-Muenchen.DE).
2119 V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
2121 V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
2122 * realloc: try to expand in both directions
2123 * malloc: swap order of clean-bin strategy;
2124 * realloc: only conditionally expand backwards
2125 * Try not to scavenge used bins
2126 * Use bin counts as a guide to preallocation
2127 * Occasionally bin return list chunks in first scan
2128 * Add a few optimizations from colin@nyx10.cs.du.edu
2130 V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
2131 * faster bin computation & slightly different binning
2132 * merged all consolidations to one part of malloc proper
2133 (eliminating old malloc_find_space & malloc_clean_bin)
2134 * Scan 2 returns chunks (not just 1)
2135 * Propagate failure in realloc if malloc returns 0
2136 * Add stuff to allow compilation on non-ANSI compilers
2137 from kpv@research.att.com
2139 V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
2140 * removed potential for odd address access in prev_chunk
2141 * removed dependency on getpagesize.h
2142 * misc cosmetics and a bit more internal documentation
2143 * anticosmetics: mangled names in macros to evade debugger strangeness
2144 * tested on sparc, hp-700, dec-mips, rs6000
2145 with gcc & native cc (hp, dec only) allowing
2146 Detlefs & Zorn comparison study (in SIGPLAN Notices.)
2148 Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
2149 * Based loosely on libg++-1.2X malloc. (It retains some of the overall
2150 structure of old version, but most details differ.)
2154 EXPORT_SYMBOL(malloc);
2155 EXPORT_SYMBOL(calloc);
2156 EXPORT_SYMBOL(free);
2157 EXPORT_SYMBOL(realloc);