6 Here are some notes on configuring Perl's malloc. (For non-perl
9 There are two macros which serve as bulk disablers of advanced
10 features of this malloc: NO_FANCY_MALLOC, PLAIN_MALLOC (undef by
11 default). Look in the list of default values below to understand
12 their exact effect. Defining NO_FANCY_MALLOC returns malloc.c to the
13 state of the malloc in Perl 5.004. Additionally defining PLAIN_MALLOC
14 returns it to the state as of Perl 5.000.
16 Note that some of the settings below may be ignored in the code based
17 on values of other macros. The PERL_CORE symbol is only defined when
18 perl itself is being compiled (so malloc can make some assumptions
19 about perl's facilities being available to it).
21 Each config option has a short description, followed by its name,
22 default value, and a comment about the default (if applicable). Some
23 options take a precise value, while the others are just boolean.
24 The boolean ones are listed first.
26 # Enable code for an emergency memory pool in $^M. See perlvar.pod
27 # for a description of $^M.
28 PERL_EMERGENCY_SBRK (!PLAIN_MALLOC && PERL_CORE)
30 # Enable code for printing memory statistics.
31 DEBUGGING_MSTATS (!PLAIN_MALLOC && PERL_CORE)
33 # Move allocation info for small buckets into separate areas.
34 # Memory optimization (especially for small allocations, of the
35 # less than 64 bytes). Since perl usually makes a large number
36 # of small allocations, this is usually a win.
37 PACK_MALLOC (!PLAIN_MALLOC && !RCHECK)
39 # Add one page to big powers of two when calculating bucket size.
40 # This is targeted at big allocations, as are common in image
42 TWO_POT_OPTIMIZE !PLAIN_MALLOC
44 # Use intermediate bucket sizes between powers-of-two. This is
45 # generally a memory optimization, and a (small) speed pessimization.
46 BUCKETS_ROOT2 !NO_FANCY_MALLOC
48 # Do not check small deallocations for bad free(). Memory
49 # and speed optimization, error reporting pessimization.
50 IGNORE_SMALL_BAD_FREE (!NO_FANCY_MALLOC && !RCHECK)
52 # Use table lookup to decide in which bucket a given allocation will go.
53 SMALL_BUCKET_VIA_TABLE !NO_FANCY_MALLOC
55 # Use a perl-defined sbrk() instead of the (presumably broken or
56 # missing) system-supplied sbrk().
59 # Use system malloc() (or calloc() etc.) to emulate sbrk(). Normally
60 # only used with broken sbrk()s.
61 PERL_SBRK_VIA_MALLOC undef
63 # Which allocator to use if PERL_SBRK_VIA_MALLOC
64 SYSTEM_ALLOC(a) malloc(a)
66 # Minimal alignment (in bytes, should be a power of 2) of SYSTEM_ALLOC
67 SYSTEM_ALLOC_ALIGNMENT MEM_ALIGNBYTES
69 # Disable memory overwrite checking with DEBUGGING. Memory and speed
70 # optimization, error reporting pessimization.
73 # Enable memory overwrite checking with DEBUGGING. Memory and speed
74 # pessimization, error reporting optimization
75 RCHECK (DEBUGGING && !NO_RCHECK)
77 # Failed allocations bigger than this size croak (if
78 # PERL_EMERGENCY_SBRK is enabled) without touching $^M. See
79 # perlvar.pod for a description of $^M.
80 BIG_SIZE (1<<16) # 64K
82 # Starting from this power of two, add an extra page to the
83 # size of the bucket. This enables optimized allocations of sizes
84 # close to powers of 2. Note that the value is indexed at 0.
85 FIRST_BIG_POW2 15 # 32K, 16K is used too often
87 # Estimate of minimal memory footprint. malloc uses this value to
88 # request the most reasonable largest blocks of memory from the system.
91 # Round up sbrk()s to multiples of this.
94 # Round up sbrk()s to multiples of this percent of footprint.
97 # Add this much memory to big powers of two to get the bucket size.
100 # This many sbrk() discontinuities should be tolerated even
101 # from the start without deciding that sbrk() is usually
103 SBRK_ALLOW_FAILURES 3
105 # This many continuous sbrk()s compensate for one discontinuous one.
106 SBRK_FAILURE_PRICE 50
108 # Some configurations may ask for 12-byte-or-so allocations which
109 # require 8-byte alignment (?!). In such situation one needs to
110 # define this to disable 12-byte bucket (will increase memory footprint)
111 STRICT_ALIGNMENT undef
113 This implementation assumes that calling PerlIO_printf() does not
114 result in any memory allocation calls (used during a panic).
119 If used outside of Perl environment, it may be useful to redefine
120 the following macros (listed below with defaults):
122 # Type of address returned by allocation functions
125 # Type of size argument for allocation functions
126 MEM_SIZE unsigned long
128 # Maximal value in LONG
131 # Unsigned integer type big enough to keep a pointer
134 # Type of pointer with 1-byte granularity
137 # Type returned by free()
140 # Very fatal condition reporting function (cannot call any )
141 fatalcroak(arg) write(2,arg,strlen(arg)) + exit(2)
143 # Fatal error reporting function
144 croak(format, arg) warn(idem) + exit(1)
146 # Error reporting function
147 warn(format, arg) fprintf(stderr, idem)
149 # Locking/unlocking for MT operation
150 MALLOC_LOCK MUTEX_LOCK(&PL_malloc_mutex)
151 MALLOC_UNLOCK MUTEX_UNLOCK(&PL_malloc_mutex)
153 # Locking/unlocking mutex for MT operation
158 #ifndef NO_FANCY_MALLOC
159 # ifndef SMALL_BUCKET_VIA_TABLE
160 # define SMALL_BUCKET_VIA_TABLE
162 # ifndef BUCKETS_ROOT2
163 # define BUCKETS_ROOT2
165 # ifndef IGNORE_SMALL_BAD_FREE
166 # define IGNORE_SMALL_BAD_FREE
170 #ifndef PLAIN_MALLOC /* Bulk enable features */
174 # ifndef TWO_POT_OPTIMIZE
175 # define TWO_POT_OPTIMIZE
177 # if defined(PERL_CORE) && !defined(PERL_EMERGENCY_SBRK)
178 # define PERL_EMERGENCY_SBRK
180 # if defined(PERL_CORE) && !defined(DEBUGGING_MSTATS)
181 # define DEBUGGING_MSTATS
185 #define MIN_BUC_POW2 (sizeof(void*) > 4 ? 3 : 2) /* Allow for 4-byte arena. */
186 #define MIN_BUCKET (MIN_BUC_POW2 * BUCKETS_PER_POW2)
188 #if !(defined(I286) || defined(atarist) || defined(__MINT__))
189 /* take 2k unless the block is bigger than that */
190 # define LOG_OF_MIN_ARENA 11
192 /* take 16k unless the block is bigger than that
193 (80286s like large segments!), probably good on the atari too */
194 # define LOG_OF_MIN_ARENA 14
198 # if defined(DEBUGGING) && !defined(NO_RCHECK)
201 # if defined(RCHECK) && defined(IGNORE_SMALL_BAD_FREE)
202 # undef IGNORE_SMALL_BAD_FREE
205 * malloc.c (Caltech) 2/21/82
206 * Chris Kingsley, kingsley@cit-20.
208 * This is a very fast storage allocator. It allocates blocks of a small
209 * number of different sizes, and keeps free lists of each size. Blocks that
210 * don't exactly fit are passed up to the next larger size. In this
211 * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long.
212 * If PACK_MALLOC is defined, small blocks are 2^n bytes long.
213 * This is designed for use in a program that uses vast quantities of memory,
214 * but bombs when it runs out.
216 * Modifications Copyright Ilya Zakharevich 1996-99.
218 * Still very quick, but much more thrifty. (Std config is 10% slower
219 * than it was, and takes 67% of old heap size for typical usage.)
221 * Allocations of small blocks are now table-driven to many different
222 * buckets. Sizes of really big buckets are increased to accomodata
223 * common size=power-of-2 blocks. Running-out-of-memory is made into
224 * an exception. Deeply configurable and thread-safe.
230 #define PERL_IN_MALLOC_C
234 # include "../EXTERN.h"
235 # include "../perl.h"
242 # define Malloc_t void *
245 # define MEM_SIZE unsigned long
248 # define LONG_MAX 0x7FFFFFFF
251 # define UV unsigned long
254 # define caddr_t char *
259 # define Copy(s,d,n,t) (void)memcpy((char*)(d),(char*)(s), (n) * sizeof(t))
260 # define PerlEnv_getenv getenv
261 # define PerlIO_printf fprintf
262 # define PerlIO_stderr() stderr
264 # ifndef croak /* make depend */
265 # define croak(mess, arg) (warn((mess), (arg)), exit(1))
268 # define warn(mess, arg) fprintf(stderr, (mess), (arg))
280 # define MUTEX_LOCK(l)
284 # define MUTEX_UNLOCK(l)
288 # define MALLOC_LOCK MUTEX_LOCK(&PL_malloc_mutex)
291 #ifndef MALLOC_UNLOCK
292 # define MALLOC_UNLOCK MUTEX_UNLOCK(&PL_malloc_mutex)
295 # ifndef fatalcroak /* make depend */
296 # define fatalcroak(mess) (write(2, (mess), strlen(mess)), exit(2))
301 # define DEBUG_m(a) if (PL_debug & 128) a
307 * The memory is broken into "blocks" which occupy multiples of 2K (and
308 * generally speaking, have size "close" to a power of 2). The addresses
309 * of such *unused* blocks are kept in nextf[i] with big enough i. (nextf
310 * is an array of linked lists.) (Addresses of used blocks are not known.)
312 * Moreover, since the algorithm may try to "bite" smaller blocks of out
313 * of unused bigger ones, there are also regions of "irregular" size,
314 * managed separately, by a linked list chunk_chain.
316 * The third type of storage is the sbrk()ed-but-not-yet-used space, its
317 * end and size are kept in last_sbrk_top and sbrked_remains.
319 * Growing blocks "in place":
320 * ~~~~~~~~~~~~~~~~~~~~~~~~~
321 * The address of the block with the greatest address is kept in last_op
322 * (if not known, last_op is 0). If it is known that the memory above
323 * last_op is not continuous, or contains a chunk from chunk_chain,
324 * last_op is set to 0.
326 * The chunk with address last_op may be grown by expanding into
327 * sbrk()ed-but-not-yet-used space, or trying to sbrk() more continuous
330 * Management of last_op:
331 * ~~~~~~~~~~~~~~~~~~~~~
333 * free() never changes the boundaries of blocks, so is not relevant.
335 * The only way realloc() may change the boundaries of blocks is if it
336 * grows a block "in place". However, in the case of success such a
337 * chunk is automatically last_op, and it remains last_op. In the case
338 * of failure getpages_adjacent() clears last_op.
340 * malloc() may change blocks by calling morecore() only.
342 * morecore() may create new blocks by:
343 * a) biting pieces from chunk_chain (cannot create one above last_op);
344 * b) biting a piece from an unused block (if block was last_op, this
345 * may create a chunk from chain above last_op, thus last_op is
346 * invalidated in such a case).
347 * c) biting of sbrk()ed-but-not-yet-used space. This creates
348 * a block which is last_op.
349 * d) Allocating new pages by calling getpages();
351 * getpages() creates a new block. It marks last_op at the bottom of
352 * the chunk of memory it returns.
354 * Active pages footprint:
355 * ~~~~~~~~~~~~~~~~~~~~~~
356 * Note that we do not need to traverse the lists in nextf[i], just take
357 * the first element of this list. However, we *need* to traverse the
358 * list in chunk_chain, but most the time it should be a very short one,
359 * so we do not step on a lot of pages we are not going to use.
363 * get_from_bigger_buckets(): forget to increment price => Quite
367 /* I don't much care whether these are defined in sys/types.h--LAW */
369 #define u_char unsigned char
370 #define u_int unsigned int
373 # define u_bigint UV /* Needs to eat *void. */
375 # define u_bigint unsigned long /* Needs to eat *void. */
378 #define u_short unsigned short
380 /* 286 and atarist like big chunks, which gives too much overhead. */
381 #if (defined(RCHECK) || defined(I286) || defined(atarist) || defined(__MINT__)) && defined(PACK_MALLOC)
386 * The description below is applicable if PACK_MALLOC is not defined.
388 * The overhead on a block is at least 4 bytes. When free, this space
389 * contains a pointer to the next free block, and the bottom two bits must
390 * be zero. When in use, the first byte is set to MAGIC, and the second
391 * byte is the size index. The remaining bytes are for alignment.
392 * If range checking is enabled and the size of the block fits
393 * in two bytes, then the top two bytes hold the size of the requested block
394 * plus the range checking words, and the header word MINUS ONE.
397 union overhead *ov_next; /* when free */
398 #if MEM_ALIGNBYTES > 4
399 double strut; /* alignment problems */
402 u_char ovu_magic; /* magic number */
403 u_char ovu_index; /* bucket # */
405 u_short ovu_size; /* actual block size */
406 u_int ovu_rmagic; /* range magic number */
409 #define ov_magic ovu.ovu_magic
410 #define ov_index ovu.ovu_index
411 #define ov_size ovu.ovu_size
412 #define ov_rmagic ovu.ovu_rmagic
415 #define MAGIC 0xff /* magic # on accounting info */
416 #define RMAGIC 0x55555555 /* magic # on range info */
417 #define RMAGIC_C 0x55 /* magic # on range info */
420 # define RSLOP sizeof (u_int)
421 # ifdef TWO_POT_OPTIMIZE
422 # define MAX_SHORT_BUCKET (12 * BUCKETS_PER_POW2)
424 # define MAX_SHORT_BUCKET (13 * BUCKETS_PER_POW2)
430 #if !defined(PACK_MALLOC) && defined(BUCKETS_ROOT2)
431 # undef BUCKETS_ROOT2
435 # define BUCKET_TABLE_SHIFT 2
436 # define BUCKET_POW2_SHIFT 1
437 # define BUCKETS_PER_POW2 2
439 # define BUCKET_TABLE_SHIFT MIN_BUC_POW2
440 # define BUCKET_POW2_SHIFT 0
441 # define BUCKETS_PER_POW2 1
444 #if !defined(MEM_ALIGNBYTES) || ((MEM_ALIGNBYTES > 4) && !defined(STRICT_ALIGNMENT))
445 /* Figure out the alignment of void*. */
450 # define ALIGN_SMALL ((int)((caddr_t)&(((struct aligner*)0)->p)))
452 # define ALIGN_SMALL MEM_ALIGNBYTES
455 #define IF_ALIGN_8(yes,no) ((ALIGN_SMALL>4) ? (yes) : (no))
458 # define MAX_BUCKET_BY_TABLE 13
459 static u_short buck_size[MAX_BUCKET_BY_TABLE + 1] =
461 0, 0, 0, 0, 4, 4, 8, 12, 16, 24, 32, 48, 64, 80,
463 # define BUCKET_SIZE(i) ((i) % 2 ? buck_size[i] : (1 << ((i) >> BUCKET_POW2_SHIFT)))
464 # define BUCKET_SIZE_REAL(i) ((i) <= MAX_BUCKET_BY_TABLE \
466 : ((1 << ((i) >> BUCKET_POW2_SHIFT)) \
468 + POW2_OPTIMIZE_SURPLUS(i)))
470 # define BUCKET_SIZE(i) (1 << ((i) >> BUCKET_POW2_SHIFT))
471 # define BUCKET_SIZE_REAL(i) (BUCKET_SIZE(i) - MEM_OVERHEAD(i) + POW2_OPTIMIZE_SURPLUS(i))
476 /* In this case it is assumed that if we do sbrk() in 2K units, we
477 * will get 2K aligned arenas (at least after some initial
478 * alignment). The bucket number of the given subblock is on the start
479 * of 2K arena which contains the subblock. Several following bytes
480 * contain the magic numbers for the subblocks in the block.
482 * Sizes of chunks are powers of 2 for chunks in buckets <=
483 * MAX_PACKED, after this they are (2^n - sizeof(union overhead)) (to
484 * get alignment right).
486 * Consider an arena for 2^n with n>MAX_PACKED. We suppose that
487 * starts of all the chunks in a 2K arena are in different
488 * 2^n-byte-long chunks. If the top of the last chunk is aligned on a
489 * boundary of 2K block, this means that sizeof(union
490 * overhead)*"number of chunks" < 2^n, or sizeof(union overhead)*2K <
491 * 4^n, or n > 6 + log2(sizeof()/2)/2, since a chunk of size 2^n -
492 * overhead is used. Since this rules out n = 7 for 8 byte alignment,
493 * we specialcase allocation of the first of 16 128-byte-long chunks.
495 * Note that with the above assumption we automatically have enough
496 * place for MAGIC at the start of 2K block. Note also that we
497 * overlay union overhead over the chunk, thus the start of small chunks
498 * is immediately overwritten after freeing. */
499 # define MAX_PACKED_POW2 6
500 # define MAX_PACKED (MAX_PACKED_POW2 * BUCKETS_PER_POW2 + BUCKET_POW2_SHIFT)
501 # define MAX_POW2_ALGO ((1<<(MAX_PACKED_POW2 + 1)) - M_OVERHEAD)
502 # define TWOK_MASK ((1<<LOG_OF_MIN_ARENA) - 1)
503 # define TWOK_MASKED(x) ((u_bigint)(x) & ~TWOK_MASK)
504 # define TWOK_SHIFT(x) ((u_bigint)(x) & TWOK_MASK)
505 # define OV_INDEXp(block) ((u_char*)(TWOK_MASKED(block)))
506 # define OV_INDEX(block) (*OV_INDEXp(block))
507 # define OV_MAGIC(block,bucket) (*(OV_INDEXp(block) + \
508 (TWOK_SHIFT(block)>> \
509 (bucket>>BUCKET_POW2_SHIFT)) + \
510 (bucket >= MIN_NEEDS_SHIFT ? 1 : 0)))
511 /* A bucket can have a shift smaller than it size, we need to
512 shift its magic number so it will not overwrite index: */
513 # ifdef BUCKETS_ROOT2
514 # define MIN_NEEDS_SHIFT (7*BUCKETS_PER_POW2 - 1) /* Shift 80 greater than chunk 64. */
516 # define MIN_NEEDS_SHIFT (7*BUCKETS_PER_POW2) /* Shift 128 greater than chunk 32. */
518 # define CHUNK_SHIFT 0
520 /* Number of active buckets of given ordinal. */
521 #ifdef IGNORE_SMALL_BAD_FREE
522 #define FIRST_BUCKET_WITH_CHECK (6 * BUCKETS_PER_POW2) /* 64 */
523 # define N_BLKS(bucket) ( (bucket) < FIRST_BUCKET_WITH_CHECK \
524 ? ((1<<LOG_OF_MIN_ARENA) - 1)/BUCKET_SIZE(bucket) \
527 # define N_BLKS(bucket) n_blks[bucket]
530 static u_short n_blks[LOG_OF_MIN_ARENA * BUCKETS_PER_POW2] =
532 # if BUCKETS_PER_POW2==1
534 (MIN_BUC_POW2==2 ? 384 : 0),
535 224, 120, 62, 31, 16, 8, 4, 2
538 (MIN_BUC_POW2==2 ? 384 : 0), (MIN_BUC_POW2==2 ? 384 : 0), /* 4, 4 */
539 224, 149, 120, 80, 62, 41, 31, 25, 16, 16, 8, 8, 4, 4, 2, 2
543 /* Shift of the first bucket with the given ordinal inside 2K chunk. */
544 #ifdef IGNORE_SMALL_BAD_FREE
545 # define BLK_SHIFT(bucket) ( (bucket) < FIRST_BUCKET_WITH_CHECK \
546 ? ((1<<LOG_OF_MIN_ARENA) \
547 - BUCKET_SIZE(bucket) * N_BLKS(bucket)) \
550 # define BLK_SHIFT(bucket) blk_shift[bucket]
553 static u_short blk_shift[LOG_OF_MIN_ARENA * BUCKETS_PER_POW2] =
555 # if BUCKETS_PER_POW2==1
557 (MIN_BUC_POW2==2 ? 512 : 0),
558 256, 128, 64, 64, /* 8 to 64 */
559 16*sizeof(union overhead),
560 8*sizeof(union overhead),
561 4*sizeof(union overhead),
562 2*sizeof(union overhead),
565 (MIN_BUC_POW2==2 ? 512 : 0), (MIN_BUC_POW2==2 ? 512 : 0),
566 256, 260, 128, 128, 64, 80, 64, 48, /* 8 to 96 */
567 16*sizeof(union overhead), 16*sizeof(union overhead),
568 8*sizeof(union overhead), 8*sizeof(union overhead),
569 4*sizeof(union overhead), 4*sizeof(union overhead),
570 2*sizeof(union overhead), 2*sizeof(union overhead),
574 # define NEEDED_ALIGNMENT 0x800 /* 2k boundaries */
575 # define WANTED_ALIGNMENT 0x800 /* 2k boundaries */
577 #else /* !PACK_MALLOC */
579 # define OV_MAGIC(block,bucket) (block)->ov_magic
580 # define OV_INDEX(block) (block)->ov_index
581 # define CHUNK_SHIFT 1
582 # define MAX_PACKED -1
583 # define NEEDED_ALIGNMENT MEM_ALIGNBYTES
584 # define WANTED_ALIGNMENT 0x400 /* 1k boundaries */
586 #endif /* !PACK_MALLOC */
588 #define M_OVERHEAD (sizeof(union overhead) + RSLOP)
591 # define MEM_OVERHEAD(bucket) \
592 (bucket <= MAX_PACKED ? 0 : M_OVERHEAD)
593 # ifdef SMALL_BUCKET_VIA_TABLE
594 # define START_SHIFTS_BUCKET ((MAX_PACKED_POW2 + 1) * BUCKETS_PER_POW2)
595 # define START_SHIFT MAX_PACKED_POW2
596 # ifdef BUCKETS_ROOT2 /* Chunks of size 3*2^n. */
597 # define SIZE_TABLE_MAX 80
599 # define SIZE_TABLE_MAX 64
601 static char bucket_of[] =
603 # ifdef BUCKETS_ROOT2 /* Chunks of size 3*2^n. */
604 /* 0 to 15 in 4-byte increments. */
605 (sizeof(void*) > 4 ? 6 : 5), /* 4/8, 5-th bucket for better reports */
607 IF_ALIGN_8(8,7), 8, /* 16/12, 16 */
608 9, 9, 10, 10, /* 24, 32 */
609 11, 11, 11, 11, /* 48 */
610 12, 12, 12, 12, /* 64 */
611 13, 13, 13, 13, /* 80 */
612 13, 13, 13, 13 /* 80 */
613 # else /* !BUCKETS_ROOT2 */
614 /* 0 to 15 in 4-byte increments. */
615 (sizeof(void*) > 4 ? 3 : 2),
621 # endif /* !BUCKETS_ROOT2 */
623 # else /* !SMALL_BUCKET_VIA_TABLE */
624 # define START_SHIFTS_BUCKET MIN_BUCKET
625 # define START_SHIFT (MIN_BUC_POW2 - 1)
626 # endif /* !SMALL_BUCKET_VIA_TABLE */
627 #else /* !PACK_MALLOC */
628 # define MEM_OVERHEAD(bucket) M_OVERHEAD
629 # ifdef SMALL_BUCKET_VIA_TABLE
630 # undef SMALL_BUCKET_VIA_TABLE
632 # define START_SHIFTS_BUCKET MIN_BUCKET
633 # define START_SHIFT (MIN_BUC_POW2 - 1)
634 #endif /* !PACK_MALLOC */
637 * Big allocations are often of the size 2^n bytes. To make them a
638 * little bit better, make blocks of size 2^n+pagesize for big n.
641 #ifdef TWO_POT_OPTIMIZE
643 # ifndef PERL_PAGESIZE
644 # define PERL_PAGESIZE 4096
646 # ifndef FIRST_BIG_POW2
647 # define FIRST_BIG_POW2 15 /* 32K, 16K is used too often. */
649 # define FIRST_BIG_BLOCK (1<<FIRST_BIG_POW2)
650 /* If this value or more, check against bigger blocks. */
651 # define FIRST_BIG_BOUND (FIRST_BIG_BLOCK - M_OVERHEAD)
652 /* If less than this value, goes into 2^n-overhead-block. */
653 # define LAST_SMALL_BOUND ((FIRST_BIG_BLOCK>>1) - M_OVERHEAD)
655 # define POW2_OPTIMIZE_ADJUST(nbytes) \
656 ((nbytes >= FIRST_BIG_BOUND) ? nbytes -= PERL_PAGESIZE : 0)
657 # define POW2_OPTIMIZE_SURPLUS(bucket) \
658 ((bucket >= FIRST_BIG_POW2 * BUCKETS_PER_POW2) ? PERL_PAGESIZE : 0)
660 #else /* !TWO_POT_OPTIMIZE */
661 # define POW2_OPTIMIZE_ADJUST(nbytes)
662 # define POW2_OPTIMIZE_SURPLUS(bucket) 0
663 #endif /* !TWO_POT_OPTIMIZE */
665 #if defined(HAS_64K_LIMIT) && defined(PERL_CORE)
666 # define BARK_64K_LIMIT(what,nbytes,size) \
667 if (nbytes > 0xffff) { \
668 PerlIO_printf(PerlIO_stderr(), \
669 "%s too large: %lx\n", what, size); \
672 #else /* !HAS_64K_LIMIT || !PERL_CORE */
673 # define BARK_64K_LIMIT(what,nbytes,size)
674 #endif /* !HAS_64K_LIMIT || !PERL_CORE */
677 # define MIN_SBRK 2048
681 # define FIRST_SBRK (48*1024)
684 /* Minimal sbrk in percents of what is already alloced. */
685 #ifndef MIN_SBRK_FRAC
686 # define MIN_SBRK_FRAC 3
689 #ifndef SBRK_ALLOW_FAILURES
690 # define SBRK_ALLOW_FAILURES 3
693 #ifndef SBRK_FAILURE_PRICE
694 # define SBRK_FAILURE_PRICE 50
697 #if defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)
700 # define BIG_SIZE (1<<16) /* 64K */
703 #ifdef I_MACH_CTHREADS
705 # define MUTEX_LOCK(m) STMT_START { if (*m) mutex_lock(*m); } STMT_END
707 # define MUTEX_UNLOCK(m) STMT_START { if (*m) mutex_unlock(*m); } STMT_END
710 static char *emergency_buffer;
711 static MEM_SIZE emergency_buffer_size;
714 emergency_sbrk(pTHX_ MEM_SIZE size)
716 MEM_SIZE rsize = (((size - 1)>>LOG_OF_MIN_ARENA) + 1)<<LOG_OF_MIN_ARENA;
718 if (size >= BIG_SIZE) {
719 /* Give the possibility to recover: */
721 croak("Out of memory during \"large\" request for %i bytes", size);
724 if (emergency_buffer_size >= rsize) {
725 char *old = emergency_buffer;
727 emergency_buffer_size -= rsize;
728 emergency_buffer += rsize;
732 /* First offense, give a possibility to recover by dieing. */
733 /* No malloc involved here: */
734 GV **gvp = (GV**)hv_fetch(PL_defstash, "^M", 2, 0);
740 if (emergency_buffer_size) {
741 add_to_chain(emergency_buffer, emergency_buffer_size, 0);
742 emergency_buffer_size = 0;
743 emergency_buffer = Nullch;
746 if (!gvp) gvp = (GV**)hv_fetch(PL_defstash, "\015", 1, 0);
747 if (!gvp || !(sv = GvSV(*gvp)) || !SvPOK(sv)
748 || (SvLEN(sv) < (1<<LOG_OF_MIN_ARENA) - M_OVERHEAD)) {
751 return (char *)-1; /* Now die die die... */
753 /* Got it, now detach SvPV: */
755 /* Check alignment: */
756 if (((UV)(pv - sizeof(union overhead))) & (NEEDED_ALIGNMENT - 1)) {
757 PerlIO_puts(PerlIO_stderr(),"Bad alignment of $^M!\n");
758 return (char *)-1; /* die die die */
761 emergency_buffer = pv - sizeof(union overhead);
762 emergency_buffer_size = malloced_size(pv) + M_OVERHEAD;
765 SvCUR(sv) = SvLEN(sv) = 0;
769 croak("Out of memory during request for %i bytes", size);
772 #else /* !(defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)) */
773 # define emergency_sbrk(size) -1
774 #endif /* !(defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)) */
777 * nextf[i] is the pointer to the next free block of size 2^i. The
778 * smallest allocatable block is 8 bytes. The overhead information
779 * precedes the data area returned to the user.
781 #define NBUCKETS (32*BUCKETS_PER_POW2 + 1)
782 static union overhead *nextf[NBUCKETS];
785 #define sbrk(a) Perl_sbrk(a)
786 Malloc_t Perl_sbrk (int size);
788 #ifdef DONT_DECLARE_STD
793 extern Malloc_t sbrk(int);
797 #ifdef DEBUGGING_MSTATS
799 * nmalloc[i] is the difference between the number of mallocs and frees
800 * for a given block size.
802 static u_int nmalloc[NBUCKETS];
803 static u_int sbrk_slack;
804 static u_int start_slack;
807 static u_int goodsbrk;
811 #define ASSERT(p,diag) if (!(p)) botch(diag,STRINGIFY(p)); else
813 botch(pTHX_ char *diag, char *s)
815 PerlIO_printf(PerlIO_stderr(), "assertion botched (%s?): %s\n", diag, s);
819 #define ASSERT(p, diag)
823 Perl_malloc(register size_t nbytes)
825 register union overhead *p;
827 register MEM_SIZE shiftr;
829 #if defined(DEBUGGING) || defined(RCHECK)
830 MEM_SIZE size = nbytes;
833 BARK_64K_LIMIT("Allocation",nbytes,nbytes);
835 if ((long)nbytes < 0)
836 croak("%s", "panic: malloc");
841 * Convert amount of memory requested into
842 * closest block size stored in hash buckets
843 * which satisfies request. Account for
844 * space used per block for accounting.
847 # ifdef SMALL_BUCKET_VIA_TABLE
850 else if (nbytes <= SIZE_TABLE_MAX) {
851 bucket = bucket_of[(nbytes - 1) >> BUCKET_TABLE_SHIFT];
856 if (nbytes <= MAX_POW2_ALGO) goto do_shifts;
861 POW2_OPTIMIZE_ADJUST(nbytes);
862 nbytes += M_OVERHEAD;
863 nbytes = (nbytes + 3) &~ 3;
865 shiftr = (nbytes - 1) >> START_SHIFT;
866 bucket = START_SHIFTS_BUCKET;
867 /* apart from this loop, this is O(1) */
869 bucket += BUCKETS_PER_POW2;
872 * If nothing in hash bucket right now,
873 * request more memory from the system.
875 if (nextf[bucket] == NULL)
877 if ((p = nextf[bucket]) == NULL) {
881 PerlIO_puts(PerlIO_stderr(),"Out of memory!\n");
889 DEBUG_m(PerlIO_printf(Perl_debug_log,
890 "0x%lx: (%05lu) malloc %ld bytes\n",
891 (unsigned long)(p+1), (unsigned long)(PL_an++),
894 /* remove from linked list */
896 if (((UV)p) & (MEM_ALIGNBYTES - 1))
897 PerlIO_printf(PerlIO_stderr(), "Corrupt malloc ptr 0x%lx at 0x%lx\n",
898 (unsigned long)*((int*)p),(unsigned long)p);
900 nextf[bucket] = p->ov_next;
901 #ifdef IGNORE_SMALL_BAD_FREE
902 if (bucket >= FIRST_BUCKET_WITH_CHECK)
904 OV_MAGIC(p, bucket) = MAGIC;
906 OV_INDEX(p) = bucket;
910 * Record allocated size of block and
911 * bound space with magic numbers.
913 p->ov_rmagic = RMAGIC;
914 if (bucket <= MAX_SHORT_BUCKET) {
917 nbytes = size + M_OVERHEAD;
918 p->ov_size = nbytes - 1;
919 if ((i = nbytes & 3)) {
922 *((char *)((caddr_t)p + nbytes - RSLOP + i)) = RMAGIC_C;
924 nbytes = (nbytes + 3) &~ 3;
925 *((u_int *)((caddr_t)p + nbytes - RSLOP)) = RMAGIC;
929 return ((Malloc_t)(p + CHUNK_SHIFT));
932 static char *last_sbrk_top;
933 static char *last_op; /* This arena can be easily extended. */
934 static int sbrked_remains;
935 static int sbrk_good = SBRK_ALLOW_FAILURES * SBRK_FAILURE_PRICE;
937 #ifdef DEBUGGING_MSTATS
941 struct chunk_chain_s {
942 struct chunk_chain_s *next;
945 static struct chunk_chain_s *chunk_chain;
947 static char max_bucket;
949 /* Cutoff a piece of one of the chunks in the chain. Prefer smaller chunk. */
951 get_from_chain(pTHX_ MEM_SIZE size)
953 struct chunk_chain_s *elt = chunk_chain, **oldp = &chunk_chain;
954 struct chunk_chain_s **oldgoodp = NULL;
955 long min_remain = LONG_MAX;
958 if (elt->size >= size) {
959 long remains = elt->size - size;
960 if (remains >= 0 && remains < min_remain) {
962 min_remain = remains;
968 oldp = &( elt->next );
971 if (!oldgoodp) return NULL;
973 void *ret = *oldgoodp;
974 struct chunk_chain_s *next = (*oldgoodp)->next;
976 *oldgoodp = (struct chunk_chain_s *)((char*)ret + size);
977 (*oldgoodp)->size = min_remain;
978 (*oldgoodp)->next = next;
981 void *ret = *oldgoodp;
982 *oldgoodp = (*oldgoodp)->next;
989 add_to_chain(pTHX_ void *p, MEM_SIZE size, MEM_SIZE chip)
991 struct chunk_chain_s *next = chunk_chain;
995 chunk_chain = (struct chunk_chain_s *)cp;
996 chunk_chain->size = size - chip;
997 chunk_chain->next = next;
1002 get_from_bigger_buckets(pTHX_ int bucket, MEM_SIZE size)
1005 static int bucketprice[NBUCKETS];
1006 while (bucket <= max_bucket) {
1007 /* We postpone stealing from bigger buckets until we want it
1009 if (nextf[bucket] && bucketprice[bucket]++ >= price) {
1011 void *ret = (void*)(nextf[bucket] - 1 + CHUNK_SHIFT);
1012 bucketprice[bucket] = 0;
1013 if (((char*)nextf[bucket]) - M_OVERHEAD == last_op) {
1014 last_op = NULL; /* Disable optimization */
1016 nextf[bucket] = nextf[bucket]->ov_next;
1017 #ifdef DEBUGGING_MSTATS
1019 start_slack -= M_OVERHEAD;
1021 add_to_chain(ret, (BUCKET_SIZE(bucket) +
1022 POW2_OPTIMIZE_SURPLUS(bucket)),
1031 STATIC union overhead *
1032 getpages(pTHX_ int needed, int *nblksp, int bucket)
1034 /* Need to do (possibly expensive) system call. Try to
1035 optimize it for rare calling. */
1036 MEM_SIZE require = needed - sbrked_remains;
1038 union overhead *ovp;
1041 if (sbrk_good > 0) {
1042 if (!last_sbrk_top && require < FIRST_SBRK)
1043 require = FIRST_SBRK;
1044 else if (require < MIN_SBRK) require = MIN_SBRK;
1046 if (require < goodsbrk * MIN_SBRK_FRAC / 100)
1047 require = goodsbrk * MIN_SBRK_FRAC / 100;
1048 require = ((require - 1 + MIN_SBRK) / MIN_SBRK) * MIN_SBRK;
1055 DEBUG_m(PerlIO_printf(Perl_debug_log,
1056 "sbrk(%ld) for %ld-byte-long arena\n",
1057 (long)require, (long) needed));
1058 cp = (char *)sbrk(require);
1059 #ifdef DEBUGGING_MSTATS
1062 if (cp == last_sbrk_top) {
1063 /* Common case, anything is fine. */
1065 ovp = (union overhead *) (cp - sbrked_remains);
1066 last_op = cp - sbrked_remains;
1067 sbrked_remains = require - (needed - sbrked_remains);
1068 } else if (cp == (char *)-1) { /* no more room! */
1069 ovp = (union overhead *)emergency_sbrk(needed);
1070 if (ovp == (union overhead *)-1)
1072 if (((char*)ovp) > last_op) { /* Cannot happen with current emergency_sbrk() */
1076 } else { /* Non-continuous or first sbrk(). */
1077 long add = sbrked_remains;
1080 if (sbrked_remains) { /* Put rest into chain, we
1081 cannot use it right now. */
1082 add_to_chain((void*)(last_sbrk_top - sbrked_remains),
1086 /* Second, check alignment. */
1089 #if !defined(atarist) && !defined(__MINT__) /* on the atari we dont have to worry about this */
1090 # ifndef I286 /* The sbrk(0) call on the I286 always returns the next segment */
1091 /* WANTED_ALIGNMENT may be more than NEEDED_ALIGNMENT, but this may
1092 improve performance of memory access. */
1093 if ((UV)cp & (WANTED_ALIGNMENT - 1)) { /* Not aligned. */
1094 slack = WANTED_ALIGNMENT - ((UV)cp & (WANTED_ALIGNMENT - 1));
1098 #endif /* !atarist && !MINT */
1101 DEBUG_m(PerlIO_printf(Perl_debug_log,
1102 "sbrk(%ld) to fix non-continuous/off-page sbrk:\n\t%ld for alignement,\t%ld were assumed to come from the tail of the previous sbrk\n",
1103 (long)add, (long) slack,
1104 (long) sbrked_remains));
1105 newcp = (char *)sbrk(add);
1106 #if defined(DEBUGGING_MSTATS)
1110 if (newcp != cp + require) {
1111 /* Too bad: even rounding sbrk() is not continuous.*/
1112 DEBUG_m(PerlIO_printf(Perl_debug_log,
1113 "failed to fix bad sbrk()\n"));
1117 fatalcroak("panic: Off-page sbrk\n");
1120 if (sbrked_remains) {
1122 #if defined(DEBUGGING_MSTATS)
1123 sbrk_slack += require;
1126 DEBUG_m(PerlIO_printf(Perl_debug_log,
1127 "straight sbrk(%ld)\n",
1129 cp = (char *)sbrk(require);
1130 #ifdef DEBUGGING_MSTATS
1133 if (cp == (char *)-1)
1136 sbrk_good = -1; /* Disable optimization!
1137 Continue with not-aligned... */
1140 require += sbrked_remains;
1144 if (last_sbrk_top) {
1145 sbrk_good -= SBRK_FAILURE_PRICE;
1148 ovp = (union overhead *) cp;
1150 * Round up to minimum allocation size boundary
1151 * and deduct from block count to reflect.
1154 # if NEEDED_ALIGNMENT > MEM_ALIGNBYTES
1155 if ((UV)ovp & (NEEDED_ALIGNMENT - 1))
1156 fatalcroak("Misalignment of sbrk()\n");
1159 #ifndef I286 /* Again, this should always be ok on an 80286 */
1160 if ((UV)ovp & (MEM_ALIGNBYTES - 1)) {
1161 DEBUG_m(PerlIO_printf(Perl_debug_log,
1162 "fixing sbrk(): %d bytes off machine alignement\n",
1163 (int)((UV)ovp & (MEM_ALIGNBYTES - 1))));
1164 ovp = (union overhead *)(((UV)ovp + MEM_ALIGNBYTES) &
1165 (MEM_ALIGNBYTES - 1));
1167 # if defined(DEBUGGING_MSTATS)
1168 /* This is only approx. if TWO_POT_OPTIMIZE: */
1169 sbrk_slack += (1 << (bucket >> BUCKET_POW2_SHIFT));
1173 ; /* Finish `else' */
1174 sbrked_remains = require - needed;
1177 last_sbrk_top = cp + require;
1178 #ifdef DEBUGGING_MSTATS
1179 goodsbrk += require;
1185 getpages_adjacent(pTHX_ int require)
1187 if (require <= sbrked_remains) {
1188 sbrked_remains -= require;
1192 require -= sbrked_remains;
1193 /* We do not try to optimize sbrks here, we go for place. */
1194 cp = (char*) sbrk(require);
1195 #ifdef DEBUGGING_MSTATS
1197 goodsbrk += require;
1199 if (cp == last_sbrk_top) {
1201 last_sbrk_top = cp + require;
1203 if (cp == (char*)-1) { /* Out of memory */
1204 #ifdef DEBUGGING_MSTATS
1205 goodsbrk -= require;
1209 /* Report the failure: */
1211 add_to_chain((void*)(last_sbrk_top - sbrked_remains),
1213 add_to_chain((void*)cp, require, 0);
1214 sbrk_good -= SBRK_FAILURE_PRICE;
1226 * Allocate more memory to the indicated bucket.
1229 morecore(pTHX_ register int bucket)
1231 register union overhead *ovp;
1232 register int rnu; /* 2^rnu bytes will be requested */
1233 int nblks; /* become nblks blocks of the desired size */
1234 register MEM_SIZE siz, needed;
1238 if (bucket == sizeof(MEM_SIZE)*8*BUCKETS_PER_POW2) {
1240 croak("%s", "Out of memory during ridiculously large request");
1242 if (bucket > max_bucket)
1243 max_bucket = bucket;
1245 rnu = ( (bucket <= (LOG_OF_MIN_ARENA << BUCKET_POW2_SHIFT))
1247 : (bucket >> BUCKET_POW2_SHIFT) );
1248 /* This may be overwritten later: */
1249 nblks = 1 << (rnu - (bucket >> BUCKET_POW2_SHIFT)); /* how many blocks to get */
1250 needed = ((MEM_SIZE)1 << rnu) + POW2_OPTIMIZE_SURPLUS(bucket);
1251 if (nextf[rnu << BUCKET_POW2_SHIFT]) { /* 2048b bucket. */
1252 ovp = nextf[rnu << BUCKET_POW2_SHIFT] - 1 + CHUNK_SHIFT;
1253 nextf[rnu << BUCKET_POW2_SHIFT]
1254 = nextf[rnu << BUCKET_POW2_SHIFT]->ov_next;
1255 #ifdef DEBUGGING_MSTATS
1256 nmalloc[rnu << BUCKET_POW2_SHIFT]--;
1257 start_slack -= M_OVERHEAD;
1259 DEBUG_m(PerlIO_printf(Perl_debug_log,
1260 "stealing %ld bytes from %ld arena\n",
1261 (long) needed, (long) rnu << BUCKET_POW2_SHIFT));
1262 } else if (chunk_chain
1263 && (ovp = (union overhead*) get_from_chain(needed))) {
1264 DEBUG_m(PerlIO_printf(Perl_debug_log,
1265 "stealing %ld bytes from chain\n",
1267 } else if ( (ovp = (union overhead*)
1268 get_from_bigger_buckets((rnu << BUCKET_POW2_SHIFT) + 1,
1270 DEBUG_m(PerlIO_printf(Perl_debug_log,
1271 "stealing %ld bytes from bigger buckets\n",
1273 } else if (needed <= sbrked_remains) {
1274 ovp = (union overhead *)(last_sbrk_top - sbrked_remains);
1275 sbrked_remains -= needed;
1276 last_op = (char*)ovp;
1278 ovp = getpages(needed, &nblks, bucket);
1284 * Add new memory allocated to that on
1285 * free list for this hash bucket.
1287 siz = BUCKET_SIZE(bucket);
1289 *(u_char*)ovp = bucket; /* Fill index. */
1290 if (bucket <= MAX_PACKED) {
1291 ovp = (union overhead *) ((char*)ovp + BLK_SHIFT(bucket));
1292 nblks = N_BLKS(bucket);
1293 # ifdef DEBUGGING_MSTATS
1294 start_slack += BLK_SHIFT(bucket);
1296 } else if (bucket < LOG_OF_MIN_ARENA * BUCKETS_PER_POW2) {
1297 ovp = (union overhead *) ((char*)ovp + BLK_SHIFT(bucket));
1298 siz -= sizeof(union overhead);
1299 } else ovp++; /* One chunk per block. */
1300 #endif /* PACK_MALLOC */
1301 nextf[bucket] = ovp;
1302 #ifdef DEBUGGING_MSTATS
1303 nmalloc[bucket] += nblks;
1304 if (bucket > MAX_PACKED) {
1305 start_slack += M_OVERHEAD * nblks;
1308 while (--nblks > 0) {
1309 ovp->ov_next = (union overhead *)((caddr_t)ovp + siz);
1310 ovp = (union overhead *)((caddr_t)ovp + siz);
1312 /* Not all sbrks return zeroed memory.*/
1313 ovp->ov_next = (union overhead *)NULL;
1315 if (bucket == 7*BUCKETS_PER_POW2) { /* Special case, explanation is above. */
1316 union overhead *n_op = nextf[7*BUCKETS_PER_POW2]->ov_next;
1317 nextf[7*BUCKETS_PER_POW2] =
1318 (union overhead *)((caddr_t)nextf[7*BUCKETS_PER_POW2]
1319 - sizeof(union overhead));
1320 nextf[7*BUCKETS_PER_POW2]->ov_next = n_op;
1322 #endif /* !PACK_MALLOC */
1326 Perl_mfree(void *mp)
1328 register MEM_SIZE size;
1329 register union overhead *ovp;
1330 char *cp = (char*)mp;
1335 DEBUG_m(PerlIO_printf(Perl_debug_log,
1336 "0x%lx: (%05lu) free\n",
1337 (unsigned long)cp, (unsigned long)(PL_an++)));
1341 ovp = (union overhead *)((caddr_t)cp
1342 - sizeof (union overhead) * CHUNK_SHIFT);
1344 bucket = OV_INDEX(ovp);
1346 #ifdef IGNORE_SMALL_BAD_FREE
1347 if ((bucket >= FIRST_BUCKET_WITH_CHECK)
1348 && (OV_MAGIC(ovp, bucket) != MAGIC))
1350 if (OV_MAGIC(ovp, bucket) != MAGIC)
1353 static int bad_free_warn = -1;
1354 if (bad_free_warn == -1) {
1355 char *pbf = PerlEnv_getenv("PERL_BADFREE");
1356 bad_free_warn = (pbf) ? atoi(pbf) : 1;
1361 warn("%s free() ignored",
1362 ovp->ov_rmagic == RMAGIC - 1 ? "Duplicate" : "Bad");
1364 warn("%s", "Bad free() ignored");
1366 return; /* sanity */
1370 ASSERT(ovp->ov_rmagic == RMAGIC, "chunk's head overwrite");
1371 if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET) {
1373 MEM_SIZE nbytes = ovp->ov_size + 1;
1375 if ((i = nbytes & 3)) {
1378 ASSERT(*((char *)((caddr_t)ovp + nbytes - RSLOP + i))
1379 == RMAGIC_C, "chunk's tail overwrite");
1382 nbytes = (nbytes + 3) &~ 3;
1383 ASSERT(*(u_int *)((caddr_t)ovp + nbytes - RSLOP) == RMAGIC, "chunk's tail overwrite");
1385 ovp->ov_rmagic = RMAGIC - 1;
1387 ASSERT(OV_INDEX(ovp) < NBUCKETS, "chunk's head overwrite");
1388 size = OV_INDEX(ovp);
1389 ovp->ov_next = nextf[size];
1395 * When a program attempts "storage compaction" as mentioned in the
1396 * old malloc man page, it realloc's an already freed block. Usually
1397 * this is the last block it freed; occasionally it might be farther
1398 * back. We have to search all the free lists for the block in order
1399 * to determine its bucket: 1st we make one pass thru the lists
1400 * checking only the first block in each; if that fails we search
1401 * ``reall_srchlen'' blocks in each list for a match (the variable
1402 * is extern so the caller can modify it). If that fails we just copy
1403 * however many bytes was given to realloc() and hope it's not huge.
1405 #define reall_srchlen 4 /* 4 should be plenty, -1 =>'s whole list */
1408 Perl_realloc(void *mp, size_t nbytes)
1410 register MEM_SIZE onb;
1411 union overhead *ovp;
1414 register int bucket;
1415 int was_alloced = 0, incr;
1416 char *cp = (char*)mp;
1418 #if defined(DEBUGGING) || !defined(PERL_CORE)
1419 MEM_SIZE size = nbytes;
1421 if ((long)nbytes < 0)
1422 croak("%s", "panic: realloc");
1425 BARK_64K_LIMIT("Reallocation",nbytes,size);
1427 return Perl_malloc(nbytes);
1430 ovp = (union overhead *)((caddr_t)cp
1431 - sizeof (union overhead) * CHUNK_SHIFT);
1432 bucket = OV_INDEX(ovp);
1433 #ifdef IGNORE_SMALL_BAD_FREE
1434 if ((bucket < FIRST_BUCKET_WITH_CHECK)
1435 || (OV_MAGIC(ovp, bucket) == MAGIC))
1437 if (OV_MAGIC(ovp, bucket) == MAGIC)
1443 * Already free, doing "compaction".
1445 * Search for the old block of memory on the
1446 * free list. First, check the most common
1447 * case (last element free'd), then (this failing)
1448 * the last ``reall_srchlen'' items free'd.
1449 * If all lookups fail, then assume the size of
1450 * the memory block being realloc'd is the
1451 * smallest possible.
1453 if ((bucket = findbucket(ovp, 1)) < 0 &&
1454 (bucket = findbucket(ovp, reall_srchlen)) < 0)
1457 onb = BUCKET_SIZE_REAL(bucket);
1459 * avoid the copy if same size block.
1460 * We are not agressive with boundary cases. Note that it might
1461 * (for a small number of cases) give false negative if
1462 * both new size and old one are in the bucket for
1463 * FIRST_BIG_POW2, but the new one is near the lower end.
1465 * We do not try to go to 1.5 times smaller bucket so far.
1467 if (nbytes > onb) incr = 1;
1469 #ifdef DO_NOT_TRY_HARDER_WHEN_SHRINKING
1470 if ( /* This is a little bit pessimal if PACK_MALLOC: */
1471 nbytes > ( (onb >> 1) - M_OVERHEAD )
1472 # ifdef TWO_POT_OPTIMIZE
1473 || (bucket == FIRST_BIG_POW2 && nbytes >= LAST_SMALL_BOUND )
1476 #else /* !DO_NOT_TRY_HARDER_WHEN_SHRINKING */
1477 prev_bucket = ( (bucket > MAX_PACKED + 1)
1478 ? bucket - BUCKETS_PER_POW2
1480 if (nbytes > BUCKET_SIZE_REAL(prev_bucket))
1481 #endif /* !DO_NOT_TRY_HARDER_WHEN_SHRINKING */
1486 #ifdef STRESS_REALLOC
1487 || 1 /* always do it the hard way */
1490 else if (incr == 0) {
1494 * Record new allocated size of block and
1495 * bound space with magic numbers.
1497 if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET) {
1498 int i, nb = ovp->ov_size + 1;
1503 ASSERT(*((char *)((caddr_t)ovp + nb - RSLOP + i)) == RMAGIC_C, "chunk's tail overwrite");
1507 ASSERT(*(u_int *)((caddr_t)ovp + nb - RSLOP) == RMAGIC, "chunk's tail overwrite");
1509 * Convert amount of memory requested into
1510 * closest block size stored in hash buckets
1511 * which satisfies request. Account for
1512 * space used per block for accounting.
1514 nbytes += M_OVERHEAD;
1515 ovp->ov_size = nbytes - 1;
1516 if ((i = nbytes & 3)) {
1519 *((char *)((caddr_t)ovp + nbytes - RSLOP + i))
1522 nbytes = (nbytes + 3) &~ 3;
1523 *((u_int *)((caddr_t)ovp + nbytes - RSLOP)) = RMAGIC;
1528 DEBUG_m(PerlIO_printf(Perl_debug_log,
1529 "0x%lx: (%05lu) realloc %ld bytes inplace\n",
1530 (unsigned long)res,(unsigned long)(PL_an++),
1532 } else if (incr == 1 && (cp - M_OVERHEAD == last_op)
1533 && (onb > (1 << LOG_OF_MIN_ARENA))) {
1534 MEM_SIZE require, newarena = nbytes, pow;
1537 POW2_OPTIMIZE_ADJUST(newarena);
1538 newarena = newarena + M_OVERHEAD;
1539 /* newarena = (newarena + 3) &~ 3; */
1540 shiftr = (newarena - 1) >> LOG_OF_MIN_ARENA;
1541 pow = LOG_OF_MIN_ARENA + 1;
1542 /* apart from this loop, this is O(1) */
1543 while (shiftr >>= 1)
1545 newarena = (1 << pow) + POW2_OPTIMIZE_SURPLUS(pow * BUCKETS_PER_POW2);
1546 require = newarena - onb - M_OVERHEAD;
1548 if (getpages_adjacent(require)) {
1549 #ifdef DEBUGGING_MSTATS
1551 nmalloc[pow * BUCKETS_PER_POW2]++;
1553 *(cp - M_OVERHEAD) = pow * BUCKETS_PER_POW2; /* Fill index. */
1560 DEBUG_m(PerlIO_printf(Perl_debug_log,
1561 "0x%lx: (%05lu) realloc %ld bytes the hard way\n",
1562 (unsigned long)cp,(unsigned long)(PL_an++),
1564 if ((res = (char*)Perl_malloc(nbytes)) == NULL)
1566 if (cp != res) /* common optimization */
1567 Copy(cp, res, (MEM_SIZE)(nbytes<onb?nbytes:onb), char);
1571 return ((Malloc_t)res);
1575 * Search ``srchlen'' elements of each free list for a block whose
1576 * header starts at ``freep''. If srchlen is -1 search the whole list.
1577 * Return bucket number, or -1 if not found.
1580 findbucket(union overhead *freep, int srchlen)
1582 register union overhead *p;
1585 for (i = 0; i < NBUCKETS; i++) {
1587 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
1597 Perl_calloc(register size_t elements, register size_t size)
1599 long sz = elements * size;
1600 Malloc_t p = Perl_malloc(sz);
1603 memset((void*)p, 0, sz);
1609 Perl_malloced_size(pTHX_ void *p)
1611 union overhead *ovp = (union overhead *)
1612 ((caddr_t)p - sizeof (union overhead) * CHUNK_SHIFT);
1613 int bucket = OV_INDEX(ovp);
1615 /* The caller wants to have a complete control over the chunk,
1616 disable the memory checking inside the chunk. */
1617 if (bucket <= MAX_SHORT_BUCKET) {
1618 MEM_SIZE size = BUCKET_SIZE_REAL(bucket);
1619 ovp->ov_size = size + M_OVERHEAD - 1;
1620 *((u_int *)((caddr_t)ovp + size + M_OVERHEAD - RSLOP)) = RMAGIC;
1623 return BUCKET_SIZE_REAL(bucket);
1626 # ifdef BUCKETS_ROOT2
1627 # define MIN_EVEN_REPORT 6
1629 # define MIN_EVEN_REPORT MIN_BUCKET
1632 * mstats - print out statistics about malloc
1634 * Prints two lines of numbers, one showing the length of the free list
1635 * for each size category, the second showing the number of mallocs -
1636 * frees for each size category.
1639 Perl_dump_mstats(pTHX_ char *s)
1641 #ifdef DEBUGGING_MSTATS
1643 register union overhead *p;
1644 int topbucket=0, topbucket_ev=0, topbucket_odd=0, totfree=0, total=0;
1645 u_int nfree[NBUCKETS];
1646 int total_chain = 0;
1647 struct chunk_chain_s* nextchain = chunk_chain;
1649 for (i = MIN_BUCKET ; i < NBUCKETS; i++) {
1650 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
1653 totfree += nfree[i] * BUCKET_SIZE_REAL(i);
1654 total += nmalloc[i] * BUCKET_SIZE_REAL(i);
1656 i % 2 ? (topbucket_odd = i) : (topbucket_ev = i);
1661 PerlIO_printf(PerlIO_stderr(),
1662 "Memory allocation statistics %s (buckets %ld(%ld)..%ld(%ld)\n",
1664 (long)BUCKET_SIZE_REAL(MIN_BUCKET),
1665 (long)BUCKET_SIZE(MIN_BUCKET),
1666 (long)BUCKET_SIZE_REAL(topbucket), (long)BUCKET_SIZE(topbucket));
1667 PerlIO_printf(PerlIO_stderr(), "%8d free:", totfree);
1668 for (i = MIN_EVEN_REPORT; i <= topbucket; i += BUCKETS_PER_POW2) {
1669 PerlIO_printf(PerlIO_stderr(),
1670 ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1672 : ((i < 12*BUCKETS_PER_POW2) ? " %3d" : " %d")),
1675 #ifdef BUCKETS_ROOT2
1676 PerlIO_printf(PerlIO_stderr(), "\n\t ");
1677 for (i = MIN_BUCKET + 1; i <= topbucket_odd; i += BUCKETS_PER_POW2) {
1678 PerlIO_printf(PerlIO_stderr(),
1679 ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1681 : ((i < 12*BUCKETS_PER_POW2) ? " %3d" : " %d")),
1685 PerlIO_printf(PerlIO_stderr(), "\n%8d used:", total - totfree);
1686 for (i = MIN_EVEN_REPORT; i <= topbucket; i += BUCKETS_PER_POW2) {
1687 PerlIO_printf(PerlIO_stderr(),
1688 ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1690 : ((i < 12*BUCKETS_PER_POW2) ? " %3d" : " %d")),
1691 nmalloc[i] - nfree[i]);
1693 #ifdef BUCKETS_ROOT2
1694 PerlIO_printf(PerlIO_stderr(), "\n\t ");
1695 for (i = MIN_BUCKET + 1; i <= topbucket_odd; i += BUCKETS_PER_POW2) {
1696 PerlIO_printf(PerlIO_stderr(),
1697 ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1699 : ((i < 12*BUCKETS_PER_POW2) ? " %3d" : " %d")),
1700 nmalloc[i] - nfree[i]);
1704 total_chain += nextchain->size;
1705 nextchain = nextchain->next;
1707 PerlIO_printf(PerlIO_stderr(), "\nTotal sbrk(): %d/%d:%d. Odd ends: pad+heads+chain+tail: %d+%d+%d+%d.\n",
1708 goodsbrk + sbrk_slack, sbrks, sbrk_good, sbrk_slack,
1709 start_slack, total_chain, sbrked_remains);
1710 #endif /* DEBUGGING_MSTATS */
1714 #ifdef USE_PERL_SBRK
1716 # if defined(__MACHTEN_PPC__) || defined(NeXT) || defined(__NeXT__)
1717 # define PERL_SBRK_VIA_MALLOC
1719 * MachTen's malloc() returns a buffer aligned on a two-byte boundary.
1720 * While this is adequate, it may slow down access to longer data
1721 * types by forcing multiple memory accesses. It also causes
1722 * complaints when RCHECK is in force. So we allocate six bytes
1723 * more than we need to, and return an address rounded up to an
1724 * eight-byte boundary.
1726 * 980701 Dominic Dunlop <domo@computer.org>
1728 # define SYSTEM_ALLOC_ALIGNMENT 2
1731 # ifdef PERL_SBRK_VIA_MALLOC
1733 /* it may seem schizophrenic to use perl's malloc and let it call system */
1734 /* malloc, the reason for that is only the 3.2 version of the OS that had */
1735 /* frequent core dumps within nxzonefreenolock. This sbrk routine put an */
1736 /* end to the cores */
1738 # ifndef SYSTEM_ALLOC
1739 # define SYSTEM_ALLOC(a) malloc(a)
1741 # ifndef SYSTEM_ALLOC_ALIGNMENT
1742 # define SYSTEM_ALLOC_ALIGNMENT MEM_ALIGNBYTES
1745 # endif /* PERL_SBRK_VIA_MALLOC */
1747 static IV Perl_sbrk_oldchunk;
1748 static long Perl_sbrk_oldsize;
1750 # define PERLSBRK_32_K (1<<15)
1751 # define PERLSBRK_64_K (1<<16)
1759 if (!size) return 0;
1761 reqsize = size; /* just for the DEBUG_m statement */
1764 size = (size + 0x7ff) & ~0x7ff;
1766 if (size <= Perl_sbrk_oldsize) {
1767 got = Perl_sbrk_oldchunk;
1768 Perl_sbrk_oldchunk += size;
1769 Perl_sbrk_oldsize -= size;
1771 if (size >= PERLSBRK_32_K) {
1774 size = PERLSBRK_64_K;
1777 # if NEEDED_ALIGNMENT > SYSTEM_ALLOC_ALIGNMENT
1778 size += NEEDED_ALIGNMENT - SYSTEM_ALLOC_ALIGNMENT;
1780 got = (IV)SYSTEM_ALLOC(size);
1781 # if NEEDED_ALIGNMENT > SYSTEM_ALLOC_ALIGNMENT
1782 got = (got + NEEDED_ALIGNMENT - 1) & ~(NEEDED_ALIGNMENT - 1);
1785 /* Chunk is small, register the rest for future allocs. */
1786 Perl_sbrk_oldchunk = got + reqsize;
1787 Perl_sbrk_oldsize = size - reqsize;
1791 DEBUG_m(PerlIO_printf(Perl_debug_log, "sbrk malloc size %ld (reqsize %ld), left size %ld, give addr 0x%lx\n",
1792 size, reqsize, Perl_sbrk_oldsize, got));
1797 #endif /* ! defined USE_PERL_SBRK */