Integrate from ansi branch to mainline.
[p5sagit/p5-mst-13.2.git] / malloc.c
1 /*    malloc.c
2  *
3  */
4
5 #define EMBEDMYMALLOC
6
7 #if defined(PERL_CORE) && !defined(DEBUGGING_MSTATS)
8 #  define DEBUGGING_MSTATS
9 #endif 
10
11 #ifndef lint
12 #  if defined(DEBUGGING) && !defined(NO_RCHECK)
13 #    define RCHECK
14 #  endif
15 /*
16  * malloc.c (Caltech) 2/21/82
17  * Chris Kingsley, kingsley@cit-20.
18  *
19  * This is a very fast storage allocator.  It allocates blocks of a small 
20  * number of different sizes, and keeps free lists of each size.  Blocks that
21  * don't exactly fit are passed up to the next larger size.  In this 
22  * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long.
23  * If PACK_MALLOC is defined, small blocks are 2^n bytes long.
24  * This is designed for use in a program that uses vast quantities of memory,
25  * but bombs when it runs out. 
26  */
27
28 #include "EXTERN.h"
29 #include "perl.h"
30
31 #ifdef DEBUGGING
32 #undef DEBUG_m
33 #define DEBUG_m(a)  if (debug & 128)   a
34 #endif
35
36 /* I don't much care whether these are defined in sys/types.h--LAW */
37
38 #define u_char unsigned char
39 #define u_int unsigned int
40 #define u_short unsigned short
41
42 /* 286 and atarist like big chunks, which gives too much overhead. */
43 #if (defined(RCHECK) || defined(I286) || defined(atarist)) && defined(PACK_MALLOC)
44 #undef PACK_MALLOC
45 #endif 
46
47
48 /*
49  * The description below is applicable if PACK_MALLOC is not defined.
50  *
51  * The overhead on a block is at least 4 bytes.  When free, this space
52  * contains a pointer to the next free block, and the bottom two bits must
53  * be zero.  When in use, the first byte is set to MAGIC, and the second
54  * byte is the size index.  The remaining bytes are for alignment.
55  * If range checking is enabled and the size of the block fits
56  * in two bytes, then the top two bytes hold the size of the requested block
57  * plus the range checking words, and the header word MINUS ONE.
58  */
59 union   overhead {
60         union   overhead *ov_next;      /* when free */
61 #if MEM_ALIGNBYTES > 4
62         double  strut;                  /* alignment problems */
63 #endif
64         struct {
65                 u_char  ovu_magic;      /* magic number */
66                 u_char  ovu_index;      /* bucket # */
67 #ifdef RCHECK
68                 u_short ovu_size;       /* actual block size */
69                 u_int   ovu_rmagic;     /* range magic number */
70 #endif
71         } ovu;
72 #define ov_magic        ovu.ovu_magic
73 #define ov_index        ovu.ovu_index
74 #define ov_size         ovu.ovu_size
75 #define ov_rmagic       ovu.ovu_rmagic
76 };
77
78 #ifdef DEBUGGING
79 static void botch _((char *s));
80 #endif
81 static void morecore _((int bucket));
82 static int findbucket _((union overhead *freep, int srchlen));
83
84 #define MAGIC           0xff            /* magic # on accounting info */
85 #define RMAGIC          0x55555555      /* magic # on range info */
86 #ifdef RCHECK
87 #  define       RSLOP           sizeof (u_int)
88 #  ifdef TWO_POT_OPTIMIZE
89 #    define MAX_SHORT_BUCKET 12
90 #  else
91 #    define MAX_SHORT_BUCKET 13
92 #  endif 
93 #else
94 #  define       RSLOP           0
95 #endif
96
97 #ifdef PACK_MALLOC
98 /*
99  * In this case it is assumed that if we do sbrk() in 2K units, we
100  * will get 2K aligned blocks. The bucket number of the given subblock is
101  * on the boundary of 2K block which contains the subblock.
102  * Several following bytes contain the magic numbers for the subblocks
103  * in the block.
104  *
105  * Sizes of chunks are powers of 2 for chunks in buckets <=
106  * MAX_PACKED, after this they are (2^n - sizeof(union overhead)) (to
107  * get alignment right).
108  *
109  * We suppose that starts of all the chunks in a 2K block are in
110  * different 2^n-byte-long chunks.  If the top of the last chunk is
111  * aligned on a boundary of 2K block, this means that
112  * sizeof(union overhead)*"number of chunks" < 2^n, or
113  * sizeof(union overhead)*2K < 4^n, or n > 6 + log2(sizeof()/2)/2, if a
114  * chunk of size 2^n - overhead is used. Since this rules out n = 7
115  * for 8 byte alignment, we specialcase allocation of the first of 16
116  * 128-byte-long chunks.
117  *
118  * Note that with the above assumption we automatically have enough
119  * place for MAGIC at the start of 2K block.  Note also that we
120  * overlay union overhead over the chunk, thus the start of the chunk
121  * is immediately overwritten after freeing.
122  */
123 #  define MAX_PACKED 6
124 #  define MAX_2_POT_ALGO ((1<<(MAX_PACKED + 1)) - M_OVERHEAD)
125 #  define TWOK_MASK ((1<<11) - 1)
126 #  define TWOK_MASKED(x) ((u_int)(x) & ~TWOK_MASK)
127 #  define TWOK_SHIFT(x) ((u_int)(x) & TWOK_MASK)
128 #  define OV_INDEXp(block) ((u_char*)(TWOK_MASKED(block)))
129 #  define OV_INDEX(block) (*OV_INDEXp(block))
130 #  define OV_MAGIC(block,bucket) (*(OV_INDEXp(block) +                  \
131                                     (TWOK_SHIFT(block)>>(bucket + 3)) + \
132                                     (bucket > MAX_NONSHIFT ? 1 : 0)))
133 #  define CHUNK_SHIFT 0
134
135 static u_char n_blks[11 - 3]     = {224, 120, 62, 31, 16, 8, 4, 2};
136 static u_short blk_shift[11 - 3] = {256, 128, 64, 32, 
137                                     16*sizeof(union overhead), 
138                                     8*sizeof(union overhead), 
139                                     4*sizeof(union overhead), 
140                                     2*sizeof(union overhead), 
141 #  define MAX_NONSHIFT 2        /* Shift 64 greater than chunk 32. */
142 };
143
144 #else  /* !PACK_MALLOC */
145
146 #  define OV_MAGIC(block,bucket) (block)->ov_magic
147 #  define OV_INDEX(block) (block)->ov_index
148 #  define CHUNK_SHIFT 1
149 #endif /* !PACK_MALLOC */
150
151 #  define M_OVERHEAD (sizeof(union overhead) + RSLOP)
152
153 /*
154  * Big allocations are often of the size 2^n bytes. To make them a
155  * little bit better, make blocks of size 2^n+pagesize for big n.
156  */
157
158 #ifdef TWO_POT_OPTIMIZE
159
160 #  ifndef PERL_PAGESIZE
161 #    define PERL_PAGESIZE 4096
162 #  endif 
163 #  ifndef FIRST_BIG_TWO_POT
164 #    define FIRST_BIG_TWO_POT 14        /* 16K */
165 #  endif
166 #  define FIRST_BIG_BLOCK (1<<FIRST_BIG_TWO_POT) /* 16K */
167 /* If this value or more, check against bigger blocks. */
168 #  define FIRST_BIG_BOUND (FIRST_BIG_BLOCK - M_OVERHEAD)
169 /* If less than this value, goes into 2^n-overhead-block. */
170 #  define LAST_SMALL_BOUND ((FIRST_BIG_BLOCK>>1) - M_OVERHEAD)
171
172 #endif /* TWO_POT_OPTIMIZE */
173
174 #if defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)
175
176 #ifndef BIG_SIZE
177 #  define BIG_SIZE (1<<16)              /* 64K */
178 #endif 
179
180 static char *emergency_buffer;
181 static MEM_SIZE emergency_buffer_size;
182
183 static char *
184 emergency_sbrk(size)
185     MEM_SIZE size;
186 {
187     if (size >= BIG_SIZE) {
188         /* Give the possibility to recover: */
189         die("Out of memory during request for %i bytes", size);
190         /* croak may eat too much memory. */
191     }
192
193     if (!emergency_buffer) {            
194         /* First offense, give a possibility to recover by dieing. */
195         /* No malloc involved here: */
196         GV **gvp = (GV**)hv_fetch(defstash, "^M", 2, 0);
197         SV *sv;
198         char *pv;
199
200         if (!gvp) gvp = (GV**)hv_fetch(defstash, "\015", 1, 0);
201         if (!gvp || !(sv = GvSV(*gvp)) || !SvPOK(sv) 
202             || (SvLEN(sv) < (1<<11) - M_OVERHEAD)) 
203             return (char *)-1;          /* Now die die die... */
204
205         /* Got it, now detach SvPV: */
206         pv = SvPV(sv, na);
207         /* Check alignment: */
208         if (((u_int)(pv - M_OVERHEAD)) & ((1<<11) - 1)) {
209             PerlIO_puts(PerlIO_stderr(),"Bad alignment of $^M!\n");
210             return (char *)-1;          /* die die die */
211         }
212
213         emergency_buffer = pv - M_OVERHEAD;
214         emergency_buffer_size = SvLEN(sv) + M_OVERHEAD;
215         SvPOK_off(sv);
216         SvREADONLY_on(sv);
217         die("Out of memory!");          /* croak may eat too much memory. */
218     }
219     else if (emergency_buffer_size >= size) {
220         emergency_buffer_size -= size;
221         return emergency_buffer + emergency_buffer_size;
222     }
223     
224     return (char *)-1;                  /* poor guy... */
225 }
226
227 #else /* !(defined(TWO_POT_OPTIMIZE) && defined(PERL_CORE)) */
228 #  define emergency_sbrk(size)  -1
229 #endif /* !(defined(TWO_POT_OPTIMIZE) && defined(PERL_CORE)) */
230
231 /*
232  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
233  * smallest allocatable block is 8 bytes.  The overhead information
234  * precedes the data area returned to the user.
235  */
236 #define NBUCKETS 30
237 static  union overhead *nextf[NBUCKETS];
238
239 #ifdef USE_PERL_SBRK
240 #define sbrk(a) Perl_sbrk(a)
241 char *  Perl_sbrk _((int size));
242 #else 
243 #ifdef DONT_DECLARE_STD
244 #ifdef I_UNISTD
245 #include <unistd.h>
246 #endif
247 #else
248 extern  char *sbrk(int);
249 #endif
250 #endif
251
252 #ifdef DEBUGGING_MSTATS
253 /*
254  * nmalloc[i] is the difference between the number of mallocs and frees
255  * for a given block size.
256  */
257 static  u_int nmalloc[NBUCKETS];
258 static  u_int goodsbrk;
259 static  u_int sbrk_slack;
260 static  u_int start_slack;
261 #endif
262
263 #ifdef DEBUGGING
264 #define ASSERT(p)   if (!(p)) botch(STRINGIFY(p));  else
265 static void
266 botch(char *s)
267 {
268         PerlIO_printf(PerlIO_stderr(), "assertion botched: %s\n", s);
269         abort();
270 }
271 #else
272 #define ASSERT(p)
273 #endif
274
275 Malloc_t
276 malloc(register size_t nbytes)
277 {
278         register union overhead *p;
279         register int bucket = 0;
280         register MEM_SIZE shiftr;
281
282 #if defined(DEBUGGING) || defined(RCHECK)
283         MEM_SIZE size = nbytes;
284 #endif
285
286 #ifdef PERL_CORE
287 #ifdef HAS_64K_LIMIT
288         if (nbytes > 0xffff) {
289                 PerlIO_printf(PerlIO_stderr(),
290                               "Allocation too large: %lx\n", (long)nbytes);
291                 my_exit(1);
292         }
293 #endif /* HAS_64K_LIMIT */
294 #ifdef DEBUGGING
295         if ((long)nbytes < 0)
296                 croak("panic: malloc");
297 #endif
298 #endif /* PERL_CORE */
299
300         MUTEX_LOCK(&malloc_mutex);
301         /*
302          * Convert amount of memory requested into
303          * closest block size stored in hash buckets
304          * which satisfies request.  Account for
305          * space used per block for accounting.
306          */
307 #ifdef PACK_MALLOC
308         if (nbytes == 0)
309             nbytes = 1;
310         else if (nbytes > MAX_2_POT_ALGO)
311 #endif
312         {
313 #ifdef TWO_POT_OPTIMIZE
314                 if (nbytes >= FIRST_BIG_BOUND)
315                         nbytes -= PERL_PAGESIZE;
316 #endif 
317                 nbytes += M_OVERHEAD;
318                 nbytes = (nbytes + 3) &~ 3; 
319         }
320         shiftr = (nbytes - 1) >> 2;
321         /* apart from this loop, this is O(1) */
322         while (shiftr >>= 1)
323                 bucket++;
324         /*
325          * If nothing in hash bucket right now,
326          * request more memory from the system.
327          */
328         if (nextf[bucket] == NULL)    
329                 morecore(bucket);
330         if ((p = (union overhead *)nextf[bucket]) == NULL) {
331                 MUTEX_UNLOCK(&malloc_mutex);
332 #ifdef PERL_CORE
333                 if (!nomemok) {
334                     PerlIO_puts(PerlIO_stderr(),"Out of memory!\n");
335                     my_exit(1);
336                 }
337 #else
338                 return (NULL);
339 #endif
340         }
341
342 #ifdef PERL_CORE
343     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05lu) malloc %ld bytes\n",
344         (unsigned long)(p+1),(unsigned long)(an++),(long)size));
345 #endif /* PERL_CORE */
346
347         /* remove from linked list */
348 #ifdef RCHECK
349         if (*((int*)p) & (sizeof(union overhead) - 1))
350             PerlIO_printf(PerlIO_stderr(), "Corrupt malloc ptr 0x%lx at 0x%lx\n",
351                 (unsigned long)*((int*)p),(unsigned long)p);
352 #endif
353         nextf[bucket] = p->ov_next;
354         OV_MAGIC(p, bucket) = MAGIC;
355 #ifndef PACK_MALLOC
356         OV_INDEX(p) = bucket;
357 #endif
358 #ifdef RCHECK
359         /*
360          * Record allocated size of block and
361          * bound space with magic numbers.
362          */
363         nbytes = (size + M_OVERHEAD + 3) &~ 3; 
364         if (nbytes <= 0x10000)
365                 p->ov_size = nbytes - 1;
366         p->ov_rmagic = RMAGIC;
367         *((u_int *)((caddr_t)p + nbytes - RSLOP)) = RMAGIC;
368 #endif
369         MUTEX_UNLOCK(&malloc_mutex);
370         return ((Malloc_t)(p + CHUNK_SHIFT));
371 }
372
373 /*
374  * Allocate more memory to the indicated bucket.
375  */
376 static void
377 morecore(register int bucket)
378 {
379         register union overhead *ovp;
380         register int rnu;       /* 2^rnu bytes will be requested */
381         register int nblks;     /* become nblks blocks of the desired size */
382         register MEM_SIZE siz, needed;
383         int slack = 0;
384
385         if (nextf[bucket])
386                 return;
387         if (bucket == (sizeof(MEM_SIZE)*8 - 3)) {
388             croak("Allocation too large");
389         }
390         /*
391          * Insure memory is allocated
392          * on a page boundary.  Should
393          * make getpageize call?
394          */
395 #ifndef atarist /* on the atari we dont have to worry about this */
396         ovp = (union overhead *)sbrk(0);
397 #  ifndef I286
398         if ((UV)ovp & (0x7FF >> CHUNK_SHIFT)) {
399             slack = (0x800 >> CHUNK_SHIFT) - ((UV)ovp & (0x7FF >> CHUNK_SHIFT));
400             (void)sbrk(slack);
401 #    if defined(DEBUGGING_MSTATS)
402             sbrk_slack += slack;
403 #    endif
404         }
405 #  else
406         /* The sbrk(0) call on the I286 always returns the next segment */
407 #  endif
408 #endif /* atarist */
409
410 #if !(defined(I286) || defined(atarist))
411         /* take 2k unless the block is bigger than that */
412         rnu = (bucket <= 8) ? 11 : bucket + 3;
413 #else
414         /* take 16k unless the block is bigger than that 
415            (80286s like large segments!), probably good on the atari too */
416         rnu = (bucket <= 11) ? 14 : bucket + 3;
417 #endif
418         nblks = 1 << (rnu - (bucket + 3));  /* how many blocks to get */
419         needed = (MEM_SIZE)1 << rnu;
420 #ifdef TWO_POT_OPTIMIZE
421         needed += (bucket >= (FIRST_BIG_TWO_POT - 3) ? PERL_PAGESIZE : 0);
422 #endif 
423         ovp = (union overhead *)sbrk(needed);
424         /* no more room! */
425         if (ovp == (union overhead *)-1) {
426             ovp = (union overhead *)emergency_sbrk(needed);
427             if (ovp == (union overhead *)-1)
428                 return;
429         }
430 #ifdef DEBUGGING_MSTATS
431         goodsbrk += needed;
432 #endif  
433         /*
434          * Round up to minimum allocation size boundary
435          * and deduct from block count to reflect.
436          */
437 #ifndef I286
438 #  ifdef PACK_MALLOC
439         if ((UV)ovp & 0x7FF)
440                 croak("panic: Off-page sbrk");
441 #  endif
442         if ((UV)ovp & 7) {
443                 ovp = (union overhead *)(((UV)ovp + 8) & ~7);
444                 nblks--;
445         }
446 #else
447         /* Again, this should always be ok on an 80286 */
448 #endif
449         /*
450          * Add new memory allocated to that on
451          * free list for this hash bucket.
452          */
453         siz = 1 << (bucket + 3);
454 #ifdef PACK_MALLOC
455         *(u_char*)ovp = bucket; /* Fill index. */
456         if (bucket <= MAX_PACKED - 3) {
457             ovp = (union overhead *) ((char*)ovp + blk_shift[bucket]);
458             nblks = n_blks[bucket];
459 #  ifdef DEBUGGING_MSTATS
460             start_slack += blk_shift[bucket];
461 #  endif
462         } else if (bucket <= 11 - 1 - 3) {
463             ovp = (union overhead *) ((char*)ovp + blk_shift[bucket]);
464             /* nblks = n_blks[bucket]; */
465             siz -= sizeof(union overhead);
466         } else ovp++;           /* One chunk per block. */
467 #endif /* !PACK_MALLOC */
468         nextf[bucket] = ovp;
469 #ifdef DEBUGGING_MSTATS
470         nmalloc[bucket] += nblks;
471 #endif 
472         while (--nblks > 0) {
473                 ovp->ov_next = (union overhead *)((caddr_t)ovp + siz);
474                 ovp = (union overhead *)((caddr_t)ovp + siz);
475         }
476         /* Not all sbrks return zeroed memory.*/
477         ovp->ov_next = (union overhead *)NULL;
478 #ifdef PACK_MALLOC
479         if (bucket == 7 - 3) {  /* Special case, explanation is above. */
480             union overhead *n_op = nextf[7 - 3]->ov_next;
481             nextf[7 - 3] = (union overhead *)((caddr_t)nextf[7 - 3] 
482                                               - sizeof(union overhead));
483             nextf[7 - 3]->ov_next = n_op;
484         }
485 #endif /* !PACK_MALLOC */
486 }
487
488 Free_t
489 free(void *mp)
490 {   
491         register MEM_SIZE size;
492         register union overhead *ovp;
493         char *cp = (char*)mp;
494 #ifdef PACK_MALLOC
495         u_char bucket;
496 #endif 
497
498 #ifdef PERL_CORE
499     DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05lu) free\n",(unsigned long)cp,(unsigned long)(an++)));
500 #endif /* PERL_CORE */
501
502         if (cp == NULL)
503                 return;
504         ovp = (union overhead *)((caddr_t)cp 
505                                  - sizeof (union overhead) * CHUNK_SHIFT);
506 #ifdef PACK_MALLOC
507         bucket = OV_INDEX(ovp);
508 #endif 
509         if (OV_MAGIC(ovp, bucket) != MAGIC) {
510                 static int bad_free_warn = -1;
511                 if (bad_free_warn == -1) {
512                     char *pbf = getenv("PERL_BADFREE");
513                     bad_free_warn = (pbf) ? atoi(pbf) : 1;
514                 }
515                 if (!bad_free_warn)
516                     return;
517 #ifdef RCHECK
518                 warn("%s free() ignored",
519                     ovp->ov_rmagic == RMAGIC - 1 ? "Duplicate" : "Bad");
520 #else
521                 warn("Bad free() ignored");
522 #endif
523                 return;                         /* sanity */
524         }
525         MUTEX_LOCK(&malloc_mutex);
526 #ifdef RCHECK
527         ASSERT(ovp->ov_rmagic == RMAGIC);
528         if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET)
529                 ASSERT(*(u_int *)((caddr_t)ovp + ovp->ov_size + 1 - RSLOP) == RMAGIC);
530         ovp->ov_rmagic = RMAGIC - 1;
531 #endif
532         ASSERT(OV_INDEX(ovp) < NBUCKETS);
533         size = OV_INDEX(ovp);
534         ovp->ov_next = nextf[size];
535         nextf[size] = ovp;
536         MUTEX_UNLOCK(&malloc_mutex);
537 }
538
539 /*
540  * When a program attempts "storage compaction" as mentioned in the
541  * old malloc man page, it realloc's an already freed block.  Usually
542  * this is the last block it freed; occasionally it might be farther
543  * back.  We have to search all the free lists for the block in order
544  * to determine its bucket: 1st we make one pass thru the lists
545  * checking only the first block in each; if that fails we search
546  * ``reall_srchlen'' blocks in each list for a match (the variable
547  * is extern so the caller can modify it).  If that fails we just copy
548  * however many bytes was given to realloc() and hope it's not huge.
549  */
550 int reall_srchlen = 4;  /* 4 should be plenty, -1 =>'s whole list */
551
552 Malloc_t
553 realloc(void *mp, size_t nbytes)
554 {   
555         register MEM_SIZE onb;
556         union overhead *ovp;
557         char *res;
558         register int i;
559         int was_alloced = 0;
560         char *cp = (char*)mp;
561
562 #ifdef DEBUGGING
563         MEM_SIZE size = nbytes;
564 #endif
565
566 #ifdef PERL_CORE
567 #ifdef HAS_64K_LIMIT
568         if (nbytes > 0xffff) {
569                 PerlIO_printf(PerlIO_stderr(),
570                               "Reallocation too large: %lx\n", size);
571                 my_exit(1);
572         }
573 #endif /* HAS_64K_LIMIT */
574         if (!cp)
575                 return malloc(nbytes);
576 #ifdef DEBUGGING
577         if ((long)nbytes < 0)
578                 croak("panic: realloc");
579 #endif
580 #endif /* PERL_CORE */
581
582         MUTEX_LOCK(&malloc_mutex);
583         ovp = (union overhead *)((caddr_t)cp 
584                                  - sizeof (union overhead) * CHUNK_SHIFT);
585         i = OV_INDEX(ovp);
586         if (OV_MAGIC(ovp, i) == MAGIC) {
587                 was_alloced = 1;
588         } else {
589                 /*
590                  * Already free, doing "compaction".
591                  *
592                  * Search for the old block of memory on the
593                  * free list.  First, check the most common
594                  * case (last element free'd), then (this failing)
595                  * the last ``reall_srchlen'' items free'd.
596                  * If all lookups fail, then assume the size of
597                  * the memory block being realloc'd is the
598                  * smallest possible.
599                  */
600                 if ((i = findbucket(ovp, 1)) < 0 &&
601                     (i = findbucket(ovp, reall_srchlen)) < 0)
602                         i = 0;
603         }
604         onb = (1L << (i + 3)) - 
605 #ifdef PACK_MALLOC
606             (i <= (MAX_PACKED - 3) ? 0 : M_OVERHEAD)
607 #else
608             M_OVERHEAD
609 #endif
610 #ifdef TWO_POT_OPTIMIZE
611             + (i >= (FIRST_BIG_TWO_POT - 3) ? PERL_PAGESIZE : 0)
612 #endif
613             ;
614         /* 
615          *  avoid the copy if same size block.
616          *  We are not agressive with boundary cases. Note that it is
617          *  possible for small number of cases give false negative if
618          *  both new size and old one are in the bucket for
619          *  FIRST_BIG_TWO_POT, but the new one is near the lower end.
620          */
621         if (was_alloced &&
622             nbytes <= onb && (nbytes > ( (onb >> 1) - M_OVERHEAD )
623 #ifdef TWO_POT_OPTIMIZE
624                               || (i == (FIRST_BIG_TWO_POT - 3) 
625                                   && nbytes >= LAST_SMALL_BOUND )
626 #endif  
627                 )) {
628 #ifdef RCHECK
629                 /*
630                  * Record new allocated size of block and
631                  * bound space with magic numbers.
632                  */
633                 if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET) {
634                         /*
635                          * Convert amount of memory requested into
636                          * closest block size stored in hash buckets
637                          * which satisfies request.  Account for
638                          * space used per block for accounting.
639                          */
640                         nbytes += M_OVERHEAD;
641                         nbytes = (nbytes + 3) &~ 3; 
642                         ovp->ov_size = nbytes - 1;
643                         *((u_int *)((caddr_t)ovp + nbytes - RSLOP)) = RMAGIC;
644                 }
645 #endif
646                 res = cp;
647                 MUTEX_UNLOCK(&malloc_mutex);
648         }
649         else {
650                 MUTEX_UNLOCK(&malloc_mutex);
651                 if ((res = (char*)malloc(nbytes)) == NULL)
652                         return (NULL);
653                 if (cp != res)                  /* common optimization */
654                         Copy(cp, res, (MEM_SIZE)(nbytes<onb?nbytes:onb), char);
655                 if (was_alloced)
656                         free(cp);
657         }
658
659 #ifdef PERL_CORE
660 #ifdef DEBUGGING
661     if (debug & 128) {
662         PerlIO_printf(Perl_debug_log, "0x%lx: (%05lu) rfree\n",(unsigned long)res,(unsigned long)(an++));
663         PerlIO_printf(Perl_debug_log, "0x%lx: (%05lu) realloc %ld bytes\n",
664             (unsigned long)res,(unsigned long)(an++),(long)size);
665     }
666 #endif
667 #endif /* PERL_CORE */
668         return ((Malloc_t)res);
669 }
670
671 /*
672  * Search ``srchlen'' elements of each free list for a block whose
673  * header starts at ``freep''.  If srchlen is -1 search the whole list.
674  * Return bucket number, or -1 if not found.
675  */
676 static int
677 findbucket(union overhead *freep, int srchlen)
678 {
679         register union overhead *p;
680         register int i, j;
681
682         for (i = 0; i < NBUCKETS; i++) {
683                 j = 0;
684                 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
685                         if (p == freep)
686                                 return (i);
687                         j++;
688                 }
689         }
690         return (-1);
691 }
692
693 Malloc_t
694 calloc(register size_t elements, register size_t size)
695 {
696     long sz = elements * size;
697     Malloc_t p = malloc(sz);
698
699     if (p) {
700         memset((void*)p, 0, sz);
701     }
702     return p;
703 }
704
705 #ifdef DEBUGGING_MSTATS
706 /*
707  * mstats - print out statistics about malloc
708  * 
709  * Prints two lines of numbers, one showing the length of the free list
710  * for each size category, the second showing the number of mallocs -
711  * frees for each size category.
712  */
713 void
714 dump_mstats(char *s)
715 {
716         register int i, j;
717         register union overhead *p;
718         int topbucket=0, totfree=0, total=0;
719         u_int nfree[NBUCKETS];
720
721         for (i=0; i < NBUCKETS; i++) {
722                 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
723                         ;
724                 nfree[i] = j;
725                 totfree += nfree[i]   * (1 << (i + 3));
726                 total += nmalloc[i] * (1 << (i + 3));
727                 if (nmalloc[i])
728                         topbucket = i;
729         }
730         if (s)
731                 PerlIO_printf(PerlIO_stderr(), "Memory allocation statistics %s (buckets 8..%d)\n",
732                         s, (1 << (topbucket + 3)) );
733         PerlIO_printf(PerlIO_stderr(), "%8d free:", totfree);
734         for (i=0; i <= topbucket; i++) {
735                 PerlIO_printf(PerlIO_stderr(), (i<5 || i==7)?" %5d": (i<9)?" %3d":" %d", nfree[i]);
736         }
737         PerlIO_printf(PerlIO_stderr(), "\n%8d used:", total - totfree);
738         for (i=0; i <= topbucket; i++) {
739                 PerlIO_printf(PerlIO_stderr(), (i<5 || i==7)?" %5d": (i<9)?" %3d":" %d", nmalloc[i] - nfree[i]);
740         }
741         PerlIO_printf(PerlIO_stderr(), "\nTotal sbrk(): %8d. Odd ends: sbrk(): %7d, malloc(): %7d bytes.\n",
742                       goodsbrk + sbrk_slack, sbrk_slack, start_slack);
743 }
744 #else
745 void
746 dump_mstats(char *s)
747 {
748 }
749 #endif
750 #endif /* lint */
751
752
753 #ifdef USE_PERL_SBRK
754
755 #   ifdef NeXT
756 #      define PERL_SBRK_VIA_MALLOC
757 #   endif
758
759 #   ifdef PERL_SBRK_VIA_MALLOC
760 #      if defined(HIDEMYMALLOC) || defined(EMBEDMYMALLOC)
761 #         undef malloc
762 #      else
763 #         include "Error: -DPERL_SBRK_VIA_MALLOC needs -D(HIDE|EMBED)MYMALLOC"
764 #      endif
765
766 /* it may seem schizophrenic to use perl's malloc and let it call system */
767 /* malloc, the reason for that is only the 3.2 version of the OS that had */
768 /* frequent core dumps within nxzonefreenolock. This sbrk routine put an */
769 /* end to the cores */
770
771 #      define SYSTEM_ALLOC(a) malloc(a)
772
773 #   endif  /* PERL_SBRK_VIA_MALLOC */
774
775 static IV Perl_sbrk_oldchunk;
776 static long Perl_sbrk_oldsize;
777
778 #   define PERLSBRK_32_K (1<<15)
779 #   define PERLSBRK_64_K (1<<16)
780
781 char *
782 Perl_sbrk(size)
783 int size;
784 {
785     IV got;
786     int small, reqsize;
787
788     if (!size) return 0;
789 #ifdef PERL_CORE
790     reqsize = size; /* just for the DEBUG_m statement */
791 #endif
792 #ifdef PACK_MALLOC
793     size = (size + 0x7ff) & ~0x7ff;
794 #endif
795     if (size <= Perl_sbrk_oldsize) {
796         got = Perl_sbrk_oldchunk;
797         Perl_sbrk_oldchunk += size;
798         Perl_sbrk_oldsize -= size;
799     } else {
800       if (size >= PERLSBRK_32_K) {
801         small = 0;
802       } else {
803 #ifndef PERL_CORE
804         reqsize = size;
805 #endif
806         size = PERLSBRK_64_K;
807         small = 1;
808       }
809       got = (IV)SYSTEM_ALLOC(size);
810 #ifdef PACK_MALLOC
811       got = (got + 0x7ff) & ~0x7ff;
812 #endif
813       if (small) {
814         /* Chunk is small, register the rest for future allocs. */
815         Perl_sbrk_oldchunk = got + reqsize;
816         Perl_sbrk_oldsize = size - reqsize;
817       }
818     }
819
820 #ifdef PERL_CORE
821     DEBUG_m(PerlIO_printf(Perl_debug_log, "sbrk malloc size %ld (reqsize %ld), left size %ld, give addr 0x%lx\n",
822                     size, reqsize, Perl_sbrk_oldsize, got));
823 #endif
824
825     return (void *)got;
826 }
827
828 #endif /* ! defined USE_PERL_SBRK */