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