]>
git.cameronkatri.com Git - bsdgames-darwin.git/blob - monop/malloc.c
1 /* $NetBSD: malloc.c,v 1.1 2003/04/21 01:23:06 christos Exp $ */
4 * Copyright (c) 1983, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 #include <sys/cdefs.h>
37 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid
[] = "@(#)malloc.c 8.1 (Berkeley) 6/4/93";
41 __RCSID("$NetBSD: malloc.c,v 1.1 2003/04/21 01:23:06 christos Exp $");
43 #endif /* LIBC_SCCS and not lint */
46 * malloc.c (Caltech) 2/21/82
47 * Chris Kingsley, kingsley@cit-20.
49 * This is a very fast storage allocator. It allocates blocks of a small
50 * number of different sizes, and keeps free lists of each size. Blocks that
51 * don't exactly fit are passed up to the next larger size. In this
52 * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
53 * This is designed for use in a virtual memory environment.
56 #include <sys/types.h>
57 #if defined(DEBUG) || defined(RCHECK)
60 #if defined(RCHECK) || defined(MSTATS)
66 #include <threadlib.h>
70 * The overhead on a block is at least 4 bytes. When free, this space
71 * contains a pointer to the next free block, and the bottom two bits must
72 * be zero. When in use, the first byte is set to MAGIC, and the second
73 * byte is the size index. The remaining bytes are for alignment.
74 * If range checking is enabled then a second word holds the size of the
75 * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
76 * The order of elements is critical: ov_magic must overlay the low order
77 * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
80 union overhead
*ov_next
; /* when free */
82 u_char ovu_magic
; /* magic number */
83 u_char ovu_index
; /* bucket # */
85 u_short ovu_rmagic
; /* range magic number */
86 u_long ovu_size
; /* actual block size */
89 #define ov_magic ovu.ovu_magic
90 #define ov_index ovu.ovu_index
91 #define ov_rmagic ovu.ovu_rmagic
92 #define ov_size ovu.ovu_size
95 #define MAGIC 0xef /* magic # on accounting info */
97 #define RMAGIC 0x5555 /* magic # on range info */
101 #define RSLOP sizeof (u_short)
107 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
108 * smallest allocatable block is 8 bytes. The overhead information
109 * precedes the data area returned to the user.
112 static union overhead
*nextf
[NBUCKETS
];
114 static long pagesz
; /* page size */
115 static int pagebucket
; /* page size bucket */
119 * nmalloc[i] is the difference between the number of mallocs and frees
120 * for a given block size.
122 static u_int nmalloc
[NBUCKETS
];
125 static mutex_t malloc_mutex
= MUTEX_INITIALIZER
;
127 static void morecore
__P((int));
128 static int findbucket
__P((union overhead
*, int));
130 void mstats
__P((const char *));
133 #if defined(DEBUG) || defined(RCHECK)
134 #define ASSERT(p) if (!(p)) botch(__STRING(p))
136 static void botch
__P((const char *));
139 * NOTE: since this may be called while malloc_mutex is locked, stdio must not
140 * be used in this function.
148 iov
[0].iov_base
= "\nassertion botched: ";
150 iov
[1].iov_base
= (void *)s
;
151 iov
[1].iov_len
= strlen(s
);
152 iov
[2].iov_base
= "\n";
156 * This place deserves a word of warning: a cancellation point will
157 * occur when executing writev(), and we might be still owning
158 * malloc_mutex. At this point we need to disable cancellation
159 * until `after' abort() because i) establishing a cancellation handler
160 * might, depending on the implementation, result in another malloc()
161 * to be executed, and ii) it is really not desirable to let execution
162 * continue. `Fix me.'
164 * Note that holding mutex_lock during abort() is safe.
167 (void)writev(STDERR_FILENO
, iov
, 3);
183 mutex_lock(&malloc_mutex
);
186 * First time malloc is called, setup page size and
187 * align break pointer so all data will be page aligned.
190 pagesz
= n
= getpagesize();
192 op
= (union overhead
*)(void *)sbrk(0);
193 n
= n
- sizeof (*op
) - ((long)op
& (n
- 1));
197 if (sbrk((int)n
) == (void *)-1) {
198 mutex_unlock(&malloc_mutex
);
204 while (pagesz
> amt
) {
211 * Convert amount of memory requested into closest block size
212 * stored in hash buckets which satisfies request.
213 * Account for space used per block for accounting.
215 if (nbytes
<= (n
= pagesz
- sizeof (*op
) - RSLOP
)) {
217 amt
= 8; /* size of first bucket */
220 amt
= 16; /* size of first bucket */
223 n
= -((long)sizeof (*op
) + RSLOP
);
225 amt
= (unsigned)pagesz
;
228 while (nbytes
> amt
+ n
) {
235 * If nothing in hash bucket right now,
236 * request more memory from the system.
238 if ((op
= nextf
[bucket
]) == NULL
) {
240 if ((op
= nextf
[bucket
]) == NULL
) {
241 mutex_unlock(&malloc_mutex
);
245 /* remove from linked list */
246 nextf
[bucket
] = op
->ov_next
;
247 op
->ov_magic
= MAGIC
;
248 op
->ov_index
= bucket
;
252 mutex_unlock(&malloc_mutex
);
255 * Record allocated size of block and
256 * bound space with magic numbers.
258 op
->ov_size
= (nbytes
+ RSLOP
- 1) & ~(RSLOP
- 1);
259 op
->ov_rmagic
= RMAGIC
;
260 *(u_short
*)((caddr_t
)(op
+ 1) + op
->ov_size
) = RMAGIC
;
262 return ((void *)(op
+ 1));
266 * Allocate more memory to the indicated bucket.
273 long sz
; /* size of desired block */
274 long amt
; /* amount to allocate */
275 long nblks
; /* how many blocks we get */
278 * sbrk_size <= 0 only for big, FLUFFY, requests (about
279 * 2^30 bytes on a VAX, I think) or for a negative arg.
281 sz
= 1 << (bucket
+ 3);
295 op
= (union overhead
*)(void *)sbrk((int)amt
);
300 * Add new memory allocated to that on
301 * free list for this hash bucket.
304 while (--nblks
> 0) {
306 (union overhead
*)(void *)((caddr_t
)(void *)op
+(size_t)sz
);
320 op
= (union overhead
*)(void *)((caddr_t
)cp
- sizeof (union overhead
));
322 ASSERT(op
->ov_magic
== MAGIC
); /* make sure it was in use */
324 if (op
->ov_magic
!= MAGIC
)
328 ASSERT(op
->ov_rmagic
== RMAGIC
);
329 ASSERT(*(u_short
*)((caddr_t
)(op
+ 1) + op
->ov_size
) == RMAGIC
);
332 ASSERT(size
< NBUCKETS
);
333 mutex_lock(&malloc_mutex
);
334 op
->ov_next
= nextf
[(unsigned int)size
];/* also clobbers ov_magic */
335 nextf
[(unsigned int)size
] = op
;
337 nmalloc
[(size_t)size
]--;
339 mutex_unlock(&malloc_mutex
);
343 * When a program attempts "storage compaction" as mentioned in the
344 * old malloc man page, it realloc's an already freed block. Usually
345 * this is the last block it freed; occasionally it might be farther
346 * back. We have to search all the free lists for the block in order
347 * to determine its bucket: 1st we make one pass thru the lists
348 * checking only the first block in each; if that fails we search
349 * ``__realloc_srchlen'' blocks in each list for a match (the variable
350 * is extern so the caller can modify it). If that fails we just copy
351 * however many bytes was given to realloc() and hope it's not huge.
353 int __realloc_srchlen
= 4; /* 4 should be plenty, -1 =>'s whole list */
367 return (malloc(nbytes
));
372 op
= (union overhead
*)(void *)((caddr_t
)cp
- sizeof (union overhead
));
373 mutex_lock(&malloc_mutex
);
374 if (op
->ov_magic
== MAGIC
) {
379 * Already free, doing "compaction".
381 * Search for the old block of memory on the
382 * free list. First, check the most common
383 * case (last element free'd), then (this failing)
384 * the last ``__realloc_srchlen'' items free'd.
385 * If all lookups fail, then assume the size of
386 * the memory block being realloc'd is the
387 * largest possible (so that all "nbytes" of new
388 * memory are copied into). Note that this could cause
389 * a memory fault if the old area was tiny, and the moon
390 * is gibbous. However, that is very unlikely.
392 if ((i
= findbucket(op
, 1)) < 0 &&
393 (i
= findbucket(op
, __realloc_srchlen
)) < 0)
396 onb
= (u_long
)1 << (u_long
)(i
+ 3);
398 onb
-= sizeof (*op
) + RSLOP
;
400 onb
+= pagesz
- sizeof (*op
) - RSLOP
;
401 /* avoid the copy if same size block */
404 i
= (long)1 << (long)(i
+ 2);
406 i
-= sizeof (*op
) + RSLOP
;
408 i
+= pagesz
- sizeof (*op
) - RSLOP
;
410 if (nbytes
<= onb
&& nbytes
> i
) {
412 op
->ov_size
= (nbytes
+ RSLOP
- 1) & ~(RSLOP
- 1);
413 *(u_short
*)((caddr_t
)(op
+ 1) + op
->ov_size
) = RMAGIC
;
415 mutex_unlock(&malloc_mutex
);
424 mutex_unlock(&malloc_mutex
);
425 if ((res
= malloc(nbytes
)) == NULL
) {
432 if (cp
!= res
) /* common optimization if "compacting" */
433 (void)memmove(res
, cp
, (size_t)((nbytes
< onb
) ? nbytes
: onb
));
435 (void)memmove(res
, cp
, (size_t)((nbytes
< onb
) ? nbytes
: onb
));
442 * Search ``srchlen'' elements of each free list for a block whose
443 * header starts at ``freep''. If srchlen is -1 search the whole list.
444 * Return bucket number, or -1 if not found.
447 findbucket(freep
, srchlen
)
448 union overhead
*freep
;
454 for (i
= 0; i
< NBUCKETS
; i
++) {
456 for (p
= nextf
[i
]; p
&& j
!= srchlen
; p
= p
->ov_next
) {
467 * mstats - print out statistics about malloc
469 * Prints two lines of numbers, one showing the length of the free list
470 * for each size category, the second showing the number of mallocs -
471 * frees for each size category.
482 fprintf(stderr
, "Memory allocation statistics %s\nfree:\t", s
);
483 for (i
= 0; i
< NBUCKETS
; i
++) {
484 for (j
= 0, p
= nextf
[i
]; p
; p
= p
->ov_next
, j
++)
486 fprintf(stderr
, " %d", j
);
487 totfree
+= j
* (1 << (i
+ 3));
489 fprintf(stderr
, "\nused:\t");
490 for (i
= 0; i
< NBUCKETS
; i
++) {
491 fprintf(stderr
, " %d", nmalloc
[i
]);
492 totused
+= nmalloc
[i
] * (1 << (i
+ 3));
494 fprintf(stderr
, "\n\tTotal in use: %d, total free: %d\n",