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_NOCONTEXT(&PL_malloc_mutex)
151 MALLOC_UNLOCK MUTEX_UNLOCK_NOCONTEXT(&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
232 # if defined(PERL_IMPLICIT_CONTEXT)
233 # define croak Perl_croak_nocontext
234 # define warn Perl_warn_nocontext
238 # include "../EXTERN.h"
239 # include "../perl.h"
246 # define Malloc_t void *
249 # define MEM_SIZE unsigned long
252 # define LONG_MAX 0x7FFFFFFF
255 # define UV unsigned long
258 # define caddr_t char *
263 # define Copy(s,d,n,t) (void)memcpy((char*)(d),(char*)(s), (n) * sizeof(t))
264 # define PerlEnv_getenv getenv
265 # define PerlIO_printf fprintf
266 # define PerlIO_stderr() stderr
268 # ifndef croak /* make depend */
269 # define croak(mess, arg) (warn((mess), (arg)), exit(1))
272 # define warn(mess, arg) fprintf(stderr, (mess), (arg))
284 # define dTHX extern int Perl___notused
285 # define WITH_THX(s) s
287 # ifndef PERL_GET_INTERP
288 # define PERL_GET_INTERP PL_curinterp
291 # define Perl_malloc malloc
294 # define Perl_mfree free
296 # ifndef Perl_realloc
297 # define Perl_realloc realloc
300 # define Perl_calloc calloc
303 # define Perl_strdup strdup
308 # define MUTEX_LOCK(l)
312 # define MUTEX_UNLOCK(l)
316 # define MALLOC_LOCK MUTEX_LOCK_NOCONTEXT(&PL_malloc_mutex)
319 #ifndef MALLOC_UNLOCK
320 # define MALLOC_UNLOCK MUTEX_UNLOCK_NOCONTEXT(&PL_malloc_mutex)
323 # ifndef fatalcroak /* make depend */
324 # define fatalcroak(mess) (write(2, (mess), strlen(mess)), exit(2))
329 # define DEBUG_m(a) \
331 if (PERL_GET_INTERP) { dTHX; if (PL_debug & 128) { a; } } \
338 * The memory is broken into "blocks" which occupy multiples of 2K (and
339 * generally speaking, have size "close" to a power of 2). The addresses
340 * of such *unused* blocks are kept in nextf[i] with big enough i. (nextf
341 * is an array of linked lists.) (Addresses of used blocks are not known.)
343 * Moreover, since the algorithm may try to "bite" smaller blocks out
344 * of unused bigger ones, there are also regions of "irregular" size,
345 * managed separately, by a linked list chunk_chain.
347 * The third type of storage is the sbrk()ed-but-not-yet-used space, its
348 * end and size are kept in last_sbrk_top and sbrked_remains.
350 * Growing blocks "in place":
351 * ~~~~~~~~~~~~~~~~~~~~~~~~~
352 * The address of the block with the greatest address is kept in last_op
353 * (if not known, last_op is 0). If it is known that the memory above
354 * last_op is not continuous, or contains a chunk from chunk_chain,
355 * last_op is set to 0.
357 * The chunk with address last_op may be grown by expanding into
358 * sbrk()ed-but-not-yet-used space, or trying to sbrk() more continuous
361 * Management of last_op:
362 * ~~~~~~~~~~~~~~~~~~~~~
364 * free() never changes the boundaries of blocks, so is not relevant.
366 * The only way realloc() may change the boundaries of blocks is if it
367 * grows a block "in place". However, in the case of success such a
368 * chunk is automatically last_op, and it remains last_op. In the case
369 * of failure getpages_adjacent() clears last_op.
371 * malloc() may change blocks by calling morecore() only.
373 * morecore() may create new blocks by:
374 * a) biting pieces from chunk_chain (cannot create one above last_op);
375 * b) biting a piece from an unused block (if block was last_op, this
376 * may create a chunk from chain above last_op, thus last_op is
377 * invalidated in such a case).
378 * c) biting of sbrk()ed-but-not-yet-used space. This creates
379 * a block which is last_op.
380 * d) Allocating new pages by calling getpages();
382 * getpages() creates a new block. It marks last_op at the bottom of
383 * the chunk of memory it returns.
385 * Active pages footprint:
386 * ~~~~~~~~~~~~~~~~~~~~~~
387 * Note that we do not need to traverse the lists in nextf[i], just take
388 * the first element of this list. However, we *need* to traverse the
389 * list in chunk_chain, but most the time it should be a very short one,
390 * so we do not step on a lot of pages we are not going to use.
394 * get_from_bigger_buckets(): forget to increment price => Quite
398 /* I don't much care whether these are defined in sys/types.h--LAW */
400 #define u_char unsigned char
401 #define u_int unsigned int
403 * I removed the definition of u_bigint which appeared to be u_bigint = UV
404 * u_bigint was only used in TWOK_MASKED and TWOK_SHIFT
405 * where I have used PTR2UV. RMB
407 #define u_short unsigned short
409 /* 286 and atarist like big chunks, which gives too much overhead. */
410 #if (defined(RCHECK) || defined(I286) || defined(atarist) || defined(__MINT__)) && defined(PACK_MALLOC)
415 * The description below is applicable if PACK_MALLOC is not defined.
417 * The overhead on a block is at least 4 bytes. When free, this space
418 * contains a pointer to the next free block, and the bottom two bits must
419 * be zero. When in use, the first byte is set to MAGIC, and the second
420 * byte is the size index. The remaining bytes are for alignment.
421 * If range checking is enabled and the size of the block fits
422 * in two bytes, then the top two bytes hold the size of the requested block
423 * plus the range checking words, and the header word MINUS ONE.
426 union overhead *ov_next; /* when free */
427 #if MEM_ALIGNBYTES > 4
428 double strut; /* alignment problems */
431 u_char ovu_magic; /* magic number */
432 u_char ovu_index; /* bucket # */
434 u_short ovu_size; /* actual block size */
435 u_int ovu_rmagic; /* range magic number */
438 #define ov_magic ovu.ovu_magic
439 #define ov_index ovu.ovu_index
440 #define ov_size ovu.ovu_size
441 #define ov_rmagic ovu.ovu_rmagic
444 #define MAGIC 0xff /* magic # on accounting info */
445 #define RMAGIC 0x55555555 /* magic # on range info */
446 #define RMAGIC_C 0x55 /* magic # on range info */
449 # define RSLOP sizeof (u_int)
450 # ifdef TWO_POT_OPTIMIZE
451 # define MAX_SHORT_BUCKET (12 * BUCKETS_PER_POW2)
453 # define MAX_SHORT_BUCKET (13 * BUCKETS_PER_POW2)
459 #if !defined(PACK_MALLOC) && defined(BUCKETS_ROOT2)
460 # undef BUCKETS_ROOT2
464 # define BUCKET_TABLE_SHIFT 2
465 # define BUCKET_POW2_SHIFT 1
466 # define BUCKETS_PER_POW2 2
468 # define BUCKET_TABLE_SHIFT MIN_BUC_POW2
469 # define BUCKET_POW2_SHIFT 0
470 # define BUCKETS_PER_POW2 1
473 #if !defined(MEM_ALIGNBYTES) || ((MEM_ALIGNBYTES > 4) && !defined(STRICT_ALIGNMENT))
474 /* Figure out the alignment of void*. */
479 # define ALIGN_SMALL ((int)((caddr_t)&(((struct aligner*)0)->p)))
481 # define ALIGN_SMALL MEM_ALIGNBYTES
484 #define IF_ALIGN_8(yes,no) ((ALIGN_SMALL>4) ? (yes) : (no))
487 # define MAX_BUCKET_BY_TABLE 13
488 static u_short buck_size[MAX_BUCKET_BY_TABLE + 1] =
490 0, 0, 0, 0, 4, 4, 8, 12, 16, 24, 32, 48, 64, 80,
492 # define BUCKET_SIZE(i) ((i) % 2 ? buck_size[i] : (1 << ((i) >> BUCKET_POW2_SHIFT)))
493 # define BUCKET_SIZE_REAL(i) ((i) <= MAX_BUCKET_BY_TABLE \
495 : ((1 << ((i) >> BUCKET_POW2_SHIFT)) \
497 + POW2_OPTIMIZE_SURPLUS(i)))
499 # define BUCKET_SIZE(i) (1 << ((i) >> BUCKET_POW2_SHIFT))
500 # define BUCKET_SIZE_REAL(i) (BUCKET_SIZE(i) - MEM_OVERHEAD(i) + POW2_OPTIMIZE_SURPLUS(i))
505 /* In this case there are several possible layout of arenas depending
506 * on the size. Arenas are of sizes multiple to 2K, 2K-aligned, and
507 * have a size close to a power of 2.
509 * Arenas of the size >= 4K keep one chunk only. Arenas of size 2K
510 * may keep one chunk or multiple chunks. Here are the possible
513 * # One chunk only, chunksize 2^k + SOMETHING - ALIGN, k >= 11
515 * INDEX MAGIC1 UNUSED CHUNK1
517 * # Multichunk with sanity checking and chunksize 2^k-ALIGN, k>7
519 * INDEX MAGIC1 MAGIC2 MAGIC3 UNUSED CHUNK1 CHUNK2 CHUNK3 ...
521 * # Multichunk with sanity checking and size 2^k-ALIGN, k=7
523 * INDEX MAGIC1 MAGIC2 MAGIC3 UNUSED CHUNK1 UNUSED CHUNK2 CHUNK3 ...
525 * # Multichunk with sanity checking and size up to 80
527 * INDEX UNUSED MAGIC1 UNUSED MAGIC2 UNUSED ... CHUNK1 CHUNK2 CHUNK3 ...
529 * # No sanity check (usually up to 48=byte-long buckets)
530 * INDEX UNUSED CHUNK1 CHUNK2 ...
532 * Above INDEX and MAGIC are one-byte-long. Sizes of UNUSED are
533 * appropriate to keep algorithms simple and memory aligned. INDEX
534 * encodes the size of the chunk, while MAGICn encodes state (used,
535 * free or non-managed-by-us-so-it-indicates-a-bug) of CHUNKn. MAGIC
536 * is used for sanity checking purposes only. SOMETHING is 0 or 4K
537 * (to make size of big CHUNK accomodate allocations for powers of two
540 * [There is no need to alignment between chunks, since C rules ensure
541 * that structs which need 2^k alignment have sizeof which is
542 * divisible by 2^k. Thus as far as the last chunk is aligned at the
543 * end of the arena, and 2K-alignment does not contradict things,
544 * everything is going to be OK for sizes of chunks 2^n and 2^n +
545 * 2^k. Say, 80-bit buckets will be 16-bit aligned, and as far as we
546 * put allocations for requests in 65..80 range, all is fine.
548 * Note, however, that standard malloc() puts more strict
549 * requirements than the above C rules. Moreover, our algorithms of
550 * realloc() may break this idyll, but we suppose that realloc() does
551 * need not change alignment.]
553 * Is very important to make calculation of the offset of MAGICm as
554 * quick as possible, since it is done on each malloc()/free(). In
555 * fact it is so quick that it has quite little effect on the speed of
556 * doing malloc()/free(). [By default] We forego such calculations
557 * for small chunks, but only to save extra 3% of memory, not because
558 * of speed considerations.
560 * Here is the algorithm [which is the same for all the allocations
561 * schemes above], see OV_MAGIC(block,bucket). Let OFFSETm be the
562 * offset of the CHUNKm from the start of ARENA. Then offset of
563 * MAGICm is (OFFSET1 >> SHIFT) + ADDOFFSET. Here SHIFT and ADDOFFSET
564 * are numbers which depend on the size of the chunks only.
566 * Let as check some sanity conditions. Numbers OFFSETm>>SHIFT are
567 * different for all the chunks in the arena if 2^SHIFT is not greater
568 * than size of the chunks in the arena. MAGIC1 will not overwrite
569 * INDEX provided ADDOFFSET is >0 if OFFSET1 < 2^SHIFT. MAGIClast
570 * will not overwrite CHUNK1 if OFFSET1 > (OFFSETlast >> SHIFT) +
573 * Make SHIFT the maximal possible (there is no point in making it
574 * smaller). Since OFFSETlast is 2K - CHUNKSIZE, above restrictions
575 * give restrictions on OFFSET1 and on ADDOFFSET.
577 * In particular, for chunks of size 2^k with k>=6 we can put
578 * ADDOFFSET to be from 0 to 2^k - 2^(11-k), and have
579 * OFFSET1==chunksize. For chunks of size 80 OFFSET1 of 2K%80=48 is
580 * large enough to have ADDOFFSET between 1 and 16 (similarly for 96,
581 * when ADDOFFSET should be 1). In particular, keeping MAGICs for
582 * these sizes gives no additional size penalty.
584 * However, for chunks of size 2^k with k<=5 this gives OFFSET1 >=
585 * ADDOFSET + 2^(11-k). Keeping ADDOFFSET 0 allows for 2^(11-k)-2^(11-2k)
586 * chunks per arena. This is smaller than 2^(11-k) - 1 which are
587 * needed if no MAGIC is kept. [In fact, having a negative ADDOFFSET
588 * would allow for slightly more buckets per arena for k=2,3.]
590 * Similarly, for chunks of size 3/2*2^k with k<=5 MAGICs would span
591 * the area up to 2^(11-k)+ADDOFFSET. For k=4 this give optimal
592 * ADDOFFSET as -7..0. For k=3 ADDOFFSET can go up to 4 (with tiny
593 * savings for negative ADDOFFSET). For k=5 ADDOFFSET can go -1..16
594 * (with no savings for negative values).
596 * In particular, keeping ADDOFFSET 0 for sizes of chunks up to 2^6
597 * leads to tiny pessimizations in case of sizes 4, 8, 12, 24, and
598 * leads to no contradictions except for size=80 (or 96.)
600 * However, it also makes sense to keep no magic for sizes 48 or less.
601 * This is what we do. In this case one needs ADDOFFSET>=1 also for
602 * chunksizes 12, 24, and 48, unless one gets one less chunk per
605 * The algo of OV_MAGIC(block,bucket) keeps ADDOFFSET 0 until
606 * chunksize of 64, then makes it 1.
608 * This allows for an additional optimization: the above scheme leads
609 * to giant overheads for sizes 128 or more (one whole chunk needs to
610 * be sacrifised to keep INDEX). Instead we use chunks not of size
611 * 2^k, but of size 2^k-ALIGN. If we pack these chunks at the end of
612 * the arena, then the beginnings are still in different 2^k-long
613 * sections of the arena if k>=7 for ALIGN==4, and k>=8 if ALIGN=8.
614 * Thus for k>7 the above algo of calculating the offset of the magic
615 * will still give different answers for different chunks. And to
616 * avoid the overrun of MAGIC1 into INDEX, one needs ADDOFFSET of >=1.
617 * In the case k=7 we just move the first chunk an extra ALIGN
618 * backward inside the ARENA (this is done once per arena lifetime,
619 * thus is not a big overhead). */
620 # define MAX_PACKED_POW2 6
621 # define MAX_PACKED (MAX_PACKED_POW2 * BUCKETS_PER_POW2 + BUCKET_POW2_SHIFT)
622 # define MAX_POW2_ALGO ((1<<(MAX_PACKED_POW2 + 1)) - M_OVERHEAD)
623 # define TWOK_MASK ((1<<LOG_OF_MIN_ARENA) - 1)
624 # define TWOK_MASKED(x) (PTR2UV(x) & ~TWOK_MASK)
625 # define TWOK_SHIFT(x) (PTR2UV(x) & TWOK_MASK)
626 # define OV_INDEXp(block) (INT2PTR(u_char*,TWOK_MASKED(block)))
627 # define OV_INDEX(block) (*OV_INDEXp(block))
628 # define OV_MAGIC(block,bucket) (*(OV_INDEXp(block) + \
629 (TWOK_SHIFT(block)>> \
630 (bucket>>BUCKET_POW2_SHIFT)) + \
631 (bucket >= MIN_NEEDS_SHIFT ? 1 : 0)))
632 /* A bucket can have a shift smaller than it size, we need to
633 shift its magic number so it will not overwrite index: */
634 # ifdef BUCKETS_ROOT2
635 # define MIN_NEEDS_SHIFT (7*BUCKETS_PER_POW2 - 1) /* Shift 80 greater than chunk 64. */
637 # define MIN_NEEDS_SHIFT (7*BUCKETS_PER_POW2) /* Shift 128 greater than chunk 32. */
639 # define CHUNK_SHIFT 0
641 /* Number of active buckets of given ordinal. */
642 #ifdef IGNORE_SMALL_BAD_FREE
643 #define FIRST_BUCKET_WITH_CHECK (6 * BUCKETS_PER_POW2) /* 64 */
644 # define N_BLKS(bucket) ( (bucket) < FIRST_BUCKET_WITH_CHECK \
645 ? ((1<<LOG_OF_MIN_ARENA) - 1)/BUCKET_SIZE(bucket) \
648 # define N_BLKS(bucket) n_blks[bucket]
651 static u_short n_blks[LOG_OF_MIN_ARENA * BUCKETS_PER_POW2] =
653 # if BUCKETS_PER_POW2==1
655 (MIN_BUC_POW2==2 ? 384 : 0),
656 224, 120, 62, 31, 16, 8, 4, 2
659 (MIN_BUC_POW2==2 ? 384 : 0), (MIN_BUC_POW2==2 ? 384 : 0), /* 4, 4 */
660 224, 149, 120, 80, 62, 41, 31, 25, 16, 16, 8, 8, 4, 4, 2, 2
664 /* Shift of the first bucket with the given ordinal inside 2K chunk. */
665 #ifdef IGNORE_SMALL_BAD_FREE
666 # define BLK_SHIFT(bucket) ( (bucket) < FIRST_BUCKET_WITH_CHECK \
667 ? ((1<<LOG_OF_MIN_ARENA) \
668 - BUCKET_SIZE(bucket) * N_BLKS(bucket)) \
671 # define BLK_SHIFT(bucket) blk_shift[bucket]
674 static u_short blk_shift[LOG_OF_MIN_ARENA * BUCKETS_PER_POW2] =
676 # if BUCKETS_PER_POW2==1
678 (MIN_BUC_POW2==2 ? 512 : 0),
679 256, 128, 64, 64, /* 8 to 64 */
680 16*sizeof(union overhead),
681 8*sizeof(union overhead),
682 4*sizeof(union overhead),
683 2*sizeof(union overhead),
686 (MIN_BUC_POW2==2 ? 512 : 0), (MIN_BUC_POW2==2 ? 512 : 0),
687 256, 260, 128, 128, 64, 80, 64, 48, /* 8 to 96 */
688 16*sizeof(union overhead), 16*sizeof(union overhead),
689 8*sizeof(union overhead), 8*sizeof(union overhead),
690 4*sizeof(union overhead), 4*sizeof(union overhead),
691 2*sizeof(union overhead), 2*sizeof(union overhead),
695 # define NEEDED_ALIGNMENT 0x800 /* 2k boundaries */
696 # define WANTED_ALIGNMENT 0x800 /* 2k boundaries */
698 #else /* !PACK_MALLOC */
700 # define OV_MAGIC(block,bucket) (block)->ov_magic
701 # define OV_INDEX(block) (block)->ov_index
702 # define CHUNK_SHIFT 1
703 # define MAX_PACKED -1
704 # define NEEDED_ALIGNMENT MEM_ALIGNBYTES
705 # define WANTED_ALIGNMENT 0x400 /* 1k boundaries */
707 #endif /* !PACK_MALLOC */
709 #define M_OVERHEAD (sizeof(union overhead) + RSLOP)
712 # define MEM_OVERHEAD(bucket) \
713 (bucket <= MAX_PACKED ? 0 : M_OVERHEAD)
714 # ifdef SMALL_BUCKET_VIA_TABLE
715 # define START_SHIFTS_BUCKET ((MAX_PACKED_POW2 + 1) * BUCKETS_PER_POW2)
716 # define START_SHIFT MAX_PACKED_POW2
717 # ifdef BUCKETS_ROOT2 /* Chunks of size 3*2^n. */
718 # define SIZE_TABLE_MAX 80
720 # define SIZE_TABLE_MAX 64
722 static char bucket_of[] =
724 # ifdef BUCKETS_ROOT2 /* Chunks of size 3*2^n. */
725 /* 0 to 15 in 4-byte increments. */
726 (sizeof(void*) > 4 ? 6 : 5), /* 4/8, 5-th bucket for better reports */
728 IF_ALIGN_8(8,7), 8, /* 16/12, 16 */
729 9, 9, 10, 10, /* 24, 32 */
730 11, 11, 11, 11, /* 48 */
731 12, 12, 12, 12, /* 64 */
732 13, 13, 13, 13, /* 80 */
733 13, 13, 13, 13 /* 80 */
734 # else /* !BUCKETS_ROOT2 */
735 /* 0 to 15 in 4-byte increments. */
736 (sizeof(void*) > 4 ? 3 : 2),
742 # endif /* !BUCKETS_ROOT2 */
744 # else /* !SMALL_BUCKET_VIA_TABLE */
745 # define START_SHIFTS_BUCKET MIN_BUCKET
746 # define START_SHIFT (MIN_BUC_POW2 - 1)
747 # endif /* !SMALL_BUCKET_VIA_TABLE */
748 #else /* !PACK_MALLOC */
749 # define MEM_OVERHEAD(bucket) M_OVERHEAD
750 # ifdef SMALL_BUCKET_VIA_TABLE
751 # undef SMALL_BUCKET_VIA_TABLE
753 # define START_SHIFTS_BUCKET MIN_BUCKET
754 # define START_SHIFT (MIN_BUC_POW2 - 1)
755 #endif /* !PACK_MALLOC */
758 * Big allocations are often of the size 2^n bytes. To make them a
759 * little bit better, make blocks of size 2^n+pagesize for big n.
762 #ifdef TWO_POT_OPTIMIZE
764 # ifndef PERL_PAGESIZE
765 # define PERL_PAGESIZE 4096
767 # ifndef FIRST_BIG_POW2
768 # define FIRST_BIG_POW2 15 /* 32K, 16K is used too often. */
770 # define FIRST_BIG_BLOCK (1<<FIRST_BIG_POW2)
771 /* If this value or more, check against bigger blocks. */
772 # define FIRST_BIG_BOUND (FIRST_BIG_BLOCK - M_OVERHEAD)
773 /* If less than this value, goes into 2^n-overhead-block. */
774 # define LAST_SMALL_BOUND ((FIRST_BIG_BLOCK>>1) - M_OVERHEAD)
776 # define POW2_OPTIMIZE_ADJUST(nbytes) \
777 ((nbytes >= FIRST_BIG_BOUND) ? nbytes -= PERL_PAGESIZE : 0)
778 # define POW2_OPTIMIZE_SURPLUS(bucket) \
779 ((bucket >= FIRST_BIG_POW2 * BUCKETS_PER_POW2) ? PERL_PAGESIZE : 0)
781 #else /* !TWO_POT_OPTIMIZE */
782 # define POW2_OPTIMIZE_ADJUST(nbytes)
783 # define POW2_OPTIMIZE_SURPLUS(bucket) 0
784 #endif /* !TWO_POT_OPTIMIZE */
786 #if defined(HAS_64K_LIMIT) && defined(PERL_CORE)
787 # define BARK_64K_LIMIT(what,nbytes,size) \
788 if (nbytes > 0xffff) { \
789 PerlIO_printf(PerlIO_stderr(), \
790 "%s too large: %lx\n", what, size); \
793 #else /* !HAS_64K_LIMIT || !PERL_CORE */
794 # define BARK_64K_LIMIT(what,nbytes,size)
795 #endif /* !HAS_64K_LIMIT || !PERL_CORE */
798 # define MIN_SBRK 2048
802 # define FIRST_SBRK (48*1024)
805 /* Minimal sbrk in percents of what is already alloced. */
806 #ifndef MIN_SBRK_FRAC
807 # define MIN_SBRK_FRAC 3
810 #ifndef SBRK_ALLOW_FAILURES
811 # define SBRK_ALLOW_FAILURES 3
814 #ifndef SBRK_FAILURE_PRICE
815 # define SBRK_FAILURE_PRICE 50
818 #if defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)
821 # define BIG_SIZE (1<<16) /* 64K */
824 #ifdef I_MACH_CTHREADS
826 # define MUTEX_LOCK(m) STMT_START { if (*m) mutex_lock(*m); } STMT_END
828 # define MUTEX_UNLOCK(m) STMT_START { if (*m) mutex_unlock(*m); } STMT_END
831 static char *emergency_buffer;
832 static MEM_SIZE emergency_buffer_size;
834 static int findbucket (union overhead *freep, int srchlen);
835 static void morecore (register int bucket);
836 # if defined(DEBUGGING)
837 static void botch (char *diag, char *s);
839 static void add_to_chain (void *p, MEM_SIZE size, MEM_SIZE chip);
840 static Malloc_t emergency_sbrk (MEM_SIZE size);
841 static void* get_from_chain (MEM_SIZE size);
842 static void* get_from_bigger_buckets(int bucket, MEM_SIZE size);
843 static union overhead *getpages (int needed, int *nblksp, int bucket);
844 static int getpages_adjacent(int require);
847 emergency_sbrk(MEM_SIZE size)
849 MEM_SIZE rsize = (((size - 1)>>LOG_OF_MIN_ARENA) + 1)<<LOG_OF_MIN_ARENA;
851 if (size >= BIG_SIZE) {
852 /* Give the possibility to recover: */
854 croak("Out of memory during \"large\" request for %i bytes", size);
857 if (emergency_buffer_size >= rsize) {
858 char *old = emergency_buffer;
860 emergency_buffer_size -= rsize;
861 emergency_buffer += rsize;
865 /* First offense, give a possibility to recover by dieing. */
866 /* No malloc involved here: */
867 GV **gvp = (GV**)hv_fetch(PL_defstash, "^M", 2, 0);
873 if (emergency_buffer_size) {
874 add_to_chain(emergency_buffer, emergency_buffer_size, 0);
875 emergency_buffer_size = 0;
876 emergency_buffer = Nullch;
879 if (!gvp) gvp = (GV**)hv_fetch(PL_defstash, "\015", 1, 0);
880 if (!gvp || !(sv = GvSV(*gvp)) || !SvPOK(sv)
881 || (SvLEN(sv) < (1<<LOG_OF_MIN_ARENA) - M_OVERHEAD)) {
884 return (char *)-1; /* Now die die die... */
886 /* Got it, now detach SvPV: */
888 /* Check alignment: */
889 if ((PTR2UV(pv) - sizeof(union overhead)) & (NEEDED_ALIGNMENT - 1)) {
890 PerlIO_puts(PerlIO_stderr(),"Bad alignment of $^M!\n");
891 return (char *)-1; /* die die die */
894 emergency_buffer = pv - sizeof(union overhead);
895 emergency_buffer_size = malloced_size(pv) + M_OVERHEAD;
898 SvCUR(sv) = SvLEN(sv) = 0;
902 croak("Out of memory during request for %i bytes", size);
907 #else /* !(defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)) */
908 # define emergency_sbrk(size) -1
909 #endif /* !(defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)) */
912 * nextf[i] is the pointer to the next free block of size 2^i. The
913 * smallest allocatable block is 8 bytes. The overhead information
914 * precedes the data area returned to the user.
916 #define NBUCKETS (32*BUCKETS_PER_POW2 + 1)
917 static union overhead *nextf[NBUCKETS];
920 #define sbrk(a) Perl_sbrk(a)
921 Malloc_t Perl_sbrk (int size);
923 #ifdef DONT_DECLARE_STD
928 extern Malloc_t sbrk(int);
932 #ifdef DEBUGGING_MSTATS
934 * nmalloc[i] is the difference between the number of mallocs and frees
935 * for a given block size.
937 static u_int nmalloc[NBUCKETS];
938 static u_int sbrk_slack;
939 static u_int start_slack;
942 static u_int goodsbrk;
946 #define ASSERT(p,diag) if (!(p)) botch(diag,STRINGIFY(p)); else
948 botch(char *diag, char *s)
951 PerlIO_printf(PerlIO_stderr(), "assertion botched (%s?): %s\n", diag, s);
955 #define ASSERT(p, diag)
959 Perl_malloc(register size_t nbytes)
961 register union overhead *p;
963 register MEM_SIZE shiftr;
965 #if defined(DEBUGGING) || defined(RCHECK)
966 MEM_SIZE size = nbytes;
969 BARK_64K_LIMIT("Allocation",nbytes,nbytes);
971 if ((long)nbytes < 0)
972 croak("%s", "panic: malloc");
976 * Convert amount of memory requested into
977 * closest block size stored in hash buckets
978 * which satisfies request. Account for
979 * space used per block for accounting.
982 # ifdef SMALL_BUCKET_VIA_TABLE
985 else if (nbytes <= SIZE_TABLE_MAX) {
986 bucket = bucket_of[(nbytes - 1) >> BUCKET_TABLE_SHIFT];
991 if (nbytes <= MAX_POW2_ALGO) goto do_shifts;
996 POW2_OPTIMIZE_ADJUST(nbytes);
997 nbytes += M_OVERHEAD;
998 nbytes = (nbytes + 3) &~ 3;
1000 shiftr = (nbytes - 1) >> START_SHIFT;
1001 bucket = START_SHIFTS_BUCKET;
1002 /* apart from this loop, this is O(1) */
1003 while (shiftr >>= 1)
1004 bucket += BUCKETS_PER_POW2;
1008 * If nothing in hash bucket right now,
1009 * request more memory from the system.
1011 if (nextf[bucket] == NULL)
1013 if ((p = nextf[bucket]) == NULL) {
1019 PerlIO_puts(PerlIO_stderr(),"Out of memory!\n");
1027 DEBUG_m(PerlIO_printf(Perl_debug_log,
1028 "0x%lx: (%05lu) malloc %ld bytes\n",
1029 (unsigned long)(p+1), (unsigned long)(PL_an++),
1032 /* remove from linked list */
1034 if ((PTR2UV(p)) & (MEM_ALIGNBYTES - 1)) {
1036 PerlIO_printf(PerlIO_stderr(), "Corrupt malloc ptr 0x%lx at 0x%lx\n",
1037 (unsigned long)*((int*)p),(unsigned long)p);
1040 nextf[bucket] = p->ov_next;
1044 #ifdef IGNORE_SMALL_BAD_FREE
1045 if (bucket >= FIRST_BUCKET_WITH_CHECK)
1047 OV_MAGIC(p, bucket) = MAGIC;
1049 OV_INDEX(p) = bucket;
1053 * Record allocated size of block and
1054 * bound space with magic numbers.
1056 p->ov_rmagic = RMAGIC;
1057 if (bucket <= MAX_SHORT_BUCKET) {
1060 nbytes = size + M_OVERHEAD;
1061 p->ov_size = nbytes - 1;
1062 if ((i = nbytes & 3)) {
1065 *((char *)((caddr_t)p + nbytes - RSLOP + i)) = RMAGIC_C;
1067 nbytes = (nbytes + 3) &~ 3;
1068 *((u_int *)((caddr_t)p + nbytes - RSLOP)) = RMAGIC;
1071 return ((Malloc_t)(p + CHUNK_SHIFT));
1074 static char *last_sbrk_top;
1075 static char *last_op; /* This arena can be easily extended. */
1076 static int sbrked_remains;
1077 static int sbrk_good = SBRK_ALLOW_FAILURES * SBRK_FAILURE_PRICE;
1079 #ifdef DEBUGGING_MSTATS
1083 struct chunk_chain_s {
1084 struct chunk_chain_s *next;
1087 static struct chunk_chain_s *chunk_chain;
1088 static int n_chunks;
1089 static char max_bucket;
1091 /* Cutoff a piece of one of the chunks in the chain. Prefer smaller chunk. */
1093 get_from_chain(MEM_SIZE size)
1095 struct chunk_chain_s *elt = chunk_chain, **oldp = &chunk_chain;
1096 struct chunk_chain_s **oldgoodp = NULL;
1097 long min_remain = LONG_MAX;
1100 if (elt->size >= size) {
1101 long remains = elt->size - size;
1102 if (remains >= 0 && remains < min_remain) {
1104 min_remain = remains;
1110 oldp = &( elt->next );
1113 if (!oldgoodp) return NULL;
1115 void *ret = *oldgoodp;
1116 struct chunk_chain_s *next = (*oldgoodp)->next;
1118 *oldgoodp = (struct chunk_chain_s *)((char*)ret + size);
1119 (*oldgoodp)->size = min_remain;
1120 (*oldgoodp)->next = next;
1123 void *ret = *oldgoodp;
1124 *oldgoodp = (*oldgoodp)->next;
1131 add_to_chain(void *p, MEM_SIZE size, MEM_SIZE chip)
1133 struct chunk_chain_s *next = chunk_chain;
1134 char *cp = (char*)p;
1137 chunk_chain = (struct chunk_chain_s *)cp;
1138 chunk_chain->size = size - chip;
1139 chunk_chain->next = next;
1144 get_from_bigger_buckets(int bucket, MEM_SIZE size)
1147 static int bucketprice[NBUCKETS];
1148 while (bucket <= max_bucket) {
1149 /* We postpone stealing from bigger buckets until we want it
1151 if (nextf[bucket] && bucketprice[bucket]++ >= price) {
1153 void *ret = (void*)(nextf[bucket] - 1 + CHUNK_SHIFT);
1154 bucketprice[bucket] = 0;
1155 if (((char*)nextf[bucket]) - M_OVERHEAD == last_op) {
1156 last_op = NULL; /* Disable optimization */
1158 nextf[bucket] = nextf[bucket]->ov_next;
1159 #ifdef DEBUGGING_MSTATS
1161 start_slack -= M_OVERHEAD;
1163 add_to_chain(ret, (BUCKET_SIZE(bucket) +
1164 POW2_OPTIMIZE_SURPLUS(bucket)),
1173 static union overhead *
1174 getpages(int needed, int *nblksp, int bucket)
1176 /* Need to do (possibly expensive) system call. Try to
1177 optimize it for rare calling. */
1178 MEM_SIZE require = needed - sbrked_remains;
1180 union overhead *ovp;
1183 if (sbrk_good > 0) {
1184 if (!last_sbrk_top && require < FIRST_SBRK)
1185 require = FIRST_SBRK;
1186 else if (require < MIN_SBRK) require = MIN_SBRK;
1188 if (require < goodsbrk * MIN_SBRK_FRAC / 100)
1189 require = goodsbrk * MIN_SBRK_FRAC / 100;
1190 require = ((require - 1 + MIN_SBRK) / MIN_SBRK) * MIN_SBRK;
1197 DEBUG_m(PerlIO_printf(Perl_debug_log,
1198 "sbrk(%ld) for %ld-byte-long arena\n",
1199 (long)require, (long) needed));
1200 cp = (char *)sbrk(require);
1201 #ifdef DEBUGGING_MSTATS
1204 if (cp == last_sbrk_top) {
1205 /* Common case, anything is fine. */
1207 ovp = (union overhead *) (cp - sbrked_remains);
1208 last_op = cp - sbrked_remains;
1209 sbrked_remains = require - (needed - sbrked_remains);
1210 } else if (cp == (char *)-1) { /* no more room! */
1211 ovp = (union overhead *)emergency_sbrk(needed);
1212 if (ovp == (union overhead *)-1)
1214 if (((char*)ovp) > last_op) { /* Cannot happen with current emergency_sbrk() */
1218 } else { /* Non-continuous or first sbrk(). */
1219 long add = sbrked_remains;
1222 if (sbrked_remains) { /* Put rest into chain, we
1223 cannot use it right now. */
1224 add_to_chain((void*)(last_sbrk_top - sbrked_remains),
1228 /* Second, check alignment. */
1231 #if !defined(atarist) && !defined(__MINT__) /* on the atari we dont have to worry about this */
1232 # ifndef I286 /* The sbrk(0) call on the I286 always returns the next segment */
1233 /* WANTED_ALIGNMENT may be more than NEEDED_ALIGNMENT, but this may
1234 improve performance of memory access. */
1235 if (PTR2UV(cp) & (WANTED_ALIGNMENT - 1)) { /* Not aligned. */
1236 slack = WANTED_ALIGNMENT - (PTR2UV(cp) & (WANTED_ALIGNMENT - 1));
1240 #endif /* !atarist && !MINT */
1243 DEBUG_m(PerlIO_printf(Perl_debug_log,
1244 "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",
1245 (long)add, (long) slack,
1246 (long) sbrked_remains));
1247 newcp = (char *)sbrk(add);
1248 #if defined(DEBUGGING_MSTATS)
1252 if (newcp != cp + require) {
1253 /* Too bad: even rounding sbrk() is not continuous.*/
1254 DEBUG_m(PerlIO_printf(Perl_debug_log,
1255 "failed to fix bad sbrk()\n"));
1259 fatalcroak("panic: Off-page sbrk\n");
1262 if (sbrked_remains) {
1264 #if defined(DEBUGGING_MSTATS)
1265 sbrk_slack += require;
1268 DEBUG_m(PerlIO_printf(Perl_debug_log,
1269 "straight sbrk(%ld)\n",
1271 cp = (char *)sbrk(require);
1272 #ifdef DEBUGGING_MSTATS
1275 if (cp == (char *)-1)
1278 sbrk_good = -1; /* Disable optimization!
1279 Continue with not-aligned... */
1282 require += sbrked_remains;
1286 if (last_sbrk_top) {
1287 sbrk_good -= SBRK_FAILURE_PRICE;
1290 ovp = (union overhead *) cp;
1292 * Round up to minimum allocation size boundary
1293 * and deduct from block count to reflect.
1296 # if NEEDED_ALIGNMENT > MEM_ALIGNBYTES
1297 if (PTR2UV(ovp) & (NEEDED_ALIGNMENT - 1))
1298 fatalcroak("Misalignment of sbrk()\n");
1301 #ifndef I286 /* Again, this should always be ok on an 80286 */
1302 if (PTR2UV(ovp) & (MEM_ALIGNBYTES - 1)) {
1303 DEBUG_m(PerlIO_printf(Perl_debug_log,
1304 "fixing sbrk(): %d bytes off machine alignement\n",
1305 (int)(PTR2UV(ovp) & (MEM_ALIGNBYTES - 1))));
1306 ovp = INT2PTR(union overhead *,(PTR2UV(ovp) + MEM_ALIGNBYTES) &
1307 (MEM_ALIGNBYTES - 1));
1309 # if defined(DEBUGGING_MSTATS)
1310 /* This is only approx. if TWO_POT_OPTIMIZE: */
1311 sbrk_slack += (1 << (bucket >> BUCKET_POW2_SHIFT));
1315 ; /* Finish `else' */
1316 sbrked_remains = require - needed;
1319 last_sbrk_top = cp + require;
1320 #ifdef DEBUGGING_MSTATS
1321 goodsbrk += require;
1327 getpages_adjacent(int require)
1329 if (require <= sbrked_remains) {
1330 sbrked_remains -= require;
1334 require -= sbrked_remains;
1335 /* We do not try to optimize sbrks here, we go for place. */
1336 cp = (char*) sbrk(require);
1337 #ifdef DEBUGGING_MSTATS
1339 goodsbrk += require;
1341 if (cp == last_sbrk_top) {
1343 last_sbrk_top = cp + require;
1345 if (cp == (char*)-1) { /* Out of memory */
1346 #ifdef DEBUGGING_MSTATS
1347 goodsbrk -= require;
1351 /* Report the failure: */
1353 add_to_chain((void*)(last_sbrk_top - sbrked_remains),
1355 add_to_chain((void*)cp, require, 0);
1356 sbrk_good -= SBRK_FAILURE_PRICE;
1368 * Allocate more memory to the indicated bucket.
1371 morecore(register int bucket)
1373 register union overhead *ovp;
1374 register int rnu; /* 2^rnu bytes will be requested */
1375 int nblks; /* become nblks blocks of the desired size */
1376 register MEM_SIZE siz, needed;
1380 if (bucket == sizeof(MEM_SIZE)*8*BUCKETS_PER_POW2) {
1382 croak("%s", "Out of memory during ridiculously large request");
1384 if (bucket > max_bucket)
1385 max_bucket = bucket;
1387 rnu = ( (bucket <= (LOG_OF_MIN_ARENA << BUCKET_POW2_SHIFT))
1389 : (bucket >> BUCKET_POW2_SHIFT) );
1390 /* This may be overwritten later: */
1391 nblks = 1 << (rnu - (bucket >> BUCKET_POW2_SHIFT)); /* how many blocks to get */
1392 needed = ((MEM_SIZE)1 << rnu) + POW2_OPTIMIZE_SURPLUS(bucket);
1393 if (nextf[rnu << BUCKET_POW2_SHIFT]) { /* 2048b bucket. */
1394 ovp = nextf[rnu << BUCKET_POW2_SHIFT] - 1 + CHUNK_SHIFT;
1395 nextf[rnu << BUCKET_POW2_SHIFT]
1396 = nextf[rnu << BUCKET_POW2_SHIFT]->ov_next;
1397 #ifdef DEBUGGING_MSTATS
1398 nmalloc[rnu << BUCKET_POW2_SHIFT]--;
1399 start_slack -= M_OVERHEAD;
1401 DEBUG_m(PerlIO_printf(Perl_debug_log,
1402 "stealing %ld bytes from %ld arena\n",
1403 (long) needed, (long) rnu << BUCKET_POW2_SHIFT));
1404 } else if (chunk_chain
1405 && (ovp = (union overhead*) get_from_chain(needed))) {
1406 DEBUG_m(PerlIO_printf(Perl_debug_log,
1407 "stealing %ld bytes from chain\n",
1409 } else if ( (ovp = (union overhead*)
1410 get_from_bigger_buckets((rnu << BUCKET_POW2_SHIFT) + 1,
1412 DEBUG_m(PerlIO_printf(Perl_debug_log,
1413 "stealing %ld bytes from bigger buckets\n",
1415 } else if (needed <= sbrked_remains) {
1416 ovp = (union overhead *)(last_sbrk_top - sbrked_remains);
1417 sbrked_remains -= needed;
1418 last_op = (char*)ovp;
1420 ovp = getpages(needed, &nblks, bucket);
1426 * Add new memory allocated to that on
1427 * free list for this hash bucket.
1429 siz = BUCKET_SIZE(bucket);
1431 *(u_char*)ovp = bucket; /* Fill index. */
1432 if (bucket <= MAX_PACKED) {
1433 ovp = (union overhead *) ((char*)ovp + BLK_SHIFT(bucket));
1434 nblks = N_BLKS(bucket);
1435 # ifdef DEBUGGING_MSTATS
1436 start_slack += BLK_SHIFT(bucket);
1438 } else if (bucket < LOG_OF_MIN_ARENA * BUCKETS_PER_POW2) {
1439 ovp = (union overhead *) ((char*)ovp + BLK_SHIFT(bucket));
1440 siz -= sizeof(union overhead);
1441 } else ovp++; /* One chunk per block. */
1442 #endif /* PACK_MALLOC */
1443 nextf[bucket] = ovp;
1444 #ifdef DEBUGGING_MSTATS
1445 nmalloc[bucket] += nblks;
1446 if (bucket > MAX_PACKED) {
1447 start_slack += M_OVERHEAD * nblks;
1450 while (--nblks > 0) {
1451 ovp->ov_next = (union overhead *)((caddr_t)ovp + siz);
1452 ovp = (union overhead *)((caddr_t)ovp + siz);
1454 /* Not all sbrks return zeroed memory.*/
1455 ovp->ov_next = (union overhead *)NULL;
1457 if (bucket == 7*BUCKETS_PER_POW2) { /* Special case, explanation is above. */
1458 union overhead *n_op = nextf[7*BUCKETS_PER_POW2]->ov_next;
1459 nextf[7*BUCKETS_PER_POW2] =
1460 (union overhead *)((caddr_t)nextf[7*BUCKETS_PER_POW2]
1461 - sizeof(union overhead));
1462 nextf[7*BUCKETS_PER_POW2]->ov_next = n_op;
1464 #endif /* !PACK_MALLOC */
1468 Perl_mfree(void *mp)
1470 register MEM_SIZE size;
1471 register union overhead *ovp;
1472 char *cp = (char*)mp;
1477 DEBUG_m(PerlIO_printf(Perl_debug_log,
1478 "0x%lx: (%05lu) free\n",
1479 (unsigned long)cp, (unsigned long)(PL_an++)));
1483 ovp = (union overhead *)((caddr_t)cp
1484 - sizeof (union overhead) * CHUNK_SHIFT);
1486 bucket = OV_INDEX(ovp);
1488 #ifdef IGNORE_SMALL_BAD_FREE
1489 if ((bucket >= FIRST_BUCKET_WITH_CHECK)
1490 && (OV_MAGIC(ovp, bucket) != MAGIC))
1492 if (OV_MAGIC(ovp, bucket) != MAGIC)
1495 static int bad_free_warn = -1;
1496 if (bad_free_warn == -1) {
1498 char *pbf = PerlEnv_getenv("PERL_BADFREE");
1499 bad_free_warn = (pbf) ? atoi(pbf) : 1;
1504 warn("%s free() ignored",
1505 ovp->ov_rmagic == RMAGIC - 1 ? "Duplicate" : "Bad");
1507 warn("%s", "Bad free() ignored");
1509 return; /* sanity */
1512 ASSERT(ovp->ov_rmagic == RMAGIC, "chunk's head overwrite");
1513 if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET) {
1515 MEM_SIZE nbytes = ovp->ov_size + 1;
1517 if ((i = nbytes & 3)) {
1520 ASSERT(*((char *)((caddr_t)ovp + nbytes - RSLOP + i))
1521 == RMAGIC_C, "chunk's tail overwrite");
1524 nbytes = (nbytes + 3) &~ 3;
1525 ASSERT(*(u_int *)((caddr_t)ovp + nbytes - RSLOP) == RMAGIC, "chunk's tail overwrite");
1527 ovp->ov_rmagic = RMAGIC - 1;
1529 ASSERT(OV_INDEX(ovp) < NBUCKETS, "chunk's head overwrite");
1530 size = OV_INDEX(ovp);
1533 ovp->ov_next = nextf[size];
1538 /* There is no need to do any locking in realloc (with an exception of
1539 trying to grow in place if we are at the end of the chain).
1540 If somebody calls us from a different thread with the same address,
1541 we are sole anyway. */
1544 Perl_realloc(void *mp, size_t nbytes)
1546 register MEM_SIZE onb;
1547 union overhead *ovp;
1550 register int bucket;
1551 int incr; /* 1 if does not fit, -1 if "easily" fits in a
1552 smaller bucket, otherwise 0. */
1553 char *cp = (char*)mp;
1555 #if defined(DEBUGGING) || !defined(PERL_CORE)
1556 MEM_SIZE size = nbytes;
1558 if ((long)nbytes < 0)
1559 croak("%s", "panic: realloc");
1562 BARK_64K_LIMIT("Reallocation",nbytes,size);
1564 return Perl_malloc(nbytes);
1566 ovp = (union overhead *)((caddr_t)cp
1567 - sizeof (union overhead) * CHUNK_SHIFT);
1568 bucket = OV_INDEX(ovp);
1570 #ifdef IGNORE_SMALL_BAD_FREE
1571 if ((bucket >= FIRST_BUCKET_WITH_CHECK)
1572 && (OV_MAGIC(ovp, bucket) != MAGIC))
1574 if (OV_MAGIC(ovp, bucket) != MAGIC)
1577 static int bad_free_warn = -1;
1578 if (bad_free_warn == -1) {
1580 char *pbf = PerlEnv_getenv("PERL_BADFREE");
1581 bad_free_warn = (pbf) ? atoi(pbf) : 1;
1586 warn("%srealloc() %signored",
1587 (ovp->ov_rmagic == RMAGIC - 1 ? "" : "Bad "),
1588 ovp->ov_rmagic == RMAGIC - 1 ? "of freed memory " : "");
1590 warn("%s", "Bad realloc() ignored");
1592 return Nullch; /* sanity */
1595 onb = BUCKET_SIZE_REAL(bucket);
1597 * avoid the copy if same size block.
1598 * We are not agressive with boundary cases. Note that it might
1599 * (for a small number of cases) give false negative if
1600 * both new size and old one are in the bucket for
1601 * FIRST_BIG_POW2, but the new one is near the lower end.
1603 * We do not try to go to 1.5 times smaller bucket so far.
1605 if (nbytes > onb) incr = 1;
1607 #ifdef DO_NOT_TRY_HARDER_WHEN_SHRINKING
1608 if ( /* This is a little bit pessimal if PACK_MALLOC: */
1609 nbytes > ( (onb >> 1) - M_OVERHEAD )
1610 # ifdef TWO_POT_OPTIMIZE
1611 || (bucket == FIRST_BIG_POW2 && nbytes >= LAST_SMALL_BOUND )
1614 #else /* !DO_NOT_TRY_HARDER_WHEN_SHRINKING */
1615 prev_bucket = ( (bucket > MAX_PACKED + 1)
1616 ? bucket - BUCKETS_PER_POW2
1618 if (nbytes > BUCKET_SIZE_REAL(prev_bucket))
1619 #endif /* !DO_NOT_TRY_HARDER_WHEN_SHRINKING */
1623 #ifdef STRESS_REALLOC
1630 * Record new allocated size of block and
1631 * bound space with magic numbers.
1633 if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET) {
1634 int i, nb = ovp->ov_size + 1;
1639 ASSERT(*((char *)((caddr_t)ovp + nb - RSLOP + i)) == RMAGIC_C, "chunk's tail overwrite");
1643 ASSERT(*(u_int *)((caddr_t)ovp + nb - RSLOP) == RMAGIC, "chunk's tail overwrite");
1645 * Convert amount of memory requested into
1646 * closest block size stored in hash buckets
1647 * which satisfies request. Account for
1648 * space used per block for accounting.
1650 nbytes += M_OVERHEAD;
1651 ovp->ov_size = nbytes - 1;
1652 if ((i = nbytes & 3)) {
1655 *((char *)((caddr_t)ovp + nbytes - RSLOP + i))
1658 nbytes = (nbytes + 3) &~ 3;
1659 *((u_int *)((caddr_t)ovp + nbytes - RSLOP)) = RMAGIC;
1663 DEBUG_m(PerlIO_printf(Perl_debug_log,
1664 "0x%lx: (%05lu) realloc %ld bytes inplace\n",
1665 (unsigned long)res,(unsigned long)(PL_an++),
1667 } else if (incr == 1 && (cp - M_OVERHEAD == last_op)
1668 && (onb > (1 << LOG_OF_MIN_ARENA))) {
1669 MEM_SIZE require, newarena = nbytes, pow;
1672 POW2_OPTIMIZE_ADJUST(newarena);
1673 newarena = newarena + M_OVERHEAD;
1674 /* newarena = (newarena + 3) &~ 3; */
1675 shiftr = (newarena - 1) >> LOG_OF_MIN_ARENA;
1676 pow = LOG_OF_MIN_ARENA + 1;
1677 /* apart from this loop, this is O(1) */
1678 while (shiftr >>= 1)
1680 newarena = (1 << pow) + POW2_OPTIMIZE_SURPLUS(pow * BUCKETS_PER_POW2);
1681 require = newarena - onb - M_OVERHEAD;
1684 if (cp - M_OVERHEAD == last_op /* We *still* are the last chunk */
1685 && getpages_adjacent(require)) {
1686 #ifdef DEBUGGING_MSTATS
1688 nmalloc[pow * BUCKETS_PER_POW2]++;
1690 *(cp - M_OVERHEAD) = pow * BUCKETS_PER_POW2; /* Fill index. */
1699 DEBUG_m(PerlIO_printf(Perl_debug_log,
1700 "0x%lx: (%05lu) realloc %ld bytes the hard way\n",
1701 (unsigned long)cp,(unsigned long)(PL_an++),
1703 if ((res = (char*)Perl_malloc(nbytes)) == NULL)
1705 if (cp != res) /* common optimization */
1706 Copy(cp, res, (MEM_SIZE)(nbytes<onb?nbytes:onb), char);
1709 return ((Malloc_t)res);
1713 * Search ``srchlen'' elements of each free list for a block whose
1714 * header starts at ``freep''. If srchlen is -1 search the whole list.
1715 * Return bucket number, or -1 if not found.
1718 findbucket(union overhead *freep, int srchlen)
1720 register union overhead *p;
1723 for (i = 0; i < NBUCKETS; i++) {
1725 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
1735 Perl_calloc(register size_t elements, register size_t size)
1737 long sz = elements * size;
1738 Malloc_t p = Perl_malloc(sz);
1741 memset((void*)p, 0, sz);
1747 Perl_strdup(const char *s)
1749 MEM_SIZE l = strlen(s);
1750 char *s1 = (char *)Perl_malloc(l);
1752 Copy(s, s1, (MEM_SIZE)l, char);
1758 Perl_putenv(char *a)
1760 /* Sometimes system's putenv conflicts with my_setenv() - this is system
1761 malloc vs Perl's free(). */
1768 while (*val && *val != '=')
1773 if (l < sizeof(buf))
1776 var = Perl_malloc(l + 1);
1777 Copy(a, var, l, char);
1787 Perl_malloced_size(void *p)
1789 union overhead *ovp = (union overhead *)
1790 ((caddr_t)p - sizeof (union overhead) * CHUNK_SHIFT);
1791 int bucket = OV_INDEX(ovp);
1793 /* The caller wants to have a complete control over the chunk,
1794 disable the memory checking inside the chunk. */
1795 if (bucket <= MAX_SHORT_BUCKET) {
1796 MEM_SIZE size = BUCKET_SIZE_REAL(bucket);
1797 ovp->ov_size = size + M_OVERHEAD - 1;
1798 *((u_int *)((caddr_t)ovp + size + M_OVERHEAD - RSLOP)) = RMAGIC;
1801 return BUCKET_SIZE_REAL(bucket);
1804 # ifdef BUCKETS_ROOT2
1805 # define MIN_EVEN_REPORT 6
1807 # define MIN_EVEN_REPORT MIN_BUCKET
1810 * mstats - print out statistics about malloc
1812 * Prints two lines of numbers, one showing the length of the free list
1813 * for each size category, the second showing the number of mallocs -
1814 * frees for each size category.
1817 Perl_dump_mstats(pTHX_ char *s)
1819 #ifdef DEBUGGING_MSTATS
1821 register union overhead *p;
1822 int topbucket=0, topbucket_ev=0, topbucket_odd=0, totfree=0, total=0;
1823 u_int nfree[NBUCKETS];
1824 int total_chain = 0;
1825 struct chunk_chain_s* nextchain;
1828 for (i = MIN_BUCKET ; i < NBUCKETS; i++) {
1829 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
1832 totfree += nfree[i] * BUCKET_SIZE_REAL(i);
1833 total += nmalloc[i] * BUCKET_SIZE_REAL(i);
1835 i % 2 ? (topbucket_odd = i) : (topbucket_ev = i);
1839 nextchain = chunk_chain;
1841 total_chain += nextchain->size;
1842 nextchain = nextchain->next;
1846 PerlIO_printf(Perl_error_log,
1847 "Memory allocation statistics %s (buckets %ld(%ld)..%ld(%ld)\n",
1849 (long)BUCKET_SIZE_REAL(MIN_BUCKET),
1850 (long)BUCKET_SIZE(MIN_BUCKET),
1851 (long)BUCKET_SIZE_REAL(topbucket), (long)BUCKET_SIZE(topbucket));
1852 PerlIO_printf(Perl_error_log, "%8d free:", totfree);
1853 for (i = MIN_EVEN_REPORT; i <= topbucket; i += BUCKETS_PER_POW2) {
1854 PerlIO_printf(Perl_error_log,
1855 ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1857 : ((i < 12*BUCKETS_PER_POW2) ? " %3d" : " %d")),
1860 #ifdef BUCKETS_ROOT2
1861 PerlIO_printf(Perl_error_log, "\n\t ");
1862 for (i = MIN_BUCKET + 1; i <= topbucket_odd; i += BUCKETS_PER_POW2) {
1863 PerlIO_printf(Perl_error_log,
1864 ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1866 : ((i < 12*BUCKETS_PER_POW2) ? " %3d" : " %d")),
1870 PerlIO_printf(Perl_error_log, "\n%8d used:", total - totfree);
1871 for (i = MIN_EVEN_REPORT; i <= topbucket; i += BUCKETS_PER_POW2) {
1872 PerlIO_printf(Perl_error_log,
1873 ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1875 : ((i < 12*BUCKETS_PER_POW2) ? " %3d" : " %d")),
1876 nmalloc[i] - nfree[i]);
1878 #ifdef BUCKETS_ROOT2
1879 PerlIO_printf(Perl_error_log, "\n\t ");
1880 for (i = MIN_BUCKET + 1; i <= topbucket_odd; i += BUCKETS_PER_POW2) {
1881 PerlIO_printf(Perl_error_log,
1882 ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1884 : ((i < 12*BUCKETS_PER_POW2) ? " %3d" : " %d")),
1885 nmalloc[i] - nfree[i]);
1888 PerlIO_printf(Perl_error_log, "\nTotal sbrk(): %d/%d:%d. Odd ends: pad+heads+chain+tail: %d+%d+%d+%d.\n",
1889 goodsbrk + sbrk_slack, sbrks, sbrk_good, sbrk_slack,
1890 start_slack, total_chain, sbrked_remains);
1891 #endif /* DEBUGGING_MSTATS */
1895 #ifdef USE_PERL_SBRK
1897 # if defined(__MACHTEN_PPC__) || defined(NeXT) || defined(__NeXT__)
1898 # define PERL_SBRK_VIA_MALLOC
1900 * MachTen's malloc() returns a buffer aligned on a two-byte boundary.
1901 * While this is adequate, it may slow down access to longer data
1902 * types by forcing multiple memory accesses. It also causes
1903 * complaints when RCHECK is in force. So we allocate six bytes
1904 * more than we need to, and return an address rounded up to an
1905 * eight-byte boundary.
1907 * 980701 Dominic Dunlop <domo@computer.org>
1909 # define SYSTEM_ALLOC_ALIGNMENT 2
1912 # ifdef PERL_SBRK_VIA_MALLOC
1914 /* it may seem schizophrenic to use perl's malloc and let it call system */
1915 /* malloc, the reason for that is only the 3.2 version of the OS that had */
1916 /* frequent core dumps within nxzonefreenolock. This sbrk routine put an */
1917 /* end to the cores */
1919 # ifndef SYSTEM_ALLOC
1920 # define SYSTEM_ALLOC(a) malloc(a)
1922 # ifndef SYSTEM_ALLOC_ALIGNMENT
1923 # define SYSTEM_ALLOC_ALIGNMENT MEM_ALIGNBYTES
1926 # endif /* PERL_SBRK_VIA_MALLOC */
1928 static IV Perl_sbrk_oldchunk;
1929 static long Perl_sbrk_oldsize;
1931 # define PERLSBRK_32_K (1<<15)
1932 # define PERLSBRK_64_K (1<<16)
1940 if (!size) return 0;
1942 reqsize = size; /* just for the DEBUG_m statement */
1945 size = (size + 0x7ff) & ~0x7ff;
1947 if (size <= Perl_sbrk_oldsize) {
1948 got = Perl_sbrk_oldchunk;
1949 Perl_sbrk_oldchunk += size;
1950 Perl_sbrk_oldsize -= size;
1952 if (size >= PERLSBRK_32_K) {
1955 size = PERLSBRK_64_K;
1958 # if NEEDED_ALIGNMENT > SYSTEM_ALLOC_ALIGNMENT
1959 size += NEEDED_ALIGNMENT - SYSTEM_ALLOC_ALIGNMENT;
1961 got = (IV)SYSTEM_ALLOC(size);
1962 # if NEEDED_ALIGNMENT > SYSTEM_ALLOC_ALIGNMENT
1963 got = (got + NEEDED_ALIGNMENT - 1) & ~(NEEDED_ALIGNMENT - 1);
1966 /* Chunk is small, register the rest for future allocs. */
1967 Perl_sbrk_oldchunk = got + reqsize;
1968 Perl_sbrk_oldsize = size - reqsize;
1972 DEBUG_m(PerlIO_printf(Perl_debug_log, "sbrk malloc size %ld (reqsize %ld), left size %ld, give addr 0x%lx\n",
1973 size, reqsize, Perl_sbrk_oldsize, got));
1978 #endif /* ! defined USE_PERL_SBRK */