1 /* Copyright 2013-2014 IBM Corp.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * 	http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12  * implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 /* Wrappers for malloc, et. al. */
17 #include <mem_region.h>
18 #include <lock.h>
19 #include <string.h>
20 #include <mem_region-malloc.h>
21 
22 #define DEFAULT_ALIGN __alignof__(long)
23 
__memalign(size_t blocksize,size_t bytes,const char * location)24 void *__memalign(size_t blocksize, size_t bytes, const char *location)
25 {
26 	void *p;
27 
28 	lock(&skiboot_heap.free_list_lock);
29 	p = mem_alloc(&skiboot_heap, bytes, blocksize, location);
30 	unlock(&skiboot_heap.free_list_lock);
31 
32 	return p;
33 }
34 
__malloc(size_t bytes,const char * location)35 void *__malloc(size_t bytes, const char *location)
36 {
37 	return __memalign(DEFAULT_ALIGN, bytes, location);
38 }
39 
__free(void * p,const char * location)40 void __free(void *p, const char *location)
41 {
42 	lock(&skiboot_heap.free_list_lock);
43 	mem_free(&skiboot_heap, p, location);
44 	unlock(&skiboot_heap.free_list_lock);
45 }
46 
__realloc(void * ptr,size_t size,const char * location)47 void *__realloc(void *ptr, size_t size, const char *location)
48 {
49 	void *newptr;
50 
51 	/* Two classic malloc corner cases. */
52 	if (!size) {
53 		__free(ptr, location);
54 		return NULL;
55 	}
56 	if (!ptr)
57 		return __malloc(size, location);
58 
59 	lock(&skiboot_heap.free_list_lock);
60 	if (mem_resize(&skiboot_heap, ptr, size, location)) {
61 		newptr = ptr;
62 	} else {
63 		newptr = mem_alloc(&skiboot_heap, size, DEFAULT_ALIGN,
64 				   location);
65 		if (newptr) {
66 			size_t copy = mem_allocated_size(ptr);
67 			if (copy > size)
68 				copy = size;
69 			memcpy(newptr, ptr, copy);
70 			mem_free(&skiboot_heap, ptr, location);
71 		}
72 	}
73 	unlock(&skiboot_heap.free_list_lock);
74 	return newptr;
75 }
76 
__zalloc(size_t bytes,const char * location)77 void *__zalloc(size_t bytes, const char *location)
78 {
79 	void *p = __malloc(bytes, location);
80 
81 	if (p)
82 		memset(p, 0, bytes);
83 	return p;
84 }
85