xref: /titanic_41/usr/src/uts/common/fs/smbsrv/smb_alloc.c (revision bdb9230ac765cb7af3fc1f4119caf2c5720dceb3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/types.h>
27 #include <sys/sunddi.h>
28 #include <sys/kmem.h>
29 #include <sys/sysmacros.h>
30 #include <sys/types.h>
31 
32 #include <smbsrv/alloc.h>
33 
34 #define	MEM_HDR_SIZE	8
35 static uint32_t mem_get_size(void *ptr);
36 
37 void *
38 mem_malloc(uint32_t size)
39 {
40 	uint8_t *p;
41 
42 	size += MEM_HDR_SIZE;
43 	p = kmem_alloc(size, KM_SLEEP);
44 	/*LINTED E_BAD_PTR_CAST_ALIGN*/
45 	*(uint32_t *)p = size;
46 	p += MEM_HDR_SIZE;
47 
48 	return (p);
49 }
50 
51 void *
52 mem_zalloc(uint32_t size)
53 {
54 	uint8_t *p;
55 
56 	p = mem_malloc(size);
57 	(void) memset(p, 0, size);
58 	return (p);
59 }
60 
61 char *
62 mem_strdup(const char *ptr)
63 {
64 	char *p;
65 	size_t size;
66 
67 	size = strlen(ptr) + 1;
68 	p = mem_malloc(size);
69 	(void) memcpy(p, ptr, size);
70 	return (p);
71 }
72 
73 static uint32_t
74 mem_get_size(void *ptr)
75 {
76 	uint32_t *p;
77 
78 	/*LINTED E_BAD_PTR_CAST_ALIGN*/
79 	p = (uint32_t *)((uint8_t *)ptr - MEM_HDR_SIZE);
80 
81 	return (*p);
82 }
83 
84 void *
85 mem_realloc(void *ptr, uint32_t size)
86 {
87 	void *new_ptr;
88 	uint32_t current_size;
89 
90 
91 	if (ptr == NULL)
92 		return (mem_malloc(size));
93 
94 	if (size == 0) {
95 		smb_mem_free(ptr);
96 		return (NULL);
97 	}
98 
99 	current_size = mem_get_size(ptr) - MEM_HDR_SIZE;
100 	if (size <= current_size)
101 		return (ptr);
102 
103 	new_ptr = mem_malloc(size);
104 	(void) memcpy(new_ptr, ptr, current_size);
105 	smb_mem_free(ptr);
106 
107 	return (new_ptr);
108 }
109 
110 void
111 smb_mem_free(void *ptr)
112 {
113 	uint8_t *p;
114 
115 	if (ptr == 0)
116 		return;
117 
118 	p = (uint8_t *)ptr - MEM_HDR_SIZE;
119 	/*LINTED E_BAD_PTR_CAST_ALIGN*/
120 	kmem_free(p, *(uint32_t *)p);
121 }
122