xref: /netbsd-src/sys/lib/libsa/alloc.c (revision 2a399c6883d870daece976daec6ffa7bb7f934ce)
1 /*	$NetBSD: alloc.c,v 1.11 1997/09/17 16:24:00 drochner Exp $	*/
2 
3 /*
4  * Copyright (c) 1997 Christopher G. Demetriou.  All rights reserved.
5  * Copyright (c) 1996
6  *	Matthias Drochner.  All rights reserved.
7  * Copyright (c) 1993
8  *	The Regents of the University of California.  All rights reserved.
9  *
10  * This code is derived from software contributed to Berkeley by
11  * The Mach Operating System project at Carnegie-Mellon University.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *	This product includes software developed by the University of
24  *	California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  *	@(#)alloc.c	8.1 (Berkeley) 6/11/93
42  *
43  *
44  * Copyright (c) 1989, 1990, 1991 Carnegie Mellon University
45  * All Rights Reserved.
46  *
47  * Author: Alessandro Forin
48  *
49  * Permission to use, copy, modify and distribute this software and its
50  * documentation is hereby granted, provided that both the copyright
51  * notice and this permission notice appear in all copies of the
52  * software, derivative works or modified versions, and any portions
53  * thereof, and that both notices appear in supporting documentation.
54  *
55  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
56  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
57  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
58  *
59  * Carnegie Mellon requests users of this software to return to
60  *
61  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
62  *  School of Computer Science
63  *  Carnegie Mellon University
64  *  Pittsburgh PA 15213-3890
65  *
66  * any improvements or extensions that they make and grant Carnegie the
67  * rights to redistribute these changes.
68  */
69 
70 /*
71  * Dynamic memory allocator.
72  *
73  * Compile options:
74  *
75  *	ALLOC_TRACE	enable tracing of allocations/deallocations
76 
77  *	ALLOC_FIRST_FIT	use a first-fit allocation algorithm, rather than
78  *			the default best-fit algorithm.
79  *
80  *	HEAP_LIMIT	heap limit address (defaults to "no limit").
81  *
82  *	HEAP_START	start address of heap (defaults to '&end').
83  *
84  *	DEBUG		enable debugging sanity checks.
85  */
86 
87 #include <sys/param.h>
88 #include "stand.h"
89 
90 /*
91  * Each block actually has ALIGN(unsigned) + ALIGN(size) bytes allocated
92  * to it, as follows:
93  *
94  * 0 ... (sizeof(unsigned) - 1)
95  *	allocated or unallocated: holds size of user-data part of block.
96  *
97  * sizeof(unsigned) ... (ALIGN(sizeof(unsigned)) - 1)
98  *	allocated: unused
99  *	unallocated: depends on packing of struct fl
100  *
101  * ALIGN(sizeof(unsigned)) ... (ALIGN(sizeof(unsigned)) + ALIGN(data size) - 1)
102  *	allocated: user data
103  *	unallocated: depends on packing of struct fl
104  *
105  * 'next' is only used when the block is unallocated (i.e. on the free list).
106  * However, note that ALIGN(sizeof(unsigned)) + ALIGN(data size) must
107  * be at least 'sizeof(struct fl)', so that blocks can be used as structures
108  * when on the free list.
109  */
110 struct fl {
111 	unsigned	size;
112 	struct fl	*next;
113 } *freelist = (struct fl *)0;
114 
115 #ifdef HEAP_VARIABLE
116 static char *top, *heapstart, *heaplimit;
117 void setheap(start, limit)
118 void *start, *limit;
119 {
120     heapstart = top = start;
121     heaplimit = limit;
122 }
123 #define HEAP_START heapstart
124 #define HEAP_LIMIT heaplimit
125 #else /* !HEAP_VARIABLE */
126 #ifndef HEAP_START
127 extern char end[];
128 #define HEAP_START end
129 #endif
130 static char *top = (char*)HEAP_START;
131 #endif /* HEAP_VARIABLE */
132 
133 void *
134 alloc(size)
135 	unsigned size;
136 {
137 	register struct fl **f = &freelist, **bestf = NULL;
138 	unsigned bestsize = 0xffffffff;	/* greater than any real size */
139 	char *help;
140 	int failed;
141 
142 #ifdef ALLOC_TRACE
143 	printf("alloc(%u)", size);
144 #endif
145 
146 #ifdef ALLOC_FIRST_FIT
147 	while (*f != (struct fl *)0 && (*f)->size < size)
148 		f = &((*f)->next);
149 	bestf = f;
150 	failed = (*bestf == (struct fl *)0);
151 #else
152 	/* scan freelist */
153 	while (*f) {
154 		if ((*f)->size >= size) {
155 			if ((*f)->size == size) /* exact match */
156 				goto found;
157 
158 			if ((*f)->size < bestsize) {
159 				/* keep best fit */
160 	                        bestf = f;
161 	                        bestsize = (*f)->size;
162 	                }
163 	        }
164 	        f = &((*f)->next);
165 	}
166 
167 	/* no match in freelist if bestsize unchanged */
168 	failed = (bestsize == 0xffffffff);
169 #endif
170 
171 	if (failed) { /* nothing found */
172 	        /*
173 		 * allocate from heap, keep chunk len in
174 		 * first word
175 		 */
176 	        help = top;
177 
178 		/* make _sure_ the region can hold a struct fl. */
179 		if (size < ALIGN(sizeof (struct fl *)))
180 			size = ALIGN(sizeof (struct fl *));
181 		top += ALIGN(sizeof(unsigned)) + ALIGN(size);
182 #ifdef HEAP_LIMIT
183 		if (top > (char*)HEAP_LIMIT)
184 		        panic("heap full (0x%lx+%u)", help, size);
185 #endif
186 		*(unsigned *)help = ALIGN(size);
187 #ifdef ALLOC_TRACE
188 		printf("=%lx\n", (u_long)help + ALIGN(sizeof(unsigned)));
189 #endif
190 		return(help + ALIGN(sizeof(unsigned)));
191 	}
192 
193 	/* we take the best fit */
194 	f = bestf;
195 
196 found:
197         /* remove from freelist */
198         help = (char*)*f;
199 	*f = (*f)->next;
200 #ifdef ALLOC_TRACE
201 	printf("=%lx (origsize %u)\n", (u_long)help + ALIGN(sizeof(unsigned)),
202 	    *(unsigned *)help);
203 #endif
204 	return(help + ALIGN(sizeof(unsigned)));
205 }
206 
207 void
208 free(ptr, size)
209 	void *ptr;
210 	unsigned size; /* only for consistence check */
211 {
212 	register struct fl *f =
213 	    (struct fl *)((char*)ptr - ALIGN(sizeof(unsigned)));
214 #ifdef ALLOC_TRACE
215 	printf("free(%lx, %u) (origsize %u)\n", (u_long)ptr, size, f->size);
216 #endif
217 #ifdef DEBUG
218         if (size > f->size)
219 	        printf("free %u bytes @%lx, should be <=%u\n",
220 		    size, (u_long)ptr, f->size);
221 
222 	if (ptr < (void *)HEAP_START)
223 		printf("free: %lx before start of heap.\n", (u_long)ptr);
224 
225 #ifdef HEAP_LIMIT
226 	if (ptr > (void *)HEAP_LIMIT)
227 		printf("free: %lx beyond end of heap.\n", (u_long)ptr);
228 #endif
229 #endif /* DEBUG */
230 	/* put into freelist */
231 	f->next = freelist;
232 	freelist = f;
233 }
234