2 * Copyright (c) 1983 Regents of the University of California.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 #if defined(LIBC_SCCS) && !defined(lint)
35 /*static char *sccsid = "from: @(#)malloc.c 5.11 (Berkeley) 2/23/91";*/
36 static char *rcsid
= "$FreeBSD$";
37 #endif /* LIBC_SCCS and not lint */
40 * malloc.c (Caltech) 2/21/82
41 * Chris Kingsley, kingsley@cit-20.
43 * This is a very fast storage allocator. It allocates blocks of a small
44 * number of different sizes, and keeps free lists of each size. Blocks that
45 * don't exactly fit are passed up to the next larger size. In this
46 * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
47 * This is designed for use in a virtual memory environment.
50 #include <sys/types.h>
59 #include <sys/param.h>
62 #define MAP_COPY MAP_PRIVATE
67 #ifndef BSD /* Need do better than this */
68 #define NEED_DEV_ZERO 1
71 static void morecore();
72 static int findbucket();
75 * Pre-allocate mmap'ed pages
77 #define NPOOLPAGES (32*1024/pagesz)
78 static caddr_t pagepool_start
, pagepool_end
;
79 static int morepages();
82 * The overhead on a block is at least 4 bytes. When free, this space
83 * contains a pointer to the next free block, and the bottom two bits must
84 * be zero. When in use, the first byte is set to MAGIC, and the second
85 * byte is the size index. The remaining bytes are for alignment.
86 * If range checking is enabled then a second word holds the size of the
87 * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
88 * The order of elements is critical: ov_magic must overlay the low order
89 * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
92 union overhead
*ov_next
; /* when free */
94 u_char ovu_magic
; /* magic number */
95 u_char ovu_index
; /* bucket # */
97 u_short ovu_rmagic
; /* range magic number */
98 u_int ovu_size
; /* actual block size */
101 #define ov_magic ovu.ovu_magic
102 #define ov_index ovu.ovu_index
103 #define ov_rmagic ovu.ovu_rmagic
104 #define ov_size ovu.ovu_size
107 #define MAGIC 0xef /* magic # on accounting info */
108 #define RMAGIC 0x5555 /* magic # on range info */
111 #define RSLOP sizeof (u_short)
117 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
118 * smallest allocatable block is 8 bytes. The overhead information
119 * precedes the data area returned to the user.
122 static union overhead
*nextf
[NBUCKETS
];
124 static int pagesz
; /* page size */
125 static int pagebucket
; /* page size bucket */
129 * nmalloc[i] is the difference between the number of mallocs and frees
130 * for a given block size.
132 static u_int nmalloc
[NBUCKETS
];
136 #if defined(MALLOC_DEBUG) || defined(RCHECK)
137 #define ASSERT(p) if (!(p)) botch("p")
143 fprintf(stderr
, "\r\nassertion botched: %s\r\n", s
);
144 (void) fflush(stderr
); /* just in case user buffered it */
151 /* Debugging stuff */
152 static void xprintf(const char *, ...);
153 #define TRACE() xprintf("TRACE %s:%d\n", __FILE__, __LINE__)
159 register union overhead
*op
;
162 register unsigned amt
;
165 * First time malloc is called, setup page size and
166 * align break pointer so all data will be page aligned.
169 pagesz
= n
= getpagesize();
170 if (morepages(NPOOLPAGES
) == 0)
172 op
= (union overhead
*)(pagepool_start
);
173 n
= n
- sizeof (*op
) - ((long)op
& (n
- 1));
181 while ((unsigned)pagesz
> amt
) {
188 * Convert amount of memory requested into closest block size
189 * stored in hash buckets which satisfies request.
190 * Account for space used per block for accounting.
192 if (nbytes
<= (unsigned long)(n
= pagesz
- sizeof (*op
) - RSLOP
)) {
194 amt
= 8; /* size of first bucket */
197 amt
= 16; /* size of first bucket */
200 n
= -(sizeof (*op
) + RSLOP
);
205 while (nbytes
> amt
+ n
) {
212 * If nothing in hash bucket right now,
213 * request more memory from the system.
215 if ((op
= nextf
[bucket
]) == NULL
) {
217 if ((op
= nextf
[bucket
]) == NULL
)
220 /* remove from linked list */
221 nextf
[bucket
] = op
->ov_next
;
222 op
->ov_magic
= MAGIC
;
223 op
->ov_index
= bucket
;
229 * Record allocated size of block and
230 * bound space with magic numbers.
232 op
->ov_size
= (nbytes
+ RSLOP
- 1) & ~(RSLOP
- 1);
233 op
->ov_rmagic
= RMAGIC
;
234 *(u_short
*)((caddr_t
)(op
+ 1) + op
->ov_size
) = RMAGIC
;
236 return ((char *)(op
+ 1));
240 calloc(size_t num
, size_t size
)
244 if (size
!= 0 && (num
* size
) / size
!= num
) {
245 /* size_t overflow. */
249 if ((ret
= malloc(num
* size
)) != NULL
)
250 memset(ret
, 0, num
* size
);
256 * Allocate more memory to the indicated bucket.
262 register union overhead
*op
;
263 register int sz
; /* size of desired block */
264 int amt
; /* amount to allocate */
265 int nblks
; /* how many blocks we get */
268 * sbrk_size <= 0 only for big, FLUFFY, requests (about
269 * 2^30 bytes on a VAX, I think) or for a negative arg.
271 sz
= 1 << (bucket
+ 3);
285 if (amt
> pagepool_end
- pagepool_start
)
286 if (morepages(amt
/pagesz
+ NPOOLPAGES
) == 0)
288 op
= (union overhead
*)pagepool_start
;
289 pagepool_start
+= amt
;
292 * Add new memory allocated to that on
293 * free list for this hash bucket.
296 while (--nblks
> 0) {
297 op
->ov_next
= (union overhead
*)((caddr_t
)op
+ sz
);
298 op
= (union overhead
*)((caddr_t
)op
+ sz
);
307 register union overhead
*op
;
311 op
= (union overhead
*)((caddr_t
)cp
- sizeof (union overhead
));
313 ASSERT(op
->ov_magic
== MAGIC
); /* make sure it was in use */
315 if (op
->ov_magic
!= MAGIC
)
319 ASSERT(op
->ov_rmagic
== RMAGIC
);
320 ASSERT(*(u_short
*)((caddr_t
)(op
+ 1) + op
->ov_size
) == RMAGIC
);
323 ASSERT(size
< NBUCKETS
);
324 op
->ov_next
= nextf
[size
]; /* also clobbers ov_magic */
332 * When a program attempts "storage compaction" as mentioned in the
333 * old malloc man page, it realloc's an already freed block. Usually
334 * this is the last block it freed; occasionally it might be farther
335 * back. We have to search all the free lists for the block in order
336 * to determine its bucket: 1st we make one pass thru the lists
337 * checking only the first block in each; if that fails we search
338 * ``realloc_srchlen'' blocks in each list for a match (the variable
339 * is extern so the caller can modify it). If that fails we just copy
340 * however many bytes was given to realloc() and hope it's not huge.
342 int realloc_srchlen
= 4; /* 4 should be plenty, -1 =>'s whole list */
356 return (malloc(nbytes
));
357 op
= (union overhead
*)((caddr_t
)cp
- sizeof (union overhead
));
358 if (op
->ov_magic
== MAGIC
) {
363 * Already free, doing "compaction".
365 * Search for the old block of memory on the
366 * free list. First, check the most common
367 * case (last element free'd), then (this failing)
368 * the last ``realloc_srchlen'' items free'd.
369 * If all lookups fail, then assume the size of
370 * the memory block being realloc'd is the
371 * largest possible (so that all "nbytes" of new
372 * memory are copied into). Note that this could cause
373 * a memory fault if the old area was tiny, and the moon
374 * is gibbous. However, that is very unlikely.
376 if ((i
= findbucket(op
, 1)) < 0 &&
377 (i
= findbucket(op
, realloc_srchlen
)) < 0)
381 if (onb
< (u_int
)pagesz
)
382 onb
-= sizeof (*op
) + RSLOP
;
384 onb
+= pagesz
- sizeof (*op
) - RSLOP
;
385 /* avoid the copy if same size block */
390 i
-= sizeof (*op
) + RSLOP
;
392 i
+= pagesz
- sizeof (*op
) - RSLOP
;
394 if (nbytes
<= onb
&& nbytes
> (size_t)i
) {
396 op
->ov_size
= (nbytes
+ RSLOP
- 1) & ~(RSLOP
- 1);
397 *(u_short
*)((caddr_t
)(op
+ 1) + op
->ov_size
) = RMAGIC
;
403 if ((res
= malloc(nbytes
)) == NULL
)
405 if (cp
!= res
) /* common optimization if "compacting" */
406 bcopy(cp
, res
, (nbytes
< onb
) ? nbytes
: onb
);
411 * Search ``srchlen'' elements of each free list for a block whose
412 * header starts at ``freep''. If srchlen is -1 search the whole list.
413 * Return bucket number, or -1 if not found.
416 findbucket(freep
, srchlen
)
417 union overhead
*freep
;
420 register union overhead
*p
;
423 for (i
= 0; i
< NBUCKETS
; i
++) {
425 for (p
= nextf
[i
]; p
&& j
!= srchlen
; p
= p
->ov_next
) {
436 * mstats - print out statistics about malloc
438 * Prints two lines of numbers, one showing the length of the free list
439 * for each size category, the second showing the number of mallocs -
440 * frees for each size category.
446 register union overhead
*p
;
450 fprintf(stderr
, "Memory allocation statistics %s\nfree:\t", s
);
451 for (i
= 0; i
< NBUCKETS
; i
++) {
452 for (j
= 0, p
= nextf
[i
]; p
; p
= p
->ov_next
, j
++)
454 fprintf(stderr
, " %d", j
);
455 totfree
+= j
* (1 << (i
+ 3));
457 fprintf(stderr
, "\nused:\t");
458 for (i
= 0; i
< NBUCKETS
; i
++) {
459 fprintf(stderr
, " %d", nmalloc
[i
]);
460 totused
+= nmalloc
[i
] * (1 << (i
+ 3));
462 fprintf(stderr
, "\n\tTotal in use: %d, total free: %d\n",
476 fd
= open(_PATH_DEVZERO
, O_RDWR
, 0);
478 perror(_PATH_DEVZERO
);
481 if (pagepool_end
- pagepool_start
> pagesz
) {
482 caddr_t addr
= (caddr_t
)
483 (((long)pagepool_start
+ pagesz
- 1) & ~(pagesz
- 1));
484 if (munmap(addr
, pagepool_end
- addr
) != 0)
485 warn("morepages: munmap %p", addr
);
488 offset
= (long)pagepool_start
- ((long)pagepool_start
& ~(pagesz
- 1));
490 if ((pagepool_start
= mmap(0, n
* pagesz
,
491 PROT_READ
|PROT_WRITE
,
492 MAP_ANON
|MAP_COPY
, fd
, 0)) == (caddr_t
)-1) {
493 xprintf("Cannot map anonymous memory");
496 pagepool_end
= pagepool_start
+ n
* pagesz
;
497 pagepool_start
+= offset
;
506 * Non-mallocing printf, for use by malloc itself.
509 xprintf(const char *fmt
, ...)
515 vsprintf(buf
, fmt
, ap
);
516 (void)write(STDOUT_FILENO
, buf
, strlen(buf
));